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_button(false)
19{
20 setAlignment(Qt::AlignCenter);
21}
22
23void KeyEditor::setValue(int key) {
24 if (m_button) {
25 if (key < 0) {
26 clear();
27 } else {
28 setText(QString::number(key));
29 }
30 } else {
31 setText(QKeySequence(key).toString(QKeySequence::NativeText));
32 }
33 m_key = key;
34 emit valueChanged(key);
35}
36
37void KeyEditor::setValueKey(int key) {
38 m_button = false;
39 setValue(key);
40}
41
42void KeyEditor::setValueButton(int button) {
43 m_button = true;
44 m_direction = GamepadAxisEvent::NEUTRAL;
45 setValue(button);
46}
47
48void KeyEditor::setValueAxis(int axis, int32_t value) {
49 m_button = true;
50 m_key = axis;
51 m_direction = value < 0 ? GamepadAxisEvent::NEGATIVE : GamepadAxisEvent::POSITIVE;
52 setText((value < 0 ? "-" : "+") + QString::number(axis));
53 emit axisChanged(axis, m_direction);
54}
55
56QSize KeyEditor::sizeHint() const {
57 QSize hint = QLineEdit::sizeHint();
58 hint.setWidth(40);
59 return hint;
60}
61
62void KeyEditor::keyPressEvent(QKeyEvent* event) {
63 if (!m_button) {
64 setValue(event->key());
65 }
66 event->accept();
67}
68
69bool KeyEditor::event(QEvent* event) {
70 if (!m_button) {
71 return QWidget::event(event);
72 }
73 if (event->type() == GamepadButtonEvent::Down()) {
74 setValueButton(static_cast<GamepadButtonEvent*>(event)->value());
75 event->accept();
76 return true;
77 }
78 if (event->type() == GamepadAxisEvent::Type()) {
79 GamepadAxisEvent* gae = static_cast<GamepadAxisEvent*>(event);
80 if (gae->isNew()) {
81 setValueAxis(gae->axis(), gae->direction());
82 }
83 event->accept();
84 return true;
85 }
86 return QWidget::event(event);
87}