resize method

void resize(
  1. int oldWidth,
  2. int oldHeight,
  3. int newWidth,
  4. int newHeight,
)

Implementation

void resize(int oldWidth, int oldHeight, int newWidth, int newHeight) {
  if (newHeight > lines.maxLength) {
    lines.maxLength = newHeight;
  }

  // 1. Adjust the height.
  if (newHeight > oldHeight) {
    // Grow larger
    for (var i = 0; i < newHeight - oldHeight; i++) {
      if (newHeight > lines.length) {
        lines.push(_newEmptyLine(newWidth));
      } else {
        _cursorY++;
      }
    }
  } else {
    // Shrink smaller
    for (var i = 0; i < oldHeight - newHeight; i++) {
      if (_cursorY > newHeight - 1) {
        _cursorY--;
      } else {
        lines.pop();
      }
    }
  }

  // Ensure cursor row is within the screen. The column is clamped after
  // width handling so reflow can preserve its logical offset.
  _cursorY = _cursorY.clamp(0, newHeight - 1);

  // 2. Adjust the width.
  if (newWidth != oldWidth) {
    if (terminal.reflowEnabled && !isAltBuffer) {
      final cursorScrollBack = max(lines.length - newHeight, 0);
      final cursorLine = _cursorY + cursorScrollBack;
      final cursorAnchor = lines[cursorLine].createAnchor(_cursorX);
      final reflowResult = reflow(lines, oldWidth, newWidth);

      while (reflowResult.length < newHeight) {
        reflowResult.add(_newEmptyLine(newWidth));
      }

      lines.replaceWith(reflowResult);
      if (cursorAnchor.attached) {
        final newScrollBack = max(lines.length - newHeight, 0);
        _cursorX = cursorAnchor.x.clamp(0, newWidth - 1);
        _cursorY = (cursorAnchor.y - newScrollBack).clamp(0, newHeight - 1);
      }
      cursorAnchor.dispose();
    } else {
      lines.forEach((item) => item.resize(newWidth));
      _cursorX = _cursorX.clamp(0, newWidth - 1);
    }
  }

  _cursorX = _cursorX.clamp(0, newWidth - 1);
  _marginLeft = 0;
  _marginRight = newWidth - 1;
}