src/platform/qt/KeyEditor.cpp (view raw)
1/* Copyright (c) 2013-2014 Jeffrey Pfau
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6#include "KeyEditor.h"
7
8#include "GamepadAxisEvent.h"
9#include "GamepadButtonEvent.h"
10
11#include <QKeyEvent>
12
13using namespace QGBA;
14
15KeyEditor::KeyEditor(QWidget* parent)
16 : QLineEdit(parent)
17 , m_direction(GamepadAxisEvent::NEUTRAL)
18 , m_key(-1)
19 , m_axis(-1)
20 , m_button(false)
21{
22 setAlignment(Qt::AlignCenter);
23}
24
25void KeyEditor::setValue(int key) {
26 m_key = key;
27 if (m_button) {
28 updateButtonText();
29 } else {
30 setText(QKeySequence(key).toString(QKeySequence::NativeText));
31 }
32 emit valueChanged(key);
33}
34
35void KeyEditor::setValueKey(int key) {
36 m_button = false;
37 setValue(key);
38}
39
40void KeyEditor::setValueButton(int button) {
41 m_button = true;
42 setValue(button);
43}
44
45void KeyEditor::setValueAxis(int axis, int32_t value) {
46 m_button = true;
47 m_axis = axis;
48 m_direction = value < 0 ? GamepadAxisEvent::NEGATIVE : GamepadAxisEvent::POSITIVE;
49 updateButtonText();
50 emit axisChanged(axis, m_direction);
51}
52
53QSize KeyEditor::sizeHint() const {
54 QSize hint = QLineEdit::sizeHint();
55 hint.setWidth(40);
56 return hint;
57}
58
59void KeyEditor::keyPressEvent(QKeyEvent* event) {
60 if (!m_button) {
61 setValue(event->key());
62 }
63 event->accept();
64}
65
66bool KeyEditor::event(QEvent* event) {
67 if (!m_button) {
68 return QWidget::event(event);
69 }
70 if (event->type() == GamepadButtonEvent::Down()) {
71 setValueButton(static_cast<GamepadButtonEvent*>(event)->value());
72 event->accept();
73 return true;
74 }
75 if (event->type() == GamepadAxisEvent::Type()) {
76 GamepadAxisEvent* gae = static_cast<GamepadAxisEvent*>(event);
77 if (gae->isNew()) {
78 setValueAxis(gae->axis(), gae->direction());
79 }
80 event->accept();
81 return true;
82 }
83 return QWidget::event(event);
84}
85
86void KeyEditor::updateButtonText() {
87 QStringList text;
88 if (m_key >= 0) {
89 text.append(QString::number(m_key));
90 }
91 if (m_direction != GamepadAxisEvent::NEUTRAL) {
92 text.append((m_direction == GamepadAxisEvent::NEGATIVE ? "-" : "+") + QString::number(m_axis));
93 }
94 if (text.isEmpty()) {
95 setText(tr("---"));
96 } else {
97 setText(text.join("/"));
98 }
99}