insertSpacesByGap function

void insertSpacesByGap(
  1. List<Artifact> artifacts,
  2. int lineHeight
)

Inserts space artifacts between character artifacts where the gap between them exceeds a threshold computed from the gap distribution.

artifacts is modified in place with space artifacts inserted. lineHeight is the height of the text line for sizing space artifacts.

Implementation

void insertSpacesByGap(List<Artifact> artifacts, int lineHeight) {
  if (artifacts.length < _minArtifactsForSpaces) {
    return;
  }

  // Collect all gaps
  final List<int> gaps = [];
  for (int i = 1; i < artifacts.length; i++) {
    final int gap =
        artifacts[i].rectFound.left - artifacts[i - 1].rectFound.right;
    if (gap > 0) {
      gaps.add(gap);
    }
  }

  if (gaps.isEmpty) {
    return;
  }

  // Compute space threshold from gap distribution
  gaps.sort();
  final int spaceThreshold = _computeSpaceThreshold(gaps);

  // Insert space artifacts
  for (int i = 1; i < artifacts.length; i++) {
    final int gap =
        artifacts[i].rectFound.left - artifacts[i - 1].rectFound.right;
    if (gap >= spaceThreshold) {
      final int spaceWidth = max(1, gap - _spaceBorderOffset);
      final Artifact spaceArtifact = Artifact(spaceWidth, lineHeight);
      spaceArtifact.matchingCharacter = ' ';
      spaceArtifact.locationFound = IntOffset(
        artifacts[i - 1].rectFound.right + 1,
        artifacts[i - 1].rectFound.top,
      );
      artifacts.insert(i, spaceArtifact);
      i++; // Skip the inserted space
    }
  }
}