cursorPosition property

Coordinate? cursorPosition

Returns the current cursor position as a coordinate.

Warning: Linux and macOS terminals report their cursor position by posting an escape sequence to stdin in response to a request. However, if there is lots of other keyboard input at the same time, some terminals may interleave that input in the response. There is no easy way around this; the recommendation is therefore to use this call before reading keyboard input, to get an original offset, and then track the local cursor independently based on keyboard input.

Implementation

Coordinate? get cursorPosition {
  rawMode = true;
  stdout.write(ansiDeviceStatusReportCursorPosition);
  // returns a Cursor Position Report result in the form <ESC>[24;80R
  // which we have to parse apart, unfortunately
  var result = '';
  var i = 0;

  // avoid infinite loop if we're getting a bad result
  while (i < 16) {
    final readByte = stdin.readByteSync();

    if (readByte == -1) break; // headless console may not report back

    // ignore: use_string_buffers
    result += String.fromCharCode(readByte);
    if (result.endsWith('R')) break;
    i++;
  }
  rawMode = false;

  if (result.isEmpty || result[0] != '\x1b') {
    print(' result: $result  result.length: ${result.length}');
    return null;
  }

  result = result.substring(2, result.length - 1);
  final coords = result.split(';');

  if (coords.length != 2) {
    print(' coords.length: ${coords.length}');
    return null;
  }
  if ((int.tryParse(coords[0]) != null) &&
      (int.tryParse(coords[1]) != null)) {
    return Coordinate(int.parse(coords[0]) - 1, int.parse(coords[1]) - 1);
  } else {
    print(' coords[0]: ${coords[0]}   coords[1]: ${coords[1]}');
    return null;
  }
}
void cursorPosition=(Coordinate? cursor)

Sets the cursor to a specific coordinate.

Coordinates are measured from the top left of the screen, and are zero-based.

Implementation

set cursorPosition(Coordinate? cursor) {
  if (cursor != null) {
    if (Platform.isWindows) {
      final winTermlib = _termlib as TermLibWindows;
      winTermlib.setCursorPosition(cursor.col, cursor.row);
    } else {
      stdout.write(ansiCursorPosition(cursor.row + 1, cursor.col + 1));
    }
  }
}