get method

  1. @override
SneathCoordinate? get()
override

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

@override
SneathCoordinate? get() {
  setRawModeDelegate(true);
  stdout.write(control_sequence_identifier + '6n');
  // returns a Cursor Position Report result in the form <ESC>[24;80R
  // which we have to parse apart.
  String result = '';
  int i = 0;
  // avoid infinite loop if we're getting a bad result
  while (i < 16) {
    // ignore: use_string_buffers
    result += String.fromCharCode(stdin.readByteSync());
    if (result.endsWith('R')) {
      break;
    }
    i++;
  }
  setRawModeDelegate(false);
  if (result[0] != "\x1b") {
    print(' result: $result  result.length: ${result.length}');
    return null;
  } else {
    result = result.substring(2, result.length - 1);
    final coords = result.split(';');
    if (coords.length != 2) {
      print(' coords.length: ${coords.length}');
      return null;
    } else {
      final parsedX = int.tryParse(coords[0]);
      final parsedY = int.tryParse(coords[1]);
      if ((parsedX != null) && (parsedY != null)) {
        return SneathCoordinateImpl(row: parsedX - 1, col: parsedY - 1);
      } else {
        print(' coords[0]: ${coords[0]}   coords[1]: ${coords[1]}');
        return null;
      }
    }
  }
}