All files / Sources/Widgets/Core/WidgetManager index.js

48.19% Statements 107/222
21.49% Branches 23/107
47.22% Functions 17/36
47.92% Lines 104/217

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 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524            1x 1x   1x             17x 17x 17x 17x 17x                               292x 292x 292x 268x   24x 24x 24x     292x 292x             8x 8x   8x 8x 8x             10x 10x 25x 25x 25x 25x 48x 48x                                     139x 139x 139x 139x 139x 139x         139x 139x 139x 139x       139x 150x 423x 390x                                                                                                                                                 8x                         3x                 10x 10x                                               8x 10x 10x     8x 10x         10x 10x     8x       8x 7x 7x 7x 7x       7x 7x       7x         7x 7x   7x         7x             7x               7x                       7x   7x 7x         10x 10x 10x     10x     8x 15x           15x 15x             15x 10x 10x 10x     15x                         8x             8x                               8x                                               8x                                                                                 8x                     8x   8x 8x 6x 36x   6x               8x                                                       8x   8x 8x         8x                 8x         1x          
import vtkMath from 'vtk.js/Sources/Common/Core/Math';
import { FieldAssociations } from 'vtk.js/Sources/Common/DataModel/DataSet/Constants';
import macro from 'vtk.js/Sources/macros';
import Constants from 'vtk.js/Sources/Widgets/Core/WidgetManager/Constants';
import { WIDGET_PRIORITY } from 'vtk.js/Sources/Widgets/Core/AbstractWidget/Constants';
 
const { ViewTypes, RenderingTypes, CaptureOn } = Constants;
const { vtkErrorMacro } = macro;
 
let viewIdCount = 1;
 
// ----------------------------------------------------------------------------
// Helper
// ----------------------------------------------------------------------------
 
export function extractRenderingComponents(renderer) {
  const camera = renderer.getActiveCamera();
  const renderWindow = renderer.getRenderWindow();
  const interactor = renderWindow.getInteractor();
  const apiSpecificRenderWindow = interactor.getView();
  return {
    renderer,
    renderWindow,
    interactor,
    apiSpecificRenderWindow,
    camera,
  };
}
 
export function getPixelWorldHeightAtCoord(worldCoord, displayScaleParams) {
  const {
    dispHeightFactor,
    cameraPosition,
    cameraDir,
    isParallel,
    rendererPixelDims,
  } = displayScaleParams;
  let scale = 1;
  if (isParallel) {
    scale = dispHeightFactor;
  } else {
    const worldCoordToCamera = [...worldCoord];
    vtkMath.subtract(worldCoordToCamera, cameraPosition, worldCoordToCamera);
    scale = vtkMath.dot(worldCoordToCamera, cameraDir) * dispHeightFactor;
  }
 
  const rHeight = rendererPixelDims[1];
  return scale / rHeight;
}
// ----------------------------------------------------------------------------
// vtkWidgetManager methods
// ----------------------------------------------------------------------------
 
function vtkWidgetManager(publicAPI, model) {
  if (!model.viewId) {
    model.viewId = `view-${viewIdCount++}`;
  }
  model.classHierarchy.push('vtkWidgetManager');
  const propsWeakMap = new WeakMap();
  const subscriptions = [];
 
  // --------------------------------------------------------------------------
  // API internal
  // --------------------------------------------------------------------------
 
  function updateWidgetWeakMap(widget) {
    const representations = widget.getRepresentations();
    for (let i = 0; i < representations.length; i++) {
      const representation = representations[i];
      const origin = { widget, representation };
      const actors = representation.getActors();
      for (let j = 0; j < actors.length; j++) {
        const actor = actors[j];
        propsWeakMap.set(actor, origin);
      }
    }
  }
 
  function getViewWidget(widget) {
    return (
      widget &&
      (widget.isA('vtkAbstractWidget')
        ? widget
        : widget.getWidgetForView({ viewId: model.viewId }))
    );
  }
 
  // --------------------------------------------------------------------------
  // Widget scaling
  // --------------------------------------------------------------------------
 
  function updateDisplayScaleParams() {
    const { _apiSpecificRenderWindow, _camera, _renderer } = model;
    if (_renderer && _apiSpecificRenderWindow && _camera) {
      const [rwW, rwH] = _apiSpecificRenderWindow.getSize();
      const [vxmin, vymin, vxmax, vymax] = _renderer.getViewport();
      const pixelRatio = _apiSpecificRenderWindow.getComputedDevicePixelRatio();
      const rendererPixelDims = [
        (rwW * (vxmax - vxmin)) / pixelRatio,
        (rwH * (vymax - vymin)) / pixelRatio,
      ];
 
      const cameraPosition = _camera.getPosition();
      const cameraDir = _camera.getDirectionOfProjection();
      const isParallel = _camera.getParallelProjection();
      const dispHeightFactor = isParallel
        ? 2 * _camera.getParallelScale()
        : 2 * Math.tan(vtkMath.radiansFromDegrees(_camera.getViewAngle()) / 2);
 
      model.widgets.forEach((w) => {
        w.getNestedProps().forEach((r) => {
          if (r.getScaleInPixels()) {
            r.setDisplayScaleParams({
              dispHeightFactor,
              cameraPosition,
              cameraDir,
              isParallel,
              rendererPixelDims,
            });
          }
        });
      });
    }
  }
 
  // --------------------------------------------------------------------------
  // API public
  // --------------------------------------------------------------------------
 
  async function updateSelection(callData, fromTouchEvent, callID) {
    const { position } = callData;
    const { requestCount, selectedState, representation, widget } =
      await publicAPI.getSelectedDataForXY(position.x, position.y);
 
    if (requestCount || callID !== model._currentUpdateSelectionCallID) {
      // requestCount > 0: Call activate only once
      // callID check: drop old calls
      return;
    }
 
    function activateHandle(w) {
      if (fromTouchEvent) {
        // release any previous left button interaction
        model._interactor.invokeLeftButtonRelease(callData);
      }
      w.activateHandle({ selectedState, representation });
      if (fromTouchEvent) {
        // re-trigger the left button press to pick the now-active widget
        model._interactor.invokeLeftButtonPress(callData);
      }
    }
 
    // Default cursor behavior
    const cursorStyles = publicAPI.getCursorStyles();
    const style = widget ? 'hover' : 'default';
    const cursor = cursorStyles[style];
    if (cursor) {
      model._apiSpecificRenderWindow.setCursor(cursor);
    }
 
    model.activeWidget = null;
    let wantRender = false;
    if (model.widgetInFocus === widget && widget.hasFocus()) {
      activateHandle(widget);
      model.activeWidget = widget;
      wantRender = true;
    } else {
      for (let i = 0; i < model.widgets.length; i++) {
        const w = model.widgets[i];
        if (w === widget && w.getNestedPickable()) {
          activateHandle(w);
          model.activeWidget = w;
          wantRender = true;
        } else {
          wantRender ||= !!w.getActiveState();
          w.deactivateAllHandles();
        }
      }
    }
 
    if (wantRender) {
      model._interactor.render();
    }
  }
 
  const handleEvent = async (callData, fromTouchEvent = false) => {
    if (
      !model.isAnimating &&
      model.pickingEnabled &&
      callData.pokedRenderer === model._renderer
    ) {
      const callID = Symbol('UpdateSelection');
      model._currentUpdateSelectionCallID = callID;
      await updateSelection(callData, fromTouchEvent, callID);
    }
  };
 
  function updateWidgetForRender(w) {
    w.updateRepresentationForRender(model.renderingType);
  }
 
  function renderPickingBuffer() {
    model.renderingType = RenderingTypes.PICKING_BUFFER;
    model.widgets.forEach(updateWidgetForRender);
  }
 
  function renderFrontBuffer() {
    model.renderingType = RenderingTypes.FRONT_BUFFER;
    model.widgets.forEach(updateWidgetForRender);
  }
 
  async function captureBuffers(x1, y1, x2, y2) {
    if (model._captureInProgress) {
      await model._captureInProgress;
      return;
    }
    renderPickingBuffer();
 
    model._capturedBuffers = null;
    model._captureInProgress = model._selector.getSourceDataAsync(
      model._renderer,
      x1,
      y1,
      x2,
      y2
    );
    model._capturedBuffers = await model._captureInProgress;
    model._captureInProgress = null;
    model.previousSelectedData = null;
    renderFrontBuffer();
  }
 
  publicAPI.enablePicking = () => {
    model.pickingEnabled = true;
    publicAPI.renderWidgets();
  };
 
  publicAPI.renderWidgets = () => {
    Iif (model.pickingEnabled && model.captureOn === CaptureOn.MOUSE_RELEASE) {
      const [w, h] = model._apiSpecificRenderWindow.getSize();
      captureBuffers(0, 0, w, h);
    }
 
    renderFrontBuffer();
    publicAPI.modified();
  };
 
  publicAPI.disablePicking = () => {
    model.pickingEnabled = false;
  };
 
  publicAPI.setRenderer = (renderer) => {
    const renderingComponents = extractRenderingComponents(renderer);
    Object.assign(model, renderingComponents);
    macro.moveToProtected({}, model, Object.keys(renderingComponents));
    while (subscriptions.length) {
      subscriptions.pop().unsubscribe();
    }
 
    model._selector = model._apiSpecificRenderWindow.createSelector();
    model._selector.setFieldAssociation(
      FieldAssociations.FIELD_ASSOCIATION_POINTS
    );
 
    subscriptions.push(
      model._apiSpecificRenderWindow.onWindowResizeEvent(
        updateDisplayScaleParams
      )
    );
    subscriptions.push(model._camera.onModified(updateDisplayScaleParams));
    updateDisplayScaleParams();
 
    subscriptions.push(
      model._interactor.onStartAnimation(() => {
        model.isAnimating = true;
      })
    );
    subscriptions.push(
      model._interactor.onEndAnimation(() => {
        model.isAnimating = false;
        publicAPI.renderWidgets();
      })
    );
 
    subscriptions.push(
      model._interactor.onMouseMove((eventData) => {
        handleEvent(eventData);
        return macro.VOID;
      })
    );
 
    // must be handled after widgets, hence the given priority.
    subscriptions.push(
      model._interactor.onLeftButtonPress((eventData) => {
        const { deviceType } = eventData;
        const touchEvent = deviceType === 'touch' || deviceType === 'pen';
        // only try selection if the left button press is from touch.
        if (touchEvent) {
          handleEvent(eventData, touchEvent);
        }
        return macro.VOID;
      }, WIDGET_PRIORITY / 2)
    );
 
    publicAPI.modified();
 
    if (model.pickingEnabled) {
      publicAPI.enablePicking();
    }
  };
 
  function addWidgetInternal(viewWidget) {
    viewWidget.setWidgetManager(publicAPI);
    updateWidgetWeakMap(viewWidget);
    updateDisplayScaleParams();
 
    // Register to renderer
    model._renderer.addActor(viewWidget);
  }
 
  publicAPI.addWidget = (widget, viewType, initialValues) => {
    Iif (!model._renderer) {
      vtkErrorMacro(
        'Widget manager MUST BE link to a view before registering widgets'
      );
      return null;
    }
    const { viewId, _renderer } = model;
    const w = widget.getWidgetForView({
      viewId,
      renderer: _renderer,
      viewType: viewType || ViewTypes.DEFAULT,
      initialValues,
    });
 
    if (w != null && model.widgets.indexOf(w) === -1) {
      model.widgets.push(w);
      addWidgetInternal(w);
      publicAPI.modified();
    }
 
    return w;
  };
 
  function removeWidgetInternal(viewWidget) {
    model._renderer.removeActor(viewWidget);
    viewWidget.delete();
  }
 
  function onWidgetRemoved() {
    model._renderer.getRenderWindow().getInteractor().render();
    publicAPI.renderWidgets();
  }
 
  publicAPI.removeWidgets = () => {
    model.widgets.forEach(removeWidgetInternal);
    model.widgets = [];
    model.widgetInFocus = null;
    onWidgetRemoved();
  };
 
  publicAPI.removeWidget = (widget) => {
    const viewWidget = getViewWidget(widget);
    const index = model.widgets.indexOf(viewWidget);
    if (index !== -1) {
      model.widgets.splice(index, 1);
 
      const isWidgetInFocus = model.widgetInFocus === viewWidget;
      if (isWidgetInFocus) {
        publicAPI.releaseFocus();
      }
 
      removeWidgetInternal(viewWidget);
      onWidgetRemoved();
    }
  };
 
  publicAPI.getSelectedDataForXY = async (x, y) => {
    model.selections = null;
    if (model.pickingEnabled) {
      // do we require a new capture?
      if (!model._capturedBuffers || model.captureOn === CaptureOn.MOUSE_MOVE) {
        await captureBuffers(x, y, x, y);
      } else {
        // or do we need a pixel that is outside the last capture?
        const capturedRegion = model._capturedBuffers.area;
        if (
          x < capturedRegion[0] ||
          x > capturedRegion[2] ||
          y < capturedRegion[1] ||
          y > capturedRegion[3]
        ) {
          await captureBuffers(x, y, x, y);
        }
      }
 
      model.selections = model._capturedBuffers.generateSelection(x, y, x, y);
    }
    return publicAPI.getSelectedData();
  };
 
  publicAPI.getSelectedData = () => {
    if (!model.selections || !model.selections.length) {
      model.previousSelectedData = null;
      return {};
    }
    const { propID, compositeID, prop } = model.selections[0].getProperties();
    let { widget, representation } = model.selections[0].getProperties();
    // widget is undefined for handle representation.
    if (
      model.previousSelectedData &&
      model.previousSelectedData.prop === prop &&
      model.previousSelectedData.widget === widget &&
      model.previousSelectedData.compositeID === compositeID
    ) {
      model.previousSelectedData.requestCount++;
      return model.previousSelectedData;
    }
 
    if (propsWeakMap.has(prop)) {
      const props = propsWeakMap.get(prop);
      widget = props.widget;
      representation = props.representation;
    }
 
    if (widget && representation) {
      const selectedState = representation.getSelectedState(prop, compositeID);
      model.previousSelectedData = {
        requestCount: 0,
        propID,
        compositeID,
        prop,
        widget,
        representation,
        selectedState,
      };
      return model.previousSelectedData;
    }
    model.previousSelectedData = null;
    return {};
  };
 
  publicAPI.grabFocus = (widget) => {
    const viewWidget = getViewWidget(widget);
    if (model.widgetInFocus && model.widgetInFocus !== viewWidget) {
      model.widgetInFocus.loseFocus();
    }
    model.widgetInFocus = viewWidget;
    if (model.widgetInFocus) {
      model.widgetInFocus.grabFocus();
    }
  };
 
  publicAPI.releaseFocus = () => publicAPI.grabFocus(null);
 
  const superDelete = publicAPI.delete;
  publicAPI.delete = () => {
    while (subscriptions.length) {
      subscriptions.pop().unsubscribe();
    }
    superDelete();
  };
}
 
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
 
const defaultValues = (initialValues = {}) => ({
  // _camera: null,
  // _selector: null,
  // _currentUpdateSelectionCallID: null,
  viewId: null,
  widgets: [],
  activeWidget: null,
  renderer: null,
  viewType: ViewTypes.DEFAULT,
  isAnimating: false,
  pickingEnabled: true,
  selections: null,
  previousSelectedData: null,
  widgetInFocus: null,
  captureOn: CaptureOn.MOUSE_MOVE,
  ...initialValues,
 
  cursorStyles: initialValues.cursorStyles
    ? { ...initialValues.cursorStyles }
    : {
        default: 'default',
        hover: 'pointer',
      },
});
 
// ----------------------------------------------------------------------------
 
export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, defaultValues(initialValues));
 
  macro.obj(publicAPI, model);
  macro.setGet(publicAPI, model, [
    'captureOn',
    'cursorStyles',
    { type: 'enum', name: 'viewType', enum: ViewTypes },
  ]);
  macro.get(publicAPI, model, [
    'selections',
    'widgets',
    'viewId',
    'pickingEnabled',
    'activeWidget',
  ]);
 
  // Object specific methods
  vtkWidgetManager(publicAPI, model);
}
 
// ----------------------------------------------------------------------------
 
export const newInstance = macro.newInstance(extend, 'vtkWidgetManager');
 
// ----------------------------------------------------------------------------
 
export default { newInstance, extend, Constants, getPixelWorldHeightAtCoord };