aboutsummaryrefslogtreecommitdiff
path: root/include/keymap/KeymapEvaluator.hpp
blob: 54409b1d30e65ea7728fa637314497f8c1491ae7 (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
#pragma once

#include "keymap/KeySeqParser.hpp"
#include <QWidget>
#include <QtCore/qmap.h>
#include <QtCore/qnamespace.h>
#include <QtCore>

struct KeyMap {
  KeySequence keySequence;
  QString action; // TODO: string for testing
};

class KeymapEvaluator : public QObject {
  Q_OBJECT

public:
  KeymapEvaluator();

  void addKeymap(QString mode, QString key, QString action) {
    if (!modalKeys.contains(mode))
      modalKeys.insert(mode, {});

    auto keySeq = keySeqParser.parse(key);
    // TODO: Add actions
    modalKeys[mode].append((KeyMap){.keySequence = keySeq, .action = action});
  }

  void evaluate(Qt::KeyboardModifiers modifiers, Qt::Key key) {
    if (key == Qt::Key_Control || key == Qt::Key_Shift || key == Qt::Key_Meta ||
        key == Qt::Key_Alt)
      return;

    auto keymaps = currentModeKeys();
    auto foundPendingMatches = false;

    activeKeySequence.append((KeyChord){.mod = modifiers, .key = key});

    for (auto &keymap : *keymaps) {
      auto matchType =
          KeySeqParser::keySequenceMatch(keymap.keySequence, activeKeySequence);

      if (matchType == KeyMatchType::Match) {
        qDebug() << "Matched!" << keymap.action;
        activeKeySequence.clear();
        return;
      } else if (matchType == KeyMatchType::Pending) {
        foundPendingMatches = true;
      }
    }

    if (!foundPendingMatches)
      activeKeySequence.clear();
  }

private:
  const QList<KeyMap> *currentModeKeys() {
    if (!modalKeys.contains(currentMode))
      return new QList<KeyMap>();

    return &modalKeys[currentMode];
  }

private:
  QMap<QString, QList<KeyMap>> modalKeys;
  KeySeqParser keySeqParser;
  QString currentMode = "default";

  KeySequence activeKeySequence;
};