aboutsummaryrefslogtreecommitdiff
path: root/src/widgets/CommandInput.cpp
blob: 3ea0f38524b9a25ecb39990fab37e6d540ba431d (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
80
81
82
83
84
#include <QCompleter>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QLabel>
#include <QLineEdit>
#include <QStringListModel>
#include <QVBoxLayout>
#include <QWidget>
#include <QWidgetAction>
#include <QWindow>
#include <QtCore/qnamespace.h>
#include <QtCore/qstringlistmodel.h>
#include <QtWidgets/qboxlayout.h>

#include "completion/CommandsModel.hpp"
#include "completion/Completer.hpp"
#include "widgets/CommandInput.hpp"

const char *rootStyles = R"(
  background-color: #000;
  color: #fff;
  border-radius: 0;
)";

CommandInput::CommandInput(QString defaultInput, QWidget *parentNode)
    : QWidget(parentNode) {
  setContentsMargins(0, 0, 0, 0);
  setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
  setStyleSheet(rootStyles);

  auto layout = new QVBoxLayout(this);
  layout->setContentsMargins(0, 0, 0, 0);

  auto listModel = new CommandsModel();
  auto completer = new Completer(this);
  completer->setModel(listModel);

  auto cmdLineBox = new QWidget();
  layout->addWidget(cmdLineBox);
  auto cmdLineLayout = new QHBoxLayout();
  cmdLineBox->setLayout(cmdLineLayout);
  cmdLineBox->layout()->setContentsMargins(0, 0, 0, 0);
  cmdLineLayout->setSpacing(0);

  auto promptPrefix = new QLabel(tr(":"));
  promptPrefix->setContentsMargins(0, 0, 0, 0);
  input = new QLineEdit(defaultInput);
  input->setFocusPolicy(Qt::StrongFocus);
  input->setCompleter(completer);
  // input->installEventFilter(completer);

  cmdLineLayout->addWidget(promptPrefix);
  cmdLineLayout->addWidget(input);

  setFixedHeight(input->sizeHint().height());
}

void CommandInput::emitSubmit() { emit submitted(getInputCommand()); }

void CommandInput::keyPressEvent(QKeyEvent *event) {
  auto combo = event->keyCombination();
  auto ctrlL = combo.key() == Qt::Key_L &&
               combo.keyboardModifiers().testFlag(Qt::ControlModifier);
  auto esc = combo.key() == Qt::Key_Escape;
  auto enter = combo.key() == Qt::Key_Return || combo.key() == Qt::Key_Enter;

  if (esc || ctrlL)
    emit cancelled();
  else if (enter)
    emitSubmit();
}

void CommandInput::setInputText(QString text) { input->setText(text); }

bool CommandInput::isInputFocussed() { return input->hasFocus(); }

void CommandInput::setInputFocus(bool focussed) {
  if (focussed)
    input->setFocus(Qt::PopupFocusReason);
  else
    input->clearFocus();
}

QString CommandInput::getInputCommand() { return input->text(); }