aboutsummaryrefslogtreecommitdiff
path: root/src/keymap/KeySeqParser.cpp
blob: f81ba2a249ecff1978bdfbd1383fe05a3f33ea97 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <QWidget>
#include <QtCore>
#include <algorithm>
#include <cstdint>

#include "keymap/KeySeqParser.hpp"

bool operator==(const KeyChord chord1, const KeyChord chord2) {
  return chord1.mod == chord2.mod && chord1.key == chord2.key;
}

QList<KeyChord> KeySeqParser::parse(QString key_sequence) {
  QList<KeyChord> key_chords;
  KeyChord last_key;

  // TODO: Refactor
  // TODO: Support <C-S-t>
  key_sequence = key_sequence.toLower();
  while (!key_sequence.isEmpty()) {
    int skip_count = 1;
    uint16_t next_closing;
    if (key_sequence.startsWith("<c-")) {
      next_closing = key_sequence.indexOf('>');
      auto key_name = key_sequence.sliced(3, next_closing - 3);
      last_key.mod = last_key.mod | Qt::KeyboardModifier::ControlModifier;
      last_key.key = parse_key(key_name);
      skip_count = next_closing + 1;
    } else if (key_sequence.startsWith("<s-")) {
      next_closing = key_sequence.indexOf('>');
      auto key_name = key_sequence.sliced(3, next_closing - 3);
      last_key.mod = last_key.mod | Qt::KeyboardModifier::ShiftModifier;
      last_key.key = parse_key(key_name);
      skip_count = next_closing + 1;
    } else if (key_sequence.startsWith("<")) {
      next_closing = key_sequence.indexOf('>');
      auto key_name = key_sequence.sliced(1, next_closing - 1);
      last_key.mod = Qt::KeyboardModifier::NoModifier;
      last_key.key = parse_key(key_name);
      skip_count = next_closing + 1;
    } else {
      auto key_name = key_sequence.first(1);
      last_key.mod = Qt::KeyboardModifier::NoModifier;
      last_key.key = parse_key(key_name);
    }

    key_sequence.slice(std::max(1, skip_count));
    key_chords.push_back(last_key);
    last_key = KeyChord();
  }

  return key_chords;
}

Qt::Key KeySeqParser::parse_key(const QString &key_name) {
  if (key_name.length() == 0)
    return Qt::Key_T; // TODO: tmp

  if (key_name.length() == 1) {
    const char key_char = key_name.toStdString().at(0);
    return Qt::Key(Qt::Key_A + (key_char - 'a'));
  }

  if (key_name == "space")
    return Qt::Key_Space;

  if (key_name == "cr")
    return Qt::Key_Return;

  if (key_name == "esc")
    return Qt::Key_Escape;

  if (key_name == "bs")
    return Qt::Key_Backspace;

  if (key_name == "tab")
    return Qt::Key_Tab;

  return Qt::Key_T;
}