@cornerstonejs/tools 3.0.2 → 3.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1262) hide show
  1. package/LICENSE +2 -2
  2. package/README.md +4 -183
  3. package/dist/esm/config.d.ts +30 -0
  4. package/dist/esm/config.js +23 -0
  5. package/dist/esm/constants/COLOR_LUT.d.ts +3 -0
  6. package/dist/esm/constants/COLOR_LUT.js +258 -0
  7. package/dist/esm/constants/index.d.ts +2 -0
  8. package/dist/esm/constants/index.js +2 -0
  9. package/dist/esm/cursors/ImageMouseCursor.d.ts +9 -0
  10. package/dist/esm/cursors/ImageMouseCursor.js +22 -0
  11. package/dist/esm/cursors/MouseCursor.d.ts +12 -0
  12. package/dist/esm/cursors/MouseCursor.js +88 -0
  13. package/dist/esm/cursors/SVGCursorDescriptor.d.ts +9 -0
  14. package/dist/esm/cursors/SVGCursorDescriptor.js +442 -0
  15. package/dist/esm/cursors/SVGMouseCursor.d.ts +6 -0
  16. package/dist/esm/cursors/SVGMouseCursor.js +74 -0
  17. package/dist/esm/cursors/elementCursor.d.ts +6 -0
  18. package/dist/esm/cursors/elementCursor.js +36 -0
  19. package/dist/esm/cursors/index.d.ts +8 -0
  20. package/dist/esm/cursors/index.js +8 -0
  21. package/dist/esm/cursors/setCursorForElement.d.ts +2 -0
  22. package/dist/esm/cursors/setCursorForElement.js +15 -0
  23. package/dist/esm/drawingSvg/_getHash.d.ts +2 -0
  24. package/dist/esm/drawingSvg/_getHash.js +4 -0
  25. package/dist/esm/drawingSvg/clearByToolType.d.ts +2 -0
  26. package/dist/esm/drawingSvg/clearByToolType.js +13 -0
  27. package/dist/esm/drawingSvg/draw.d.ts +3 -0
  28. package/dist/esm/drawingSvg/draw.js +7 -0
  29. package/dist/esm/drawingSvg/drawArrow.d.ts +3 -0
  30. package/dist/esm/drawingSvg/drawArrow.js +79 -0
  31. package/dist/esm/drawingSvg/drawCircle.d.ts +4 -0
  32. package/dist/esm/drawingSvg/drawCircle.js +42 -0
  33. package/dist/esm/drawingSvg/drawEllipse.d.ts +4 -0
  34. package/dist/esm/drawingSvg/drawEllipse.js +10 -0
  35. package/dist/esm/drawingSvg/drawEllipseByCoordinates.d.ts +4 -0
  36. package/dist/esm/drawingSvg/drawEllipseByCoordinates.js +46 -0
  37. package/dist/esm/drawingSvg/drawHandle.d.ts +4 -0
  38. package/dist/esm/drawingSvg/drawHandle.js +60 -0
  39. package/dist/esm/drawingSvg/drawHandles.d.ts +4 -0
  40. package/dist/esm/drawingSvg/drawHandles.js +7 -0
  41. package/dist/esm/drawingSvg/drawHeight.d.ts +3 -0
  42. package/dist/esm/drawingSvg/drawHeight.js +45 -0
  43. package/dist/esm/drawingSvg/drawLine.d.ts +3 -0
  44. package/dist/esm/drawingSvg/drawLine.js +39 -0
  45. package/dist/esm/drawingSvg/drawLink.d.ts +4 -0
  46. package/dist/esm/drawingSvg/drawLink.js +26 -0
  47. package/dist/esm/drawingSvg/drawLinkedTextBox.d.ts +4 -0
  48. package/dist/esm/drawingSvg/drawLinkedTextBox.js +15 -0
  49. package/dist/esm/drawingSvg/drawPath.d.ts +11 -0
  50. package/dist/esm/drawingSvg/drawPath.js +48 -0
  51. package/dist/esm/drawingSvg/drawPolyline.d.ts +13 -0
  52. package/dist/esm/drawingSvg/drawPolyline.js +40 -0
  53. package/dist/esm/drawingSvg/drawRect.d.ts +3 -0
  54. package/dist/esm/drawingSvg/drawRect.js +9 -0
  55. package/dist/esm/drawingSvg/drawRectByCoordinates.d.ts +3 -0
  56. package/dist/esm/drawingSvg/drawRectByCoordinates.js +52 -0
  57. package/dist/esm/drawingSvg/drawRedactionRect.d.ts +3 -0
  58. package/dist/esm/drawingSvg/drawRedactionRect.js +37 -0
  59. package/dist/esm/drawingSvg/drawTextBox.d.ts +4 -0
  60. package/dist/esm/drawingSvg/drawTextBox.js +123 -0
  61. package/dist/esm/drawingSvg/getSvgDrawingHelper.d.ts +3 -0
  62. package/dist/esm/drawingSvg/getSvgDrawingHelper.js +65 -0
  63. package/dist/esm/drawingSvg/index.d.ts +19 -0
  64. package/dist/esm/drawingSvg/index.js +19 -0
  65. package/dist/esm/drawingSvg/setAttributesIfNecessary.d.ts +2 -0
  66. package/dist/esm/drawingSvg/setAttributesIfNecessary.js +13 -0
  67. package/dist/esm/drawingSvg/setNewAttributesIfValid.d.ts +2 -0
  68. package/dist/esm/drawingSvg/setNewAttributesIfValid.js +9 -0
  69. package/dist/esm/enums/AnnotationStyleStates.d.ts +8 -0
  70. package/dist/esm/enums/AnnotationStyleStates.js +9 -0
  71. package/dist/esm/enums/ChangeTypes.d.ts +11 -0
  72. package/dist/esm/enums/ChangeTypes.js +12 -0
  73. package/dist/esm/enums/Events.d.ts +42 -0
  74. package/dist/esm/enums/Events.js +43 -0
  75. package/dist/esm/enums/SegmentationRepresentations.d.ts +6 -0
  76. package/dist/esm/enums/SegmentationRepresentations.js +7 -0
  77. package/dist/esm/enums/StrategyCallbacks.d.ts +19 -0
  78. package/dist/esm/enums/StrategyCallbacks.js +20 -0
  79. package/dist/esm/enums/ToolBindings.d.ts +26 -0
  80. package/dist/esm/enums/ToolBindings.js +28 -0
  81. package/dist/esm/enums/ToolModes.d.ts +7 -0
  82. package/dist/esm/enums/ToolModes.js +8 -0
  83. package/dist/esm/enums/Touch.d.ts +7 -0
  84. package/dist/esm/enums/Touch.js +8 -0
  85. package/dist/esm/enums/WorkerTypes.d.ts +10 -0
  86. package/dist/esm/enums/WorkerTypes.js +11 -0
  87. package/dist/esm/enums/index.d.ts +11 -0
  88. package/dist/esm/enums/index.js +10 -0
  89. package/dist/esm/eventDispatchers/annotationInterpolationEventDispatcher.d.ts +5 -0
  90. package/dist/esm/eventDispatchers/annotationInterpolationEventDispatcher.js +17 -0
  91. package/dist/esm/eventDispatchers/annotationModifiedEventDispatcher.d.ts +5 -0
  92. package/dist/esm/eventDispatchers/annotationModifiedEventDispatcher.js +18 -0
  93. package/dist/esm/eventDispatchers/cameraModifiedEventDispatcher.d.ts +5 -0
  94. package/dist/esm/eventDispatchers/cameraModifiedEventDispatcher.js +26 -0
  95. package/dist/esm/eventDispatchers/cameraResetEventDispatcher.d.ts +5 -0
  96. package/dist/esm/eventDispatchers/cameraResetEventDispatcher.js +26 -0
  97. package/dist/esm/eventDispatchers/imageRenderedEventDispatcher.d.ts +5 -0
  98. package/dist/esm/eventDispatchers/imageRenderedEventDispatcher.js +15 -0
  99. package/dist/esm/eventDispatchers/imageSpacingCalibratedEventDispatcher.d.ts +5 -0
  100. package/dist/esm/eventDispatchers/imageSpacingCalibratedEventDispatcher.js +26 -0
  101. package/dist/esm/eventDispatchers/index.d.ts +9 -0
  102. package/dist/esm/eventDispatchers/index.js +9 -0
  103. package/dist/esm/eventDispatchers/keyboardEventHandlers/index.d.ts +3 -0
  104. package/dist/esm/eventDispatchers/keyboardEventHandlers/index.js +3 -0
  105. package/dist/esm/eventDispatchers/keyboardEventHandlers/keyDown.d.ts +2 -0
  106. package/dist/esm/eventDispatchers/keyboardEventHandlers/keyDown.js +25 -0
  107. package/dist/esm/eventDispatchers/keyboardEventHandlers/keyUp.d.ts +2 -0
  108. package/dist/esm/eventDispatchers/keyboardEventHandlers/keyUp.js +16 -0
  109. package/dist/esm/eventDispatchers/keyboardToolEventDispatcher.d.ts +5 -0
  110. package/dist/esm/eventDispatchers/keyboardToolEventDispatcher.js +15 -0
  111. package/dist/esm/eventDispatchers/mouseEventHandlers/index.d.ts +9 -0
  112. package/dist/esm/eventDispatchers/mouseEventHandlers/index.js +9 -0
  113. package/dist/esm/eventDispatchers/mouseEventHandlers/mouseClick.d.ts +2 -0
  114. package/dist/esm/eventDispatchers/mouseEventHandlers/mouseClick.js +3 -0
  115. package/dist/esm/eventDispatchers/mouseEventHandlers/mouseDoubleClick.d.ts +2 -0
  116. package/dist/esm/eventDispatchers/mouseEventHandlers/mouseDoubleClick.js +3 -0
  117. package/dist/esm/eventDispatchers/mouseEventHandlers/mouseDown.d.ts +2 -0
  118. package/dist/esm/eventDispatchers/mouseEventHandlers/mouseDown.js +90 -0
  119. package/dist/esm/eventDispatchers/mouseEventHandlers/mouseDownActivate.d.ts +2 -0
  120. package/dist/esm/eventDispatchers/mouseEventHandlers/mouseDownActivate.js +19 -0
  121. package/dist/esm/eventDispatchers/mouseEventHandlers/mouseDownAnnotationAction.d.ts +2 -0
  122. package/dist/esm/eventDispatchers/mouseEventHandlers/mouseDownAnnotationAction.js +34 -0
  123. package/dist/esm/eventDispatchers/mouseEventHandlers/mouseDrag.d.ts +2 -0
  124. package/dist/esm/eventDispatchers/mouseEventHandlers/mouseDrag.js +13 -0
  125. package/dist/esm/eventDispatchers/mouseEventHandlers/mouseMove.d.ts +2 -0
  126. package/dist/esm/eventDispatchers/mouseEventHandlers/mouseMove.js +37 -0
  127. package/dist/esm/eventDispatchers/mouseEventHandlers/mouseUp.d.ts +2 -0
  128. package/dist/esm/eventDispatchers/mouseEventHandlers/mouseUp.js +3 -0
  129. package/dist/esm/eventDispatchers/mouseEventHandlers/mouseWheel.d.ts +3 -0
  130. package/dist/esm/eventDispatchers/mouseEventHandlers/mouseWheel.js +16 -0
  131. package/dist/esm/eventDispatchers/mouseToolEventDispatcher.d.ts +5 -0
  132. package/dist/esm/eventDispatchers/mouseToolEventDispatcher.js +27 -0
  133. package/dist/esm/eventDispatchers/shared/customCallbackHandler.d.ts +1 -0
  134. package/dist/esm/eventDispatchers/shared/customCallbackHandler.js +30 -0
  135. package/dist/esm/eventDispatchers/shared/getActiveToolForKeyboardEvent.d.ts +2 -0
  136. package/dist/esm/eventDispatchers/shared/getActiveToolForKeyboardEvent.js +29 -0
  137. package/dist/esm/eventDispatchers/shared/getActiveToolForMouseEvent.d.ts +2 -0
  138. package/dist/esm/eventDispatchers/shared/getActiveToolForMouseEvent.js +28 -0
  139. package/dist/esm/eventDispatchers/shared/getActiveToolForTouchEvent.d.ts +2 -0
  140. package/dist/esm/eventDispatchers/shared/getActiveToolForTouchEvent.js +29 -0
  141. package/dist/esm/eventDispatchers/shared/getMouseModifier.d.ts +3 -0
  142. package/dist/esm/eventDispatchers/shared/getMouseModifier.js +32 -0
  143. package/dist/esm/eventDispatchers/shared/getToolsWithActionsForKeyboardEvents.d.ts +3 -0
  144. package/dist/esm/eventDispatchers/shared/getToolsWithActionsForKeyboardEvents.js +28 -0
  145. package/dist/esm/eventDispatchers/shared/getToolsWithActionsForMouseEvent.d.ts +4 -0
  146. package/dist/esm/eventDispatchers/shared/getToolsWithActionsForMouseEvent.js +32 -0
  147. package/dist/esm/eventDispatchers/shared/getToolsWithModesForMouseEvent.d.ts +5 -0
  148. package/dist/esm/eventDispatchers/shared/getToolsWithModesForMouseEvent.js +23 -0
  149. package/dist/esm/eventDispatchers/shared/getToolsWithModesForTouchEvent.d.ts +5 -0
  150. package/dist/esm/eventDispatchers/shared/getToolsWithModesForTouchEvent.js +23 -0
  151. package/dist/esm/eventDispatchers/touchEventHandlers/index.d.ts +7 -0
  152. package/dist/esm/eventDispatchers/touchEventHandlers/index.js +7 -0
  153. package/dist/esm/eventDispatchers/touchEventHandlers/touchDrag.d.ts +2 -0
  154. package/dist/esm/eventDispatchers/touchEventHandlers/touchDrag.js +13 -0
  155. package/dist/esm/eventDispatchers/touchEventHandlers/touchEnd.d.ts +2 -0
  156. package/dist/esm/eventDispatchers/touchEventHandlers/touchEnd.js +3 -0
  157. package/dist/esm/eventDispatchers/touchEventHandlers/touchPress.d.ts +2 -0
  158. package/dist/esm/eventDispatchers/touchEventHandlers/touchPress.js +3 -0
  159. package/dist/esm/eventDispatchers/touchEventHandlers/touchStart.d.ts +2 -0
  160. package/dist/esm/eventDispatchers/touchEventHandlers/touchStart.js +79 -0
  161. package/dist/esm/eventDispatchers/touchEventHandlers/touchStartActivate.d.ts +2 -0
  162. package/dist/esm/eventDispatchers/touchEventHandlers/touchStartActivate.js +19 -0
  163. package/dist/esm/eventDispatchers/touchEventHandlers/touchTap.d.ts +2 -0
  164. package/dist/esm/eventDispatchers/touchEventHandlers/touchTap.js +3 -0
  165. package/dist/esm/eventDispatchers/touchToolEventDispatcher.d.ts +5 -0
  166. package/dist/esm/eventDispatchers/touchToolEventDispatcher.js +22 -0
  167. package/dist/esm/eventListeners/annotations/annotationCompletedListener.d.ts +2 -0
  168. package/dist/esm/eventListeners/annotations/annotationCompletedListener.js +8 -0
  169. package/dist/esm/eventListeners/annotations/annotationModifiedListener.d.ts +2 -0
  170. package/dist/esm/eventListeners/annotations/annotationModifiedListener.js +6 -0
  171. package/dist/esm/eventListeners/annotations/annotationRemovedListener.d.ts +2 -0
  172. package/dist/esm/eventListeners/annotations/annotationRemovedListener.js +8 -0
  173. package/dist/esm/eventListeners/annotations/annotationSelectionListener.d.ts +2 -0
  174. package/dist/esm/eventListeners/annotations/annotationSelectionListener.js +15 -0
  175. package/dist/esm/eventListeners/annotations/contourSegmentation/contourSegmentationCompleted.d.ts +5 -0
  176. package/dist/esm/eventListeners/annotations/contourSegmentation/contourSegmentationCompleted.js +233 -0
  177. package/dist/esm/eventListeners/annotations/contourSegmentation/contourSegmentationRemoved.d.ts +2 -0
  178. package/dist/esm/eventListeners/annotations/contourSegmentation/contourSegmentationRemoved.js +5 -0
  179. package/dist/esm/eventListeners/annotations/contourSegmentation/index.d.ts +2 -0
  180. package/dist/esm/eventListeners/annotations/contourSegmentation/index.js +2 -0
  181. package/dist/esm/eventListeners/annotations/index.d.ts +5 -0
  182. package/dist/esm/eventListeners/annotations/index.js +5 -0
  183. package/dist/esm/eventListeners/index.d.ts +7 -0
  184. package/dist/esm/eventListeners/index.js +7 -0
  185. package/dist/esm/eventListeners/keyboard/index.d.ts +9 -0
  186. package/dist/esm/eventListeners/keyboard/index.js +13 -0
  187. package/dist/esm/eventListeners/keyboard/keyDownListener.d.ts +4 -0
  188. package/dist/esm/eventListeners/keyboard/keyDownListener.js +64 -0
  189. package/dist/esm/eventListeners/mouse/getMouseEventPoints.d.ts +2 -0
  190. package/dist/esm/eventListeners/mouse/getMouseEventPoints.js +31 -0
  191. package/dist/esm/eventListeners/mouse/index.d.ts +7 -0
  192. package/dist/esm/eventListeners/mouse/index.js +24 -0
  193. package/dist/esm/eventListeners/mouse/mouseDoubleClickListener.d.ts +2 -0
  194. package/dist/esm/eventListeners/mouse/mouseDoubleClickListener.js +32 -0
  195. package/dist/esm/eventListeners/mouse/mouseDownListener.d.ts +4 -0
  196. package/dist/esm/eventListeners/mouse/mouseDownListener.js +266 -0
  197. package/dist/esm/eventListeners/mouse/mouseMoveListener.d.ts +2 -0
  198. package/dist/esm/eventListeners/mouse/mouseMoveListener.js +28 -0
  199. package/dist/esm/eventListeners/segmentation/imageChangeEventListener.d.ts +5 -0
  200. package/dist/esm/eventListeners/segmentation/imageChangeEventListener.js +128 -0
  201. package/dist/esm/eventListeners/segmentation/index.d.ts +4 -0
  202. package/dist/esm/eventListeners/segmentation/index.js +4 -0
  203. package/dist/esm/eventListeners/segmentation/labelmap/onLabelmapSegmentationDataModified.d.ts +3 -0
  204. package/dist/esm/eventListeners/segmentation/labelmap/onLabelmapSegmentationDataModified.js +83 -0
  205. package/dist/esm/eventListeners/segmentation/segmentationDataModifiedEventListener.d.ts +3 -0
  206. package/dist/esm/eventListeners/segmentation/segmentationDataModifiedEventListener.js +12 -0
  207. package/dist/esm/eventListeners/segmentation/segmentationModifiedEventListener.d.ts +3 -0
  208. package/dist/esm/eventListeners/segmentation/segmentationModifiedEventListener.js +6 -0
  209. package/dist/esm/eventListeners/segmentation/segmentationRepresentationModifiedListener.d.ts +3 -0
  210. package/dist/esm/eventListeners/segmentation/segmentationRepresentationModifiedListener.js +6 -0
  211. package/dist/esm/eventListeners/touch/getTouchEventPoints.d.ts +2 -0
  212. package/dist/esm/eventListeners/touch/getTouchEventPoints.js +38 -0
  213. package/dist/esm/eventListeners/touch/index.d.ts +7 -0
  214. package/dist/esm/eventListeners/touch/index.js +17 -0
  215. package/dist/esm/eventListeners/touch/preventGhostClick.d.ts +7 -0
  216. package/dist/esm/eventListeners/touch/preventGhostClick.js +47 -0
  217. package/dist/esm/eventListeners/touch/touchStartListener.d.ts +2 -0
  218. package/dist/esm/eventListeners/touch/touchStartListener.js +282 -0
  219. package/dist/esm/eventListeners/wheel/index.d.ts +7 -0
  220. package/dist/esm/eventListeners/wheel/index.js +12 -0
  221. package/dist/esm/eventListeners/wheel/normalizeWheel.d.ts +6 -0
  222. package/dist/esm/eventListeners/wheel/normalizeWheel.js +48 -0
  223. package/dist/esm/eventListeners/wheel/wheelListener.d.ts +2 -0
  224. package/dist/esm/eventListeners/wheel/wheelListener.js +34 -0
  225. package/dist/esm/index.d.ts +17 -0
  226. package/dist/esm/index.js +17 -0
  227. package/dist/esm/init.d.ts +4 -0
  228. package/dist/esm/init.js +70 -0
  229. package/dist/esm/stateManagement/annotation/AnnotationGroup.d.ts +18 -0
  230. package/dist/esm/stateManagement/annotation/AnnotationGroup.js +69 -0
  231. package/dist/esm/stateManagement/annotation/AnnotationRenderingEngine.d.ts +20 -0
  232. package/dist/esm/stateManagement/annotation/AnnotationRenderingEngine.js +112 -0
  233. package/dist/esm/stateManagement/annotation/FrameOfReferenceSpecificAnnotationManager.d.ts +27 -0
  234. package/dist/esm/stateManagement/annotation/FrameOfReferenceSpecificAnnotationManager.js +210 -0
  235. package/dist/esm/stateManagement/annotation/annotationLocking.d.ts +7 -0
  236. package/dist/esm/stateManagement/annotation/annotationLocking.js +73 -0
  237. package/dist/esm/stateManagement/annotation/annotationSelection.d.ts +7 -0
  238. package/dist/esm/stateManagement/annotation/annotationSelection.js +85 -0
  239. package/dist/esm/stateManagement/annotation/annotationState.d.ts +18 -0
  240. package/dist/esm/stateManagement/annotation/annotationState.js +118 -0
  241. package/dist/esm/stateManagement/annotation/annotationVisibility.d.ts +5 -0
  242. package/dist/esm/stateManagement/annotation/annotationVisibility.js +65 -0
  243. package/dist/esm/stateManagement/annotation/config/ToolStyle.d.ts +18 -0
  244. package/dist/esm/stateManagement/annotation/config/ToolStyle.js +135 -0
  245. package/dist/esm/stateManagement/annotation/config/getFont.d.ts +4 -0
  246. package/dist/esm/stateManagement/annotation/config/getFont.js +7 -0
  247. package/dist/esm/stateManagement/annotation/config/getState.d.ts +4 -0
  248. package/dist/esm/stateManagement/annotation/config/getState.js +21 -0
  249. package/dist/esm/stateManagement/annotation/config/helpers.d.ts +4 -0
  250. package/dist/esm/stateManagement/annotation/config/helpers.js +21 -0
  251. package/dist/esm/stateManagement/annotation/config/index.d.ts +4 -0
  252. package/dist/esm/stateManagement/annotation/config/index.js +4 -0
  253. package/dist/esm/stateManagement/annotation/helpers/state.d.ts +10 -0
  254. package/dist/esm/stateManagement/annotation/helpers/state.js +76 -0
  255. package/dist/esm/stateManagement/annotation/index.d.ts +34 -0
  256. package/dist/esm/stateManagement/annotation/index.js +15 -0
  257. package/dist/esm/stateManagement/annotation/resetAnnotationManager.d.ts +1 -0
  258. package/dist/esm/stateManagement/annotation/resetAnnotationManager.js +21 -0
  259. package/dist/esm/stateManagement/annotation/utilities/defineProperties.d.ts +4 -0
  260. package/dist/esm/stateManagement/annotation/utilities/defineProperties.js +22 -0
  261. package/dist/esm/stateManagement/index.d.ts +18 -0
  262. package/dist/esm/stateManagement/index.js +6 -0
  263. package/dist/esm/stateManagement/segmentation/SegmentationRenderingEngine.d.ts +20 -0
  264. package/dist/esm/stateManagement/segmentation/SegmentationRenderingEngine.js +153 -0
  265. package/dist/esm/stateManagement/segmentation/SegmentationStateManager.d.ts +91 -0
  266. package/dist/esm/stateManagement/segmentation/SegmentationStateManager.js +470 -0
  267. package/dist/esm/stateManagement/segmentation/SegmentationStyle.d.ts +39 -0
  268. package/dist/esm/stateManagement/segmentation/SegmentationStyle.js +223 -0
  269. package/dist/esm/stateManagement/segmentation/activeSegmentation.d.ts +4 -0
  270. package/dist/esm/stateManagement/segmentation/activeSegmentation.js +9 -0
  271. package/dist/esm/stateManagement/segmentation/addColorLUT.d.ts +2 -0
  272. package/dist/esm/stateManagement/segmentation/addColorLUT.js +25 -0
  273. package/dist/esm/stateManagement/segmentation/addSegmentationRepresentationsToViewport.d.ts +15 -0
  274. package/dist/esm/stateManagement/segmentation/addSegmentationRepresentationsToViewport.js +49 -0
  275. package/dist/esm/stateManagement/segmentation/addSegmentations.d.ts +3 -0
  276. package/dist/esm/stateManagement/segmentation/addSegmentations.js +14 -0
  277. package/dist/esm/stateManagement/segmentation/config/index.d.ts +4 -0
  278. package/dist/esm/stateManagement/segmentation/config/index.js +4 -0
  279. package/dist/esm/stateManagement/segmentation/config/segmentationColor.d.ts +6 -0
  280. package/dist/esm/stateManagement/segmentation/config/segmentationColor.js +50 -0
  281. package/dist/esm/stateManagement/segmentation/config/segmentationVisibility.d.ts +22 -0
  282. package/dist/esm/stateManagement/segmentation/config/segmentationVisibility.js +49 -0
  283. package/dist/esm/stateManagement/segmentation/config/styleHelpers.d.ts +25 -0
  284. package/dist/esm/stateManagement/segmentation/config/styleHelpers.js +37 -0
  285. package/dist/esm/stateManagement/segmentation/events/triggerSegmentationAdded.d.ts +1 -0
  286. package/dist/esm/stateManagement/segmentation/events/triggerSegmentationAdded.js +8 -0
  287. package/dist/esm/stateManagement/segmentation/events/triggerSegmentationDataModified.d.ts +1 -0
  288. package/dist/esm/stateManagement/segmentation/events/triggerSegmentationDataModified.js +12 -0
  289. package/dist/esm/stateManagement/segmentation/events/triggerSegmentationModified.d.ts +1 -0
  290. package/dist/esm/stateManagement/segmentation/events/triggerSegmentationModified.js +8 -0
  291. package/dist/esm/stateManagement/segmentation/events/triggerSegmentationRemoved.d.ts +1 -0
  292. package/dist/esm/stateManagement/segmentation/events/triggerSegmentationRemoved.js +8 -0
  293. package/dist/esm/stateManagement/segmentation/events/triggerSegmentationRepresentationModified.d.ts +2 -0
  294. package/dist/esm/stateManagement/segmentation/events/triggerSegmentationRepresentationModified.js +10 -0
  295. package/dist/esm/stateManagement/segmentation/events/triggerSegmentationRepresentationRemoved.d.ts +2 -0
  296. package/dist/esm/stateManagement/segmentation/events/triggerSegmentationRepresentationRemoved.js +10 -0
  297. package/dist/esm/stateManagement/segmentation/getActiveSegmentIndex.d.ts +1 -0
  298. package/dist/esm/stateManagement/segmentation/getActiveSegmentIndex.js +9 -0
  299. package/dist/esm/stateManagement/segmentation/getActiveSegmentation.d.ts +2 -0
  300. package/dist/esm/stateManagement/segmentation/getActiveSegmentation.js +5 -0
  301. package/dist/esm/stateManagement/segmentation/getColorLUT.d.ts +2 -0
  302. package/dist/esm/stateManagement/segmentation/getColorLUT.js +5 -0
  303. package/dist/esm/stateManagement/segmentation/getCurrentLabelmapImageIdForViewport.d.ts +1 -0
  304. package/dist/esm/stateManagement/segmentation/getCurrentLabelmapImageIdForViewport.js +5 -0
  305. package/dist/esm/stateManagement/segmentation/getGlobalStyle.d.ts +3 -0
  306. package/dist/esm/stateManagement/segmentation/getGlobalStyle.js +4 -0
  307. package/dist/esm/stateManagement/segmentation/getLabelmapImageIds.d.ts +1 -0
  308. package/dist/esm/stateManagement/segmentation/getLabelmapImageIds.js +7 -0
  309. package/dist/esm/stateManagement/segmentation/getNextColorLUTIndex.d.ts +1 -0
  310. package/dist/esm/stateManagement/segmentation/getNextColorLUTIndex.js +5 -0
  311. package/dist/esm/stateManagement/segmentation/getSegmentation.d.ts +2 -0
  312. package/dist/esm/stateManagement/segmentation/getSegmentation.js +5 -0
  313. package/dist/esm/stateManagement/segmentation/getSegmentationRepresentation.d.ts +14 -0
  314. package/dist/esm/stateManagement/segmentation/getSegmentationRepresentation.js +17 -0
  315. package/dist/esm/stateManagement/segmentation/getSegmentationRepresentationVisibility.d.ts +5 -0
  316. package/dist/esm/stateManagement/segmentation/getSegmentationRepresentationVisibility.js +5 -0
  317. package/dist/esm/stateManagement/segmentation/getSegmentations.d.ts +2 -0
  318. package/dist/esm/stateManagement/segmentation/getSegmentations.js +6 -0
  319. package/dist/esm/stateManagement/segmentation/getStackSegmentationImageIdsForViewport.d.ts +1 -0
  320. package/dist/esm/stateManagement/segmentation/getStackSegmentationImageIdsForViewport.js +5 -0
  321. package/dist/esm/stateManagement/segmentation/getViewportIdsWithSegmentation.d.ts +1 -0
  322. package/dist/esm/stateManagement/segmentation/getViewportIdsWithSegmentation.js +10 -0
  323. package/dist/esm/stateManagement/segmentation/getViewportSegmentations.d.ts +3 -0
  324. package/dist/esm/stateManagement/segmentation/getViewportSegmentations.js +15 -0
  325. package/dist/esm/stateManagement/segmentation/helpers/clearSegmentValue.d.ts +1 -0
  326. package/dist/esm/stateManagement/segmentation/helpers/clearSegmentValue.js +30 -0
  327. package/dist/esm/stateManagement/segmentation/helpers/computeStackLabelmapFromVolume.d.ts +13 -0
  328. package/dist/esm/stateManagement/segmentation/helpers/computeStackLabelmapFromVolume.js +22 -0
  329. package/dist/esm/stateManagement/segmentation/helpers/computeVolumeLabelmapFromStack.d.ts +3 -0
  330. package/dist/esm/stateManagement/segmentation/helpers/computeVolumeLabelmapFromStack.js +4 -0
  331. package/dist/esm/stateManagement/segmentation/helpers/convertStackToVolumeLabelmap.d.ts +1 -0
  332. package/dist/esm/stateManagement/segmentation/helpers/convertStackToVolumeLabelmap.js +7 -0
  333. package/dist/esm/stateManagement/segmentation/helpers/getSegmentationActor.d.ts +6 -0
  334. package/dist/esm/stateManagement/segmentation/helpers/getSegmentationActor.js +34 -0
  335. package/dist/esm/stateManagement/segmentation/helpers/index.d.ts +3 -0
  336. package/dist/esm/stateManagement/segmentation/helpers/index.js +3 -0
  337. package/dist/esm/stateManagement/segmentation/helpers/internalGetHiddenSegmentIndices.d.ts +5 -0
  338. package/dist/esm/stateManagement/segmentation/helpers/internalGetHiddenSegmentIndices.js +14 -0
  339. package/dist/esm/stateManagement/segmentation/helpers/normalizeSegmentationInput.d.ts +3 -0
  340. package/dist/esm/stateManagement/segmentation/helpers/normalizeSegmentationInput.js +71 -0
  341. package/dist/esm/stateManagement/segmentation/helpers/updateStackSegmentationState.d.ts +8 -0
  342. package/dist/esm/stateManagement/segmentation/helpers/updateStackSegmentationState.js +31 -0
  343. package/dist/esm/stateManagement/segmentation/helpers/validateSegmentationInput.d.ts +3 -0
  344. package/dist/esm/stateManagement/segmentation/helpers/validateSegmentationInput.js +20 -0
  345. package/dist/esm/stateManagement/segmentation/index.d.ts +28 -0
  346. package/dist/esm/stateManagement/segmentation/index.js +28 -0
  347. package/dist/esm/stateManagement/segmentation/internalAddRepresentationData.d.ts +12 -0
  348. package/dist/esm/stateManagement/segmentation/internalAddRepresentationData.js +32 -0
  349. package/dist/esm/stateManagement/segmentation/internalAddSegmentationRepresentation.d.ts +3 -0
  350. package/dist/esm/stateManagement/segmentation/internalAddSegmentationRepresentation.js +38 -0
  351. package/dist/esm/stateManagement/segmentation/removeColorLUT.d.ts +1 -0
  352. package/dist/esm/stateManagement/segmentation/removeColorLUT.js +5 -0
  353. package/dist/esm/stateManagement/segmentation/removeSegment.d.ts +3 -0
  354. package/dist/esm/stateManagement/segmentation/removeSegment.js +50 -0
  355. package/dist/esm/stateManagement/segmentation/removeSegmentation.d.ts +2 -0
  356. package/dist/esm/stateManagement/segmentation/removeSegmentation.js +24 -0
  357. package/dist/esm/stateManagement/segmentation/removeSegmentationRepresentations.d.ts +20 -0
  358. package/dist/esm/stateManagement/segmentation/removeSegmentationRepresentations.js +73 -0
  359. package/dist/esm/stateManagement/segmentation/segmentIndex.d.ts +3 -0
  360. package/dist/esm/stateManagement/segmentation/segmentIndex.js +48 -0
  361. package/dist/esm/stateManagement/segmentation/segmentLocking.d.ts +4 -0
  362. package/dist/esm/stateManagement/segmentation/segmentLocking.js +29 -0
  363. package/dist/esm/stateManagement/segmentation/segmentationState.d.ts +17 -0
  364. package/dist/esm/stateManagement/segmentation/segmentationState.js +20 -0
  365. package/dist/esm/stateManagement/segmentation/setActiveSegmentation.d.ts +1 -0
  366. package/dist/esm/stateManagement/segmentation/setActiveSegmentation.js +5 -0
  367. package/dist/esm/stateManagement/segmentation/setGlobalStyle.d.ts +3 -0
  368. package/dist/esm/stateManagement/segmentation/setGlobalStyle.js +8 -0
  369. package/dist/esm/stateManagement/segmentation/setSegmentationRepresentationVisibility.d.ts +5 -0
  370. package/dist/esm/stateManagement/segmentation/setSegmentationRepresentationVisibility.js +5 -0
  371. package/dist/esm/stateManagement/segmentation/triggerSegmentationEvents.d.ts +6 -0
  372. package/dist/esm/stateManagement/segmentation/triggerSegmentationEvents.js +6 -0
  373. package/dist/esm/stateManagement/segmentation/updateLabelmapSegmentationImageReferences.d.ts +1 -0
  374. package/dist/esm/stateManagement/segmentation/updateLabelmapSegmentationImageReferences.js +5 -0
  375. package/dist/esm/stateManagement/segmentation/updateSegmentations.d.ts +5 -0
  376. package/dist/esm/stateManagement/segmentation/updateSegmentations.js +11 -0
  377. package/dist/esm/store/SynchronizerManager/Synchronizer.d.ts +48 -0
  378. package/dist/esm/store/SynchronizerManager/Synchronizer.js +221 -0
  379. package/dist/esm/store/SynchronizerManager/createSynchronizer.d.ts +4 -0
  380. package/dist/esm/store/SynchronizerManager/createSynchronizer.js +12 -0
  381. package/dist/esm/store/SynchronizerManager/destroy.d.ts +2 -0
  382. package/dist/esm/store/SynchronizerManager/destroy.js +8 -0
  383. package/dist/esm/store/SynchronizerManager/destroySynchronizer.d.ts +2 -0
  384. package/dist/esm/store/SynchronizerManager/destroySynchronizer.js +10 -0
  385. package/dist/esm/store/SynchronizerManager/getAllSynchronizers.d.ts +3 -0
  386. package/dist/esm/store/SynchronizerManager/getAllSynchronizers.js +5 -0
  387. package/dist/esm/store/SynchronizerManager/getSynchronizer.d.ts +3 -0
  388. package/dist/esm/store/SynchronizerManager/getSynchronizer.js +5 -0
  389. package/dist/esm/store/SynchronizerManager/getSynchronizersForViewport.d.ts +3 -0
  390. package/dist/esm/store/SynchronizerManager/getSynchronizersForViewport.js +18 -0
  391. package/dist/esm/store/SynchronizerManager/index.d.ts +7 -0
  392. package/dist/esm/store/SynchronizerManager/index.js +7 -0
  393. package/dist/esm/store/ToolGroupManager/ToolGroup.d.ts +48 -0
  394. package/dist/esm/store/ToolGroupManager/ToolGroup.js +460 -0
  395. package/dist/esm/store/ToolGroupManager/createToolGroup.d.ts +3 -0
  396. package/dist/esm/store/ToolGroupManager/createToolGroup.js +13 -0
  397. package/dist/esm/store/ToolGroupManager/destroy.d.ts +2 -0
  398. package/dist/esm/store/ToolGroupManager/destroy.js +10 -0
  399. package/dist/esm/store/ToolGroupManager/destroyToolGroup.d.ts +2 -0
  400. package/dist/esm/store/ToolGroupManager/destroyToolGroup.js +8 -0
  401. package/dist/esm/store/ToolGroupManager/getAllToolGroups.d.ts +3 -0
  402. package/dist/esm/store/ToolGroupManager/getAllToolGroups.js +5 -0
  403. package/dist/esm/store/ToolGroupManager/getToolGroup.d.ts +3 -0
  404. package/dist/esm/store/ToolGroupManager/getToolGroup.js +5 -0
  405. package/dist/esm/store/ToolGroupManager/getToolGroupForViewport.d.ts +3 -0
  406. package/dist/esm/store/ToolGroupManager/getToolGroupForViewport.js +18 -0
  407. package/dist/esm/store/ToolGroupManager/getToolGroupsWithToolName.d.ts +3 -0
  408. package/dist/esm/store/ToolGroupManager/getToolGroupsWithToolName.js +21 -0
  409. package/dist/esm/store/ToolGroupManager/index.d.ts +8 -0
  410. package/dist/esm/store/ToolGroupManager/index.js +8 -0
  411. package/dist/esm/store/addEnabledElement.d.ts +2 -0
  412. package/dist/esm/store/addEnabledElement.js +68 -0
  413. package/dist/esm/store/addTool.d.ts +5 -0
  414. package/dist/esm/store/addTool.js +31 -0
  415. package/dist/esm/store/cancelActiveManipulations.d.ts +1 -0
  416. package/dist/esm/store/cancelActiveManipulations.js +16 -0
  417. package/dist/esm/store/filterMoveableAnnotationTools.d.ts +3 -0
  418. package/dist/esm/store/filterMoveableAnnotationTools.js +20 -0
  419. package/dist/esm/store/filterToolsWithAnnotationsForElement.d.ts +3 -0
  420. package/dist/esm/store/filterToolsWithAnnotationsForElement.js +22 -0
  421. package/dist/esm/store/filterToolsWithMoveableHandles.d.ts +3 -0
  422. package/dist/esm/store/filterToolsWithMoveableHandles.js +21 -0
  423. package/dist/esm/store/index.d.ts +10 -0
  424. package/dist/esm/store/index.js +10 -0
  425. package/dist/esm/store/removeEnabledElement.d.ts +3 -0
  426. package/dist/esm/store/removeEnabledElement.js +85 -0
  427. package/dist/esm/store/state.d.ts +18 -0
  428. package/dist/esm/store/state.js +34 -0
  429. package/dist/esm/store/svgNodeCache.d.ts +3 -0
  430. package/dist/esm/store/svgNodeCache.js +5 -0
  431. package/dist/esm/synchronizers/callbacks/areViewportsCoplanar.d.ts +2 -0
  432. package/dist/esm/synchronizers/callbacks/areViewportsCoplanar.js +7 -0
  433. package/dist/esm/synchronizers/callbacks/cameraSyncCallback.d.ts +3 -0
  434. package/dist/esm/synchronizers/callbacks/cameraSyncCallback.js +11 -0
  435. package/dist/esm/synchronizers/callbacks/imageSliceSyncCallback.d.ts +3 -0
  436. package/dist/esm/synchronizers/callbacks/imageSliceSyncCallback.js +67 -0
  437. package/dist/esm/synchronizers/callbacks/presentationViewSyncCallback.d.ts +2 -0
  438. package/dist/esm/synchronizers/callbacks/presentationViewSyncCallback.js +12 -0
  439. package/dist/esm/synchronizers/callbacks/slabThicknessSyncCallback.d.ts +2 -0
  440. package/dist/esm/synchronizers/callbacks/slabThicknessSyncCallback.js +15 -0
  441. package/dist/esm/synchronizers/callbacks/voiSyncCallback.d.ts +5 -0
  442. package/dist/esm/synchronizers/callbacks/voiSyncCallback.js +35 -0
  443. package/dist/esm/synchronizers/callbacks/zoomPanSyncCallback.d.ts +3 -0
  444. package/dist/esm/synchronizers/callbacks/zoomPanSyncCallback.js +19 -0
  445. package/dist/esm/synchronizers/index.d.ts +8 -0
  446. package/dist/esm/synchronizers/index.js +8 -0
  447. package/dist/esm/synchronizers/synchronizers/createCameraPositionSynchronizer.d.ts +2 -0
  448. package/dist/esm/synchronizers/synchronizers/createCameraPositionSynchronizer.js +8 -0
  449. package/dist/esm/synchronizers/synchronizers/createImageSliceSynchronizer.d.ts +2 -0
  450. package/dist/esm/synchronizers/synchronizers/createImageSliceSynchronizer.js +14 -0
  451. package/dist/esm/synchronizers/synchronizers/createPresentationViewSynchronizer.d.ts +3 -0
  452. package/dist/esm/synchronizers/synchronizers/createPresentationViewSynchronizer.js +8 -0
  453. package/dist/esm/synchronizers/synchronizers/createSlabThicknessSynchronizer.d.ts +2 -0
  454. package/dist/esm/synchronizers/synchronizers/createSlabThicknessSynchronizer.js +8 -0
  455. package/dist/esm/synchronizers/synchronizers/createVOISynchronizer.d.ts +7 -0
  456. package/dist/esm/synchronizers/synchronizers/createVOISynchronizer.js +15 -0
  457. package/dist/esm/synchronizers/synchronizers/createZoomPanSynchronizer.d.ts +2 -0
  458. package/dist/esm/synchronizers/synchronizers/createZoomPanSynchronizer.js +8 -0
  459. package/dist/esm/synchronizers/synchronizers/index.d.ts +7 -0
  460. package/dist/esm/synchronizers/synchronizers/index.js +7 -0
  461. package/dist/esm/tools/AdvancedMagnifyTool.d.ts +130 -0
  462. package/dist/esm/tools/AdvancedMagnifyTool.js +927 -0
  463. package/dist/esm/tools/AnnotationEraserTool.d.ts +10 -0
  464. package/dist/esm/tools/AnnotationEraserTool.js +56 -0
  465. package/dist/esm/tools/CrosshairsTool.d.ts +71 -0
  466. package/dist/esm/tools/CrosshairsTool.js +1449 -0
  467. package/dist/esm/tools/MIPJumpToClickTool.d.ts +8 -0
  468. package/dist/esm/tools/MIPJumpToClickTool.js +56 -0
  469. package/dist/esm/tools/MagnifyTool.d.ts +25 -0
  470. package/dist/esm/tools/MagnifyTool.js +180 -0
  471. package/dist/esm/tools/OrientationMarkerTool.d.ts +78 -0
  472. package/dist/esm/tools/OrientationMarkerTool.js +284 -0
  473. package/dist/esm/tools/OverlayGridTool.d.ts +29 -0
  474. package/dist/esm/tools/OverlayGridTool.js +164 -0
  475. package/dist/esm/tools/PanTool.d.ts +10 -0
  476. package/dist/esm/tools/PanTool.js +44 -0
  477. package/dist/esm/tools/PlanarRotateTool.d.ts +12 -0
  478. package/dist/esm/tools/PlanarRotateTool.js +64 -0
  479. package/dist/esm/tools/ReferenceCursors.d.ts +24 -0
  480. package/dist/esm/tools/ReferenceCursors.js +308 -0
  481. package/dist/esm/tools/ReferenceLinesTool.d.ts +27 -0
  482. package/dist/esm/tools/ReferenceLinesTool.js +232 -0
  483. package/dist/esm/tools/ScaleOverlayTool.d.ts +38 -0
  484. package/dist/esm/tools/ScaleOverlayTool.js +397 -0
  485. package/dist/esm/tools/SculptorTool/CircleSculptCursor.d.ts +20 -0
  486. package/dist/esm/tools/SculptorTool/CircleSculptCursor.js +107 -0
  487. package/dist/esm/tools/SculptorTool.d.ts +41 -0
  488. package/dist/esm/tools/SculptorTool.js +289 -0
  489. package/dist/esm/tools/SegmentationIntersectionTool.d.ts +18 -0
  490. package/dist/esm/tools/SegmentationIntersectionTool.js +177 -0
  491. package/dist/esm/tools/StackScrollTool.d.ts +15 -0
  492. package/dist/esm/tools/StackScrollTool.js +78 -0
  493. package/dist/esm/tools/TrackballRotateTool.d.ts +19 -0
  494. package/dist/esm/tools/TrackballRotateTool.js +179 -0
  495. package/dist/esm/tools/VolumeRotateTool.d.ts +10 -0
  496. package/dist/esm/tools/VolumeRotateTool.js +52 -0
  497. package/dist/esm/tools/WindowLevelRegionTool.d.ts +26 -0
  498. package/dist/esm/tools/WindowLevelRegionTool.js +220 -0
  499. package/dist/esm/tools/WindowLevelTool.d.ts +37 -0
  500. package/dist/esm/tools/WindowLevelTool.js +201 -0
  501. package/dist/esm/tools/ZoomTool.d.ts +19 -0
  502. package/dist/esm/tools/ZoomTool.js +180 -0
  503. package/dist/esm/tools/annotation/AngleTool.d.ts +37 -0
  504. package/dist/esm/tools/annotation/AngleTool.js +486 -0
  505. package/dist/esm/tools/annotation/ArrowAnnotateTool.d.ts +39 -0
  506. package/dist/esm/tools/annotation/ArrowAnnotateTool.js +467 -0
  507. package/dist/esm/tools/annotation/BidirectionalTool.d.ts +40 -0
  508. package/dist/esm/tools/annotation/BidirectionalTool.js +728 -0
  509. package/dist/esm/tools/annotation/CircleROITool.d.ts +39 -0
  510. package/dist/esm/tools/annotation/CircleROITool.js +638 -0
  511. package/dist/esm/tools/annotation/CobbAngleTool.d.ts +61 -0
  512. package/dist/esm/tools/annotation/CobbAngleTool.js +688 -0
  513. package/dist/esm/tools/annotation/DragProbeTool.d.ts +23 -0
  514. package/dist/esm/tools/annotation/DragProbeTool.js +130 -0
  515. package/dist/esm/tools/annotation/ETDRSGridTool.d.ts +41 -0
  516. package/dist/esm/tools/annotation/ETDRSGridTool.js +354 -0
  517. package/dist/esm/tools/annotation/EllipticalROITool.d.ts +45 -0
  518. package/dist/esm/tools/annotation/EllipticalROITool.js +710 -0
  519. package/dist/esm/tools/annotation/HeightTool.d.ts +36 -0
  520. package/dist/esm/tools/annotation/HeightTool.js +434 -0
  521. package/dist/esm/tools/annotation/KeyImageTool.d.ts +34 -0
  522. package/dist/esm/tools/annotation/KeyImageTool.js +269 -0
  523. package/dist/esm/tools/annotation/LabelTool.d.ts +35 -0
  524. package/dist/esm/tools/annotation/LabelTool.js +323 -0
  525. package/dist/esm/tools/annotation/LengthTool.d.ts +38 -0
  526. package/dist/esm/tools/annotation/LengthTool.js +468 -0
  527. package/dist/esm/tools/annotation/LivewireContourSegmentationTool.d.ts +10 -0
  528. package/dist/esm/tools/annotation/LivewireContourSegmentationTool.js +89 -0
  529. package/dist/esm/tools/annotation/LivewireContourTool.d.ts +67 -0
  530. package/dist/esm/tools/annotation/LivewireContourTool.js +657 -0
  531. package/dist/esm/tools/annotation/PlanarFreehandContourSegmentationTool.d.ts +9 -0
  532. package/dist/esm/tools/annotation/PlanarFreehandContourSegmentationTool.js +29 -0
  533. package/dist/esm/tools/annotation/PlanarFreehandROITool.d.ts +59 -0
  534. package/dist/esm/tools/annotation/PlanarFreehandROITool.js +530 -0
  535. package/dist/esm/tools/annotation/ProbeTool.d.ts +35 -0
  536. package/dist/esm/tools/annotation/ProbeTool.js +363 -0
  537. package/dist/esm/tools/annotation/RectangleROITool.d.ts +43 -0
  538. package/dist/esm/tools/annotation/RectangleROITool.js +566 -0
  539. package/dist/esm/tools/annotation/RegionSegmentPlusTool.d.ts +16 -0
  540. package/dist/esm/tools/annotation/RegionSegmentPlusTool.js +55 -0
  541. package/dist/esm/tools/annotation/RegionSegmentTool.d.ts +21 -0
  542. package/dist/esm/tools/annotation/RegionSegmentTool.js +102 -0
  543. package/dist/esm/tools/annotation/SplineContourSegmentationTool.d.ts +8 -0
  544. package/dist/esm/tools/annotation/SplineContourSegmentationTool.js +17 -0
  545. package/dist/esm/tools/annotation/SplineROITool.d.ts +73 -0
  546. package/dist/esm/tools/annotation/SplineROITool.js +788 -0
  547. package/dist/esm/tools/annotation/UltrasoundDirectionalTool.d.ts +34 -0
  548. package/dist/esm/tools/annotation/UltrasoundDirectionalTool.js +461 -0
  549. package/dist/esm/tools/annotation/VideoRedactionTool.d.ts +46 -0
  550. package/dist/esm/tools/annotation/VideoRedactionTool.js +442 -0
  551. package/dist/esm/tools/annotation/WholeBodySegmentTool.d.ts +29 -0
  552. package/dist/esm/tools/annotation/WholeBodySegmentTool.js +223 -0
  553. package/dist/esm/tools/annotation/planarFreehandROITool/closedContourEditLoop.d.ts +2 -0
  554. package/dist/esm/tools/annotation/planarFreehandROITool/closedContourEditLoop.js +260 -0
  555. package/dist/esm/tools/annotation/planarFreehandROITool/drawLoop.d.ts +2 -0
  556. package/dist/esm/tools/annotation/planarFreehandROITool/drawLoop.js +289 -0
  557. package/dist/esm/tools/annotation/planarFreehandROITool/editLoopCommon.d.ts +2 -0
  558. package/dist/esm/tools/annotation/planarFreehandROITool/editLoopCommon.js +146 -0
  559. package/dist/esm/tools/annotation/planarFreehandROITool/findOpenUShapedContourVectorToPeak.d.ts +4 -0
  560. package/dist/esm/tools/annotation/planarFreehandROITool/findOpenUShapedContourVectorToPeak.js +39 -0
  561. package/dist/esm/tools/annotation/planarFreehandROITool/openContourEditLoop.d.ts +2 -0
  562. package/dist/esm/tools/annotation/planarFreehandROITool/openContourEditLoop.js +329 -0
  563. package/dist/esm/tools/annotation/planarFreehandROITool/openContourEndEditLoop.d.ts +2 -0
  564. package/dist/esm/tools/annotation/planarFreehandROITool/openContourEndEditLoop.js +48 -0
  565. package/dist/esm/tools/annotation/planarFreehandROITool/renderMethods.d.ts +2 -0
  566. package/dist/esm/tools/annotation/planarFreehandROITool/renderMethods.js +216 -0
  567. package/dist/esm/tools/annotation/splines/BSpline.d.ts +5 -0
  568. package/dist/esm/tools/annotation/splines/BSpline.js +9 -0
  569. package/dist/esm/tools/annotation/splines/CardinalSpline.d.ts +12 -0
  570. package/dist/esm/tools/annotation/splines/CardinalSpline.js +32 -0
  571. package/dist/esm/tools/annotation/splines/CatmullRomSpline.d.ts +5 -0
  572. package/dist/esm/tools/annotation/splines/CatmullRomSpline.js +7 -0
  573. package/dist/esm/tools/annotation/splines/CubicSpline.d.ts +13 -0
  574. package/dist/esm/tools/annotation/splines/CubicSpline.js +164 -0
  575. package/dist/esm/tools/annotation/splines/LinearSpline.d.ts +5 -0
  576. package/dist/esm/tools/annotation/splines/LinearSpline.js +7 -0
  577. package/dist/esm/tools/annotation/splines/QuadraticBezier.d.ts +6 -0
  578. package/dist/esm/tools/annotation/splines/QuadraticBezier.js +15 -0
  579. package/dist/esm/tools/annotation/splines/QuadraticSpline.d.ts +9 -0
  580. package/dist/esm/tools/annotation/splines/QuadraticSpline.js +13 -0
  581. package/dist/esm/tools/annotation/splines/Spline.d.ts +51 -0
  582. package/dist/esm/tools/annotation/splines/Spline.js +395 -0
  583. package/dist/esm/tools/annotation/splines/index.d.ts +9 -0
  584. package/dist/esm/tools/annotation/splines/index.js +9 -0
  585. package/dist/esm/tools/base/AnnotationDisplayTool.d.ts +14 -0
  586. package/dist/esm/tools/base/AnnotationDisplayTool.js +98 -0
  587. package/dist/esm/tools/base/AnnotationTool.d.ts +71 -0
  588. package/dist/esm/tools/base/AnnotationTool.js +271 -0
  589. package/dist/esm/tools/base/BaseTool.d.ts +38 -0
  590. package/dist/esm/tools/base/BaseTool.js +128 -0
  591. package/dist/esm/tools/base/ContourBaseTool.d.ts +25 -0
  592. package/dist/esm/tools/base/ContourBaseTool.js +121 -0
  593. package/dist/esm/tools/base/ContourSegmentationBaseTool.d.ts +19 -0
  594. package/dist/esm/tools/base/ContourSegmentationBaseTool.js +133 -0
  595. package/dist/esm/tools/base/GrowCutBaseTool.d.ts +64 -0
  596. package/dist/esm/tools/base/GrowCutBaseTool.js +209 -0
  597. package/dist/esm/tools/base/index.d.ts +4 -0
  598. package/dist/esm/tools/base/index.js +4 -0
  599. package/dist/esm/tools/displayTools/Contour/contourConfig.d.ts +3 -0
  600. package/dist/esm/tools/displayTools/Contour/contourConfig.js +20 -0
  601. package/dist/esm/tools/displayTools/Contour/contourDisplay.d.ts +9 -0
  602. package/dist/esm/tools/displayTools/Contour/contourDisplay.js +51 -0
  603. package/dist/esm/tools/displayTools/Contour/contourHandler/handleContourSegmentation.d.ts +5 -0
  604. package/dist/esm/tools/displayTools/Contour/contourHandler/handleContourSegmentation.js +77 -0
  605. package/dist/esm/tools/displayTools/Contour/contourHandler/utils.d.ts +4 -0
  606. package/dist/esm/tools/displayTools/Contour/contourHandler/utils.js +41 -0
  607. package/dist/esm/tools/displayTools/Contour/index.d.ts +2 -0
  608. package/dist/esm/tools/displayTools/Contour/index.js +2 -0
  609. package/dist/esm/tools/displayTools/Contour/removeContourFromElement.d.ts +2 -0
  610. package/dist/esm/tools/displayTools/Contour/removeContourFromElement.js +12 -0
  611. package/dist/esm/tools/displayTools/Labelmap/addLabelmapToElement.d.ts +7 -0
  612. package/dist/esm/tools/displayTools/Labelmap/addLabelmapToElement.js +93 -0
  613. package/dist/esm/tools/displayTools/Labelmap/addVolumesAsIndependentComponents.d.ts +10 -0
  614. package/dist/esm/tools/displayTools/Labelmap/addVolumesAsIndependentComponents.js +123 -0
  615. package/dist/esm/tools/displayTools/Labelmap/index.d.ts +4 -0
  616. package/dist/esm/tools/displayTools/Labelmap/index.js +4 -0
  617. package/dist/esm/tools/displayTools/Labelmap/labelmapConfig.d.ts +3 -0
  618. package/dist/esm/tools/displayTools/Labelmap/labelmapConfig.js +17 -0
  619. package/dist/esm/tools/displayTools/Labelmap/labelmapDisplay.d.ts +11 -0
  620. package/dist/esm/tools/displayTools/Labelmap/labelmapDisplay.js +267 -0
  621. package/dist/esm/tools/displayTools/Labelmap/removeLabelmapFromElement.d.ts +2 -0
  622. package/dist/esm/tools/displayTools/Labelmap/removeLabelmapFromElement.js +8 -0
  623. package/dist/esm/tools/displayTools/Surface/addOrUpdateSurfaceToElement.d.ts +3 -0
  624. package/dist/esm/tools/displayTools/Surface/addOrUpdateSurfaceToElement.js +67 -0
  625. package/dist/esm/tools/displayTools/Surface/index.d.ts +2 -0
  626. package/dist/esm/tools/displayTools/Surface/index.js +2 -0
  627. package/dist/esm/tools/displayTools/Surface/removeSurfaceFromElement.d.ts +2 -0
  628. package/dist/esm/tools/displayTools/Surface/removeSurfaceFromElement.js +10 -0
  629. package/dist/esm/tools/displayTools/Surface/surfaceConfig.d.ts +3 -0
  630. package/dist/esm/tools/displayTools/Surface/surfaceConfig.js +8 -0
  631. package/dist/esm/tools/displayTools/Surface/surfaceDisplay.d.ts +10 -0
  632. package/dist/esm/tools/displayTools/Surface/surfaceDisplay.js +76 -0
  633. package/dist/esm/tools/distancePointToContour.d.ts +3 -0
  634. package/dist/esm/tools/distancePointToContour.js +18 -0
  635. package/dist/esm/tools/index.d.ts +57 -0
  636. package/dist/esm/tools/index.js +57 -0
  637. package/dist/esm/tools/segmentation/BrushTool.d.ts +27 -0
  638. package/dist/esm/tools/segmentation/BrushTool.js +355 -0
  639. package/dist/esm/tools/segmentation/CircleROIStartEndThresholdTool.d.ts +68 -0
  640. package/dist/esm/tools/segmentation/CircleROIStartEndThresholdTool.js +478 -0
  641. package/dist/esm/tools/segmentation/CircleScissorsTool.d.ts +34 -0
  642. package/dist/esm/tools/segmentation/CircleScissorsTool.js +233 -0
  643. package/dist/esm/tools/segmentation/LabelmapBaseTool.d.ts +99 -0
  644. package/dist/esm/tools/segmentation/LabelmapBaseTool.js +289 -0
  645. package/dist/esm/tools/segmentation/PaintFillTool.d.ts +13 -0
  646. package/dist/esm/tools/segmentation/PaintFillTool.js +231 -0
  647. package/dist/esm/tools/segmentation/RectangleROIStartEndThresholdTool.d.ts +69 -0
  648. package/dist/esm/tools/segmentation/RectangleROIStartEndThresholdTool.js +437 -0
  649. package/dist/esm/tools/segmentation/RectangleROIThresholdTool.d.ts +45 -0
  650. package/dist/esm/tools/segmentation/RectangleROIThresholdTool.js +145 -0
  651. package/dist/esm/tools/segmentation/RectangleScissorsTool.d.ts +32 -0
  652. package/dist/esm/tools/segmentation/RectangleScissorsTool.js +227 -0
  653. package/dist/esm/tools/segmentation/SegmentSelectTool.d.ts +20 -0
  654. package/dist/esm/tools/segmentation/SegmentSelectTool.js +99 -0
  655. package/dist/esm/tools/segmentation/SphereScissorsTool.d.ts +33 -0
  656. package/dist/esm/tools/segmentation/SphereScissorsTool.js +227 -0
  657. package/dist/esm/tools/segmentation/strategies/BrushStrategy.d.ts +125 -0
  658. package/dist/esm/tools/segmentation/strategies/BrushStrategy.js +156 -0
  659. package/dist/esm/tools/segmentation/strategies/compositions/determineSegmentIndex.d.ts +6 -0
  660. package/dist/esm/tools/segmentation/strategies/compositions/determineSegmentIndex.js +59 -0
  661. package/dist/esm/tools/segmentation/strategies/compositions/dynamicThreshold.d.ts +7 -0
  662. package/dist/esm/tools/segmentation/strategies/compositions/dynamicThreshold.js +83 -0
  663. package/dist/esm/tools/segmentation/strategies/compositions/ensureImageVolume.d.ts +4 -0
  664. package/dist/esm/tools/segmentation/strategies/compositions/ensureImageVolume.js +35 -0
  665. package/dist/esm/tools/segmentation/strategies/compositions/ensureSegmentationVolume.d.ts +4 -0
  666. package/dist/esm/tools/segmentation/strategies/compositions/ensureSegmentationVolume.js +20 -0
  667. package/dist/esm/tools/segmentation/strategies/compositions/erase.d.ts +5 -0
  668. package/dist/esm/tools/segmentation/strategies/compositions/erase.js +6 -0
  669. package/dist/esm/tools/segmentation/strategies/compositions/index.d.ts +47 -0
  670. package/dist/esm/tools/segmentation/strategies/compositions/index.js +24 -0
  671. package/dist/esm/tools/segmentation/strategies/compositions/islandRemovalComposition.d.ts +5 -0
  672. package/dist/esm/tools/segmentation/strategies/compositions/islandRemovalComposition.js +28 -0
  673. package/dist/esm/tools/segmentation/strategies/compositions/labelmapStatistics.d.ts +7 -0
  674. package/dist/esm/tools/segmentation/strategies/compositions/labelmapStatistics.js +12 -0
  675. package/dist/esm/tools/segmentation/strategies/compositions/preview.d.ts +8 -0
  676. package/dist/esm/tools/segmentation/strategies/compositions/preview.js +92 -0
  677. package/dist/esm/tools/segmentation/strategies/compositions/regionFill.d.ts +5 -0
  678. package/dist/esm/tools/segmentation/strategies/compositions/regionFill.js +23 -0
  679. package/dist/esm/tools/segmentation/strategies/compositions/setValue.d.ts +8 -0
  680. package/dist/esm/tools/segmentation/strategies/compositions/setValue.js +29 -0
  681. package/dist/esm/tools/segmentation/strategies/compositions/threshold.d.ts +5 -0
  682. package/dist/esm/tools/segmentation/strategies/compositions/threshold.js +21 -0
  683. package/dist/esm/tools/segmentation/strategies/eraseCircle.d.ts +2 -0
  684. package/dist/esm/tools/segmentation/strategies/eraseCircle.js +6 -0
  685. package/dist/esm/tools/segmentation/strategies/eraseRectangle.d.ts +8 -0
  686. package/dist/esm/tools/segmentation/strategies/eraseRectangle.js +13 -0
  687. package/dist/esm/tools/segmentation/strategies/eraseSphere.d.ts +2 -0
  688. package/dist/esm/tools/segmentation/strategies/eraseSphere.js +6 -0
  689. package/dist/esm/tools/segmentation/strategies/fillCircle.d.ts +14 -0
  690. package/dist/esm/tools/segmentation/strategies/fillCircle.js +71 -0
  691. package/dist/esm/tools/segmentation/strategies/fillRectangle.d.ts +6 -0
  692. package/dist/esm/tools/segmentation/strategies/fillRectangle.js +71 -0
  693. package/dist/esm/tools/segmentation/strategies/fillSphere.d.ts +7 -0
  694. package/dist/esm/tools/segmentation/strategies/fillSphere.js +40 -0
  695. package/dist/esm/tools/segmentation/strategies/index.d.ts +3 -0
  696. package/dist/esm/tools/segmentation/strategies/index.js +3 -0
  697. package/dist/esm/tools/segmentation/strategies/utils/getStrategyData.d.ts +15 -0
  698. package/dist/esm/tools/segmentation/strategies/utils/getStrategyData.js +112 -0
  699. package/dist/esm/tools/segmentation/strategies/utils/isWithinThreshold.d.ts +5 -0
  700. package/dist/esm/tools/segmentation/strategies/utils/isWithinThreshold.js +8 -0
  701. package/dist/esm/types/AnnotationGroupSelector.d.ts +2 -0
  702. package/dist/esm/types/AnnotationGroupSelector.js +0 -0
  703. package/dist/esm/types/AnnotationRenderContext.d.ts +12 -0
  704. package/dist/esm/types/AnnotationRenderContext.js +0 -0
  705. package/dist/esm/types/AnnotationStyle.d.ts +30 -0
  706. package/dist/esm/types/AnnotationStyle.js +0 -0
  707. package/dist/esm/types/AnnotationTypes.d.ts +45 -0
  708. package/dist/esm/types/AnnotationTypes.js +0 -0
  709. package/dist/esm/types/BoundsIJK.d.ts +3 -0
  710. package/dist/esm/types/BoundsIJK.js +0 -0
  711. package/dist/esm/types/CINETypes.d.ts +30 -0
  712. package/dist/esm/types/CINETypes.js +0 -0
  713. package/dist/esm/types/CalculatorTypes.d.ts +42 -0
  714. package/dist/esm/types/CalculatorTypes.js +0 -0
  715. package/dist/esm/types/CardinalSplineProps.d.ts +5 -0
  716. package/dist/esm/types/CardinalSplineProps.js +0 -0
  717. package/dist/esm/types/ClosestControlPoint.d.ts +4 -0
  718. package/dist/esm/types/ClosestControlPoint.js +0 -0
  719. package/dist/esm/types/ClosestPoint.d.ts +5 -0
  720. package/dist/esm/types/ClosestPoint.js +0 -0
  721. package/dist/esm/types/ClosestSplinePoint.d.ts +4 -0
  722. package/dist/esm/types/ClosestSplinePoint.js +0 -0
  723. package/dist/esm/types/ContourAnnotation.d.ts +20 -0
  724. package/dist/esm/types/ContourAnnotation.js +6 -0
  725. package/dist/esm/types/ContourSegmentationAnnotation.d.ts +24 -0
  726. package/dist/esm/types/ContourSegmentationAnnotation.js +0 -0
  727. package/dist/esm/types/ContourTypes.d.ts +27 -0
  728. package/dist/esm/types/ContourTypes.js +0 -0
  729. package/dist/esm/types/ControlPointInfo.d.ts +5 -0
  730. package/dist/esm/types/ControlPointInfo.js +0 -0
  731. package/dist/esm/types/CursorTypes.d.ts +18 -0
  732. package/dist/esm/types/CursorTypes.js +0 -0
  733. package/dist/esm/types/EventTypes.d.ts +234 -0
  734. package/dist/esm/types/EventTypes.js +0 -0
  735. package/dist/esm/types/FloodFillTypes.d.ts +16 -0
  736. package/dist/esm/types/FloodFillTypes.js +0 -0
  737. package/dist/esm/types/IAnnotationManager.d.ts +14 -0
  738. package/dist/esm/types/IAnnotationManager.js +0 -0
  739. package/dist/esm/types/IBaseTool.d.ts +2 -0
  740. package/dist/esm/types/IBaseTool.js +0 -0
  741. package/dist/esm/types/IDistance.d.ts +7 -0
  742. package/dist/esm/types/IDistance.js +0 -0
  743. package/dist/esm/types/IPoints.d.ts +8 -0
  744. package/dist/esm/types/IPoints.js +0 -0
  745. package/dist/esm/types/ISculptToolShape.d.ts +12 -0
  746. package/dist/esm/types/ISculptToolShape.js +0 -0
  747. package/dist/esm/types/ISetToolModeOptions.d.ts +16 -0
  748. package/dist/esm/types/ISetToolModeOptions.js +0 -0
  749. package/dist/esm/types/ISpline.d.ts +30 -0
  750. package/dist/esm/types/ISpline.js +0 -0
  751. package/dist/esm/types/ISynchronizerEventHandler.d.ts +5 -0
  752. package/dist/esm/types/ISynchronizerEventHandler.js +0 -0
  753. package/dist/esm/types/IToolClassReference.d.ts +3 -0
  754. package/dist/esm/types/IToolClassReference.js +0 -0
  755. package/dist/esm/types/IToolGroup.d.ts +3 -0
  756. package/dist/esm/types/IToolGroup.js +0 -0
  757. package/dist/esm/types/ITouchPoints.d.ts +11 -0
  758. package/dist/esm/types/ITouchPoints.js +0 -0
  759. package/dist/esm/types/InteractionTypes.d.ts +2 -0
  760. package/dist/esm/types/InteractionTypes.js +0 -0
  761. package/dist/esm/types/InternalToolTypes.d.ts +15 -0
  762. package/dist/esm/types/InternalToolTypes.js +0 -0
  763. package/dist/esm/types/InterpolationTypes.d.ts +20 -0
  764. package/dist/esm/types/InterpolationTypes.js +0 -0
  765. package/dist/esm/types/LabelmapToolOperationData.d.ts +26 -0
  766. package/dist/esm/types/LabelmapToolOperationData.js +0 -0
  767. package/dist/esm/types/LabelmapTypes.d.ts +29 -0
  768. package/dist/esm/types/LabelmapTypes.js +0 -0
  769. package/dist/esm/types/PlanarBoundingBox.d.ts +7 -0
  770. package/dist/esm/types/PlanarBoundingBox.js +0 -0
  771. package/dist/esm/types/SVGDrawingHelper.d.ts +9 -0
  772. package/dist/esm/types/SVGDrawingHelper.js +0 -0
  773. package/dist/esm/types/SegmentationStateTypes.d.ts +96 -0
  774. package/dist/esm/types/SegmentationStateTypes.js +0 -0
  775. package/dist/esm/types/SplineCurveSegment.d.ts +14 -0
  776. package/dist/esm/types/SplineCurveSegment.js +0 -0
  777. package/dist/esm/types/SplineLineSegment.d.ts +10 -0
  778. package/dist/esm/types/SplineLineSegment.js +0 -0
  779. package/dist/esm/types/SplineProps.d.ts +5 -0
  780. package/dist/esm/types/SplineProps.js +0 -0
  781. package/dist/esm/types/SurfaceTypes.d.ts +5 -0
  782. package/dist/esm/types/SurfaceTypes.js +0 -0
  783. package/dist/esm/types/ToolAction.d.ts +8 -0
  784. package/dist/esm/types/ToolAction.js +0 -0
  785. package/dist/esm/types/ToolHandle.d.ts +15 -0
  786. package/dist/esm/types/ToolHandle.js +0 -0
  787. package/dist/esm/types/ToolProps.d.ts +13 -0
  788. package/dist/esm/types/ToolProps.js +0 -0
  789. package/dist/esm/types/ToolSpecificAnnotationTypes.d.ts +477 -0
  790. package/dist/esm/types/ToolSpecificAnnotationTypes.js +0 -0
  791. package/dist/esm/types/index.d.ts +49 -0
  792. package/dist/esm/types/index.js +0 -0
  793. package/dist/esm/utilities/AnnotationMultiSlice.d.ts +11 -0
  794. package/dist/esm/utilities/AnnotationMultiSlice.js +68 -0
  795. package/dist/esm/utilities/BucketQueue.d.ts +20 -0
  796. package/dist/esm/utilities/BucketQueue.js +78 -0
  797. package/dist/esm/utilities/annotationHydration.d.ts +9 -0
  798. package/dist/esm/utilities/annotationHydration.js +82 -0
  799. package/dist/esm/utilities/boundingBox/extend2DBoundingBoxInViewAxis.d.ts +3 -0
  800. package/dist/esm/utilities/boundingBox/extend2DBoundingBoxInViewAxis.js +10 -0
  801. package/dist/esm/utilities/boundingBox/getBoundingBoxAroundShape.d.ts +5 -0
  802. package/dist/esm/utilities/boundingBox/getBoundingBoxAroundShape.js +55 -0
  803. package/dist/esm/utilities/boundingBox/index.d.ts +3 -0
  804. package/dist/esm/utilities/boundingBox/index.js +3 -0
  805. package/dist/esm/utilities/calibrateImageSpacing.d.ts +2 -0
  806. package/dist/esm/utilities/calibrateImageSpacing.js +18 -0
  807. package/dist/esm/utilities/cine/events.d.ts +5 -0
  808. package/dist/esm/utilities/cine/events.js +6 -0
  809. package/dist/esm/utilities/cine/index.d.ts +4 -0
  810. package/dist/esm/utilities/cine/index.js +4 -0
  811. package/dist/esm/utilities/cine/playClip.d.ts +8 -0
  812. package/dist/esm/utilities/cine/playClip.js +352 -0
  813. package/dist/esm/utilities/cine/state.d.ts +5 -0
  814. package/dist/esm/utilities/cine/state.js +16 -0
  815. package/dist/esm/utilities/contourSegmentation/addContourSegmentationAnnotation.d.ts +2 -0
  816. package/dist/esm/utilities/contourSegmentation/addContourSegmentationAnnotation.js +24 -0
  817. package/dist/esm/utilities/contourSegmentation/areSameSegment.d.ts +2 -0
  818. package/dist/esm/utilities/contourSegmentation/areSameSegment.js +6 -0
  819. package/dist/esm/utilities/contourSegmentation/index.d.ts +4 -0
  820. package/dist/esm/utilities/contourSegmentation/index.js +4 -0
  821. package/dist/esm/utilities/contourSegmentation/isContourSegmentationAnnotation.d.ts +3 -0
  822. package/dist/esm/utilities/contourSegmentation/isContourSegmentationAnnotation.js +3 -0
  823. package/dist/esm/utilities/contourSegmentation/removeContourSegmentationAnnotation.d.ts +2 -0
  824. package/dist/esm/utilities/contourSegmentation/removeContourSegmentationAnnotation.js +17 -0
  825. package/dist/esm/utilities/contours/AnnotationToPointData.d.ts +11 -0
  826. package/dist/esm/utilities/contours/AnnotationToPointData.js +38 -0
  827. package/dist/esm/utilities/contours/RectangleROIStartEndThreshold.d.ts +6 -0
  828. package/dist/esm/utilities/contours/RectangleROIStartEndThreshold.js +40 -0
  829. package/dist/esm/utilities/contours/areCoplanarContours.d.ts +2 -0
  830. package/dist/esm/utilities/contours/areCoplanarContours.js +15 -0
  831. package/dist/esm/utilities/contours/calculatePerimeter.d.ts +2 -0
  832. package/dist/esm/utilities/contours/calculatePerimeter.js +16 -0
  833. package/dist/esm/utilities/contours/contourFinder.d.ts +7 -0
  834. package/dist/esm/utilities/contours/contourFinder.js +62 -0
  835. package/dist/esm/utilities/contours/detectContourHoles.d.ts +5 -0
  836. package/dist/esm/utilities/contours/detectContourHoles.js +73 -0
  837. package/dist/esm/utilities/contours/findHandlePolylineIndex.d.ts +2 -0
  838. package/dist/esm/utilities/contours/findHandlePolylineIndex.js +31 -0
  839. package/dist/esm/utilities/contours/generateContourSetsFromLabelmap.d.ts +4 -0
  840. package/dist/esm/utilities/contours/generateContourSetsFromLabelmap.js +110 -0
  841. package/dist/esm/utilities/contours/getContourHolesDataCanvas.d.ts +3 -0
  842. package/dist/esm/utilities/contours/getContourHolesDataCanvas.js +14 -0
  843. package/dist/esm/utilities/contours/getContourHolesDataWorld.d.ts +3 -0
  844. package/dist/esm/utilities/contours/getContourHolesDataWorld.js +5 -0
  845. package/dist/esm/utilities/contours/getDeduplicatedVTKPolyDataPoints.d.ts +11 -0
  846. package/dist/esm/utilities/contours/getDeduplicatedVTKPolyDataPoints.js +45 -0
  847. package/dist/esm/utilities/contours/index.d.ts +13 -0
  848. package/dist/esm/utilities/contours/index.js +13 -0
  849. package/dist/esm/utilities/contours/interpolation/acceptAutogeneratedInterpolations.d.ts +3 -0
  850. package/dist/esm/utilities/contours/interpolation/acceptAutogeneratedInterpolations.js +4 -0
  851. package/dist/esm/utilities/contours/interpolation/createPolylineToolData.d.ts +2 -0
  852. package/dist/esm/utilities/contours/interpolation/createPolylineToolData.js +38 -0
  853. package/dist/esm/utilities/contours/interpolation/findAnnotationForInterpolation.d.ts +7 -0
  854. package/dist/esm/utilities/contours/interpolation/findAnnotationForInterpolation.js +106 -0
  855. package/dist/esm/utilities/contours/interpolation/getInterpolationData.d.ts +7 -0
  856. package/dist/esm/utilities/contours/interpolation/getInterpolationData.js +47 -0
  857. package/dist/esm/utilities/contours/interpolation/getInterpolationDataCollection.d.ts +4 -0
  858. package/dist/esm/utilities/contours/interpolation/getInterpolationDataCollection.js +14 -0
  859. package/dist/esm/utilities/contours/interpolation/interpolate.d.ts +11 -0
  860. package/dist/esm/utilities/contours/interpolation/interpolate.js +339 -0
  861. package/dist/esm/utilities/contours/interpolation/selectHandles.d.ts +4 -0
  862. package/dist/esm/utilities/contours/interpolation/selectHandles.js +162 -0
  863. package/dist/esm/utilities/contours/interpolation/updateChildInterpolationUID.d.ts +2 -0
  864. package/dist/esm/utilities/contours/interpolation/updateChildInterpolationUID.js +12 -0
  865. package/dist/esm/utilities/contours/reverseIfAntiClockwise.d.ts +2 -0
  866. package/dist/esm/utilities/contours/reverseIfAntiClockwise.js +11 -0
  867. package/dist/esm/utilities/contours/updateContourPolyline.d.ts +17 -0
  868. package/dist/esm/utilities/contours/updateContourPolyline.js +52 -0
  869. package/dist/esm/utilities/debounce.d.ts +6 -0
  870. package/dist/esm/utilities/debounce.js +113 -0
  871. package/dist/esm/utilities/drawing/getTextBoxCoordsCanvas.d.ts +2 -0
  872. package/dist/esm/utilities/drawing/getTextBoxCoordsCanvas.js +24 -0
  873. package/dist/esm/utilities/drawing/index.d.ts +2 -0
  874. package/dist/esm/utilities/drawing/index.js +2 -0
  875. package/dist/esm/utilities/dynamicVolume/generateImageFromTimeData.d.ts +12 -0
  876. package/dist/esm/utilities/dynamicVolume/generateImageFromTimeData.js +98 -0
  877. package/dist/esm/utilities/dynamicVolume/getDataInTime.d.ts +8 -0
  878. package/dist/esm/utilities/dynamicVolume/getDataInTime.js +111 -0
  879. package/dist/esm/utilities/dynamicVolume/index.d.ts +4 -0
  880. package/dist/esm/utilities/dynamicVolume/index.js +4 -0
  881. package/dist/esm/utilities/geometricSurfaceUtils.d.ts +8 -0
  882. package/dist/esm/utilities/geometricSurfaceUtils.js +103 -0
  883. package/dist/esm/utilities/getAnnotationNearPoint.d.ts +5 -0
  884. package/dist/esm/utilities/getAnnotationNearPoint.js +46 -0
  885. package/dist/esm/utilities/getCalibratedUnits.d.ts +16 -0
  886. package/dist/esm/utilities/getCalibratedUnits.js +155 -0
  887. package/dist/esm/utilities/getPixelValueUnits.d.ts +8 -0
  888. package/dist/esm/utilities/getPixelValueUnits.js +31 -0
  889. package/dist/esm/utilities/getSphereBoundsInfo.d.ts +14 -0
  890. package/dist/esm/utilities/getSphereBoundsInfo.js +64 -0
  891. package/dist/esm/utilities/getToolsWithModesForElement.d.ts +4 -0
  892. package/dist/esm/utilities/getToolsWithModesForElement.js +24 -0
  893. package/dist/esm/utilities/getVOIMultipliers.d.ts +5 -0
  894. package/dist/esm/utilities/getVOIMultipliers.js +18 -0
  895. package/dist/esm/utilities/getViewportForAnnotation.d.ts +3 -0
  896. package/dist/esm/utilities/getViewportForAnnotation.js +5 -0
  897. package/dist/esm/utilities/getViewportsForAnnotation.d.ts +3 -0
  898. package/dist/esm/utilities/getViewportsForAnnotation.js +16 -0
  899. package/dist/esm/utilities/index.d.ts +40 -0
  900. package/dist/esm/utilities/index.js +40 -0
  901. package/dist/esm/utilities/isObject.d.ts +2 -0
  902. package/dist/esm/utilities/isObject.js +5 -0
  903. package/dist/esm/utilities/livewire/LiveWirePath.d.ts +19 -0
  904. package/dist/esm/utilities/livewire/LiveWirePath.js +71 -0
  905. package/dist/esm/utilities/livewire/LivewireScissors.d.ts +38 -0
  906. package/dist/esm/utilities/livewire/LivewireScissors.js +305 -0
  907. package/dist/esm/utilities/math/aabb/distanceToPoint.d.ts +2 -0
  908. package/dist/esm/utilities/math/aabb/distanceToPoint.js +4 -0
  909. package/dist/esm/utilities/math/aabb/distanceToPointSquared.d.ts +2 -0
  910. package/dist/esm/utilities/math/aabb/distanceToPointSquared.js +20 -0
  911. package/dist/esm/utilities/math/aabb/index.d.ts +3 -0
  912. package/dist/esm/utilities/math/aabb/index.js +3 -0
  913. package/dist/esm/utilities/math/aabb/intersectAABB.d.ts +2 -0
  914. package/dist/esm/utilities/math/aabb/intersectAABB.js +6 -0
  915. package/dist/esm/utilities/math/angle/angleBetweenLines.d.ts +6 -0
  916. package/dist/esm/utilities/math/angle/angleBetweenLines.js +30 -0
  917. package/dist/esm/utilities/math/angle/index.d.ts +2 -0
  918. package/dist/esm/utilities/math/angle/index.js +2 -0
  919. package/dist/esm/utilities/math/basic/BasicStatsCalculator.d.ts +26 -0
  920. package/dist/esm/utilities/math/basic/BasicStatsCalculator.js +119 -0
  921. package/dist/esm/utilities/math/basic/Calculator.d.ts +8 -0
  922. package/dist/esm/utilities/math/basic/Calculator.js +3 -0
  923. package/dist/esm/utilities/math/basic/index.d.ts +3 -0
  924. package/dist/esm/utilities/math/basic/index.js +3 -0
  925. package/dist/esm/utilities/math/circle/_types.d.ts +5 -0
  926. package/dist/esm/utilities/math/circle/_types.js +0 -0
  927. package/dist/esm/utilities/math/circle/getCanvasCircleCorners.d.ts +3 -0
  928. package/dist/esm/utilities/math/circle/getCanvasCircleCorners.js +8 -0
  929. package/dist/esm/utilities/math/circle/getCanvasCircleRadius.d.ts +2 -0
  930. package/dist/esm/utilities/math/circle/getCanvasCircleRadius.js +5 -0
  931. package/dist/esm/utilities/math/circle/index.d.ts +3 -0
  932. package/dist/esm/utilities/math/circle/index.js +3 -0
  933. package/dist/esm/utilities/math/ellipse/getCanvasEllipseCorners.d.ts +8 -0
  934. package/dist/esm/utilities/math/ellipse/getCanvasEllipseCorners.js +6 -0
  935. package/dist/esm/utilities/math/ellipse/index.d.ts +3 -0
  936. package/dist/esm/utilities/math/ellipse/index.js +3 -0
  937. package/dist/esm/utilities/math/ellipse/pointInEllipse.d.ts +11 -0
  938. package/dist/esm/utilities/math/ellipse/pointInEllipse.js +36 -0
  939. package/dist/esm/utilities/math/ellipse/pointInEllipsoidWithConstraint.d.ts +9 -0
  940. package/dist/esm/utilities/math/ellipse/pointInEllipsoidWithConstraint.js +2 -0
  941. package/dist/esm/utilities/math/index.d.ts +11 -0
  942. package/dist/esm/utilities/math/index.js +11 -0
  943. package/dist/esm/utilities/math/line/distanceToPoint.d.ts +2 -0
  944. package/dist/esm/utilities/math/line/distanceToPoint.js +7 -0
  945. package/dist/esm/utilities/math/line/distanceToPointSquared.d.ts +2 -0
  946. package/dist/esm/utilities/math/line/distanceToPointSquared.js +4 -0
  947. package/dist/esm/utilities/math/line/distanceToPointSquaredInfo.d.ts +5 -0
  948. package/dist/esm/utilities/math/line/distanceToPointSquaredInfo.js +29 -0
  949. package/dist/esm/utilities/math/line/index.d.ts +6 -0
  950. package/dist/esm/utilities/math/line/index.js +6 -0
  951. package/dist/esm/utilities/math/line/intersectLine.d.ts +2 -0
  952. package/dist/esm/utilities/math/line/intersectLine.js +41 -0
  953. package/dist/esm/utilities/math/line/isPointOnLineSegment.d.ts +2 -0
  954. package/dist/esm/utilities/math/line/isPointOnLineSegment.js +18 -0
  955. package/dist/esm/utilities/math/midPoint.d.ts +5 -0
  956. package/dist/esm/utilities/math/midPoint.js +15 -0
  957. package/dist/esm/utilities/math/point/distanceToPoint.d.ts +4 -0
  958. package/dist/esm/utilities/math/point/distanceToPoint.js +4 -0
  959. package/dist/esm/utilities/math/point/distanceToPointSquared.d.ts +4 -0
  960. package/dist/esm/utilities/math/point/distanceToPointSquared.js +11 -0
  961. package/dist/esm/utilities/math/point/index.d.ts +3 -0
  962. package/dist/esm/utilities/math/point/index.js +3 -0
  963. package/dist/esm/utilities/math/point/mirror.d.ts +2 -0
  964. package/dist/esm/utilities/math/point/mirror.js +7 -0
  965. package/dist/esm/utilities/math/polyline/addCanvasPointsToArray.d.ts +4 -0
  966. package/dist/esm/utilities/math/polyline/addCanvasPointsToArray.js +38 -0
  967. package/dist/esm/utilities/math/polyline/areLineSegmentsIntersecting.d.ts +2 -0
  968. package/dist/esm/utilities/math/polyline/areLineSegmentsIntersecting.js +55 -0
  969. package/dist/esm/utilities/math/polyline/combinePolyline.d.ts +4 -0
  970. package/dist/esm/utilities/math/polyline/combinePolyline.js +186 -0
  971. package/dist/esm/utilities/math/polyline/containsPoint.d.ts +5 -0
  972. package/dist/esm/utilities/math/polyline/containsPoint.js +39 -0
  973. package/dist/esm/utilities/math/polyline/containsPoints.d.ts +2 -0
  974. package/dist/esm/utilities/math/polyline/containsPoints.js +9 -0
  975. package/dist/esm/utilities/math/polyline/decimate.d.ts +2 -0
  976. package/dist/esm/utilities/math/polyline/decimate.js +46 -0
  977. package/dist/esm/utilities/math/polyline/getAABB.d.ts +4 -0
  978. package/dist/esm/utilities/math/polyline/getAABB.js +40 -0
  979. package/dist/esm/utilities/math/polyline/getArea.d.ts +2 -0
  980. package/dist/esm/utilities/math/polyline/getArea.js +10 -0
  981. package/dist/esm/utilities/math/polyline/getClosestLineSegmentIntersection.d.ts +5 -0
  982. package/dist/esm/utilities/math/polyline/getClosestLineSegmentIntersection.js +44 -0
  983. package/dist/esm/utilities/math/polyline/getFirstLineSegmentIntersectionIndexes.d.ts +2 -0
  984. package/dist/esm/utilities/math/polyline/getFirstLineSegmentIntersectionIndexes.js +21 -0
  985. package/dist/esm/utilities/math/polyline/getLineSegmentIntersectionsCoordinates.d.ts +2 -0
  986. package/dist/esm/utilities/math/polyline/getLineSegmentIntersectionsCoordinates.js +13 -0
  987. package/dist/esm/utilities/math/polyline/getLineSegmentIntersectionsIndexes.d.ts +2 -0
  988. package/dist/esm/utilities/math/polyline/getLineSegmentIntersectionsIndexes.js +15 -0
  989. package/dist/esm/utilities/math/polyline/getLinesIntersection.d.ts +2 -0
  990. package/dist/esm/utilities/math/polyline/getLinesIntersection.js +51 -0
  991. package/dist/esm/utilities/math/polyline/getNormal2.d.ts +2 -0
  992. package/dist/esm/utilities/math/polyline/getNormal2.js +5 -0
  993. package/dist/esm/utilities/math/polyline/getNormal3.d.ts +2 -0
  994. package/dist/esm/utilities/math/polyline/getNormal3.js +25 -0
  995. package/dist/esm/utilities/math/polyline/getSignedArea.d.ts +2 -0
  996. package/dist/esm/utilities/math/polyline/getSignedArea.js +19 -0
  997. package/dist/esm/utilities/math/polyline/getSubPixelSpacingAndXYDirections.d.ts +7 -0
  998. package/dist/esm/utilities/math/polyline/getSubPixelSpacingAndXYDirections.js +72 -0
  999. package/dist/esm/utilities/math/polyline/getWindingDirection.d.ts +2 -0
  1000. package/dist/esm/utilities/math/polyline/getWindingDirection.js +5 -0
  1001. package/dist/esm/utilities/math/polyline/index.d.ts +23 -0
  1002. package/dist/esm/utilities/math/polyline/index.js +23 -0
  1003. package/dist/esm/utilities/math/polyline/intersectPolyline.d.ts +2 -0
  1004. package/dist/esm/utilities/math/polyline/intersectPolyline.js +13 -0
  1005. package/dist/esm/utilities/math/polyline/isClosed.d.ts +2 -0
  1006. package/dist/esm/utilities/math/polyline/isClosed.js +12 -0
  1007. package/dist/esm/utilities/math/polyline/isPointInsidePolyline3D.d.ts +4 -0
  1008. package/dist/esm/utilities/math/polyline/isPointInsidePolyline3D.js +25 -0
  1009. package/dist/esm/utilities/math/polyline/planarFreehandROIInternalTypes.d.ts +25 -0
  1010. package/dist/esm/utilities/math/polyline/planarFreehandROIInternalTypes.js +0 -0
  1011. package/dist/esm/utilities/math/polyline/pointCanProjectOnLine.d.ts +3 -0
  1012. package/dist/esm/utilities/math/polyline/pointCanProjectOnLine.js +32 -0
  1013. package/dist/esm/utilities/math/polyline/pointsAreWithinCloseContourProximity.d.ts +3 -0
  1014. package/dist/esm/utilities/math/polyline/pointsAreWithinCloseContourProximity.js +5 -0
  1015. package/dist/esm/utilities/math/polyline/projectTo2D.d.ts +5 -0
  1016. package/dist/esm/utilities/math/polyline/projectTo2D.js +25 -0
  1017. package/dist/esm/utilities/math/rectangle/distanceToPoint.d.ts +2 -0
  1018. package/dist/esm/utilities/math/rectangle/distanceToPoint.js +34 -0
  1019. package/dist/esm/utilities/math/rectangle/index.d.ts +2 -0
  1020. package/dist/esm/utilities/math/rectangle/index.js +2 -0
  1021. package/dist/esm/utilities/math/sphere/index.d.ts +2 -0
  1022. package/dist/esm/utilities/math/sphere/index.js +2 -0
  1023. package/dist/esm/utilities/math/sphere/pointInSphere.d.ts +9 -0
  1024. package/dist/esm/utilities/math/sphere/pointInSphere.js +8 -0
  1025. package/dist/esm/utilities/math/vec2/findClosestPoint.d.ts +2 -0
  1026. package/dist/esm/utilities/math/vec2/findClosestPoint.js +17 -0
  1027. package/dist/esm/utilities/math/vec2/index.d.ts +3 -0
  1028. package/dist/esm/utilities/math/vec2/index.js +3 -0
  1029. package/dist/esm/utilities/math/vec2/liangBarksyClip.d.ts +1 -0
  1030. package/dist/esm/utilities/math/vec2/liangBarksyClip.js +68 -0
  1031. package/dist/esm/utilities/math/vec3/interpolateVec3.d.ts +2 -0
  1032. package/dist/esm/utilities/math/vec3/interpolateVec3.js +8 -0
  1033. package/dist/esm/utilities/normalizeViewportPlane.d.ts +19 -0
  1034. package/dist/esm/utilities/normalizeViewportPlane.js +35 -0
  1035. package/dist/esm/utilities/orientation/getOrientationStringLPS.d.ts +2 -0
  1036. package/dist/esm/utilities/orientation/getOrientationStringLPS.js +41 -0
  1037. package/dist/esm/utilities/orientation/index.d.ts +3 -0
  1038. package/dist/esm/utilities/orientation/index.js +3 -0
  1039. package/dist/esm/utilities/orientation/invertOrientationStringLPS.d.ts +1 -0
  1040. package/dist/esm/utilities/orientation/invertOrientationStringLPS.js +10 -0
  1041. package/dist/esm/utilities/planar/filterAnnotationsForDisplay.d.ts +3 -0
  1042. package/dist/esm/utilities/planar/filterAnnotationsForDisplay.js +26 -0
  1043. package/dist/esm/utilities/planar/filterAnnotationsWithinPlane.d.ts +3 -0
  1044. package/dist/esm/utilities/planar/filterAnnotationsWithinPlane.js +26 -0
  1045. package/dist/esm/utilities/planar/filterAnnotationsWithinSlice.d.ts +3 -0
  1046. package/dist/esm/utilities/planar/filterAnnotationsWithinSlice.js +46 -0
  1047. package/dist/esm/utilities/planar/getPointInLineOfSightWithCriteria.d.ts +6 -0
  1048. package/dist/esm/utilities/planar/getPointInLineOfSightWithCriteria.js +49 -0
  1049. package/dist/esm/utilities/planar/getWorldWidthAndHeightFromCorners.d.ts +5 -0
  1050. package/dist/esm/utilities/planar/getWorldWidthAndHeightFromCorners.js +18 -0
  1051. package/dist/esm/utilities/planar/getWorldWidthAndHeightFromTwoPoints.d.ts +5 -0
  1052. package/dist/esm/utilities/planar/getWorldWidthAndHeightFromTwoPoints.js +18 -0
  1053. package/dist/esm/utilities/planar/index.d.ts +19 -0
  1054. package/dist/esm/utilities/planar/index.js +18 -0
  1055. package/dist/esm/utilities/planar/isPlaneIntersectingAABB.d.ts +1 -0
  1056. package/dist/esm/utilities/planar/isPlaneIntersectingAABB.js +27 -0
  1057. package/dist/esm/utilities/planarFreehandROITool/index.d.ts +6 -0
  1058. package/dist/esm/utilities/planarFreehandROITool/index.js +5 -0
  1059. package/dist/esm/utilities/planarFreehandROITool/interpolation/algorithms/bspline.d.ts +2 -0
  1060. package/dist/esm/utilities/planarFreehandROITool/interpolation/algorithms/bspline.js +22 -0
  1061. package/dist/esm/utilities/planarFreehandROITool/interpolation/interpolateSegmentPoints.d.ts +2 -0
  1062. package/dist/esm/utilities/planarFreehandROITool/interpolation/interpolateSegmentPoints.js +41 -0
  1063. package/dist/esm/utilities/planarFreehandROITool/smoothAnnotation.d.ts +6 -0
  1064. package/dist/esm/utilities/planarFreehandROITool/smoothAnnotation.js +56 -0
  1065. package/dist/esm/utilities/planarFreehandROITool/smoothPoints.d.ts +11 -0
  1066. package/dist/esm/utilities/planarFreehandROITool/smoothPoints.js +91 -0
  1067. package/dist/esm/utilities/pointInSurroundingSphereCallback.d.ts +8 -0
  1068. package/dist/esm/utilities/pointInSurroundingSphereCallback.js +71 -0
  1069. package/dist/esm/utilities/pointToString.d.ts +1 -0
  1070. package/dist/esm/utilities/pointToString.js +8 -0
  1071. package/dist/esm/utilities/polyData/utils.d.ts +5 -0
  1072. package/dist/esm/utilities/polyData/utils.js +53 -0
  1073. package/dist/esm/utilities/rectangleROITool/getBoundsIJKFromRectangleAnnotations.d.ts +5 -0
  1074. package/dist/esm/utilities/rectangleROITool/getBoundsIJKFromRectangleAnnotations.js +44 -0
  1075. package/dist/esm/utilities/rectangleROITool/index.d.ts +3 -0
  1076. package/dist/esm/utilities/rectangleROITool/index.js +3 -0
  1077. package/dist/esm/utilities/rectangleROITool/isAxisAlignedRectangle.d.ts +2 -0
  1078. package/dist/esm/utilities/rectangleROITool/isAxisAlignedRectangle.js +22 -0
  1079. package/dist/esm/utilities/registerComputeWorker.d.ts +1 -0
  1080. package/dist/esm/utilities/registerComputeWorker.js +23 -0
  1081. package/dist/esm/utilities/segmentation/InterpolationManager/InterpolationManager.d.ts +11 -0
  1082. package/dist/esm/utilities/segmentation/InterpolationManager/InterpolationManager.js +177 -0
  1083. package/dist/esm/utilities/segmentation/InterpolationManager/deleteRelatedAnnotations.d.ts +2 -0
  1084. package/dist/esm/utilities/segmentation/InterpolationManager/deleteRelatedAnnotations.js +66 -0
  1085. package/dist/esm/utilities/segmentation/VolumetricCalculator.d.ts +15 -0
  1086. package/dist/esm/utilities/segmentation/VolumetricCalculator.js +48 -0
  1087. package/dist/esm/utilities/segmentation/brushSizeForToolGroup.d.ts +2 -0
  1088. package/dist/esm/utilities/segmentation/brushSizeForToolGroup.js +40 -0
  1089. package/dist/esm/utilities/segmentation/brushThresholdForToolGroup.d.ts +7 -0
  1090. package/dist/esm/utilities/segmentation/brushThresholdForToolGroup.js +45 -0
  1091. package/dist/esm/utilities/segmentation/computeAndAddRepresentation.d.ts +3 -0
  1092. package/dist/esm/utilities/segmentation/computeAndAddRepresentation.js +45 -0
  1093. package/dist/esm/utilities/segmentation/contourAndFindLargestBidirectional.d.ts +1 -0
  1094. package/dist/esm/utilities/segmentation/contourAndFindLargestBidirectional.js +23 -0
  1095. package/dist/esm/utilities/segmentation/createBidirectionalToolData.d.ts +14 -0
  1096. package/dist/esm/utilities/segmentation/createBidirectionalToolData.js +35 -0
  1097. package/dist/esm/utilities/segmentation/createLabelmapMemo.d.ts +44 -0
  1098. package/dist/esm/utilities/segmentation/createLabelmapMemo.js +68 -0
  1099. package/dist/esm/utilities/segmentation/createLabelmapVolumeForViewport.d.ts +9 -0
  1100. package/dist/esm/utilities/segmentation/createLabelmapVolumeForViewport.js +28 -0
  1101. package/dist/esm/utilities/segmentation/createMergedLabelmapForIndex.d.ts +3 -0
  1102. package/dist/esm/utilities/segmentation/createMergedLabelmapForIndex.js +34 -0
  1103. package/dist/esm/utilities/segmentation/findLargestBidirectional.d.ts +1 -0
  1104. package/dist/esm/utilities/segmentation/findLargestBidirectional.js +95 -0
  1105. package/dist/esm/utilities/segmentation/floodFill.d.ts +4 -0
  1106. package/dist/esm/utilities/segmentation/floodFill.js +120 -0
  1107. package/dist/esm/utilities/segmentation/getBrushToolInstances.d.ts +1 -0
  1108. package/dist/esm/utilities/segmentation/getBrushToolInstances.js +17 -0
  1109. package/dist/esm/utilities/segmentation/getHoveredContourSegmentationAnnotation.d.ts +1 -0
  1110. package/dist/esm/utilities/segmentation/getHoveredContourSegmentationAnnotation.js +13 -0
  1111. package/dist/esm/utilities/segmentation/getOrCreateSegmentationVolume.d.ts +2 -0
  1112. package/dist/esm/utilities/segmentation/getOrCreateSegmentationVolume.js +21 -0
  1113. package/dist/esm/utilities/segmentation/getSVGStyleForSegment.d.ts +17 -0
  1114. package/dist/esm/utilities/segmentation/getSVGStyleForSegment.js +68 -0
  1115. package/dist/esm/utilities/segmentation/getSegmentIndexAtLabelmapBorder.d.ts +7 -0
  1116. package/dist/esm/utilities/segmentation/getSegmentIndexAtLabelmapBorder.js +76 -0
  1117. package/dist/esm/utilities/segmentation/getSegmentIndexAtWorldPoint.d.ts +11 -0
  1118. package/dist/esm/utilities/segmentation/getSegmentIndexAtWorldPoint.js +74 -0
  1119. package/dist/esm/utilities/segmentation/getStatistics.d.ts +5 -0
  1120. package/dist/esm/utilities/segmentation/getStatistics.js +210 -0
  1121. package/dist/esm/utilities/segmentation/getUniqueSegmentIndices.d.ts +2 -0
  1122. package/dist/esm/utilities/segmentation/getUniqueSegmentIndices.js +80 -0
  1123. package/dist/esm/utilities/segmentation/growCut/growCutShader.d.ts +2 -0
  1124. package/dist/esm/utilities/segmentation/growCut/growCutShader.js +106 -0
  1125. package/dist/esm/utilities/segmentation/growCut/index.d.ts +7 -0
  1126. package/dist/esm/utilities/segmentation/growCut/index.js +4 -0
  1127. package/dist/esm/utilities/segmentation/growCut/runGrowCut.d.ts +16 -0
  1128. package/dist/esm/utilities/segmentation/growCut/runGrowCut.js +269 -0
  1129. package/dist/esm/utilities/segmentation/growCut/runGrowCutForBoundingBox.d.ts +15 -0
  1130. package/dist/esm/utilities/segmentation/growCut/runGrowCutForBoundingBox.js +110 -0
  1131. package/dist/esm/utilities/segmentation/growCut/runGrowCutForSphere.d.ts +9 -0
  1132. package/dist/esm/utilities/segmentation/growCut/runGrowCutForSphere.js +164 -0
  1133. package/dist/esm/utilities/segmentation/growCut/runOneClickGrowCut.d.ts +9 -0
  1134. package/dist/esm/utilities/segmentation/growCut/runOneClickGrowCut.js +176 -0
  1135. package/dist/esm/utilities/segmentation/index.d.ts +28 -0
  1136. package/dist/esm/utilities/segmentation/index.js +28 -0
  1137. package/dist/esm/utilities/segmentation/invalidateBrushCursor.d.ts +1 -0
  1138. package/dist/esm/utilities/segmentation/invalidateBrushCursor.js +20 -0
  1139. package/dist/esm/utilities/segmentation/isLineInSegment.d.ts +9 -0
  1140. package/dist/esm/utilities/segmentation/isLineInSegment.js +49 -0
  1141. package/dist/esm/utilities/segmentation/islandRemoval.d.ts +28 -0
  1142. package/dist/esm/utilities/segmentation/islandRemoval.js +181 -0
  1143. package/dist/esm/utilities/segmentation/rectangleROIThresholdVolumeByRange.d.ts +20 -0
  1144. package/dist/esm/utilities/segmentation/rectangleROIThresholdVolumeByRange.js +35 -0
  1145. package/dist/esm/utilities/segmentation/segmentContourAction.d.ts +17 -0
  1146. package/dist/esm/utilities/segmentation/segmentContourAction.js +95 -0
  1147. package/dist/esm/utilities/segmentation/thresholdSegmentationByRange.d.ts +4 -0
  1148. package/dist/esm/utilities/segmentation/thresholdSegmentationByRange.js +58 -0
  1149. package/dist/esm/utilities/segmentation/thresholdVolumeByRange.d.ts +11 -0
  1150. package/dist/esm/utilities/segmentation/thresholdVolumeByRange.js +79 -0
  1151. package/dist/esm/utilities/segmentation/utilities.d.ts +25 -0
  1152. package/dist/esm/utilities/segmentation/utilities.js +86 -0
  1153. package/dist/esm/utilities/segmentation/validateLabelmap.d.ts +4 -0
  1154. package/dist/esm/utilities/segmentation/validateLabelmap.js +32 -0
  1155. package/dist/esm/utilities/stackPrefetch/index.d.ts +3 -0
  1156. package/dist/esm/utilities/stackPrefetch/index.js +3 -0
  1157. package/dist/esm/utilities/stackPrefetch/stackContextPrefetch.d.ts +16 -0
  1158. package/dist/esm/utilities/stackPrefetch/stackContextPrefetch.js +221 -0
  1159. package/dist/esm/utilities/stackPrefetch/stackPrefetch.d.ts +14 -0
  1160. package/dist/esm/utilities/stackPrefetch/stackPrefetch.js +150 -0
  1161. package/dist/esm/utilities/stackPrefetch/stackPrefetchUtils.d.ts +14 -0
  1162. package/dist/esm/utilities/stackPrefetch/stackPrefetchUtils.js +76 -0
  1163. package/dist/esm/utilities/stackPrefetch/state.d.ts +22 -0
  1164. package/dist/esm/utilities/stackPrefetch/state.js +13 -0
  1165. package/dist/esm/utilities/throttle.d.ts +5 -0
  1166. package/dist/esm/utilities/throttle.js +19 -0
  1167. package/dist/esm/utilities/touch/index.d.ts +10 -0
  1168. package/dist/esm/utilities/touch/index.js +152 -0
  1169. package/dist/esm/utilities/triggerAnnotationRender.d.ts +2 -0
  1170. package/dist/esm/utilities/triggerAnnotationRender.js +5 -0
  1171. package/dist/esm/utilities/triggerAnnotationRenderForToolGroupIds.d.ts +2 -0
  1172. package/dist/esm/utilities/triggerAnnotationRenderForToolGroupIds.js +24 -0
  1173. package/dist/esm/utilities/triggerAnnotationRenderForViewportIds.d.ts +2 -0
  1174. package/dist/esm/utilities/triggerAnnotationRenderForViewportIds.js +22 -0
  1175. package/dist/esm/utilities/viewport/index.d.ts +2 -0
  1176. package/dist/esm/utilities/viewport/index.js +2 -0
  1177. package/dist/esm/utilities/viewport/isViewportPreScaled.d.ts +3 -0
  1178. package/dist/esm/utilities/viewport/isViewportPreScaled.js +16 -0
  1179. package/dist/esm/utilities/viewportFilters/filterViewportsWithFrameOfReferenceUID.d.ts +2 -0
  1180. package/dist/esm/utilities/viewportFilters/filterViewportsWithFrameOfReferenceUID.js +11 -0
  1181. package/dist/esm/utilities/viewportFilters/filterViewportsWithParallelNormals.d.ts +2 -0
  1182. package/dist/esm/utilities/viewportFilters/filterViewportsWithParallelNormals.js +10 -0
  1183. package/dist/esm/utilities/viewportFilters/filterViewportsWithSameOrientation.d.ts +2 -0
  1184. package/dist/esm/utilities/viewportFilters/filterViewportsWithSameOrientation.js +9 -0
  1185. package/dist/esm/utilities/viewportFilters/filterViewportsWithToolEnabled.d.ts +2 -0
  1186. package/dist/esm/utilities/viewportFilters/filterViewportsWithToolEnabled.js +28 -0
  1187. package/dist/esm/utilities/viewportFilters/getViewportIdsWithToolToRender.d.ts +1 -0
  1188. package/dist/esm/utilities/viewportFilters/getViewportIdsWithToolToRender.js +17 -0
  1189. package/dist/esm/utilities/viewportFilters/index.d.ts +5 -0
  1190. package/dist/esm/utilities/viewportFilters/index.js +5 -0
  1191. package/dist/esm/utilities/voi/colorbar/Colorbar.d.ts +44 -0
  1192. package/dist/esm/utilities/voi/colorbar/Colorbar.js +242 -0
  1193. package/dist/esm/utilities/voi/colorbar/ColorbarCanvas.d.ts +29 -0
  1194. package/dist/esm/utilities/voi/colorbar/ColorbarCanvas.js +182 -0
  1195. package/dist/esm/utilities/voi/colorbar/ColorbarTicks.d.ts +46 -0
  1196. package/dist/esm/utilities/voi/colorbar/ColorbarTicks.js +280 -0
  1197. package/dist/esm/utilities/voi/colorbar/ViewportColorbar.d.ts +25 -0
  1198. package/dist/esm/utilities/voi/colorbar/ViewportColorbar.js +146 -0
  1199. package/dist/esm/utilities/voi/colorbar/common/areColorbarRangesEqual.d.ts +3 -0
  1200. package/dist/esm/utilities/voi/colorbar/common/areColorbarRangesEqual.js +4 -0
  1201. package/dist/esm/utilities/voi/colorbar/common/areColorbarSizesEqual.d.ts +3 -0
  1202. package/dist/esm/utilities/voi/colorbar/common/areColorbarSizesEqual.js +4 -0
  1203. package/dist/esm/utilities/voi/colorbar/common/index.d.ts +4 -0
  1204. package/dist/esm/utilities/voi/colorbar/common/index.js +4 -0
  1205. package/dist/esm/utilities/voi/colorbar/common/isColorbarSizeValid.d.ts +3 -0
  1206. package/dist/esm/utilities/voi/colorbar/common/isColorbarSizeValid.js +4 -0
  1207. package/dist/esm/utilities/voi/colorbar/common/isRangeTextPositionValid.d.ts +3 -0
  1208. package/dist/esm/utilities/voi/colorbar/common/isRangeTextPositionValid.js +9 -0
  1209. package/dist/esm/utilities/voi/colorbar/common/isRangeValid.d.ts +3 -0
  1210. package/dist/esm/utilities/voi/colorbar/common/isRangeValid.js +4 -0
  1211. package/dist/esm/utilities/voi/colorbar/enums/ColorbarRangeTextPosition.d.ts +6 -0
  1212. package/dist/esm/utilities/voi/colorbar/enums/ColorbarRangeTextPosition.js +7 -0
  1213. package/dist/esm/utilities/voi/colorbar/enums/index.d.ts +1 -0
  1214. package/dist/esm/utilities/voi/colorbar/enums/index.js +1 -0
  1215. package/dist/esm/utilities/voi/colorbar/index.d.ts +6 -0
  1216. package/dist/esm/utilities/voi/colorbar/index.js +4 -0
  1217. package/dist/esm/utilities/voi/colorbar/types/ColorbarCanvasProps.d.ts +12 -0
  1218. package/dist/esm/utilities/voi/colorbar/types/ColorbarCanvasProps.js +0 -0
  1219. package/dist/esm/utilities/voi/colorbar/types/ColorbarCommonProps.d.ts +11 -0
  1220. package/dist/esm/utilities/voi/colorbar/types/ColorbarCommonProps.js +0 -0
  1221. package/dist/esm/utilities/voi/colorbar/types/ColorbarImageRange.d.ts +4 -0
  1222. package/dist/esm/utilities/voi/colorbar/types/ColorbarImageRange.js +0 -0
  1223. package/dist/esm/utilities/voi/colorbar/types/ColorbarProps.d.ts +7 -0
  1224. package/dist/esm/utilities/voi/colorbar/types/ColorbarProps.js +0 -0
  1225. package/dist/esm/utilities/voi/colorbar/types/ColorbarSize.d.ts +4 -0
  1226. package/dist/esm/utilities/voi/colorbar/types/ColorbarSize.js +0 -0
  1227. package/dist/esm/utilities/voi/colorbar/types/ColorbarTicksProps.d.ts +7 -0
  1228. package/dist/esm/utilities/voi/colorbar/types/ColorbarTicksProps.js +0 -0
  1229. package/dist/esm/utilities/voi/colorbar/types/ColorbarTicksStyle.d.ts +8 -0
  1230. package/dist/esm/utilities/voi/colorbar/types/ColorbarTicksStyle.js +0 -0
  1231. package/dist/esm/utilities/voi/colorbar/types/ColorbarVOIRange.d.ts +2 -0
  1232. package/dist/esm/utilities/voi/colorbar/types/ColorbarVOIRange.js +0 -0
  1233. package/dist/esm/utilities/voi/colorbar/types/ViewportColorbarProps.d.ts +5 -0
  1234. package/dist/esm/utilities/voi/colorbar/types/ViewportColorbarProps.js +0 -0
  1235. package/dist/esm/utilities/voi/colorbar/types/index.d.ts +8 -0
  1236. package/dist/esm/utilities/voi/colorbar/types/index.js +0 -0
  1237. package/dist/esm/utilities/voi/index.d.ts +3 -0
  1238. package/dist/esm/utilities/voi/index.js +3 -0
  1239. package/dist/esm/utilities/voi/windowlevel/calculateMinMaxMean.d.ts +6 -0
  1240. package/dist/esm/utilities/voi/windowlevel/calculateMinMaxMean.js +25 -0
  1241. package/dist/esm/utilities/voi/windowlevel/extractWindowLevelRegionToolData.d.ts +11 -0
  1242. package/dist/esm/utilities/voi/windowlevel/extractWindowLevelRegionToolData.js +42 -0
  1243. package/dist/esm/utilities/voi/windowlevel/getLuminanceFromRegion.d.ts +2 -0
  1244. package/dist/esm/utilities/voi/windowlevel/getLuminanceFromRegion.js +27 -0
  1245. package/dist/esm/utilities/voi/windowlevel/index.d.ts +4 -0
  1246. package/dist/esm/utilities/voi/windowlevel/index.js +4 -0
  1247. package/dist/esm/widgets/Widget.d.ts +17 -0
  1248. package/dist/esm/widgets/Widget.js +66 -0
  1249. package/dist/esm/widgets/types/WidgetProps.d.ts +4 -0
  1250. package/dist/esm/widgets/types/WidgetProps.js +0 -0
  1251. package/dist/esm/widgets/types/WidgetSize.d.ts +4 -0
  1252. package/dist/esm/widgets/types/WidgetSize.js +0 -0
  1253. package/dist/esm/widgets/types/index.d.ts +2 -0
  1254. package/dist/esm/widgets/types/index.js +0 -0
  1255. package/dist/esm/workers/computeWorker.d.ts +1 -0
  1256. package/dist/esm/workers/computeWorker.js +78 -0
  1257. package/package.json +113 -100
  1258. package/changelog.md +0 -304
  1259. package/dist/cornerstoneTools.js +0 -27391
  1260. package/dist/cornerstoneTools.js.map +0 -1
  1261. package/dist/cornerstoneTools.min.js +0 -3
  1262. package/dist/cornerstoneTools.min.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["webpack://cornerstoneTools/webpack/universalModuleDefinition","webpack://cornerstoneTools/webpack/bootstrap","webpack://cornerstoneTools/../node_modules/@babel/runtime/helpers/assertThisInitialized.js","webpack://cornerstoneTools/../node_modules/@babel/runtime/helpers/classCallCheck.js","webpack://cornerstoneTools/../node_modules/@babel/runtime/helpers/createClass.js","webpack://cornerstoneTools/../node_modules/@babel/runtime/helpers/inherits.js","webpack://cornerstoneTools/../node_modules/@babel/runtime/helpers/getPrototypeOf.js","webpack://cornerstoneTools/../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js","webpack://cornerstoneTools/../node_modules/@babel/runtime/helpers/typeof.js","webpack://cornerstoneTools/../node_modules/@babel/runtime/regenerator/index.js","webpack://cornerstoneTools/../node_modules/@babel/runtime/helpers/asyncToGenerator.js","webpack://cornerstoneTools/../node_modules/@babel/runtime/helpers/toConsumableArray.js","webpack://cornerstoneTools/./externalModules.js","webpack://cornerstoneTools/./events.js","webpack://cornerstoneTools/./util/triggerEvent.js","webpack://cornerstoneTools/./store/modules/brushModule.js","webpack://cornerstoneTools/./store/modules/globalConfigurationModule.js","webpack://cornerstoneTools/./store/index.js","webpack://cornerstoneTools/./store/getToolForElement.js","webpack://cornerstoneTools/./store/setToolMode.js","webpack://cornerstoneTools/./mixins/enabledOrDisabledBinaryTool.js","webpack://cornerstoneTools/./mixins/index.js","webpack://cornerstoneTools/./mixins/activeOrDisabledBinaryTool.js","webpack://cornerstoneTools/./tools/base/BaseTool.js","webpack://cornerstoneTools/./stateManagement/imageIdSpecificStateManager.js","webpack://cornerstoneTools/./stateManagement/toolState.js","webpack://cornerstoneTools/./util/pointInsideBoundingBox.js","webpack://cornerstoneTools/./manipulators/getHandleNearImagePoint.js","webpack://cornerstoneTools/./manipulators/handleActivator.js","webpack://cornerstoneTools/./manipulators/anyHandlesOutsideImage.js","webpack://cornerstoneTools/./util/clip.js","webpack://cornerstoneTools/./manipulators/moveAllHandles.js","webpack://cornerstoneTools/./manipulators/moveHandle.js","webpack://cornerstoneTools/./manipulators/moveNewHandle.js","webpack://cornerstoneTools/./util/findAndMoveHelpers.js","webpack://cornerstoneTools/./tools/base/BaseAnnotationTool.js","webpack://cornerstoneTools/./stateManagement/toolStyle.js","webpack://cornerstoneTools/./stateManagement/toolColors.js","webpack://cornerstoneTools/./drawing/draw.js","webpack://cornerstoneTools/./drawing/path.js","webpack://cornerstoneTools/./drawing/drawLine.js","webpack://cornerstoneTools/./drawing/drawJoinedLines.js","webpack://cornerstoneTools/./drawing/drawArrow.js","webpack://cornerstoneTools/./drawing/drawCircle.js","webpack://cornerstoneTools/./drawing/drawEllipse.js","webpack://cornerstoneTools/./drawing/drawHandles.js","webpack://cornerstoneTools/./drawing/drawLink.js","webpack://cornerstoneTools/./stateManagement/textStyle.js","webpack://cornerstoneTools/./drawing/fillTextLines.js","webpack://cornerstoneTools/./drawing/fillBox.js","webpack://cornerstoneTools/./drawing/drawTextBox.js","webpack://cornerstoneTools/./drawing/drawLinkedTextBox.js","webpack://cornerstoneTools/./drawing/drawRect.js","webpack://cornerstoneTools/./drawing/getNewContext.js","webpack://cornerstoneTools/./util/getDefault.js","webpack://cornerstoneTools/./drawing/setShadow.js","webpack://cornerstoneTools/./drawing/transformCanvasContext.js","webpack://cornerstoneTools/./drawing/resetCanvasContextTransform.js","webpack://cornerstoneTools/./util/lineSegDistance.js","webpack://cornerstoneTools/./util/roundToDecimal.js","webpack://cornerstoneTools/./tools/annotation/AngleTool.js","webpack://cornerstoneTools/./tools/annotation/ArrowAnnotateTool.js","webpack://cornerstoneTools/./stateManagement/toolCoordinates.js","webpack://cornerstoneTools/./tools/annotation/bidirectionalTool/createNewMeasurement.js","webpack://cornerstoneTools/./tools/annotation/bidirectionalTool/pointNearTool.js","webpack://cornerstoneTools/./tools/annotation/bidirectionalTool/renderToolData.js","webpack://cornerstoneTools/./tools/annotation/bidirectionalTool/utils/updatePerpendicularLineHandles.js","webpack://cornerstoneTools/./tools/annotation/bidirectionalTool/addNewMeasurement.js","webpack://cornerstoneTools/./tools/annotation/bidirectionalTool/mouseMoveCallback.js","webpack://cornerstoneTools/./tools/annotation/bidirectionalTool/moveHandle/setHandlesPosition.js","webpack://cornerstoneTools/./tools/annotation/bidirectionalTool/moveHandle/perpendicularBothFixedLeft.js","webpack://cornerstoneTools/./tools/annotation/bidirectionalTool/moveHandle/perpendicularBothFixedRight.js","webpack://cornerstoneTools/./tools/annotation/bidirectionalTool/moveHandle/perpendicularLeftFixedPoint.js","webpack://cornerstoneTools/./tools/annotation/bidirectionalTool/moveHandle/perpendicularRightFixedPoint.js","webpack://cornerstoneTools/./tools/annotation/bidirectionalTool/invertHandles.js","webpack://cornerstoneTools/./tools/annotation/bidirectionalTool/preMouseDownCallback.js","webpack://cornerstoneTools/./tools/annotation/bidirectionalTool/moveHandle/moveHandle.js","webpack://cornerstoneTools/./tools/annotation/bidirectionalTool/moveHandle/touchMoveHandle.js","webpack://cornerstoneTools/./tools/annotation/bidirectionalTool/preTouchStartCallback.js","webpack://cornerstoneTools/./tools/annotation/BidirectionalTool.js","webpack://cornerstoneTools/./tools/annotation/CobbAngleTool.js","webpack://cornerstoneTools/./util/calculateSUV.js","webpack://cornerstoneTools/./util/ellipse/pointInEllipse.js","webpack://cornerstoneTools/./util/ellipse/calculateEllipseStatistics.js","webpack://cornerstoneTools/./util/ellipse/index.js","webpack://cornerstoneTools/./util/numbersWithCommas.js","webpack://cornerstoneTools/./util/isObject.js","webpack://cornerstoneTools/./util/debounce.js","webpack://cornerstoneTools/./util/throttle.js","webpack://cornerstoneTools/./tools/annotation/EllipticalRoiTool.js","webpack://cornerstoneTools/./util/freehand/pointInFreehand.js","webpack://cornerstoneTools/./util/freehand/calculateFreehandStatistics.js","webpack://cornerstoneTools/./util/freehand/ClickedLineData.js","webpack://cornerstoneTools/./util/freehand/FreehandHandleData.js","webpack://cornerstoneTools/./util/freehand/freehandIntersect.js","webpack://cornerstoneTools/./util/freehand/FreehandLineFinder.js","webpack://cornerstoneTools/./util/freehand/index.js","webpack://cornerstoneTools/./util/freehand/freehandArea.js","webpack://cornerstoneTools/./util/freehand/insertOrDelete.js","webpack://cornerstoneTools/./tools/annotation/FreehandMouseTool.js","webpack://cornerstoneTools/./tools/annotation/LengthTool.js","webpack://cornerstoneTools/./util/getRGBPixels.js","webpack://cornerstoneTools/./tools/annotation/ProbeTool.js","webpack://cornerstoneTools/./tools/annotation/RectangleRoiTool.js","webpack://cornerstoneTools/./tools/annotation/TextMarkerTool.js","webpack://cornerstoneTools/./tools/base/BaseBrushTool.js","webpack://cornerstoneTools/./store/isToolActive.js","webpack://cornerstoneTools/./util/brush/index.js","webpack://cornerstoneTools/./util/brush/drawBrush.js","webpack://cornerstoneTools/./util/brush/getCircle.js","webpack://cornerstoneTools/./tools/brush/BrushTool.js","webpack://cornerstoneTools/./tools/brush/index.js","webpack://cornerstoneTools/./stateManagement/loadHandlerManager.js","webpack://cornerstoneTools/./util/convertToVector3.js","webpack://cornerstoneTools/./util/pointProjector.js","webpack://cornerstoneTools/./toolOptions.js","webpack://cornerstoneTools/./tools/CrosshairsTool.js","webpack://cornerstoneTools/./tools/DoubleTapFitToWindowTool.js","webpack://cornerstoneTools/./tools/DragProbeTool.js","webpack://cornerstoneTools/./tools/EraserTool.js","webpack://cornerstoneTools/./tools/FreehandSculpterMouseTool.js","webpack://cornerstoneTools/./tools/MagnifyTool.js","webpack://cornerstoneTools/./tools/OverlayTool.js","webpack://cornerstoneTools/./tools/PanMultiTouchTool.js","webpack://cornerstoneTools/./tools/PanTool.js","webpack://cornerstoneTools/./tools/referenceLines/renderActiveReferenceLine.js","webpack://cornerstoneTools/./tools/referenceLines/calculateReferenceLine.js","webpack://cornerstoneTools/./util/wait.js","webpack://cornerstoneTools/./util/getMaxSimultaneousRequests.js","webpack://cornerstoneTools/./tools/ReferenceLinesTool.js","webpack://cornerstoneTools/./util/angleBetweenPoints.js","webpack://cornerstoneTools/./tools/RotateTool.js","webpack://cornerstoneTools/./tools/RotateTouchTool.js","webpack://cornerstoneTools/./tools/ScaleOverlayTool.js","webpack://cornerstoneTools/./requestPool/requestPoolManager.js","webpack://cornerstoneTools/./util/scrollToIndex.js","webpack://cornerstoneTools/./util/scroll.js","webpack://cornerstoneTools/./tools/StackScrollMouseWheelTool.js","webpack://cornerstoneTools/./tools/StackScrollMultiTouchTool.js","webpack://cornerstoneTools/./tools/StackScrollTool.js","webpack://cornerstoneTools/./util/getLuminance.js","webpack://cornerstoneTools/./tools/WwwcRegionTool.js","webpack://cornerstoneTools/./tools/WwwcTool.js","webpack://cornerstoneTools/./util/zoom/changeViewportScale.js","webpack://cornerstoneTools/./util/zoom/index.js","webpack://cornerstoneTools/./util/zoom/correctShift.js","webpack://cornerstoneTools/./tools/ZoomMouseWheelTool.js","webpack://cornerstoneTools/./tools/ZoomTool.js","webpack://cornerstoneTools/./tools/ZoomTouchPinchTool.js","webpack://cornerstoneTools/./util/copyPoints.js","webpack://cornerstoneTools/./util/setContextToDisplayFontSize.js","webpack://cornerstoneTools/./eventListeners/mouseEventListeners.js","webpack://cornerstoneTools/./util/getKeyFromKeyCode.js","webpack://cornerstoneTools/./lib.js","webpack://cornerstoneTools/./drawing/drawLines.js","webpack://cornerstoneTools/./drawing/fillOutsideRect.js","webpack://cornerstoneTools/./util/makeUnselectable.js","webpack://cornerstoneTools/./import.js","webpack://cornerstoneTools/./eventListeners/internals/normalizeWheel.js","webpack://cornerstoneTools/./eventListeners/wheelEventListener.js","webpack://cornerstoneTools/./eventListeners/preventGhostClick.js","webpack://cornerstoneTools/./eventListeners/touchEventListeners.js","webpack://cornerstoneTools/./store/getActiveToolsForElement.js","webpack://cornerstoneTools/./eventListeners/onImageRenderedBrushEventHandler.js","webpack://cornerstoneTools/./eventDispatchers/imageRenderedEventDispatcher.js","webpack://cornerstoneTools/./eventDispatchers/shared/customCallbackHandler.js","webpack://cornerstoneTools/./store/getToolsWithMoveableHandles.js","webpack://cornerstoneTools/./store/getInteractiveToolsForElement.js","webpack://cornerstoneTools/./store/getToolsWithDataForElement.js","webpack://cornerstoneTools/./eventDispatchers/mouseEventHandlers/mouseDown.js","webpack://cornerstoneTools/./eventDispatchers/mouseEventHandlers/mouseDownActivate.js","webpack://cornerstoneTools/./eventDispatchers/mouseEventHandlers/addNewMeasurement.js","webpack://cornerstoneTools/./eventDispatchers/mouseEventHandlers/mouseDrag.js","webpack://cornerstoneTools/./eventDispatchers/mouseEventHandlers/mouseMove.js","webpack://cornerstoneTools/./eventDispatchers/mouseEventHandlers/index.js","webpack://cornerstoneTools/./eventDispatchers/mouseToolEventDispatcher.js","webpack://cornerstoneTools/./eventDispatchers/newImageEventDispatcher.js","webpack://cornerstoneTools/./eventListeners/onNewImageBrushEventHandler.js","webpack://cornerstoneTools/./eventDispatchers/touchEventHandlers/multiTouchDrag.js","webpack://cornerstoneTools/./eventDispatchers/touchEventHandlers/touchStartActive.js","webpack://cornerstoneTools/./eventDispatchers/touchEventHandlers/addNewMeasurement.js","webpack://cornerstoneTools/./eventDispatchers/touchEventHandlers/shared/deactivateAllToolInstances.js","webpack://cornerstoneTools/./eventDispatchers/touchEventHandlers/tap.js","webpack://cornerstoneTools/./eventDispatchers/touchEventHandlers/touchStart.js","webpack://cornerstoneTools/./eventDispatchers/touchEventHandlers/index.js","webpack://cornerstoneTools/./eventDispatchers/touchToolEventDispatcher.js","webpack://cornerstoneTools/./store/addTool.js","webpack://cornerstoneTools/./store/internals/addEnabledElement.js","webpack://cornerstoneTools/./store/internals/removeEnabledElement.js","webpack://cornerstoneTools/./eventListeners/windowResizeHandler.js","webpack://cornerstoneTools/./init.js","webpack://cornerstoneTools/./stackTools/stackPrefetch.js","webpack://cornerstoneTools/./stackTools/fusionRenderer.js","webpack://cornerstoneTools/./stackTools/stackRenderers.js","webpack://cornerstoneTools/./stackTools/playClip.js","webpack://cornerstoneTools/./store/removeTool.js","webpack://cornerstoneTools/./store/setToolOptions.js","webpack://cornerstoneTools/./stateManagement/stackSpecificStateManager.js","webpack://cornerstoneTools/./stateManagement/frameOfReferenceStateManager.js","webpack://cornerstoneTools/./orientation/index.js","webpack://cornerstoneTools/./orientation/getOrientationString.js","webpack://cornerstoneTools/./orientation/invertOrientationString.js","webpack://cornerstoneTools/./util/SaveAs.js","webpack://cornerstoneTools/./thirdParty/registerModule.js","webpack://cornerstoneTools/./thirdParty/registerMixin.js","webpack://cornerstoneTools/./thirdParty/registerItem.js","webpack://cornerstoneTools/./thirdParty/register.js","webpack://cornerstoneTools/./thirdParty/registerSome.js","webpack://cornerstoneTools/./synchronization/wwwcSynchronizer.js","webpack://cornerstoneTools/./synchronization/updateImageSynchronizer.js","webpack://cornerstoneTools/./synchronization/Synchronizer.js","webpack://cornerstoneTools/./synchronization/stackScrollSynchronizer.js","webpack://cornerstoneTools/./synchronization/stackImagePositionSynchronizer.js","webpack://cornerstoneTools/./synchronization/stackImagePositionOffsetSynchronizer.js","webpack://cornerstoneTools/./synchronization/stackImageIndexSynchronizer.js","webpack://cornerstoneTools/./synchronization/panZoomSynchronizer.js","webpack://cornerstoneTools/./index.js","webpack://cornerstoneTools/./version.js","webpack://cornerstoneTools/../node_modules/regenerator-runtime/runtime.js","webpack://cornerstoneTools/../node_modules/regenerator-runtime/runtime-module.js","webpack://cornerstoneTools/../node_modules/@babel/runtime/helpers/nonIterableSpread.js","webpack://cornerstoneTools/../node_modules/@babel/runtime/helpers/iterableToArray.js","webpack://cornerstoneTools/../node_modules/@babel/runtime/helpers/arrayWithoutHoles.js","webpack://cornerstoneTools/../node_modules/@babel/runtime/helpers/setPrototypeOf.js"],"names":["root","factory","exports","module","define","amd","window","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","configurable","enumerable","get","r","value","n","__esModule","object","property","prototype","hasOwnProperty","p","s","self","ReferenceError","instance","Constructor","TypeError","_defineProperties","target","props","length","descriptor","writable","key","protoProps","staticProps","setPrototypeOf","subClass","superClass","create","constructor","_getPrototypeOf","getPrototypeOf","__proto__","_typeof","assertThisInitialized","_typeof2","obj","Symbol","iterator","asyncGeneratorStep","gen","resolve","reject","_next","_throw","arg","info","error","done","Promise","then","fn","this","args","arguments","apply","err","undefined","arrayWithoutHoles","iterableToArray","nonIterableSpread","arr","cornerstone","cornerstoneMath","Hammer","externalModules","cs","cm","EVENTS","MOUSE_DOWN","MOUSE_UP","MOUSE_DOWN_ACTIVATE","MOUSE_DRAG","MOUSE_MOVE","MOUSE_CLICK","MOUSE_DOUBLE_CLICK","MOUSE_WHEEL","TOUCH_START","TOUCH_START_ACTIVE","TOUCH_END","TOUCH_DRAG","TOUCH_DRAG_END","TOUCH_PINCH","TOUCH_ROTATE","TOUCH_PRESS","TAP","DOUBLE_TAP","MULTI_TOUCH_START","MULTI_TOUCH_START_ACTIVE","MULTI_TOUCH_DRAG","KEY_DOWN","KEY_UP","KEY_PRESS","MEASUREMENT_ADDED","MEASUREMENT_MODIFIED","MEASUREMENT_REMOVED","TOOL_DEACTIVATED","CLIP_STOPPED","STACK_SCROLL","triggerEvent","el","type","event","detail","CustomEvent","cancelable","document","createEvent","initCustomEvent","dispatchEvent","state","drawColorId","radius","minRadius","maxRadius","alpha","renderBrushIfHiddenButActive","hiddenButActiveAlpha","colorMapId","visibleSegmentations","imageBitmapCache","segmentationMetadata","setters","Math","min","max","brushColorMap","colors","colormap","external","getColormap","setNumberOfColors","setColor","elementVisible","enabledElement","enabledElementUID","getEnabledElement","uuid","numberOfColors","getNumberOfColors","push","brushVisibilityForElement","segIndex","visible","imageBitmapCacheForElement","imageBitmap","clearImageBitmapCacheForElement","metadata","seriesInstanceUid","brushModule","onRegisterCallback","distinctColors","_generateInterpolatedColor","_initDefaultColorMap","enabledElementCallback","getters","visibleSegmentationsForElement","colorPairIndex","randIndicies","indexPair","_getNextColorPair","fraction","random","interpolatedColor","floor","globalTools","globalToolChangeHistory","enabledElements","tools","isToolLocked","mousePositionImage","clickProximity","touchProximity","handleRadius","deleteIfHandleOutsideImage","preventHandleOutsideImage","mouseTools","filter","tool","supportedInteractionTypes","includes","touchTools","enabledElementByUID","find","element","brush","globalConfiguration","mouseEnabled","touchEnabled","globalToolSyncEnabled","store","getToolForElement","setToolActiveForElement","toolName","options","interactionTypes","Array","isArray","forEach","interactionType","inputResolver","_inputResolvers","console","warn","concat","t","mode","toolHasAnyActiveInteractionType","setToolPassiveForElement","_resolveInputConflicts","setToolModeForElement","setToolActive","_trackGlobalToolModeChange","setToolDisabledForElement","bind","setToolDisabled","setToolMode","setToolEnabledForElement","setToolEnabled","setToolPassive","changeEvent","_getNormalizedOptions","mouseButtonMask","mergeOptions","_resolveGenericInputConflicts","activeToolWithActiveInteractionType","historyEvent","shift","globalTool","stringBindings","configuration","mouseButtonMasks","mask","touchPointers","_determineStringBindings","keys","activeBindings","binding","some","Mouse","activeToolWithMatchingMouseButtonMask","isMouseActive","v","MouseWheel","Touch","activeTouchTool","isTouchActive","activeMultiTouchToolWithOneTouchPointer","isMultiTouchActive","TouchPinch","TouchRotate","DoubleTap","MultiTouch","activeMultiTouchTool","tempArray","mixins_0","activeOrDisabledBinaryTool","passiveCallback","enabledCallback","enabledOrDisabledBinaryTool","activeCallback","BaseTool","_ref","strategies","defaultStrategy","mixins","classCallCheck_default","activeStrategy","_options","_configuration","assign","hasCursor","_applyMixins","evt","mixinsArray","mixin","typeof_default","newImageIdSpecificToolStateManager","toolState","toolType","enabledImage","image","imageId","imageIdToolState","add","data","clear","saveImageIdToolState","restoreImageIdToolState","saveToolState","restoreToolState","savedToolState","globalImageIdSpecificToolStateManager","getElementToolStateManager","toolStateManager","addToolState","measurementData","getToolState","removeToolState","toolData","indexOfData","splice","clearToolState","setElementToolStateManager","pointInsideBoundingBox","handle","coords","boundingBox","point","insideRect","_isHandleNearImagePoint","distanceThreshold","pointNearHandle","hasBoundingBox","handleCanvas","pixelToCanvas","distance","getHandleNearImagePoint","handles","nearbyHandle","handleKeys","handleName","manipulators_handleActivator","canvasPoint","activeHandle","active","_getActiveHandle","anyHandlesOutsideImage","renderData","imageRect","left","top","width","height","handleOutsideImage","allowedOutsideImage","clip","val","low","high","clipToBox","box","x","y","_dragEvents","mouse","touch","_upOrEndEvents","moveAllHandles","annotation","dragHandler","_evt$detail","_evt$detail$deltaPoin","deltaPoints","invalidated","movesIndependently","updateImage","eventType","preventDefault","stopPropagation","upOrEndHandler","_ref2","eventData","removeEventListener","doneMovingCallback","_upOrEndHandler","addEventListener","runAnimation","moveHandle","evtDetail","currentPoints","page","targetLocation","pageToPixel","hasMoved","handlePressed","aboveFinger","_animate","distanceRemaining","abs","linearDistEachFrame","requestAnimationFrame","_moveEvents","_moveEndEvents","moveNewHandle","moveHandler","moveEndHandler","_evt$detail2","_stopImmediatePropagation","_moveEndHandler","stopImmediatePropagation","moveHandleNearImagePoint","findHandleDataNearImagePoint","moveAnnotation","toolOptions","BaseAnnotationTool","possibleConstructorReturn_default","getPrototypeOf_default","Error","canvas","imageNeedsUpdate","handleActivator","nearToolAndNotMarkedActive","pointNearTool","notNearToolAndMarkedActive","defaultWidth","activeWidth","toolStyle","setToolWidth","getToolWidth","setActiveWidth","getActiveWidth","defaultColor","activeColor","fillColor","toolColors","setFillColor","color","getFillColor","setToolColor","getToolColor","setActiveColor","getActiveColor","getColorIfActive","draw","context","save","restore","path","lineWidth","fillStyle","lineDash","beginPath","strokeStyle","setLineDash","fill","stroke","drawLine","start","end","coordSystem","moveTo","lineTo","drawJoinedLines","points","map","drawArrow","angle","atan2","cos","PI","sin","drawCircle","center","arc","drawEllipse","corner1","corner2","w","h","ox","oy","xe","ye","xm","ym","bezierCurveTo","closePath","drawHandles","_loop","handleKey","drawnIndependently","drawHandlesIfActive","handleCanvasCoords","drawLink","linkAnchorPoints","refPoint","findClosestPoint","boundingBoxPoints","defaultFontSize","defaultFont","defaultBackgroundColor","textStyle","setFont","font","getFont","setFontSize","fontSize","getFontSize","setBackgroundColor","backgroundColor","getBackgroundColor","fillTextLines","textLines","padding","textBaseline","text","index","fillText","fillBox","fillRect","textBoxWidth","origFont","measureText","drawTextBox","toString","maxWidth","centering","debug","drawLinkedTextBox","textBox","textBoxAnchorPoints","xOffset","yCenter","textCoords","drawRect","rect","getNewContext","getContext","setTransform","getDefault","defaultValue","setShadow","shadow","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","transformCanvasContext","viewport","vflip","rotation","translation","scale","translate","rotate","hflip","resetCanvasContextTransform","lineSegDistance","lineSegment","distanceToPoint","roundToDecimal","precision","multiplier","pow","round","vector","sqrt","AngleTool","_this","initialConfiguration","preventNewMeasurement","highlight","middle","_this2","_this$configuration","drawHandlesOnHover","currentTarget","canvasContext","handleStartCanvas","handleMiddleCanvas","handleOptions","columnPixelSpacing","rowPixelSpacing","sideA","sideB","sideC","sideALength","sideBLength","sideCLength","acos","rAngle","suffix","String","fromCharCode","parseInt","textBoxText","textWidth","transform","internal","getTransform","invert","transformPoint","_this3","createNewMeasurement","doneMovingEndHandleOptions","doneMovingMiddleHandleOptions","ArrowAnnotateTool","defaultConfig","getTextCallback","changeTextCallback","arrowFirst","handleEndCanvas","textHeight","midpoint","buttons","_updateTextForNearbyAnnotation","_doneChangingTextCallback","updatedText","deleteTool","doneChangingTextCallback","prompt","coordsData","getHandle","extraAttributes","bidirectionalTool_createNewMeasurement","mouseEventData","_mouseEventData$curre","isCreating","perpendicularStart","locked","perpendicularEnd","longestDiameter","shortestDiameter","bidirectionalTool_pointNearTool","pointNearPerpendicular","bidirectionalTool_renderToolData","imagePlane","metaData","colPixelSpacing","rowImagePixelSpacing","colImagePixelSpacing","getMeasurementData","_data$handles","strokeWidth","startX","startY","endX","endY","mid","dx","dy","vectorX","vectorY","perpendicularLineLength","updatePerpendicularLineHandles","getTextBoxText","additionalData","_data$handles2","wx","wy","tempL","toFixed","bidirectionalTool_addNewMeasurement","config","checkPixelSpacing","doneCallback","timestamp","Date","getTime","_measurementData$hand","hasHandlesOutside","longestDiameterSize","parseFloat","shortestDiameterSize","isTooSmal","isTooFast","cancelled","getMeasurementLocationCallback","toolCoordinates","setCoords","getCoords","bidirectionalTool_mouseMoveCallback","handleActivatorChanged","newActiveState","hover","nearTool","nearToolAndInactive","notNearToolAndActive","setHandlesPosition","distanceFromTool","outOfBounds","intersection","d1","d2","longLine","perpendicularLine","proposedPoint","intersectLine","distanceFromPerpendicularP1","distanceFromPerpendicularP2","distanceToLineP2","newLineLength","k","newIntersection","perpendicularBothFixedLeft","perpendicularBothFixedRight","movedPoint","fixedPoint","distanceFromFixed","distanceFromMoved","total","adjustedLineP1","adjustedLineP2","perpendicularLeftFixedPoint","perpendicularRightFixedPoint","swapAttribute","a","b","attribute","originalA","originalB","swapHandles","bidirectionalTool_preMouseDownCallback","handleDoneMove","moving","selected","style","cursor","_moveCallback","startPoints","handleParams","unselectAllHandles","_eventData$image","values","invertHandles","_dragCallback","modifiedEventData","currentImage","getImage","imageRenderedHandler","interactionEndCallback","IMAGE_RENDERED","preventPropagation","_ret","getDoneMovingCallback","setHandlesMovingState","touchEndEvents","preTouchStartCallback","touchDragCallback","touchEndCallback","touchMoveHandle","emptyLocationCallback","BidirectionalTool","changeMeasurementLocationCallback","mergedConfiguration","assertThisInitialized_default","renderToolData","addNewMeasurement","preMouseDownCallback","CobbAngleTool","hasIncomplete","complete","start2","end2","toMoveHandle","maybePending","getIncomplete","ev","dx1","ceil","dy1","dx2","dy2","Number","isNaN","calculateValue","onMeasureModified","calculateSUV","storedPixelValue","skipRescale","patientStudyModule","seriesModule","modality","modalityPixelValue","slope","intercept","patientWeight","petSequenceModule","radiopharmaceuticalInfo","startTime","radiopharmaceuticalStartTime","totalDose","radionuclideTotalDose","halfLife","radionuclideHalfLife","seriesAcquisitionTime","seriesTime","durationInSeconds","fracToDec","fractionalSeconds","seconds","minutes","hours","exp","log","fractionalValue","pointInEllipse","ellipse","location","xRadius","yRadius","normalized","calculateEllipseStatistics","sp","sum","sumSquared","count","mean","variance","stdDev","util_ellipse","numbersWithCommas","parts","split","replace","join","isObject","debounce","func","wait","lastArgs","lastThis","maxWait","result","timerId","lastCallTime","lastInvokeTime","leading","maxing","trailing","useRAF","invokeFunc","time","thisArg","startTimer","pendingFunc","setTimeout","shouldInvoke","timeSinceLastCall","timerExpired","now","trailingEdge","timeSinceLastInvoke","timeWaiting","remainingWait","debounced","isInvoking","_len","_key","leadingEdge","Boolean","cancel","id","cancelAnimationFrame","clearTimeout","cancelTimer","flush","pending","throttle","EllipticalRoiTool","validParameters","startCanvas","endCanvas","minorEllipse","majorEllipse","pointInMinorEllipse","hasPixelSpacing","pixelSpacing","cachedStats","_throttledUpdateCachedStats","_updateCachedStats","textBoxContent","_createTextBoxContent","startHandle","endHandle","_getEllipseImageCoord","_getEllipseImageCoordinates","stats","meanStdDevSUV","ellipseCoordinates","pixels","getPixels","ellipseMeanStdDev","area","_calculateStats","isColorImage","showMinMax","showHounsfieldUnits","otherLines","hasStandardUptakeValues","meanString","stdDevString","meanSuvString","stdDevSuvString","targetStringLength","minString","maxString","_formatArea","pointInFreehand","dataHandles","inROI","j","rayFromPointCrosssesLine","handleI","handleJ","yp","y1","y2","lp1","lp2","lptemp","lPointY","dydx","gradient","lineSegmentAtPoint","sign","isLineRightOfPoint","sumPointIfInFreehand","workingSum","pixelValue","squared","ClickedLineData","toolIndex","handleIndexArray","FreehandHandleData","position","lines","doesIntersectOtherLines","p1","q1","ignoredHandleIds","indexOf","doesIntersect","p2","q2","orient","orientation","onSegment","dataHandle","q","orientationValue","freehandIntersect","newHandle","candidateHandle","lastHandleId","modify","modifiedHandleId","modifiedHandle","neighborHandleId","neighborHandle","FreehandLineFinder","_eventData","_toolName","closestToolIndex","findTool","closeLines","_getCloseLinesInTool","_findCorrectLine","_toolData","_mousePoint","_nearestHandleToPointAllTools","closestHandle","handleIndex","Infinity","closestHandleForToolI","_nearestHandleToPoint","closest","handleDistanceFromMousePoint","nextIndex","getNextHandleIndex","_distanceOfPointfromLine","_pointProjectsToLineSegment","handle1","handle2","getCanvasPointsFromHandles","getLineAsVector","_getLineOriginToMouseAsVector","mProj","magnitude","pMouse","currentIndex","util_freehand","calculateFreehandStatistics","statisticsObj","getSum","freehandArea","scaling","freeHandArea","insertOrDelete","nearby","handleNearby","deleteInfo","deleteHandle","pop","insertInfo","findLine","insertIndex","arrayContainsZero","_getInsertionIndex","handleData","freehandUtils","FreehandMouseTool","mouseLocation","spacing","activeHandleRadius","completeHandleRadius","alwaysShowHandles","invalidColor","currentHandle","currentTool","_drawing","_dragging","_modifying","_drawingMouseDownCallback","_drawingMouseMoveCallback","_drawingMouseDragCallback","_drawingMouseUpCallback","_editMouseUpCallback","_editMouseDragCallback","_pointNearHandle","distanceI","canvasCoords","invalidHandlePlacement","toConsumableArray_default","polyBoundingBox","meanStdDev","canComplete","bounds","right","bottom","freehand","moSuffix","meanText","stdDevText","areaText","_startDrawing","_addPoint","_pointNearHandleAllTools","ctrlKey","dragOrigin","_activateModify","_getMouseLocation","_checkInvalidHandleLocation","_addPointPencilMode","lastHandlePlaced","_endDrawing","lastLineIndex","lastLine","_deactivateModify","_dropHandle","previousHandleData","currentHandleData","_referencedElement","_activateDraw","newHandleData","mousePoint","every","_isDistanceLargerThanSpacingCanvas","_deactivateDraw","_checkHandlesPencilMode","_checkHandlesPolygonMode","_isDistanceSmallerThanSpacingCanvas","_invalidHandlePencilMode","_compareDistanceToSpacingCanvas","comparison","p1Canvas","p2Canvas","_closeToolIfDrawing","LengthTool","_eventData$currentPoi","getRGBPixels","spIndex","row","column","storedPixelData","pixelData","getPixelData","red","columns","green","blue","ProbeTool","probeCoords","fontHeight","storedPixels","str","rows","getStoredPixels","mo","suv","RectangleRoiTool","_getRectangleImageCoo","_getRectangleImageCoordinates","roiCoordinates","roiMeanStdDev","rectangle","_calculateRectangleStats","TextMarkerTool","markers","current","ascending","loop","touchPressCallback","_changeText","doubleClickCallback","insideBoundingBox","BaseBrushTool","referencedToolData","_startPainting","_paint","_startListeningForMouseUp","_lastImageCoords","isToolActive","renderBrush","drawId","colorArray","getColor","_mouseUpRender","_stopListeningForMouseUp","oldRadius","newRadius","_getEnabledElement","stackToolState","imageIds","brushData","dim","xy","z","xyz","buffer","ArrayBuffer","Uint8Array","drawBrushPixels","pointerArray","shouldErase","drawBrushOnCanvas","canvasPtTL","canvasPtBR","sizeX","sizeY","canvasPt","getCircle","xCoord","yCoord","x0","y0","circleArray","brushUtils","BrushTool","overlapping","_overlappingStrategy","nonOverlapping","_nonOverlappingStrategy","mousePosition","_mousePosition","_getBrushColor","circleRadius","mouseCoordsCanvas","applyActiveStrategy","_eventData$image2","_isCtrlDown","segmentationIndex","newPixelData","Uint8ClampedArray","_eventData$image3","_eventData$currentPoi2","activeSegmentationIndex","defaultStartLoadHandler","defaultEndLoadHandler","defaultErrorLoadingHandler","loadHandlerManager","setStartLoadHandler","handler","getStartLoadHandler","setEndLoadHandler","getEndLoadHandler","setErrorLoadingHandler","getErrorLoadingHandler","convertToVector3","arrayOrVector3","Vector3","projectPatientPointToImagePlane","patientPoint","rowCosines","columnCosines","imagePositionPatient","clone","sub","dot","imagePointToPatientPoint","imagePoint","multiplyScalar","planePlaneIntersection","targetImagePlane","referenceImagePlane","targetRowCosines","targetColumnCosines","targetImagePositionPatient","referenceRowCosines","referenceColumnCosines","referenceImagePositionPatient","targetNormal","cross","targetPlane","Plane","setFromNormalAndCoplanarPoint","referenceNormal","referencePlane","originDirection","intersectPlane","origin","direction","bottomRight","distanceTo","line","Line3","intersections","side","segment","lineRectangleIntersection","topLeft","topRight","bottomLeft","getRectangleFromImagePlane","elementToolOptions","getToolOptions","optionsObject","toolOptionObject","setToolOptions","findIndex","elementOptions","CrosshairsTool","mouseDownCallback","_chooseLocation","mouseDragCallback","sourceElement","sourceImageId","sourceImagePlane","synchronizationContext","getSourceElements","targetElement","minDistance","MAX_VALUE","newImageIdIndex","stackToolDataSource","stackData","imagePosition","normal","currentImageIdIndex","startLoadingHandler","endLoadingHandler","errorLoadingHandler","preventCache","loadImage","loadAndCacheImage","getViewport","displayImage","DoubleTapFitToWindowTool","fitToWindow","DragProbeTool","default","minimal","minimalStrategy","_movingEventCallback","_endMovingEventCallback","mouseUpCallback","dragEventData","isTouchEvent","pageCoordY","toolCoords","modalityPixelValueText","EraserTool","_deleteAllNearbyTools","FreehandSculpterMouseTool","referencedToolName","minSpacing","maxSpacing","dragColor","hoverColor","showCursorOnHover","limitRadiusOutsideRegion","hoverCursorFadeAlpha","hoverCursorFadeDistance","_active","activeMouseUpCallback","activeMouseDragCallback","_toolSizeCanvas","_renderHoverCursor","_selectFreehandTool","_initialiseSculpting","_sculpt","_invalidateToolData","mouseUpRender","_deactivateSculpt","radiusCanvas","distanceFromPointCanvas","unlimitedRadius","_limitCursorRadiusCanvas","globalAlpha","_deselectAllTools","_getClosestFreehandToolOnElement","_configureToolSize","_activateFreehandTool","_activateSculpt","sculptData","toolSize","_toolSizeImage","_pushHandles","_insertNewHandles","_consolidateHandles","distanceToHandle","_pushOneHandle","directionUnitVector","lastHandleIndex","_getPreviousHandleIndex","indiciesToInsertAfter","_findNewHandleIndicies","newIndexModifier","_insertHandleRadially","nextHandleIndex","_getNextHandleIndex","nextHandleCanvas","previousIndex","_getNextHandleIndexBeforeInsert","insertPosition","_getInsertPosition","closePairs","_findCloseHandlePairs","_mergeCloseHandles","pair","removedIndexModifier","_getCorrectedPair","_combineHandles","newClosePairs","handlePair","midPoint","handleAfterPairIndex","freehandMouseTool","radiusImage","distanceFromPoint","_limitCursorRadiusImage","_limitCursorRadius","areaModifier","pixelCoords","distanceFromToolI","correctedPair","distanceToMidPoint","MagnifyTool","magnifySize","magnificationLevel","zoomCanvas","zoomElement","_createMagnificationCanvas","disabledCallback","_destroyMagnificationCanvas","postTouchStartCallback","_addMagnifyingGlass","_updateMagnifyingGlass","_removeMagnifyingGlass","touchDragEndCallback","postMouseDownCallback","mouseClickCallback","newImageCallback","_drawMagnificationTool","_removeZoomElement","_drawZoomedElement","querySelector","display","body","magnifyCanvas","canvasLocation","copyFrom","drawImage","touchOffset","magnifyPosition","magnifierBox","getBoundingClientRect","origCanvas","createElement","enable","zoomEnabledElement","setViewport","disable","classList","appendChild","removeChild","OverlayTool","forceImageUpdate","overlays","imageWidth","displayedArea","brhc","tlhc","imageHeight","overlay","layerCanvas","layerContext","globalCompositeOperation","PanMultiTouchTool","multiTouchDragCallback","numPointers","_getTranslation","_applyTranslation","widthScale","heightScale","PanTool","renderActiveReferenceLine","referenceElement","targetImage","referenceImage","frameOfReferenceUID","angleInRadians","angleTo","referenceLine","calculateReferenceLine","ms","waitForEnabledElementImageToLoad","ex","configMaxSimultaneousRequests","ReferenceLinesTool","renderer","setToPixelCoordinateSystem","referenceEnabledElement","angleBetweenPoints","p0","p12","p13","p23","RotateTool","horizontal","horizontalStrategy","vertical","verticalStrategy","dragCallback","initialRotation","clientWidth","clientHeight","initialPoints","client","centerPoints","angleInfo","RotateTouchTool","ScaleOverlayTool","minorTickLength","majorTickLength","canvasSize","verticalIntervalScale","horizontalIntervalScale","hscaleBounds","computeScaleBounds","vscaleBounds","imageAttributes","verticalMinorTick","horizontalMinorTick","verticalLine","horizontalLine","drawVerticalScalebarIntervals","drawHorizontalScalebarIntervals","horizontalReduction","verticalReduction","hReduction","vReduction","canvasBounds","startPoint","endPoint","maxSimultaneousRequests","IE","9","10","Firefox","Opera","11","12","Chrome","Safari","getBrowserInfo","tem","ua","navigator","userAgent","M","match","test","exec","slice","appName","appVersion","getMaxSimultaneousRequests","getDefaultSimultaneousRequests","browserName","browserVersion","browserData","requestPool","interaction","thumbnail","prefetch","numRequests","maxNumRequests","awake","grabDelay","startAgain","startGrabbing","sendRequest","requestDetails","failCallback","imageLoadObject","imageCache","getImageLoadObject","promise","priority","requestTypeToLoadPriority","requestsToSend","getNextRequest","requestPoolManager","addRequest","addToBeginning","unshift","clearRequestStack","getRequestPool","scrollToIndex","stackRenderer","stackRendererData","newImageId","render","util_scroll","images","allowSkipping","pendingEvent","scrollWithoutSkipping","NEW_IMAGE","newImageHandler","StackScrollMouseWheelTool","scroll","StackScrollMultiTouchTool","pixelsPerImage","_getPixelPerImage","deltaY","_getDeltaY","imageIdIndexOffset","deltaPointsY","stackScrollSpeed","offsetHeight","StackScrollTool","getLuminance","luminance","WwwcRegionTool","minWindowWidth","_resetHandles","_startOutliningRegion","_setHandlesAndUpdate","_applyStrategy","mouseMoveCallback","_isEmptyObject","_applyWWWCRegion","_evt$detail$handles","pixelLuminanceData","minMaxMean","_calculateMinMaxMean","minPixelValue","maxPixelValue","voi","windowWidth","windowCenter","pixelLuminance","globalMin","globalMax","numPixels","spv","WwwcTool","basicLevelingStrategy","deltaX","changeViewportScale","ticks","scaleLimits","maxScale","minScale","factor","zoom","correctShift","viewportOrientation","cosA","sinA","newX","newY","ZoomMouseWheelTool","spinY","updatedViewport","zoomUtils","ZoomTool","translateStrategy","zoomToCenter","zoomToCenterStrategy","preventZoomOutsideImage","imageX","imageY","newCoords","_ref3","_ref4","desiredTranslation","distanceToDesired","_ref5","ZoomTouchPinchTool","scaleChange","pageStartX","pageStartY","imageStartX","imageStartY","copyPoints","_copy","preventClickTimeout","KEY_CODES","48","49","50","51","52","53","54","55","56","57","96","97","98","99","100","101","102","103","104","105","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","112","113","114","115","116","13","8","46","27","20","173","189","109","61","187","107","219","221","59","186","188","190","199","lib","base/BaseTool","base/BaseAnnotationTool","base/BaseBrushTool","manipulators/anyHandlesOutsideImage","manipulators/getHandleNearImagePoint","manipulators/handleActivator","manipulators/moveAllHandles","manipulators/moveHandle","manipulators/moveNewHandle","manipulators/moveHandleNearImagePoint","manipulators/findHandleDataNearImagePoint","manipulators/moveAnnotation","mixins/activeOrDisabledBinaryTool","mixins/enabledOrDisabledBinaryTool","drawing/getNewContext","drawing/draw","drawing/path","drawing/setShadow","drawing/drawLine","drawing/drawLines","drawing/drawJoinedLines","drawing/drawCircle","drawing/drawEllipse","drawing/drawRect","drawing/fillOutsideRect","drawing/drawTextBox","drawing/drawArrow","drawing/fillBox","drawing/fillTextLines","drawing/drawLink","drawing/drawLinkedTextBox","drawing/drawHandles","drawing/textBoxWidth","util/getLuminance","util/copyPoints","util/calculateSUV","util/setContextToDisplayFontSize","lineHeight","fontScale","util/scrollToIndex","util/scroll","util/roundToDecimal","util/projectPatientPointToImagePlane","util/imagePointToPatientPoint","util/planePlaneIntersection","util/pointInsideBoundingBox","util/makeUnselectable","ignorePointerEvents","webkitUserSelect","webkitTouchCallout","mozUserSelect","msUserSelect","oUserSelect","khtmlUserSelect","userSelect","unselectable","oncontextmenu","pointerEvents","util/getRGBPixels","util/getDefaultSimultaneousRequests","util/getMaxSimultaneousRequests","util/getBrowserInfo","util/isMobileDevice","RegExp","util/angleBetweenPoints","util/getKeyFromKeyCode","keyCode","util/numbersWithCommas","util/lineSegDistance","util/triggerEvent","util/convertToVectro3","util/ellipseUtils","ellipseUtils","util/freehandUtils","util/brushUtils","util/zoomUtils","import_0","uri","isClickEvent","clickDelay","getEventButtons","which","preventClickHandler","mouseDoubleClick","e","pageToPoint","pageX","pageY","clientX","clientY","lastPoints","mouseDown","mouseMove","onMouseMove","onMouseUp","subtract","metaKey","shiftKey","mouseEventListeners","normalizeWheel","spinX","pixelX","pixelY","wheelDelta","wheelDeltaY","wheelDeltaX","deltaMode","wheelEventHandler","startingCoords","_normalizeWheel","mouseWheelData","passive","lastInteractionType","lastInteractionTime","wheelEventListener","antiGhostDelay","pointerType","handleTap","handleTapMouse","handleTapTouch","attachEvents","eventList","tapHandler","eventName","removeEvents","mouseEvents","touchEvents","touchStartDelay","pressTimeout","pageDistanceMoved","lastDelta","preventGhostClick","lastScale","lastRotation","preventNextPinch","isPress","pressDelay","pressMaxDistance","onTouch","srcEvent","delta","pointers","touches","changedTouches","changedPointers","mc","hammer","off","touchInput","hammerOptions","inputClass","SUPPORT_POINTER_EVENTS","PointerEventInput","TouchInput","Manager","panOptions","DIRECTION_ALL","threshold","pan","Pan","pinch","Pinch","Rotate","recognizeWith","doubleTap","Tap","taps","interval","posThreshold","on","getActiveToolsForElement","handlerType","createImageBitmap","asyncToGenerator_default","regenerator_default","mark","_callee","imageData","wrap","_context","prev","next","abrupt","img","conversionCanvas","putImageData","src","toDataURL","stop","_x","shouldRenderSegmentation","segData","renderSegmentation","alwaysVisible","canvasTopLeft","canvasTopRight","canvasBottomRight","cornerstoneCanvasWidth","cornerstoneCanvasHeight","imageSmoothingEnabled","getLayerAlpha","canvasViewportTranslation","_drawImageBitmap","colormapId","colorLutTable","ImageData","storedPixelDataToCanvasImageDataColorLUT","newImageBitmap","createNewBitmapAndQueueRenderOfSegmentation","onImageRendered","toolsToRender","maxSegmentations","getReferencedToolDataName","onImageRenderedBrushEventHandler","imageRenderedEventDispatcher","customCallbackHandler","customFunction","getToolsWithMoveableHandles","proximity","getInteractiveToolsForElement","getToolsWithDataForElement","mouseEventHandlers_mouseDown","activeAndPassiveTools","activeTools","firstActiveToolWithCallback","annotationTools","annotationToolsWithMoveableHandles","firstToolWithMoveableHandles","_findHandleDataNearIm","handleSelectedCallback","annotationToolsWithPointNearClick","firstToolNearPoint","firstAnnotationNearPoint","toolSelectedCallback","mouseDownActivate","activeTool","preMouseDownActivateCallback","mouseDrag","mouseEventHandlers_mouseMove","mouseClick","mouseUp","mouseWheel","mouseToolEventDispatcher","onNewImage","onNewImageBrushEventHandler","newImageEventDispatcher","multiTouchDrag","touchStartActive","touchEventData","deactivateAllToolInstances","deactivateAllHandles","tap","toolsWithMoveableHandles","moveableHandle","toolsNearPoint","allActiveTools","touchStartActiveCallback","touchStart","annotationToolsWithPointNearTouch","touchDrag","touchEnd","touchPinch","touchPress","touchRotate","touchToolEventDispatcher","addToolForElement","apiTool","addTool","_addToolGlobally","addEnabledElement","elementEnabledEvt","touchEventListeners","_addEnabledElmenet","_initModulesOnElement","_store$state$globalTo","_addGlobalToolsToElement","setToolModeFns","enabled","disabled","_repeatGlobalToolHistory","removeEnabledElement","elementDisabledEvt","_removeAllToolsForElement","_removeEnabledElement","removeEnabledElementCallback","_cleanModulesOnElement","foundElementIndex","resizeTimeout","resizeThrottler","forceEnabledElementResize","resize","windowResizeHandler","init","elementEnabledEvent","ELEMENT_ENABLED","elementDisabledEvent","ELEMENT_DISABLED","events","_removeCornerstoneEventListeners","_addCornerstoneEventListeners","resetPrefetchTimeout","requestType","maxImagesToPrefetch","resetPrefetchDelay","stack","stackPrefetchData","stackPrefetch","indicesToRequest","sort","imageIdIndex","removeFromList","nextImageIdIndex","nearest","lowerIndex","higherIndex","shouldSkipLower","shouldSkipHigher","shouldLoadLower","shouldLoadHigher","getPromiseRemovedHandler","onImageUpdated","lowEnd","highEnd","range","indexOfCurrentImage","promiseRemovedHandler","IMAGE_CACHE_PROMISE_REMOVED","getConfiguration","setConfiguration","newMaxSimultaneousRequests","FusionRenderer","layerIds","findImageFn","imageStacks","isInteger","baseImageObject","currentImageId","overlayImageStacks","baseImage","baseLayerId","setLayerImage","addLayer","imgObj","overlayLayerIndex","layerIndex","currentLayerId","setActiveLayer","stackRenderers","stopClipWithData","playClipData","intervalId","usingFrameTimeVector","clearInterval","playClip","framesPerSecond","playClipTimeouts","stackToolData","playClipToolData","lastFrameTimeStamp","frameRate","frameTimeVector","ignoreFrameTimeVector","speed","reverse","sample","delay","limit","timeouts","isTimeVarying","getPlayClipTimeouts","playClipAction","imageCount","eventDetail","triggerStopEvent","playClipTimeoutHandler","setInterval","stopClip","removeToolForElement","removeTool","_removeToolGlobally","setToolOptionsForElement","newStackSpecificToolStateManager","toolTypes","oldStateManager","stackStateManagers","addStackStateManager","otherTools","stackTools","stackSpecificStateManager","newFrameOfReferenceSpecificToolStateManager","frameOfReference","frameOfReferenceToolState","remove","globalFrameOfReferenceSpecificToolStateManager","getOrientationString","vec3","orientationX","orientationY","orientationZ","invertOrientationString","orientationString","inverted","toUpperCase","SaveAs","filename","mimetype","msToBlob","blob","msSaveBlob","lnk","download","href","initMouseEvent","fireEvent","registerModule","newModule","overwrite","isModuleNameRegistered","registerMixin","isMixinRegistered","registerItem","item","isItemNameRegistered","register","isValidInput","registerSome","items","_items$i","wwwcSynchronizer","synchronizer","sourceViewport","targetViewport","updateImageSynchronizer","unique","array","Synchronizer","that","sourceElements","targetElements","ignoreFiredEvents","initialData","eventHandler","isDisabled","noElements","targetIndex","targetImageId","sourceIndex","positionDifference","distances","onEvent","disableHandler","clearToolOptionsByElement","setHandler","getHandler","getDistances","sourceEnabledElement","sourceImagePosition","targetEnabledElement","targetImagePosition","addSource","oneEvent","updateDisableHandlers","addTarget","removeSource","removeTarget","getTargetElements","destroy","stackScrollSynchronizer","stackImagePositionSynchronizer","sourceStackData","distanceToSquared","stackImagePositionOffsetSynchronizer","finalPosition","stackImageIndexSynchronizer","targetStackData","panZoomSynchronizer","__webpack_exports__","annotation_AngleTool","ArrowAnnotateTool_ArrowAnnotateTool","BidirectionalTool_BidirectionalTool","CobbAngleTool_CobbAngleTool","EllipticalRoiTool_EllipticalRoiTool","FreehandMouseTool_FreehandMouseTool","LengthTool_LengthTool","ProbeTool_ProbeTool","RectangleRoiTool_RectangleRoiTool","TextMarkerTool_TextMarkerTool","BrushTool_BrushTool","CrosshairsTool_CrosshairsTool","DoubleTapFitToWindowTool_DoubleTapFitToWindowTool","DragProbeTool_DragProbeTool","EraserTool_EraserTool","FreehandSculpterMouseTool_FreehandSculpterMouseTool","MagnifyTool_MagnifyTool","OverlayTool_OverlayTool","PanMultiTouchTool_PanMultiTouchTool","PanTool_PanTool","ReferenceLinesTool_ReferenceLinesTool","RotateTool_RotateTool","RotateTouchTool_RotateTouchTool","ScaleOverlayTool_ScaleOverlayTool","StackScrollMouseWheelTool_StackScrollMouseWheelTool","StackScrollMultiTouchTool_StackScrollMultiTouchTool","StackScrollTool_StackScrollTool","WwwcRegionTool_WwwcRegionTool","WwwcTool_WwwcTool","ZoomMouseWheelTool_ZoomMouseWheelTool","ZoomTool_ZoomTool","ZoomTouchPinchTool_ZoomTouchPinchTool","stackTools_stackPrefetch","stackTools_stackRenderers","addTool_addTool","addTool_addToolForElement","removeTool_removeTool","removeTool_removeToolForElement","setToolOptions_setToolOptions","setToolOptions_setToolOptionsForElement","setToolMode_setToolActive","setToolMode_setToolActiveForElement","stateManagement_textStyle","stateManagement_toolStyle","stateManagement_toolColors","stateManagement_toolCoordinates","stackSpecificStateManager_stackSpecificStateManager","stateManagement_loadHandlerManager","windowResizeHandler_forceEnabledElementResize","orientation_0","synchronization_Synchronizer","cornerstoneTools","import","imp","version","global","Op","hasOwn","$Symbol","iteratorSymbol","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","toStringTag","inModule","runtime","regeneratorRuntime","GenStateSuspendedStart","GenStateSuspendedYield","GenStateExecuting","GenStateCompleted","ContinueSentinel","IteratorPrototype","getProto","NativeIteratorPrototype","Gp","GeneratorFunctionPrototype","Generator","GeneratorFunction","displayName","isGeneratorFunction","genFun","ctor","awrap","__await","defineIteratorMethods","AsyncIterator","async","innerFn","outerFn","tryLocsList","iter","Context","reset","skipTempReset","sent","_sent","delegate","method","tryEntries","resetTryEntry","charAt","rootRecord","completion","rval","dispatchException","exception","loc","caught","record","entry","tryLoc","hasCatch","hasFinally","catchLoc","finallyLoc","finallyEntry","afterLoc","finish","catch","thrown","delegateYield","iterable","resultName","nextLoc","protoGenerator","generator","_invoke","doneResult","delegateResult","maybeInvokeDelegate","tryCatch","makeInvokeMethod","previousPromise","callInvokeWithMethodAndArg","invoke","unwrapped","return","pushTryEntry","locs","iteratorMethod","Function","g","hadRuntime","getOwnPropertyNames","oldRuntime","from","arr2","_setPrototypeOf"],"mappings":";CAAA,SAAAA,EAAAC,GACA,iBAAAC,SAAA,iBAAAC,OACAA,OAAAD,QAAAD,IACA,mBAAAG,eAAAC,IACAD,OAAA,uBAAAH,GACA,iBAAAC,QACAA,QAAA,qBAAAD,IAEAD,EAAA,iBAAAC,IARA,CASCK,OAAA,WACD,mBCTA,IAAAC,KAGA,SAAAC,EAAAC,GAGA,GAAAF,EAAAE,GACA,OAAAF,EAAAE,GAAAP,QAGA,IAAAC,EAAAI,EAAAE,IACAC,EAAAD,EACAE,GAAA,EACAT,YAUA,OANAU,EAAAH,GAAAI,KAAAV,EAAAD,QAAAC,IAAAD,QAAAM,GAGAL,EAAAQ,GAAA,EAGAR,EAAAD,QA2CA,OAtCAM,EAAAM,EAAAF,EAGAJ,EAAAO,EAAAR,EAGAC,EAAAQ,EAAA,SAAAd,EAAAe,EAAAC,GACAV,EAAAW,EAAAjB,EAAAe,IACAG,OAAAC,eAAAnB,EAAAe,GACAK,cAAA,EACAC,YAAA,EACAC,IAAAN,KAMAV,EAAAiB,EAAA,SAAAvB,GACAkB,OAAAC,eAAAnB,EAAA,cAAiDwB,OAAA,KAIjDlB,EAAAmB,EAAA,SAAAxB,GACA,IAAAe,EAAAf,KAAAyB,WACA,WAA2B,OAAAzB,E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AAqC,UAAAvB,EACAd,GAGA8vE,EAAA9vE,EAAAc,GAGA9B,EAAAD,QAAA+wE","file":"cornerstoneTools.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"cornerstone-tools\", [], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"cornerstone-tools\"] = factory();\n\telse\n\t\troot[\"cornerstoneTools\"] = factory();\n})(window, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, {\n \t\t\t\tconfigurable: false,\n \t\t\t\tenumerable: true,\n \t\t\t\tget: getter\n \t\t\t});\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 10);\n","function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}\n\nmodule.exports = _assertThisInitialized;","function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nmodule.exports = _classCallCheck;","function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n}\n\nmodule.exports = _createClass;","var setPrototypeOf = require(\"./setPrototypeOf\");\n\nfunction _inherits(subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n writable: true,\n configurable: true\n }\n });\n if (superClass) setPrototypeOf(subClass, superClass);\n}\n\nmodule.exports = _inherits;","function _getPrototypeOf(o) {\n module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}\n\nmodule.exports = _getPrototypeOf;","var _typeof = require(\"../helpers/typeof\");\n\nvar assertThisInitialized = require(\"./assertThisInitialized\");\n\nfunction _possibleConstructorReturn(self, call) {\n if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) {\n return call;\n }\n\n return assertThisInitialized(self);\n}\n\nmodule.exports = _possibleConstructorReturn;","function _typeof2(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof2(obj); }\n\nfunction _typeof(obj) {\n if (typeof Symbol === \"function\" && _typeof2(Symbol.iterator) === \"symbol\") {\n module.exports = _typeof = function _typeof(obj) {\n return _typeof2(obj);\n };\n } else {\n module.exports = _typeof = function _typeof(obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : _typeof2(obj);\n };\n }\n\n return _typeof(obj);\n}\n\nmodule.exports = _typeof;","module.exports = require(\"regenerator-runtime\");\n","function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n}\n\nfunction _asyncToGenerator(fn) {\n return function () {\n var self = this,\n args = arguments;\n return new Promise(function (resolve, reject) {\n var gen = fn.apply(self, args);\n\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n\n _next(undefined);\n });\n };\n}\n\nmodule.exports = _asyncToGenerator;","var arrayWithoutHoles = require(\"./arrayWithoutHoles\");\n\nvar iterableToArray = require(\"./iterableToArray\");\n\nvar nonIterableSpread = require(\"./nonIterableSpread\");\n\nfunction _toConsumableArray(arr) {\n return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread();\n}\n\nmodule.exports = _toConsumableArray;","let cornerstone = window.cornerstone;\nlet cornerstoneMath = window.cornerstoneMath;\nlet Hammer = window.Hammer;\n\nexport default {\n set cornerstone(cs) {\n cornerstone = cs;\n },\n get cornerstone() {\n return cornerstone;\n },\n set cornerstoneMath(cm) {\n cornerstoneMath = cm;\n },\n get cornerstoneMath() {\n return cornerstoneMath;\n },\n set Hammer(module) {\n Hammer = module;\n },\n get Hammer() {\n return Hammer;\n },\n};\n","/**\n * Enumerates the events for CornestoneTools. Native events are captured,\n * normalized, and re-triggered with a `cornerstonetools` prefix. This allows\n * us to handle events consistently across different browsers.\n *\n * @enum {String}\n * @memberof CornerstoneTools\n * @readonly\n */\nconst EVENTS = {\n //\n // MOUSE\n //\n\n /**\n * https://developer.mozilla.org/en-US/docs/Web/Events/mousedown\n * @type {String}\n */\n MOUSE_DOWN: 'cornerstonetoolsmousedown',\n\n /**\n * https://developer.mozilla.org/en-US/docs/Web/Events/mouseup\n * @type {String}\n */\n MOUSE_UP: 'cornerstonetoolsmouseup',\n\n /**\n * Is fired if a handled `MOUSE_DOWN` event does not `stopPropagation`. The hook\n * we use to create new measurement data for mouse events.\n * @type {String}\n */\n MOUSE_DOWN_ACTIVATE: 'cornerstonetoolsmousedownactivate',\n\n /**\n * https://developer.mozilla.org/en-US/docs/Web/Events/drag\n * @type {String}\n */\n MOUSE_DRAG: 'cornerstonetoolsmousedrag',\n\n /**\n * https://developer.mozilla.org/en-US/docs/Web/Events/mousemove\n * @type {String}\n */\n MOUSE_MOVE: 'cornerstonetoolsmousemove',\n\n /**\n * https://developer.mozilla.org/en-US/docs/Web/Events/click\n * @type {String}\n */\n MOUSE_CLICK: 'cornerstonetoolsmouseclick',\n\n /**\n * https://developer.mozilla.org/en-US/docs/Web/Events/dblclick\n * @type {String}\n */\n MOUSE_DOUBLE_CLICK: 'cornerstonetoolsmousedoubleclick',\n\n /**\n * https://developer.mozilla.org/en-US/docs/Web/Events/wheel\n * @type {String}\n */\n MOUSE_WHEEL: 'cornerstonetoolsmousewheel',\n\n //\n // TOUCH\n //\n\n /**\n * https://developer.mozilla.org/en-US/docs/Web/Events/touchstart\n * @type {String}\n */\n TOUCH_START: 'cornerstonetoolstouchstart',\n\n /**\n * Is fired if a handled `TOUCH_START` event does not `stopPropagation`. The hook\n * we use to create new measurement data for touch events.\n * @type {String}\n */\n TOUCH_START_ACTIVE: 'cornerstonetoolstouchstartactive',\n\n /**\n * @type {String}\n */\n TOUCH_END: 'cornerstonetoolstouchend',\n\n /**\n * @type {String}\n */\n TOUCH_DRAG: 'cornerstonetoolstouchdrag',\n\n /**\n * @type {String}\n */\n TOUCH_DRAG_END: 'cornerstonetoolstouchdragend',\n\n /**\n * http://hammerjs.github.io/recognizer-pinch/\n * @type {String}\n */\n TOUCH_PINCH: 'cornerstonetoolstouchpinch',\n\n /**\n * http://hammerjs.github.io/recognizer-rotate/\n * @type {String}\n */\n TOUCH_ROTATE: 'cornerstonetoolstouchrotate',\n\n /**\n * http://hammerjs.github.io/recognizer-press/\n * @type {String}\n */\n TOUCH_PRESS: 'cornerstonetoolstouchpress',\n\n /**\n * http://hammerjs.github.io/recognizer-tap/\n * @type {String}\n */\n TAP: 'cornerstonetoolstap',\n\n /**\n * @type {String}\n */\n DOUBLE_TAP: 'cornerstonetoolsdoubletap',\n\n /**\n * @type {String}\n */\n MULTI_TOUCH_START: 'cornerstonetoolsmultitouchstart',\n\n /**\n * @type {String}\n */\n MULTI_TOUCH_START_ACTIVE: 'cornerstonetoolsmultitouchstartactive',\n\n /**\n * @type {String}\n */\n MULTI_TOUCH_DRAG: 'cornerstonetoolsmultitouchdrag',\n\n //\n // KEYBOARD\n //\n\n /**\n * https://developer.mozilla.org/en-US/docs/Web/Events/keydown\n * @type {String}\n */\n KEY_DOWN: 'cornerstonetoolskeydown',\n\n /**\n * https://developer.mozilla.org/en-US/docs/Web/Events/keyup\n * @type {String}\n */\n KEY_UP: 'cornerstonetoolskeyup',\n\n /**\n * https://developer.mozilla.org/en-US/docs/Web/Events/keypress\n * @type {String}\n */\n KEY_PRESS: 'cornerstonetoolskeypress',\n\n //\n // CUSTOM\n //\n\n /**\n * @type {String}\n */\n MEASUREMENT_ADDED: 'cornerstonetoolsmeasurementadded',\n\n /**\n * @type {String}\n */\n MEASUREMENT_MODIFIED: 'cornerstonetoolsmeasurementmodified',\n\n /**\n * @type {String}\n */\n MEASUREMENT_REMOVED: 'cornerstonetoolsmeasurementremoved',\n\n /**\n * @type {String}\n */\n TOOL_DEACTIVATED: 'cornerstonetoolstooldeactivated',\n\n /**\n * @type {String}\n */\n CLIP_STOPPED: 'cornerstonetoolsclipstopped',\n\n /**\n * @type {String}\n */\n STACK_SCROLL: 'cornerstonetoolsstackscroll',\n};\n\nexport default EVENTS;\n","/**\n * Triggers a CustomEvent.\n * @public\n * @method triggerEvent\n *\n * @param {EventTarget} el The element or EventTarget to trigger the event upon.\n * @param {String} type The event type name.\n * @param {Object|null} [detail=null] The event data to be sent.\n * @returns {Boolean} The return value is false if at least one event listener called preventDefault(). Otherwise it returns true.\n */\nexport default function triggerEvent(el, type, detail = null) {\n let event;\n\n // This check is needed to polyfill CustomEvent on IE11-\n if (typeof window.CustomEvent === 'function') {\n event = new CustomEvent(type, {\n detail,\n cancelable: true,\n });\n } else {\n event = document.createEvent('CustomEvent');\n event.initCustomEvent(type, true, true, detail);\n }\n\n return el.dispatchEvent(event);\n}\n","import external from './../../externalModules.js';\n\nconst state = {\n drawColorId: 0,\n radius: 10,\n minRadius: 1,\n maxRadius: 50,\n alpha: 0.4,\n renderBrushIfHiddenButActive: true,\n hiddenButActiveAlpha: 0.2,\n colorMapId: 'BrushColorMap',\n visibleSegmentations: {},\n imageBitmapCache: {},\n segmentationMetadata: {},\n};\n\nconst setters = {\n /**\n * Sets the brush radius, account for global min/max radius\n *\n * @param {number} radius\n */\n radius: radius => {\n state.radius = Math.min(Math.max(radius, state.minRadius), state.maxRadius);\n },\n\n /**\n * TODO: Should this be a init config property?\n * Sets the brush color map to something other than the default\n *\n * @param {Array} colors An array of 4D [red, green, blue, alpha] arrays.\n */\n brushColorMap: colors => {\n const colormap = external.cornerstone.colors.getColormap(state.colorMapId);\n\n colormap.setNumberOfColors(colors.length);\n\n for (let i = 0; i < colors.length; i++) {\n colormap.setColor(i, colors[i]);\n }\n },\n elementVisible: enabledElement => {\n if (!external.cornerstone) {\n return;\n }\n\n const cornerstoneEnabledElement = external.cornerstone.getEnabledElement(\n enabledElement\n );\n\n const enabledElementUID = cornerstoneEnabledElement.uuid;\n const colormap = external.cornerstone.colors.getColormap(state.colorMapId);\n const numberOfColors = colormap.getNumberOfColors();\n\n state.visibleSegmentations[enabledElementUID] = [];\n\n for (let i = 0; i < numberOfColors; i++) {\n state.visibleSegmentations[enabledElementUID].push(true);\n }\n },\n brushVisibilityForElement: (enabledElementUID, segIndex, visible = true) => {\n if (!state.visibleSegmentations[enabledElementUID]) {\n state.imageBitmapCache[enabledElementUID] = [];\n }\n\n state.visibleSegmentations[enabledElementUID][segIndex] = visible;\n },\n imageBitmapCacheForElement: (enabledElementUID, segIndex, imageBitmap) => {\n if (!state.imageBitmapCache[enabledElementUID]) {\n state.imageBitmapCache[enabledElementUID] = [];\n }\n\n state.imageBitmapCache[enabledElementUID][segIndex] = imageBitmap;\n },\n clearImageBitmapCacheForElement: enabledElementUID => {\n state.imageBitmapCache[enabledElementUID] = [];\n },\n metadata: (seriesInstanceUid, segIndex, metadata) => {\n if (!state.segmentationMetadata[seriesInstanceUid]) {\n state.segmentationMetadata[seriesInstanceUid] = [];\n }\n\n state.segmentationMetadata[seriesInstanceUid][segIndex] = metadata;\n },\n};\n\nconst getters = {\n imageBitmapCacheForElement: enabledElementUID => {\n if (!state.imageBitmapCache[enabledElementUID]) {\n return null;\n }\n\n return state.imageBitmapCache[enabledElementUID];\n },\n visibleSegmentationsForElement: enabledElementUID => {\n if (!state.visibleSegmentations[enabledElementUID]) {\n return null;\n }\n\n return state.visibleSegmentations[enabledElementUID];\n },\n\n /**\n * Retrieves series-specific brush segmentation metadata.\n * @public\n * @function metadata\n * @param {string} seriesInstanceUid - The seriesInstanceUid of the scan.\n * @param {number} [segIndex] - The segmentation index.\n *\n * @returns {Object[]|Object} An array of segmentation metadata, or specifc\n * segmentation data if segIndex is defined.\n */\n metadata: (seriesInstanceUid, segIndex) => {\n if (!state.segmentationMetadata[seriesInstanceUid]) {\n return;\n }\n\n if (segIndex !== undefined) {\n return state.segmentationMetadata[seriesInstanceUid][segIndex];\n }\n\n return state.segmentationMetadata[seriesInstanceUid];\n },\n};\n\n/**\n * EnabledElementCallback - Element specific initilisation.\n * @public\n * @param {Object} enabledElement The element on which the module is\n * being initialised.\n */\nfunction enabledElementCallback(enabledElement) {\n setters.elementVisible(enabledElement);\n}\n\n/**\n * RemoveEnabledElementCallback - Element specific memory cleanup.\n * @public\n * @param {Object} enabledElement The element being removed.\n */\nfunction removeEnabledElementCallback(enabledElement) {\n if (!external.cornerstone) {\n return;\n }\n\n const cornerstoneEnabledElement = external.cornerstone.getEnabledElement(\n enabledElement\n );\n\n const enabledElementUID = cornerstoneEnabledElement.uuid;\n const colormap = external.cornerstone.colors.getColormap(state.colorMapId);\n const numberOfColors = colormap.getNumberOfColors();\n\n // Remove enabledElement specific data.\n delete state.visibleSegmentations[enabledElementUID];\n delete state.imageBitmapCache[enabledElementUID];\n}\n\n/**\n * OnRegisterCallback - Initialise the module when a new element is added.\n * @public\n */\nfunction onRegisterCallback() {\n _initDefaultColorMap();\n}\n\nexport default {\n state,\n onRegisterCallback,\n enabledElementCallback,\n getters,\n setters,\n};\n\nconst distinctColors = [\n [230, 25, 75, 255],\n [60, 180, 175, 255],\n [255, 225, 25, 255],\n [0, 130, 200, 255],\n [245, 130, 48, 255],\n [145, 30, 180, 255],\n [70, 240, 240, 255],\n [240, 50, 230, 255],\n [210, 245, 60, 255],\n [250, 190, 190, 255],\n [0, 128, 128, 255],\n [230, 190, 255, 255],\n [170, 110, 40, 255],\n [255, 250, 200, 255],\n [128, 0, 0, 255],\n [170, 255, 195, 255],\n [128, 128, 0, 255],\n [255, 215, 180, 255],\n [0, 0, 128, 255],\n];\n\nlet colorPairIndex = 0;\n\nfunction _initDefaultColorMap() {\n const defaultSegmentationCount = 19;\n const colormap = external.cornerstone.colors.getColormap(state.colorMapId);\n\n colormap.setNumberOfColors(defaultSegmentationCount);\n\n /*\n 19 Colors selected to be as distinct from each other as possible,\n and ordered such that between each index you make large jumps around the\n color wheel. If defaultSegmentationCount is greater than 19, generate a\n random linearly interperlated color between 2 colors.\n */\n for (let i = 0; i < defaultSegmentationCount; i++) {\n if (i < distinctColors.length) {\n colormap.setColor(i, distinctColors[i]);\n } else {\n colormap.setColor(i, _generateInterpolatedColor());\n }\n }\n}\n\n/**\n * _generateInterpolatedColor - generates a color interpolated between two\n * colors. Humans can only distinguish between\n * ~15-20 colors, so this is the best we can do.\n * @private\n *\n * @returns {type} description\n */\nfunction _generateInterpolatedColor() {\n const randIndicies = _getNextColorPair();\n const fraction = Math.random();\n const interpolatedColor = [];\n\n for (let i = 0; i < 4; i++) {\n interpolatedColor.push(\n Math.floor(\n fraction * distinctColors[randIndicies[0]][i] +\n (1.0 - fraction) * distinctColors[randIndicies[1]][i]\n )\n );\n }\n\n return interpolatedColor;\n}\n\n/**\n * _getNextColorPair - returns the next pair of indicies to interpolate between.\n *\n * @private\n *\n * @returns {Array} An array containing the two indicies.\n */\nfunction _getNextColorPair() {\n const indexPair = [colorPairIndex];\n\n if (colorPairIndex < distinctColors.length - 1) {\n colorPairIndex++;\n indexPair.push(colorPairIndex);\n } else {\n colorPairIndex = 0;\n indexPair.push(colorPairIndex);\n }\n\n return indexPair;\n}\n","const state = {\n mouseEnabled: true,\n touchEnabled: true,\n globalToolSyncEnabled: false,\n};\n\nexport default {\n state,\n setters: {},\n};\n","// Modules\nimport brush from './modules/brushModule.js';\nimport globalConfiguration from './modules/globalConfigurationModule.js';\nimport external from '../externalModules.js';\n\nexport const state = {\n // Global\n globalTools: {},\n globalToolChangeHistory: [],\n // Tracking\n enabledElements: [],\n tools: [],\n isToolLocked: false,\n mousePositionImage: {},\n // Settings\n clickProximity: 6,\n touchProximity: 10,\n handleRadius: 6,\n deleteIfHandleOutsideImage: true,\n preventHandleOutsideImage: false,\n};\n\nexport const getters = {\n mouseTools: () =>\n state.tools.filter(tool =>\n tool.supportedInteractionTypes.includes('Mouse')\n ),\n touchTools: () =>\n state.tools.filter(tool =>\n tool.supportedInteractionTypes.includes('Touch')\n ),\n enabledElementByUID: enabledElementUID =>\n state.enabledElements.find(\n element =>\n external.cornerstone.getEnabledElement(element).uuid ===\n enabledElementUID\n ),\n};\n\nexport const setters = {};\n\nexport const modules = {\n brush,\n globalConfiguration,\n};\n\nexport default {\n modules,\n state,\n getters,\n};\n","import { state } from './index.js';\n\n/**\n * Returns the tool instance attached to the element.\n * @export\n * @public\n * @method\n * @name getToolForElement\n *\n * @param {HTMLElement} element The element.\n * @param {string} name The tool's name.\n * @returns {Object} The tool instance.\n */\nexport default function(element, name) {\n return state.tools.find(\n tool => tool.element === element && tool.name === name\n );\n}\n","import EVENTS from './../events.js';\nimport triggerEvent from './../util/triggerEvent.js';\nimport getToolForElement from './getToolForElement.js';\nimport store from './../store/index.js';\n\n/**\n * Sets a tool's state, with the provided toolName and element, to 'active'. Active tools are rendered,\n * respond to user input, and can create new data.\n *\n * @public\n * @function setToolActiveForElement\n * @memberof CornerstoneTools\n *\n * @example <caption>Setting a tool 'active' for a specific interaction type.</caption>\n * // Sets length tool to Active\n * setToolActiveForElement(element, 'Length', {\n * mouseButtonMask: 1\n * }, ['Mouse'])\n * @example <caption>Setting a tool 'active' for all interaction types.</caption>\n * // Sets length tool to Active\n * setToolActiveForElement(element, 'Length', {\n * mouseButtonMask: 1\n * })\n * @param {HTMLElement} element\n * @param {string} toolName\n * @param {(Object|string[]|number)} options\n * @param {(string[])} interactionTypes\n * @returns {undefined}\n */\nconst setToolActiveForElement = function(\n element,\n toolName,\n options,\n interactionTypes\n) {\n // If interactionTypes was passed in via options\n if (interactionTypes === undefined && Array.isArray(options)) {\n interactionTypes = options;\n options = null;\n }\n\n const tool = getToolForElement(element, toolName);\n\n if (tool) {\n _resolveInputConflicts(element, tool, options, interactionTypes);\n\n // Iterate over specific interaction types and set active\n // This is used as a secondary check on active tools to find the active \"parts\" of the tool\n tool.supportedInteractionTypes.forEach(interactionType => {\n if (\n interactionTypes === undefined ||\n interactionTypes.includes(interactionType)\n ) {\n options[`is${interactionType}Active`] = true;\n } else {\n options[`is${interactionType}Active`] = false;\n }\n });\n }\n\n // Resume normal behavior\n setToolModeForElement('active', null, element, toolName, options);\n};\n\n/**\n * Sets all tool's state, with the provided toolName, to 'active'. Active tools are rendered,\n * respond to user input, and can create new data.\n * @public\n * @function setToolActive\n * @memberof CornerstoneTools\n *\n * @param {string} toolName\n * @param {(Object|string[]|number)} options\n * @param {(string[])} interactionTypes\n * @returns {undefined}\n */\nconst setToolActive = function(toolName, options, interactionTypes) {\n _trackGlobalToolModeChange('active', toolName, options, interactionTypes);\n store.state.enabledElements.forEach(element => {\n setToolActiveForElement(element, toolName, options, interactionTypes);\n });\n};\n\n/**\n * Sets a tool's state, with the provided toolName and element, to 'disabled'. Disabled tools are not rendered,\n * and do not respond to user input\n * @public\n * @function setToolDisabledForElement\n * @memberof CornerstoneTools\n *\n * @param {HTMLElement} element\n * @param {string} toolName\n * @param {(Object|number)} options\n * @returns {undefined}\n */\nconst setToolDisabledForElement = setToolModeForElement.bind(\n null,\n 'disabled',\n null\n);\n\n/**\n * Sets all tool's state, with the provided toolName, to 'disabled'. Disabled tools are not rendered,\n * and do not respond to user input\n * @public\n * @function setToolDisabled\n * @memberof CornerstoneTools\n *\n * @param {string} toolName\n * @param {(Object|number)} options\n * @returns {undefined}\n */\nconst setToolDisabled = setToolMode.bind(null, 'disabled', null);\n\n/**\n * Sets a tool's state, with the provided toolName and element, to 'enabled'. Enabled tools are rendered,\n * but do not respond to user input\n * @public\n * @function setToolEnabledForElement\n * @memberof CornerstoneTools\n *\n * @param {HTMLElement} element\n * @param {string} toolName\n * @param {(Object|number)} options\n * @returns {undefined}\n */\nconst setToolEnabledForElement = setToolModeForElement.bind(\n null,\n 'enabled',\n null\n);\n\n/**\n * Sets all tool's state, with the provided toolName, to 'enabled'. Enabled tools are rendered,\n * but do not respond to user input\n * @public\n * @function setToolEnabled\n * @memberof CornerstoneTools\n *\n * @param {string} toolName\n * @param {(Object|number)} options\n * @returns {undefined}\n */\nconst setToolEnabled = setToolMode.bind(null, 'enabled', null);\n\n/**\n * Sets a tool's state, with the provided toolName and element, to 'passive'. Passive tools are rendered and respond to user input,\n * but do not create new measurements or annotations.\n * @public\n * @function setToolPassiveForElement\n * @memberof CornerstoneTools\n *\n * @param {HTMLElement} element\n * @param {string} toolName\n * @param {(Object|number)} options\n * @returns {undefined}\n */\nconst setToolPassiveForElement = setToolModeForElement.bind(\n null,\n 'passive',\n EVENTS.TOOL_DEACTIVATED\n);\n\n/**\n * Sets all tool's state, with the provided toolName, to 'passive'. Passive tools are rendered and respond to user input,\n * but do not create new measurements or annotations.\n * @public\n * @function setToolPassive\n * @memberof CornerstoneTools\n *\n * @param {string} toolName\n * @param {(Object|number)} options\n * @returns {undefined}\n */\nconst setToolPassive = setToolMode.bind(\n null,\n 'passive',\n EVENTS.TOOL_DEACTIVATED\n);\n\n/**\n * An internal method that helps make sure we change tool mode in a consistent\n * way\n * @private\n * @function setToolModeForElement\n *\n * @param {string} mode\n * @param {string} changeEvent\n * @param {HTMLElement} element\n * @param {string} toolName\n * @param {(Object|number[]|number)} options\n * @returns {undefined}\n */\nfunction setToolModeForElement(mode, changeEvent, element, toolName, options) {\n const tool = getToolForElement(element, toolName);\n\n if (!tool) {\n console.warn(`Unable to find tool '${toolName}' for enabledElement`);\n\n return;\n }\n\n options = _getNormalizedOptions(options);\n\n // Keep the same if not an array (undefined)\n // Reset if empty array\n // Merge if array contains any bindings\n if (\n Array.isArray(options.mouseButtonMask) &&\n options.mouseButtonMask.length !== 0 &&\n Array.isArray(tool.options.mouseButtonMask)\n ) {\n options.mouseButtonMask = options.mouseButtonMask.concat(\n tool.options.mouseButtonMask\n );\n }\n\n // Set mode & options\n tool.mode = mode;\n tool.mergeOptions(options);\n\n // Call tool's hook for this event, if one exists\n if (tool[`${mode}Callback`]) {\n tool[`${mode}Callback`](element, options);\n }\n\n // Emit event indicating tool state change\n if (changeEvent) {\n const statusChangeEventData = {\n options,\n toolName,\n type: changeEvent,\n };\n\n triggerEvent(element, changeEvent, statusChangeEventData);\n }\n\n // Trigger Update\n // Todo: don't error out if image hasn't been loaded...\n // Cornerstone.updateImage(element);\n}\n\n/**\n * A helper/quick way to set a tool's mode for all canvases\n *\n * @private\n * @function setToolMode\n *\n * @param {string} mode\n * @param {string} changeEvent\n * @param {string} toolName\n * @param {(Object|number)} options\n * @returns {undefined}\n */\nfunction setToolMode(mode, changeEvent, toolName, options) {\n _trackGlobalToolModeChange(mode, toolName, options);\n store.state.enabledElements.forEach(element => {\n setToolModeForElement(mode, changeEvent, element, toolName, options);\n });\n}\n\n/**\n * Find tool's that conflict with the incoming tool's mouse/touch bindings and\n * resolve those conflicts.\n *\n * @private\n * @function _resolveInputConflicts\n *\n * @param {HTMLElement} element\n * @param {Object} tool\n * @param {(Object|number)} options\n * @param {(Array)} interactionTypes\n * @returns {undefined}\n */\nfunction _resolveInputConflicts(element, tool, options, interactionTypes) {\n // Iterate over the interaction types our tool supports.\n // For each one we intend to activate, check for potential conflicts\n // And resolve them\n tool.supportedInteractionTypes.forEach(interactionType => {\n if (\n interactionTypes === undefined ||\n interactionTypes.includes(interactionType)\n ) {\n const inputResolver = _inputResolvers[interactionType];\n\n if (inputResolver) {\n inputResolver(tool, element, options);\n } else {\n console.warn(\n `Unable to resolve input conflicts for type ${interactionType}`\n );\n }\n }\n });\n\n const activeToolsForElement = store.state.tools.filter(\n t =>\n t.element === element &&\n t.mode === 'active' &&\n t.supportedInteractionTypes.length > 0\n );\n\n activeToolsForElement.forEach(t => {\n let toolHasAnyActiveInteractionType = false;\n\n t.supportedInteractionTypes.forEach(interactionType => {\n if (t.options[`is${interactionType}Active`]) {\n toolHasAnyActiveInteractionType = true;\n }\n });\n\n if (!toolHasAnyActiveInteractionType) {\n console.info(`Setting tool ${t.name}'s to PASSIVE`);\n setToolPassiveForElement(element, t.name);\n }\n });\n}\n\n/**\n * Resolves conflicting active tools when activating a tool for mouse interaction\n * @private\n * @function _resolveMouseInputConflicts\n *\n * @param {Object} tool\n * @param {HTMLElement} element\n * @param {(Object|number)} options\n * @returns {undefined}\n */\nfunction _resolveMouseInputConflicts(tool, element, options) {\n const mouseButtonMask = _getNormalizedOptions(options).mouseButtonMask;\n const hasMouseButtonMask =\n Array.isArray(mouseButtonMask) && mouseButtonMask.length > 0;\n\n if (!hasMouseButtonMask) {\n return;\n }\n\n const activeToolWithMatchingMouseButtonMask = store.state.tools.find(\n t =>\n t.element === element &&\n t.mode === 'active' &&\n t.options.isMouseActive === true &&\n Array.isArray(t.options.mouseButtonMask) &&\n t.options.mouseButtonMask.some(v => mouseButtonMask.includes(v))\n );\n\n if (activeToolWithMatchingMouseButtonMask) {\n // Remove collissions\n activeToolWithMatchingMouseButtonMask.options.mouseButtonMask = activeToolWithMatchingMouseButtonMask.options.mouseButtonMask.filter(\n mask => !mouseButtonMask.includes(mask)\n );\n\n // If no remaining bindings, set inactive\n if (\n activeToolWithMatchingMouseButtonMask.options.mouseButtonMask.length === 0\n ) {\n activeToolWithMatchingMouseButtonMask.options.isMouseActive = false;\n }\n }\n}\n\n/**\n * Resolves conflicting active tools when activating a tool for touch interaction\n * @private\n * @function _resolveTouchInputConflicts\n *\n * @param {Object} tool\n * @param {HTMLElement} element\n * @param {Object} options\n * @returns {undefined}\n */\nfunction _resolveTouchInputConflicts(tool, element, options) {\n const activeTouchTool = store.state.tools.find(\n t =>\n t.element === element &&\n t.mode === 'active' &&\n t.options.isTouchActive === true\n );\n\n const activeMultiTouchToolWithOneTouchPointer = store.state.tools.find(\n t =>\n t.element === element &&\n t.mode === 'active' &&\n t.options.isMultiTouchActive === true &&\n t.configuration.touchPointers === 1\n );\n\n if (activeTouchTool) {\n console.info(\n `Setting tool ${activeTouchTool.name}'s isTouchActive to false`\n );\n activeTouchTool.options.isTouchActive = false;\n }\n if (activeMultiTouchToolWithOneTouchPointer) {\n console.info(\n `Setting tool ${\n activeMultiTouchToolWithOneTouchPointer.name\n }'s isTouchActive to false`\n );\n activeMultiTouchToolWithOneTouchPointer.options.isMultiTouchActive = false;\n }\n}\n\n/**\n * Resolves conflicting active tools when activating a tool for MultiTouch interaction\n * @private\n * @function _resolveMultiTouchInputConflicts\n *\n * @param {Object} tool\n * @param {HTMLElement} element\n * @param {Object} options\n * @returns {undefined}\n */\nfunction _resolveMultiTouchInputConflicts(tool, element, options) {\n const activeMultiTouchTool = store.state.tools.find(\n t =>\n t.element === element &&\n t.mode === 'active' &&\n t.options.isMultiTouchActive === true &&\n t.configuration.touchPointers === tool.configuration.touchPointers\n );\n\n let activeTouchTool;\n\n if (tool.configuration.touchPointers === 1) {\n activeTouchTool = store.state.tools.find(\n t =>\n t.element === element &&\n t.mode === 'active' &&\n t.options.isTouchActive === true\n );\n }\n\n if (activeMultiTouchTool) {\n console.info(\n `Setting tool ${activeMultiTouchTool.name}'s isMultiTouchActive to false`\n );\n activeMultiTouchTool.options.isMultiTouchActive = false;\n }\n\n if (activeTouchTool) {\n console.info(\n `Setting tool ${activeTouchTool.name}'s isTouchActive to false`\n );\n activeTouchTool.options.isTouchActive = false;\n }\n}\n\n/**\n * If the incoming tool isTouchActive, find any conflicting tools\n * and set their isTouchActive to false to avoid conflicts.\n *\n * @private\n * @function _resolveGenericInputConflicts\n *\n * @param {string} interactionType\n * @param {Object} tool\n * @param {HTMLElement} element\n * @param {(Object|number)} options\n * @returns {undefined}\n */\nfunction _resolveGenericInputConflicts(\n interactionType,\n tool,\n element,\n options\n) {\n const activeToolWithActiveInteractionType = store.state.tools.find(\n t =>\n t.element === element &&\n t.mode === 'active' &&\n t.options[`is${interactionType}Active`] === true\n );\n\n if (activeToolWithActiveInteractionType) {\n console.info(\n `Setting tool ${\n activeToolWithActiveInteractionType.name\n }'s is${interactionType}Active to false`\n );\n activeToolWithActiveInteractionType.options[\n `is${interactionType}Active`\n ] = false;\n }\n}\n\nfunction _trackGlobalToolModeChange(mode, toolName, options, interactionTypes) {\n if (!store.modules.globalConfiguration.state.globalToolSyncEnabled) {\n return;\n }\n\n // Update Tool History\n const historyEvent = {\n mode,\n args: [toolName, options],\n };\n\n if (interactionTypes) {\n historyEvent.push(interactionTypes);\n }\n\n store.state.globalToolChangeHistory.push(historyEvent);\n\n const arbitraryChangeHistoryLimit = 50;\n\n if (\n store.state.globalToolChangeHistory.length > arbitraryChangeHistoryLimit\n ) {\n store.state.globalToolChangeHistory.shift();\n }\n\n // Update ActiveBindings Array\n const globalTool = store.state.globalTools[toolName];\n\n if (mode === 'active') {\n let stringBindings = _determineStringBindings(\n toolName,\n options,\n interactionTypes\n );\n\n // Remove the incoming bindings from all global tools\n Object.keys(store.state.globalTools).forEach(key => {\n const tool = store.state.globalTools[key];\n\n tool.activeBindings = tool.activeBindings.filter(\n binding => !stringBindings.includes(binding)\n );\n });\n\n // @HACK: Clear mouse bindings\n if (stringBindings.some(binding => binding.includes('Mouse-DELETE'))) {\n globalTool.activeBindings = globalTool.activeBindings.filter(\n binding => !binding.includes('Mouse')\n );\n stringBindings = stringBindings.filter(\n binding => !binding.includes('Mouse')\n );\n }\n\n globalTool.activeBindings = globalTool.activeBindings.concat(\n stringBindings\n );\n } else {\n globalTool.activeBindings = [];\n }\n}\n\nfunction _determineStringBindings(toolName, options, interactionTypes) {\n if (interactionTypes === undefined && Array.isArray(options)) {\n interactionTypes = options;\n options = null;\n }\n\n const stringBindings = [];\n const globalTool = store.state.globalTools[toolName];\n\n if (globalTool) {\n const tool = new globalTool.tool(globalTool.configuration);\n\n tool.supportedInteractionTypes.forEach(interactionType => {\n if (\n interactionTypes === undefined ||\n interactionTypes.includes(interactionType)\n ) {\n if (interactionType === 'Mouse') {\n const mouseButtonMasks = _getNormalizedOptions(options)\n .mouseButtonMask;\n\n // Add or delete\n if (Array.isArray(mouseButtonMasks) && mouseButtonMasks.length > 0) {\n mouseButtonMasks.forEach(mask =>\n stringBindings.push(`${interactionType}-${mask}`)\n );\n } else if (\n Array.isArray(mouseButtonMasks) &&\n mouseButtonMasks.length === 0\n ) {\n stringBindings.push(`${interactionType}-DELETE`);\n }\n } else if (interactionType === 'MultiTouch') {\n stringBindings.push(\n `${interactionType}-${tool.configuration.touchPointers}`\n );\n } else {\n stringBindings.push(interactionType);\n }\n }\n });\n }\n\n return stringBindings;\n}\n\nconst _inputResolvers = {\n Mouse: _resolveMouseInputConflicts,\n MouseWheel: _resolveGenericInputConflicts.bind(this, 'MouseWheel'),\n Touch: _resolveTouchInputConflicts,\n TouchPinch: _resolveGenericInputConflicts.bind(this, 'TouchPinch'),\n TouchRotate: _resolveGenericInputConflicts.bind(this, 'TouchRotate'),\n DoubleTap: _resolveGenericInputConflicts.bind(this, 'DoubleTap'),\n MultiTouch: _resolveMultiTouchInputConflicts,\n};\n\nexport {\n setToolActive,\n setToolActiveForElement,\n setToolDisabled,\n setToolDisabledForElement,\n setToolEnabled,\n setToolEnabledForElement,\n setToolPassive,\n setToolPassiveForElement,\n};\n\nfunction _getNormalizedOptions(options) {\n // Is an object, but not an Array\n if (options === Object(options) && !Array.isArray(options)) {\n if (options.mouseButtonMask === 0 || options.mouseButtonMask === null) {\n options.mouseButtonMask = [];\n } else if (typeof options.mouseButtonMask === 'number') {\n const tempArray = [];\n\n tempArray.push(options.mouseButtonMask);\n options.mouseButtonMask = tempArray;\n }\n } else if (typeof options === 'number') {\n const tempArray = [];\n\n tempArray.push(options);\n options = {\n mouseButtonMask: options === 0 ? [] : tempArray,\n };\n } else if (options === null) {\n options = {\n mouseButtonMask: [],\n };\n } else {\n console.info(`No options provided when changing tool mode`);\n options = {};\n }\n\n return options;\n}\n","import {\n setToolDisabledForElement,\n setToolEnabledForElement,\n} from '../store/setToolMode.js';\n\n/**\n * If one attempts to change mode to 'passive', redirect the tool to 'disabled'.\n *\n * @param {HTMLElement} element The element on which the tool resides.\n * @returns {undefined}\n */\nfunction passiveCallback(element) {\n setToolDisabledForElement(element, this.name);\n}\n\n/**\n * If one attempts to change mode to 'active', redirect the tool to 'enabled'.\n *\n * @param {HTMLElement} element The element on which the tool resides.\n * @returns {undefined}\n */\nfunction activeCallback(element) {\n setToolEnabledForElement(element, this.name);\n}\n\n/**\n *\n * @mixin enabledOrDisabledBinaryTool - Redirect active/passive mode changes to enabled/disabled.\n * @memberof Mixins\n */\nexport default {\n passiveCallback,\n activeCallback,\n};\n","import activeOrDisabledBinaryTool from './activeOrDisabledBinaryTool.js';\nimport enabledOrDisabledBinaryTool from './enabledOrDisabledBinaryTool.js';\n\nexport default {\n activeOrDisabledBinaryTool,\n enabledOrDisabledBinaryTool,\n};\n","import {\n setToolDisabledForElement,\n setToolActiveForElement,\n} from '../store/setToolMode.js';\n\n/**\n * If one attempts to change mode to 'passive', redirect the tool to 'disabled'.\n *\n * @param {HTMLElement} element The element on which the tool resides.\n * @returns {undefined}\n */\nfunction passiveCallback(element) {\n setToolDisabledForElement(element, this.name);\n}\n\n/**\n * If one attempts to turn the tool 'enabled', redirect the tool to 'active'.\n *\n * @param {HTMLElement} element The element on which the tool resides.\n * @returns {undefined}\n */\nfunction enabledCallback(element) {\n setToolActiveForElement(element, this.name);\n}\n\n/**\n * @mixin activeOrDisabledBinaryTool - Redirect enabled/passive mode changes to active/disabled.\n * @memberof Mixins\n */\nexport default {\n passiveCallback,\n enabledCallback,\n};\n","import mixins from './../../mixins/index.js';\n\n/**\n * @typedef ToolConfiguration\n * @param {String} name\n * @param {object} strategies - Named strategy functions\n * @param {String} defaultStrategy - The name of the strategy to use by default\n * @param {Object} configuration\n * @param {String[]} mixins - A list of mixin names to apply to the tool\n */\n\n/**\n * @memberof Tools.Base\n * @classdesc BaseTool Class description\n * @property {String[]} supportedInteractionTypes - A string list of ways the tool can interact with the user\n */\nclass BaseTool {\n /**\n * Constructor description\n * @param {ToolConfiguration} [ToolConfiguration={}]\n */\n constructor({\n name,\n strategies,\n defaultStrategy,\n configuration,\n supportedInteractionTypes,\n mixins,\n } = {}) {\n /**\n * A unique, identifying tool name\n * @type {String}\n */\n this.name = name;\n\n /** @type {String} */\n this.mode = 'disabled';\n this.element = undefined;\n this.supportedInteractionTypes = supportedInteractionTypes || [];\n\n this.strategies = strategies || {};\n this.defaultStrategy =\n defaultStrategy || Object.keys(this.strategies)[0] || undefined;\n this.activeStrategy = this.defaultStrategy;\n\n // Options are set when a tool is added, during a \"mode\" change,\n // Or via a tool's option's setter\n this._options = {};\n // Configuration is set at tool initalization\n this._configuration = Object.assign({}, configuration);\n\n // True if tool has a custom cursor, causes the frame to render on every mouse move when the tool is active.\n this.hasCursor = false;\n\n // Apply mixins if mixinsArray is not empty.\n if (mixins && mixins.length) {\n this._applyMixins(mixins);\n }\n }\n\n //\n // CONFIGURATION\n //\n\n /**\n * Config...\n * @public\n * @type {Object}\n * @instance\n */\n static get configuration() {}\n\n get configuration() {\n return this._configuration;\n }\n\n set configuration(configuration) {\n this._configuration = configuration;\n }\n\n //\n // OPTIONS\n //\n\n /**\n * Options...\n * @readonly\n * @instance\n */\n get options() {\n return this._options;\n }\n\n /**\n * Merges provided options with existing options.\n *\n * @public\n * @instance\n * @param {Object} options - options object to merge with existing options.\n * @returns {undefined}\n */\n mergeOptions(options) {\n this._options = Object.assign({}, this._options, options);\n }\n\n /**\n * Clears the tools options.\n *\n * @public\n * @instance\n * @memberof Tools.Base.BaseTool\n * @returns {undefined}\n */\n clearOptions() {\n this._options = {};\n }\n\n /**\n * Apply the currently set/active strategy.\n *\n * @public\n * @instance\n * @method applyActiveStrategy\n * @memberof Tools.Base.BaseTool\n *\n * @param {*} evt The event that triggered the strategies application\n * @returns {*} strategies vary widely; check each specific strategy to find expected return value\n */\n applyActiveStrategy(evt) {\n return this.strategies[this.activeStrategy](evt, this.configuration);\n }\n\n /**\n * Iterates over registered mixins; any matching names in the provided `mixinsArray` will\n * be merged with this instance.\n *\n * @private\n * @method _applyMixins\n * @param {string[]} mixinsArray An array of mixin identifiers (strings).\n * @returns {undefined}\n */\n _applyMixins(mixinsArray) {\n for (let i = 0; i < mixinsArray.length; i++) {\n const mixin = mixins[`${mixinsArray[i]}`];\n\n if (typeof mixin === 'object') {\n Object.assign(this, mixin);\n } else {\n console.warn(`${this.name}: mixin ${mixins[i]} does not exist.`);\n }\n }\n }\n\n // ===================================================================\n // Virtual Methods - Have default behavior but may be overriden.\n // ===================================================================\n\n //\n // MOUSE\n //\n\n /**\n * Callback that takes priority if the tool is active, before `MOUSE_DOWN`\n * events are processed. Does nothing by default.\n *\n * @callback BaseTool~preMouseDownCallback\n * @param {CornerstoneTools.event:cornerstonetoolsmousedown} evt\n * @returns {boolean} consumedEvent - True if function consumed the event.\n */\n /**\n * Callback that takes priority if the tool is active, after `MOUSE_DOWN`\n * events are processed. Does nothing by default.\n *\n * @callback BaseTool~postMouseDownCallback\n * @param {CornerstoneTools.event:cornerstonetoolsmousedown} evt\n * @returns {boolean} consumedEvent - True if function consumed the event.\n */\n\n /**\n * Callback that is called if the tool is active, after `MOUSE_DOWN`\n * events are processed. Does nothing by default.\n *\n * @virtual\n * @param {type} evt\n * @returns {boolean} consumedEvent - True if function consumed the event.\n */\n /**\n * Example implementation:\n *\n * postMouseDownCallback(evt) {\n * return false;\n * }\n */\n\n /**\n * Callback that takes priority if the tool is active, before `TOUCH_START`\n * events are processed. Does nothing by default.\n *\n * @virtual\n * @param {type} evt\n * @returns {boolean} consumedEvent - True if function consumed the event.\n */\n /**\n * Example implementation:\n *\n * preTouchStartCallback(evt) {\n * return false;\n * }\n */\n\n /**\n * Callback that is called if the tool is active, after `TOUCH_START`\n * events are processed. Does nothing by default.\n *\n * @virtual\n * @param {type} evt\n * @returns {boolean} consumedEvent - True if function consumed the event.\n */\n /**\n * Example implementation:\n *\n * postTouchStartCallback(evt) {\n * return false;\n * }\n */\n}\n\nexport default BaseTool;\n","import external from '../externalModules.js';\n\n/**\n * Implements an imageId specific tool state management strategy. This means that\n * Measurements data is tied to a specific imageId and only visible for enabled elements\n * That are displaying that imageId.\n * @public\n * @constructor newImageIdSpecificToolStateManager\n * @memberof StateManagement\n *\n * @returns {Object} An imageIdSpecificToolStateManager instance.\n */\nfunction newImageIdSpecificToolStateManager() {\n let toolState = {};\n\n // Here we add tool state, this is done by tools as well\n // As modules that restore saved state\n\n function saveImageIdToolState(imageId) {\n return toolState[imageId];\n }\n\n function restoreImageIdToolState(imageId, imageIdToolState) {\n toolState[imageId] = imageIdToolState;\n }\n\n function saveToolState() {\n return toolState;\n }\n\n function restoreToolState(savedToolState) {\n toolState = savedToolState;\n }\n\n // Here we add tool state, this is done by tools as well\n // As modules that restore saved state\n function addImageIdSpecificToolState(element, toolType, data) {\n const enabledImage = external.cornerstone.getEnabledElement(element);\n // If we don't have any tool state for this imageId, add an empty object\n\n if (\n !enabledImage.image ||\n toolState.hasOwnProperty(enabledImage.image.imageId) === false\n ) {\n toolState[enabledImage.image.imageId] = {};\n }\n\n const imageIdToolState = toolState[enabledImage.image.imageId];\n\n // If we don't have tool state for this type of tool, add an empty object\n if (imageIdToolState.hasOwnProperty(toolType) === false) {\n imageIdToolState[toolType] = {\n data: [],\n };\n }\n\n const toolData = imageIdToolState[toolType];\n\n // Finally, add this new tool to the state\n toolData.data.push(data);\n }\n\n // Here you can get state - used by tools as well as modules\n // That save state persistently\n function getImageIdSpecificToolState(element, toolType) {\n const enabledImage = external.cornerstone.getEnabledElement(element);\n // If we don't have any tool state for this imageId, return undefined\n\n if (\n !enabledImage.image ||\n toolState.hasOwnProperty(enabledImage.image.imageId) === false\n ) {\n return;\n }\n\n const imageIdToolState = toolState[enabledImage.image.imageId];\n\n // If we don't have tool state for this type of tool, return undefined\n if (imageIdToolState.hasOwnProperty(toolType) === false) {\n return;\n }\n\n const toolData = imageIdToolState[toolType];\n\n return toolData;\n }\n\n // Clears all tool data from this toolStateManager.\n function clearImageIdSpecificToolStateManager(element) {\n const enabledImage = external.cornerstone.getEnabledElement(element);\n\n if (\n !enabledImage.image ||\n toolState.hasOwnProperty(enabledImage.image.imageId) === false\n ) {\n return;\n }\n\n delete toolState[enabledImage.image.imageId];\n }\n\n return {\n get: getImageIdSpecificToolState,\n add: addImageIdSpecificToolState,\n clear: clearImageIdSpecificToolStateManager,\n saveImageIdToolState,\n restoreImageIdToolState,\n saveToolState,\n restoreToolState,\n toolState,\n };\n}\n\n// A global imageIdSpecificToolStateManager - the most common case is to share state between all\n// Visible enabled images\nconst globalImageIdSpecificToolStateManager = newImageIdSpecificToolStateManager();\n\nexport {\n newImageIdSpecificToolStateManager,\n globalImageIdSpecificToolStateManager,\n};\n","import EVENTS from '../events.js';\nimport external from '../externalModules.js';\nimport { globalImageIdSpecificToolStateManager } from './imageIdSpecificStateManager.js';\nimport triggerEvent from '../util/triggerEvent.js';\n\n/**\n * Returns the toolstate for a specific element.\n * @public\n * @function getElementToolStateManager\n *\n * @param {HTMLElement} element The element.\n * @returns {Object} The toolState.\n */\nfunction getElementToolStateManager(element) {\n const enabledElement = external.cornerstone.getEnabledElement(element);\n // If the enabledImage has no toolStateManager, create a default one for it\n // NOTE: This makes state management element specific\n\n if (enabledElement.toolStateManager === undefined) {\n enabledElement.toolStateManager = globalImageIdSpecificToolStateManager;\n }\n\n return enabledElement.toolStateManager;\n}\n\n/**\n * Adds tool state to the toolStateManager, this is done by tools as well\n * as modules that restore saved state.\n * @public\n * @method addToolState\n *\n * @param {HTMLElement} element The element.\n * @param {string} toolType The toolType of the state.\n * @param {Object} measurementData The data to store in the state.\n * @returns {undefined}\n */\nfunction addToolState(element, toolType, measurementData) {\n const toolStateManager = getElementToolStateManager(element);\n\n toolStateManager.add(element, toolType, measurementData);\n\n const eventType = EVENTS.MEASUREMENT_ADDED;\n const eventData = {\n toolType,\n element,\n measurementData,\n };\n\n triggerEvent(element, eventType, eventData);\n}\n\n/**\n * Returns tool specific state of an element. Used by tools as well as modules\n * that save state persistently\n * @export\n * @public\n * @method\n * @name getToolState\n *\n * @param {HTMLElement} element The element.\n * @param {string} toolType The toolType of the state.\n * @returns {Object} The element's state for the given toolType.\n */\nfunction getToolState(element, toolType) {\n const toolStateManager = getElementToolStateManager(element);\n\n return toolStateManager.get(element, toolType);\n}\n\n/**\n * Removes specific tool state from the toolStateManager.\n * @public\n * @method removeToolState\n *\n * @param {HTMLElement} element The element.\n * @param {string} toolType The toolType of the state.\n * @param {Object} data The data to remove from the toolStateManager.\n * @returns {undefined}\n */\nfunction removeToolState(element, toolType, data) {\n const toolStateManager = getElementToolStateManager(element);\n const toolData = toolStateManager.get(element, toolType);\n // Find this tool data\n let indexOfData = -1;\n\n for (let i = 0; i < toolData.data.length; i++) {\n if (toolData.data[i] === data) {\n indexOfData = i;\n }\n }\n\n if (indexOfData !== -1) {\n toolData.data.splice(indexOfData, 1);\n\n const eventType = EVENTS.MEASUREMENT_REMOVED;\n const eventData = {\n toolType,\n element,\n measurementData: data,\n };\n\n triggerEvent(element, eventType, eventData);\n }\n}\n\n/**\n * Removes all toolState from the toolStateManager corresponding to\n * the toolType and element.\n * @public\n * @method clearToolState\n *\n * @param {HTMLElement} element The element.\n * @param {string} toolType The toolType of the state.\n * @returns {undefined}\n */\nfunction clearToolState(element, toolType) {\n const toolStateManager = getElementToolStateManager(element);\n const toolData = toolStateManager.get(element, toolType);\n\n // If any toolData actually exists, clear it\n if (toolData !== undefined) {\n toolData.data = [];\n }\n}\n\n/**\n * Sets the tool state manager for an element\n * @public\n * @method setElementToolStateManager\n *\n * @param {HTMLElement} element The element.\n * @param {Object} toolStateManager The toolStateManager.\n * @returns {undefined}\n */\nfunction setElementToolStateManager(element, toolStateManager) {\n const enabledElement = external.cornerstone.getEnabledElement(element);\n\n enabledElement.toolStateManager = toolStateManager;\n}\n\nexport {\n addToolState,\n getToolState,\n removeToolState,\n clearToolState,\n setElementToolStateManager,\n getElementToolStateManager,\n};\n","import external from '../externalModules.js';\n\n/**\n * Returns true if a point is enclosed within a bounding box.\n * @export @public @method\n * @name pointInsideBoundingBox\n *\n * @param {Object} handle The handle containing the boundingBox.\n * @param {Object} coords The coordinate to check.\n * @returns {boolean} True if the point is enclosed within the bounding box.\n */\nexport default function(handle, coords) {\n if (!handle.boundingBox) {\n return;\n }\n\n return external.cornerstoneMath.point.insideRect(coords, handle.boundingBox);\n}\n","import external from '../externalModules.js';\nimport pointInsideBoundingBox from '../util/pointInsideBoundingBox.js';\n\n/**\n * Returns the first handle found to be near the provided point. Handles to search can be an array of handles, an\n * object of named handles, or an object of named handles AND named arrays of handles.\n *\n * @public\n * @function getHandleNearImagePoint\n * @memberof Manipulators\n *\n * @param {*} element - Target enabledElement\n * @param {(Array|Object)} handles - An arry of handles, object with named handles, or object with named handles AND named arrays of handles\n * @param {Object} coords - The coordinates to measure from when determining distance from handles\n * @param {number} distanceThreshold - minimum distance handle needs to be from provided coords\n * @returns {Object} Handle\n */\nconst getHandleNearImagePoint = function(\n element,\n handles,\n coords,\n distanceThreshold\n) {\n let nearbyHandle;\n\n if (!handles) {\n return;\n }\n\n if (Array.isArray(handles)) {\n const handleKeys = Object.keys(handles);\n\n for (let i = 0; i < handleKeys.length; i++) {\n const key = handleKeys[i];\n const handle = handles[key];\n\n if (\n // Not a true handle\n !handle.hasOwnProperty('x') ||\n !handle.hasOwnProperty('y')\n ) {\n continue;\n }\n\n if (_isHandleNearImagePoint(handle, element, coords, distanceThreshold)) {\n nearbyHandle = handle;\n break;\n }\n }\n } else if (typeof handles === 'object') {\n const handleKeys = Object.keys(handles);\n\n for (let i = 0; i < handleKeys.length; i++) {\n const handleName = handleKeys[i];\n\n if (Array.isArray(handles[handleName])) {\n nearbyHandle = getHandleNearImagePoint(\n element,\n handles[handleName],\n coords,\n distanceThreshold\n );\n if (nearbyHandle) {\n break;\n }\n } else {\n const handle = handles[handleName];\n\n if (\n _isHandleNearImagePoint(handle, element, coords, distanceThreshold)\n ) {\n nearbyHandle = handle;\n break;\n }\n }\n }\n }\n\n return nearbyHandle;\n};\n\n/**\n * Determines if the handle is less than the provided distance from the provided coordinates\n * @private\n * @function _isHandleNearImagePoint\n *\n * @param {*} handle\n * @param {*} element\n * @param {*} coords\n * @param {*} distanceThreshold\n * @returns {boolean} true if handles is near image point\n */\nconst _isHandleNearImagePoint = function(\n handle,\n element,\n coords,\n distanceThreshold\n) {\n if (handle.hasOwnProperty('pointNearHandle')) {\n if (handle.pointNearHandle(element, handle, coords)) {\n return true;\n }\n } else if (handle.hasBoundingBox === true) {\n if (pointInsideBoundingBox(handle, coords)) {\n return true;\n }\n } else {\n const handleCanvas = external.cornerstone.pixelToCanvas(element, handle);\n const distance = external.cornerstoneMath.point.distance(\n handleCanvas,\n coords\n );\n\n if (distance <= distanceThreshold) {\n return true;\n }\n }\n\n return false;\n};\n\nexport default getHandleNearImagePoint;\n","import getHandleNearImagePoint from './getHandleNearImagePoint.js';\n\n/**\n * Update the active handle\n * @public\n * @function handleActivator\n * @memberof Manipulators\n *\n * @param {*} element\n * @param {*} handles\n * @param {*} canvasPoint\n * @param {*} distanceThreshold\n * @returns {Boolean} - True if a handle was activated\n */\nexport default function(element, handles, canvasPoint, distanceThreshold) {\n if (!distanceThreshold) {\n distanceThreshold = 6;\n }\n\n const activeHandle = _getActiveHandle(handles);\n const nearbyHandle = getHandleNearImagePoint(\n element,\n handles,\n canvasPoint,\n distanceThreshold\n );\n\n if (activeHandle !== nearbyHandle) {\n if (nearbyHandle !== undefined) {\n nearbyHandle.active = true;\n }\n\n if (activeHandle !== undefined) {\n activeHandle.active = false;\n }\n\n return true;\n }\n\n return false;\n}\n\n/**\n *\n * @private\n *\n * @param {*} handles\n * @returns {Object} - Activated Handle\n */\nfunction _getActiveHandle(handles) {\n let activeHandle;\n\n Object.keys(handles).forEach(function(name) {\n const handle = handles[name];\n\n if (handle.active === true) {\n activeHandle = handle;\n\n return;\n }\n });\n\n return activeHandle;\n}\n","import external from '../externalModules.js';\n\n/**\n * Determine if a handle is outside the bounds of the rendered image.\n * @public\n * @function anyHandlesOutsideImage\n * @memberof Manipulators\n *\n * @param {*} renderData - Cornerstone Tool's event detail\n * @param {Object} handles - An object containing named handles\n * @returns {Boolean} - True if the handle was placed outside the image\n */\nexport default function(renderData, handles) {\n const image = renderData.image;\n const imageRect = {\n left: 0,\n top: 0,\n width: image.width,\n height: image.height,\n };\n\n let handleOutsideImage = false;\n\n Object.keys(handles).forEach(function(name) {\n const handle = handles[name];\n\n if (handle.allowedOutsideImage === true) {\n return;\n }\n\n if (\n external.cornerstoneMath.point.insideRect(handle, imageRect) === false\n ) {\n handleOutsideImage = true;\n }\n });\n\n return handleOutsideImage;\n}\n","/**\n * Clips a value to an upper and lower bound.\n * @export @public @method\n * @name clip\n *\n * @param {number} val The value to clip.\n * @param {number} low The lower bound.\n * @param {number} high The upper bound.\n * @returns {number} The clipped value.\n */\nexport default function clip(val, low, high) {\n return Math.min(Math.max(low, val), high);\n}\n\n/**\n * Clips a value within a box.\n * @export @public @method\n * @name clipToBox\n *\n * @param {Object} point The point to clip\n * @param {Object} box The bounding box to clip to.\n * @returns {Object} The clipped point.\n */\nexport function clipToBox(point, box) {\n // Clip an {x, y} point to a box of size {width, height}\n point.x = clip(point.x, 0, box.width);\n point.y = clip(point.y, 0, box.height);\n}\n","import EVENTS from '../events.js';\nimport external from '../externalModules.js';\nimport anyHandlesOutsideImage from './anyHandlesOutsideImage.js';\nimport { removeToolState } from '../stateManagement/toolState.js';\nimport triggerEvent from '../util/triggerEvent.js';\nimport { clipToBox } from '../util/clip.js';\nimport { state } from './../store/index.js';\n\nconst _dragEvents = {\n mouse: [EVENTS.MOUSE_DRAG],\n touch: [EVENTS.TOUCH_DRAG],\n};\n\nconst _upOrEndEvents = {\n mouse: [EVENTS.MOUSE_UP, EVENTS.MOUSE_CLICK],\n touch: [\n EVENTS.TOUCH_END,\n EVENTS.TOUCH_DRAG_END,\n EVENTS.TOUCH_PINCH,\n EVENTS.TOUCH_PRESS,\n EVENTS.TAP,\n ],\n};\n\n/**\n * Manipulator to move all provided handles at the same time\n * @public\n * @function moveAllHandles\n * @memberof Manipulators\n *\n * @param {*} evtDetail\n * @param {*} evtDetail.element\n * @param {String} toolName\n * @param {*} annotation\n * @param {*} [handle=null] - not needed by moveAllHandles, but keeps call signature the same as `moveHandle`\n * @param {Object} [options={}]\n * @param {Boolean} [options.deleteIfHandleOutsideImage]\n * @param {function} [options.doneMovingCallback]\n * @param {Boolean} [options.preventHandleOutsideImage]\n * @param {string} [interactionType=mouse]\n * @returns {undefined}\n */\nexport default function(\n { element },\n toolName,\n annotation,\n handle = null,\n options = {},\n interactionType = 'mouse'\n) {\n // Use global defaults, unless overidden by provided options\n options = Object.assign(\n {\n deleteIfHandleOutsideImage: state.deleteIfHandleOutsideImage,\n preventHandleOutsideImage: state.preventHandleOutsideImage,\n },\n options\n );\n\n const dragHandler = _dragHandler.bind(this, toolName, annotation, options);\n // So we don't need to inline the entire `upOrEndHandler` function\n const upOrEndHandler = evt => {\n _upOrEndHandler(\n toolName,\n annotation,\n options,\n interactionType,\n {\n dragHandler,\n upOrEndHandler,\n },\n evt\n );\n };\n\n annotation.active = true;\n state.isToolLocked = true;\n\n // Add Event Listeners\n _dragEvents[interactionType].forEach(eventType => {\n element.addEventListener(eventType, dragHandler);\n });\n _upOrEndEvents[interactionType].forEach(eventType => {\n element.addEventListener(eventType, upOrEndHandler);\n });\n}\n\nfunction _dragHandler(toolName, annotation, options = {}, evt) {\n const { element, image } = evt.detail;\n const { x, y } = evt.detail.deltaPoints.image;\n\n annotation.active = true;\n annotation.invalidated = true;\n\n const handleKeys = Object.keys(annotation.handles);\n\n for (let i = 0; i < handleKeys.length; i++) {\n const key = handleKeys[i];\n const handle = annotation.handles[key];\n\n if (\n // Don't move this part of the annotation\n handle.movesIndependently === true ||\n // Not a true handle\n !handle.hasOwnProperty('x') ||\n !handle.hasOwnProperty('y')\n ) {\n continue;\n }\n\n handle.x += x;\n handle.y += y;\n\n if (options.preventHandleOutsideImage) {\n clipToBox(handle, image);\n }\n }\n\n external.cornerstone.updateImage(element);\n\n const eventType = EVENTS.MEASUREMENT_MODIFIED;\n const modifiedEventData = {\n toolName,\n element,\n measurementData: annotation,\n };\n\n triggerEvent(element, eventType, modifiedEventData);\n\n evt.preventDefault();\n evt.stopPropagation();\n}\n\nfunction _upOrEndHandler(\n toolName,\n annotation,\n options = {},\n interactionType,\n { dragHandler, upOrEndHandler },\n evt\n) {\n const eventData = evt.detail;\n const element = evt.detail.element;\n\n annotation.active = false;\n annotation.invalidated = true;\n state.isToolLocked = false;\n\n // Remove Event Listeners\n _dragEvents[interactionType].forEach(eventType => {\n element.removeEventListener(eventType, dragHandler);\n });\n _upOrEndEvents[interactionType].forEach(eventType => {\n element.removeEventListener(eventType, upOrEndHandler);\n });\n\n // If any handle is outside the image, delete the tool data\n if (\n options.deleteIfHandleOutsideImage &&\n anyHandlesOutsideImage(eventData, annotation.handles)\n ) {\n removeToolState(element, toolName, annotation);\n }\n\n if (typeof options.doneMovingCallback === 'function') {\n options.doneMovingCallback();\n }\n\n external.cornerstone.updateImage(element);\n}\n","import EVENTS from '../events.js';\nimport external from '../externalModules.js';\nimport anyHandlesOutsideImage from './anyHandlesOutsideImage.js';\nimport { removeToolState } from '../stateManagement/toolState.js';\nimport triggerEvent from '../util/triggerEvent.js';\nimport { clipToBox } from '../util/clip.js';\nimport { state } from './../store/index.js';\n\nconst runAnimation = {\n value: false,\n};\n\nconst _dragEvents = {\n mouse: [EVENTS.MOUSE_DRAG],\n touch: [EVENTS.TOUCH_DRAG],\n};\n\nconst _upOrEndEvents = {\n mouse: [EVENTS.MOUSE_UP, EVENTS.MOUSE_CLICK],\n touch: [\n EVENTS.TOUCH_END,\n EVENTS.TOUCH_DRAG_END,\n EVENTS.TOUCH_PINCH,\n EVENTS.TOUCH_PRESS,\n EVENTS.TAP,\n ],\n};\n\n/**\n * Move the provided handle\n *\n * @public\n * @method moveHandle\n * @memberof Manipulators\n *\n * @param {*} evtDetail\n * @param {*} toolName\n * @param {*} annotation\n * @param {*} handle\n * @param {*} [options={}]\n * @param {Boolean} [options.deleteIfHandleOutsideImage]\n * @param {function} [options.doneMovingCallback]\n * @param {Boolean} [options.preventHandleOutsideImage]\n * @param {*} [interactionType=mouse]\n * @returns {undefined}\n */\nexport default function(\n evtDetail,\n toolName,\n annotation,\n handle,\n options = {},\n interactionType = 'mouse'\n) {\n // Use global defaults, unless overidden by provided options\n options = Object.assign(\n {\n deleteIfHandleOutsideImage: state.deleteIfHandleOutsideImage,\n preventHandleOutsideImage: state.preventHandleOutsideImage,\n },\n options\n );\n\n const element = evtDetail.element;\n const dragHandler = _dragHandler.bind(\n this,\n toolName,\n annotation,\n handle,\n options,\n interactionType\n );\n // So we don't need to inline the entire `upOrEndHandler` function\n const upOrEndHandler = evt => {\n _upOrEndHandler(\n toolName,\n evtDetail,\n annotation,\n handle,\n options,\n interactionType,\n {\n dragHandler,\n upOrEndHandler,\n },\n evt\n );\n };\n\n handle.active = true;\n annotation.active = true;\n state.isToolLocked = true;\n\n // Add Event Listeners\n _dragEvents[interactionType].forEach(eventType => {\n element.addEventListener(eventType, dragHandler);\n });\n _upOrEndEvents[interactionType].forEach(eventType => {\n element.addEventListener(eventType, upOrEndHandler);\n });\n\n // ==========================\n // ======== TOUCH ==========\n // ==========================\n if (interactionType === 'touch') {\n runAnimation.value = true;\n const enabledElement = external.cornerstone.getEnabledElement(element);\n\n // Average pixel width of index finger is 45-57 pixels\n // https://www.smashingmagazine.com/2012/02/finger-friendly-design-ideal-mobile-touchscreen-target-sizes/\n const fingerDistance = -57;\n\n const aboveFinger = {\n x: evtDetail.currentPoints.page.x,\n y: evtDetail.currentPoints.page.y + fingerDistance,\n };\n\n const targetLocation = external.cornerstone.pageToPixel(\n element,\n aboveFinger.x,\n aboveFinger.y\n );\n\n _animate(handle, runAnimation, enabledElement, targetLocation);\n }\n}\n\nfunction _dragHandler(\n toolName,\n annotation,\n handle,\n options,\n interactionType,\n evt\n) {\n const { image, currentPoints, element } = evt.detail;\n const page = currentPoints.page;\n const fingerOffset = -57;\n const targetLocation = external.cornerstone.pageToPixel(\n element,\n page.x,\n interactionType === 'touch' ? page.y + fingerOffset : page.y\n );\n\n runAnimation.value = false;\n handle.active = true;\n handle.hasMoved = true;\n handle.x = targetLocation.x;\n handle.y = targetLocation.y;\n // TODO: A way to not flip this for textboxes on annotations\n annotation.invalidated = true;\n\n if (options.preventHandleOutsideImage) {\n clipToBox(handle, image);\n }\n\n external.cornerstone.updateImage(element);\n\n const eventType = EVENTS.MEASUREMENT_MODIFIED;\n const modifiedEventData = {\n toolName,\n element,\n measurementData: annotation,\n };\n\n triggerEvent(element, eventType, modifiedEventData);\n}\n\nfunction _upOrEndHandler(\n toolName,\n evtDetail,\n annotation,\n handle,\n options = {},\n interactionType,\n { dragHandler, upOrEndHandler },\n evt\n) {\n const image = evtDetail.currentPoints.image;\n const element = evt.detail.element;\n\n handle.active = false;\n annotation.active = false;\n // TODO: A way to not flip this for textboxes on annotations\n annotation.invalidated = true;\n state.isToolLocked = false;\n runAnimation.value = false;\n\n // Remove Event Listeners\n _dragEvents[interactionType].forEach(eventType => {\n element.removeEventListener(eventType, dragHandler);\n });\n _upOrEndEvents[interactionType].forEach(eventType => {\n element.removeEventListener(eventType, upOrEndHandler);\n });\n\n // If any handle is outside the image, delete the tool data\n if (\n options.deleteIfHandleOutsideImage &&\n anyHandlesOutsideImage(evtDetail, annotation.handles)\n ) {\n removeToolState(element, toolName, annotation);\n }\n\n // TODO: What dark magic makes us want to handle TOUCH_PRESS differently?\n if (evt.type === EVENTS.TOUCH_PRESS) {\n evt.detail.handlePressed = annotation;\n handle.x = image.x; // Original Event\n handle.y = image.y;\n }\n\n if (typeof options.doneMovingCallback === 'function') {\n options.doneMovingCallback();\n }\n\n external.cornerstone.updateImage(element);\n}\n\n/**\n * Animates the provided handle using `requestAnimationFrame`\n * @private\n * @method _animate\n *\n * @param {*} handle\n * @param {*} runAnimation\n * @param {*} enabledElement\n * @param {*} targetLocation\n * @returns {undefined}\n */\nfunction _animate(handle, runAnimation, enabledElement, targetLocation) {\n if (!runAnimation.value) {\n return;\n }\n\n // Pixels / second\n const distanceRemaining = Math.abs(handle.y - targetLocation.y);\n const linearDistEachFrame = distanceRemaining / 10;\n\n if (distanceRemaining < 1) {\n handle.y = targetLocation.y;\n runAnimation.value = false;\n\n return;\n }\n\n if (handle.y > targetLocation.y) {\n handle.y -= linearDistEachFrame;\n } else if (handle.y < targetLocation.y) {\n handle.y += linearDistEachFrame;\n }\n\n // Update the image\n external.cornerstone.updateImage(enabledElement.element);\n\n // Request a new frame\n external.cornerstone.requestAnimationFrame(function() {\n _animate(handle, runAnimation, enabledElement, targetLocation);\n });\n}\n","import EVENTS from '../events.js';\nimport external from '../externalModules.js';\nimport anyHandlesOutsideImage from './anyHandlesOutsideImage.js';\nimport { removeToolState } from '../stateManagement/toolState.js';\nimport triggerEvent from '../util/triggerEvent.js';\nimport { clipToBox } from '../util/clip.js';\nimport { state } from './../store/index.js';\n\nconst _moveEvents = {\n mouse: [EVENTS.MOUSE_MOVE, EVENTS.MOUSE_DRAG],\n touch: [EVENTS.TOUCH_DRAG],\n};\n\nconst _moveEndEvents = {\n mouse: [EVENTS.MOUSE_UP, EVENTS.MOUSE_CLICK],\n touch: [EVENTS.TOUCH_END, EVENTS.TOUCH_PINCH, EVENTS.TAP],\n};\n\n/**\n * Move a new handle\n * @public\n * @method moveNewHandle\n * @memberof Manipulators\n *\n * @param {*} evtDetail\n * @param {*} toolName\n * @param {*} annotation\n * @param {*} handle\n * @param {*} [options={}]\n * @param {Boolean} [options.deleteIfHandleOutsideImage]\n * @param {function} [options.doneMovingCallback]\n * @param {Boolean} [options.preventHandleOutsideImage]\n * @param {*} [interactionType=mouse]\n * @returns {undefined}\n */\nexport default function(\n evtDetail,\n toolName,\n annotation,\n handle,\n options,\n interactionType = 'mouse'\n) {\n // Use global defaults, unless overidden by provided options\n options = Object.assign(\n {\n deleteIfHandleOutsideImage: state.deleteIfHandleOutsideImage,\n preventHandleOutsideImage: state.preventHandleOutsideImage,\n },\n options\n );\n\n const element = evtDetail.element;\n\n annotation.active = true;\n handle.active = true;\n state.isToolLocked = true;\n\n const moveHandler = _moveHandler.bind(\n this,\n toolName,\n annotation,\n handle,\n options,\n interactionType\n );\n // So we don't need to inline the entire `moveEndEventHandler` function\n const moveEndHandler = evt => {\n _moveEndHandler(\n toolName,\n annotation,\n handle,\n options,\n interactionType,\n {\n moveHandler,\n moveEndHandler,\n },\n evt\n );\n };\n\n // Add event listeners\n _moveEvents[interactionType].forEach(eventType => {\n element.addEventListener(eventType, moveHandler);\n });\n _moveEndEvents[interactionType].forEach(eventType => {\n element.addEventListener(eventType, moveEndHandler);\n });\n element.addEventListener(EVENTS.TOUCH_START, _stopImmediatePropagation);\n}\n\nfunction _moveHandler(\n toolName,\n annotation,\n handle,\n options,\n interactionType,\n evt\n) {\n const { currentPoints, image, element } = evt.detail;\n const page = currentPoints.page;\n const fingerOffset = -57;\n const targetLocation = external.cornerstone.pageToPixel(\n element,\n interactionType === 'touch' ? page.x + fingerOffset : page.x,\n interactionType === 'touch' ? page.y + fingerOffset : page.y\n );\n\n annotation.invalidated = true;\n handle.active = true;\n handle.x = targetLocation.x;\n handle.y = targetLocation.y;\n\n if (options && options.preventHandleOutsideImage) {\n clipToBox(handle, image);\n }\n\n external.cornerstone.updateImage(element);\n\n const eventType = EVENTS.MEASUREMENT_MODIFIED;\n const modifiedEventData = {\n toolName,\n element,\n measurementData: annotation,\n };\n\n triggerEvent(element, eventType, modifiedEventData);\n}\n\nfunction _moveEndHandler(\n toolName,\n annotation,\n handle,\n options,\n interactionType,\n { moveHandler, moveEndHandler },\n evt\n) {\n const { element, currentPoints } = evt.detail;\n const page = currentPoints.page;\n const fingerOffset = -57;\n const targetLocation = external.cornerstone.pageToPixel(\n element,\n interactionType === 'touch' ? page.x + fingerOffset : page.x,\n interactionType === 'touch' ? page.y + fingerOffset : page.y\n );\n\n // \"Release\" the handle\n annotation.active = false;\n annotation.invalidated = true;\n handle.active = false;\n handle.x = targetLocation.x;\n handle.y = targetLocation.y;\n state.isToolLocked = false;\n\n // Remove event listeners\n _moveEvents[interactionType].forEach(eventType => {\n element.removeEventListener(eventType, moveHandler);\n });\n _moveEndEvents[interactionType].forEach(eventType => {\n element.removeEventListener(eventType, moveEndHandler);\n });\n element.removeEventListener(EVENTS.TOUCH_START, _stopImmediatePropagation);\n\n // TODO: WHY?\n // Why would a Touch_Pinch or Touch_Press be associated with a new handle?\n if (evt.type === EVENTS.TOUCH_PINCH || evt.type === EVENTS.TOUCH_PRESS) {\n handle.active = false;\n external.cornerstone.updateImage(element);\n if (typeof options.doneMovingCallback === 'function') {\n options.doneMovingCallback();\n }\n\n return;\n }\n\n if (options.preventHandleOutsideImage) {\n clipToBox(handle, evt.detail.image);\n }\n\n // If any handle is outside the image, delete the tool data\n if (\n options.deleteIfHandleOutsideImage &&\n anyHandlesOutsideImage(evt.detail, annotation.handles)\n ) {\n removeToolState(element, toolName, annotation);\n }\n\n if (typeof options.doneMovingCallback === 'function') {\n options.doneMovingCallback();\n }\n\n // Update Image\n external.cornerstone.updateImage(element);\n}\n\n/**\n * Stop the CornerstoneToolsTouchStart event from\n * Becoming a CornerstoneToolsTouchStartActive event when\n * MoveNewHandle ends\n *\n * @private\n * @function _stopImmediatePropagation\n *\n * @param {*} evt\n * @returns {Boolean} false\n */\nfunction _stopImmediatePropagation(evt) {\n evt.stopImmediatePropagation();\n\n return false;\n}\n","import { state } from '../store/index.js';\nimport getHandleNearImagePoint from '../manipulators/getHandleNearImagePoint.js';\nimport { moveHandle, moveAllHandles } from './../manipulators/index.js';\n\n// TODO this should just be in manipulators? They are just manipulator wrappers anyway.\n\n/**\n * Moves a handle near the image point.\n * @public\n * @function moveHandleNearImagePoint\n * @memberof Util\n *\n * @param {Event} evt The event.\n * @param {*} tool The tool\n * @param {Object} toolData The toolData that corresponds to the handle.\n * @param {Object} handle The handle to be moved.\n * @param {string} interactionType\n * @returns {undefined}\n */\nconst moveHandleNearImagePoint = function(\n evt,\n tool,\n toolData,\n handle,\n interactionType\n) {\n toolData.active = true;\n state.isToolLocked = true;\n\n moveHandle(\n evt.detail,\n tool.name,\n toolData,\n handle,\n tool.options,\n interactionType\n );\n\n evt.stopImmediatePropagation();\n evt.stopPropagation();\n evt.preventDefault();\n\n return;\n};\n\n/**\n * Finds the handle near the image point and its corresponding data.\n *\n * @public\n * @function findHandleDataNearImagePoint\n * @memberof Util\n *\n * @param {HTMLElement} element The elment.\n * @param {Object} toolState The state of the tool.\n * @param {string} toolName The name of the tool the handle corrosponds to.\n * @param {Object} coords The coordinates that need to be checked.\n * @param {String} [interactionType=mouse]\n * @returns {*}\n */\nconst findHandleDataNearImagePoint = function(\n element,\n toolState,\n toolName,\n coords,\n interactionType = 'mouse'\n) {\n for (let i = 0; i < toolState.data.length; i++) {\n const data = toolState.data[i];\n const handle = getHandleNearImagePoint(\n element,\n data.handles,\n coords,\n interactionType === 'mouse' ? state.clickProximity : state.touchProximity\n );\n\n if (handle) {\n return {\n handle,\n data,\n };\n }\n }\n};\n\n/**\n * Moves an entire annotation near the click.\n *\n * @public\n * @function moveAnnotation\n * @memberof Util\n *\n * @param {Event} evt The event.\n * @param {Object} tool The tool that the annotation belongs to.\n * @param {string} tool.name\n * @param {Object} [tool.options={}]\n * @param {Boolean} [tool.options.preventHandleOutsideImage]\n * @param {Boolean} [tool.options.deleteIfHandleOutsideImage]\n * @param {Object} annotation The toolData that corresponds to the annotation.\n * @param {String} [interactionType=mouse]\n * @returns {undefined}\n */\nconst moveAnnotation = function(\n evt,\n tool,\n annotation,\n interactionType = 'mouse'\n) {\n const toolOptions = Object.assign(\n {},\n {\n doneMovingCallback: () => {\n annotation.active = false;\n state.isToolLocked = false;\n },\n },\n tool.options\n );\n\n annotation.active = true;\n state.isToolLocked = true;\n\n moveAllHandles(\n evt.detail,\n tool.name,\n annotation,\n null,\n toolOptions,\n interactionType\n );\n\n evt.stopImmediatePropagation();\n evt.stopPropagation();\n evt.preventDefault();\n\n return;\n};\n\nexport {\n moveHandleNearImagePoint,\n findHandleDataNearImagePoint,\n moveAnnotation,\n};\n","import BaseTool from './BaseTool.js';\nimport { getToolState } from './../../stateManagement/toolState.js';\nimport handleActivator from './../../manipulators/handleActivator.js';\nimport {\n moveHandleNearImagePoint,\n moveAnnotation,\n} from './../../util/findAndMoveHelpers.js';\n\n/**\n * @memberof Tools.Base\n * @classdesc Abstract class for tools which create and display annotations on the\n * cornerstone canvas.\n * @extends Tools.Base.BaseTool\n */\nclass BaseAnnotationTool extends BaseTool {\n constructor({\n name,\n strategies,\n defaultStrategy,\n configuration,\n supportedInteractionTypes,\n mixins,\n }) {\n super({\n name,\n strategies,\n defaultStrategy,\n configuration,\n supportedInteractionTypes,\n mixins,\n });\n }\n\n // ===================================================================\n // Abstract Methods - Must be implemented.\n // ===================================================================\n\n /**\n * Creates a new annotation.\n *\n * @method createNewMeasurement\n * @memberof Tools.Base.BaseAnnotationTool\n *\n * @param {type} evt description\n * @returns {type} description\n */\n createNewMeasurement(evt) {\n throw new Error(\n `Method createNewMeasurement not implemented for ${this.name}.`\n );\n }\n\n /**\n *\n * Returns true if the given coords are need the tool.\n *\n * @method pointNearTool\n * @memberof Tools.Base.BaseAnnotationTool\n *\n * @param {*} element\n * @param {*} data\n * @param {*} coords\n * @param {string} [interactionType=mouse]\n * @returns {boolean} If the point is near the tool\n */\n pointNearTool(element, data, coords, interactionType = 'mouse') {\n throw new Error(`Method pointNearTool not implemented for ${this.name}.`);\n }\n\n /**\n * Returns the distance in px from the given coords to the closest handle of the annotation.\n *\n * @method distanceFromPoint\n * @memberof Tools.Base.BaseAnnotationTool\n *\n * @param {*} element\n * @param {*} data\n * @param {*} coords\n * @returns {number} - the distance in px from the provided coordinates to the\n * closest rendered portion of the annotation. -1 if the distance cannot be\n * calculated.\n */\n distanceFromPoint(element, data, coords) {\n throw new Error(\n `Method distanceFromPoint not implemented for ${this.name}.`\n );\n }\n\n /**\n * Used to redraw the tool's annotation data per render\n *\n * @abstract\n * @param {*} evt\n */\n renderToolData(evt) {\n throw new Error(`renderToolData not implemented for ${this.name}.`);\n }\n\n // ===================================================================\n // Virtual Methods - Have default behavior but may be overriden.\n // ===================================================================\n\n /**\n * Event handler for MOUSE_MOVE event.\n *\n * @abstract\n * @event\n * @param {Object} evt - The event.\n */\n mouseMoveCallback(evt) {\n const { element, currentPoints } = evt.detail;\n const coords = currentPoints.canvas;\n const toolState = getToolState(element, this.name);\n\n let imageNeedsUpdate = false;\n\n for (let d = 0; d < toolState.data.length; d++) {\n const data = toolState.data[d];\n\n // Hovering a handle?\n if (handleActivator(element, data.handles, coords) === true) {\n imageNeedsUpdate = true;\n }\n\n // Tool data's 'active' does not match coordinates\n // TODO: can't we just do an if/else and save on a pointNearTool check?\n const nearToolAndNotMarkedActive =\n this.pointNearTool(element, data, coords) && !data.active;\n const notNearToolAndMarkedActive =\n !this.pointNearTool(element, data, coords) && data.active;\n\n if (nearToolAndNotMarkedActive || notNearToolAndMarkedActive) {\n data.active = !data.active;\n imageNeedsUpdate = true;\n }\n }\n\n return imageNeedsUpdate;\n }\n\n /**\n * Custom callback for when a handle is selected.\n * @method handleSelectedCallback\n * @memberof Tools.Base.BaseAnnotationTool\n *\n * @param {*} evt -\n * @param {*} toolData -\n * @param {*} handle - The selected handle.\n * @param {String} interactionType -\n * @returns {undefined}\n */\n handleSelectedCallback(evt, toolData, handle, interactionType = 'mouse') {\n moveHandleNearImagePoint(evt, this, toolData, handle, interactionType);\n }\n\n /**\n * Custom callback for when a tool is selected.\n *\n * @method toolSelectedCallback\n * @memberof Tools.Base.BaseAnnotationTool\n *\n * @param {*} evt\n * @param {*} annotation\n * @param {string} [interactionType=mouse]\n * @returns {undefined}\n */\n toolSelectedCallback(evt, annotation, interactionType = 'mouse') {\n moveAnnotation(evt, this, annotation, interactionType);\n }\n}\n\nexport default BaseAnnotationTool;\n","let defaultWidth = 1,\n activeWidth = 2;\n\nfunction setToolWidth(width) {\n defaultWidth = width;\n}\n\nfunction getToolWidth() {\n return defaultWidth;\n}\n\nfunction setActiveWidth(width) {\n activeWidth = width;\n}\n\nfunction getActiveWidth() {\n return activeWidth;\n}\n\nconst toolStyle = {\n setToolWidth,\n getToolWidth,\n setActiveWidth,\n getActiveWidth,\n};\n\nexport default toolStyle;\n","let defaultColor = 'white',\n activeColor = 'greenyellow',\n fillColor = 'transparent';\n\nfunction setFillColor(color) {\n fillColor = color;\n}\n\nfunction getFillColor() {\n return fillColor;\n}\n\nfunction setToolColor(color) {\n defaultColor = color;\n}\n\nfunction getToolColor() {\n return defaultColor;\n}\n\nfunction setActiveColor(color) {\n activeColor = color;\n}\n\nfunction getActiveColor() {\n return activeColor;\n}\n\nfunction getColorIfActive(data) {\n if (data.color) {\n return data.color;\n }\n\n return data.active ? activeColor : defaultColor;\n}\n\nconst toolColors = {\n setFillColor,\n getFillColor,\n setToolColor,\n getToolColor,\n setActiveColor,\n getActiveColor,\n getColorIfActive,\n};\n\nexport default toolColors;\n","/**\n * This function manages the {@link https://www.w3.org/TR/2dcontext/#the-canvas-state|save/restore}\n * pattern for working in a new context state stack. The parameter `fn` is passed the `context` and can\n * execute any API calls in a clean stack.\n * @public\n * @method draw\n * @memberof Drawing\n *\n * @param {CanvasRenderingContext2D} context - Target Canvas\n * @param {ContextFn} fn - A function which performs drawing operations within the given context.\n * @returns {undefined}\n */\nexport default function(context, fn) {\n context.save();\n fn(context);\n context.restore();\n}\n","import toolStyle from './../stateManagement/toolStyle.js';\n\n/**\n * This function manages the beginPath/stroke pattern for working with\n * {@link https://www.w3.org/TR/2dcontext/#drawing-paths-to-the-canvas|path objects}.\n *\n * @public\n * @function path\n * @memberof Drawing\n *\n * @param {CanvasRenderingContext2D} context - Context to add path to\n * @param {Object} [options={}] - Drawing Options\n * @param {StrokeStyle} [options.color] - The stroke style of the path.\n * @param {Number} [options.lineWidth] - The width of lines in the path. If null, no line width is set.\n * If undefined then toolStyle.getToolWidth() is set.\n * @param {FillStyle} [options.fillStyle] - The style to fill the path with. If undefined then no filling is done.\n * @param {Number[]} [options.lineDash] - The {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash|dash pattern}\n * to use on the lines.\n * @param {ContextFn} fn - A drawing function to execute with the provided stroke pattern.\n * @returns {undefined}\n */\nexport default function(context, options = {}, fn) {\n const { color, lineWidth, fillStyle, lineDash } = options;\n\n context.beginPath();\n context.strokeStyle = color || context.strokeStyle;\n context.lineWidth =\n lineWidth ||\n (lineWidth === undefined && toolStyle.getToolWidth()) ||\n context.lineWidth;\n if (lineDash) {\n context.setLineDash(lineDash);\n }\n\n fn(context);\n\n if (fillStyle) {\n context.fillStyle = fillStyle;\n context.fill();\n }\n context.stroke();\n if (lineDash) {\n context.setLineDash([]);\n }\n}\n","import external from './../externalModules.js';\nimport path from './path.js';\n\n/**\n * Draw a line between `start` and `end`.\n *\n * @public\n * @method drawLine\n * @memberof Drawing\n *\n * @param {CanvasRenderingContext2D} context\n * @param {HTMLElement} element - The DOM Element to draw on\n * @param {Object} start - `{ x, y } in either pixel or canvas coordinates.\n * @param {Object} end - `{ x, y }` in either pixel or canvas coordinates.\n * @param {Object} options - See {@link path}\n * @param {String} [coordSystem='pixel'] - Can be \"pixel\" (default) or \"canvas\". The coordinate\n * system of the points passed in to the function. If \"pixel\" then cornerstone.pixelToCanvas\n * is used to transform the points from pixel to canvas coordinates.\n * @returns {undefined}\n */\nexport default function drawLine(\n context,\n element,\n start,\n end,\n options,\n coordSystem = 'pixel'\n) {\n path(context, options, context => {\n if (coordSystem === 'pixel') {\n start = external.cornerstone.pixelToCanvas(element, start);\n end = external.cornerstone.pixelToCanvas(element, end);\n }\n\n context.moveTo(start.x, start.y);\n context.lineTo(end.x, end.y);\n });\n}\n","import external from './../externalModules.js';\nimport path from './path.js';\n\n/**\n * Draw a series of joined lines, starting at `start` and then going to each point in `points`.\n * @public\n * @method drawJoinedLines\n * @memberof Drawing\n *\n * @param {CanvasRenderingContext2D} context - Target context\n * @param {HTMLElement} element - The DOM Element to draw on\n * @param {Object} start - `{ x, y }` in either pixel or canvas coordinates.\n * @param {Object[]} points - `[{ x, y }]` An array of points in either pixel or canvas coordinates.\n * @param {Object} options - See {@link path}\n * @param {String} [coordSystem='pixel'] - Can be \"pixel\" (default) or \"canvas\". The coordinate\n * system of the points passed in to the function. If \"pixel\" then cornerstone.pixelToCanvas\n * is used to transform the points from pixel to canvas coordinates.\n * @returns {undefined}\n */\nexport default function(\n context,\n element,\n start,\n points,\n options,\n coordSystem = 'pixel'\n) {\n path(context, options, context => {\n if (coordSystem === 'pixel') {\n start = external.cornerstone.pixelToCanvas(element, start);\n points = points.map(p => external.cornerstone.pixelToCanvas(element, p));\n }\n context.moveTo(start.x, start.y);\n points.forEach(({ x, y }) => {\n context.lineTo(x, y);\n });\n });\n}\n","import drawLine from './drawLine.js';\nimport drawJoinedLines from './drawJoinedLines.js';\n\n/**\n * Draw an arrow using the drawing API.\n * @public\n * @method drawArrow\n * @memberof Drawing\n *\n * @param {Object} context The canvas context.\n * @param {Object} start The start position.\n * @param {Object} end The end position.\n * @param {string} color The color of the arrow.\n * @param {number} lineWidth The width of the arrow line.\n * @returns {undefined}\n */\nexport default function(context, start, end, color, lineWidth) {\n // Variables to be used when creating the arrow\n const headLength = 10;\n\n const angle = Math.atan2(end.y - start.y, end.x - start.x);\n\n // Starting path of the arrow from the start square to the end square and drawing the stroke\n let options = {\n color,\n lineWidth,\n };\n\n drawLine(context, undefined, start, end, options, 'canvas');\n options = {\n color,\n lineWidth,\n fillStyle: color,\n };\n\n const points = [\n {\n x: end.x - headLength * Math.cos(angle - Math.PI / 7),\n y: end.y - headLength * Math.sin(angle - Math.PI / 7),\n },\n {\n x: end.x - headLength * Math.cos(angle + Math.PI / 7),\n y: end.y - headLength * Math.sin(angle + Math.PI / 7),\n },\n end,\n ];\n\n drawJoinedLines(context, undefined, end, points, options, 'canvas');\n}\n","import external from './../externalModules.js';\nimport path from './path.js';\n\n/**\n * Draw a circle with given `center` and `radius`.\n * @public\n * @method drawCircle\n * @memberof Drawing\n *\n * @param {CanvasRenderingContext2D} context - Target context\n * @param {HTMLElement} element - The DOM Element to draw on\n * @param {Object} center - `{ x, y }` in either pixel or canvas coordinates.\n * @param {number} radius - The circle's radius in canvas units.\n * @param {Object} options - See {@link path}\n * @param {String} [coordSystem='pixel'] - Can be \"pixel\" (default) or \"canvas\". The coordinate\n * system of the points passed in to the function. If \"pixel\" then cornerstone.pixelToCanvas\n * is used to transform the points from pixel to canvas coordinates.\n * @returns {undefined}\n */\nexport default function(\n context,\n element,\n center,\n radius,\n options,\n coordSystem = 'pixel'\n) {\n if (coordSystem === 'pixel') {\n center = external.cornerstone.pixelToCanvas(element, center);\n }\n\n path(context, options, context => {\n context.arc(center.x, center.y, radius, 0, 2 * Math.PI);\n });\n}\n","import external from './../externalModules.js';\nimport path from './path.js';\n\n/**\n * Draw an ellipse within the bounding box defined by `corner1` and `corner2`.\n * @public\n * @method drawEllipse\n * @memberof Drawing\n *\n * @param {CanvasRenderingContext2D} context - Target context\n * @param {HTMLElement} element - The DOM Element to draw on\n * @param {Object} corner1 - `{ x, y }` in either pixel or canvas coordinates.\n * @param {Object} corner2 - `{ x, y }` in either pixel or canvas coordinates.\n * @param {Object} options - See {@link path}\n * @param {String} [coordSystem='pixel'] - Can be \"pixel\" (default) or \"canvas\". The coordinate\n * system of the points passed in to the function. If \"pixel\" then cornerstone.pixelToCanvas\n * is used to transform the points from pixel to canvas coordinates.\n * @returns {undefined}\n */\nexport default function(\n context,\n element,\n corner1,\n corner2,\n options,\n coordSystem = 'pixel'\n) {\n // http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas\n if (coordSystem === 'pixel') {\n corner1 = external.cornerstone.pixelToCanvas(element, corner1);\n corner2 = external.cornerstone.pixelToCanvas(element, corner2);\n }\n const x = Math.min(corner1.x, corner2.x);\n const y = Math.min(corner1.y, corner2.y);\n const w = Math.abs(corner1.x - corner2.x);\n const h = Math.abs(corner1.y - corner2.y);\n\n const kappa = 0.5522848,\n ox = (w / 2) * kappa, // Control point offset horizontal\n oy = (h / 2) * kappa, // Control point offset vertical\n xe = x + w, // X-end\n ye = y + h, // Y-end\n xm = x + w / 2, // X-middle\n ym = y + h / 2; // Y-middle\n\n path(context, options, context => {\n context.moveTo(x, ym);\n context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);\n context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);\n context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);\n context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);\n context.closePath();\n });\n}\n","import external from './../externalModules.js';\nimport toolStyle from './../stateManagement/toolStyle.js';\nimport toolColors from './../stateManagement/toolColors.js';\nimport path from './path.js';\nimport { state } from './../store/index.js';\n\n/**\n * Draws proivded handles to the provided context\n * @public\n * @method drawHandles\n * @memberof Drawing\n *\n * @param {CanvasRenderingContext2D} context - Target context\n * @param {*} evtDetail - Cornerstone's 'cornerstoneimagerendered' event's `detail`\n * @param {Object[]|Object} handles - An array of handle objects, or an object w/ named handle objects\n * @param {Object} [options={}] - Options object\n * @param {string} [options.color]\n * @param {Boolean} [options.drawHandlesIfActive=false] - Whether the handles should only be drawn if Active (hovered/selected)\n * @param {string} [options.fill]\n * @param {Number} [options.handleRadius=6]\n * @returns {undefined}\n */\nexport default function(context, evtDetail, handles, options = {}) {\n const element = evtDetail.element;\n const defaultColor = toolColors.getToolColor();\n\n context.strokeStyle = options.color || defaultColor;\n\n const handleKeys = Object.keys(handles);\n\n for (let i = 0; i < handleKeys.length; i++) {\n const handleKey = handleKeys[i];\n const handle = handles[handleKey];\n\n if (handle.drawnIndependently === true) {\n continue;\n }\n\n if (options.drawHandlesIfActive === true && !handle.active) {\n continue;\n }\n\n const lineWidth = handle.active\n ? toolStyle.getActiveWidth()\n : toolStyle.getToolWidth();\n const fillStyle = options.fill;\n\n path(\n context,\n {\n lineWidth,\n fillStyle,\n },\n context => {\n const handleCanvasCoords = external.cornerstone.pixelToCanvas(\n element,\n handle\n );\n\n // Handle's radisu, then tool's radius, then default radius\n const handleRadius =\n handle.radius || options.handleRadius || state.handleRadius;\n\n context.arc(\n handleCanvasCoords.x,\n handleCanvasCoords.y,\n handleRadius,\n 0,\n 2 * Math.PI\n );\n }\n );\n }\n}\n","import external from '../externalModules.js';\nimport drawLine from './drawLine.js';\n\n/**\n * Draw a link between an annotation to a box.\n * @public\n * @method drawLink\n * @memberof Drawing\n *\n * @param {Object[]} linkAnchorPoints An array of possible anchor points.\n * @param {Object} refPoint A reference point to select the anchor point.\n * @param {Object} boundingBox The bounding box to link.\n * @param {Object} context The canvas context.\n * @param {string} color The link color.\n * @param {number} lineWidth The line width of the link.\n * @returns {undefined}\n */\nexport default function(\n linkAnchorPoints,\n refPoint,\n boundingBox,\n context,\n color,\n lineWidth\n) {\n // Draw a link from \"the closest anchor point to refPoint\" to \"the nearest midpoint on the bounding box\".\n\n // Find the closest anchor point to RefPoint\n const start =\n linkAnchorPoints.length > 0\n ? external.cornerstoneMath.point.findClosestPoint(\n linkAnchorPoints,\n refPoint\n )\n : refPoint;\n\n // Calculate the midpoints of the bounding box\n const boundingBoxPoints = [\n {\n x: boundingBox.left + boundingBox.width / 2,\n y: boundingBox.top,\n },\n {\n x: boundingBox.left,\n y: boundingBox.top + boundingBox.height / 2,\n },\n {\n x: boundingBox.left + boundingBox.width / 2,\n y: boundingBox.top + boundingBox.height,\n },\n {\n x: boundingBox.left + boundingBox.width,\n y: boundingBox.top + boundingBox.height / 2,\n },\n ];\n\n // Calculate the link endpoint by identifying which midpoint of the bounding box\n // Is closest to the start point.\n const end = external.cornerstoneMath.point.findClosestPoint(\n boundingBoxPoints,\n start\n );\n\n // Finally we draw the dashed linking line\n const options = {\n color,\n lineWidth,\n lineDash: [2, 3],\n };\n\n drawLine(context, undefined, start, end, options, 'canvas');\n}\n","let defaultFontSize = 15,\n defaultFont = `${defaultFontSize}px Arial`,\n defaultBackgroundColor = 'transparent';\n\nfunction setFont(font) {\n defaultFont = font;\n}\n\nfunction getFont() {\n return defaultFont;\n}\n\nfunction setFontSize(fontSize) {\n defaultFontSize = fontSize;\n}\n\nfunction getFontSize() {\n return defaultFontSize;\n}\n\nfunction setBackgroundColor(backgroundColor) {\n defaultBackgroundColor = backgroundColor;\n}\n\nfunction getBackgroundColor() {\n return defaultBackgroundColor;\n}\n\nconst textStyle = {\n setFont,\n getFont,\n setFontSize,\n getFontSize,\n setBackgroundColor,\n getBackgroundColor,\n};\n\nexport default textStyle;\n","import textStyle from './../stateManagement/textStyle.js';\n\n/**\n * Draw multiple lines of text within a bounding box.\n * @public\n * @method fillTextLines\n * @memberof Drawing\n *\n * @param {CanvasRenderingContext2D} context - Target context\n * @param {Object} boundingBox - `{ left, top }` in canvas coordinates. Only the top-left corner is specified, as the text will take up as much space as it needs.\n * @param {String[]} textLines - The text to be displayed.\n * @param {FillStyle} fillStyle - The fillStyle to apply to the text.\n * @param {Number} padding - The amount of padding above/below each line in canvas units. Note this gives an inter-line spacing of `2*padding`.\n * @returns {undefined}\n */\nexport default function(context, boundingBox, textLines, fillStyle, padding) {\n const fontSize = textStyle.getFontSize();\n\n context.font = textStyle.getFont();\n context.textBaseline = 'top';\n context.fillStyle = fillStyle;\n textLines.forEach(function(text, index) {\n context.fillText(\n text,\n boundingBox.left + padding,\n boundingBox.top + padding + index * (fontSize + padding)\n );\n });\n}\n","/**\n * Draw a filled rectangle defined by `boundingBox` using the style defined by `fillStyle`.\n * @public\n * @method fillBox\n * @memberof Drawing\n *\n * @param {CanvasRenderingContext2D} context - Target context\n * @param {Object} boundingBox - `{ left, top, width, height }` in canvas coordinates.\n * @param {FillStyle} fillStyle - The fillStyle to apply to the region.\n * @returns {undefined}\n */\nexport default function(context, boundingBox, fillStyle) {\n context.fillStyle = fillStyle;\n context.fillRect(\n boundingBox.left,\n boundingBox.top,\n boundingBox.width,\n boundingBox.height\n );\n}\n","import textStyle from '../stateManagement/textStyle.js';\nimport draw from './draw.js';\nimport fillTextLines from './fillTextLines.js';\nimport fillBox from './fillBox.js';\n\n/**\n * Compute the width of the box required to display the given `text` with a given `padding`.\n * @public\n * @function textBoxWidth\n * @memberof Drawing\n *\n * @param {CanvasRenderingContext2D} context - Target context\n * @param {String} text - The text to find the width of.\n * @param {Number} padding - The padding to apply on either end of the text.\n * @returns {Number} computed text box width\n */\nexport function textBoxWidth(context, text, padding) {\n const font = textStyle.getFont();\n const origFont = context.font;\n\n if (font && font !== origFont) {\n context.font = font;\n }\n const width = context.measureText(text).width;\n\n if (font && font !== origFont) {\n context.font = origFont;\n }\n\n return width + 2 * padding;\n}\n\n/**\n * Draws a textBox.\n * @public\n * @function drawTextBox\n * @memberof Drawing\n *\n * @param {CanvasRenderingContext2D} context The canvas context.\n * @param {string} textLines The text to display.\n * @param {number} x The x position of the textBox.\n * @param {number} y The y position of the textBox.\n * @param {string} color The color of the textBox.\n * @param {Object} options Options for the textBox.\n * @returns {Object} {top, left, width, height} - Bounding box; can be used for pointNearTool\n */\nexport default function(context, textLines, x, y, color, options) {\n if (Object.prototype.toString.call(textLines) !== '[object Array]') {\n textLines = [textLines];\n }\n\n const padding = 5;\n const fontSize = textStyle.getFontSize();\n const backgroundColor = textStyle.getBackgroundColor();\n\n // Find the longest text width in the array of text data\n let maxWidth = 0;\n\n textLines.forEach(function(text) {\n // Get the text width in the current font\n const width = textBoxWidth(context, text, padding);\n\n // Find the maximum with for all the text rows;\n maxWidth = Math.max(maxWidth, width);\n });\n\n // Calculate the bounding box for this text box\n const boundingBox = {\n width: maxWidth,\n height: padding + textLines.length * (fontSize + padding),\n };\n\n draw(context, context => {\n context.strokeStyle = color;\n\n // Draw the background box with padding\n if (options && options.centering && options.centering.x === true) {\n x -= boundingBox.width / 2;\n }\n\n if (options && options.centering && options.centering.y === true) {\n y -= boundingBox.height / 2;\n }\n\n boundingBox.left = x;\n boundingBox.top = y;\n\n const fillStyle =\n options && options.debug === true ? '#FF0000' : backgroundColor;\n\n fillBox(context, boundingBox, fillStyle);\n\n // Draw each of the text lines on top of the background box\n fillTextLines(context, boundingBox, textLines, color, padding);\n });\n\n // Return the bounding box so it can be used for pointNearHandle\n return boundingBox;\n}\n","import external from '../externalModules.js';\nimport drawTextBox from './drawTextBox.js';\nimport drawLink from './drawLink.js';\n\n/**\n * Draw a link between an annotation to a textBox.\n * @public\n * @method drawLinkedTextBox\n * @memberof Drawing\n *\n * @param {Object} context - The canvas context.\n * @param {HTMLElement} element - The element on which to draw the link.\n * @param {Object} textBox - The textBox to link.\n * @param {Object} text - The text to display in the textbox.\n * @param {Object[]} handles - The handles of the annotation.\n * @param {Object[]} textBoxAnchorPoints - An array of possible anchor points on the textBox.\n * @param {string} color - The link color.\n * @param {number} lineWidth - The line width of the link.\n * @param {number} xOffset - The x offset of the textbox.\n * @param {boolean} yCenter - Vertically centers the text if true.\n * @returns {undefined}\n */\nexport default function(\n context,\n element,\n textBox,\n text,\n handles,\n textBoxAnchorPoints,\n color,\n lineWidth,\n xOffset,\n yCenter\n) {\n const cornerstone = external.cornerstone;\n\n // Convert the textbox Image coordinates into Canvas coordinates\n const textCoords = cornerstone.pixelToCanvas(element, textBox);\n\n if (xOffset) {\n textCoords.x += xOffset;\n }\n\n const options = {\n centering: {\n x: false,\n y: yCenter,\n },\n };\n\n // Draw the text box\n textBox.boundingBox = drawTextBox(\n context,\n text,\n textCoords.x,\n textCoords.y,\n color,\n options\n );\n if (textBox.hasMoved) {\n // Identify the possible anchor points for the tool -> text line\n const linkAnchorPoints = textBoxAnchorPoints(handles).map(h =>\n cornerstone.pixelToCanvas(element, h)\n );\n\n // Draw dashed link line between tool and text\n drawLink(\n linkAnchorPoints,\n textCoords,\n textBox.boundingBox,\n context,\n color,\n lineWidth\n );\n }\n}\n","import external from './../externalModules.js';\nimport path from './path.js';\n\n/**\n * Draw a rectangle defined by `corner1` and `corner2`.\n * @public\n * @method drawRect\n * @memberof Drawing\n *\n * @param {CanvasRenderingContext2D} context - Target context\n * @param {HTMLElement} element - The DOM Element to draw on\n * @param {Object} corner1 - `{ x, y }` in either pixel or canvas coordinates.\n * @param {Object} corner2 - `{ x, y }` in either pixel or canvas coordinates.\n * @param {Object} options - See {@link path}\n * @param {String} [coordSystem='pixel'] - Can be \"pixel\" (default) or \"canvas\". The coordinate\n * system of the points passed in to the function. If \"pixel\" then cornerstone.pixelToCanvas\n * is used to transform the points from pixel to canvas coordinates.\n * @returns {undefined}\n */\nexport default function(\n context,\n element,\n corner1,\n corner2,\n options,\n coordSystem = 'pixel'\n) {\n if (coordSystem === 'pixel') {\n const cornerstone = external.cornerstone;\n\n corner1 = cornerstone.pixelToCanvas(element, corner1);\n corner2 = cornerstone.pixelToCanvas(element, corner2);\n }\n\n const left = Math.min(corner1.x, corner2.x);\n const top = Math.min(corner1.y, corner2.y);\n const width = Math.abs(corner1.x - corner2.x);\n const height = Math.abs(corner1.y - corner2.y);\n\n path(context, options, context => {\n context.rect(left, top, width, height);\n });\n}\n","/**\n * Create a new {@link CanvasRenderingContext2D|context} object for the given {@link HTMLCanvasElement|canvas}\n * and set the transform to the {@link https://www.w3.org/TR/2dcontext/#transformations|identity transform}.\n *\n * @public\n * @function getNewContext\n * @memberof Drawing\n *\n * @param {HTMLCanvasElement} canvas - Canvas you would like the context for\n * @returns {CanvasRenderingContext2D} - The provided canvas's 2d context\n */\nexport default function(canvas) {\n const context = canvas.getContext('2d');\n\n context.setTransform(1, 0, 0, 1, 0, 0);\n\n return context;\n}\n","/**\n * Returns the first argument if defined, otherwise returns the second\n *\n * @param {*} value\n * @param {*} defaultValue\n * @returns {*}\n */\nexport default function(value, defaultValue) {\n return value === undefined ? defaultValue : value;\n}\n","import getDefault from './../util/getDefault.js';\n\n/**\n * Set the {@link https://www.w3.org/TR/2dcontext/#shadows|shadow} properties of the context.\n * Each property is set on the context object if defined, otherwise a default value is set.\n *\n * @public\n * @method setShadow\n * @memberof Drawing\n *\n * @param {CanvasRenderingContext2D} context - Context to apply shadow options on\n * @param {Object} [options={}] - Options object\n * @param {Boolean} [options.shadow=undefined] - Whether to set any shadow options\n * @param {String} [options.shadowColor=#000000] - Default value: #000000\n * @param {Number} [options.shadowBlur=0] - Default Value: 0\n * @param {Number} [options.shadowOffsetX=1] - Default value: 1\n * @param {Number} [options.shadowOffsetY=1] - Default value: 1\n * @returns {undefined}\n */\nexport default function(context, options = {}) {\n if (options.shadow) {\n context.shadowColor = getDefault(options.shadowColor, '#000000');\n context.shadowBlur = getDefault(options.shadowBlur, 0);\n context.shadowOffsetX = getDefault(options.shadowOffsetX, 1);\n context.shadowOffsetY = getDefault(options.shadowOffsetY, 1);\n }\n}\n","/**\n * Transform the canvas {@link CanvasRenderingContext2D|context} such that it\n * coincides with the orientation of the viewport.\n *\n * @public\n * @function transformCanvasContext\n * @memberof Drawing\n *\n * @param {CanvasRenderingContext2D} context - Context you wish to transform.\n * @param {HTMLCanvasElement} canvas - Canvas the context relates to.\n * @param {*} viewport - The viewport you wish to map on to.\n * @returns null\n */\nexport default function(context, canvas, viewport) {\n if (!(viewport.vflip || viewport.vflip || viewport.rotation)) {\n return;\n }\n\n const translation = {\n x: canvas.width / 2 + viewport.translation.x * viewport.scale,\n y: canvas.height / 2 + viewport.translation.y * viewport.scale,\n };\n\n context.translate(translation.x, translation.y);\n\n if (viewport.rotation) {\n context.rotate((viewport.rotation * Math.PI) / 180);\n }\n\n if (viewport.vflip) {\n context.scale(1, -1);\n }\n\n if (viewport.hflip) {\n context.scale(-1, 1);\n }\n\n context.translate(-translation.x, -translation.y);\n}\n","/**\n * Resets the canvas {@link CanvasRenderingContext2D|context} transform to the\n * {@link https://www.w3.org/TR/2dcontext/#transformations|identity transform}.\n *\n * @public\n * @function resetCanvasContextTransform\n * @memberof Drawing\n *\n * @param {CanvasRenderingContext2D} context - context you wish to transform\n * @returns null\n */\nexport default function(context) {\n context.setTransform(1, 0, 0, 1, 0, 0);\n}\n","import external from '../externalModules.js';\n\n/**\n * Calculates the distance of a line segment from a point.\n * @export @public @method\n * @name lineSegDistance\n *\n * @param {HTMLElement} element The element.\n * @param {Object} start The starting position of the line.\n * @param {Object} end The end position of the line.\n * @param {Object} coords The coordinates of the point.\n * @returns {name} The distance between the line and the point.\n */\nexport default function(element, start, end, coords) {\n const cornerstone = external.cornerstone;\n\n const lineSegment = {\n start: cornerstone.pixelToCanvas(element, start),\n end: cornerstone.pixelToCanvas(element, end),\n };\n\n return external.cornerstoneMath.lineSegment.distanceToPoint(\n lineSegment,\n coords\n );\n}\n","/**\n * Rounds a number to the specified precision.\n * @export @public @method\n * @name roundToDecimal\n *\n * @param {number} value The value to round.\n * @param {number} precision The required precision.\n * @returns {number} The rounded number.\n */\nexport default function(value, precision) {\n const multiplier = Math.pow(10, precision);\n\n return Math.round(value * multiplier) / multiplier;\n}\n","import external from './../../externalModules.js';\nimport BaseAnnotationTool from '../base/BaseAnnotationTool.js';\n// State\nimport {\n addToolState,\n getToolState,\n} from './../../stateManagement/toolState.js';\nimport toolStyle from './../../stateManagement/toolStyle.js';\nimport toolColors from './../../stateManagement/toolColors.js';\n// Manipulators\nimport { moveNewHandle } from './../../manipulators/index.js';\n// Drawing\nimport {\n getNewContext,\n draw,\n setShadow,\n drawJoinedLines,\n} from './../../drawing/index.js';\nimport drawLinkedTextBox from './../../drawing/drawLinkedTextBox.js';\nimport { textBoxWidth } from './../../drawing/drawTextBox.js';\nimport drawHandles from './../../drawing/drawHandles.js';\nimport lineSegDistance from './../../util/lineSegDistance.js';\nimport roundToDecimal from './../../util/roundToDecimal.js';\n\n/**\n * @public\n * @class AngleTool\n * @memberof Tools.Annotation\n * @classdesc Create and position an angle by placing three consecutive points.\n * @extends Tools.Base.BaseAnnotationTool\n * @hideconstructor\n *\n * @param {ToolConfiguration} [configuration={}]\n */\nclass AngleTool extends BaseAnnotationTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'Angle',\n supportedInteractionTypes: ['Mouse', 'Touch'],\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n this.preventNewMeasurement = false;\n }\n\n createNewMeasurement(eventData) {\n // Create the measurement data for this tool with the end handle activated\n return {\n visible: true,\n active: true,\n color: undefined,\n handles: {\n start: {\n x: eventData.currentPoints.image.x,\n y: eventData.currentPoints.image.y,\n highlight: true,\n active: false,\n },\n middle: {\n x: eventData.currentPoints.image.x,\n y: eventData.currentPoints.image.y,\n highlight: true,\n active: true,\n },\n end: {\n x: eventData.currentPoints.image.x,\n y: eventData.currentPoints.image.y,\n highlight: true,\n active: false,\n },\n textBox: {\n active: false,\n hasMoved: false,\n movesIndependently: false,\n drawnIndependently: true,\n allowedOutsideImage: true,\n hasBoundingBox: true,\n },\n },\n };\n }\n\n pointNearTool(element, data, coords) {\n if (data.visible === false) {\n return false;\n }\n\n return (\n lineSegDistance(\n element,\n data.handles.start,\n data.handles.middle,\n coords\n ) < 25 ||\n lineSegDistance(element, data.handles.middle, data.handles.end, coords) <\n 25\n );\n }\n\n renderToolData(evt) {\n const eventData = evt.detail;\n const enabledElement = eventData.enabledElement;\n const { handleRadius, drawHandlesOnHover } = this.configuration;\n // If we have no toolData for this element, return immediately as there is nothing to do\n const toolData = getToolState(evt.currentTarget, this.name);\n\n if (!toolData) {\n return;\n }\n\n // We have tool data for this element - iterate over each one and draw it\n const context = getNewContext(eventData.canvasContext.canvas);\n\n const lineWidth = toolStyle.getToolWidth();\n\n for (let i = 0; i < toolData.data.length; i++) {\n const data = toolData.data[i];\n\n if (data.visible === false) {\n continue;\n }\n\n draw(context, context => {\n setShadow(context, this.configuration);\n\n // Differentiate the color of activation tool\n const color = toolColors.getColorIfActive(data);\n\n const handleStartCanvas = external.cornerstone.pixelToCanvas(\n eventData.element,\n data.handles.start\n );\n const handleMiddleCanvas = external.cornerstone.pixelToCanvas(\n eventData.element,\n data.handles.middle\n );\n\n drawJoinedLines(\n context,\n eventData.element,\n data.handles.start,\n [data.handles.middle, data.handles.end],\n { color }\n );\n\n // Draw the handles\n const handleOptions = {\n color,\n handleRadius,\n drawHandlesIfActive: drawHandlesOnHover,\n };\n\n drawHandles(context, eventData, data.handles, handleOptions);\n\n // Default to isotropic pixel size, update suffix to reflect this\n const columnPixelSpacing = eventData.image.columnPixelSpacing || 1;\n const rowPixelSpacing = eventData.image.rowPixelSpacing || 1;\n\n const sideA = {\n x:\n (data.handles.middle.x - data.handles.start.x) * columnPixelSpacing,\n y: (data.handles.middle.y - data.handles.start.y) * rowPixelSpacing,\n };\n\n const sideB = {\n x: (data.handles.end.x - data.handles.middle.x) * columnPixelSpacing,\n y: (data.handles.end.y - data.handles.middle.y) * rowPixelSpacing,\n };\n\n const sideC = {\n x: (data.handles.end.x - data.handles.start.x) * columnPixelSpacing,\n y: (data.handles.end.y - data.handles.start.y) * rowPixelSpacing,\n };\n\n const sideALength = length(sideA);\n const sideBLength = length(sideB);\n const sideCLength = length(sideC);\n\n // Cosine law\n let angle = Math.acos(\n (Math.pow(sideALength, 2) +\n Math.pow(sideBLength, 2) -\n Math.pow(sideCLength, 2)) /\n (2 * sideALength * sideBLength)\n );\n\n angle *= 180 / Math.PI;\n\n data.rAngle = roundToDecimal(angle, 2);\n\n if (data.rAngle) {\n const text = textBoxText(\n data,\n eventData.image.rowPixelSpacing,\n eventData.image.columnPixelSpacing\n );\n\n const distance = 15;\n\n let textCoords;\n\n if (!data.handles.textBox.hasMoved) {\n textCoords = {\n x: handleMiddleCanvas.x,\n y: handleMiddleCanvas.y,\n };\n\n const padding = 5;\n const textWidth = textBoxWidth(context, text, padding);\n\n if (handleMiddleCanvas.x < handleStartCanvas.x) {\n textCoords.x -= distance + textWidth + 10;\n } else {\n textCoords.x += distance;\n }\n\n const transform = external.cornerstone.internal.getTransform(\n enabledElement\n );\n\n transform.invert();\n\n const coords = transform.transformPoint(textCoords.x, textCoords.y);\n\n data.handles.textBox.x = coords.x;\n data.handles.textBox.y = coords.y;\n }\n\n drawLinkedTextBox(\n context,\n eventData.element,\n data.handles.textBox,\n text,\n data.handles,\n textBoxAnchorPoints,\n color,\n lineWidth,\n 0,\n true\n );\n }\n });\n }\n\n function textBoxText(data, rowPixelSpacing, columnPixelSpacing) {\n const suffix =\n !rowPixelSpacing || !columnPixelSpacing ? ' (isotropic)' : '';\n const str = '00B0'; // Degrees symbol\n\n return (\n data.rAngle.toString() + String.fromCharCode(parseInt(str, 16)) + suffix\n );\n }\n\n function textBoxAnchorPoints(handles) {\n return [handles.start, handles.middle, handles.end];\n }\n }\n\n addNewMeasurement(evt, interactionType) {\n if (this.preventNewMeasurement) {\n return;\n }\n\n this.preventNewMeasurement = true;\n evt.preventDefault();\n evt.stopPropagation();\n\n const eventData = evt.detail;\n const measurementData = this.createNewMeasurement(eventData);\n const element = evt.detail.element;\n\n // Associate this data with this imageId so we can render it and manipulate it\n addToolState(element, this.name, measurementData);\n external.cornerstone.updateImage(element);\n\n const doneMovingEndHandleOptions = Object.assign(\n {},\n {\n doneMovingCallback: () => {\n measurementData.active = false;\n this.preventNewMeasurement = false;\n external.cornerstone.updateImage(element);\n },\n },\n this.options\n );\n\n const doneMovingMiddleHandleOptions = Object.assign(\n {},\n {\n doneMovingCallback: () => {\n measurementData.active = false;\n measurementData.handles.end.active = true;\n\n external.cornerstone.updateImage(element);\n\n moveNewHandle(\n eventData,\n this.name,\n measurementData,\n measurementData.handles.end,\n doneMovingEndHandleOptions,\n interactionType\n );\n },\n },\n this.options\n );\n\n // Step 1, create start and second middle\n moveNewHandle(\n eventData,\n this.name,\n measurementData,\n measurementData.handles.middle,\n doneMovingMiddleHandleOptions,\n interactionType\n );\n }\n}\n\nfunction length(vector) {\n return Math.sqrt(Math.pow(vector.x, 2) + Math.pow(vector.y, 2));\n}\n\nexport default AngleTool;\n","/* eslint no-alert: 0 */\nimport external from './../../externalModules.js';\nimport BaseAnnotationTool from '../base/BaseAnnotationTool.js';\n\nimport toolStyle from './../../stateManagement/toolStyle.js';\nimport textStyle from './../../stateManagement/textStyle.js';\nimport toolColors from './../../stateManagement/toolColors.js';\nimport { moveNewHandle } from './../../manipulators/index.js';\nimport pointInsideBoundingBox from './../../util/pointInsideBoundingBox.js';\nimport lineSegDistance from './../../util/lineSegDistance.js';\nimport {\n addToolState,\n removeToolState,\n getToolState,\n} from './../../stateManagement/toolState.js';\nimport drawLinkedTextBox from './../../drawing/drawLinkedTextBox.js';\nimport { getNewContext, draw, setShadow } from './../../drawing/index.js';\nimport drawArrow from './../../drawing/drawArrow.js';\nimport drawHandles from './../../drawing/drawHandles.js';\nimport { textBoxWidth } from './../../drawing/drawTextBox.js';\n\n/**\n * @public\n * @class ArrowAnnotateTool\n * @memberof Tools.Annotation\n * @classdesc Create and position an arrow and label\n * @extends Tools.Base.BaseAnnotationTool\n */\nexport default class ArrowAnnotateTool extends BaseAnnotationTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'ArrowAnnotate',\n supportedInteractionTypes: ['Mouse', 'Touch'],\n configuration: {\n getTextCallback,\n changeTextCallback,\n drawHandles: false,\n drawHandlesOnHover: true,\n arrowFirst: true,\n },\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n this.preventNewMeasurement = false;\n }\n\n createNewMeasurement(evt) {\n // Create the measurement data for this tool with the end handle activated\n return {\n visible: true,\n active: true,\n color: undefined,\n handles: {\n start: {\n x: evt.detail.currentPoints.image.x,\n y: evt.detail.currentPoints.image.y,\n highlight: true,\n active: false,\n },\n end: {\n x: evt.detail.currentPoints.image.x,\n y: evt.detail.currentPoints.image.y,\n highlight: true,\n active: false,\n },\n textBox: {\n active: false,\n hasMoved: false,\n movesIndependently: false,\n drawnIndependently: true,\n allowedOutsideImage: true,\n hasBoundingBox: true,\n },\n },\n };\n }\n\n pointNearTool(element, data, coords) {\n if (data.visible === false) {\n return false;\n }\n\n return (\n lineSegDistance(element, data.handles.start, data.handles.end, coords) <\n 25\n );\n }\n\n renderToolData(evt) {\n const { element, enabledElement } = evt.detail;\n const { handleRadius, drawHandlesOnHover } = this.configuration;\n\n // If we have no toolData for this element, return immediately as there is nothing to do\n const toolData = getToolState(element, this.name);\n\n if (!toolData) {\n return;\n }\n\n // We have tool data for this element - iterate over each one and draw it\n const canvas = evt.detail.canvasContext.canvas;\n const context = getNewContext(canvas);\n\n const lineWidth = toolStyle.getToolWidth();\n\n for (let i = 0; i < toolData.data.length; i++) {\n const data = toolData.data[i];\n\n if (data.visible === false) {\n continue;\n }\n\n draw(context, context => {\n setShadow(context, this.configuration);\n\n const color = toolColors.getColorIfActive(data);\n\n // Draw the arrow\n const handleStartCanvas = external.cornerstone.pixelToCanvas(\n element,\n data.handles.start\n );\n const handleEndCanvas = external.cornerstone.pixelToCanvas(\n element,\n data.handles.end\n );\n\n // Config.arrowFirst = false;\n if (this.configuration.arrowFirst) {\n drawArrow(\n context,\n handleEndCanvas,\n handleStartCanvas,\n color,\n lineWidth\n );\n } else {\n drawArrow(\n context,\n handleStartCanvas,\n handleEndCanvas,\n color,\n lineWidth\n );\n }\n\n const handleOptions = {\n color,\n handleRadius,\n drawHandlesIfActive: drawHandlesOnHover,\n };\n\n if (this.configuration.drawHandles) {\n drawHandles(context, evt.detail, data.handles, handleOptions);\n }\n\n const text = textBoxText(data);\n\n // Draw the text\n if (text && text !== '') {\n // Calculate the text coordinates.\n const padding = 5;\n const textWidth = textBoxWidth(context, text, padding);\n const textHeight = textStyle.getFontSize() + 10;\n\n let distance = Math.max(textWidth, textHeight) / 2 + 5;\n\n if (handleEndCanvas.x < handleStartCanvas.x) {\n distance = -distance;\n }\n\n if (!data.handles.textBox.hasMoved) {\n let textCoords;\n\n if (this.configuration.arrowFirst) {\n textCoords = {\n x: handleEndCanvas.x - textWidth / 2 + distance,\n y: handleEndCanvas.y - textHeight / 2,\n };\n } else {\n // If the arrow is at the End position, the text should\n // Be placed near the Start position\n textCoords = {\n x: handleStartCanvas.x - textWidth / 2 - distance,\n y: handleStartCanvas.y - textHeight / 2,\n };\n }\n\n const transform = external.cornerstone.internal.getTransform(\n enabledElement\n );\n\n transform.invert();\n\n const coords = transform.transformPoint(textCoords.x, textCoords.y);\n\n data.handles.textBox.x = coords.x;\n data.handles.textBox.y = coords.y;\n }\n\n drawLinkedTextBox(\n context,\n element,\n data.handles.textBox,\n text,\n data.handles,\n textBoxAnchorPoints,\n color,\n lineWidth,\n 0,\n false\n );\n }\n });\n }\n\n function textBoxText(data) {\n return data.text;\n }\n\n function textBoxAnchorPoints(handles) {\n const midpoint = {\n x: (handles.start.x + handles.end.x) / 2,\n y: (handles.start.y + handles.end.y) / 2,\n };\n\n return [handles.start, midpoint, handles.end];\n }\n }\n\n addNewMeasurement(evt, interactionType) {\n const element = evt.detail.element;\n const measurementData = this.createNewMeasurement(evt);\n\n // Associate this data with this imageId so we can render it and manipulate it\n addToolState(element, this.name, measurementData);\n external.cornerstone.updateImage(element);\n\n const toolOptions = Object.assign(\n {},\n {\n doneMovingCallback: () => {\n if (measurementData.text === undefined) {\n this.configuration.getTextCallback(text => {\n if (text) {\n measurementData.text = text;\n } else {\n removeToolState(element, this.name, measurementData);\n }\n\n measurementData.active = false;\n external.cornerstone.updateImage(element);\n });\n }\n\n external.cornerstone.updateImage(element);\n },\n },\n this.options\n );\n\n moveNewHandle(\n evt.detail,\n this.name,\n measurementData,\n measurementData.handles.end,\n toolOptions,\n interactionType\n );\n }\n\n doubleClickCallback(evt) {\n if (\n !Array.isArray(this.options.mouseButtonMask) ||\n !this.options.mouseButtonMask.includes(evt.detail.buttons)\n ) {\n return;\n }\n\n return this._updateTextForNearbyAnnotation(evt);\n }\n\n touchPressCallback(evt) {\n return this._updateTextForNearbyAnnotation(evt);\n }\n\n _updateTextForNearbyAnnotation(evt) {\n const element = evt.detail.element;\n const coords = evt.detail.currentPoints.canvas;\n const toolState = getToolState(element, this.name);\n\n if (!toolState) {\n return false;\n }\n\n for (let i = 0; i < toolState.data.length; i++) {\n const data = toolState.data[i];\n\n if (\n this.pointNearTool(element, data, coords) ||\n pointInsideBoundingBox(data.handles.textBox, coords)\n ) {\n data.active = true;\n external.cornerstone.updateImage(element);\n // Allow relabelling via a callback\n this.configuration.changeTextCallback(\n data,\n evt.detail,\n this._doneChangingTextCallback.bind(this, element, data)\n );\n\n evt.stopImmediatePropagation();\n evt.preventDefault();\n evt.stopPropagation();\n\n return true;\n }\n }\n }\n\n _doneChangingTextCallback(element, data, updatedText, deleteTool) {\n if (deleteTool === true) {\n removeToolState(element, this.name, data);\n } else {\n data.text = updatedText;\n }\n\n data.active = false;\n external.cornerstone.updateImage(element);\n }\n}\n\nfunction getTextCallback(doneChangingTextCallback) {\n doneChangingTextCallback(prompt('Enter your annotation:'));\n}\n\nfunction changeTextCallback(data, eventData, doneChangingTextCallback) {\n doneChangingTextCallback(prompt('Change your annotation:'));\n}\n","let coordsData;\n\nfunction setCoords(eventData) {\n coordsData = eventData.currentPoints.canvas;\n}\n\nfunction getCoords() {\n return coordsData;\n}\n\nconst toolCoordinates = {\n setCoords,\n getCoords,\n};\n\nexport default toolCoordinates;\n","const getHandle = (x, y, index, extraAttributes = {}) =>\n Object.assign(\n {\n x,\n y,\n index,\n drawnIndependently: false,\n allowedOutsideImage: false,\n highlight: true,\n active: false,\n },\n extraAttributes\n );\n\nexport default function(mouseEventData) {\n const { x, y } = mouseEventData.currentPoints.image;\n // Create the measurement data for this tool with the end handle activated\n const measurementData = {\n toolType: this.name,\n isCreating: true,\n visible: true,\n active: true,\n handles: {\n start: getHandle(x, y, 0),\n end: getHandle(x, y, 1, { active: true }),\n perpendicularStart: getHandle(x, y, 2, { locked: true }),\n perpendicularEnd: getHandle(x, y, 3),\n textBox: getHandle(x - 50, y - 70, null, {\n highlight: false,\n hasMoved: true,\n active: false,\n movesIndependently: false,\n drawnIndependently: true,\n allowedOutsideImage: true,\n hasBoundingBox: true,\n }),\n },\n longestDiameter: 0,\n shortestDiameter: 0,\n };\n\n return measurementData;\n}\n","import { state } from '../../../store/index.js';\nimport external from './../../../externalModules.js';\nimport pointInsideBoundingBox from './../../../util/pointInsideBoundingBox.js';\n\nconst pointNearPerpendicular = (\n element,\n handles,\n coords,\n distanceThreshold\n) => {\n const cornerstone = external.cornerstone;\n const cornerstoneMath = external.cornerstoneMath;\n const lineSegment = {\n start: cornerstone.pixelToCanvas(element, handles.perpendicularStart),\n end: cornerstone.pixelToCanvas(element, handles.perpendicularEnd),\n };\n\n const distanceToPoint = cornerstoneMath.lineSegment.distanceToPoint(\n lineSegment,\n coords\n );\n\n return distanceToPoint < distanceThreshold;\n};\n\nexport default function(element, data, coords, interactionType = 'mouse') {\n const cornerstone = external.cornerstone;\n const cornerstoneMath = external.cornerstoneMath;\n const { handles } = data;\n const lineSegment = {\n start: cornerstone.pixelToCanvas(element, handles.start),\n end: cornerstone.pixelToCanvas(element, handles.end),\n };\n\n const distanceToPoint = cornerstoneMath.lineSegment.distanceToPoint(\n lineSegment,\n coords\n );\n\n if (pointInsideBoundingBox(handles.textBox, coords)) {\n return true;\n }\n\n const distanceThreshold =\n interactionType === 'mouse' ? state.clickProximity : state.touchProximity;\n\n if (pointNearPerpendicular(element, handles, coords, distanceThreshold)) {\n return true;\n }\n\n return distanceToPoint < distanceThreshold;\n}\n","/* eslint no-loop-func: 0 */ // --> OFF\nimport external from './../../../externalModules.js';\nimport drawHandles from './../../../drawing/drawHandles.js';\nimport updatePerpendicularLineHandles from './utils/updatePerpendicularLineHandles.js';\n\nimport toolStyle from './../../../stateManagement/toolStyle.js';\nimport toolColors from './../../../stateManagement/toolColors.js';\nimport { getToolState } from './../../../stateManagement/toolState.js';\nimport {\n getNewContext,\n draw,\n setShadow,\n drawLine,\n} from './../../../drawing/index.js';\nimport drawLinkedTextBox from './../../../drawing/drawLinkedTextBox.js';\n\nexport default function(evt) {\n const eventData = evt.detail;\n const { element, canvasContext, image } = eventData;\n const { handleRadius, drawHandlesOnHover } = this.configuration;\n\n // If we have no toolData for this element, return immediately as there is nothing to do\n const toolData = getToolState(element, this.name);\n\n if (!toolData) {\n return;\n }\n\n const imagePlane = external.cornerstone.metaData.get(\n 'imagePlaneModule',\n image.imageId\n );\n\n let rowPixelSpacing = image.rowPixelSpacing;\n let colPixelSpacing = image.columnPixelSpacing;\n\n if (imagePlane) {\n rowPixelSpacing =\n imagePlane.rowPixelSpacing || imagePlane.rowImagePixelSpacing;\n colPixelSpacing =\n imagePlane.columnPixelSpacing || imagePlane.colImagePixelSpacing;\n }\n\n // LT-29 Disable Target Measurements when pixel spacing is not available\n if (!rowPixelSpacing || !colPixelSpacing) {\n return;\n }\n\n // We have tool data for this element - iterate over each one and draw it\n const context = getNewContext(canvasContext.canvas);\n\n let color;\n const activeColor = toolColors.getActiveColor();\n const lineWidth = toolStyle.getToolWidth();\n\n for (let i = 0; i < toolData.data.length; i++) {\n const data = toolData.data[i];\n\n if (data.visible === false) {\n continue;\n }\n\n color = data.active ? activeColor : toolColors.getToolColor();\n\n // Calculate the data measurements\n getMeasurementData(data, rowPixelSpacing, colPixelSpacing);\n\n draw(context, context => {\n // Configurable shadow\n setShadow(context, this.configuration);\n\n const {\n start,\n end,\n perpendicularStart,\n perpendicularEnd,\n textBox,\n } = data.handles;\n\n // Draw the measurement line\n drawLine(context, element, start, end, { color });\n\n // Draw perpendicular line\n const strokeWidth = lineWidth;\n\n updatePerpendicularLineHandles(eventData, data);\n drawLine(context, element, perpendicularStart, perpendicularEnd, {\n color,\n strokeWidth,\n });\n\n // Draw the handles\n const handleOptions = {\n color,\n handleRadius,\n drawHandlesIfActive: drawHandlesOnHover,\n };\n\n // Draw the handles\n drawHandles(context, eventData, data.handles, handleOptions);\n\n // Draw the textbox\n // Move the textbox slightly to the right and upwards\n // So that it sits beside the length tool handle\n const xOffset = 10;\n const textBoxAnchorPoints = handles => [\n handles.start,\n handles.end,\n handles.perpendicularStart,\n handles.perpendicularEnd,\n ];\n let textLines = getTextBoxText(data, rowPixelSpacing, colPixelSpacing);\n\n if (data.additionalData && Array.isArray(data.additionalData)) {\n textLines = data.additionalData.concat(textLines);\n }\n\n drawLinkedTextBox(\n context,\n element,\n textBox,\n textLines,\n data.handles,\n textBoxAnchorPoints,\n color,\n lineWidth,\n xOffset,\n true\n );\n });\n }\n}\n\nconst getMeasurementData = (data, rowPixelSpacing, colPixelSpacing) => {\n const { start, end, perpendicularStart, perpendicularEnd } = data.handles;\n // Calculate the long axis length\n const dx = (start.x - end.x) * (colPixelSpacing || 1);\n const dy = (start.y - end.y) * (rowPixelSpacing || 1);\n let length = Math.sqrt(dx * dx + dy * dy);\n\n // Calculate the short axis length\n const wx =\n (perpendicularStart.x - perpendicularEnd.x) * (colPixelSpacing || 1);\n const wy =\n (perpendicularStart.y - perpendicularEnd.y) * (rowPixelSpacing || 1);\n let width = Math.sqrt(wx * wx + wy * wy);\n\n if (!width) {\n width = 0;\n }\n\n // Length is always longer than width\n if (width > length) {\n const tempW = width;\n const tempL = length;\n\n length = tempW;\n width = tempL;\n }\n\n // Set measurement values to be use externaly\n data.longestDiameter = length.toFixed(1);\n data.shortestDiameter = width.toFixed(1);\n};\n\nconst getTextBoxText = (data, rowPixelSpacing, colPixelSpacing) => {\n let suffix = ' mm';\n\n if (!rowPixelSpacing || !colPixelSpacing) {\n suffix = ' pixels';\n }\n\n const lengthText = ` L ${data.longestDiameter}${suffix}`;\n const widthText = ` W ${data.shortestDiameter}${suffix}`;\n\n return [lengthText, widthText];\n};\n","// Update the perpendicular line handles\nexport default function(eventData, data) {\n if (!data.handles.perpendicularStart.locked) {\n return;\n }\n\n let startX, startY, endX, endY;\n\n const { start, end } = data.handles;\n\n if (start.x === end.x && start.y === end.y) {\n startX = start.x;\n startY = start.y;\n endX = end.x;\n endY = end.y;\n } else {\n // Mid point of long-axis line\n const mid = {\n x: (start.x + end.x) / 2,\n y: (start.y + end.y) / 2,\n };\n\n // Length of long-axis\n const dx = (start.x - end.x) * (eventData.image.columnPixelSpacing || 1);\n const dy = (start.y - end.y) * (eventData.image.rowPixelSpacing || 1);\n const length = Math.sqrt(dx * dx + dy * dy);\n\n const vectorX = (start.x - end.x) / length;\n const vectorY = (start.y - end.y) / length;\n\n const perpendicularLineLength = length / 2;\n\n startX = mid.x + (perpendicularLineLength / 2) * vectorY;\n startY = mid.y - (perpendicularLineLength / 2) * vectorX;\n endX = mid.x - (perpendicularLineLength / 2) * vectorY;\n endY = mid.y + (perpendicularLineLength / 2) * vectorX;\n }\n\n data.handles.perpendicularStart.x = startX;\n data.handles.perpendicularStart.y = startY;\n data.handles.perpendicularEnd.x = endX;\n data.handles.perpendicularEnd.y = endY;\n}\n","import external from './../../../externalModules.js';\nimport { moveNewHandle } from './../../../manipulators/index.js';\nimport anyHandlesOutsideImage from './../../../manipulators/anyHandlesOutsideImage.js';\nimport {\n addToolState,\n removeToolState,\n} from './../../../stateManagement/toolState.js';\n\nexport default function(evt, interactionType) {\n const eventData = evt.detail;\n const { element, image } = eventData;\n const config = this.configuration;\n\n if (checkPixelSpacing(image)) {\n return;\n }\n\n const measurementData = this.createNewMeasurement(eventData);\n\n const doneCallback = () => {\n measurementData.active = false;\n external.cornerstone.updateImage(element);\n };\n\n // Associate this data with this imageId so we can render it and manipulate it\n addToolState(element, this.name, measurementData);\n external.cornerstone.updateImage(element);\n\n const timestamp = new Date().getTime();\n const { end, perpendicularStart } = measurementData.handles;\n\n moveNewHandle(\n eventData,\n this.name,\n measurementData,\n end,\n {\n doneMovingCallback: () => {\n const { handles, longestDiameter, shortestDiameter } = measurementData;\n const hasHandlesOutside = anyHandlesOutsideImage(eventData, handles);\n const longestDiameterSize = parseFloat(longestDiameter) || 0;\n const shortestDiameterSize = parseFloat(shortestDiameter) || 0;\n const isTooSmal = longestDiameterSize < 1 || shortestDiameterSize < 1;\n const isTooFast = new Date().getTime() - timestamp < 150;\n\n if (hasHandlesOutside || isTooSmal || isTooFast) {\n // Delete the measurement\n measurementData.cancelled = true;\n removeToolState(element, this.name, measurementData);\n } else {\n // Set lesionMeasurementData Session\n config.getMeasurementLocationCallback(\n measurementData,\n eventData,\n doneCallback\n );\n }\n\n // Perpendicular line is not connected to long-line\n perpendicularStart.locked = false;\n\n external.cornerstone.updateImage(element);\n },\n },\n interactionType\n );\n}\n\nconst checkPixelSpacing = image => {\n const imagePlane = external.cornerstone.metaData.get(\n 'imagePlaneModule',\n image.imageId\n );\n let rowPixelSpacing = image.rowPixelSpacing;\n let colPixelSpacing = image.columnPixelSpacing;\n\n if (imagePlane) {\n rowPixelSpacing =\n imagePlane.rowPixelSpacing || imagePlane.rowImagePixelSpacing;\n colPixelSpacing =\n imagePlane.columnPixelSpacing || imagePlane.colImagePixelSpacing;\n }\n\n // LT-29 Disable Target Measurements when pixel spacing is not available\n return !rowPixelSpacing || !colPixelSpacing;\n};\n","import external from './../../../externalModules.js';\nimport toolCoordinates from './../../../stateManagement/toolCoordinates.js';\nimport getHandleNearImagePoint from './../../../manipulators/getHandleNearImagePoint.js';\nimport { getToolState } from './../../../stateManagement/toolState.js';\n\n// Replaces the cornerstoneTools.handleActivator function by skiping the active handle comparison\nconst handleActivator = (\n element,\n handles,\n canvasPoint,\n distanceThreshold = 6\n) => {\n const nearbyHandle = getHandleNearImagePoint(\n element,\n handles,\n canvasPoint,\n distanceThreshold\n );\n\n let handleActivatorChanged = false;\n\n Object.keys(handles).forEach(handleKey => {\n if (handleKey === 'textBox') {\n return;\n }\n const handle = handles[handleKey];\n const newActiveState = handle === nearbyHandle;\n\n if (handle.active !== newActiveState) {\n handleActivatorChanged = true;\n }\n\n handle.active = newActiveState;\n });\n\n return handleActivatorChanged;\n};\n\n// MouseMoveCallback is used to hide handles when mouse is away\nexport default function(event) {\n const eventData = event.detail;\n const { element } = eventData;\n\n toolCoordinates.setCoords(eventData);\n\n // If we have no tool data for this element, do nothing\n const toolData = getToolState(element, this.name);\n\n if (!toolData) {\n return;\n }\n\n // We have tool data, search through all data and see if we can activate a handle\n let imageNeedsUpdate = false;\n\n for (let i = 0; i < toolData.data.length; i++) {\n // Get the cursor position in canvas coordinates\n const coords = eventData.currentPoints.canvas;\n\n const data = toolData.data[i];\n const handleActivatorChanged = handleActivator(\n element,\n data.handles,\n coords\n );\n\n Object.keys(data.handles).forEach(handleKey => {\n if (handleKey === 'textBox') {\n return;\n }\n const handle = data.handles[handleKey];\n\n handle.hover = handle.active;\n });\n\n if (handleActivatorChanged) {\n imageNeedsUpdate = true;\n }\n\n const nearTool = this.pointNearTool(element, data, coords, 'mouse');\n const nearToolAndInactive = nearTool && !data.active;\n const notNearToolAndActive = !nearTool && data.active;\n\n if (nearToolAndInactive || notNearToolAndActive) {\n data.active = !data.active;\n imageNeedsUpdate = true;\n }\n }\n\n // Handle activation status changed, redraw the image\n if (imageNeedsUpdate === true) {\n external.cornerstone.updateImage(element);\n }\n}\n","import external from './../../../../externalModules.js';\nimport perpendicularBothFixedLeft from './perpendicularBothFixedLeft.js';\nimport perpendicularBothFixedRight from './perpendicularBothFixedRight.js';\nimport perpendicularLeftFixedPoint from './perpendicularLeftFixedPoint.js';\nimport perpendicularRightFixedPoint from './perpendicularRightFixedPoint.js';\n\n// Sets position of handles(start, end, perpendicularStart, perpendicularEnd)\nexport default function(handle, eventData, data, distanceFromTool) {\n let movedPoint;\n let outOfBounds;\n let result;\n let intersection;\n let d1;\n let d2;\n\n const longLine = {};\n const perpendicularLine = {};\n const proposedPoint = {\n x: eventData.currentPoints.image.x + distanceFromTool.x,\n y: eventData.currentPoints.image.y + distanceFromTool.y,\n };\n\n if (handle.index === 0) {\n // If long-axis start point is moved\n result = perpendicularBothFixedLeft(proposedPoint, data);\n if (result) {\n handle.x = proposedPoint.x;\n handle.y = proposedPoint.y;\n } else {\n eventData.currentPoints.image.x = handle.x;\n eventData.currentPoints.image.y = handle.y;\n }\n } else if (handle.index === 1) {\n // If long-axis end point is moved\n result = perpendicularBothFixedRight(proposedPoint, data);\n if (result) {\n handle.x = proposedPoint.x;\n handle.y = proposedPoint.y;\n } else {\n eventData.currentPoints.image.x = handle.x;\n eventData.currentPoints.image.y = handle.y;\n }\n } else if (handle.index === 2) {\n outOfBounds = false;\n // If perpendicular start point is moved\n longLine.start = {\n x: data.handles.start.x,\n y: data.handles.start.y,\n };\n longLine.end = {\n x: data.handles.end.x,\n y: data.handles.end.y,\n };\n\n perpendicularLine.start = {\n x: data.handles.perpendicularEnd.x,\n y: data.handles.perpendicularEnd.y,\n };\n perpendicularLine.end = {\n x: proposedPoint.x,\n y: proposedPoint.y,\n };\n\n intersection = external.cornerstoneMath.lineSegment.intersectLine(\n longLine,\n perpendicularLine\n );\n if (!intersection) {\n perpendicularLine.end = {\n x: data.handles.perpendicularStart.x,\n y: data.handles.perpendicularStart.y,\n };\n\n intersection = external.cornerstoneMath.lineSegment.intersectLine(\n longLine,\n perpendicularLine\n );\n\n d1 = external.cornerstoneMath.point.distance(\n intersection,\n data.handles.start\n );\n d2 = external.cornerstoneMath.point.distance(\n intersection,\n data.handles.end\n );\n\n if (!intersection || d1 < 3 || d2 < 3) {\n outOfBounds = true;\n }\n }\n\n movedPoint = false;\n\n if (!outOfBounds) {\n movedPoint = perpendicularLeftFixedPoint(proposedPoint, data);\n\n if (!movedPoint) {\n eventData.currentPoints.image.x = data.handles.perpendicularStart.x;\n eventData.currentPoints.image.y = data.handles.perpendicularStart.y;\n }\n }\n } else if (handle.index === 3) {\n outOfBounds = false;\n\n // If perpendicular end point is moved\n longLine.start = {\n x: data.handles.start.x,\n y: data.handles.start.y,\n };\n longLine.end = {\n x: data.handles.end.x,\n y: data.handles.end.y,\n };\n\n perpendicularLine.start = {\n x: data.handles.perpendicularStart.x,\n y: data.handles.perpendicularStart.y,\n };\n perpendicularLine.end = {\n x: proposedPoint.x,\n y: proposedPoint.y,\n };\n\n intersection = external.cornerstoneMath.lineSegment.intersectLine(\n longLine,\n perpendicularLine\n );\n if (!intersection) {\n perpendicularLine.end = {\n x: data.handles.perpendicularEnd.x,\n y: data.handles.perpendicularEnd.y,\n };\n\n intersection = external.cornerstoneMath.lineSegment.intersectLine(\n longLine,\n perpendicularLine\n );\n\n d1 = external.cornerstoneMath.point.distance(\n intersection,\n data.handles.start\n );\n d2 = external.cornerstoneMath.point.distance(\n intersection,\n data.handles.end\n );\n\n if (!intersection || d1 < 3 || d2 < 3) {\n outOfBounds = true;\n }\n }\n\n movedPoint = false;\n\n if (!outOfBounds) {\n movedPoint = perpendicularRightFixedPoint(proposedPoint, data);\n\n if (!movedPoint) {\n eventData.currentPoints.image.x = data.handles.perpendicularEnd.x;\n eventData.currentPoints.image.y = data.handles.perpendicularEnd.y;\n }\n }\n }\n}\n","import external from './../../../../externalModules.js';\n\n// Move long-axis start point\nexport default function(proposedPoint, data) {\n const { distance } = external.cornerstoneMath.point;\n const { start, end, perpendicularStart, perpendicularEnd } = data.handles;\n\n const longLine = {\n start: {\n x: start.x,\n y: start.y,\n },\n end: {\n x: end.x,\n y: end.y,\n },\n };\n\n const perpendicularLine = {\n start: {\n x: perpendicularStart.x,\n y: perpendicularStart.y,\n },\n end: {\n x: perpendicularEnd.x,\n y: perpendicularEnd.y,\n },\n };\n\n const intersection = external.cornerstoneMath.lineSegment.intersectLine(\n longLine,\n perpendicularLine\n );\n\n const distanceFromPerpendicularP1 = distance(\n perpendicularStart,\n intersection\n );\n const distanceFromPerpendicularP2 = distance(perpendicularEnd, intersection);\n\n const distanceToLineP2 = distance(end, intersection);\n const newLineLength = distance(end, proposedPoint);\n\n if (newLineLength <= distanceToLineP2) {\n return false;\n }\n\n const dx = (end.x - proposedPoint.x) / newLineLength;\n const dy = (end.y - proposedPoint.y) / newLineLength;\n\n const k = distanceToLineP2 / newLineLength;\n\n const newIntersection = {\n x: end.x + (proposedPoint.x - end.x) * k,\n y: end.y + (proposedPoint.y - end.y) * k,\n };\n\n perpendicularStart.x = newIntersection.x - distanceFromPerpendicularP1 * dy;\n perpendicularStart.y = newIntersection.y + distanceFromPerpendicularP1 * dx;\n\n perpendicularEnd.x = newIntersection.x + distanceFromPerpendicularP2 * dy;\n perpendicularEnd.y = newIntersection.y - distanceFromPerpendicularP2 * dx;\n\n return true;\n}\n","import external from './../../../../externalModules.js';\n\n// Move long-axis end point\nexport default function(proposedPoint, data) {\n const { distance } = external.cornerstoneMath.point;\n const { start, end, perpendicularStart, perpendicularEnd } = data.handles;\n\n const longLine = {\n start: {\n x: start.x,\n y: start.y,\n },\n end: {\n x: end.x,\n y: end.y,\n },\n };\n\n const perpendicularLine = {\n start: {\n x: perpendicularStart.x,\n y: perpendicularStart.y,\n },\n end: {\n x: perpendicularEnd.x,\n y: perpendicularEnd.y,\n },\n };\n\n const intersection = external.cornerstoneMath.lineSegment.intersectLine(\n longLine,\n perpendicularLine\n );\n\n const distanceFromPerpendicularP1 = distance(\n perpendicularStart,\n intersection\n );\n const distanceFromPerpendicularP2 = distance(perpendicularEnd, intersection);\n\n const distanceToLineP2 = distance(start, intersection);\n const newLineLength = distance(start, proposedPoint);\n\n if (newLineLength <= distanceToLineP2) {\n return false;\n }\n\n const dx = (start.x - proposedPoint.x) / newLineLength;\n const dy = (start.y - proposedPoint.y) / newLineLength;\n\n const k = distanceToLineP2 / newLineLength;\n\n const newIntersection = {\n x: start.x + (proposedPoint.x - start.x) * k,\n y: start.y + (proposedPoint.y - start.y) * k,\n };\n\n perpendicularStart.x = newIntersection.x + distanceFromPerpendicularP1 * dy;\n perpendicularStart.y = newIntersection.y - distanceFromPerpendicularP1 * dx;\n\n perpendicularEnd.x = newIntersection.x - distanceFromPerpendicularP2 * dy;\n perpendicularEnd.y = newIntersection.y + distanceFromPerpendicularP2 * dx;\n\n return true;\n}\n","import external from './../../../../externalModules.js';\n\n// Move perpendicular line start point\nexport default function(movedPoint, data) {\n const { distance } = external.cornerstoneMath.point;\n const { start, end, perpendicularStart, perpendicularEnd } = data.handles;\n\n const fudgeFactor = 1;\n const fixedPoint = perpendicularEnd;\n\n const distanceFromFixed = external.cornerstoneMath.lineSegment.distanceToPoint(\n data.handles,\n fixedPoint\n );\n const distanceFromMoved = external.cornerstoneMath.lineSegment.distanceToPoint(\n data.handles,\n movedPoint\n );\n\n const distanceBetweenPoints = distance(fixedPoint, movedPoint);\n\n const total = distanceFromFixed + distanceFromMoved;\n\n if (distanceBetweenPoints <= distanceFromFixed) {\n return false;\n }\n\n const length = distance(start, end);\n\n if (length === 0) {\n return false;\n }\n\n const dx = (start.x - end.x) / length;\n const dy = (start.y - end.y) / length;\n\n const adjustedLineP1 = {\n x: start.x - fudgeFactor * dx,\n y: start.y - fudgeFactor * dy,\n };\n const adjustedLineP2 = {\n x: end.x + fudgeFactor * dx,\n y: end.y + fudgeFactor * dy,\n };\n\n perpendicularStart.x = movedPoint.x;\n perpendicularStart.y = movedPoint.y;\n perpendicularEnd.x = movedPoint.x - total * dy;\n perpendicularEnd.y = movedPoint.y + total * dx;\n\n const longLine = {\n start: {\n x: start.x,\n y: start.y,\n },\n end: {\n x: end.x,\n y: end.y,\n },\n };\n\n const perpendicularLine = {\n start: {\n x: perpendicularStart.x,\n y: perpendicularStart.y,\n },\n end: {\n x: perpendicularEnd.x,\n y: perpendicularEnd.y,\n },\n };\n\n const intersection = external.cornerstoneMath.lineSegment.intersectLine(\n longLine,\n perpendicularLine\n );\n\n if (!intersection) {\n if (distance(movedPoint, start) > distance(movedPoint, end)) {\n perpendicularStart.x = adjustedLineP2.x + distanceFromMoved * dy;\n perpendicularStart.y = adjustedLineP2.y - distanceFromMoved * dx;\n perpendicularEnd.x = perpendicularStart.x - total * dy;\n perpendicularEnd.y = perpendicularStart.y + total * dx;\n } else {\n perpendicularStart.x = adjustedLineP1.x + distanceFromMoved * dy;\n perpendicularStart.y = adjustedLineP1.y - distanceFromMoved * dx;\n perpendicularEnd.x = perpendicularStart.x - total * dy;\n perpendicularEnd.y = perpendicularStart.y + total * dx;\n }\n }\n\n return true;\n}\n","import external from './../../../../externalModules.js';\n\n// Move perpendicular line end point\nexport default function(movedPoint, data) {\n const { distance } = external.cornerstoneMath.point;\n const { start, end, perpendicularStart, perpendicularEnd } = data.handles;\n\n const fudgeFactor = 1;\n\n const fixedPoint = perpendicularStart;\n\n const distanceFromFixed = external.cornerstoneMath.lineSegment.distanceToPoint(\n data.handles,\n fixedPoint\n );\n const distanceFromMoved = external.cornerstoneMath.lineSegment.distanceToPoint(\n data.handles,\n movedPoint\n );\n\n const distanceBetweenPoints = distance(fixedPoint, movedPoint);\n\n const total = distanceFromFixed + distanceFromMoved;\n\n if (distanceBetweenPoints <= distanceFromFixed) {\n return false;\n }\n\n const length = distance(start, end);\n const dx = (start.x - end.x) / length;\n const dy = (start.y - end.y) / length;\n\n const adjustedLineP1 = {\n x: start.x - fudgeFactor * dx,\n y: start.y - fudgeFactor * dy,\n };\n const adjustedLineP2 = {\n x: end.x + fudgeFactor * dx,\n y: end.y + fudgeFactor * dy,\n };\n\n perpendicularStart.x = movedPoint.x + total * dy;\n perpendicularStart.y = movedPoint.y - total * dx;\n perpendicularEnd.x = movedPoint.x;\n perpendicularEnd.y = movedPoint.y;\n perpendicularEnd.locked = false;\n perpendicularStart.locked = false;\n\n const longLine = {\n start: {\n x: start.x,\n y: start.y,\n },\n end: {\n x: end.x,\n y: end.y,\n },\n };\n\n const perpendicularLine = {\n start: {\n x: perpendicularStart.x,\n y: perpendicularStart.y,\n },\n end: {\n x: perpendicularEnd.x,\n y: perpendicularEnd.y,\n },\n };\n\n const intersection = external.cornerstoneMath.lineSegment.intersectLine(\n longLine,\n perpendicularLine\n );\n\n if (!intersection) {\n if (distance(movedPoint, start) > distance(movedPoint, end)) {\n perpendicularEnd.x = adjustedLineP2.x - distanceFromMoved * dy;\n perpendicularEnd.y = adjustedLineP2.y + distanceFromMoved * dx;\n perpendicularStart.x = perpendicularEnd.x + total * dy;\n perpendicularStart.y = perpendicularEnd.y - total * dx;\n } else {\n perpendicularEnd.x = adjustedLineP1.x - distanceFromMoved * dy;\n perpendicularEnd.y = adjustedLineP1.y + distanceFromMoved * dx;\n perpendicularStart.x = perpendicularEnd.x + total * dy;\n perpendicularStart.y = perpendicularEnd.y - total * dx;\n }\n }\n\n return true;\n}\n","const swapAttribute = (a, b, attribute) => {\n const originalA = a[attribute];\n const originalB = b[attribute];\n\n a[attribute] = originalB;\n b[attribute] = originalA;\n};\n\nconst swapHandles = (a, b) => {\n swapAttribute(a, b, 'x');\n swapAttribute(a, b, 'y');\n swapAttribute(a, b, 'moving');\n swapAttribute(a, b, 'hover');\n swapAttribute(a, b, 'active');\n swapAttribute(a, b, 'selected');\n};\n\nexport default function invertHandles(eventData, measurementData, handle) {\n const { rowPixelSpacing, columnPixelSpacing } = eventData.image;\n const { handles } = measurementData;\n const { start, end, perpendicularStart, perpendicularEnd } = handles;\n\n // Calculate the long axis length\n const dx = (start.x - end.x) * (columnPixelSpacing || 1);\n const dy = (start.y - end.y) * (rowPixelSpacing || 1);\n const length = Math.sqrt(dx * dx + dy * dy);\n\n // Calculate the short axis length\n const wx =\n (perpendicularStart.x - perpendicularEnd.x) * (columnPixelSpacing || 1);\n const wy =\n (perpendicularStart.y - perpendicularEnd.y) * (rowPixelSpacing || 1);\n const width = Math.sqrt(wx * wx + wy * wy) || 0;\n\n if (width > length) {\n swapHandles(start, end);\n swapHandles(start, perpendicularStart);\n swapHandles(end, perpendicularEnd);\n\n return Object.values(handles).find(h => h.moving === true);\n }\n\n return handle;\n}\n","/* jshint -W083 */\nimport external from './../../../externalModules.js';\nimport { state } from '../../../store/index.js';\nimport EVENTS from './../../../events.js';\nimport {\n removeToolState,\n getToolState,\n} from './../../../stateManagement/toolState.js';\nimport anyHandlesOutsideImage from './../../../manipulators/anyHandlesOutsideImage.js';\nimport getHandleNearImagePoint from './../../../manipulators/getHandleNearImagePoint.js';\nimport { moveAllHandles } from './../../../manipulators/index.js';\nimport moveHandle from './moveHandle/moveHandle.js';\nimport invertHandles from './invertHandles.js';\n\nexport default function(evt) {\n const eventData = evt.detail;\n\n const { element } = eventData;\n let data;\n\n const distanceThreshold = state.clickProximity;\n\n const handleDoneMove = handle => {\n data.invalidated = true;\n if (anyHandlesOutsideImage(eventData, data.handles)) {\n // Delete the measurement\n removeToolState(element, this.name, data);\n }\n\n // Update the handles to keep selected state\n if (handle) {\n handle.moving = false;\n handle.selected = true;\n }\n\n element.style.cursor = '';\n\n external.cornerstone.updateImage(element);\n element.addEventListener(EVENTS.MOUSE_MOVE, this._moveCallback);\n element.addEventListener(EVENTS.TOUCH_START, this._moveCallback);\n };\n\n const coords = eventData.startPoints.canvas;\n const toolData = getToolState(evt.currentTarget, this.name);\n\n if (!toolData) {\n return;\n }\n\n // Now check to see if there is a handle we can move\n for (let i = 0; i < toolData.data.length; i++) {\n data = toolData.data[i];\n const handleParams = [element, data.handles, coords, distanceThreshold];\n let handle = getHandleNearImagePoint(...handleParams);\n\n if (handle) {\n element.removeEventListener(EVENTS.MOUSE_MOVE, this._moveCallback);\n element.removeEventListener(EVENTS.TOUCH_START, this._moveCallback);\n\n data.active = true;\n\n unselectAllHandles(data.handles);\n handle.moving = true;\n\n // Invert handles if needed\n handle = invertHandles(eventData, data, handle);\n\n /* Hide the cursor to improve precision while resizing the line or set to move\n if dragging text box\n */\n element.style.cursor = handle.hasBoundingBox ? 'move' : 'none';\n\n moveHandle(eventData, this.name, data, handle, () =>\n handleDoneMove(handle)\n );\n\n preventPropagation(evt);\n\n return true;\n }\n }\n\n const getDoneMovingCallback = handles => () => {\n setHandlesMovingState(handles, false);\n handleDoneMove();\n };\n\n for (let i = 0; i < toolData.data.length; i++) {\n data = toolData.data[i];\n if (this.pointNearTool(element, data, coords, 'mouse')) {\n element.removeEventListener(EVENTS.MOUSE_MOVE, this._moveCallback);\n element.removeEventListener(EVENTS.TOUCH_START, this._moveCallback);\n data.active = true;\n\n unselectAllHandles(data.handles);\n setHandlesMovingState(data.handles, true);\n\n const doneMovingCallback = getDoneMovingCallback(data.handles);\n\n moveAllHandles(\n eventData,\n this.name,\n data,\n null,\n {\n deleteIfHandleOutsideImage: true,\n preventHandleOutsideImage: false,\n doneMovingCallback,\n },\n 'mouse'\n );\n\n preventPropagation(evt);\n\n return true;\n }\n }\n}\n\n// Clear the selected state for the given handles object\nconst unselectAllHandles = handles => {\n let imageNeedsUpdate = false;\n\n Object.keys(handles).forEach(handleKey => {\n if (handleKey === 'textBox') {\n return;\n }\n handles[handleKey].selected = false;\n imageNeedsUpdate = handles[handleKey].active || imageNeedsUpdate;\n handles[handleKey].active = false;\n });\n\n return imageNeedsUpdate;\n};\n\nconst setHandlesMovingState = (handles, state) => {\n Object.keys(handles).forEach(handleKey => {\n if (handleKey === 'textBox') {\n return;\n }\n handles[handleKey].moving = state;\n });\n};\n\nconst preventPropagation = evt => {\n evt.stopImmediatePropagation();\n evt.stopPropagation();\n evt.preventDefault();\n};\n","import external from './../../../../externalModules.js';\nimport EVENTS from './../../../../events.js';\nimport setHandlesPosition from './setHandlesPosition.js';\n\nexport default function(\n mouseEventData,\n toolType,\n data,\n handle,\n doneMovingCallback,\n preventHandleOutsideImage\n) {\n const element = mouseEventData.element;\n const distanceFromTool = {\n x: handle.x - mouseEventData.currentPoints.image.x,\n y: handle.y - mouseEventData.currentPoints.image.y,\n };\n\n const _dragCallback = event => {\n const eventData = event.detail;\n\n handle.active = true;\n handle.hasMoved = true;\n\n if (handle.index === undefined || handle.index === null) {\n handle.x = eventData.currentPoints.image.x + distanceFromTool.x;\n handle.y = eventData.currentPoints.image.y + distanceFromTool.y;\n } else {\n setHandlesPosition(handle, eventData, data, distanceFromTool);\n }\n\n if (preventHandleOutsideImage) {\n handle.x = Math.max(handle.x, 0);\n handle.x = Math.min(handle.x, eventData.image.width);\n\n handle.y = Math.max(handle.y, 0);\n handle.y = Math.min(handle.y, eventData.image.height);\n }\n\n external.cornerstone.updateImage(element);\n\n const modifiedEventData = {\n toolType,\n element,\n measurementData: data,\n };\n\n external.cornerstone.triggerEvent(\n element,\n EVENTS.MEASUREMENT_MODIFIED,\n modifiedEventData\n );\n };\n\n element.addEventListener(EVENTS.MOUSE_DRAG, _dragCallback);\n element.addEventListener(EVENTS.TOUCH_DRAG, _dragCallback);\n\n const currentImage = external.cornerstone.getImage(element);\n const imageRenderedHandler = () => {\n const newImage = external.cornerstone.getImage(element);\n\n // Check if the rendered image changed during measurement modifying and stop it if so\n if (newImage.imageId !== currentImage.imageId) {\n interactionEndCallback();\n }\n };\n\n // Bind the event listener for image rendering\n element.addEventListener(\n external.cornerstone.EVENTS.IMAGE_RENDERED,\n imageRenderedHandler\n );\n\n const interactionEndCallback = () => {\n element.removeEventListener(\n external.cornerstone.EVENTS.IMAGE_RENDERED,\n imageRenderedHandler\n );\n\n element.removeEventListener(EVENTS.MOUSE_DRAG, _dragCallback);\n element.removeEventListener(EVENTS.MOUSE_UP, interactionEndCallback);\n element.removeEventListener(EVENTS.MOUSE_CLICK, interactionEndCallback);\n\n element.removeEventListener(EVENTS.TOUCH_DRAG, _dragCallback);\n element.removeEventListener(EVENTS.TOUCH_DRAG_END, interactionEndCallback);\n element.removeEventListener(EVENTS.TAP, interactionEndCallback);\n\n external.cornerstone.updateImage(element);\n\n if (typeof doneMovingCallback === 'function') {\n doneMovingCallback();\n }\n };\n\n element.addEventListener(EVENTS.MOUSE_UP, interactionEndCallback);\n element.addEventListener(EVENTS.MOUSE_CLICK, interactionEndCallback);\n\n element.addEventListener(EVENTS.TOUCH_DRAG_END, interactionEndCallback);\n element.addEventListener(EVENTS.TAP, interactionEndCallback);\n}\n","import external from './../../../../externalModules.js';\nimport EVENTS from './../../../../events.js';\nimport setHandlesPosition from './setHandlesPosition.js';\n\nconst touchEndEvents = [\n EVENTS.TOUCH_END,\n EVENTS.TOUCH_DRAG_END,\n EVENTS.TOUCH_PINCH,\n EVENTS.TOUCH_PRESS,\n EVENTS.TAP,\n];\n\nexport default function(\n mouseEventData,\n toolType,\n data,\n handle,\n doneMovingCallback,\n preventHandleOutsideImage\n) {\n const element = mouseEventData.element;\n const distanceFromTool = {\n x: handle.x - mouseEventData.currentPoints.image.x,\n y: handle.y - mouseEventData.currentPoints.image.y,\n };\n\n const touchDragCallback = event => {\n const eventData = event.detail;\n\n handle.active = true;\n handle.hasMoved = true;\n\n if (handle.index === undefined || handle.index === null) {\n handle.x = eventData.currentPoints.image.x + distanceFromTool.x;\n handle.y = eventData.currentPoints.image.y + distanceFromTool.y;\n } else {\n setHandlesPosition(handle, eventData, data, distanceFromTool);\n }\n\n if (preventHandleOutsideImage) {\n handle.x = Math.max(handle.x, 0);\n handle.x = Math.min(handle.x, eventData.image.width);\n\n handle.y = Math.max(handle.y, 0);\n handle.y = Math.min(handle.y, eventData.image.height);\n }\n\n external.cornerstone.updateImage(element);\n\n const eventType = EVENTS.MEASUREMENT_MODIFIED;\n const modifiedEventData = {\n toolType,\n element,\n measurementData: data,\n };\n\n external.cornerstone.triggerEvent(element, eventType, modifiedEventData);\n };\n\n element.addEventListener(EVENTS.TOUCH_DRAG, touchDragCallback);\n\n const touchEndCallback = () => {\n element.removeEventListener(EVENTS.TOUCH_DRAG, touchDragCallback);\n touchEndEvents.forEach(eventType => {\n element.removeEventListener(eventType, touchEndCallback);\n });\n\n external.cornerstone.updateImage(element);\n\n if (typeof doneMovingCallback === 'function') {\n doneMovingCallback();\n }\n };\n\n touchEndEvents.forEach(eventType => {\n element.addEventListener(eventType, touchEndCallback);\n });\n}\n","/* jshint -W083 */\nimport external from './../../../externalModules.js';\nimport { state } from '../../../store/index.js';\nimport EVENTS from './../../../events.js';\nimport {\n removeToolState,\n getToolState,\n} from './../../../stateManagement/toolState.js';\nimport anyHandlesOutsideImage from './../../../manipulators/anyHandlesOutsideImage.js';\nimport getHandleNearImagePoint from './../../../manipulators/getHandleNearImagePoint.js';\nimport { moveAllHandles } from './../../../manipulators/index.js';\nimport touchMoveHandle from './moveHandle/touchMoveHandle.js';\n\nexport default function(evt) {\n const eventData = evt.detail;\n const { element } = eventData;\n let data;\n\n const distanceThreshold = state.touchProximity;\n\n const handleDoneMove = handle => {\n data.invalidated = true;\n if (anyHandlesOutsideImage(eventData, data.handles)) {\n // Delete the measurement\n removeToolState(element, this.name, data);\n }\n\n // Update the handles to keep selected state\n if (handle) {\n handle.moving = false;\n handle.selected = true;\n }\n\n external.cornerstone.updateImage(element);\n element.addEventListener(EVENTS.TOUCH_DRAG, this._moveCallback);\n };\n\n const coords = eventData.startPoints.canvas;\n const toolData = getToolState(evt.currentTarget, this.name);\n\n if (!toolData) {\n return;\n }\n\n // Now check to see if there is a handle we can move\n for (let i = 0; i < toolData.data.length; i++) {\n data = toolData.data[i];\n const handleParams = [element, data.handles, coords, distanceThreshold];\n const handle = getHandleNearImagePoint(...handleParams);\n\n if (handle) {\n element.removeEventListener(EVENTS.TOUCH_DRAG, this._moveCallback);\n\n data.active = true;\n\n unselectAllHandles(data.handles);\n handle.moving = true;\n touchMoveHandle(eventData, this.name, data, handle, () =>\n handleDoneMove(handle)\n );\n preventPropagation(evt);\n\n return true;\n }\n }\n\n const getDoneMovingCallback = handles => () => {\n setHandlesMovingState(handles, false);\n handleDoneMove();\n };\n\n for (let i = 0; i < toolData.data.length; i++) {\n data = toolData.data[i];\n if (this.pointNearTool(element, data, coords, 'touch')) {\n element.removeEventListener(EVENTS.TOUCH_DRAG, this._moveCallback);\n data.active = true;\n\n unselectAllHandles(data.handles);\n setHandlesMovingState(data.handles, true);\n\n const doneMovingCallback = getDoneMovingCallback(data.handles);\n\n moveAllHandles(\n eventData,\n this.name,\n data,\n null,\n {\n deleteIfHandleOutsideImage: true,\n preventHandleOutsideImage: false,\n doneMovingCallback,\n },\n 'touch'\n );\n\n preventPropagation(evt);\n\n return true;\n }\n }\n}\n\n// Clear the selected state for the given handles object\nconst unselectAllHandles = handles => {\n let imageNeedsUpdate = false;\n\n Object.keys(handles).forEach(handleKey => {\n if (handleKey === 'textBox') {\n return;\n }\n handles[handleKey].selected = false;\n imageNeedsUpdate = handles[handleKey].active || imageNeedsUpdate;\n handles[handleKey].active = false;\n });\n\n return imageNeedsUpdate;\n};\n\nconst setHandlesMovingState = (handles, state) => {\n Object.keys(handles).forEach(handleKey => {\n if (handleKey === 'textBox') {\n return;\n }\n handles[handleKey].moving = state;\n });\n};\n\nconst preventPropagation = evt => {\n evt.stopImmediatePropagation();\n evt.stopPropagation();\n evt.preventDefault();\n};\n","import BaseAnnotationTool from '../base/BaseAnnotationTool.js';\n\nimport createNewMeasurement from './bidirectionalTool/createNewMeasurement.js';\nimport pointNearTool from './bidirectionalTool/pointNearTool.js';\nimport renderToolData from './bidirectionalTool/renderToolData.js';\nimport addNewMeasurement from './bidirectionalTool/addNewMeasurement.js';\nimport _moveCallback from './bidirectionalTool/mouseMoveCallback.js';\nimport preMouseDownCallback from './bidirectionalTool/preMouseDownCallback.js';\nimport preTouchStartCallback from './bidirectionalTool/preTouchStartCallback.js';\n\nconst emptyLocationCallback = (measurementData, eventData, doneCallback) =>\n doneCallback();\n\n/**\n * @public\n * @class BidirectionalTool\n * @memberof Tools.Annotation\n * @classdesc Create and position an annotation that measures the\n * length and width of a region.\n * @extends Tools.Base.BaseAnnotationTool\n */\n\nexport default class BidirectionalTool extends BaseAnnotationTool {\n constructor(configuration = {}) {\n const textBoxConfig = '';\n const shadowConfig = '';\n\n const defaultConfig = {\n name: 'Bidirectional',\n supportedInteractionTypes: ['Mouse', 'Touch'],\n configuration: {\n changeMeasurementLocationCallback: emptyLocationCallback,\n getMeasurementLocationCallback: emptyLocationCallback,\n textBox: textBoxConfig,\n shadow: shadowConfig,\n drawHandlesOnHover: true,\n additionalData: [],\n },\n };\n\n const mergedConfiguration = Object.assign(\n defaultConfig.configuration,\n configuration\n );\n const initialConfiguration = Object.assign(defaultConfig, {\n configuration: mergedConfiguration,\n });\n\n super(initialConfiguration);\n\n this.createNewMeasurement = createNewMeasurement.bind(this);\n this.pointNearTool = pointNearTool.bind(this);\n this.renderToolData = renderToolData.bind(this);\n this.addNewMeasurement = addNewMeasurement.bind(this);\n this._moveCallback = _moveCallback.bind(this);\n\n this.preMouseDownCallback = preMouseDownCallback.bind(this);\n this.preTouchStartCallback = preTouchStartCallback.bind(this);\n }\n}\n","import external from './../../externalModules.js';\nimport BaseAnnotationTool from '../base/BaseAnnotationTool.js';\n// State\nimport textStyle from './../../stateManagement/textStyle.js';\nimport {\n addToolState,\n getToolState,\n} from './../../stateManagement/toolState.js';\nimport toolStyle from './../../stateManagement/toolStyle.js';\nimport toolColors from './../../stateManagement/toolColors.js';\n// Manipulators\nimport { moveNewHandle } from './../../manipulators/index.js';\n// Drawing\nimport {\n getNewContext,\n draw,\n setShadow,\n drawLine,\n} from './../../drawing/index.js';\nimport drawHandles from './../../drawing/drawHandles.js';\nimport drawLinkedTextBox from './../../drawing/drawLinkedTextBox.js';\nimport lineSegDistance from './../../util/lineSegDistance.js';\nimport roundToDecimal from './../../util/roundToDecimal.js';\nimport EVENTS from './../../events.js';\n\n/**\n * @public\n * @class CobbAngleTool\n * @memberof Tools.Annotation\n * @classdesc Tool for measuring the angle between two straight lines.\n * @extends Tools.Base.BaseAnnotationTool\n */\nexport default class CobbAngleTool extends BaseAnnotationTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'CobbAngle',\n supportedInteractionTypes: ['Mouse', 'Touch'],\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n this.hasIncomplete = false;\n }\n\n createNewMeasurement(eventData) {\n // Create the measurement data for this tool with the end handle activated\n this.hasIncomplete = true;\n\n return {\n visible: true,\n active: true,\n color: undefined,\n complete: false,\n value: '',\n handles: {\n start: {\n x: eventData.currentPoints.image.x,\n y: eventData.currentPoints.image.y,\n highlight: true,\n active: false,\n },\n end: {\n x: eventData.currentPoints.image.x,\n y: eventData.currentPoints.image.y,\n highlight: true,\n active: true,\n },\n start2: {\n x: eventData.currentPoints.image.x,\n y: eventData.currentPoints.image.y,\n highlight: true,\n active: false,\n drawnIndependently: true,\n },\n end2: {\n x: eventData.currentPoints.image.x + 1,\n y: eventData.currentPoints.image.y,\n highlight: true,\n active: false,\n drawnIndependently: true,\n },\n textBox: {\n active: false,\n hasMoved: false,\n movesIndependently: false,\n drawnIndependently: true,\n allowedOutsideImage: true,\n hasBoundingBox: true,\n },\n },\n };\n }\n\n /**\n *\n *\n * @param {*} element\n * @param {*} data\n * @param {*} coords\n * @returns {Boolean}\n */\n pointNearTool(element, data, coords) {\n if (data.visible === false) {\n return false;\n }\n\n if (this.hasIncomplete) {\n return false;\n }\n\n return (\n lineSegDistance(element, data.handles.start, data.handles.end, coords) <\n 25 ||\n lineSegDistance(element, data.handles.start2, data.handles.end2, coords) <\n 25\n );\n }\n\n renderToolData(evt) {\n const eventData = evt.detail;\n const { handleRadius, drawHandlesOnHover } = this.configuration;\n // If we have no toolData for this element, return immediately as there is nothing to do\n const toolData = getToolState(evt.currentTarget, this.name);\n\n if (!toolData) {\n return;\n }\n\n // We have tool data for this element - iterate over each one and draw it\n const context = getNewContext(eventData.canvasContext.canvas);\n\n const lineWidth = toolStyle.getToolWidth();\n const font = textStyle.getFont();\n\n for (let i = 0; i < toolData.data.length; i++) {\n const data = toolData.data[i];\n\n if (data.visible === false) {\n continue;\n }\n\n draw(context, context => {\n setShadow(context, this.configuration);\n\n // Differentiate the color of activation tool\n const color = toolColors.getColorIfActive(data);\n\n drawLine(\n context,\n eventData.element,\n data.handles.start,\n data.handles.end,\n {\n color,\n }\n );\n\n if (data.complete) {\n drawLine(\n context,\n eventData.element,\n data.handles.start2,\n data.handles.end2,\n {\n color,\n }\n );\n }\n\n // Draw the handles\n const handleOptions = {\n color,\n handleRadius,\n drawHandlesIfActive: drawHandlesOnHover,\n };\n\n drawHandles(context, eventData, data.handles, handleOptions);\n\n // Draw the text\n context.fillStyle = color;\n\n const text = data.value;\n\n if (!data.handles.textBox.hasMoved) {\n const textCoords = {\n x: (data.handles.start.x + data.handles.end.x) / 2,\n y: (data.handles.start.y + data.handles.end.y) / 2 - 10,\n };\n\n context.font = font;\n data.handles.textBox.x = textCoords.x;\n data.handles.textBox.y = textCoords.y;\n }\n\n drawLinkedTextBox(\n context,\n eventData.element,\n data.handles.textBox,\n text,\n data.handles,\n textBoxAnchorPoints,\n color,\n lineWidth,\n 0,\n true\n );\n });\n }\n\n function textBoxAnchorPoints(handles) {\n return [handles.start, handles.start2, handles.end, handles.end2];\n }\n }\n\n getIncomplete(target) {\n const toolData = getToolState(target, this.name);\n\n if (toolData === undefined) {\n return;\n }\n\n for (let i = 0; i < toolData.data.length; i++) {\n if (toolData.data[i].complete === false) {\n return toolData.data[i];\n }\n }\n }\n\n addNewMeasurement(evt, interactionType) {\n evt.preventDefault();\n evt.stopPropagation();\n\n const eventData = evt.detail;\n\n let measurementData;\n let toMoveHandle;\n\n // Search for incomplete measurements\n const element = evt.detail.element;\n const maybePending = this.getIncomplete(element);\n\n if (maybePending) {\n measurementData = maybePending;\n measurementData.complete = true;\n measurementData.handles.start2 = {\n x: eventData.currentPoints.image.x,\n y: eventData.currentPoints.image.y,\n drawnIndependently: false,\n highlight: true,\n active: false,\n };\n measurementData.handles.end2 = {\n x: eventData.currentPoints.image.x,\n y: eventData.currentPoints.image.y,\n drawnIndependently: false,\n highlight: true,\n active: true,\n };\n toMoveHandle = measurementData.handles.end2;\n this.hasIncomplete = false;\n } else {\n measurementData = this.createNewMeasurement(eventData);\n addToolState(element, this.name, measurementData);\n toMoveHandle = measurementData.handles.end;\n }\n\n // Associate this data with this imageId so we can render it and manipulate it\n external.cornerstone.updateImage(element);\n\n moveNewHandle(\n eventData,\n this.name,\n measurementData,\n toMoveHandle,\n this.options,\n interactionType\n );\n }\n\n onMeasureModified(ev) {\n const image = external.cornerstone.getEnabledElement(ev.detail.element)\n .image;\n\n if (ev.detail.toolName !== this.name) {\n return;\n }\n const data = ev.detail.measurementData;\n\n data.value = calculateValue(data, image);\n\n function calculateValue(data, image) {\n // Default to isotropic pixel size, update suffix to reflect this\n const columnPixelSpacing = image.columnPixelSpacing || 1;\n const rowPixelSpacing = image.rowPixelSpacing || 1;\n\n const dx1 =\n (Math.ceil(data.handles.start.x) - Math.ceil(data.handles.end.x)) *\n columnPixelSpacing;\n const dy1 =\n (Math.ceil(data.handles.start.y) - Math.ceil(data.handles.end.y)) *\n rowPixelSpacing;\n const dx2 =\n (Math.ceil(data.handles.start2.x) - Math.ceil(data.handles.end2.x)) *\n columnPixelSpacing;\n const dy2 =\n (Math.ceil(data.handles.start2.y) - Math.ceil(data.handles.end2.y)) *\n rowPixelSpacing;\n\n let angle = Math.acos(\n Math.abs(\n (dx1 * dx2 + dy1 * dy2) /\n (Math.sqrt(dx1 * dx1 + dy1 * dy1) *\n Math.sqrt(dx2 * dx2 + dy2 * dy2))\n )\n );\n\n angle *= 180 / Math.PI;\n\n const rAngle = roundToDecimal(angle, 2);\n\n if (!Number.isNaN(data.rAngle)) {\n return textBoxText(\n rAngle,\n image.rowPixelSpacing,\n image.columnPixelSpacing\n );\n }\n\n return '';\n }\n\n function textBoxText(rAngle, rowPixelSpacing, columnPixelSpacing) {\n const suffix =\n !rowPixelSpacing || !columnPixelSpacing ? ' (isotropic)' : '';\n const str = '00B0'; // Degrees symbol\n\n return (\n rAngle.toString() + String.fromCharCode(parseInt(str, 16)) + suffix\n );\n }\n }\n\n activeCallback(element) {\n this.onMeasureModified = this.onMeasureModified.bind(this);\n element.addEventListener(\n EVENTS.MEASUREMENT_MODIFIED,\n this.onMeasureModified\n );\n }\n\n passiveCallback(element) {\n this.onMeasureModified = this.onMeasureModified.bind(this);\n element.addEventListener(\n EVENTS.MEASUREMENT_MODIFIED,\n this.onMeasureModified\n );\n }\n\n enabledCallback(element) {\n element.removeEventListener(\n EVENTS.MEASUREMENT_MODIFIED,\n this.onMeasureModified\n );\n }\n\n disabledCallback(element) {\n element.removeEventListener(\n EVENTS.MEASUREMENT_MODIFIED,\n this.onMeasureModified\n );\n }\n}\n","import external from '../externalModules.js';\n\n/**\n * Calculates a Standardized Uptake Value.\n * @export @public @method\n * @name calculateSUV\n *\n * @param {Object} image The image.\n * @param {number} storedPixelValue The raw pixel value.\n * @param {bool} [skipRescale=fale]\n * @returns {number} The SUV.\n */\nexport default function(image, storedPixelValue, skipRescale = false) {\n const cornerstone = external.cornerstone;\n const patientStudyModule = cornerstone.metaData.get(\n 'patientStudyModule',\n image.imageId\n );\n const seriesModule = cornerstone.metaData.get(\n 'generalSeriesModule',\n image.imageId\n );\n\n if (!patientStudyModule || !seriesModule) {\n return;\n }\n\n const modality = seriesModule.modality;\n\n // Image must be PET\n if (modality !== 'PT') {\n return;\n }\n\n const modalityPixelValue = skipRescale\n ? storedPixelValue\n : storedPixelValue * image.slope + image.intercept;\n\n const patientWeight = patientStudyModule.patientWeight; // In kg\n\n if (!patientWeight) {\n return;\n }\n\n const petSequenceModule = cornerstone.metaData.get(\n 'petIsotopeModule',\n image.imageId\n );\n\n if (!petSequenceModule) {\n return;\n }\n\n const radiopharmaceuticalInfo = petSequenceModule.radiopharmaceuticalInfo;\n const startTime = radiopharmaceuticalInfo.radiopharmaceuticalStartTime;\n const totalDose = radiopharmaceuticalInfo.radionuclideTotalDose;\n const halfLife = radiopharmaceuticalInfo.radionuclideHalfLife;\n const seriesAcquisitionTime = seriesModule.seriesTime;\n\n if (!startTime || !totalDose || !halfLife || !seriesAcquisitionTime) {\n return;\n }\n\n const acquisitionTimeInSeconds =\n fracToDec(seriesAcquisitionTime.fractionalSeconds || 0) +\n seriesAcquisitionTime.seconds +\n seriesAcquisitionTime.minutes * 60 +\n seriesAcquisitionTime.hours * 60 * 60;\n const injectionStartTimeInSeconds =\n fracToDec(startTime.fractionalSeconds) +\n startTime.seconds +\n startTime.minutes * 60 +\n startTime.hours * 60 * 60;\n const durationInSeconds =\n acquisitionTimeInSeconds - injectionStartTimeInSeconds;\n const correctedDose =\n totalDose * Math.exp((-durationInSeconds * Math.log(2)) / halfLife);\n const suv = ((modalityPixelValue * patientWeight) / correctedDose) * 1000;\n\n return suv;\n}\n\n/**\n * Returns a decimal value given a fractional value.\n * @private\n * @method\n * @name fracToDec\n *\n * @param {number} fractionalValue The value to convert.\n * @returns {number} The value converted to decimal.\n */\nfunction fracToDec(fractionalValue) {\n return parseFloat(`.${fractionalValue}`);\n}\n","/**\n * Returns true if a point is within an ellipse\n * @export @public @method\n * @name pointInEllipse\n *\n * @param {Object} ellipse Object defining the ellipse.\n * @param {Object} location The location of the point.\n * @returns {boolean} True if the point is within the ellipse.\n */\nexport default function(ellipse, location) {\n const xRadius = ellipse.width / 2;\n const yRadius = ellipse.height / 2;\n\n if (xRadius <= 0.0 || yRadius <= 0.0) {\n return false;\n }\n\n const center = {\n x: ellipse.left + xRadius,\n y: ellipse.top + yRadius,\n };\n\n /* This is a more general form of the circle equation\n *\n * X^2/a^2 + Y^2/b^2 <= 1\n */\n\n const normalized = {\n x: location.x - center.x,\n y: location.y - center.y,\n };\n\n const inEllipse =\n (normalized.x * normalized.x) / (xRadius * xRadius) +\n (normalized.y * normalized.y) / (yRadius * yRadius) <=\n 1.0;\n\n return inEllipse;\n}\n","import pointInEllipse from './pointInEllipse.js';\n\n/**\n * Calculates the statistics of an elliptical region of interest.\n *\n * @private\n * @function calculateEllipseStatistics\n *\n * @param {number[]} sp - Array of the image data's pixel values.\n * @param {Object} ellipse - { top, left, height, width } - An object describing the ellipse.\n * @returns {Object} { count, mean, variance, stdDev, min, max }\n */\nexport default function(sp, ellipse) {\n let sum = 0;\n let sumSquared = 0;\n let count = 0;\n let index = 0;\n let min = null;\n let max = null;\n\n for (let y = ellipse.top; y < ellipse.top + ellipse.height; y++) {\n for (let x = ellipse.left; x < ellipse.left + ellipse.width; x++) {\n const point = {\n x,\n y,\n };\n\n if (pointInEllipse(ellipse, point)) {\n if (min === null) {\n min = sp[index];\n max = sp[index];\n }\n\n sum += sp[index];\n sumSquared += sp[index] * sp[index];\n min = Math.min(min, sp[index]);\n max = Math.max(max, sp[index]);\n count++;\n }\n\n index++;\n }\n }\n\n if (count === 0) {\n return {\n count,\n mean: 0.0,\n variance: 0.0,\n stdDev: 0.0,\n min: 0.0,\n max: 0.0,\n };\n }\n\n const mean = sum / count;\n const variance = sumSquared / count - mean * mean;\n\n return {\n count,\n mean,\n variance,\n stdDev: Math.sqrt(variance),\n min,\n max,\n };\n}\n","import calculateEllipseStatistics from './calculateEllipseStatistics.js';\nimport pointInEllipse from './pointInEllipse.js';\n\n// Named\nexport { calculateEllipseStatistics, pointInEllipse };\n\n// Default\nexport default {\n calculateEllipseStatistics,\n pointInEllipse,\n};\n","/**\n * Converts a number to a string with comma separators.\n * http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript\n * @export @public @method\n * @name numbersWithCommas\n *\n * @param {number} x The number to convert.\n * @returns {string} The pretty-printed number as a string.\n */\nexport default function(x) {\n const parts = x.toString().split('.');\n\n parts[0] = parts[0].replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n\n return parts.join('.');\n}\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * isObject({})\n * // => true\n *\n * isObject([1, 2, 3])\n * // => true\n *\n * isObject(Function)\n * // => true\n *\n * isObject(null)\n * // => false\n */\nfunction isObject(value) {\n const type = typeof value;\n\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","import isObject from './isObject.js';\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked, or until the next browser frame is drawn. The debounced function\n * comes with a `cancel` method to cancel delayed `func` invocations and a\n * `flush` method to immediately invoke them. Provide `options` to indicate\n * whether `func` should be invoked on the leading and/or trailing edge of the\n * `wait` timeout. The `func` is invoked with the last arguments provided to the\n * debounced function. Subsequent calls to the debounced function return the\n * result of the last `func` invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * If `wait` is omitted in an environment with `requestAnimationFrame`, `func`\n * invocation will be deferred until the next frame is drawn (typically about\n * 16ms).\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `debounce` and `throttle`.\n *\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0]\n * The number of milliseconds to delay; if omitted, `requestAnimationFrame` is\n * used (if available).\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', debounce(calculateLayout, 150))\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }))\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * const debounced = debounce(batchLog, 250, { 'maxWait': 1000 })\n * const source = new EventSource('/stream')\n * jQuery(source).on('message', debounced)\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel)\n *\n * // Check for pending invocations.\n * const status = debounced.pending() ? \"Pending...\" : \"Ready\"\n */\nfunction debounce(func, wait, options) {\n let lastArgs, lastThis, maxWait, result, timerId, lastCallTime;\n\n let lastInvokeTime = 0;\n let leading = false;\n let maxing = false;\n let trailing = true;\n\n // Bypass `requestAnimationFrame` by explicitly setting `wait=0`.\n const useRAF =\n !wait && wait !== 0 && typeof window.requestAnimationFrame === 'function';\n\n if (typeof func !== 'function') {\n throw new TypeError('Expected a function');\n }\n wait = Number(wait) || 0;\n if (isObject(options)) {\n leading = Boolean(options.leading);\n maxing = 'maxWait' in options;\n maxWait = maxing ? Math.max(Number(options.maxWait) || 0, wait) : maxWait;\n trailing = 'trailing' in options ? Boolean(options.trailing) : trailing;\n }\n\n function invokeFunc(time) {\n const args = lastArgs;\n const thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n\n return result;\n }\n\n function startTimer(pendingFunc, wait) {\n if (useRAF) {\n return window.requestAnimationFrame(pendingFunc);\n }\n\n return setTimeout(pendingFunc, wait);\n }\n\n function cancelTimer(id) {\n if (useRAF) {\n return window.cancelAnimationFrame(id);\n }\n clearTimeout(id);\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = startTimer(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n const timeSinceLastCall = time - lastCallTime;\n const timeSinceLastInvoke = time - lastInvokeTime;\n const timeWaiting = wait - timeSinceLastCall;\n\n return maxing\n ? Math.min(timeWaiting, maxWait - timeSinceLastInvoke)\n : timeWaiting;\n }\n\n function shouldInvoke(time) {\n const timeSinceLastCall = time - lastCallTime;\n const timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (\n lastCallTime === undefined ||\n timeSinceLastCall >= wait ||\n timeSinceLastCall < 0 ||\n (maxing && timeSinceLastInvoke >= maxWait)\n );\n }\n\n function timerExpired() {\n const time = Date.now();\n\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = startTimer(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n cancelTimer(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(Date.now());\n }\n\n function pending() {\n return timerId !== undefined;\n }\n\n function debounced(...args) {\n const time = Date.now();\n const isInvoking = shouldInvoke(time);\n\n lastArgs = args;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n timerId = startTimer(timerExpired, wait);\n\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = startTimer(timerExpired, wait);\n }\n\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n debounced.pending = pending;\n\n return debounced;\n}\n\nexport default debounce;\n","import debounce from './debounce.js';\nimport isObject from './isObject.js';\n\n/**\n * Creates a throttled function that only invokes `func` at most once per\n * every `wait` milliseconds (or once per browser frame). The throttled function\n * comes with a `cancel` method to cancel delayed `func` invocations and a\n * `flush` method to immediately invoke them. Provide `options` to indicate\n * whether `func` should be invoked on the leading and/or trailing edge of the\n * `wait` timeout. The `func` is invoked with the last arguments provided to the\n * throttled function. Subsequent calls to the throttled function return the\n * result of the last `func` invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the throttled function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * If `wait` is omitted in an environment with `requestAnimationFrame`, `func`\n * invocation will be deferred until the next frame is drawn (typically about\n * 16ms).\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `throttle` and `debounce`.\n *\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to throttle.\n * @param {number} [wait=0]\n * The number of milliseconds to throttle invocations to; if omitted,\n * `requestAnimationFrame` is used (if available).\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=true]\n * Specify invoking on the leading edge of the timeout.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new throttled function.\n * @example\n *\n * // Avoid excessively updating the position while scrolling.\n * jQuery(window).on('scroll', throttle(updatePosition, 100))\n *\n * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.\n * const throttled = throttle(renewToken, 300000, { 'trailing': false })\n * jQuery(element).on('click', throttled)\n *\n * // Cancel the trailing throttled invocation.\n * jQuery(window).on('popstate', throttled.cancel)\n */\nfunction throttle(func, wait, options) {\n let leading = true;\n let trailing = true;\n\n if (typeof func !== 'function') {\n throw new TypeError('Expected a function');\n }\n if (isObject(options)) {\n leading = 'leading' in options ? Boolean(options.leading) : leading;\n trailing = 'trailing' in options ? Boolean(options.trailing) : trailing;\n }\n\n return debounce(func, wait, {\n leading,\n trailing,\n maxWait: wait,\n });\n}\n\nexport default throttle;\n","import external from './../../externalModules.js';\nimport BaseAnnotationTool from '../base/BaseAnnotationTool.js';\n\n// State\nimport { getToolState } from './../../stateManagement/toolState.js';\nimport toolStyle from './../../stateManagement/toolStyle.js';\nimport toolColors from './../../stateManagement/toolColors.js';\n\n// Drawing\nimport {\n getNewContext,\n draw,\n setShadow,\n drawEllipse,\n drawHandles,\n drawLinkedTextBox,\n} from './../../drawing/index.js';\n\n// Util\nimport calculateSUV from './../../util/calculateSUV.js';\nimport {\n pointInEllipse,\n calculateEllipseStatistics,\n} from './../../util/ellipse/index.js';\nimport numbersWithCommas from './../../util/numbersWithCommas.js';\nimport throttle from './../../util/throttle.js';\n\n/**\n * @public\n * @class EllipticalRoiTool\n * @memberof Tools.Annotation\n * @classdesc Tool for drawing elliptical regions of interest, and measuring\n * the statistics of the enclosed pixels.\n * @extends Tools.Base.BaseAnnotationTool\n */\nexport default class EllipticalRoiTool extends BaseAnnotationTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'EllipticalRoi',\n supportedInteractionTypes: ['Mouse', 'Touch'],\n configuration: {\n // showMinMax: false,\n // showHounsfieldUnits: true,\n },\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n this.initialConfiguration = initialConfiguration;\n }\n\n createNewMeasurement(eventData) {\n const goodEventData =\n eventData && eventData.currentPoints && eventData.currentPoints.image;\n\n if (!goodEventData) {\n console.error(\n `required eventData not supplied to tool ${\n this.name\n }'s createNewMeasurement`\n );\n\n return;\n }\n\n return {\n visible: true,\n active: true,\n color: undefined,\n invalidated: true,\n handles: {\n start: {\n x: eventData.currentPoints.image.x,\n y: eventData.currentPoints.image.y,\n highlight: true,\n active: false,\n },\n end: {\n x: eventData.currentPoints.image.x,\n y: eventData.currentPoints.image.y,\n highlight: true,\n active: true,\n },\n textBox: {\n active: false,\n hasMoved: false,\n movesIndependently: false,\n drawnIndependently: true,\n allowedOutsideImage: true,\n hasBoundingBox: true,\n },\n },\n };\n }\n\n pointNearTool(element, data, coords, interactionType) {\n const hasStartAndEndHandles =\n data && data.handles && data.handles.start && data.handles.end;\n const validParameters = hasStartAndEndHandles;\n\n if (!validParameters) {\n console.warn(\n `invalid parameters supplieed to tool ${this.name}'s pointNearTool`\n );\n }\n\n if (!validParameters || data.visible === false) {\n return false;\n }\n\n const distance = interactionType === 'mouse' ? 15 : 25;\n const startCanvas = external.cornerstone.pixelToCanvas(\n element,\n data.handles.start\n );\n const endCanvas = external.cornerstone.pixelToCanvas(\n element,\n data.handles.end\n );\n\n const minorEllipse = {\n left: Math.min(startCanvas.x, endCanvas.x) + distance / 2,\n top: Math.min(startCanvas.y, endCanvas.y) + distance / 2,\n width: Math.abs(startCanvas.x - endCanvas.x) - distance,\n height: Math.abs(startCanvas.y - endCanvas.y) - distance,\n };\n\n const majorEllipse = {\n left: Math.min(startCanvas.x, endCanvas.x) - distance / 2,\n top: Math.min(startCanvas.y, endCanvas.y) - distance / 2,\n width: Math.abs(startCanvas.x - endCanvas.x) + distance,\n height: Math.abs(startCanvas.y - endCanvas.y) + distance,\n };\n\n const pointInMinorEllipse = pointInEllipse(minorEllipse, coords);\n const pointInMajorEllipse = pointInEllipse(majorEllipse, coords);\n\n if (pointInMajorEllipse && !pointInMinorEllipse) {\n return true;\n }\n\n return false;\n }\n\n renderToolData(evt) {\n const toolData = getToolState(evt.currentTarget, this.name);\n\n if (!toolData) {\n return;\n }\n\n const eventData = evt.detail;\n const { image, element } = eventData;\n const lineWidth = toolStyle.getToolWidth();\n const { handleRadius, drawHandlesOnHover } = this.configuration;\n const context = getNewContext(eventData.canvasContext.canvas);\n\n // Meta\n const seriesModule =\n external.cornerstone.metaData.get('generalSeriesModule', image.imageId) ||\n {};\n let imagePlane = external.cornerstone.metaData.get(\n 'imagePlaneModule',\n image.imageId\n );\n\n // Pixel Spacing\n const modality = seriesModule.modality;\n const hasPixelSpacing =\n imagePlane && imagePlane.rowPixelSpacing && imagePlane.columnPixelSpacing;\n\n imagePlane = imagePlane || {};\n const pixelSpacing = {\n rowPixelSpacing: imagePlane.rowPixelSpacing || 1,\n columnPixelSpacing: imagePlane.columnPixelSpacing || 1,\n };\n\n draw(context, context => {\n // If we have tool data for this element - iterate over each set and draw it\n for (let i = 0; i < toolData.data.length; i++) {\n const data = toolData.data[i];\n\n if (data.visible === false) {\n continue;\n }\n\n // Configure\n const color = toolColors.getColorIfActive(data);\n const handleOptions = {\n color,\n handleRadius,\n drawHandlesIfActive: drawHandlesOnHover,\n };\n\n setShadow(context, this.configuration);\n\n // Draw\n drawEllipse(context, element, data.handles.start, data.handles.end, {\n color,\n });\n drawHandles(context, eventData, data.handles, handleOptions);\n\n // Update textbox stats\n if (data.invalidated === true) {\n if (data.cachedStats) {\n _throttledUpdateCachedStats(\n image,\n element,\n data,\n modality,\n pixelSpacing\n );\n } else {\n _updateCachedStats(image, element, data, modality, pixelSpacing);\n }\n }\n\n // Default to textbox on right side of ROI\n if (!data.handles.textBox.hasMoved) {\n data.handles.textBox.x = Math.max(\n data.handles.start.x,\n data.handles.end.x\n );\n data.handles.textBox.y =\n (data.handles.start.y + data.handles.end.y) / 2;\n }\n\n const textBoxAnchorPoints = handles =>\n _findTextBoxAnchorPoints(handles.start, handles.end);\n const textBoxContent = _createTextBoxContent(\n context,\n image.color,\n data.cachedStats,\n modality,\n hasPixelSpacing,\n this.configuration\n );\n\n drawLinkedTextBox(\n context,\n element,\n data.handles.textBox,\n textBoxContent,\n data.handles,\n textBoxAnchorPoints,\n color,\n lineWidth,\n 0,\n true\n );\n }\n });\n }\n}\n\n/**\n *\n */\nconst _throttledUpdateCachedStats = throttle(_updateCachedStats, 110);\n\n/**\n *\n *\n * @param {*} image\n * @param {*} element\n * @param {*} data\n * @param {string} modality\n * @param {*} pixelSpacing\n */\nfunction _updateCachedStats(image, element, data, modality, pixelSpacing) {\n const stats = _calculateStats(\n image,\n element,\n data.handles,\n modality,\n pixelSpacing\n );\n\n data.cachedStats = stats;\n data.invalidated = false;\n}\n\n/**\n *\n *\n * @param {*} startHandle\n * @param {*} endHandle\n * @returns\n */\nfunction _findTextBoxAnchorPoints(startHandle, endHandle) {\n const { left, top, width, height } = _getEllipseImageCoordinates(\n startHandle,\n endHandle\n );\n\n return [\n {\n // Top middle point of ellipse\n x: left + width / 2,\n y: top,\n },\n {\n // Left middle point of ellipse\n x: left,\n y: top + height / 2,\n },\n {\n // Bottom middle point of ellipse\n x: left + width / 2,\n y: top + height,\n },\n {\n // Right middle point of ellipse\n x: left + width,\n y: top + height / 2,\n },\n ];\n}\n\n/**\n *\n *\n * @param {*} context\n * @param {*} isColorImage\n * @param {*} [{ area, mean, stdDev, min, max, meanStdDevSUV }={}]\n * @param {*} modality\n * @param {*} hasPixelSpacing\n * @param {*} [options={}] - { showMinMax, showHounsfieldUnits }\n * @returns\n */\nfunction _createTextBoxContent(\n context,\n isColorImage,\n { area, mean, stdDev, min, max, meanStdDevSUV } = {},\n modality,\n hasPixelSpacing,\n options = {}\n) {\n const showMinMax = options.showMinMax || false;\n const showHounsfieldUnits = options.showHounsfieldUnits !== false;\n const textLines = [];\n\n // Don't display mean/standardDev for color images\n const otherLines = [];\n\n if (!isColorImage) {\n const hasStandardUptakeValues = meanStdDevSUV && meanStdDevSUV.mean !== 0;\n const suffix = modality === 'CT' && showHounsfieldUnits ? ' HU' : '';\n\n let meanString = `Mean: ${numbersWithCommas(mean.toFixed(2))}${suffix}`;\n const stdDevString = `Std Dev: ${numbersWithCommas(\n stdDev.toFixed(2)\n )}${suffix}`;\n\n // If this image has SUV values to display, concatenate them to the text line\n if (hasStandardUptakeValues) {\n const SUVtext = ' SUV: ';\n\n const meanSuvString = `${SUVtext}${numbersWithCommas(\n meanStdDevSUV.mean.toFixed(2)\n )}`;\n const stdDevSuvString = `${SUVtext}${numbersWithCommas(\n meanStdDevSUV.stdDev.toFixed(2)\n )}`;\n\n const targetStringLength = Math.floor(\n context.measureText(`${stdDevString} `).width\n );\n\n while (context.measureText(meanString).width < targetStringLength) {\n meanString += ' ';\n }\n\n otherLines.push(`${meanString}${meanSuvString}`);\n otherLines.push(`${stdDevString} ${stdDevSuvString}`);\n } else {\n otherLines.push(`${meanString} ${stdDevString}`);\n }\n\n if (showMinMax) {\n let minString = `Min: ${min}${suffix}`;\n const maxString = `Max: ${max}${suffix}`;\n const targetStringLength = hasStandardUptakeValues\n ? Math.floor(context.measureText(`${stdDevString} `).width)\n : Math.floor(context.measureText(`${meanString} `).width);\n\n while (context.measureText(minString).width < targetStringLength) {\n minString += ' ';\n }\n\n otherLines.push(`${minString}${maxString}`);\n }\n }\n\n textLines.push(_formatArea(area, hasPixelSpacing));\n otherLines.forEach(x => textLines.push(x));\n\n return textLines;\n}\n\n/**\n *\n *\n * @param {*} area\n * @param {*} hasPixelSpacing\n * @returns\n */\nfunction _formatArea(area, hasPixelSpacing) {\n // This uses Char code 178 for a superscript 2\n const suffix = hasPixelSpacing\n ? ` mm${String.fromCharCode(178)}`\n : ` px${String.fromCharCode(178)}`;\n\n return `Area: ${numbersWithCommas(area.toFixed(2))}${suffix}`;\n}\n\n/**\n *\n *\n * @param {*} image\n * @param {*} element\n * @param {*} handles\n * @param {*} modality\n * @param {*} pixelSpacing\n * @returns\n */\nfunction _calculateStats(image, element, handles, modality, pixelSpacing) {\n // Retrieve the bounds of the ellipse in image coordinates\n const ellipseCoordinates = _getEllipseImageCoordinates(\n handles.start,\n handles.end\n );\n\n // Retrieve the array of pixels that the ellipse bounds cover\n const pixels = external.cornerstone.getPixels(\n element,\n ellipseCoordinates.left,\n ellipseCoordinates.top,\n ellipseCoordinates.width,\n ellipseCoordinates.height\n );\n\n // Calculate the mean & standard deviation from the pixels and the ellipse details\n const ellipseMeanStdDev = calculateEllipseStatistics(\n pixels,\n ellipseCoordinates\n );\n\n let meanStdDevSUV;\n\n if (modality === 'PT') {\n meanStdDevSUV = {\n mean: calculateSUV(image, ellipseMeanStdDev.mean, true) || 0,\n stdDev: calculateSUV(image, ellipseMeanStdDev.stdDev, true) || 0,\n };\n }\n\n // Calculate the image area from the ellipse dimensions and pixel spacing\n const area =\n Math.PI *\n ((ellipseCoordinates.width * (pixelSpacing.columnPixelSpacing || 1)) / 2) *\n ((ellipseCoordinates.height * (pixelSpacing.rowPixelSpacing || 1)) / 2);\n\n return {\n area: area || 0,\n count: ellipseMeanStdDev.count || 0,\n mean: ellipseMeanStdDev.mean || 0,\n variance: ellipseMeanStdDev.variance || 0,\n stdDev: ellipseMeanStdDev.stdDev || 0,\n min: ellipseMeanStdDev.min || 0,\n max: ellipseMeanStdDev.max || 0,\n meanStdDevSUV,\n };\n}\n\n/**\n * Retrieve the bounds of the ellipse in image coordinates\n *\n * @param {*} startHandle\n * @param {*} endHandle\n * @returns\n */\nfunction _getEllipseImageCoordinates(startHandle, endHandle) {\n return {\n left: Math.round(Math.min(startHandle.x, endHandle.x)),\n top: Math.round(Math.min(startHandle.y, endHandle.y)),\n width: Math.round(Math.abs(startHandle.x - endHandle.x)),\n height: Math.round(Math.abs(startHandle.y - endHandle.y)),\n };\n}\n","/**\n * Calculates whether \"location\" is inside the polygon defined by dataHandles\n * by counting the number of times a ray originating from \"point\" crosses the\n * edges of the polygon. Odd === inside, Even === outside.\n * @export @public @method\n * @name pointInFreehand\n *\n * @param {Object} dataHandles Data object associated with the tool.\n * @param {Object} location The coordinates being queried.\n * @returns {boolean} True if the location is inside the polygon defined by dataHandles.\n */\nexport default function(dataHandles, location) {\n let inROI = false;\n\n // Cycle round pairs of points\n let j = dataHandles.length - 1; // The last vertex is the previous one to the first\n\n for (let i = 0; i < dataHandles.length; i++) {\n if (rayFromPointCrosssesLine(location, dataHandles[i], dataHandles[j])) {\n inROI = !inROI;\n }\n\n j = i; // Here j is previous vertex to i\n }\n\n return inROI;\n}\n\n/**\n * Returns true if the y-position yp is enclosed within y-positions y1 and y2.\n * @private\n * @method\n * @name isEnclosedY\n *\n * @param {number} yp The y position of point p.\n * @param {number} y1 The y position of point 1.\n * @param {number} y2 The y position of point 2.\n * @returns {boolean} True if the y-position yp is enclosed within y-positions y1 and y2.\n */\nfunction isEnclosedY(yp, y1, y2) {\n if ((y1 < yp && yp < y2) || (y2 < yp && yp < y1)) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Returns true if the line segment is to the right of the point.\n * @private\n * @method\n * @name isLineRightOfPoint\n *\n * @param {Object} point The point being queried.\n * @param {Object} lp1 The first point of the line segment.\n * @param {Object} lp2 The second point of the line segment.\n * @returns {boolean} True if the line is to the right of the point.\n */\nfunction isLineRightOfPoint(point, lp1, lp2) {\n // If both right of point return true\n if (lp1.x > point.x && lp2.x > point.x) {\n return true;\n }\n\n // Catch when line is vertical.\n if (lp1.x === lp2.x) {\n return point.x < lp1.x;\n }\n\n // Put leftmost point in lp1\n if (lp1.x > lp2.x) {\n const lptemp = lp1;\n\n lp1 = lp2;\n lp2 = lptemp;\n }\n const lPointY = lineSegmentAtPoint(point, lp1, lp2);\n\n // If the lp1.x and lp2.x enclose point.x check gradient of line and see if\n // Point is above or below the line to calculate if it inside.\n if (Math.sign(lPointY.gradient) * point.y > lPointY.value) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Returns the y value of the line segment at the x value of the point.\n * @private\n * @method\n * @name lineSegmentAtPoint\n *\n * @param {Object} point The point being queried.\n * @param {Object} lp1 The first point of the line segment.\n * @param {Object} lp2 The second point of the line segment.\n * @returns {Object} An object containing the y value as well as the gradient of the line segment.\n */\nfunction lineSegmentAtPoint(point, lp1, lp2) {\n const dydx = (lp2.y - lp1.y) / (lp2.x - lp1.x);\n const fx = {\n value: lp1.x + dydx * (point.x - lp1.x),\n gradient: dydx,\n };\n\n return fx;\n}\n\n/**\n * Returns true if a rightwards ray originating from the point crosses the line defined by handleI and handleJ.\n * @private\n * @method\n * @name rayFromPointCrosssesLine\n *\n * @param {Object} point The point being queried.\n * @param {Object} handleI The first handle of the line segment.\n * @param {Object} handleJ The second handle of the line segment.\n * @returns {boolean} True if a rightwards ray originating from the point crosses the line defined by handleI and handleJ.\n */\nfunction rayFromPointCrosssesLine(point, handleI, handleJ) {\n if (\n isEnclosedY(point.y, handleI.y, handleJ.y) &&\n isLineRightOfPoint(point, handleI, handleJ)\n ) {\n return true;\n }\n\n return false;\n}\n","import pointInFreehand from './pointInFreehand.js';\n\n/**\n * Calculates the statistics of all the pixels within the freehand object.\n * @export @public @method\n * @name calculateFreehandStatistics\n *\n * @param {Object} sp An array of the pixel data.\n * @param {Object} boundingBox Rectangular box enclosing the polygon.\n * @param {Object} dataHandles Data object associated with the tool.\n * @returns {Object} Object containing the derived statistics.\n */\nexport default function(sp, boundingBox, dataHandles) {\n const statisticsObj = {\n count: 0,\n mean: 0.0,\n variance: 0.0,\n stdDev: 0.0,\n };\n\n const sum = getSum(sp, boundingBox, dataHandles);\n\n if (sum.count === 0) {\n return statisticsObj;\n }\n\n statisticsObj.count = sum.count;\n statisticsObj.mean = sum.value / sum.count;\n statisticsObj.variance =\n sum.squared / sum.count - statisticsObj.mean * statisticsObj.mean;\n statisticsObj.stdDev = Math.sqrt(statisticsObj.variance);\n\n return statisticsObj;\n}\n\n/**\n * Calculates the sum, squared sum and count of all pixels within the polygon.\n * @private\n * @method\n * @name getSum\n *\n * @param {Object} sp An array of the pixel data.\n * @param {Object} boundingBox Rectangular box enclosing the polygon.\n * @param {Object} dataHandles Data object associated with the tool.\n * @returns {Object} Object containing the sum, squared sum and pixel count.\n */\nfunction getSum(sp, boundingBox, dataHandles) {\n const sum = {\n value: 0,\n squared: 0,\n count: 0,\n };\n let index = 0;\n\n for (let y = boundingBox.top; y < boundingBox.top + boundingBox.height; y++) {\n for (\n let x = boundingBox.left;\n x < boundingBox.left + boundingBox.width;\n x++\n ) {\n const point = {\n x,\n y,\n };\n\n sumPointIfInFreehand(dataHandles, point, sum, sp[index]);\n index++;\n }\n }\n\n return sum;\n}\n\n/**\n * Adds the pixel to the workingSum if it is within the polygon.\n * @private\n * @method sumPointIfInFreehand\n *\n * @param {Object} dataHandles Data object associated with the tool.\n * @param {Object} point The pixel coordinates.\n * @param {Object} workingSum The working sum, squared sum and pixel count.\n * @param {Object} pixelValue The pixel value. // @modifies {workingSum}\n * @returns {undefined}\n */\nfunction sumPointIfInFreehand(dataHandles, point, workingSum, pixelValue) {\n if (pointInFreehand(dataHandles, point)) {\n workingSum.value += pixelValue;\n workingSum.squared += pixelValue * pixelValue;\n workingSum.count++;\n }\n}\n","/**\n * @public\n * @name ClickedLineData\n * @classdesc Creates an object containing information about the clicked line.\n * @property {number} toolIndex ID of the tool that the line corresponds to.\n * @property {Object} handleIndexArray An array of the handle indicies that correspond to the line segment.\n */\nexport default class ClickedLineData {\n /**\n * Constructs an object containing information about the clicked line.\n * @param {number} toolIndex - The ID of the tool the line corresponds to.\n * @param {Object} handleIndexArray - An array of the handle indicies that correspond to the line segment.\n */\n constructor(toolIndex, handleIndexArray) {\n this.toolIndex = toolIndex;\n this.handleIndexArray = handleIndexArray;\n }\n}\n","/**\n * @public\n * @name FreehandHandleData\n * @classdesc Creates a single handle for the freehand tool.\n *\n * @property {number} x The x position.\n * @property {number} y The y position.\n * @property {boolean} highlight Whether the handle should be rendered as the highlighted color.\n * @property {boolean} active Whether the handle is active.\n * @property {Object} lines An array of lines associated with the handle.\n */\nexport default class FreehandHandleData {\n /**\n * Constructs a a single handle for the freehand tool\n *\n * @param {Object} position - The position of the handle.\n * @param {boolean} highlight - whether the handle should be rendered as the highlighted color.\n * @param {boolean} active - whether the handle is active.\n */\n constructor(position, highlight = true, active = true) {\n this.x = position.x;\n this.y = position.y;\n this.highlight = highlight;\n this.active = active;\n this.lines = [];\n }\n}\n","/**\n * Orientation algoritm to determine if two lines cross.\n * Credit and details: geeksforgeeks.org/check-if-two-given-line-segments-intersect/\n */\n\n/**\n * Determines whether a new handle causes an intersection of the lines of the polygon.\n * @public\n * @function newHandle\n *\n * @param {Object} candidateHandle The new handle to check.\n * @param {Object} dataHandles data object associated with the tool.\n * @returns {boolean} - Whether the new line intersects with any other lines of the polygon.\n */\nfunction newHandle(candidateHandle, dataHandles) {\n // Check if the proposed line will intersect any existent line\n const lastHandleId = dataHandles.length - 1;\n const lastHandle = getCoords(dataHandles[lastHandleId]);\n const newHandle = getCoords(candidateHandle);\n\n return doesIntersectOtherLines(dataHandles, lastHandle, newHandle, [\n lastHandleId,\n ]);\n}\n\n/**\n * Checks if the last line of a polygon will intersect the other lines of the polgyon.\n * @public\n * @function end\n *\n * @param {Object} dataHandles data object associated with the tool.\n * @returns {boolean} Whether the last line intersects with any other lines of the polygon.\n */\nfunction end(dataHandles) {\n const lastHandleId = dataHandles.length - 1;\n const lastHandle = getCoords(dataHandles[lastHandleId]);\n const firstHandle = getCoords(dataHandles[0]);\n\n return doesIntersectOtherLines(dataHandles, lastHandle, firstHandle, [\n lastHandleId,\n 0,\n ]);\n}\n\n/**\n * Checks whether the modification of a handle's position causes intersection of the lines of the polygon.\n * @public\n * @method modify\n *\n * @param {Object} dataHandles Data object associated with the tool.\n * @param {number} modifiedHandleId The id of the handle being modified.\n * @returns {boolean} Whether the modfication causes any intersections.\n */\nfunction modify(dataHandles, modifiedHandleId) {\n // Check if the modifiedHandle's previous and next lines will intersect any other line in the polygon\n const modifiedHandle = getCoords(dataHandles[modifiedHandleId]);\n\n // Previous neightbor handle\n let neighborHandleId = modifiedHandleId - 1;\n\n if (modifiedHandleId === 0) {\n neighborHandleId = dataHandles.length - 1;\n }\n\n let neighborHandle = getCoords(dataHandles[neighborHandleId]);\n\n if (\n doesIntersectOtherLines(dataHandles, modifiedHandle, neighborHandle, [\n modifiedHandleId,\n neighborHandleId,\n ])\n ) {\n return true;\n }\n\n // Next neightbor handle\n if (modifiedHandleId === dataHandles.length - 1) {\n neighborHandleId = 0;\n } else {\n neighborHandleId = modifiedHandleId + 1;\n }\n\n neighborHandle = getCoords(dataHandles[neighborHandleId]);\n\n return doesIntersectOtherLines(dataHandles, modifiedHandle, neighborHandle, [\n modifiedHandleId,\n neighborHandleId,\n ]);\n}\n\n/**\n * Checks whether the line (p1,q1) intersects any of the other lines in the polygon.\n * @private\n * @function doesIntersectOtherLines\n *\n * @param {Object} dataHandles Data object associated with the tool.\n * @param {Object} p1 Coordinates of the start of the line.\n * @param {Object} q1 Coordinates of the end of the line.\n * @param {Object} ignoredHandleIds Ids of handles to ignore (i.e. lines that share a vertex with the line being tested).\n * @returns {boolean} Whether the line intersects any of the other lines in the polygon.\n */\nfunction doesIntersectOtherLines(dataHandles, p1, q1, ignoredHandleIds) {\n let j = dataHandles.length - 1;\n\n for (let i = 0; i < dataHandles.length; i++) {\n if (\n ignoredHandleIds.indexOf(i) !== -1 ||\n ignoredHandleIds.indexOf(j) !== -1\n ) {\n j = i;\n continue;\n }\n\n const p2 = getCoords(dataHandles[j]);\n const q2 = getCoords(dataHandles[i]);\n\n if (doesIntersect(p1, q1, p2, q2)) {\n return true;\n }\n\n j = i;\n }\n\n return false;\n}\n\n/**\n * Checks whether the line (p1,q1) intersects the line (p2,q2) via an orientation algorithm.\n * @private\n * @function doesIntersect\n *\n * @param {Object} p1 Coordinates of the start of the line 1.\n * @param {Object} q1 Coordinates of the end of the line 1.\n * @param {Object} p2 Coordinates of the start of the line 2.\n * @param {Object} q2 Coordinates of the end of the line 2.\n * @returns {boolean} Whether lines (p1,q1) and (p2,q2) intersect.\n */\nfunction doesIntersect(p1, q1, p2, q2) {\n let result = false;\n\n const orient = [\n orientation(p1, q1, p2),\n orientation(p1, q1, q2),\n orientation(p2, q2, p1),\n orientation(p2, q2, q1),\n ];\n\n // General Case\n if (orient[0] !== orient[1] && orient[2] !== orient[3]) {\n return true;\n }\n\n // Special Cases\n if (orient[0] === 0 && onSegment(p1, p2, q1)) {\n // If p1, q1 and p2 are colinear and p2 lies on segment p1q1\n result = true;\n } else if (orient[1] === 0 && onSegment(p1, q2, q1)) {\n // If p1, q1 and p2 are colinear and q2 lies on segment p1q1\n result = true;\n } else if (orient[2] === 0 && onSegment(p2, p1, q2)) {\n // If p2, q2 and p1 are colinear and p1 lies on segment p2q2\n result = true;\n } else if (orient[3] === 0 && onSegment(p2, q1, q2)) {\n // If p2, q2 and q1 are colinear and q1 lies on segment p2q2\n result = true;\n }\n\n return result;\n}\n\n/**\n * Returns an object with two properties, x and y, from a heavier FreehandHandleData object.\n * @private\n * @function getCoords\n *\n * @param {Object} dataHandle Data object associated with a single handle in the freehand tool.\n * @returns {Object} An object containing position propeties x and y.\n */\nfunction getCoords(dataHandle) {\n return {\n x: dataHandle.x,\n y: dataHandle.y,\n };\n}\n\n/**\n * Checks the orientation of 3 points.\n * @private\n * @function orientation\n *\n * @param {Object} p First point.\n * @param {Object} q Second point.\n * @param {Object} r Third point.\n * @returns {number} - 0: Colinear, 1: Clockwise, 2: Anticlockwise\n */\nfunction orientation(p, q, r) {\n const orientationValue =\n (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);\n\n if (orientationValue === 0) {\n return 0; // Colinear\n }\n\n return orientationValue > 0 ? 1 : 2;\n}\n\n/**\n * Checks if point q lines on the segment (p,r).\n * @private\n * @function onSegment\n *\n * @param {Object} p Point p.\n * @param {Object} q Point q.\n * @param {Object} r Point r.\n * @returns {boolean} - If q lies on line segment (p,r).\n */\nfunction onSegment(p, q, r) {\n if (\n q.x <= Math.max(p.x, r.x) &&\n q.x >= Math.min(p.x, r.x) &&\n q.y <= Math.max(p.y, r.y) &&\n q.y >= Math.min(p.y, r.y)\n ) {\n return true;\n }\n\n return false;\n}\n\nexport default {\n newHandle,\n end,\n modify,\n};\n","import { getToolState } from '../../stateManagement/toolState.js';\nimport external from '../../externalModules.js';\nimport ClickedLineData from './ClickedLineData.js';\n\nconst distanceThreshold = 10;\n\n/**\n * @public\n * @class FreehandLineFinder\n * @classdesc Class that finds lines of freehand ROIs based on click proximity.\n */\nexport default class FreehandLineFinder {\n /**\n * Creates an instance of FreehandLineFinder.\n * @param {*} eventData - Data object associated with the event.\n * @memberof FreehandLineFinder\n */\n constructor(eventData, toolName) {\n this._eventData = eventData;\n this._toolName = toolName;\n }\n\n /**\n * Looks for lines near the mouse cursor.\n *\n * @public\n * @method\n * @returns {ClickedLineData} Data object corresponding to the clicked line.\n */\n findLine() {\n const closestToolIndex = this.findTool();\n\n if (closestToolIndex === null) {\n return null;\n }\n\n const closeLines = this._getCloseLinesInTool(closestToolIndex);\n\n if (closeLines) {\n const clickedLineData = this._findCorrectLine(\n closestToolIndex,\n closeLines\n );\n\n // Note: clickedLineData may be null if no valid projections are found.\n return clickedLineData;\n }\n\n // Return null if no valid close lines found.\n return null;\n }\n\n /**\n * Looks for tools near the mouse cursor.\n *\n * @public\n * @method\n *\n * @returns {ClickedLineData} Data object corresponding to the clicked line.\n */\n findTool() {\n this._toolData = getToolState(this._eventData.element, this._toolName);\n this._mousePoint = this._eventData.currentPoints.canvas;\n\n if (!this._toolData) {\n return null;\n }\n\n const closestHandle = this._nearestHandleToPointAllTools();\n\n return closestHandle.toolIndex;\n }\n\n /**\n * Finds the nearest handle to the mouse cursor for all tools.\n * @private\n * @method\n * @returns {Object} The handle closest to the point.\n */\n _nearestHandleToPointAllTools() {\n const toolData = this._toolData;\n\n let closestHandle = {\n toolIndex: null,\n handleIndex: null,\n distance: Infinity, // Some large number\n };\n\n for (let toolIndex = 0; toolIndex < toolData.data.length; toolIndex++) {\n const closestHandleForToolI = this._nearestHandleToPoint(toolIndex);\n\n if (closestHandleForToolI === null) {\n continue;\n }\n\n if (closestHandleForToolI.distance < closestHandle.distance) {\n closestHandle = closestHandleForToolI;\n }\n }\n\n return closestHandle;\n }\n\n /**\n * Finds the nearest handle to the mouse cursor for a specific tool.\n * @private\n * @method\n *\n * @param {number} toolIndex The index of the particular freehand tool.\n * @returns {Object} An object containing information about the closest handle.\n */\n _nearestHandleToPoint(toolIndex) {\n const eventData = this._eventData;\n const toolData = this._toolData;\n\n const data = toolData.data[toolIndex];\n\n if (data.handles === undefined) {\n return null;\n }\n\n if (data.visible === false) {\n return null;\n }\n\n const closest = {\n toolIndex,\n handleIndex: null,\n distance: Infinity, // Some large number\n };\n\n for (let i = 0; i < data.handles.length; i++) {\n const handleCanvas = external.cornerstone.pixelToCanvas(\n eventData.element,\n data.handles[i]\n );\n const handleDistanceFromMousePoint = external.cornerstoneMath.point.distance(\n handleCanvas,\n this._mousePoint\n );\n\n if (handleDistanceFromMousePoint < closest.distance) {\n closest.handleIndex = i;\n closest.distance = handleDistanceFromMousePoint;\n }\n }\n\n return closest;\n }\n\n /**\n * Finds all the lines close to the mouse point for a particular tool.\n * @private\n * @method\n *\n * @param {number} toolIndex The index of the particular freehand tool.\n * @returns {Object} An array of lines close to the mouse point.\n */\n _getCloseLinesInTool(toolIndex) {\n const toolData = this._toolData;\n const dataHandles = toolData.data[toolIndex].handles;\n\n const closeLines = [];\n\n for (let i = 0; i < dataHandles.length; i++) {\n const nextIndex = FreehandLineFinder.getNextHandleIndex(\n i,\n dataHandles.length\n );\n const d = this._distanceOfPointfromLine(\n dataHandles[i],\n dataHandles[nextIndex]\n );\n\n if (d < distanceThreshold) {\n closeLines.push([i, nextIndex]);\n }\n }\n\n return closeLines;\n }\n\n /**\n * Finds the line the user clicked on from an array of close lines.\\\n * @private\n * @method\n *\n * @param {number} toolIndex The index of the particular freehand tool.\n * @param {Object} closeLines An array of lines close to the mouse point.\n * @returns {ClickedLineData|null} An instance of ClickedLineData containing information about the line, or null if no line is correct.\n */\n _findCorrectLine(toolIndex, closeLines) {\n // Test if any candidate lines can be projected onto by the mousePoint\n for (let i = 0; i < closeLines.length; i++) {\n if (this._pointProjectsToLineSegment(toolIndex, closeLines[i])) {\n return new ClickedLineData(toolIndex, closeLines[i]);\n }\n }\n\n // No valid line found\n return null;\n }\n\n /**\n * Returns true if the mouse point projects onto the line segment.\n * @private\n * @method\n *\n * @param {number} toolIndex The index of the particular freehand tool.\n * @param {Object} handleIndexArray An array of indicies corresponding to the line segment.\n * @returns {boolean} True if the mouse point projects onto the line segment\n */\n _pointProjectsToLineSegment(toolIndex, handleIndexArray) {\n const eventData = this._eventData;\n const toolData = this._toolData;\n const data = toolData.data[toolIndex];\n\n if (data.handles === undefined) {\n return;\n }\n\n if (data.visible === false) {\n return false;\n }\n\n const handle1 = data.handles[handleIndexArray[0]];\n const handle2 = data.handles[handleIndexArray[1]];\n\n const p = FreehandLineFinder.getCanvasPointsFromHandles(\n handle1,\n handle2,\n eventData.element\n );\n\n const r = FreehandLineFinder.getLineAsVector(p);\n const m = this._getLineOriginToMouseAsVector(p);\n\n // Project vector m onto r to see if the point is within bounds of line segment\n const mProj = (m[0] * r[0] + m[1] * r[1]) / r.magnitude;\n\n if (mProj > 0 && mProj < r.magnitude) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Returns the canvas positions from the handle's pixel positions.\n *\n * @static\n * @public\n * @method\n * @param {FreehandHandleData} handle1 The first handle.\n * @param {FreehandHandleData} handle2 The second handle.\n * @param {Object} element The element on which the handles reside.\n * @returns {Object} An array contsining the handle positions in canvas coordinates.\n */\n static getCanvasPointsFromHandles(handle1, handle2, element) {\n const p = [];\n\n // Point r from left to right so that we only have one orientation to test.\n if (handle1.x < handle2.x) {\n p.push(external.cornerstone.pixelToCanvas(element, handle1));\n p.push(external.cornerstone.pixelToCanvas(element, handle2));\n } else {\n p.push(external.cornerstone.pixelToCanvas(element, handle2));\n p.push(external.cornerstone.pixelToCanvas(element, handle1));\n }\n\n return p;\n }\n\n /**\n * Converts a line segment to a vector.\n *\n * @static\n * @public\n * @method\n * @param {Object} p An array of two points respresenting the line segment.\n * @returns {Object} An array containing the x and y components of the vector, as well as a magnitude property.\n */\n static getLineAsVector(p) {\n const r = [p[1].x - p[0].x, p[1].y - p[0].y];\n\n r.magnitude = external.cornerstoneMath.point.distance(p[0], p[1]);\n\n return r;\n }\n\n /**\n * Constructs a vector from the direction and magnitude of the line from the the line origin to the mouse cursor.\n * @private\n * @method\n *\n * @param {Object} p An array of two points respresenting the line segment.\n * @returns {Object} An array containing the x and y components of the vector.\n */\n _getLineOriginToMouseAsVector(p) {\n const m = [this._mousePoint.x - p[0].x, this._mousePoint.y - p[0].y];\n\n return m;\n }\n\n /**\n * Calculates the perpendicular distance of the mouse cursor from a line segment.\n * @private\n * @method\n *\n * @param {FreehandHandleData} handle1 The first handle.\n * @param {FreehandHandleData} handle2 The first handle.\n * @returns {number} The perpendicular distance of the mouse cursor from the line segment.\n */\n _distanceOfPointfromLine(handle1, handle2) {\n const eventData = this._eventData;\n\n const p1 = external.cornerstone.pixelToCanvas(eventData.element, handle1);\n const p2 = external.cornerstone.pixelToCanvas(eventData.element, handle2);\n const pMouse = this._mousePoint;\n\n // Perpendicular distance of point from line:\n // = 2* area of triangle(p1,p2,pm) / length of triangle's base |p2 - p1|\n const twiceAreaOfTriangle = Math.abs(\n (p2.y - p1.y) * pMouse.x -\n (p2.x - p1.x) * pMouse.y +\n p2.x * p1.y -\n p2.y * p1.x\n );\n const rMagnitude = external.cornerstoneMath.point.distance(p1, p2);\n const d = twiceAreaOfTriangle / rMagnitude;\n\n return d;\n }\n\n /**\n * Gets the next handl index from a cyclical array of points.\n *\n * @static\n * @public\n * @method\n *\n * @param {number} currentIndex The current index.\n * @param {number} length The number of handles in the polygon.\n * @returns {number} The index of the next handle.\n */\n static getNextHandleIndex(currentIndex, length) {\n let nextIndex;\n\n if (currentIndex < length - 1) {\n nextIndex = currentIndex + 1;\n } else {\n nextIndex = 0;\n }\n\n return nextIndex;\n }\n}\n","import calculateFreehandStatistics from './calculateFreehandStatistics.js';\nimport ClickedLineData from './ClickedLineData.js';\nimport freehandArea from './freehandArea.js';\nimport FreehandHandleData from './FreehandHandleData.js';\nimport freehandIntersect from './freehandIntersect.js';\nimport FreehandLineFinder from './FreehandLineFinder.js';\nimport insertOrDelete from './insertOrDelete.js';\nimport pointInFreehand from './pointInFreehand.js';\n\nexport default {\n calculateFreehandStatistics,\n ClickedLineData,\n freehandArea,\n FreehandHandleData,\n freehandIntersect,\n FreehandLineFinder,\n insertOrDelete,\n pointInFreehand,\n};\n","/**\n * Calculates the area of a freehand tool polygon.\n * @export @public @method\n * @name freehandArea\n *\n * @param {Object} dataHandles Data object associated with the tool.\n * @param {Object} scaling Area scaling of image.\n * @returns {number} The area of the polygon.\n */\nexport default function(dataHandles, scaling) {\n let freeHandArea = 0;\n let j = dataHandles.length - 1; // The last vertex is the previous one to the first\n\n scaling = scaling || 1; // If scaling is falsy, set scaling to 1\n\n for (let i = 0; i < dataHandles.length; i++) {\n freeHandArea +=\n (dataHandles[j].x + dataHandles[i].x) *\n (dataHandles[j].y - dataHandles[i].y);\n j = i; // Here j is previous vertex to i\n }\n\n return Math.abs((freeHandArea * scaling) / 2.0);\n}\n","import FreehandLineFinder from './FreehandLineFinder.js';\nimport FreehandHandleData from './FreehandHandleData.js';\nimport { getToolState } from '../../stateManagement/toolState.js';\nimport external from '../../externalModules.js';\n\n/**\n * Inserts or deletes a point from a freehand tool.\n * @export @public @method\n * @name insertOrDelete\n *\n * @param {Object} e The event.\n * @param {Object} nearby Object containing information about a nearby handle.\n */\nexport default function(evt, nearby) {\n const eventData = evt.detail;\n\n if (nearby && nearby.handleNearby !== null) {\n const deleteInfo = {\n toolIndex: nearby.toolIndex,\n handleIndex: nearby.handleNearby,\n };\n\n _deletePoint.call(this, eventData, deleteInfo);\n } else {\n const freehandLineFinder = new FreehandLineFinder(eventData, this.name);\n const insertInfo = freehandLineFinder.findLine();\n\n if (insertInfo) {\n _insertPoint.call(this, eventData, insertInfo);\n }\n }\n}\n\n/**\n * Deletes a point from a freehand tool.\n * @private\n * @method\n *\n * @param {Object} eventData The data object associated with the event.\n * @param {Object} deleteInfo Object containing information about which point to delete.\n */\nfunction _deletePoint(eventData, deleteInfo) {\n const toolData = getToolState(eventData.element, this.name);\n\n if (toolData === undefined) {\n return;\n }\n\n const deleteHandle = deleteInfo.handleIndex;\n const toolIndex = deleteInfo.toolIndex;\n\n // Get the toolData from insertInfo\n const data = toolData.data[toolIndex];\n\n // Only allow delete if > 3 points\n if (data.handles.length <= 3) {\n return;\n }\n\n // Link the line of the previous handle to the one after handles[deleteHandle];\n if (deleteHandle === data.handles.length - 1) {\n data.handles[deleteHandle - 1].lines.pop();\n data.handles[deleteHandle - 1].lines.push(data.handles[0]);\n } else if (deleteHandle === 0) {\n data.handles[data.handles.length - 1].lines.pop();\n data.handles[data.handles.length - 1].lines.push(\n data.handles[deleteHandle + 1]\n );\n } else {\n data.handles[deleteHandle - 1].lines.pop();\n data.handles[deleteHandle - 1].lines.push(data.handles[deleteHandle + 1]);\n }\n\n // Remove the handle\n data.handles.splice(deleteHandle, 1);\n\n data.invalidated = true;\n data.active = true;\n data.highlight = true;\n\n // Force onImageRendered to fire\n external.cornerstone.updateImage(eventData.element);\n}\n\n/**\n * Inserts a new point into a freehand tool.\n * @private\n * @method\n *\n * @param {Object} eventData - The data object associated with the event.\n * @param {Object} insertInfo - Object containing information about where to insert the point.\n */\nfunction _insertPoint(eventData, insertInfo) {\n const toolData = getToolState(eventData.element, this.name);\n\n if (toolData === undefined) {\n return;\n }\n\n // Get the toolData from insertInfo\n const data = toolData.data[insertInfo.toolIndex];\n\n const insertIndex = _getInsertionIndex(insertInfo);\n\n if (insertIndex === Infinity) {\n return;\n }\n\n const handleData = new FreehandHandleData(eventData.currentPoints.image);\n\n // Add the new handle\n data.handles.splice(insertIndex, 0, handleData);\n\n // Add the line from the previous handle to the inserted handle (note the tool is now one increment longer)\n data.handles[insertIndex - 1].lines.pop();\n data.handles[insertIndex - 1].lines.push(eventData.currentPoints.image);\n\n // Add the line from the inserted handle to the handle after\n if (insertIndex === data.handles.length - 1) {\n data.handles[insertIndex].lines.push(data.handles[0]);\n } else {\n data.handles[insertIndex].lines.push(data.handles[insertIndex + 1]);\n }\n\n data.active = true;\n data.highlight = true;\n\n // Force onImageRendered to fire\n data.invalidated = true;\n external.cornerstone.updateImage(eventData.element);\n}\n\n/**\n * Gets the handle index of a tool in which to insert the new point.\n * @private\n * @method\n *\n * @param {Object} insertInfo - Object containing information about where to insert the point.\n */\nfunction _getInsertionIndex(insertInfo) {\n // Get lowest index that isn't zero\n const handleIndexArray = insertInfo.handleIndexArray;\n let insertIndex = Infinity;\n const arrayContainsZero = handleIndexArray.includes(0);\n\n for (let i = 0; i < handleIndexArray.length; i++) {\n const index = handleIndexArray[i];\n\n if (index !== 0 && index < insertIndex) {\n insertIndex = index;\n }\n }\n\n // Treat the special case of handleIndexArray === [0,1] || [1,0]\n if (arrayContainsZero && insertIndex === 1) {\n insertIndex = 0;\n }\n\n // The insertion index shall be just after the lower index\n insertIndex++;\n\n return insertIndex;\n}\n","import EVENTS from './../../events.js';\nimport external from './../../externalModules.js';\nimport BaseAnnotationTool from './../base/BaseAnnotationTool.js';\n// State\nimport {\n addToolState,\n getToolState,\n} from './../../stateManagement/toolState.js';\nimport toolStyle from './../../stateManagement/toolStyle.js';\nimport toolColors from './../../stateManagement/toolColors.js';\nimport { state } from '../../store/index.js';\n// Manipulators\nimport { moveHandleNearImagePoint } from '../../util/findAndMoveHelpers.js';\n// Implementation Logic\nimport pointInsideBoundingBox from '../../util/pointInsideBoundingBox.js';\nimport calculateSUV from '../../util/calculateSUV.js';\nimport numbersWithCommas from '../../util/numbersWithCommas.js';\n\n// Drawing\nimport { getNewContext, draw, drawJoinedLines } from '../../drawing/index.js';\nimport drawLinkedTextBox from '../../drawing/drawLinkedTextBox.js';\nimport drawHandles from '../../drawing/drawHandles.js';\nimport { clipToBox } from '../../util/clip.js';\n\nimport freehandUtils from '../../util/freehand/index.js';\n\nconst {\n insertOrDelete,\n freehandArea,\n calculateFreehandStatistics,\n freehandIntersect,\n FreehandHandleData,\n} = freehandUtils;\n\n/**\n * @public\n * @class FreehandMouseTool\n * @memberof Tools.Annotation\n * @classdesc Tool for drawing arbitrary polygonal regions of interest, and\n * measuring the statistics of the enclosed pixels.\n * @extends Tools.Base.BaseAnnotationTool\n */\nexport default class FreehandMouseTool extends BaseAnnotationTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'FreehandMouse',\n supportedInteractionTypes: ['Mouse'],\n configuration: defaultFreehandConfiguration(),\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n\n this._drawing = false;\n this._dragging = false;\n this._modifying = false;\n\n // Create bound callback functions for private event loops\n this._drawingMouseDownCallback = this._drawingMouseDownCallback.bind(this);\n this._drawingMouseMoveCallback = this._drawingMouseMoveCallback.bind(this);\n this._drawingMouseDragCallback = this._drawingMouseDragCallback.bind(this);\n this._drawingMouseUpCallback = this._drawingMouseUpCallback.bind(this);\n\n this._editMouseUpCallback = this._editMouseUpCallback.bind(this);\n this._editMouseDragCallback = this._editMouseDragCallback.bind(this);\n }\n\n createNewMeasurement(eventData) {\n const goodEventData =\n eventData && eventData.currentPoints && eventData.currentPoints.image;\n\n if (!goodEventData) {\n console.error(\n `required eventData not supplied to tool ${\n this.name\n }'s createNewMeasurement`\n );\n\n return;\n }\n\n const measurementData = {\n visible: true,\n active: true,\n invalidated: true,\n color: undefined,\n handles: [],\n };\n\n measurementData.handles.textBox = {\n active: false,\n hasMoved: false,\n movesIndependently: false,\n drawnIndependently: true,\n allowedOutsideImage: true,\n hasBoundingBox: true,\n };\n\n return measurementData;\n }\n\n /**\n *\n *\n * @param {*} element\n * @param {*} data\n * @param {*} coords\n * @returns {Boolean}\n */\n pointNearTool(element, data, coords) {\n const validParameters = data && data.handles;\n\n if (!validParameters) {\n throw new Error(\n `invalid parameters supplied to tool ${this.name}'s pointNearTool`\n );\n }\n\n if (!validParameters || data.visible === false) {\n return false;\n }\n\n const isPointNearTool = this._pointNearHandle(element, data, coords);\n\n return isPointNearTool !== undefined;\n }\n\n /**\n * @param {*} element\n * @param {*} data\n * @param {*} coords\n * @returns {number} the distance in px from the provided coordinates to the\n * closest rendered portion of the annotation. -1 if the distance cannot be\n * calculated.\n */\n distanceFromPoint(element, data, coords) {\n let distance = Infinity;\n\n for (let i = 0; i < data.handles.length; i++) {\n const distanceI = external.cornerstoneMath.point.distance(\n data.handles[i],\n coords\n );\n\n distance = Math.min(distance, distanceI);\n }\n\n // If an error caused distance not to be calculated, return -1.\n if (distance === Infinity) {\n return -1;\n }\n\n return distance;\n }\n\n /**\n * @param {*} element\n * @param {*} data\n * @param {*} coords\n * @returns {number} the distance in canvas units from the provided coordinates to the\n * closest rendered portion of the annotation. -1 if the distance cannot be\n * calculated.\n */\n distanceFromPointCanvas(element, data, coords) {\n let distance = Infinity;\n\n const canvasCoords = external.cornerstone.pixelToCanvas(element, coords);\n\n const dataHandles = data.handles;\n\n for (let i = 0; i < dataHandles.length; i++) {\n const handleCanvas = external.cornerstone.pixelToCanvas(\n element,\n dataHandles[i]\n );\n\n const distanceI = external.cornerstoneMath.point.distance(\n handleCanvas,\n canvasCoords\n );\n\n distance = Math.min(distance, distanceI);\n }\n\n // If an error caused distance not to be calculated, return -1.\n if (distance === Infinity) {\n return -1;\n }\n\n return distance;\n }\n\n /**\n *\n *\n * @param {*} evt\n * @returns {undefined}\n */\n renderToolData(evt) {\n const eventData = evt.detail;\n\n // If we have no toolState for this element, return immediately as there is nothing to do\n const toolState = getToolState(evt.currentTarget, this.name);\n\n if (!toolState) {\n return;\n }\n\n const image = eventData.image;\n const element = eventData.element;\n const config = this.configuration;\n const seriesModule = external.cornerstone.metaData.get(\n 'generalSeriesModule',\n image.imageId\n );\n let modality;\n\n if (seriesModule) {\n modality = seriesModule.modality;\n }\n\n // We have tool data for this element - iterate over each one and draw it\n const context = getNewContext(eventData.canvasContext.canvas);\n\n const lineWidth = toolStyle.getToolWidth();\n\n for (let i = 0; i < toolState.data.length; i++) {\n const data = toolState.data[i];\n\n if (data.visible === false) {\n continue;\n }\n\n draw(context, context => {\n let color = toolColors.getColorIfActive(data);\n let fillColor;\n\n if (data.active) {\n if (data.handles.invalidHandlePlacement) {\n color = config.invalidColor;\n fillColor = config.invalidColor;\n } else {\n color = toolColors.getColorIfActive(data);\n fillColor = toolColors.getFillColor();\n }\n } else {\n fillColor = toolColors.getToolColor();\n }\n\n if (data.handles.length) {\n for (let j = 0; j < data.handles.length; j++) {\n const points = [...data.handles[j].lines];\n\n if (j === data.handles.length - 1 && !data.polyBoundingBox) {\n // If it's still being actively drawn, keep the last line to\n // The mouse location\n points.push(config.mouseLocation.handles.start);\n }\n drawJoinedLines(\n context,\n eventData.element,\n data.handles[j],\n points,\n { color }\n );\n }\n }\n\n // Draw handles\n\n const options = {\n color,\n fill: fillColor,\n };\n\n if (config.alwaysShowHandles || (data.active && data.polyBoundingBox)) {\n // Render all handles\n options.handleRadius = config.activeHandleRadius;\n drawHandles(context, eventData, data.handles, options);\n }\n\n if (data.canComplete) {\n // Draw large handle at the origin if can complete drawing\n options.handleRadius = config.completeHandleRadius;\n drawHandles(context, eventData, [data.handles[0]], options);\n }\n\n if (data.active && !data.polyBoundingBox) {\n // Draw handle at origin and at mouse if actively drawing\n options.handleRadius = config.activeHandleRadius;\n drawHandles(\n context,\n eventData,\n config.mouseLocation.handles,\n options\n );\n drawHandles(context, eventData, [data.handles[0]], options);\n }\n\n // Define variables for the area and mean/standard deviation\n let area, meanStdDev, meanStdDevSUV;\n\n // Perform a check to see if the tool has been invalidated. This is to prevent\n // Unnecessary re-calculation of the area, mean, and standard deviation if the\n // Image is re-rendered but the tool has not moved (e.g. during a zoom)\n if (data.invalidated === false) {\n // If the data is not invalidated, retrieve it from the toolState\n meanStdDev = data.meanStdDev;\n meanStdDevSUV = data.meanStdDevSUV;\n area = data.area;\n } else if (!data.active) {\n // If the data has been invalidated, and the tool is not currently active,\n // We need to calculate it again.\n\n // Retrieve the bounds of the ROI in image coordinates\n const bounds = {\n left: data.handles[0].x,\n right: data.handles[0].x,\n bottom: data.handles[0].y,\n top: data.handles[0].x,\n };\n\n for (let i = 0; i < data.handles.length; i++) {\n bounds.left = Math.min(bounds.left, data.handles[i].x);\n bounds.right = Math.max(bounds.right, data.handles[i].x);\n bounds.bottom = Math.min(bounds.bottom, data.handles[i].y);\n bounds.top = Math.max(bounds.top, data.handles[i].y);\n }\n\n const polyBoundingBox = {\n left: bounds.left,\n top: bounds.bottom,\n width: Math.abs(bounds.right - bounds.left),\n height: Math.abs(bounds.top - bounds.bottom),\n };\n\n // Store the bounding box information for the text box\n data.polyBoundingBox = polyBoundingBox;\n\n // First, make sure this is not a color image, since no mean / standard\n // Deviation will be calculated for color images.\n if (!image.color) {\n // Retrieve the array of pixels that the ROI bounds cover\n const pixels = external.cornerstone.getPixels(\n element,\n polyBoundingBox.left,\n polyBoundingBox.top,\n polyBoundingBox.width,\n polyBoundingBox.height\n );\n\n // Calculate the mean & standard deviation from the pixels and the object shape\n meanStdDev = calculateFreehandStatistics.call(\n this,\n pixels,\n polyBoundingBox,\n data.handles\n );\n\n if (modality === 'PT') {\n // If the image is from a PET scan, use the DICOM tags to\n // Calculate the SUV from the mean and standard deviation.\n\n // Note that because we are using modality pixel values from getPixels, and\n // The calculateSUV routine also rescales to modality pixel values, we are first\n // Returning the values to storedPixel values before calcuating SUV with them.\n // TODO: Clean this up? Should we add an option to not scale in calculateSUV?\n meanStdDevSUV = {\n mean: calculateSUV(\n image,\n (meanStdDev.mean - image.intercept) / image.slope\n ),\n stdDev: calculateSUV(\n image,\n (meanStdDev.stdDev - image.intercept) / image.slope\n ),\n };\n }\n\n // If the mean and standard deviation values are sane, store them for later retrieval\n if (meanStdDev && !isNaN(meanStdDev.mean)) {\n data.meanStdDev = meanStdDev;\n data.meanStdDevSUV = meanStdDevSUV;\n }\n }\n\n // Retrieve the pixel spacing values, and if they are not\n // Real non-zero values, set them to 1\n const columnPixelSpacing = image.columnPixelSpacing || 1;\n const rowPixelSpacing = image.rowPixelSpacing || 1;\n const scaling = columnPixelSpacing * rowPixelSpacing;\n\n area = freehandArea(data.handles, scaling);\n\n // If the area value is sane, store it for later retrieval\n if (!isNaN(area)) {\n data.area = area;\n }\n\n // Set the invalidated flag to false so that this data won't automatically be recalculated\n data.invalidated = false;\n }\n\n // Only render text if polygon ROI has been completed and freehand 'shiftKey' mode was not used:\n if (data.polyBoundingBox && !data.handles.textBox.freehand) {\n // If the textbox has not been moved by the user, it should be displayed on the right-most\n // Side of the tool.\n if (!data.handles.textBox.hasMoved) {\n // Find the rightmost side of the polyBoundingBox at its vertical center, and place the textbox here\n // Note that this calculates it in image coordinates\n data.handles.textBox.x =\n data.polyBoundingBox.left + data.polyBoundingBox.width;\n data.handles.textBox.y =\n data.polyBoundingBox.top + data.polyBoundingBox.height / 2;\n }\n\n const text = textBoxText.call(this, data);\n\n drawLinkedTextBox(\n context,\n element,\n data.handles.textBox,\n text,\n data.handles,\n textBoxAnchorPoints,\n color,\n lineWidth,\n 0,\n true\n );\n }\n });\n }\n\n function textBoxText(data) {\n const { meanStdDev, meanStdDevSUV, area } = data;\n // Define an array to store the rows of text for the textbox\n const textLines = [];\n\n // If the mean and standard deviation values are present, display them\n if (meanStdDev && meanStdDev.mean !== undefined) {\n // If the modality is CT, add HU to denote Hounsfield Units\n let moSuffix = '';\n\n if (modality === 'CT') {\n moSuffix = ' HU';\n }\n\n // Create a line of text to display the mean and any units that were specified (i.e. HU)\n let meanText = `Mean: ${numbersWithCommas(\n meanStdDev.mean.toFixed(2)\n )}${moSuffix}`;\n // Create a line of text to display the standard deviation and any units that were specified (i.e. HU)\n let stdDevText = `StdDev: ${numbersWithCommas(\n meanStdDev.stdDev.toFixed(2)\n )}${moSuffix}`;\n\n // If this image has SUV values to display, concatenate them to the text line\n if (meanStdDevSUV && meanStdDevSUV.mean !== undefined) {\n const SUVtext = ' SUV: ';\n\n meanText +=\n SUVtext + numbersWithCommas(meanStdDevSUV.mean.toFixed(2));\n stdDevText +=\n SUVtext + numbersWithCommas(meanStdDevSUV.stdDev.toFixed(2));\n }\n\n // Add these text lines to the array to be displayed in the textbox\n textLines.push(meanText);\n textLines.push(stdDevText);\n }\n\n // If the area is a sane value, display it\n if (area) {\n // Determine the area suffix based on the pixel spacing in the image.\n // If pixel spacing is present, use millimeters. Otherwise, use pixels.\n // This uses Char code 178 for a superscript 2\n let suffix = ` mm${String.fromCharCode(178)}`;\n\n if (!image.rowPixelSpacing || !image.columnPixelSpacing) {\n suffix = ` pixels${String.fromCharCode(178)}`;\n }\n\n // Create a line of text to display the area and its units\n const areaText = `Area: ${numbersWithCommas(area.toFixed(2))}${suffix}`;\n\n // Add this text line to the array to be displayed in the textbox\n textLines.push(areaText);\n }\n\n return textLines;\n }\n\n function textBoxAnchorPoints(handles) {\n return handles;\n }\n }\n\n addNewMeasurement(evt) {\n const eventData = evt.detail;\n\n this._drawing = true;\n\n this._startDrawing(eventData);\n this._addPoint(eventData);\n\n preventPropagation(evt);\n }\n\n preMouseDownCallback(evt) {\n const eventData = evt.detail;\n const nearby = this._pointNearHandleAllTools(eventData);\n\n if (eventData.event.ctrlKey) {\n if (nearby !== undefined && nearby.handleNearby.hasBoundingBox) {\n // Ctrl + clicked textBox, do nothing but still consume event.\n } else {\n insertOrDelete.call(this, evt, nearby);\n }\n\n preventPropagation(evt);\n\n return true;\n }\n\n return false;\n }\n\n handleSelectedCallback(evt, toolData, handle, interactionType = 'mouse') {\n const eventData = evt.detail;\n const element = eventData.element;\n\n if (handle.hasBoundingBox) {\n // Use default move handler.\n moveHandleNearImagePoint(evt, this, toolData, handle, interactionType);\n\n return;\n }\n\n const config = this.configuration;\n\n config.dragOrigin = {\n x: handle.x,\n y: handle.y,\n };\n\n // Have to do this to get tool index.\n const nearby = this._pointNearHandleAllTools(eventData);\n const handleNearby = nearby.handleNearby;\n const toolIndex = nearby.toolIndex;\n\n this._modifying = true;\n config.currentHandle = handleNearby;\n config.currentTool = toolIndex;\n\n this._activateModify(element);\n\n // Interupt eventDispatchers\n state.isToolLocked = true;\n\n preventPropagation(evt);\n }\n\n /**\n * Event handler for MOUSE_MOVE during drawing event loop.\n *\n * @event\n * @param {Object} evt - The event.\n * @returns {undefined}\n */\n _drawingMouseMoveCallback(evt) {\n const eventData = evt.detail;\n const element = eventData.element;\n const toolState = getToolState(eventData.element, this.name);\n\n const config = this.configuration;\n const currentTool = config.currentTool;\n\n const data = toolState.data[currentTool];\n const coords = eventData.currentPoints.canvas;\n\n // Set the mouseLocation handle\n this._getMouseLocation(eventData);\n this._checkInvalidHandleLocation(data, eventData);\n\n // Mouse move -> Polygon Mode\n const handleNearby = this._pointNearHandle(element, data, coords);\n\n // If there is a handle nearby to snap to\n // (and it's not the actual mouse handle)\n if (\n handleNearby !== undefined &&\n !handleNearby.hasBoundingBox &&\n handleNearby < data.handles.length - 1\n ) {\n config.mouseLocation.handles.start.x = data.handles[handleNearby].x;\n config.mouseLocation.handles.start.y = data.handles[handleNearby].y;\n }\n\n // Force onImageRendered\n external.cornerstone.updateImage(eventData.element);\n }\n\n /**\n * Event handler for MOUSE_DRAG during drawing event loop.\n *\n * @event\n * @param {Object} evt - The event.\n * @returns {undefined}\n */\n _drawingMouseDragCallback(evt) {\n const eventData = evt.detail;\n const toolState = getToolState(eventData.element, this.name);\n\n const config = this.configuration;\n const currentTool = config.currentTool;\n\n const data = toolState.data[currentTool];\n\n // Set the mouseLocation handle\n this._getMouseLocation(eventData);\n this._checkInvalidHandleLocation(data, eventData);\n this._addPointPencilMode(eventData, data.handles);\n this._dragging = true;\n\n // Force onImageRendered\n external.cornerstone.updateImage(eventData.element);\n }\n\n /**\n * Event handler for MOUSE_UP during drawing event loop.\n *\n * @event\n * @param {Object} evt - The event.\n * @returns {undefined}\n */\n _drawingMouseUpCallback(evt) {\n if (!this._dragging) {\n return;\n }\n\n this._dragging = false;\n\n const eventData = evt.detail;\n const element = eventData.element;\n\n const config = this.configuration;\n const currentTool = config.currentTool;\n const toolState = getToolState(eventData.element, this.name);\n const data = toolState.data[currentTool];\n\n if (!freehandIntersect.end(data.handles) && data.canComplete) {\n const lastHandlePlaced = config.currentHandle;\n\n this._endDrawing(element, lastHandlePlaced);\n }\n\n preventPropagation(evt);\n\n return;\n }\n\n /**\n * Event handler for MOUSE_DOWN during drawing event loop.\n *\n * @event\n * @param {Object} evt - The event.\n * @returns {undefined}\n */\n _drawingMouseDownCallback(evt) {\n const eventData = evt.detail;\n const element = eventData.element;\n const coords = eventData.currentPoints.canvas;\n\n const config = this.configuration;\n const currentTool = config.currentTool;\n const toolState = getToolState(eventData.element, this.name);\n const data = toolState.data[currentTool];\n\n const handleNearby = this._pointNearHandle(element, data, coords);\n\n if (!freehandIntersect.end(data.handles) && data.canComplete) {\n const lastHandlePlaced = config.currentHandle;\n\n this._endDrawing(element, lastHandlePlaced);\n } else if (handleNearby === undefined) {\n this._addPoint(eventData);\n }\n\n preventPropagation(evt);\n\n return;\n }\n\n /**\n * Event handler for MOUSE_DRAG during handle drag event loop.\n *\n * @event\n * @param {Object} evt - The event.\n * @returns {undefined}\n */\n _editMouseDragCallback(evt) {\n const eventData = evt.detail;\n const toolState = getToolState(eventData.element, this.name);\n\n const config = this.configuration;\n const data = toolState.data[config.currentTool];\n const currentHandle = config.currentHandle;\n\n // Set the mouseLocation handle\n this._getMouseLocation(eventData);\n\n data.handles.invalidHandlePlacement = freehandIntersect.modify(\n data.handles,\n currentHandle\n );\n data.active = true;\n data.highlight = true;\n data.handles[currentHandle].x = config.mouseLocation.handles.start.x;\n data.handles[currentHandle].y = config.mouseLocation.handles.start.y;\n\n if (currentHandle !== 0) {\n const lastLineIndex = data.handles[currentHandle - 1].lines.length - 1;\n const lastLine = data.handles[currentHandle - 1].lines[lastLineIndex];\n\n lastLine.x = config.mouseLocation.handles.start.x;\n lastLine.y = config.mouseLocation.handles.start.y;\n }\n\n // Update the image\n external.cornerstone.updateImage(eventData.element);\n }\n\n /**\n * Event handler for MOUSE_UP during handle drag event loop.\n *\n * @private\n * @param {Object} evt - The event.\n * @returns {undefined}\n */\n _editMouseUpCallback(evt) {\n const eventData = evt.detail;\n const element = eventData.element;\n const toolState = getToolState(eventData.element, this.name);\n\n this._deactivateModify(element);\n\n this._dropHandle(eventData, toolState);\n this._endDrawing(element);\n\n state.isToolLocked = false;\n\n external.cornerstone.updateImage(eventData.element);\n }\n\n /**\n * Places a handle of the freehand tool if the new location is valid.\n * If the new location is invalid the handle snaps back to its previous position.\n *\n * @private\n * @param {Object} eventData - Data object associated with the event.\n * @param {Object} toolState - The data associated with the freehand tool.\n * @modifies {toolState}\n * @returns {undefined}\n */\n _dropHandle(eventData, toolState) {\n const config = this.configuration;\n const currentTool = config.currentTool;\n\n const dataHandles = toolState.data[currentTool].handles;\n\n // Don't allow the line being modified to intersect other lines\n if (dataHandles.invalidHandlePlacement) {\n const currentHandle = config.currentHandle;\n const currentHandleData = dataHandles[currentHandle];\n let previousHandleData;\n\n if (currentHandle === 0) {\n const lastHandleID = dataHandles.length - 1;\n\n previousHandleData = dataHandles[lastHandleID];\n } else {\n previousHandleData = dataHandles[currentHandle - 1];\n }\n\n // Snap back to previous position\n currentHandleData.x = config.dragOrigin.x;\n currentHandleData.y = config.dragOrigin.y;\n previousHandleData.lines[0] = currentHandleData;\n\n dataHandles.invalidHandlePlacement = false;\n }\n }\n\n /**\n * Begining of drawing loop when tool is active and a click event happens far\n * from existing handles.\n *\n * @private\n * @param {Object} eventData - data object associated with an event.\n * @returns {undefined}\n */\n _startDrawing(eventData) {\n const measurementData = this.createNewMeasurement(eventData);\n const element = eventData.element;\n const config = this.configuration;\n\n // Block event distpatcher whilst drawing\n state.isToolLocked = true;\n\n this._referencedElement = element;\n\n this._activateDraw(element);\n this._getMouseLocation(eventData);\n\n addToolState(eventData.element, this.name, measurementData);\n\n const toolState = getToolState(eventData.element, this.name);\n\n config.currentTool = toolState.data.length - 1;\n }\n\n /**\n * Adds a point on mouse click in polygon mode.\n *\n * @private\n * @param {Object} eventData - data object associated with an event.\n * @returns {undefined}\n */\n _addPoint(eventData) {\n const toolState = getToolState(eventData.element, this.name);\n\n // Get the toolState from the last-drawn polygon\n const config = this.configuration;\n const data = toolState.data[config.currentTool];\n\n if (data.handles.invalidHandlePlacement) {\n return;\n }\n\n const newHandleData = new FreehandHandleData(eventData.currentPoints.image);\n\n // If this is not the first handle\n if (data.handles.length) {\n // Add the line from the current handle to the new handle\n data.handles[config.currentHandle - 1].lines.push(\n eventData.currentPoints.image\n );\n }\n\n // Add the new handle\n data.handles.push(newHandleData);\n\n // Increment the current handle value\n config.currentHandle += 1;\n\n // Force onImageRendered to fire\n external.cornerstone.updateImage(eventData.element);\n }\n\n /**\n * If in pencilMode, check the mouse position is farther than the minimum\n * distance between points, then add a point.\n *\n * @private\n * @param {Object} eventData - Data object associated with an event.\n * @param {Object} dataHandles - Data object associated with the tool.\n * @returns {undefined}\n */\n _addPointPencilMode(eventData, dataHandles) {\n const config = this.configuration;\n const element = eventData.element;\n const mousePoint = config.mouseLocation.handles.start;\n\n const handleFurtherThanMinimumSpacing = handle =>\n this._isDistanceLargerThanSpacingCanvas(element, handle, mousePoint);\n\n if (dataHandles.every(handleFurtherThanMinimumSpacing)) {\n this._addPoint(eventData);\n }\n }\n\n /**\n * Ends the active drawing loop and completes the polygon.\n *\n * @private\n * @param {Object} element - The element on which the roi is being drawn.\n * @param {Object} handleNearby - the handle nearest to the mouse cursor.\n * @returns {undefined}\n */\n _endDrawing(element, handleNearby) {\n const toolState = getToolState(element, this.name);\n\n const config = this.configuration;\n\n const data = toolState.data[config.currentTool];\n\n data.active = false;\n data.highlight = false;\n data.handles.invalidHandlePlacement = false;\n\n // Connect the end handle to the origin handle\n if (handleNearby !== undefined) {\n data.handles[config.currentHandle - 1].lines.push(data.handles[0]);\n }\n\n if (this._modifying) {\n this._modifying = false;\n data.invalidated = true;\n }\n\n // Reset the current handle\n config.currentHandle = 0;\n config.currentTool = -1;\n data.canComplete = false;\n\n if (this._drawing) {\n this._drawing = false;\n state.isToolLocked = false;\n this._deactivateDraw(element);\n }\n\n external.cornerstone.updateImage(element);\n }\n\n /**\n * Returns a handle of a particular tool if it is close to the mouse cursor\n *\n * @private\n * @param {Object} element - The element on which the roi is being drawn.\n * @param {Object} data Data object associated with the tool.\n * @param {*} coords\n * @returns {Number|Object|Boolean}\n */\n _pointNearHandle(element, data, coords) {\n const config = this.configuration;\n\n if (data.handles === undefined) {\n return;\n }\n\n if (data.visible === false) {\n return;\n }\n\n for (let i = 0; i < data.handles.length; i++) {\n const handleCanvas = external.cornerstone.pixelToCanvas(\n element,\n data.handles[i]\n );\n\n if (\n external.cornerstoneMath.point.distance(handleCanvas, coords) <\n config.spacing\n ) {\n return i;\n }\n }\n\n // Check to see if mouse in bounding box of textbox\n if (data.handles.textBox) {\n if (pointInsideBoundingBox(data.handles.textBox, coords)) {\n return data.handles.textBox;\n }\n }\n }\n\n /**\n * Returns a handle if it is close to the mouse cursor (all tools)\n *\n * @private\n * @param {Object} eventData - data object associated with an event.\n * @returns {Object}\n */\n _pointNearHandleAllTools(eventData) {\n const element = eventData.element;\n const coords = eventData.currentPoints.canvas;\n const toolState = getToolState(element, this.name);\n\n if (!toolState) {\n return;\n }\n\n let handleNearby;\n\n for (let toolIndex = 0; toolIndex < toolState.data.length; toolIndex++) {\n handleNearby = this._pointNearHandle(\n element,\n toolState.data[toolIndex],\n coords\n );\n if (handleNearby !== undefined) {\n return {\n handleNearby,\n toolIndex,\n };\n }\n }\n }\n\n /**\n * Gets the current mouse location and stores it in the configuration object.\n *\n * @private\n * @param {Object} eventData The data assoicated with the event.\n * @returns {undefined}\n */\n _getMouseLocation(eventData) {\n // Set the mouseLocation handle\n const config = this.configuration;\n\n config.mouseLocation.handles.start.x = eventData.currentPoints.image.x;\n config.mouseLocation.handles.start.y = eventData.currentPoints.image.y;\n clipToBox(config.mouseLocation.handles.start, eventData.image);\n }\n\n /**\n * Returns true if the proposed location of a new handle is invalid.\n *\n * @private\n * @param {Object} data Data object associated with the tool.\n * @param {Object} eventData The data assoicated with the event.\n * @returns {Boolean}\n */\n _checkInvalidHandleLocation(data, eventData) {\n if (data.handles.length < 2) {\n return true;\n }\n\n let invalidHandlePlacement;\n\n if (this._dragging) {\n invalidHandlePlacement = this._checkHandlesPencilMode(data, eventData);\n } else {\n invalidHandlePlacement = this._checkHandlesPolygonMode(data, eventData);\n }\n\n data.handles.invalidHandlePlacement = invalidHandlePlacement;\n }\n\n /**\n * Returns true if the proposed location of a new handle is invalid (in polygon mode).\n *\n * @private\n *\n * @param {Object} data - data object associated with the tool.\n * @param {Object} eventData The data assoicated with the event.\n * @returns {Boolean}\n */\n _checkHandlesPolygonMode(data, eventData) {\n const config = this.configuration;\n const element = eventData.element;\n const mousePoint = config.mouseLocation.handles.start;\n const dataHandles = data.handles;\n let invalidHandlePlacement = false;\n\n data.canComplete = false;\n\n const mouseAtOriginHandle = this._isDistanceSmallerThanSpacingCanvas(\n element,\n dataHandles[0],\n mousePoint\n );\n\n if (mouseAtOriginHandle && !freehandIntersect.end(dataHandles)) {\n data.canComplete = true;\n invalidHandlePlacement = false;\n } else {\n invalidHandlePlacement = freehandIntersect.newHandle(\n mousePoint,\n dataHandles\n );\n }\n\n return invalidHandlePlacement;\n }\n\n /**\n * Returns true if the proposed location of a new handle is invalid (in pencilMode).\n *\n * @private\n * @param {Object} data - data object associated with the tool.\n * @param {Object} eventData The data associated with the event.\n * @returns {Boolean}\n */\n _checkHandlesPencilMode(data, eventData) {\n const config = this.configuration;\n const mousePoint = config.mouseLocation.handles.start;\n const dataHandles = data.handles;\n let invalidHandlePlacement = freehandIntersect.newHandle(\n mousePoint,\n dataHandles\n );\n\n if (invalidHandlePlacement === false) {\n invalidHandlePlacement = this._invalidHandlePencilMode(data, eventData);\n }\n\n return invalidHandlePlacement;\n }\n\n /**\n * Returns true if the mouse position is far enough from previous points (in pencilMode).\n *\n * @private\n * @param {Object} data - data object associated with the tool.\n * @param {Object} eventData The data associated with the event.\n * @returns {Boolean}\n */\n _invalidHandlePencilMode(data, eventData) {\n const config = this.configuration;\n const element = eventData.element;\n const mousePoint = config.mouseLocation.handles.start;\n const dataHandles = data.handles;\n\n const mouseAtOriginHandle = this._isDistanceSmallerThanSpacingCanvas(\n element,\n dataHandles[0],\n mousePoint\n );\n\n if (mouseAtOriginHandle) {\n data.canComplete = true;\n\n return false;\n }\n\n data.canComplete = false;\n\n // Compare with all other handles appart from the last one\n for (let i = 1; i < dataHandles.length - 1; i++) {\n if (\n this._isDistanceSmallerThanSpacingCanvas(\n element,\n dataHandles[i],\n mousePoint\n )\n ) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Returns true if two points are closer than this.configuration.spacing.\n *\n * @private\n * @param {Object} element The element on which the roi is being drawn.\n * @param {Object} p1 The first point, in pixel space.\n * @param {Object} p2 The second point, in pixel space.\n * @returns {boolean} True if the distance is smaller than the\n * allowed canvas spacing.\n */\n _isDistanceSmallerThanSpacingCanvas(element, p1, p2) {\n return this._compareDistanceToSpacingCanvas(element, p1, p2, '<');\n }\n\n /**\n * Returns true if two points are farther than this.configuration.spacing.\n *\n * @private\n * @param {Object} element The element on which the roi is being drawn.\n * @param {Object} p1 The first point, in pixel space.\n * @param {Object} p2 The second point, in pixel space.\n * @returns {boolean} True if the distance is smaller than the\n * allowed canvas spacing.\n */\n _isDistanceLargerThanSpacingCanvas(element, p1, p2) {\n return this._compareDistanceToSpacingCanvas(element, p1, p2, '>');\n }\n\n /**\n * Compares the distance between two points to this.configuration.spacing.\n *\n * @private\n * @param {Object} element The element on which the roi is being drawn.\n * @param {Object} p1 The first point, in pixel space.\n * @param {Object} p2 The second point, in pixel space.\n * @param {string} comparison The comparison to make.\n * @returns {boolean} True if the distance is smaller than the\n * allowed canvas spacing.\n */\n _compareDistanceToSpacingCanvas(element, p1, p2, comparison = '>') {\n const config = this.configuration;\n\n const p1Canvas = external.cornerstone.pixelToCanvas(element, p1);\n const p2Canvas = external.cornerstone.pixelToCanvas(element, p2);\n\n let result;\n\n if (comparison === '>') {\n result =\n external.cornerstoneMath.point.distance(p1Canvas, p2Canvas) >\n config.spacing;\n } else {\n result =\n external.cornerstoneMath.point.distance(p1Canvas, p2Canvas) <\n config.spacing;\n }\n\n return result;\n }\n\n /**\n * Adds drawing loop event listeners.\n *\n * @private\n * @param {Object} element - The viewport element to add event listeners to.\n * @modifies {element}\n * @returns {undefined}\n */\n _activateDraw(element) {\n // Polygonal Mode\n element.addEventListener(EVENTS.MOUSE_DOWN, this._drawingMouseDownCallback);\n element.addEventListener(EVENTS.MOUSE_MOVE, this._drawingMouseMoveCallback);\n\n // Drag/Pencil Mode\n element.addEventListener(EVENTS.MOUSE_DRAG, this._drawingMouseDragCallback);\n element.addEventListener(EVENTS.MOUSE_UP, this._drawingMouseUpCallback);\n\n external.cornerstone.updateImage(element);\n }\n\n /**\n * Removes drawing loop event listeners.\n *\n * @private\n * @param {Object} element - The viewport element to add event listeners to.\n * @modifies {element}\n * @returns {undefined}\n */\n _deactivateDraw(element) {\n element.removeEventListener(\n EVENTS.MOUSE_DOWN,\n this._drawingMouseDownCallback\n );\n element.removeEventListener(\n EVENTS.MOUSE_MOVE,\n this._drawingMouseMoveCallback\n );\n element.removeEventListener(\n EVENTS.MOUSE_DRAG,\n this._drawingMouseDragCallback\n );\n element.removeEventListener(EVENTS.MOUSE_UP, this._drawingMouseUpCallback);\n\n external.cornerstone.updateImage(element);\n }\n\n /**\n * Adds modify loop event listeners.\n *\n * @private\n * @param {Object} element - The viewport element to add event listeners to.\n * @modifies {element}\n * @returns {undefined}\n */\n _activateModify(element) {\n element.addEventListener(EVENTS.MOUSE_UP, this._editMouseUpCallback);\n element.addEventListener(EVENTS.MOUSE_DRAG, this._editMouseDragCallback);\n element.addEventListener(EVENTS.MOUSE_CLICK, this._editMouseUpCallback);\n\n external.cornerstone.updateImage(element);\n }\n\n /**\n * Removes modify loop event listeners.\n *\n * @private\n * @param {Object} element - The viewport element to add event listeners to.\n * @modifies {element}\n * @returns {undefined}\n */\n _deactivateModify(element) {\n element.removeEventListener(EVENTS.MOUSE_UP, this._editMouseUpCallback);\n element.removeEventListener(EVENTS.MOUSE_DRAG, this._editMouseDragCallback);\n element.removeEventListener(EVENTS.MOUSE_CLICK, this._editMouseUpCallback);\n\n external.cornerstone.updateImage(element);\n }\n\n passiveCallback(element) {\n this._closeToolIfDrawing(element);\n }\n\n enabledCallback(element) {\n this._closeToolIfDrawing(element);\n }\n\n disabledCallback(element) {\n this._closeToolIfDrawing(element);\n }\n\n _closeToolIfDrawing(element) {\n if (this._drawing) {\n // Actively drawing but changed mode.\n const config = this.configuration;\n const lastHandlePlaced = config.currentHandle;\n\n this._endDrawing(element, lastHandlePlaced);\n external.cornerstone.updateImage(element);\n }\n }\n\n // ===================================================================\n // Public Configuration API. .\n // ===================================================================\n\n get spacing() {\n return this.configuration.spacing;\n }\n\n set spacing(value) {\n if (typeof value !== 'number') {\n throw new Error(\n 'Attempting to set freehand spacing to a value other than a number.'\n );\n }\n\n this.configuration.spacing = value;\n external.cornerstone.updateImage(this.element);\n }\n\n get activeHandleRadius() {\n return this.configuration.activeHandleRadius;\n }\n\n set activeHandleRadius(value) {\n if (typeof value !== 'number') {\n throw new Error(\n 'Attempting to set freehand activeHandleRadius to a value other than a number.'\n );\n }\n\n this.configuration.activeHandleRadius = value;\n external.cornerstone.updateImage(this.element);\n }\n\n get completeHandleRadius() {\n return this.configuration.completeHandleRadius;\n }\n\n set completeHandleRadius(value) {\n if (typeof value !== 'number') {\n throw new Error(\n 'Attempting to set freehand completeHandleRadius to a value other than a number.'\n );\n }\n\n this.configuration.completeHandleRadius = value;\n external.cornerstone.updateImage(this.element);\n }\n\n get alwaysShowHandles() {\n return this.configuration.alwaysShowHandles;\n }\n\n set alwaysShowHandles(value) {\n if (typeof value !== 'boolean') {\n throw new Error(\n 'Attempting to set freehand alwaysShowHandles to a value other than a boolean.'\n );\n }\n\n this.configuration.alwaysShowHandles = value;\n external.cornerstone.updateImage(this.element);\n }\n\n get invalidColor() {\n return this.configuration.invalidColor;\n }\n\n set invalidColor(value) {\n /*\n It'd be easy to check if the color was e.g. a valid rgba color. However\n it'd be difficult to check if the color was a named CSS color without\n bloating the library, so we don't. If the canvas can't intepret the color\n it'll show up grey.\n */\n\n this.configuration.invalidColor = value;\n external.cornerstone.updateImage(this.element);\n }\n}\n\nfunction defaultFreehandConfiguration() {\n return {\n mouseLocation: {\n handles: {\n start: {\n highlight: true,\n active: true,\n },\n },\n },\n spacing: 5,\n activeHandleRadius: 3,\n completeHandleRadius: 6,\n alwaysShowHandles: false,\n invalidColor: 'crimson',\n currentHandle: 0,\n currentTool: -1,\n };\n}\n\nfunction preventPropagation(evt) {\n evt.stopImmediatePropagation();\n evt.stopPropagation();\n evt.preventDefault();\n}\n","import external from './../../externalModules.js';\nimport BaseAnnotationTool from '../base/BaseAnnotationTool.js';\n// State\nimport { getToolState } from './../../stateManagement/toolState.js';\nimport toolStyle from './../../stateManagement/toolStyle.js';\nimport toolColors from './../../stateManagement/toolColors.js';\n// Drawing\nimport {\n getNewContext,\n draw,\n setShadow,\n drawLine,\n} from './../../drawing/index.js';\nimport drawLinkedTextBox from './../../drawing/drawLinkedTextBox.js';\nimport drawHandles from './../../drawing/drawHandles.js';\nimport lineSegDistance from './../../util/lineSegDistance.js';\n\n/**\n * @public\n * @class LengthTool\n * @memberof Tools.Annotation\n * @classdesc Tool for measuring distances.\n * @extends Tools.Base.BaseAnnotationTool\n */\nexport default class LengthTool extends BaseAnnotationTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'Length',\n supportedInteractionTypes: ['Mouse', 'Touch'],\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n }\n\n createNewMeasurement(eventData) {\n const goodEventData =\n eventData && eventData.currentPoints && eventData.currentPoints.image;\n\n if (!goodEventData) {\n console.error(\n `required eventData not supplied to tool ${\n this.name\n }'s createNewMeasurement`\n );\n\n return;\n }\n\n const { x, y } = eventData.currentPoints.image;\n\n return {\n visible: true,\n active: true,\n color: undefined,\n handles: {\n start: {\n x,\n y,\n highlight: true,\n active: false,\n },\n end: {\n x,\n y,\n highlight: true,\n active: true,\n },\n textBox: {\n active: false,\n hasMoved: false,\n movesIndependently: false,\n drawnIndependently: true,\n allowedOutsideImage: true,\n hasBoundingBox: true,\n },\n },\n };\n }\n\n /**\n *\n *\n * @param {*} element\n * @param {*} data\n * @param {*} coords\n * @returns {Boolean}\n */\n pointNearTool(element, data, coords) {\n const hasStartAndEndHandles =\n data && data.handles && data.handles.start && data.handles.end;\n const validParameters = hasStartAndEndHandles;\n\n if (!validParameters) {\n console.warn(\n `invalid parameters supplieed to tool ${this.name}'s pointNearTool`\n );\n }\n\n if (!validParameters || data.visible === false) {\n return false;\n }\n\n return (\n lineSegDistance(element, data.handles.start, data.handles.end, coords) <\n 25\n );\n }\n\n renderToolData(evt) {\n const eventData = evt.detail;\n const { handleRadius, drawHandlesOnHover } = this.configuration;\n const toolData = getToolState(evt.currentTarget, this.name);\n\n if (!toolData) {\n return;\n }\n\n // We have tool data for this element - iterate over each one and draw it\n const context = getNewContext(eventData.canvasContext.canvas);\n const { image, element } = eventData;\n\n const lineWidth = toolStyle.getToolWidth();\n const imagePlane = external.cornerstone.metaData.get(\n 'imagePlaneModule',\n image.imageId\n );\n let rowPixelSpacing;\n let colPixelSpacing;\n\n if (imagePlane) {\n rowPixelSpacing =\n imagePlane.rowPixelSpacing || imagePlane.rowImagePixelSpacing;\n colPixelSpacing =\n imagePlane.columnPixelSpacing || imagePlane.colImagePixelSpacing;\n } else {\n rowPixelSpacing = image.rowPixelSpacing;\n colPixelSpacing = image.columnPixelSpacing;\n }\n\n for (let i = 0; i < toolData.data.length; i++) {\n const data = toolData.data[i];\n\n if (data.visible === false) {\n continue;\n }\n\n draw(context, context => {\n // Configurable shadow\n setShadow(context, this.configuration);\n\n const color = toolColors.getColorIfActive(data);\n\n // Draw the measurement line\n drawLine(context, element, data.handles.start, data.handles.end, {\n color,\n });\n\n // Draw the handles\n const handleOptions = {\n color,\n handleRadius,\n drawHandlesIfActive: drawHandlesOnHover,\n };\n\n drawHandles(context, eventData, data.handles, handleOptions);\n\n // Set rowPixelSpacing and columnPixelSpacing to 1 if they are undefined (or zero)\n const dx =\n (data.handles.end.x - data.handles.start.x) * (colPixelSpacing || 1);\n const dy =\n (data.handles.end.y - data.handles.start.y) * (rowPixelSpacing || 1);\n\n // Calculate the length, and create the text variable with the millimeters or pixels suffix\n const length = Math.sqrt(dx * dx + dy * dy);\n\n // Store the length inside the tool for outside access\n data.length = length;\n\n if (!data.handles.textBox.hasMoved) {\n const coords = {\n x: Math.max(data.handles.start.x, data.handles.end.x),\n };\n\n // Depending on which handle has the largest x-value,\n // Set the y-value for the text box\n if (coords.x === data.handles.start.x) {\n coords.y = data.handles.start.y;\n } else {\n coords.y = data.handles.end.y;\n }\n\n data.handles.textBox.x = coords.x;\n data.handles.textBox.y = coords.y;\n }\n\n // Move the textbox slightly to the right and upwards\n // So that it sits beside the length tool handle\n const xOffset = 10;\n\n const text = textBoxText(data, rowPixelSpacing, colPixelSpacing);\n\n drawLinkedTextBox(\n context,\n element,\n data.handles.textBox,\n text,\n data.handles,\n textBoxAnchorPoints,\n color,\n lineWidth,\n xOffset,\n true\n );\n });\n }\n\n function textBoxText(data, rowPixelSpacing, colPixelSpacing) {\n // Set the length text suffix depending on whether or not pixelSpacing is available\n let suffix = ' mm';\n\n if (!rowPixelSpacing || !colPixelSpacing) {\n suffix = ' pixels';\n }\n\n return `${data.length.toFixed(2)}${suffix}`;\n }\n\n function textBoxAnchorPoints(handles) {\n const midpoint = {\n x: (handles.start.x + handles.end.x) / 2,\n y: (handles.start.y + handles.end.y) / 2,\n };\n\n return [handles.start, midpoint, handles.end];\n }\n }\n}\n","import external from '../externalModules.js';\n\n/**\n * Gets pixels of an RGB image.\n * @export @public @method\n * @name getRGBPixels\n *\n * @param {HTMLElement} element The element.\n * @param {number} x The x position of the top-left corner of the region.\n * @param {number} y The y position of the top-left corner of the region.\n * @param {number} width The width of the region.\n * @param {number} height The height of the region\n * @returns {number[]} The pixel data.\n */\nexport default function(element, x, y, width, height) {\n if (!element) {\n throw new Error('getRGBPixels: parameter element must not be undefined');\n }\n\n x = Math.round(x);\n y = Math.round(y);\n const enabledElement = external.cornerstone.getEnabledElement(element);\n const storedPixelData = [];\n let index = 0;\n const pixelData = enabledElement.image.getPixelData();\n let spIndex, row, column;\n\n if (enabledElement.image.color) {\n for (row = 0; row < height; row++) {\n for (column = 0; column < width; column++) {\n spIndex = ((row + y) * enabledElement.image.columns + (column + x)) * 4;\n const red = pixelData[spIndex];\n const green = pixelData[spIndex + 1];\n const blue = pixelData[spIndex + 2];\n const alpha = pixelData[spIndex + 3];\n\n storedPixelData[index++] = red;\n storedPixelData[index++] = green;\n storedPixelData[index++] = blue;\n storedPixelData[index++] = alpha;\n }\n }\n }\n\n return storedPixelData;\n}\n","import external from './../../externalModules.js';\nimport BaseAnnotationTool from '../base/BaseAnnotationTool.js';\n// State\nimport { getToolState } from './../../stateManagement/toolState.js';\nimport textStyle from './../../stateManagement/textStyle.js';\nimport toolColors from './../../stateManagement/toolColors.js';\n// Drawing\nimport { getNewContext, draw } from './../../drawing/index.js';\nimport drawTextBox from './../../drawing/drawTextBox.js';\nimport drawHandles from './../../drawing/drawHandles.js';\n// Utilities\nimport getRGBPixels from './../../util/getRGBPixels.js';\nimport calculateSUV from './../../util/calculateSUV.js';\n\n/**\n * @public\n * @class ProbeTool\n * @memberof Tools.Annotation\n * @classdesc Tool which provides a probe of the image data at the\n * desired position.\n * @extends Tools.Base.BaseAnnotationTool\n */\nexport default class ProbeTool extends BaseAnnotationTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'Probe',\n supportedInteractionTypes: ['Mouse', 'Touch'],\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n }\n\n createNewMeasurement(eventData) {\n const goodEventData =\n eventData && eventData.currentPoints && eventData.currentPoints.image;\n\n if (!goodEventData) {\n console.error(\n `required eventData not supplieed to tool ${\n this.name\n }'s createNewMeasurement`\n );\n\n return;\n }\n\n return {\n visible: true,\n active: true,\n color: undefined,\n handles: {\n end: {\n x: eventData.currentPoints.image.x,\n y: eventData.currentPoints.image.y,\n highlight: true,\n active: true,\n },\n },\n };\n }\n\n /**\n *\n *\n * @param {*} element\n * @param {*} data\n * @param {*} coords\n * @returns {Boolean}\n */\n pointNearTool(element, data, coords) {\n const hasEndHandle = data && data.handles && data.handles.end;\n const validParameters = hasEndHandle;\n\n if (!validParameters) {\n console.warn(\n `invalid parameters supplieed to tool ${this.name}'s pointNearTool`\n );\n }\n\n if (!validParameters || data.visible === false) {\n return false;\n }\n\n const probeCoords = external.cornerstone.pixelToCanvas(\n element,\n data.handles.end\n );\n\n return external.cornerstoneMath.point.distance(probeCoords, coords) < 5;\n }\n\n renderToolData(evt) {\n const eventData = evt.detail;\n const { handleRadius } = this.configuration;\n const toolData = getToolState(evt.currentTarget, this.name);\n\n if (!toolData) {\n return;\n }\n\n // We have tool data for this element - iterate over each one and draw it\n const context = getNewContext(eventData.canvasContext.canvas);\n const { image } = eventData;\n const fontHeight = textStyle.getFontSize();\n\n for (let i = 0; i < toolData.data.length; i++) {\n const data = toolData.data[i];\n\n if (data.visible === false) {\n continue;\n }\n\n draw(context, context => {\n const color = toolColors.getColorIfActive(data);\n\n // Draw the handles\n drawHandles(context, eventData, data.handles, {\n handleRadius,\n color,\n });\n\n const x = Math.round(data.handles.end.x);\n const y = Math.round(data.handles.end.y);\n let storedPixels;\n\n let text, str;\n\n if (x >= 0 && y >= 0 && x < image.columns && y < image.rows) {\n text = `${x}, ${y}`;\n\n if (image.color) {\n storedPixels = getRGBPixels(eventData.element, x, y, 1, 1);\n str = `R: ${storedPixels[0]} G: ${storedPixels[1]} B: ${\n storedPixels[2]\n }`;\n } else {\n storedPixels = external.cornerstone.getStoredPixels(\n eventData.element,\n x,\n y,\n 1,\n 1\n );\n const sp = storedPixels[0];\n const mo = sp * image.slope + image.intercept;\n const suv = calculateSUV(image, sp);\n\n // Draw text\n str = `SP: ${sp} MO: ${parseFloat(mo.toFixed(3))}`;\n if (suv) {\n str += ` SUV: ${parseFloat(suv.toFixed(3))}`;\n }\n }\n\n // Coords for text\n const coords = {\n // Translate the x/y away from the cursor\n x: data.handles.end.x + 3,\n y: data.handles.end.y - 3,\n };\n const textCoords = external.cornerstone.pixelToCanvas(\n eventData.element,\n coords\n );\n\n drawTextBox(\n context,\n str,\n textCoords.x,\n textCoords.y + fontHeight + 5,\n color\n );\n drawTextBox(context, text, textCoords.x, textCoords.y, color);\n }\n });\n }\n }\n}\n","import external from './../../externalModules.js';\nimport BaseAnnotationTool from '../base/BaseAnnotationTool.js';\n\n// State\nimport { getToolState } from './../../stateManagement/toolState.js';\nimport toolStyle from './../../stateManagement/toolStyle.js';\nimport toolColors from './../../stateManagement/toolColors.js';\n\n// Drawing\nimport {\n getNewContext,\n draw,\n drawHandles,\n drawRect,\n drawLinkedTextBox,\n setShadow,\n} from './../../drawing/index.js';\n\n// Util\nimport calculateSUV from './../../util/calculateSUV.js';\nimport numbersWithCommas from './../../util/numbersWithCommas.js';\nimport throttle from './../../util/throttle.js';\n\n/**\n * @public\n * @class RectangleRoiTool\n * @memberof Tools.Annotation\n * @classdesc Tool for drawing rectangular regions of interest, and measuring\n * the statistics of the enclosed pixels.\n * @extends Tools.Base.BaseAnnotationTool\n */\nexport default class RectangleRoiTool extends BaseAnnotationTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'RectangleRoi',\n supportedInteractionTypes: ['Mouse', 'Touch'],\n configuration: {\n // showMinMax: false,\n // showHounsfieldUnits: true\n },\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n this.initialConfiguration = initialConfiguration;\n }\n\n createNewMeasurement(eventData) {\n const goodEventData =\n eventData && eventData.currentPoints && eventData.currentPoints.image;\n\n if (!goodEventData) {\n console.error(\n `required eventData not supplied to tool ${\n this.name\n }'s createNewMeasurement`\n );\n\n return;\n }\n\n return {\n visible: true,\n active: true,\n color: undefined,\n invalidated: true,\n handles: {\n start: {\n x: eventData.currentPoints.image.x,\n y: eventData.currentPoints.image.y,\n highlight: true,\n active: false,\n },\n end: {\n x: eventData.currentPoints.image.x,\n y: eventData.currentPoints.image.y,\n highlight: true,\n active: true,\n },\n textBox: {\n active: false,\n hasMoved: false,\n movesIndependently: false,\n drawnIndependently: true,\n allowedOutsideImage: true,\n hasBoundingBox: true,\n },\n },\n };\n }\n\n pointNearTool(element, data, coords, interactionType) {\n const hasStartAndEndHandles =\n data && data.handles && data.handles.start && data.handles.end;\n const validParameters = hasStartAndEndHandles;\n\n if (!validParameters) {\n console.warn(\n `invalid parameters supplieed to tool ${this.name}'s pointNearTool`\n );\n }\n\n if (!validParameters || data.visible === false) {\n return false;\n }\n\n const distance = interactionType === 'mouse' ? 15 : 25;\n const startCanvas = external.cornerstone.pixelToCanvas(\n element,\n data.handles.start\n );\n const endCanvas = external.cornerstone.pixelToCanvas(\n element,\n data.handles.end\n );\n\n const rect = {\n left: Math.min(startCanvas.x, endCanvas.x),\n top: Math.min(startCanvas.y, endCanvas.y),\n width: Math.abs(startCanvas.x - endCanvas.x),\n height: Math.abs(startCanvas.y - endCanvas.y),\n };\n\n const distanceToPoint = external.cornerstoneMath.rect.distanceToPoint(\n rect,\n coords\n );\n\n return distanceToPoint < distance;\n }\n\n renderToolData(evt) {\n const toolData = getToolState(evt.currentTarget, this.name);\n\n if (!toolData) {\n return;\n }\n\n const eventData = evt.detail;\n const { image, element } = eventData;\n const lineWidth = toolStyle.getToolWidth();\n const { handleRadius, drawHandlesOnHover } = this.configuration;\n const context = getNewContext(eventData.canvasContext.canvas);\n\n // Meta\n const seriesModule =\n external.cornerstone.metaData.get('generalSeriesModule', image.imageId) ||\n {};\n let imagePlane = external.cornerstone.metaData.get(\n 'imagePlaneModule',\n image.imageId\n );\n\n // Pixel Spacing\n const modality = seriesModule.modality;\n const hasPixelSpacing =\n imagePlane && imagePlane.rowPixelSpacing && imagePlane.columnPixelSpacing;\n\n imagePlane = imagePlane || {};\n const pixelSpacing = {\n rowPixelSpacing: imagePlane.rowPixelSpacing || 1,\n columnPixelSpacing: imagePlane.columnPixelSpacing || 1,\n };\n\n draw(context, context => {\n // If we have tool data for this element - iterate over each set and draw it\n for (let i = 0; i < toolData.data.length; i++) {\n const data = toolData.data[i];\n\n if (data.visible === false) {\n continue;\n }\n\n // Configure\n const color = toolColors.getColorIfActive(data);\n const handleOptions = {\n color,\n handleRadius,\n drawHandlesIfActive: drawHandlesOnHover,\n };\n\n setShadow(context, this.configuration);\n\n // Draw\n drawRect(context, element, data.handles.start, data.handles.end, {\n color,\n });\n drawHandles(context, eventData, data.handles, handleOptions);\n\n // Update textbox stats\n if (data.invalidated === true) {\n if (data.cachedStats) {\n _throttledUpdateCachedStats(\n image,\n element,\n data,\n modality,\n pixelSpacing\n );\n } else {\n _updateCachedStats(image, element, data, modality, pixelSpacing);\n }\n }\n\n // Default to textbox on right side of ROI\n if (!data.handles.textBox.hasMoved) {\n data.handles.textBox.x = Math.max(\n data.handles.start.x,\n data.handles.end.x\n );\n data.handles.textBox.y =\n (data.handles.start.y + data.handles.end.y) / 2;\n }\n\n const textBoxAnchorPoints = handles =>\n _findTextBoxAnchorPoints(handles.start, handles.end);\n const textBoxContent = _createTextBoxContent(\n context,\n image.color,\n data.cachedStats,\n modality,\n hasPixelSpacing,\n this.configuration\n );\n\n drawLinkedTextBox(\n context,\n element,\n data.handles.textBox,\n textBoxContent,\n data.handles,\n textBoxAnchorPoints,\n color,\n lineWidth,\n 0,\n true\n );\n }\n });\n }\n}\n\n/**\n *\n */\nconst _throttledUpdateCachedStats = throttle(_updateCachedStats, 110);\n\n/**\n *\n *\n * @param {*} image\n * @param {*} element\n * @param {*} data\n * @param {string} modality\n * @param {*} pixelSpacing\n */\nfunction _updateCachedStats(image, element, data, modality, pixelSpacing) {\n const stats = _calculateStats(\n image,\n element,\n data.handles,\n modality,\n pixelSpacing\n );\n\n data.cachedStats = stats;\n data.invalidated = false;\n}\n\n/**\n * TODO: This is the same method (+ GetPixels) for the other ROIs\n * TODO: The pixel filtering is the unique bit\n *\n * @param {*} startHandle\n * @param {*} endHandle\n * @returns\n */\nfunction _getRectangleImageCoordinates(startHandle, endHandle) {\n return {\n left: Math.min(startHandle.x, endHandle.x),\n top: Math.min(startHandle.y, endHandle.y),\n width: Math.abs(startHandle.x - endHandle.x),\n height: Math.abs(startHandle.y - endHandle.y),\n };\n}\n\n/**\n *\n *\n * @param {*} image\n * @param {*} element\n * @param {*} handles\n * @param {*} modality\n * @param {*} pixelSpacing\n * @returns\n */\nfunction _calculateStats(image, element, handles, modality, pixelSpacing) {\n // Retrieve the bounds of the rectangle in image coordinates\n const roiCoordinates = _getRectangleImageCoordinates(\n handles.start,\n handles.end\n );\n\n // Retrieve the array of pixels that the rectangle bounds cover\n const pixels = external.cornerstone.getPixels(\n element,\n roiCoordinates.left,\n roiCoordinates.top,\n roiCoordinates.width,\n roiCoordinates.height\n );\n\n // Calculate the mean & standard deviation from the pixels and the rectangle details\n const roiMeanStdDev = _calculateRectangleStats(pixels, roiCoordinates);\n\n let meanStdDevSUV;\n\n if (modality === 'PT') {\n meanStdDevSUV = {\n mean: calculateSUV(image, roiMeanStdDev.mean, true) || 0,\n stdDev: calculateSUV(image, roiMeanStdDev.stdDev, true) || 0,\n };\n }\n\n // Calculate the image area from the rectangle dimensions and pixel spacing\n const area =\n roiCoordinates.width *\n (pixelSpacing.columnPixelSpacing || 1) *\n (roiCoordinates.height * (pixelSpacing.rowPixelSpacing || 1));\n\n return {\n area: area || 0,\n count: roiMeanStdDev.count || 0,\n mean: roiMeanStdDev.mean || 0,\n variance: roiMeanStdDev.variance || 0,\n stdDev: roiMeanStdDev.stdDev || 0,\n min: roiMeanStdDev.min || 0,\n max: roiMeanStdDev.max || 0,\n meanStdDevSUV,\n };\n}\n\n/**\n *\n *\n * @param {*} sp\n * @param {*} rectangle\n * @returns\n */\nfunction _calculateRectangleStats(sp, rectangle) {\n let sum = 0;\n let sumSquared = 0;\n let count = 0;\n let index = 0;\n let min = sp ? sp[0] : null;\n let max = sp ? sp[0] : null;\n\n for (let y = rectangle.top; y < rectangle.top + rectangle.height; y++) {\n for (let x = rectangle.left; x < rectangle.left + rectangle.width; x++) {\n sum += sp[index];\n sumSquared += sp[index] * sp[index];\n min = Math.min(min, sp[index]);\n max = Math.max(max, sp[index]);\n count++; // TODO: Wouldn't this just be sp.length?\n index++;\n }\n }\n\n if (count === 0) {\n return {\n count,\n mean: 0.0,\n variance: 0.0,\n stdDev: 0.0,\n min: 0.0,\n max: 0.0,\n };\n }\n\n const mean = sum / count;\n const variance = sumSquared / count - mean * mean;\n\n return {\n count,\n mean,\n variance,\n stdDev: Math.sqrt(variance),\n min,\n max,\n };\n}\n\n/**\n *\n *\n * @param {*} startHandle\n * @param {*} endHandle\n * @returns\n */\nfunction _findTextBoxAnchorPoints(startHandle, endHandle) {\n const { left, top, width, height } = _getRectangleImageCoordinates(\n startHandle,\n endHandle\n );\n\n return [\n {\n // Top middle point of rectangle\n x: left + width / 2,\n y: top,\n },\n {\n // Left middle point of rectangle\n x: left,\n y: top + height / 2,\n },\n {\n // Bottom middle point of rectangle\n x: left + width / 2,\n y: top + height,\n },\n {\n // Right middle point of rectangle\n x: left + width,\n y: top + height / 2,\n },\n ];\n}\n\n/**\n *\n *\n * @param {*} area\n * @param {*} hasPixelSpacing\n * @returns\n */\nfunction _formatArea(area, hasPixelSpacing) {\n // This uses Char code 178 for a superscript 2\n const suffix = hasPixelSpacing\n ? ` mm${String.fromCharCode(178)}`\n : ` px${String.fromCharCode(178)}`;\n\n return `Area: ${numbersWithCommas(area.toFixed(2))}${suffix}`;\n}\n\n/**\n * TODO: This is identical to EllipticalROI's same fn\n * TODO: We may want to make this a utility for ROIs with these values?\n *\n * @param {*} context\n * @param {*} isColorImage\n * @param {*} { area, mean, stdDev, min, max, meanStdDevSUV }\n * @param {*} modality\n * @param {*} hasPixelSpacing\n * @param {*} [options={}]\n * @returns\n */\nfunction _createTextBoxContent(\n context,\n isColorImage,\n { area, mean, stdDev, min, max, meanStdDevSUV },\n modality,\n hasPixelSpacing,\n options = {}\n) {\n const showMinMax = options.showMinMax || false;\n const showHounsfieldUnits = options.showHounsfieldUnits !== false;\n const textLines = [];\n\n const otherLines = [];\n\n if (!isColorImage) {\n const hasStandardUptakeValues = meanStdDevSUV && meanStdDevSUV.mean !== 0;\n const suffix = modality === 'CT' && showHounsfieldUnits ? ' HU' : '';\n\n let meanString = `Mean: ${numbersWithCommas(mean.toFixed(2))}${suffix}`;\n const stdDevString = `Std Dev: ${numbersWithCommas(\n stdDev.toFixed(2)\n )}${suffix}`;\n\n // If this image has SUV values to display, concatenate them to the text line\n if (hasStandardUptakeValues) {\n const SUVtext = ' SUV: ';\n\n const meanSuvString = `${SUVtext}${numbersWithCommas(\n meanStdDevSUV.mean.toFixed(2)\n )}`;\n const stdDevSuvString = `${SUVtext}${numbersWithCommas(\n meanStdDevSUV.stdDev.toFixed(2)\n )}`;\n\n const targetStringLength = Math.floor(\n context.measureText(`${stdDevString} `).width\n );\n\n while (context.measureText(meanString).width < targetStringLength) {\n meanString += ' ';\n }\n\n otherLines.push(`${meanString}${meanSuvString}`);\n otherLines.push(`${stdDevString} ${stdDevSuvString}`);\n } else {\n otherLines.push(`${meanString} ${stdDevString}`);\n }\n\n if (showMinMax) {\n let minString = `Min: ${min}${suffix}`;\n const maxString = `Max: ${max}${suffix}`;\n const targetStringLength = hasStandardUptakeValues\n ? Math.floor(context.measureText(`${stdDevString} `).width)\n : Math.floor(context.measureText(`${meanString} `).width);\n\n while (context.measureText(minString).width < targetStringLength) {\n minString += ' ';\n }\n\n otherLines.push(`${minString}${maxString}`);\n }\n }\n\n textLines.push(_formatArea(area, hasPixelSpacing));\n otherLines.forEach(x => textLines.push(x));\n\n return textLines;\n}\n","import BaseAnnotationTool from '../base/BaseAnnotationTool.js';\nimport external from './../../externalModules.js';\nimport pointInsideBoundingBox from './../../util/pointInsideBoundingBox.js';\nimport toolColors from './../../stateManagement/toolColors.js';\nimport { getNewContext, draw, setShadow } from './../../drawing/index.js';\nimport drawTextBox from './../../drawing/drawTextBox.js';\nimport {\n removeToolState,\n getToolState,\n} from './../../stateManagement/toolState.js';\n\n/**\n * @public\n * @class TextMarkerTool\n * @memberof Tools.Annotation\n *\n * @classdesc Tool for annotating an image with text markers.\n * @extends Tools.Base.BaseAnnotationTool\n */\nexport default class TextMarkerTool extends BaseAnnotationTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'TextMarker',\n supportedInteractionTypes: ['Mouse', 'Touch'],\n configuration: {\n markers: [],\n current: '',\n ascending: true,\n loop: false,\n changeTextCallback,\n },\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n this.touchPressCallback = this._changeText.bind(this);\n this.doubleClickCallback = this._changeText.bind(this);\n }\n\n createNewMeasurement(eventData) {\n const config = this.configuration;\n\n if (!config.current) {\n return;\n }\n\n // Create the measurement data for this tool with the end handle activated\n const measurementData = {\n visible: true,\n active: true,\n text: config.current,\n color: undefined,\n handles: {\n end: {\n x: eventData.currentPoints.image.x,\n y: eventData.currentPoints.image.y,\n highlight: true,\n active: true,\n hasBoundingBox: true,\n },\n },\n };\n\n // Create a rectangle representing the image\n const imageRect = {\n left: 0,\n top: 0,\n width: eventData.image.width,\n height: eventData.image.height,\n };\n\n // Check if the current handle is outside the image,\n // If it is, prevent the handle creation\n if (\n !external.cornerstoneMath.point.insideRect(\n measurementData.handles.end,\n imageRect\n )\n ) {\n return;\n }\n\n // Update the current marker for the next marker\n let currentIndex = config.markers.indexOf(config.current);\n\n const increment = config.ascending ? 1 : -1;\n\n currentIndex += increment;\n\n if (currentIndex >= config.markers.length) {\n currentIndex = config.loop ? 0 : -1;\n } else if (currentIndex < 0) {\n currentIndex = config.loop ? config.markers.length : -1;\n }\n\n config.current = config.markers[currentIndex];\n\n return measurementData;\n }\n\n pointNearTool(element, data, coords) {\n if (data.visible === false) {\n return false;\n }\n\n if (!data.handles.end.boundingBox) {\n return;\n }\n\n const distanceToPoint = external.cornerstoneMath.rect.distanceToPoint(\n data.handles.end.boundingBox,\n coords\n );\n const insideBoundingBox = pointInsideBoundingBox(data.handles.end, coords);\n\n return distanceToPoint < 10 || insideBoundingBox;\n }\n\n renderToolData(evt) {\n const eventData = evt.detail;\n const config = this.configuration;\n\n // If we have no toolData for this element, return immediately as there is nothing to do\n const toolData = getToolState(eventData.element, this.name);\n\n if (!toolData) {\n return;\n }\n\n // We have tool data for this element - iterate over each one and draw it\n const context = getNewContext(eventData.canvasContext.canvas);\n\n for (let i = 0; i < toolData.data.length; i++) {\n const data = toolData.data[i];\n\n if (data.visible === false) {\n continue;\n }\n\n const color = toolColors.getColorIfActive(data);\n\n draw(context, context => {\n setShadow(context, config);\n\n const textCoords = external.cornerstone.pixelToCanvas(\n eventData.element,\n data.handles.end\n );\n\n const options = {\n centering: {\n x: true,\n y: true,\n },\n };\n\n data.handles.end.boundingBox = drawTextBox(\n context,\n data.text,\n textCoords.x,\n textCoords.y - 10,\n color,\n options\n );\n });\n }\n }\n\n _changeText(evt) {\n const eventData = evt.detail;\n const { element, currentPoints } = eventData;\n let data;\n\n function doneChangingTextCallback(data, updatedText, deleteTool) {\n if (deleteTool === true) {\n removeToolState(element, this.name, data);\n } else {\n data.text = updatedText;\n }\n\n data.active = false;\n external.cornerstone.updateImage(element);\n }\n\n const config = this.configuration;\n const coords = currentPoints.canvas;\n const toolData = getToolState(element, this.name);\n\n // Now check to see if there is a handle we can move\n if (!toolData) {\n return;\n }\n\n for (let i = 0; i < toolData.data.length; i++) {\n data = toolData.data[i];\n if (this.pointNearTool(element, data, coords)) {\n data.active = true;\n external.cornerstone.updateImage(element);\n\n // Allow relabelling via a callback\n config.changeTextCallback(data, eventData, doneChangingTextCallback);\n\n evt.stopImmediatePropagation();\n evt.preventDefault();\n evt.stopPropagation();\n\n return;\n }\n }\n }\n}\n\n/**\n * This function is a callback to be overwriten in order to provide the wante feature\n * modal, overlay, popup or any kind of interaction with the user to be able to update\n * the text marker label.\n *\n * @param {} data\n * @param {} eventData\n * @param {} doneChangingTextCallback\n */\nconst changeTextCallback = (data, eventData, doneChangingTextCallback) => {\n doneChangingTextCallback(data, prompt('Change your annotation:'));\n};\n","import external from './../../externalModules.js';\nimport EVENTS from './../../events.js';\nimport BaseTool from './BaseTool.js';\nimport isToolActive from './../../store/isToolActive.js';\nimport store from './../../store/index.js';\nimport { getToolState } from '../../stateManagement/toolState.js';\nimport { globalImageIdSpecificToolStateManager } from '../../stateManagement/imageIdSpecificStateManager.js';\n\nconst { state, setters } = store.modules.brush;\n\n/**\n * @abstract\n * @memberof Tools.Base\n * @classdesc Abstract class for tools which manipulate the mask data to be displayed on\n * the cornerstone canvas.\n * @extends Tools.Base.BaseTool\n */\nclass BaseBrushTool extends BaseTool {\n constructor({\n name,\n strategies,\n defaultStrategy,\n configuration,\n supportedInteractionTypes,\n mixins,\n }) {\n configuration.referencedToolData = 'brush';\n\n super({\n name,\n strategies,\n defaultStrategy,\n configuration,\n supportedInteractionTypes,\n mixins,\n });\n\n this.hasCursor = true;\n\n this._drawing = false;\n this._drawingMouseUpCallback = this._drawingMouseUpCallback.bind(this);\n }\n\n // ===================================================================\n // Abstract Methods - Must be implemented.\n // ===================================================================\n\n /**\n * Helper function for rendering the brush.\n *\n * @abstract\n * @param {Object} evt - The event.\n */\n renderBrush(evt) {\n throw new Error(`Method renderBrush not implemented for ${this.name}.`);\n }\n\n /**\n * Paints the data to the canvas.\n *\n * @protected\n * @abstract\n * @param {Object} evt The event.\n */\n _paint(evt) {\n throw new Error(`Method _paint not implemented for ${this.name}.`);\n }\n\n // ===================================================================\n // Virtual Methods - Have default behavior but may be overriden.\n // ===================================================================\n\n /**\n * Event handler for MOUSE_DRAG event.\n *\n * @override\n * @event\n * @param {Object} evt - The event.\n */\n mouseDragCallback(evt) {\n this._startPainting(evt);\n }\n\n /**\n * Event handler for MOUSE_DOWN event.\n *\n * @override\n * @event\n * @param {Object} evt - The event.\n */\n preMouseDownCallback(evt) {\n this._startPainting(evt);\n\n return true;\n }\n\n /**\n * Initialise painting with baseBrushTool\n *\n * @protected\n * @event\n * @param {Object} evt - The event.\n */\n _startPainting(evt) {\n const eventData = evt.detail;\n const element = eventData.element;\n\n this._paint(evt);\n this._drawing = true;\n this._startListeningForMouseUp(element);\n this._lastImageCoords = eventData.currentPoints.image;\n }\n\n /**\n * Event handler for MOUSE_MOVE event.\n *\n * @override\n * @event\n * @param {Object} evt - The event.\n */\n mouseMoveCallback(evt) {\n const { currentPoints } = evt.detail;\n\n this._lastImageCoords = currentPoints.image;\n }\n\n /**\n * Event handler for switching mode to passive;\n *\n * @override\n * @event\n * @param {Object} evt - The event.\n */\n passiveCallback(evt) {\n external.cornerstone.updateImage(this.element);\n }\n\n /**\n * Used to redraw the tool's annotation data per render.\n *\n * @override\n * @param {Object} evt - The event.\n */\n renderToolData(evt) {\n const eventData = evt.detail;\n const element = eventData.element;\n\n // Only brush needs to render.\n if (isToolActive(element, this.name)) {\n // Call the hover event for the brush\n this.renderBrush(evt);\n }\n }\n\n // ===================================================================\n // Implementation interface\n // ===================================================================\n\n /**\n * Get the draw color (segmentation) of the tool.\n *\n * @protected\n * @param {Number} drawId The id of the color (segmentation) to switch to.\n */\n _getBrushColor(drawId) {\n const colormap = external.cornerstone.colors.getColormap(state.colorMapId);\n const colorArray = colormap.getColor(drawId);\n\n if (this._drawing) {\n return `rgba(${colorArray[[0]]}, ${colorArray[[1]]}, ${\n colorArray[[2]]\n }, 1.0 )`;\n }\n\n return `rgba(${colorArray[[0]]}, ${colorArray[[1]]}, ${\n colorArray[[2]]\n }, 0.8 )`;\n }\n\n /**\n * Event handler for MOUSE_UP during the drawing event loop.\n *\n * @protected\n * @event\n * @param {Object} evt - The event.\n */\n _drawingMouseUpCallback(evt) {\n const eventData = evt.detail;\n const element = eventData.element;\n\n this._drawing = false;\n this._mouseUpRender = true;\n\n this._stopListeningForMouseUp(element);\n }\n\n /**\n * Adds modify loop event listeners.\n *\n * @protected\n * @param {Object} element - The viewport element to add event listeners to.\n * @modifies {element}\n */\n _startListeningForMouseUp(element) {\n element.removeEventListener(EVENTS.MOUSE_UP, this._drawingMouseUpCallback);\n element.removeEventListener(\n EVENTS.MOUSE_CLICK,\n this._drawingMouseUpCallback\n );\n\n element.addEventListener(EVENTS.MOUSE_UP, this._drawingMouseUpCallback);\n element.addEventListener(EVENTS.MOUSE_CLICK, this._drawingMouseUpCallback);\n\n external.cornerstone.updateImage(element);\n }\n\n /**\n * Adds modify loop event listeners.\n *\n * @protected\n * @param {Object} element - The viewport element to add event listeners to.\n * @modifies {element}\n */\n _stopListeningForMouseUp(element) {\n element.removeEventListener(EVENTS.MOUSE_UP, this._drawingMouseUpCallback);\n element.removeEventListener(\n EVENTS.MOUSE_CLICK,\n this._drawingMouseUpCallback\n );\n\n external.cornerstone.updateImage(element);\n }\n\n // ===================================================================\n // Segmentation API. This is effectively a wrapper around the store.\n // ===================================================================\n\n /**\n * Switches to the next segmentation color.\n *\n * @public\n * @api\n */\n nextSegmentation() {\n const numberOfColors = this.constructor.getNumberOfColors();\n\n let drawId = state.drawColorId + 1;\n\n if (drawId === numberOfColors) {\n drawId = 0;\n }\n\n state.drawColorId = drawId;\n }\n\n /**\n * Switches to the previous segmentation color.\n *\n * @public\n * @api\n */\n previousSegmentation() {\n const numberOfColors = this.constructor.getNumberOfColors();\n\n let drawId = state.drawColorId - 1;\n\n if (drawId < 0) {\n drawId = numberOfColors - 1;\n }\n\n state.drawColorId = drawId;\n }\n\n /**\n * Increases the brush size\n *\n * @public\n * @api\n */\n increaseBrushSize() {\n const oldRadius = state.radius;\n let newRadius = Math.floor(oldRadius * 1.2);\n\n // If e.g. only 2 pixels big. Math.floor(2*1.2) = 2.\n // Hence, have minimum increment of 1 pixel.\n if (newRadius === oldRadius) {\n newRadius += 1;\n }\n\n setters.radius(newRadius);\n }\n\n /**\n * Decreases the brush size\n *\n * @public\n * @api\n */\n decreaseBrushSize() {\n const oldRadius = state.radius;\n const newRadius = Math.floor(oldRadius * 0.8);\n\n setters.radius(newRadius);\n }\n\n /**\n * Displays a segmentation on the element.\n *\n * @public\n * @api\n * @param {String} enabledElement The enabledElement on which to display.\n * @param {Number} segIndex The index of the segmentation.\n */\n showSegmentationOnElement(segIndex) {\n const enabledElement = this._getEnabledElement();\n const enabledElementUID = enabledElement.uuid;\n\n setters.brushVisibilityForElement(enabledElementUID, segIndex, true);\n\n external.cornerstone.updateImage(enabledElement.element);\n }\n\n /**\n * Hides a segmentation on an element.\n *\n * @public\n * @api\n * @param {Number} segIndex The index of the segmentation.\n */\n hideSegmentationOnElement(segIndex) {\n const enabledElement = this._getEnabledElement();\n const enabledElementUID = enabledElement.uuid;\n\n setters.brushVisibilityForElement(enabledElementUID, segIndex, false);\n external.cornerstone.updateImage(enabledElement.element);\n }\n\n /**\n * Displays all segmentations on an element.\n *\n * @public\n * @api\n */\n showAllSegmentationsOnElement() {\n const enabledElement = this._getEnabledElement();\n const enabledElementUID = enabledElement.uuid;\n const colormap = external.cornerstone.colors.getColormap(state.colorMapId);\n const numberOfColors = colormap.getNumberOfColors();\n\n for (let segIndex = 0; segIndex < numberOfColors; segIndex++) {\n setters.brushVisibilityForElement(enabledElementUID, segIndex, true);\n }\n\n external.cornerstone.updateImage(enabledElement.element);\n }\n\n /**\n * Hides all segmentations on an element.\n *\n * @public\n * @api\n */\n hideAllSegmentationsOnElement() {\n const enabledElement = this._getEnabledElement();\n const enabledElementUID = enabledElement.uuid;\n const colormap = external.cornerstone.colors.getColormap(state.colorMapId);\n const numberOfColors = colormap.getNumberOfColors();\n\n for (let segIndex = 0; segIndex < numberOfColors; segIndex++) {\n setters.brushVisibilityForElement(enabledElementUID, segIndex, false);\n }\n\n external.cornerstone.updateImage(enabledElement.element);\n }\n\n /**\n * Returns the number of colors in the colormap.\n *\n * @static\n * @public\n * @api\n * @returns {Number} The number of colors in the color map.\n */\n static getNumberOfColors() {\n const colormap = external.cornerstone.colors.getColormap(state.colorMapId);\n\n return colormap.getNumberOfColors();\n }\n\n get alpha() {\n state.alpha;\n }\n\n set alpha(value) {\n const enabledElement = this._getEnabledElement();\n\n state.alpha = value;\n external.cornerstone.updateImage(enabledElement.element);\n }\n\n get hiddenButActiveAlpha() {\n state.hiddenButActiveAlpha;\n }\n\n set hiddenButActiveAlpha(value) {\n const enabledElement = this._getEnabledElement();\n\n state.hiddenButActiveAlpha = value;\n external.cornerstone.updateImage(enabledElement.element);\n }\n\n _getEnabledElement() {\n return external.cornerstone.getEnabledElement(this.element);\n }\n\n /**\n * Returns the toolData type assoicated with this type of tool.\n *\n * @static\n * @public\n * @returns {String} The number of colors in the color map.\n */\n static getReferencedToolDataName() {\n return 'brush';\n }\n\n /**\n * @static invalidateBrushOnEnabledElement - invalidate all the brush data.\n *\n * @returns {null}\n */\n static invalidateBrushOnEnabledElement(enabledElementUID) {\n const element = store.getters.enabledElementByUID(enabledElementUID);\n\n const stackToolState = getToolState(element, 'stack');\n\n if (!stackToolState) {\n return;\n }\n\n const imageIds = stackToolState.data[0].imageIds;\n\n const enabledElement = external.cornerstone.getEnabledElement(element);\n\n const image = enabledElement.image;\n\n const dim = {\n xy: image.columns * image.rows,\n z: image.rows,\n xyz: image.columns * image.rows * imageIds.length,\n };\n\n const toolState = globalImageIdSpecificToolStateManager.saveToolState();\n\n // TODO -> Put this elsewhere\n /*\n const buffer = new ArrayBuffer(dim.xyz);\n\n const unit8View = new Uint8Array(buffer);\n\n console.log(unit8View.length);\n */\n\n for (let i = 0; i < imageIds.length; i++) {\n const imageId = imageIds[i];\n\n if (toolState[imageId] && toolState[imageId].brush) {\n const brushData = toolState[imageId].brush.data;\n\n for (let j = 0; j < brushData.length; j++) {\n if (brushData[j].pixelData) {\n brushData[j].invalidated = true;\n }\n }\n }\n }\n\n external.cornerstone.updateImage(element, true);\n }\n\n /**\n * @static getDataAsVolume - Returns a datacube for the segmentation.\n *\n * @return {type} description\n */\n static getDataAsVolume(enabledElementUID) {\n const element = store.getters.enabledElementByUID(enabledElementUID);\n\n const stackToolState = getToolState(element, 'stack');\n\n if (!stackToolState) {\n return;\n }\n\n const imageIds = stackToolState.data[0].imageIds;\n\n const enabledElement = external.cornerstone.getEnabledElement(element);\n\n const image = enabledElement.image;\n\n const dim = {\n xy: image.columns * image.rows,\n z: image.rows,\n xyz: image.columns * image.rows * imageIds.length,\n };\n\n const toolState = globalImageIdSpecificToolStateManager.saveToolState();\n\n const buffer = new ArrayBuffer(dim.xyz);\n\n const uint8View = new Uint8Array(buffer);\n\n for (let i = 0; i < imageIds.length; i++) {\n const imageId = imageIds[i];\n\n // TODO -> Workout HTF we will do this for multiple colors etc.\n if (\n toolState[imageId] &&\n toolState[imageId].brush &&\n toolState[imageId].brush.data[0].pixelData\n ) {\n // ADD brush data to the location of that slice.\n }\n }\n }\n}\n\nexport default BaseBrushTool;\n","import getToolForElement from './getToolForElement.js';\n\n/**\n * Queries if a tool is active on the specified element.\n * @export\n * @public\n * @method\n * @name isToolActive\n *\n * @param {HTMLElement} element The element being queried.\n * @param {string} name The name of the tool.\n * @returns {boolean} True if the tool is active.\n */\nexport default function(element, name) {\n const tool = getToolForElement(element, name);\n\n return tool.mode === 'active';\n}\n","import { drawBrushPixels, drawBrushOnCanvas } from './drawBrush.js';\nimport getCircle from './getCircle.js';\n\nexport default {\n drawBrushPixels,\n drawBrushOnCanvas,\n getCircle,\n};\n","import external from '../../externalModules.js';\nimport { draw, fillBox } from '../../drawing/index.js';\n\n/**\n * Fills in the brush mask data with new data.\n * @export @public @method\n * @name drawBrushPixels\n *\n * @param {Object[]} pointerArray The array of points to draw.\n * @param {number[]} storedPixels The brush mask to modify.\n * @param {number} columns The number of columns in the mask.\n * @param {boolean} [shouldErase = false] If true the modified mask pixels will be set to 0, rather than 1.\n */\nfunction drawBrushPixels(\n pointerArray,\n storedPixels,\n columns,\n shouldErase = false\n) {\n const getPixelIndex = (x, y) => y * columns + x;\n\n pointerArray.forEach(point => {\n const spIndex = getPixelIndex(point[0], point[1]);\n\n storedPixels[spIndex] = shouldErase ? 0 : 1;\n });\n}\n\n/**\n * Draws the brush data to the canvas.\n * @export @public @method\n *\n * @param {Object[]} pointerArray Array of points to draw.\n * @param {Object} context The canvas context.\n * @param {string} color The color to draw the pixels.\n * @param {HTMLElement} element The element on which the canvas resides.\n */\nfunction drawBrushOnCanvas(pointerArray, context, color, element) {\n const canvasPtTL = external.cornerstone.pixelToCanvas(element, {\n x: 0,\n y: 0,\n });\n const canvasPtBR = external.cornerstone.pixelToCanvas(element, {\n x: 1,\n y: 1,\n });\n const sizeX = canvasPtBR.x - canvasPtTL.x;\n const sizeY = canvasPtBR.y - canvasPtTL.y;\n\n draw(context, context => {\n pointerArray.forEach(point => {\n const canvasPt = external.cornerstone.pixelToCanvas(element, {\n x: point[0],\n y: point[1],\n });\n const boundingBox = {\n left: canvasPt.x,\n top: canvasPt.y,\n width: sizeX,\n height: sizeY,\n };\n\n fillBox(context, boundingBox, color);\n });\n });\n}\n\nexport { drawBrushPixels, drawBrushOnCanvas };\n","/**\n * Gets the pixels within the circle.\n * @export @public @method\n * @name getCircle\n *\n * @param {number} radius The radius of the circle.\n * @param {number} rows The number of rows.\n * @param {number} columns The number of columns.\n * @param {number} [xCoord = 0] The x-location of the center of the circle.\n * @param {number} [yCoord = 0] The y-location of the center of the circle.\n * @returns {number[][]} Array of pixels contained within the circle.\n */\nexport default function getCircle(\n radius,\n rows,\n columns,\n xCoord = 0,\n yCoord = 0\n) {\n const x0 = Math.round(xCoord);\n const y0 = Math.round(yCoord);\n\n if (radius === 1) {\n return [[x0, y0]];\n }\n\n const circleArray = [];\n let index = 0;\n\n for (let y = -radius; y <= radius; y++) {\n const yCoord = y0 + y;\n\n if (yCoord > rows || yCoord < 0) {\n continue;\n }\n\n for (let x = -radius; x <= radius; x++) {\n const xCoord = x0 + x;\n\n if (xCoord > columns || xCoord < 0) {\n continue;\n }\n\n if (x * x + y * y < radius * radius) {\n circleArray[index++] = [x0 + x, y0 + y];\n }\n }\n }\n\n return circleArray;\n}\n","import external from './../../externalModules.js';\nimport BaseBrushTool from './../base/BaseBrushTool.js';\nimport { getToolState } from './../../stateManagement/toolState.js';\nimport store from './../../store/index.js';\nimport brushUtils from './../../util/brush/index.js';\nimport EVENTS from '../../events';\n\nconst { drawBrushPixels, getCircle } = brushUtils;\nconst { state } = store.modules.brush;\n\n/**\n * @public\n * @class BrushTool\n * @memberof Tools.Brush\n * @classdesc Tool for drawing segmentations on an image.\n * @extends Tools.Base.BaseBrushTool\n */\nexport default class BrushTool extends BaseBrushTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'Brush',\n supportedInteractionTypes: ['Mouse'],\n strategies: {\n overlapping: _overlappingStrategy,\n nonOverlapping: _nonOverlappingStrategy,\n },\n defaultStrategy: 'overlapping',\n configuration: {},\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n }\n\n /**\n * Called by the event dispatcher to render the image.\n *\n * @param {Object} evt - The event.\n */\n renderBrush(evt) {\n const eventData = evt.detail;\n const viewport = eventData.viewport;\n\n let mousePosition;\n\n if (this._drawing) {\n mousePosition = this._lastImageCoords;\n } else if (this._mouseUpRender) {\n mousePosition = this._lastImageCoords;\n this._mouseUpRender = false;\n } else {\n mousePosition = store.state.mousePositionImage;\n }\n\n if (!mousePosition) {\n return;\n }\n\n const { rows, columns } = eventData.image;\n const { x, y } = mousePosition;\n\n if (x < 0 || x > columns || y < 0 || y > rows) {\n return;\n }\n\n // Draw the hover overlay on top of the pixel data\n const configuration = this._configuration;\n const radius = state.radius;\n const context = eventData.canvasContext;\n const element = eventData.element;\n const drawId = state.drawColorId;\n const color = this._getBrushColor(drawId);\n\n context.setTransform(1, 0, 0, 1, 0, 0);\n\n const { cornerstone } = external;\n\n const circleRadius = radius * viewport.scale;\n const mouseCoordsCanvas = cornerstone.pixelToCanvas(element, mousePosition);\n\n context.beginPath();\n context.strokeStyle = color;\n context.ellipse(\n mouseCoordsCanvas.x,\n mouseCoordsCanvas.y,\n circleRadius,\n circleRadius,\n 0,\n 0,\n 2 * Math.PI\n );\n context.stroke();\n }\n\n /**\n * Paints the data to the canvas.\n *\n * @private\n * @param {Object} eventData The data object associated with the event.\n */\n _paint(evt) {\n this.applyActiveStrategy(evt, this.configuration);\n\n external.cornerstone.triggerEvent(\n evt.detail.element,\n EVENTS.MEASUREMENT_MODIFIED,\n evt.detail\n );\n\n external.cornerstone.updateImage(evt.detail.element);\n }\n}\n\nfunction _overlappingStrategy(evt, configuration) {\n const eventData = evt.detail;\n const element = eventData.element;\n const { rows, columns } = eventData.image;\n const { x, y } = eventData.currentPoints.image;\n const toolData = getToolState(element, configuration.referencedToolData);\n\n let shouldErase = false;\n\n // Check for key, could be a mouseDown or mouseDrag event.\n if (_isCtrlDown(eventData)) {\n console.log('ctrlDown');\n shouldErase = true;\n }\n\n const segmentationIndex = state.drawColorId;\n\n if (!toolData.data[segmentationIndex].pixelData) {\n const newPixelData = new Uint8ClampedArray(\n eventData.image.width * eventData.image.height\n );\n\n toolData.data[segmentationIndex].pixelData = newPixelData;\n }\n\n const pixelData = toolData.data[segmentationIndex].pixelData;\n\n const radius = state.radius;\n\n if (x < 0 || x > columns || y < 0 || y > rows) {\n return;\n }\n\n const pointerArray = getCircle(radius, rows, columns, x, y);\n\n drawBrushPixels(pointerArray, pixelData, columns, shouldErase);\n\n toolData.data[segmentationIndex].invalidated = true;\n}\n\nfunction _nonOverlappingStrategy(evt, configuration) {\n const eventData = evt.detail;\n const element = eventData.element;\n const { rows, columns } = eventData.image;\n const { x, y } = eventData.currentPoints.image;\n const toolState = getToolState(element, configuration.referencedToolData);\n const toolData = toolState.data;\n\n let shouldErase = false;\n\n // Check for key, could be a mouseDown or mouseDrag event.\n if (_isCtrlDown(eventData)) {\n console.log('ctrlDown');\n shouldErase = true;\n }\n\n const activeSegmentationIndex = state.drawColorId;\n\n if (!toolData[activeSegmentationIndex].pixelData) {\n const newPixelData = new Uint8ClampedArray(\n eventData.image.width * eventData.image.height\n );\n\n toolData[activeSegmentationIndex].pixelData = newPixelData;\n }\n\n const pixelData = toolData[activeSegmentationIndex].pixelData;\n\n const radius = state.radius;\n\n if (x < 0 || x > columns || y < 0 || y > rows) {\n return;\n }\n\n const pointerArray = getCircle(radius, rows, columns, x, y);\n\n // Draw / Erase the active color.\n drawBrushPixels(pointerArray, pixelData, columns, shouldErase);\n\n toolData[activeSegmentationIndex].invalidated = true;\n\n const numberOfColors = BaseBrushTool.getNumberOfColors();\n\n // If there is brush data in this region for other colors, delete it.\n for (let i = 0; i < numberOfColors; i++) {\n if (i === activeSegmentationIndex) {\n continue;\n }\n\n if (toolData[i] && toolData[i].pixelData) {\n drawBrushPixels(pointerArray, toolData[i].pixelData, columns, true);\n toolData[i].invalidated = true;\n }\n }\n}\n\nfunction _isCtrlDown(eventData) {\n return (eventData.event && eventData.event.ctrlKey) || eventData.ctrlKey;\n}\n","import BrushTool from './BrushTool.js';\n\n// Named Exports\nexport { default as BrushTool } from './BrushTool.js';\n\n// Namespace, default export\nexport default {\n BrushTool,\n};\n","let defaultStartLoadHandler;\nlet defaultEndLoadHandler;\nlet defaultErrorLoadingHandler;\n\nfunction setStartLoadHandler(handler) {\n defaultStartLoadHandler = handler;\n}\n\nfunction getStartLoadHandler() {\n return defaultStartLoadHandler;\n}\n\nfunction setEndLoadHandler(handler) {\n defaultEndLoadHandler = handler;\n}\n\nfunction getEndLoadHandler() {\n return defaultEndLoadHandler;\n}\n\nfunction setErrorLoadingHandler(handler) {\n defaultErrorLoadingHandler = handler;\n}\n\nfunction getErrorLoadingHandler() {\n return defaultErrorLoadingHandler;\n}\n\nconst loadHandlerManager = {\n setStartLoadHandler,\n getStartLoadHandler,\n setEndLoadHandler,\n getEndLoadHandler,\n setErrorLoadingHandler,\n getErrorLoadingHandler,\n};\n\nexport default loadHandlerManager;\n","import external from '../externalModules.js';\n\n/**\n * Convert an Array to a cornerstoneMath.Vector3\n * @export @public @method\n * @name convertToVector3\n *\n * @param {Array|cornerstoneMath.Vector3} arrayOrVector3 Input array or Vector3\n * @returns {cornerstoneMath.Vector3}\n */\nexport default function convertToVector3(arrayOrVector3) {\n const cornerstoneMath = external.cornerstoneMath;\n\n if (arrayOrVector3 instanceof cornerstoneMath.Vector3) {\n return arrayOrVector3;\n }\n\n return new cornerstoneMath.Vector3(\n arrayOrVector3[0],\n arrayOrVector3[1],\n arrayOrVector3[2]\n );\n}\n","import external from '../externalModules.js';\nimport convertToVector3 from '../util/convertToVector3.js';\n\n/**\n * Projects a patient point to an image point\n * @export @public @method\n * @name projectPatientPointToImagePlane\n *\n * @param {Object} patientPoint The patient point.\n * @param {Object} imagePlane The image plane used for projection.\n * @returns {Object} The projected coordinates.\n */\nexport function projectPatientPointToImagePlane(patientPoint, imagePlane) {\n const rowCosines = convertToVector3(imagePlane.rowCosines);\n const columnCosines = convertToVector3(imagePlane.columnCosines);\n const imagePositionPatient = convertToVector3(\n imagePlane.imagePositionPatient\n );\n const point = patientPoint.clone().sub(imagePositionPatient);\n const x = rowCosines.dot(point) / imagePlane.columnPixelSpacing;\n const y = columnCosines.dot(point) / imagePlane.rowPixelSpacing;\n\n return {\n x,\n y,\n };\n}\n\n//\n/**\n * Projects an image point to a patient point\n * @export @public @method\n * @name imagePointToPatientPoint\n *\n * @param {Object} imagePoint The image point.\n * @param {Object} imagePlane The image plane used for projection.\n * @returns {Object} The projected coordinates.\n */\nexport function imagePointToPatientPoint(imagePoint, imagePlane) {\n const rowCosines = convertToVector3(imagePlane.rowCosines);\n const columnCosines = convertToVector3(imagePlane.columnCosines);\n const imagePositionPatient = convertToVector3(\n imagePlane.imagePositionPatient\n );\n\n const x = rowCosines.clone().multiplyScalar(imagePoint.x);\n\n x.multiplyScalar(imagePlane.columnPixelSpacing);\n const y = columnCosines.clone().multiplyScalar(imagePoint.y);\n\n y.multiplyScalar(imagePlane.rowPixelSpacing);\n const patientPoint = x.add(y);\n\n patientPoint.add(imagePositionPatient);\n\n return patientPoint;\n}\n\n/**\n * Returns a rectangle from the imagePlane.\n * @export @public @method\n * @name getRectangleFromImagePlane\n *\n * @param {Object} imagePlane The imagePlane.\n * @returns {Object} The rect.\n */\nfunction getRectangleFromImagePlane(imagePlane) {\n // Get the points\n const topLeft = imagePointToPatientPoint(\n {\n x: 0,\n y: 0,\n },\n imagePlane\n );\n const topRight = imagePointToPatientPoint(\n {\n x: imagePlane.columns,\n y: 0,\n },\n imagePlane\n );\n const bottomLeft = imagePointToPatientPoint(\n {\n x: 0,\n y: imagePlane.rows,\n },\n imagePlane\n );\n const bottomRight = imagePointToPatientPoint(\n {\n x: imagePlane.columns,\n y: imagePlane.rows,\n },\n imagePlane\n );\n\n // Get each side as a vector\n const rect = {\n top: new external.cornerstoneMath.Line3(topLeft, topRight),\n left: new external.cornerstoneMath.Line3(topLeft, bottomLeft),\n right: new external.cornerstoneMath.Line3(topRight, bottomRight),\n bottom: new external.cornerstoneMath.Line3(bottomLeft, bottomRight),\n };\n\n return rect;\n}\n\n/**\n * Gets all the intersections of a line with a rect.\n * @private\n * @method\n * @name lineRectangleIntersection\n *\n * @param {Object} line The line to check.\n * @param {Object} rect The rect being intersected.\n * @returns {Object[]} An array of the intersections.\n */\nfunction lineRectangleIntersection(line, rect) {\n const intersections = [];\n\n Object.keys(rect).forEach(function(side) {\n const segment = rect[side];\n const intersection = line.intersectLine(segment);\n\n if (intersection) {\n intersections.push(intersection);\n }\n });\n\n return intersections;\n}\n\n/**\n * Gets the line of intersection between two planes in patient space.\n * @export @public @method\n * @name planePlaneIntersection\n *\n * @param {Object} targetImagePlane The target plane.\n * @param {Object} referenceImagePlane The reference plane\n * @returns {Object} The intersections.\n */\nexport function planePlaneIntersection(targetImagePlane, referenceImagePlane) {\n const targetRowCosines = convertToVector3(targetImagePlane.rowCosines);\n const targetColumnCosines = convertToVector3(targetImagePlane.columnCosines);\n const targetImagePositionPatient = convertToVector3(\n targetImagePlane.imagePositionPatient\n );\n const referenceRowCosines = convertToVector3(referenceImagePlane.rowCosines);\n const referenceColumnCosines = convertToVector3(\n referenceImagePlane.columnCosines\n );\n const referenceImagePositionPatient = convertToVector3(\n referenceImagePlane.imagePositionPatient\n );\n\n // First, get the normals of each image plane\n const targetNormal = targetRowCosines.clone().cross(targetColumnCosines);\n const targetPlane = new external.cornerstoneMath.Plane();\n\n targetPlane.setFromNormalAndCoplanarPoint(\n targetNormal,\n targetImagePositionPatient\n );\n\n const referenceNormal = referenceRowCosines\n .clone()\n .cross(referenceColumnCosines);\n const referencePlane = new external.cornerstoneMath.Plane();\n\n referencePlane.setFromNormalAndCoplanarPoint(\n referenceNormal,\n referenceImagePositionPatient\n );\n\n const originDirection = referencePlane.clone().intersectPlane(targetPlane);\n const origin = originDirection.origin;\n const direction = originDirection.direction;\n\n // Calculate the longest possible length in the reference image plane (the length of the diagonal)\n const bottomRight = imagePointToPatientPoint(\n {\n x: referenceImagePlane.columns,\n y: referenceImagePlane.rows,\n },\n referenceImagePlane\n );\n const distance = referenceImagePositionPatient.distanceTo(bottomRight);\n\n // Use this distance to bound the ray intersecting the two planes\n const line = new external.cornerstoneMath.Line3();\n\n line.start = origin;\n line.end = origin.clone().add(direction.multiplyScalar(distance));\n\n // Find the intersections between this line and the reference image plane's four sides\n const rect = getRectangleFromImagePlane(referenceImagePlane);\n const intersections = lineRectangleIntersection(line, rect);\n\n // Return the intersections between this line and the reference image plane's sides\n // In order to draw the reference line from the target image.\n if (intersections.length !== 2) {\n return;\n }\n\n return {\n start: intersections[0],\n end: intersections[1],\n };\n}\n","const elementToolOptions = {};\n\n/**\n * Retrieve the options object associated with a particular toolType and element\n * @export\n * @public\n * @method\n * @name getToolOptions\n *\n * @param {string} toolType Tool type identifier of the target options object\n * @param {HTMLElement} element Element of the target options object\n *\n * @returns {Object} Target options object (empty if not yet set)\n */\nfunction getToolOptions(toolType, element) {\n if (!elementToolOptions[toolType]) {\n return {};\n }\n\n const toolOptions = elementToolOptions[toolType];\n const optionsObject = toolOptions.find(\n toolOptionObject => toolOptionObject.element === element\n );\n\n if (!optionsObject) {\n return {};\n }\n\n return optionsObject.options;\n}\n\n/**\n * Set the options object associated with a particular toolType and element.\n * @export\n * @public\n * @method\n * @name setToolOptions\n *\n * @param {string} toolType Tool type identifier of the target options object.\n * @param {HTMLElement} element Element of the target options object.\n * @param {Object} options Options object to store at target.\n */\nfunction setToolOptions(toolType, element, options) {\n if (!elementToolOptions[toolType]) {\n elementToolOptions[toolType] = [\n {\n element,\n options,\n },\n ];\n\n return;\n }\n\n const toolOptions = elementToolOptions[toolType];\n const index = toolOptions.findIndex(\n toolOptionObject => toolOptionObject.element === element\n );\n\n if (index === -1) {\n elementToolOptions[toolType].push({\n element,\n options,\n });\n } else {\n const elementOptions = elementToolOptions[toolType][index].options || {};\n\n elementToolOptions[toolType][index].options = Object.assign(\n elementOptions,\n options\n );\n }\n}\n\n/**\n * Clear the options object associated with a particular toolType and element.\n * @export\n * @public\n * @method\n * @name clearToolOptions\n *\n * @param {string} toolType Tool type identifier of the target options object.\n * @param {HTMLElement} element Element of the target options object.\n */\nfunction clearToolOptions(toolType, element) {\n const toolOptions = elementToolOptions[toolType];\n\n if (toolOptions) {\n elementToolOptions[toolType] = toolOptions.filter(\n toolOptionObject => toolOptionObject.element !== element\n );\n }\n}\n\n/**\n * Clear the options objects associated with a particular toolType.\n * @export\n * @public\n * @method\n * @name clearToolOptionsByToolType\n *\n * @param {string} toolType Tool type identifier of the target options objects.\n */\nfunction clearToolOptionsByToolType(toolType) {\n delete elementToolOptions[toolType];\n}\n\n/**\n * Clear the options objects associated with a particular element.\n * @export\n * @public\n * @method\n * @name clearToolOptionsByElement\n *\n * @param {HTMLElement} element Element of the target options objects.\n */\nfunction clearToolOptionsByElement(element) {\n for (const toolType in elementToolOptions) {\n elementToolOptions[toolType] = elementToolOptions[toolType].filter(\n toolOptionObject => toolOptionObject.element !== element\n );\n }\n}\n\nexport {\n getToolOptions,\n setToolOptions,\n clearToolOptions,\n clearToolOptionsByToolType,\n clearToolOptionsByElement,\n};\n","import BaseTool from './base/BaseTool.js';\nimport external from './../externalModules.js';\n\nimport loadHandlerManager from '../stateManagement/loadHandlerManager.js';\nimport {\n addToolState,\n getToolState,\n clearToolState,\n} from '../stateManagement/toolState.js';\nimport { imagePointToPatientPoint } from '../util/pointProjector.js';\nimport convertToVector3 from '../util/convertToVector3.js';\nimport { setToolOptions } from '../toolOptions.js';\n\n/**\n * @public\n * @class CrosshairsTool\n * @memberof Tools\n *\n * @classdesc Tool for finding the slice in another element corresponding to the\n * image position in a synchronized image series.\n * @extends Tools.Base.BaseTool\n */\nexport default class CrosshairsTool extends BaseTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'Crosshairs',\n supportedInteractionTypes: ['Mouse', 'Touch'],\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n this.mouseDownCallback = this._chooseLocation.bind(this);\n this.mouseDragCallback = this._chooseLocation.bind(this);\n this.touchDragCallback = this._chooseLocation.bind(this);\n }\n\n _chooseLocation(evt) {\n const eventData = evt.detail;\n const { element } = eventData;\n\n // Prevent CornerstoneToolsTouchStartActive from killing any press events\n evt.stopImmediatePropagation();\n\n // If we have no toolData for this element, return immediately as there is nothing to do\n const toolData = getToolState(element, this.name);\n\n if (!toolData) {\n return;\n }\n\n // Get current element target information\n const sourceElement = element;\n const sourceEnabledElement = external.cornerstone.getEnabledElement(\n sourceElement\n );\n const sourceImageId = sourceEnabledElement.image.imageId;\n const sourceImagePlane = external.cornerstone.metaData.get(\n 'imagePlaneModule',\n sourceImageId\n );\n\n if (!sourceImagePlane) {\n return;\n }\n\n // Get currentPoints from mouse cursor on selected element\n const sourceImagePoint = eventData.currentPoints.image;\n\n // Transfer this to a patientPoint given imagePlane metadata\n const patientPoint = imagePointToPatientPoint(\n sourceImagePoint,\n sourceImagePlane\n );\n\n // Get the enabled elements associated with this synchronization context\n const syncContext = toolData.data[0].synchronizationContext;\n const enabledElements = syncContext.getSourceElements();\n\n // Iterate over each synchronized element\n enabledElements.forEach(function(targetElement) {\n // Don't do anything if the target is the same as the source\n if (targetElement === sourceElement) {\n return;\n }\n\n let minDistance = Number.MAX_VALUE;\n let newImageIdIndex = -1;\n\n const stackToolDataSource = getToolState(targetElement, 'stack');\n\n if (stackToolDataSource === undefined) {\n return;\n }\n\n const stackData = stackToolDataSource.data[0];\n\n // Find within the element's stack the closest image plane to selected location\n stackData.imageIds.forEach(function(imageId, index) {\n const imagePlane = external.cornerstone.metaData.get(\n 'imagePlaneModule',\n imageId\n );\n\n // Skip if the image plane is not ready\n if (\n !imagePlane ||\n !imagePlane.imagePositionPatient ||\n !imagePlane.rowCosines ||\n !imagePlane.columnCosines\n ) {\n return;\n }\n\n const imagePosition = convertToVector3(imagePlane.imagePositionPatient);\n const row = convertToVector3(imagePlane.rowCosines);\n const column = convertToVector3(imagePlane.columnCosines);\n const normal = column.clone().cross(row.clone());\n const distance = Math.abs(\n normal.clone().dot(imagePosition) - normal.clone().dot(patientPoint)\n );\n\n if (distance < minDistance) {\n minDistance = distance;\n newImageIdIndex = index;\n }\n });\n\n if (newImageIdIndex === stackData.currentImageIdIndex) {\n return;\n }\n\n // Switch the loaded image to the required image\n if (\n newImageIdIndex !== -1 &&\n stackData.imageIds[newImageIdIndex] !== undefined\n ) {\n const startLoadingHandler = loadHandlerManager.getStartLoadHandler();\n const endLoadingHandler = loadHandlerManager.getEndLoadHandler();\n const errorLoadingHandler = loadHandlerManager.getErrorLoadingHandler();\n\n if (startLoadingHandler) {\n startLoadingHandler(targetElement);\n }\n\n let loader;\n\n if (stackData.preventCache === true) {\n loader = external.cornerstone.loadImage(\n stackData.imageIds[newImageIdIndex]\n );\n } else {\n loader = external.cornerstone.loadAndCacheImage(\n stackData.imageIds[newImageIdIndex]\n );\n }\n\n loader.then(\n function(image) {\n const viewport = external.cornerstone.getViewport(targetElement);\n\n stackData.currentImageIdIndex = newImageIdIndex;\n external.cornerstone.displayImage(targetElement, image, viewport);\n if (endLoadingHandler) {\n endLoadingHandler(targetElement, image);\n }\n },\n function(error) {\n const imageId = stackData.imageIds[newImageIdIndex];\n\n if (errorLoadingHandler) {\n errorLoadingHandler(targetElement, imageId, error);\n }\n }\n );\n }\n });\n }\n\n activeCallback(element, { mouseButtonMask, synchronizationContext }) {\n setToolOptions(this.name, element, { mouseButtonMask });\n\n // Clear any currently existing toolData\n clearToolState(element, this.name);\n\n addToolState(element, this.name, {\n synchronizationContext,\n });\n }\n}\n","import external from '../externalModules.js';\nimport BaseTool from './base/BaseTool.js';\n\n/**\n * @public\n * @class DoubleTapFitToWindowTool\n * @memberof Tools\n *\n * @classdesc Tool which calls the external cornerstone.fitToWindow() function\n * on double tap.\n * @extends Tools.Base.BaseTool\n */\nexport default class DoubleTapFitToWindowTool extends BaseTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'DoubleTapFitToWindow',\n supportedInteractionTypes: ['DoubleTap'],\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n }\n\n doubleTapCallback(evt) {\n const eventData = evt.detail;\n\n external.cornerstone.fitToWindow(eventData.element);\n }\n}\n","import external from '../externalModules.js';\nimport BaseTool from './base/BaseTool.js';\n\nimport textStyle from '../stateManagement/textStyle.js';\nimport toolColors from '../stateManagement/toolColors.js';\nimport getRGBPixels from '../util/getRGBPixels.js';\nimport calculateSUV from '../util/calculateSUV.js';\nimport {\n getNewContext,\n draw,\n setShadow,\n drawCircle,\n} from '../drawing/index.js';\nimport drawTextBox, { textBoxWidth } from '../drawing/drawTextBox.js';\n\n/**\n * @public\n * @class DragProbeTool\n * @memberof Tools\n *\n * @classdesc Tool which provides a probe of the image data at the\n * input position on drag.\n * @extends Tools.Base.BaseTool\n */\nexport default class DragProbeTool extends BaseTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'DragProbe',\n strategies: {\n default: defaultStrategy,\n minimal: minimalStrategy,\n },\n defaultStrategy: 'default',\n supportedInteractionTypes: ['Mouse', 'Touch'],\n configuration: {},\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.touchDragCallback = this._movingEventCallback.bind(this);\n this.touchEndCallback = this._endMovingEventCallback.bind(this);\n\n this.mouseDragCallback = this._movingEventCallback.bind(this);\n this.mouseUpCallback = this._endMovingEventCallback.bind(this);\n\n this.initialConfiguration = initialConfiguration;\n this.dragEventData = {};\n }\n\n _movingEventCallback(evt) {\n const eventData = evt.detail;\n const { element } = eventData;\n\n this.dragEventData = eventData;\n external.cornerstone.updateImage(element);\n }\n\n _endMovingEventCallback(evt) {\n const eventData = evt.detail;\n const { element } = eventData;\n\n this.dragEventData = {};\n external.cornerstone.updateImage(element);\n }\n\n renderToolData(evt) {\n if (!this.dragEventData.currentPoints) {\n return;\n }\n\n if (\n evt &&\n evt.detail &&\n Boolean(Object.keys(this.dragEventData.currentPoints).length)\n ) {\n evt.detail.currentPoints = this.dragEventData.currentPoints;\n this.applyActiveStrategy(evt);\n }\n }\n}\n\n/**\n * Default strategy will pick the exactly point of mouse/touch interact and display the probe data.\n *\n * @param {} evt Image rendered event\n * @param {} config Tool configuration\n */\nconst defaultStrategy = (evt, config) => {\n const cornerstone = external.cornerstone;\n const eventData = evt.detail;\n const { element, image, currentPoints, canvasContext } = eventData;\n\n const context = getNewContext(canvasContext.canvas);\n\n const color = toolColors.getActiveColor();\n const fontHeight = textStyle.getFontSize();\n\n const x = Math.round(currentPoints.image.x);\n const y = Math.round(currentPoints.image.y);\n\n if (x < 0 || y < 0 || x >= image.columns || y >= image.rows) {\n return;\n }\n\n draw(context, context => {\n setShadow(context, config);\n\n const text = `${x}, ${y}`;\n let storedPixels;\n let str;\n\n if (image.color) {\n storedPixels = getRGBPixels(element, x, y, 1, 1);\n str = `R: ${storedPixels[0]} G: ${storedPixels[1]} B: ${\n storedPixels[2]\n } A: ${storedPixels[3]}`;\n } else {\n storedPixels = cornerstone.getStoredPixels(element, x, y, 1, 1);\n const sp = storedPixels[0];\n const mo = sp * image.slope + image.intercept;\n const suv = calculateSUV(image, sp);\n\n // Draw text\n str = `SP: ${sp} MO: ${parseFloat(mo.toFixed(3))}`;\n if (suv) {\n str += ` SUV: ${parseFloat(suv.toFixed(3))}`;\n }\n }\n\n // Draw text 5px away from cursor\n const textCoords = {\n x: currentPoints.canvas.x + 5,\n y: currentPoints.canvas.y - 5,\n };\n\n drawTextBox(\n context,\n str,\n textCoords.x,\n textCoords.y + fontHeight + 5,\n color\n );\n drawTextBox(context, text, textCoords.x, textCoords.y, color);\n });\n};\n\n/**\n * Minimal strategy will position a circle and use the center of the circle to calculate and display probe data.\n *\n * @param {} evt Image rendered event\n * @param {} config Tool configuration\n */\nconst minimalStrategy = (evt, config) => {\n const cornerstone = external.cornerstone;\n const eventData = evt.detail;\n const {\n element,\n image,\n currentPoints,\n canvasContext,\n isTouchEvent,\n } = eventData;\n\n const context = getNewContext(canvasContext.canvas);\n const color = toolColors.getActiveColor();\n\n let pageCoordY = currentPoints.page.y - textStyle.getFontSize() / 2;\n\n if (isTouchEvent) {\n pageCoordY = currentPoints.page.y - textStyle.getFontSize() * 4;\n }\n const toolCoords = cornerstone.pageToPixel(\n element,\n currentPoints.page.x,\n pageCoordY\n );\n\n if (\n toolCoords.x < 0 ||\n toolCoords.y < 0 ||\n toolCoords.x >= image.columns ||\n toolCoords.y >= image.rows\n ) {\n return;\n }\n\n draw(context, context => {\n setShadow(context, config);\n\n const seriesModule = cornerstone.metaData.get(\n 'generalSeriesModule',\n image.imageId\n );\n const modality = seriesModule && seriesModule.modality;\n\n let storedPixels;\n let text = '';\n\n if (image.color) {\n storedPixels = getRGBPixels(element, toolCoords.x, toolCoords.y, 1, 1);\n text = `R: ${storedPixels[0]} G: ${storedPixels[1]} B: ${\n storedPixels[2]\n }`;\n } else {\n storedPixels = cornerstone.getStoredPixels(\n element,\n toolCoords.x,\n toolCoords.y,\n 1,\n 1\n );\n const sp = storedPixels[0];\n const mo = sp * image.slope + image.intercept;\n\n const modalityPixelValueText = parseFloat(mo.toFixed(2));\n\n if (modality === 'CT') {\n text += `HU: ${modalityPixelValueText}`;\n } else if (modality === 'PT') {\n text += modalityPixelValueText;\n const suv = calculateSUV(image, sp);\n\n if (suv) {\n text += ` SUV: ${parseFloat(suv.toFixed(2))}`;\n }\n } else {\n text += modalityPixelValueText;\n }\n }\n\n // Prepare text\n const textCoords = cornerstone.pixelToCanvas(element, toolCoords);\n\n // Translate the x/y away from the cursor\n let translation = {\n x: 12,\n y: -(textStyle.getFontSize() + 10) / 2,\n };\n\n const handleRadius = 6;\n const padding = 5;\n const width = textBoxWidth(context, text, padding);\n\n if (isTouchEvent) {\n translation = {\n x: -width / 2,\n y: -textStyle.getFontSize() - 10 - 2 * handleRadius,\n };\n }\n\n drawCircle(context, element, textCoords, handleRadius, { color }, 'canvas');\n drawTextBox(\n context,\n text,\n textCoords.x + translation.x,\n textCoords.y + translation.y,\n color\n );\n });\n};\n","import external from '../externalModules.js';\nimport BaseTool from './base/BaseTool.js';\nimport { getToolState, removeToolState } from '../stateManagement/toolState.js';\nimport { state } from '../store/index.js';\n\n/**\n * @public\n * @class EraserTool\n * @memberof Tools\n *\n * @classdesc Tool for deleting the data of other Annotation Tools.\n * @extends Tools.Base.BaseTool\n */\nexport default class EraserTool extends BaseTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'Eraser',\n supportedInteractionTypes: ['Mouse', 'Touch'],\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n\n this.preMouseDownCallback = this._deleteAllNearbyTools.bind(this);\n this.preTouchStartCallback = this._deleteAllNearbyTools.bind(this);\n }\n\n _deleteAllNearbyTools(evt) {\n const coords = evt.detail.currentPoints.canvas;\n const element = evt.detail.element;\n\n state.tools.forEach(function(tool) {\n const toolState = getToolState(element, tool.name);\n\n if (toolState) {\n // Modifying in a foreach? Probably not ideal\n toolState.data.forEach(function(data) {\n if (\n typeof tool.pointNearTool === 'function' &&\n tool.pointNearTool(element, data, coords)\n ) {\n removeToolState(element, tool.name, data);\n external.cornerstone.updateImage(element);\n }\n });\n }\n });\n\n const consumeEvent = true;\n\n return consumeEvent;\n }\n}\n","import EVENTS from '../events.js';\nimport external from '../externalModules.js';\nimport toolColors from '../stateManagement/toolColors.js';\nimport drawHandles from '../drawing/drawHandles.js';\nimport { state } from '../store/index.js';\nimport { getToolState } from '../stateManagement/toolState.js';\nimport { clipToBox } from '../util/clip.js';\nimport getToolForElement from '../store/getToolForElement.js';\nimport BaseTool from './base/BaseTool.js';\n\nimport freehandUtils from '../util/freehand/index.js';\n\nconst { FreehandHandleData } = freehandUtils;\n\n/**\n * @public\n * @class FreehandSculpterMouseTool\n * @memberof Tools\n *\n * @classdesc Tool for easily sculpting annotations drawn with\n * the FreehandMouseTool.\n * @extends Tools.Base.BaseTool\n */\nexport default class FreehandSculpterMouseTool extends BaseTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'FreehandSculpterMouse',\n referencedToolName: 'FreehandMouse',\n supportedInteractionTypes: ['Mouse'],\n mixins: ['activeOrDisabledBinaryTool'],\n configuration: getDefaultFreehandSculpterMouseToolConfiguration(),\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.hasCursor = true;\n this.initialConfiguration = initialConfiguration;\n this.referencedToolName = initialConfiguration.referencedToolName;\n\n this._active = false;\n\n // Create bound functions for private event loop.\n this.activeMouseUpCallback = this.activeMouseUpCallback.bind(this);\n this.activeMouseDragCallback = this.activeMouseDragCallback.bind(this);\n }\n\n renderToolData(evt) {\n const eventData = evt.detail;\n\n if (this.configuration.currentTool === null) {\n return false;\n }\n\n if (this._active) {\n const context = eventData.canvasContext.canvas.getContext('2d');\n const options = {\n color: this.configuration.dragColor,\n fill: null,\n handleRadius: this._toolSizeCanvas,\n };\n\n drawHandles(\n context,\n eventData,\n this.configuration.mouseLocation.handles,\n options\n );\n } else if (this.configuration.showCursorOnHover) {\n this._renderHoverCursor(evt);\n }\n }\n\n doubleClickCallback(evt) {\n const eventData = evt.detail;\n\n this._selectFreehandTool(eventData);\n\n external.cornerstone.updateImage(eventData.element);\n }\n\n /**\n * Event handler for MOUSE_DOWN.\n *\n * @param {Object} evt - The event.\n */\n preMouseDownCallback(evt) {\n const eventData = evt.detail;\n const config = this.configuration;\n\n const imageNeedsUpdate = false;\n\n if (config.currentTool === null) {\n this._selectFreehandTool(eventData);\n } else {\n this._initialiseSculpting(eventData);\n }\n\n external.cornerstone.updateImage(eventData.element);\n\n return true;\n }\n\n /**\n * Event handler for MOUSE_DRAG during the active loop.\n *\n * @event\n * @param {Object} evt - The event.\n */\n activeMouseDragCallback(evt) {\n const config = this.configuration;\n\n if (!this._active) {\n return;\n }\n\n const eventData = evt.detail;\n const toolState = getToolState(eventData.element, this.referencedToolName);\n\n if (!toolState) {\n return;\n }\n\n const dataHandles = toolState.data[config.currentTool].handles;\n\n // Set the mouseLocation handle\n this._getMouseLocation(eventData);\n this._sculpt(eventData, dataHandles);\n\n // Update the image\n external.cornerstone.updateImage(eventData.element);\n }\n\n /**\n * Event handler for MOUSE_UP during the active loop.\n *\n * @param {Object} evt - The event.\n */\n activeMouseUpCallback(evt) {\n const eventData = evt.detail;\n const element = eventData.element;\n const config = this.configuration;\n\n this._active = false;\n\n state.isToolLocked = false;\n\n this._getMouseLocation(eventData);\n this._invalidateToolData(eventData);\n\n config.mouseUpRender = true;\n\n this._deactivateSculpt(element);\n\n // Update the image\n external.cornerstone.updateImage(eventData.element);\n\n preventPropagation(evt);\n }\n\n /**\n * Renders the cursor\n *\n * @private\n * @param {type} evt description\n */\n _renderHoverCursor(evt) {\n const eventData = evt.detail;\n const element = eventData.element;\n const context = eventData.canvasContext.canvas.getContext('2d');\n\n const toolState = getToolState(element, this.referencedToolName);\n const data = toolState.data[this.configuration.currentTool];\n\n let coords;\n\n if (this.configuration.mouseUpRender) {\n coords = this.configuration.mouseLocation.handles.start;\n this.configuration.mouseUpRender = false;\n } else {\n coords = state.mousePositionImage;\n }\n\n const freehandMouseTool = getToolForElement(\n element,\n this.referencedToolName\n );\n let radiusCanvas = freehandMouseTool.distanceFromPointCanvas(\n element,\n data,\n coords\n );\n\n this.configuration.mouseLocation.handles.start.x = coords.x;\n this.configuration.mouseLocation.handles.start.y = coords.y;\n\n if (this.configuration.limitRadiusOutsideRegion) {\n const unlimitedRadius = radiusCanvas;\n\n radiusCanvas = this._limitCursorRadiusCanvas(eventData, radiusCanvas);\n\n // Fade if distant\n if (\n unlimitedRadius >\n this.configuration.hoverCursorFadeDistance * radiusCanvas\n ) {\n context.globalAlpha = this.configuration.hoverCursorFadeAlpha;\n }\n }\n\n const options = {\n fill: null,\n color: this.configuration.hoverColor,\n handleRadius: radiusCanvas,\n };\n\n drawHandles(\n context,\n eventData,\n this.configuration.mouseLocation.handles,\n options\n );\n\n if (this.configuration.limitRadiusOutsideRegion) {\n context.globalAlpha = 1.0; // Reset drawing alpha for other draw calls.\n }\n }\n\n /**\n * Event handler for NEW_IMAGE event.\n *\n * @public\n * @param {Object} evt - The event.\n */\n newImageCallback(evt) {\n this._deselectAllTools(evt);\n }\n\n /**\n * Event handler for switching mode to enabled.\n *\n * @public\n * @param {Object} evt - The event.\n */\n enabledCallback(evt) {\n this._deselectAllTools(evt);\n }\n\n /**\n * Event handler for switching mode to passive.\n *\n * @public\n * @param {Object} evt - The event.\n */\n passiveCallback(evt) {\n this._deselectAllTools(evt);\n }\n\n /**\n * Event handler for switching mode to disabled.\n *\n * @public\n * @param {Object} evt - The event.\n */\n disabledCallback(evt) {\n this._deselectAllTools(evt);\n }\n\n /**\n * Select the freehand tool to be edited.\n *\n * @private\n * @param {Object} eventData - Data object associated with the event.\n */\n _selectFreehandTool(eventData) {\n const config = this.configuration;\n const element = eventData.element;\n const closestToolIndex = this._getClosestFreehandToolOnElement(\n element,\n eventData\n );\n\n if (closestToolIndex === undefined) {\n return;\n }\n\n config.currentTool = closestToolIndex;\n }\n\n /**\n * Activate the selected freehand tool and deactivate others.\n *\n * @private\n * @param {Object} element - The parent element of the freehand tool.\n * @param {Number} toolIndex - The ID of the freehand tool.\n */\n\n _activateFreehandTool(element, toolIndex) {\n const toolState = getToolState(element, this.referencedToolName);\n const data = toolState.data;\n const config = this.configuration;\n\n config.currentTool = toolIndex;\n\n for (let i = 0; i < data.length; i++) {\n if (i === toolIndex) {\n data[i].active = true;\n } else {\n data[i].active = false;\n }\n }\n }\n\n /**\n * Choose the tool radius from the mouse position relative to the active freehand\n * tool, and begin sculpting.\n *\n * @private\n * @param {Object} eventData - Data object associated with the event.\n */\n _initialiseSculpting(eventData) {\n const element = eventData.element;\n const config = this.configuration;\n\n this._active = true;\n\n // Interupt event dispatcher\n state.isToolLocked = true;\n\n this._configureToolSize(eventData);\n this._getMouseLocation(eventData);\n\n this._activateFreehandTool(element, config.currentTool);\n this._activateSculpt(element);\n }\n\n /**\n * Sculpts the freehand ROI with the circular freehandSculpter tool, moving,\n * adding and removing handles as necessary.\n *\n * @private\n * @param {Object} eventData - Data object associated with the event.\n * @param {Object} dataHandles - Data object containing tool handle data.\n */\n _sculpt(eventData, dataHandles) {\n const config = this.configuration;\n\n const sculptData = {\n element: eventData.element,\n image: eventData.image,\n mousePoint: eventData.currentPoints.image,\n dataHandles,\n toolSize: this._toolSizeImage,\n minSpacing: config.minSpacing,\n maxSpacing: config.maxSpacing,\n };\n\n // Push existing handles radially away from tool.\n this._pushHandles(sculptData);\n // Insert new handles in sparsely populated areas.\n this._insertNewHandles(sculptData);\n // If any handles have been pushed very close together or even overlap,\n // Combine these into a single handle.\n this._consolidateHandles(sculptData);\n }\n\n /**\n * Pushes the handles in dataHandles radially away from the mouse if they are\n * contained within the circle defined by the freehandSculpter's toolSize and\n * the mouse position.\n *\n * @private\n * @param {Object} sculptData - Data object associated with the sculpt event.\n */\n _pushHandles(sculptData) {\n const dataHandles = sculptData.dataHandles;\n const mousePoint = sculptData.mousePoint;\n const toolSize = sculptData.toolSize;\n\n for (let i = 0; i < dataHandles.length; i++) {\n const distanceToHandle = external.cornerstoneMath.point.distance(\n dataHandles[i],\n mousePoint\n );\n\n // Push point if inside circle, to edge of circle.\n if (distanceToHandle < toolSize) {\n this._pushOneHandle(sculptData, i, distanceToHandle);\n }\n }\n }\n\n /**\n * Pushes one handle.\n *\n * @private\n * @param {Object} sculptData - Data object associated with the sculpt event.\n * @param {Number} i - The index of the handle to push.\n * @param {Number} distanceToHandle - The distance between the mouse cursor and the handle.\n */\n _pushOneHandle(sculptData, i, distanceToHandle) {\n const dataHandles = sculptData.dataHandles;\n const handle = dataHandles[i];\n const mousePoint = sculptData.mousePoint;\n const toolSize = sculptData.toolSize;\n const image = sculptData.image;\n\n const directionUnitVector = {\n x: (handle.x - mousePoint.x) / distanceToHandle,\n y: (handle.y - mousePoint.y) / distanceToHandle,\n };\n\n const position = {\n x: mousePoint.x + toolSize * directionUnitVector.x,\n y: mousePoint.y + toolSize * directionUnitVector.y,\n };\n\n clipToBox(position, image);\n\n handle.x = position.x;\n handle.y = position.y;\n\n // Push lines\n const lastHandleIndex = this.constructor._getPreviousHandleIndex(\n i,\n dataHandles.length\n );\n\n dataHandles[lastHandleIndex].lines.pop();\n dataHandles[lastHandleIndex].lines.push(handle);\n }\n\n /**\n * Inserts additional handles in sparsely sampled regions of the contour. The\n * new handles are placed on the circle defined by the the freehandSculpter's\n * toolSize and the mouse position.\n * @private\n * @param {Object} sculptData - Data object associated with the sculpt event.\n */\n _insertNewHandles(sculptData) {\n const indiciesToInsertAfter = this._findNewHandleIndicies(sculptData);\n let newIndexModifier = 0;\n\n for (let i = 0; i < indiciesToInsertAfter.length; i++) {\n const insertIndex = indiciesToInsertAfter[i] + 1 + newIndexModifier;\n\n this._insertHandleRadially(sculptData, insertIndex); // TODO\n newIndexModifier++;\n }\n }\n\n /**\n * Returns an array of indicies that describe where new handles should be\n * inserted (where the distance between subsequent handles is >\n * config.maxSpacing).\n *\n * @private\n * @param {Object} sculptData - Data object associated with the sculpt event.\n * @returns {Object} An array of indicies that describe where new handles should be inserted.\n */\n _findNewHandleIndicies(sculptData) {\n const element = sculptData.element;\n const dataHandles = sculptData.dataHandles;\n\n const indiciesToInsertAfter = [];\n\n for (let i = 0; i < dataHandles.length; i++) {\n const handleCanvas = external.cornerstone.pixelToCanvas(\n element,\n dataHandles[i]\n );\n const nextHandleIndex = this.constructor._getNextHandleIndex(\n i,\n dataHandles.length\n );\n\n const nextHandleCanvas = external.cornerstone.pixelToCanvas(\n element,\n dataHandles[nextHandleIndex]\n );\n const distanceToNextHandleCanvas = external.cornerstoneMath.point.distance(\n handleCanvas,\n nextHandleCanvas\n );\n\n if (distanceToNextHandleCanvas > sculptData.maxSpacing) {\n indiciesToInsertAfter.push(i);\n }\n }\n\n return indiciesToInsertAfter;\n }\n\n /**\n * Inserts a handle on the surface of the circle defined by toolSize and the\n * mousePoint.\n *\n * @private\n * @param {Object} sculptData - Data object associated with the sculpt event.\n * @param {Object} insertIndex - The index to insert the new handle.\n */\n _insertHandleRadially(sculptData, insertIndex) {\n const dataHandles = sculptData.dataHandles;\n\n const previousIndex = insertIndex - 1;\n const nextIndex = this.constructor._getNextHandleIndexBeforeInsert(\n insertIndex,\n dataHandles.length\n );\n const insertPosition = this.constructor._getInsertPosition(\n sculptData,\n insertIndex,\n previousIndex,\n nextIndex\n );\n const handleData = new FreehandHandleData(insertPosition);\n\n dataHandles.splice(insertIndex, 0, handleData);\n\n // Add the line from the previous handle to the inserted handle (note the tool is now one increment longer)\n dataHandles[previousIndex].lines.pop();\n dataHandles[previousIndex].lines.push(dataHandles[insertIndex]);\n\n // Add the line from the inserted handle to the handle after\n if (insertIndex === dataHandles.length - 1) {\n dataHandles[insertIndex].lines.push(dataHandles[0]);\n } else {\n dataHandles[insertIndex].lines.push(dataHandles[insertIndex + 1]);\n }\n }\n\n /**\n * Checks dataHandles for any very close handles and consolidates these to a\n * single handle.\n *\n * @private\n * @param {Object} sculptData - Data object associated with the sculpt event.\n */\n _consolidateHandles(sculptData) {\n const dataHandles = sculptData.dataHandles;\n\n if (dataHandles.length > 3) {\n // Don't merge handles if it would destroy the polygon.\n const closePairs = this._findCloseHandlePairs(sculptData);\n\n this._mergeCloseHandles(sculptData, closePairs);\n }\n }\n\n /**\n * Finds pairs of close handles with seperations < config.minSpacing. No handle\n * is included in more than one pair, to avoid spurious deletion of densely\n * populated regions of the contour (see mergeCloseHandles).\n *\n * @private\n * @param {Object} sculptData - Data object associated with the sculpt event.\n * @returns {Object} An array of close pairs in dataHandles.\n */\n _findCloseHandlePairs(sculptData) {\n const dataHandles = sculptData.dataHandles;\n const element = sculptData.element;\n const minSpacing = sculptData.minSpacing;\n\n const closePairs = [];\n\n let length = dataHandles.length;\n\n for (let i = 0; i < length; i++) {\n const handleCanvas = external.cornerstone.pixelToCanvas(\n element,\n dataHandles[i]\n );\n const nextHandleIndex = this.constructor._getNextHandleIndex(\n i,\n dataHandles.length\n );\n\n const nextHandleCanvas = external.cornerstone.pixelToCanvas(\n element,\n dataHandles[nextHandleIndex]\n );\n const distanceToNextHandleCanvas = external.cornerstoneMath.point.distance(\n handleCanvas,\n nextHandleCanvas\n );\n\n if (distanceToNextHandleCanvas < minSpacing) {\n const pair = [i, nextHandleIndex];\n\n closePairs.push(pair);\n\n // Don't check last node if first in pair to avoid double counting.\n if (i === 0) {\n length -= 1;\n }\n\n // Don't double count pairs in order to prevent your polygon collapsing to a singularity.\n i++;\n }\n }\n\n return closePairs;\n }\n\n /**\n * Merges handles in dataHandles given a list of close pairs. The handles are\n * merged in an iterative fashion to prevent generating a singularity in some\n * edge cases.\n *\n * @private\n * @param {Object} sculptData - Data object associated with the sculpt event.\n * @param {Object} closePairs - An array of pairs of handle indicies.\n */\n _mergeCloseHandles(sculptData, closePairs) {\n let removedIndexModifier = 0;\n\n for (let i = 0; i < closePairs.length; i++) {\n const pair = this.constructor._getCorrectedPair(\n closePairs[i],\n removedIndexModifier\n );\n\n this._combineHandles(sculptData, pair);\n removedIndexModifier++;\n }\n\n // Recursively remove problem childs\n const newClosePairs = this._findCloseHandlePairs(sculptData);\n\n if (newClosePairs.length) {\n this._mergeCloseHandles(sculptData, newClosePairs);\n }\n }\n\n /**\n * Combines two handles defined by the indicies in handlePairs.\n *\n * @private\n * @param {Object} sculptData - Data object associated with the sculpt event.\n * @param {Object} handlePair - A pair of handle indicies.\n */\n _combineHandles(sculptData, handlePair) {\n const dataHandles = sculptData.dataHandles;\n const image = sculptData.image;\n\n // Calculate combine position: half way between the handles.\n const midPoint = {\n x: (dataHandles[handlePair[0]].x + dataHandles[handlePair[1]].x) / 2.0,\n y: (dataHandles[handlePair[0]].y + dataHandles[handlePair[1]].y) / 2.0,\n };\n\n clipToBox(midPoint, image);\n\n // Move first point to midpoint\n dataHandles[handlePair[0]].x = midPoint.x;\n dataHandles[handlePair[0]].y = midPoint.y;\n\n // Link first point to handle that second point links to.\n const handleAfterPairIndex = this.constructor._getNextHandleIndex(\n handlePair[1],\n dataHandles.length\n );\n\n dataHandles[handlePair[0]].lines.pop();\n dataHandles[handlePair[0]].lines.push(dataHandles[handleAfterPairIndex]);\n\n // Remove the latter handle\n dataHandles.splice(handlePair[1], 1);\n }\n\n /**\n * Calculates the distance to the closest handle in the tool, and stores the\n * result in this._toolSizeImage and this._toolSizeCanvas.\n *\n * @private\n * @param {Object} eventData - Data object associated with the event.\n */\n _configureToolSize(eventData) {\n const element = eventData.element;\n const config = this.configuration;\n const toolIndex = config.currentTool;\n const coords = eventData.currentPoints.image;\n\n const toolState = getToolState(element, this.referencedToolName);\n const data = toolState.data[toolIndex];\n\n const freehandMouseTool = getToolForElement(\n element,\n this.referencedToolName\n );\n\n let radiusImage = freehandMouseTool.distanceFromPoint(\n element,\n data,\n coords\n );\n let radiusCanvas = freehandMouseTool.distanceFromPointCanvas(\n element,\n data,\n coords\n );\n\n // Check if should limit maximum size.\n if (config.limitRadiusOutsideRegion) {\n radiusImage = this._limitCursorRadiusImage(eventData, radiusImage);\n radiusCanvas = this._limitCursorRadiusCanvas(eventData, radiusCanvas);\n }\n\n this._toolSizeImage = radiusImage;\n this._toolSizeCanvas = radiusCanvas;\n }\n\n /**\n * Gets the current mouse location and stores it in the configuration object.\n *\n * @private\n * @param {Object} eventData - The data assoicated with the event.\n */\n _getMouseLocation(eventData) {\n const config = this.configuration;\n\n config.mouseLocation.handles.start.x = eventData.currentPoints.image.x;\n config.mouseLocation.handles.start.y = eventData.currentPoints.image.y;\n clipToBox(config.mouseLocation.handles.start, eventData.image);\n }\n\n /**\n * Attaches event listeners to the element such that is is visible, modifiable, and new data can be created.\n *\n * @private\n * @param {Object} element - The viewport element to attach event listeners to.\n * @modifies {element}\n */\n _activateSculpt(element) {\n this._deactivateSculpt(element);\n\n // Begin activeMouseDragCallback loop - call activeMouseUpCallback at end of drag or straight away if just a click.\n element.addEventListener(EVENTS.MOUSE_UP, this.activeMouseUpCallback);\n element.addEventListener(EVENTS.MOUSE_CLICK, this.activeMouseUpCallback);\n element.addEventListener(EVENTS.MOUSE_DRAG, this.activeMouseDragCallback);\n\n external.cornerstone.updateImage(element);\n }\n\n /**\n * Removes event listeners from the element.\n *\n * @private\n * @param {Object} element - The viewport element to remove event listeners from.\n * @modifies {element}\n */\n _deactivateSculpt(element) {\n element.removeEventListener(EVENTS.MOUSE_UP, this.activeMouseUpCallback);\n element.removeEventListener(EVENTS.MOUSE_CLICK, this.activeMouseUpCallback);\n element.removeEventListener(\n EVENTS.MOUSE_DRAG,\n this.activeMouseDragCallback\n );\n\n external.cornerstone.updateImage(element);\n }\n\n /**\n * Invalidate the freehand tool data, tirggering re-calculation of statistics.\n *\n * @private\n * @param {Object} eventData - Data object associated with the event.\n */\n _invalidateToolData(eventData) {\n const config = this.configuration;\n const element = eventData.element;\n const toolData = getToolState(element, this.referencedToolName);\n const data = toolData.data[config.currentTool];\n\n data.invalidated = true;\n }\n\n /**\n * Deactivates all freehand ROIs and change currentTool to null\n *\n * @private\n * @param {Object} evt - The event.\n */\n _deselectAllTools(evt) {\n const config = this.configuration;\n const toolData = getToolState(this.element, this.referencedToolName);\n\n config.currentTool = null;\n\n if (toolData) {\n for (let i = 0; i < toolData.data.length; i++) {\n toolData.data[i].active = false;\n }\n }\n\n external.cornerstone.updateImage(this.element);\n }\n\n /**\n * Given a pair of indicies, and the number of points already removed,\n * convert to the correct live indicies.\n *\n * @private\n * @static\n * @param {Object} pair A pairs of handle indicies.\n * @param {Number} removedIndexModifier The number of handles already removed.\n * @returns {Object} The corrected pair of handle indicies.\n */\n static _getCorrectedPair(pair, removedIndexModifier) {\n const correctedPair = [\n pair[0] - removedIndexModifier,\n pair[1] - removedIndexModifier,\n ];\n\n // Deal with edge case of last node + first node.\n if (correctedPair[1] < 0) {\n correctedPair[1] = 0;\n }\n\n return correctedPair;\n }\n\n /**\n * Limits the cursor radius so that it its maximum area is the same as the\n * ROI being sculpted (in canvas coordinates).\n *\n * @private\n * @param {Object} eventData Data object associated with the event.\n * @param {Number} radius The distance from the mouse to the ROI\n * in canvas coordinates.\n * @returns {Number} The limited radius in canvas coordinates.\n */\n _limitCursorRadiusCanvas(eventData, radiusCanvas) {\n return this._limitCursorRadius(eventData, radiusCanvas, true);\n }\n\n /**\n * Limits the cursor radius so that it its maximum area is the same as the\n * ROI being sculpted (in image coordinates).\n *\n * @private\n * @param {Object} eventData Data object associated with the event.\n * @param {Number} radius The distance from the mouse to the ROI\n * in image coordinates.\n * @returns {Number} The limited radius in image coordinates.\n */\n _limitCursorRadiusImage(eventData, radiusImage) {\n return this._limitCursorRadius(eventData, radiusImage, false);\n }\n\n /**\n * Limits the cursor radius so that it its maximum area is the same as the\n * ROI being sculpted.\n *\n * @private\n * @param {Object} eventData Data object associated with the event.\n * @param {Number} radius The distance from the mouse to the ROI.\n * @param {Boolean} canvasCoords Whether the calculation should be performed\n * In canvas coordinates.\n * @returns {Number} The limited radius.\n */\n _limitCursorRadius(eventData, radius, canvasCoords = false) {\n const element = eventData.element;\n const image = eventData.image;\n const config = this.configuration;\n\n const toolState = getToolState(element, this.referencedToolName);\n const data = toolState.data[config.currentTool];\n\n let areaModifier = 1.0;\n\n if (canvasCoords) {\n const topLeft = external.cornerstone.pixelToCanvas(element, {\n x: 0,\n y: 0,\n });\n const bottomRight = external.cornerstone.pixelToCanvas(element, {\n x: image.width,\n y: image.height,\n });\n const canvasArea =\n (bottomRight.x - topLeft.x) * (bottomRight.y - topLeft.y);\n\n areaModifier = canvasArea / (image.width * image.height);\n }\n\n const area = data.area * areaModifier;\n const maxRadius = Math.pow(area / Math.PI, 0.5);\n\n return Math.min(radius, maxRadius);\n }\n\n /**\n * Finds the nearest handle to the mouse cursor for all freehand\n * data on the element.\n *\n * @private\n * @param {Object} element - The element.\n * @param {Object} eventData - Data object associated with the event.\n * @returns {Number} The tool index of the closest freehand tool.\n */\n _getClosestFreehandToolOnElement(element, eventData) {\n const freehand = getToolForElement(element, this.referencedToolName);\n const toolState = getToolState(element, this.referencedToolName);\n\n if (!toolState) {\n return;\n }\n\n const data = toolState.data;\n const pixelCoords = eventData.currentPoints.image;\n\n const closest = {\n distance: Infinity,\n toolIndex: null,\n };\n\n for (let i = 0; i < data.length; i++) {\n const distanceFromToolI = freehand.distanceFromPoint(\n element,\n data[i],\n pixelCoords\n );\n\n if (distanceFromToolI === -1) {\n continue;\n }\n\n if (distanceFromToolI < closest.distance) {\n closest.distance = distanceFromToolI;\n closest.toolIndex = i;\n }\n }\n\n return closest.toolIndex;\n }\n\n /**\n * Returns the next handle index.\n *\n * @private\n * @static\n * @param {Number} i - The handle index.\n * @param {Number} length - The length of the polygon.\n * @returns {Number} The next handle index.\n */\n static _getNextHandleIndex(i, length) {\n if (i === length - 1) {\n return 0;\n }\n\n return i + 1;\n }\n\n /**\n * Returns the previous handle index.\n *\n * @private\n * @static\n * @param {Number} i - The handle index.\n * @param {Number} length - The length of the polygon.\n * @returns {Number} The previous handle index.\n */\n static _getPreviousHandleIndex(i, length) {\n if (i === 0) {\n return length - 1;\n }\n\n return i - 1;\n }\n\n /**\n * Returns the next handle index, with a correction considering a handle is\n * about to be inserted.\n *\n * @private\n * @static\n * @param {Number} insertIndex - The index in which the handle is being inserted.\n * @param {Number} length - The length of the polygon.\n * @returns {Number} The next handle index.\n */\n static _getNextHandleIndexBeforeInsert(insertIndex, length) {\n if (insertIndex === length) {\n return 0;\n }\n // Index correction here: The line bellow is correct, as we haven't inserted our handle yet!\n\n return insertIndex;\n }\n\n /**\n * Calculates the position that a new handle should be inserted.\n *\n * @private\n * @static\n * @param {Object} sculptData - Data object associated with the sculpt event.\n * @param {Number} insertIndex - The index to insert the new handle.\n * @param {Number} previousIndex - The previous index.\n * @param {Number} nextIndex - The next index.\n * @returns {Object} The position the handle should be inserted.\n */\n static _getInsertPosition(sculptData, insertIndex, previousIndex, nextIndex) {\n const toolSize = sculptData.toolSize;\n const mousePoint = sculptData.mousePoint;\n const dataHandles = sculptData.dataHandles;\n const image = sculptData.image;\n\n // Calculate insert position: half way between the handles, then pushed out\n // Radially to the edge of the freehandSculpter.\n const midPoint = {\n x: (dataHandles[previousIndex].x + dataHandles[nextIndex].x) / 2.0,\n y: (dataHandles[previousIndex].y + dataHandles[nextIndex].y) / 2.0,\n };\n\n const distanceToMidPoint = external.cornerstoneMath.point.distance(\n mousePoint,\n midPoint\n );\n\n let insertPosition;\n\n if (distanceToMidPoint < toolSize) {\n const directionUnitVector = {\n x: (midPoint.x - mousePoint.x) / distanceToMidPoint,\n y: (midPoint.y - mousePoint.y) / distanceToMidPoint,\n };\n\n insertPosition = {\n x: mousePoint.x + toolSize * directionUnitVector.x,\n y: mousePoint.y + toolSize * directionUnitVector.y,\n };\n } else {\n insertPosition = midPoint;\n }\n\n clipToBox(insertPosition, image);\n\n return insertPosition;\n }\n\n // ===================================================================\n // Public Configuration API. .\n // ===================================================================\n\n get minSpacing() {\n return this.configuration.minSpacing;\n }\n\n set minSpacing(value) {\n if (typeof value !== 'number') {\n throw new Error(\n 'Attempting to set freehandSculpter minSpacing to a value other than a number.'\n );\n }\n\n this.configuration.minSpacing = value;\n }\n\n get maxSpacing() {\n return this.configuration.maxSpacing;\n }\n\n set maxSpacing(value) {\n if (typeof value !== 'number') {\n throw new Error(\n 'Attempting to set freehandSculpter maxSpacing to a value other than a number.'\n );\n }\n\n this.configuration.maxSpacing = value;\n }\n\n get showCursorOnHover() {\n return this.configuration.showCursorOnHover;\n }\n\n set showCursorOnHover(value) {\n if (typeof value !== 'boolean') {\n throw new Error(\n 'Attempting to set freehandSculpter showCursorOnHover to a value other than a boolean.'\n );\n }\n\n this.configuration.showCursorOnHover = value;\n external.cornerstone.updateImage(this.element);\n }\n\n get limitRadiusOutsideRegion() {\n return this.configuration.limitRadiusOutsideRegion;\n }\n\n set limitRadiusOutsideRegion(value) {\n if (typeof value !== 'boolean') {\n throw new Error(\n 'Attempting to set freehandSculpter limitRadiusOutsideRegion to a value other than a boolean.'\n );\n }\n\n this.configuration.limitRadiusOutsideRegion = value;\n external.cornerstone.updateImage(this.element);\n }\n\n get hoverCursorFadeAlpha() {\n return this.configuration.hoverCursorFadeAlpha;\n }\n\n set hoverCursorFadeAlpha(value) {\n if (typeof value !== 'number') {\n throw new Error(\n 'Attempting to set freehandSculpter hoverCursorFadeAlpha to a value other than a number.'\n );\n }\n\n // Clamp the value from 0 to 1.\n value = Math.max(Math.min(value, 1.0), 0.0);\n\n this.configuration.hoverCursorFadeAlpha = value;\n external.cornerstone.updateImage(this.element);\n }\n\n get hoverCursorFadeDistance() {\n return this.configuration.hoverCursorFadeDistance;\n }\n\n set hoverCursorFadeDistance(value) {\n if (typeof value !== 'number') {\n throw new Error(\n 'Attempting to set freehandSculpter hoverCursorFadeDistance to a value other than a number.'\n );\n }\n\n // Don't allow to fade a distances smaller than the tool's radius.\n value = Math.max(value, 1.0);\n\n this.configuration.hoverCursorFadeDistance = value;\n external.cornerstone.updateImage(this.element);\n }\n}\n\n/**\n * Returns the default freehandSculpterMouseTool configuration.\n *\n * @returns {Object} The default configuration object.\n */\nfunction getDefaultFreehandSculpterMouseToolConfiguration() {\n return {\n mouseLocation: {\n handles: {\n start: {\n highlight: true,\n active: true,\n },\n },\n },\n minSpacing: 5,\n maxSpacing: 20,\n currentTool: null,\n dragColor: toolColors.getActiveColor(),\n hoverColor: toolColors.getToolColor(),\n\n /* --- Hover options ---\n showCursorOnHover: Shows a preview of the sculpting radius on hover.\n limitRadiusOutsideRegion: Limit max toolsize outside the subject ROI based\n on subject ROI area.\n hoverCursorFadeAlpha: Alpha to fade to when tool very distant from\n subject ROI.\n hoverCursorFadeDistance: Distance from ROI in which to fade the hoverCursor\n (in units of radii).\n */\n showCursorOnHover: true,\n limitRadiusOutsideRegion: true,\n hoverCursorFadeAlpha: 0.5,\n hoverCursorFadeDistance: 1.2,\n };\n}\n\nfunction preventPropagation(evt) {\n evt.stopImmediatePropagation();\n evt.stopPropagation();\n evt.preventDefault();\n}\n","import external from '../externalModules.js';\nimport { getNewContext } from '../drawing/index.js';\nimport BaseTool from './base/BaseTool.js';\n\n/**\n * @public\n * @class MagnifyTool\n * @memberof Tools\n *\n * @classdesc Tool for inspecting a region at increased magnification.\n * @extends Tools.Base.BaseTool\n */\nexport default class MagnifyTool extends BaseTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'Magnify',\n supportedInteractionTypes: ['Mouse', 'Touch'],\n configuration: {\n magnifySize: 300,\n magnificationLevel: 2,\n },\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n this.zoomCanvas = undefined;\n this.zoomElement = undefined;\n\n // Mode Callbacks: (element, options)\n this.activeCallback = this._createMagnificationCanvas.bind(this);\n this.enabledCallback = this._createMagnificationCanvas.bind(this);\n this.disabledCallback = this._destroyMagnificationCanvas.bind(this);\n\n // Touch\n this.postTouchStartCallback = this._addMagnifyingGlass.bind(this);\n this.touchDragCallback = this._updateMagnifyingGlass.bind(this);\n this.touchEndCallback = this._removeMagnifyingGlass.bind(this);\n this.touchDragEndCallback = this._removeMagnifyingGlass.bind(this);\n // Mouse\n this.postMouseDownCallback = this._addMagnifyingGlass.bind(this);\n this.mouseDragCallback = this._updateMagnifyingGlass.bind(this);\n this.mouseUpCallback = this._removeMagnifyingGlass.bind(this);\n // On quick clicks, mouseUp does not fire, but this does\n this.mouseClickCallback = this._removeMagnifyingGlass.bind(this);\n // Misc\n this.newImageCallback = this._drawMagnificationTool.bind(this);\n }\n\n _addMagnifyingGlass(evt) {\n // Ignore until next event\n this._removeZoomElement();\n this._drawZoomedElement(evt);\n // On next frame\n window.requestAnimationFrame(() => this._drawMagnificationTool(evt));\n\n evt.preventDefault();\n evt.stopPropagation();\n }\n\n _updateMagnifyingGlass(evt) {\n this._drawMagnificationTool(evt);\n\n evt.preventDefault();\n evt.stopPropagation();\n }\n\n _removeMagnifyingGlass(evt) {\n const element = evt.detail.element;\n\n element.querySelector('.magnifyTool').style.display = 'none';\n // Re-enable the mouse cursor\n document.body.style.cursor = 'default';\n this._removeZoomElement();\n }\n\n _drawMagnificationTool(evt) {\n const element = evt.detail.element;\n const magnifyCanvas = element.querySelector('.magnifyTool');\n\n if (!magnifyCanvas) {\n this._createMagnificationCanvas(element);\n }\n\n if (this.zoomCanvas === undefined) {\n return;\n }\n\n // The 'not' magnifyTool class here is necessary because cornerstone places\n // No classes of it's own on the canvas we want to select\n const canvas = element.querySelector('canvas:not(.magnifyTool)');\n const context = getNewContext(magnifyCanvas);\n\n // Calculate the on-canvas location of the mouse pointer / touch\n const canvasLocation = external.cornerstone.pixelToCanvas(\n evt.detail.element,\n evt.detail.currentPoints.image\n );\n\n // Shrink magnifier to smallest canvas dimension if smaller than desired magnifier size\n const magnifySize = Math.min(\n this.configuration.magnifySize,\n canvas.width,\n canvas.height\n );\n const magnificationLevel = this.configuration.magnificationLevel;\n\n magnifyCanvas.width = magnifySize;\n magnifyCanvas.height = magnifySize;\n\n // Constrain drag movement to zoomed image boundaries\n canvasLocation.x = Math.max(\n canvasLocation.x,\n (0.5 * magnifySize) / magnificationLevel\n );\n canvasLocation.x = Math.min(\n canvasLocation.x,\n canvas.width - (0.5 * magnifySize) / magnificationLevel\n );\n canvasLocation.y = Math.max(\n canvasLocation.y,\n (0.5 * magnifySize) / magnificationLevel\n );\n canvasLocation.y = Math.min(\n canvasLocation.y,\n canvas.height - (0.5 * magnifySize) / magnificationLevel\n );\n\n const copyFrom = {\n x: canvasLocation.x * magnificationLevel - 0.5 * magnifySize,\n y: canvasLocation.y * magnificationLevel - 0.5 * magnifySize,\n };\n\n copyFrom.x = Math.max(copyFrom.x, 0);\n copyFrom.y = Math.max(copyFrom.y, 0);\n\n context.drawImage(\n this.zoomCanvas,\n copyFrom.x,\n copyFrom.y,\n magnifySize,\n magnifySize,\n 0,\n 0,\n magnifySize,\n magnifySize\n );\n\n // Place the magnification tool at the same location as the pointer\n const touchOffset = evt.detail.isTouchEvent ? 120 : 0;\n const magnifyPosition = {\n top: Math.max(canvasLocation.y - 0.5 * magnifySize - touchOffset, 0),\n left: Math.max(canvasLocation.x - 0.5 * magnifySize, 0),\n };\n\n // Get full magnifier dimensions with borders\n const magnifierBox = magnifyCanvas.getBoundingClientRect();\n\n // Constrain magnifier to canvas boundaries\n magnifyPosition.top = Math.min(\n magnifyPosition.top,\n canvas.height - magnifierBox.height\n );\n magnifyPosition.left = Math.min(\n magnifyPosition.left,\n canvas.width - magnifierBox.width\n );\n magnifyCanvas.style.top = `${magnifyPosition.top}px`;\n magnifyCanvas.style.left = `${magnifyPosition.left}px`;\n magnifyCanvas.style.display = 'block';\n\n // Hide the mouse cursor, so the user can see better\n document.body.style.cursor = 'none';\n }\n\n /**\n * Creates a cornerstone enabled element, and renders the target image at the\n * desired magnification level using it.\n *\n * @private\n * @param {*} evt\n */\n _drawZoomedElement(evt) {\n const element = evt.detail.element;\n let enabledElement = evt.detail.enabledElement;\n\n if (enabledElement === undefined) {\n enabledElement = external.cornerstone.getEnabledElement(element);\n }\n\n const magnificationLevel = this.configuration.magnificationLevel;\n const origCanvas = enabledElement.canvas;\n const image = enabledElement.image;\n\n // Create a new cornerstone enabledElement\n this.zoomElement = document.createElement('div');\n this.zoomElement.width = origCanvas.width * magnificationLevel;\n this.zoomElement.height = origCanvas.height * magnificationLevel;\n external.cornerstone.enable(this.zoomElement, enabledElement.options);\n\n const zoomEnabledElement = external.cornerstone.getEnabledElement(\n this.zoomElement\n );\n const viewport = external.cornerstone.getViewport(enabledElement.element);\n\n this.zoomCanvas = zoomEnabledElement.canvas;\n this.zoomCanvas.width = origCanvas.width * magnificationLevel;\n this.zoomCanvas.height = origCanvas.height * magnificationLevel;\n\n zoomEnabledElement.viewport = Object.assign({}, viewport);\n\n // Update it's viewport to render at desired magnification level\n viewport.scale *= magnificationLevel;\n external.cornerstone.displayImage(this.zoomElement, image);\n external.cornerstone.setViewport(this.zoomElement, viewport);\n }\n\n /**\n * Removes the canvas and associated enabled element that's\n * used to render the zoomed image.\n *\n */\n _removeZoomElement() {\n if (this.zoomElement !== undefined) {\n external.cornerstone.disable(this.zoomCanvas);\n this.zoomElement = undefined;\n this.zoomCanvas = undefined;\n }\n }\n\n /**\n * The canvas used to render the zoomed image.\n * It will be displayed and clipped inside the magnifying glass frame/element.\n *\n * @private\n *\n * @param {*} element\n */\n _createMagnificationCanvas(element) {\n // If the magnifying glass canvas doesn't already exist\n if (element.querySelector('.magnifyTool') === null) {\n // Create a canvas and append it as a child to the element\n const magnifyCanvas = document.createElement('canvas');\n\n // The magnifyTool class is used to find the canvas later on\n // Make sure position is absolute so the canvas can follow the mouse / touch\n magnifyCanvas.classList.add('magnifyTool');\n magnifyCanvas.width = this.configuration.magnifySize;\n magnifyCanvas.height = this.configuration.magnifySize;\n magnifyCanvas.style.position = 'absolute';\n magnifyCanvas.style.display = 'none';\n element.appendChild(magnifyCanvas);\n }\n }\n\n /**\n *\n *\n * @param {*} evt\n */\n _destroyMagnificationCanvas(evt) {\n const element = evt.detail.element;\n const magnifyCanvas = element.querySelector('.magnifyTool');\n\n if (magnifyCanvas) {\n element.removeChild(magnifyCanvas);\n }\n }\n}\n","import external from '../externalModules.js';\nimport BaseTool from './base/BaseTool.js';\n// Drawing\nimport { getNewContext } from '../drawing/index.js';\n\n/**\n *\n * http://dicom.nema.org/dicom/2013/output/chtml/part03/sect_C.9.html\n *\n * @public\n * @class Overlay\n * @memberof Tools\n *\n * @classdesc Tool for displaying a scale overlay on the image.\n * @extends Tools.Base.BaseTool\n */\nexport default class OverlayTool extends BaseTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'Overlay',\n configuration: {},\n mixins: ['enabledOrDisabledBinaryTool'],\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n }\n\n enabledCallback(element) {\n this.forceImageUpdate(element);\n }\n\n disabledCallback(element) {\n this.forceImageUpdate(element);\n }\n\n forceImageUpdate(element) {\n const enabledElement = external.cornerstone.getEnabledElement(element);\n\n if (enabledElement.image) {\n external.cornerstone.updateImage(element);\n }\n }\n\n renderToolData(evt) {\n const eventData = evt.detail;\n\n if (\n !eventData ||\n !eventData.enabledElement ||\n !eventData.image ||\n !eventData.image.overlays ||\n !eventData.image.overlays.length === 0\n ) {\n return;\n }\n\n const context = getNewContext(eventData.canvasContext.canvas);\n const overlays = eventData.image.overlays;\n const { enabledElement, viewport } = eventData;\n\n const imageWidth =\n Math.abs(viewport.displayedArea.brhc.x - viewport.displayedArea.tlhc.x) *\n viewport.displayedArea.columnPixelSpacing;\n const imageHeight =\n Math.abs(viewport.displayedArea.brhc.y - viewport.displayedArea.tlhc.y) *\n viewport.displayedArea.rowPixelSpacing;\n\n context.save();\n\n overlays.forEach(overlay => {\n if (!overlay.visible) {\n return;\n }\n const layerCanvas = document.createElement('canvas');\n\n layerCanvas.width = imageWidth;\n layerCanvas.height = imageHeight;\n const layerContext = layerCanvas.getContext('2d');\n const transform = external.cornerstone.internal.getTransform(\n enabledElement\n );\n\n layerContext.setTransform(\n transform.m[0],\n transform.m[1],\n transform.m[2],\n transform.m[3],\n transform.m[4],\n transform.m[5]\n );\n layerContext.save();\n layerContext.setTransform(1, 0, 0, 1, 0, 0);\n layerContext.fillStyle = overlay.fillStyle;\n\n if (overlay.type === 'R') {\n layerContext.fillRect(0, 0, layerCanvas.width, layerCanvas.height);\n layerContext.globalCompositeOperation = 'xor';\n }\n\n let i = 0;\n\n for (let y = 0; y < overlay.rows; y++) {\n for (let x = 0; x < overlay.columns; x++) {\n if (overlay.pixelData[i++] > 0) {\n layerContext.fillRect(x, y, 1, 1);\n }\n }\n }\n layerContext.restore();\n context.drawImage(layerCanvas, 0, 0);\n });\n\n context.restore();\n }\n}\n","import external from '../externalModules.js';\nimport BaseTool from './base/BaseTool.js';\n\n/**\n * @public\n * @class PanMultiTouchTool\n * @memberof Tools\n *\n * @classdesc Tool for panning the image using multi-touch.\n * @extends Tools.Base.BaseTool\n */\nexport default class PanMultiTouchTool extends BaseTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'PanMultiTouch',\n supportedInteractionTypes: ['MultiTouch'],\n configuration: {\n touchPointers: 2,\n },\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n\n // Touch\n this.multiTouchDragCallback = this._dragCallback.bind(this);\n }\n\n _dragCallback(evt) {\n const eventData = evt.detail;\n const { element, viewport } = eventData;\n\n if (eventData.numPointers === this.configuration.touchPointers) {\n const translation = this._getTranslation(eventData);\n\n this._applyTranslation(viewport, translation);\n external.cornerstone.setViewport(element, viewport);\n }\n }\n\n _getTranslation(eventData) {\n const { viewport, image, deltaPoints } = eventData;\n\n let widthScale = viewport.scale;\n let heightScale = viewport.scale;\n\n if (image.rowPixelSpacing < image.columnPixelSpacing) {\n widthScale *= image.columnPixelSpacing / image.rowPixelSpacing;\n } else if (image.columnPixelSpacing < image.rowPixelSpacing) {\n heightScale *= image.rowPixelSpacing / image.columnPixelSpacing;\n }\n\n return {\n x: deltaPoints.page.x / widthScale,\n y: deltaPoints.page.y / heightScale,\n };\n }\n\n _applyTranslation(viewport, translation) {\n viewport.translation.x += translation.x;\n viewport.translation.y += translation.y;\n }\n}\n","import external from './../externalModules.js';\nimport BaseTool from './base/BaseTool.js';\n\n/**\n * @public\n * @class PanTool\n * @memberof Tools\n *\n * @classdesc Tool for panning the image.\n * @extends Tools.Base.BaseTool\n */\nexport default class PanTool extends BaseTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'Pan',\n supportedInteractionTypes: ['Mouse', 'Touch'],\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n // Touch\n this.touchDragCallback = this._dragCallback.bind(this);\n // Mouse\n this.mouseDragCallback = this._dragCallback.bind(this);\n }\n\n _dragCallback(evt) {\n const eventData = evt.detail;\n const { element, viewport } = eventData;\n\n const translation = this._getTranslation(eventData);\n\n this._applyTranslation(viewport, translation);\n external.cornerstone.setViewport(element, viewport);\n }\n\n _getTranslation(eventData) {\n const { viewport, image, deltaPoints } = eventData;\n\n let widthScale = viewport.scale;\n let heightScale = viewport.scale;\n\n if (image.rowPixelSpacing < image.columnPixelSpacing) {\n widthScale *= image.columnPixelSpacing / image.rowPixelSpacing;\n } else if (image.columnPixelSpacing < image.rowPixelSpacing) {\n heightScale *= image.rowPixelSpacing / image.columnPixelSpacing;\n }\n\n return {\n x: deltaPoints.page.x / widthScale,\n y: deltaPoints.page.y / heightScale,\n };\n }\n\n _applyTranslation(viewport, translation) {\n viewport.translation.x += translation.x;\n viewport.translation.y += translation.y;\n }\n}\n","import external from './../../externalModules.js';\nimport calculateReferenceLine from './calculateReferenceLine.js';\nimport toolColors from './../../stateManagement/toolColors.js';\nimport convertToVector3 from './../../util/convertToVector3.js';\nimport { draw, drawLine } from './../../drawing/index.js';\n\n/**\n * Renders the active reference line.\n *\n * @export @public @method\n * @name renderActiveReferenceLine\n * @param {Object} context The canvas context.\n * @param {Object} eventData The data associated with the event.\n * @param {HTMLElement} targetElement The element on which to render the reference line.\n * @param {HTMLElement} referenceElement The element referenced by the line.\n */\nexport default function(context, eventData, targetElement, referenceElement) {\n const cornerstone = external.cornerstone;\n const targetImage = cornerstone.getEnabledElement(targetElement).image;\n const referenceImage = cornerstone.getEnabledElement(referenceElement).image;\n\n // Make sure the images are actually loaded for the target and reference\n if (!targetImage || !referenceImage) {\n return;\n }\n\n const targetImagePlane = cornerstone.metaData.get(\n 'imagePlaneModule',\n targetImage.imageId\n );\n const referenceImagePlane = cornerstone.metaData.get(\n 'imagePlaneModule',\n referenceImage.imageId\n );\n\n // Make sure the target and reference actually have image plane metadata\n if (\n !targetImagePlane ||\n !referenceImagePlane ||\n !targetImagePlane.rowCosines ||\n !targetImagePlane.columnCosines ||\n !targetImagePlane.imagePositionPatient ||\n !referenceImagePlane.rowCosines ||\n !referenceImagePlane.columnCosines ||\n !referenceImagePlane.imagePositionPatient\n ) {\n return;\n }\n\n // The image planes must be in the same frame of reference\n if (\n targetImagePlane.frameOfReferenceUID !==\n referenceImagePlane.frameOfReferenceUID\n ) {\n return;\n }\n\n targetImagePlane.rowCosines = convertToVector3(targetImagePlane.rowCosines);\n targetImagePlane.columnCosines = convertToVector3(\n targetImagePlane.columnCosines\n );\n targetImagePlane.imagePositionPatient = convertToVector3(\n targetImagePlane.imagePositionPatient\n );\n referenceImagePlane.rowCosines = convertToVector3(\n referenceImagePlane.rowCosines\n );\n referenceImagePlane.columnCosines = convertToVector3(\n referenceImagePlane.columnCosines\n );\n referenceImagePlane.imagePositionPatient = convertToVector3(\n referenceImagePlane.imagePositionPatient\n );\n\n // The image plane normals must be > 30 degrees apart\n const targetNormal = targetImagePlane.rowCosines\n .clone()\n .cross(targetImagePlane.columnCosines);\n const referenceNormal = referenceImagePlane.rowCosines\n .clone()\n .cross(referenceImagePlane.columnCosines);\n let angleInRadians = targetNormal.angleTo(referenceNormal);\n\n angleInRadians = Math.abs(angleInRadians);\n if (angleInRadians < 0.5) {\n // 0.5 radians = ~30 degrees\n return;\n }\n\n const referenceLine = calculateReferenceLine(\n targetImagePlane,\n referenceImagePlane\n );\n\n if (!referenceLine) {\n return;\n }\n\n const color = toolColors.getActiveColor();\n\n // Draw the referenceLines\n context.setTransform(1, 0, 0, 1, 0, 0);\n\n draw(context, context => {\n drawLine(\n context,\n eventData.element,\n referenceLine.start,\n referenceLine.end,\n { color }\n );\n });\n}\n","import {\n planePlaneIntersection,\n projectPatientPointToImagePlane,\n} from './../../util/pointProjector.js';\n\n/**\n * Calculates a reference line between two planes by projecting the top left hand corner and bottom right hand corner\n * Of the reference image onto the target image. Ideally we would calculate the intersection between the planes but\n * That requires a bit more math and this works fine for most cases.\n *\n * @export\n * @public\n * @method\n * @name calculateReferenceLine\n * @param {Object} targetImagePlane The imagePlane on which the reference line will be drawn.\n * @param {Object} referenceImagePlane The imagePlane being referenced.\n * @returns {Object} The start and end points of the line to be drawn.\n */\nexport default function(targetImagePlane, referenceImagePlane) {\n const points = planePlaneIntersection(targetImagePlane, referenceImagePlane);\n\n if (!points) {\n return;\n }\n\n return {\n start: projectPatientPointToImagePlane(points.start, targetImagePlane),\n end: projectPatientPointToImagePlane(points.end, targetImagePlane),\n };\n}\n","import external from './../externalModules.js';\n\n/**\n * Waits a set amount of time, then resolves. Can be chained off of to delay\n * next call in promise chain.\n * @public\n * @function wait\n * @param {number} ms - number in ms to wait\n * @returns {Promise} - A promise that resolves when setTimeout elapses\n */\nexport const wait = ms => new Promise(resolve => setTimeout(resolve, ms));\n\n/**\n * A promise that returns an EnabledElement who's image has loaded, or\n * null if the provided element ceases being an enabledElement before an\n * image has been loaded.\n * @public\n * @function waitForEnabledElementImageToLoad\n *\n * @param {HTMLElement} element - An element that is an EnabledElement\n * @returns {EnabledElement} - The enabled element that has loaded an image\n */\nexport function waitForEnabledElementImageToLoad(element) {\n try {\n const enabledElement = external.cornerstone.getEnabledElement(element);\n\n if (!enabledElement.image) {\n return wait(250).then(() => waitForEnabledElementImageToLoad(element));\n }\n\n // EnabledElement's image is loaded.\n return enabledElement;\n } catch (ex) {\n // Is no longer, or never was an enabled element, stop polling\n return null;\n }\n}\n\nexport default wait;\n","let configMaxSimultaneousRequests;\n\n// Maximum concurrent connections to the same server\n// Information from http://sgdev-blog.blogspot.fr/2014/01/maximum-concurrent-connection-to-same.html\nconst maxSimultaneousRequests = {\n default: 6,\n IE: {\n 9: 6,\n 10: 8,\n default: 8,\n },\n Firefox: {\n default: 6,\n },\n Opera: {\n 10: 8,\n 11: 6,\n 12: 6,\n default: 6,\n },\n Chrome: {\n default: 6,\n },\n Safari: {\n default: 6,\n },\n};\n\n// Browser name / version detection\n//\n//\n\n/**\n * Browser name / version detection\n * http://stackoverflow.com/questions/2400935/browser-detection-in-javascript\n * @export @public @method\n * @name getBrowserInfo\n *\n * @returns {string} The name and version of the browser.\n */\nfunction getBrowserInfo() {\n const ua = navigator.userAgent;\n let M =\n ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\\/))\\/?\\s*(\\d+)/i) ||\n [];\n let tem;\n\n if (/trident/i.test(M[1])) {\n tem = /\\brv[ :]+(\\d+)/g.exec(ua) || [];\n\n return `IE ${tem[1] || ''}`;\n }\n\n if (M[1] === 'Chrome') {\n tem = ua.match(/\\b(OPR|Edge)\\/(\\d+)/);\n if (tem !== null) {\n return tem\n .slice(1)\n .join(' ')\n .replace('OPR', 'Opera');\n }\n }\n\n M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];\n if ((tem = ua.match(/version\\/(\\d+)/i)) !== null) {\n M.splice(1, 1, tem[1]);\n }\n\n return M.join(' ');\n}\n\n/**\n * Sets the maximum number of simultaneous requests.\n * @export @public @method\n * @name setMaxSimultaneousRequests\n *\n * @param {number} newMaxSimultaneousRequests The value.\n */\nfunction setMaxSimultaneousRequests(newMaxSimultaneousRequests) {\n configMaxSimultaneousRequests = newMaxSimultaneousRequests;\n}\n\n/**\n * Returns the maximum number of simultaneous requests.\n * @export @public @method\n * @name getMaxSimultaneousRequests\n *\n * @returns {number} The maximum number of simultaneous requests\n */\nfunction getMaxSimultaneousRequests() {\n if (configMaxSimultaneousRequests) {\n return configMaxSimultaneousRequests;\n }\n\n return getDefaultSimultaneousRequests();\n}\n\n/**\n * Returns the default number of simultaneous requests.\n * @export @public @method\n * @name getDefaultSimultaneousRequests\n *\n * @returns {number} The default number of simultaneous requests.\n */\nfunction getDefaultSimultaneousRequests() {\n const infoString = getBrowserInfo();\n const info = infoString.split(' ');\n const browserName = info[0];\n const browserVersion = info[1];\n const browserData = maxSimultaneousRequests[browserName];\n\n if (!browserData) {\n return maxSimultaneousRequests.default;\n }\n\n if (!browserData[browserVersion]) {\n return browserData.default;\n }\n\n return browserData[browserVersion];\n}\n\n/**\n * Checks if cornerstoneTools is operating on a mobile device.\n * @export @public @method\n * @name isMobileDevice\n *\n * @returns {boolean} True if running on a mobile device.\n */\nfunction isMobileDevice() {\n const pattern = new RegExp(\n 'Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini'\n );\n\n return pattern.test(navigator.userAgent);\n}\n\nexport {\n getDefaultSimultaneousRequests,\n getMaxSimultaneousRequests,\n setMaxSimultaneousRequests,\n getBrowserInfo,\n isMobileDevice,\n};\n","import external from './../externalModules.js';\nimport BaseTool from './base/BaseTool.js';\n\nimport { getNewContext } from '../drawing/index.js';\nimport renderActiveReferenceLine from './referenceLines/renderActiveReferenceLine.js';\nimport { waitForEnabledElementImageToLoad } from './../util/wait.js';\n\n/**\n * When enabled, this tool will display references lines for each source\n * enabledElement in the provided synchronizer. This tool can also be configured\n * to use a custom renderer for alternative reference line rendering behavior\n *\n * TODO: Need to watch for configuration changes to update ToolState\n * TODO:\n *\n * @export @public @class\n * @name ReferenceLinesTool\n * @classdesc Tool for displaying reference lines of other enabledElements\n * @extends Tools.Base.BaseTool\n */\nexport default class ReferenceLinesTool extends BaseTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'ReferenceLines',\n mixins: ['enabledOrDisabledBinaryTool'],\n configuration: {\n renderer: renderActiveReferenceLine,\n },\n };\n\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n this.initialConfiguration = initialConfiguration;\n this.renderer = null;\n this.synchronizationContext = null;\n }\n\n async enabledCallback(element, { synchronizationContext } = {}) {\n const renderer = this.configuration.renderer;\n const enabledElement = await waitForEnabledElementImageToLoad(element);\n\n if (!enabledElement || !renderer || !synchronizationContext) {\n // TODO: Unable to add tool state, image never loaded.\n // Should we `setToolDisabledForElement` here?\n console.warn(\n `Unable to enable ${\n this.name\n }. Exiting enable callback. Tool will be enabled, but will not render.`\n );\n\n return;\n }\n this.renderer = renderer;\n this.synchronizationContext = synchronizationContext;\n\n this.forceImageUpdate(element);\n }\n\n disabledCallback(element) {\n this.forceImageUpdate(element);\n }\n\n forceImageUpdate(element) {\n const enabledElement = external.cornerstone.getEnabledElement(element);\n\n if (enabledElement.image) {\n external.cornerstone.updateImage(element);\n }\n }\n\n renderToolData(evt) {\n const eventData = evt.detail;\n\n // No renderer or synch context? Adios\n if (!this.renderer || !this.synchronizationContext) {\n return;\n }\n\n // Get the enabled elements associated with this synchronization context and draw them\n const enabledElements = this.synchronizationContext.getSourceElements();\n const context = getNewContext(eventData.canvasContext.canvas);\n\n external.cornerstone.setToPixelCoordinateSystem(\n eventData.enabledElement,\n context\n );\n enabledElements.forEach(referenceEnabledElement => {\n // Don't draw ourselves\n if (referenceEnabledElement === evt.currentTarget) {\n return;\n }\n\n // Render it\n this.renderer(\n context,\n eventData,\n evt.currentTarget,\n referenceEnabledElement\n );\n });\n }\n}\n","/**\n * Calculates the (interior) angle in degrees from the initial mouse location\n * to the current mouse location in relation to the center point.\n * @public\n * @function angleBetweenPoints\n *\n * @param {Object} p0 The center point.\n * @param {Object} p1 The initial point.\n * @param {Object} p2 The final point.\n * @returns {Object} { angle, direction }\n */\nexport default (p0, p1, p2) => {\n const p12 = Math.sqrt(Math.pow(p0.x - p1.x, 2) + Math.pow(p0.y - p1.y, 2));\n const p13 = Math.sqrt(Math.pow(p0.x - p2.x, 2) + Math.pow(p0.y - p2.y, 2));\n const p23 = Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));\n\n const angle =\n (Math.acos(\n (Math.pow(p12, 2) + Math.pow(p13, 2) - Math.pow(p23, 2)) / (2 * p12 * p13)\n ) *\n 180) /\n Math.PI;\n\n // The direction of the angle (> 0 clockwise, < 0 anti-clockwise)\n const direction =\n (p1.x - p0.x) * (p2.y - p0.y) - (p1.y - p0.y) * (p2.x - p0.x);\n\n return {\n angle,\n direction,\n };\n};\n","import external from './../externalModules.js';\nimport BaseTool from './base/BaseTool.js';\nimport angleBetweenPoints from '../util/angleBetweenPoints.js';\n\n/**\n * @public\n * @class RotateTool\n * @memberof Tools\n *\n * @classdesc Tool for rotating the image.\n * @extends Tools.Base.BaseTool\n */\nexport default class RotateTool extends BaseTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'Rotate',\n strategies: {\n default: defaultStrategy,\n horizontal: horizontalStrategy,\n vertical: verticalStrategy,\n },\n defaultStrategy: 'default',\n supportedInteractionTypes: ['Mouse', 'Touch'],\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n }\n\n touchDragCallback(evt) {\n this.dragCallback(evt);\n }\n\n mouseDragCallback(evt) {\n this.dragCallback(evt);\n }\n\n postMouseDownCallback(evt) {\n this.initialRotation = evt.detail.viewport.rotation;\n }\n\n dragCallback(evt) {\n evt.detail.viewport.initialRotation = this.initialRotation;\n this.applyActiveStrategy(evt, this.configuration);\n external.cornerstone.setViewport(evt.detail.element, evt.detail.viewport);\n }\n}\n\nconst defaultStrategy = evt => {\n const eventData = evt.detail;\n const { element, viewport } = eventData;\n const initialRotation = viewport.initialRotation;\n\n // Calculate the center of the image\n const rect = element.getBoundingClientRect(element);\n const { clientWidth: width, clientHeight: height } = element;\n\n const initialPoints = {\n x: eventData.startPoints.client.x,\n y: eventData.startPoints.client.y,\n };\n const { scale, translation } = viewport;\n const centerPoints = {\n x: rect.left + width / 2 + translation.x * scale,\n y: rect.top + height / 2 + translation.y * scale,\n };\n\n const currentPoints = {\n x: eventData.currentPoints.client.x,\n y: eventData.currentPoints.client.y,\n };\n\n const angleInfo = angleBetweenPoints(\n centerPoints,\n initialPoints,\n currentPoints\n );\n\n if (angleInfo.direction < 0) {\n angleInfo.angle = -angleInfo.angle;\n }\n\n viewport.rotation = initialRotation + angleInfo.angle;\n};\n\nconst horizontalStrategy = evt => {\n const eventData = evt.detail;\n const { viewport, deltaPoints } = eventData;\n\n viewport.rotation += deltaPoints.page.x / viewport.scale;\n};\n\nconst verticalStrategy = evt => {\n const eventData = evt.detail;\n const { viewport, deltaPoints } = eventData;\n\n viewport.rotation += deltaPoints.page.y / viewport.scale;\n};\n","import external from './../externalModules.js';\nimport BaseTool from './base/BaseTool.js';\n\n/**\n * @public\n * @class RotateTouchTool\n * @memberof Tools\n *\n * @classdesc Tool for rotating the image using touch.\n * @extends Tools.Base.BaseTool\n */\nexport default class RotateTouchTool extends BaseTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'RotateTouch',\n supportedInteractionTypes: ['TouchRotate'],\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n }\n\n touchRotateCallback(evt) {\n const eventData = evt.detail;\n const { element, viewport, rotation } = eventData;\n\n viewport.rotation += rotation;\n external.cornerstone.setViewport(element, viewport);\n }\n}\n","import external from './../externalModules.js';\nimport BaseTool from './base/BaseTool.js';\n// Drawing\nimport { getNewContext, draw, setShadow, drawLine } from '../drawing/index.js';\nimport toolStyle from './../stateManagement/toolStyle.js';\nimport toolColors from './../stateManagement/toolColors.js';\n\n/**\n * @public\n * @class ScaleOverlayTool\n * @memberof Tools\n *\n * @classdesc Tool for displaying a scale overlay on the image.\n * @extends Tools.Base.BaseTool\n */\nexport default class ScaleOverlayTool extends BaseTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'ScaleOverlay',\n configuration: {\n minorTickLength: 12.5,\n majorTickLength: 25,\n },\n mixins: ['enabledOrDisabledBinaryTool'],\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n }\n\n enabledCallback(element) {\n this.forceImageUpdate(element);\n }\n\n disabledCallback(element) {\n this.forceImageUpdate(element);\n }\n\n forceImageUpdate(element) {\n const enabledElement = external.cornerstone.getEnabledElement(element);\n\n if (enabledElement.image) {\n external.cornerstone.updateImage(element);\n }\n }\n\n renderToolData(evt) {\n const eventData = evt.detail;\n\n const context = getNewContext(eventData.canvasContext.canvas);\n const { image, viewport, element } = eventData;\n\n let rowPixelSpacing = image.rowPixelSpacing;\n let colPixelSpacing = image.columnPixelSpacing;\n const imagePlane = external.cornerstone.metaData.get(\n 'imagePlaneModule',\n image.imageId\n );\n\n if (imagePlane) {\n rowPixelSpacing =\n imagePlane.rowPixelSpacing || imagePlane.rowImagePixelSpacing;\n colPixelSpacing =\n imagePlane.columnPixelSpacing || imagePlane.colImagePixelSpacing;\n }\n\n // Check whether pixel spacing is defined\n if (!rowPixelSpacing || !colPixelSpacing) {\n console.warn(\n `unable to define rowPixelSpacing or colPixelSpacing from data on ${\n this.name\n }'s renderToolData`\n );\n\n return;\n }\n\n const canvasSize = {\n width: context.canvas.width,\n height: context.canvas.height,\n };\n\n // Distance between intervals is 10mm\n const verticalIntervalScale = (10.0 / rowPixelSpacing) * viewport.scale;\n const horizontalIntervalScale = (10.0 / colPixelSpacing) * viewport.scale;\n\n // 0.1 and 0.05 gives margin to horizontal and vertical lines\n const hscaleBounds = computeScaleBounds(canvasSize, 0.25, 0.05);\n const vscaleBounds = computeScaleBounds(canvasSize, 0.05, 0.15);\n\n if (\n !canvasSize.width ||\n !canvasSize.height ||\n !hscaleBounds ||\n !vscaleBounds\n ) {\n return;\n }\n\n const color = toolColors.getToolColor();\n const lineWidth = toolStyle.getToolWidth();\n\n const imageAttributes = Object.assign(\n {},\n {\n hscaleBounds,\n vscaleBounds,\n verticalMinorTick: verticalIntervalScale,\n horizontalMinorTick: horizontalIntervalScale,\n verticalLine: {\n start: {\n x: vscaleBounds.bottomRight.x,\n y: vscaleBounds.topLeft.y,\n },\n end: {\n x: vscaleBounds.bottomRight.x,\n y: vscaleBounds.bottomRight.y,\n },\n },\n horizontalLine: {\n start: {\n x: hscaleBounds.topLeft.x,\n y: hscaleBounds.bottomRight.y,\n },\n end: {\n x: hscaleBounds.bottomRight.x,\n y: hscaleBounds.bottomRight.y,\n },\n },\n color,\n lineWidth,\n },\n this.configuration\n );\n\n draw(context, context => {\n setShadow(context, imageAttributes);\n\n // Draw vertical line\n drawLine(\n context,\n element,\n imageAttributes.verticalLine.start,\n imageAttributes.verticalLine.end,\n {\n color,\n lineWidth,\n },\n 'canvas'\n );\n drawVerticalScalebarIntervals(context, element, imageAttributes);\n\n // Draw horizontal line\n drawLine(\n context,\n element,\n imageAttributes.horizontalLine.start,\n imageAttributes.horizontalLine.end,\n {\n color,\n lineWidth,\n },\n 'canvas'\n );\n drawHorizontalScalebarIntervals(context, element, imageAttributes);\n });\n }\n}\n\n/**\n * Computes the max bound for scales on the image\n * @param {} canvasSize\n * @param {} horizontalReduction\n * @param {} verticalReduction\n */\nconst computeScaleBounds = (\n canvasSize,\n horizontalReduction,\n verticalReduction\n) => {\n const hReduction = horizontalReduction * Math.min(1000, canvasSize.width);\n const vReduction = verticalReduction * Math.min(1000, canvasSize.height);\n const canvasBounds = {\n left: hReduction,\n top: vReduction,\n width: canvasSize.width - 2 * hReduction,\n height: canvasSize.height - 2 * vReduction,\n };\n\n return {\n topLeft: {\n x: canvasBounds.left,\n y: canvasBounds.top,\n },\n bottomRight: {\n x: canvasBounds.left + canvasBounds.width,\n y: canvasBounds.top + canvasBounds.height,\n },\n };\n};\n\n/**\n * @param {} context\n * @param {} imageAttributes\n */\nconst drawVerticalScalebarIntervals = (context, element, imageAttributes) => {\n let i = 0;\n\n while (\n imageAttributes.verticalLine.start.y +\n i * imageAttributes.verticalMinorTick <=\n imageAttributes.vscaleBounds.bottomRight.y\n ) {\n const { color, lineWidth } = imageAttributes;\n const startPoint = {\n x: imageAttributes.verticalLine.start.x,\n y:\n imageAttributes.verticalLine.start.y +\n i * imageAttributes.verticalMinorTick,\n };\n\n const endPoint = {\n x: 0,\n y:\n imageAttributes.verticalLine.start.y +\n i * imageAttributes.verticalMinorTick,\n };\n\n if (i % 5 === 0) {\n endPoint.x =\n imageAttributes.verticalLine.start.x - imageAttributes.majorTickLength;\n } else {\n endPoint.x =\n imageAttributes.verticalLine.start.x - imageAttributes.minorTickLength;\n }\n\n drawLine(\n context,\n element,\n startPoint,\n endPoint,\n {\n color,\n lineWidth,\n },\n 'canvas'\n );\n\n i++;\n }\n};\n\nconst drawHorizontalScalebarIntervals = (context, element, imageAttributes) => {\n let i = 0;\n\n while (\n imageAttributes.horizontalLine.start.x +\n i * imageAttributes.horizontalMinorTick <=\n imageAttributes.hscaleBounds.bottomRight.x\n ) {\n const { color, lineWidth } = imageAttributes;\n const startPoint = {\n x:\n imageAttributes.horizontalLine.start.x +\n i * imageAttributes.horizontalMinorTick,\n y: imageAttributes.horizontalLine.start.y,\n };\n\n const endPoint = {\n x:\n imageAttributes.horizontalLine.start.x +\n i * imageAttributes.horizontalMinorTick,\n y: 0,\n };\n\n if (i % 5 === 0) {\n endPoint.y =\n imageAttributes.horizontalLine.start.y -\n imageAttributes.majorTickLength;\n } else {\n endPoint.y =\n imageAttributes.horizontalLine.start.y -\n imageAttributes.minorTickLength;\n }\n\n drawLine(\n context,\n element,\n startPoint,\n endPoint,\n {\n color,\n lineWidth,\n },\n 'canvas'\n );\n\n i++;\n }\n};\n","import external from '../externalModules.js';\nimport { getMaxSimultaneousRequests } from '../util/getMaxSimultaneousRequests.js';\n\nconst requestPool = {\n interaction: [],\n thumbnail: [],\n prefetch: [],\n};\n\nconst numRequests = {\n interaction: 0,\n thumbnail: 0,\n prefetch: 0,\n};\n\nlet maxNumRequests = {\n interaction: 6,\n thumbnail: 6,\n prefetch: 5,\n};\n\nlet awake = false;\nconst grabDelay = 20;\n\nfunction addRequest(\n element,\n imageId,\n type,\n preventCache,\n doneCallback,\n failCallback,\n addToBeginning\n) {\n if (!requestPool.hasOwnProperty(type)) {\n throw new Error(\n 'Request type must be one of interaction, thumbnail, or prefetch'\n );\n }\n\n if (!element || !imageId) {\n return;\n }\n\n // Describe the request\n const requestDetails = {\n type,\n imageId,\n preventCache,\n doneCallback,\n failCallback,\n };\n\n // If this imageId is in the cache, resolve it immediately\n const imageLoadObject = external.cornerstone.imageCache.getImageLoadObject(\n imageId\n );\n\n if (imageLoadObject) {\n imageLoadObject.promise.then(\n function(image) {\n doneCallback(image);\n },\n function(error) {\n failCallback(error);\n }\n );\n\n return;\n }\n\n if (addToBeginning) {\n // Add it to the beginning of the stack\n requestPool[type].unshift(requestDetails);\n } else {\n // Add it to the end of the stack\n requestPool[type].push(requestDetails);\n }\n\n // Wake up\n awake = true;\n}\n\nfunction clearRequestStack(type) {\n // Console.log('clearRequestStack');\n if (!requestPool.hasOwnProperty(type)) {\n throw new Error(\n 'Request type must be one of interaction, thumbnail, or prefetch'\n );\n }\n\n requestPool[type] = [];\n}\n\nfunction startAgain() {\n if (!awake) {\n return;\n }\n\n setTimeout(function() {\n startGrabbing();\n }, grabDelay);\n}\n\nfunction sendRequest(requestDetails) {\n const cornerstone = external.cornerstone;\n // Increment the number of current requests of this type\n const type = requestDetails.type;\n\n numRequests[type]++;\n\n awake = true;\n const imageId = requestDetails.imageId;\n const doneCallback = requestDetails.doneCallback;\n const failCallback = requestDetails.failCallback;\n\n // Check if we already have this image promise in the cache\n const imageLoadObject = cornerstone.imageCache.getImageLoadObject(imageId);\n\n if (imageLoadObject) {\n // If we do, remove from list (when resolved, as we could have\n // Pending prefetch requests) and stop processing this iteration\n imageLoadObject.promise.then(\n function(image) {\n numRequests[type]--;\n // Console.log(numRequests);\n\n doneCallback(image);\n startAgain();\n },\n function(error) {\n numRequests[type]--;\n // Console.log(numRequests);\n failCallback(error);\n startAgain();\n }\n );\n\n return;\n }\n\n function requestTypeToLoadPriority(requestDetails) {\n if (requestDetails.type === 'prefetch') {\n return -5;\n } else if (requestDetails.type === 'interactive') {\n return 0;\n } else if (requestDetails.type === 'thumbnail') {\n return 5;\n }\n }\n\n const priority = requestTypeToLoadPriority(requestDetails);\n\n let loader;\n\n if (requestDetails.preventCache === true) {\n loader = cornerstone.loadImage(imageId, {\n priority,\n type: requestDetails.type,\n });\n } else {\n loader = cornerstone.loadAndCacheImage(imageId, {\n priority,\n type: requestDetails.type,\n });\n }\n\n // Load and cache the image\n loader.then(\n function(image) {\n numRequests[type]--;\n // Console.log(numRequests);\n doneCallback(image);\n startAgain();\n },\n function(error) {\n numRequests[type]--;\n // Console.log(numRequests);\n failCallback(error);\n startAgain();\n }\n );\n}\n\nfunction startGrabbing() {\n // Begin by grabbing X images\n const maxSimultaneousRequests = getMaxSimultaneousRequests();\n\n maxNumRequests = {\n interaction: Math.max(maxSimultaneousRequests, 1),\n thumbnail: Math.max(maxSimultaneousRequests - 2, 1),\n prefetch: Math.max(maxSimultaneousRequests - 1, 1),\n };\n\n const currentRequests =\n numRequests.interaction + numRequests.thumbnail + numRequests.prefetch;\n const requestsToSend = maxSimultaneousRequests - currentRequests;\n\n for (let i = 0; i < requestsToSend; i++) {\n const requestDetails = getNextRequest();\n\n if (requestDetails) {\n sendRequest(requestDetails);\n }\n }\n}\n\nfunction getNextRequest() {\n if (\n requestPool.interaction.length &&\n numRequests.interaction < maxNumRequests.interaction\n ) {\n return requestPool.interaction.shift();\n }\n\n if (\n requestPool.thumbnail.length &&\n numRequests.thumbnail < maxNumRequests.thumbnail\n ) {\n return requestPool.thumbnail.shift();\n }\n\n if (\n requestPool.prefetch.length &&\n numRequests.prefetch < maxNumRequests.prefetch\n ) {\n return requestPool.prefetch.shift();\n }\n\n if (\n !requestPool.interaction.length &&\n !requestPool.thumbnail.length &&\n !requestPool.prefetch.length\n ) {\n awake = false;\n }\n\n return false;\n}\n\nfunction getRequestPool() {\n return requestPool;\n}\n\nexport default {\n addRequest,\n clearRequestStack,\n startGrabbing,\n getRequestPool,\n};\n","import EVENTS from '../events.js';\nimport external from '../externalModules.js';\nimport { getToolState } from '../stateManagement/toolState.js';\nimport requestPoolManager from '../requestPool/requestPoolManager.js';\nimport loadHandlerManager from '../stateManagement/loadHandlerManager.js';\nimport triggerEvent from '../util/triggerEvent.js';\n\n/**\n * Scrolls through the stack to the image index requested.\n * @export @public @method\n * @name scrollToIndex\n *\n * @param {type} element The element to scroll through.\n * @param {type} newImageIdIndex The target image index.\n */\nexport default function(element, newImageIdIndex) {\n const toolData = getToolState(element, 'stack');\n\n if (!toolData || !toolData.data || !toolData.data.length) {\n return;\n }\n\n const cornerstone = external.cornerstone;\n // If we have more than one stack, check if we have a stack renderer defined\n let stackRenderer;\n\n if (toolData.data.length > 1) {\n const stackRendererData = getToolState(element, 'stackRenderer');\n\n if (\n stackRendererData &&\n stackRendererData.data &&\n stackRendererData.data.length\n ) {\n stackRenderer = stackRendererData.data[0];\n }\n }\n\n const stackData = toolData.data[0];\n\n // Allow for negative indexing\n if (newImageIdIndex < 0) {\n newImageIdIndex += stackData.imageIds.length;\n }\n\n const startLoadingHandler = loadHandlerManager.getStartLoadHandler();\n const endLoadingHandler = loadHandlerManager.getEndLoadHandler();\n const errorLoadingHandler = loadHandlerManager.getErrorLoadingHandler();\n\n function doneCallback(image) {\n if (stackData.currentImageIdIndex !== newImageIdIndex) {\n return;\n }\n\n // Check if the element is still enabled in Cornerstone,\n // If an error is thrown, stop here.\n try {\n // TODO: Add 'isElementEnabled' to Cornerstone?\n cornerstone.getEnabledElement(element);\n } catch (error) {\n return;\n }\n\n if (stackRenderer) {\n stackRenderer.currentImageIdIndex = newImageIdIndex;\n stackRenderer.render(element, toolData.data);\n } else {\n cornerstone.displayImage(element, image);\n }\n\n if (endLoadingHandler) {\n endLoadingHandler(element, image);\n }\n }\n\n function failCallback(error) {\n const imageId = stackData.imageIds[newImageIdIndex];\n\n if (errorLoadingHandler) {\n errorLoadingHandler(element, imageId, error);\n }\n }\n\n if (newImageIdIndex === stackData.currentImageIdIndex) {\n return;\n }\n\n if (startLoadingHandler) {\n startLoadingHandler(element);\n }\n\n const eventData = {\n newImageIdIndex,\n direction: newImageIdIndex - stackData.currentImageIdIndex,\n };\n\n stackData.currentImageIdIndex = newImageIdIndex;\n const newImageId = stackData.imageIds[newImageIdIndex];\n\n // Retry image loading in cases where previous image promise\n // Was rejected, if the option is set\n /*\n\n Const config = stackScroll.getConfiguration();\n\n TODO: Revisit this. It appears that Core's imageCache is not\n keeping rejected promises anywhere, so we have no way to know\n if something was previously rejected.\n\n if (config && config.retryLoadOnScroll === true) {\n }\n */\n\n // Convert the preventCache value in stack data to a boolean\n const preventCache = Boolean(stackData.preventCache);\n\n let imagePromise;\n\n if (preventCache) {\n imagePromise = cornerstone.loadImage(newImageId);\n } else {\n imagePromise = cornerstone.loadAndCacheImage(newImageId);\n }\n\n imagePromise.then(doneCallback, failCallback);\n // Make sure we kick off any changed download request pools\n requestPoolManager.startGrabbing();\n\n triggerEvent(element, EVENTS.STACK_SCROLL, eventData);\n}\n","import EVENTS from '../events.js';\nimport scrollToIndex from './scrollToIndex.js';\nimport { getToolState } from '../stateManagement/toolState.js';\nimport clip from './clip.js';\nimport external from './../externalModules.js';\n\n/**\n * Scrolls through the stack.\n * @export @public @method\n * @name scroll\n *\n * @param {HTMLElement} element The element to scroll.\n * @param {number} images The number of images to scroll through.\n * @param {type} [loop = false] Whether to loop the scrolling.\n * @param {type} [allowSkipping = true] Whether frames can be skipped.\n */\nexport default function(element, images, loop = false, allowSkipping = true) {\n const toolData = getToolState(element, 'stack');\n\n if (!toolData || !toolData.data || !toolData.data.length) {\n return;\n }\n\n const stackData = toolData.data[0];\n\n if (!stackData.pending) {\n stackData.pending = [];\n }\n\n let newImageIdIndex = stackData.currentImageIdIndex + images;\n\n if (loop) {\n const nbImages = stackData.imageIds.length;\n\n newImageIdIndex %= nbImages;\n } else {\n newImageIdIndex = clip(newImageIdIndex, 0, stackData.imageIds.length - 1);\n }\n\n if (allowSkipping) {\n scrollToIndex(element, newImageIdIndex);\n } else {\n const pendingEvent = {\n index: newImageIdIndex,\n };\n\n stackData.pending.push(pendingEvent);\n scrollWithoutSkipping(stackData, pendingEvent, element);\n }\n}\n\n/**\n * Recursively scrolls the stack until the desired image is reached.\n * @private\n * @method\n * @name scrollWithoutSkipping\n *\n * @param {type} stackData Data object containing information about the stack.\n * @param {Object} pendingEvent The event to process next.\n * @param {HTMLElement} element The element being scrolled through.\n */\nfunction scrollWithoutSkipping(stackData, pendingEvent, element) {\n if (stackData.pending[0] === pendingEvent) {\n if (stackData.currentImageIdIndex === pendingEvent.index) {\n stackData.pending.splice(stackData.pending.indexOf(pendingEvent), 1);\n\n if (stackData.pending.length > 0) {\n scrollWithoutSkipping(stackData, stackData.pending[0], element);\n }\n\n return;\n }\n\n const newImageHandler = function(event) {\n const index = stackData.imageIds.indexOf(event.detail.image.imageId);\n\n if (index === pendingEvent.index) {\n stackData.pending.splice(stackData.pending.indexOf(pendingEvent), 1);\n element.removeEventListener(\n external.cornerstone.EVENTS.NEW_IMAGE,\n newImageHandler\n );\n\n if (stackData.pending.length > 0) {\n scrollWithoutSkipping(stackData, stackData.pending[0], element);\n }\n }\n };\n\n element.addEventListener(\n external.cornerstone.EVENTS.NEW_IMAGE,\n newImageHandler\n );\n\n scrollToIndex(element, pendingEvent.index);\n }\n}\n","import BaseTool from './base/BaseTool.js';\nimport scroll from '../util/scroll.js';\n\n/**\n * @public\n * @class StackScrollMouseWheelTool\n * @memberof Tools\n *\n * @classdesc Tool for scrolling through a series using the mouse wheel.\n * @extends Tools.Base.BaseTool\n */\nexport default class StackScrollMouseWheelTool extends BaseTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'StackScrollMouseWheel',\n supportedInteractionTypes: ['MouseWheel'],\n configuration: {\n loop: false,\n allowSkipping: true,\n invert: false,\n },\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n }\n\n mouseWheelCallback(evt) {\n const { direction: images, element } = evt.detail;\n const { loop, allowSkipping, invert } = this.configuration;\n const direction = invert ? -images : images;\n\n scroll(element, direction, loop, allowSkipping);\n }\n}\n","import BaseTool from './base/BaseTool.js';\nimport scroll from '../util/scroll.js';\nimport { getToolState } from '../stateManagement/toolState.js';\nimport { setToolOptions, getToolOptions } from '../toolOptions.js';\n\n/**\n * @public\n * @class StackScrollMultiTouchTool\n * @memberof Tools\n *\n * @classdesc Tool for scrolling through a series using multi-touch.\n * @extends Tools.Base.BaseTool\n */\nexport default class StackScrollMultiTouchTool extends BaseTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'StackScrollMultiTouch',\n supportedInteractionTypes: ['MultiTouch'],\n configuration: {\n loop: false,\n allowSkipping: true,\n touchPointers: 3,\n },\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n this.multiTouchDragCallback = this._dragCallback.bind(this);\n }\n\n _dragCallback(evt) {\n const eventData = evt.detail;\n\n if (eventData.numPointers === this.configuration.touchPointers) {\n const { element, deltaPoints } = eventData;\n const { loop, allowSkipping } = this.configuration;\n const options = getToolOptions(this.name, element);\n\n const pixelsPerImage = this._getPixelPerImage(element);\n const deltaY = this._getDeltaY(element, deltaPoints.page.y);\n\n if (!pixelsPerImage) {\n return;\n }\n\n if (Math.abs(deltaY) >= pixelsPerImage) {\n const imageIdIndexOffset = Math.round(deltaY / pixelsPerImage);\n\n scroll(element, imageIdIndexOffset, loop, allowSkipping);\n\n options.deltaY = deltaY % pixelsPerImage;\n } else {\n options.deltaY = deltaY;\n }\n\n setToolOptions(this.name, element, options);\n }\n }\n\n _getDeltaY(element, deltaPointsY) {\n const options = getToolOptions(this.name, element);\n const deltaY = options.deltaY || 0;\n\n return deltaY + deltaPointsY;\n }\n\n _getPixelPerImage(element) {\n const toolData = getToolState(element, 'stack');\n\n if (!toolData || !toolData.data || !toolData.data.length) {\n return;\n }\n\n const stackData = toolData.data[0];\n const { stackScrollSpeed } = this.configuration;\n\n // The Math.max here makes it easier to mouseDrag-scroll small or really large image stacks\n return (\n stackScrollSpeed ||\n Math.max(2, element.offsetHeight / Math.max(stackData.imageIds.length, 8))\n );\n }\n}\n","import BaseTool from './base/BaseTool.js';\nimport scroll from '../util/scroll.js';\nimport { getToolState } from '../stateManagement/toolState.js';\nimport { setToolOptions, getToolOptions } from '../toolOptions.js';\n\n/**\n * @public\n * @class StackScrollTool\n * @memberof Tools\n *\n * @classdesc Tool for scrolling through a series.\n * @extends Tools.Base.BaseTool\n */\nexport default class StackScrollTool extends BaseTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'StackScroll',\n supportedInteractionTypes: ['Mouse', 'Touch'],\n configuration: {\n loop: false,\n allowSkipping: true,\n },\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n\n this.mouseDragCallback = this._dragCallback.bind(this);\n this.touchDragCallback = this._dragCallback.bind(this);\n }\n\n _dragCallback(evt) {\n const eventData = evt.detail;\n const { element, deltaPoints } = eventData;\n const { loop, allowSkipping } = this.configuration;\n const options = getToolOptions(this.name, element);\n\n const pixelsPerImage = this._getPixelPerImage(element);\n const deltaY = this._getDeltaY(element, deltaPoints.page.y);\n\n if (!pixelsPerImage) {\n return;\n }\n\n if (Math.abs(deltaY) >= pixelsPerImage) {\n const imageIdIndexOffset = Math.round(deltaY / pixelsPerImage);\n\n scroll(element, imageIdIndexOffset, loop, allowSkipping);\n\n options.deltaY = deltaY % pixelsPerImage;\n } else {\n options.deltaY = deltaY;\n }\n\n setToolOptions(this.name, element, options);\n }\n\n _getDeltaY(element, deltaPointsY) {\n const options = getToolOptions(this.name, element);\n const deltaY = options.deltaY || 0;\n\n return deltaY + deltaPointsY;\n }\n\n _getPixelPerImage(element) {\n const toolData = getToolState(element, 'stack');\n\n if (!toolData || !toolData.data || !toolData.data.length) {\n return;\n }\n\n const stackData = toolData.data[0];\n const { stackScrollSpeed } = this.configuration;\n\n // The Math.max here makes it easier to mouseDrag-scroll small or really large image stacks\n return (\n stackScrollSpeed ||\n Math.max(2, element.offsetHeight / Math.max(stackData.imageIds.length, 8))\n );\n }\n}\n","import external from '../externalModules.js';\n\n/**\n * Returns the luminance of a region.\n * @public\n * @function getLuminance\n *\n * @param {HTMLElement} element The element.\n * @param {number} x The x position of the top-left corner of the region.\n * @param {number} y The y position of the top-left corner of the region.\n * @param {number} width The width of the region.\n * @param {number} height The height of the region\n * @returns {number[]} The luminance.\n */\nexport default function(element, x, y, width, height) {\n if (!element) {\n throw new Error('getLuminance: parameter element must not be undefined');\n }\n\n x = Math.round(x);\n y = Math.round(y);\n const enabledElement = external.cornerstone.getEnabledElement(element);\n const image = enabledElement.image;\n const luminance = [];\n let index = 0;\n const pixelData = image.getPixelData();\n let spIndex, row, column;\n\n if (image.color) {\n for (row = 0; row < height; row++) {\n for (column = 0; column < width; column++) {\n spIndex = ((row + y) * image.columns + (column + x)) * 4;\n const red = pixelData[spIndex];\n const green = pixelData[spIndex + 1];\n const blue = pixelData[spIndex + 2];\n\n luminance[index++] = 0.2126 * red + 0.7152 * green + 0.0722 * blue;\n }\n }\n } else {\n for (row = 0; row < height; row++) {\n for (column = 0; column < width; column++) {\n spIndex = (row + y) * image.columns + (column + x);\n luminance[index++] = pixelData[spIndex] * image.slope + image.intercept;\n }\n }\n }\n\n return luminance;\n}\n","import external from '../externalModules.js';\nimport BaseTool from './base/BaseTool.js';\n// Drawing\nimport { draw, drawRect, getNewContext } from '../drawing/index.js';\nimport clip from '../util/clip.js';\nimport getLuminance from '../util/getLuminance.js';\nimport toolColors from '../stateManagement/toolColors.js';\n\n/**\n * @public\n * @class WwwcRegionTool\n * @memberof Tools\n *\n * @classdesc Tool for setting wwwc based on a rectangular region.\n * @extends Tools.Base.BaseTool\n */\nexport default class WwwcRegionTool extends BaseTool {\n /** @inheritdoc */\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'WwwcRegion',\n supportedInteractionTypes: ['Mouse', 'Touch'],\n configuration: {\n minWindowWidth: 10,\n },\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n this._resetHandles();\n\n //\n // Touch\n //\n\n /** @inheritdoc */\n this.postTouchStartCallback = this._startOutliningRegion.bind(this);\n\n /** @inheritdoc */\n this.touchDragCallback = this._setHandlesAndUpdate.bind(this);\n\n /** @inheritdoc */\n this.touchEndCallback = this._applyStrategy.bind(this);\n\n //\n // MOUSE\n //\n\n /** @inheritdoc */\n this.postMouseDownCallback = this._startOutliningRegion.bind(this);\n\n /** @inheritdoc */\n this.mouseClickCallback = this._startOutliningRegion.bind(this);\n\n /** @inheritdoc */\n this.mouseDragCallback = this._setHandlesAndUpdate.bind(this);\n\n /** @inheritdoc */\n this.mouseMoveCallback = this._setHandlesAndUpdate.bind(this);\n\n /** @inheritdoc */\n this.mouseUpCallback = this._applyStrategy.bind(this);\n }\n\n /**\n * Render hook: draws the WWWCRegion's \"box\" when selecting\n *\n * @param {Cornerstone.event:cornerstoneimagerendered} evt cornerstoneimagerendered event\n * @memberof Tools.WwwcRegionTool\n * @returns {undefined}\n */\n renderToolData(evt) {\n const eventData = evt.detail;\n const { element } = eventData;\n const color = toolColors.getColorIfActive({ active: true });\n const context = getNewContext(eventData.canvasContext.canvas);\n\n draw(context, context => {\n drawRect(context, element, this.handles.start, this.handles.end, {\n color,\n });\n });\n }\n\n /**\n * Sets the start handle point and claims the eventDispatcher event\n *\n * @private\n * @param {*} evt // mousedown, touchstart, click\n * @returns {Boolean} True\n */\n _startOutliningRegion(evt) {\n const consumeEvent = true;\n const element = evt.detail.element;\n const image = evt.detail.currentPoints.image;\n\n if (_isEmptyObject(this.handles.start)) {\n this.handles.start = image;\n } else {\n this.handles.end = image;\n this._applyStrategy(evt);\n }\n\n external.cornerstone.updateImage(element);\n\n return consumeEvent;\n }\n\n /**\n * This function will update the handles and updateImage to force re-draw\n *\n * @private\n * @method _setHandlesAndUpdate\n * @param {(CornerstoneTools.event:cornerstonetoolstouchdrag|CornerstoneTools.event:cornerstonetoolsmousedrag|CornerstoneTools.event:cornerstonetoolsmousemove)} evt Interaction event emitted by an enabledElement\n * @returns {undefined}\n */\n _setHandlesAndUpdate(evt) {\n const element = evt.detail.element;\n const image = evt.detail.currentPoints.image;\n\n this.handles.end = image;\n external.cornerstone.updateImage(element);\n }\n\n /**\n * Event handler for MOUSE_UP/TOUCH_END during handle drag event loop.\n *\n * @private\n * @method _applyStrategy\n * @param {(CornerstoneTools.event:cornerstonetoolsmouseup|CornerstoneTools.event:cornerstonetoolstouchend)} evt Interaction event emitted by an enabledElement\n * @returns {undefined}\n */\n _applyStrategy(evt) {\n if (\n _isEmptyObject(this.handles.start) ||\n _isEmptyObject(this.handles.end)\n ) {\n return;\n }\n\n evt.detail.handles = this.handles;\n _applyWWWCRegion(evt, this.configuration);\n this._resetHandles();\n }\n\n /**\n * Sets the start and end handle points to empty objects\n *\n * @private\n * @method _resetHandles\n * @returns {undefined}\n */\n _resetHandles() {\n this.handles = {\n start: {},\n end: {},\n };\n }\n}\n\n/**\n * Helper to determine if an object has no keys and is the correct type (is empty)\n *\n * @private\n * @function _isEmptyObject\n * @param {Object} obj The object to check\n * @returns {Boolean} true if the object is empty\n */\nconst _isEmptyObject = obj =>\n Object.keys(obj).length === 0 && obj.constructor === Object;\n\n/**\n * Calculates the minimum and maximum value in the given pixel array\n * and updates the viewport of the element in the event.\n *\n * @private\n * @method _applyWWWCRegion\n * @param {(CornerstoneTools.event:cornerstonetoolsmouseup|CornerstoneTools.event:cornerstonetoolstouchend)} evt Interaction event emitted by an enabledElement\n * @param {Object} config The tool's configuration object\n * @returns {undefined}\n */\nconst _applyWWWCRegion = function(evt, config) {\n const eventData = evt.detail;\n const { image, element } = eventData;\n const { start: startPoint, end: endPoint } = evt.detail.handles;\n\n // Get the rectangular region defined by the handles\n let left = Math.min(startPoint.x, endPoint.x);\n let top = Math.min(startPoint.y, endPoint.y);\n let width = Math.abs(startPoint.x - endPoint.x);\n let height = Math.abs(startPoint.y - endPoint.y);\n\n // Bound the rectangle so we don't get undefined pixels\n left = clip(left, 0, image.width);\n top = clip(top, 0, image.height);\n width = Math.floor(Math.min(width, Math.abs(image.width - left)));\n height = Math.floor(Math.min(height, Math.abs(image.height - top)));\n\n // Get the pixel data in the rectangular region\n const pixelLuminanceData = getLuminance(element, left, top, width, height);\n\n // Calculate the minimum and maximum pixel values\n const minMaxMean = _calculateMinMaxMean(\n pixelLuminanceData,\n image.minPixelValue,\n image.maxPixelValue\n );\n\n // Adjust the viewport window width and center based on the calculated values\n const viewport = eventData.viewport;\n\n if (config.minWindowWidth === undefined) {\n config.minWindowWidth = 10;\n }\n\n viewport.voi.windowWidth = Math.max(\n Math.abs(minMaxMean.max - minMaxMean.min),\n config.minWindowWidth\n );\n viewport.voi.windowCenter = minMaxMean.mean;\n\n external.cornerstone.setViewport(element, viewport);\n external.cornerstone.updateImage(element);\n};\n\n/**\n * Calculates the minimum, maximum, and mean value in the given pixel array\n *\n * @private\n * @method _calculateMinMaxMean\n * @param {number[]} pixelLuminance array of pixel luminance values\n * @param {number} globalMin starting \"min\" valie\n * @param {bumber} globalMax starting \"max\" value\n * @returns {Object} {min: number, max: number, mean: number }\n */\nconst _calculateMinMaxMean = function(pixelLuminance, globalMin, globalMax) {\n const numPixels = pixelLuminance.length;\n let min = globalMax;\n let max = globalMin;\n let sum = 0;\n\n if (numPixels < 2) {\n return {\n min,\n max,\n mean: (globalMin + globalMax) / 2,\n };\n }\n\n for (let index = 0; index < numPixels; index++) {\n const spv = pixelLuminance[index];\n\n min = Math.min(min, spv);\n max = Math.max(max, spv);\n sum += spv;\n }\n\n return {\n min,\n max,\n mean: sum / numPixels,\n };\n};\n","import external from '../externalModules.js';\nimport BaseTool from './base/BaseTool.js';\n\n/**\n * @public\n * @class WwwcTool\n * @memberof Tools\n *\n * @classdesc Tool for setting wwwc by dragging with mouse/touch.\n * @extends Tools.Base.BaseTool\n */\nexport default class WwwcTool extends BaseTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'Wwwc',\n strategies: { basicLevelingStrategy },\n supportedInteractionTypes: ['Mouse', 'Touch'],\n configuration: {\n orientation: 0,\n },\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n }\n\n mouseDragCallback(evt) {\n this.applyActiveStrategy(evt);\n external.cornerstone.setViewport(evt.detail.element, evt.detail.viewport);\n }\n\n touchDragCallback(evt) {\n // Prevent CornerstoneToolsTouchStartActive from killing any press events\n evt.stopImmediatePropagation();\n this.applyActiveStrategy(evt);\n external.cornerstone.setViewport(evt.detail.element, evt.detail.viewport);\n }\n}\n\n/**\n * Here we normalize the ww/wc adjustments so the same number of on screen pixels\n * adjusts the same percentage of the dynamic range of the image. This is needed to\n * provide consistency for the ww/wc tool regardless of the dynamic range (e.g. an 8 bit\n * image will feel the same as a 16 bit image would)\n *\n * @param eventData\n */\nfunction basicLevelingStrategy(evt, { orientation }) {\n const eventData = evt.detail;\n\n const maxVOI =\n eventData.image.maxPixelValue * eventData.image.slope +\n eventData.image.intercept;\n const minVOI =\n eventData.image.minPixelValue * eventData.image.slope +\n eventData.image.intercept;\n const imageDynamicRange = maxVOI - minVOI;\n const multiplier = imageDynamicRange / 1024;\n\n const deltaX = eventData.deltaPoints.page.x * multiplier;\n const deltaY = eventData.deltaPoints.page.y * multiplier;\n\n if (orientation === 0) {\n eventData.viewport.voi.windowWidth += deltaX;\n eventData.viewport.voi.windowCenter += deltaY;\n } else {\n eventData.viewport.voi.windowWidth += deltaY;\n eventData.viewport.voi.windowCenter += deltaX;\n }\n}\n","/**\n * Changes the scale of the viewport.\n *\n * @private\n * @function changeViewportScale\n *\n * @param {Object} viewport The viewport to scale.\n * @param {number} ticks The change in magnifcation factor.\n * @param {Object} scaleLimits The limits in scale.\n * @returns {Object} The scaled viewport.\n */\nexport default function(viewport, ticks, scaleLimits) {\n const { maxScale, minScale } = scaleLimits;\n const pow = 1.7;\n const oldFactor = Math.log(viewport.scale) / Math.log(pow);\n const factor = oldFactor + ticks;\n const scale = Math.pow(pow, factor);\n\n if (maxScale && scale > maxScale) {\n viewport.scale = maxScale;\n } else if (minScale && scale < minScale) {\n viewport.scale = minScale;\n } else {\n viewport.scale = scale;\n }\n\n return viewport;\n}\n","import changeViewportScale from './changeViewportScale.js';\nimport correctShift from './correctShift.js';\n\n// Named\nexport { changeViewportScale, correctShift };\n\n// Default\nexport default {\n changeViewportScale,\n correctShift,\n};\n","/**\n * Corrects the shift by accountoing for viewport rotation and flips.\n * @export @public @method\n * @name correctShift\n *\n * @param {Object} shift The shift to correct.\n * @param {Object} viewportOrientation Object containing information on the viewport orientation.\n * @returns {Object} The corrected shift.\n */\nexport default function(shift, viewportOrientation) {\n const { hflip, vflip, rotation } = viewportOrientation;\n\n // Apply Flips\n shift.x *= hflip ? -1 : 1;\n shift.y *= vflip ? -1 : 1;\n\n // Apply rotations\n if (rotation !== 0) {\n const angle = (rotation * Math.PI) / 180;\n\n const cosA = Math.cos(angle);\n const sinA = Math.sin(angle);\n\n const newX = shift.x * cosA - shift.y * sinA;\n const newY = shift.x * sinA + shift.y * cosA;\n\n shift.x = newX;\n shift.y = newY;\n }\n\n return shift;\n}\n","import external from './../externalModules.js';\nimport BaseTool from './base/BaseTool.js';\nimport { changeViewportScale } from '../util/zoom/index.js';\n\n/**\n * @public\n * @class ZoomMouseWheelTool\n * @memberof Tools\n *\n * @classdesc Tool for changing magnification with the mouse wheel.\n * @extends Tools.Base.BaseTool\n */\nexport default class ZoomMouseWheelTool extends BaseTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'ZoomMouseWheel',\n supportedInteractionTypes: ['MouseWheel'],\n configuration: {\n minScale: 0.25,\n maxScale: 20.0,\n invert: false,\n },\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n }\n\n mouseWheelCallback(evt) {\n const { element, viewport, spinY } = evt.detail;\n const { invert, maxScale, minScale } = this.configuration;\n const ticks = invert ? spinY / 4 : -spinY / 4;\n\n const updatedViewport = changeViewportScale(viewport, ticks, {\n maxScale,\n minScale,\n });\n\n external.cornerstone.setViewport(element, updatedViewport);\n }\n}\n","import external from '../externalModules.js';\nimport BaseTool from './base/BaseTool.js';\nimport { clipToBox } from '../util/clip.js';\nimport zoomUtils from '../util/zoom/index.js';\n\nconst { correctShift, changeViewportScale } = zoomUtils;\n\n/**\n * @public\n * @class ZoomTool\n * @memberof Tools\n *\n * @classdesc Tool for changing magnification.\n * @extends Tools.Base.BaseTool\n */\nexport default class ZoomTool extends BaseTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'Zoom',\n strategies: {\n default: defaultStrategy,\n translate: translateStrategy,\n zoomToCenter: zoomToCenterStrategy,\n },\n defaultStrategy: 'default',\n supportedInteractionTypes: ['Mouse', 'Touch'],\n configuration: {\n invert: false,\n preventZoomOutsideImage: false,\n minScale: 0.25,\n maxScale: 20.0,\n },\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n }\n\n touchDragCallback(evt) {\n dragCallback.call(this, evt);\n }\n\n mouseDragCallback(evt) {\n dragCallback.call(this, evt);\n }\n}\n\nconst dragCallback = function(evt) {\n const deltaY = evt.detail.deltaPoints.page.y;\n\n if (!deltaY) {\n return false;\n }\n\n this.applyActiveStrategy(evt, this.configuration);\n external.cornerstone.setViewport(evt.detail.element, evt.detail.viewport);\n};\n\n/**\n * The default strategy keeps the target location fixed on the page\n * as we zoom in/out.\n *\n * @param {*} evt\n * @param {*} { invert, maxScale, minScale }\n */\nfunction defaultStrategy(evt, { invert, maxScale, minScale }) {\n const deltaY = evt.detail.deltaPoints.page.y;\n const ticks = invert ? -deltaY / 100 : deltaY / 100;\n const { element, viewport } = evt.detail;\n const [startX, startY, imageX, imageY] = [\n evt.detail.startPoints.page.x,\n evt.detail.startPoints.page.y,\n evt.detail.startPoints.image.x,\n evt.detail.startPoints.image.y,\n ];\n\n // Calculate the new scale factor based on how far the mouse has changed\n const updatedViewport = changeViewportScale(viewport, ticks, {\n maxScale,\n minScale,\n });\n\n external.cornerstone.setViewport(element, updatedViewport);\n\n // Now that the scale has been updated, determine the offset we need to apply to the center so we can\n // Keep the original start location in the same position\n const newCoords = external.cornerstone.pageToPixel(element, startX, startY);\n\n // The shift we will use is the difference between the original image coordinates of the point we've selected\n // And the image coordinates of the same point on the page after the viewport scaling above has been performed\n // This shift is in image coordinates, and is designed to keep the target location fixed on the page.\n let shift = {\n x: imageX - newCoords.x,\n y: imageY - newCoords.y,\n };\n\n // Correct the required shift using the viewport rotation and flip parameters\n shift = correctShift(shift, updatedViewport);\n\n // Apply the shift to the Viewport's translation setting\n viewport.translation.x -= shift.x;\n viewport.translation.y -= shift.y;\n}\n\nfunction translateStrategy(\n evt,\n { invert, preventZoomOutsideImage, maxScale, minScale }\n) {\n const deltaY = evt.detail.deltaPoints.page.y;\n const ticks = invert ? -deltaY / 100 : deltaY / 100;\n const image = evt.detail.image;\n const viewport = evt.detail.viewport;\n const [startX, startY] = [\n evt.detail.startPoints.image.x,\n evt.detail.startPoints.image.y,\n ];\n\n // Calculate the new scale factor based on how far the mouse has changed\n // Note that in this case we don't need to update the viewport after the initial\n // Zoom step since we aren't don't intend to keep the target position static on\n // The page\n const updatedViewport = changeViewportScale(viewport, ticks, {\n maxScale,\n minScale,\n });\n\n // Define the default shift to take place during this zoom step\n const shift = {\n x: 0,\n y: 0,\n };\n\n // Define the parameters for the translate strategy\n const translateSpeed = 8;\n const outwardsMinScaleToTranslate = 3;\n const minTranslation = 0.01;\n\n if (ticks < 0) {\n // Zoom outwards from the image center\n if (updatedViewport.scale < outwardsMinScaleToTranslate) {\n // If the current translation is smaller than the minimum desired translation,\n // Set the translation to zero\n if (Math.abs(updatedViewport.translation.x) < minTranslation) {\n updatedViewport.translation.x = 0;\n } else {\n shift.x = updatedViewport.translation.x / translateSpeed;\n }\n\n // If the current translation is smaller than the minimum desired translation,\n // Set the translation to zero\n if (Math.abs(updatedViewport.translation.y) < minTranslation) {\n updatedViewport.translation.y = 0;\n } else {\n shift.y = updatedViewport.translation.y / translateSpeed;\n }\n }\n } else {\n // Zoom inwards to the current image point\n\n // Identify the coordinates of the point the user is trying to zoom into\n // If we are not allowed to zoom outside the image, bound the user-selected position to\n // A point inside the image\n if (preventZoomOutsideImage) {\n clipToBox(evt.detail.startPoints.image, image);\n }\n\n // Calculate the translation value that would place the desired image point in the center\n // Of the viewport\n let desiredTranslation = {\n x: image.width / 2 - startX,\n y: image.height / 2 - startY,\n };\n\n // Correct the target location using the viewport rotation and flip parameters\n desiredTranslation = correctShift(desiredTranslation, updatedViewport);\n\n // Calculate the difference between the current viewport translation value and the\n // Final desired translation values\n const distanceToDesired = {\n x: updatedViewport.translation.x - desiredTranslation.x,\n y: updatedViewport.translation.y - desiredTranslation.y,\n };\n\n // If the current translation is smaller than the minimum desired translation,\n // Stop translating in the x-direction\n if (Math.abs(distanceToDesired.x) < minTranslation) {\n updatedViewport.translation.x = desiredTranslation.x;\n } else {\n // Otherwise, shift the viewport by one step\n shift.x = distanceToDesired.x / translateSpeed;\n }\n\n // If the current translation is smaller than the minimum desired translation,\n // Stop translating in the y-direction\n if (Math.abs(distanceToDesired.y) < minTranslation) {\n updatedViewport.translation.y = desiredTranslation.y;\n } else {\n // Otherwise, shift the viewport by one step\n shift.y = distanceToDesired.y / translateSpeed;\n }\n }\n\n // Apply the shift to the Viewport's translation setting\n updatedViewport.translation.x -= shift.x;\n updatedViewport.translation.y -= shift.y;\n}\n\nfunction zoomToCenterStrategy(evt, { invert, maxScale, minScale }) {\n const deltaY = evt.detail.deltaPoints.page.y;\n const ticks = invert ? -deltaY / 100 : deltaY / 100;\n const viewport = evt.detail.viewport;\n\n // Calculate the new scale factor based on how far the mouse has changed\n changeViewportScale(viewport, ticks, {\n maxScale,\n minScale,\n });\n}\n","import external from './../externalModules.js';\nimport BaseTool from './base/BaseTool.js';\nimport zoomUtils from '../util/zoom/index.js';\n\nconst { correctShift } = zoomUtils;\n\n/**\n *\n *\n * @public\n * @class ZoomTouchPinchTool\n * @memberof Tools\n *\n * @extends {BaseTool}\n */\nexport default class ZoomTouchPinchTool extends BaseTool {\n constructor(configuration = {}) {\n const defaultConfig = {\n name: 'ZoomTouchPinch',\n // TODO: Do we need a better way to specify touchPinch?\n supportedInteractionTypes: ['TouchPinch'],\n configuration: {\n minScale: 0.25,\n maxScale: 20.0,\n },\n };\n const initialConfiguration = Object.assign(defaultConfig, configuration);\n\n super(initialConfiguration);\n\n this.initialConfiguration = initialConfiguration;\n }\n\n touchPinchCallback(evt) {\n const { element, viewport, scaleChange } = evt.detail;\n const [pageStartX, pageStartY, imageStartX, imageStartY] = [\n evt.detail.startPoints.page.x,\n evt.detail.startPoints.page.y,\n evt.detail.startPoints.image.x,\n evt.detail.startPoints.image.y,\n ];\n const { maxScale, minScale } = this.configuration;\n\n // Change the scale based on the pinch gesture's scale change\n viewport.scale += scaleChange * viewport.scale;\n if (maxScale && viewport.scale > maxScale) {\n viewport.scale = maxScale;\n } else if (minScale && viewport.scale < minScale) {\n viewport.scale = minScale;\n }\n\n external.cornerstone.setViewport(element, viewport);\n\n // Now that the scale has been updated, determine the offset we need to apply to the center so we can\n // Keep the original start location in the same position\n const newCoords = external.cornerstone.pageToPixel(\n element,\n pageStartX,\n pageStartY\n );\n let shift = {\n x: imageStartX - newCoords.x,\n y: imageStartY - newCoords.y,\n };\n\n shift = correctShift(shift, viewport);\n viewport.translation.x -= shift.x;\n viewport.translation.y -= shift.y;\n external.cornerstone.setViewport(element, viewport);\n }\n}\n","/**\n * Returns a copy of the points object.\n * @public\n * @function copyPoints\n *\n * @param {Object} points - The object to copy.\n * @returns {Object} - The copy.\n */\nexport default function(points) {\n const page = _copy(points.page);\n const image = _copy(points.image);\n const client = _copy(points.client);\n const canvas = _copy(points.canvas);\n\n return {\n page,\n image,\n client,\n canvas,\n };\n}\n\n/**\n *\n * @private\n * @function _copy\n *\n * @param {Object} point - { x, y }\n * @returns {Object} { x, y }\n */\nfunction _copy({ x, y } = {}) {\n return {\n x,\n y,\n };\n}\n","import external from '../externalModules.js';\n\n/**\n * Sets the canvas context transformation matrix so it is scaled to show text\n * more cleanly even if the image is scaled up. See\n * https://github.com/cornerstonejs/cornerstoneTools/wiki/DrawingText\n * for more information\n * @export @public @function\n * @name setContextToDisplayFontSize\n *\n * @param enabledElement The cornerstone enabled element.\n * @param context The canvas context.\n * @param fontSize The font size.\n * @returns {Object} {fontSize: number, lineHeight: number, fontScale: number}\n */\nexport default function(enabledElement, context, fontSize) {\n const fontScale = 0.1;\n\n external.cornerstone.setToPixelCoordinateSystem(\n enabledElement,\n context,\n fontScale\n );\n // Return the font size to use\n const scaledFontSize = fontSize / enabledElement.viewport.scale / fontScale;\n // TODO: actually calculate this?\n const lineHeight = fontSize / enabledElement.viewport.scale / fontScale;\n\n return {\n fontSize: scaledFontSize,\n lineHeight,\n fontScale,\n };\n}\n","import EVENTS from '../events.js';\nimport external from '../externalModules.js';\nimport copyPoints from '../util/copyPoints.js';\nimport triggerEvent from '../util/triggerEvent.js';\n\nlet isClickEvent = true;\nlet preventClickTimeout;\nconst clickDelay = 200;\n\nfunction getEventButtons(event) {\n if (typeof event.buttons === 'number') {\n return event.buttons;\n }\n\n switch (event.which) {\n // No button\n case 0:\n return 0;\n // Left\n case 1:\n return 1;\n // Middle\n case 2:\n return 4;\n // Right\n case 3:\n return 2;\n }\n\n return 0;\n}\n\nfunction preventClickHandler() {\n isClickEvent = false;\n}\n\nfunction mouseDoubleClick(e) {\n const element = e.currentTarget;\n const enabledElement = external.cornerstone.getEnabledElement(element);\n\n if (!enabledElement.image) {\n return;\n }\n\n const eventType = EVENTS.MOUSE_DOUBLE_CLICK;\n\n const startPoints = {\n page: external.cornerstoneMath.point.pageToPoint(e),\n image: external.cornerstone.pageToPixel(element, e.pageX, e.pageY),\n client: {\n x: e.clientX,\n y: e.clientY,\n },\n };\n\n startPoints.canvas = external.cornerstone.pixelToCanvas(\n element,\n startPoints.image\n );\n\n const lastPoints = copyPoints(startPoints);\n\n console.log(`double-click: ${getEventButtons(e)}`);\n const eventData = {\n event: e,\n buttons: getEventButtons(e),\n viewport: external.cornerstone.getViewport(element),\n image: enabledElement.image,\n element,\n startPoints,\n lastPoints,\n currentPoints: startPoints,\n deltaPoints: {\n x: 0,\n y: 0,\n },\n type: eventType,\n };\n\n triggerEvent(element, eventType, eventData);\n}\n\nfunction mouseDown(e) {\n const element = e.currentTarget;\n const enabledElement = external.cornerstone.getEnabledElement(element);\n\n if (!enabledElement.image) {\n return;\n }\n\n preventClickTimeout = setTimeout(preventClickHandler, clickDelay);\n\n // Prevent CornerstoneToolsMouseMove while mouse is down\n element.removeEventListener('mousemove', mouseMove);\n\n const startPoints = {\n page: external.cornerstoneMath.point.pageToPoint(e),\n image: external.cornerstone.pageToPixel(element, e.pageX, e.pageY),\n client: {\n x: e.clientX,\n y: e.clientY,\n },\n };\n\n startPoints.canvas = external.cornerstone.pixelToCanvas(\n element,\n startPoints.image\n );\n\n let lastPoints = copyPoints(startPoints);\n\n const eventData = {\n event: e,\n buttons: getEventButtons(e),\n viewport: external.cornerstone.getViewport(element),\n image: enabledElement.image,\n element,\n startPoints,\n lastPoints,\n currentPoints: startPoints,\n deltaPoints: {\n x: 0,\n y: 0,\n },\n type: EVENTS.MOUSE_DOWN,\n };\n\n const eventPropagated = triggerEvent(\n eventData.element,\n EVENTS.MOUSE_DOWN,\n eventData\n );\n\n if (eventPropagated) {\n // No tools responded to this event, create a new tool\n eventData.type = EVENTS.MOUSE_DOWN_ACTIVATE;\n triggerEvent(eventData.element, EVENTS.MOUSE_DOWN_ACTIVATE, eventData);\n }\n\n function onMouseMove(e) {\n // Calculate our current points in page and image coordinates\n const eventType = EVENTS.MOUSE_DRAG;\n const currentPoints = {\n page: external.cornerstoneMath.point.pageToPoint(e),\n image: external.cornerstone.pageToPixel(element, e.pageX, e.pageY),\n client: {\n x: e.clientX,\n y: e.clientY,\n },\n };\n\n currentPoints.canvas = external.cornerstone.pixelToCanvas(\n element,\n currentPoints.image\n );\n\n // Calculate delta values in page and image coordinates\n const deltaPoints = {\n page: external.cornerstoneMath.point.subtract(\n currentPoints.page,\n lastPoints.page\n ),\n image: external.cornerstoneMath.point.subtract(\n currentPoints.image,\n lastPoints.image\n ),\n client: external.cornerstoneMath.point.subtract(\n currentPoints.client,\n lastPoints.client\n ),\n canvas: external.cornerstoneMath.point.subtract(\n currentPoints.canvas,\n lastPoints.canvas\n ),\n };\n\n console.log(`mousemove ${getEventButtons(e)}`);\n const eventData = {\n buttons: getEventButtons(e),\n viewport: external.cornerstone.getViewport(element),\n image: enabledElement.image,\n element,\n startPoints,\n lastPoints,\n currentPoints,\n deltaPoints,\n type: eventType,\n ctrlKey: e.ctrlKey,\n metaKey: e.metaKey,\n shiftKey: e.shiftKey,\n };\n\n triggerEvent(eventData.element, eventType, eventData);\n\n // Update the last points\n lastPoints = copyPoints(currentPoints);\n }\n\n // Hook mouseup so we can unbind our event listeners\n // When they stop dragging\n function onMouseUp(e) {\n // Cancel the timeout preventing the click event from triggering\n clearTimeout(preventClickTimeout);\n\n let eventType = EVENTS.MOUSE_UP;\n\n if (isClickEvent) {\n eventType = EVENTS.MOUSE_CLICK;\n }\n\n // Calculate our current points in page and image coordinates\n const currentPoints = {\n page: external.cornerstoneMath.point.pageToPoint(e),\n image: external.cornerstone.pageToPixel(element, e.pageX, e.pageY),\n client: {\n x: e.clientX,\n y: e.clientY,\n },\n };\n\n currentPoints.canvas = external.cornerstone.pixelToCanvas(\n element,\n currentPoints.image\n );\n\n // Calculate delta values in page and image coordinates\n const deltaPoints = {\n page: external.cornerstoneMath.point.subtract(\n currentPoints.page,\n lastPoints.page\n ),\n image: external.cornerstoneMath.point.subtract(\n currentPoints.image,\n lastPoints.image\n ),\n client: external.cornerstoneMath.point.subtract(\n currentPoints.client,\n lastPoints.client\n ),\n canvas: external.cornerstoneMath.point.subtract(\n currentPoints.canvas,\n lastPoints.canvas\n ),\n };\n\n console.log(`mouseup: ${getEventButtons(e)}`);\n const eventData = {\n event: e,\n buttons: getEventButtons(e),\n viewport: external.cornerstone.getViewport(element),\n image: enabledElement.image,\n element,\n startPoints,\n lastPoints,\n currentPoints,\n deltaPoints,\n type: eventType,\n };\n\n triggerEvent(eventData.element, eventType, eventData);\n\n document.removeEventListener('mousemove', onMouseMove);\n document.removeEventListener('mouseup', onMouseUp);\n\n element.addEventListener('mousemove', mouseMove);\n\n isClickEvent = true;\n }\n\n document.addEventListener('mousemove', onMouseMove);\n document.addEventListener('mouseup', onMouseUp);\n}\n\nfunction mouseMove(e) {\n const element = e.currentTarget;\n const enabledElement = external.cornerstone.getEnabledElement(element);\n\n if (!enabledElement.image) {\n return;\n }\n\n const eventType = EVENTS.MOUSE_MOVE;\n\n const startPoints = {\n page: external.cornerstoneMath.point.pageToPoint(e),\n image: external.cornerstone.pageToPixel(element, e.pageX, e.pageY),\n client: {\n x: e.clientX,\n y: e.clientY,\n },\n };\n\n startPoints.canvas = external.cornerstone.pixelToCanvas(\n element,\n startPoints.image\n );\n\n let lastPoints = copyPoints(startPoints);\n\n // Calculate our current points in page and image coordinates\n const currentPoints = {\n page: external.cornerstoneMath.point.pageToPoint(e),\n image: external.cornerstone.pageToPixel(element, e.pageX, e.pageY),\n client: {\n x: e.clientX,\n y: e.clientY,\n },\n };\n\n currentPoints.canvas = external.cornerstone.pixelToCanvas(\n element,\n currentPoints.image\n );\n\n // Calculate delta values in page and image coordinates\n const deltaPoints = {\n page: external.cornerstoneMath.point.subtract(\n currentPoints.page,\n lastPoints.page\n ),\n image: external.cornerstoneMath.point.subtract(\n currentPoints.image,\n lastPoints.image\n ),\n client: external.cornerstoneMath.point.subtract(\n currentPoints.client,\n lastPoints.client\n ),\n canvas: external.cornerstoneMath.point.subtract(\n currentPoints.canvas,\n lastPoints.canvas\n ),\n };\n\n const eventData = {\n viewport: external.cornerstone.getViewport(element),\n image: enabledElement.image,\n element,\n startPoints,\n lastPoints,\n currentPoints,\n deltaPoints,\n type: eventType,\n };\n\n triggerEvent(element, eventType, eventData);\n\n // Update the last points\n lastPoints = copyPoints(currentPoints);\n}\n\nfunction disable(element) {\n element.removeEventListener('mousedown', mouseDown);\n element.removeEventListener('mousemove', mouseMove);\n element.removeEventListener('dblclick', mouseDoubleClick);\n}\n\nfunction enable(element) {\n // Prevent handlers from being attached multiple times\n disable(element);\n\n element.addEventListener('mousedown', mouseDown);\n element.addEventListener('mousemove', mouseMove);\n element.addEventListener('dblclick', mouseDoubleClick);\n}\n\nexport default {\n enable,\n disable,\n};\n","/**\n * Returns a string representation of the a key, given a keycode. Useful for\n * hooking up api calls to buttons using external libraries.\n * @export @public @method\n * @name getKeyFromKeyCode\n *\n * @param {number} keyCode The keycode to look up.\n * @returns {string} The corresponding character.\n */\nexport default function(keyCode) {\n return KEY_CODES[keyCode];\n}\n\nconst KEY_CODES = {\n // Numbers - above letter keys\n 48: '0',\n 49: '1',\n 50: '2',\n 51: '3',\n 52: '4',\n 53: '5',\n 54: '6',\n 55: '7',\n 56: '8',\n 57: '9',\n\n // Numbers - numpad\n 96: '0',\n 97: '1',\n 98: '2',\n 99: '3',\n 100: '4',\n 101: '5',\n 102: '6',\n 103: '7',\n 104: '8',\n 105: '9',\n\n // Letters\n 65: 'a',\n 66: 'b',\n 67: 'c',\n 68: 'd',\n 69: 'e',\n 70: 'f',\n 71: 'g',\n 72: 'h',\n 73: 'i',\n 74: 'j',\n 75: 'k',\n 76: 'l',\n 77: 'm',\n 78: 'n',\n 79: 'o',\n 80: 'p',\n 81: 'q',\n 82: 'r',\n 83: 's',\n 84: 't',\n 85: 'u',\n 86: 'v',\n 87: 'w',\n 88: 'x',\n 89: 'y',\n 90: 'z',\n\n // Function keys\n 112: 'F1',\n 113: 'F2',\n 114: 'F3',\n 115: 'F4',\n 116: 'F5',\n\n // Command keys\n 13: 'RETURN',\n 8: 'BACKSPACE',\n 9: 'TAB',\n 46: 'DELETE',\n 12: 'DELETE',\n 27: 'ESCAPE',\n 20: 'CAPSLOCK',\n\n // Misc - NOTE: There are multiple keycodes for certain characters due to browsers having different mappings.\n 173: '-',\n 189: '-',\n 109: '-',\n 61: '+',\n 187: '+',\n 107: '+',\n 219: '[',\n 221: ']',\n 59: ';',\n 186: ';',\n 188: ',',\n 190: '.',\n 199: '/',\n};\n","import BaseTool from './tools/base/BaseTool.js';\nimport BaseAnnotationTool from './tools/base/BaseAnnotationTool.js';\nimport BaseBrushTool from './tools/base/BaseBrushTool.js';\n\nimport {\n anyHandlesOutsideImage,\n getHandleNearImagePoint,\n handleActivator,\n moveHandle,\n moveAllHandles,\n moveNewHandle,\n} from './manipulators/index.js';\n\nimport {\n moveHandleNearImagePoint,\n findHandleDataNearImagePoint,\n moveAnnotation,\n} from './util/findAndMoveHelpers.js';\n\nimport mixins from './mixins/index.js';\n\nimport {\n getNewContext,\n draw,\n path,\n setShadow,\n drawLine,\n drawLines,\n drawJoinedLines,\n drawCircle,\n drawEllipse,\n drawRect,\n fillOutsideRect,\n fillBox,\n fillTextLines,\n} from './drawing/index.js';\nimport drawTextBox, { textBoxWidth } from './drawing/drawTextBox.js';\nimport drawArrow from './drawing/drawArrow.js';\nimport drawLink from './drawing/drawLink.js';\nimport drawLinkedTextBox from './drawing/drawLinkedTextBox.js';\nimport drawHandles from './drawing/drawHandles.js';\n\nimport getLuminance from './util/getLuminance.js';\nimport copyPoints from './util/copyPoints.js';\nimport calculateSUV from './util/calculateSUV.js';\nimport setContextToDisplayFontSize from './util/setContextToDisplayFontSize.js';\nimport scrollToIndex from './util/scrollToIndex.js';\nimport scroll from './util/scroll.js';\nimport roundToDecimal from './util/roundToDecimal.js';\nimport {\n projectPatientPointToImagePlane,\n imagePointToPatientPoint,\n planePlaneIntersection,\n} from './util/pointProjector.js';\nimport lineSegDistance from './util/lineSegDistance.js';\n\nimport pointInsideBoundingBox from './util/pointInsideBoundingBox.js';\nimport makeUnselectable from './util/makeUnselectable.js';\nimport getRGBPixels from './util/getRGBPixels.js';\nimport {\n getDefaultSimultaneousRequests,\n getMaxSimultaneousRequests,\n getBrowserInfo,\n isMobileDevice,\n} from './util/getMaxSimultaneousRequests.js';\nimport angleBetweenPoints from './util/angleBetweenPoints.js';\nimport getKeyFromKeyCode from './util/getKeyFromKeyCode.js';\nimport numbersWithCommas from './util/numbersWithCommas.js';\n\nimport ellipseUtils from './util/ellipse/index.js';\nimport freehandUtils from './util/freehand/index.js';\nimport brushUtils from './util/brush/index.js';\nimport zoomUtils from './util/zoom/index.js';\nimport triggerEvent from './util/triggerEvent.js';\nimport convertToVector3 from './util/convertToVector3.js';\n\nexport const lib = {\n 'base/BaseTool': BaseTool,\n 'base/BaseAnnotationTool': BaseAnnotationTool,\n 'base/BaseBrushTool': BaseBrushTool,\n\n 'manipulators/anyHandlesOutsideImage': anyHandlesOutsideImage,\n 'manipulators/getHandleNearImagePoint': getHandleNearImagePoint,\n 'manipulators/handleActivator': handleActivator,\n 'manipulators/moveAllHandles': moveAllHandles,\n 'manipulators/moveHandle': moveHandle,\n 'manipulators/moveNewHandle': moveNewHandle,\n 'manipulators/moveHandleNearImagePoint': moveHandleNearImagePoint,\n 'manipulators/findHandleDataNearImagePoint': findHandleDataNearImagePoint,\n 'manipulators/moveAnnotation': moveAnnotation,\n\n 'mixins/activeOrDisabledBinaryTool': mixins.activeOrDisabledBinaryTool,\n 'mixins/enabledOrDisabledBinaryTool': mixins.enabledOrDisabledBinaryTool,\n\n 'drawing/getNewContext': getNewContext,\n 'drawing/draw': draw,\n 'drawing/path': path,\n 'drawing/setShadow': setShadow,\n 'drawing/drawLine': drawLine,\n 'drawing/drawLines': drawLines,\n 'drawing/drawJoinedLines': drawJoinedLines,\n 'drawing/drawCircle': drawCircle,\n 'drawing/drawEllipse': drawEllipse,\n 'drawing/drawRect': drawRect,\n 'drawing/fillOutsideRect': fillOutsideRect,\n 'drawing/drawTextBox': drawTextBox,\n 'drawing/drawArrow': drawArrow,\n 'drawing/fillBox': fillBox,\n 'drawing/fillTextLines': fillTextLines,\n 'drawing/drawLink': drawLink,\n 'drawing/drawLinkedTextBox': drawLinkedTextBox,\n 'drawing/drawHandles': drawHandles,\n 'drawing/textBoxWidth': textBoxWidth,\n\n 'util/getLuminance': getLuminance,\n 'util/copyPoints': copyPoints,\n 'util/calculateSUV': calculateSUV,\n 'util/setContextToDisplayFontSize': setContextToDisplayFontSize,\n 'util/scrollToIndex': scrollToIndex,\n 'util/scroll': scroll,\n 'util/roundToDecimal': roundToDecimal,\n 'util/projectPatientPointToImagePlane': projectPatientPointToImagePlane,\n 'util/imagePointToPatientPoint': imagePointToPatientPoint,\n 'util/planePlaneIntersection': planePlaneIntersection,\n 'util/pointInsideBoundingBox': pointInsideBoundingBox,\n 'util/makeUnselectable': makeUnselectable,\n 'util/getRGBPixels': getRGBPixels,\n 'util/getDefaultSimultaneousRequests': getDefaultSimultaneousRequests,\n 'util/getMaxSimultaneousRequests': getMaxSimultaneousRequests,\n 'util/getBrowserInfo': getBrowserInfo,\n 'util/isMobileDevice': isMobileDevice,\n 'util/angleBetweenPoints': angleBetweenPoints,\n 'util/getKeyFromKeyCode': getKeyFromKeyCode,\n 'util/numbersWithCommas': numbersWithCommas,\n 'util/lineSegDistance': lineSegDistance,\n 'util/triggerEvent': triggerEvent,\n 'util/convertToVectro3': convertToVector3,\n\n // Whole tool specific util packages\n 'util/ellipseUtils': ellipseUtils,\n 'util/freehandUtils': freehandUtils,\n 'util/brushUtils': brushUtils,\n 'util/zoomUtils': zoomUtils,\n};\n","import external from './../externalModules.js';\nimport path from './path.js';\n\n/**\n * Draw multiple lines.\n * @public\n * @method drawJoinedLines\n * @memberof Drawing\n *\n * @param {CanvasRenderingContext2D} context - Target context\n * @param {HTMLElement} element - The DOM Element to draw on\n * @param {Object[]} lines - `[{ start: {x, y}, end: { x, y }]` An array of `start`, `end` pairs.\n * Each point is `{ x, y }` in either pixel or canvas coordinates.\n * @param {Object} options - See {@link path}\n * @param {String} [coordSystem='pixel'] - Can be \"pixel\" (default) or \"canvas\". The coordinate\n * system of the points passed in to the function. If \"pixel\" then cornerstone.pixelToCanvas\n * is used to transform the points from pixel to canvas coordinates.\n * @returns {undefined}\n */\nexport default function(\n context,\n element,\n lines,\n options,\n coordSystem = 'pixel'\n) {\n path(context, options, context => {\n lines.forEach(line => {\n let start = line.start;\n let end = line.end;\n\n if (coordSystem === 'pixel') {\n const cornerstone = external.cornerstone;\n\n start = cornerstone.pixelToCanvas(element, start);\n end = cornerstone.pixelToCanvas(element, end);\n }\n\n context.moveTo(start.x, start.y);\n context.lineTo(end.x, end.y);\n });\n });\n}\n","import external from './../externalModules.js';\nimport path from './path.js';\n\n/**\n * Fill the region outside a rectangle defined by `corner1` and `corner2`.\n * @public\n * @method fillOutsideRect\n * @memberof Drawing\n *\n * @param {CanvasRenderingContext2D} context - Target context\n * @param {HTMLElement} element - The DOM Element to draw on\n * @param {Object} corner1 - `{ x, y }` in either pixel or canvas coordinates.\n * @param {Object} corner2 - `{ x, y }` in either pixel or canvas coordinates.\n * @param {Object} options - See {@link path}\n * @param {String} [coordSystem='pixel'] - Can be \"pixel\" (default) or \"canvas\". The coordinate\n * system of the points passed in to the function. If \"pixel\" then cornerstone.pixelToCanvas\n * is used to transform the points from pixel to canvas coordinates.\n * @returns {undefined}\n */\nexport default function(\n context,\n element,\n corner1,\n corner2,\n options,\n coordSystem = 'pixel'\n) {\n if (coordSystem === 'pixel') {\n const cornerstone = external.cornerstone;\n\n corner1 = cornerstone.pixelToCanvas(element, corner1);\n corner2 = cornerstone.pixelToCanvas(element, corner2);\n }\n\n const left = Math.min(corner1.x, corner2.x);\n const top = Math.min(corner1.y, corner2.y);\n const width = Math.abs(corner1.x - corner2.x);\n const height = Math.abs(corner1.y - corner2.y);\n\n path(context, options, context => {\n context.rect(0, 0, context.canvas.clientWidth, context.canvas.clientHeight);\n context.rect(left + width, top, -width, height);\n });\n}\n","/**\n * A helper function to make an element (and its content) being non selectable.\n * @export @public @method\n * @name makeUnselectable\n *\n * @param {HTMLElement} element The element to make unselectable\n * @param {Boolean} ignorePointerEvents true to make this element also\n * ignore events (e.g. mouse click), false otherwise.\n */\nexport default function(element, ignorePointerEvents) {\n element.style.webkitUserSelect = 'none';\n element.style.webkitTouchCallout = 'none';\n element.style.mozUserSelect = 'none';\n element.style.msUserSelect = 'none';\n element.style.oUserSelect = 'none';\n element.style.khtmlUserSelect = 'none';\n element.style.userSelect = 'none';\n\n element.unselectable = 'on';\n element.oncontextmenu = () => false;\n\n if (ignorePointerEvents === true) {\n element.style.pointerEvents = 'none';\n }\n}\n","import { lib } from './lib.js';\n\n/**\n * Imports functionality from cornerstoneTools for use in external packages/plugins.\n * @export\n * @public\n * @method\n * @name import\n *\n * @param {string} uri the import path for the entity to import.\n * @returns {Class|Object|Function} The entity requested.\n */\nexport default function(uri) {\n return lib[uri];\n}\n","// Reasonable defaults\nconst PIXEL_STEP = 10;\nconst LINE_HEIGHT = 40;\nconst PAGE_HEIGHT = 800;\n\n/**\n * Normalizes wheel events and provides properties that are more\n * consistent and helpful across different browsers\n *\n * @private\n * @function normalizeWheel\n * @param {WheelEvent} event\n * @returns {Object} { spinX, spinY, pixlX, pixelY }\n */\nexport default function(event) {\n let spinX = 0,\n spinY = 0,\n pixelX = 0,\n pixelY = 0;\n\n // Legacy\n if ('detail' in event) {\n spinY = event.detail;\n }\n if ('wheelDelta' in event) {\n spinY = -event.wheelDelta / 120;\n }\n if ('wheelDeltaY' in event) {\n spinY = -event.wheelDeltaY / 120;\n }\n if ('wheelDeltaX' in event) {\n spinX = -event.wheelDeltaX / 120;\n }\n\n pixelX = spinX * PIXEL_STEP;\n pixelY = spinY * PIXEL_STEP;\n\n if ('deltaY' in event) {\n pixelY = event.deltaY;\n }\n if ('deltaX' in event) {\n pixelX = event.deltaX;\n }\n\n if ((pixelX || pixelY) && event.deltaMode) {\n if (event.deltaMode === 1) {\n // Delta in LINE units\n pixelX *= LINE_HEIGHT;\n pixelY *= LINE_HEIGHT;\n } else {\n // Delta in PAGE units\n pixelX *= PAGE_HEIGHT;\n pixelY *= PAGE_HEIGHT;\n }\n }\n\n // Fall-back if spin cannot be determined\n if (pixelX && !spinX) {\n spinX = pixelX < 1 ? -1 : 1;\n }\n if (pixelY && !spinY) {\n spinY = pixelY < 1 ? -1 : 1;\n }\n\n return {\n spinX,\n spinY,\n pixelX,\n pixelY,\n };\n}\n","/**\n * Internal module used to turn on listening, handling, and normalizing of the\n * native `wheel` event\n */\n\nimport EVENTS from '../events.js';\nimport external from '../externalModules.js';\nimport triggerEvent from '../util/triggerEvent.js';\nimport normalizeWheel from './internals/normalizeWheel.js';\n\n/**\n *\n * @private\n * @function wheelEventHandler\n * @param {WheelEvent} evt\n * @returns {undefined}\n */\nfunction wheelEventHandler(evt) {\n const element = evt.currentTarget;\n const enabledElement = external.cornerstone.getEnabledElement(element);\n\n if (!enabledElement.image) {\n return;\n }\n\n evt.preventDefault();\n\n const { pageX, pageY } = evt;\n const startingCoords = external.cornerstone.pageToPixel(\n element,\n pageX,\n pageY\n );\n const { spinX, spinY, pixelX, pixelY } = normalizeWheel(evt);\n const direction = spinY < 0 ? -1 : 1;\n\n const mouseWheelData = {\n element,\n viewport: external.cornerstone.getViewport(element),\n detail: evt,\n image: enabledElement.image,\n direction,\n spinX,\n spinY,\n pixelX,\n pixelY,\n pageX,\n pageY,\n imageX: startingCoords.x,\n imageY: startingCoords.y,\n };\n\n triggerEvent(element, EVENTS.MOUSE_WHEEL, mouseWheelData);\n}\n\n/**\n * Listens for the wheel event, and handles it. Handled event\n * will be \"normalized\" and re-emitted as `EVENTS.MOUSE_WHEEL`\n *\n * @private\n * @param {HTMLElement} element\n * @returns {undefined}\n */\nfunction enable(element) {\n disable(element);\n element.addEventListener('wheel', wheelEventHandler, { passive: false });\n}\n\n/**\n * Removes listener and handler for wheel event. `EVENTS.MOUSE_WHEEL`\n * will no longer be emitted.\n *\n * @private\n * @param {HTMLElement} element\n * @returns {undefined}\n */\nfunction disable(element) {\n element.removeEventListener('wheel', wheelEventHandler, { passive: false });\n}\n\nexport default {\n enable,\n disable,\n};\n","// Functions to prevent ghost clicks following a touch\n// All credit to @kosich\n// https://gist.github.com/kosich/23188dd86633b6c2efb7\n\nconst antiGhostDelay = 2000,\n pointerType = {\n mouse: 0,\n touch: 1,\n };\n\nlet lastInteractionType, lastInteractionTime;\n\nfunction handleTap(type, e) {\n const now = Date.now();\n\n if (type !== lastInteractionType) {\n if (now - lastInteractionTime <= antiGhostDelay) {\n e.preventDefault();\n e.stopPropagation();\n e.stopImmediatePropagation();\n\n return false;\n }\n\n lastInteractionType = type;\n }\n\n lastInteractionTime = now;\n}\n\n// Cacheing the function references\n// Necessary because a new function reference is created after .bind() is called\n// http://stackoverflow.com/questions/11565471/removing-event-listener-which-was-added-with-bind\nconst handleTapMouse = handleTap.bind(null, pointerType.mouse);\nconst handleTapTouch = handleTap.bind(null, pointerType.touch);\n\nfunction attachEvents(element, eventList, interactionType) {\n const tapHandler = interactionType ? handleTapMouse : handleTapTouch;\n\n eventList.forEach(function(eventName) {\n element.addEventListener(eventName, tapHandler, { passive: false });\n });\n}\n\nfunction removeEvents(element, eventList, interactionType) {\n const tapHandler = interactionType ? handleTapMouse : handleTapTouch;\n\n eventList.forEach(function(eventName) {\n element.removeEventListener(eventName, tapHandler);\n });\n}\n\nconst mouseEvents = ['mousedown', 'mouseup'];\nconst touchEvents = ['touchstart', 'touchend'];\n\nfunction disable(element) {\n removeEvents(element, mouseEvents, pointerType.mouse);\n removeEvents(element, touchEvents, pointerType.touch);\n}\n\nfunction enable(element) {\n disable(element);\n attachEvents(element, mouseEvents, pointerType.mouse);\n attachEvents(element, touchEvents, pointerType.touch);\n}\n\nexport default {\n enable,\n disable,\n};\n","import EVENTS from '../events.js';\nimport external from '../externalModules.js';\nimport copyPoints from '../util/copyPoints.js';\nimport preventGhostClick from './preventGhostClick.js';\nimport triggerEvent from '../util/triggerEvent.js';\nimport { setToolOptions, getToolOptions } from '../toolOptions.js';\n\nlet startPoints,\n currentPoints,\n lastPoints,\n deltaPoints,\n eventData,\n touchStartDelay,\n pressTimeout,\n pageDistanceMoved;\n\nlet lastScale = 1.0,\n lastRotation = 0.0,\n preventNextPinch = false,\n isPress = false,\n lastDelta;\n\nconst pressDelay = 700,\n pressMaxDistance = 5;\n\nconst toolType = 'touchInput';\n\nfunction onTouch(e) {\n const element = e.currentTarget || e.srcEvent.currentTarget;\n const enabledElement = external.cornerstone.getEnabledElement(element);\n\n if (!enabledElement.image) {\n return;\n }\n\n let eventType, scaleChange, delta, remainingPointers, rotation;\n\n // Prevent mouse events from occurring alongside touch events\n e.preventDefault();\n\n // If more than one finger is placed on the element, stop the press timeout\n if (\n (e.pointers && e.pointers.length > 1) ||\n (e.touches && e.touches.length > 1)\n ) {\n isPress = false;\n clearTimeout(pressTimeout);\n }\n\n switch (e.type) {\n case 'tap':\n isPress = false;\n clearTimeout(pressTimeout);\n\n // Calculate our current points in page and image coordinates\n currentPoints = {\n page: external.cornerstoneMath.point.pageToPoint(e.pointers[0]),\n image: external.cornerstone.pageToPixel(\n element,\n e.pointers[0].pageX,\n e.pointers[0].pageY\n ),\n client: {\n x: e.pointers[0].clientX,\n y: e.pointers[0].clientY,\n },\n };\n currentPoints.canvas = external.cornerstone.pixelToCanvas(\n element,\n currentPoints.image\n );\n\n eventType = EVENTS.TAP;\n eventData = {\n event: e,\n viewport: external.cornerstone.getViewport(element),\n image: enabledElement.image,\n element,\n currentPoints,\n type: eventType,\n isTouchEvent: true,\n };\n\n triggerEvent(element, eventType, eventData);\n break;\n\n case 'doubletap':\n isPress = false;\n clearTimeout(pressTimeout);\n\n // Calculate our current points in page and image coordinates\n currentPoints = {\n page: external.cornerstoneMath.point.pageToPoint(e.pointers[0]),\n image: external.cornerstone.pageToPixel(\n element,\n e.pointers[0].pageX,\n e.pointers[0].pageY\n ),\n client: {\n x: e.pointers[0].clientX,\n y: e.pointers[0].clientY,\n },\n };\n currentPoints.canvas = external.cornerstone.pixelToCanvas(\n element,\n currentPoints.image\n );\n\n eventType = EVENTS.DOUBLE_TAP;\n eventData = {\n event: e,\n viewport: external.cornerstone.getViewport(element),\n image: enabledElement.image,\n element,\n currentPoints,\n type: eventType,\n isTouchEvent: true,\n };\n\n triggerEvent(element, eventType, eventData);\n break;\n\n case 'pinchstart':\n isPress = false;\n clearTimeout(pressTimeout);\n\n lastScale = 1.0;\n break;\n\n case 'pinchmove':\n isPress = false;\n clearTimeout(pressTimeout);\n\n if (preventNextPinch === true) {\n lastScale = e.scale;\n preventNextPinch = false;\n break;\n }\n\n scaleChange = (e.scale - lastScale) / lastScale;\n\n startPoints = {\n page: e.center,\n image: external.cornerstone.pageToPixel(\n element,\n e.center.x,\n e.center.y\n ),\n };\n startPoints.canvas = external.cornerstone.pixelToCanvas(\n element,\n startPoints.image\n );\n\n eventType = EVENTS.TOUCH_PINCH;\n eventData = {\n event: e,\n startPoints,\n viewport: external.cornerstone.getViewport(element),\n image: enabledElement.image,\n element,\n direction: e.scale < 1 ? 1 : -1,\n scaleChange,\n type: eventType,\n isTouchEvent: true,\n };\n\n triggerEvent(element, eventType, eventData);\n\n lastScale = e.scale;\n break;\n\n case 'touchstart':\n lastScale = 1.0;\n\n clearTimeout(pressTimeout);\n\n clearTimeout(touchStartDelay);\n touchStartDelay = setTimeout(function() {\n startPoints = {\n page: external.cornerstoneMath.point.pageToPoint(e.touches[0]),\n image: external.cornerstone.pageToPixel(\n element,\n e.touches[0].pageX,\n e.touches[0].pageY\n ),\n client: {\n x: e.touches[0].clientX,\n y: e.touches[0].clientY,\n },\n };\n startPoints.canvas = external.cornerstone.pixelToCanvas(\n element,\n startPoints.image\n );\n\n eventType = EVENTS.TOUCH_START;\n if (e.touches.length > 1) {\n eventType = EVENTS.MULTI_TOUCH_START;\n }\n\n eventData = {\n event: e,\n viewport: external.cornerstone.getViewport(element),\n image: enabledElement.image,\n element,\n startPoints,\n currentPoints: startPoints,\n type: eventType,\n isTouchEvent: true,\n };\n\n const eventPropagated = triggerEvent(element, eventType, eventData);\n\n if (eventPropagated === true) {\n // IsPress = false;\n // ClearTimeout(pressTimeout);\n\n // No current tools responded to the drag action.\n // Create new tool measurement\n eventType = EVENTS.TOUCH_START_ACTIVE;\n if (e.touches.length > 1) {\n eventType = EVENTS.MULTI_TOUCH_START_ACTIVE;\n }\n\n eventData.type = eventType;\n triggerEvent(element, eventType, eventData);\n }\n\n // Console.log(eventType);\n lastPoints = copyPoints(startPoints);\n }, 50);\n\n isPress = true;\n pageDistanceMoved = 0;\n pressTimeout = setTimeout(function() {\n if (!isPress) {\n return;\n }\n\n currentPoints = {\n page: external.cornerstoneMath.point.pageToPoint(e.touches[0]),\n image: external.cornerstone.pageToPixel(\n element,\n e.touches[0].pageX,\n e.touches[0].pageY\n ),\n client: {\n x: e.touches[0].clientX,\n y: e.touches[0].clientY,\n },\n };\n currentPoints.canvas = external.cornerstone.pixelToCanvas(\n element,\n startPoints.image\n );\n\n eventType = EVENTS.TOUCH_PRESS;\n eventData = {\n event: e,\n viewport: external.cornerstone.getViewport(element),\n image: enabledElement.image,\n element,\n currentPoints,\n type: eventType,\n isTouchEvent: true,\n };\n\n triggerEvent(element, eventType, eventData);\n\n // Console.log(eventType);\n }, pressDelay);\n break;\n\n case 'touchend':\n lastScale = 1.0;\n\n isPress = false;\n clearTimeout(pressTimeout);\n\n setTimeout(function() {\n startPoints = {\n page: external.cornerstoneMath.point.pageToPoint(e.changedTouches[0]),\n image: external.cornerstone.pageToPixel(\n element,\n e.changedTouches[0].pageX,\n e.changedTouches[0].pageY\n ),\n client: {\n x: e.changedTouches[0].clientX,\n y: e.changedTouches[0].clientY,\n },\n };\n startPoints.canvas = external.cornerstone.pixelToCanvas(\n element,\n startPoints.image\n );\n\n eventType = EVENTS.TOUCH_END;\n\n eventData = {\n event: e,\n viewport: external.cornerstone.getViewport(element),\n image: enabledElement.image,\n element,\n startPoints,\n currentPoints: startPoints,\n type: eventType,\n isTouchEvent: true,\n };\n\n triggerEvent(element, eventType, eventData);\n }, 50);\n break;\n\n case 'panmove':\n // Using the delta-value of HammerJS, because it takes all pointers into account\n // This is very important when using panning in combination with pinch-zooming\n // But HammerJS' delta is relative to the start of the pan event\n // So it needs to be converted to a per-event-delta for CornerstoneTools\n delta = {\n x: e.deltaX - lastDelta.x,\n y: e.deltaY - lastDelta.y,\n };\n\n lastDelta = {\n x: e.deltaX,\n y: e.deltaY,\n };\n\n // Calculate our current points in page and image coordinates\n currentPoints = {\n page: {\n x: lastPoints.page.x + delta.x,\n y: lastPoints.page.y + delta.y,\n },\n image: external.cornerstone.pageToPixel(\n element,\n lastPoints.page.x + delta.x,\n lastPoints.page.y + delta.y\n ),\n client: {\n x: lastPoints.client.x + delta.x,\n y: lastPoints.client.y + delta.y,\n },\n };\n currentPoints.canvas = external.cornerstone.pixelToCanvas(\n element,\n currentPoints.image\n );\n\n // Calculate delta values in page and image coordinates\n deltaPoints = {\n page: external.cornerstoneMath.point.subtract(\n currentPoints.page,\n lastPoints.page\n ),\n image: external.cornerstoneMath.point.subtract(\n currentPoints.image,\n lastPoints.image\n ),\n client: external.cornerstoneMath.point.subtract(\n currentPoints.client,\n lastPoints.client\n ),\n canvas: external.cornerstoneMath.point.subtract(\n currentPoints.canvas,\n lastPoints.canvas\n ),\n };\n\n pageDistanceMoved += Math.sqrt(\n deltaPoints.page.x * deltaPoints.page.x +\n deltaPoints.page.y * deltaPoints.page.y\n );\n // Console.log(\"pageDistanceMoved: \" + pageDistanceMoved);\n if (pageDistanceMoved > pressMaxDistance) {\n // Console.log('Press event aborted due to movement');\n isPress = false;\n clearTimeout(pressTimeout);\n }\n\n eventType = EVENTS.TOUCH_DRAG;\n if (e.pointers.length > 1) {\n eventType = EVENTS.MULTI_TOUCH_DRAG;\n }\n\n eventData = {\n viewport: external.cornerstone.getViewport(element),\n image: enabledElement.image,\n element,\n startPoints,\n lastPoints,\n currentPoints,\n deltaPoints,\n numPointers: e.pointers.length,\n type: eventType,\n isTouchEvent: true,\n };\n\n triggerEvent(element, eventType, eventData);\n\n lastPoints = copyPoints(currentPoints);\n break;\n\n case 'panstart':\n lastDelta = {\n x: e.deltaX,\n y: e.deltaY,\n };\n\n currentPoints = {\n page: external.cornerstoneMath.point.pageToPoint(e.pointers[0]),\n image: external.cornerstone.pageToPixel(\n element,\n e.pointers[0].pageX,\n e.pointers[0].pageY\n ),\n client: {\n x: e.pointers[0].clientX,\n y: e.pointers[0].clientY,\n },\n };\n currentPoints.canvas = external.cornerstone.pixelToCanvas(\n element,\n currentPoints.image\n );\n lastPoints = copyPoints(currentPoints);\n break;\n\n case 'panend':\n isPress = false;\n clearTimeout(pressTimeout);\n\n // If lastPoints is not yet set, it means panend fired without panstart or pan,\n // So we can ignore this event\n if (!lastPoints) {\n return false;\n }\n\n currentPoints = {\n page: external.cornerstoneMath.point.pageToPoint(e.pointers[0]),\n image: external.cornerstone.pageToPixel(\n element,\n e.pointers[0].pageX,\n e.pointers[0].pageY\n ),\n client: {\n x: e.pointers[0].clientX,\n y: e.pointers[0].clientY,\n },\n };\n currentPoints.canvas = external.cornerstone.pixelToCanvas(\n element,\n currentPoints.image\n );\n\n // Calculate delta values in page and image coordinates\n deltaPoints = {\n page: external.cornerstoneMath.point.subtract(\n currentPoints.page,\n lastPoints.page\n ),\n image: external.cornerstoneMath.point.subtract(\n currentPoints.image,\n lastPoints.image\n ),\n client: external.cornerstoneMath.point.subtract(\n currentPoints.client,\n lastPoints.client\n ),\n canvas: external.cornerstoneMath.point.subtract(\n currentPoints.canvas,\n lastPoints.canvas\n ),\n };\n\n eventType = EVENTS.TOUCH_DRAG_END;\n\n eventData = {\n event: e.srcEvent,\n viewport: external.cornerstone.getViewport(element),\n image: enabledElement.image,\n element,\n startPoints,\n lastPoints,\n currentPoints,\n deltaPoints,\n type: eventType,\n isTouchEvent: true,\n };\n\n triggerEvent(element, eventType, eventData);\n\n remainingPointers = e.pointers.length - e.changedPointers.length;\n\n if (remainingPointers === 2) {\n preventNextPinch = true;\n }\n break;\n\n case 'rotatemove':\n isPress = false;\n clearTimeout(pressTimeout);\n\n rotation = e.rotation - lastRotation;\n\n lastRotation = e.rotation;\n\n eventType = EVENTS.TOUCH_ROTATE;\n eventData = {\n event: e.srcEvent,\n viewport: external.cornerstone.getViewport(element),\n image: enabledElement.image,\n element,\n rotation,\n type: eventType,\n };\n triggerEvent(element, eventType, eventData);\n break;\n }\n\n return false;\n}\n\nfunction enable(element) {\n disable(element);\n const Hammer = external.Hammer;\n\n const hammerOptions = {\n inputClass: Hammer.SUPPORT_POINTER_EVENTS\n ? Hammer.PointerEventInput\n : Hammer.TouchInput,\n };\n\n const mc = new Hammer.Manager(element, hammerOptions);\n\n const panOptions = {\n pointers: 0,\n direction: Hammer.DIRECTION_ALL,\n threshold: 0,\n };\n\n const pan = new Hammer.Pan(panOptions);\n const pinch = new Hammer.Pinch({\n threshold: 0,\n });\n const rotate = new Hammer.Rotate({\n threshold: 0,\n });\n\n pinch.recognizeWith(pan);\n pinch.recognizeWith(rotate);\n rotate.recognizeWith(pan);\n\n const doubleTap = new Hammer.Tap({\n event: 'doubletap',\n taps: 2,\n interval: 1500,\n threshold: 50,\n posThreshold: 50,\n });\n\n doubleTap.recognizeWith(pan);\n\n // Add to the Manager\n mc.add([doubleTap, pan, rotate, pinch]);\n mc.on(\n 'tap doubletap panstart panmove panend pinchstart pinchmove rotatemove',\n onTouch\n );\n\n preventGhostClick.enable(element);\n\n const touchEvents = ['touchstart', 'touchend'];\n\n touchEvents.forEach(eventType => {\n element.addEventListener(eventType, onTouch, { passive: false });\n });\n\n const options = getToolOptions(toolType, element);\n\n options.hammer = mc;\n\n setToolOptions(toolType, element, options);\n}\n\nfunction disable(element) {\n preventGhostClick.disable(element);\n\n const touchEvents = ['touchstart', 'touchend'];\n\n touchEvents.forEach(eventType => {\n element.removeEventListener(eventType, onTouch);\n });\n\n const options = getToolOptions(toolType, element);\n const mc = options.hammer;\n\n if (mc) {\n mc.off(\n 'tap doubletap panstart panmove panend pinchstart pinchmove rotatemove',\n onTouch\n );\n }\n}\n\n// Module exports\nconst touchInput = {\n enable,\n disable,\n};\n\nexport default touchInput;\n","/**\n * Filters an array of tools, returning only tools which are active.\n * @export\n * @public\n * @method\n * @name getActiveToolsForElement\n *\n * @param {HTMLElement} element The element.\n * @param {Object[]} tools The input tool array.\n * @param {string} handlerType The input type being queried.\n * @returns {Object[]} The filtered array.\n */\nexport default function(element, tools, handlerType) {\n return tools.filter(\n tool =>\n tool.element === element &&\n tool.mode === 'active' &&\n (handlerType === undefined || tool.options[`is${handlerType}Active`])\n );\n}\n","import store from '../store/index.js';\nimport getActiveToolsForElement from '../store/getActiveToolsForElement.js';\nimport { getToolState, addToolState } from '../stateManagement/toolState.js';\nimport external from '../externalModules.js';\nimport BaseBrushTool from './../tools/base/BaseBrushTool.js';\nimport { getNewContext } from '../drawing/index.js';\nimport {\n resetCanvasContextTransform,\n transformCanvasContext,\n} from '../drawing/index.js';\n\n/* Safari and Edge polyfill for createImageBitmap\n * https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/createImageBitmap\n */\n\n// TODO: Do we still need this? I've yanked the package for now\n// It should be covered by @babel/runtime and plugin-transform-runtime:\n// https://babeljs.io/docs/en/babel-plugin-transform-runtime\n// @James, I think Babel should take care of this for us\n// Import regeneratorRuntime from \"regenerator-runtime\";\n\nif (!('createImageBitmap' in window)) {\n window.createImageBitmap = async function(imageData) {\n return new Promise(resolve => {\n const img = document.createElement('img');\n\n img.addEventListener('load', function() {\n resolve(this);\n });\n\n const conversionCanvas = document.createElement('canvas');\n\n conversionCanvas.width = imageData.width;\n conversionCanvas.height = imageData.height;\n\n const conversionCanvasContext = conversionCanvas.getContext('2d');\n\n conversionCanvasContext.putImageData(\n imageData,\n 0,\n 0,\n 0,\n 0,\n conversionCanvas.width,\n conversionCanvas.height\n );\n img.src = conversionCanvas.toDataURL();\n });\n };\n}\n\nconst { state, getters, setters } = store.modules.brush;\n\n/**\n * Used to redraw the brush label map data per render.\n *\n * @private\n * @param {Object} evt - The event.\n */\nexport default function(evt) {\n const eventData = evt.detail;\n const element = eventData.element;\n const maxSegmentations = BaseBrushTool.getNumberOfColors();\n let toolData = getToolState(\n element,\n BaseBrushTool.getReferencedToolDataName()\n );\n\n if (!toolData) {\n // Make toolData array as big as max number of segmentations.\n for (let i = 0; i < maxSegmentations; i++) {\n addToolState(element, BaseBrushTool.getReferencedToolDataName(), {});\n }\n\n toolData = getToolState(element, BaseBrushTool.getReferencedToolDataName());\n\n // TEMP: HACK: Create first pixel data such that the tool has some data and the brush\n // Cursor can be rendered. Can be replaced once we have a mechanism for SVG cursors.\n const newPixelData = new Uint8ClampedArray(\n eventData.image.width * eventData.image.height\n );\n\n toolData.data[0].pixelData = newPixelData;\n\n toolData = getToolState(element, BaseBrushTool.getReferencedToolDataName());\n }\n\n const enabledElement = external.cornerstone.getEnabledElement(element);\n const enabledElementUID = enabledElement.uuid;\n\n const segData = {\n visibleSegmentations: getters.visibleSegmentationsForElement(\n enabledElementUID\n ),\n imageBitmapCache: getters.imageBitmapCacheForElement(enabledElementUID),\n toolData,\n };\n\n for (let segIndex = 0; segIndex < maxSegmentations; segIndex++) {\n if (shouldRenderSegmentation(evt, segIndex, segData)) {\n renderSegmentation(evt, segIndex, segData);\n }\n }\n}\n\nfunction shouldRenderSegmentation(evt, segIndex, segData) {\n const element = evt.detail.element;\n const toolData = segData.toolData;\n const visibleSegmentations = segData.visibleSegmentations;\n\n if (!toolData.data[segIndex] || !toolData.data[segIndex].pixelData) {\n // No data, no render.\n return false;\n }\n\n if (visibleSegmentations[segIndex]) {\n // Has data and marked as visible, render!\n return true;\n }\n\n const currentColor = state.drawColorId;\n\n if (currentColor !== segIndex) {\n // Hidden and not current color, don't render.\n return false;\n }\n\n // Check that a brush tool is active.\n const activeTools = getActiveToolsForElement(element, store.state.tools);\n const brushTools = activeTools.filter(tool => tool instanceof BaseBrushTool);\n\n if (brushTools.length > 0) {\n // Active brush tool with same color, render!\n return true;\n }\n\n return false;\n}\n\nfunction renderSegmentation(evt, segIndex, segData) {\n const toolData = segData.toolData;\n const imageBitmapCache = segData.imageBitmapCache;\n const visibleSegmentations = segData.visibleSegmentations;\n\n // Draw previous image if cached.\n if (imageBitmapCache && imageBitmapCache[segIndex]) {\n _drawImageBitmap(\n evt,\n imageBitmapCache[segIndex],\n visibleSegmentations[segIndex]\n );\n }\n\n if (toolData.data[segIndex].invalidated) {\n createNewBitmapAndQueueRenderOfSegmentation(evt, toolData, segIndex);\n }\n}\n\nfunction createNewBitmapAndQueueRenderOfSegmentation(evt, toolData, segIndex) {\n const eventData = evt.detail;\n const element = eventData.element;\n const enabledElement = external.cornerstone.getEnabledElement(element);\n\n const pixelData = toolData.data[segIndex].pixelData;\n\n if (!pixelData) {\n return;\n }\n\n const colormapId = state.colorMapId;\n const colormap = external.cornerstone.colors.getColormap(colormapId);\n const colorLutTable = [[0, 0, 0, 0], colormap.getColor(segIndex)];\n\n const imageData = new ImageData(\n eventData.image.width,\n eventData.image.height\n );\n const image = {\n stats: {},\n minPixelValue: 0,\n getPixelData: () => pixelData,\n };\n\n external.cornerstone.storedPixelDataToCanvasImageDataColorLUT(\n image,\n colorLutTable,\n imageData.data\n );\n\n window.createImageBitmap(imageData).then(newImageBitmap => {\n setters.imageBitmapCacheForElement(\n enabledElement.uuid,\n segIndex,\n newImageBitmap\n );\n toolData.data[segIndex].invalidated = false;\n\n external.cornerstone.updateImage(eventData.element);\n });\n}\n\n/**\n * Draws the ImageBitmap the canvas.\n *\n * @private\n * @param {Object} evt description\n */\nfunction _drawImageBitmap(evt, imageBitmap, alwaysVisible) {\n const eventData = evt.detail;\n const context = getNewContext(eventData.canvasContext.canvas);\n\n const canvasTopLeft = external.cornerstone.pixelToCanvas(eventData.element, {\n x: 0,\n y: 0,\n });\n\n const canvasTopRight = external.cornerstone.pixelToCanvas(eventData.element, {\n x: eventData.image.width,\n y: 0,\n });\n\n const canvasBottomRight = external.cornerstone.pixelToCanvas(\n eventData.element,\n {\n x: eventData.image.width,\n y: eventData.image.height,\n }\n );\n\n const cornerstoneCanvasWidth = external.cornerstoneMath.point.distance(\n canvasTopLeft,\n canvasTopRight\n );\n const cornerstoneCanvasHeight = external.cornerstoneMath.point.distance(\n canvasTopRight,\n canvasBottomRight\n );\n\n const canvas = eventData.canvasContext.canvas;\n const viewport = eventData.viewport;\n\n context.imageSmoothingEnabled = false;\n context.globalAlpha = getLayerAlpha(alwaysVisible);\n\n transformCanvasContext(context, canvas, viewport);\n\n const canvasViewportTranslation = {\n x: viewport.translation.x * viewport.scale,\n y: viewport.translation.y * viewport.scale,\n };\n\n context.drawImage(\n imageBitmap,\n canvas.width / 2 - cornerstoneCanvasWidth / 2 + canvasViewportTranslation.x,\n canvas.height / 2 -\n cornerstoneCanvasHeight / 2 +\n canvasViewportTranslation.y,\n cornerstoneCanvasWidth,\n cornerstoneCanvasHeight\n );\n\n context.globalAlpha = 1.0;\n\n resetCanvasContextTransform(context);\n}\n\nfunction getLayerAlpha(alwaysVisible) {\n if (alwaysVisible) {\n return state.alpha;\n }\n\n return state.hiddenButActiveAlpha;\n}\n","import { state } from './../store/index.js';\nimport BaseBrushTool from './../tools/base/BaseBrushTool.js';\nimport onImageRenderedBrushEventHandler from '../eventListeners/onImageRenderedBrushEventHandler.js';\nimport external from './../externalModules.js';\n\nconst onImageRendered = function(evt) {\n const eventData = evt.detail;\n const element = eventData.element;\n\n // Render Annotation Tools\n const toolsToRender = state.tools.filter(\n tool =>\n tool.element === element &&\n (tool.mode === 'active' ||\n tool.mode === 'passive' ||\n tool.mode === 'enabled')\n );\n\n const brushTools = toolsToRender.filter(\n tool => tool instanceof BaseBrushTool\n );\n\n if (brushTools.length > 0) {\n onImageRenderedBrushEventHandler(evt);\n }\n\n toolsToRender.forEach(tool => {\n if (tool.renderToolData) {\n tool.renderToolData(evt);\n }\n });\n};\n\nconst enable = function(element) {\n element.addEventListener(\n external.cornerstone.EVENTS.IMAGE_RENDERED,\n onImageRendered\n );\n};\n\nconst disable = function(element) {\n element.removeEventListener(\n external.cornerstone.EVENTS.IMAGE_RENDERED,\n onImageRendered\n );\n};\n\nexport default {\n enable,\n disable,\n};\n","import { state } from './../../store/index.js';\nimport getActiveToolsForElement from './../../store/getActiveToolsForElement.js';\n\nexport default function(handlerType, customFunction, evt) {\n if (state.isToolLocked) {\n return false;\n }\n\n // TODO: We sometimes see a null detail for TOUCH_PRESS\n const element = evt.detail.element;\n let tools = state.tools.filter(tool =>\n tool.supportedInteractionTypes.includes(handlerType)\n );\n\n // Tool is active, and specific callback is active\n tools = getActiveToolsForElement(element, tools, handlerType);\n // Tool has expected callback custom function\n tools = tools.filter(tool => typeof tool[customFunction] === 'function');\n\n if (tools.length === 0) {\n return false;\n }\n\n tools[0][customFunction](evt);\n}\n","import { state } from './index.js';\nimport { getToolState } from '../stateManagement/toolState.js';\nimport getHandleNearImagePoint from '../manipulators/getHandleNearImagePoint.js';\n\n/**\n * Filters an array of tools, returning only tools with moveable handles at the\n * mouse location.\n *\n * @public\n * @function getToolsWithMoveableHandles\n *\n * @param {HTMLElement} element The element\n * @param {Object[]} tools The input tool array.\n * @param {Object} coords The coordinates of the mouse position.\n * @param {string} [interactionType=mouse]\n * @returns {Object[]} The filtered array.\n */\nexport default function(element, tools, coords, interactionType = 'mouse') {\n const proximity =\n interactionType === 'mouse' ? state.clickProximity : state.touchProximity;\n\n return tools.filter(tool => {\n const toolState = getToolState(element, tool.name);\n\n for (let i = 0; i < toolState.data.length; i++) {\n if (\n getHandleNearImagePoint(\n element,\n toolState.data[i].handles,\n coords,\n proximity\n ) !== undefined\n ) {\n return true;\n }\n }\n\n return false;\n });\n}\n","/**\n * Filters an array of tools, returning only tools which are active or passive.\n * @export\n * @public\n * @method\n * @name getInteractiveToolsForElement\n *\n * @param {HTMLElement} element The element.\n * @param {Object[]} tools The input tool array.\n * @returns {Object[]} The filtered array.\n */\nexport default function(element, tools) {\n return tools.filter(\n tool =>\n tool.element === element &&\n (tool.mode === 'active' || tool.mode === 'passive')\n );\n}\n","import { getToolState } from './../stateManagement/toolState.js';\n\n/**\n * Filters an array of tools, returning only tools which have annotation data.\n * @export\n * @public\n * @method\n * @name getToolsWithDataForElement\n *\n * @param {HTMLElement} element The element.\n * @param {Object[]} tools The input tool array.\n * @returns {Object[]} The filtered array.\n */\nexport default function(element, tools) {\n return tools.filter(tool => {\n const toolState = getToolState(element, tool.name);\n\n return toolState && toolState.data.length > 0;\n });\n}\n","// State\nimport { getters, state } from './../../store/index.js';\nimport { getToolState } from './../../stateManagement/toolState.js';\n// Util\nimport getToolsWithMoveableHandles from '../../store/getToolsWithMoveableHandles.js';\nimport { findHandleDataNearImagePoint } from '../../util/findAndMoveHelpers.js';\nimport getInteractiveToolsForElement from './../../store/getInteractiveToolsForElement.js';\nimport getToolsWithDataForElement from './../../store/getToolsWithDataForElement.js';\n\n/**\n * MouseDown is called before MouseDownActivate. If MouseDown\n * finds an existing tool to interact with, it can prevent the\n * event from bubbling to MouseDownActivate.\n *\n * @private\n * @param {mousedown} evt\n * @listens {CornerstoneTools.event:cornerstonetoolsmousedown}\n * @returns {undefined}\n */\nexport default function(evt) {\n if (state.isToolLocked) {\n return;\n }\n\n const eventData = evt.detail;\n const element = evt.detail.element;\n const coords = evt.detail.currentPoints.canvas;\n\n // High level filtering\n const activeAndPassiveTools = getInteractiveToolsForElement(\n element,\n getters.mouseTools()\n );\n\n // ACTIVE TOOL W/ PRE CALLBACK?\n // Note: In theory, this should only ever be a single tool.\n const activeTools = activeAndPassiveTools.filter(\n tool =>\n tool.mode === 'active' &&\n Array.isArray(tool.options.mouseButtonMask) &&\n tool.options.mouseButtonMask.includes(eventData.buttons) &&\n tool.options.isMouseActive\n );\n\n // If any tools are active, check if they have a special reason for dealing with the event.\n if (activeTools.length > 0) {\n // TODO: If length > 1, you could assess fitness and select the ideal tool\n // TODO: But because we're locking this to 'active' tools, that should rarely be an issue\n // Super-Meta-TODO: ^ I think we should just take the approach of one active tool per mouse button?\n const firstActiveToolWithCallback = activeTools.find(\n tool => typeof tool.preMouseDownCallback === 'function'\n );\n\n if (firstActiveToolWithCallback) {\n const consumedEvent = firstActiveToolWithCallback.preMouseDownCallback(\n evt\n );\n\n if (consumedEvent) {\n return;\n }\n }\n }\n\n // Annotation tool specific\n const annotationTools = getToolsWithDataForElement(\n element,\n activeAndPassiveTools\n );\n\n // NEAR HANDLES?\n const annotationToolsWithMoveableHandles = getToolsWithMoveableHandles(\n element,\n annotationTools,\n coords,\n 'mouse'\n );\n\n if (annotationToolsWithMoveableHandles.length > 0) {\n const firstToolWithMoveableHandles = annotationToolsWithMoveableHandles[0];\n const toolState = getToolState(element, firstToolWithMoveableHandles.name);\n\n const { handle, data } = findHandleDataNearImagePoint(\n element,\n toolState,\n firstToolWithMoveableHandles.name,\n coords\n );\n\n firstToolWithMoveableHandles.handleSelectedCallback(\n evt,\n data,\n handle,\n 'mouse'\n );\n\n return;\n }\n\n // NEAR TOOL?\n const annotationToolsWithPointNearClick = activeAndPassiveTools.filter(\n tool => {\n const toolState = getToolState(element, tool.name);\n const isNearPoint =\n toolState &&\n toolState.data &&\n tool.pointNearTool &&\n toolState.data.some(data =>\n tool.pointNearTool(element, data, coords, 'mouse')\n );\n\n return isNearPoint;\n }\n );\n\n if (annotationToolsWithPointNearClick.length > 0) {\n const firstToolNearPoint = annotationToolsWithPointNearClick[0];\n const toolState = getToolState(element, firstToolNearPoint.name);\n const firstAnnotationNearPoint = toolState.data.find(data =>\n firstToolNearPoint.pointNearTool(element, data, coords)\n );\n\n firstToolNearPoint.toolSelectedCallback(\n evt,\n firstAnnotationNearPoint,\n 'mouse'\n );\n\n return;\n }\n\n // ACTIVE TOOL W/ POST CALLBACK?\n // If any tools are active, check if they have a special reason for dealing with the event.\n if (activeTools.length > 0) {\n // TODO: If length > 1, you could assess fitness and select the ideal tool\n // TODO: But because we're locking this to 'active' tools, that should rarely be an issue\n // Super-Meta-TODO: ^ I think we should just take the approach of one active tool per mouse button?\n const firstActiveToolWithCallback = activeTools.find(\n tool => typeof tool.postMouseDownCallback === 'function'\n );\n\n if (firstActiveToolWithCallback) {\n const consumedEvent = firstActiveToolWithCallback.postMouseDownCallback(\n evt\n );\n\n if (consumedEvent) {\n return;\n }\n }\n }\n}\n","import addNewMeasurement from './addNewMeasurement.js';\nimport { getters, state } from './../../store/index.js';\nimport getActiveToolsForElement from './../../store/getActiveToolsForElement.js';\nimport BaseAnnotationTool from './../../tools/base/BaseAnnotationTool.js';\n\n// Todo: We could simplify this if we only allow one active\n// Tool per mouse button mask?\nexport default function(evt) {\n if (state.isToolLocked) {\n return;\n }\n\n const eventData = evt.detail;\n const element = eventData.element;\n\n // Filter out disabled, enabled, and passive\n let tools = getActiveToolsForElement(element, getters.mouseTools());\n\n // Filter out tools that do not match mouseButtonMask\n tools = tools.filter(\n tool =>\n Array.isArray(tool.options.mouseButtonMask) &&\n tool.options.mouseButtonMask.includes(eventData.buttons) &&\n tool.options.isMouseActive\n );\n\n if (tools.length === 0) {\n return;\n }\n\n const activeTool = tools[0];\n\n if (typeof activeTool.preMouseDownActivateCallback === 'function') {\n const consumedEvent = activeTool.preMouseDownActivateCallback(evt);\n\n if (consumedEvent) {\n return;\n }\n }\n\n // Note: custom `addNewMeasurement` will need to prevent event bubbling\n if (activeTool.addNewMeasurement) {\n activeTool.addNewMeasurement(evt, 'mouse');\n } else if (activeTool instanceof BaseAnnotationTool) {\n addNewMeasurement(evt, activeTool);\n }\n}\n","import external from '../../externalModules.js';\nimport { addToolState } from '../../stateManagement/toolState.js';\nimport { moveHandle, moveNewHandle } from '../../manipulators/index.js';\n\nexport default function(evt, tool) {\n //\n evt.preventDefault();\n evt.stopPropagation();\n const eventData = evt.detail;\n const element = eventData.element;\n const measurementData = tool.createNewMeasurement(eventData);\n\n if (!measurementData) {\n return;\n }\n\n // Associate this data with this imageId so we can render it and manipulate it\n addToolState(element, tool.name, measurementData);\n\n external.cornerstone.updateImage(element);\n\n const handleMover =\n Object.keys(measurementData.handles).length === 1\n ? moveHandle\n : moveNewHandle;\n\n handleMover(\n eventData,\n tool.name,\n measurementData,\n measurementData.handles.end,\n tool.options,\n 'mouse'\n );\n}\n","import { getters, state } from './../../store/index.js';\nimport getActiveToolsForElement from './../../store/getActiveToolsForElement.js';\n\n// Tools like wwwc. Non-annotation tools w/ specific\n// Down + mouse behavior\n// TODO: I don't like filtering in drag because it's such\n// A high frequency event. Anything we can do to reduce\n// Repeat math here would be a big help\nexport default function(evt) {\n if (state.isToolLocked) {\n return;\n }\n\n let tools;\n const eventData = evt.detail;\n const element = eventData.element;\n\n // Filter out disabled, enabled, and passive\n tools = getActiveToolsForElement(element, getters.mouseTools());\n tools = tools.filter(\n tool =>\n Array.isArray(tool.options.mouseButtonMask) &&\n tool.options.mouseButtonMask.includes(eventData.buttons) &&\n tool.options.isMouseActive\n );\n tools = tools.filter(tool => typeof tool.mouseDragCallback === 'function');\n\n if (tools.length === 0) {\n return;\n }\n\n const activeTool = tools[0];\n\n activeTool.mouseDragCallback(evt);\n}\n","import external from './../../externalModules.js';\n// State\nimport { getters, state } from './../../store/index.js';\nimport getInteractiveToolsForElement from './../../store/getInteractiveToolsForElement.js';\nimport getToolsWithDataForElement from './../../store/getToolsWithDataForElement.js';\n\n/**\n * This is mostly used to update the [un]hover state\n * of a tool.\n *\n * @private\n * @param {*} evt\n */\nexport default function(evt) {\n if (state.isToolLocked) {\n return;\n }\n\n let tools;\n const { element, currentPoints } = evt.detail;\n\n // Set the mouse position incase any tool needs it.\n state.mousePositionImage = currentPoints.image;\n\n // TODO: instead of filtering these for every interaction, we can change our\n // TODO: State's structure to always know these values.\n // Filter out disabled and enabled\n tools = getInteractiveToolsForElement(element, getters.mouseTools());\n\n const activeTools = tools.filter(\n tool => tool.mode === 'active' && tool.options.isMouseActive\n );\n\n let imageNeedsUpdate = false;\n\n // If any tools are active, check if they have a cursor, and if so update image.\n if (activeTools.length > 0) {\n imageNeedsUpdate = activeTools.some(tool => tool.hasCursor);\n }\n\n tools = getToolsWithDataForElement(element, tools);\n\n // Iterate over each tool, and each tool's data\n // Activate any handles we're hovering over, or whole tools if we're near the tool\n // If we've changed the state of anything, redrawn the image\n\n for (let t = 0; t < tools.length; t++) {\n const tool = tools[t];\n\n if (typeof tool.mouseMoveCallback === 'function') {\n imageNeedsUpdate = tool.mouseMoveCallback(evt) || imageNeedsUpdate;\n }\n }\n\n // Tool data activation status changed, redraw the image\n if (imageNeedsUpdate === true) {\n external.cornerstone.updateImage(element);\n }\n}\n","import customCallbackHandler from './../shared/customCallbackHandler.js';\nimport mouseDown from './mouseDown.js';\nimport mouseDownActivate from './mouseDownActivate.js';\nimport mouseDrag from './mouseDrag.js';\nimport mouseMove from './mouseMove.js';\n\nconst mouseClick = customCallbackHandler.bind(\n null,\n 'Mouse',\n 'mouseClickCallback'\n);\n\nconst mouseDoubleClick = customCallbackHandler.bind(\n null,\n 'Mouse',\n 'doubleClickCallback'\n);\n\nconst mouseUp = customCallbackHandler.bind(null, 'Mouse', 'mouseUpCallback');\n\nconst mouseWheel = customCallbackHandler.bind(\n null,\n 'MouseWheel',\n 'mouseWheelCallback'\n);\n\nexport {\n mouseClick,\n mouseDown,\n mouseDownActivate,\n mouseDoubleClick,\n mouseDrag,\n mouseMove,\n mouseUp,\n mouseWheel,\n};\n","import EVENTS from './../events.js';\nimport {\n mouseClick,\n mouseDown,\n mouseDownActivate,\n mouseDoubleClick,\n mouseDrag,\n mouseMove,\n mouseUp,\n mouseWheel,\n} from './mouseEventHandlers/index.js';\n\n/**\n * These listeners are emitted in order, and can be cancelled/prevented from bubbling\n * by any previous event.\n * - mouseMove: used to update the [un]hover state of a tool (highlighting)\n * - mouseDown: check to see if we are close to an existing annotation, grab it\n * - mouseDownActivate: createNewMeasurement (usually)\n * - mouseDrag: update measurement or apply strategy (wwwc)\n * - mouseDoubleClick: usually a one-time apply specialty action\n * - onImageRendered: redraw visible tool data\n * @private\n * @param {*} element\n * @returns {undefined}\n */\nconst enable = function(element) {\n element.addEventListener(EVENTS.MOUSE_CLICK, mouseClick);\n element.addEventListener(EVENTS.MOUSE_DOWN, mouseDown);\n element.addEventListener(EVENTS.MOUSE_DOWN_ACTIVATE, mouseDownActivate);\n element.addEventListener(EVENTS.MOUSE_DOUBLE_CLICK, mouseDoubleClick);\n element.addEventListener(EVENTS.MOUSE_DRAG, mouseDrag);\n element.addEventListener(EVENTS.MOUSE_MOVE, mouseMove);\n element.addEventListener(EVENTS.MOUSE_UP, mouseUp);\n element.addEventListener(EVENTS.MOUSE_WHEEL, mouseWheel);\n};\n\nconst disable = function(element) {\n element.removeEventListener(EVENTS.MOUSE_CLICK, mouseClick);\n element.removeEventListener(EVENTS.MOUSE_DOWN, mouseDown);\n element.removeEventListener(EVENTS.MOUSE_DOWN_ACTIVATE, mouseDownActivate);\n element.removeEventListener(EVENTS.MOUSE_DOUBLE_CLICK, mouseDoubleClick);\n element.removeEventListener(EVENTS.MOUSE_DRAG, mouseDrag);\n element.removeEventListener(EVENTS.MOUSE_MOVE, mouseMove);\n element.removeEventListener(EVENTS.MOUSE_UP, mouseUp);\n element.removeEventListener(EVENTS.MOUSE_WHEEL, mouseWheel);\n};\n\nexport default {\n enable,\n disable,\n};\n","import { state } from './../store/index.js';\nimport BaseBrushTool from './../tools/base/BaseBrushTool.js';\nimport onNewImageBrushEventHandler from '../eventListeners/onNewImageBrushEventHandler.js';\nimport external from './../externalModules.js';\n\nconst onNewImage = function(evt) {\n if (state.isToolLocked) {\n return false;\n }\n\n const element = evt.detail.element;\n\n const tools = state.tools.filter(\n tool =>\n tool.element === element &&\n (tool.mode === 'active' ||\n tool.mode === 'passive' ||\n tool.mode === 'enabled')\n );\n\n if (tools.length === 0) {\n return false;\n }\n\n tools.forEach(tool => {\n if (tool.newImageCallback) {\n tool.newImageCallback(evt);\n }\n });\n\n // Check if any brush tools are present.\n const brushTools = tools.filter(tool => tool instanceof BaseBrushTool);\n\n if (brushTools.length > 0) {\n onNewImageBrushEventHandler(evt);\n }\n};\n\nconst enable = function(element) {\n element.addEventListener(external.cornerstone.EVENTS.NEW_IMAGE, onNewImage);\n};\n\nconst disable = function(element) {\n element.removeEventListener(\n external.cornerstone.EVENTS.NEW_IMAGE,\n onNewImage\n );\n};\n\nexport default {\n enable,\n disable,\n};\n","import store from '../store/index.js';\nimport { getToolState, addToolState } from '../stateManagement/toolState.js';\nimport BaseBrushTool from './../tools/base/BaseBrushTool.js';\nimport external from '../externalModules.js';\n\nconst { setters } = store.modules.brush;\n\n/**\n * Clears the brush imageBitmapCache,\n * invaldates the data and calls for a re-render.\n * @private\n * @param {Object} evt - The event.\n */\nexport default function(evt) {\n const eventData = evt.detail;\n const element = eventData.element;\n let toolData = getToolState(\n element,\n BaseBrushTool.getReferencedToolDataName()\n );\n\n if (!toolData) {\n // Make toolData array as big as max number of segmentations.\n const maxSegmentations = BaseBrushTool.getNumberOfColors();\n\n for (let i = 0; i < maxSegmentations; i++) {\n addToolState(element, BaseBrushTool.getReferencedToolDataName(), {});\n }\n\n toolData = getToolState(element, BaseBrushTool.getReferencedToolDataName());\n\n // TEMP: HACK: Create first pixel data such that the tool has some data and the brush\n // Cursor can be rendered. Can be replaced once we have a mechanism for SVG cursors.\n const newPixelData = new Uint8ClampedArray(\n eventData.image.width * eventData.image.height\n );\n\n toolData.data[0].pixelData = newPixelData;\n\n toolData = getToolState(element, BaseBrushTool.getReferencedToolDataName());\n }\n const enabledElement = external.cornerstone.getEnabledElement(element);\n const maxSegmentations = BaseBrushTool.getNumberOfColors();\n\n // Invalidate the segmentation bitmap such that it gets redrawn.\n for (let i = 0; i < maxSegmentations; i++) {\n if (toolData.data[i]) {\n toolData.data[i].invalidated = true;\n }\n }\n\n // Refresh the canvas\n external.cornerstone.updateImage(eventData.element);\n}\n","import { state } from '../../store/index.js';\nimport getActiveToolsForElement from '../../store/getActiveToolsForElement.js';\n\nexport default function(evt) {\n if (state.isToolLocked) {\n return false;\n }\n\n // TODO: We sometimes see a null detail for TOUCH_PRESS\n const { element, numPointers } = evt.detail;\n let tools = state.tools.filter(tool =>\n tool.supportedInteractionTypes.includes('MultiTouch')\n );\n\n // Tool is active, and specific callback is active\n tools = getActiveToolsForElement(element, tools, 'MultiTouch');\n // Tool has expected callback custom function\n tools = tools.filter(\n tool =>\n typeof tool.multiTouchDragCallback === 'function' &&\n numPointers === tool.configuration.touchPointers\n );\n\n if (tools.length === 0) {\n return false;\n }\n\n const activeTool = tools[0];\n\n activeTool.multiTouchDragCallback(evt);\n}\n","// State\nimport { getters, state } from './../../store/index.js';\nimport getActiveToolsForElement from './../../store/getActiveToolsForElement.js';\nimport addNewMeasurement from './addNewMeasurement.js';\nimport BaseAnnotationTool from './../../tools/base/BaseAnnotationTool.js';\n\nexport default function(evt) {\n if (state.isToolLocked) {\n return;\n }\n\n const element = evt.detail.element;\n let tools = getActiveToolsForElement(element, getters.touchTools());\n\n tools = tools.filter(tool => tool.options.isTouchActive);\n\n if (tools.length === 0) {\n return;\n }\n\n const activeTool = tools[0];\n\n // Note: custom `addNewMeasurement` will need to prevent event bubbling\n if (activeTool && activeTool.addNewMeasurement) {\n activeTool.addNewMeasurement(evt, 'touch');\n } else if (activeTool instanceof BaseAnnotationTool) {\n addNewMeasurement(evt, activeTool);\n }\n}\n","import EVENTS from '../../events.js';\nimport external from '../../externalModules.js';\nimport { state } from '../../store/index.js';\nimport anyHandlesOutsideImage from './../../manipulators/anyHandlesOutsideImage.js';\nimport { moveNewHandle } from '../../manipulators/index.js';\nimport {\n addToolState,\n removeToolState,\n} from '../../stateManagement/toolState.js';\n\nexport default function(evt, tool) {\n console.log('touch: addNewMeasurement');\n //\n evt.preventDefault();\n evt.stopPropagation();\n //\n const touchEventData = evt.detail;\n const element = touchEventData.element;\n const measurementData = tool.createNewMeasurement(touchEventData);\n\n if (!measurementData) {\n return;\n }\n\n addToolState(element, tool.name, measurementData);\n\n // Todo: Looks like we're handling the \"up\" of the tap?\n if (\n Object.keys(measurementData.handles).length === 1 &&\n touchEventData.type === EVENTS.TAP\n ) {\n // Todo: bold assumptions about measurement data for all tools?\n measurementData.active = false;\n measurementData.handles.end.active = false;\n measurementData.handles.end.highlight = false;\n measurementData.invalidated = true;\n\n const deleteIfHandleOutsideImage =\n state.deleteIfHandleOutsideImage ||\n tool.options.deleteIfHandleOutsideImage;\n\n if (\n deleteIfHandleOutsideImage &&\n anyHandlesOutsideImage(touchEventData, measurementData.handles)\n ) {\n // Delete the measurement\n removeToolState(element, tool.name, measurementData);\n }\n\n external.cornerstone.updateImage(element);\n\n return;\n }\n\n external.cornerstone.updateImage(element);\n\n moveNewHandle(\n touchEventData,\n tool.name,\n measurementData,\n measurementData.handles.end,\n tool.options,\n 'touch'\n );\n}\n","export default function(toolData) {\n if (!toolData) {\n return;\n }\n\n for (let i = 0; i < toolData.data.length; i++) {\n const data = toolData.data[i];\n\n data.active = false;\n if (!data.handles) {\n continue;\n }\n\n deactivateAllHandles(data.handles);\n }\n}\n\nfunction deactivateAllHandles(handles) {\n Object.keys(handles).forEach(function(name) {\n const handle = handles[name];\n\n handle.active = false;\n });\n}\n","import external from '../../externalModules.js';\nimport touchStartActive from './touchStartActive.js';\n// State\nimport { getters, state } from '../../store/index.js';\nimport getActiveToolsForElement from '../../store/getActiveToolsForElement.js';\nimport getToolsWithDataForElement from '../../store/getToolsWithDataForElement.js';\nimport { getToolState } from '../../stateManagement/toolState.js';\n//\nimport getHandleNearImagePoint from '../../manipulators/getHandleNearImagePoint.js';\nimport { moveHandle, moveAllHandles } from '../../manipulators/index.js';\n//\nimport deactivateAllToolInstances from './shared/deactivateAllToolInstances.js';\n\nexport default function(evt) {\n if (state.isToolLocked) {\n return;\n }\n\n let tools;\n const distanceFromHandle = 28;\n const element = evt.detail.element;\n const coords = evt.detail.currentPoints.canvas;\n\n tools = getActiveToolsForElement(element, getters.touchTools());\n tools = getToolsWithDataForElement(element, tools);\n\n // Deactivate everything\n // DeactivateAllToolInstances(toolData);\n\n // Find all tools w/ handles that we are near\n const toolsWithMoveableHandles = tools.filter(tool => {\n const toolState = getToolState(element, tool.name);\n\n for (let i = 0; i < toolState.data.length; i++) {\n if (\n getHandleNearImagePoint(\n element,\n toolState.data[i].handles,\n coords,\n distanceFromHandle\n ) !== undefined\n ) {\n return true;\n }\n }\n\n return false;\n });\n\n // TODO: More than one? Which one was moved most recently?\n // We'll just grab the first one we encounter for now\n if (toolsWithMoveableHandles.length > 0) {\n // Todo: ignore: touch_start, tap\n\n const firstToolWithMoveableHandles = toolsWithMoveableHandles[0];\n const toolState = getToolState(element, firstToolWithMoveableHandles.name);\n const moveableHandle = toolState.data.find(\n d =>\n getHandleNearImagePoint(\n element,\n d.handles,\n coords,\n distanceFromHandle\n ) !== undefined\n );\n\n toolState.data.active = true;\n moveableHandle.active = true; // Why here, but not touchStart?\n external.cornerstone.updateImage(element);\n\n const toolOptions = Object.assign(\n {},\n {\n doneMovingCallback: () => {\n deactivateAllToolInstances(toolState);\n },\n },\n firstToolWithMoveableHandles.options\n );\n\n moveHandle(\n evt.detail,\n firstToolWithMoveableHandles.name,\n toolState.data,\n moveableHandle,\n toolOptions,\n 'touch'\n );\n evt.stopImmediatePropagation();\n evt.preventDefault();\n // Why no stopPropagation?\n\n return;\n }\n\n // Find all tools near our point\n const toolsNearPoint = tools.filter(tool => {\n const toolState = getToolState(element, tool.name);\n const isNearPoint =\n toolState &&\n toolState.data &&\n tool.pointNearTool &&\n toolState.data.some(data => tool.pointNearTool(element, data, coords));\n\n return isNearPoint;\n });\n\n // TODO: More than one? Which one was moved most recently?\n // We'll just grab the first one we encounter for now\n if (toolsNearPoint.length > 0) {\n // Todo: Ignore: TAP, START, PRESS\n const firstToolNearPoint = toolsNearPoint[0];\n const toolState = getToolState(element, firstToolNearPoint.name);\n const firstAnnotationNearPoint = toolState.data.find(data =>\n firstToolNearPoint.pointNearTool(element, data, coords)\n );\n\n // Todo: ignore: touch_start, tap\n firstAnnotationNearPoint.active = true;\n external.cornerstone.updateImage(element);\n\n const toolOptions = Object.assign(\n {},\n {\n doneMovingCallback: () => {\n deactivateAllToolInstances(toolState);\n },\n },\n firstToolNearPoint.options\n );\n\n moveAllHandles(\n evt.detail,\n firstToolNearPoint.name,\n firstAnnotationNearPoint,\n null,\n toolOptions,\n 'touch'\n );\n\n evt.stopImmediatePropagation();\n evt.preventDefault();\n // TODO: Why no stop propagation?\n\n return;\n }\n\n // If there is nothing to move, add a new instance of the tool\n // Need to check here to see if activation is allowed!\n // TODO: What would this be? First active tool?\n // Or should _always_ pass through to our larger event handler that checks\n // All tools anyway?\n const allActiveTools = getActiveToolsForElement(\n element,\n getters.touchTools()\n );\n\n if (allActiveTools.length > 0 && allActiveTools[0].touchStartActiveCallback) {\n allActiveTools[0].touchStartActiveCallback(evt);\n } else {\n touchStartActive(evt);\n }\n\n return false;\n}\n","// State\nimport { getters, state } from '../../store/index.js';\n// Import anyHandlesOutsideImage from '../manipulators/anyHandlesOutsideImage.js';\nimport { findHandleDataNearImagePoint } from '../../util/findAndMoveHelpers.js';\nimport getToolsWithMoveableHandles from '../../store/getToolsWithMoveableHandles.js';\nimport { getToolState } from './../../stateManagement/toolState.js';\nimport getInteractiveToolsForElement from './../../store/getInteractiveToolsForElement.js';\nimport getToolsWithDataForElement from './../../store/getToolsWithDataForElement.js';\n\nexport default function(evt) {\n if (state.isToolLocked) {\n return;\n }\n\n const eventData = evt.detail;\n const element = eventData.element;\n const coords = eventData.startPoints.canvas;\n\n const activeAndPassiveTools = getInteractiveToolsForElement(\n element,\n getters.touchTools()\n );\n\n const activeTools = activeAndPassiveTools.filter(\n tool => tool.mode === 'active' && tool.options.isTouchActive\n );\n\n // If any tools are active, check if they have a special reason for dealing with the event.\n if (activeTools.length > 0) {\n // TODO: If length > 1, you could assess fitness and select the ideal tool\n // TODO: But because we're locking this to 'active' tools, that should rarely be an issue\n // Super-Meta-TODO: ^ I think we should just take the approach of one active tool per mouse button?\n const firstActiveToolWithCallback = activeTools.find(\n tool => typeof tool.preTouchStartCallback === 'function'\n );\n\n if (firstActiveToolWithCallback) {\n const consumedEvent = firstActiveToolWithCallback.preTouchStartCallback(\n evt\n );\n\n if (consumedEvent) {\n return;\n }\n }\n }\n\n const annotationTools = getToolsWithDataForElement(\n element,\n activeAndPassiveTools\n );\n\n // NEAR HANDLES?\n const annotationToolsWithMoveableHandles = getToolsWithMoveableHandles(\n element,\n annotationTools,\n coords,\n 'touch'\n );\n\n // TODO: More than one? Which one was moved most recently?\n // We'll just grab the first one we encounter for now\n if (annotationToolsWithMoveableHandles.length > 0) {\n // Todo: Ignore TAP, START, PRESS\n\n const firstToolWithMoveableHandles = annotationToolsWithMoveableHandles[0];\n const toolState = getToolState(element, firstToolWithMoveableHandles.name);\n\n const { handle, data } = findHandleDataNearImagePoint(\n element,\n toolState,\n firstToolWithMoveableHandles.name,\n coords,\n 'touch'\n );\n\n firstToolWithMoveableHandles.handleSelectedCallback(\n evt,\n data,\n handle,\n 'touch'\n );\n\n return;\n }\n\n // NEAR POINT?\n const annotationToolsWithPointNearTouch = annotationTools.filter(tool => {\n const toolState = getToolState(element, tool.name);\n const isNearPoint =\n toolState &&\n toolState.data &&\n tool.pointNearTool &&\n toolState.data.some(data =>\n tool.pointNearTool(element, data, coords, 'touch')\n );\n\n return isNearPoint;\n });\n\n // TODO: More than one? Which one was moved most recently?\n // We'll just grab the first one we encounter for now\n if (annotationToolsWithPointNearTouch.length > 0) {\n // Todo: Ignore: TAP, START, PRESS\n const firstToolNearPoint = annotationToolsWithPointNearTouch[0];\n const toolState = getToolState(element, firstToolNearPoint.name);\n const firstAnnotationNearPoint = toolState.data.find(data =>\n firstToolNearPoint.pointNearTool(element, data, coords)\n );\n\n firstToolNearPoint.toolSelectedCallback(\n evt,\n firstAnnotationNearPoint,\n 'touch'\n );\n\n return;\n }\n\n // If any tools are active, check if they have a special reason for dealing with the event.\n if (activeTools.length > 0) {\n // TODO: If length > 1, you could assess fitness and select the ideal tool\n // TODO: But because we're locking this to 'active' tools, that should rarely be an issue\n // Super-Meta-TODO: ^ I think we should just take the approach of one active tool per mouse button?\n const firstActiveToolWithCallback = activeTools.find(\n tool => typeof tool.postTouchStartCallback === 'function'\n );\n\n if (firstActiveToolWithCallback) {\n const consumedEvent = firstActiveToolWithCallback.postTouchStartCallback(\n evt\n );\n\n if (consumedEvent) {\n return;\n }\n }\n }\n}\n","import customCallbackHandler from './../shared/customCallbackHandler.js';\nimport multiTouchDrag from './multiTouchDrag.js';\nimport tap from './tap.js';\nimport touchStart from './touchStart.js';\nimport touchStartActive from './touchStartActive.js';\n\nconst doubleTap = customCallbackHandler.bind(\n null,\n 'DoubleTap',\n 'doubleTapCallback'\n);\n// TODO: some touchDrag tools don't want to fire on touchStart\n// TODO: Drag tools have an option `fireOnTouchStart` used to filter\n// TODO: Them out of TOUCH_START handler\nconst touchDrag = customCallbackHandler.bind(\n null,\n 'Touch',\n 'touchDragCallback'\n);\nconst touchEnd = customCallbackHandler.bind(null, 'Touch', 'touchEndCallback');\nconst touchPinch = customCallbackHandler.bind(\n null,\n 'TouchPinch',\n 'touchPinchCallback'\n);\nconst touchPress = customCallbackHandler.bind(\n null,\n 'Touch',\n 'touchPressCallback'\n);\nconst touchRotate = customCallbackHandler.bind(\n null,\n 'TouchRotate',\n 'touchRotateCallback'\n);\n\nexport {\n doubleTap,\n multiTouchDrag,\n tap,\n touchDrag,\n touchEnd,\n touchPinch,\n touchPress,\n touchRotate,\n touchStart,\n touchStartActive,\n};\n","import EVENTS from '../events.js';\nimport {\n tap,\n doubleTap,\n multiTouchDrag,\n touchStart,\n touchStartActive,\n touchRotate,\n touchDrag,\n touchEnd,\n touchPress,\n touchPinch,\n} from './touchEventHandlers/index.js';\n\n/**\n * These listeners are emitted in order, and can be cancelled/prevented from bubbling\n * by any previous event.\n * - tap:\n * - touchStart: check to see if we are close to an existing annotation, grab it\n * - touchDrag:\n * - touchStartActive: createNewMeasurement (usually)\n * - touchPress:\n * - touchRotate:\n * - doubleTap: usually a one-time apply specialty action\n * - touchPinch:\n * - onImageRendered: redraw visible tool data\n * @private\n * @param {*} element\n */\nconst enable = function(element) {\n element.addEventListener(EVENTS.TAP, tap);\n element.addEventListener(EVENTS.TOUCH_START, touchStart, { passive: false });\n element.addEventListener(EVENTS.TOUCH_DRAG, touchDrag, { passive: false });\n element.addEventListener(EVENTS.TOUCH_END, touchEnd);\n // Mouse equivelant is `mouse_down_activate`\n // Should the naming pattern here match?\n element.addEventListener(EVENTS.TOUCH_START_ACTIVE, touchStartActive);\n element.addEventListener(EVENTS.TOUCH_PRESS, touchPress);\n element.addEventListener(EVENTS.DOUBLE_TAP, doubleTap);\n element.addEventListener(EVENTS.TOUCH_PINCH, touchPinch);\n element.addEventListener(EVENTS.TOUCH_ROTATE, touchRotate);\n element.addEventListener(EVENTS.MULTI_TOUCH_DRAG, multiTouchDrag);\n};\n\nconst disable = function(element) {\n element.removeEventListener(EVENTS.TAP, tap);\n element.removeEventListener(EVENTS.TOUCH_START, touchStart);\n element.removeEventListener(EVENTS.TOUCH_DRAG, touchDrag);\n element.removeEventListener(EVENTS.TOUCH_END, touchEnd);\n // Mouse equivelant is `mouse_down_activate`\n // Should the naming pattern here match?\n element.removeEventListener(EVENTS.TOUCH_START_ACTIVE, touchStartActive);\n element.removeEventListener(EVENTS.TOUCH_PRESS, touchPress);\n element.removeEventListener(EVENTS.DOUBLE_TAP, doubleTap);\n element.removeEventListener(EVENTS.TOUCH_PINCH, touchPinch);\n element.removeEventListener(EVENTS.TOUCH_ROTATE, touchRotate);\n element.removeEventListener(EVENTS.MULTI_TOUCH_DRAG, multiTouchDrag);\n};\n\nexport default {\n enable,\n disable,\n};\n","import store from './index.js';\nimport getToolForElement from './getToolForElement.js';\n\n/**\n * Adds a tool to an enabled element.\n *\n * @public\n * @function addToolForElement\n * @memberof CornerstoneTools\n *\n * @param {HTMLElement} element The element to add the tool to.\n * @param {BaseTool} apiTool The tool to add to the element.\n * @param {Object} [configuration] Override the default tool configuration\n * @returns {undefined}\n */\nconst addToolForElement = function(element, apiTool, configuration) {\n // Instantiating the tool here makes it harder to accidentally add\n // The same tool (by reference) for multiple elements (which would reassign the tool\n // To a new element).\n const tool = new apiTool(configuration);\n const toolAlreadyAddedToElement = getToolForElement(element, tool.name);\n\n if (toolAlreadyAddedToElement) {\n console.warn(`${tool.name} has already been added to the target element`);\n\n return;\n }\n\n tool.element = element;\n store.state.tools.push(tool);\n};\n\n/**\n * Adds a tool to all enabled element.\n *\n * @public\n * @function addTool\n * @memberof CornerstoneTools\n *\n * @param {BaseTool} apiTool The tool to add to each element.\n * @param {Object} [configuration] Override the default tool configuration\n * @returns {undefined}\n */\nconst addTool = function(apiTool, configuration) {\n _addToolGlobally(apiTool, configuration);\n store.state.enabledElements.forEach(element => {\n addToolForElement(element, apiTool, configuration);\n });\n};\n\n/**\n * Adds tool with matching name from globally registered tools.\n * Requires `globalToolSyncEnabled` to be set to true\n *\n * @private\n * @function addToolGlobally\n *\n * @param {BaseTool} apiTool\n * @param {Object} [configuration] Override the default tool configuration\n * @returns {undefined}\n */\nconst _addToolGlobally = function(apiTool, configuration) {\n if (!store.modules.globalConfiguration.state.globalToolSyncEnabled) {\n return;\n }\n\n const tool = new apiTool(configuration);\n const toolAlreadyAddedGlobally =\n store.state.globalTools[tool.name] !== undefined;\n\n if (toolAlreadyAddedGlobally) {\n console.warn(`${tool.name} has already been added globally`);\n\n return;\n }\n\n store.state.globalTools[tool.name] = {\n tool: apiTool,\n configuration,\n activeBindings: [],\n };\n};\n\nexport { addTool, addToolForElement };\n","import {\n mouseEventListeners,\n wheelEventListener,\n touchEventListeners,\n} from '../../eventListeners/index.js';\nimport {\n imageRenderedEventDispatcher,\n mouseToolEventDispatcher,\n newImageEventDispatcher,\n touchToolEventDispatcher,\n} from '../../eventDispatchers/index.js';\nimport { addToolForElement } from './../addTool.js';\nimport {\n setToolActiveForElement,\n setToolPassiveForElement,\n setToolEnabledForElement,\n setToolDisabledForElement,\n} from './../setToolMode.js';\nimport store from '../index.js';\n\n/**\n * Element Enabled event.\n *\n * @event Cornerstone#ElementEnabled\n * @type {Object}\n * @property {string} type\n * @property {Object} detail\n * @property {HTMLElement} detail.element - The element being enabled.\n */\n\n/* TODO: It would be nice if this automatically added \"all tools\"\n * To the enabledElement that already exist on all other tools.\n * A half-measure might be a new method to \"duplicate\" the tool\n * Configuration for an existing enabled element\n * We may need to also save/store the original class/constructor per tool\n * To accomplish this\n */\n/**\n * Adds an enabledElement to our store.\n * @export\n * @private\n * @method\n * @name addEnabledElement\n * @param {Cornerstone#ElementEnabled} elementEnabledEvt\n * @listens Cornerstone#ElementEnabled\n */\nexport default function(elementEnabledEvt) {\n console.log('EVENT:ELEMENT_ENABLED');\n const enabledElement = elementEnabledEvt.detail.element;\n\n // Dispatchers\n imageRenderedEventDispatcher.enable(enabledElement);\n newImageEventDispatcher.enable(enabledElement);\n\n // Mouse\n if (store.modules.globalConfiguration.state.mouseEnabled) {\n mouseEventListeners.enable(enabledElement);\n wheelEventListener.enable(enabledElement);\n mouseToolEventDispatcher.enable(enabledElement);\n }\n\n // Touch\n if (store.modules.globalConfiguration.state.touchEnabled) {\n touchEventListeners.enable(enabledElement);\n touchToolEventDispatcher.enable(enabledElement);\n }\n\n // State\n _addEnabledElmenet(enabledElement);\n}\n\n/**\n * Adds the enabled element to the store.\n * @private\n * @method\n * @param {HTMLElement} enabledElement\n */\nconst _addEnabledElmenet = function(enabledElement) {\n store.state.enabledElements.push(enabledElement);\n if (store.modules) {\n _initModulesOnElement(enabledElement);\n }\n _addGlobalToolsToElement(enabledElement);\n _repeatGlobalToolHistory(enabledElement);\n};\n\n/**\n * Iterate over our store's modules. If the module has an `enabledElementCallback`\n * call it and pass it a reference to our enabled element.\n * @private\n * @method\n * @param {Object} enabledElement\n */\nfunction _initModulesOnElement(enabledElement) {\n const modules = store.modules;\n\n Object.keys(modules).forEach(function(key) {\n if (typeof modules[key].enabledElementCallback === 'function') {\n modules[key].enabledElementCallback(enabledElement);\n }\n });\n}\n\nfunction _addGlobalToolsToElement(enabledElement) {\n if (!store.modules.globalConfiguration.state.globalToolSyncEnabled) {\n return;\n }\n\n Object.keys(store.state.globalTools).forEach(function(key) {\n const { tool, configuration } = store.state.globalTools[key];\n\n addToolForElement(enabledElement, tool, configuration);\n });\n}\n\nfunction _repeatGlobalToolHistory(enabledElement) {\n if (!store.modules.globalConfiguration.state.globalToolSyncEnabled) {\n return;\n }\n\n const setToolModeFns = {\n active: setToolActiveForElement,\n passive: setToolPassiveForElement,\n enabled: setToolEnabledForElement,\n disabled: setToolDisabledForElement,\n };\n\n store.state.globalToolChangeHistory.forEach(historyEvent => {\n const args = historyEvent.args.slice(0);\n\n args.unshift(enabledElement);\n setToolModeFns[historyEvent.mode].apply(null, args);\n });\n}\n","import {\n mouseEventListeners,\n wheelEventListener,\n touchEventListeners,\n} from '../../eventListeners/index.js';\nimport {\n imageRenderedEventDispatcher,\n mouseToolEventDispatcher,\n newImageEventDispatcher,\n touchToolEventDispatcher,\n} from '../../eventDispatchers/index.js';\nimport store from '../index.js';\n\n/**\n * Element Disabled event.\n *\n * @event Cornerstone#ElementDisabled\n * @type {Object}\n * @property {string} type\n * @property {Object} detail\n * @property {HTMLElement} detail.element - The element being disabled.\n */\n\n/**\n * Removes an enabledElement from our store, and all associated tools that were added to it.\n * @export\n * @private\n * @method\n * @name removeEnabledElement\n * @param {Cornerstone#ElementDisabled} elementDisabledEvt\n * @listens Cornerstone#ElementDisabled\n */\nexport default function(elementDisabledEvt) {\n console.info('EVENT:ELEMENT_DISABLED');\n const enabledElement = elementDisabledEvt.detail.element;\n\n // Dispatchers\n imageRenderedEventDispatcher.disable(enabledElement);\n newImageEventDispatcher.disable(enabledElement);\n\n // Mouse\n if (store.modules.globalConfiguration.state.mouseEnabled) {\n mouseEventListeners.disable(enabledElement);\n wheelEventListener.disable(enabledElement);\n mouseToolEventDispatcher.disable(enabledElement);\n }\n\n // Touch\n if (store.modules.globalConfiguration.state.touchEnabled) {\n touchEventListeners.disable(enabledElement);\n touchToolEventDispatcher.disable(enabledElement);\n }\n\n // State\n _removeAllToolsForElement(enabledElement);\n _removeEnabledElement(enabledElement);\n}\n\n/**\n * Remove all tools associated with enabled element.\n * @private\n * @method\n * @param {HTMLElement} enabledElement\n */\nconst _removeAllToolsForElement = function(enabledElement) {\n // Note: We may want to `setToolDisabled` before removing from store\n // Or take other action to remove any lingering eventListeners/state\n store.state.tools = store.state.tools.filter(\n tool => tool.element !== enabledElement\n );\n};\n\n/**\n * Remove the enabled element from the store if it exists.\n * @private\n * @method\n * @param {HTMLElement} enabledElement\n */\nconst _removeEnabledElement = function(enabledElement) {\n if (store.modules) {\n _cleanModulesOnElement(enabledElement);\n }\n\n const foundElementIndex = store.state.enabledElements.findIndex(\n element => element === enabledElement\n );\n\n if (foundElementIndex > -1) {\n store.state.enabledElements.splice(foundElementIndex, 1);\n } else {\n console.warn('unable to remove element');\n }\n};\n\n/**\n * Iterate over our store's modules. If the module has a\n * `removeEnabledElementCallback` call it and clean up unneeded metadata.\n * @private\n * @method\n * @param {Object} enabledElement\n */\nfunction _cleanModulesOnElement(enabledElement) {\n const modules = store.modules;\n\n Object.keys(modules).forEach(function(key) {\n if (typeof modules[key].removeEnabledElementCallback === 'function') {\n modules[key].removeEnabledElementCallback(enabledElement);\n }\n });\n}\n","import { state } from './../store/index.js';\nimport external from './../externalModules.js';\n\nconst enable = function() {\n disable(); // Clean up any lingering listeners\n window.addEventListener('resize', resizeThrottler, false);\n};\n\nconst disable = function() {\n window.removeEventListener('resize', resizeThrottler, false);\n};\n\nlet resizeTimeout;\n\nfunction resizeThrottler() {\n // Ignore resize events as long as an actualResizeHandler execution is in the queue\n if (!resizeTimeout) {\n resizeTimeout = setTimeout(function() {\n resizeTimeout = null;\n forceEnabledElementResize();\n\n // The actualResizeHandler will execute at a rate of 15fps\n }, 66);\n }\n}\n\nexport const forceEnabledElementResize = function() {\n state.enabledElements.forEach(element => {\n external.cornerstone.resize(element);\n });\n};\n\nexport default {\n enable,\n disable,\n};\n","import external from './externalModules.js';\nimport store from './store/index.js';\nimport addEnabledElement from './store/internals/addEnabledElement.js';\nimport removeEnabledElement from './store/internals/removeEnabledElement.js';\nimport windowResizeHandler from './eventListeners/windowResizeHandler.js';\n\n/**\n * Merges the provided configuration with default values and returns a\n * configured CornerstoneTools instance.\n * @export\n * @public\n * @method\n * @name init\n *\n * @param {Object} configuration\n * @returns {Object} A configured CornerstoneTools instance with top level API members.\n */\nexport default function(configuration) {\n _addCornerstoneEventListeners();\n _initModules();\n windowResizeHandler.enable();\n\n // Apply global configuration\n store.modules.globalConfiguration.state = Object.assign(\n {},\n store.modules.globalConfiguration.state,\n configuration\n );\n}\n\n/**\n * Wires up event listeners for the Cornerstone#ElementDisabled and\n * Cornerstone#ElementEnabled events.\n * @private\n * @method\n */\nfunction _addCornerstoneEventListeners() {\n // Clear any listeners that may already be set\n _removeCornerstoneEventListeners();\n\n const cornerstone = external.cornerstone;\n const elementEnabledEvent = cornerstone.EVENTS.ELEMENT_ENABLED;\n const elementDisabledEvent = cornerstone.EVENTS.ELEMENT_DISABLED;\n\n cornerstone.events.addEventListener(elementEnabledEvent, addEnabledElement);\n cornerstone.events.addEventListener(\n elementDisabledEvent,\n removeEnabledElement\n );\n}\n\n/**\n * Removes event listeners for the Cornerstone#ElementDisabled and\n * Cornerstone#ElementEnabled events.\n * @private\n * @method\n */\nfunction _removeCornerstoneEventListeners() {\n const cornerstone = external.cornerstone;\n const elementEnabledEvent = cornerstone.EVENTS.ELEMENT_ENABLED;\n const elementDisabledEvent = cornerstone.EVENTS.ELEMENT_DISABLED;\n\n cornerstone.events.removeEventListener(\n elementEnabledEvent,\n addEnabledElement\n );\n cornerstone.events.removeEventListener(\n elementDisabledEvent,\n removeEnabledElement\n );\n}\n\n/*\n * TODO: This could cause issues if the module was already initialized for\n * the store. As there's nothing stopping implementers from calling `init`\n * multiple times. Modules should self-check if they have already been\n * registered to prevent issues.\n */\n\n/**\n * Iterate over our store's modules. If the module has an `onRegisterCallback`\n * call it. This hook can be used to setup any global store requirements per\n * module.\n * @private\n * @method\n */\nfunction _initModules() {\n const modules = store.modules;\n\n Object.keys(modules).forEach(function(key) {\n if (typeof modules[key].onRegisterCallback === 'function') {\n modules[key].onRegisterCallback();\n }\n });\n}\n","import external from './../externalModules.js';\nimport requestPoolManager from '../requestPool/requestPoolManager.js';\nimport loadHandlerManager from '../stateManagement/loadHandlerManager.js';\nimport { addToolState, getToolState } from '../stateManagement/toolState.js';\nimport { setMaxSimultaneousRequests } from '../util/getMaxSimultaneousRequests.js';\n\nconst toolType = 'stackPrefetch';\nconst requestType = 'prefetch';\n\nlet configuration = {\n maxImagesToPrefetch: Infinity,\n};\n\nlet resetPrefetchTimeout;\nconst resetPrefetchDelay = 10;\n\nfunction range(lowEnd, highEnd) {\n // Javascript version of Python's range function\n // http://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-an-array-based-on-suppl\n lowEnd = Math.round(lowEnd) || 0;\n highEnd = Math.round(highEnd) || 0;\n\n const arr = [];\n let c = highEnd - lowEnd + 1;\n\n if (c <= 0) {\n return arr;\n }\n\n while (c--) {\n arr[c] = highEnd--;\n }\n\n return arr;\n}\n\nconst max = function(arr) {\n return Math.max.apply(null, arr);\n};\n\nconst min = function(arr) {\n return Math.min.apply(null, arr);\n};\n\nfunction nearestIndex(arr, x) {\n // Return index of nearest values in array\n // http://stackoverflow.com/questions/25854212/return-index-of-nearest-values-in-an-array\n const l = [];\n const h = [];\n\n arr.forEach(function(v) {\n if (v < x) {\n l.push(v);\n } else if (v > x) {\n h.push(v);\n }\n });\n\n return {\n low: arr.indexOf(max(l)),\n high: arr.indexOf(min(h)),\n };\n}\n\nfunction prefetch(element) {\n // Check to make sure stack data exists\n const stackData = getToolState(element, 'stack');\n\n if (!stackData || !stackData.data || !stackData.data.length) {\n return;\n }\n\n const stack = stackData.data[0];\n\n // Get the stackPrefetch tool data\n const stackPrefetchData = getToolState(element, toolType);\n\n if (!stackPrefetchData) {\n return;\n }\n\n const stackPrefetch = stackPrefetchData.data[0] || {};\n\n // If all the requests are complete, disable the stackPrefetch tool\n if (\n !stackPrefetch.indicesToRequest ||\n !stackPrefetch.indicesToRequest.length\n ) {\n stackPrefetch.enabled = false;\n }\n\n // Make sure the tool is still enabled\n if (stackPrefetch.enabled === false) {\n return;\n }\n\n // Remove an imageIdIndex from the list of indices to request\n // This fires when the individual image loading deferred is resolved\n function removeFromList(imageIdIndex) {\n const index = stackPrefetch.indicesToRequest.indexOf(imageIdIndex);\n\n if (index > -1) {\n // Don't remove last element if imageIdIndex not found\n stackPrefetch.indicesToRequest.splice(index, 1);\n }\n }\n\n // Remove all already cached images from the\n // IndicesToRequest array\n stackPrefetchData.data[0].indicesToRequest.sort((a, b) => a - b);\n const indicesToRequestCopy = stackPrefetch.indicesToRequest.slice();\n\n indicesToRequestCopy.forEach(function(imageIdIndex) {\n const imageId = stack.imageIds[imageIdIndex];\n\n if (!imageId) {\n return;\n }\n\n const imageLoadObject = external.cornerstone.imageCache.getImageLoadObject(\n imageId\n );\n\n if (imageLoadObject) {\n removeFromList(imageIdIndex);\n }\n });\n\n // Stop here if there are no images left to request\n // After those in the cache have been removed\n if (!stackPrefetch.indicesToRequest.length) {\n return;\n }\n\n // Clear the requestPool of prefetch requests\n requestPoolManager.clearRequestStack(requestType);\n\n // Identify the nearest imageIdIndex to the currentImageIdIndex\n const nearest = nearestIndex(\n stackPrefetch.indicesToRequest,\n stack.currentImageIdIndex\n );\n\n let imageId;\n let nextImageIdIndex;\n const preventCache = false;\n\n function doneCallback(image) {\n // Console.log('prefetch done: ' + image.imageId);\n const imageIdIndex = stack.imageIds.indexOf(image.imageId);\n\n removeFromList(imageIdIndex);\n }\n\n // Retrieve the errorLoadingHandler if one exists\n const errorLoadingHandler = loadHandlerManager.getErrorLoadingHandler();\n\n function failCallback(error) {\n console.log(`prefetch errored: ${error}`);\n if (errorLoadingHandler) {\n errorLoadingHandler(element, imageId, error, 'stackPrefetch');\n }\n }\n\n // Prefetch images around the current image (before and after)\n let lowerIndex = nearest.low;\n let higherIndex = nearest.high;\n\n while (\n lowerIndex >= 0 ||\n higherIndex < stackPrefetch.indicesToRequest.length\n ) {\n const currentIndex = stack.currentImageIdIndex;\n const shouldSkipLower =\n currentIndex - stackPrefetch.indicesToRequest[lowerIndex] >\n configuration.maxImagesToPrefetch;\n const shouldSkipHigher =\n stackPrefetch.indicesToRequest[higherIndex] - currentIndex >\n configuration.maxImagesToPrefetch;\n\n const shouldLoadLower = !shouldSkipLower && lowerIndex >= 0;\n const shouldLoadHigher =\n !shouldSkipHigher && higherIndex < stackPrefetch.indicesToRequest.length;\n\n if (!shouldLoadHigher && !shouldLoadLower) {\n break;\n }\n\n if (shouldLoadLower) {\n nextImageIdIndex = stackPrefetch.indicesToRequest[lowerIndex--];\n imageId = stack.imageIds[nextImageIdIndex];\n requestPoolManager.addRequest(\n element,\n imageId,\n requestType,\n preventCache,\n doneCallback,\n failCallback\n );\n }\n\n if (shouldLoadHigher) {\n nextImageIdIndex = stackPrefetch.indicesToRequest[higherIndex++];\n imageId = stack.imageIds[nextImageIdIndex];\n requestPoolManager.addRequest(\n element,\n imageId,\n requestType,\n preventCache,\n doneCallback,\n failCallback\n );\n }\n }\n\n // Try to start the requestPool's grabbing procedure\n // In case it isn't already running\n requestPoolManager.startGrabbing();\n}\n\nfunction getPromiseRemovedHandler(element) {\n return function(e) {\n const eventData = e.detail;\n\n // When an imagePromise has been pushed out of the cache, re-add its index\n // It to the indicesToRequest list so that it will be retrieved later if the\n // CurrentImageIdIndex is changed to an image nearby\n let stackData;\n\n try {\n // It will throw an exception in some cases (eg: thumbnails)\n stackData = getToolState(element, 'stack');\n } catch (error) {\n return;\n }\n\n if (!stackData || !stackData.data || !stackData.data.length) {\n return;\n }\n\n const stack = stackData.data[0];\n const imageIdIndex = stack.imageIds.indexOf(eventData.imageId);\n\n // Make sure the image that was removed is actually in this stack\n // Before adding it to the indicesToRequest array\n if (imageIdIndex < 0) {\n return;\n }\n\n const stackPrefetchData = getToolState(element, toolType);\n\n if (\n !stackPrefetchData ||\n !stackPrefetchData.data ||\n !stackPrefetchData.data.length\n ) {\n return;\n }\n\n stackPrefetchData.data[0].indicesToRequest.push(imageIdIndex);\n };\n}\n\nfunction onImageUpdated(e) {\n // Start prefetching again (after a delay)\n // When the user has scrolled to a new image\n clearTimeout(resetPrefetchTimeout);\n resetPrefetchTimeout = setTimeout(function() {\n const element = e.target;\n\n // If playClip is enabled and the user loads a different series in the viewport\n // An exception will be thrown because the element will not be enabled anymore\n try {\n prefetch(element);\n } catch (error) {\n return;\n }\n }, resetPrefetchDelay);\n}\n\nfunction enable(element) {\n // Clear old prefetch data. Skipping this can cause problems when changing the series inside an element\n const stackPrefetchDataArray = getToolState(element, toolType);\n\n stackPrefetchDataArray.data = [];\n\n // First check that there is stack data available\n const stackData = getToolState(element, 'stack');\n\n if (!stackData || !stackData.data || !stackData.data.length) {\n return;\n }\n\n const stack = stackData.data[0];\n\n // Check if we are allowed to cache images in this stack\n if (stack.preventCache === true) {\n console.warn(\n 'A stack that should not be cached was given the stackPrefetch'\n );\n\n return;\n }\n\n // Use the currentImageIdIndex from the stack as the initalImageIdIndex\n const stackPrefetchData = {\n indicesToRequest: range(0, stack.imageIds.length - 1),\n enabled: true,\n direction: 1,\n };\n\n // Remove the currentImageIdIndex from the list to request\n const indexOfCurrentImage = stackPrefetchData.indicesToRequest.indexOf(\n stack.currentImageIdIndex\n );\n\n stackPrefetchData.indicesToRequest.splice(indexOfCurrentImage, 1);\n\n addToolState(element, toolType, stackPrefetchData);\n\n prefetch(element);\n\n element.removeEventListener(\n external.cornerstone.EVENTS.NEW_IMAGE,\n onImageUpdated\n );\n element.addEventListener(\n external.cornerstone.EVENTS.NEW_IMAGE,\n onImageUpdated\n );\n\n const promiseRemovedHandler = getPromiseRemovedHandler(element);\n\n external.cornerstone.events.removeEventListener(\n external.cornerstone.EVENTS.IMAGE_CACHE_PROMISE_REMOVED,\n promiseRemovedHandler\n );\n external.cornerstone.events.addEventListener(\n external.cornerstone.EVENTS.IMAGE_CACHE_PROMISE_REMOVED,\n promiseRemovedHandler\n );\n}\n\nfunction disable(element) {\n clearTimeout(resetPrefetchTimeout);\n element.removeEventListener(\n external.cornerstone.EVENTS.NEW_IMAGE,\n onImageUpdated\n );\n\n const promiseRemovedHandler = getPromiseRemovedHandler(element);\n\n external.cornerstone.events.removeEventListener(\n external.cornerstone.EVENTS.IMAGE_CACHE_PROMISE_REMOVED,\n promiseRemovedHandler\n );\n\n const stackPrefetchData = getToolState(element, toolType);\n // If there is actually something to disable, disable it\n\n if (stackPrefetchData && stackPrefetchData.data.length) {\n stackPrefetchData.data[0].enabled = false;\n\n // Clear current prefetch requests from the requestPool\n requestPoolManager.clearRequestStack(requestType);\n }\n}\n\nfunction getConfiguration() {\n return configuration;\n}\n\nfunction setConfiguration(config) {\n configuration = config;\n\n if (config.maxSimultaneousRequests) {\n setMaxSimultaneousRequests(config.maxSimultaneousRequests);\n }\n}\n\n// Module/private exports\nconst stackPrefetch = {\n enable,\n disable,\n getConfiguration,\n setConfiguration,\n};\n\nexport default stackPrefetch;\n","import external from '../externalModules.js';\nimport { getToolState } from '../stateManagement/toolState.js';\n\nexport default class FusionRenderer {\n constructor() {\n this.currentImageIdIndex = 0;\n this.layerIds = [];\n this.findImageFn = undefined;\n }\n\n render(element, imageStacks) {\n // Move this to base Renderer class\n if (!Number.isInteger(this.currentImageIdIndex)) {\n throw new Error(\n 'FusionRenderer: render - Image ID Index is not an integer'\n );\n }\n\n if (!this.findImageFn) {\n throw new Error('No findImage function has been defined');\n }\n\n if (!imageStacks) {\n const toolData = getToolState(element, 'stack');\n\n imageStacks = toolData.data;\n }\n // TODO: Figure out what to do with LoadHandlers in this scenario...\n\n const cornerstone = external.cornerstone;\n\n // For the base layer, go to the currentImageIdIndex\n const baseImageObject = imageStacks[0];\n const currentImageId = baseImageObject.imageIds[this.currentImageIdIndex];\n const overlayImageStacks = imageStacks.slice(1, imageStacks.length);\n\n cornerstone.loadAndCacheImage(currentImageId).then(baseImage => {\n let baseLayerId = this.layerIds[0];\n\n // Get the base layer if one exists\n if (baseLayerId) {\n cornerstone.setLayerImage(element, baseImage, baseLayerId);\n } else {\n // Otherwise, create a new layer with the base layer's image\n baseLayerId = cornerstone.addLayer(\n element,\n baseImage,\n baseImageObject.options\n );\n this.layerIds.push(baseLayerId);\n }\n\n // Display the image immediately while the overlay images are identified\n cornerstone.displayImage(element, baseImage);\n\n // Loop through the remaining 'overlay' image stacks\n overlayImageStacks.forEach((imgObj, overlayLayerIndex) => {\n const imageId = this.findImageFn(imgObj.imageIds, currentImageId);\n const layerIndex = overlayLayerIndex + 1;\n let currentLayerId = this.layerIds[layerIndex];\n\n // If no layer exists yet for this overlaid stack, create\n // One and add it to the layerIds property for this instance\n // Of the fusion renderer.\n if (!currentLayerId) {\n currentLayerId = cornerstone.addLayer(\n element,\n undefined,\n imgObj.options\n );\n this.layerIds.push(currentLayerId);\n }\n\n if (imageId) {\n // If an imageId was returned from the findImage function,\n // Load it, make sure it's visible and update the layer\n // With the new image object.\n cornerstone.loadAndCacheImage(imageId).then(image => {\n cornerstone.setLayerImage(element, image, currentLayerId);\n cornerstone.updateImage(element);\n });\n } else {\n // If no imageId was returned from the findImage function.\n // This means that there is no relevant image to display.\n cornerstone.setLayerImage(element, undefined, currentLayerId);\n cornerstone.setActiveLayer(element, baseLayerId);\n cornerstone.updateImage(element);\n }\n });\n });\n }\n}\n","import FusionRenderer from './fusionRenderer.js';\n\nconst stackRenderers = {};\n\nstackRenderers.FusionRenderer = FusionRenderer;\n\nexport default stackRenderers;\n","/* eslint no-bitwise:0 */\nimport EVENTS from '../events.js';\nimport external from '../externalModules.js';\nimport loadHandlerManager from '../stateManagement/loadHandlerManager.js';\nimport { addToolState, getToolState } from '../stateManagement/toolState.js';\nimport triggerEvent from '../util/triggerEvent.js';\n\nconst toolType = 'playClip';\n\n/**\n * [private] Turns a Frame Time Vector (0018,1065) array into a normalized array of timeouts. Each element\n * ... of the resulting array represents the amount of time each frame will remain on the screen.\n * @param {Array} vector A Frame Time Vector (0018,1065) as specified in section C.7.6.5.1.2 of DICOM standard.\n * @param {Number} speed A speed factor which will be applied to each element of the resulting array.\n * @returns {Array} An array with timeouts for each animation frame.\n */\nfunction getPlayClipTimeouts(vector, speed) {\n let i;\n let sample;\n let delay;\n let sum = 0;\n const limit = vector.length;\n const timeouts = [];\n\n // Initialize time varying to false\n timeouts.isTimeVarying = false;\n\n if (typeof speed !== 'number' || speed <= 0) {\n speed = 1;\n }\n\n // First element of a frame time vector must be discarded\n for (i = 1; i < limit; i++) {\n delay = (Number(vector[i]) / speed) | 0; // Integral part only\n timeouts.push(delay);\n if (i === 1) {\n // Use first item as a sample for comparison\n sample = delay;\n } else if (delay !== sample) {\n timeouts.isTimeVarying = true;\n }\n\n sum += delay;\n }\n\n if (timeouts.length > 0) {\n if (timeouts.isTimeVarying) {\n // If it's a time varying vector, make the last item an average...\n delay = (sum / timeouts.length) | 0;\n } else {\n delay = timeouts[0];\n }\n\n timeouts.push(delay);\n }\n\n return timeouts;\n}\n\n/**\n * [private] Performs the heavy lifting of stopping an ongoing animation.\n * @param {Object} playClipData The data from playClip that needs to be stopped.\n */\nfunction stopClipWithData(playClipData) {\n const id = playClipData.intervalId;\n\n if (typeof id !== 'undefined') {\n playClipData.intervalId = undefined;\n if (playClipData.usingFrameTimeVector) {\n clearTimeout(id);\n } else {\n clearInterval(id);\n }\n }\n}\n\n/**\n * [private] Trigger playClip tool stop event.\n * @param element\n */\nfunction triggerStopEvent(element) {\n const eventDetail = {\n element,\n };\n\n triggerEvent(element, EVENTS.CLIP_STOPPED, eventDetail);\n}\n\n/**\n * Starts playing a clip or adjusts the frame rate of an already playing clip. framesPerSecond is\n * optional and defaults to 30 if not specified. A negative framesPerSecond will play the clip in reverse.\n * The element must be a stack of images\n * @param element\n * @param framesPerSecond\n */\nfunction playClip(element, framesPerSecond) {\n let playClipData;\n let playClipTimeouts;\n\n if (element === undefined) {\n throw new Error('playClip: element must not be undefined');\n }\n\n const stackToolData = getToolState(element, 'stack');\n\n if (!stackToolData || !stackToolData.data || !stackToolData.data.length) {\n return;\n }\n\n const cornerstone = external.cornerstone;\n // If we have more than one stack, check if we have a stack renderer defined\n let stackRenderer;\n\n if (stackToolData.data.length > 1) {\n const stackRendererData = getToolState(element, 'stackRenderer');\n\n if (\n stackRendererData &&\n stackRendererData.data &&\n stackRendererData.data.length\n ) {\n stackRenderer = stackRendererData.data[0];\n }\n }\n\n const stackData = stackToolData.data[0];\n\n const playClipToolData = getToolState(element, toolType);\n\n if (\n !playClipToolData ||\n !playClipToolData.data ||\n !playClipToolData.data.length\n ) {\n playClipData = {\n intervalId: undefined,\n framesPerSecond: 30,\n lastFrameTimeStamp: undefined,\n frameRate: 0,\n frameTimeVector: undefined,\n ignoreFrameTimeVector: false,\n usingFrameTimeVector: false,\n speed: 1,\n reverse: false,\n loop: true,\n };\n addToolState(element, toolType, playClipData);\n } else {\n playClipData = playClipToolData.data[0];\n // Make sure the specified clip is not running before any property update\n stopClipWithData(playClipData);\n }\n\n // If a framesPerSecond is specified and is valid, update the playClipData now\n if (framesPerSecond < 0 || framesPerSecond > 0) {\n playClipData.framesPerSecond = Number(framesPerSecond);\n playClipData.reverse = playClipData.framesPerSecond < 0;\n // If framesPerSecond is given, frameTimeVector will be ignored...\n playClipData.ignoreFrameTimeVector = true;\n }\n\n // Determine if frame time vector should be used instead of a fixed frame rate...\n if (\n playClipData.ignoreFrameTimeVector !== true &&\n playClipData.frameTimeVector &&\n playClipData.frameTimeVector.length === stackData.imageIds.length\n ) {\n playClipTimeouts = getPlayClipTimeouts(\n playClipData.frameTimeVector,\n playClipData.speed\n );\n }\n\n // This function encapsulates the frame rendering logic...\n const playClipAction = () => {\n // Hoisting of context variables\n let loader,\n startLoadingHandler,\n endLoadingHandler,\n errorLoadingHandler,\n newImageIdIndex = stackData.currentImageIdIndex;\n\n const imageCount = stackData.imageIds.length;\n\n if (playClipData.reverse) {\n newImageIdIndex--;\n } else {\n newImageIdIndex++;\n }\n\n if (\n !playClipData.loop &&\n (newImageIdIndex < 0 || newImageIdIndex >= imageCount)\n ) {\n stopClipWithData(playClipData);\n triggerStopEvent(element);\n\n return;\n }\n\n // Loop around if we go outside the stack\n if (newImageIdIndex >= imageCount) {\n newImageIdIndex = 0;\n }\n\n if (newImageIdIndex < 0) {\n newImageIdIndex = imageCount - 1;\n }\n\n if (newImageIdIndex !== stackData.currentImageIdIndex) {\n startLoadingHandler = loadHandlerManager.getStartLoadHandler();\n endLoadingHandler = loadHandlerManager.getEndLoadHandler();\n errorLoadingHandler = loadHandlerManager.getErrorLoadingHandler();\n\n if (startLoadingHandler) {\n startLoadingHandler(element);\n }\n\n if (stackData.preventCache === true) {\n loader = cornerstone.loadImage(stackData.imageIds[newImageIdIndex]);\n } else {\n loader = cornerstone.loadAndCacheImage(\n stackData.imageIds[newImageIdIndex]\n );\n }\n\n loader.then(\n function(image) {\n try {\n stackData.currentImageIdIndex = newImageIdIndex;\n if (stackRenderer) {\n stackRenderer.currentImageIdIndex = newImageIdIndex;\n stackRenderer.render(element, stackToolData.data);\n } else {\n cornerstone.displayImage(element, image);\n }\n if (endLoadingHandler) {\n endLoadingHandler(element, image);\n }\n } catch (error) {\n return;\n }\n },\n function(error) {\n const imageId = stackData.imageIds[newImageIdIndex];\n\n if (errorLoadingHandler) {\n errorLoadingHandler(element, imageId, error);\n }\n }\n );\n }\n };\n\n // If playClipTimeouts array is available, not empty and its elements are NOT uniform ...\n // ... (at least one timeout is different from the others), use alternate setTimeout implementation\n if (\n playClipTimeouts &&\n playClipTimeouts.length > 0 &&\n playClipTimeouts.isTimeVarying\n ) {\n playClipData.usingFrameTimeVector = true;\n playClipData.intervalId = setTimeout(function playClipTimeoutHandler() {\n playClipData.intervalId = setTimeout(\n playClipTimeoutHandler,\n playClipTimeouts[stackData.currentImageIdIndex]\n );\n playClipAction();\n }, 0);\n } else {\n // ... otherwise user setInterval implementation which is much more efficient.\n playClipData.usingFrameTimeVector = false;\n playClipData.intervalId = setInterval(\n playClipAction,\n 1000 / Math.abs(playClipData.framesPerSecond)\n );\n }\n}\n\n/**\n * Stops an already playing clip.\n * * @param element\n */\nfunction stopClip(element) {\n const playClipToolData = getToolState(element, toolType);\n\n if (\n !playClipToolData ||\n !playClipToolData.data ||\n !playClipToolData.data.length\n ) {\n return;\n }\n\n stopClipWithData(playClipToolData.data[0]);\n}\n\nexport { playClip, stopClip };\n","import store from './index.js';\n\n/**\n * Deactivates and removes the tool from the target element with the provided name\n *\n * @export\n * @public\n * @method\n * @name removeToolForElement\n * @param {HTMLElement} element The element.\n * @param {string} toolName The name of the tool.\n */\nconst removeToolForElement = function(element, toolName) {\n const toolIndex = store.state.tools.findIndex(\n tool => tool.element === element && tool.name === toolName\n );\n\n if (toolIndex >= 0) {\n store.state.tools.splice(toolIndex, 1);\n }\n};\n\n/**\n * Removes all tools from all enabled elements with the provided name.\n *\n * @export\n * @public\n * @method\n * @name removeTool\n * @param {string} toolName The name of the tool.\n */\nconst removeTool = function(toolName) {\n _removeToolGlobally(toolName);\n store.state.enabledElements.forEach(element => {\n removeToolForElement(element, toolName);\n });\n};\n\n/**\n * Removes tool with matching name from globally registered tools.\n * Requires `globalToolSyncEnabled` to be set to true\n *\n * @private\n * @method\n * @name removeToolGlobally\n * @param {string} toolName The name of the tool to remove.\n */\nconst _removeToolGlobally = function(toolName) {\n if (!store.modules.globalConfiguration.state.globalToolSyncEnabled) {\n return;\n }\n\n if (store.state.globalTools[toolName]) {\n delete store.state.globalTools[toolName];\n }\n};\n\nexport { removeTool, removeToolForElement };\n","import { state } from './index.js';\nimport getToolForElement from './getToolForElement.js';\n\n/**\n * Sets the options of a tool on a specific element.\n * @export\n * @public\n * @method\n * @name setToolOptionsForElement\n *\n * @param {HTMLElement} element The element.\n * @param {string} toolName The name of the tool.\n * @param {Object} options The options to set.\n */\nconst setToolOptionsForElement = function(element, toolName, options) {\n const tool = getToolForElement(element, toolName);\n\n if (tool) {\n tool.mergeOptions(options);\n }\n};\n\n/**\n * Sets the options of a tool for all elements.\n * @export\n * @public\n * @method\n * @name setToolOptions\n *\n * @param {string} toolName\n * @param {Object} options\n */\nconst setToolOptions = function(toolName, options) {\n state.enabledElements.forEach(element => {\n setToolOptionsForElement(element, options);\n });\n};\n\nexport { setToolOptions, setToolOptionsForElement };\n","import { globalImageIdSpecificToolStateManager } from './imageIdSpecificStateManager.js';\nimport {\n getElementToolStateManager,\n setElementToolStateManager,\n} from './toolState.js';\n\n/**\n * Implements an Stack specific tool state management strategy. This means\n * That tool data is shared between all imageIds in a given stack.\n * @public\n * @constructor newStackSpecificToolStateManager\n * @memberof StateManagement\n *\n * @param {string[]} toolTypes The tool types to apply to the stack.\n * @param {Object} oldStateManager The imageIdSpecificStateManager.\n * @returns {Object} A stackSpecificToolStateManager instance.\n */\nfunction newStackSpecificToolStateManager(toolTypes, oldStateManager) {\n let toolState = {};\n\n function saveToolState() {\n return toolState;\n }\n\n function restoreToolState(stackToolState) {\n toolState = stackToolState;\n }\n\n // Here we add tool state, this is done by tools as well\n // As modules that restore saved state\n function addStackSpecificToolState(element, toolType, data) {\n // If this is a tool type to apply to the stack, do so\n if (toolTypes.indexOf(toolType) >= 0) {\n // If we don't have tool state for this type of tool, add an empty object\n if (toolState.hasOwnProperty(toolType) === false) {\n toolState[toolType] = {\n data: [],\n };\n }\n\n const toolData = toolState[toolType];\n\n // Finally, add this new tool to the state\n toolData.data.push(data);\n } else {\n // Call the imageId specific tool state manager\n return oldStateManager.add(element, toolType, data);\n }\n }\n\n // Here you can get state - used by tools as well as modules\n // That save state persistently\n function getStackSpecificToolState(element, toolType) {\n // If this is a tool type to apply to the stack, do so\n if (toolTypes.indexOf(toolType) >= 0) {\n // If we don't have tool state for this type of tool, add an empty object\n if (toolState.hasOwnProperty(toolType) === false) {\n toolState[toolType] = {\n data: [],\n };\n }\n\n return toolState[toolType];\n }\n\n // Call the imageId specific tool state manager\n return oldStateManager.get(element, toolType);\n }\n\n const stackSpecificToolStateManager = {\n get: getStackSpecificToolState,\n add: addStackSpecificToolState,\n saveToolState,\n restoreToolState,\n toolState,\n };\n\n return stackSpecificToolStateManager;\n}\n\nconst stackStateManagers = [];\n\nfunction addStackStateManager(element, otherTools) {\n let oldStateManager = getElementToolStateManager(element);\n\n if (!oldStateManager) {\n oldStateManager = globalImageIdSpecificToolStateManager;\n }\n\n let stackTools = [\n 'stack',\n 'stackPrefetch',\n 'playClip',\n 'volume',\n 'slab',\n 'referenceLines',\n 'crosshairs',\n 'stackRenderer',\n ];\n\n if (otherTools) {\n stackTools = stackTools.concat(otherTools);\n }\n\n const stackSpecificStateManager = newStackSpecificToolStateManager(\n stackTools,\n oldStateManager\n );\n\n stackStateManagers.push(stackSpecificStateManager);\n setElementToolStateManager(element, stackSpecificStateManager);\n}\n\nconst stackSpecificStateManager = {\n newStackSpecificToolStateManager,\n addStackStateManager,\n};\n\nexport {\n stackSpecificStateManager,\n newStackSpecificToolStateManager,\n addStackStateManager,\n};\n","/**\n * Implements a frame-of-reference specific tool state management strategy. This means that\n * Measurement data are tied to a specific frame of reference UID and only visible to objects using\n * That frame-of-reference UID.\n * @public\n * @constructor newFrameOfReferenceSpecificToolStateManager\n * @memberof StateManagement\n *\n * @returns {Object} A frameOfReferenceSpecificToolStateManager instance.\n */\nfunction newFrameOfReferenceSpecificToolStateManager() {\n const toolState = {};\n\n // Here we add tool state, this is done by tools as well\n // As modules that restore saved state\n function addFrameOfReferenceSpecificToolState(\n frameOfReference,\n toolType,\n data\n ) {\n // If we don't have any tool state for this frameOfReference, add an empty object\n if (toolState.hasOwnProperty(frameOfReference) === false) {\n toolState[frameOfReference] = {};\n }\n\n const frameOfReferenceToolState = toolState[frameOfReference];\n\n // If we don't have tool state for this type of tool, add an empty object\n if (frameOfReferenceToolState.hasOwnProperty(toolType) === false) {\n frameOfReferenceToolState[toolType] = {\n data: [],\n };\n }\n\n const toolData = frameOfReferenceToolState[toolType];\n\n // Finally, add this new tool to the state\n toolData.data.push(data);\n }\n\n // Here you can get state - used by tools as well as modules\n // That save state persistently\n function getFrameOfReferenceSpecificToolState(frameOfReference, toolType) {\n // If we don't have any tool state for this frame of reference, return undefined\n if (toolState.hasOwnProperty(frameOfReference) === false) {\n return;\n }\n\n const frameOfReferenceToolState = toolState[frameOfReference];\n\n // If we don't have tool state for this type of tool, return undefined\n if (frameOfReferenceToolState.hasOwnProperty(toolType) === false) {\n return;\n }\n\n const toolData = frameOfReferenceToolState[toolType];\n\n return toolData;\n }\n\n function removeFrameOfReferenceSpecificToolState(\n frameOfReference,\n toolType,\n data\n ) {\n // If we don't have any tool state for this frame of reference, return undefined\n if (toolState.hasOwnProperty(frameOfReference) === false) {\n return;\n }\n\n const frameOfReferenceToolState = toolState[frameOfReference];\n\n // If we don't have tool state for this type of tool, return undefined\n if (frameOfReferenceToolState.hasOwnProperty(toolType) === false) {\n return;\n }\n\n const toolData = frameOfReferenceToolState[toolType];\n // Find this tool data\n let indexOfData = -1;\n\n for (let i = 0; i < toolData.data.length; i++) {\n if (toolData.data[i] === data) {\n indexOfData = i;\n }\n }\n\n if (indexOfData !== -1) {\n toolData.data.splice(indexOfData, 1);\n }\n }\n\n return {\n get: getFrameOfReferenceSpecificToolState,\n add: addFrameOfReferenceSpecificToolState,\n remove: removeFrameOfReferenceSpecificToolState,\n };\n}\n\n// A global frameOfReferenceSpecificToolStateManager - the most common case is to share 3d information\n// Between stacks of images\nconst globalFrameOfReferenceSpecificToolStateManager = newFrameOfReferenceSpecificToolStateManager();\n\nexport {\n newFrameOfReferenceSpecificToolStateManager,\n globalFrameOfReferenceSpecificToolStateManager,\n};\n","import getOrientationString from './getOrientationString.js';\nimport invertOrientationString from './invertOrientationString.js';\n\nconst orientation = {\n getOrientationString,\n invertOrientationString,\n};\n\nexport default orientation;\n","import external from '../externalModules.js';\nimport convertToVector3 from '../util/convertToVector3.js';\n\n/**\n * Returns the orientation of the vector in the patient coordinate system.\n * @public\n * @function getOrientationString\n *\n * @param {Array|cornerstoneMath.Vector3} vector Input array or Vector3\n * @returns {string} The orientation in the patient coordinate system.\n */\nexport default function(vector) {\n const vec3 = convertToVector3(vector);\n\n // Thanks to David Clunie\n // https://sites.google.com/site/dicomnotes/\n\n let orientation = '';\n const orientationX = vec3.x < 0 ? 'R' : 'L';\n const orientationY = vec3.y < 0 ? 'A' : 'P';\n const orientationZ = vec3.z < 0 ? 'F' : 'H';\n\n // Should probably make this a function vector3.abs\n const abs = new external.cornerstoneMath.Vector3(\n Math.abs(vec3.x),\n Math.abs(vec3.y),\n Math.abs(vec3.z)\n );\n\n for (let i = 0; i < 3; i++) {\n if (abs.x > 0.0001 && abs.x > abs.y && abs.x > abs.z) {\n orientation += orientationX;\n abs.x = 0;\n } else if (abs.y > 0.0001 && abs.y > abs.x && abs.y > abs.z) {\n orientation += orientationY;\n abs.y = 0;\n } else if (abs.z > 0.0001 && abs.z > abs.x && abs.z > abs.y) {\n orientation += orientationZ;\n abs.z = 0;\n } else {\n break;\n }\n }\n\n return orientation;\n}\n","/**\n * Inverts an orientation string.\n * @public\n * @function invertOrientationString\n *\n * @param {string} orientationString The orientation.\n * @returns {string} The inverted orientationString.\n */\nexport default function(orientationString) {\n let inverted = orientationString.replace('H', 'f');\n\n inverted = inverted.replace('F', 'h');\n inverted = inverted.replace('R', 'l');\n inverted = inverted.replace('L', 'r');\n inverted = inverted.replace('A', 'p');\n inverted = inverted.replace('P', 'a');\n inverted = inverted.toUpperCase();\n\n return inverted;\n}\n","/**\n * Exports an image of the canvas.\n * @export @public @method\n * @name saveAs\n *\n * @param {HTMLElement} element The element to export.\n * @param {string} filename The name of the exported image.\n * @param {string} [mimetype = 'image/png'] The mimetype of the exported image.\n */\nexport default (element, filename, mimetype = 'image/png') => {\n const canvas = element.querySelector('canvas');\n\n // If we are using IE, use canvas.msToBlob\n if (canvas.msToBlob) {\n const blob = canvas.msToBlob();\n\n return window.navigator.msSaveBlob(blob, filename);\n }\n\n // Thanks to Ken Fyrstenber\n // http://stackoverflow.com/questions/18480474/how-to-save-an-image-from-canvas\n const lnk = document.createElement('a');\n\n // The key here is to set the download attribute of the a tag\n lnk.download = filename;\n\n // Convert canvas content to data-uri for link. When download\n // Attribute is set the content pointed to by link will be\n // Pushed as 'download' in HTML5 capable browsers\n lnk.href = canvas.toDataURL(mimetype, 1);\n\n // Create a 'fake' click-event to trigger the download\n if (document.createEvent) {\n const e = document.createEvent('MouseEvents');\n\n e.initMouseEvent(\n 'click',\n true,\n true,\n window,\n 0,\n 0,\n 0,\n 0,\n 0,\n false,\n false,\n false,\n false,\n 0,\n null\n );\n\n lnk.dispatchEvent(e);\n } else if (lnk.fireEvent) {\n lnk.fireEvent('onclick');\n }\n};\n","import { state, modules } from '../store/index.js';\n\n/**\n * Register a module.\n * @export\n * @private\n * @method\n * @name registerModule\n *\n * @param {string} name The name of the module.\n * @param {Object} newModule The module to register.\n * @param {boolean} [overwrite] Whether a module should be overwritten,\n * should it have the same name.\n */\nexport default function(name, newModule, overwrite = false) {\n if (isModuleNameRegistered(name)) {\n console.warn(`A module with the name ${name} is already registered`);\n\n if (overwrite) {\n console.warn(`Overwriting module ${name}`);\n } else {\n return;\n }\n }\n\n modules[name] = newModule;\n}\n\nfunction isModuleNameRegistered(name) {\n return Object.keys(modules).some(key => key === name);\n}\n","import { lib } from '../lib.js';\nimport mixins from '../mixins/index.js';\n\n/**\n * Register an mixin to cornerstoneTools.\n * @export\n * @private\n * @method\n * @name registerMixin\n *\n * @param {string} name The name of the mixin.\n * @param {Object} mixin The mixin itself.\n * @param {boolean} [overwrite=false] Whether an mixin should be overwritten,\n * should it have the same name.\n */\nexport default function(name, mixin, overwrite = false) {\n if (isMixinRegistered(name)) {\n console.warn(`mixins/${name} is already registered`);\n\n if (overwrite) {\n console.warn(`Overwriting mixins/${name}`);\n } else {\n return;\n }\n }\n\n // Register to the mixins object\n mixins[name] = mixin;\n\n // Reference the mixin from the library so it can be exported externally.\n lib[`mixins/${name}`] = mixins[name];\n}\n\nfunction isMixinRegistered(name) {\n return mixins[name] !== undefined;\n}\n","import { lib } from '../lib.js';\n\n/**\n * Register an item to cornerstoneTools.\n * @export\n * @private\n * @method\n * @name registerItem\n *\n * @param {string} type The type of the item.\n * @param {string} name The name of the item.\n * @param {Object|function} item The item itself.\n * @param {boolean} [overwrite=false] Whether an item should be overwritten,\n * should it have the same name.\n */\nexport default function(type, name, item, overwrite = false) {\n if (isItemNameRegistered(type, name)) {\n console.warn(`${type}/${name} is already registered`);\n\n if (overwrite) {\n console.warn(`Overwriting ${type}/${name}`);\n } else {\n return;\n }\n }\n\n lib[`${type}/${name}`] = item;\n}\n\nfunction isItemNameRegistered(type, name) {\n return lib[`${type}/${name}`] !== undefined;\n}\n","import registerModule from './registerModule.js';\nimport registerMixin from './registerMixin.js';\nimport registerItem from './registerItem.js';\n\n/**\n * Register an item or module to cornerstoneTools.\n * @export\n * @public\n * @method\n * @name register\n *\n * @param {string} type The type of the item/module.\n * @param {string} name The name of the item/module.\n * @param {Object|function} item The item/module itself.\n * @param {boolean} [overwrite=false] Whether an item/module should be\n * overwritten, should it have the same name.\n */\nexport default function(type, name, item, overwrite = false) {\n if (!isValidInput(type, name, item)) {\n return;\n }\n\n switch (type) {\n case 'module':\n registerModule(name, item, overwrite);\n break;\n case 'mixin':\n registerMixin(name, item, overwrite);\n break;\n default:\n registerItem(type, name, item, overwrite);\n console.warn(`unrecognised type ${type}, not registering ${name}`);\n }\n}\n\n/**\n * Returns true if the item is valid, this avoids\n * clogging up the library with invalid data.\n * @private\n * @method\n * @name isValidInput\n *\n * @param {string} type The type of the item/module.\n * @param {string} name The name of the item/module.\n * @param {Object|function} item The item/module itself.\n * @returns {boolean} Whether the input is valid.\n */\nfunction isValidInput(type, name, item) {\n if (!type) {\n console.warn('The type must be given in order to register.');\n\n return false;\n }\n\n if (!name) {\n console.warn(`The ${type} must have a name in order to register.`);\n\n return false;\n }\n\n if (typeof item !== 'object' && typeof item !== 'function') {\n console.warn(\n `The ${item} is a ${typeof item}, it should be an Object or a function.`\n );\n\n return false;\n }\n\n return true;\n}\n","import register from './register.js';\n\n/**\n * Register an array of items and/or modules to cornerstoneTools.\n * @export\n * @public\n * @method\n * @name registerSome\n *\n * @param {Object[]} items An array of items/modules to register.\n * @param {boolean} [overwrite=false] Whether an item/module should be\n * overwritten, should it have the same name.\n */\nexport default function(items, overwrite = false) {\n for (let i = 0; i < items.length; i++) {\n const { type, name, item } = items[i];\n\n register(type, name, item, overwrite);\n }\n}\n","import external from '../externalModules.js';\n\n/**\n * Synchronize the target viewport ww/wc to match the source element.\n * @export\n * @public\n * @method\n * @name wwwcSynchronizer\n *\n * @param {Object} synchronizer - The Synchronizer instance that attaches this\n * handler to an event\n * @param {HTMLElement} sourceElement - The source element for the ww/wc values\n * @param {HTMLElement} targetElement - The target element\n */\nexport default function(synchronizer, sourceElement, targetElement) {\n // Ignore the case where the source and target are the same enabled element\n if (targetElement === sourceElement) {\n return;\n }\n\n const cornerstone = external.cornerstone;\n // Get the source and target viewports\n const sourceViewport = cornerstone.getViewport(sourceElement);\n const targetViewport = cornerstone.getViewport(targetElement);\n\n // Do nothing if the ww/wc already match\n if (\n targetViewport.voi.windowWidth === sourceViewport.voi.windowWidth &&\n targetViewport.voi.windowCenter === sourceViewport.voi.windowCenter &&\n targetViewport.invert === sourceViewport.invert\n ) {\n return;\n }\n\n // Www/wc are different, sync them\n targetViewport.voi.windowWidth = sourceViewport.voi.windowWidth;\n targetViewport.voi.windowCenter = sourceViewport.voi.windowCenter;\n targetViewport.invert = sourceViewport.invert;\n synchronizer.setViewport(targetElement, targetViewport);\n}\n","import external from '../externalModules.js';\n\n/**\n * Redraw target image immediately any time handler is called from source element.\n * @export\n * @public\n * @method\n * @name updateImageSynchronizer\n *\n * @param {Object} synchronizer - The Synchronizer instance that attaches this\n * handler to an event\n * @param {HTMLElement} sourceElement - The source element\n * @param {HTMLElement} targetElement - The target element\n */\nexport default function(synchronizer, sourceElement, targetElement) {\n // Ignore the case where the source and target are the same enabled element\n if (targetElement === sourceElement) {\n return;\n }\n\n external.cornerstone.updateImage(targetElement);\n}\n","import external from '../externalModules.js';\nimport convertToVector3 from '../util/convertToVector3.js';\nimport { clearToolOptionsByElement } from '../toolOptions.js';\n\n/**\n * Return an array filtered to only its unique members\n *\n * @private\n * @param {Array} array - The array to filter\n * @returns {Array}\n */\nfunction unique(array) {\n return array.filter(function(value, index, self) {\n return self.indexOf(value) === index;\n });\n}\n\n/**\n * Synchronize target and source elements when an event fires on the source element\n * @export @public constructor\n * @name Synchronizer\n *\n * @param {String} event - The event(s) that will trigger synchronization. Separate multiple events by a space\n * @param {Function} handler - The function that will make the necessary changes to the target element in order to synchronize it with the source element\n */\nfunction Synchronizer(event, handler) {\n const cornerstone = external.cornerstone;\n const that = this;\n const sourceElements = []; // Source elements fire the events we want to synchronize to\n const targetElements = []; // Target elements we want to synchronize to source elements\n\n let ignoreFiredEvents = false;\n const initialData = {};\n let eventHandler = handler;\n\n this.enabled = true;\n\n /**\n * Update the event handler to perform synchronization\n * @param {Function} handler - The event handler function\n */\n this.setHandler = function(handler) {\n eventHandler = handler;\n };\n\n /**\n * Return a reference to the event handler function\n */\n this.getHandler = function() {\n return eventHandler;\n };\n\n /**\n * Calculate the initial distances between the source image and each\n * of the target images\n */\n this.getDistances = function() {\n if (!sourceElements.length || !targetElements.length) {\n return;\n }\n\n initialData.distances = {};\n initialData.imageIds = {\n sourceElements: [],\n targetElements: [],\n };\n\n sourceElements.forEach(function(sourceElement) {\n const sourceEnabledElement = cornerstone.getEnabledElement(sourceElement);\n\n if (!sourceEnabledElement || !sourceEnabledElement.image) {\n return;\n }\n\n const sourceImageId = sourceEnabledElement.image.imageId;\n const sourceImagePlane = cornerstone.metaData.get(\n 'imagePlaneModule',\n sourceImageId\n );\n\n if (!sourceImagePlane || !sourceImagePlane.imagePositionPatient) {\n return;\n }\n\n const sourceImagePosition = convertToVector3(\n sourceImagePlane.imagePositionPatient\n );\n\n if (initialData.hasOwnProperty(sourceEnabledElement)) {\n return;\n }\n initialData.distances[sourceImageId] = {};\n\n initialData.imageIds.sourceElements.push(sourceImageId);\n\n targetElements.forEach(function(targetElement) {\n const targetEnabledElement = cornerstone.getEnabledElement(\n targetElement\n );\n\n if (!targetEnabledElement || !targetEnabledElement.image) {\n return;\n }\n\n const targetImageId = targetEnabledElement.image.imageId;\n\n initialData.imageIds.targetElements.push(targetImageId);\n\n if (sourceElement === targetElement) {\n return;\n }\n\n if (sourceImageId === targetImageId) {\n return;\n }\n\n if (\n initialData.distances[sourceImageId].hasOwnProperty(targetImageId)\n ) {\n return;\n }\n\n const targetImagePlane = cornerstone.metaData.get(\n 'imagePlaneModule',\n targetImageId\n );\n\n if (!targetImagePlane || !targetImagePlane.imagePositionPatient) {\n return;\n }\n\n const targetImagePosition = convertToVector3(\n targetImagePlane.imagePositionPatient\n );\n\n initialData.distances[sourceImageId][\n targetImageId\n ] = targetImagePosition.clone().sub(sourceImagePosition);\n });\n\n if (!Object.keys(initialData.distances[sourceImageId]).length) {\n delete initialData.distances[sourceImageId];\n }\n });\n };\n\n /**\n * Gather necessary event data and call synchronization handler\n *\n * @private\n * @param {HTMLElement} sourceElement - The source element for the event\n * @param {Object} eventData - The data object for the source event\n */\n function fireEvent(sourceElement, eventData) {\n const isDisabled = !that.enabled;\n const noElements = !sourceElements.length || !targetElements.length;\n\n if (isDisabled || noElements) {\n return;\n }\n\n ignoreFiredEvents = true;\n targetElements.forEach(function(targetElement) {\n const targetIndex = targetElements.indexOf(targetElement);\n\n if (targetIndex === -1) {\n return;\n }\n\n const targetImageId = initialData.imageIds.targetElements[targetIndex];\n const sourceIndex = sourceElements.indexOf(sourceElement);\n\n if (sourceIndex === -1) {\n return;\n }\n\n const sourceImageId = initialData.imageIds.sourceElements[sourceIndex];\n\n let positionDifference;\n\n if (sourceImageId === targetImageId) {\n positionDifference = 0;\n } else if (initialData.distances[sourceImageId] !== undefined) {\n positionDifference =\n initialData.distances[sourceImageId][targetImageId];\n }\n\n eventHandler(\n that,\n sourceElement,\n targetElement,\n eventData,\n positionDifference\n );\n });\n ignoreFiredEvents = false;\n }\n\n /**\n * Call fireEvent if not ignoring events, and pass along event data\n *\n * @private\n * @param {Event} e - The source event object\n */\n function onEvent(e) {\n const eventData = e.detail;\n\n if (ignoreFiredEvents === true) {\n return;\n }\n\n fireEvent(e.currentTarget, eventData);\n }\n\n /**\n * Add a source element to this synchronizer\n *\n * @param {HTMLElement} element - The new source element\n */\n this.addSource = function(element) {\n // Return if this element was previously added\n const index = sourceElements.indexOf(element);\n\n if (index !== -1) {\n return;\n }\n\n // Add to our list of enabled elements\n sourceElements.push(element);\n\n // Subscribe to the event\n event.split(' ').forEach(oneEvent => {\n element.addEventListener(oneEvent, onEvent);\n });\n\n // Update the initial distances between elements\n that.getDistances();\n\n that.updateDisableHandlers();\n };\n\n /**\n * Add a target element to this synchronizer\n *\n * @param {HTMLElement} element - The new target element to be synchronized\n */\n this.addTarget = function(element) {\n // Return if this element was previously added\n const index = targetElements.indexOf(element);\n\n if (index !== -1) {\n return;\n }\n\n // Add to our list of enabled elements\n targetElements.push(element);\n\n // Update the initial distances between elements\n that.getDistances();\n\n // Invoke the handler for this new target element\n eventHandler(that, element, element, 0);\n\n that.updateDisableHandlers();\n };\n\n /**\n * Add an element to this synchronizer as both a source and a target\n *\n * @param {HTMLElement} element - The new element\n */\n this.add = function(element) {\n that.addSource(element);\n that.addTarget(element);\n };\n\n /**\n * Remove a source element from this synchronizer\n *\n * @param {HTMLElement} element - The element to be removed\n */\n this.removeSource = function(element) {\n // Find the index of this element\n const index = sourceElements.indexOf(element);\n\n if (index === -1) {\n return;\n }\n\n // Remove this element from the array\n sourceElements.splice(index, 1);\n\n // Stop listening for the event\n event.split(' ').forEach(oneEvent => {\n element.removeEventListener(oneEvent, onEvent);\n });\n\n // Update the initial distances between elements\n that.getDistances();\n\n // Update everyone listening for events\n fireEvent(element);\n that.updateDisableHandlers();\n };\n\n /**\n * Remove a target element from this synchronizer\n *\n * @param {HTMLElement} element - The element to be removed\n */\n this.removeTarget = function(element) {\n // Find the index of this element\n const index = targetElements.indexOf(element);\n\n if (index === -1) {\n return;\n }\n\n // Remove this element from the array\n targetElements.splice(index, 1);\n\n // Update the initial distances between elements\n that.getDistances();\n\n // Invoke the handler for the removed target\n eventHandler(that, element, element, 0);\n that.updateDisableHandlers();\n };\n\n /**\n * Remove an element from this synchronizer as both a target and source\n *\n * @param {HTMLElement} element - The element to be removed\n */\n this.remove = function(element) {\n that.removeTarget(element);\n that.removeSource(element);\n };\n\n /**\n * Get the array of source elements\n *\n * @returns {HTMLElement[]}\n */\n this.getSourceElements = function() {\n return sourceElements;\n };\n\n /**\n * Get the array of target elements\n *\n * @returns {HTMLElement[]}\n */\n this.getTargetElements = function() {\n return targetElements;\n };\n\n /**\n * Display an image while halting synchronization\n *\n * @param {HTMLElement} element - The element containing the image\n * @param {Object} image - The cornerstone image object\n * @param {Object} viewport - The cornerstone viewport object\n */\n this.displayImage = function(element, image, viewport) {\n ignoreFiredEvents = true;\n cornerstone.displayImage(element, image, viewport);\n ignoreFiredEvents = false;\n };\n\n /**\n * Update a viewport while halting synchronization\n *\n * @param {HTMLElement} element - The target element\n * @param {Object} viewport - The new cornerstone viewport object\n */\n this.setViewport = function(element, viewport) {\n ignoreFiredEvents = true;\n cornerstone.setViewport(element, viewport);\n ignoreFiredEvents = false;\n };\n\n /**\n * Remove an element from the synchronizer based on an event from that element\n *\n * @private\n * @param {Event} e - The event whose element will be removed\n */\n function disableHandler(e) {\n const element = e.detail.element;\n\n that.remove(element);\n clearToolOptionsByElement(element);\n }\n\n /**\n * Add an event listener to each element that can remove it from the synchronizer\n *\n */\n this.updateDisableHandlers = function() {\n const elements = unique(sourceElements.concat(targetElements));\n\n elements.forEach(function(element) {\n element.removeEventListener(\n external.cornerstone.EVENTS.ELEMENT_DISABLED,\n disableHandler\n );\n element.addEventListener(\n external.cornerstone.EVENTS.ELEMENT_DISABLED,\n disableHandler\n );\n });\n };\n\n /**\n * Remove all elements from this synchronizer\n *\n */\n this.destroy = function() {\n const elements = unique(sourceElements.concat(targetElements));\n\n elements.forEach(function(element) {\n that.remove(element);\n });\n };\n}\n\nexport default Synchronizer;\n","import external from '../externalModules.js';\nimport { getToolState } from '../stateManagement/toolState.js';\nimport loadHandlerManager from '../stateManagement/loadHandlerManager.js';\nimport clip from '../util/clip.js';\n\n/**\n * Propogate scrolling actions from the source element to the target element.\n * @export\n * @public\n * @method\n * @name stackScrollSynchronizer\n *\n * @param {Object} synchronizer - The Synchronizer instance that attaches this\n * handler to an event\n * @param {HTMLElement} sourceElement - The source element for the scroll event\n * @param {HTMLElement} targetElement - The target element\n * @param {Object} eventData - The data object from the triggering event\n */\nexport default function(synchronizer, sourceElement, targetElement, eventData) {\n // If the target and source are the same, stop\n if (sourceElement === targetElement) {\n return;\n }\n\n // If there is no event, or direction is 0, stop\n if (!eventData || !eventData.direction) {\n return;\n }\n\n const cornerstone = external.cornerstone;\n // Get the stack of the target viewport\n const stackToolDataSource = getToolState(targetElement, 'stack');\n const stackData = stackToolDataSource.data[0];\n\n // Get the new index for the stack\n let newImageIdIndex = stackData.currentImageIdIndex + eventData.direction;\n\n // Ensure the index does not exceed the bounds of the stack\n newImageIdIndex = clip(newImageIdIndex, 0, stackData.imageIds.length - 1);\n\n // If the index has not changed, stop here\n if (stackData.currentImageIdIndex === newImageIdIndex) {\n return;\n }\n\n const startLoadingHandler = loadHandlerManager.getStartLoadHandler();\n const endLoadingHandler = loadHandlerManager.getEndLoadHandler();\n const errorLoadingHandler = loadHandlerManager.getErrorLoadingHandler();\n\n stackData.currentImageIdIndex = newImageIdIndex;\n const newImageId = stackData.imageIds[newImageIdIndex];\n\n if (startLoadingHandler) {\n startLoadingHandler(targetElement);\n }\n\n let loader;\n\n if (stackData.preventCache === true) {\n loader = cornerstone.loadImage(newImageId);\n } else {\n loader = cornerstone.loadAndCacheImage(newImageId);\n }\n\n loader.then(\n function(image) {\n const viewport = cornerstone.getViewport(targetElement);\n\n if (stackData.currentImageIdIndex !== newImageIdIndex) {\n return;\n }\n\n synchronizer.displayImage(targetElement, image, viewport);\n if (endLoadingHandler) {\n endLoadingHandler(targetElement, image);\n }\n },\n function(error) {\n const imageId = stackData.imageIds[newImageIdIndex];\n\n if (errorLoadingHandler) {\n errorLoadingHandler(targetElement, imageId, error);\n }\n }\n );\n}\n","import external from '../externalModules.js';\nimport { getToolState } from '../stateManagement/toolState.js';\nimport loadHandlerManager from '../stateManagement/loadHandlerManager.js';\nimport convertToVector3 from '../util/convertToVector3.js';\n\n/**\n * Synchronize the target stack to the image closest to the source image's position\n * @export\n * @public\n * @method\n * @name stackImagePositionSynchronizer\n *\n * @param {Object} synchronizer - The Synchronizer instance that attaches this\n * handler to an event\n * @param {HTMLElement} sourceElement - The source element for the image position\n * @param {HTMLElement} targetElement - The target element\n */\nexport default function(synchronizer, sourceElement, targetElement) {\n // Ignore the case where the source and target are the same enabled element\n if (targetElement === sourceElement) {\n return;\n }\n\n const cornerstone = external.cornerstone;\n const sourceStackData = getToolState(sourceElement, 'stack').data[0];\n const sourceImageId =\n sourceStackData.imageIds[sourceStackData.currentImageIdIndex];\n const sourceImagePlane = cornerstone.metaData.get(\n 'imagePlaneModule',\n sourceImageId\n );\n\n if (\n sourceImagePlane === undefined ||\n sourceImagePlane.imagePositionPatient === undefined\n ) {\n // Console.log('No position found for image ' + sourceImage.imageId);\n\n return;\n }\n\n const sourceImagePosition = convertToVector3(\n sourceImagePlane.imagePositionPatient\n );\n const stackToolDataSource = getToolState(targetElement, 'stack');\n const stackData = stackToolDataSource.data[0];\n\n let minDistance = Number.MAX_VALUE;\n let newImageIdIndex = -1;\n\n stackData.imageIds.forEach((imageId, index) => {\n const imagePlane = cornerstone.metaData.get('imagePlaneModule', imageId);\n\n if (\n imagePlane === undefined ||\n imagePlane.imagePositionPatient === undefined\n ) {\n // Console.log('No position found for image ' + imageId);\n\n return;\n }\n\n const imagePosition = convertToVector3(imagePlane.imagePositionPatient);\n const distance = imagePosition.distanceToSquared(sourceImagePosition);\n // Console.log(index + '=' + distance);\n\n if (distance < minDistance) {\n minDistance = distance;\n newImageIdIndex = index;\n }\n });\n\n if (newImageIdIndex === stackData.currentImageIdIndex) {\n return;\n }\n\n const startLoadingHandler = loadHandlerManager.getStartLoadHandler();\n const endLoadingHandler = loadHandlerManager.getEndLoadHandler();\n const errorLoadingHandler = loadHandlerManager.getErrorLoadingHandler();\n\n stackData.currentImageIdIndex = newImageIdIndex;\n const newImageId = stackData.imageIds[newImageIdIndex];\n\n if (startLoadingHandler) {\n startLoadingHandler(targetElement);\n }\n\n if (newImageIdIndex !== -1) {\n let loader;\n\n if (stackData.preventCache === true) {\n loader = cornerstone.loadImage(newImageId);\n } else {\n loader = cornerstone.loadAndCacheImage(newImageId);\n }\n\n loader.then(\n function(image) {\n const viewport = cornerstone.getViewport(targetElement);\n\n if (stackData.currentImageIdIndex !== newImageIdIndex) {\n return;\n }\n\n synchronizer.displayImage(targetElement, image, viewport);\n if (endLoadingHandler) {\n endLoadingHandler(targetElement, image);\n }\n },\n function(error) {\n const imageId = stackData.imageIds[newImageIdIndex];\n\n if (errorLoadingHandler) {\n errorLoadingHandler(targetElement, imageId, error);\n }\n }\n );\n }\n}\n","import external from '../externalModules.js';\nimport { getToolState } from '../stateManagement/toolState.js';\nimport loadHandlerManager from '../stateManagement/loadHandlerManager.js';\nimport convertToVector3 from '../util/convertToVector3.js';\n\n// In the future we will want to have a way to manually register links sets of the same orientation (e.g. an axial link set from a prior with an axial link set of a current). The user could do this by scrolling the two stacks to a similar location and then doing a user action (e.g. right click link) at which point the system will capture the delta between the image position (patient) of both stacks and use that to sync them. This offset will need to be adjustable.\n\n/**\n * Calculate a position in space that is offset from the source image's position,\n * and synchronize the target stack to the image that is closest to that position.\n * @export\n * @public\n * @method\n * @name stackImagePositionOffsetSynchronizer\n *\n * @param {Object} synchronizer - The Synchronizer instance that attaches this\n * handler to an event\n * @param {HTMLElement} sourceElement - The source element\n * @param {HTMLElement} targetElement - The target element\n * @param {Object} eventData - The data object from the triggering event\n * @param {Object} positionDifference - An object with { x, y, z } values that will be\n * added to the source image's coordinates\n */\nexport default function(\n synchronizer,\n sourceElement,\n targetElement,\n eventData,\n positionDifference\n) {\n // Ignore the case where the source and target are the same enabled element\n if (targetElement === sourceElement) {\n return;\n }\n\n const cornerstone = external.cornerstone;\n const sourceStackData = getToolState(sourceElement, 'stack').data[0];\n const sourceImageId =\n sourceStackData.imageIds[sourceStackData.currentImageIdIndex];\n const sourceImagePlane = cornerstone.metaData.get(\n 'imagePlaneModule',\n sourceImageId\n );\n\n if (\n sourceImagePlane === undefined ||\n sourceImagePlane.imagePositionPatient === undefined\n ) {\n return;\n }\n\n const sourceImagePosition = convertToVector3(\n sourceImagePlane.imagePositionPatient\n );\n\n const stackToolDataSource = getToolState(targetElement, 'stack');\n const stackData = stackToolDataSource.data[0];\n\n let minDistance = Number.MAX_VALUE;\n let newImageIdIndex = -1;\n\n if (!positionDifference) {\n return;\n }\n\n const finalPosition = sourceImagePosition.clone().add(positionDifference);\n\n stackData.imageIds.forEach(function(imageId, index) {\n const imagePlane = cornerstone.metaData.get('imagePlaneModule', imageId);\n\n if (\n imagePlane === undefined ||\n imagePlane.imagePositionPatient === undefined\n ) {\n return;\n }\n\n const imagePosition = convertToVector3(imagePlane.imagePositionPatient);\n const distance = finalPosition.distanceToSquared(imagePosition);\n\n if (distance < minDistance) {\n minDistance = distance;\n newImageIdIndex = index;\n }\n });\n\n if (\n newImageIdIndex === stackData.currentImageIdIndex ||\n newImageIdIndex === -1\n ) {\n return;\n }\n\n const startLoadingHandler = loadHandlerManager.getStartLoadHandler();\n const endLoadingHandler = loadHandlerManager.getEndLoadHandler();\n const errorLoadingHandler = loadHandlerManager.getErrorLoadingHandler();\n\n stackData.currentImageIdIndex = newImageIdIndex;\n const newImageId = stackData.imageIds[newImageIdIndex];\n\n if (startLoadingHandler) {\n startLoadingHandler(targetElement);\n }\n\n let loader;\n\n if (stackData.preventCache === true) {\n loader = cornerstone.loadImage(newImageId);\n } else {\n loader = cornerstone.loadAndCacheImage(newImageId);\n }\n\n loader.then(\n function(image) {\n const viewport = cornerstone.getViewport(targetElement);\n\n if (stackData.currentImageIdIndex !== newImageIdIndex) {\n return;\n }\n\n synchronizer.displayImage(targetElement, image, viewport);\n if (endLoadingHandler) {\n endLoadingHandler(targetElement, image);\n }\n },\n function(error) {\n const imageId = stackData.imageIds[newImageIdIndex];\n\n if (errorLoadingHandler) {\n errorLoadingHandler(targetElement, imageId, error);\n }\n }\n );\n}\n","import external from '../externalModules.js';\nimport { getToolState } from '../stateManagement/toolState.js';\nimport loadHandlerManager from '../stateManagement/loadHandlerManager.js';\nimport clip from '../util/clip.js';\n\n/**\n * Synchronize the target stack to the index closest to the source stack's index\n * @export\n * @public\n * @method\n * @name stackImageIndexSynchronizer\n *\n * @param {Object} synchronizer - The Synchronizer instance that attaches this\n * handler to an event\n * @param {HTMLElement} sourceElement - The source element for the index value\n * @param {HTMLElement} targetElement - The target element\n */\nexport default function(synchronizer, sourceElement, targetElement) {\n // Ignore the case where the source and target are the same enabled element\n if (targetElement === sourceElement) {\n return;\n }\n\n const cornerstone = external.cornerstone;\n const sourceStackToolDataSource = getToolState(sourceElement, 'stack');\n const sourceStackData = sourceStackToolDataSource.data[0];\n const targetStackToolDataSource = getToolState(targetElement, 'stack');\n const targetStackData = targetStackToolDataSource.data[0];\n\n let newImageIdIndex = sourceStackData.currentImageIdIndex;\n\n // Clamp the index\n newImageIdIndex = clip(\n newImageIdIndex,\n 0,\n targetStackData.imageIds.length - 1\n );\n\n // Do nothing if the index has not changed\n if (newImageIdIndex === targetStackData.currentImageIdIndex) {\n return;\n }\n\n const startLoadingHandler = loadHandlerManager.getStartLoadHandler();\n const endLoadingHandler = loadHandlerManager.getEndLoadHandler();\n const errorLoadingHandler = loadHandlerManager.getErrorLoadingHandler();\n\n if (startLoadingHandler) {\n startLoadingHandler(targetElement);\n }\n\n let loader;\n\n if (targetStackData.preventCache === true) {\n loader = cornerstone.loadImage(targetStackData.imageIds[newImageIdIndex]);\n } else {\n loader = cornerstone.loadAndCacheImage(\n targetStackData.imageIds[newImageIdIndex]\n );\n }\n\n loader.then(\n function(image) {\n const viewport = cornerstone.getViewport(targetElement);\n\n targetStackData.currentImageIdIndex = newImageIdIndex;\n synchronizer.displayImage(targetElement, image, viewport);\n if (endLoadingHandler) {\n endLoadingHandler(targetElement, image);\n }\n },\n function(error) {\n const imageId = targetStackData.imageIds[newImageIdIndex];\n\n if (errorLoadingHandler) {\n errorLoadingHandler(targetElement, imageId, error);\n }\n }\n );\n}\n","import external from '../externalModules.js';\n\n/**\n * Synchronize the target zoom and pan to match the source\n * @export\n * @public\n * @method\n * @name panZoomSynchronizer\n *\n * @param {Object} synchronizer - The Synchronizer instance that attaches this\n * handler to an event\n * @param {HTMLElement} sourceElement - The source element for the zoom and pan values\n * @param {HTMLElement} targetElement - The target element\n */\nexport default function(synchronizer, sourceElement, targetElement) {\n // Ignore the case where the source and target are the same enabled element\n if (targetElement === sourceElement) {\n return;\n }\n\n const cornerstone = external.cornerstone;\n // Get the source and target viewports\n const sourceViewport = cornerstone.getViewport(sourceElement);\n const targetViewport = cornerstone.getViewport(targetElement);\n\n // Do nothing if the scale and translation are the same\n if (\n targetViewport.scale === sourceViewport.scale &&\n targetViewport.translation.x === sourceViewport.translation.x &&\n targetViewport.translation.y === sourceViewport.translation.y\n ) {\n return;\n }\n\n // Scale and/or translation are different, sync them\n targetViewport.scale = sourceViewport.scale;\n targetViewport.translation.x = sourceViewport.translation.x;\n targetViewport.translation.y = sourceViewport.translation.y;\n synchronizer.setViewport(targetElement, targetViewport);\n}\n","/**\n * Root\n * @namespace CornerstoneTools\n */\n\n/**\n * Drawing API to assist in consistent annotation creation\n * @namespace Drawing\n */\n\n/**\n * Event dispatchers listen for events from `cornerstone` and `enabledElements`. Dispatchers\n * choose which tool(s) get to handle the event by looking at callbacks, priority, and other factors.\n * @private\n * @namespace EventDispatchers\n */\n\n/**\n * Event listeners normalize events emitted by `cornerstone` and `enabledElements`. The listeners\n * then re-emit events prefixed with `cornerstonetools`. For example, `mousemove` becomes `cornerstonetoolsmousemove`.\n * Most of these events are caught by an `eventDispatcher`, and used to shape tool behavior.\n * @private\n * @namespace EventListeners\n */\n\n/**\n * Manipulators describe a tool's `handle` behavior. Leveraging a small set of manipulators\n * allows us to create a consistent experience when interacting with tools via their handles.\n * @namespace Manipulators\n */\n\n/**\n * Mixins are \"tool beahviors\" that can be added to a tool via its mixin\n * array configuration property\n * @namespace Mixins\n */\n\n/**\n * StateManagement\n * @namespace StateManagement\n */\n\n/**\n * Sync\n * @namespace Synchronization\n */\n\n/**\n * Third party\n * @namespace ThirdParty\n */\n\n/**\n * Tools\n * @namespace Tools\n */\n\n/**\n * Tools that extend the {@link #Tools.Base.BaseAnnotationTool|`BaseAnnotationTool`}\n * @namespace Tools.Annotation\n */\n\n/**\n * The parent (abstract) classes that all tools derive from.\n * @namespace Tools.Base\n */\n\n/**\n * Tools that extend the {@link #Tools.Base.BaseBrushTool|`BaseBrushTool`}\n * @namespace Tools.Brush\n */\n\n/**\n * Util\n * @namespace Util\n */\n\nimport {\n AngleTool,\n ArrowAnnotateTool,\n BidirectionalTool,\n CobbAngleTool,\n EllipticalRoiTool,\n FreehandMouseTool,\n LengthTool,\n ProbeTool,\n RectangleRoiTool,\n TextMarkerTool,\n} from './tools/annotation/index.js';\nimport { BrushTool } from './tools/brush/index.js';\nimport {\n CrosshairsTool,\n DoubleTapFitToWindowTool,\n DragProbeTool,\n EraserTool,\n FreehandSculpterMouseTool,\n MagnifyTool,\n OverlayTool,\n PanMultiTouchTool,\n PanTool,\n ReferenceLinesTool,\n RotateTool,\n RotateTouchTool,\n ScaleOverlayTool,\n StackScrollMouseWheelTool,\n StackScrollMultiTouchTool,\n StackScrollTool,\n WwwcRegionTool,\n WwwcTool,\n ZoomMouseWheelTool,\n ZoomTool,\n ZoomTouchPinchTool,\n} from './tools/index.js';\n\nimport { default as imp } from './import.js';\n\nimport { default as init } from './init.js';\n\n// ~~~~~~ STACK TOOLS ~~~~~ //\nimport { default as stackPrefetch } from './stackTools/stackPrefetch.js';\nimport { default as stackRenderers } from './stackTools/stackRenderers.js';\nimport { playClip, stopClip } from './stackTools/playClip.js';\n\n// ~~~~~~ STATE MANAGEMENT ~~~~~ //\nimport { default as store } from './store/index.js';\nimport { default as getToolForElement } from './store/getToolForElement.js';\nimport { addTool, addToolForElement } from './store/addTool.js';\nimport { removeTool, removeToolForElement } from './store/removeTool.js';\nimport {\n setToolOptions,\n setToolOptionsForElement,\n} from './store/setToolOptions.js';\nimport {\n setToolActive,\n setToolActiveForElement,\n setToolEnabled,\n setToolEnabledForElement,\n setToolDisabled,\n setToolDisabledForElement,\n setToolPassive,\n setToolPassiveForElement,\n} from './store/setToolMode.js';\nimport {\n addToolState,\n getToolState,\n removeToolState,\n clearToolState,\n setElementToolStateManager,\n getElementToolStateManager,\n} from './stateManagement/toolState.js';\nimport { default as textStyle } from './stateManagement/textStyle.js';\nimport { default as toolStyle } from './stateManagement/toolStyle.js';\nimport { default as toolColors } from './stateManagement/toolColors.js';\nimport { default as toolCoordinates } from './stateManagement/toolCoordinates.js';\nimport {\n stackSpecificStateManager,\n newStackSpecificToolStateManager,\n addStackStateManager,\n} from './stateManagement/stackSpecificStateManager.js';\nimport { default as loadHandlerManager } from './stateManagement/loadHandlerManager.js';\nimport {\n newImageIdSpecificToolStateManager,\n globalImageIdSpecificToolStateManager,\n} from './stateManagement/imageIdSpecificStateManager.js';\nimport {\n newFrameOfReferenceSpecificToolStateManager,\n globalFrameOfReferenceSpecificToolStateManager,\n} from './stateManagement/frameOfReferenceStateManager.js';\nimport { forceEnabledElementResize } from './eventListeners/windowResizeHandler.js';\n\n// ~~~~~~ ORIENTATION ~~~~~ //\nimport { default as orientation } from './orientation/index.js';\n\n// ~~~~~~ CANVAS EXPORT ~~~~~ //\nimport { default as SaveAs } from './util/SaveAs.js';\n\n// ~~~~~~ THIRD PARTY SUPPORT ~~~~~ //\nimport { default as register } from './thirdParty/register.js';\nimport { default as registerSome } from './thirdParty/registerSome.js';\n\n// ~~~~~~ SYNCHRONIZERS ~~~~~ //\nimport { default as wwwcSynchronizer } from './synchronization/wwwcSynchronizer.js';\nimport { default as updateImageSynchronizer } from './synchronization/updateImageSynchronizer.js';\nimport { default as Synchronizer } from './synchronization/Synchronizer.js';\nimport { default as stackScrollSynchronizer } from './synchronization/stackScrollSynchronizer.js';\nimport { default as stackImagePositionSynchronizer } from './synchronization/stackImagePositionSynchronizer.js';\nimport { default as stackImagePositionOffsetSynchronizer } from './synchronization/stackImagePositionOffsetSynchronizer.js';\nimport { default as stackImageIndexSynchronizer } from './synchronization/stackImageIndexSynchronizer.js';\nimport { default as panZoomSynchronizer } from './synchronization/panZoomSynchronizer.js';\n\n// ~~~~~~ REQUEST POOL MANAGER ~~~~~ //\nimport { default as requestPoolManager } from './requestPool/requestPoolManager.js';\n\nimport { default as external } from './externalModules.js';\nimport { default as EVENTS } from './events.js';\nimport { default as version } from './version.js';\n\nconst cornerstoneTools = {\n // ~~~ TOOLS\n // ~ Annotation Tools\n AngleTool,\n ArrowAnnotateTool,\n BidirectionalTool,\n CobbAngleTool,\n EllipticalRoiTool,\n FreehandMouseTool,\n LengthTool,\n ProbeTool,\n RectangleRoiTool,\n TextMarkerTool,\n // ~ Brush Tools\n BrushTool,\n // ~ Tools\n CrosshairsTool,\n DoubleTapFitToWindowTool,\n DragProbeTool,\n EraserTool,\n FreehandSculpterMouseTool,\n MagnifyTool,\n OverlayTool,\n PanMultiTouchTool,\n PanTool,\n ReferenceLinesTool,\n RotateTool,\n RotateTouchTool,\n ScaleOverlayTool,\n StackScrollMouseWheelTool,\n StackScrollMultiTouchTool,\n StackScrollTool,\n WwwcRegionTool,\n WwwcTool,\n ZoomMouseWheelTool,\n ZoomTool,\n ZoomTouchPinchTool,\n init,\n stackPrefetch,\n stackRenderers,\n playClip,\n stopClip,\n store,\n getToolForElement,\n addTool,\n addToolForElement,\n removeTool,\n removeToolForElement,\n setToolOptions,\n setToolOptionsForElement,\n setToolActive,\n setToolActiveForElement,\n setToolEnabled,\n setToolEnabledForElement,\n setToolDisabled,\n setToolDisabledForElement,\n setToolPassive,\n setToolPassiveForElement,\n addToolState,\n getToolState,\n removeToolState,\n clearToolState,\n setElementToolStateManager,\n getElementToolStateManager,\n textStyle,\n toolStyle,\n toolColors,\n toolCoordinates,\n stackSpecificStateManager,\n newStackSpecificToolStateManager,\n addStackStateManager,\n loadHandlerManager,\n newImageIdSpecificToolStateManager,\n globalImageIdSpecificToolStateManager,\n newFrameOfReferenceSpecificToolStateManager,\n globalFrameOfReferenceSpecificToolStateManager,\n forceEnabledElementResize,\n orientation,\n SaveAs,\n import: imp,\n register,\n registerSome,\n wwwcSynchronizer,\n updateImageSynchronizer,\n Synchronizer,\n stackScrollSynchronizer,\n stackImagePositionSynchronizer,\n stackImagePositionOffsetSynchronizer,\n stackImageIndexSynchronizer,\n panZoomSynchronizer,\n requestPoolManager,\n external,\n EVENTS,\n version,\n};\n\n// Named Exports\nexport {\n // ~~~ TOOLS\n // ~ Annotation Tools\n AngleTool,\n ArrowAnnotateTool,\n BidirectionalTool,\n CobbAngleTool,\n EllipticalRoiTool,\n FreehandMouseTool,\n LengthTool,\n ProbeTool,\n RectangleRoiTool,\n TextMarkerTool,\n // ~ Brush Tools\n BrushTool,\n // ~ Tools\n CrosshairsTool,\n DoubleTapFitToWindowTool,\n DragProbeTool,\n EraserTool,\n FreehandSculpterMouseTool,\n MagnifyTool,\n OverlayTool,\n PanMultiTouchTool,\n PanTool,\n ReferenceLinesTool,\n RotateTool,\n RotateTouchTool,\n ScaleOverlayTool,\n StackScrollMouseWheelTool,\n StackScrollMultiTouchTool,\n StackScrollTool,\n WwwcRegionTool,\n WwwcTool,\n ZoomMouseWheelTool,\n ZoomTool,\n ZoomTouchPinchTool,\n init,\n stackPrefetch,\n stackRenderers,\n playClip,\n stopClip,\n store,\n getToolForElement,\n addTool,\n addToolForElement,\n removeTool,\n removeToolForElement,\n setToolOptions,\n setToolOptionsForElement,\n setToolActive,\n setToolActiveForElement,\n setToolEnabled,\n setToolEnabledForElement,\n setToolDisabled,\n setToolDisabledForElement,\n setToolPassive,\n setToolPassiveForElement,\n addToolState,\n getToolState,\n removeToolState,\n clearToolState,\n setElementToolStateManager,\n getElementToolStateManager,\n textStyle,\n toolStyle,\n toolColors,\n toolCoordinates,\n stackSpecificStateManager,\n newStackSpecificToolStateManager,\n addStackStateManager,\n loadHandlerManager,\n newImageIdSpecificToolStateManager,\n globalImageIdSpecificToolStateManager,\n newFrameOfReferenceSpecificToolStateManager,\n globalFrameOfReferenceSpecificToolStateManager,\n forceEnabledElementResize,\n orientation,\n SaveAs,\n register,\n registerSome,\n wwwcSynchronizer,\n updateImageSynchronizer,\n Synchronizer,\n stackScrollSynchronizer,\n stackImagePositionSynchronizer,\n stackImagePositionOffsetSynchronizer,\n stackImageIndexSynchronizer,\n panZoomSynchronizer,\n requestPoolManager,\n external,\n EVENTS,\n version,\n};\n\n// This has a weird name, so we can't just import it as 'import';\nexport { default as import } from './import.js';\n\nexport default cornerstoneTools;\n","export default '3.0.2';\n","/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n!(function(global) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n var inModule = typeof module === \"object\";\n var runtime = global.regeneratorRuntime;\n if (runtime) {\n if (inModule) {\n // If regeneratorRuntime is defined globally and we're in a module,\n // make the exports object identical to regeneratorRuntime.\n module.exports = runtime;\n }\n // Don't bother evaluating the rest of this file if the runtime was\n // already defined globally.\n return;\n }\n\n // Define the runtime globally (as expected by generated code) as either\n // module.exports (if we're in a module) or a new, empty object.\n runtime = global.regeneratorRuntime = inModule ? module.exports : {};\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n return generator;\n }\n runtime.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n IteratorPrototype[iteratorSymbol] = function () {\n return this;\n };\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;\n GeneratorFunctionPrototype.constructor = GeneratorFunction;\n GeneratorFunctionPrototype[toStringTagSymbol] =\n GeneratorFunction.displayName = \"GeneratorFunction\";\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n prototype[method] = function(arg) {\n return this._invoke(method, arg);\n };\n });\n }\n\n runtime.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n runtime.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n if (!(toStringTagSymbol in genFun)) {\n genFun[toStringTagSymbol] = \"GeneratorFunction\";\n }\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n // meant to be awaited.\n runtime.awrap = function(arg) {\n return { __await: arg };\n };\n\n function AsyncIterator(generator) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value &&\n typeof value === \"object\" &&\n hasOwn.call(value, \"__await\")) {\n return Promise.resolve(value.__await).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return Promise.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration.\n result.value = unwrapped;\n resolve(result);\n }, function(error) {\n // If a rejected Promise was yielded, throw the rejection back\n // into the async generator function so it can be handled there.\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new Promise(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n this._invoke = enqueue;\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n AsyncIterator.prototype[asyncIteratorSymbol] = function () {\n return this;\n };\n runtime.AsyncIterator = AsyncIterator;\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n runtime.async = function(innerFn, outerFn, self, tryLocsList) {\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList)\n );\n\n return runtime.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n context.method = method;\n context.arg = arg;\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n\n if (context.method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = context.arg;\n\n } else if (context.method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw context.arg;\n }\n\n context.dispatchException(context.arg);\n\n } else if (context.method === \"return\") {\n context.abrupt(\"return\", context.arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n if (record.arg === ContinueSentinel) {\n continue;\n }\n\n return {\n value: record.arg,\n done: context.done\n };\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(context.arg) call above.\n context.method = \"throw\";\n context.arg = record.arg;\n }\n }\n };\n }\n\n // Call delegate.iterator[context.method](context.arg) and handle the\n // result, either by returning a { value, done } result from the\n // delegate iterator, or by modifying context.method and context.arg,\n // setting context.delegate to null, and returning the ContinueSentinel.\n function maybeInvokeDelegate(delegate, context) {\n var method = delegate.iterator[context.method];\n if (method === undefined) {\n // A .throw or .return when the delegate iterator has no .throw\n // method always terminates the yield* loop.\n context.delegate = null;\n\n if (context.method === \"throw\") {\n if (delegate.iterator.return) {\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n context.method = \"return\";\n context.arg = undefined;\n maybeInvokeDelegate(delegate, context);\n\n if (context.method === \"throw\") {\n // If maybeInvokeDelegate(context) changed context.method from\n // \"return\" to \"throw\", let that override the TypeError below.\n return ContinueSentinel;\n }\n }\n\n context.method = \"throw\";\n context.arg = new TypeError(\n \"The iterator does not provide a 'throw' method\");\n }\n\n return ContinueSentinel;\n }\n\n var record = tryCatch(method, delegate.iterator, context.arg);\n\n if (record.type === \"throw\") {\n context.method = \"throw\";\n context.arg = record.arg;\n context.delegate = null;\n return ContinueSentinel;\n }\n\n var info = record.arg;\n\n if (! info) {\n context.method = \"throw\";\n context.arg = new TypeError(\"iterator result is not an object\");\n context.delegate = null;\n return ContinueSentinel;\n }\n\n if (info.done) {\n // Assign the result of the finished delegate to the temporary\n // variable specified by delegate.resultName (see delegateYield).\n context[delegate.resultName] = info.value;\n\n // Resume execution at the desired location (see delegateYield).\n context.next = delegate.nextLoc;\n\n // If context.method was \"throw\" but the delegate handled the\n // exception, let the outer generator proceed normally. If\n // context.method was \"next\", forget context.arg since it has been\n // \"consumed\" by the delegate iterator. If context.method was\n // \"return\", allow the original .return call to continue in the\n // outer generator.\n if (context.method !== \"return\") {\n context.method = \"next\";\n context.arg = undefined;\n }\n\n } else {\n // Re-yield the result returned by the delegate method.\n return info;\n }\n\n // The delegate iterator is finished, so forget it and continue with\n // the outer generator.\n context.delegate = null;\n return ContinueSentinel;\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n Gp[toStringTagSymbol] = \"Generator\";\n\n // A Generator should always return itself as the iterator object when the\n // @@iterator function is called on it. Some browsers' implementations of the\n // iterator prototype chain incorrectly implement this, causing the Generator\n // object to not be returned from this call. This ensures that doesn't happen.\n // See https://github.com/facebook/regenerator/issues/274 for more details.\n Gp[iteratorSymbol] = function() {\n return this;\n };\n\n Gp.toString = function() {\n return \"[object Generator]\";\n };\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n runtime.keys = function(object) {\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n }\n runtime.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.method = \"next\";\n this.arg = undefined;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n\n if (caught) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n context.method = \"next\";\n context.arg = undefined;\n }\n\n return !! caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.method = \"next\";\n this.next = finallyEntry.finallyLoc;\n return ContinueSentinel;\n }\n\n return this.complete(record);\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = this.arg = record.arg;\n this.method = \"return\";\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n\n return ContinueSentinel;\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n if (this.method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n this.arg = undefined;\n }\n\n return ContinueSentinel;\n }\n };\n})(\n // In sloppy mode, unbound `this` refers to the global object, fallback to\n // Function constructor if we're in global strict mode. That is sadly a form\n // of indirect eval which violates Content Security Policy.\n (function() {\n return this || (typeof self === \"object\" && self);\n })() || Function(\"return this\")()\n);\n","/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n// This method of obtaining a reference to the global object needs to be\n// kept identical to the way it is obtained in runtime.js\nvar g = (function() {\n return this || (typeof self === \"object\" && self);\n})() || Function(\"return this\")();\n\n// Use `getOwnPropertyNames` because not all browsers support calling\n// `hasOwnProperty` on the global `self` object in a worker. See #183.\nvar hadRuntime = g.regeneratorRuntime &&\n Object.getOwnPropertyNames(g).indexOf(\"regeneratorRuntime\") >= 0;\n\n// Save the old regeneratorRuntime in case it needs to be restored later.\nvar oldRuntime = hadRuntime && g.regeneratorRuntime;\n\n// Force reevalutation of runtime.js.\ng.regeneratorRuntime = undefined;\n\nmodule.exports = require(\"./runtime\");\n\nif (hadRuntime) {\n // Restore the original runtime.\n g.regeneratorRuntime = oldRuntime;\n} else {\n // Remove the global property added by runtime.js.\n try {\n delete g.regeneratorRuntime;\n } catch(e) {\n g.regeneratorRuntime = undefined;\n }\n}\n","function _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance\");\n}\n\nmodule.exports = _nonIterableSpread;","function _iterableToArray(iter) {\n if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === \"[object Arguments]\") return Array.from(iter);\n}\n\nmodule.exports = _iterableToArray;","function _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) {\n for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {\n arr2[i] = arr[i];\n }\n\n return arr2;\n }\n}\n\nmodule.exports = _arrayWithoutHoles;","function _setPrototypeOf(o, p) {\n module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}\n\nmodule.exports = _setPrototypeOf;"],"sourceRoot":""}