getOffsetForCaret method

Offset getOffsetForCaret(
  1. TextPosition position,
  2. Rect caretPrototype
)

Returns the offset at which to paint the caret.

Valid only after layout has been called.

Implementation

Offset getOffsetForCaret(TextPosition position, Rect caretPrototype) {
  final _CaretMetrics caretMetrics;
  final _TextPainterLayoutCacheWithOffset layoutCache = _layoutCache!;
  if (position.offset < 0) {
    caretMetrics = const _EmptyLineCaretMetrics(lineHorizontalOffset: 0);
  } else {
    caretMetrics = _computeCaretMetrics(position);
  }

  final Offset rawOffset;
  switch (caretMetrics) {
    case _EmptyLineCaretMetrics(:final double lineHorizontalOffset):
      final double paintOffsetAlignment =
          _computePaintOffsetFraction(textAlign);
      // The full height is not (height - caretPrototype.height)
      // because MongolRenderEditable reserves cursor height on the bottom. Ideally this
      // should be handled by MongolRenderEditable instead.
      final double dy = paintOffsetAlignment == 0
          ? 0
          : paintOffsetAlignment * layoutCache.contentHeight;
      return Offset(lineHorizontalOffset, dy);
    case _LineCaretMetrics(:final Offset offset):
      rawOffset = offset;
  }
  // If offset.dy is outside of the advertised content area, then the associated
  // glyph cluster belongs to a trailing newline character. Ideally the behavior
  // should be handled by higher-level implementations (for instance,
  // MongolRenderEditable reserves height for showing the caret, it's best to handle
  // the clamping there).
  final double adjustedDy = clampDouble(
      rawOffset.dy + layoutCache.paintOffset.dy,
      0,
      layoutCache.contentHeight);
  return Offset(rawOffset.dx + layoutCache.paintOffset.dx, adjustedDy);
}