File indexing completed on 2024-05-12 05:35:40
0001 /* 0002 SPDX-FileCopyrightText: 2023 Joshua Goins <josh@redstrate.com> 0003 SPDX-FileCopyrightText: 2023 Jeremy Whiting <jpwhiting@kde.org> 0004 SPDX-FileCopyrightText: 2023 Niccolò Venerandi <niccolo@venerandi.com> 0005 0006 SPDX-License-Identifier: GPL-2.0-or-later 0007 */ 0008 0009 #include "buttonmodel.h" 0010 #include "gamepad.h" 0011 0012 #include <SDL2/SDL_joystick.h> 0013 0014 #include <KLocalizedString> 0015 0016 ButtonModel::ButtonModel(QObject *parent) 0017 : QAbstractTableModel(parent) 0018 { 0019 connect(this, &ButtonModel::deviceChanged, this, &ButtonModel::initDeviceButtons); 0020 } 0021 0022 void ButtonModel::initDeviceButtons() 0023 { 0024 beginResetModel(); 0025 m_buttons.clear(); 0026 0027 if (!m_device) { 0028 endResetModel(); 0029 return; 0030 } 0031 0032 const int numButtons = SDL_JoystickNumButtons(m_device->joystick()); 0033 for (int i = 0; i < SDL_CONTROLLER_BUTTON_MAX; i++) { 0034 const SDL_GameControllerButton button = static_cast<SDL_GameControllerButton>(i); 0035 if (SDL_GameControllerHasButton(m_device->gamecontroller(), button)) { 0036 m_buttons << button; 0037 if (m_buttons.count() == numButtons) { 0038 break; 0039 } 0040 } 0041 } 0042 0043 endResetModel(); 0044 0045 connect(m_device, &Gamepad::buttonStateChanged, this, [this](SDL_GameControllerButton button) { 0046 const int row = m_buttons.indexOf(button); 0047 if (row >= 0) { 0048 const QModelIndex changedIndex = index(row, 0); 0049 Q_EMIT dataChanged(changedIndex, changedIndex, {Qt::DisplayRole}); 0050 } 0051 }); 0052 } 0053 0054 int ButtonModel::rowCount(const QModelIndex &parent) const 0055 { 0056 Q_UNUSED(parent); 0057 return m_buttons.count(); 0058 } 0059 0060 int ButtonModel::columnCount(const QModelIndex &parent) const 0061 { 0062 Q_UNUSED(parent); 0063 return 1; 0064 } 0065 0066 QVariant ButtonModel::data(const QModelIndex &index, int role) const 0067 { 0068 if (!checkIndex(index) || m_device == nullptr) { 0069 return {}; 0070 } 0071 0072 if (index.column() == 0 && role == Qt::DisplayRole) { 0073 const int pressed = SDL_GameControllerGetButton(m_device->gamecontroller(), m_buttons.at(index.row())); 0074 return pressed ? i18nc("Status of a gamepad button", "PRESSED") : QStringLiteral("-"); 0075 } 0076 0077 return {}; 0078 } 0079 0080 QVariant ButtonModel::headerData(int section, Qt::Orientation orientation, int role) const 0081 { 0082 if (role == Qt::DisplayRole) { 0083 if (orientation == Qt::Horizontal && section == 0) { 0084 return i18nc("@label Button state", "State"); 0085 } else if (orientation == Qt::Vertical) { 0086 return QString::number(section + 1); 0087 } 0088 } 0089 0090 return {}; 0091 } 0092 0093 #include "moc_buttonmodel.cpp"