All files / Sources/Widgets/Widgets3D/LineWidget behavior.js

2.14% Statements 3/140
0% Branches 0/89
0% Functions 0/21
2.14% Lines 3/140

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373                      1x   1x   1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
import Constants from 'vtk.js/Sources/Widgets/Widgets3D/LineWidget/Constants';
import macro from 'vtk.js/Sources/macros';
import * as vtkMath from 'vtk.js/Sources/Common/Core/Math/';
import {
  calculateTextPosition,
  updateTextPosition,
  getNumberOfPlacedHandles,
  isHandlePlaced,
  getPoint,
} from 'vtk.js/Sources/Widgets/Widgets3D/LineWidget/helpers';
 
const { ShapeType } = Constants;
// Total number of points to place
const MAX_POINTS = 2;
 
const handleGetters = ['getHandle1', 'getHandle2', 'getMoveHandle'];
 
export default function widgetBehavior(publicAPI, model) {
  model.classHierarchy.push('vtkLineWidgetProp');
  model._isDragging = false;
 
  /**
   * Returns the handle at the handleIndex'th index.
   * @param {number} handleIndex 0, 1 or 2
   */
  publicAPI.getHandle = (handleIndex) =>
    model.widgetState[handleGetters[handleIndex]]();
 
  /**
   * Return the index in the of tbe handle in `representations` array,
   * or -1 if the handle is not present in the widget state.
   */
  publicAPI.getHandleIndex = (handle) => {
    switch (handle) {
      case model.widgetState.getHandle1():
        return 0;
      case model.widgetState.getHandle2():
        return 1;
      case model.widgetState.getMoveHandle():
        return 2;
      default:
        return -1;
    }
  };
 
  publicAPI.isPlaced = () =>
    getNumberOfPlacedHandles(model.widgetState) === MAX_POINTS;
 
  // --------------------------------------------------------------------------
  // Interactor event
  // --------------------------------------------------------------------------
 
  function ignoreKey(e) {
    return e.altKey || e.controlKey || e.shiftKey;
  }
 
  function updateCursor(callData) {
    model._isDragging = true;
    const manipulator =
      model.activeState?.getManipulator?.() ?? model.manipulator;
    model.previousPosition = manipulator.handleEvent(
      callData,
      model._apiSpecificRenderWindow
    ).worldCoords;
    model._apiSpecificRenderWindow.setCursor('grabbing');
    model._interactor.requestAnimation(publicAPI);
  }
 
  // --------------------------------------------------------------------------
  // Text methods
  // --------------------------------------------------------------------------
 
  publicAPI.setText = (text) => {
    model.widgetState.getText().setText(text);
    model._interactor.render();
  };
 
  // --------------------------------------------------------------------------
  // Handle positioning methods
  // --------------------------------------------------------------------------
 
  // Handle utilities ---------------------------------------------------------
 
  function getLineDirection(p1, p2) {
    const dir = vtkMath.subtract(p1, p2, []);
    vtkMath.normalize(dir);
    return dir;
  }
 
  // Handle orientation & rotation ---------------------------------------------------------
 
  function computeMousePosition(p1, callData) {
    const displayMousePos = publicAPI.computeWorldToDisplay(
      model._renderer,
      ...p1
    );
    const worldMousePos = publicAPI.computeDisplayToWorld(
      model._renderer,
      callData.position.x,
      callData.position.y,
      displayMousePos[2]
    );
    return worldMousePos;
  }
 
  /**
   * Returns the  handle orientation to match the direction vector of the polyLine from one tip to another
   * @param {number} handleIndex 0 for handle1, 1 for handle2
   * @param {object} callData if specified, uses mouse position as 2nd point
   */
  function getHandleOrientation(handleIndex, callData = null) {
    const point1 = getPoint(handleIndex, model.widgetState);
    const point2 = callData
      ? computeMousePosition(point1, callData)
      : getPoint(1 - handleIndex, model.widgetState);
    return point1 && point2 ? getLineDirection(point1, point2) : null;
  }
 
  /**
   * Orient handle
   * @param {number} handleIndex 0, 1 or 2
   * @param {object} callData optional, see getHandleOrientation for details.
   */
  function updateHandleOrientation(handleIndex) {
    const orientation = getHandleOrientation(Math.min(1, handleIndex));
    model.representations[handleIndex].setOrientation(orientation);
  }
 
  publicAPI.updateHandleOrientations = () => {
    updateHandleOrientation(0);
    updateHandleOrientation(1);
    updateHandleOrientation(2);
  };
 
  publicAPI.rotateHandlesToFaceCamera = () => {
    model.representations[0].setViewMatrix(
      Array.from(model._camera.getViewMatrix())
    );
    model.representations[1].setViewMatrix(
      Array.from(model._camera.getViewMatrix())
    );
  };
 
  // Handles visibility ---------------------------------------------------------
 
  /**
   * Set actor visibility to true unless it is a NONE handle
   * and uses state visibility variable for the displayActor visibility to
   * allow pickable handles even when they are not displayed on screen
   * @param handle : the handle state object
   * @param handleNb : the handle number according to its label in widget state
   */
  publicAPI.updateHandleVisibility = (handleIndex) => {
    const handle = publicAPI.getHandle(handleIndex);
    const visibility =
      handle.getVisible() && isHandlePlaced(handleIndex, model.widgetState);
    model.representations[handleIndex].setVisibilityFlagArray([
      visibility,
      visibility && handle.getShape() !== ShapeType.NONE,
    ]);
    model.representations[handleIndex].updateActorVisibility();
    model._interactor.render();
  };
 
  /**
   * Called when placing a point from the first time.
   * @param {number} handleIndex
   */
  publicAPI.placeHandle = (handleIndex) => {
    const handle = publicAPI.getHandle(handleIndex);
    handle.setOrigin(...model.widgetState.getMoveHandle().getOrigin());
 
    publicAPI.updateHandleOrientations();
    publicAPI.rotateHandlesToFaceCamera();
    model.widgetState.getText().setOrigin(calculateTextPosition(model));
    publicAPI.updateHandleVisibility(handleIndex);
 
    if (handleIndex === 0) {
      // For the line (handle1, handle2, moveHandle) to be displayed
      // correctly, handle2 origin must be valid.
      publicAPI
        .getHandle(1)
        .setOrigin(...model.widgetState.getMoveHandle().getOrigin());
      // Now that handle2 has a valid origin, hide it
      publicAPI.updateHandleVisibility(1);
 
      model.widgetState
        .getMoveHandle()
        .setShape(publicAPI.getHandle(1).getShape());
    }
    if (handleIndex === 1) {
      publicAPI.loseFocus();
    }
  };
 
  // --------------------------------------------------------------------------
  // Left press: Select handle to drag
  // --------------------------------------------------------------------------
 
  publicAPI.handleLeftButtonPress = (e) => {
    if (
      !model.activeState ||
      !model.activeState.getActive() ||
      !model.pickable ||
      ignoreKey(e)
    ) {
      return macro.VOID;
    }
    if (
      model.activeState === model.widgetState.getMoveHandle() &&
      getNumberOfPlacedHandles(model.widgetState) === 0
    ) {
      publicAPI.placeHandle(0);
    } else if (
      model.widgetState.getMoveHandle().getActive() &&
      getNumberOfPlacedHandles(model.widgetState) === 1
    ) {
      publicAPI.placeHandle(1);
    } else if (model.dragable && !model.widgetState.getText().getActive()) {
      // Grab handle1, handle2 or whole widget
      updateCursor(e);
    }
    publicAPI.invokeStartInteractionEvent();
    return macro.EVENT_ABORT;
  };
 
  // --------------------------------------------------------------------------
  // Mouse move: Drag selected handle / Handle follow the mouse
  // --------------------------------------------------------------------------
 
  publicAPI.handleMouseMove = (callData) => {
    const manipulator =
      model.activeState?.getManipulator?.() ?? model.manipulator;
    if (
      manipulator &&
      model.pickable &&
      model.dragable &&
      model.activeState &&
      model.activeState.getActive() &&
      !ignoreKey(callData)
    ) {
      const { worldCoords } = manipulator.handleEvent(
        callData,
        model._apiSpecificRenderWindow
      );
      const translation = model.previousPosition
        ? vtkMath.subtract(worldCoords, model.previousPosition, [])
        : [0, 0, 0];
      model.previousPosition = worldCoords;
      if (
        // is placing first or second handle
        model.activeState === model.widgetState.getMoveHandle() ||
        // is dragging already placed first or second handle
        model._isDragging
      ) {
        if (model.activeState.setOrigin) {
          model.activeState.setOrigin(worldCoords);
          publicAPI.updateHandleVisibility(
            publicAPI.getHandleIndex(model.activeState)
          );
        } else {
          // Dragging line
          publicAPI
            .getHandle(0)
            .setOrigin(
              vtkMath.add(publicAPI.getHandle(0).getOrigin(), translation, [])
            );
          publicAPI
            .getHandle(1)
            .setOrigin(
              vtkMath.add(publicAPI.getHandle(1).getOrigin(), translation, [])
            );
        }
        publicAPI.updateHandleOrientations();
        updateTextPosition(model);
        publicAPI.invokeInteractionEvent();
        return macro.EVENT_ABORT;
      }
    }
    return macro.VOID;
  };
 
  // --------------------------------------------------------------------------
  // Left release: Finish drag
  // --------------------------------------------------------------------------
 
  publicAPI.handleLeftButtonRelease = () => {
    if (
      !model.activeState ||
      !model.activeState.getActive() ||
      !model.pickable
    ) {
      publicAPI.rotateHandlesToFaceCamera();
      return macro.VOID;
    }
    if (model.hasFocus && publicAPI.isPlaced()) {
      publicAPI.loseFocus();
      return macro.VOID;
    }
 
    if (model._isDragging && publicAPI.isPlaced()) {
      const wasTextActive = model.widgetState.getText().getActive();
      // Recompute offsets
      model.widgetState.deactivate();
      model.activeState = null;
      if (!wasTextActive) {
        model._interactor.cancelAnimation(publicAPI);
      }
      model._apiSpecificRenderWindow.setCursor('pointer');
 
      model.hasFocus = false;
      model._isDragging = false;
    } else if (model.activeState !== model.widgetState.getMoveHandle()) {
      model.widgetState.deactivate();
    }
 
    if (
      (model.hasFocus && !model.activeState) ||
      (model.activeState && !model.activeState.getActive())
    ) {
      model._widgetManager.enablePicking();
      model._interactor.render();
    }
 
    publicAPI.invokeEndInteractionEvent();
    return macro.EVENT_ABORT;
  };
 
  // --------------------------------------------------------------------------
  // Focus API - moveHandle follow mouse when widget has focus
  // --------------------------------------------------------------------------
 
  publicAPI.grabFocus = () => {
    if (!model.hasFocus && !publicAPI.isPlaced()) {
      model.activeState = model.widgetState.getMoveHandle();
      model.activeState.setShape(publicAPI.getHandle(0).getShape());
      model.activeState.activate();
      model._interactor.requestAnimation(publicAPI);
      publicAPI.invokeStartInteractionEvent();
    }
    model.hasFocus = true;
  };
 
  // --------------------------------------------------------------------------
 
  publicAPI.loseFocus = () => {
    if (model.hasFocus) {
      model._interactor.cancelAnimation(publicAPI);
      publicAPI.invokeEndInteractionEvent();
    }
    model.widgetState.deactivate();
    model.widgetState.getMoveHandle().deactivate();
    model.widgetState.getMoveHandle().setOrigin(null);
    model.activeState = null;
    model.hasFocus = false;
    model._widgetManager.enablePicking();
    model._interactor.render();
  };
 
  publicAPI.reset = () => {
    model.widgetState.deactivate();
    model.widgetState.getMoveHandle().deactivate();
 
    model.widgetState.getHandle1().setOrigin(null);
    model.widgetState.getHandle2().setOrigin(null);
    model.widgetState.getMoveHandle().setOrigin(null);
    model.widgetState.getText().setOrigin(null);
    model.widgetState.getText().setText('');
 
    model.activeState = null;
  };
}