keyPressFor function

KeyPressMsg keyPressFor(
  1. String key
)

The KeyPressMsg a terminal produces for the keystroke key (see TuiTester.press).

Implementation

KeyPressMsg keyPressFor(String key) {
  final cut = key.length > 1 ? key.lastIndexOf('+', key.length - 2) : -1;
  final base = key.substring(cut + 1);
  final mods = cut < 0 ? const <String>[] : key.substring(0, cut).split('+');
  const bits = {
    'shift': 1,
    'alt': 2,
    'ctrl': 4,
    'super': 8,
    'hyper': 16,
    'meta': 32,
  };
  var m = 0;
  for (final mod in mods) {
    final bit = bits[mod];
    if (bit == null) {
      throw ArgumentError.value(key, 'key', 'unknown modifier "$mod"');
    }
    m |= bit;
  }
  // The keystroke() spelling: modifiers in a fixed order.
  final want = [
    for (final (name, bit) in const [
      ('ctrl', 4),
      ('alt', 2),
      ('shift', 1),
      ('meta', 32),
      ('hyper', 16),
      ('super', 8),
    ])
      if (m & bit != 0) name,
    base,
  ].join('+');

  const finals = {
    'up': 'A',
    'down': 'B',
    'right': 'C',
    'left': 'D',
    'home': 'H',
    'end': 'F',
    'f1': 'P',
    'f2': 'Q',
    'f3': 'R',
    'f4': 'S',
  };
  const tildes = {
    'insert': 2,
    'delete': 3,
    'pgup': 5,
    'pgdown': 6,
    'f5': 15,
    'f6': 17,
    'f7': 18,
    'f8': 19,
    'f9': 20,
    'f10': 21,
    'f11': 23,
    'f12': 24,
  };
  const named = {
    'enter': 13,
    'tab': 9,
    'esc': 27,
    'backspace': 127,
    'space': 32,
  };
  final rune = base.runes.length == 1 ? base.runes.single : null;
  final code = named[base] ?? rune;

  // What a legacy terminal sends; then the xterm / kitty form with modifiers.
  String? legacy() {
    if (m == 0) {
      if (finals[base] case final f?) return '\x1b[$f';
      if (tildes[base] case final n?) return '\x1b[$n~';
      return code == null ? null : String.fromCharCode(code);
    }
    if (m == 1 && base == 'tab') return '\x1b[Z';
    if (m == 4 && base == 'space') return '\x00';
    if (m == 4 && rune != null && rune >= 0x61 && rune <= 0x7a) {
      return String.fromCharCode(rune - 0x60);
    }
    if (m == 2 && code != null) return '\x1b${String.fromCharCode(code)}';
    return null;
  }

  String? modified() {
    if (m == 0) return null;
    if (finals[base] case final f?) return '\x1b[1;${m + 1}$f';
    if (tildes[base] case final n?) return '\x1b[$n;${m + 1}~';
    return code == null ? null : '\x1b[$code;${m + 1}u';
  }

  for (final bytes in [legacy(), modified()]) {
    if (bytes == null) continue;
    final msgs = _decode(utf8.encode(bytes));
    if (msgs case [final KeyPressMsg msg] when msg.key == want) return msg;
  }
  throw ArgumentError.value(
      key, 'key', 'the input decoder does not read this keystroke');
}