identifySpacesInBand method

void identifySpacesInBand()

Identifies and inserts space artifacts between existing artifacts in the band.

This method analyzes the Kerning between artifacts and inserts space artifacts where the Kerning exceeds a certain threshold.

The process involves:

  1. Calculating a threshold Kerning size based on the average width.
  2. Iterating through artifacts to identify Kerning exceeding the threshold.
  3. Creating a list of artifacts that need spaces inserted before them.
  4. Inserting space artifacts at the appropriate positions.

The threshold is derived from the median gap between artifacts.

Implementation

void identifySpacesInBand() {
  updateStatistics();

  if (artifacts.length < _minArtifactsForSpaceDetection) {
    return;
  }

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

  // Calculate a threshold based on gap distribution (robust to large spaces)
  final int spaceThreshold = calculateSpaceThreshold(gaps);
  _insertSpacesAboveThreshold(spaceThreshold);

  // Validate: if too many short words, the threshold was too low.
  // Retry with a conservative (median-based) threshold.
  if (_hasExcessiveShortWords()) {
    artifacts.removeWhere((a) => a.matchingCharacter == ' ');
    final int conservativeThreshold = _conservativeSpaceThreshold(gaps);
    if (conservativeThreshold > spaceThreshold) {
      _insertSpacesAboveThreshold(conservativeThreshold);
    } else {
      // Conservative threshold is not higher — the original was reasonable.
      _insertSpacesAboveThreshold(spaceThreshold);
    }
  }
}