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
53void KeyEditor::clearButton() {
54 m_button = true;
55 setValue(-1);
56}
57
58void KeyEditor::clearAxis() {
59 m_button = true;
60 m_axis = -1;
61 m_direction = GamepadAxisEvent::NEUTRAL;
62 updateButtonText();
63 emit axisChanged(m_axis, m_direction);
64}
65
66QSize KeyEditor::sizeHint() const {
67 QSize hint = QLineEdit::sizeHint();
68 hint.setWidth(40);
69 return hint;
70}
71
72void KeyEditor::keyPressEvent(QKeyEvent* event) {
73 if (!m_button) {
74 setValue(event->key());
75 }
76 event->accept();
77}
78
79bool KeyEditor::event(QEvent* event) {
80 if (!m_button) {
81 return QWidget::event(event);
82 }
83 if (event->type() == GamepadButtonEvent::Down()) {
84 setValueButton(static_cast<GamepadButtonEvent*>(event)->value());
85 event->accept();
86 return true;
87 }
88 if (event->type() == GamepadAxisEvent::Type()) {
89 GamepadAxisEvent* gae = static_cast<GamepadAxisEvent*>(event);
90 if (gae->isNew()) {
91 setValueAxis(gae->axis(), gae->direction());
92 }
93 event->accept();
94 return true;
95 }
96 return QWidget::event(event);
97}
98
99void KeyEditor::updateButtonText() {
100 QStringList text;
101 if (m_key >= 0) {
102 text.append(QString::number(m_key));
103 }
104 if (m_direction != GamepadAxisEvent::NEUTRAL) {
105 text.append((m_direction == GamepadAxisEvent::NEGATIVE ? "-" : "+") + QString::number(m_axis));
106 }
107 if (text.isEmpty()) {
108 setText(tr("---"));
109 } else {
110 setText(text.join("/"));
111 }
112}