text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef JOYSTICKSTATUSWINDOW_H
#define JOYSTICKSTATUSWINDOW_H
#include <QDialog>
#include "inputdevice.h"
namespace Ui {
class JoystickStatusWindow;
}
class JoystickStatusWindow : public QDialog
{
Q_OBJECT
public:
explicit JoystickStatusWindow(InputDevice *joystick, QWidget *parent = 0);
~JoystickStatusWindow();
protected:
InputDevice *joystick;
private:
Ui::JoystickStatusWindow *ui;
private slots:
void restoreButtonStates(int code);
void obliterate();
};
#endif // JOYSTICKSTATUSWINDOW_H
``` | /content/code_sandbox/src/joystickstatuswindow.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 219 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include "joyaxiscontextmenu.h"
#include "mousedialog/mouseaxissettingsdialog.h"
#include "antkeymapper.h"
#include "inputdevice.h"
#include "common.h"
JoyAxisContextMenu::JoyAxisContextMenu(JoyAxis *axis, QWidget *parent) :
QMenu(parent),
helper(axis)
{
this->axis = axis;
helper.moveToThread(axis->thread());
connect(this, SIGNAL(aboutToHide()), this, SLOT(deleteLater()));
}
void JoyAxisContextMenu::buildMenu()
{
bool actAsTrigger = false;
PadderCommon::inputDaemonMutex.lock();
if (axis->getThrottle() == JoyAxis::PositiveThrottle ||
axis->getThrottle() == JoyAxis::PositiveHalfThrottle)
{
actAsTrigger = true;
}
PadderCommon::inputDaemonMutex.unlock();
if (actAsTrigger)
{
buildTriggerMenu();
}
else
{
buildAxisMenu();
}
}
void JoyAxisContextMenu::buildAxisMenu()
{
QAction *action = 0;
QActionGroup *presetGroup = new QActionGroup(this);
int presetMode = 0;
int currentPreset = getPresetIndex();
action = this->addAction(tr("Mouse (Horizontal)"));
action->setCheckable(true);
action->setChecked(currentPreset == presetMode+1);
action->setData(QVariant(presetMode));
connect(action, SIGNAL(triggered()), this, SLOT(setAxisPreset()));
presetGroup->addAction(action);
presetMode++;
action = this->addAction(tr("Mouse (Inverted Horizontal)"));
action->setCheckable(true);
action->setChecked(currentPreset == presetMode+1);
action->setData(QVariant(presetMode));
connect(action, SIGNAL(triggered()), this, SLOT(setAxisPreset()));
presetGroup->addAction(action);
presetMode++;
action = this->addAction(tr("Mouse (Vertical)"));
action->setCheckable(true);
action->setChecked(currentPreset == presetMode+1);
action->setData(QVariant(presetMode));
connect(action, SIGNAL(triggered()), this, SLOT(setAxisPreset()));
presetGroup->addAction(action);
presetMode++;
action = this->addAction(tr("Mouse (Inverted Vertical)"));
action->setCheckable(true);
action->setChecked(currentPreset == presetMode+1);
action->setData(QVariant(presetMode));
connect(action, SIGNAL(triggered()), this, SLOT(setAxisPreset()));
presetGroup->addAction(action);
presetMode++;
action = this->addAction(tr("Arrows: Up | Down"));
action->setCheckable(true);
action->setChecked(currentPreset == presetMode+1);
action->setData(QVariant(presetMode));
connect(action, SIGNAL(triggered()), this, SLOT(setAxisPreset()));
presetGroup->addAction(action);
presetMode++;
action = this->addAction(tr("Arrows: Left | Right"));
action->setCheckable(true);
action->setChecked(currentPreset == presetMode+1);
action->setData(QVariant(presetMode));
connect(action, SIGNAL(triggered()), this, SLOT(setAxisPreset()));
presetGroup->addAction(action);
presetMode++;
action = this->addAction(tr("Keys: W | S"));
action->setCheckable(true);
action->setChecked(currentPreset == presetMode+1);
action->setData(QVariant(presetMode));
connect(action, SIGNAL(triggered()), this, SLOT(setAxisPreset()));
presetGroup->addAction(action);
presetMode++;
action = this->addAction(tr("Keys: A | D"));
action->setCheckable(true);
action->setChecked(currentPreset == presetMode+1);
action->setData(QVariant(presetMode));
connect(action, SIGNAL(triggered()), this, SLOT(setAxisPreset()));
presetGroup->addAction(action);
presetMode++;
action = this->addAction(tr("NumPad: KP_8 | KP_2"));
action->setCheckable(true);
action->setChecked(currentPreset == presetMode+1);
action->setData(QVariant(presetMode));
connect(action, SIGNAL(triggered()), this, SLOT(setAxisPreset()));
presetGroup->addAction(action);
presetMode++;
action = this->addAction(tr("NumPad: KP_4 | KP_6"));
action->setCheckable(true);
action->setChecked(currentPreset == presetMode+1);
action->setData(QVariant(presetMode));
connect(action, SIGNAL(triggered()), this, SLOT(setAxisPreset()));
presetGroup->addAction(action);
presetMode++;
action = this->addAction(tr("None"));
action->setCheckable(true);
action->setChecked(currentPreset == presetMode+1);
action->setData(QVariant(presetMode));
connect(action, SIGNAL(triggered()), this, SLOT(setAxisPreset()));
presetGroup->addAction(action);
this->addSeparator();
action = this->addAction(tr("Mouse Settings"));
action->setCheckable(false);
connect(action, SIGNAL(triggered()), this, SLOT(openMouseSettingsDialog()));
}
int JoyAxisContextMenu::getPresetIndex()
{
int result = 0;
PadderCommon::inputDaemonMutex.lock();
JoyAxisButton *naxisbutton = axis->getNAxisButton();
QList<JoyButtonSlot*> *naxisslots = naxisbutton->getAssignedSlots();
JoyAxisButton *paxisbutton = axis->getPAxisButton();
QList<JoyButtonSlot*> *paxisslots = paxisbutton->getAssignedSlots();
if (naxisslots->length() == 1 && paxisslots->length() == 1)
{
JoyButtonSlot *nslot = naxisslots->at(0);
JoyButtonSlot *pslot = paxisslots->at(0);
if (nslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && nslot->getSlotCode() == JoyButtonSlot::MouseLeft &&
pslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && pslot->getSlotCode() == JoyButtonSlot::MouseRight)
{
result = 1;
}
else if (nslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && nslot->getSlotCode() == JoyButtonSlot::MouseRight &&
pslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && pslot->getSlotCode() == JoyButtonSlot::MouseLeft)
{
result = 2;
}
else if (nslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && nslot->getSlotCode() == JoyButtonSlot::MouseUp &&
pslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && pslot->getSlotCode() == JoyButtonSlot::MouseDown)
{
result = 3;
}
else if (nslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && nslot->getSlotCode() == JoyButtonSlot::MouseDown &&
pslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && pslot->getSlotCode() == JoyButtonSlot::MouseUp)
{
result = 4;
}
else if (nslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && (unsigned int)nslot->getSlotCode() == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Up) &&
pslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && (unsigned int)pslot->getSlotCode() == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Down))
{
result = 5;
}
else if (nslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && (unsigned int)nslot->getSlotCode() == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Left) &&
pslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && (unsigned int)pslot->getSlotCode() == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Right))
{
result = 6;
}
else if (nslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && (unsigned int)nslot->getSlotCode() == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_W) &&
pslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && (unsigned int)pslot->getSlotCode() == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_S))
{
result = 7;
}
else if (nslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && (unsigned int)nslot->getSlotCode() == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_A) &&
pslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && (unsigned int)pslot->getSlotCode() == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_D))
{
result = 8;
}
else if (nslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && (unsigned int)nslot->getSlotCode() == AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_8) &&
pslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && (unsigned int)pslot->getSlotCode() == AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_2))
{
result = 9;
}
else if (nslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && (unsigned int)nslot->getSlotCode() == AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_4) &&
pslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && (unsigned int)pslot->getSlotCode() == AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_6))
{
result = 10;
}
}
else if (naxisslots->length() == 0 && paxisslots->length() == 0)
{
result = 11;
}
PadderCommon::inputDaemonMutex.unlock();
return result;
}
void JoyAxisContextMenu::setAxisPreset()
{
//PadderCommon::lockInputDevices();
//InputDevice *tempDevice = axis->getParentSet()->getInputDevice();
//QMetaObject::invokeMethod(tempDevice, "haltServices", Qt::BlockingQueuedConnection);
QAction *action = static_cast<QAction*>(sender());
int item = action->data().toInt();
JoyButtonSlot *nbuttonslot = 0;
JoyButtonSlot *pbuttonslot = 0;
if (item == 0)
{
nbuttonslot = new JoyButtonSlot(JoyButtonSlot::MouseLeft, JoyButtonSlot::JoyMouseMovement, this);
pbuttonslot = new JoyButtonSlot(JoyButtonSlot::MouseRight, JoyButtonSlot::JoyMouseMovement, this);
}
else if (item == 1)
{
nbuttonslot = new JoyButtonSlot(JoyButtonSlot::MouseRight, JoyButtonSlot::JoyMouseMovement, this);
pbuttonslot = new JoyButtonSlot(JoyButtonSlot::MouseLeft, JoyButtonSlot::JoyMouseMovement, this);
}
else if (item == 2)
{
nbuttonslot = new JoyButtonSlot(JoyButtonSlot::MouseUp, JoyButtonSlot::JoyMouseMovement, this);
pbuttonslot = new JoyButtonSlot(JoyButtonSlot::MouseDown, JoyButtonSlot::JoyMouseMovement, this);
}
else if (item == 3)
{
nbuttonslot = new JoyButtonSlot(JoyButtonSlot::MouseDown, JoyButtonSlot::JoyMouseMovement, this);
pbuttonslot = new JoyButtonSlot(JoyButtonSlot::MouseUp, JoyButtonSlot::JoyMouseMovement, this);
}
else if (item == 4)
{
nbuttonslot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Up), Qt::Key_Up, JoyButtonSlot::JoyKeyboard, this);
pbuttonslot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Down), Qt::Key_Down, JoyButtonSlot::JoyKeyboard, this);
}
else if (item == 5)
{
nbuttonslot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Left), Qt::Key_Left, JoyButtonSlot::JoyKeyboard, this);
pbuttonslot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Right), Qt::Key_Right, JoyButtonSlot::JoyKeyboard, this);
}
else if (item == 6)
{
nbuttonslot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_W), Qt::Key_W, JoyButtonSlot::JoyKeyboard, this);
pbuttonslot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_S), Qt::Key_S, JoyButtonSlot::JoyKeyboard, this);
}
else if (item == 7)
{
nbuttonslot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_A), Qt::Key_A, JoyButtonSlot::JoyKeyboard, this);
pbuttonslot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_D), Qt::Key_D, JoyButtonSlot::JoyKeyboard, this);
}
else if (item == 8)
{
nbuttonslot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_8), QtKeyMapperBase::AntKey_KP_8, JoyButtonSlot::JoyKeyboard, this);
pbuttonslot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_2), QtKeyMapperBase::AntKey_KP_2, JoyButtonSlot::JoyKeyboard, this);
}
else if (item == 9)
{
nbuttonslot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_4), QtKeyMapperBase::AntKey_KP_4, JoyButtonSlot::JoyKeyboard, this);
pbuttonslot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_6), QtKeyMapperBase::AntKey_KP_6, JoyButtonSlot::JoyKeyboard, this);
}
else if (item == 10)
{
QMetaObject::invokeMethod(&helper, "clearAndResetAxisButtons", Qt::BlockingQueuedConnection);
}
if (nbuttonslot)
{
QMetaObject::invokeMethod(&helper, "setNAssignedSlot", Qt::BlockingQueuedConnection,
Q_ARG(int, nbuttonslot->getSlotCode()),
Q_ARG(unsigned int, nbuttonslot->getSlotCodeAlias()),
Q_ARG(JoyButtonSlot::JoySlotInputAction, nbuttonslot->getSlotMode()));
//JoyAxisButton *button = axis->getNAxisButton();
//QMetaObject::invokeMethod(button, "clearSlotsEventReset",
// Q_ARG(bool, false));
//button->clearSlotsEventReset(false);
/*QMetaObject::invokeMethod(button, "setAssignedSlot", Qt::BlockingQueuedConnection,
Q_ARG(int, nbuttonslot->getSlotCode()),
Q_ARG(unsigned int, nbuttonslot->getSlotCodeAlias()),
Q_ARG(JoyButtonSlot::JoySlotInputAction, nbuttonslot->getSlotMode()));
*/
//button->setAssignedSlot(nbuttonslot->getSlotCode(), nbuttonslot->getSlotCodeAlias(), nbuttonslot->getSlotMode());
nbuttonslot->deleteLater();
}
if (pbuttonslot)
{
QMetaObject::invokeMethod(&helper, "setPAssignedSlot", Qt::BlockingQueuedConnection,
Q_ARG(int, nbuttonslot->getSlotCode()),
Q_ARG(unsigned int, nbuttonslot->getSlotCodeAlias()),
Q_ARG(JoyButtonSlot::JoySlotInputAction, nbuttonslot->getSlotMode()));
//JoyAxisButton *button = axis->getPAxisButton();
//QMetaObject::invokeMethod(button, "clearSlotsEventReset",
// Q_ARG(bool, false));
//button->clearSlotsEventReset(false);
/*QMetaObject::invokeMethod(button, "setAssignedSlot", Qt::BlockingQueuedConnection,
Q_ARG(int, pbuttonslot->getSlotCode()),
Q_ARG(unsigned int, pbuttonslot->getSlotCodeAlias()),
Q_ARG(JoyButtonSlot::JoySlotInputAction, pbuttonslot->getSlotMode()));
*/
//button->setAssignedSlot(pbuttonslot->getSlotCode(), pbuttonslot->getSlotCodeAlias(), pbuttonslot->getSlotMode());
pbuttonslot->deleteLater();
}
//PadderCommon::unlockInputDevices();
}
void JoyAxisContextMenu::openMouseSettingsDialog()
{
MouseAxisSettingsDialog *dialog = new MouseAxisSettingsDialog(this->axis, parentWidget());
dialog->show();
}
void JoyAxisContextMenu::buildTriggerMenu()
{
QAction *action = 0;
QActionGroup *presetGroup = new QActionGroup(this);
int presetMode = 0;
int currentPreset = getTriggerPresetIndex();
action = this->addAction(tr("Left Mouse Button"));
action->setCheckable(true);
action->setChecked(currentPreset == presetMode+1);
action->setData(QVariant(presetMode));
connect(action, SIGNAL(triggered()), this, SLOT(setTriggerPreset()));
presetGroup->addAction(action);
presetMode++;
action = this->addAction(tr("Right Mouse Button"));
action->setCheckable(true);
action->setChecked(currentPreset == presetMode+1);
action->setData(QVariant(presetMode));
connect(action, SIGNAL(triggered()), this, SLOT(setTriggerPreset()));
presetGroup->addAction(action);
presetMode++;
action = this->addAction(tr("None"));
action->setCheckable(true);
action->setChecked(currentPreset == presetMode+1);
action->setData(QVariant(presetMode));
connect(action, SIGNAL(triggered()), this, SLOT(setTriggerPreset()));
presetGroup->addAction(action);
this->addSeparator();
action = this->addAction(tr("Mouse Settings"));
action->setCheckable(false);
connect(action, SIGNAL(triggered()), this, SLOT(openMouseSettingsDialog()));
}
int JoyAxisContextMenu::getTriggerPresetIndex()
{
int result = 0;
PadderCommon::inputDaemonMutex.lock();
JoyAxisButton *paxisbutton = axis->getPAxisButton();
QList<JoyButtonSlot*> *paxisslots = paxisbutton->getAssignedSlots();
if (paxisslots->length() == 1)
{
JoyButtonSlot *pslot = paxisslots->at(0);
if (pslot->getSlotMode() == JoyButtonSlot::JoyMouseButton &&
pslot->getSlotCode() == JoyButtonSlot::MouseLB)
{
result = 1;
}
else if (pslot->getSlotMode() == JoyButtonSlot::JoyMouseButton &&
pslot->getSlotCode() == JoyButtonSlot::MouseRB)
{
result = 2;
}
}
else if (paxisslots->length() == 0)
{
result = 3;
}
PadderCommon::inputDaemonMutex.unlock();
return result;
}
void JoyAxisContextMenu::setTriggerPreset()
{
QAction *action = static_cast<QAction*>(sender());
int item = action->data().toInt();
JoyButtonSlot *pbuttonslot = 0;
if (item == 0)
{
pbuttonslot = new JoyButtonSlot(JoyButtonSlot::MouseLB, JoyButtonSlot::JoyMouseButton, this);
}
else if (item == 1)
{
pbuttonslot = new JoyButtonSlot(JoyButtonSlot::MouseRB, JoyButtonSlot::JoyMouseButton, this);
}
else if (item == 2)
{
JoyAxisButton *pbutton = axis->getPAxisButton();
QMetaObject::invokeMethod(pbutton, "clearSlotsEventReset", Qt::BlockingQueuedConnection);
}
if (pbuttonslot)
{
QMetaObject::invokeMethod(&helper, "setPAssignedSlot", Qt::BlockingQueuedConnection,
Q_ARG(int, pbuttonslot->getSlotCode()),
Q_ARG(unsigned int, pbuttonslot->getSlotCodeAlias()),
Q_ARG(JoyButtonSlot::JoySlotInputAction, pbuttonslot->getSlotMode()));
//JoyAxisButton *button = axis->getPAxisButton();
//QMetaObject::invokeMethod(button, "clearSlotsEventReset",
// Q_ARG(bool, false));
//button->clearSlotsEventReset(false);
/*QMetaObject::invokeMethod(button, "setAssignedSlot", Qt::BlockingQueuedConnection,
Q_ARG(int, pbuttonslot->getSlotCode()),
Q_ARG(unsigned int, pbuttonslot->getSlotCodeAlias()),
Q_ARG(JoyButtonSlot::JoySlotInputAction, pbuttonslot->getSlotMode()));
*/
//button->setAssignedSlot(pbuttonslot->getSlotCode(), pbuttonslot->getSlotCodeAlias(), pbuttonslot->getSlotMode());
pbuttonslot->deleteLater();
}
}
``` | /content/code_sandbox/src/joyaxiscontextmenu.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 4,797 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef QTKEYMAPPERBASE_H
#define QTKEYMAPPERBASE_H
#include <QObject>
#include <QHash>
class QtKeyMapperBase : public QObject
{
Q_OBJECT
public:
explicit QtKeyMapperBase(QObject *parent = 0);
typedef struct _charKeyInformation
{
Qt::KeyboardModifiers modifiers;
unsigned int virtualkey;
} charKeyInformation;
virtual unsigned int returnVirtualKey(unsigned int qkey);
virtual unsigned int returnQtKey(unsigned int key, unsigned int scancode=0);
virtual bool isModifier(unsigned int qkey);
charKeyInformation getCharKeyInformation(QChar value);
QString getIdentifier();
static const unsigned int customQtKeyPrefix = 0x10000000;
static const unsigned int customKeyPrefix = 0x20000000;
static const unsigned int nativeKeyPrefix = 0x60000000;
enum {
AntKey_Shift_R = Qt::Key_Shift | customQtKeyPrefix,
AntKey_Control_R = Qt::Key_Control | customQtKeyPrefix,
AntKey_Shift_Lock = 0xffe6 | customKeyPrefix, // XK_Shift_Lock | 0x20000000
AntKey_Meta_R = Qt::Key_Meta | customQtKeyPrefix,
AntKey_Alt_R = Qt::Key_Alt | customQtKeyPrefix,
AntKey_KP_Divide = Qt::Key_Slash | customQtKeyPrefix,
AntKey_KP_Multiply = Qt::Key_Asterisk | customQtKeyPrefix,
AntKey_KP_Subtract = Qt::Key_Minus | customQtKeyPrefix,
AntKey_KP_Add = Qt::Key_Plus | customQtKeyPrefix,
AntKey_KP_Decimal = Qt::Key_Period | customQtKeyPrefix,
AntKey_KP_Insert = Qt::Key_Insert | customQtKeyPrefix,
AntKey_KP_Delete = Qt::Key_Delete | customQtKeyPrefix,
AntKey_KP_End = Qt::Key_End | customQtKeyPrefix,
AntKey_KP_Down = Qt::Key_Down | customQtKeyPrefix,
AntKey_KP_Prior = Qt::Key_PageDown | customQtKeyPrefix,
AntKey_KP_Left = Qt::Key_Left | customQtKeyPrefix,
AntKey_KP_Begin = Qt::Key_Clear | customQtKeyPrefix,
AntKey_KP_Right = Qt::Key_Right | customQtKeyPrefix,
AntKey_KP_Home = Qt::Key_Home | customQtKeyPrefix,
AntKey_KP_Up = Qt::Key_Up | customQtKeyPrefix,
AntKey_KP_Next = Qt::Key_PageUp | customQtKeyPrefix,
AntKey_KP_0 = Qt::Key_0 | customQtKeyPrefix,
AntKey_KP_1 = Qt::Key_1 | customQtKeyPrefix,
AntKey_KP_2 = Qt::Key_2 | customQtKeyPrefix,
AntKey_KP_3 = Qt::Key_3 | customQtKeyPrefix,
AntKey_KP_4 = Qt::Key_4 | customQtKeyPrefix,
AntKey_KP_5 = Qt::Key_5 | customQtKeyPrefix,
AntKey_KP_6 = Qt::Key_6 | customQtKeyPrefix,
AntKey_KP_7 = Qt::Key_7 | customQtKeyPrefix,
AntKey_KP_8 = Qt::Key_8 | customQtKeyPrefix,
AntKey_KP_9 = Qt::Key_9 | customQtKeyPrefix
};
protected:
virtual void populateMappingHashes() = 0;
virtual void populateCharKeyInformation() = 0;
QHash<unsigned int, unsigned int> qtKeyToVirtualKey;
QHash<unsigned int, unsigned int> virtualKeyToQtKey;
// Unicode representation -> VK+Modifier information
QHash<unsigned int, charKeyInformation> virtualkeyToCharKeyInformation;
QString identifier;
signals:
public slots:
};
#endif // QTKEYMAPPERBASE_H
``` | /content/code_sandbox/src/qtkeymapperbase.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 947 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef ANTKEYMAPPER_H
#define ANTKEYMAPPER_H
#include <QObject>
#ifdef Q_OS_WIN
#include "qtwinkeymapper.h"
#ifdef WITH_VMULTI
#include "qtvmultikeymapper.h"
#endif
#else
#if defined(WITH_XTEST)
#include "qtx11keymapper.h"
#endif
#if defined(WITH_UINPUT)
#include "qtuinputkeymapper.h"
#endif
#endif
class AntKeyMapper : public QObject
{
Q_OBJECT
public:
static AntKeyMapper* getInstance(QString handler = "");
void deleteInstance();
unsigned int returnVirtualKey(unsigned int qkey);
unsigned int returnQtKey(unsigned int key, unsigned int scancode=0);
bool isModifierKey(unsigned int qkey);
QtKeyMapperBase* getNativeKeyMapper();
QtKeyMapperBase* getKeyMapper();
bool hasNativeKeyMapper();
protected:
explicit AntKeyMapper(QString handler = "", QObject *parent = 0);
static AntKeyMapper *_instance;
QtKeyMapperBase *internalMapper;
QtKeyMapperBase *nativeKeyMapper;
#ifdef Q_OS_WIN
QtWinKeyMapper winMapper;
#ifdef WITH_VMULTI
QtVMultiKeyMapper vmultiMapper;
#endif
#else
#if defined(WITH_XTEST)
QtX11KeyMapper x11Mapper;
#endif
#if defined(WITH_UINPUT)
QtUInputKeyMapper uinputMapper;
#endif
#endif
signals:
public slots:
};
#endif // ANTKEYMAPPER_H
``` | /content/code_sandbox/src/antkeymapper.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 444 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef MOUSEHELPER_H
#define MOUSEHELPER_H
#include <QObject>
#include <QTimer>
#include <QDesktopWidget>
class MouseHelper : public QObject
{
Q_OBJECT
public:
explicit MouseHelper(QObject *parent = 0);
QDesktopWidget* getDesktopWidget();
bool springMouseMoving;
int previousCursorLocation[2];
int pivotPoint[2];
QTimer mouseTimer;
QDesktopWidget *deskWid;
signals:
public slots:
void deleteDeskWid();
void initDeskWid();
private slots:
void resetSpringMouseMoving();
};
#endif // MOUSEHELPER_H
``` | /content/code_sandbox/src/mousehelper.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 230 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include <QHashIterator>
#include "qtvmultikeymapper.h"
QtVMultiKeyMapper::QtVMultiKeyMapper(QObject *parent) :
QtKeyMapperBase(parent)
{
identifier = "vmulti";
populateMappingHashes();
}
void QtVMultiKeyMapper::populateMappingHashes()
{
if (qtKeyToVirtualKey.isEmpty())
{
// Map A - Z keys
for (int i=0; i <= (Qt::Key_Z - Qt::Key_A); i++)
{
qtKeyToVirtualKey[Qt::Key_A + i] = 0x04 + i;
}
// Map 1 - 9 numeric keys
for (int i=0; i <= (Qt::Key_9 - Qt::Key_1); i++)
{
qtKeyToVirtualKey[Qt::Key_1 + i] = 0x1E + i;
}
// Map 0 numeric key
qtKeyToVirtualKey[Qt::Key_0] = 0x27;
qtKeyToVirtualKey[Qt::Key_Return] = 0x28;
qtKeyToVirtualKey[Qt::Key_Escape] = 0x29;
qtKeyToVirtualKey[Qt::Key_Backspace] = 0x2A;
qtKeyToVirtualKey[Qt::Key_Tab] = 0x2B;
qtKeyToVirtualKey[Qt::Key_Space] = 0x2C;
qtKeyToVirtualKey[Qt::Key_Minus] = 0x2D;
qtKeyToVirtualKey[Qt::Key_Equal] = 0x2E;
qtKeyToVirtualKey[Qt::Key_BracketLeft] = 0x2F;
qtKeyToVirtualKey[Qt::Key_BracketRight] = 0x30;
qtKeyToVirtualKey[Qt::Key_Backslash] = 0x31;
qtKeyToVirtualKey[Qt::Key_NumberSign] = 0x32;
qtKeyToVirtualKey[Qt::Key_Semicolon] = 0x33;
qtKeyToVirtualKey[Qt::Key_Apostrophe] = 0x34;
qtKeyToVirtualKey[Qt::Key_QuoteLeft] = 0x35;
qtKeyToVirtualKey[Qt::Key_Comma] = 0x36;
qtKeyToVirtualKey[Qt::Key_Period] = 0x37;
qtKeyToVirtualKey[Qt::Key_Slash] = 0x38;
qtKeyToVirtualKey[Qt::Key_CapsLock] = 0x39;
// Map F1 - F12 keys
for (int i=0; i <= (Qt::Key_F12 - Qt::Key_F1); i++)
{
qtKeyToVirtualKey[Qt::Key_F1 + i] = 0x3A + i;
}
qtKeyToVirtualKey[Qt::Key_Print] = 0x46;
qtKeyToVirtualKey[Qt::Key_ScrollLock] = 0x47;
qtKeyToVirtualKey[Qt::Key_Pause] = 0x48;
qtKeyToVirtualKey[Qt::Key_Insert] = 0x49;
qtKeyToVirtualKey[Qt::Key_Home] = 0x4A;
qtKeyToVirtualKey[Qt::Key_PageUp] = 0x4B;
qtKeyToVirtualKey[Qt::Key_Delete] = 0x4C;
qtKeyToVirtualKey[Qt::Key_End] = 0x4D;
qtKeyToVirtualKey[Qt::Key_PageDown] = 0x4E;
qtKeyToVirtualKey[Qt::Key_Right] = 0x4F;
qtKeyToVirtualKey[Qt::Key_Left] = 0x50;
qtKeyToVirtualKey[Qt::Key_Down] = 0x51;
qtKeyToVirtualKey[Qt::Key_Up] = 0x52;
qtKeyToVirtualKey[Qt::Key_NumLock] = 0x53;
qtKeyToVirtualKey[AntKey_KP_Divide] = 0x54;
qtKeyToVirtualKey[AntKey_KP_Multiply] = 0x55;
qtKeyToVirtualKey[AntKey_KP_Subtract] = 0x56;
qtKeyToVirtualKey[AntKey_KP_Add] = 0x57;
qtKeyToVirtualKey[Qt::Key_Enter] = 0x58;
// Map Numpad 1 - 9 keys
for (int i=0; i <= (AntKey_KP_9 - AntKey_KP_1); i++)
{
qtKeyToVirtualKey[AntKey_KP_1 + i] = 0x59 + i;
}
// Map Numpad 0 key
qtKeyToVirtualKey[AntKey_KP_0] = 0x62;
qtKeyToVirtualKey[AntKey_KP_Decimal] = 0x63;
//qtKeyToVirtualKey[Qt::Key_Backslash] = 0x64;
qtKeyToVirtualKey[Qt::Key_ApplicationLeft] = 0x65;
qtKeyToVirtualKey[Qt::Key_PowerOff] = 0x66;
//qtKeyToVirtualKey[] = 0x67;
for (int i=0; i <= (Qt::Key_F24 - Qt::Key_F13); i++)
{
qtKeyToVirtualKey[Qt::Key_F13 + i] = 0x68 + i;
}
qtKeyToVirtualKey[Qt::Key_Execute] = 0x74;
qtKeyToVirtualKey[Qt::Key_Help] = 0x75;
qtKeyToVirtualKey[Qt::Key_Menu] = 0x76;
qtKeyToVirtualKey[Qt::Key_Select] = 0x77;
qtKeyToVirtualKey[Qt::Key_Stop] = 0x78;
//qtKeyToVirtualKey[] = 0x79;
qtKeyToVirtualKey[Qt::Key_Undo] = 0x7A;
qtKeyToVirtualKey[Qt::Key_Cut] = 0x7B;
qtKeyToVirtualKey[Qt::Key_Copy] = 0x7C;
qtKeyToVirtualKey[Qt::Key_Paste] = 0x7D;
qtKeyToVirtualKey[Qt::Key_Find] = 0x7E;
qtKeyToVirtualKey[Qt::Key_VolumeMute] = 0x7F;
qtKeyToVirtualKey[Qt::Key_VolumeUp] = 0x80;
qtKeyToVirtualKey[Qt::Key_VolumeDown] = 0x81;
//qtKeyToVirtualKey[] = 0x82;
//qtKeyToVirtualKey[] = 0x83;
//qtKeyToVirtualKey[] = 0x84;
//qtKeyToVirtualKey[] = 0x85;
// International Keys?
//qtKeyToVirtualKey[] = 0x87;
//qtKeyToVirtualKey[] = 0x88;
//qtKeyToVirtualKey[] = 0x89;
//qtKeyToVirtualKey[] = 0x8A;
//qtKeyToVirtualKey[] = 0x8B;
//qtKeyToVirtualKey[] = 0x8C;
//qtKeyToVirtualKey[] = 0x8D;
//qtKeyToVirtualKey[] = 0x8E;
//qtKeyToVirtualKey[] = 0x8F;
qtKeyToVirtualKey[Qt::Key_Control] = 0xE0;
qtKeyToVirtualKey[Qt::Key_Shift] = 0xE1;
qtKeyToVirtualKey[Qt::Key_Alt] = 0xE2;
qtKeyToVirtualKey[Qt::Key_Meta] = 0xE3;
qtKeyToVirtualKey[AntKey_Control_R] = 0xE4;
qtKeyToVirtualKey[AntKey_Shift_R] = 0xE5;
qtKeyToVirtualKey[AntKey_Meta_R] = 0xE7;
qtKeyToVirtualKey[Qt::Key_MediaPause] = 0xB1 | consumerUsagePagePrefix;
qtKeyToVirtualKey[Qt::Key_MediaNext] = 0xB5 | consumerUsagePagePrefix;
qtKeyToVirtualKey[Qt::Key_MediaPrevious] = 0xB6 | consumerUsagePagePrefix;
qtKeyToVirtualKey[Qt::Key_MediaStop] = 0xB7 | consumerUsagePagePrefix;
qtKeyToVirtualKey[Qt::Key_HomePage] = 0x189 | consumerUsagePagePrefix;
qtKeyToVirtualKey[Qt::Key_Launch0] = 0x194 | consumerUsagePagePrefix;
qtKeyToVirtualKey[Qt::Key_Calculator] = 0x192 | consumerUsagePagePrefix;
qtKeyToVirtualKey[Qt::Key_Favorites] = 0x22a | consumerUsagePagePrefix;
qtKeyToVirtualKey[Qt::Key_Search] = 0x221 | consumerUsagePagePrefix;
qtKeyToVirtualKey[Qt::Key_Stop] = 0x226 | consumerUsagePagePrefix;
qtKeyToVirtualKey[Qt::Key_Back] = 0x224 | consumerUsagePagePrefix;
qtKeyToVirtualKey[Qt::Key_LaunchMedia] = 0x87 | consumerUsagePagePrefix;
qtKeyToVirtualKey[Qt::Key_LaunchMail] = 0x18a | consumerUsagePagePrefix;
// Populate other hash. Flip key and value so mapping
// goes VK -> Qt Key.
QHashIterator<unsigned int, unsigned int> iter(qtKeyToVirtualKey);
while (iter.hasNext())
{
iter.next();
virtualKeyToQtKey[iter.value()] = iter.key();
}
}
}
void QtVMultiKeyMapper::populateCharKeyInformation()
{
}
``` | /content/code_sandbox/src/qtvmultikeymapper.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 2,328 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef MAINSETTINGSDIALOG_H
#define MAINSETTINGSDIALOG_H
#include <QDialog>
#include <QTableWidgetItem>
#include <QHash>
#include <QList>
#include <QSettings>
#include <QMap>
#include "autoprofileinfo.h"
#include "inputdevice.h"
#include "antimicrosettings.h"
namespace Ui {
class MainSettingsDialog;
}
class MainSettingsDialog : public QDialog
{
Q_OBJECT
public:
explicit MainSettingsDialog(AntiMicroSettings *settings, QList<InputDevice*> *devices, QWidget *parent = 0);
~MainSettingsDialog();
protected:
void fillControllerMappingsTable();
void insertTempControllerMapping(QHash<QString, QList<QVariant> > &hash, QString newGUID);
void checkLocaleChange();
void populateAutoProfiles();
void fillAutoProfilesTable(QString guid);
void fillAllAutoProfilesTable();
void clearAutoProfileData();
void changePresetLanguage();
void fillSpringScreenPresets();
void refreshExtraMouseInfo();
AntiMicroSettings *settings;
// GUID, AutoProfileInfo*
// Default profiles assigned to a specific device
QMap<QString, AutoProfileInfo*> defaultAutoProfiles;
// GUID, QList<AutoProfileInfo*>
// Profiles assigned with an association with an application
QMap<QString, QList<AutoProfileInfo*> > deviceAutoProfiles;
// Path, QList<AutoProfileInfo*>
// TODO: CHECK IF NEEDED ANYMORE
QMap<QString, QList<AutoProfileInfo*> > exeAutoProfiles;
QList<AutoProfileInfo*> defaultList;
QList<AutoProfileInfo*> profileList;
AutoProfileInfo* allDefaultProfile;
QList<InputDevice*> *connectedDevices;
private:
Ui::MainSettingsDialog *ui;
signals:
void changeLanguage(QString language);
protected slots:
void mappingsTableItemChanged(QTableWidgetItem *item);
void insertMappingRow();
void deleteMappingRow();
void syncMappingSettings();
void saveNewSettings();
void selectDefaultProfileDir();
void fillGUIDComboBox();
void changeDeviceForProfileTable(int index);
void saveAutoProfileSettings();
void processAutoProfileActiveClick(QTableWidgetItem *item);
void openAddAutoProfileDialog();
void openEditAutoProfileDialog();
void openDeleteAutoProfileConfirmDialog();
void changeAutoProfileButtonsState();
void transferEditsToCurrentTableRow();
void transferAllProfileEditToCurrentTableRow();
void addNewAutoProfile();
void autoProfileButtonsActiveState(bool enabled);
void changeKeyRepeatWidgetsStatus(bool enabled);
void checkSmoothingWidgetStatus(bool enabled);
void resetMouseAcceleration();
void selectLogFile();
};
#endif // MAINSETTINGSDIALOG_H
``` | /content/code_sandbox/src/mainsettingsdialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 666 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef SETJOYSTICK_H
#define SETJOYSTICK_H
#include <QObject>
#include <QHash>
#include <QList>
#include <QTimer>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include "joyaxis.h"
#include "joycontrolstick.h"
#include "joydpad.h"
#include "joybutton.h"
#include "vdpad.h"
class InputDevice;
class SetJoystick : public QObject
{
Q_OBJECT
public:
explicit SetJoystick(InputDevice *device, int index, QObject *parent=0);
explicit SetJoystick(InputDevice *device, int index, bool runreset, QObject *parent=0);
~SetJoystick();
JoyAxis* getJoyAxis(int index);
JoyButton* getJoyButton(int index);
JoyDPad* getJoyDPad(int index);
JoyControlStick* getJoyStick(int index);
VDPad *getVDPad(int index);
int getNumberButtons ();
int getNumberAxes();
int getNumberHats();
int getNumberSticks();
int getNumberVDPads();
int getIndex();
unsigned int getRealIndex();
virtual void refreshButtons ();
virtual void refreshAxes();
virtual void refreshHats();
void release();
void addControlStick(int index, JoyControlStick *stick);
void removeControlStick(int index);
void addVDPad(int index, VDPad *vdpad);
void removeVDPad(int index);
void setIgnoreEventState(bool ignore);
InputDevice* getInputDevice();
void setName(QString name);
QString getName();
QString getSetLabel();
void raiseAxesDeadZones(int deadZone=0);
void currentAxesDeadZones(QList<int> *axesDeadZones);
void setAxesDeadZones(QList<int> *axesDeadZones);
void setAxisThrottle(int axisNum, JoyAxis::ThrottleTypes throttle);
virtual void readConfig(QXmlStreamReader *xml);
virtual void writeConfig(QXmlStreamWriter *xml);
static const int MAXNAMELENGTH;
static const int RAISEDDEADZONE;
protected:
bool isSetEmpty();
void deleteButtons();
void deleteAxes();
void deleteHats();
void deleteSticks();
void deleteVDpads();
void enableButtonConnections(JoyButton *button);
void enableAxisConnections(JoyAxis *axis);
void enableHatConnections(JoyDPad *dpad);
QHash<int, JoyButton*> buttons;
QHash<int, JoyAxis*> axes;
QHash<int, JoyDPad*> hats;
QHash<int, JoyControlStick*> sticks;
QHash<int, VDPad*> vdpads;
int index;
InputDevice *device;
QString name;
signals:
void setChangeActivated(int index);
void setAssignmentButtonChanged(int button, int originset, int newset, int mode);
void setAssignmentAxisChanged(int button, int axis, int originset, int newset, int mode);
void setAssignmentStickChanged(int button, int stick, int originset, int newset, int mode);
void setAssignmentDPadChanged(int button, int dpad, int originset, int newset, int mode);
void setAssignmentVDPadChanged(int button, int dpad, int originset, int newset, int mode);
void setAssignmentAxisThrottleChanged(int axis, int originset);
void setButtonClick(int index, int button);
void setButtonRelease(int index, int button);
void setAxisButtonClick(int setindex, int axis, int button);
void setAxisButtonRelease(int setindex, int axis, int button);
void setAxisActivated(int setindex, int axis, int value);
void setAxisReleased(int setindex, int axis, int value);
void setStickButtonClick(int setindex, int stick, int button);
void setStickButtonRelease(int setindex, int stick, int button);
void setDPadButtonClick(int setindex, int dpad, int button);
void setDPadButtonRelease(int setindex, int dpad, int button);
void setButtonNameChange(int index);
void setAxisButtonNameChange(int axisIndex, int buttonIndex);
void setStickButtonNameChange(int stickIndex, int buttonIndex);
void setDPadButtonNameChange(int dpadIndex, int buttonIndex);
void setVDPadButtonNameChange(int vdpadIndex, int buttonIndex);
void setAxisNameChange(int axisIndex);
void setStickNameChange(int stickIndex);
void setDPadNameChange(int dpadIndex);
void setVDPadNameChange(int vdpadIndex);
void propertyUpdated();
public slots:
virtual void reset();
void copyAssignments(SetJoystick *destSet);
void propogateSetChange(int index);
void propogateSetButtonAssociation(int button, int newset, int mode);
void propogateSetAxisButtonAssociation(int button, int axis, int newset, int mode);
void propogateSetStickButtonAssociation(int button, int stick, int newset, int mode);
void propogateSetDPadButtonAssociation(int button, int dpad, int newset, int mode);
void propogateSetVDPadButtonAssociation(int button, int dpad, int newset, int mode);
void establishPropertyUpdatedConnection();
void disconnectPropertyUpdatedConnection();
protected slots:
void propogateSetAxisThrottleSetting(int index);
void propogateSetButtonClick(int button);
void propogateSetButtonRelease(int button);
void propogateSetAxisButtonClick(int button);
void propogateSetAxisButtonRelease(int button);
void propogateSetStickButtonClick(int button);
void propogateSetStickButtonRelease(int button);
void propogateSetDPadButtonClick(int button);
void propogateSetDPadButtonRelease(int button);
void propogateSetAxisActivated(int value);
void propogateSetAxisReleased(int value);
void propogateSetButtonNameChange();
void propogateSetAxisButtonNameChange();
void propogateSetStickButtonNameChange();
void propogateSetDPadButtonNameChange();
void propogateSetVDPadButtonNameChange();
void propogateSetAxisNameChange();
void propogateSetStickNameChange();
void propogateSetDPadNameChange();
void propogateSetVDPadNameChange();
};
Q_DECLARE_METATYPE(SetJoystick*)
#endif // SETJOYSTICK_H
``` | /content/code_sandbox/src/setjoystick.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,506 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef SPRINGMOUSEMOVEINFO_H
#define SPRINGMOUSEMOVEINFO_H
namespace PadderCommon {
typedef struct _springModeInfo
{
// Displacement of the X axis
double displacementX;
// Displacement of the Y axis
double displacementY;
// Width and height of the spring mode box
unsigned int width;
unsigned int height;
// Should the cursor not move around the center
// of the screen.
bool relative;
int screen;
double springDeadX;
double springDeadY;
} springModeInfo;
}
#endif // SPRINGMOUSEMOVEINFO_H
``` | /content/code_sandbox/src/springmousemoveinfo.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 232 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include "joycontrolstickpushbutton.h"
#include "joycontrolstickcontextmenu.h"
JoyControlStickPushButton::JoyControlStickPushButton(JoyControlStick *stick, bool displayNames, QWidget *parent) :
FlashButtonWidget(displayNames, parent)
{
this->stick = stick;
refreshLabel();
tryFlash();
this->setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showContextMenu(const QPoint&)));
connect(stick, SIGNAL(active(int, int)), this, SLOT(flash()), Qt::QueuedConnection);
connect(stick, SIGNAL(released(int, int)), this, SLOT(unflash()), Qt::QueuedConnection);
connect(stick, SIGNAL(stickNameChanged()), this, SLOT(refreshLabel()));
}
JoyControlStick* JoyControlStickPushButton::getStick()
{
return stick;
}
/**
* @brief Generate the string that will be displayed on the button
* @return Display string
*/
QString JoyControlStickPushButton::generateLabel()
{
QString temp;
if (!stick->getStickName().isEmpty() && displayNames)
{
temp.append(stick->getPartialName(false, true));
}
else
{
temp.append(stick->getPartialName(false));
}
return temp;
}
void JoyControlStickPushButton::disableFlashes()
{
disconnect(stick, SIGNAL(active(int, int)), this, SLOT(flash()));
disconnect(stick, SIGNAL(released(int, int)), this, SLOT(unflash()));
this->unflash();
}
void JoyControlStickPushButton::enableFlashes()
{
connect(stick, SIGNAL(active(int, int)), this, SLOT(flash()), Qt::QueuedConnection);
connect(stick, SIGNAL(released(int, int)), this, SLOT(unflash()), Qt::QueuedConnection);
}
void JoyControlStickPushButton::showContextMenu(const QPoint &point)
{
QPoint globalPos = this->mapToGlobal(point);
JoyControlStickContextMenu *contextMenu = new JoyControlStickContextMenu(stick, this);
contextMenu->buildMenu();
contextMenu->popup(globalPos);
}
void JoyControlStickPushButton::tryFlash()
{
if (stick->getCurrentDirection() != JoyControlStick::StickCentered)
{
flash();
}
}
``` | /content/code_sandbox/src/joycontrolstickpushbutton.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 579 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
//#include <QDebug>
#include "setaxisthrottledialog.h"
#include "ui_setaxisthrottledialog.h"
SetAxisThrottleDialog::SetAxisThrottleDialog(JoyAxis *axis, QWidget *parent) :
QDialog(parent),
ui(new Ui::SetAxisThrottleDialog)
{
ui->setupUi(this);
this->axis = axis;
QString currentText = ui->label->text();
currentText = currentText.arg(QString::number(axis->getRealJoyIndex()));
ui->label->setText(currentText);
connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(propogateThrottleChange()));
connect(this, SIGNAL(initiateSetAxisThrottleChange()), axis, SLOT(propogateThrottleChange()));
}
SetAxisThrottleDialog::~SetAxisThrottleDialog()
{
delete ui;
}
void SetAxisThrottleDialog::propogateThrottleChange()
{
emit initiateSetAxisThrottleChange();
}
``` | /content/code_sandbox/src/setaxisthrottledialog.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 301 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef JOYBUTTONWIDGET_H
#define JOYBUTTONWIDGET_H
#include <QPoint>
#include "flashbuttonwidget.h"
#include "joybutton.h"
class JoyButtonWidget : public FlashButtonWidget
{
Q_OBJECT
public:
explicit JoyButtonWidget(JoyButton* button, bool displayNames, QWidget *parent=0);
JoyButton* getJoyButton();
void tryFlash();
protected:
virtual QString generateLabel();
JoyButton* button;
signals:
public slots:
void disableFlashes();
void enableFlashes();
private slots:
void showContextMenu(const QPoint &point);
};
#endif // JOYBUTTONWIDGET_H
``` | /content/code_sandbox/src/joybuttonwidget.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 234 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include "inputdevicebitarraystatus.h"
InputDeviceBitArrayStatus::InputDeviceBitArrayStatus(InputDevice *device, bool readCurrent, QObject *parent) :
QObject(parent)
{
for (int i=0; i < device->getNumberRawAxes(); i++)
{
SetJoystick *currentSet = device->getActiveSetJoystick();
JoyAxis *axis = currentSet->getJoyAxis(i);
if (axis && readCurrent)
{
axesStatus.append(!axis->inDeadZone(axis->getCurrentRawValue()) ? true : false);
}
else
{
axesStatus.append(false);
}
}
for (int i=0; i < device->getNumberRawHats(); i++)
{
SetJoystick *currentSet = device->getActiveSetJoystick();
JoyDPad *dpad = currentSet->getJoyDPad(i);
if (dpad && readCurrent)
{
hatButtonStatus.append(dpad->getCurrentDirection() != JoyDPadButton::DpadCentered ? true : false);
}
else
{
hatButtonStatus.append(false);
}
}
buttonStatus.resize(device->getNumberRawButtons());
buttonStatus.fill(0);
for (int i=0; i < device->getNumberRawButtons(); i++)
{
SetJoystick *currentSet = device->getActiveSetJoystick();
JoyButton *button = currentSet->getJoyButton(i);
if (button && readCurrent)
{
buttonStatus.setBit(i, button->getButtonState());
}
}
}
void InputDeviceBitArrayStatus::changeAxesStatus(int axisIndex, bool value)
{
if (axisIndex >= 0 && axisIndex <= axesStatus.size())
{
axesStatus.replace(axisIndex, value);
}
}
void InputDeviceBitArrayStatus::changeButtonStatus(int buttonIndex, bool value)
{
if (buttonIndex >= 0 && buttonIndex <= buttonStatus.size())
{
buttonStatus.setBit(buttonIndex, value);
}
}
void InputDeviceBitArrayStatus::changeHatStatus(int hatIndex, bool value)
{
if (hatIndex >= 0 && hatIndex <= hatButtonStatus.size())
{
hatButtonStatus.replace(hatIndex, value);
}
}
QBitArray InputDeviceBitArrayStatus::generateFinalBitArray()
{
unsigned int totalArraySize = 0;
totalArraySize = axesStatus.size() + hatButtonStatus.size() + buttonStatus.size();
QBitArray aggregateBitArray(totalArraySize, false);
unsigned int currentBit = 0;
for (int i=0; i < axesStatus.size(); i++)
{
aggregateBitArray.setBit(currentBit, axesStatus.at(i));
currentBit++;
}
for (int i=0; i < hatButtonStatus.size(); i++)
{
aggregateBitArray.setBit(currentBit, hatButtonStatus.at(i));
currentBit++;
}
for (int i=0; i < buttonStatus.size(); i++)
{
aggregateBitArray.setBit(currentBit, buttonStatus.at(i));
currentBit++;
}
return aggregateBitArray;
}
void InputDeviceBitArrayStatus::clearStatusValues()
{
for (int i=0; i < axesStatus.size(); i++)
{
axesStatus.replace(i, false);
}
for (int i=0; i < hatButtonStatus.size(); i++)
{
hatButtonStatus.replace(i, false);
}
buttonStatus.fill(false);
}
``` | /content/code_sandbox/src/inputdevicebitarraystatus.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 856 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef JOYDPADBUTTONWIDGET_H
#define JOYDPADBUTTONWIDGET_H
#include "joybuttonwidget.h"
class JoyDPadButtonWidget : public JoyButtonWidget
{
Q_OBJECT
public:
explicit JoyDPadButtonWidget(JoyButton* button, bool displayNames, QWidget *parent = 0);
protected:
virtual QString generateLabel();
signals:
public slots:
};
#endif // JOYDPADBUTTONWIDGET_H
``` | /content/code_sandbox/src/joydpadbuttonwidget.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 192 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
//#include <QDebug>
#include <QActionGroup>
#include "joybuttoncontextmenu.h"
#include "inputdevice.h"
#include "common.h"
JoyButtonContextMenu::JoyButtonContextMenu(JoyButton *button, QWidget *parent) :
QMenu(parent)
{
this->button = button;
connect(this, SIGNAL(aboutToHide()), this, SLOT(deleteLater()));
}
void JoyButtonContextMenu::buildMenu()
{
QAction *action = 0;
PadderCommon::inputDaemonMutex.lock();
action = this->addAction(tr("Toggle"));
action->setCheckable(true);
action->setChecked(button->getToggleState());
connect(action, SIGNAL(triggered()), this, SLOT(switchToggle()));
action = this->addAction(tr("Turbo"));
action->setCheckable(true);
action->setChecked(button->isUsingTurbo());
connect(action, SIGNAL(triggered()), this, SLOT(switchToggle()));
this->addSeparator();
action = this->addAction(tr("Clear"));
action->setCheckable(false);
connect(action, SIGNAL(triggered()), this, SLOT(clearButton()));
this->addSeparator();
QMenu *setSectionMenu = this->addMenu(tr("Set Select"));
action = setSectionMenu->addAction(tr("Disabled"));
if (button->getChangeSetCondition() == JoyButton::SetChangeDisabled)
{
action->setCheckable(true);
action->setChecked(true);
}
connect(action, SIGNAL(triggered()), this, SLOT(disableSetMode()));
setSectionMenu->addSeparator();
for (int i=0; i < InputDevice::NUMBER_JOYSETS; i++)
{
QMenu *tempSetMenu = setSectionMenu->addMenu(tr("Set %1").arg(i+1));
int setSelection = i*3;
if (i == button->getSetSelection())
{
QFont tempFont = tempSetMenu->menuAction()->font();
tempFont.setBold(true);
tempSetMenu->menuAction()->setFont(tempFont);
}
QActionGroup *tempGroup = new QActionGroup(tempSetMenu);
action = tempSetMenu->addAction(tr("Set %1 1W").arg(i+1));
action->setData(QVariant(setSelection + 0));
action->setCheckable(true);
if (button->getSetSelection() == i &&
button->getChangeSetCondition() == JoyButton::SetChangeOneWay)
{
action->setChecked(true);
}
connect(action, SIGNAL(triggered()), this, SLOT(switchSetMode()));
tempGroup->addAction(action);
action = tempSetMenu->addAction(tr("Set %1 2W").arg(i+1));
action->setData(QVariant(setSelection + 1));
action->setCheckable(true);
if (button->getSetSelection() == i &&
button->getChangeSetCondition() == JoyButton::SetChangeTwoWay)
{
action->setChecked(true);
}
connect(action, SIGNAL(triggered()), this, SLOT(switchSetMode()));
tempGroup->addAction(action);
action = tempSetMenu->addAction(tr("Set %1 WH").arg(i+1));
action->setData(QVariant(setSelection + 2));
action->setCheckable(true);
if (button->getSetSelection() == i &&
button->getChangeSetCondition() == JoyButton::SetChangeWhileHeld)
{
action->setChecked(true);
}
connect(action, SIGNAL(triggered()), this, SLOT(switchSetMode()));
tempGroup->addAction(action);
if (i == button->getParentSet()->getIndex())
{
tempSetMenu->setEnabled(false);
}
}
PadderCommon::inputDaemonMutex.unlock();
}
void JoyButtonContextMenu::switchToggle()
{
PadderCommon::inputDaemonMutex.lock();
button->setToggle(!button->getToggleState());
PadderCommon::inputDaemonMutex.unlock();
}
void JoyButtonContextMenu::switchTurbo()
{
PadderCommon::inputDaemonMutex.lock();
button->setToggle(!button->isUsingTurbo());
PadderCommon::inputDaemonMutex.unlock();
}
void JoyButtonContextMenu::switchSetMode()
{
QAction *action = static_cast<QAction*>(sender());
int item = action->data().toInt();
int setSelection = item / 3;
int setChangeCondition = item % 3;
JoyButton::SetChangeCondition temp;
if (setChangeCondition == 0)
{
temp = JoyButton::SetChangeOneWay;
}
else if (setChangeCondition == 1)
{
temp = JoyButton::SetChangeTwoWay;
}
else if (setChangeCondition == 2)
{
temp = JoyButton::SetChangeWhileHeld;
}
PadderCommon::inputDaemonMutex.lock();
// First, remove old condition for the button in both sets.
// After that, make the new assignment.
button->setChangeSetCondition(JoyButton::SetChangeDisabled);
button->setChangeSetSelection(setSelection);
button->setChangeSetCondition(temp);
PadderCommon::inputDaemonMutex.unlock();
}
void JoyButtonContextMenu::disableSetMode()
{
PadderCommon::inputDaemonMutex.lock();
button->setChangeSetCondition(JoyButton::SetChangeDisabled);
PadderCommon::inputDaemonMutex.unlock();
}
void JoyButtonContextMenu::clearButton()
{
QMetaObject::invokeMethod(button, "clearSlotsEventReset");
}
``` | /content/code_sandbox/src/joybuttoncontextmenu.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,265 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include "mousehelper.h"
MouseHelper::MouseHelper(QObject *parent) :
QObject(parent)
{
springMouseMoving = false;
previousCursorLocation[0] = 0;
previousCursorLocation[1] = 0;
pivotPoint[0] = -1;
pivotPoint[1] = -1;
mouseTimer.setParent(this);
mouseTimer.setSingleShot(true);
QObject::connect(&mouseTimer, SIGNAL(timeout()), this, SLOT(resetSpringMouseMoving()));
}
void MouseHelper::resetSpringMouseMoving()
{
springMouseMoving = false;
}
void MouseHelper::initDeskWid()
{
if (!deskWid)
{
deskWid = new QDesktopWidget;
}
}
void MouseHelper::deleteDeskWid()
{
if (deskWid)
{
delete deskWid;
deskWid = 0;
}
}
QDesktopWidget* MouseHelper::getDesktopWidget()
{
return deskWid;
}
``` | /content/code_sandbox/src/mousehelper.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 306 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef SETAXISTHROTTLEDIALOG_H
#define SETAXISTHROTTLEDIALOG_H
#include <QDialog>
#include "joyaxis.h"
namespace Ui {
class SetAxisThrottleDialog;
}
class SetAxisThrottleDialog : public QDialog
{
Q_OBJECT
public:
explicit SetAxisThrottleDialog(JoyAxis *axis, QWidget *parent = 0);
~SetAxisThrottleDialog();
private:
Ui::SetAxisThrottleDialog *ui;
protected:
JoyAxis *axis;
signals:
void initiateSetAxisThrottleChange();
private slots:
void propogateThrottleChange();
};
#endif // SETAXISTHROTTLEDIALOG_H
``` | /content/code_sandbox/src/setaxisthrottledialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 243 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
//#include <QDebug>
#include <QHash>
#include <QHashIterator>
#include <QMapIterator>
#include <QLocalSocket>
#include <QTextStream>
#include <QDesktopServices>
#include <QUrl>
#include <QMessageBox>
#include <QLibraryInfo>
#ifdef Q_OS_WIN
#include <QSysInfo>
#endif
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "joyaxiswidget.h"
#include "joybuttonwidget.h"
#include "joycontrolstickpushbutton.h"
#include "joytabwidget.h"
#include "joydpadbuttonwidget.h"
#include "joycontrolstickbuttonpushbutton.h"
#include "dpadpushbutton.h"
#include "joystickstatuswindow.h"
#include "qkeydisplaydialog.h"
#include "mainsettingsdialog.h"
#include "advancestickassignmentdialog.h"
#include "common.h"
#ifdef USE_SDL_2
#include "gamecontrollermappingdialog.h"
#if defined(WITH_X11) || defined(Q_OS_WIN)
#include "autoprofileinfo.h"
#endif
#endif
#ifdef Q_OS_WIN
#include "winextras.h"
#endif
#ifdef Q_OS_UNIX
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
#include <QApplication>
#endif
#endif
MainWindow::MainWindow(QMap<SDL_JoystickID, InputDevice*> *joysticks,
CommandLineUtility *cmdutility, AntiMicroSettings *settings,
bool graphical, QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->stackedWidget->setCurrentIndex(0);
this->translator = 0;
this->appTranslator = 0;
this->cmdutility = cmdutility;
this->graphical = graphical;
this->settings = settings;
ui->actionStick_Pad_Assign->setVisible(false);
#ifndef USE_SDL_2
ui->actionGameController_Mapping->setVisible(false);
#endif
#ifdef Q_OS_UNIX
#if defined(USE_SDL_2) && defined(WITH_X11)
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
this->appWatcher = new AutoProfileWatcher(settings, this);
checkAutoProfileWatcherTimer();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
else
{
this->appWatcher = 0;
}
#endif
#endif
#elif defined(Q_OS_WIN)
this->appWatcher = new AutoProfileWatcher(settings, this);
checkAutoProfileWatcherTimer();
#else
this->appWatcher = 0;
#endif
signalDisconnect = false;
showTrayIcon = !cmdutility->isTrayHidden() && graphical &&
!cmdutility->shouldListControllers() && !cmdutility->shouldMapController();
this->joysticks = joysticks;
if (showTrayIcon)
{
trayIconMenu = new QMenu(this);
trayIcon = new QSystemTrayIcon(this);
trayIcon->setContextMenu(trayIconMenu);
connect(trayIconMenu, SIGNAL(aboutToShow()), this, SLOT(refreshTrayIconMenu()));
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(trayIconClickAction(QSystemTrayIcon::ActivationReason)));
}
// Look at flags and call setEnabled as desired; defaults to true.
// Enabled status is used to specify whether errors in profile loading and
// saving should be display in a window or written to stderr.
if (graphical)
{
if (cmdutility->isHiddenRequested() && cmdutility->isTrayHidden())
{
setEnabled(false);
}
}
else
{
setEnabled(false);
}
resize(settings->value("WindowSize", size()).toSize());
move(settings->value("WindowPosition", pos()).toPoint());
if (graphical)
{
aboutDialog = new AboutDialog(this);
}
else
{
aboutDialog = 0;
}
connect(ui->menuQuit, SIGNAL(aboutToShow()), this, SLOT(mainMenuChange()));
connect(ui->menuOptions, SIGNAL(aboutToShow()), this, SLOT(mainMenuChange()));
connect(ui->actionKeyValue, SIGNAL(triggered()), this, SLOT(openKeyCheckerDialog()));
connect(ui->actionAbout_Qt, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(ui->actionProperties, SIGNAL(triggered()), this, SLOT(openJoystickStatusWindow()));
connect(ui->actionGitHubPage, SIGNAL(triggered()), this, SLOT(openGitHubPage()));
connect(ui->actionOptions, SIGNAL(triggered()), this, SLOT(openMainSettingsDialog()));
connect(ui->actionWiki, SIGNAL(triggered()), this, SLOT(openWikiPage()));
connect(ui->updateButton, &QPushButton::pressed, this, &MainWindow::updateButtonPressed);
#ifdef USE_SDL_2
connect(ui->actionGameController_Mapping, SIGNAL(triggered()), this, SLOT(openGameControllerMappingWindow()));
#if defined(Q_OS_UNIX) && defined(WITH_X11)
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
connect(appWatcher, SIGNAL(foundApplicableProfile(AutoProfileInfo*)), this, SLOT(autoprofileLoad(AutoProfileInfo*)));
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
#endif
#elif defined(Q_OS_WIN)
connect(appWatcher, SIGNAL(foundApplicableProfile(AutoProfileInfo*)), this, SLOT(autoprofileLoad(AutoProfileInfo*)));
#endif
#endif
#ifdef Q_OS_WIN
if (graphical)
{
if (!WinExtras::IsRunningAsAdmin())
{
if (QSysInfo::windowsVersion() >= QSysInfo::WV_VISTA)
{
QIcon uacIcon = QApplication::style()->standardIcon(QStyle::SP_VistaShield);
ui->uacPushButton->setIcon(uacIcon);
}
connect(ui->uacPushButton, SIGNAL(clicked()), this, SLOT(restartAsElevated()));
}
else
{
ui->uacPushButton->setVisible(false);
}
}
#else
ui->uacPushButton->setVisible(false);
#endif
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::alterConfigFromSettings()
{
if (cmdutility->shouldListControllers())
{
graphical = false;
this->graphical = graphical;
}
else if (cmdutility->hasProfile())
{
if (cmdutility->hasControllerNumber())
{
loadConfigFile(cmdutility->getProfileLocation(),
cmdutility->getControllerNumber());
}
else if (cmdutility->hasControllerID())
{
loadConfigFile(cmdutility->getProfileLocation(),
cmdutility->hasControllerID());
}
else
{
loadConfigFile(cmdutility->getProfileLocation());
}
}
QList<ControllerOptionsInfo> *tempList = cmdutility->getControllerOptionsList();
//unsigned int optionListSize = tempList->size();
QListIterator<ControllerOptionsInfo> optionIter(*tempList);
while (optionIter.hasNext())
{
ControllerOptionsInfo temp = optionIter.next();
if (temp.hasProfile())
{
if (temp.hasControllerNumber())
{
loadConfigFile(temp.getProfileLocation(),
temp.getControllerNumber());
}
else if (temp.hasControllerID())
{
loadConfigFile(temp.getProfileLocation(),
temp.hasControllerID());
}
else
{
loadConfigFile(temp.getProfileLocation());
}
}
else if (temp.isUnloadRequested())
{
if (temp.hasControllerNumber())
{
unloadCurrentConfig(temp.getControllerNumber());
}
else if (temp.hasControllerID())
{
unloadCurrentConfig(temp.hasControllerID());
}
else
{
unloadCurrentConfig(0);
}
}
if (temp.getStartSetNumber() > 0)
{
if (temp.hasControllerNumber())
{
changeStartSetNumber(temp.getJoyStartSetNumber(),
temp.getControllerNumber());
}
else if (temp.hasControllerID())
{
changeStartSetNumber(temp.getJoyStartSetNumber(),
temp.getControllerID());
}
else
{
changeStartSetNumber(temp.getJoyStartSetNumber());
}
}
}
}
#ifdef USE_SDL_2
void MainWindow::controllerMapOpening()
{
if (cmdutility->shouldMapController())
{
graphical = false;
this->graphical = graphical;
QList<ControllerOptionsInfo> *tempList = cmdutility->getControllerOptionsList();
ControllerOptionsInfo temp = tempList->at(0);
if (temp.hasControllerNumber())
{
unsigned int joypadIndex = cmdutility->getControllerNumber();
selectControllerJoyTab(joypadIndex);
openGameControllerMappingWindow(true);
}
else if (temp.hasControllerID())
{
QString joypadGUID = cmdutility->getControllerID();
selectControllerJoyTab(joypadGUID);
openGameControllerMappingWindow(true);
}
else
{
Logger::LogInfo(tr("Could not find a proper controller identifier. "
"Exiting."));
qApp->quit();
}
}
}
#endif
void MainWindow::fillButtons()
{
fillButtons(joysticks);
}
void MainWindow::makeJoystickTabs()
{
ui->stackedWidget->setCurrentIndex(0);
removeJoyTabs();
#ifdef USE_SDL_2
// Make temporary QMap with devices inserted using the device index as the
// key rather than joystick ID.
QMap<SDL_JoystickID, InputDevice*> temp;
QMapIterator<SDL_JoystickID, InputDevice*> iterTemp(*joysticks);
while (iterTemp.hasNext())
{
iterTemp.next();
InputDevice *joystick = iterTemp.value();
temp.insert(joystick->getJoyNumber(), joystick);
}
QMapIterator<SDL_JoystickID, InputDevice*> iter(temp);
#else
QMapIterator<SDL_JoystickID, InputDevice*> iter(*joysticks);
#endif
while (iter.hasNext())
{
iter.next();
InputDevice *joystick = iter.value();
JoyTabWidget *tabwidget = new JoyTabWidget(joystick, settings, this);
QString joytabName = joystick->getSDLName();
joytabName.append(" ").append(tr("(%1)").arg(joystick->getName()));
ui->tabWidget->addTab(tabwidget, joytabName);
}
if (joysticks->size() > 0)
{
ui->tabWidget->setCurrentIndex(0);
ui->stackedWidget->setCurrentIndex(1);
}
}
void MainWindow::fillButtons(InputDevice *joystick)
{
int joyindex = joystick->getJoyNumber();
JoyTabWidget *tabwidget = static_cast<JoyTabWidget*>(ui->tabWidget->widget(joyindex));
tabwidget->refreshButtons();
}
void MainWindow::fillButtons(QMap<SDL_JoystickID, InputDevice *> *joysticks)
{
ui->stackedWidget->setCurrentIndex(0);
removeJoyTabs();
#ifdef USE_SDL_2
// Make temporary QMap with devices inserted using the device index as the
// key rather than joystick ID.
QMap<SDL_JoystickID, InputDevice*> temp;
QMapIterator<SDL_JoystickID, InputDevice*> iterTemp(*joysticks);
while (iterTemp.hasNext())
{
iterTemp.next();
InputDevice *joystick = iterTemp.value();
temp.insert(joystick->getJoyNumber(), joystick);
}
QMapIterator<SDL_JoystickID, InputDevice*> iter(temp);
#else
QMapIterator<SDL_JoystickID, InputDevice*> iter(*joysticks);
#endif
while (iter.hasNext())
{
iter.next();
InputDevice *joystick = iter.value();
JoyTabWidget *tabwidget = new JoyTabWidget(joystick, settings, this);
QString joytabName = joystick->getSDLName();
joytabName.append(" ").append(tr("(%1)").arg(joystick->getName()));
ui->tabWidget->addTab(tabwidget, joytabName);
tabwidget->refreshButtons();
connect(tabwidget, SIGNAL(namesDisplayChanged(bool)), this, SLOT(propogateNameDisplayStatus(bool)));
#ifdef USE_SDL_2
connect(tabwidget, SIGNAL(mappingUpdated(QString,InputDevice*)), this, SLOT(propogateMappingUpdate(QString,InputDevice*)));
#endif
if (showTrayIcon)
{
connect(tabwidget, SIGNAL(joystickConfigChanged(int)), this, SLOT(populateTrayIcon()));
}
}
if (joysticks->size() > 0)
{
loadAppConfig();
ui->tabWidget->setCurrentIndex(0);
ui->stackedWidget->setCurrentIndex(1);
}
if (showTrayIcon)
{
trayIcon->hide();
populateTrayIcon();
trayIcon->show();
}
ui->actionUpdate_Joysticks->setEnabled(true);
ui->actionHide->setEnabled(true);
ui->actionQuit->setEnabled(true);
}
// Intermediate slot to be used in Form Designer
void MainWindow::startJoystickRefresh()
{
ui->stackedWidget->setCurrentIndex(0);
ui->actionUpdate_Joysticks->setEnabled(false);
ui->actionHide->setEnabled(false);
ui->actionQuit->setEnabled(false);
removeJoyTabs();
emit joystickRefreshRequested();
}
void MainWindow::populateTrayIcon()
{
disconnect(trayIconMenu, SIGNAL(aboutToShow()), this, SLOT(singleTrayProfileMenuShow()));
trayIconMenu->clear();
profileActions.clear();
unsigned int joystickCount = joysticks->size();
if (joystickCount > 0)
{
QMapIterator<SDL_JoystickID, InputDevice*> iter(*joysticks);
bool useSingleList = settings->value("TrayProfileList", false).toBool();
if (!useSingleList && joystickCount == 1)
{
useSingleList = true;
}
int i = 0;
while (iter.hasNext())
{
iter.next();
InputDevice *current = iter.value();
QString joytabName = current->getSDLName();
joytabName.append(" ").append(tr("(%1)").arg(current->getName()));
QMenu *joysticksubMenu = 0;
if (!useSingleList)
{
joysticksubMenu = trayIconMenu->addMenu(joytabName);
}
JoyTabWidget *widget = static_cast<JoyTabWidget*>(ui->tabWidget->widget(i));
if (widget)
{
QHash<int, QString> *configs = widget->recentConfigs();
QHashIterator<int, QString> configIter(*configs);
QList<QAction*> tempProfileList;
while (configIter.hasNext())
{
configIter.next();
QAction *newaction = 0;
if (joysticksubMenu)
{
newaction = new QAction(configIter.value(), joysticksubMenu);
}
else
{
newaction = new QAction(configIter.value(), trayIconMenu);
}
newaction->setCheckable(true);
newaction->setChecked(false);
if (configIter.key() == widget->getCurrentConfigIndex())
{
newaction->setChecked(true);
}
QHash<QString, QVariant> tempmap;
tempmap.insert(QString::number(i), QVariant (configIter.key()));
QVariant tempvar (tempmap);
newaction->setData(tempvar);
connect(newaction, SIGNAL(triggered(bool)), this, SLOT(profileTrayActionTriggered(bool)));
if (useSingleList)
{
tempProfileList.append(newaction);
}
else
{
joysticksubMenu->addAction(newaction);
}
}
delete configs;
configs = 0;
QAction *newaction = 0;
if (joysticksubMenu)
{
newaction = new QAction(tr("Open File"), joysticksubMenu);
}
else
{
newaction = new QAction(tr("Open File"), trayIconMenu);
}
newaction->setIcon(QIcon::fromTheme("document-open"));
connect(newaction, SIGNAL(triggered()), widget, SLOT(openConfigFileDialog()));
if (useSingleList)
{
QAction *titleAction = new QAction(joytabName, trayIconMenu);
titleAction->setCheckable(false);
QFont actionFont = titleAction->font();
actionFont.setBold(true);
titleAction->setFont(actionFont);
trayIconMenu->addAction(titleAction);
trayIconMenu->addActions(tempProfileList);
trayIconMenu->addAction(newaction);
profileActions.insert(i, tempProfileList);
if (iter.hasNext())
{
trayIconMenu->addSeparator();
}
}
else
{
joysticksubMenu->addAction(newaction);
connect(joysticksubMenu, SIGNAL(aboutToShow()), this, SLOT(joystickTrayShow()));
}
i++;
}
}
if (useSingleList)
{
connect(trayIconMenu, SIGNAL(aboutToShow()), this, SLOT(singleTrayProfileMenuShow()));
}
trayIconMenu->addSeparator();
}
hideAction = new QAction(tr("&Hide"), trayIconMenu);
hideAction->setIcon(QIcon::fromTheme("view-restore"));
connect(hideAction, SIGNAL(triggered()), this, SLOT(hideWindow()));
restoreAction = new QAction(tr("&Restore"), trayIconMenu);
restoreAction->setIcon(QIcon::fromTheme("view-fullscreen"));
connect(restoreAction, SIGNAL(triggered()), this, SLOT(show()));
closeAction = new QAction(tr("&Quit"), trayIconMenu);
closeAction->setIcon(QIcon::fromTheme("application-exit"));
connect(closeAction, SIGNAL(triggered()), this, SLOT(quitProgram()));
updateJoy = new QAction(tr("&Update Joysticks"), trayIconMenu);
updateJoy->setIcon(QIcon::fromTheme("view-refresh"));
connect(updateJoy, SIGNAL(triggered()), this, SLOT(startJoystickRefresh()));
trayIconMenu->addAction(hideAction);
trayIconMenu->addAction(restoreAction);
trayIconMenu->addAction(updateJoy);
trayIconMenu->addAction(closeAction);
QIcon icon = QIcon::fromTheme("antimicro", QIcon(":/images/antimicro_trayicon.png"));
trayIcon->setIcon(icon);
trayIcon->setContextMenu(trayIconMenu);
}
void MainWindow::quitProgram()
{
bool discard = true;
for (int i=0; i < ui->tabWidget->count() && discard; i++)
{
JoyTabWidget *tab = static_cast<JoyTabWidget*>(ui->tabWidget->widget(i));
discard = tab->discardUnsavedProfileChanges();
}
if (discard)
{
qApp->quit();
}
}
void MainWindow::refreshTrayIconMenu()
{
if (this->isHidden())
{
hideAction->setEnabled(false);
restoreAction->setEnabled(true);
}
else
{
hideAction->setEnabled(true);
restoreAction->setEnabled(false);
}
}
void MainWindow::trayIconClickAction(QSystemTrayIcon::ActivationReason reason)
{
if (reason == QSystemTrayIcon::Trigger)
{
if (this->isHidden())
{
this->show();
}
else
{
this->hideWindow();
}
}
}
void MainWindow::mainMenuChange()
{
QMenu *tempMenu = static_cast<QMenu*>(sender());
if (tempMenu == ui->menuQuit)
{
if (showTrayIcon)
{
ui->actionHide->setEnabled(true);
}
else
{
ui->actionHide->setEnabled(false);
}
}
#ifndef USE_SDL_2
if (tempMenu == ui->menuOptions)
{
ui->actionGameController_Mapping->setVisible(false);
}
#endif
}
void MainWindow::saveAppConfig()
{
if (joysticks->size() > 0)
{
JoyTabWidget *temptabwidget = static_cast<JoyTabWidget*>(ui->tabWidget->widget(0));
settings->setValue("DisplayNames",
temptabwidget->isDisplayingNames() ? "1" : "0");
settings->beginGroup("Controllers");
QStringList tempIdentifierHolder;
for (int i=0; i < ui->tabWidget->count(); i++)
{
bool prepareSave = true;
JoyTabWidget *tabwidget = static_cast<JoyTabWidget*>(ui->tabWidget->widget(i));
InputDevice *device = tabwidget->getJoystick();
// Do not allow multi-controller adapters to overwrite each
// others recent config file list. Use first controller
// detected to save recent config list. Flag controller string
// afterwards.
if (!device->getStringIdentifier().isEmpty())
{
if (tempIdentifierHolder.contains(device->getStringIdentifier()))
{
prepareSave = false;
}
else
{
tempIdentifierHolder.append(device->getStringIdentifier());
}
}
if (prepareSave)
{
tabwidget->saveSettings();
}
}
settings->endGroup();
}
settings->setValue("WindowSize", size());
settings->setValue("WindowPosition", pos());
}
void MainWindow::loadAppConfig(bool forceRefresh)
{
for (int i=0; i < ui->tabWidget->count(); i++)
{
JoyTabWidget *tabwidget = static_cast<JoyTabWidget*>(ui->tabWidget->widget(i));
tabwidget->loadSettings(forceRefresh);
}
}
void MainWindow::disableFlashActions()
{
for (int i=0; i < ui->tabWidget->count(); i++)
{
QList<JoyButtonWidget*> list = ui->tabWidget->widget(i)->findChildren<JoyButtonWidget*>();
QListIterator<JoyButtonWidget*> iter(list);
while (iter.hasNext())
{
JoyButtonWidget *buttonWidget = iter.next();
buttonWidget->disableFlashes();
}
QList<JoyAxisWidget*> list2 = ui->tabWidget->widget(i)->findChildren<JoyAxisWidget*>();
QListIterator<JoyAxisWidget*> iter2(list2);
while (iter2.hasNext())
{
JoyAxisWidget *axisWidget = iter2.next();
axisWidget->disableFlashes();
}
QList<JoyControlStickPushButton*> list3 = ui->tabWidget->widget(i)->findChildren<JoyControlStickPushButton*>();
QListIterator<JoyControlStickPushButton*> iter3(list3);
while (iter3.hasNext())
{
JoyControlStickPushButton *stickWidget = iter3.next();
stickWidget->disableFlashes();
}
QList<JoyDPadButtonWidget*> list4 = ui->tabWidget->widget(i)->findChildren<JoyDPadButtonWidget*>();
QListIterator<JoyDPadButtonWidget*> iter4(list4);
while (iter4.hasNext())
{
JoyDPadButtonWidget *dpadWidget = iter4.next();
dpadWidget->disableFlashes();
}
QList<JoyControlStickButtonPushButton*> list6 = ui->tabWidget->widget(i)->findChildren<JoyControlStickButtonPushButton*>();
QListIterator<JoyControlStickButtonPushButton*> iter6(list6);
while (iter6.hasNext())
{
JoyControlStickButtonPushButton *stickButtonWidget = iter6.next();
stickButtonWidget->disableFlashes();
}
QList<DPadPushButton*> list7 = ui->tabWidget->widget(i)->findChildren<DPadPushButton*>();
QListIterator<DPadPushButton*> iter7(list7);
while (iter7.hasNext())
{
DPadPushButton *dpadWidget = iter7.next();
dpadWidget->disableFlashes();
}
JoyTabWidget *tabWidget = static_cast<JoyTabWidget*>(ui->tabWidget->widget(i));
ui->tabWidget->disableFlashes(tabWidget->getJoystick());
}
}
void MainWindow::enableFlashActions()
{
for (int i=0; i < ui->tabWidget->count(); i++)
{
QList<JoyButtonWidget*> list = ui->tabWidget->widget(i)->findChildren<JoyButtonWidget*>();
QListIterator<JoyButtonWidget*> iter(list);
while (iter.hasNext())
{
JoyButtonWidget *buttonWidget = iter.next();
buttonWidget->enableFlashes();
buttonWidget->tryFlash();
}
QList<JoyAxisWidget*> list2 = ui->tabWidget->widget(i)->findChildren<JoyAxisWidget*>();
QListIterator<JoyAxisWidget*> iter2(list2);
while (iter2.hasNext())
{
JoyAxisWidget *axisWidget = iter2.next();
axisWidget->enableFlashes();
axisWidget->tryFlash();
}
QList<JoyControlStickPushButton*> list3 = ui->tabWidget->widget(i)->findChildren<JoyControlStickPushButton*>();
QListIterator<JoyControlStickPushButton*> iter3(list3);
while (iter3.hasNext())
{
JoyControlStickPushButton *stickWidget = iter3.next();
stickWidget->enableFlashes();
stickWidget->tryFlash();
}
QList<JoyDPadButtonWidget*> list4 = ui->tabWidget->widget(i)->findChildren<JoyDPadButtonWidget*>();
QListIterator<JoyDPadButtonWidget*> iter4(list4);
while (iter4.hasNext())
{
JoyDPadButtonWidget *dpadWidget = iter4.next();
dpadWidget->enableFlashes();
dpadWidget->tryFlash();
}
QList<JoyControlStickButtonPushButton*> list6 = ui->tabWidget->widget(i)->findChildren<JoyControlStickButtonPushButton*>();
QListIterator<JoyControlStickButtonPushButton*> iter6(list6);
while (iter6.hasNext())
{
JoyControlStickButtonPushButton *stickButtonWidget = iter6.next();
stickButtonWidget->enableFlashes();
stickButtonWidget->tryFlash();
}
QList<DPadPushButton*> list7 = ui->tabWidget->widget(i)->findChildren<DPadPushButton*>();
QListIterator<DPadPushButton*> iter7(list7);
while (iter7.hasNext())
{
DPadPushButton *dpadWidget = iter7.next();
dpadWidget->enableFlashes();
dpadWidget->tryFlash();
}
JoyTabWidget *tabWidget = static_cast<JoyTabWidget*>(ui->tabWidget->widget(i));
ui->tabWidget->enableFlashes(tabWidget->getJoystick());
}
}
// Intermediate slot used in Design mode
void MainWindow::hideWindow()
{
disableFlashActions();
signalDisconnect = true;
hide();
}
void MainWindow::joystickTrayShow()
{
QMenu *tempmenu = static_cast<QMenu*>(sender());
QList<QAction*> menuactions = tempmenu->actions();
QListIterator<QAction*> listiter (menuactions);
while (listiter.hasNext())
{
QAction *action = listiter.next();
action->setChecked(false);
QHash<QString, QVariant> tempmap = action->data().toHash();
QHashIterator<QString, QVariant> iter(tempmap);
while (iter.hasNext())
{
iter.next();
int joyindex = iter.key().toInt();
int configindex = iter.value().toInt();
JoyTabWidget *widget = static_cast<JoyTabWidget*>(ui->tabWidget->widget(joyindex));
if (configindex == widget->getCurrentConfigIndex())
{
action->setChecked(true);
if (widget->getJoystick()->isDeviceEdited())
{
action->setIcon(QIcon::fromTheme("document-save-as"));
}
else if (!action->icon().isNull())
{
action->setIcon(QIcon());
}
}
else if (!action->icon().isNull())
{
action->setIcon(QIcon());
}
if (action->text() != widget->getConfigName(configindex))
{
action->setText(widget->getConfigName(configindex));
}
}
}
}
void MainWindow::showEvent(QShowEvent *event)
{
bool propogate = true;
// Check if hideEvent has been processed
if (signalDisconnect && isVisible())
{
// Restore flashing buttons
enableFlashActions();
signalDisconnect = false;
// Only needed if hidden with the system tray enabled
if (showTrayIcon)
{
if (isMinimized())
{
if (isMaximized())
{
showMaximized();
}
else
{
showNormal();
}
activateWindow();
raise();
}
}
}
if (propogate)
{
QMainWindow::showEvent(event);
}
}
void MainWindow::changeEvent(QEvent *event)
{
if (event->type() == QEvent::WindowStateChange)
{
QWindowStateChangeEvent *e = static_cast<QWindowStateChangeEvent*>(event);
if (e->oldState() != Qt::WindowMinimized && isMinimized())
{
bool minimizeToTaskbar = settings->value("MinimizeToTaskbar", false).toBool();
if (QSystemTrayIcon::isSystemTrayAvailable() && showTrayIcon && !minimizeToTaskbar)
{
this->hideWindow();
}
else
{
disableFlashActions();
signalDisconnect = true;
}
}
}
else if (event->type() == QEvent::LanguageChange)
{
retranslateUi();
}
QMainWindow::changeEvent(event);
}
void MainWindow::openAboutDialog()
{
aboutDialog->show();
}
void MainWindow::loadConfigFile(QString fileLocation, int joystickIndex)
{
if (joystickIndex > 0 && joysticks->contains(joystickIndex-1))
{
JoyTabWidget *widget = static_cast<JoyTabWidget*>(ui->tabWidget->widget(joystickIndex-1));
if (widget)
{
widget->loadConfigFile(fileLocation);
}
}
else if (joystickIndex <= 0)
{
for (int i=0; i < ui->tabWidget->count(); i++)
{
JoyTabWidget *widget = static_cast<JoyTabWidget*>(ui->tabWidget->widget(i));
if (widget)
{
widget->loadConfigFile(fileLocation);
}
}
}
}
void MainWindow::loadConfigFile(QString fileLocation, QString controllerID)
{
if (!controllerID.isEmpty())
{
QListIterator<JoyTabWidget*> iter(ui->tabWidget->findChildren<JoyTabWidget*>());
while (iter.hasNext())
{
JoyTabWidget *tab = iter.next();
if (tab)
{
InputDevice *tempdevice = tab->getJoystick();
if (controllerID == tempdevice->getStringIdentifier())
{
tab->loadConfigFile(fileLocation);
}
}
}
}
}
void MainWindow::removeJoyTabs()
{
int oldtabcount = ui->tabWidget->count();
for (int i = oldtabcount-1; i >= 0; i--)
{
QWidget *tab = ui->tabWidget->widget(i);
delete tab;
tab = 0;
}
ui->tabWidget->clear();
}
void MainWindow::handleInstanceDisconnect()
{
settings->sync();
loadAppConfig(true);
}
void MainWindow::openJoystickStatusWindow()
{
int index = ui->tabWidget->currentIndex();
if (index >= 0)
{
JoyTabWidget *joyTab = static_cast<JoyTabWidget*>(ui->tabWidget->widget(index));
InputDevice *joystick = joyTab->getJoystick();
if (joystick)
{
JoystickStatusWindow *dialog = new JoystickStatusWindow(joystick, this);
dialog->show();
}
}
}
void MainWindow::openKeyCheckerDialog()
{
QKeyDisplayDialog *dialog = new QKeyDisplayDialog(this);
dialog->show();
}
void MainWindow::openGitHubPage()
{
QDesktopServices::openUrl(QUrl(PadderCommon::githubProjectPage));
}
void MainWindow::openWikiPage()
{
QDesktopServices::openUrl(QUrl(PadderCommon::wikiPage));
}
void MainWindow::unloadCurrentConfig(int joystickIndex)
{
if (joystickIndex > 0 && joysticks->contains(joystickIndex-1))
{
JoyTabWidget *widget = static_cast<JoyTabWidget*> (ui->tabWidget->widget(joystickIndex-1));
if (widget)
{
widget->unloadConfig();
}
}
else if (joystickIndex <= 0)
{
for (int i=0; i < ui->tabWidget->count(); i++)
{
JoyTabWidget *widget = static_cast<JoyTabWidget*> (ui->tabWidget->widget(i));
if (widget)
{
widget->unloadConfig();
}
}
}
}
void MainWindow::unloadCurrentConfig(QString controllerID)
{
if (!controllerID.isEmpty())
{
QListIterator<JoyTabWidget*> iter(ui->tabWidget->findChildren<JoyTabWidget*>());
while (iter.hasNext())
{
JoyTabWidget *tab = iter.next();
if (tab)
{
InputDevice *tempdevice = tab->getJoystick();
if (controllerID == tempdevice->getStringIdentifier())
{
tab->unloadConfig();
}
}
}
}
}
void MainWindow::propogateNameDisplayStatus(bool displayNames)
{
JoyTabWidget *tabwidget = static_cast<JoyTabWidget*>(sender());
for (int i=0; i < ui->tabWidget->count(); i++)
{
JoyTabWidget *tab = static_cast<JoyTabWidget*>(ui->tabWidget->widget(i));
if (tab && tab != tabwidget)
{
if (tab->isDisplayingNames() != displayNames)
{
tab->changeNameDisplay(displayNames);
}
}
}
}
void MainWindow::changeStartSetNumber(unsigned int startSetNumber, QString controllerID)
{
if (!controllerID.isEmpty())
{
QListIterator<JoyTabWidget*> iter(ui->tabWidget->findChildren<JoyTabWidget*>());
while (iter.hasNext())
{
JoyTabWidget *tab = iter.next();
if (tab)
{
InputDevice *tempdevice = tab->getJoystick();
if (controllerID == tempdevice->getStringIdentifier())
{
tab->changeCurrentSet(startSetNumber);
}
}
}
}
}
void MainWindow::changeStartSetNumber(unsigned int startSetNumber, unsigned int joystickIndex)
{
if (joystickIndex > 0 && joysticks->contains(joystickIndex-1))
{
JoyTabWidget *widget = static_cast<JoyTabWidget*>(ui->tabWidget->widget(joystickIndex-1));
if (widget)
{
widget->changeCurrentSet(startSetNumber);
}
}
else if (joystickIndex <= 0)
{
for (int i=0; i < ui->tabWidget->count(); i++)
{
JoyTabWidget *widget = static_cast<JoyTabWidget*>(ui->tabWidget->widget(i));
if (widget)
{
widget->changeCurrentSet(startSetNumber);
}
}
}
}
void MainWindow::updateButtonPressed() {
QMessageBox *box = new QMessageBox(this);
box->setText(
tr("AntiMicro is no longer maintained anymore, it won't get any new "
"features or bug fixes. This is the last release of AntiMicro.\nIt is "
"recommended to migrate to new, currently developed version of this "
"app called AntiMicroX. It contains a lot of bug fixes and new "
"features like: showing battery status, mapping gamepad moves with "
"gyroscope, proper calibration and many more...\nPress Open to to open "
"AntiMicroX website."));
box->setWindowTitle(tr("Deprecation Notice"));
box->setStandardButtons(QMessageBox::Cancel | QMessageBox::Open);
int ret = box->exec();
if (ret == QMessageBox::Open) {
qInfo() << "Opening antimicrox website";
QDesktopServices::openUrl(
QUrl("path_to_url"));
}
}
/**
* @brief Build list of current input devices and pass it to settings dialog
* instance. Open Settings dialog.
*/
void MainWindow::openMainSettingsDialog()
{
QList<InputDevice*> *devices = new QList<InputDevice*>(joysticks->values());
MainSettingsDialog *dialog = new MainSettingsDialog(settings, devices, this);
connect(dialog, SIGNAL(changeLanguage(QString)), this, SLOT(changeLanguage(QString)));
if (appWatcher)
{
#if defined(USE_SDL_2) && defined(Q_OS_UNIX) && defined(WITH_X11)
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
connect(dialog, SIGNAL(accepted()), appWatcher, SLOT(syncProfileAssignment()));
connect(dialog, SIGNAL(accepted()), this, SLOT(checkAutoProfileWatcherTimer()));
connect(dialog, SIGNAL(rejected()), this, SLOT(checkAutoProfileWatcherTimer()));
appWatcher->stopTimer();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
#endif
#elif defined(USE_SDL_2) && defined(Q_OS_WIN)
connect(dialog, SIGNAL(accepted()), appWatcher, SLOT(syncProfileAssignment()));
connect(dialog, SIGNAL(accepted()), this, SLOT(checkAutoProfileWatcherTimer()));
connect(dialog, SIGNAL(rejected()), this, SLOT(checkAutoProfileWatcherTimer()));
appWatcher->stopTimer();
#endif
}
connect(dialog, SIGNAL(accepted()), this, SLOT(populateTrayIcon()));
connect(dialog, SIGNAL(accepted()), this, SLOT(checkHideEmptyOption()));
#ifdef Q_OS_WIN
connect(dialog, SIGNAL(accepted()), this, SLOT(checkKeyRepeatOptions()));
#endif
dialog->show();
}
/**
* @brief Change language used by the application.
* @param Language code
*/
void MainWindow::changeLanguage(QString language)
{
if (translator && appTranslator)
{
PadderCommon::reloadTranslations(translator, appTranslator, language);
}
}
/**
* @brief Check if the program should really quit or if it should
* be minimized.
* @param QCloseEvent
*/
void MainWindow::closeEvent(QCloseEvent *event)
{
bool closeToTray = settings->value("CloseToTray", false).toBool();
if (closeToTray && QSystemTrayIcon::isSystemTrayAvailable() && showTrayIcon)
{
this->hideWindow();
}
else
{
qApp->quit();
}
QMainWindow::closeEvent(event);
}
/**
* @brief Show abstracted controller dialog for use in SDL 1.2. No longer
* used for versions of the program running SDL 2. In SDL 2,
* the Game Controller API is being used instead.
*/
void MainWindow::showStickAssignmentDialog()
{
int index = ui->tabWidget->currentIndex();
if (index >= 0)
{
JoyTabWidget *joyTab = static_cast<JoyTabWidget*>(ui->tabWidget->widget(index));
Joystick *joystick = static_cast<Joystick*>(joyTab->getJoystick());
AdvanceStickAssignmentDialog *dialog = new AdvanceStickAssignmentDialog(joystick, this);
connect(dialog, SIGNAL(finished(int)), joyTab, SLOT(fillButtons()));
dialog->show();
}
}
/**
* @brief Display a version of the tray menu that shows all recent profiles for
* all controllers in one list.
*/
void MainWindow::singleTrayProfileMenuShow()
{
if (!profileActions.isEmpty())
{
QMapIterator<int, QList<QAction*> > mapIter(profileActions);
while (mapIter.hasNext())
{
mapIter.next();
QList<QAction*> menuactions = mapIter.value();
QListIterator<QAction*> listiter (menuactions);
while (listiter.hasNext())
{
QAction *action = listiter.next();
action->setChecked(false);
QHash<QString, QVariant> tempmap = action->data().toHash();
QHashIterator<QString, QVariant> iter(tempmap);
while (iter.hasNext())
{
iter.next();
int joyindex = iter.key().toInt();
int configindex = iter.value().toInt();
JoyTabWidget *widget = static_cast<JoyTabWidget*>(ui->tabWidget->widget(joyindex));
if (configindex == widget->getCurrentConfigIndex())
{
action->setChecked(true);
if (widget->getJoystick()->isDeviceEdited())
{
action->setIcon(QIcon::fromTheme("document-save-as"));
}
else if (!action->icon().isNull())
{
action->setIcon(QIcon());
}
}
else if (!action->icon().isNull())
{
action->setIcon(QIcon());
}
if (action->text() != widget->getConfigName(configindex))
{
action->setText(widget->getConfigName(configindex));
}
}
}
}
}
}
void MainWindow::profileTrayActionTriggered(bool checked)
{
// Obtaining the selected config
QAction *action = static_cast<QAction*>(sender());
QHash<QString, QVariant> tempmap = action->data().toHash();
QHashIterator<QString, QVariant> iter(tempmap);
while (iter.hasNext())
{
iter.next();
// Fetching indicies and tab associated with the current joypad
int joyindex = iter.key().toInt();
int configindex = iter.value().toInt();
JoyTabWidget *widget = static_cast<JoyTabWidget*>(ui->tabWidget->widget(joyindex));
// Checking if the selected config has been disabled by the change (action->isChecked() represents the state of the checkbox AFTER the click)
if (!checked)
{
// It has - disabling - the 0th config is the new/'null' config
widget->setCurrentConfig(0);
}
else
{
// It hasn't - enabling - note that setting this causes the menu to be updated
widget->setCurrentConfig(configindex);
}
}
}
void MainWindow::checkHideEmptyOption()
{
for (int i=0; i < ui->tabWidget->count(); i++)
{
JoyTabWidget *tab = static_cast<JoyTabWidget*>(ui->tabWidget->widget(i));
if (tab)
{
tab->checkHideEmptyOption();
}
}
}
#ifdef Q_OS_WIN
void MainWindow::checkKeyRepeatOptions()
{
for (int i=0; i < ui->tabWidget->count(); i++)
{
JoyTabWidget *tab = static_cast<JoyTabWidget*>(ui->tabWidget->widget(i));
tab->deviceKeyRepeatSettings();
}
}
/**
* @brief Check if user really wants to restart the program with elevated
* privileges. If yes, attempt to restart the program.
*/
void MainWindow::restartAsElevated()
{
QMessageBox msg;
msg.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msg.setWindowTitle(tr("Run as Administrator?"));
msg.setText(tr("Are you sure that you want to run this program as Adminstrator?"
"\n\n"
"Some games run as Administrator which will cause events generated by antimicro "
"to not be used by those games unless antimicro is also run "
"as the Adminstrator. "
"This is due to permission problems caused by User Account "
"Control (UAC) options in Windows Vista and later."));
if (QSysInfo::windowsVersion() >= QSysInfo::WV_VISTA)
{
QIcon uacIcon = QApplication::style()->standardIcon(QStyle::SP_VistaShield);
msg.button(QMessageBox::Yes)->setIcon(uacIcon);
}
int result = msg.exec();
if (result == QMessageBox::Yes)
{
bool result = WinExtras::elevateAntiMicro();
if (result)
{
qApp->quit();
}
else
{
msg.setStandardButtons(QMessageBox::Close);
msg.setWindowTitle(tr("Failed to elevate program"));
msg.setText(tr("Failed to restart this program as the Administrator"));
msg.exec();
}
}
}
#endif
#ifdef USE_SDL_2
void MainWindow::openGameControllerMappingWindow(bool openAsMain)
{
int index = ui->tabWidget->currentIndex();
if (index >= 0)
{
JoyTabWidget *joyTab = static_cast<JoyTabWidget*>(ui->tabWidget->widget(index));
InputDevice *joystick = joyTab->getJoystick();
if (joystick)
{
GameControllerMappingDialog *dialog = new GameControllerMappingDialog(joystick, settings, this);
if (openAsMain)
{
dialog->setParent(0);
dialog->setWindowFlags(Qt::Window);
connect(dialog, SIGNAL(finished(int)), qApp, SLOT(quit()));
}
else
{
connect(dialog, SIGNAL(mappingUpdate(QString,InputDevice*)), this, SLOT(propogateMappingUpdate(QString, InputDevice*)));
}
dialog->show();
}
}
else if (openAsMain)
{
Logger::LogInfo(tr("Could not find controller. Exiting."));
qApp->quit();
}
}
void MainWindow::propogateMappingUpdate(QString mapping, InputDevice *device)
{
emit mappingUpdated(mapping, device);
}
void MainWindow::testMappingUpdateNow(int index, InputDevice *device)
{
QWidget *tab = ui->tabWidget->widget(index);
if (tab)
{
ui->tabWidget->removeTab(index);
delete tab;
tab = 0;
}
JoyTabWidget *tabwidget = new JoyTabWidget(device, settings, this);
QString joytabName = device->getSDLName();
joytabName.append(" ").append(tr("(%1)").arg(device->getName()));
ui->tabWidget->insertTab(index, tabwidget, joytabName);
tabwidget->refreshButtons();
ui->tabWidget->setCurrentIndex(index);
connect(tabwidget, SIGNAL(namesDisplayChanged(bool)), this, SLOT(propogateNameDisplayStatus(bool)));
connect(tabwidget, SIGNAL(mappingUpdated(QString,InputDevice*)), this, SLOT(propogateMappingUpdate(QString,InputDevice*)));
if (showTrayIcon)
{
connect(tabwidget, SIGNAL(joystickConfigChanged(int)), this, SLOT(populateTrayIcon()));
trayIcon->hide();
populateTrayIcon();
trayIcon->show();
}
}
void MainWindow::removeJoyTab(SDL_JoystickID deviceID)
{
bool found = false;
for (int i=0; i < ui->tabWidget->count() && !found; i++)
{
JoyTabWidget *tab = static_cast<JoyTabWidget*>(ui->tabWidget->widget(i));
if (tab && deviceID == tab->getJoystick()->getSDLJoystickID())
{
// Save most recent profile list to settings before removing tab.
tab->saveDeviceSettings();
// Remove flash event connections between buttons and
// the tab before deleting tab.
ui->tabWidget->disableFlashes(tab->getJoystick());
ui->tabWidget->removeTab(i);
QMetaObject::invokeMethod(tab->getJoystick(), "finalRemoval");
delete tab;
tab = 0;
found = true;
}
}
// Refresh tab text to reflect new index values.
for (int i=0; i < ui->tabWidget->count(); i++)
{
JoyTabWidget *tab = static_cast<JoyTabWidget*>(ui->tabWidget->widget(i));
if (tab)
{
InputDevice *device = tab->getJoystick();
QString joytabName = device->getSDLName();
joytabName.append(" ").append(tr("(%1)").arg(device->getName()));
ui->tabWidget->setTabText(i, joytabName);
}
}
if (showTrayIcon)
{
trayIcon->hide();
populateTrayIcon();
trayIcon->show();
}
if (ui->tabWidget->count() == 0)
{
ui->stackedWidget->setCurrentIndex(0);
}
}
void MainWindow::addJoyTab(InputDevice *device)
{
JoyTabWidget *tabwidget = new JoyTabWidget(device, settings, this);
QString joytabName = device->getSDLName();
joytabName.append(" ").append(tr("(%1)").arg(device->getName()));
ui->tabWidget->addTab(tabwidget, joytabName);
tabwidget->loadDeviceSettings();
tabwidget->refreshButtons();
// Refresh tab text to reflect new index values.
for (int i=0; i < ui->tabWidget->count(); i++)
{
JoyTabWidget *tab = static_cast<JoyTabWidget*>(ui->tabWidget->widget(i));
if (tab)
{
InputDevice *device = tab->getJoystick();
QString joytabName = device->getSDLName();
joytabName.append(" ").append(tr("(%1)").arg(device->getName()));
ui->tabWidget->setTabText(i, joytabName);
}
}
connect(tabwidget, SIGNAL(namesDisplayChanged(bool)), this, SLOT(propogateNameDisplayStatus(bool)));
connect(tabwidget, SIGNAL(mappingUpdated(QString,InputDevice*)), this, SLOT(propogateMappingUpdate(QString,InputDevice*)));
if (showTrayIcon)
{
connect(tabwidget, SIGNAL(joystickConfigChanged(int)), this, SLOT(populateTrayIcon()));
trayIcon->hide();
populateTrayIcon();
trayIcon->show();
}
ui->stackedWidget->setCurrentIndex(1);
}
void MainWindow::autoprofileLoad(AutoProfileInfo *info)
{
if( info != NULL ) {
Logger::LogDebug(QObject::tr("Auto-switching to profile \"%1\".").
arg(info->getProfileLocation()));
} else {
Logger::LogError(QObject::tr("Auto-switching to NULL profile!"));
}
#if defined(USE_SDL_2) && (defined(WITH_X11) || defined(Q_OS_WIN))
#if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
for (int i = 0; i < ui->tabWidget->count(); i++)
{
JoyTabWidget *widget = static_cast<JoyTabWidget*>(ui->tabWidget->widget(i));
if (widget)
{
if (info->getGUID() == "all")
{
// If the all option for a Default profile was found,
// first check for controller specific associations. If one exists,
// skip changing the profile on the controller. A later call will
// be used to switch the profile for that controller.
QList<AutoProfileInfo*> *customs = appWatcher->getCustomDefaults();
bool found = false;
QListIterator<AutoProfileInfo*> iter(*customs);
while (iter.hasNext())
{
AutoProfileInfo *tempinfo = iter.next();
if (tempinfo->getGUID() == widget->getJoystick()->getGUIDString() &&
info->isCurrentDefault())
{
found = true;
iter.toBack();
}
}
delete customs;
customs = 0;
// Check if profile has already been switched for a particular
// controller.
if (!found)
{
QString tempguid = widget->getJoystick()->getGUIDString();
if (appWatcher->isGUIDLocked(tempguid))
{
found = true;
}
}
if (!found)
{
// If the profile location is empty, assume
// that an empty profile should get loaded.
if (info->getProfileLocation().isEmpty())
{
widget->setCurrentConfig(0);
}
else
{
widget->loadConfigFile(info->getProfileLocation());
}
}
}
else if (info->getGUID() == widget->getJoystick()->getStringIdentifier())
{
if (info->getProfileLocation().isEmpty())
{
widget->setCurrentConfig(0);
}
else
{
widget->loadConfigFile(info->getProfileLocation());
}
}
}
}
#if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
#endif
#endif
}
void MainWindow::checkAutoProfileWatcherTimer()
{
#if defined(USE_SDL_2) && (defined(WITH_X11) || defined(Q_OS_WIN))
#if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
QString autoProfileActive = settings->value("AutoProfiles/AutoProfilesActive", "0").toString();
if (autoProfileActive == "1")
{
appWatcher->startTimer();
}
else
{
appWatcher->stopTimer();
}
#if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
#endif
#endif
}
/**
* @brief TODO: Check if method is save to remove.
*/
void MainWindow::updateMenuOptions()
{
int index = ui->tabWidget->currentIndex();
if (index >= 0)
{
JoyTabWidget *joyTab = static_cast<JoyTabWidget*>(ui->tabWidget->widget(index));
InputDevice *joystick = joyTab->getJoystick();
if (qobject_cast<GameController*>(joystick) != 0)
{
ui->actionStick_Pad_Assign->setEnabled(false);
}
else
{
ui->actionStick_Pad_Assign->setEnabled(true);
}
}
}
/**
* @brief Select appropriate tab with the specified index.
* @param Index of appropriate tab.
*/
void MainWindow::selectControllerJoyTab(unsigned int index)
{
if (index > 0 && joysticks->contains(index-1))
{
JoyTabWidget *widget = static_cast<JoyTabWidget*> (ui->tabWidget->widget(index-1));
if (widget)
{
ui->tabWidget->setCurrentIndex(index-1);
}
}
}
/**
* @brief Select appropriate tab that has a device with the specified GUID.
* @param GUID of joystick device.
*/
void MainWindow::selectControllerJoyTab(QString GUID)
{
if (!GUID.isEmpty())
{
InputDevice *device = 0;
QMapIterator<SDL_JoystickID, InputDevice*> deviceIter(*joysticks);
while (deviceIter.hasNext())
{
deviceIter.next();
InputDevice *tempDevice = deviceIter.value();
if (tempDevice && GUID == tempDevice->getStringIdentifier())
{
device = tempDevice;
deviceIter.toBack();
}
}
if (device)
{
ui->tabWidget->setCurrentIndex(device->getJoyNumber());
}
}
}
#endif
void MainWindow::changeWindowStatus()
{
// Check flags to see if user requested for the main window and the tray icon
// to not be displayed.
if (graphical)
{
bool launchInTraySetting = settings->runtimeValue("LaunchInTray", false).toBool();
if (!cmdutility->isHiddenRequested() &&
(!launchInTraySetting || !QSystemTrayIcon::isSystemTrayAvailable()))
{
show();
}
else if (cmdutility->isHiddenRequested() && cmdutility->isTrayHidden())
{
// Window should already be hidden but make sure
// to disable flashing buttons.
hideWindow();
setEnabled(false); // Should already be disabled. Do it again just to be sure.
}
else if (cmdutility->isHiddenRequested() || launchInTraySetting)
{
// Window should already be hidden but make sure
// to disable flashing buttons.
hideWindow();
}
}
}
bool MainWindow::getGraphicalStatus()
{
return graphical;
}
void MainWindow::setTranslator(QTranslator *translator)
{
this->translator = translator;
}
QTranslator* MainWindow::getTranslator()
{
return translator;
}
void MainWindow::setAppTranslator(QTranslator *translator)
{
this->appTranslator = translator;
}
QTranslator* MainWindow::getAppTranslator()
{
return appTranslator;
}
void MainWindow::retranslateUi()
{
ui->retranslateUi(this);
}
void MainWindow::refreshTabHelperThreads()
{
for (int i=0; i < ui->tabWidget->count(); i++)
{
JoyTabWidget *widget = static_cast<JoyTabWidget*>(ui->tabWidget->widget(i));
if (widget)
{
widget->refreshHelperThread();
}
}
}
``` | /content/code_sandbox/src/mainwindow.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 12,456 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
//#include <QDebug>
#include <QHash>
#include <QHashIterator>
#include <QList>
#include "joycontrolstickeditdialog.h"
#include "ui_joycontrolstickeditdialog.h"
#include "mousedialog/mousecontrolsticksettingsdialog.h"
#include "event.h"
#include "antkeymapper.h"
#include "setjoystick.h"
#include "buttoneditdialog.h"
#include "inputdevice.h"
#include "common.h"
JoyControlStickEditDialog::JoyControlStickEditDialog(JoyControlStick *stick, QWidget *parent) :
QDialog(parent, Qt::Window),
ui(new Ui::JoyControlStickEditDialog),
helper(stick)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
this->stick = stick;
helper.moveToThread(stick->thread());
PadderCommon::inputDaemonMutex.lock();
updateWindowTitleStickName();
ui->deadZoneSlider->setValue(stick->getDeadZone());
ui->deadZoneSpinBox->setValue(stick->getDeadZone());
ui->maxZoneSlider->setValue(stick->getMaxZone());
ui->maxZoneSpinBox->setValue(stick->getMaxZone());
ui->diagonalRangeSlider->setValue(stick->getDiagonalRange());
ui->diagonalRangeSpinBox->setValue(stick->getDiagonalRange());
QString xCoorString = QString::number(stick->getXCoordinate());
if (stick->getCircleAdjust() > 0.0)
{
xCoorString.append(QString(" (%1)").arg(stick->getCircleXCoordinate()));
}
ui->xCoordinateLabel->setText(xCoorString);
QString yCoorString = QString::number(stick->getYCoordinate());
if (stick->getCircleAdjust() > 0.0)
{
yCoorString.append(QString(" (%1)").arg(stick->getCircleYCoordinate()));
}
ui->yCoordinateLabel->setText(yCoorString);
ui->distanceLabel->setText(QString::number(stick->getAbsoluteRawDistance()));
ui->diagonalLabel->setText(QString::number(stick->calculateBearing()));
if (stick->getJoyMode() == JoyControlStick::StandardMode)
{
ui->joyModeComboBox->setCurrentIndex(0);
}
else if (stick->getJoyMode() == JoyControlStick::EightWayMode)
{
ui->joyModeComboBox->setCurrentIndex(1);
}
else if (stick->getJoyMode() == JoyControlStick::FourWayCardinal)
{
ui->joyModeComboBox->setCurrentIndex(2);
ui->diagonalRangeSlider->setEnabled(false);
ui->diagonalRangeSpinBox->setEnabled(false);
}
else if (stick->getJoyMode() == JoyControlStick::FourWayDiagonal)
{
ui->joyModeComboBox->setCurrentIndex(3);
ui->diagonalRangeSlider->setEnabled(false);
ui->diagonalRangeSpinBox->setEnabled(false);
}
ui->stickStatusBoxWidget->setStick(stick);
selectCurrentPreset();
ui->stickNameLineEdit->setText(stick->getStickName());
double validDistance = stick->getDistanceFromDeadZone() * 100.0;
ui->fromSafeZoneValueLabel->setText(QString::number(validDistance));
double circleValue = stick->getCircleAdjust();
ui->squareStickSlider->setValue(circleValue * 100);
ui->squareStickSpinBox->setValue(circleValue * 100);
unsigned int stickDelay = stick->getStickDelay();
ui->stickDelaySlider->setValue(stickDelay * .1);
ui->stickDelayDoubleSpinBox->setValue(stickDelay * .001);
ui->modifierPushButton->setText(stick->getModifierButton()->getSlotsSummary());
stick->getModifierButton()->establishPropertyUpdatedConnections();
PadderCommon::inputDaemonMutex.unlock();
connect(ui->presetsComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(implementPresets(int)));
connect(ui->joyModeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(implementModes(int)));
connect(ui->deadZoneSlider, SIGNAL(valueChanged(int)), ui->deadZoneSpinBox, SLOT(setValue(int)));
connect(ui->maxZoneSlider, SIGNAL(valueChanged(int)), ui->maxZoneSpinBox, SLOT(setValue(int)));
connect(ui->diagonalRangeSlider, SIGNAL(valueChanged(int)), ui->diagonalRangeSpinBox, SLOT(setValue(int)));
connect(ui->squareStickSlider, SIGNAL(valueChanged(int)), ui->squareStickSpinBox, SLOT(setValue(int)));
connect(ui->deadZoneSpinBox, SIGNAL(valueChanged(int)), ui->deadZoneSlider, SLOT(setValue(int)));
connect(ui->maxZoneSpinBox, SIGNAL(valueChanged(int)), ui->maxZoneSlider, SLOT(setValue(int)));
connect(ui->maxZoneSpinBox, SIGNAL(valueChanged(int)), this, SLOT(checkMaxZone(int)));
connect(ui->diagonalRangeSpinBox, SIGNAL(valueChanged(int)), ui->diagonalRangeSlider, SLOT(setValue(int)));
connect(ui->squareStickSpinBox, SIGNAL(valueChanged(int)), ui->squareStickSlider, SLOT(setValue(int)));
connect(ui->stickDelaySlider, SIGNAL(valueChanged(int)), &helper, SLOT(updateControlStickDelay(int)));
connect(ui->deadZoneSpinBox, SIGNAL(valueChanged(int)), stick, SLOT(setDeadZone(int)));
connect(ui->diagonalRangeSpinBox, SIGNAL(valueChanged(int)), stick, SLOT(setDiagonalRange(int)));
connect(ui->squareStickSpinBox, SIGNAL(valueChanged(int)), this, SLOT(changeCircleAdjust(int)));
connect(stick, SIGNAL(stickDelayChanged(int)), this, SLOT(updateStickDelaySpinBox(int)));
connect(ui->stickDelayDoubleSpinBox, SIGNAL(valueChanged(double)), this, SLOT(updateStickDelaySlider(double)));
connect(stick, SIGNAL(moved(int,int)), this, SLOT(refreshStickStats(int,int)));
connect(ui->mouseSettingsPushButton, SIGNAL(clicked()), this, SLOT(openMouseSettingsDialog()));
connect(ui->stickNameLineEdit, SIGNAL(textEdited(QString)), stick, SLOT(setStickName(QString)));
connect(stick, SIGNAL(stickNameChanged()), this, SLOT(updateWindowTitleStickName()));
connect(ui->modifierPushButton, SIGNAL(clicked()), this, SLOT(openModifierEditDialog()));
connect(stick->getModifierButton(), SIGNAL(slotsChanged()), this, SLOT(changeModifierSummary()));
}
JoyControlStickEditDialog::~JoyControlStickEditDialog()
{
delete ui;
}
void JoyControlStickEditDialog::implementPresets(int index)
{
JoyButtonSlot *upButtonSlot = 0;
JoyButtonSlot *downButtonSlot = 0;
JoyButtonSlot *leftButtonSlot = 0;
JoyButtonSlot *rightButtonSlot = 0;
JoyButtonSlot *upLeftButtonSlot = 0;
JoyButtonSlot *upRightButtonSlot = 0;
JoyButtonSlot *downLeftButtonSlot = 0;
JoyButtonSlot *downRightButtonSlot = 0;
if (index == 1)
{
PadderCommon::inputDaemonMutex.lock();
upButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseUp, JoyButtonSlot::JoyMouseMovement, this);
downButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseDown, JoyButtonSlot::JoyMouseMovement, this);
leftButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseLeft, JoyButtonSlot::JoyMouseMovement, this);
rightButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseRight, JoyButtonSlot::JoyMouseMovement, this);
PadderCommon::inputDaemonMutex.unlock();
ui->joyModeComboBox->setCurrentIndex(0);
ui->diagonalRangeSlider->setValue(65);
}
else if (index == 2)
{
PadderCommon::inputDaemonMutex.lock();
upButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseUp, JoyButtonSlot::JoyMouseMovement, this);
downButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseDown, JoyButtonSlot::JoyMouseMovement, this);
leftButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseRight, JoyButtonSlot::JoyMouseMovement, this);
rightButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseLeft, JoyButtonSlot::JoyMouseMovement, this);
PadderCommon::inputDaemonMutex.unlock();
ui->joyModeComboBox->setCurrentIndex(0);
ui->diagonalRangeSlider->setValue(65);
}
else if (index == 3)
{
PadderCommon::inputDaemonMutex.lock();
upButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseDown, JoyButtonSlot::JoyMouseMovement, this);
downButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseUp, JoyButtonSlot::JoyMouseMovement, this);
leftButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseLeft, JoyButtonSlot::JoyMouseMovement, this);
rightButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseRight, JoyButtonSlot::JoyMouseMovement, this);
PadderCommon::inputDaemonMutex.unlock();
ui->joyModeComboBox->setCurrentIndex(0);
ui->diagonalRangeSlider->setValue(65);
}
else if (index == 4)
{
PadderCommon::inputDaemonMutex.lock();
upButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseDown, JoyButtonSlot::JoyMouseMovement, this);
downButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseUp, JoyButtonSlot::JoyMouseMovement, this);
leftButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseRight, JoyButtonSlot::JoyMouseMovement, this);
rightButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseLeft, JoyButtonSlot::JoyMouseMovement, this);
PadderCommon::inputDaemonMutex.unlock();
ui->joyModeComboBox->setCurrentIndex(0);
ui->diagonalRangeSlider->setValue(65);
}
else if (index == 5)
{
PadderCommon::inputDaemonMutex.lock();
upButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Up), Qt::Key_Up, JoyButtonSlot::JoyKeyboard, this);
downButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Down), Qt::Key_Down, JoyButtonSlot::JoyKeyboard, this);
leftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Left), Qt::Key_Left, JoyButtonSlot::JoyKeyboard, this);
rightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Right), Qt::Key_Right, JoyButtonSlot::JoyKeyboard, this);
PadderCommon::inputDaemonMutex.unlock();
ui->joyModeComboBox->setCurrentIndex(0);
ui->diagonalRangeSlider->setValue(45);
}
else if (index == 6)
{
PadderCommon::inputDaemonMutex.lock();
upButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_W), Qt::Key_W, JoyButtonSlot::JoyKeyboard, this);
downButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_S), Qt::Key_S, JoyButtonSlot::JoyKeyboard, this);
leftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_A), Qt::Key_A, JoyButtonSlot::JoyKeyboard, this);
rightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_D), Qt::Key_D, JoyButtonSlot::JoyKeyboard, this);
PadderCommon::inputDaemonMutex.unlock();
ui->joyModeComboBox->setCurrentIndex(0);
ui->diagonalRangeSlider->setValue(45);
}
else if (index == 7)
{
PadderCommon::inputDaemonMutex.lock();
if (ui->joyModeComboBox->currentIndex() == 0 ||
ui->joyModeComboBox->currentIndex() == 2)
{
upButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_8), QtKeyMapperBase::AntKey_KP_8, JoyButtonSlot::JoyKeyboard, this);
downButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_2), QtKeyMapperBase::AntKey_KP_2, JoyButtonSlot::JoyKeyboard, this);
leftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_4), QtKeyMapperBase::AntKey_KP_4, JoyButtonSlot::JoyKeyboard, this);
rightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_6), QtKeyMapperBase::AntKey_KP_6, JoyButtonSlot::JoyKeyboard, this);
}
else if (ui->joyModeComboBox->currentIndex() == 1)
{
upButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_8), QtKeyMapperBase::AntKey_KP_8, JoyButtonSlot::JoyKeyboard, this);
downButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_2), QtKeyMapperBase::AntKey_KP_2, JoyButtonSlot::JoyKeyboard, this);
leftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_4), QtKeyMapperBase::AntKey_KP_4, JoyButtonSlot::JoyKeyboard, this);
rightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_6), QtKeyMapperBase::AntKey_KP_6, JoyButtonSlot::JoyKeyboard, this);
upLeftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_7), QtKeyMapperBase::AntKey_KP_7, JoyButtonSlot::JoyKeyboard, this);
upRightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_9), QtKeyMapperBase::AntKey_KP_9, JoyButtonSlot::JoyKeyboard, this);
downLeftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_1), QtKeyMapperBase::AntKey_KP_1, JoyButtonSlot::JoyKeyboard, this);
downRightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_3), QtKeyMapperBase::AntKey_KP_3, JoyButtonSlot::JoyKeyboard, this);
}
else if (ui->joyModeComboBox->currentIndex() == 3)
{
upLeftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_7), QtKeyMapperBase::AntKey_KP_7, JoyButtonSlot::JoyKeyboard, this);
upRightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_9), QtKeyMapperBase::AntKey_KP_9, JoyButtonSlot::JoyKeyboard, this);
downLeftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_1), QtKeyMapperBase::AntKey_KP_1, JoyButtonSlot::JoyKeyboard, this);
downRightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_3), QtKeyMapperBase::AntKey_KP_3, JoyButtonSlot::JoyKeyboard, this);
}
PadderCommon::inputDaemonMutex.unlock();
ui->diagonalRangeSlider->setValue(45);
}
else if (index == 8)
{
QMetaObject::invokeMethod(&helper, "clearButtonsSlotsEventReset", Qt::BlockingQueuedConnection);
ui->diagonalRangeSlider->setValue(45);
}
QHash<JoyControlStick::JoyStickDirections, JoyButtonSlot*> tempHash;
tempHash.insert(JoyControlStick::StickUp, upButtonSlot);
tempHash.insert(JoyControlStick::StickDown, downButtonSlot);
tempHash.insert(JoyControlStick::StickLeft, leftButtonSlot);
tempHash.insert(JoyControlStick::StickRight, rightButtonSlot);
tempHash.insert(JoyControlStick::StickLeftUp, upLeftButtonSlot);
tempHash.insert(JoyControlStick::StickRightUp, upRightButtonSlot);
tempHash.insert(JoyControlStick::StickLeftDown, downLeftButtonSlot);
tempHash.insert(JoyControlStick::StickRightDown, downRightButtonSlot);
helper.setPendingSlots(&tempHash);
QMetaObject::invokeMethod(&helper, "setFromPendingSlots", Qt::BlockingQueuedConnection);
}
void JoyControlStickEditDialog::refreshStickStats(int x, int y)
{
Q_UNUSED(x);
Q_UNUSED(y);
PadderCommon::inputDaemonMutex.lock();
QString xCoorString = QString::number(stick->getXCoordinate());
if (stick->getCircleAdjust() > 0.0)
{
xCoorString.append(QString(" (%1)").arg(stick->getCircleXCoordinate()));
}
ui->xCoordinateLabel->setText(xCoorString);
QString yCoorString = QString::number(stick->getYCoordinate());
if (stick->getCircleAdjust() > 0.0)
{
yCoorString.append(QString(" (%1)").arg(stick->getCircleYCoordinate()));
}
ui->yCoordinateLabel->setText(yCoorString);
ui->distanceLabel->setText(QString::number(stick->getAbsoluteRawDistance()));
ui->diagonalLabel->setText(QString::number(stick->calculateBearing()));
double validDistance = stick->getDistanceFromDeadZone() * 100.0;
ui->fromSafeZoneValueLabel->setText(QString::number(validDistance));
PadderCommon::inputDaemonMutex.unlock();
}
void JoyControlStickEditDialog::checkMaxZone(int value)
{
if (value > ui->deadZoneSpinBox->value())
{
QMetaObject::invokeMethod(stick, "setMaxZone", Q_ARG(int, value));
}
}
void JoyControlStickEditDialog::implementModes(int index)
{
PadderCommon::inputDaemonMutex.lock();
stick->releaseButtonEvents();
if (index == 0)
{
stick->setJoyMode(JoyControlStick::StandardMode);
ui->diagonalRangeSlider->setEnabled(true);
ui->diagonalRangeSpinBox->setEnabled(true);
}
else if (index == 1)
{
stick->setJoyMode(JoyControlStick::EightWayMode);
ui->diagonalRangeSlider->setEnabled(true);
ui->diagonalRangeSpinBox->setEnabled(true);
}
else if (index == 2)
{
stick->setJoyMode(JoyControlStick::FourWayCardinal);
ui->diagonalRangeSlider->setEnabled(false);
ui->diagonalRangeSpinBox->setEnabled(false);
}
else if (index == 3)
{
stick->setJoyMode(JoyControlStick::FourWayDiagonal);
ui->diagonalRangeSlider->setEnabled(false);
ui->diagonalRangeSpinBox->setEnabled(false);
}
PadderCommon::inputDaemonMutex.unlock();
}
void JoyControlStickEditDialog::selectCurrentPreset()
{
JoyControlStickButton *upButton = stick->getDirectionButton(JoyControlStick::StickUp);
QList<JoyButtonSlot*> *upslots = upButton->getAssignedSlots();
JoyControlStickButton *downButton = stick->getDirectionButton(JoyControlStick::StickDown);
QList<JoyButtonSlot*> *downslots = downButton->getAssignedSlots();
JoyControlStickButton *leftButton = stick->getDirectionButton(JoyControlStick::StickLeft);
QList<JoyButtonSlot*> *leftslots = leftButton->getAssignedSlots();
JoyControlStickButton *rightButton = stick->getDirectionButton(JoyControlStick::StickRight);
QList<JoyButtonSlot*> *rightslots = rightButton->getAssignedSlots();
if (upslots->length() == 1 && downslots->length() == 1 &&
leftslots->length() == 1 && rightslots->length() == 1)
{
JoyButtonSlot *upslot = upslots->at(0);
JoyButtonSlot *downslot = downslots->at(0);
JoyButtonSlot *leftslot = leftslots->at(0);
JoyButtonSlot *rightslot = rightslots->at(0);
if (upslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && upslot->getSlotCode() == JoyButtonSlot::MouseUp &&
downslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && downslot->getSlotCode() == JoyButtonSlot::MouseDown &&
leftslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && leftslot->getSlotCode() == JoyButtonSlot::MouseLeft &&
rightslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && rightslot->getSlotCode() == JoyButtonSlot::MouseRight)
{
ui->presetsComboBox->setCurrentIndex(1);
}
else if (upslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && upslot->getSlotCode() == JoyButtonSlot::MouseUp &&
downslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && downslot->getSlotCode() == JoyButtonSlot::MouseDown &&
leftslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && leftslot->getSlotCode() == JoyButtonSlot::MouseRight &&
rightslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && rightslot->getSlotCode() == JoyButtonSlot::MouseLeft)
{
ui->presetsComboBox->setCurrentIndex(2);
}
else if (upslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && upslot->getSlotCode() == JoyButtonSlot::MouseDown &&
downslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && downslot->getSlotCode() == JoyButtonSlot::MouseUp &&
leftslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && leftslot->getSlotCode() == JoyButtonSlot::MouseLeft &&
rightslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && rightslot->getSlotCode() == JoyButtonSlot::MouseRight)
{
ui->presetsComboBox->setCurrentIndex(3);
}
else if (upslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && upslot->getSlotCode() == JoyButtonSlot::MouseDown &&
downslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && downslot->getSlotCode() == JoyButtonSlot::MouseUp &&
leftslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && leftslot->getSlotCode() == JoyButtonSlot::MouseRight &&
rightslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && rightslot->getSlotCode() == JoyButtonSlot::MouseLeft)
{
ui->presetsComboBox->setCurrentIndex(4);
}
else if (upslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(upslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Up) &&
downslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(downslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Down) &&
leftslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(leftslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Left) &&
rightslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(rightslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Right))
{
ui->presetsComboBox->setCurrentIndex(5);
}
else if (upslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(upslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_W) &&
downslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(downslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_S) &&
leftslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(leftslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_A) &&
rightslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(rightslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_D))
{
ui->presetsComboBox->setCurrentIndex(6);
}
else if (upslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(upslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_8) &&
downslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(downslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_2) &&
leftslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(leftslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_4) &&
rightslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(rightslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_6))
{
ui->presetsComboBox->setCurrentIndex(7);
}
}
else if (upslots->length() == 0 && downslots->length() == 0 &&
leftslots->length() == 0 && rightslots->length() == 0)
{
ui->presetsComboBox->setCurrentIndex(8);
}
}
void JoyControlStickEditDialog::updateMouseMode(int index)
{
PadderCommon::inputDaemonMutex.lock();
if (index == 1)
{
stick->setButtonsMouseMode(JoyButton::MouseCursor);
}
else if (index == 2)
{
stick->setButtonsMouseMode(JoyButton::MouseSpring);
}
PadderCommon::inputDaemonMutex.unlock();
}
void JoyControlStickEditDialog::openMouseSettingsDialog()
{
ui->mouseSettingsPushButton->setEnabled(false);
MouseControlStickSettingsDialog *dialog = new MouseControlStickSettingsDialog(this->stick, this);
dialog->show();
connect(this, SIGNAL(finished(int)), dialog, SLOT(close()));
connect(dialog, SIGNAL(finished(int)), this, SLOT(enableMouseSettingButton()));
}
void JoyControlStickEditDialog::enableMouseSettingButton()
{
ui->mouseSettingsPushButton->setEnabled(true);
}
void JoyControlStickEditDialog::updateWindowTitleStickName()
{
QString temp = QString(tr("Set")).append(" ");
if (!stick->getStickName().isEmpty())
{
temp.append(stick->getPartialName(false, true));
}
else
{
temp.append(stick->getPartialName());
}
if (stick->getParentSet()->getIndex() != 0)
{
unsigned int setIndex = stick->getParentSet()->getRealIndex();
temp.append(" [").append(tr("Set %1").arg(setIndex));
QString setName = stick->getParentSet()->getName();
if (!setName.isEmpty())
{
temp.append(": ").append(setName);
}
temp.append("]");
}
setWindowTitle(temp);
}
void JoyControlStickEditDialog::changeCircleAdjust(int value)
{
QMetaObject::invokeMethod(stick, "setCircleAdjust", Q_ARG(double, value * 0.01));
}
/**
* @brief Update QDoubleSpinBox value based on updated stick delay value.
* @param Delay value obtained from JoyControlStick.
*/
void JoyControlStickEditDialog::updateStickDelaySpinBox(int value)
{
double temp = static_cast<double>(value * 0.001);
ui->stickDelayDoubleSpinBox->setValue(temp);
}
/**
* @brief Update QSlider value based on value from QDoubleSpinBox.
* @param Value from QDoubleSpinBox.
*/
void JoyControlStickEditDialog::updateStickDelaySlider(double value)
{
int temp = static_cast<int>(value * 100);
if (ui->stickDelaySlider->value() != temp)
{
ui->stickDelaySlider->setValue(temp);
}
}
void JoyControlStickEditDialog::openModifierEditDialog()
{
ButtonEditDialog *dialog = new ButtonEditDialog(stick->getModifierButton(), this);
dialog->show();
}
void JoyControlStickEditDialog::changeModifierSummary()
{
ui->modifierPushButton->setText(stick->getModifierButton()->getSlotsSummary());
}
``` | /content/code_sandbox/src/joycontrolstickeditdialog.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 6,497 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include <QHash>
#include "dpadcontextmenu.h"
#include "mousedialog/mousedpadsettingsdialog.h"
#include "antkeymapper.h"
#include "inputdevice.h"
#include "common.h"
DPadContextMenu::DPadContextMenu(JoyDPad *dpad, QWidget *parent) :
QMenu(parent),
helper(dpad)
{
this->dpad = dpad;
helper.moveToThread(dpad->thread());
connect(this, SIGNAL(aboutToHide()), this, SLOT(deleteLater()));
}
/**
* @brief Generate the context menu that will be shown to a user when the person
* right clicks on the DPad settings button.
*/
void DPadContextMenu::buildMenu()
{
QAction *action = 0;
QActionGroup *presetGroup = new QActionGroup(this);
int presetMode = 0;
int currentPreset = getPresetIndex();
action = this->addAction(tr("Mouse (Normal)"));
action->setCheckable(true);
action->setChecked(currentPreset == presetMode+1);
action->setData(QVariant(presetMode));
connect(action, SIGNAL(triggered()), this, SLOT(setDPadPreset()));
presetGroup->addAction(action);
presetMode++;
action = this->addAction(tr("Mouse (Inverted Horizontal)"));
action->setCheckable(true);
action->setChecked(currentPreset == presetMode+1);
action->setData(QVariant(presetMode));
connect(action, SIGNAL(triggered()), this, SLOT(setDPadPreset()));
presetGroup->addAction(action);
presetMode++;
action = this->addAction(tr("Mouse (Inverted Vertical)"));
action->setCheckable(true);
action->setChecked(currentPreset == presetMode+1);
action->setData(QVariant(presetMode));
connect(action, SIGNAL(triggered()), this, SLOT(setDPadPreset()));
presetGroup->addAction(action);
presetMode++;
action = this->addAction(tr("Mouse (Inverted Horizontal + Vertical)"));
action->setCheckable(true);
action->setChecked(currentPreset == presetMode+1);
action->setData(QVariant(presetMode));
connect(action, SIGNAL(triggered()), this, SLOT(setDPadPreset()));
presetGroup->addAction(action);
presetMode++;
action = this->addAction(tr("Arrows"));
action->setCheckable(true);
action->setChecked(currentPreset == presetMode+1);
action->setData(QVariant(presetMode));
connect(action, SIGNAL(triggered()), this, SLOT(setDPadPreset()));
presetGroup->addAction(action);
presetMode++;
action = this->addAction(tr("Keys: W | A | S | D"));
action->setCheckable(true);
action->setChecked(currentPreset == presetMode+1);
action->setData(QVariant(presetMode));
connect(action, SIGNAL(triggered()), this, SLOT(setDPadPreset()));
presetGroup->addAction(action);
presetMode++;
action = this->addAction(tr("NumPad"));
action->setCheckable(true);
action->setChecked(currentPreset == presetMode+1);
action->setData(QVariant(presetMode));
connect(action, SIGNAL(triggered()), this, SLOT(setDPadPreset()));
presetGroup->addAction(action);
presetMode++;
action = this->addAction(tr("None"));
action->setCheckable(true);
action->setChecked(currentPreset == presetMode+1);
action->setData(QVariant(presetMode));
connect(action, SIGNAL(triggered()), this, SLOT(setDPadPreset()));
presetGroup->addAction(action);
this->addSeparator();
QActionGroup *modesGroup = new QActionGroup(this);
int mode = (int)JoyDPad::StandardMode;
action = this->addAction(tr("Standard"));
action->setCheckable(true);
action->setChecked(dpad->getJoyMode() == JoyDPad::StandardMode);
action->setData(QVariant(mode));
connect(action, SIGNAL(triggered()), this, SLOT(setDPadMode()));
modesGroup->addAction(action);
action = this->addAction(tr("Eight Way"));
action->setCheckable(true);
action->setChecked(dpad->getJoyMode() == JoyDPad::EightWayMode);
mode = (int)JoyDPad::EightWayMode;
action->setData(QVariant(mode));
connect(action, SIGNAL(triggered()), this, SLOT(setDPadMode()));
modesGroup->addAction(action);
action = this->addAction(tr("4 Way Cardinal"));
action->setCheckable(true);
action->setChecked(dpad->getJoyMode() == JoyDPad::FourWayCardinal);
mode = (int)JoyDPad::FourWayCardinal;
action->setData(QVariant(mode));
connect(action, SIGNAL(triggered()), this, SLOT(setDPadMode()));
modesGroup->addAction(action);
action = this->addAction(tr("4 Way Diagonal"));
action->setCheckable(true);
action->setChecked(dpad->getJoyMode() == JoyDPad::FourWayDiagonal);
mode = (int)JoyDPad::FourWayDiagonal;
action->setData(QVariant(mode));
connect(action, SIGNAL(triggered()), this, SLOT(setDPadMode()));
modesGroup->addAction(action);
this->addSeparator();
action = this->addAction(tr("Mouse Settings"));
action->setCheckable(false);
connect(action, SIGNAL(triggered()), this, SLOT(openMouseSettingsDialog()));
}
/**
* @brief Set the appropriate mode for a DPad based on the item chosen.
*/
void DPadContextMenu::setDPadMode()
{
QAction *action = static_cast<QAction*>(sender());
int item = action->data().toInt();
dpad->setJoyMode((JoyDPad::JoyMode)item);
}
/**
* @brief Assign the appropriate slots to DPad buttons based on the preset item
* that was chosen.
*/
void DPadContextMenu::setDPadPreset()
{
QAction *action = static_cast<QAction*>(sender());
int item = action->data().toInt();
JoyButtonSlot *upButtonSlot = 0;
JoyButtonSlot *downButtonSlot = 0;
JoyButtonSlot *leftButtonSlot = 0;
JoyButtonSlot *rightButtonSlot = 0;
JoyButtonSlot *upLeftButtonSlot = 0;
JoyButtonSlot *upRightButtonSlot = 0;
JoyButtonSlot *downLeftButtonSlot = 0;
JoyButtonSlot *downRightButtonSlot = 0;
if (item == 0)
{
PadderCommon::inputDaemonMutex.lock();
upButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseUp, JoyButtonSlot::JoyMouseMovement, this);
downButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseDown, JoyButtonSlot::JoyMouseMovement, this);
leftButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseLeft, JoyButtonSlot::JoyMouseMovement, this);
rightButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseRight, JoyButtonSlot::JoyMouseMovement, this);
dpad->setJoyMode(JoyDPad::StandardMode);
PadderCommon::inputDaemonMutex.unlock();
}
else if (item == 1)
{
PadderCommon::inputDaemonMutex.lock();
upButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseUp, JoyButtonSlot::JoyMouseMovement, this);
downButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseDown, JoyButtonSlot::JoyMouseMovement, this);
leftButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseRight, JoyButtonSlot::JoyMouseMovement, this);
rightButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseLeft, JoyButtonSlot::JoyMouseMovement, this);
dpad->setJoyMode(JoyDPad::StandardMode);
PadderCommon::inputDaemonMutex.unlock();
}
else if (item == 2)
{
PadderCommon::inputDaemonMutex.lock();
upButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseDown, JoyButtonSlot::JoyMouseMovement, this);
downButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseUp, JoyButtonSlot::JoyMouseMovement, this);
leftButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseLeft, JoyButtonSlot::JoyMouseMovement, this);
rightButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseRight, JoyButtonSlot::JoyMouseMovement, this);
dpad->setJoyMode(JoyDPad::StandardMode);
PadderCommon::inputDaemonMutex.unlock();
}
else if (item == 3)
{
PadderCommon::inputDaemonMutex.lock();
upButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseDown, JoyButtonSlot::JoyMouseMovement, this);
downButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseUp, JoyButtonSlot::JoyMouseMovement, this);
leftButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseRight, JoyButtonSlot::JoyMouseMovement, this);
rightButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseLeft, JoyButtonSlot::JoyMouseMovement, this);
dpad->setJoyMode(JoyDPad::StandardMode);
PadderCommon::inputDaemonMutex.unlock();
}
else if (item == 4)
{
PadderCommon::inputDaemonMutex.lock();
upButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Up), Qt::Key_Up, JoyButtonSlot::JoyKeyboard, this);
downButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Down), Qt::Key_Down, JoyButtonSlot::JoyKeyboard, this);
leftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Left), Qt::Key_Left, JoyButtonSlot::JoyKeyboard, this);
rightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Right), Qt::Key_Right, JoyButtonSlot::JoyKeyboard, this);
dpad->setJoyMode(JoyDPad::StandardMode);
PadderCommon::inputDaemonMutex.unlock();
}
else if (item == 5)
{
PadderCommon::inputDaemonMutex.lock();
upButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_W), Qt::Key_W, JoyButtonSlot::JoyKeyboard, this);
downButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_S), Qt::Key_S, JoyButtonSlot::JoyKeyboard, this);
leftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_A), Qt::Key_A, JoyButtonSlot::JoyKeyboard, this);
rightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_D), Qt::Key_D, JoyButtonSlot::JoyKeyboard, this);
dpad->setJoyMode(JoyDPad::StandardMode);
PadderCommon::inputDaemonMutex.unlock();
}
else if (item == 6)
{
PadderCommon::inputDaemonMutex.lock();
if (dpad->getJoyMode() == JoyDPad::StandardMode ||
dpad->getJoyMode() == JoyDPad::FourWayCardinal)
{
upButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_8), QtKeyMapperBase::AntKey_KP_8, JoyButtonSlot::JoyKeyboard, this);
downButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_2), QtKeyMapperBase::AntKey_KP_2, JoyButtonSlot::JoyKeyboard, this);
leftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_4), QtKeyMapperBase::AntKey_KP_4, JoyButtonSlot::JoyKeyboard, this);
rightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_6), QtKeyMapperBase::AntKey_KP_6, JoyButtonSlot::JoyKeyboard, this);
}
else if (dpad->getJoyMode() == JoyDPad::EightWayMode)
{
upButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_8), QtKeyMapperBase::AntKey_KP_8, JoyButtonSlot::JoyKeyboard, this);
downButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_2), QtKeyMapperBase::AntKey_KP_2, JoyButtonSlot::JoyKeyboard, this);
leftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_4), QtKeyMapperBase::AntKey_KP_4, JoyButtonSlot::JoyKeyboard, this);
rightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_6), QtKeyMapperBase::AntKey_KP_6, JoyButtonSlot::JoyKeyboard, this);
upLeftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_7), QtKeyMapperBase::AntKey_KP_7, JoyButtonSlot::JoyKeyboard, this);
upRightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_9), QtKeyMapperBase::AntKey_KP_9, JoyButtonSlot::JoyKeyboard, this);
downLeftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_1), QtKeyMapperBase::AntKey_KP_1, JoyButtonSlot::JoyKeyboard, this);
downRightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_3), QtKeyMapperBase::AntKey_KP_3, JoyButtonSlot::JoyKeyboard, this);
}
else if (dpad->getJoyMode() == JoyDPad::FourWayDiagonal)
{
upLeftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_7), QtKeyMapperBase::AntKey_KP_7, JoyButtonSlot::JoyKeyboard, this);
upRightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_9), QtKeyMapperBase::AntKey_KP_9, JoyButtonSlot::JoyKeyboard, this);
downLeftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_1), QtKeyMapperBase::AntKey_KP_1, JoyButtonSlot::JoyKeyboard, this);
downRightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_3), QtKeyMapperBase::AntKey_KP_3, JoyButtonSlot::JoyKeyboard, this);
}
PadderCommon::inputDaemonMutex.unlock();
}
else if (item == 7)
{
QMetaObject::invokeMethod(&helper, "clearButtonsSlotsEventReset", Qt::BlockingQueuedConnection);
}
QHash<JoyDPadButton::JoyDPadDirections, JoyButtonSlot*> tempHash;
tempHash.insert(JoyDPadButton::DpadUp, upButtonSlot);
tempHash.insert(JoyDPadButton::DpadDown, downButtonSlot);
tempHash.insert(JoyDPadButton::DpadLeft, leftButtonSlot);
tempHash.insert(JoyDPadButton::DpadRight, rightButtonSlot);
tempHash.insert(JoyDPadButton::DpadLeftUp, upLeftButtonSlot);
tempHash.insert(JoyDPadButton::DpadRightUp, upRightButtonSlot);
tempHash.insert(JoyDPadButton::DpadLeftDown, downLeftButtonSlot);
tempHash.insert(JoyDPadButton::DpadRightDown, downRightButtonSlot);
helper.setPendingSlots(&tempHash);
QMetaObject::invokeMethod(&helper, "setFromPendingSlots", Qt::BlockingQueuedConnection);
}
/**
* @brief Find the appropriate menu item index for the currently assigned
* slots that are assigned to a DPad.
* @return Menu index that corresponds to the currently assigned preset choice.
* 0 means that no matching preset was found.
*/
int DPadContextMenu::getPresetIndex()
{
int result = 0;
PadderCommon::inputDaemonMutex.lock();
JoyDPadButton *upButton = dpad->getJoyButton(JoyDPadButton::DpadUp);
QList<JoyButtonSlot*> *upslots = upButton->getAssignedSlots();
JoyDPadButton *downButton = dpad->getJoyButton(JoyDPadButton::DpadDown);
QList<JoyButtonSlot*> *downslots = downButton->getAssignedSlots();
JoyDPadButton *leftButton = dpad->getJoyButton(JoyDPadButton::DpadLeft);
QList<JoyButtonSlot*> *leftslots = leftButton->getAssignedSlots();
JoyDPadButton *rightButton = dpad->getJoyButton(JoyDPadButton::DpadRight);
QList<JoyButtonSlot*> *rightslots = rightButton->getAssignedSlots();
if (upslots->length() == 1 && downslots->length() == 1 && leftslots->length() == 1 && rightslots->length() == 1)
{
JoyButtonSlot *upslot = upslots->at(0);
JoyButtonSlot *downslot = downslots->at(0);
JoyButtonSlot *leftslot = leftslots->at(0);
JoyButtonSlot *rightslot = rightslots->at(0);
if (upslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && upslot->getSlotCode() == JoyButtonSlot::MouseUp &&
downslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && downslot->getSlotCode() == JoyButtonSlot::MouseDown &&
leftslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && leftslot->getSlotCode() == JoyButtonSlot::MouseLeft &&
rightslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && rightslot->getSlotCode() == JoyButtonSlot::MouseRight)
{
result = 1;
}
else if (upslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && upslot->getSlotCode() == JoyButtonSlot::MouseUp &&
downslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && downslot->getSlotCode() == JoyButtonSlot::MouseDown &&
leftslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && leftslot->getSlotCode() == JoyButtonSlot::MouseRight &&
rightslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && rightslot->getSlotCode() == JoyButtonSlot::MouseLeft)
{
result = 2;
}
else if (upslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && upslot->getSlotCode() == JoyButtonSlot::MouseDown &&
downslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && downslot->getSlotCode() == JoyButtonSlot::MouseUp &&
leftslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && leftslot->getSlotCode() == JoyButtonSlot::MouseLeft &&
rightslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && rightslot->getSlotCode() == JoyButtonSlot::MouseRight)
{
result = 3;
}
else if (upslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && upslot->getSlotCode() == JoyButtonSlot::MouseDown &&
downslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && downslot->getSlotCode() == JoyButtonSlot::MouseUp &&
leftslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && leftslot->getSlotCode() == JoyButtonSlot::MouseRight &&
rightslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && rightslot->getSlotCode() == JoyButtonSlot::MouseLeft)
{
result = 4;
}
else if (upslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(upslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Up) &&
downslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(downslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Down) &&
leftslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(leftslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Left) &&
rightslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(rightslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Right))
{
result = 5;
}
else if (upslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(upslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_W) &&
downslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(downslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_S) &&
leftslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(leftslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_A) &&
rightslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(rightslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_D))
{
result = 6;
}
else if (upslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(upslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_8) &&
downslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(downslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_2) &&
leftslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(leftslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_4) &&
rightslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(rightslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_6))
{
result = 7;
}
}
else if (upslots->length() == 0 && downslots->length() == 0 && leftslots->length() == 0 && rightslots->length() == 0)
{
result = 8;
}
PadderCommon::inputDaemonMutex.unlock();
return result;
}
/**
* @brief Open a mouse settings dialog for changing the mouse speed settings
* for all DPad buttons.
*/
void DPadContextMenu::openMouseSettingsDialog()
{
MouseDPadSettingsDialog *dialog = new MouseDPadSettingsDialog(dpad, parentWidget());
dialog->show();
}
``` | /content/code_sandbox/src/dpadcontextmenu.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 5,316 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef QTUINPUTKEYMAPPER_H
#define QTUINPUTKEYMAPPER_H
#include <QObject>
#include <QHash>
#include "qtkeymapperbase.h"
class QtUInputKeyMapper : public QtKeyMapperBase
{
Q_OBJECT
public:
explicit QtUInputKeyMapper(QObject *parent = 0);
protected:
void populateMappingHashes();
void populateCharKeyInformation();
void populateAlphaHashes();
void populateFKeyHashes();
void populateNumPadHashes();
void populateSpecialCharHashes();
signals:
public slots:
};
#endif // QTUINPUTKEYMAPPER_H
``` | /content/code_sandbox/src/qtuinputkeymapper.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 228 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
//#include <QDebug>
#include <QFileDialog>
#include <QFileInfo>
#include <QList>
#include <QListIterator>
#include <QMessageBox>
#include <QThread>
#include "addeditautoprofiledialog.h"
#include "ui_addeditautoprofiledialog.h"
#if defined(Q_OS_UNIX)
#ifdef WITH_X11
#include "unixcapturewindowutility.h"
#include "capturedwindowinfodialog.h"
#include "x11extras.h"
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
#include <QApplication>
#endif
#elif defined(Q_OS_WIN)
#include "winappprofiletimerdialog.h"
#include "capturedwindowinfodialog.h"
#include "winextras.h"
#endif
#include "common.h"
AddEditAutoProfileDialog::AddEditAutoProfileDialog(AutoProfileInfo *info, AntiMicroSettings *settings,
QList<InputDevice*> *devices,
QList<QString> &reservedGUIDS, bool edit, QWidget *parent) :
QDialog(parent),
ui(new Ui::AddEditAutoProfileDialog)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
this->info = info;
this->settings = settings;
this->editForm = edit;
this->devices = devices;
this->originalGUID = info->getGUID();
this->originalExe = info->getExe();
this->originalWindowClass = info->getWindowClass();
this->originalWindowName = info->getWindowName();
QListIterator<QString> iterGUIDs(reservedGUIDS);
while (iterGUIDs.hasNext())
{
QString guid = iterGUIDs.next();
if (!this->reservedGUIDs.contains(guid))
{
this->reservedGUIDs.append(guid);
}
}
bool allowDefault = false;
if (info->getGUID() != "all" &&
info->getGUID() != "" &&
!this->reservedGUIDs.contains(info->getGUID()))
{
allowDefault = true;
}
if (allowDefault && info->getExe().isEmpty())
{
ui->asDefaultCheckBox->setEnabled(true);
if (info->isCurrentDefault())
{
ui->asDefaultCheckBox->setChecked(true);
}
}
else
{
ui->asDefaultCheckBox->setToolTip(tr("A different profile is already selected as the default for this device."));
}
//if (!edit)
//{
ui->devicesComboBox->addItem("all");
QListIterator<InputDevice*> iter(*devices);
int found = -1;
int numItems = 1;
while (iter.hasNext())
{
InputDevice *device = iter.next();
ui->devicesComboBox->addItem(device->getSDLName(), QVariant::fromValue<InputDevice*>(device));
if (device->getGUIDString() == info->getGUID())
{
found = numItems;
}
numItems++;
}
if (!info->getGUID().isEmpty() && info->getGUID() != "all")
{
if (found >= 0)
{
ui->devicesComboBox->setCurrentIndex(found);
}
else
{
ui->devicesComboBox->addItem(tr("Current (%1)").arg(info->getDeviceName()));
ui->devicesComboBox->setCurrentIndex(ui->devicesComboBox->count()-1);
}
}
//}
ui->profileLineEdit->setText(info->getProfileLocation());
ui->applicationLineEdit->setText(info->getExe());
ui->winClassLineEdit->setText(info->getWindowClass());
ui->winNameLineEdit->setText(info->getWindowName());
#ifdef Q_OS_UNIX
ui->selectWindowPushButton->setVisible(false);
#elif defined(Q_OS_WIN)
ui->detectWinPropsSelectWindowPushButton->setVisible(false);
ui->winClassLineEdit->setVisible(false);
ui->winClassLabel->setVisible(false);
//ui->winNameLineEdit->setVisible(false);
//ui->winNameLabel->setVisible(false);
#endif
connect(ui->profileBrowsePushButton, SIGNAL(clicked()), this, SLOT(openProfileBrowseDialog()));
connect(ui->applicationPushButton, SIGNAL(clicked()), this, SLOT(openApplicationBrowseDialog()));
connect(ui->devicesComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(checkForReservedGUIDs(int)));
connect(ui->applicationLineEdit, SIGNAL(textChanged(QString)), this, SLOT(checkForDefaultStatus()));
connect(ui->winClassLineEdit, SIGNAL(textChanged(QString)), this, SLOT(checkForDefaultStatus()));
connect(ui->winNameLineEdit, SIGNAL(textChanged(QString)), this, SLOT(checkForDefaultStatus()));
#if defined(Q_OS_UNIX)
connect(ui->detectWinPropsSelectWindowPushButton, SIGNAL(clicked()), this, SLOT(showCaptureHelpWindow()));
#elif defined(Q_OS_WIN)
connect(ui->selectWindowPushButton, SIGNAL(clicked()), this, SLOT(openWinAppProfileDialog()));
#endif
connect(this, SIGNAL(accepted()), this, SLOT(saveAutoProfileInformation()));
}
AddEditAutoProfileDialog::~AddEditAutoProfileDialog()
{
delete ui;
}
void AddEditAutoProfileDialog::openProfileBrowseDialog()
{
QString lookupDir = PadderCommon::preferredProfileDir(settings);
QString filename = QFileDialog::getOpenFileName(this, tr("Open Config"), lookupDir, QString("Config Files (*.amgp *.xml)"));
if (!filename.isNull() && !filename.isEmpty())
{
ui->profileLineEdit->setText(QDir::toNativeSeparators(filename));
}
}
void AddEditAutoProfileDialog::openApplicationBrowseDialog()
{
/*QString filename;
QFileDialog dialog(this, tr("Select Program"), QDir::homePath());
dialog.setFilter(QDir::Files | QDir::Executable);
if (dialog.exec())
{
filename = dialog.selectedFiles().first();
}*/
#ifdef Q_OS_WIN
QString filename = QFileDialog::getOpenFileName(this, tr("Select Program"), QDir::homePath(), tr("Programs (*.exe)"));
#else
QString filename = QFileDialog::getOpenFileName(this, tr("Select Program"), QDir::homePath(), QString());
#endif
if (!filename.isNull() && !filename.isEmpty())
{
QFileInfo exe(filename);
if (exe.exists() && exe.isExecutable())
{
ui->applicationLineEdit->setText(filename);
}
}
}
AutoProfileInfo* AddEditAutoProfileDialog::getAutoProfile()
{
return info;
}
void AddEditAutoProfileDialog::saveAutoProfileInformation()
{
info->setProfileLocation(ui->profileLineEdit->text());
int deviceIndex = ui->devicesComboBox->currentIndex();
if (deviceIndex > 0)
{
QVariant temp = ui->devicesComboBox->itemData(deviceIndex, Qt::UserRole);
// Assume that if the following is not true, the GUID should
// not be changed.
if (!temp.isNull())
{
InputDevice *device = ui->devicesComboBox->itemData(deviceIndex, Qt::UserRole).value<InputDevice*>();
info->setGUID(device->getGUIDString());
info->setDeviceName(device->getSDLName());
}
}
else
{
info->setGUID("all");
info->setDeviceName("");
}
info->setExe(ui->applicationLineEdit->text());
info->setWindowClass(ui->winClassLineEdit->text());
info->setWindowName(ui->winNameLineEdit->text());
info->setDefaultState(ui->asDefaultCheckBox->isChecked());
//info->setActive(true);
}
void AddEditAutoProfileDialog::checkForReservedGUIDs(int index)
{
QVariant data = ui->devicesComboBox->itemData(index);
if (index == 0)
{
ui->asDefaultCheckBox->setChecked(false);
ui->asDefaultCheckBox->setEnabled(false);
ui->asDefaultCheckBox->setToolTip(tr("Please use the main default profile selection."));
}
else if (!data.isNull())
{
InputDevice *device = data.value<InputDevice*>();
if (reservedGUIDs.contains(device->getGUIDString()))
{
ui->asDefaultCheckBox->setChecked(false);
ui->asDefaultCheckBox->setEnabled(false);
ui->asDefaultCheckBox->setToolTip(tr("A different profile is already selected as the default for this device."));
}
else
{
ui->asDefaultCheckBox->setEnabled(true);
ui->asDefaultCheckBox->setToolTip(tr("Select this profile to be the default loaded for\nthe specified device. The selection will be used instead\nof the all default profile option."));
}
}
}
QString AddEditAutoProfileDialog::getOriginalGUID()
{
return originalGUID;
}
QString AddEditAutoProfileDialog::getOriginalExe()
{
return originalExe;
}
QString AddEditAutoProfileDialog::getOriginalWindowClass()
{
return originalWindowClass;
}
QString AddEditAutoProfileDialog::getOriginalWindowName()
{
return originalWindowName;
}
#ifdef Q_OS_UNIX
/**
* @brief Display a simple message box and attempt to capture a window using the mouse
*/
void AddEditAutoProfileDialog::showCaptureHelpWindow()
{
#ifdef WITH_X11
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
QMessageBox *box = new QMessageBox(this);
box->setText(tr("Please select a window by using the mouse. Press Escape if you want to cancel."));
box->setWindowTitle(tr("Capture Application Window"));
box->setStandardButtons(QMessageBox::NoButton);
box->setModal(true);
box->show();
UnixCaptureWindowUtility *util = new UnixCaptureWindowUtility();
QThread *thread = new QThread(this);
util->moveToThread(thread);
connect(thread, SIGNAL(started()), util, SLOT(attemptWindowCapture()));
connect(util, SIGNAL(captureFinished()), thread, SLOT(quit()));
connect(util, SIGNAL(captureFinished()), box, SLOT(hide()));
connect(util, SIGNAL(captureFinished()), this, SLOT(checkForGrabbedWindow()), Qt::QueuedConnection);
connect(thread, SIGNAL(finished()), box, SLOT(deleteLater()));
connect(util, SIGNAL(destroyed()), thread, SLOT(deleteLater()));
thread->start();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
#endif
#endif
}
/**
* @brief Check if there is a program path saved in an UnixCaptureWindowUtility
* object
*/
void AddEditAutoProfileDialog::checkForGrabbedWindow()
{
#ifdef WITH_X11
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
UnixCaptureWindowUtility *util = static_cast<UnixCaptureWindowUtility*>(sender());
unsigned long targetWindow = util->getTargetWindow();
bool escaped = !util->hasFailed();
bool failed = false;
QString path;
if (targetWindow != None)
{
// Attempt to find the appropriate window below the root window
// that was clicked.
//qDebug() << "ORIGINAL: " << QString::number(targetWindow, 16);
unsigned long tempWindow = X11Extras::getInstance()->findClientWindow(targetWindow);
if (tempWindow > 0)
{
targetWindow = tempWindow;
}
//qDebug() << "ADJUSTED: " << QString::number(targetWindow, 16);
}
if (targetWindow != None)
{
CapturedWindowInfoDialog *dialog = new CapturedWindowInfoDialog(targetWindow, this);
connect(dialog, SIGNAL(accepted()), this, SLOT(windowPropAssignment()));
dialog->show();
/*QString ham = X11Info::getInstance()->getWindowTitle(targetWindow);
int pid = X11Info::getInstance()->getApplicationPid(targetWindow);
if (pid > 0)
{
//qDebug() << "THIS ID: " << pid;
QString exepath = X11Info::getInstance()->getApplicationLocation(pid);
if (!exepath.isEmpty())
{
path = exepath;
}
else if (!failed)
{
failed = true;
}
}
else if (!failed)
{
failed = true;
}*/
}
else if (!escaped)
{
failed = true;
}
/*if (!path.isEmpty())
{
ui->applicationLineEdit->setText(path);
}*/
// Ensure that the operation was not cancelled (Escape wasn't pressed).
if (failed)
{
QMessageBox box;
box.setText(tr("Could not obtain information for the selected window."));
box.setWindowTitle(tr("Application Capture Failed"));
box.setStandardButtons(QMessageBox::Close);
box.raise();
box.exec();
}
util->deleteLater();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
#endif
#endif
}
#endif
void AddEditAutoProfileDialog::windowPropAssignment()
{
disconnect(ui->applicationLineEdit, SIGNAL(textChanged(QString)), this, SLOT(checkForDefaultStatus()));
disconnect(ui->winClassLineEdit, SIGNAL(textChanged(QString)), this, SLOT(checkForDefaultStatus()));
disconnect(ui->winNameLineEdit, SIGNAL(textChanged(QString)), this, SLOT(checkForDefaultStatus()));
CapturedWindowInfoDialog *dialog = static_cast<CapturedWindowInfoDialog*>(sender());
if (dialog->getSelectedOptions() & CapturedWindowInfoDialog::WindowPath)
{
if (dialog->useFullWindowPath())
{
ui->applicationLineEdit->setText(dialog->getWindowPath());
}
else
{
QString temp;
temp = QFileInfo(dialog->getWindowPath()).fileName();
ui->applicationLineEdit->setText(temp);
}
}
else
{
ui->applicationLineEdit->clear();
}
if (dialog->getSelectedOptions() & CapturedWindowInfoDialog::WindowClass)
{
ui->winClassLineEdit->setText(dialog->getWindowClass());
}
else
{
ui->winClassLineEdit->clear();
}
if (dialog->getSelectedOptions() & CapturedWindowInfoDialog::WindowName)
{
ui->winNameLineEdit->setText(dialog->getWindowName());
}
else
{
ui->winNameLineEdit->clear();
}
checkForDefaultStatus();
connect(ui->applicationLineEdit, SIGNAL(textChanged(QString)), this, SLOT(checkForDefaultStatus()));
connect(ui->winClassLineEdit, SIGNAL(textChanged(QString)), this, SLOT(checkForDefaultStatus()));
connect(ui->winNameLineEdit, SIGNAL(textChanged(QString)), this, SLOT(checkForDefaultStatus()));
}
void AddEditAutoProfileDialog::checkForDefaultStatus()
{
bool status = ui->applicationLineEdit->text().length() > 0;
status = status ? status : ui->winClassLineEdit->text().length() > 0;
status = status ? status : ui->winNameLineEdit->text().length() > 0;
if (status)
{
ui->asDefaultCheckBox->setChecked(false);
ui->asDefaultCheckBox->setEnabled(false);
}
else
{
ui->asDefaultCheckBox->setEnabled(true);
}
}
/**
* @brief Validate the form that is contained in this window
*/
void AddEditAutoProfileDialog::accept()
{
bool validForm = true;
bool propertyFound = false;
QString errorString;
if (ui->profileLineEdit->text().length() > 0)
{
QString profileFilename = ui->profileLineEdit->text();
QFileInfo info(profileFilename);
if (!info.exists())
{
validForm = false;
errorString = tr("Profile file path is invalid.");
}
}
if (validForm &&
(ui->applicationLineEdit->text().isEmpty() &&
ui->winClassLineEdit->text().isEmpty() &&
ui->winNameLineEdit->text().isEmpty()))
{
validForm = false;
errorString = tr("No window matching property was specified.");
}
else
{
propertyFound = true;
}
if (validForm && !ui->applicationLineEdit->text().isEmpty())
{
QString exeFileName = ui->applicationLineEdit->text();
QFileInfo info(exeFileName);
if (info.isAbsolute() && (!info.exists() || !info.isExecutable()))
{
validForm = false;
errorString = tr("Program path is invalid or not executable.");
}
#ifdef Q_OS_WIN
else if (!info.isAbsolute() &&
(info.fileName() != exeFileName ||
info.suffix() != "exe"))
{
validForm = false;
errorString = tr("File is not an .exe file.");
}
#endif
}
if (validForm && !propertyFound && !ui->asDefaultCheckBox->isChecked())
{
validForm = false;
errorString = tr("No window matching property was selected.");
}
if (validForm)
{
QDialog::accept();
}
else
{
QMessageBox msgBox;
msgBox.setText(errorString);
msgBox.setStandardButtons(QMessageBox::Close);
msgBox.exec();
}
}
#ifdef Q_OS_WIN
void AddEditAutoProfileDialog::openWinAppProfileDialog()
{
WinAppProfileTimerDialog *dialog = new WinAppProfileTimerDialog(this);
connect(dialog, SIGNAL(accepted()), this, SLOT(captureWindowsApplicationPath()));
dialog->show();
}
void AddEditAutoProfileDialog::captureWindowsApplicationPath()
{
CapturedWindowInfoDialog *dialog = new CapturedWindowInfoDialog(this);
connect(dialog, SIGNAL(accepted()), this, SLOT(windowPropAssignment()));
dialog->show();
/*QString temp = WinExtras::getForegroundWindowExePath();
if (!temp.isEmpty())
{
ui->applicationLineEdit->setText(temp);
}
*/
}
#endif
``` | /content/code_sandbox/src/addeditautoprofiledialog.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 3,908 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef UNIXCAPTUREWINDOWUTILITY_H
#define UNIXCAPTUREWINDOWUTILITY_H
#include <QObject>
class UnixCaptureWindowUtility : public QObject
{
Q_OBJECT
public:
explicit UnixCaptureWindowUtility(QObject *parent = 0);
QString getTargetPath();
bool hasFailed();
unsigned long getTargetWindow();
protected:
QString targetPath;
bool failed;
unsigned long targetWindow;
signals:
void captureFinished();
public slots:
void attemptWindowCapture();
};
#endif // UNIXCAPTUREWINDOWUTILITY_H
``` | /content/code_sandbox/src/unixcapturewindowutility.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 206 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef MOUSESETTINGSDIALOG_H
#define MOUSESETTINGSDIALOG_H
#include <QDialog>
#include <QTime>
#include "joybutton.h"
namespace Ui {
class MouseSettingsDialog;
}
class MouseSettingsDialog : public QDialog
{
Q_OBJECT
public:
explicit MouseSettingsDialog(QWidget *parent = 0);
~MouseSettingsDialog();
protected:
void updateAccelerationCurvePresetComboBox(JoyButton::JoyMouseCurve mouseCurve);
void updateExtraAccelerationCurvePresetComboBox(JoyButton::JoyExtraAccelerationCurve curve);
JoyButton::JoyMouseCurve getMouseCurveForIndex(int index);
JoyButton::JoyExtraAccelerationCurve getExtraAccelCurveForIndex(int index);
Ui::MouseSettingsDialog *ui;
QTime lastMouseStatUpdate;
public slots:
void changeSettingsWidgetStatus(int index);
void changeSpringSectionStatus(int index);
void changeMouseSpeedBoxStatus(int index);
void changeWheelSpeedBoxStatus(int index);
void updateHorizontalSpeedConvertLabel(int value);
void updateVerticalSpeedConvertLabel(int value);
void moveSpeedsTogether(int value);
//void changeSmoothingStatus(int index);
void updateWheelVerticalSpeedLabel(int value);
void updateWheelHorizontalSpeedLabel(int value);
void changeSensitivityStatusForMouseMode(int index);
virtual void changeMouseMode(int index) = 0;
virtual void changeMouseCurve(int index) = 0;
private slots:
void updateMouseCursorStatusLabels(int mouseX, int mouseY, int elapsed);
void updateMouseSpringStatusLabels(int coordX, int coordY);
void refreshMouseCursorSpeedValues(int index);
void disableReleaseSpringBox(bool enable);
void resetReleaseRadius(bool enabled);
};
#endif // MOUSESETTINGSDIALOG_H
``` | /content/code_sandbox/src/mousesettingsdialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 466 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include <QTime>
#include "logger.h"
Logger* Logger::instance = 0;
/**
* @brief Outputs log messages to a given text stream. Client code
* should determine whether it points to a console stream or
* to a file.
* @param Stream used to output text
* @param Messages based of a given output level or lower will be logged
* @param Parent object
*/
Logger::Logger(QTextStream *stream, LogLevel outputLevel, QObject *parent) :
QObject(parent)
{
instance = this;
instance->outputStream = stream;
instance->outputLevel = outputLevel;
instance->errorStream = 0;
instance->pendingTimer.setInterval(1);
instance->pendingTimer.setSingleShot(true);
instance->writeTime = false;
connect(instance, SIGNAL(pendingMessage()), instance, SLOT(startPendingTimer()));
connect(&(instance->pendingTimer), SIGNAL(timeout()), instance, SLOT(Log()));
}
/**
* @brief Outputs log messages to a given text stream. Client code
* should determine whether it points to a console stream or
* to a file.
* @param Stream used to output standard text
* @param Stream used to output error text
* @param Messages based of a given output level or lower will be logged
* @param Parent object
*/
Logger::Logger(QTextStream *stream, QTextStream *errorStream,
LogLevel outputLevel, QObject *parent) :
QObject(parent)
{
instance = this;
instance->outputStream = stream;
instance->outputLevel = outputLevel;
instance->errorStream = errorStream;
instance->pendingTimer.setInterval(1);
instance->pendingTimer.setSingleShot(true);
instance->writeTime = false;
connect(instance, SIGNAL(pendingMessage()), instance, SLOT(startPendingTimer()));
connect(&(instance->pendingTimer), SIGNAL(timeout()), instance, SLOT(Log()));
}
/**
* @brief Close output stream and set instance to 0.
*/
Logger::~Logger()
{
closeLogger();
closeErrorLogger();
}
/**
* @brief Set the highest logging level. Determines which messages
* are output to the output stream.
* @param Highest log level utilized.
*/
void Logger::setLogLevel(LogLevel level)
{
Q_ASSERT(instance != 0);
QMutexLocker locker(&instance->logMutex);
Q_UNUSED(locker);
instance->outputLevel = level;
}
/**
* @brief Get the current output level associated with the logger.
* @return Current output level
*/
Logger::LogLevel Logger::getCurrentLogLevel()
{
Q_ASSERT(instance != 0);
return instance->outputLevel;
}
void Logger::setCurrentStream(QTextStream *stream)
{
Q_ASSERT(instance != 0);
QMutexLocker locker(&instance->logMutex);
Q_UNUSED(locker);
instance->outputStream->flush();
instance->outputStream = stream;
}
QTextStream* Logger::getCurrentStream()
{
Q_ASSERT(instance != 0);
return instance->outputStream;
}
void Logger::setCurrentErrorStream(QTextStream *stream)
{
Q_ASSERT(instance != 0);
QMutexLocker locker(&instance->logMutex);
Q_UNUSED(locker);
if (instance->errorStream)
{
instance->errorStream->flush();
}
instance->errorStream = stream;
}
QTextStream* Logger::getCurrentErrorStream()
{
Q_ASSERT(instance != 0);
return instance->errorStream;
}
/**
* @brief Go through a list of pending messages and check if message should be
* logged according to the set log level. Log the message to the output
* stream.
* @param Log level
* @param String to write to output stream if appropriate to the current
* log level.
*/
void Logger::Log()
{
QMutexLocker locker(&logMutex);
Q_UNUSED(locker);
QListIterator<LogMessage> iter(pendingMessages);
while (iter.hasNext())
{
LogMessage pendingMessage = iter.next();
logMessage(pendingMessage);
}
pendingMessages.clear();
instance->pendingTimer.stop();
}
/**
* @brief Flushes output stream and closes stream if requested.
* @param Whether to close the current stream. Defaults to true.
*/
void Logger::closeLogger(bool closeStream)
{
if (outputStream)
{
outputStream->flush();
if (closeStream && outputStream->device() != 0)
{
QIODevice *device = outputStream->device();
if (device->isOpen())
{
device->close();
}
}
}
}
/**
* @brief Flushes output stream and closes stream if requested.
* @param Whether to close the current stream. Defaults to true.
*/
void Logger::closeErrorLogger(bool closeStream)
{
if (errorStream)
{
errorStream->flush();
if (closeStream && errorStream->device() != 0)
{
QIODevice *device = errorStream->device();
if (device->isOpen())
{
device->close();
}
}
}
instance->pendingTimer.stop();
instance = 0;
}
/**
* @brief Append message to list of messages that might get placed in the
* log. Messages will be written later.
* @param Log level
* @param String to write to output stream if appropriate to the current
* log level.
* @param Whether the logger should add a newline to the end of the message.
*/
void Logger::appendLog(LogLevel level, const QString &message, bool newline)
{
Q_ASSERT(instance != 0);
QMutexLocker locker(&instance->logMutex);
Q_UNUSED(locker);
LogMessage temp;
temp.level = level;
temp.message = QString(message);
temp.newline = newline;
instance->pendingMessages.append(temp);
/*if (!instance->pendingTimer.isActive())
{
instance->pendingTimer.start();
}
*/
emit instance->pendingMessage();
}
/**
* @brief Immediately write a message to a text stream.
* @param Log level
* @param String to write to output stream if appropriate to the current
* log level.
* @param Whether the logger should add a newline to the end of the message.
*/
void Logger::directLog(LogLevel level, const QString &message, bool newline)
{
Q_ASSERT(instance != 0);
QMutexLocker locker(&instance->logMutex);
Q_UNUSED(locker);
LogMessage temp;
temp.level = level;
temp.message = QString(message);
temp.newline = newline;
instance->logMessage(temp);
}
/**
* @brief Write an individual message to the text stream.
* @param LogMessage instance for a single message
*/
void Logger::logMessage(LogMessage msg)
{
LogLevel level = msg.level;
QString message = msg.message;
bool newline = msg.newline;
if (outputLevel != LOG_NONE && level <= outputLevel)
{
QString displayTime = "";
QString initialPrefix = "";
QString finalMessage;
if (outputLevel > LOG_INFO || writeTime)
{
displayTime = QString("[%1] - ").arg(QTime::currentTime().toString("hh:mm:ss.zzz"));
initialPrefix = displayTime;
}
QTextStream *writeStream = outputStream;
if (level < LOG_INFO && errorStream)
{
writeStream = errorStream;
}
finalMessage.append(initialPrefix).append(message);
//*writeStream << initialPrefix << message;
if (newline)
{
finalMessage.append("\n");
//*writeStream << endl;
}
*writeStream << finalMessage;
writeStream->flush();
emit stringWritten(finalMessage);
}
}
/**
* @brief Get the associated timer used by the logger.
* @return QTimer instance
*/
QTimer* Logger::getLogTimer()
{
return &pendingTimer;
}
/**
* @brief Stop the logger's timer if it is currently active.
*/
void Logger::stopLogTimer()
{
if (pendingTimer.isActive())
{
pendingTimer.stop();
}
}
/**
* @brief Set whether the current time should be written with a message.
* This property is only used if outputLevel is set to LOG_INFO.
* @param status
*/
void Logger::setWriteTime(bool status)
{
Q_ASSERT(instance != 0);
QMutexLocker locker(&instance->logMutex);
Q_UNUSED(locker);
writeTime = status;
}
/**
* @brief Get whether the current time should be written with a LOG_INFO
* message.
* @return Whether the current time is written with a LOG_INFO message
*/
bool Logger::getWriteTime()
{
Q_ASSERT(instance != 0);
return writeTime;
}
void Logger::startPendingTimer()
{
Q_ASSERT(instance != 0);
if (!instance->pendingTimer.isActive())
{
instance->pendingTimer.start();
}
}
void Logger::setCurrentLogFile(QString filename) {
Q_ASSERT(instance != 0);
if( instance->outputFile.isOpen() ) {
instance->closeLogger(true);
}
instance->outputFile.setFileName( filename );
instance->outputFile.open( QIODevice::WriteOnly | QIODevice::Append );
instance->outFileStream.setDevice( &instance->outputFile );
instance->setCurrentStream( &instance->outFileStream );
instance->LogInfo(QObject::tr("Logging started"), true, true);
}
void Logger::setCurrentErrorLogFile(QString filename) {
Q_ASSERT(instance != 0);
if( instance->errorFile.isOpen() ) {
instance->closeErrorLogger(true);
}
instance->errorFile.setFileName( filename );
instance->errorFile.open( QIODevice::WriteOnly | QIODevice::Append );
instance->outErrorFileStream.setDevice( &instance->errorFile );
instance->setCurrentErrorStream( &instance->outErrorFileStream );
}
``` | /content/code_sandbox/src/logger.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 2,180 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef DPADPUSHBUTTONGROUP_H
#define DPADPUSHBUTTONGROUP_H
#include <QGridLayout>
#include "joydpad.h"
#include "joydpadbuttonwidget.h"
#include "dpadpushbutton.h"
class DPadPushButtonGroup : public QGridLayout
{
Q_OBJECT
public:
explicit DPadPushButtonGroup(JoyDPad *dpad, bool displayNames = false, QWidget *parent = 0);
JoyDPad *getDPad();
protected:
void generateButtons();
JoyDPad *dpad;
bool displayNames;
JoyDPadButtonWidget *upButton;
JoyDPadButtonWidget *downButton;
JoyDPadButtonWidget *leftButton;
JoyDPadButtonWidget *rightButton;
JoyDPadButtonWidget *upLeftButton;
JoyDPadButtonWidget *upRightButton;
JoyDPadButtonWidget *downLeftButton;
JoyDPadButtonWidget *downRightButton;
DPadPushButton *dpadWidget;
signals:
void buttonSlotChanged();
public slots:
void changeButtonLayout();
void toggleNameDisplay();
private slots:
void propogateSlotsChanged();
void openDPadButtonDialog();
void showDPadDialog();
};
#endif // DPADPUSHBUTTONGROUP_H
``` | /content/code_sandbox/src/dpadpushbuttongroup.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 378 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
//#include <QDebug>
#include <QCoreApplication>
#include <QLayoutItem>
#include <QGroupBox>
#include <QMessageBox>
#include <QTextStream>
#include <QStringListIterator>
#include <QMenu>
#include "joytabwidget.h"
#include "joyaxiswidget.h"
#include "joybuttonwidget.h"
#include "xmlconfigreader.h"
#include "xmlconfigwriter.h"
#include "buttoneditdialog.h"
#include "advancestickassignmentdialog.h"
#include "quicksetdialog.h"
#include "extraprofilesettingsdialog.h"
#include "setnamesdialog.h"
#include "stickpushbuttongroup.h"
#include "dpadpushbuttongroup.h"
#include "common.h"
#ifdef USE_SDL_2
#include "gamecontroller/gamecontroller.h"
#include "gamecontrollermappingdialog.h"
#endif
JoyTabWidget::JoyTabWidget(InputDevice *joystick, AntiMicroSettings *settings, QWidget *parent) :
QWidget(parent),
tabHelper(joystick)
{
this->joystick = joystick;
this->settings = settings;
tabHelper.moveToThread(joystick->thread());
comboBoxIndex = 0;
hideEmptyButtons = false;
verticalLayout = new QVBoxLayout (this);
verticalLayout->setContentsMargins(4, 4, 4, 4);
configHorizontalLayout = new QHBoxLayout();
configBox = new QComboBox(this);
configBox->addItem(tr("<New>"), "");
configBox->setObjectName(QString::fromUtf8("configBox"));
configBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
configHorizontalLayout->addWidget(configBox);
spacer1 = new QSpacerItem(30, 20, QSizePolicy::Fixed, QSizePolicy::Fixed);
configHorizontalLayout->addItem(spacer1);
removeButton = new QPushButton(tr("Remove"), this);
removeButton->setObjectName(QString::fromUtf8("removeButton"));
removeButton->setToolTip(tr("Remove configuration from recent list."));
//removeButton->setFixedWidth(100);
removeButton->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
removeButton->setIcon(QIcon::fromTheme("edit-clear-list"));
configHorizontalLayout->addWidget(removeButton);
loadButton = new QPushButton(tr("Load"), this);
loadButton->setObjectName(QString::fromUtf8("loadButton"));
loadButton->setToolTip(tr("Load configuration file."));
//loadButton->setFixedWidth(100);
loadButton->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
loadButton->setIcon(QIcon::fromTheme("document-open"));
configHorizontalLayout->addWidget(loadButton);
saveButton = new QPushButton(tr("Save"), this);
saveButton->setObjectName(QString::fromUtf8("saveButton"));
saveButton->setToolTip(tr("Save changes to configuration file."));
//saveButton->setFixedWidth(100);
saveButton->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
saveButton->setIcon(QIcon::fromTheme("document-save"));
configHorizontalLayout->addWidget(saveButton);
//configHorizontalLayout->setSpacing(-1);
saveAsButton = new QPushButton(tr("Save As"), this);
saveAsButton->setObjectName(QString::fromUtf8("saveAsButton"));
saveAsButton->setToolTip(tr("Save changes to a new configuration file."));
//saveAsButton->setFixedWidth(100);
saveAsButton->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
saveAsButton->setIcon(QIcon::fromTheme("document-save-as"));
configHorizontalLayout->addWidget(saveAsButton);
verticalLayout->addLayout(configHorizontalLayout);
verticalLayout->setStretchFactor(configHorizontalLayout, 1);
spacer2 = new QSpacerItem(20, 5, QSizePolicy::Fixed, QSizePolicy::Fixed);
verticalLayout->addItem(spacer2);
verticalSpacer_2 = new QSpacerItem(20, 5, QSizePolicy::Minimum, QSizePolicy::Fixed);
verticalLayout->addItem(verticalSpacer_2);
stackedWidget_2 = new QStackedWidget(this);
stackedWidget_2->setObjectName(QString::fromUtf8("stackedWidget_2"));
page = new QWidget();
page->setObjectName(QString::fromUtf8("page"));
QVBoxLayout *tempVBoxLayout = new QVBoxLayout(page);
QScrollArea *scrollArea = new QScrollArea();
scrollArea->setObjectName(QString::fromUtf8("scrollArea1"));
QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
//sizePolicy.setHorizontalStretch(0);
//sizePolicy.setVerticalStretch(0);
scrollArea->setSizePolicy(sizePolicy);
scrollArea->setWidgetResizable(true);
QWidget *scrollAreaWidgetContents1 = new QWidget();
scrollAreaWidgetContents1->setObjectName(QString::fromUtf8("scrollAreaWidgetContents1"));
gridLayout = new QGridLayout(scrollAreaWidgetContents1);
gridLayout->setSpacing(4);
gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
scrollArea->setWidget(scrollAreaWidgetContents1);
tempVBoxLayout->addWidget(scrollArea);
stackedWidget_2->addWidget(page);
page_2 = new QWidget();
page_2->setObjectName(QString::fromUtf8("page_2"));
tempVBoxLayout = new QVBoxLayout(page_2);
QScrollArea *scrollArea2 = new QScrollArea();
scrollArea2->setObjectName(QString::fromUtf8("scrollArea2"));
scrollArea2->setSizePolicy(sizePolicy);
scrollArea2->setWidgetResizable(true);
QWidget *scrollAreaWidgetContents2 = new QWidget();
scrollAreaWidgetContents2->setObjectName(QString::fromUtf8("scrollAreaWidgetContents2"));
gridLayout2 = new QGridLayout(scrollAreaWidgetContents2);
gridLayout2->setSpacing(4);
gridLayout2->setObjectName(QString::fromUtf8("gridLayout2"));
scrollArea2->setWidget(scrollAreaWidgetContents2);
tempVBoxLayout->addWidget(scrollArea2);
stackedWidget_2->addWidget(page_2);
page_3 = new QWidget();
page_3->setObjectName(QString::fromUtf8("page_3"));
tempVBoxLayout = new QVBoxLayout(page_3);
QScrollArea *scrollArea3 = new QScrollArea();
scrollArea3->setObjectName(QString::fromUtf8("scrollArea3"));
scrollArea3->setSizePolicy(sizePolicy);
scrollArea3->setWidgetResizable(true);
QWidget *scrollAreaWidgetContents3 = new QWidget();
scrollAreaWidgetContents3->setObjectName(QString::fromUtf8("scrollAreaWidgetContents3"));
gridLayout3 = new QGridLayout(scrollAreaWidgetContents3);
gridLayout3->setSpacing(4);
gridLayout3->setObjectName(QString::fromUtf8("gridLayout3"));
scrollArea3->setWidget(scrollAreaWidgetContents3);
tempVBoxLayout->addWidget(scrollArea3);
stackedWidget_2->addWidget(page_3);
page_4 = new QWidget();
page_4->setObjectName(QString::fromUtf8("page_4"));
tempVBoxLayout = new QVBoxLayout(page_4);
QScrollArea *scrollArea4 = new QScrollArea();
scrollArea4->setObjectName(QString::fromUtf8("scrollArea4"));
scrollArea4->setSizePolicy(sizePolicy);
scrollArea4->setWidgetResizable(true);
QWidget *scrollAreaWidgetContents4 = new QWidget();
scrollAreaWidgetContents4->setObjectName(QString::fromUtf8("scrollAreaWidgetContents4"));
gridLayout4 = new QGridLayout(scrollAreaWidgetContents4);
gridLayout4->setSpacing(4);
gridLayout4->setObjectName(QString::fromUtf8("gridLayout4"));
scrollArea4->setWidget(scrollAreaWidgetContents4);
tempVBoxLayout->addWidget(scrollArea4);
stackedWidget_2->addWidget(page_4);
page_5 = new QWidget();
page_5->setObjectName(QString::fromUtf8("page_5"));
tempVBoxLayout = new QVBoxLayout(page_5);
QScrollArea *scrollArea5 = new QScrollArea();
scrollArea5->setObjectName(QString::fromUtf8("scrollArea5"));
scrollArea5->setSizePolicy(sizePolicy);
scrollArea5->setWidgetResizable(true);
QWidget *scrollAreaWidgetContents5 = new QWidget();
scrollAreaWidgetContents5->setObjectName(QString::fromUtf8("scrollAreaWidgetContents5"));
gridLayout5 = new QGridLayout(scrollAreaWidgetContents5);
gridLayout5->setSpacing(4);
gridLayout5->setObjectName(QString::fromUtf8("gridLayout5"));
scrollArea5->setWidget(scrollAreaWidgetContents5);
tempVBoxLayout->addWidget(scrollArea5);
stackedWidget_2->addWidget(page_5);
page_6 = new QWidget();
page_6->setObjectName(QString::fromUtf8("page_6"));
tempVBoxLayout = new QVBoxLayout(page_6);
QScrollArea *scrollArea6 = new QScrollArea();
scrollArea6->setObjectName(QString::fromUtf8("scrollArea6"));
scrollArea6->setSizePolicy(sizePolicy);
scrollArea6->setWidgetResizable(true);
QWidget *scrollAreaWidgetContents6 = new QWidget();
scrollAreaWidgetContents6->setObjectName(QString::fromUtf8("scrollAreaWidgetContents6"));
gridLayout6 = new QGridLayout(scrollAreaWidgetContents6);
gridLayout6->setSpacing(4);
gridLayout6->setObjectName(QString::fromUtf8("gridLayout6"));
scrollArea6->setWidget(scrollAreaWidgetContents6);
tempVBoxLayout->addWidget(scrollArea6);
stackedWidget_2->addWidget(page_6);
page_7 = new QWidget();
page_7->setObjectName(QString::fromUtf8("page_7"));
tempVBoxLayout = new QVBoxLayout(page_7);
QScrollArea *scrollArea7 = new QScrollArea();
scrollArea7->setObjectName(QString::fromUtf8("scrollArea7"));
scrollArea7->setSizePolicy(sizePolicy);
scrollArea7->setWidgetResizable(true);
QWidget *scrollAreaWidgetContents7 = new QWidget();
scrollAreaWidgetContents7->setObjectName(QString::fromUtf8("scrollAreaWidgetContents7"));
gridLayout7 = new QGridLayout(scrollAreaWidgetContents7);
gridLayout7->setSpacing(4);
gridLayout7->setObjectName(QString::fromUtf8("gridLayout7"));
scrollArea7->setWidget(scrollAreaWidgetContents7);
tempVBoxLayout->addWidget(scrollArea7);
stackedWidget_2->addWidget(page_7);
page_8 = new QWidget();
page_8->setObjectName(QString::fromUtf8("page_8"));
tempVBoxLayout = new QVBoxLayout(page_8);
QScrollArea *scrollArea8 = new QScrollArea();
scrollArea8->setObjectName(QString::fromUtf8("scrollArea8"));
scrollArea8->setSizePolicy(sizePolicy);
scrollArea8->setWidgetResizable(true);
QWidget *scrollAreaWidgetContents8 = new QWidget();
scrollAreaWidgetContents8->setObjectName(QString::fromUtf8("scrollAreaWidgetContents8"));
gridLayout8 = new QGridLayout(scrollAreaWidgetContents8);
gridLayout8->setSpacing(4);
gridLayout8->setObjectName(QString::fromUtf8("gridLayout8"));
scrollArea8->setWidget(scrollAreaWidgetContents8);
tempVBoxLayout->addWidget(scrollArea8);
stackedWidget_2->addWidget(page_8);
verticalLayout->addWidget(stackedWidget_2);
verticalSpacer_3 = new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Fixed);
verticalLayout->addItem(verticalSpacer_3);
horizontalLayout_2 = new QHBoxLayout();
horizontalLayout_2->setSpacing(6);
horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2"));
setsMenuButton = new QPushButton(tr("Sets"), this);
QMenu *setMenu = new QMenu(setsMenuButton);
copySetMenu = new QMenu(tr("Copy from Set"), setMenu);
QAction *setSettingsAction = new QAction(tr("Settings"), setMenu);
connect(setSettingsAction, SIGNAL(triggered()), this, SLOT(showSetNamesDialog()));
setMenu->addAction(setSettingsAction);
setMenu->addMenu(copySetMenu);
setMenu->addSeparator();
refreshCopySetActions();
setAction1 = new QAction(tr("Set 1"), setMenu);
connect(setAction1, SIGNAL(triggered()), this, SLOT(changeSetOne()));
setMenu->addAction(setAction1);
setAction2 = new QAction(tr("Set 2"), setMenu);
connect(setAction2, SIGNAL(triggered()), this, SLOT(changeSetTwo()));
setMenu->addAction(setAction2);
setAction3 = new QAction(tr("Set 3"), setMenu);
connect(setAction3, SIGNAL(triggered()), this, SLOT(changeSetThree()));
setMenu->addAction(setAction3);
setAction4 = new QAction(tr("Set 4"), setMenu);
connect(setAction4, SIGNAL(triggered()), this, SLOT(changeSetFour()));
setMenu->addAction(setAction4);
setAction5 = new QAction(tr("Set 5"), setMenu);
connect(setAction5, SIGNAL(triggered()), this, SLOT(changeSetFive()));
setMenu->addAction(setAction5);
setAction6 = new QAction(tr("Set 6"), setMenu);
connect(setAction6, SIGNAL(triggered()), this, SLOT(changeSetSix()));
setMenu->addAction(setAction6);
setAction7 = new QAction(tr("Set 7"), setMenu);
connect(setAction7, SIGNAL(triggered()), this, SLOT(changeSetSeven()));
setMenu->addAction(setAction7);
setAction8 = new QAction(tr("Set 8"), setMenu);
connect(setAction8, SIGNAL(triggered()), this, SLOT(changeSetEight()));
setMenu->addAction(setAction8);
setsMenuButton->setMenu(setMenu);
horizontalLayout_2->addWidget(setsMenuButton);
setPushButton1 = new QPushButton("1", this);
setPushButton1->setObjectName(QString::fromUtf8("setPushButton1"));
setPushButton1->setProperty("setActive", true);
horizontalLayout_2->addWidget(setPushButton1);
setPushButton2 = new QPushButton("2", this);
setPushButton2->setObjectName(QString::fromUtf8("setPushButton2"));
setPushButton2->setProperty("setActive", false);
horizontalLayout_2->addWidget(setPushButton2);
setPushButton3 = new QPushButton("3", this);
setPushButton3->setObjectName(QString::fromUtf8("setPushButton3"));
setPushButton3->setProperty("setActive", false);
horizontalLayout_2->addWidget(setPushButton3);
setPushButton4 = new QPushButton("4", this);
setPushButton4->setObjectName(QString::fromUtf8("setPushButton4"));
setPushButton4->setProperty("setActive", false);
horizontalLayout_2->addWidget(setPushButton4);
setPushButton5 = new QPushButton("5", this);
setPushButton5->setObjectName(QString::fromUtf8("setPushButton5"));
setPushButton5->setProperty("setActive", false);
horizontalLayout_2->addWidget(setPushButton5);
setPushButton6 = new QPushButton("6", this);
setPushButton6->setObjectName(QString::fromUtf8("setPushButton6"));
setPushButton6->setProperty("setActive", false);
horizontalLayout_2->addWidget(setPushButton6);
setPushButton7 = new QPushButton("7", this);
setPushButton7->setObjectName(QString::fromUtf8("setPushButton7"));
setPushButton7->setProperty("setActive", false);
horizontalLayout_2->addWidget(setPushButton7);
setPushButton8 = new QPushButton("8", this);
setPushButton8->setObjectName(QString::fromUtf8("setPushButton8"));
setPushButton8->setProperty("setActive", false);
horizontalLayout_2->addWidget(setPushButton8);
refreshSetButtons();
verticalLayout->addLayout(horizontalLayout_2);
spacer3 = new QSpacerItem(20, 5, QSizePolicy::Fixed, QSizePolicy::Fixed);
verticalLayout->addItem(spacer3);
horizontalLayout_3 = new QHBoxLayout();
horizontalLayout_3->setSpacing(6);
horizontalLayout_3->setObjectName(QString::fromUtf8("horizontalLayout_3"));
stickAssignPushButton = new QPushButton(tr("Stick/Pad Assign"), this);
stickAssignPushButton->setObjectName(QString::fromUtf8("stickAssignPushButton"));
QIcon icon7(QIcon::fromTheme(QString::fromUtf8("games-config-options")));
stickAssignPushButton->setIcon(icon7);
horizontalLayout_3->addWidget(stickAssignPushButton);
gameControllerMappingPushButton = new QPushButton(tr("Controller Mapping"), this);
gameControllerMappingPushButton->setObjectName(QString::fromUtf8("gameControllerMappingPushButton"));
gameControllerMappingPushButton->setIcon(QIcon::fromTheme("games-config-options"));
gameControllerMappingPushButton->setEnabled(false);
gameControllerMappingPushButton->setVisible(false);
horizontalLayout_3->addWidget(gameControllerMappingPushButton);
quickSetPushButton = new QPushButton(tr("Quick Set"), this);
quickSetPushButton->setObjectName(QString::fromUtf8("quickSetPushButton"));
horizontalLayout_3->addWidget(quickSetPushButton);
QSpacerItem *horizontalSpacer_2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_3->addItem(horizontalSpacer_2);
namesPushButton = new QPushButton(tr("Names"), this);
namesPushButton->setObjectName(QString::fromUtf8("namesPushButton"));
namesPushButton->setToolTip(tr("Toggle button name displaying."));
namesPushButton->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
namesPushButton->setIcon(QIcon::fromTheme("text-field"));
horizontalLayout_3->addWidget(namesPushButton);
delayButton = new QPushButton(tr("Pref"), this);
delayButton->setObjectName(QString::fromUtf8("delayButton"));
delayButton->setToolTip(tr("Change global profile settings."));
delayButton->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
horizontalLayout_3->addWidget(delayButton);
resetButton = new QPushButton(tr("Reset"), this);
resetButton->setObjectName(QString::fromUtf8("resetButton"));
resetButton->setToolTip(tr("Revert changes to the configuration. Reload configuration file."));
resetButton->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
resetButton->setIcon(QIcon::fromTheme("document-revert"));
//verticalLayout->addWidget(resetButton, 0, Qt::AlignRight);
horizontalLayout_3->addWidget(resetButton);
verticalLayout->addLayout(horizontalLayout_3);
displayingNames = false;
#ifdef USE_SDL_2
stickAssignPushButton->setEnabled(false);
stickAssignPushButton->setVisible(false);
gameControllerMappingPushButton->setEnabled(true);
gameControllerMappingPushButton->setVisible(true);
#endif
#ifdef Q_OS_WIN
deviceKeyRepeatSettings();
#endif
checkHideEmptyOption();
connect(loadButton, SIGNAL(clicked()), this, SLOT(openConfigFileDialog()));
connect(saveButton, SIGNAL(clicked()), this, SLOT(saveConfigFile()));
connect(resetButton, SIGNAL(clicked()), this, SLOT(resetJoystick()));
connect(namesPushButton, SIGNAL(clicked()), this, SLOT(toggleNames()));
connect(saveAsButton, SIGNAL(clicked()), this, SLOT(saveAsConfig()));
connect(delayButton, SIGNAL(clicked()), this, SLOT(showKeyDelayDialog()));
connect(removeButton, SIGNAL(clicked()), this, SLOT(removeConfig()));
connect(setPushButton1, SIGNAL(clicked()), this, SLOT(changeSetOne()));
connect(setPushButton2, SIGNAL(clicked()), this, SLOT(changeSetTwo()));
connect(setPushButton3, SIGNAL(clicked()), this, SLOT(changeSetThree()));
connect(setPushButton4, SIGNAL(clicked()), this, SLOT(changeSetFour()));
connect(setPushButton5, SIGNAL(clicked()), this, SLOT(changeSetFive()));
connect(setPushButton6, SIGNAL(clicked()), this, SLOT(changeSetSix()));
connect(setPushButton7, SIGNAL(clicked()), this, SLOT(changeSetSeven()));
connect(setPushButton8, SIGNAL(clicked()), this, SLOT(changeSetEight()));
connect(stickAssignPushButton, SIGNAL(clicked()), this, SLOT(showStickAssignmentDialog()));
#ifdef USE_SDL_2
connect(gameControllerMappingPushButton, SIGNAL(clicked()), this, SLOT(openGameControllerMappingWindow()));
#endif
connect(quickSetPushButton, SIGNAL(clicked()), this, SLOT(showQuickSetDialog()));
connect(this, SIGNAL(joystickConfigChanged(int)), this, SLOT(refreshSetButtons()));
connect(this, SIGNAL(joystickConfigChanged(int)), this, SLOT(refreshCopySetActions()));
connect(joystick, SIGNAL(profileUpdated()), this, SLOT(displayProfileEditNotification()));
connect(joystick, SIGNAL(requestProfileLoad(QString)), this, SLOT(loadConfigFile(QString)), Qt::QueuedConnection);
reconnectCheckUnsavedEvent();
reconnectMainComboBoxEvents();
}
void JoyTabWidget::openConfigFileDialog()
{
settings->getLock()->lock();
int numberRecentProfiles = settings->value("NumberRecentProfiles", DEFAULTNUMBERPROFILES).toInt();
QString lookupDir = PadderCommon::preferredProfileDir(settings);
QString filename = QFileDialog::getOpenFileName(this, tr("Open Config"), lookupDir, tr("Config Files (*.amgp *.xml)"));
settings->getLock()->unlock();
if (!filename.isNull() && !filename.isEmpty())
{
QFileInfo fileinfo(filename);
int searchIndex = configBox->findData(fileinfo.absoluteFilePath());
if (searchIndex == -1)
{
if (numberRecentProfiles > 0 && configBox->count() == numberRecentProfiles + 1)
{
configBox->removeItem(numberRecentProfiles);
}
configBox->insertItem(1, PadderCommon::getProfileName(fileinfo), fileinfo.absoluteFilePath());
configBox->setCurrentIndex(1);
saveDeviceSettings();
emit joystickConfigChanged(joystick->getJoyNumber());
}
else
{
configBox->setCurrentIndex(searchIndex);
saveDeviceSettings();
emit joystickConfigChanged(joystick->getJoyNumber());
}
QString outputFilename = fileinfo.absoluteDir().absolutePath();
#if defined(Q_OS_WIN) && defined(WIN_PORTABLE_PACKAGE)
if (fileinfo.absoluteDir().isAbsolute())
{
QDir tempDir = fileinfo.dir();
tempDir.cdUp();
if (tempDir.path() == qApp->applicationDirPath())
{
outputFilename = QString("%1/").arg(fileinfo.dir().dirName());
}
}
#endif
settings->getLock()->lock();
settings->setValue("LastProfileDir", outputFilename);
settings->sync();
settings->getLock()->unlock();
}
}
/**
* @brief Create and render all push buttons corresponding to joystick
* controls for all sets.
*/
void JoyTabWidget::fillButtons()
{
joystick->establishPropertyUpdatedConnection();
connect(joystick, SIGNAL(setChangeActivated(int)), this, SLOT(changeCurrentSet(int)), Qt::QueuedConnection);
for (int i=0; i < Joystick::NUMBER_JOYSETS; i++)
{
SetJoystick *currentSet = joystick->getSetJoystick(i);
fillSetButtons(currentSet);
}
refreshCopySetActions();
}
void JoyTabWidget::showButtonDialog()
{
JoyButtonWidget *buttonWidget = static_cast<JoyButtonWidget*>(sender());
JoyButton *button = buttonWidget->getJoyButton();
ButtonEditDialog *dialog = new ButtonEditDialog(button, this);
dialog->show();
}
void JoyTabWidget::showAxisDialog()
{
JoyAxisWidget *axisWidget = static_cast<JoyAxisWidget*>(sender());
JoyAxis *axis = axisWidget->getAxis();
axisDialog = new AxisEditDialog (axis, this);
axisDialog->show();
}
void JoyTabWidget::saveConfigFile()
{
int index = configBox->currentIndex();
settings->getLock()->lock();
int numberRecentProfiles = settings->value("NumberRecentProfiles", DEFAULTNUMBERPROFILES).toInt();
QString filename;
if (index == 0)
{
QString lookupDir = PadderCommon::preferredProfileDir(settings);
settings->getLock()->unlock();
QString tempfilename = QFileDialog::getSaveFileName(this, tr("Save Config"), lookupDir, tr("Config File (*.%1.amgp)").arg(joystick->getXmlName()));
if (!tempfilename.isEmpty())
{
filename = tempfilename;
QFileInfo fileinfo(filename);
QString deviceTypeName = joystick->getXmlName();
QString fileSuffix = deviceTypeName.append(".amgp");
if (fileinfo.suffix() != "xml" && fileinfo.suffix() != "amgp")
{
filename = filename.append(".").append(fileSuffix);
}
}
}
else
{
settings->getLock()->unlock();
filename = configBox->itemData(index).toString();
}
if (!filename.isEmpty())
{
//PadderCommon::inputDaemonMutex.lock();
QFileInfo fileinfo(filename);
QMetaObject::invokeMethod(&tabHelper, "writeConfigFile", Qt::BlockingQueuedConnection,
Q_ARG(QString, fileinfo.absoluteFilePath()));
XMLConfigWriter *writer = tabHelper.getWriter();
/*XMLConfigWriter writer;
writer.setFileName(fileinfo.absoluteFilePath());
writer.write(joystick);
*/
//PadderCommon::inputDaemonMutex.unlock();
if (writer->hasError() && this->window()->isEnabled())
{
QMessageBox msg;
msg.setStandardButtons(QMessageBox::Close);
msg.setText(writer->getErrorString());
msg.setModal(true);
msg.exec();
}
else if (writer->hasError() && !this->window()->isEnabled())
{
QTextStream error(stderr);
error << writer->getErrorString() << endl;
}
else
{
int existingIndex = configBox->findData(fileinfo.absoluteFilePath());
if (existingIndex == -1)
{
//PadderCommon::inputDaemonMutex.lock();
if (numberRecentProfiles > 0 && configBox->count() == numberRecentProfiles+1)
{
configBox->removeItem(numberRecentProfiles);
}
joystick->revertProfileEdited();
QString tempProfileName = PadderCommon::getProfileName(fileinfo);
if (!joystick->getProfileName().isEmpty())
{
oldProfileName = joystick->getProfileName();
tempProfileName = oldProfileName;
}
disconnectCheckUnsavedEvent();
disconnectMainComboBoxEvents();
configBox->insertItem(1, tempProfileName, fileinfo.absoluteFilePath());
reconnectCheckUnsavedEvent();
reconnectMainComboBoxEvents();
configBox->setCurrentIndex(1);
saveDeviceSettings(true);
//PadderCommon::inputDaemonMutex.unlock();
emit joystickConfigChanged(joystick->getJoyNumber());
}
else
{
//PadderCommon::inputDaemonMutex.lock();
joystick->revertProfileEdited();
if (!joystick->getProfileName().isEmpty())
{
oldProfileName = joystick->getProfileName();
}
configBox->setItemIcon(existingIndex, QIcon());
saveDeviceSettings(true);
//PadderCommon::inputDaemonMutex.unlock();
emit joystickConfigChanged(joystick->getJoyNumber());
}
}
}
}
void JoyTabWidget::resetJoystick()
{
int currentIndex = configBox->currentIndex();
if (currentIndex != 0)
{
QString filename = configBox->itemData(currentIndex).toString();
removeCurrentButtons();
QMetaObject::invokeMethod(&tabHelper, "readConfigFileWithRevert", Qt::BlockingQueuedConnection,
Q_ARG(QString, filename));
fillButtons();
refreshSetButtons();
refreshCopySetActions();
XMLConfigReader *reader = tabHelper.getReader();
if (!reader->hasError())
{
configBox->setItemIcon(currentIndex, QIcon());
QString tempProfileName;
if (!joystick->getProfileName().isEmpty())
{
tempProfileName = joystick->getProfileName();
configBox->setItemText(currentIndex, tempProfileName);
}
else
{
tempProfileName = oldProfileName;
configBox->setItemText(currentIndex, oldProfileName);
}
oldProfileName = tempProfileName;
}
else if (reader->hasError() && this->window()->isEnabled())
{
QMessageBox msg;
msg.setStandardButtons(QMessageBox::Close);
msg.setText(reader->getErrorString());
msg.setModal(true);
msg.exec();
}
else if (reader->hasError() && !this->window()->isEnabled())
{
QTextStream error(stderr);
error << reader->getErrorString() << endl;
}
}
else
{
configBox->setItemText(0, tr("<New>"));
configBox->setItemIcon(0, QIcon());
removeCurrentButtons();
QMetaObject::invokeMethod(&tabHelper, "reInitDevice", Qt::BlockingQueuedConnection);
fillButtons();
refreshSetButtons();
refreshCopySetActions();
}
}
void JoyTabWidget::saveAsConfig()
{
int index = configBox->currentIndex();
settings->getLock()->lock();
int numberRecentProfiles = settings->value("NumberRecentProfiles", DEFAULTNUMBERPROFILES).toInt();
QString filename;
if (index == 0)
{
QString lookupDir = PadderCommon::preferredProfileDir(settings);
settings->getLock()->unlock();
QString tempfilename = QFileDialog::getSaveFileName(this, tr("Save Config"), lookupDir, tr("Config File (*.%1.amgp)").arg(joystick->getXmlName()));
if (!tempfilename.isEmpty())
{
filename = tempfilename;
}
}
else
{
settings->getLock()->unlock();
QString configPath = configBox->itemData(index).toString();
QFileInfo temp(configPath);
QString tempfilename = QFileDialog::getSaveFileName(this, tr("Save Config"), temp.absoluteDir().absolutePath(), tr("Config File (*.%1.amgp)").arg(joystick->getXmlName()));
if (!tempfilename.isEmpty())
{
filename = tempfilename;
}
}
if (!filename.isEmpty())
{
QFileInfo fileinfo(filename);
QString deviceTypeName = joystick->getXmlName();
QString fileSuffix = deviceTypeName.append(".amgp");
if (fileinfo.suffix() != "xml" && fileinfo.suffix() != "amgp")
{
filename = filename.append(".").append(fileSuffix);
}
fileinfo.setFile(filename);
/*XMLConfigWriter writer;
writer.setFileName(fileinfo.absoluteFilePath());
writer.write(joystick);
*/
QMetaObject::invokeMethod(&tabHelper, "writeConfigFile", Qt::BlockingQueuedConnection,
Q_ARG(QString, fileinfo.absoluteFilePath()));
XMLConfigWriter *writer = tabHelper.getWriter();
if (writer->hasError() && this->window()->isEnabled())
{
QMessageBox msg;
msg.setStandardButtons(QMessageBox::Close);
msg.setText(writer->getErrorString());
msg.setModal(true);
msg.exec();
}
else if (writer->hasError() && !this->window()->isEnabled())
{
QTextStream error(stderr);
error << writer->getErrorString() << endl;
}
else
{
int existingIndex = configBox->findData(fileinfo.absoluteFilePath());
if (existingIndex == -1)
{
disconnectCheckUnsavedEvent();
disconnectMainComboBoxEvents();
if (numberRecentProfiles > 0 && configBox->count() == numberRecentProfiles+1)
{
configBox->removeItem(numberRecentProfiles);
}
joystick->revertProfileEdited();
QString tempProfileName = PadderCommon::getProfileName(fileinfo);
if (!joystick->getProfileName().isEmpty())
{
oldProfileName = joystick->getProfileName();
tempProfileName = oldProfileName;
}
configBox->insertItem(1, tempProfileName, fileinfo.absoluteFilePath());
reconnectCheckUnsavedEvent();
reconnectMainComboBoxEvents();
configBox->setCurrentIndex(1);
saveDeviceSettings(true);
emit joystickConfigChanged(joystick->getJoyNumber());
}
else
{
joystick->revertProfileEdited();
if (!joystick->getProfileName().isEmpty())
{
oldProfileName = joystick->getProfileName();
}
configBox->setItemIcon(existingIndex, QIcon());
saveDeviceSettings(true);
emit joystickConfigChanged(joystick->getJoyNumber());
}
}
}
}
void JoyTabWidget::changeJoyConfig(int index)
{
disconnect(joystick, SIGNAL(profileUpdated()), this, SLOT(displayProfileEditNotification()));
QString filename;
if (index > 0)
{
filename = configBox->itemData(index).toString();
}
if (!filename.isEmpty())
{
removeCurrentButtons();
emit forceTabUnflash(this);
QMetaObject::invokeMethod(&tabHelper, "readConfigFile", Qt::BlockingQueuedConnection,
Q_ARG(QString, filename));
fillButtons();
refreshSetButtons();
refreshCopySetActions();
configBox->setItemText(0, tr("<New>"));
XMLConfigReader *reader = tabHelper.getReader();
if (!reader->hasError())
{
QString profileName;
if (!joystick->getProfileName().isEmpty())
{
profileName = joystick->getProfileName();
oldProfileName = profileName;
}
else
{
QFileInfo profile(filename);
oldProfileName = PadderCommon::getProfileName(profile);
profileName = oldProfileName;
}
configBox->setItemText(index, profileName);
}
else if (reader->hasError() && this->window()->isEnabled())
{
QMessageBox msg;
msg.setStandardButtons(QMessageBox::Close);
msg.setText(reader->getErrorString());
msg.setModal(true);
msg.exec();
}
else if (reader->hasError() && !this->window()->isEnabled())
{
QTextStream error(stderr);
error << reader->getErrorString() << endl;
}
}
else if (index == 0)
{
removeCurrentButtons();
emit forceTabUnflash(this);
QMetaObject::invokeMethod(&tabHelper, "reInitDevice", Qt::BlockingQueuedConnection);
fillButtons();
refreshSetButtons();
refreshCopySetActions();
configBox->setItemText(0, tr("<New>"));
oldProfileName = "";
}
comboBoxIndex = index;
connect(joystick, SIGNAL(profileUpdated()), this, SLOT(displayProfileEditNotification()));
}
void JoyTabWidget::saveSettings()
{
QString filename = "";
QString lastfile = "";
settings->getLock()->lock();
int index = configBox->currentIndex();
int currentjoy = 1;
QString identifier = joystick->getStringIdentifier();
QString controlEntryPrefix = QString("Controller%1").arg(identifier);
QString controlEntryString = QString("Controller%1ConfigFile%2").arg(identifier);
QString controlEntryLastSelected = QString("Controller%1LastSelected").arg(identifier);
QString controlEntryProfileName = QString("Controller%1ProfileName%2").arg(joystick->getStringIdentifier());
// Remove current settings for a controller
QStringList tempkeys = settings->allKeys();
QStringListIterator iter(tempkeys);
while (iter.hasNext())
{
QString tempstring = iter.next();
if (!identifier.isEmpty() && tempstring.startsWith(controlEntryPrefix))
{
settings->remove(tempstring);
}
}
// Output currently selected profile as first profile on the list
if (index != 0)
{
filename = lastfile = configBox->itemData(index).toString();
QString profileText = configBox->itemText(index);
if (!identifier.isEmpty())
{
QFileInfo profileBaseFile(filename);
QString outputFilename = filename;
#if defined(Q_OS_WIN) && defined(WIN_PORTABLE_PACKAGE)
if (profileBaseFile.isAbsolute())
{
QDir tempDir = profileBaseFile.dir();
tempDir.cdUp();
if (tempDir.path() == qApp->applicationDirPath())
{
outputFilename = QString("%1/%2")
.arg(profileBaseFile.dir().dirName())
.arg(profileBaseFile.fileName());
}
}
#endif
settings->setValue(controlEntryString.arg(currentjoy), outputFilename);
if (PadderCommon::getProfileName(profileBaseFile) != profileText)
{
settings->setValue(controlEntryProfileName.arg(currentjoy), profileText);
}
}
currentjoy++;
}
else
{
lastfile = "";
}
// Write the remaining profile locations to the settings file
for (int i=1; i < configBox->count(); i++)
{
if (i != index)
{
filename = configBox->itemData(i).toString();
QString profileText = configBox->itemText(i);
if (!identifier.isEmpty())
{
QFileInfo profileBaseFile(filename);
QString outputFilename = filename;
#if defined(Q_OS_WIN) && defined(WIN_PORTABLE_PACKAGE)
if (profileBaseFile.isAbsolute())
{
QDir tempDir = profileBaseFile.dir();
tempDir.cdUp();
if (tempDir.path() == qApp->applicationDirPath())
{
outputFilename = QString("%1/%2")
.arg(profileBaseFile.dir().dirName())
.arg(profileBaseFile.fileName());
}
}
#endif
settings->setValue(controlEntryString.arg(currentjoy), outputFilename);
if (PadderCommon::getProfileName(profileBaseFile) != profileText)
{
settings->setValue(controlEntryProfileName.arg(currentjoy), profileText);
}
}
currentjoy++;
}
}
if (!identifier.isEmpty())
{
QFileInfo profileBaseFile(lastfile);
QString outputFilename = lastfile;
#if defined(Q_OS_WIN) && defined(WIN_PORTABLE_PACKAGE)
if (profileBaseFile.isAbsolute())
{
QDir tempDir = profileBaseFile.dir();
tempDir.cdUp();
if (tempDir.path() == qApp->applicationDirPath())
{
outputFilename = QString("%1/%2")
.arg(profileBaseFile.dir().dirName())
.arg(profileBaseFile.fileName());
}
}
#endif
settings->setValue(controlEntryLastSelected, outputFilename);
}
settings->getLock()->unlock();
}
void JoyTabWidget::loadSettings(bool forceRefresh)
{
disconnect(configBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeJoyConfig(int)));
settings->getLock()->lock();
if (configBox->count() > 1)
{
configBox->clear();
configBox->addItem(tr("<New>"), "");
configBox->setCurrentIndex(-1);
}
else if (forceRefresh)
{
configBox->setCurrentIndex(-1);
}
int shouldisplaynames = settings->value("DisplayNames", "0").toInt();
if (shouldisplaynames == 1)
{
changeNameDisplay(shouldisplaynames);
}
int numberRecentProfiles = settings->value("NumberRecentProfiles", DEFAULTNUMBERPROFILES).toInt();
bool autoOpenLastProfile = settings->value("AutoOpenLastProfile", true).toBool();
settings->beginGroup("Controllers");
QString controlEntryString = QString("Controller%1ConfigFile%2").arg(joystick->getStringIdentifier());
QString controlEntryLastSelected = QString("Controller%1LastSelected").arg(joystick->getStringIdentifier());
QString controlEntryProfileName = QString("Controller%1ProfileName%2").arg(joystick->getStringIdentifier());
bool finished = false;
for (int i=1; !finished; i++)
{
QString tempfilepath;
if (!joystick->getStringIdentifier().isEmpty())
{
tempfilepath = settings->value(controlEntryString.arg(i), "").toString();
}
if (!tempfilepath.isEmpty())
{
QFileInfo fileInfo(tempfilepath);
if (fileInfo.exists() && configBox->findData(fileInfo.absoluteFilePath()) == -1)
{
QString profileName = settings->value(controlEntryProfileName.arg(i), "").toString();
profileName = !profileName.isEmpty() ? profileName : PadderCommon::getProfileName(fileInfo);
configBox->addItem(profileName, fileInfo.absoluteFilePath());
}
}
else
{
finished = true;
}
if (numberRecentProfiles > 0 && (i == numberRecentProfiles))
{
finished = true;
}
}
connect(configBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeJoyConfig(int)), Qt::QueuedConnection);
QString lastfile;
if (!joystick->getStringIdentifier().isEmpty() && autoOpenLastProfile)
{
lastfile = settings->value(controlEntryLastSelected, "").toString();
}
settings->endGroup();
settings->getLock()->unlock();
if (!lastfile.isEmpty())
{
QString lastFileAbsolute = lastfile;
#if defined(Q_OS_WIN) && defined(WIN_PORTABLE_PACKAGE)
QFileInfo lastFileInfo(lastfile);
lastFileAbsolute = lastFileInfo.absoluteFilePath();
#endif
int lastindex = configBox->findData(lastFileAbsolute);
if (lastindex > 0)
{
configBox->setCurrentIndex(lastindex);
emit joystickConfigChanged(joystick->getJoyNumber());
}
else if (configBox->currentIndex() != 0)
{
configBox->setCurrentIndex(0);
emit joystickConfigChanged(joystick->getJoyNumber());
}
}
else if (configBox->currentIndex() != 0)
{
configBox->setCurrentIndex(0);
emit joystickConfigChanged(joystick->getJoyNumber());
}
}
QHash<int, QString>* JoyTabWidget::recentConfigs()
{
QHash<int, QString> *temp = new QHash<int, QString>();
for (int i=1; i < configBox->count(); i++)
{
QString current = configBox->itemText(i);
temp->insert(i, current);
}
return temp;
}
void JoyTabWidget::setCurrentConfig(int index)
{
// Allow 0 to select new/'null' config and therefore disable any mapping
if (index >= 0 && index < configBox->count())
{
configBox->setCurrentIndex(index);
}
}
int JoyTabWidget::getCurrentConfigIndex()
{
return configBox->currentIndex();
}
QString JoyTabWidget::getCurrentConfigName()
{
return configBox->currentText();
}
QString JoyTabWidget::getConfigName(int index)
{
return configBox->itemText(index);
}
void JoyTabWidget::changeCurrentSet(int index)
{
int currentPage = stackedWidget_2->currentIndex();
QPushButton *oldSetButton = 0;
QPushButton *activeSetButton = 0;
switch (currentPage)
{
case 0: oldSetButton = setPushButton1; break;
case 1: oldSetButton = setPushButton2; break;
case 2: oldSetButton = setPushButton3; break;
case 3: oldSetButton = setPushButton4; break;
case 4: oldSetButton = setPushButton5; break;
case 5: oldSetButton = setPushButton6; break;
case 6: oldSetButton = setPushButton7; break;
case 7: oldSetButton = setPushButton8; break;
default: break;
}
if (oldSetButton)
{
oldSetButton->setProperty("setActive", false);
oldSetButton->style()->unpolish(oldSetButton);
oldSetButton->style()->polish(oldSetButton);
}
joystick->setActiveSetNumber(index);
stackedWidget_2->setCurrentIndex(index);
switch (index)
{
case 0: activeSetButton = setPushButton1; break;
case 1: activeSetButton = setPushButton2; break;
case 2: activeSetButton = setPushButton3; break;
case 3: activeSetButton = setPushButton4; break;
case 4: activeSetButton = setPushButton5; break;
case 5: activeSetButton = setPushButton6; break;
case 6: activeSetButton = setPushButton7; break;
case 7: activeSetButton = setPushButton8; break;
default: break;
}
if (activeSetButton)
{
activeSetButton->setProperty("setActive", true);
activeSetButton->style()->unpolish(activeSetButton);
activeSetButton->style()->polish(activeSetButton);
}
}
void JoyTabWidget::changeSetOne()
{
changeCurrentSet(0);
}
void JoyTabWidget::changeSetTwo()
{
changeCurrentSet(1);
}
void JoyTabWidget::changeSetThree()
{
changeCurrentSet(2);
}
void JoyTabWidget::changeSetFour()
{
changeCurrentSet(3);
}
void JoyTabWidget::changeSetFive()
{
changeCurrentSet(4);
}
void JoyTabWidget::changeSetSix()
{
changeCurrentSet(5);
}
void JoyTabWidget::changeSetSeven()
{
changeCurrentSet(6);
}
void JoyTabWidget::changeSetEight()
{
changeCurrentSet(7);
}
void JoyTabWidget::showStickAssignmentDialog()
{
Joystick *temp = static_cast<Joystick*>(joystick);
AdvanceStickAssignmentDialog *dialog = new AdvanceStickAssignmentDialog(temp, this);
connect(dialog, SIGNAL(finished(int)), this, SLOT(refreshButtons()));
dialog->show();
}
void JoyTabWidget::loadConfigFile(QString fileLocation)
{
checkForUnsavedProfile(-1);
if (!joystick->isDeviceEdited())
{
int numberRecentProfiles = settings->value("NumberRecentProfiles", DEFAULTNUMBERPROFILES).toInt();
QFileInfo fileinfo(fileLocation);
if (fileinfo.exists() && (fileinfo.suffix() == "xml" || fileinfo.suffix() == "amgp"))
{
int searchIndex = configBox->findData(fileinfo.absoluteFilePath());
if (searchIndex == -1)
{
disconnectCheckUnsavedEvent();
disconnectMainComboBoxEvents();
if (numberRecentProfiles > 0 && configBox->count() == numberRecentProfiles+1)
{
configBox->removeItem(numberRecentProfiles-1);
//configBox->removeItem(5);
}
configBox->insertItem(1, PadderCommon::getProfileName(fileinfo), fileinfo.absoluteFilePath());
reconnectCheckUnsavedEvent();
reconnectMainComboBoxEvents();
configBox->setCurrentIndex(1);
emit joystickConfigChanged(joystick->getJoyNumber());
}
else if (searchIndex != configBox->currentIndex())
{
configBox->setCurrentIndex(searchIndex);
emit joystickConfigChanged(joystick->getJoyNumber());
}
}
}
}
void JoyTabWidget::showQuickSetDialog()
{
QuickSetDialog *dialog = new QuickSetDialog(joystick, this);
connect(dialog, SIGNAL(finished(int)), this, SLOT(refreshButtons()));
dialog->show();
}
void JoyTabWidget::showKeyDelayDialog()
{
ExtraProfileSettingsDialog *dialog = new ExtraProfileSettingsDialog(joystick, this);
dialog->show();
}
void JoyTabWidget::showSetNamesDialog()
{
SetNamesDialog *dialog = new SetNamesDialog(joystick, this);
connect(dialog, SIGNAL(accepted()), this, SLOT(refreshSetButtons()));
connect(dialog, SIGNAL(accepted()), this, SLOT(refreshCopySetActions()));
dialog->show();
}
void JoyTabWidget::removeCurrentButtons()
{
joystick->disconnectPropertyUpdatedConnection();
disconnect(joystick, SIGNAL(setChangeActivated(int)), this, SLOT(changeCurrentSet(int)));
for (int i=0; i < Joystick::NUMBER_JOYSETS; i++)
{
SetJoystick *currentSet = joystick->getSetJoystick(i);
removeSetButtons(currentSet);
}
}
InputDevice *JoyTabWidget::getJoystick()
{
return joystick;
}
void JoyTabWidget::removeConfig()
{
int currentIndex = configBox->currentIndex();
if (currentIndex > 0)
{
configBox->removeItem(currentIndex);
saveDeviceSettings(true);
emit joystickConfigChanged(joystick->getJoyNumber());
}
}
void JoyTabWidget::toggleNames()
{
displayingNames = !displayingNames;
namesPushButton->setProperty("isDisplayingNames", displayingNames);
namesPushButton->style()->unpolish(namesPushButton);
namesPushButton->style()->polish(namesPushButton);
emit namesDisplayChanged(displayingNames);
}
void JoyTabWidget::unloadConfig()
{
configBox->setCurrentIndex(0);
}
void JoyTabWidget::saveDeviceSettings(bool sync)
{
settings->getLock()->lock();
settings->beginGroup("Controllers");
settings->getLock()->unlock();
saveSettings();
settings->getLock()->lock();
settings->endGroup();
if (sync)
{
settings->sync();
}
settings->getLock()->unlock();
}
void JoyTabWidget::loadDeviceSettings()
{
//settings.beginGroup("Controllers");
loadSettings();
//settings.endGroup();
}
bool JoyTabWidget::isDisplayingNames()
{
return displayingNames;
}
void JoyTabWidget::changeNameDisplay(bool displayNames)
{
displayingNames = displayNames;
namesPushButton->setProperty("isDisplayingNames", displayingNames);
namesPushButton->style()->unpolish(namesPushButton);
namesPushButton->style()->polish(namesPushButton);
}
void JoyTabWidget::refreshSetButtons()
{
for (int i=0; i < InputDevice::NUMBER_JOYSETS; i++)
{
QPushButton *tempSetButton = 0;
QAction *tempSetAction = 0;
SetJoystick *tempSet = joystick->getSetJoystick(i);
switch (i)
{
case 0:
tempSetButton = setPushButton1;
tempSetAction = setAction1;
break;
case 1:
tempSetButton = setPushButton2;
tempSetAction = setAction2;
break;
case 2:
tempSetButton = setPushButton3;
tempSetAction = setAction3;
break;
case 3:
tempSetButton = setPushButton4;
tempSetAction = setAction4;
break;
case 4:
tempSetButton = setPushButton5;
tempSetAction = setAction5;
break;
case 5:
tempSetButton = setPushButton6;
tempSetAction = setAction6;
break;
case 6:
tempSetButton = setPushButton7;
tempSetAction = setAction7;
break;
case 7:
tempSetButton = setPushButton8;
tempSetAction = setAction8;
break;
}
if (!tempSet->getName().isEmpty())
{
QString tempName = tempSet->getName();
QString tempNameEscaped = tempName;
tempNameEscaped.replace("&", "&&");
tempSetButton->setText(tempNameEscaped);
tempSetButton->setToolTip(tempName);
tempSetAction->setText(tr("Set").append(" %1: %2").arg(i+1).arg(tempNameEscaped));
}
else
{
tempSetButton->setText(QString::number(i+1));
tempSetButton->setToolTip("");
tempSetAction->setText(tr("Set").append(" %1").arg(i+1));
}
}
}
void JoyTabWidget::displayProfileEditNotification()
{
int currentIndex = configBox->currentIndex();
configBox->setItemIcon(currentIndex, QIcon::fromTheme("document-save-as",
QIcon(":/icons/16x16/actions/document-save.png")));
}
void JoyTabWidget::removeProfileEditNotification()
{
for (int i=0; i < configBox->count(); i++)
{
if (!configBox->itemIcon(i).isNull())
{
configBox->setItemIcon(i, QIcon());
}
}
}
void JoyTabWidget::retranslateUi()
{
removeButton->setText(tr("Remove"));
removeButton->setToolTip(tr("Remove configuration from recent list."));
loadButton->setText(tr("Load"));
loadButton->setToolTip(tr("Load configuration file."));
saveButton->setText(tr("Save"));
saveButton->setToolTip(tr("Save changes to configuration file."));
saveAsButton->setText(tr("Save As"));
saveAsButton->setToolTip(tr("Save changes to a new configuration file."));
setsMenuButton->setText(tr("Sets"));
setAction1->setText(tr("Set 1"));
setAction2->setText(tr("Set 2"));
setAction3->setText(tr("Set 3"));
setAction4->setText(tr("Set 4"));
setAction5->setText(tr("Set 5"));
setAction6->setText(tr("Set 6"));
setAction7->setText(tr("Set 7"));
setAction8->setText(tr("Set 8"));
refreshSetButtons();
refreshCopySetActions();
gameControllerMappingPushButton->setText(tr("Controller Mapping"));
stickAssignPushButton->setText(tr("Stick/Pad Assign"));
quickSetPushButton->setText(tr("Quick Set"));
resetButton->setText(tr("Reset"));
namesPushButton->setText(tr("Names"));
namesPushButton->setToolTip(tr("Toggle button name displaying."));
delayButton->setText(tr("Pref"));
delayButton->setToolTip(tr("Change global profile settings."));
resetButton->setText(tr("Reset"));
resetButton->setToolTip(tr("Revert changes to the configuration. Reload configuration file."));
refreshButtons();
}
void JoyTabWidget::checkForUnsavedProfile(int newindex)
{
if (joystick->isDeviceEdited())
{
disconnectCheckUnsavedEvent();
disconnectMainComboBoxEvents();
if (configBox->currentIndex() != comboBoxIndex)
{
configBox->setCurrentIndex(comboBoxIndex);
}
QMessageBox msg;
msg.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
msg.setWindowTitle(tr("Save Profile Changes?"));
if (comboBoxIndex == 0)
{
msg.setText(tr("Changes to the new profile have not been saved. Would you like to save or discard the current profile?"));
}
else
{
msg.setText(tr("Changes to the profile \"%1\" have not been saved. Would you like to save or discard changes to the current profile?")
.arg(configBox->currentText()));
}
int status = msg.exec();
if (status == QMessageBox::Save)
{
saveConfigFile();
reconnectCheckUnsavedEvent();
reconnectMainComboBoxEvents();
if (newindex > -1)
{
configBox->setCurrentIndex(newindex);
}
}
else if (status == QMessageBox::Discard)
{
joystick->revertProfileEdited();
configBox->setItemText(comboBoxIndex, oldProfileName);
reconnectCheckUnsavedEvent();
reconnectMainComboBoxEvents();
if (newindex > -1)
{
configBox->setCurrentIndex(newindex);
}
}
else if (status == QMessageBox::Cancel)
{
reconnectCheckUnsavedEvent();
reconnectMainComboBoxEvents();
}
}
}
bool JoyTabWidget::discardUnsavedProfileChanges()
{
bool discarded = true;
if (joystick->isDeviceEdited())
{
disconnectCheckUnsavedEvent();
QMessageBox msg;
msg.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
msg.setWindowTitle(tr("Save Profile Changes?"));
int currentIndex = configBox->currentIndex();
if (currentIndex == 0)
{
msg.setText(tr("Changes to the new profile have not been saved. Would you like to save or discard the current profile?"));
}
else
{
msg.setText(tr("Changes to the profile \"%1\" have not been saved. Would you like to save or discard changes to the current profile?")
.arg(configBox->currentText()));
}
int status = msg.exec();
if (status == QMessageBox::Save)
{
saveConfigFile();
if (currentIndex == 0 && currentIndex == configBox->currentIndex())
{
discarded = false;
}
}
else if (status == QMessageBox::Discard)
{
joystick->revertProfileEdited();
configBox->setItemText(currentIndex, oldProfileName);
resetJoystick();
}
else if (status == QMessageBox::Cancel)
{
discarded = false;
}
disconnectMainComboBoxEvents();
reconnectCheckUnsavedEvent();
reconnectMainComboBoxEvents();
}
return discarded;
}
void JoyTabWidget::disconnectMainComboBoxEvents()
{
disconnect(configBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeJoyConfig(int)));
disconnect(configBox, SIGNAL(currentIndexChanged(int)), this, SLOT(removeProfileEditNotification()));
disconnect(joystick, SIGNAL(profileNameEdited(QString)), this, SLOT(editCurrentProfileItemText(QString)));
}
void JoyTabWidget::reconnectMainComboBoxEvents()
{
connect(configBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeJoyConfig(int)), Qt::QueuedConnection);
connect(configBox, SIGNAL(currentIndexChanged(int)), this, SLOT(removeProfileEditNotification()), Qt::QueuedConnection);
connect(joystick, SIGNAL(profileNameEdited(QString)), this, SLOT(editCurrentProfileItemText(QString)));
}
void JoyTabWidget::disconnectCheckUnsavedEvent()
{
disconnect(configBox, SIGNAL(currentIndexChanged(int)), this, SLOT(checkForUnsavedProfile(int)));
}
void JoyTabWidget::reconnectCheckUnsavedEvent()
{
connect(configBox, SIGNAL(currentIndexChanged(int)), this, SLOT(checkForUnsavedProfile(int)));
}
void JoyTabWidget::refreshButtons()
{
removeCurrentButtons();
fillButtons();
}
void JoyTabWidget::checkStickDisplay()
{
JoyControlStickButton *button = static_cast<JoyControlStickButton*>(sender());
JoyControlStick *stick = button->getStick();
if (stick && stick->hasSlotsAssigned())
{
SetJoystick *currentSet = joystick->getActiveSetJoystick();
removeSetButtons(currentSet);
fillSetButtons(currentSet);
}
}
void JoyTabWidget::checkDPadButtonDisplay()
{
JoyDPadButton *button = static_cast<JoyDPadButton*>(sender());
JoyDPad *dpad = button->getDPad();
if (dpad && dpad->hasSlotsAssigned())
{
SetJoystick *currentSet = joystick->getActiveSetJoystick();
removeSetButtons(currentSet);
fillSetButtons(currentSet);
}
}
void JoyTabWidget::checkAxisButtonDisplay()
{
JoyAxisButton *button = static_cast<JoyAxisButton*>(sender());
if (button->getAssignedSlots()->count() > 0)
{
SetJoystick *currentSet = joystick->getActiveSetJoystick();
removeSetButtons(currentSet);
fillSetButtons(currentSet);
}
}
void JoyTabWidget::checkButtonDisplay()
{
JoyButton *button = static_cast<JoyButton*>(sender());
if (button->getAssignedSlots()->count() > 0)
{
SetJoystick *currentSet = joystick->getActiveSetJoystick();
removeSetButtons(currentSet);
fillSetButtons(currentSet);
}
}
void JoyTabWidget::checkStickEmptyDisplay()
{
StickPushButtonGroup *group = static_cast<StickPushButtonGroup*>(sender());
JoyControlStick *stick = group->getStick();
//JoyControlStickButton *button = static_cast<JoyControlStickButton*>(sender());
//JoyControlStick *stick = button->getStick();
if (stick && !stick->hasSlotsAssigned())
{
SetJoystick *currentSet = joystick->getActiveSetJoystick();
removeSetButtons(currentSet);
fillSetButtons(currentSet);
}
}
void JoyTabWidget::checkDPadButtonEmptyDisplay()
{
DPadPushButtonGroup *group = static_cast<DPadPushButtonGroup*>(sender());
JoyDPad *dpad = group->getDPad();
//JoyDPadButton *button = static_cast<JoyDPadButton*>(sender());
//JoyDPad *dpad = button->getDPad();
if (dpad && !dpad->hasSlotsAssigned())
{
SetJoystick *currentSet = joystick->getActiveSetJoystick();
removeSetButtons(currentSet);
fillSetButtons(currentSet);
}
}
void JoyTabWidget::checkAxisButtonEmptyDisplay()
{
JoyAxisButton *button = static_cast<JoyAxisButton*>(sender());
if (button->getAssignedSlots()->count() == 0)
{
SetJoystick *currentSet = joystick->getActiveSetJoystick();
removeSetButtons(currentSet);
fillSetButtons(currentSet);
}
}
void JoyTabWidget::checkButtonEmptyDisplay()
{
JoyButton *button = static_cast<JoyButton*>(sender());
if (button->getAssignedSlots()->count() == 0)
{
SetJoystick *currentSet = joystick->getActiveSetJoystick();
removeSetButtons(currentSet);
fillSetButtons(currentSet);
}
}
void JoyTabWidget::checkHideEmptyOption()
{
bool currentHideEmptyButtons = settings->value("HideEmptyButtons", false).toBool();
if (currentHideEmptyButtons != hideEmptyButtons)
{
hideEmptyButtons = currentHideEmptyButtons;
refreshButtons();
}
}
void JoyTabWidget::fillSetButtons(SetJoystick *set)
{
int row = 0;
int column = 0;
//QWidget *child = 0;
QGridLayout *current_layout = 0;
switch (set->getIndex())
{
case 0:
{
current_layout = gridLayout;
break;
}
case 1:
{
current_layout = gridLayout2;
break;
}
case 2:
{
current_layout = gridLayout3;
break;
}
case 3:
{
current_layout = gridLayout4;
break;
}
case 4:
{
current_layout = gridLayout5;
break;
}
case 5:
{
current_layout = gridLayout6;
break;
}
case 6:
{
current_layout = gridLayout7;
break;
}
case 7:
{
current_layout = gridLayout8;
break;
}
default:
break;
}
/*while (current_layout && current_layout->count() > 0)
{
child = current_layout->takeAt(0)->widget();
current_layout->removeWidget (child);
delete child;
child = 0;
}
*/
SetJoystick *currentSet = set;
currentSet->establishPropertyUpdatedConnection();
QGridLayout *stickGrid = 0;
QGroupBox *stickGroup = 0;
int stickGridColumn = 0;
int stickGridRow = 0;
for (int j=0; j < joystick->getNumberSticks(); j++)
{
JoyControlStick *stick = currentSet->getJoyStick(j);
stick->establishPropertyUpdatedConnection();
QHash<JoyControlStick::JoyStickDirections, JoyControlStickButton*> *stickButtons = stick->getButtons();
if (!hideEmptyButtons || stick->hasSlotsAssigned())
{
if (!stickGroup)
{
stickGroup = new QGroupBox(tr("Sticks"), this);
}
if (!stickGrid)
{
stickGrid = new QGridLayout();
stickGridColumn = 0;
stickGridRow = 0;
}
QWidget *groupContainer = new QWidget(stickGroup);
StickPushButtonGroup *stickButtonGroup = new StickPushButtonGroup(stick, displayingNames, groupContainer);
if (hideEmptyButtons)
{
connect(stickButtonGroup, SIGNAL(buttonSlotChanged()), this, SLOT(checkStickEmptyDisplay()));
}
connect(namesPushButton, SIGNAL(clicked()), stickButtonGroup, SLOT(toggleNameDisplay()));
if (stickGridColumn > 1)
{
stickGridColumn = 0;
stickGridRow++;
}
groupContainer->setLayout(stickButtonGroup);
stickGrid->addWidget(groupContainer, stickGridRow, stickGridColumn);
stickGridColumn++;
}
else
{
QHashIterator<JoyControlStick::JoyStickDirections, JoyControlStickButton*> tempiter(*stickButtons);
while (tempiter.hasNext())
{
JoyControlStickButton *button = tempiter.next().value();
button->establishPropertyUpdatedConnections();
connect(button, SIGNAL(slotsChanged()), this, SLOT(checkStickDisplay()));
}
}
}
if (stickGroup)
{
QSpacerItem *tempspacer = new QSpacerItem(10, 4, QSizePolicy::Minimum, QSizePolicy::Fixed);
QVBoxLayout *tempvbox = new QVBoxLayout;
tempvbox->addLayout(stickGrid);
tempvbox->addItem(tempspacer);
stickGroup->setLayout(tempvbox);
current_layout->addWidget(stickGroup, row, column, 1, 2, Qt::AlignTop);
row++;
}
column = 0;
QGridLayout *hatGrid = 0;
QGroupBox *hatGroup = 0;
int hatGridColumn = 0;
int hatGridRow = 0;
for (int j=0; j < joystick->getNumberHats(); j++)
{
JoyDPad *dpad = currentSet->getJoyDPad(j);
dpad->establishPropertyUpdatedConnection();
QHash<int, JoyDPadButton*> *buttons = dpad->getJoyButtons();
if (!hideEmptyButtons || dpad->hasSlotsAssigned())
{
if (!hatGroup)
{
hatGroup = new QGroupBox(tr("DPads"), this);
}
if (!hatGrid)
{
hatGrid = new QGridLayout();
hatGridColumn = 0;
hatGridRow = 0;
}
QWidget *groupContainer = new QWidget(hatGroup);
DPadPushButtonGroup *dpadButtonGroup = new DPadPushButtonGroup(dpad, displayingNames, groupContainer);
if (hideEmptyButtons)
{
connect(dpadButtonGroup, SIGNAL(buttonSlotChanged()), this, SLOT(checkDPadButtonEmptyDisplay()));
}
connect(namesPushButton, SIGNAL(clicked()), dpadButtonGroup, SLOT(toggleNameDisplay()));
if (hatGridColumn > 1)
{
hatGridColumn = 0;
hatGridRow++;
}
groupContainer->setLayout(dpadButtonGroup);
hatGrid->addWidget(groupContainer, hatGridRow, hatGridColumn);
hatGridColumn++;
}
else
{
QHashIterator<int, JoyDPadButton*> tempiter(*buttons);
while (tempiter.hasNext())
{
JoyDPadButton *button = tempiter.next().value();
button->establishPropertyUpdatedConnections();
connect(button, SIGNAL(slotsChanged()), this, SLOT(checkDPadButtonDisplay()));
}
}
}
for (int j=0; j < joystick->getNumberVDPads(); j++)
{
VDPad *vdpad = currentSet->getVDPad(j);
vdpad->establishPropertyUpdatedConnection();
QHash<int, JoyDPadButton*> *buttons = vdpad->getButtons();
if (!hideEmptyButtons || vdpad->hasSlotsAssigned())
{
if (!hatGroup)
{
hatGroup = new QGroupBox(tr("DPads"), this);
}
if (!hatGrid)
{
hatGrid = new QGridLayout();
hatGridColumn = 0;
hatGridRow = 0;
}
QWidget *groupContainer = new QWidget(hatGroup);
DPadPushButtonGroup *dpadButtonGroup = new DPadPushButtonGroup(vdpad, displayingNames, groupContainer);
if (hideEmptyButtons)
{
connect(dpadButtonGroup, SIGNAL(buttonSlotChanged()), this, SLOT(checkDPadButtonEmptyDisplay()));
}
connect(namesPushButton, SIGNAL(clicked()), dpadButtonGroup, SLOT(toggleNameDisplay()));
if (hatGridColumn > 1)
{
hatGridColumn = 0;
hatGridRow++;
}
groupContainer->setLayout(dpadButtonGroup);
hatGrid->addWidget(groupContainer, hatGridRow, hatGridColumn);
hatGridColumn++;
}
else
{
QHashIterator<int, JoyDPadButton*> tempiter(*buttons);
while (tempiter.hasNext())
{
JoyDPadButton *button = tempiter.next().value();
button->establishPropertyUpdatedConnections();
connect(button, SIGNAL(slotsChanged()), this, SLOT(checkDPadButtonDisplay()));
}
}
}
if (hatGroup)
{
QSpacerItem *tempspacer = new QSpacerItem(10, 4, QSizePolicy::Minimum, QSizePolicy::Fixed);
QVBoxLayout *tempvbox = new QVBoxLayout;
tempvbox->addLayout(hatGrid);
tempvbox->addItem(tempspacer);
hatGroup->setLayout(tempvbox);
current_layout->addWidget(hatGroup, row, column, 1, 2, Qt::AlignTop);
row++;
}
column = 0;
for (int j=0; j < joystick->getNumberAxes(); j++)
{
JoyAxis *axis = currentSet->getJoyAxis(j);
if (!axis->isPartControlStick() && axis->hasControlOfButtons())
{
JoyAxisButton *paxisbutton = axis->getPAxisButton();
JoyAxisButton *naxisbutton = axis->getNAxisButton();
if (!hideEmptyButtons ||
(paxisbutton->getAssignedSlots()->count() > 0 ||
naxisbutton->getAssignedSlots()->count() > 0))
{
JoyAxisWidget *axisWidget = new JoyAxisWidget(axis, displayingNames, this);
axisWidget->setText(axis->getName());
axisWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
axisWidget->setMinimumSize(200, 24);
connect(axisWidget, SIGNAL(clicked()), this, SLOT(showAxisDialog()));
connect(namesPushButton, SIGNAL(clicked()), axisWidget, SLOT(toggleNameDisplay()));
if (hideEmptyButtons)
{
connect(paxisbutton, SIGNAL(slotsChanged()), this, SLOT(checkAxisButtonEmptyDisplay()));
connect(naxisbutton, SIGNAL(slotsChanged()), this, SLOT(checkAxisButtonEmptyDisplay()));
}
if (column > 1)
{
column = 0;
row++;
}
current_layout->addWidget(axisWidget, row, column);
column++;
}
else
{
paxisbutton->establishPropertyUpdatedConnections();
naxisbutton->establishPropertyUpdatedConnections();
connect(paxisbutton, SIGNAL(slotsChanged()), this, SLOT(checkAxisButtonDisplay()));
connect(naxisbutton, SIGNAL(slotsChanged()), this, SLOT(checkAxisButtonDisplay()));
}
}
}
for (int j=0; j < joystick->getNumberButtons(); j++)
{
JoyButton *button = currentSet->getJoyButton(j);
if (button && !button->isPartVDPad())
{
button->establishPropertyUpdatedConnections();
if (!hideEmptyButtons || button->getAssignedSlots()->count() > 0)
{
JoyButtonWidget *buttonWidget = new JoyButtonWidget (button, displayingNames, this);
buttonWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
buttonWidget->setText(buttonWidget->text());
buttonWidget->setMinimumSize(200, 24);
connect(buttonWidget, SIGNAL(clicked()), this, SLOT(showButtonDialog()));
connect(namesPushButton, SIGNAL(clicked()), buttonWidget, SLOT(toggleNameDisplay()));
if (hideEmptyButtons)
{
connect(button, SIGNAL(slotsChanged()), this, SLOT(checkButtonEmptyDisplay()));
}
if (column > 1)
{
column = 0;
row++;
}
current_layout->addWidget(buttonWidget, row, column);
column++;
}
else
{
button->establishPropertyUpdatedConnections();
connect(button, SIGNAL(slotsChanged()), this, SLOT(checkButtonDisplay()));
}
}
}
if (current_layout->count() == 0)
{
QLabel *newlabel = new QLabel(tr("No buttons have been assigned. Please use Quick Set to assign keys\nto buttons or disable hiding empty buttons."));
current_layout->addWidget(newlabel, 0, 0, Qt::AlignCenter);
}
}
void JoyTabWidget::removeSetButtons(SetJoystick *set)
{
SetJoystick *currentSet = set;
currentSet->disconnectPropertyUpdatedConnection();
QLayoutItem *child = 0;
QGridLayout *current_layout = 0;
switch (currentSet->getIndex())
{
case 0:
{
current_layout = gridLayout;
break;
}
case 1:
{
current_layout = gridLayout2;
break;
}
case 2:
{
current_layout = gridLayout3;
break;
}
case 3:
{
current_layout = gridLayout4;
break;
}
case 4:
{
current_layout = gridLayout5;
break;
}
case 5:
{
current_layout = gridLayout6;
break;
}
case 6:
{
current_layout = gridLayout7;
break;
}
case 7:
{
current_layout = gridLayout8;
break;
}
}
while (current_layout && (child = current_layout->takeAt(0)) != 0)
{
current_layout->removeWidget(child->widget());
delete child->widget();
delete child;
child = 0;
}
for (int j=0; j < joystick->getNumberSticks(); j++)
{
JoyControlStick *stick = currentSet->getJoyStick(j);
stick->disconnectPropertyUpdatedConnection();
QHash<JoyControlStick::JoyStickDirections, JoyControlStickButton*> *stickButtons = stick->getButtons();
QHashIterator<JoyControlStick::JoyStickDirections, JoyControlStickButton*> tempiter(*stickButtons);
while (tempiter.hasNext())
{
JoyControlStickButton *button = tempiter.next().value();
button->disconnectPropertyUpdatedConnections();
disconnect(button, SIGNAL(slotsChanged()), this, SLOT(checkStickDisplay()));
disconnect(button, SIGNAL(slotsChanged()), this, SLOT(checkStickEmptyDisplay()));
}
}
for (int j=0; j < joystick->getNumberHats(); j++)
{
JoyDPad *dpad = currentSet->getJoyDPad(j);
dpad->establishPropertyUpdatedConnection();
QHash<int, JoyDPadButton*> *buttons = dpad->getJoyButtons();
QHashIterator<int, JoyDPadButton*> tempiter(*buttons);
while (tempiter.hasNext())
{
JoyDPadButton *button = tempiter.next().value();
button->disconnectPropertyUpdatedConnections();
disconnect(button, SIGNAL(slotsChanged()), this, SLOT(checkDPadButtonDisplay()));
disconnect(button, SIGNAL(slotsChanged()), this, SLOT(checkDPadButtonEmptyDisplay()));
}
}
for (int j=0; j < joystick->getNumberVDPads(); j++)
{
VDPad *vdpad = currentSet->getVDPad(j);
vdpad->establishPropertyUpdatedConnection();
QHash<int, JoyDPadButton*> *buttons = vdpad->getButtons();
QHashIterator<int, JoyDPadButton*> tempiter(*buttons);
while (tempiter.hasNext())
{
JoyDPadButton *button = tempiter.next().value();
button->disconnectPropertyUpdatedConnections();
disconnect(button, SIGNAL(slotsChanged()), this, SLOT(checkDPadButtonDisplay()));
disconnect(button, SIGNAL(slotsChanged()), this, SLOT(checkDPadButtonEmptyDisplay()));
}
}
for (int j=0; j < joystick->getNumberAxes(); j++)
{
JoyAxis *axis = currentSet->getJoyAxis(j);
if (!axis->isPartControlStick() && axis->hasControlOfButtons())
{
JoyAxisButton *paxisbutton = axis->getPAxisButton();
JoyAxisButton *naxisbutton = axis->getNAxisButton();
paxisbutton->disconnectPropertyUpdatedConnections();
naxisbutton->disconnectPropertyUpdatedConnections();
disconnect(paxisbutton, SIGNAL(slotsChanged()), this, SLOT(checkAxisButtonDisplay()));
disconnect(naxisbutton, SIGNAL(slotsChanged()), this, SLOT(checkAxisButtonDisplay()));
disconnect(paxisbutton, SIGNAL(slotsChanged()), this, SLOT(checkAxisButtonEmptyDisplay()));
disconnect(naxisbutton, SIGNAL(slotsChanged()), this, SLOT(checkAxisButtonEmptyDisplay()));
}
}
for (int j=0; j < joystick->getNumberButtons(); j++)
{
JoyButton *button = currentSet->getJoyButton(j);
if (button && !button->isPartVDPad())
{
button->disconnectPropertyUpdatedConnections();
disconnect(button, SIGNAL(slotsChanged()), this, SLOT(checkButtonDisplay()));
disconnect(button, SIGNAL(slotsChanged()), this, SLOT(checkButtonEmptyDisplay()));
}
}
}
void JoyTabWidget::editCurrentProfileItemText(QString text)
{
int currentIndex = configBox->currentIndex();
if (currentIndex >= 0)
{
if (!text.isEmpty())
{
configBox->setItemText(currentIndex, text);
}
else if (currentIndex == 0)
{
configBox->setItemText(currentIndex, tr("<New>"));
}
else if (currentIndex > 0)
{
QFileInfo profileName(configBox->itemData(currentIndex).toString());
configBox->setItemText(currentIndex, PadderCommon::getProfileName(profileName));
}
}
}
#ifdef Q_OS_WIN
void JoyTabWidget::deviceKeyRepeatSettings()
{
bool keyRepeatActive = settings->value("KeyRepeat/KeyRepeatEnabled", true).toBool();
int keyRepeatDelay = settings->value("KeyRepeat/KeyRepeatDelay", InputDevice::DEFAULTKEYREPEATDELAY).toInt();
int keyRepeatRate = settings->value("KeyRepeat/KeyRepeatRate", InputDevice::DEFAULTKEYREPEATRATE).toInt();
joystick->setKeyRepeatStatus(keyRepeatActive);
joystick->setKeyRepeatDelay(keyRepeatDelay);
joystick->setKeyRepeatRate(keyRepeatRate);
}
#endif
void JoyTabWidget::refreshCopySetActions()
{
copySetMenu->clear();
for (int i=0; i < InputDevice::NUMBER_JOYSETS; i++)
{
SetJoystick *tempSet = joystick->getSetJoystick(i);
QAction *newaction = 0;
if (!tempSet->getName().isEmpty())
{
QString tempName = tempSet->getName();
QString tempNameEscaped = tempName;
tempNameEscaped.replace("&", "&&");
newaction = new QAction(tr("Set %1: %2").arg(i+1).arg(tempNameEscaped), copySetMenu);
}
else
{
newaction = new QAction(tr("Set %1").arg(i+1), copySetMenu);
}
newaction->setData(i);
connect(newaction, SIGNAL(triggered()), this, SLOT(performSetCopy()));
copySetMenu->addAction(newaction);
}
connect(copySetMenu, SIGNAL(aboutToShow()), this, SLOT(disableCopyCurrentSet()));
}
void JoyTabWidget::performSetCopy()
{
QAction *action = static_cast<QAction*>(sender());
int sourceSetIndex = action->data().toInt();
SetJoystick *sourceSet = joystick->getSetJoystick(sourceSetIndex);
QString sourceName;
if (!sourceSet->getName().isEmpty())
{
QString tempNameEscaped = sourceSet->getName();
tempNameEscaped.replace("&", "&&");
sourceName = tr("Set %1: %2").arg(sourceSetIndex+1).arg(tempNameEscaped);
}
else
{
sourceName = tr("Set %1").arg(sourceSetIndex+1);
}
SetJoystick *destSet = joystick->getActiveSetJoystick();
if (sourceSet && destSet)
{
QMessageBox msgBox;
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msgBox.setWindowTitle(tr("Copy Set Assignments"));
msgBox.setText(tr("Are you sure you want to copy the assignments and device properties from %1?").arg(sourceName));
int status = msgBox.exec();
if (status == QMessageBox::Yes)
{
PadderCommon::lockInputDevices();
removeSetButtons(destSet);
QMetaObject::invokeMethod(sourceSet, "copyAssignments", Qt::BlockingQueuedConnection,
Q_ARG(SetJoystick*, destSet));
//sourceSet->copyAssignments(destSet);
fillSetButtons(destSet);
PadderCommon::unlockInputDevices();
}
}
}
void JoyTabWidget::disableCopyCurrentSet()
{
SetJoystick *activeSet = joystick->getActiveSetJoystick();
QMenu *menu = static_cast<QMenu*>(sender());
QList<QAction*> actions = menu->actions();
QListIterator<QAction*> iter(actions);
while (iter.hasNext())
{
QAction *action = iter.next();
if (action->data().toInt() == activeSet->getIndex())
{
action->setEnabled(false);
}
else
{
action->setEnabled(true);
}
}
}
#ifdef USE_SDL_2
void JoyTabWidget::openGameControllerMappingWindow()
{
GameControllerMappingDialog *dialog = new GameControllerMappingDialog(joystick, settings, this);
dialog->show();
connect(dialog, SIGNAL(mappingUpdate(QString,InputDevice*)), this, SLOT(propogateMappingUpdate(QString, InputDevice*)));
}
void JoyTabWidget::propogateMappingUpdate(QString mapping, InputDevice *device)
{
emit mappingUpdated(mapping, device);
}
#endif
void JoyTabWidget::refreshHelperThread()
{
tabHelper.moveToThread(joystick->thread());
}
void JoyTabWidget::changeEvent(QEvent *event)
{
if (event->type() == QEvent::LanguageChange)
{
retranslateUi();
}
QWidget::changeEvent(event);
}
``` | /content/code_sandbox/src/joytabwidget.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 17,836 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef QKEYDISPLAYDIALOG_H
#define QKEYDISPLAYDIALOG_H
#include <QDialog>
#include <QKeyEvent>
namespace Ui {
class QKeyDisplayDialog;
}
class QKeyDisplayDialog : public QDialog
{
Q_OBJECT
public:
explicit QKeyDisplayDialog(QWidget *parent = 0);
~QKeyDisplayDialog();
protected:
virtual void keyPressEvent(QKeyEvent *event);
virtual void keyReleaseEvent(QKeyEvent *event);
private:
Ui::QKeyDisplayDialog *ui;
};
#endif // QKEYDISPLAYDIALOG_H
``` | /content/code_sandbox/src/qkeydisplaydialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 213 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef INPUTDEVICE_H
#define INPUTDEVICE_H
#include <QObject>
#include <QList>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QRegExp>
#ifdef USE_SDL_2
#include <SDL2/SDL_joystick.h>
#include <SDL2/SDL_platform.h>
#else
#include <SDL/SDL_joystick.h>
typedef Sint32 SDL_JoystickID;
#endif
#include "setjoystick.h"
#include "common.h"
#include "antimicrosettings.h"
class InputDevice : public QObject
{
Q_OBJECT
public:
explicit InputDevice(int deviceIndex, AntiMicroSettings *settings, QObject *parent = 0);
virtual ~InputDevice();
virtual int getNumberButtons();
virtual int getNumberAxes();
virtual int getNumberHats();
virtual int getNumberSticks();
virtual int getNumberVDPads();
int getJoyNumber();
int getRealJoyNumber();
int getActiveSetNumber();
SetJoystick* getActiveSetJoystick();
SetJoystick* getSetJoystick(int index);
void removeControlStick(int index);
bool isActive();
int getButtonDownCount();
virtual QString getName() = 0;
virtual QString getSDLName() = 0;
// GUID only available on SDL 2.
virtual QString getGUIDString() = 0;
virtual QString getRawGUIDString();
virtual QString getStringIdentifier();
virtual QString getXmlName() = 0;
virtual void closeSDLDevice() = 0;
#ifdef USE_SDL_2
virtual SDL_JoystickID getSDLJoystickID() = 0;
QString getSDLPlatform();
#endif
virtual bool isGameController();
virtual bool isKnownController();
void setButtonName(int index, QString tempName);
void setAxisButtonName(int axisIndex, int buttonIndex, QString tempName);
void setStickButtonName(int stickIndex, int buttonIndex, QString tempName);
void setDPadButtonName(int dpadIndex, int buttonIndex, QString tempName);
void setVDPadButtonName(int vdpadIndex, int buttonIndex, QString tempName);
void setAxisName(int axisIndex, QString tempName);
void setStickName(int stickIndex, QString tempName);
void setDPadName(int dpadIndex, QString tempName);
void setVDPadName(int vdpadIndex, QString tempName);
virtual int getNumberRawButtons() = 0;
virtual int getNumberRawAxes() = 0;
virtual int getNumberRawHats() = 0;
unsigned int getDeviceKeyPressTime();
void setIndex(int index);
bool isDeviceEdited();
void revertProfileEdited();
void setKeyRepeatStatus(bool enabled);
void setKeyRepeatDelay(int delay);
void setKeyRepeatRate(int rate);
bool isKeyRepeatEnabled();
int getKeyRepeatDelay();
int getKeyRepeatRate();
QString getProfileName();
bool hasCalibrationThrottle(int axisNum);
JoyAxis::ThrottleTypes getCalibrationThrottle(int axisNum);
void setCalibrationThrottle(int axisNum, JoyAxis::ThrottleTypes throttle);
void setCalibrationStatus(int axisNum, JoyAxis::ThrottleTypes throttle);
void removeCalibrationStatus(int axisNum);
void sendLoadProfileRequest(QString location);
AntiMicroSettings *getSettings();
void activatePossiblePendingEvents();
void activatePossibleControlStickEvents();
void activatePossibleAxisEvents();
void activatePossibleDPadEvents();
void activatePossibleVDPadEvents();
void activatePossibleButtonEvents();
bool isEmptyGUID(QString tempGUID);
bool isRelevantGUID(QString tempGUID);
void setRawAxisDeadZone(int deadZone);
int getRawAxisDeadZone();
void rawAxisEvent(int index, int value);
static const int NUMBER_JOYSETS;
static const int DEFAULTKEYPRESSTIME;
static const unsigned int DEFAULTKEYREPEATDELAY;
static const unsigned int DEFAULTKEYREPEATRATE;
static const int RAISEDDEADZONE;
protected:
void enableSetConnections(SetJoystick *setstick);
bool elementsHaveNames();
SDL_Joystick* joyhandle;
QHash<int, SetJoystick*> joystick_sets;
QHash<int, JoyAxis::ThrottleTypes> cali;
AntiMicroSettings *settings;
int active_set;
int joyNumber;
int buttonDownCount;
SDL_JoystickID joystickID;
unsigned int keyPressTime;
bool deviceEdited;
bool keyRepeatEnabled;
int keyRepeatDelay;
int keyRepeatRate;
QString profileName;
QList<bool> buttonstates;
QList<int> axesstates;
QList<int> dpadstates;
int rawAxisDeadZone;
static QRegExp emptyGUID;
signals:
void setChangeActivated(int index);
void setAxisThrottleActivated(int index);
void clicked(int index);
void released(int index);
void rawButtonClick(int index);
void rawButtonRelease(int index);
void rawAxisButtonClick(int axis, int buttonindex);
void rawAxisButtonRelease(int axis, int buttonindex);
void rawDPadButtonClick(int dpad, int buttonindex);
void rawDPadButtonRelease(int dpad, int buttonindex);
void rawAxisActivated(int axis, int value);
void rawAxisReleased(int axis, int value);
void rawAxisMoved(int axis, int value);
void profileUpdated();
void propertyUpdated();
void profileNameEdited(QString text);
void requestProfileLoad(QString location);
void requestWait();
public slots:
void reset();
void transferReset();
void reInitButtons();
void resetButtonDownCount();
void setActiveSetNumber(int index);
void changeSetButtonAssociation(int button_index, int originset, int newset, int mode);
void changeSetAxisButtonAssociation(int button_index, int axis_index, int originset, int newset, int mode);
void changeSetStickButtonAssociation(int button_index, int stick_index, int originset, int newset, int mode);
void changeSetDPadButtonAssociation(int button_index, int dpad_index, int originset, int newset, int mode);
void changeSetVDPadButtonAssociation(int button_index, int dpad_index, int originset, int newset, int mode);
void setDeviceKeyPressTime(unsigned int newPressTime);
void profileEdited();
void setProfileName(QString value);
void haltServices();
void finalRemoval();
virtual void readConfig(QXmlStreamReader *xml);
virtual void writeConfig(QXmlStreamWriter *xml);
void establishPropertyUpdatedConnection();
void disconnectPropertyUpdatedConnection();
protected slots:
void propogateSetChange(int index);
void propogateSetAxisThrottleChange(int index, int originset);
void buttonDownEvent(int setindex, int buttonindex);
void buttonUpEvent(int setindex, int buttonindex);
virtual void axisActivatedEvent(int setindex, int axisindex, int value);
virtual void axisReleasedEvent(int setindex, int axisindex, int value);
virtual void buttonClickEvent(int buttonindex);
virtual void buttonReleaseEvent(int buttonindex);
virtual void axisButtonDownEvent(int setindex, int axisindex, int buttonindex);
virtual void axisButtonUpEvent(int setindex, int axisindex, int buttonindex);
virtual void dpadButtonDownEvent(int setindex, int dpadindex, int buttonindex);
virtual void dpadButtonUpEvent(int setindex, int dpadindex, int buttonindex);
virtual void dpadButtonClickEvent(int buttonindex);
virtual void dpadButtonReleaseEvent(int buttonindex);
virtual void stickButtonDownEvent(int setindex, int stickindex, int buttonindex);
virtual void stickButtonUpEvent(int setindex, int stickindex, int buttonindex);
void updateSetButtonNames(int index);
void updateSetAxisButtonNames(int axisIndex, int buttonIndex);
void updateSetStickButtonNames(int stickIndex, int buttonIndex);
void updateSetDPadButtonNames(int dpadIndex, int buttonIndex);
void updateSetVDPadButtonNames(int vdpadIndex, int buttonIndex);
void updateSetAxisNames(int axisIndex);
void updateSetStickNames(int stickIndex);
void updateSetDPadNames(int dpadIndex);
void updateSetVDPadNames(int vdpadIndex);
};
Q_DECLARE_METATYPE(InputDevice*)
Q_DECLARE_METATYPE(SDL_JoystickID)
#endif // INPUTDEVICE_H
``` | /content/code_sandbox/src/inputdevice.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,912 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef QTX11KEYMAPPER_H
#define QTX11KEYMAPPER_H
#include <QObject>
#include <QHash>
#include <QChar>
#include "qtkeymapperbase.h"
class QtX11KeyMapper : public QtKeyMapperBase
{
Q_OBJECT
public:
explicit QtX11KeyMapper(QObject *parent = 0);
protected:
void populateMappingHashes();
void populateCharKeyInformation();
signals:
public slots:
};
#endif // QTX11KEYMAPPER_H
``` | /content/code_sandbox/src/qtx11keymapper.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 202 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include "vdpad.h"
const QString VDPad::xmlName = "vdpad";
VDPad::VDPad(int index, int originset, SetJoystick *parentSet, QObject *parent) :
JoyDPad(index, originset, parentSet, parent)
{
this->upButton = 0;
this->downButton = 0;
this->leftButton = 0;
this->rightButton = 0;
pendingVDPadEvent = false;
}
VDPad::VDPad(JoyButton *upButton, JoyButton *downButton, JoyButton *leftButton, JoyButton *rightButton,
int index, int originset, SetJoystick *parentSet, QObject *parent) :
JoyDPad(index, originset, parentSet, parent)
{
this->upButton = upButton;
upButton->setVDPad(this);
this->downButton = downButton;
downButton->setVDPad(this);
this->leftButton = leftButton;
leftButton->setVDPad(this);
this->rightButton = rightButton;
rightButton->setVDPad(this);
pendingVDPadEvent = false;
}
VDPad::~VDPad()
{
if (upButton)
{
upButton->removeVDPad();
upButton = 0;
}
if (downButton)
{
downButton->removeVDPad();
downButton = 0;
}
if (leftButton)
{
leftButton->removeVDPad();
leftButton = 0;
}
if (rightButton)
{
rightButton->removeVDPad();
rightButton = 0;
}
}
QString VDPad::getXmlName()
{
return this->xmlName;
}
QString VDPad::getName(bool forceFullFormat, bool displayName)
{
QString label;
if (!dpadName.isEmpty() && displayName)
{
if (forceFullFormat)
{
label.append(tr("VDPad")).append(" ");
}
label.append(dpadName);
}
else if (!defaultDPadName.isEmpty())
{
if (forceFullFormat)
{
label.append(tr("VDPad")).append(" ");
}
label.append(defaultDPadName);
}
else
{
label.append(tr("VDPad")).append(" ");
label.append(QString::number(getRealJoyNumber()));
}
return label;
}
void VDPad::joyEvent(bool pressed, bool ignoresets)
{
Q_UNUSED(pressed);
int tempDirection = static_cast<int>(JoyDPadButton::DpadCentered);
/*
* Check which buttons are currently active
*/
if (upButton && upButton->getButtonState())
{
tempDirection |= JoyDPadButton::DpadUp;
}
if (downButton && downButton->getButtonState())
{
tempDirection |= JoyDPadButton::DpadDown;
}
if (leftButton && leftButton->getButtonState())
{
tempDirection |= JoyDPadButton::DpadLeft;
}
if (rightButton && rightButton->getButtonState())
{
tempDirection |= JoyDPadButton::DpadRight;
}
JoyDPad::joyEvent(tempDirection, ignoresets);
pendingVDPadEvent = false;
}
void VDPad::addVButton(JoyDPadButton::JoyDPadDirections direction, JoyButton *button)
{
if (direction == JoyDPadButton::DpadUp)
{
if (upButton)
{
upButton->removeVDPad();
}
upButton = button;
upButton->setVDPad(this);
}
else if (direction == JoyDPadButton::DpadDown)
{
if (downButton)
{
downButton->removeVDPad();
}
downButton = button;
downButton->setVDPad(this);
}
else if (direction == JoyDPadButton::DpadLeft)
{
if (leftButton)
{
leftButton->removeVDPad();
}
leftButton = button;
leftButton->setVDPad(this);
}
else if (direction == JoyDPadButton::DpadRight)
{
if (rightButton)
{
rightButton->removeVDPad();
}
rightButton = button;
rightButton->setVDPad(this);
}
}
void VDPad::removeVButton(JoyDPadButton::JoyDPadDirections direction)
{
if (direction == JoyDPadButton::DpadUp && upButton)
{
upButton->removeVDPad();
upButton = 0;
}
else if (direction == JoyDPadButton::DpadDown && downButton)
{
downButton->removeVDPad();
downButton = 0;
}
else if (direction == JoyDPadButton::DpadLeft && leftButton)
{
leftButton->removeVDPad();
leftButton = 0;
}
else if (direction == JoyDPadButton::DpadRight && rightButton)
{
rightButton->removeVDPad();
rightButton = 0;
}
}
void VDPad::removeVButton(JoyButton *button)
{
if (button && button == upButton)
{
upButton->removeVDPad();
upButton = 0;
}
else if (button && button == downButton)
{
downButton->removeVDPad();
downButton = 0;
}
else if (button && button == leftButton)
{
leftButton->removeVDPad();
leftButton = 0;
}
else if (button && button == rightButton)
{
rightButton->removeVDPad();
rightButton = 0;
}
}
bool VDPad::isEmpty()
{
bool empty = true;
if (upButton || downButton || leftButton || rightButton)
{
empty = false;
}
return empty;
}
JoyButton* VDPad::getVButton(JoyDPadButton::JoyDPadDirections direction)
{
JoyButton *button = 0;
if (direction == JoyDPadButton::DpadUp)
{
button = upButton;
}
else if (direction == JoyDPadButton::DpadDown)
{
button = downButton;
}
else if (direction == JoyDPadButton::DpadLeft)
{
button = leftButton;
}
else if (direction == JoyDPadButton::DpadRight)
{
button = rightButton;
}
return button;
}
bool VDPad::hasPendingEvent()
{
return pendingVDPadEvent;
}
void VDPad::queueJoyEvent(bool ignoresets)
{
Q_UNUSED(ignoresets);
pendingVDPadEvent = true;
}
void VDPad::activatePendingEvent()
{
if (pendingVDPadEvent)
{
// Always use true. The proper direction value will be determined
// in the joyEvent method.
joyEvent(true);
pendingVDPadEvent = false;
}
}
void VDPad::clearPendingEvent()
{
pendingVDPadEvent = false;
}
``` | /content/code_sandbox/src/vdpad.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,692 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef AUTOPROFILEINFO_H
#define AUTOPROFILEINFO_H
#include <QObject>
#include <QMetaType>
class AutoProfileInfo : public QObject
{
Q_OBJECT
public:
explicit AutoProfileInfo(QString guid, QString profileLocation,
bool active, QObject *parent = 0);
explicit AutoProfileInfo(QString guid, QString profileLocation,
QString exe, bool active, QObject *parent = 0);
explicit AutoProfileInfo(QObject *parent=0);
~AutoProfileInfo();
void setGUID(QString guid);
QString getGUID();
void setProfileLocation(QString profileLocation);
QString getProfileLocation();
void setExe(QString exe);
QString getExe();
void setWindowClass(QString windowClass);
QString getWindowClass();
void setWindowName(QString winName);
QString getWindowName();
void setActive(bool active);
bool isActive();
void setDeviceName(QString name);
QString getDeviceName();
void setDefaultState(bool value);
bool isCurrentDefault();
protected:
QString guid;
QString profileLocation;
QString exe;
QString deviceName;
QString windowClass;
QString windowName;
bool active;
bool defaultState;
signals:
public slots:
};
Q_DECLARE_METATYPE(AutoProfileInfo*)
#endif // AUTOPROFILEINFO_H
``` | /content/code_sandbox/src/autoprofileinfo.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 373 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef JOYBUTTONCONTEXTMENU_H
#define JOYBUTTONCONTEXTMENU_H
#include <QMenu>
#include "joybutton.h"
class JoyButtonContextMenu : public QMenu
{
Q_OBJECT
public:
explicit JoyButtonContextMenu(JoyButton *button, QWidget *parent = 0);
void buildMenu();
protected:
JoyButton *button;
signals:
private slots:
void switchToggle();
void switchTurbo();
void switchSetMode();
void disableSetMode();
void clearButton();
};
#endif // JOYBUTTONCONTEXTMENU_H
``` | /content/code_sandbox/src/joybuttoncontextmenu.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 213 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include "event.h"
#include "antkeymapper.h"
#ifdef Q_OS_UNIX
#include "eventhandlerfactory.h"
#endif
#include "xmlconfigmigration.h"
XMLConfigMigration::XMLConfigMigration(QXmlStreamReader *reader, QObject *parent) :
QObject(parent)
{
this->reader = reader;
if (reader->device() && reader->device()->isOpen())
{
this->fileVersion = reader->attributes().value("configversion").toString().toInt();
}
else
{
this->fileVersion = 0;
}
}
bool XMLConfigMigration::requiresMigration()
{
bool toMigrate = false;
if (fileVersion == 0)
{
toMigrate = false;
}
else if (fileVersion >= 2 && fileVersion <= PadderCommon::LATESTCONFIGMIGRATIONVERSION)
{
toMigrate = true;
}
return toMigrate;
}
QString XMLConfigMigration::migrate()
{
QString tempXmlString;
if (requiresMigration())
{
int tempFileVersion = fileVersion;
QString initialData = readConfigToString();
reader->clear();
reader->addData(initialData);
if (tempFileVersion >= 2 && tempFileVersion <= 5)
{
tempXmlString = version0006Migration();
tempFileVersion = PadderCommon::LATESTCONFIGFILEVERSION;
}
}
return tempXmlString;
}
QString XMLConfigMigration::readConfigToString()
{
QString tempXmlString;
QXmlStreamWriter writer(&tempXmlString);
writer.setAutoFormatting(true);
while (!reader->atEnd())
{
writer.writeCurrentToken(*reader);
reader->readNext();
}
return tempXmlString;
}
QString XMLConfigMigration::version0006Migration()
{
QString tempXmlString;
QXmlStreamWriter writer(&tempXmlString);
writer.setAutoFormatting(true);
reader->readNextStartElement();
reader->readNextStartElement();
writer.writeStartDocument();
writer.writeStartElement("joystick");
writer.writeAttribute("configversion", QString::number(6));
writer.writeAttribute("appversion", PadderCommon::programVersion);
while (!reader->atEnd())
{
if (reader->name() == "slot" && reader->isStartElement())
{
unsigned int slotcode = 0;
QString slotmode;
writer.writeCurrentToken(*reader);
reader->readNext();
// Grab current slot code and slot mode
while (!reader->atEnd() && (!reader->isEndElement() && reader->name() != "slot"))
{
if (reader->name() == "code" && reader->isStartElement())
{
QString tempcode = reader->readElementText();
slotcode = tempcode.toInt();
}
else if (reader->name() == "mode" && reader->isStartElement())
{
slotmode = reader->readElementText();
}
else
{
writer.writeCurrentToken(*reader);
}
reader->readNext();
}
// Reformat slot code if associated with the keyboard
if (slotcode && !slotmode.isEmpty())
{
if (slotmode == "keyboard")
{
unsigned int tempcode = slotcode;
#ifdef Q_OS_WIN
slotcode = AntKeyMapper::getInstance()->returnQtKey(slotcode);
#else
BaseEventHandler *handler = EventHandlerFactory::getInstance()->handler();
if (handler->getIdentifier() == "xtest")
{
slotcode = AntKeyMapper::getInstance()->returnQtKey(X11KeyCodeToX11KeySym(slotcode));
}
else
{
slotcode = 0;
tempcode = 0;
}
#endif
if (slotcode > 0)
{
writer.writeTextElement("code", QString("0x%1").arg(slotcode, 0, 16));
}
else if (tempcode > 0)
{
writer.writeTextElement("code", QString("0x%1").arg(tempcode | QtKeyMapperBase::nativeKeyPrefix, 0, 16));
}
}
else
{
writer.writeTextElement("code", QString::number(slotcode));
}
writer.writeTextElement("mode", slotmode);
}
writer.writeCurrentToken(*reader);
}
else
{
writer.writeCurrentToken(*reader);
}
reader->readNext();
}
return tempXmlString;
}
``` | /content/code_sandbox/src/xmlconfigmigration.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,048 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
//#include <QDebug>
#include <cmath>
#include "joyaxis.h"
#include "joycontrolstick.h"
#include "inputdevice.h"
#include "event.h"
// Set default values for many properties.
const int JoyAxis::AXISMIN = -32767;
const int JoyAxis::AXISMAX = 32767;
const int JoyAxis::AXISDEADZONE = 6000;
const int JoyAxis::AXISMAXZONE = 32000;
// Speed in pixels/second
const float JoyAxis::JOYSPEED = 20.0;
const JoyAxis::ThrottleTypes JoyAxis::DEFAULTTHROTTLE = JoyAxis::NormalThrottle;
const QString JoyAxis::xmlName = "axis";
JoyAxis::JoyAxis(int index, int originset, SetJoystick *parentSet,
QObject *parent) :
QObject(parent)
{
stick = 0;
lastKnownThottledValue = 0;
lastKnownRawValue = 0;
this->originset = originset;
this->parentSet = parentSet;
naxisbutton = new JoyAxisButton(this, 0, originset, parentSet, this);
paxisbutton = new JoyAxisButton(this, 1, originset, parentSet, this);
reset();
this->index = index;
}
JoyAxis::~JoyAxis()
{
reset();
}
void JoyAxis::queuePendingEvent(int value, bool ignoresets, bool updateLastValues)
{
pendingEvent = false;
pendingValue = 0;
pendingIgnoreSets = false;
//pendingUpdateLastValues = true;
if (this->stick)
{
stickPassEvent(value, ignoresets, updateLastValues);
}
else
{
pendingEvent = true;
pendingValue = value;
pendingIgnoreSets = ignoresets;
//pendingUpdateLastValues = updateLastValues;
}
}
void JoyAxis::activatePendingEvent()
{
if (pendingEvent)
{
joyEvent(pendingValue, pendingIgnoreSets);
pendingEvent = false;
pendingValue = false;
pendingIgnoreSets = false;
//pendingUpdateLastValues = true;
}
}
bool JoyAxis::hasPendingEvent()
{
return pendingEvent;
}
void JoyAxis::clearPendingEvent()
{
pendingEvent = false;
pendingValue = false;
pendingIgnoreSets = false;
}
void JoyAxis::stickPassEvent(int value, bool ignoresets, bool updateLastValues)
{
if (this->stick)
{
if (updateLastValues)
{
lastKnownThottledValue = currentThrottledValue;
lastKnownRawValue = currentRawValue;
}
setCurrentRawValue(value);
//currentRawValue = value;
bool safezone = !inDeadZone(currentRawValue);
currentThrottledValue = calculateThrottledValue(value);
if (safezone && !isActive)
{
isActive = eventActive = true;
emit active(value);
}
else if (!safezone && isActive)
{
isActive = eventActive = false;
emit released(value);
}
if (!ignoresets)
{
stick->queueJoyEvent(ignoresets);
}
else
{
stick->joyEvent(ignoresets);
}
emit moved(currentRawValue);
}
}
void JoyAxis::joyEvent(int value, bool ignoresets, bool updateLastValues)
{
if (this->stick && !pendingEvent)
{
stickPassEvent(value, ignoresets, updateLastValues);
}
else
{
if (updateLastValues)
{
lastKnownThottledValue = currentThrottledValue;
lastKnownRawValue = currentRawValue;
}
setCurrentRawValue(value);
//currentRawValue = value;
bool safezone = !inDeadZone(currentRawValue);
currentThrottledValue = calculateThrottledValue(value);
// If in joystick mode and this is the first detected event,
// use the current value as the axis center point. If the value
// is below -30,000 then consider it a trigger.
InputDevice *device = parentSet->getInputDevice();
if (!device->isGameController() && !device->hasCalibrationThrottle(index))
{
performCalibration(currentRawValue);
safezone = !inDeadZone(currentRawValue);
currentThrottledValue = calculateThrottledValue(value);
}
if (safezone && !isActive)
{
isActive = eventActive = true;
emit active(value);
createDeskEvent(ignoresets);
}
else if (!safezone && isActive)
{
isActive = eventActive = false;
emit released(value);
createDeskEvent(ignoresets);
}
else if (isActive)
{
createDeskEvent(ignoresets);
}
}
emit moved(currentRawValue);
}
bool JoyAxis::inDeadZone(int value)
{
bool result = false;
int temp = calculateThrottledValue(value);
if (abs(temp) <= deadZone)
{
result = true;
}
return result;
}
QString JoyAxis::getName(bool forceFullFormat, bool displayNames)
{
QString label = getPartialName(forceFullFormat, displayNames);
label.append(": ");
if (throttle == NormalThrottle)
{
label.append("-");
if (!naxisbutton->getActionName().isEmpty() && displayNames)
{
label.append(naxisbutton->getActionName());
}
else
{
label.append(naxisbutton->getCalculatedActiveZoneSummary());
}
label.append(" | +");
if (!paxisbutton->getActionName().isEmpty() && displayNames)
{
label.append(paxisbutton->getActionName());
}
else
{
label.append(paxisbutton->getCalculatedActiveZoneSummary());
}
}
else if (throttle == PositiveThrottle || throttle == PositiveHalfThrottle)
{
label.append("+");
if (!paxisbutton->getActionName().isEmpty() && displayNames)
{
label.append(paxisbutton->getActionName());
}
else
{
label.append(paxisbutton->getCalculatedActiveZoneSummary());
}
}
else if (throttle == NegativeThrottle || throttle == NegativeHalfThrottle)
{
label.append("-");
if (!naxisbutton->getActionName().isEmpty() && displayNames)
{
label.append(naxisbutton->getActionName());
}
else
{
label.append(naxisbutton->getCalculatedActiveZoneSummary());
}
}
return label;
}
int JoyAxis::getRealJoyIndex()
{
return index + 1;
}
int JoyAxis::getCurrentThrottledValue()
{
return currentThrottledValue;
}
int JoyAxis::calculateThrottledValue(int value)
{
int temp = value;
if (throttle == NegativeHalfThrottle)
{
value = value <= 0 ? value : -value;
temp = value;
}
else if (throttle == NegativeThrottle)
{
temp = (value + AXISMIN) / 2;
}
else if (throttle == PositiveThrottle)
{
temp = (value + AXISMAX) / 2;
}
else if (throttle == PositiveHalfThrottle)
{
value = value >= 0 ? value : -value;
temp = value;
}
return temp;
}
void JoyAxis::setIndex(int index)
{
this->index = index;
}
int JoyAxis::getIndex()
{
return index;
}
void JoyAxis::createDeskEvent(bool ignoresets)
{
JoyAxisButton *eventbutton = 0;
if (currentThrottledValue > deadZone)
{
eventbutton = paxisbutton;
}
else if (currentThrottledValue < -deadZone)
{
eventbutton = naxisbutton;
}
if (eventbutton && !activeButton)
{
// There is no active button. Call joyEvent and set current
// button as active button
eventbutton->joyEvent(eventActive, ignoresets);
activeButton = eventbutton;
}
else if (!eventbutton && activeButton)
{
// Currently in deadzone. Disable currently active button.
activeButton->joyEvent(eventActive, ignoresets);
activeButton = 0;
}
else if (eventbutton && activeButton && eventbutton == activeButton)
{
//Button is currently active. Just pass current value
eventbutton->joyEvent(eventActive, ignoresets);
}
else if (eventbutton && activeButton && eventbutton != activeButton)
{
// Deadzone skipped. Button for new event is not the currently
// active button. Disable the active button before enabling
// the new button
activeButton->joyEvent(!eventActive, ignoresets);
eventbutton->joyEvent(eventActive, ignoresets);
activeButton = eventbutton;
}
}
void JoyAxis::setDeadZone(int value)
{
deadZone = abs(value);
emit propertyUpdated();
}
int JoyAxis::getDeadZone()
{
return deadZone;
}
void JoyAxis::setMaxZoneValue(int value)
{
value = abs(value);
if (value >= AXISMAX)
{
maxZoneValue = AXISMAX;
emit propertyUpdated();
}
else
{
maxZoneValue = value;
emit propertyUpdated();
}
}
int JoyAxis::getMaxZoneValue()
{
return maxZoneValue;
}
/**
* @brief Set throttle value for axis.
* @param Current value for axis.
*/
void JoyAxis::setThrottle(int value)
{
if (value >= JoyAxis::NegativeHalfThrottle && value <= JoyAxis::PositiveHalfThrottle)
{
if (value != throttle)
{
throttle = value;
adjustRange();
emit throttleChanged();
emit propertyUpdated();
}
}
}
/**
* @brief Set the initial calibrated throttle based on the first event
* passed by SDL.
* @param Current value for axis.
*/
void JoyAxis::setInitialThrottle(int value)
{
if (value >= JoyAxis::NegativeHalfThrottle && value <= JoyAxis::PositiveHalfThrottle)
{
if (value != throttle)
{
throttle = value;
adjustRange();
emit throttleChanged();
}
}
}
int JoyAxis::getThrottle()
{
return throttle;
}
void JoyAxis::readConfig(QXmlStreamReader *xml)
{
if (xml->isStartElement() && xml->name() == getXmlName())
{
//reset();
xml->readNextStartElement();
while (!xml->atEnd() && (!xml->isEndElement() && xml->name() != getXmlName()))
{
bool found = false;
found = readMainConfig(xml);
if (!found && xml->name() == naxisbutton->getXmlName() && xml->isStartElement())
{
found = true;
readButtonConfig(xml);
}
if (!found)
{
xml->skipCurrentElement();
}
xml->readNextStartElement();
}
}
}
void JoyAxis::writeConfig(QXmlStreamWriter *xml)
{
bool currentlyDefault = isDefault();
xml->writeStartElement(getXmlName());
xml->writeAttribute("index", QString::number(index+1));
if (!currentlyDefault)
{
if (deadZone != AXISDEADZONE)
{
xml->writeTextElement("deadZone", QString::number(deadZone));
}
if (maxZoneValue != AXISMAXZONE)
{
xml->writeTextElement("maxZone", QString::number(maxZoneValue));
}
}
//if (throttle != DEFAULTTHROTTLE)
//{
xml->writeStartElement("throttle");
if (throttle == JoyAxis::NegativeHalfThrottle)
{
xml->writeCharacters("negativehalf");
}
else if (throttle == JoyAxis::NegativeThrottle)
{
xml->writeCharacters("negative");
}
else if (throttle == JoyAxis::NormalThrottle)
{
xml->writeCharacters("normal");
}
else if (throttle == JoyAxis::PositiveThrottle)
{
xml->writeCharacters("positive");
}
else if (throttle == JoyAxis::PositiveHalfThrottle)
{
xml->writeCharacters("positivehalf");
}
xml->writeEndElement();
//}
if (!currentlyDefault)
{
naxisbutton->writeConfig(xml);
paxisbutton->writeConfig(xml);
}
xml->writeEndElement();
}
bool JoyAxis::readMainConfig(QXmlStreamReader *xml)
{
bool found = false;
if (xml->name() == "deadZone" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
int tempchoice = temptext.toInt();
this->setDeadZone(tempchoice);
}
else if (xml->name() == "maxZone" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
int tempchoice = temptext.toInt();
this->setMaxZoneValue(tempchoice);
}
else if (xml->name() == "throttle" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
if (temptext == "negativehalf")
{
this->setThrottle(JoyAxis::NegativeHalfThrottle);
}
else if (temptext == "negative")
{
this->setThrottle(JoyAxis::NegativeThrottle);
}
else if (temptext == "normal")
{
this->setThrottle(JoyAxis::NormalThrottle);
}
else if (temptext == "positive")
{
this->setThrottle(JoyAxis::PositiveThrottle);
}
else if (temptext == "positivehalf")
{
this->setThrottle(JoyAxis::PositiveHalfThrottle);
}
InputDevice *device = parentSet->getInputDevice();
if (!device->hasCalibrationThrottle(index))
{
device->setCalibrationStatus(index,
static_cast<JoyAxis::ThrottleTypes>(throttle));
}
setCurrentRawValue(currentThrottledDeadValue);
//currentRawValue = currentThrottledDeadValue;
currentThrottledValue = calculateThrottledValue(currentRawValue);
}
return found;
}
bool JoyAxis::readButtonConfig(QXmlStreamReader *xml)
{
bool found = false;
int index = xml->attributes().value("index").toString().toInt();
if (index == 1)
{
found = true;
naxisbutton->readConfig(xml);
}
else if (index == 2)
{
found = true;
paxisbutton->readConfig(xml);
}
return found;
}
void JoyAxis::reset()
{
deadZone = getDefaultDeadZone();
isActive = false;
eventActive = false;
maxZoneValue = getDefaultMaxZone();
throttle = getDefaultThrottle();
paxisbutton->reset();
naxisbutton->reset();
activeButton = 0;
lastKnownThottledValue = 0;
lastKnownRawValue = 0;
adjustRange();
setCurrentRawValue(currentThrottledDeadValue);
currentThrottledValue = calculateThrottledValue(currentRawValue);
axisName.clear();
pendingEvent = false;
pendingValue = currentRawValue;
pendingIgnoreSets = false;
//pendingUpdateLastValues = true;
}
void JoyAxis::reset(int index)
{
reset();
this->index = index;
}
JoyAxisButton* JoyAxis::getPAxisButton()
{
return paxisbutton;
}
JoyAxisButton* JoyAxis::getNAxisButton()
{
return naxisbutton;
}
int JoyAxis::getCurrentRawValue()
{
return currentRawValue;
}
void JoyAxis::adjustRange()
{
if (throttle == JoyAxis::NegativeThrottle)
{
currentThrottledDeadValue = AXISMAX;
}
else if (throttle == JoyAxis::NormalThrottle ||
throttle == JoyAxis::PositiveHalfThrottle ||
throttle == JoyAxis::NegativeHalfThrottle)
{
currentThrottledDeadValue = 0;
}
else if (throttle == JoyAxis::PositiveThrottle)
{
currentThrottledDeadValue = AXISMIN;
}
currentThrottledValue = calculateThrottledValue(currentRawValue);
}
int JoyAxis::getCurrentThrottledDeadValue()
{
return currentThrottledDeadValue;
}
double JoyAxis::getDistanceFromDeadZone()
{
return getDistanceFromDeadZone(currentThrottledValue);
}
double JoyAxis::getDistanceFromDeadZone(int value)
{
double distance = 0.0;
int currentValue = value;
if (currentValue >= deadZone)
{
distance = (currentValue - deadZone)/static_cast<double>(maxZoneValue - deadZone);
}
else if (currentValue <= -deadZone)
{
distance = (currentValue + deadZone)/static_cast<double>(-maxZoneValue + deadZone);
}
distance = qBound(0.0, distance, 1.0);
return distance;
}
/**
* @brief Get the current value for an axis in either direction converted to
* the range of -1.0 to 1.0.
* @param Current interger value of the axis
* @return Axis value in the range of -1.0 to 1.0
*/
double JoyAxis::getRawDistance(int value)
{
double distance = 0.0;
int currentValue = value;
distance = currentValue / static_cast<double>(maxZoneValue);
distance = qBound(-1.0, distance, 1.0);
return distance;
}
void JoyAxis::propogateThrottleChange()
{
emit throttleChangePropogated(this->index);
}
int JoyAxis::getCurrentlyAssignedSet()
{
return originset;
}
void JoyAxis::setControlStick(JoyControlStick *stick)
{
removeVDPads();
removeControlStick();
this->stick = stick;
emit propertyUpdated();
}
bool JoyAxis::isPartControlStick()
{
return (this->stick != 0);
}
JoyControlStick* JoyAxis::getControlStick()
{
return this->stick;
}
void JoyAxis::removeControlStick(bool performRelease)
{
if (stick)
{
if (performRelease)
{
stick->releaseButtonEvents();
}
this->stick = 0;
emit propertyUpdated();
}
}
bool JoyAxis::hasControlOfButtons()
{
bool value = true;
if (paxisbutton->isPartVDPad() || naxisbutton->isPartVDPad())
{
value = false;
}
return value;
}
void JoyAxis::removeVDPads()
{
if (paxisbutton->isPartVDPad())
{
paxisbutton->joyEvent(false, true);
paxisbutton->removeVDPad();
}
if (naxisbutton->isPartVDPad())
{
naxisbutton->joyEvent(false, true);
naxisbutton->removeVDPad();
}
}
bool JoyAxis::isDefault()
{
bool value = true;
value = value && (deadZone == getDefaultDeadZone());
value = value && (maxZoneValue == getDefaultMaxZone());
//value = value && (throttle == getDefaultThrottle());
value = value && (paxisbutton->isDefault());
value = value && (naxisbutton->isDefault());
return value;
}
/* Use this method to keep currentRawValue in the expected range.
* SDL has a minimum axis value of -32768 which should be ignored to
* ensure that JoyControlStick will not encounter overflow problems
* on a 32 bit machine.
*/
void JoyAxis::setCurrentRawValue(int value)
{
if (value >= JoyAxis::AXISMIN && value <= JoyAxis::AXISMAX)
{
currentRawValue = value;
}
else if (value > JoyAxis::AXISMAX)
{
currentRawValue = JoyAxis::AXISMAX;
}
else if (value < JoyAxis::AXISMIN)
{
currentRawValue = JoyAxis::AXISMIN;
}
}
void JoyAxis::setButtonsMouseMode(JoyButton::JoyMouseMovementMode mode)
{
paxisbutton->setMouseMode(mode);
naxisbutton->setMouseMode(mode);
}
bool JoyAxis::hasSameButtonsMouseMode()
{
bool result = true;
if (paxisbutton->getMouseMode() != naxisbutton->getMouseMode())
{
result = false;
}
return result;
}
JoyButton::JoyMouseMovementMode JoyAxis::getButtonsPresetMouseMode()
{
JoyButton::JoyMouseMovementMode resultMode = JoyButton::MouseCursor;
if (paxisbutton->getMouseMode() == naxisbutton->getMouseMode())
{
resultMode = paxisbutton->getMouseMode();
}
return resultMode;
}
void JoyAxis::setButtonsMouseCurve(JoyButton::JoyMouseCurve mouseCurve)
{
paxisbutton->setMouseCurve(mouseCurve);
naxisbutton->setMouseCurve(mouseCurve);
}
bool JoyAxis::hasSameButtonsMouseCurve()
{
bool result = true;
if (paxisbutton->getMouseCurve() != naxisbutton->getMouseCurve())
{
result = false;
}
return result;
}
JoyButton::JoyMouseCurve JoyAxis::getButtonsPresetMouseCurve()
{
JoyButton::JoyMouseCurve resultCurve = JoyButton::LinearCurve;
if (paxisbutton->getMouseCurve() == naxisbutton->getMouseCurve())
{
resultCurve = paxisbutton->getMouseCurve();
}
return resultCurve;
}
void JoyAxis::setButtonsSpringWidth(int value)
{
paxisbutton->setSpringWidth(value);
naxisbutton->setSpringWidth(value);
}
void JoyAxis::setButtonsSpringHeight(int value)
{
paxisbutton->setSpringHeight(value);
naxisbutton->setSpringHeight(value);
}
int JoyAxis::getButtonsPresetSpringWidth()
{
int presetSpringWidth = 0;
if (paxisbutton->getSpringWidth() == naxisbutton->getSpringWidth())
{
presetSpringWidth = paxisbutton->getSpringWidth();
}
return presetSpringWidth;
}
int JoyAxis::getButtonsPresetSpringHeight()
{
int presetSpringHeight = 0;
if (paxisbutton->getSpringHeight() == naxisbutton->getSpringHeight())
{
presetSpringHeight = paxisbutton->getSpringHeight();
}
return presetSpringHeight;
}
void JoyAxis::setButtonsSensitivity(double value)
{
paxisbutton->setSensitivity(value);
naxisbutton->setSensitivity(value);
}
double JoyAxis::getButtonsPresetSensitivity()
{
double presetSensitivity = 1.0;
if (paxisbutton->getSensitivity() == naxisbutton->getSensitivity())
{
presetSensitivity = paxisbutton->getSensitivity();
}
return presetSensitivity;
}
JoyAxisButton* JoyAxis::getAxisButtonByValue(int value)
{
JoyAxisButton *eventbutton = 0;
int throttledValue = calculateThrottledValue(value);
if (throttledValue > deadZone)
{
eventbutton = paxisbutton;
}
else if (throttledValue < -deadZone)
{
eventbutton = naxisbutton;
}
return eventbutton;
}
void JoyAxis::setAxisName(QString tempName)
{
if (tempName.length() <= 20 && tempName != axisName)
{
axisName = tempName;
emit axisNameChanged();
emit propertyUpdated();
}
}
QString JoyAxis::getAxisName()
{
return axisName;
}
void JoyAxis::setButtonsWheelSpeedX(int value)
{
paxisbutton->setWheelSpeedX(value);
naxisbutton->setWheelSpeedX(value);
}
void JoyAxis::setButtonsWheelSpeedY(int value)
{
paxisbutton->setWheelSpeedY(value);
naxisbutton->setWheelSpeedY(value);
}
void JoyAxis::setDefaultAxisName(QString tempname)
{
defaultAxisName = tempname;
}
QString JoyAxis::getDefaultAxisName()
{
return defaultAxisName;
}
QString JoyAxis::getPartialName(bool forceFullFormat, bool displayNames)
{
QString label;
if (!axisName.isEmpty() && displayNames)
{
if (forceFullFormat)
{
label.append(tr("Axis")).append(" ");
}
label.append(axisName);
}
else if (!defaultAxisName.isEmpty())
{
if (forceFullFormat)
{
label.append(tr("Axis")).append(" ");
}
label.append(defaultAxisName);
}
else
{
label.append(tr("Axis")).append(" ");
label.append(QString::number(getRealJoyIndex()));
}
return label;
}
QString JoyAxis::getXmlName()
{
return this->xmlName;
}
int JoyAxis::getDefaultDeadZone()
{
return this->AXISDEADZONE;
}
int JoyAxis::getDefaultMaxZone()
{
return this->AXISMAXZONE;
}
JoyAxis::ThrottleTypes JoyAxis::getDefaultThrottle()
{
return this->DEFAULTTHROTTLE;
}
SetJoystick* JoyAxis::getParentSet()
{
return parentSet;
}
void JoyAxis::establishPropertyUpdatedConnection()
{
connect(this, SIGNAL(propertyUpdated()), getParentSet()->getInputDevice(), SLOT(profileEdited()));
}
void JoyAxis::disconnectPropertyUpdatedConnection()
{
disconnect(this, SIGNAL(propertyUpdated()), getParentSet()->getInputDevice(), SLOT(profileEdited()));
}
void JoyAxis::setButtonsSpringRelativeStatus(bool value)
{
paxisbutton->setSpringRelativeStatus(value);
naxisbutton->setSpringRelativeStatus(value);
}
bool JoyAxis::isRelativeSpring()
{
bool relative = false;
if (paxisbutton->isRelativeSpring() == naxisbutton->isRelativeSpring())
{
relative = paxisbutton->isRelativeSpring();
}
return relative;
}
void JoyAxis::performCalibration(int value)
{
InputDevice *device = parentSet->getInputDevice();
if (value <= -30000)
{
// Assume axis is a trigger. Set default throttle to Positive.
device->setCalibrationThrottle(index, PositiveThrottle);
}
else
{
// Ensure that default throttle is used when a device is reset.
device->setCalibrationThrottle(index,
static_cast<JoyAxis::ThrottleTypes>(throttle));
}
//else if (value >= -15000 && value <= 15000)
//{
// device->setCalibrationThrottle(index, NormalThrottle);
//}
}
void JoyAxis::copyAssignments(JoyAxis *destAxis)
{
destAxis->reset();
destAxis->deadZone = deadZone;
destAxis->maxZoneValue = maxZoneValue;
destAxis->axisName = axisName;
paxisbutton->copyAssignments(destAxis->paxisbutton);
naxisbutton->copyAssignments(destAxis->naxisbutton);
if (!destAxis->isDefault())
{
emit propertyUpdated();
}
}
void JoyAxis::setButtonsEasingDuration(double value)
{
paxisbutton->setEasingDuration(value);
naxisbutton->setEasingDuration(value);
}
double JoyAxis::getButtonsEasingDuration()
{
double result = JoyButton::DEFAULTEASINGDURATION;
if (paxisbutton->getEasingDuration() == naxisbutton->getEasingDuration())
{
result = paxisbutton->getEasingDuration();
}
return result;
}
int JoyAxis::getLastKnownThrottleValue()
{
return lastKnownThottledValue;
}
int JoyAxis::getLastKnownRawValue()
{
return lastKnownRawValue;
}
/**
* @brief Determine an appropriate release value for an axis depending
* on the current throttle setting being used.
* @return Release value for an axis
*/
int JoyAxis::getProperReleaseValue()
{
// Handles NormalThrottle case
int value = 0;
if (throttle == NegativeHalfThrottle)
{
value = 0;
}
else if (throttle == NegativeThrottle)
{
value = JoyAxis::AXISMAX;
}
else if (throttle == PositiveThrottle)
{
value = JoyAxis::AXISMIN;
}
else if (throttle == PositiveHalfThrottle)
{
value = 0;
}
return value;
}
void JoyAxis::setExtraAccelerationCurve(JoyButton::JoyExtraAccelerationCurve curve)
{
paxisbutton->setExtraAccelerationCurve(curve);
naxisbutton->setExtraAccelerationCurve(curve);
}
JoyButton::JoyExtraAccelerationCurve JoyAxis::getExtraAccelerationCurve()
{
JoyButton::JoyExtraAccelerationCurve result = JoyButton::LinearAccelCurve;
if (paxisbutton->getExtraAccelerationCurve() == naxisbutton->getExtraAccelerationCurve())
{
result = paxisbutton->getExtraAccelerationCurve();
}
return result;
}
void JoyAxis::copyRawValues(JoyAxis *srcAxis)
{
this->lastKnownRawValue = srcAxis->lastKnownRawValue;
this->currentRawValue = srcAxis->currentRawValue;
}
void JoyAxis::copyThrottledValues(JoyAxis *srcAxis)
{
this->lastKnownThottledValue = srcAxis->lastKnownThottledValue;
this->currentThrottledValue = srcAxis->currentThrottledValue;
}
void JoyAxis::eventReset()
{
naxisbutton->eventReset();
paxisbutton->eventReset();
}
``` | /content/code_sandbox/src/joyaxis.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 6,629 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include <QTableWidgetItem>
#include "setnamesdialog.h"
#include "ui_setnamesdialog.h"
SetNamesDialog::SetNamesDialog(InputDevice *device, QWidget *parent) :
QDialog(parent),
ui(new Ui::SetNamesDialog)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
this->device = device;
for (int i=0; i < InputDevice::NUMBER_JOYSETS; i++)
{
QString tempSetName = device->getSetJoystick(i)->getName();
ui->setNamesTableWidget->setItem(i, 0, new QTableWidgetItem(tempSetName));
}
connect(this, SIGNAL(accepted()), this, SLOT(saveSetNameChanges()));
}
SetNamesDialog::~SetNamesDialog()
{
delete ui;
}
void SetNamesDialog::saveSetNameChanges()
{
for (int i=0; i < ui->setNamesTableWidget->rowCount(); i++)
{
QTableWidgetItem *setNameItem = ui->setNamesTableWidget->item(i, 0);
QString setNameText = setNameItem->text();
QString oldSetNameText = device->getSetJoystick(i)->getName();
if (setNameText != oldSetNameText)
{
device->getSetJoystick(i)->setName(setNameText);
}
}
}
``` | /content/code_sandbox/src/setnamesdialog.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 368 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef XMLCONFIGWRITER_H
#define XMLCONFIGWRITER_H
#include <QObject>
#include <QFile>
#include <QXmlStreamWriter>
#include "inputdevice.h"
#include "common.h"
class XMLConfigWriter : public QObject
{
Q_OBJECT
public:
explicit XMLConfigWriter(QObject *parent = 0);
~XMLConfigWriter();
void setFileName(QString filename);
bool hasError();
QString getErrorString();
protected:
QXmlStreamWriter *xml;
QString fileName;
QFile *configFile;
InputDevice* joystick;
bool writerError;
QString writerErrorString;
signals:
public slots:
void write(InputDevice* joystick);
};
#endif // XMLCONFIGWRITER_H
``` | /content/code_sandbox/src/xmlconfigwriter.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 246 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef UINPUTHELPER_H
#define UINPUTHELPER_H
#include <QObject>
#include <QString>
#include <QHash>
class UInputHelper : public QObject
{
Q_OBJECT
public:
static UInputHelper* getInstance();
void deleteInstance();
QString getDisplayString(unsigned int virtualkey);
unsigned int getVirtualKey(QString codestring);
protected:
explicit UInputHelper(QObject *parent = 0);
~UInputHelper();
void populateKnownAliases();
static UInputHelper *_instance;
QHash<QString, unsigned int> knownAliasesX11SymVK;
QHash<unsigned int, QString> knownAliasesVKStrings;
signals:
public slots:
};
#endif // UINPUTHELPER_H
``` | /content/code_sandbox/src/uinputhelper.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 247 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef BUTTONEDITDIALOGTWO_H
#define BUTTONEDITDIALOGTWO_H
#include <QDialog>
#include "joybutton.h"
#include "keyboard/virtualkeyboardmousewidget.h"
#include "advancebuttondialog.h"
#include "uihelpers/buttoneditdialoghelper.h"
namespace Ui {
class ButtonEditDialog;
}
class ButtonEditDialog : public QDialog
{
Q_OBJECT
public:
explicit ButtonEditDialog(JoyButton *button, QWidget *parent = 0);
~ButtonEditDialog();
protected:
JoyButton *button;
bool ignoreRelease;
ButtonEditDialogHelper helper;
virtual void keyReleaseEvent(QKeyEvent *event);
virtual void keyPressEvent(QKeyEvent *event);
private:
Ui::ButtonEditDialog *ui;
signals:
void advancedDialogOpened();
void sendTempSlotToAdvanced(JoyButtonSlot *tempslot);
void keyGrabbed(JoyButtonSlot *tempslot);
void selectionCleared();
void selectionFinished();
private slots:
void refreshSlotSummaryLabel();
void changeToggleSetting();
void changeTurboSetting();
void openAdvancedDialog();
void closedAdvancedDialog();
void createTempSlot(int keycode, unsigned int alias);
void checkTurboSetting(bool state);
void setTurboButtonEnabled(bool state);
void processSlotAssignment(JoyButtonSlot *tempslot);
void clearButtonSlots();
void sendSelectionFinished();
void updateWindowTitleButtonName();
void checkForKeyboardWidgetFocus(QWidget *old, QWidget *now);
};
#endif // BUTTONEDITDIALOGTWO_H
``` | /content/code_sandbox/src/buttoneditdialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 424 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef JOYKEYREPEATHELPER_H
#define JOYKEYREPEATHELPER_H
#include <QObject>
#include <QTimer>
#include "joybuttonslot.h"
class JoyKeyRepeatHelper : public QObject
{
Q_OBJECT
public:
explicit JoyKeyRepeatHelper(QObject *parent = 0);
QTimer* getRepeatTimer();
void setLastActiveKey(JoyButtonSlot *slot);
JoyButtonSlot* getLastActiveKey();
//void setKeyRepeatDelay(unsigned int repeatDelay);
//unsigned int getKeyRepeatDelay();
void setKeyRepeatRate(unsigned int repeatRate);
unsigned int getKeyRepeatRate();
protected:
QTimer keyRepeatTimer;
JoyButtonSlot *lastActiveKey;
unsigned int keyRepeatDelay;
unsigned int keyRepeatRate;
signals:
private slots:
void repeatKeysEvent();
};
#endif // JOYKEYREPEATHELPER_H
``` | /content/code_sandbox/src/joykeyrepeathelper.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 282 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef APPLAUNCHHELPER_H
#define APPLAUNCHHELPER_H
#include <QObject>
#include <QMap>
#include <QThread>
#include "inputdevice.h"
#include "joybutton.h"
#include "antimicrosettings.h"
class AppLaunchHelper : public QObject
{
Q_OBJECT
public:
explicit AppLaunchHelper(AntiMicroSettings *settings, bool graphical=false,
QObject *parent=0);
void printControllerList(QMap<SDL_JoystickID, InputDevice *> *joysticks);
protected:
void enablePossibleMouseSmoothing();
void establishMouseTimerConnections();
void changeMouseRefreshRate();
void changeSpringModeScreen();
void changeGamepadPollRate();
#ifdef Q_OS_WIN
void checkPointerPrecision();
#endif
AntiMicroSettings *settings;
bool graphical;
signals:
public slots:
#ifdef Q_OS_WIN
void appQuitPointerPrecision();
#endif
void initRunMethods();
void revertMouseThread();
void changeMouseThread(QThread *thread);
};
#endif // APPLAUNCHHELPER_H
``` | /content/code_sandbox/src/applaunchhelper.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 323 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef DPADPUSHBUTTON_H
#define DPADPUSHBUTTON_H
#include <QPoint>
#include "flashbuttonwidget.h"
#include "joydpad.h"
class DPadPushButton : public FlashButtonWidget
{
Q_OBJECT
public:
explicit DPadPushButton(JoyDPad *dpad, bool displayNames, QWidget *parent = 0);
JoyDPad* getDPad();
void tryFlash();
protected:
QString generateLabel();
JoyDPad *dpad;
signals:
public slots:
void disableFlashes();
void enableFlashes();
private slots:
void showContextMenu(const QPoint &point);
};
#endif // DPADPUSHBUTTON_H
``` | /content/code_sandbox/src/dpadpushbutton.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 240 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef QTVMULTIKEYMAPPER_H
#define QTVMULTIKEYMAPPER_H
#include <QObject>
#include <QHash>
#include "qtkeymapperbase.h"
#include "qtwinkeymapper.h"
class QtVMultiKeyMapper : public QtKeyMapperBase
{
Q_OBJECT
public:
explicit QtVMultiKeyMapper(QObject *parent = 0);
static const unsigned int consumerUsagePagePrefix = 0x12000;
protected:
void populateMappingHashes();
void populateCharKeyInformation();
//static QtWinKeyMapper nativeKeyMapper;
signals:
public slots:
};
#endif // QTVMULTIKEYMAPPER_H
``` | /content/code_sandbox/src/qtvmultikeymapper.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 235 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef DPADCONTEXTMENU_H
#define DPADCONTEXTMENU_H
#include <QMenu>
#include "joydpad.h"
#include "uihelpers/dpadcontextmenuhelper.h"
class DPadContextMenu : public QMenu
{
Q_OBJECT
public:
explicit DPadContextMenu(JoyDPad *dpad, QWidget *parent = 0);
void buildMenu();
protected:
int getPresetIndex();
JoyDPad *dpad;
DPadContextMenuHelper helper;
signals:
public slots:
private slots:
void setDPadPreset();
void setDPadMode();
void openMouseSettingsDialog();
};
#endif // DPADCONTEXTMENU_H
``` | /content/code_sandbox/src/dpadcontextmenu.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 236 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
//#include <QDebug>
#include <QHashIterator>
#include <QList>
#include "dpadeditdialog.h"
#include "ui_dpadeditdialog.h"
#include "mousedialog/mousedpadsettingsdialog.h"
#include "event.h"
#include "antkeymapper.h"
#include "setjoystick.h"
#include "inputdevice.h"
#include "common.h"
DPadEditDialog::DPadEditDialog(JoyDPad *dpad, QWidget *parent) :
QDialog(parent, Qt::Window),
ui(new Ui::DPadEditDialog),
helper(dpad)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
this->dpad = dpad;
helper.moveToThread(dpad->thread());
PadderCommon::inputDaemonMutex.lock();
updateWindowTitleDPadName();
if (dpad->getJoyMode() == JoyDPad::StandardMode)
{
ui->joyModeComboBox->setCurrentIndex(0);
}
else if (dpad->getJoyMode() == JoyDPad::EightWayMode)
{
ui->joyModeComboBox->setCurrentIndex(1);
}
else if (dpad->getJoyMode() == JoyDPad::FourWayCardinal)
{
ui->joyModeComboBox->setCurrentIndex(2);
}
else if (dpad->getJoyMode() == JoyDPad::FourWayDiagonal)
{
ui->joyModeComboBox->setCurrentIndex(3);
}
selectCurrentPreset();
ui->dpadNameLineEdit->setText(dpad->getDpadName());
unsigned int dpadDelay = dpad->getDPadDelay();
ui->dpadDelaySlider->setValue(dpadDelay * .1);
ui->dpadDelayDoubleSpinBox->setValue(dpadDelay * .001);
PadderCommon::inputDaemonMutex.unlock();
connect(ui->presetsComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(implementPresets(int)));
connect(ui->joyModeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(implementModes(int)));
connect(ui->mouseSettingsPushButton, SIGNAL(clicked()), this, SLOT(openMouseSettingsDialog()));
connect(ui->dpadNameLineEdit, SIGNAL(textEdited(QString)), dpad, SLOT(setDPadName(QString)));
connect(ui->dpadDelaySlider, SIGNAL(valueChanged(int)), &helper, SLOT(updateJoyDPadDelay(int)));
connect(dpad, SIGNAL(dpadDelayChanged(int)), this, SLOT(updateDPadDelaySpinBox(int)));
connect(ui->dpadDelayDoubleSpinBox, SIGNAL(valueChanged(double)), this, SLOT(updateDPadDelaySlider(double)));
connect(dpad, SIGNAL(dpadNameChanged()), this, SLOT(updateWindowTitleDPadName()));
}
DPadEditDialog::~DPadEditDialog()
{
delete ui;
}
void DPadEditDialog::implementPresets(int index)
{
JoyButtonSlot *upButtonSlot = 0;
JoyButtonSlot *downButtonSlot = 0;
JoyButtonSlot *leftButtonSlot = 0;
JoyButtonSlot *rightButtonSlot = 0;
JoyButtonSlot *upLeftButtonSlot = 0;
JoyButtonSlot *upRightButtonSlot = 0;
JoyButtonSlot *downLeftButtonSlot = 0;
JoyButtonSlot *downRightButtonSlot = 0;
if (index == 1)
{
PadderCommon::inputDaemonMutex.lock();
upButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseUp, JoyButtonSlot::JoyMouseMovement, this);
downButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseDown, JoyButtonSlot::JoyMouseMovement, this);
leftButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseLeft, JoyButtonSlot::JoyMouseMovement, this);
rightButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseRight, JoyButtonSlot::JoyMouseMovement, this);
PadderCommon::inputDaemonMutex.unlock();
ui->joyModeComboBox->setCurrentIndex(0);
}
else if (index == 2)
{
PadderCommon::inputDaemonMutex.lock();
upButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseUp, JoyButtonSlot::JoyMouseMovement, this);
downButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseDown, JoyButtonSlot::JoyMouseMovement, this);
leftButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseRight, JoyButtonSlot::JoyMouseMovement, this);
rightButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseLeft, JoyButtonSlot::JoyMouseMovement, this);
PadderCommon::inputDaemonMutex.unlock();
ui->joyModeComboBox->setCurrentIndex(0);
}
else if (index == 3)
{
PadderCommon::inputDaemonMutex.lock();
upButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseDown, JoyButtonSlot::JoyMouseMovement, this);
downButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseUp, JoyButtonSlot::JoyMouseMovement, this);
leftButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseLeft, JoyButtonSlot::JoyMouseMovement, this);
rightButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseRight, JoyButtonSlot::JoyMouseMovement, this);
PadderCommon::inputDaemonMutex.unlock();
ui->joyModeComboBox->setCurrentIndex(0);
}
else if (index == 4)
{
PadderCommon::inputDaemonMutex.lock();
upButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseDown, JoyButtonSlot::JoyMouseMovement, this);
downButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseUp, JoyButtonSlot::JoyMouseMovement, this);
leftButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseRight, JoyButtonSlot::JoyMouseMovement, this);
rightButtonSlot = new JoyButtonSlot(JoyButtonSlot::MouseLeft, JoyButtonSlot::JoyMouseMovement, this);
PadderCommon::inputDaemonMutex.unlock();
ui->joyModeComboBox->setCurrentIndex(0);
}
else if (index == 5)
{
PadderCommon::inputDaemonMutex.lock();
upButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Up), Qt::Key_Up, JoyButtonSlot::JoyKeyboard, this);
downButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Down), Qt::Key_Down, JoyButtonSlot::JoyKeyboard, this);
leftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Left), Qt::Key_Left, JoyButtonSlot::JoyKeyboard, this);
rightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Right), Qt::Key_Right, JoyButtonSlot::JoyKeyboard, this);
PadderCommon::inputDaemonMutex.unlock();
ui->joyModeComboBox->setCurrentIndex(0);
}
else if (index == 6)
{
PadderCommon::inputDaemonMutex.lock();
upButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_W), Qt::Key_W, JoyButtonSlot::JoyKeyboard, this);
downButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_S), Qt::Key_S, JoyButtonSlot::JoyKeyboard, this);
leftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_A), Qt::Key_A, JoyButtonSlot::JoyKeyboard, this);
rightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_D), Qt::Key_D, JoyButtonSlot::JoyKeyboard, this);
PadderCommon::inputDaemonMutex.unlock();
ui->joyModeComboBox->setCurrentIndex(0);
}
else if (index == 7)
{
PadderCommon::inputDaemonMutex.lock();
if (ui->joyModeComboBox->currentIndex() == 0 ||
ui->joyModeComboBox->currentIndex() == 2)
{
upButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_8), QtKeyMapperBase::AntKey_KP_8, JoyButtonSlot::JoyKeyboard, this);
downButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_2), QtKeyMapperBase::AntKey_KP_2, JoyButtonSlot::JoyKeyboard, this);
leftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_4), QtKeyMapperBase::AntKey_KP_4, JoyButtonSlot::JoyKeyboard, this);
rightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_6), QtKeyMapperBase::AntKey_KP_6, JoyButtonSlot::JoyKeyboard, this);
}
else if (ui->joyModeComboBox->currentIndex() == 1)
{
upButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_8), QtKeyMapperBase::AntKey_KP_8, JoyButtonSlot::JoyKeyboard, this);
downButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_2), QtKeyMapperBase::AntKey_KP_2, JoyButtonSlot::JoyKeyboard, this);
leftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_4), QtKeyMapperBase::AntKey_KP_4, JoyButtonSlot::JoyKeyboard, this);
rightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_6), QtKeyMapperBase::AntKey_KP_6, JoyButtonSlot::JoyKeyboard, this);
upLeftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_7), QtKeyMapperBase::AntKey_KP_7, JoyButtonSlot::JoyKeyboard, this);
upRightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_9), QtKeyMapperBase::AntKey_KP_9, JoyButtonSlot::JoyKeyboard, this);
downLeftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_1), QtKeyMapperBase::AntKey_KP_1, JoyButtonSlot::JoyKeyboard, this);
downRightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_3), QtKeyMapperBase::AntKey_KP_3, JoyButtonSlot::JoyKeyboard, this);
}
else if (ui->joyModeComboBox->currentIndex() == 3)
{
upLeftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_7), QtKeyMapperBase::AntKey_KP_7, JoyButtonSlot::JoyKeyboard, this);
upRightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_9), QtKeyMapperBase::AntKey_KP_9, JoyButtonSlot::JoyKeyboard, this);
downLeftButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_1), QtKeyMapperBase::AntKey_KP_1, JoyButtonSlot::JoyKeyboard, this);
downRightButtonSlot = new JoyButtonSlot(AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_3), QtKeyMapperBase::AntKey_KP_3, JoyButtonSlot::JoyKeyboard, this);
}
PadderCommon::inputDaemonMutex.unlock();
}
else if (index == 8)
{
QMetaObject::invokeMethod(&helper, "clearButtonsSlotsEventReset", Qt::BlockingQueuedConnection);
}
QHash<JoyDPadButton::JoyDPadDirections, JoyButtonSlot*> tempHash;
tempHash.insert(JoyDPadButton::DpadUp, upButtonSlot);
tempHash.insert(JoyDPadButton::DpadDown, downButtonSlot);
tempHash.insert(JoyDPadButton::DpadLeft, leftButtonSlot);
tempHash.insert(JoyDPadButton::DpadRight, rightButtonSlot);
tempHash.insert(JoyDPadButton::DpadLeftUp, upLeftButtonSlot);
tempHash.insert(JoyDPadButton::DpadRightUp, upRightButtonSlot);
tempHash.insert(JoyDPadButton::DpadLeftDown, downLeftButtonSlot);
tempHash.insert(JoyDPadButton::DpadRightDown, downRightButtonSlot);
helper.setPendingSlots(&tempHash);
QMetaObject::invokeMethod(&helper, "setFromPendingSlots", Qt::BlockingQueuedConnection);
}
void DPadEditDialog::implementModes(int index)
{
PadderCommon::inputDaemonMutex.lock();
dpad->releaseButtonEvents();
if (index == 0)
{
dpad->setJoyMode(JoyDPad::StandardMode);
}
else if (index == 1)
{
dpad->setJoyMode(JoyDPad::EightWayMode);
}
else if (index == 2)
{
dpad->setJoyMode(JoyDPad::FourWayCardinal);
}
else if (index == 3)
{
dpad->setJoyMode(JoyDPad::FourWayDiagonal);
}
PadderCommon::inputDaemonMutex.unlock();
}
void DPadEditDialog::selectCurrentPreset()
{
JoyDPadButton *upButton = dpad->getJoyButton(JoyDPadButton::DpadUp);
QList<JoyButtonSlot*> *upslots = upButton->getAssignedSlots();
JoyDPadButton *downButton = dpad->getJoyButton(JoyDPadButton::DpadDown);
QList<JoyButtonSlot*> *downslots = downButton->getAssignedSlots();
JoyDPadButton *leftButton = dpad->getJoyButton(JoyDPadButton::DpadLeft);
QList<JoyButtonSlot*> *leftslots = leftButton->getAssignedSlots();
JoyDPadButton *rightButton = dpad->getJoyButton(JoyDPadButton::DpadRight);
QList<JoyButtonSlot*> *rightslots = rightButton->getAssignedSlots();
if (upslots->length() == 1 && downslots->length() == 1 && leftslots->length() == 1 && rightslots->length() == 1)
{
JoyButtonSlot *upslot = upslots->at(0);
JoyButtonSlot *downslot = downslots->at(0);
JoyButtonSlot *leftslot = leftslots->at(0);
JoyButtonSlot *rightslot = rightslots->at(0);
if (upslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && upslot->getSlotCode() == JoyButtonSlot::MouseUp &&
downslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && downslot->getSlotCode() == JoyButtonSlot::MouseDown &&
leftslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && leftslot->getSlotCode() == JoyButtonSlot::MouseLeft &&
rightslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && rightslot->getSlotCode() == JoyButtonSlot::MouseRight)
{
ui->presetsComboBox->setCurrentIndex(1);
}
else if (upslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && upslot->getSlotCode() == JoyButtonSlot::MouseUp &&
downslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && downslot->getSlotCode() == JoyButtonSlot::MouseDown &&
leftslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && leftslot->getSlotCode() == JoyButtonSlot::MouseRight &&
rightslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && rightslot->getSlotCode() == JoyButtonSlot::MouseLeft)
{
ui->presetsComboBox->setCurrentIndex(2);
}
else if (upslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && upslot->getSlotCode() == JoyButtonSlot::MouseDown &&
downslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && downslot->getSlotCode() == JoyButtonSlot::MouseUp &&
leftslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && leftslot->getSlotCode() == JoyButtonSlot::MouseLeft &&
rightslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && rightslot->getSlotCode() == JoyButtonSlot::MouseRight)
{
ui->presetsComboBox->setCurrentIndex(3);
}
else if (upslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && upslot->getSlotCode() == JoyButtonSlot::MouseDown &&
downslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && downslot->getSlotCode() == JoyButtonSlot::MouseUp &&
leftslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && leftslot->getSlotCode() == JoyButtonSlot::MouseRight &&
rightslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && rightslot->getSlotCode() == JoyButtonSlot::MouseLeft)
{
ui->presetsComboBox->setCurrentIndex(4);
}
else if (upslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(upslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Up) &&
downslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(downslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Down) &&
leftslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(leftslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Left) &&
rightslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(rightslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Right))
{
ui->presetsComboBox->setCurrentIndex(5);
}
else if (upslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(upslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_W) &&
downslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(downslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_S) &&
leftslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(leftslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_A) &&
rightslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(rightslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_D))
{
ui->presetsComboBox->setCurrentIndex(6);
}
else if (upslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(upslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_8) &&
downslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(downslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_2) &&
leftslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(leftslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_4) &&
rightslot->getSlotMode() == JoyButtonSlot::JoyKeyboard && static_cast<unsigned int>(rightslot->getSlotCode()) == AntKeyMapper::getInstance()->returnVirtualKey(QtKeyMapperBase::AntKey_KP_6))
{
ui->presetsComboBox->setCurrentIndex(7);
}
}
else if (upslots->length() == 0 && downslots->length() == 0 &&
leftslots->length() == 0 && rightslots->length() == 0)
{
ui->presetsComboBox->setCurrentIndex(8);
}
}
void DPadEditDialog::openMouseSettingsDialog()
{
ui->mouseSettingsPushButton->setEnabled(false);
MouseDPadSettingsDialog *dialog = new MouseDPadSettingsDialog(this->dpad, this);
dialog->show();
connect(this, SIGNAL(finished(int)), dialog, SLOT(close()));
connect(dialog, SIGNAL(finished(int)), this, SLOT(enableMouseSettingButton()));
}
void DPadEditDialog::enableMouseSettingButton()
{
ui->mouseSettingsPushButton->setEnabled(true);
}
/**
* @brief Update QDoubleSpinBox value based on updated dpad delay value.
* @param Delay value obtained from JoyDPad.
*/
void DPadEditDialog::updateDPadDelaySpinBox(int value)
{
double temp = static_cast<double>(value * 0.001);
ui->dpadDelayDoubleSpinBox->setValue(temp);
}
/**
* @brief Update QSlider value based on value from QDoubleSpinBox.
* @param Value from QDoubleSpinBox.
*/
void DPadEditDialog::updateDPadDelaySlider(double value)
{
int temp = static_cast<int>(value * 100);
if (ui->dpadDelaySlider->value() != temp)
{
ui->dpadDelaySlider->setValue(temp);
}
}
void DPadEditDialog::updateWindowTitleDPadName()
{
QString temp = QString(tr("Set")).append(" ");
if (!dpad->getDpadName().isEmpty())
{
temp.append(dpad->getName(false, true));
}
else
{
temp.append(dpad->getName());
}
if (dpad->getParentSet()->getIndex() != 0)
{
unsigned int setIndex = dpad->getParentSet()->getRealIndex();
temp.append(" [").append(tr("Set %1").arg(setIndex));
QString setName = dpad->getParentSet()->getName();
if (!setName.isEmpty())
{
temp.append(": ").append(setName);
}
temp.append("]");
}
setWindowTitle(temp);
}
``` | /content/code_sandbox/src/dpadeditdialog.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 5,076 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef SDLEVENTREADER_H
#define SDLEVENTREADER_H
#include <QObject>
#include <QMap>
#include <QTimer>
#ifdef USE_SDL_2
#include <SDL2/SDL.h>
#else
#include <SDL/SDL.h>
#endif
#include "joystick.h"
#include "inputdevice.h"
#include "antimicrosettings.h"
class SDLEventReader : public QObject
{
Q_OBJECT
public:
explicit SDLEventReader(QMap<SDL_JoystickID, InputDevice*> *joysticks,
AntiMicroSettings *settings,
QObject *parent = 0);
~SDLEventReader();
bool isSDLOpen();
protected:
void initSDL();
void closeSDL();
void clearEvents();
int CheckForEvents();
QMap<SDL_JoystickID, InputDevice*> *joysticks;
bool sdlIsOpen;
AntiMicroSettings *settings;
unsigned int pollRate;
QTimer pollRateTimer;
signals:
void eventRaised();
void finished();
void sdlStarted();
void sdlClosed();
public slots:
void performWork();
void stop();
void refresh();
void updatePollRate(unsigned int tempPollRate);
void resetJoystickMap();
void quit();
void closeDevices();
void haltServices();
private slots:
void secondaryRefresh();
};
#endif // SDLEVENTREADER_H
``` | /content/code_sandbox/src/sdleventreader.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 390 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef JOYBUTTON_H
#define JOYBUTTON_H
#include <QObject>
#include <QTimer>
#include <QElapsedTimer>
#include <QTime>
#include <QList>
#include <QListIterator>
#include <QHash>
#include <QQueue>
#include <QReadWriteLock>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include "joybuttonslot.h"
#include "springmousemoveinfo.h"
#include "joybuttonmousehelper.h"
#ifdef Q_OS_WIN
#include "joykeyrepeathelper.h"
#endif
class VDPad;
class SetJoystick;
class JoyButton : public QObject
{
Q_OBJECT
public:
explicit JoyButton(int index, int originset, SetJoystick *parentSet, QObject *parent=0);
~JoyButton();
enum SetChangeCondition {SetChangeDisabled=0, SetChangeOneWay,
SetChangeTwoWay, SetChangeWhileHeld};
enum JoyMouseMovementMode {MouseCursor=0, MouseSpring};
enum JoyMouseCurve {EnhancedPrecisionCurve=0, LinearCurve, QuadraticCurve,
CubicCurve, QuadraticExtremeCurve, PowerCurve,
EasingQuadraticCurve, EasingCubicCurve};
enum JoyExtraAccelerationCurve {LinearAccelCurve, EaseOutSineCurve,
EaseOutQuadAccelCurve, EaseOutCubicAccelCurve};
enum TurboMode {NormalTurbo=0, GradientTurbo, PulseTurbo};
void joyEvent(bool pressed, bool ignoresets=false);
void queuePendingEvent(bool pressed, bool ignoresets=false);
void activatePendingEvent();
bool hasPendingEvent();
void clearPendingEvent();
int getJoyNumber();
virtual int getRealJoyNumber();
void setJoyNumber(int index);
bool getToggleState();
int getTurboInterval();
bool isUsingTurbo();
void setCustomName(QString name);
QString getCustomName();
QList<JoyButtonSlot*> *getAssignedSlots();
virtual void readConfig(QXmlStreamReader *xml);
virtual void writeConfig(QXmlStreamWriter *xml);
virtual QString getPartialName(bool forceFullFormat=false, bool displayNames=false);
virtual QString getSlotsSummary();
virtual QString getSlotsString();
virtual QList<JoyButtonSlot*> getActiveZoneList();
virtual QString getActiveZoneSummary();
virtual QString getCalculatedActiveZoneSummary();
virtual QString getName(bool forceFullFormat=false, bool displayNames=false);
virtual QString getXmlName();
int getMouseSpeedX();
int getMouseSpeedY();
int getWheelSpeedX();
int getWheelSpeedY();
void setChangeSetSelection(int index, bool updateActiveString=true);
int getSetSelection();
virtual void setChangeSetCondition(SetChangeCondition condition,
bool passive=false, bool updateActiveString=true);
SetChangeCondition getChangeSetCondition();
bool getButtonState();
int getOriginSet();
bool containsSequence();
bool containsDistanceSlots();
bool containsReleaseSlots();
virtual double getDistanceFromDeadZone();
virtual double getMouseDistanceFromDeadZone();
virtual double getLastMouseDistanceFromDeadZone();
// Don't use direct assignment but copying from a current button.
virtual void copyLastMouseDistanceFromDeadZone(JoyButton *srcButton);
virtual void copyLastAccelerationDistance(JoyButton *srcButton);
void copyExtraAccelerationState(JoyButton *srcButton);
void setUpdateInitAccel(bool state);
virtual void setVDPad(VDPad *vdpad);
void removeVDPad();
bool isPartVDPad();
VDPad* getVDPad();
virtual bool isDefault();
void setIgnoreEventState(bool ignore);
bool getIgnoreEventState();
void setMouseMode(JoyMouseMovementMode mousemode);
JoyMouseMovementMode getMouseMode();
void setMouseCurve(JoyMouseCurve selectedCurve);
JoyMouseCurve getMouseCurve();
int getSpringWidth();
int getSpringHeight();
double getSensitivity();
bool getWhileHeldStatus();
void setWhileHeldStatus(bool status);
QString getActionName();
QString getButtonName();
virtual void setDefaultButtonName(QString tempname);
virtual QString getDefaultButtonName();
SetJoystick* getParentSet();
void setCycleResetTime(unsigned int interval);
unsigned int getCycleResetTime();
void setCycleResetStatus(bool enabled);
bool isCycleResetActive();
bool isRelativeSpring();
void copyAssignments(JoyButton *destButton);
virtual void setTurboMode(TurboMode mode);
TurboMode getTurboMode();
virtual bool isPartRealAxis();
virtual bool isModifierButton();
bool hasActiveSlots();
static int calculateFinalMouseSpeed(JoyMouseCurve curve, int value);
double getEasingDuration();
static void moveMouseCursor(int &movedX, int &movedY, int &movedElapsed);
static void moveSpringMouse(int &movedX, int &movedY, bool &hasMoved);
static JoyButtonMouseHelper* getMouseHelper();
static QList<JoyButton*>* getPendingMouseButtons();
static bool hasCursorEvents();
static bool hasSpringEvents();
static double getWeightModifier();
static void setWeightModifier(double modifier);
static int getMouseHistorySize();
static void setMouseHistorySize(int size);
static int getMouseRefreshRate();
static void setMouseRefreshRate(int refresh);
static int getSpringModeScreen();
static void setSpringModeScreen(int screen);
static void resetActiveButtonMouseDistances();
void resetAccelerationDistances();
void setExtraAccelerationStatus(bool status);
void setExtraAccelerationMultiplier(double value);
bool isExtraAccelerationEnabled();
double getExtraAccelerationMultiplier();
virtual void initializeDistanceValues();
void setMinAccelThreshold(double value);
double getMinAccelThreshold();
void setMaxAccelThreshold(double value);
double getMaxAccelThreshold();
void setStartAccelMultiplier(double value);
double getStartAccelMultiplier();
void setAccelExtraDuration(double value);
double getAccelExtraDuration();
void setExtraAccelerationCurve(JoyExtraAccelerationCurve curve);
JoyExtraAccelerationCurve getExtraAccelerationCurve();
virtual double getAccelerationDistance();
virtual double getLastAccelerationDistance();
void setSpringDeadCircleMultiplier(int value);
int getSpringDeadCircleMultiplier();
static int getGamepadRefreshRate();
static void setGamepadRefreshRate(int refresh);
static void restartLastMouseTime();
static void setStaticMouseThread(QThread *thread);
static void indirectStaticMouseThread(QThread *thread);
static bool shouldInvokeMouseEvents();
static void invokeMouseEvents();
static const QString xmlName;
// Define default values for many properties.
static const int ENABLEDTURBODEFAULT;
static const double DEFAULTMOUSESPEEDMOD;
static const unsigned int DEFAULTKEYREPEATDELAY;
static const unsigned int DEFAULTKEYREPEATRATE;
static const JoyMouseCurve DEFAULTMOUSECURVE;
static const bool DEFAULTTOGGLE;
static const int DEFAULTTURBOINTERVAL;
static const bool DEFAULTUSETURBO;
static const int DEFAULTMOUSESPEEDX;
static const int DEFAULTMOUSESPEEDY;
static const int DEFAULTSETSELECTION;
static const SetChangeCondition DEFAULTSETCONDITION;
static const JoyMouseMovementMode DEFAULTMOUSEMODE;
static const int DEFAULTSPRINGWIDTH;
static const int DEFAULTSPRINGHEIGHT;
static const double DEFAULTSENSITIVITY;
static const int DEFAULTWHEELX;
static const int DEFAULTWHEELY;
static const bool DEFAULTCYCLERESETACTIVE;
static const int DEFAULTCYCLERESET;
static const bool DEFAULTRELATIVESPRING;
static const TurboMode DEFAULTTURBOMODE;
static const double DEFAULTEASINGDURATION;
static const double MINIMUMEASINGDURATION;
static const double MAXIMUMEASINGDURATION;
static const int DEFAULTMOUSEHISTORYSIZE;
static const double DEFAULTWEIGHTMODIFIER;
static const int MAXIMUMMOUSEHISTORYSIZE;
static const double MAXIMUMWEIGHTMODIFIER;
static const int MAXIMUMMOUSEREFRESHRATE;
static const int DEFAULTIDLEMOUSEREFRESHRATE;
static int IDLEMOUSEREFRESHRATE;
static const unsigned int MINCYCLERESETTIME;
static const unsigned int MAXCYCLERESETTIME;
static const double DEFAULTEXTRACCELVALUE;
static const double DEFAULTMINACCELTHRESHOLD;
static const double DEFAULTMAXACCELTHRESHOLD;
static const double DEFAULTSTARTACCELMULTIPLIER;
static const double DEFAULTACCELEASINGDURATION;
static const JoyExtraAccelerationCurve DEFAULTEXTRAACCELCURVE;
static const int DEFAULTSPRINGRELEASERADIUS;
static QList<double> mouseHistoryX;
static QList<double> mouseHistoryY;
static double cursorRemainderX;
static double cursorRemainderY;
protected:
double getTotalSlotDistance(JoyButtonSlot *slot);
bool distanceEvent();
void clearAssignedSlots(bool signalEmit=true);
void releaseSlotEvent();
void findReleaseEventEnd();
void findReleaseEventIterEnd(QListIterator<JoyButtonSlot*> *tempiter);
void findHoldEventEnd();
bool checkForDelaySequence();
void checkForPressedSetChange();
bool insertAssignedSlot(JoyButtonSlot *newSlot, bool updateActiveString=true);
unsigned int getPreferredKeyPressTime();
void checkTurboCondition(JoyButtonSlot *slot);
static bool hasFutureSpringEvents();
virtual double getCurrentSpringDeadCircle();
void vdpadPassEvent(bool pressed, bool ignoresets=false);
QString buildActiveZoneSummary(QList<JoyButtonSlot*> &tempList);
void localBuildActiveZoneSummaryString();
virtual bool readButtonConfig(QXmlStreamReader *xml);
typedef struct _mouseCursorInfo
{
JoyButtonSlot *slot;
double code;
} mouseCursorInfo;
// Used to denote whether the actual joypad button is pressed
bool isButtonPressed;
// Used to denote whether the virtual key is pressed
bool isKeyPressed;
bool toggle;
bool quitEvent;
// Used to denote the SDL index of the actual joypad button
int index;
int turboInterval;
QTimer turboTimer;
QTimer pauseTimer;
QTimer holdTimer;
QTimer pauseWaitTimer;
QTimer createDeskTimer;
QTimer releaseDeskTimer;
QTimer mouseWheelVerticalEventTimer;
QTimer mouseWheelHorizontalEventTimer;
QTimer setChangeTimer;
QTimer keyPressTimer;
QTimer delayTimer;
QTimer slotSetChangeTimer;
static QTimer staticMouseEventTimer;
bool isDown;
bool toggleActiveState;
bool useTurbo;
QList<JoyButtonSlot*> assignments;
QList<JoyButtonSlot*> activeSlots;
QString customName;
int mouseSpeedX;
int mouseSpeedY;
int wheelSpeedX;
int wheelSpeedY;
int setSelection;
SetChangeCondition setSelectionCondition;
int originset;
QListIterator<JoyButtonSlot*> *slotiter;
JoyButtonSlot *currentPause;
JoyButtonSlot *currentHold;
JoyButtonSlot *currentCycle;
JoyButtonSlot *previousCycle;
JoyButtonSlot *currentDistance;
JoyButtonSlot *currentMouseEvent;
JoyButtonSlot *currentRelease;
JoyButtonSlot *currentWheelVerticalEvent;
JoyButtonSlot *currentWheelHorizontalEvent;
JoyButtonSlot *currentKeyPress;
JoyButtonSlot *currentDelay;
JoyButtonSlot *currentSetChangeSlot;
bool ignoresets;
QTime buttonHold;
QTime pauseHold;
QTime inpauseHold;
QTime buttonHeldRelease;
QTime keyPressHold;
QTime buttonDelay;
QTime turboHold;
QTime wheelVerticalTime;
QTime wheelHorizontalTime;
//static QElapsedTimer lastMouseTime;
static QTime testOldMouseTime;
QQueue<bool> ignoreSetQueue;
QQueue<bool> isButtonPressedQueue;
QQueue<JoyButtonSlot*> mouseEventQueue;
QQueue<JoyButtonSlot*> mouseWheelVerticalEventQueue;
QQueue<JoyButtonSlot*> mouseWheelHorizontalEventQueue;
int currentRawValue;
VDPad *vdpad;
bool ignoreEvents;
JoyMouseMovementMode mouseMode;
JoyMouseCurve mouseCurve;
int springWidth;
int springHeight;
double sensitivity;
bool smoothing;
bool whileHeldStatus;
double lastDistance;
double lastWheelVerticalDistance;
double lastWheelHorizontalDistance;
int tempTurboInterval;
// Keep track of the previous mouse distance from the previous gamepad
// poll.
double lastMouseDistance;
// Keep track of the previous full distance from the previous gamepad
// poll.
double lastAccelerationDistance;
// Multiplier and time used for acceleration easing.
double currentAccelMulti;
QTime accelExtraDurationTime;
double accelDuration;
double oldAccelMulti;
double accelTravel; // Track travel when accel started
// Should lastMouseDistance be updated. Set after mouse event.
bool updateLastMouseDistance;
// Should startingMouseDistance be updated. Set after acceleration
// has finally been applied.
bool updateStartingMouseDistance;
double updateOldAccelMulti;
bool updateInitAccelValues;
// Keep track of the current mouse distance after a poll. Used
// to update lastMouseDistance later.
double currentMouseDistance;
// Keep track of the current mouse distance after a poll. Used
// to update lastMouseDistance later.
double currentAccelerationDistance;
// Take into account when mouse acceleration started
double startingAccelerationDistance;
double minMouseDistanceAccelThreshold;
double maxMouseDistanceAccelThreshold;
double startAccelMultiplier;
JoyExtraAccelerationCurve extraAccelCurve;
QString actionName;
QString buttonName; // User specified button name
QString defaultButtonName; // Name used by the system
SetJoystick *parentSet; // Pointer to set that button is assigned to.
bool cycleResetActive;
unsigned int cycleResetInterval;
QTime cycleResetHold;
bool relativeSpring;
TurboMode currentTurboMode;
double easingDuration;
bool extraAccelerationEnabled;
double extraAccelerationMultiplier;
int springDeadCircleMultiplier;
bool pendingPress;
bool pendingEvent;
bool pendingIgnoreSets;
QReadWriteLock activeZoneLock;
QReadWriteLock assignmentsLock;
QReadWriteLock activeZoneStringLock;
QString activeZoneString;
QTimer activeZoneTimer;
static double mouseSpeedModifier;
static QList<JoyButtonSlot*> mouseSpeedModList;
static QList<mouseCursorInfo> cursorXSpeeds;
static QList<mouseCursorInfo> cursorYSpeeds;
static QList<PadderCommon::springModeInfo> springXSpeeds;
static QList<PadderCommon::springModeInfo> springYSpeeds;
static QList<JoyButton*> pendingMouseButtons;
static QHash<unsigned int, int> activeKeys;
static QHash<unsigned int, int> activeMouseButtons;
#ifdef Q_OS_WIN
static JoyKeyRepeatHelper repeatHelper;
#endif
static JoyButtonSlot *lastActiveKey;
static JoyButtonMouseHelper mouseHelper;
static double weightModifier;
static int mouseHistorySize;
static int mouseRefreshRate;
static int springModeScreen;
static int gamepadRefreshRate;
signals:
void clicked (int index);
void released (int index);
void keyChanged(int keycode);
void mouseChanged(int mousecode);
void setChangeActivated(int index);
void setAssignmentChanged(int current_button, int associated_set, int mode);
void finishedPause();
void turboChanged(bool state);
void toggleChanged(bool state);
void turboIntervalChanged(int interval);
void slotsChanged();
void actionNameChanged();
void buttonNameChanged();
void propertyUpdated();
void activeZoneChanged();
public slots:
void setTurboInterval (int interval);
void setToggle (bool toggle);
void setUseTurbo(bool useTurbo);
void setMouseSpeedX(int speed);
void setMouseSpeedY(int speed);
void setWheelSpeedX(int speed);
void setWheelSpeedY(int speed);
void setSpringWidth(int value);
void setSpringHeight(int value);
void setSensitivity(double value);
void setSpringRelativeStatus(bool value);
void setActionName(QString tempName);
void setButtonName(QString tempName);
void setEasingDuration(double value);
virtual void reset();
virtual void reset(int index);
virtual void resetProperties();
virtual void clearSlotsEventReset(bool clearSignalEmit=true);
virtual void eventReset();
bool setAssignedSlot(int code, unsigned int alias, int index,
JoyButtonSlot::JoySlotInputAction mode=JoyButtonSlot::JoyKeyboard);
bool setAssignedSlot(int code,
JoyButtonSlot::JoySlotInputAction mode=JoyButtonSlot::JoyKeyboard);
bool setAssignedSlot(int code, unsigned int alias,
JoyButtonSlot::JoySlotInputAction mode=JoyButtonSlot::JoyKeyboard);
bool setAssignedSlot(JoyButtonSlot *otherSlot, int index);
bool insertAssignedSlot(int code, unsigned int alias, int index,
JoyButtonSlot::JoySlotInputAction mode=JoyButtonSlot::JoyKeyboard);
void removeAssignedSlot(int index);
static void establishMouseTimerConnections();
void establishPropertyUpdatedConnections();
void disconnectPropertyUpdatedConnections();
virtual void mouseEvent();
protected slots:
virtual void turboEvent();
virtual void wheelEventVertical();
virtual void wheelEventHorizontal();
void createDeskEvent();
void releaseDeskEvent(bool skipsetchange=false);
void buildActiveZoneSummaryString();
private slots:
void releaseActiveSlots();
void activateSlots();
void waitForDeskEvent();
void waitForReleaseDeskEvent();
void holdEvent();
void delayEvent();
void pauseWaitEvent();
void checkForSetChange();
void keyPressEvent();
void slotSetChange();
};
#endif // JOYBUTTON_H
``` | /content/code_sandbox/src/joybutton.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 4,012 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
//#include <QDebug>
#include <QVariant>
#include <QApplication>
#include <QTime>
#include <cmath>
#include <QFileInfo>
#include <QStringList>
#include <QCursor>
#include <QDesktopWidget>
#include <QProcess>
#include "event.h"
#include "eventhandlerfactory.h"
#include "joybutton.h"
#if defined(Q_OS_UNIX)
#if defined(WITH_X11)
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/XKBlib.h>
#include "x11extras.h"
#ifdef WITH_XTEST
#include <X11/extensions/XTest.h>
#endif
#endif
#if defined(WITH_UINPUT)
#include "uinputhelper.h"
#endif
#elif defined (Q_OS_WIN)
#include <qt_windows.h>
#include "winextras.h"
#endif
// TODO: Implement function for determining final mouse pointer position
// based around a fixed bounding box resolution.
void fakeAbsMouseCoordinates(double springX, double springY,
unsigned int width, unsigned int height,
unsigned int &finalx, unsigned int &finaly, int screen=-1)
{
//Q_UNUSED(finalx);
//Q_UNUSED(finaly);
//Q_UNUSED(width);
//Q_UNUSED(height);
int screenWidth = 0;
int screenHeight = 0;
int screenMidwidth = 0;
int screenMidheight = 0;
int destSpringWidth = 0;
int destSpringHeight = 0;
int destMidWidth = 0;
int destMidHeight = 0;
//int currentMouseX = 0;
//int currentMouseY = 0;
QRect deskRect = PadderCommon::mouseHelperObj.getDesktopWidget()
->screenGeometry(screen);
screenWidth = deskRect.width();
screenHeight = deskRect.height();
screenMidwidth = screenWidth / 2;
screenMidheight = screenHeight / 2;
if (width >= 2 && height >= 2)
{
destSpringWidth = qMin(static_cast<int>(width), screenWidth);
destSpringHeight = qMin(static_cast<int>(height), screenHeight);
}
else
{
destSpringWidth = screenWidth;
destSpringHeight = screenHeight;
}
/*#if defined(Q_OS_UNIX) && defined(WITH_X11)
QPoint currentPoint;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
currentPoint = X11Extras::getInstance()->getPos();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
else
{
currentPoint = QCursor::pos();
}
#endif
#else
QPoint currentPoint = QCursor::pos();
#endif
*/
destMidWidth = destSpringWidth / 2;
destMidHeight = destSpringHeight / 2;
finalx = (screenMidwidth + (springX * destMidWidth) + deskRect.x());
finaly = (screenMidheight + (springY * destMidHeight) + deskRect.y());
}
// Create the event used by the operating system.
void sendevent(JoyButtonSlot *slot, bool pressed)
{
//int code = slot->getSlotCode();
JoyButtonSlot::JoySlotInputAction device = slot->getSlotMode();
if (device == JoyButtonSlot::JoyKeyboard)
{
EventHandlerFactory::getInstance()->handler()->sendKeyboardEvent(slot, pressed);
}
else if (device == JoyButtonSlot::JoyMouseButton)
{
EventHandlerFactory::getInstance()->handler()->sendMouseButtonEvent(slot, pressed);
}
else if (device == JoyButtonSlot::JoyTextEntry && pressed && !slot->getTextData().isEmpty())
{
EventHandlerFactory::getInstance()->handler()->sendTextEntryEvent(slot->getTextData());
}
else if (device == JoyButtonSlot::JoyExecute && pressed && !slot->getTextData().isEmpty())
{
QString execString = slot->getTextData();
if (slot->getExtraData().canConvert<QString>())
{
QString argumentsString = slot->getExtraData().toString();
QStringList argumentsTempList(PadderCommon::parseArgumentsString(argumentsString));
QProcess::startDetached(execString, argumentsTempList);
}
else
{
QProcess::startDetached(execString);
}
}
}
// Create the relative mouse event used by the operating system.
void sendevent(int code1, int code2)
{
EventHandlerFactory::getInstance()->handler()->sendMouseEvent(code1, code2);
}
// TODO: Re-implement spring event generation to simplify the process
// and reduce overhead. Refactor old function to only be used when an absmouse
// position must be faked.
void sendSpringEventRefactor(PadderCommon::springModeInfo *fullSpring,
PadderCommon::springModeInfo *relativeSpring,
int* const mousePosX, int* const mousePosY)
{
Q_UNUSED(relativeSpring);
Q_UNUSED(mousePosX);
Q_UNUSED(mousePosY);
PadderCommon::mouseHelperObj.mouseTimer.stop();
if (fullSpring)
{
unsigned int xmovecoor = 0;
unsigned int ymovecoor = 0;
int width = 0;
int height = 0;
int midwidth = 0;
int midheight = 0;
int destSpringWidth = 0;
int destSpringHeight = 0;
int destMidWidth = 0;
int destMidHeight = 0;
int currentMouseX = 0;
int currentMouseY = 0;
double displacementX = 0.0;
double displacementY = 0.0;
bool useFullScreen = true;
PadderCommon::mouseHelperObj.mouseTimer.stop();
BaseEventHandler *handler = EventHandlerFactory::getInstance()->handler();
if (fullSpring->screen >= -1 &&
fullSpring->screen >= PadderCommon::mouseHelperObj.getDesktopWidget()->screenCount())
{
fullSpring->screen = -1;
}
int springWidth = fullSpring->width;
int springHeight = fullSpring->height;
if (springWidth >= 2 && springHeight >= 2)
{
useFullScreen = false;
displacementX = fullSpring->displacementX;
displacementY = fullSpring->displacementY;
}
else
{
useFullScreen = true;
displacementX = fullSpring->displacementX;
displacementY = fullSpring->displacementY;
}
unsigned int pivotX = 0;
unsigned int pivotY = 0;
if (relativeSpring && relativeSpring->width >= 2 && relativeSpring->height >= 2)
{
if (PadderCommon::mouseHelperObj.pivotPoint[0] != -1)
{
pivotX = PadderCommon::mouseHelperObj.pivotPoint[0];
}
if (PadderCommon::mouseHelperObj.pivotPoint[1] != -1)
{
pivotY = PadderCommon::mouseHelperObj.pivotPoint[1];
}
if (pivotX >= 0 && pivotY >= 0)
{
// Find a use for this routine in this context.
int destRelativeWidth = relativeSpring->width;
int destRelativeHeight = relativeSpring->height;
int xRelativeMoovCoor = 0;
if (relativeSpring->displacementX >= -1.0)
{
xRelativeMoovCoor = (relativeSpring->displacementX * destRelativeWidth) / 2;
}
int yRelativeMoovCoor = 0;
if (relativeSpring->displacementY >= -1.0)
{
yRelativeMoovCoor = (relativeSpring->displacementY * destRelativeHeight) / 2;
}
xmovecoor += xRelativeMoovCoor;
ymovecoor += yRelativeMoovCoor;
}
}
if (handler->getIdentifier() == "xtest")
{
fakeAbsMouseCoordinates(displacementX, displacementY,
springWidth, springHeight, xmovecoor, ymovecoor,
fullSpring->screen);
//EventHandlerFactory::getInstance()->handler()->sendMouseAbsEvent(xmovecoor,
// ymovecoor);
}
else if (handler->getIdentifier() == "uinput")
{
//EventHandlerFactory::getInstance()->handler()->sendMouseAbsEvent(displacementX,
// displacementY);
fakeAbsMouseCoordinates(displacementX, displacementY,
springWidth, springHeight, xmovecoor, ymovecoor,
fullSpring->screen);
//EventHandlerFactory::getInstance()->handler()
// ->sendMouseSpringEvent(xmovecoor, ymovecoor, width, height);
}
}
else
{
PadderCommon::mouseHelperObj.springMouseMoving = false;
PadderCommon::mouseHelperObj.pivotPoint[0] = -1;
PadderCommon::mouseHelperObj.pivotPoint[1] = -1;
}
}
// TODO: Change to only use this routine when using a relative mouse
// pointer to fake absolute mouse moves. Otherwise, don't worry about
// current position of the mouse and just send an absolute mouse pointer
// event.
void sendSpringEvent(PadderCommon::springModeInfo *fullSpring,
PadderCommon::springModeInfo *relativeSpring,
int* const mousePosX, int* const mousePosY)
{
PadderCommon::mouseHelperObj.mouseTimer.stop();
if ((fullSpring->displacementX >= -2.0 && fullSpring->displacementX <= 1.0 &&
fullSpring->displacementY >= -2.0 && fullSpring->displacementY <= 1.0) ||
(relativeSpring && (relativeSpring->displacementX >= -2.0 && relativeSpring->displacementX <= 1.0 &&
relativeSpring->displacementY >= -2.0 && relativeSpring->displacementY <= 1.0)))
{
int xmovecoor = 0;
int ymovecoor = 0;
int width = 0;
int height = 0;
int midwidth = 0;
int midheight = 0;
int destSpringWidth = 0;
int destSpringHeight = 0;
int destMidWidth = 0;
int destMidHeight = 0;
int currentMouseX = 0;
int currentMouseY = 0;
//QDesktopWidget deskWid;
if (fullSpring->screen >= -1 &&
fullSpring->screen >= PadderCommon::mouseHelperObj.getDesktopWidget()->screenCount())
{
fullSpring->screen = -1;
}
QRect deskRect = PadderCommon::mouseHelperObj.getDesktopWidget()
->screenGeometry(fullSpring->screen);
width = deskRect.width();
height = deskRect.height();
#if defined(Q_OS_UNIX) && defined(WITH_X11)
QPoint currentPoint;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
currentPoint = X11Extras::getInstance()->getPos();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
else
{
currentPoint = QCursor::pos();
}
#endif
#else
QPoint currentPoint = QCursor::pos();
#endif
currentMouseX = currentPoint.x();
currentMouseY = currentPoint.y();
midwidth = width / 2;
midheight = height / 2;
int springWidth = fullSpring->width;
int springHeight = fullSpring->height;
if (springWidth >= 2 && springHeight >= 2)
{
destSpringWidth = qMin(springWidth, width);
destSpringHeight = qMin(springHeight, height);
}
else
{
destSpringWidth = width;
destSpringHeight = height;
}
destMidWidth = destSpringWidth / 2;
destMidHeight = destSpringHeight / 2;
unsigned int pivotX = currentMouseX;
unsigned int pivotY = currentMouseY;
if (relativeSpring)
{
if (PadderCommon::mouseHelperObj.pivotPoint[0] != -1)
{
pivotX = PadderCommon::mouseHelperObj.pivotPoint[0];
}
else
{
pivotX = currentMouseX;
}
if (PadderCommon::mouseHelperObj.pivotPoint[1] != -1)
{
pivotY = PadderCommon::mouseHelperObj.pivotPoint[1];
}
else
{
pivotY = currentMouseY;
}
}
xmovecoor = (fullSpring->displacementX >= -1.0) ? (midwidth + (fullSpring->displacementX * destMidWidth) + deskRect.x()): pivotX;
ymovecoor = (fullSpring->displacementY >= -1.0) ? (midheight + (fullSpring->displacementY * destMidHeight) + deskRect.y()) : pivotY;
unsigned int fullSpringDestX = xmovecoor;
unsigned int fullSpringDestY = ymovecoor;
unsigned int destRelativeWidth = 0;
unsigned int destRelativeHeight = 0;
if (relativeSpring && relativeSpring->width >= 2 && relativeSpring->height >= 2)
{
destRelativeWidth = relativeSpring->width;
destRelativeHeight = relativeSpring->height;
int xRelativeMoovCoor = 0;
if (relativeSpring->displacementX >= -1.0)
{
xRelativeMoovCoor = (relativeSpring->displacementX * destRelativeWidth) / 2;
}
int yRelativeMoovCoor = 0;
if (relativeSpring->displacementY >= -1.0)
{
yRelativeMoovCoor = (relativeSpring->displacementY * destRelativeHeight) / 2;
}
xmovecoor += xRelativeMoovCoor;
ymovecoor += yRelativeMoovCoor;
}
if (mousePosX)
{
*mousePosX = xmovecoor;
}
if (mousePosY)
{
*mousePosY = ymovecoor;
}
if (xmovecoor != currentMouseX || ymovecoor != currentMouseY)
{
double diffx = abs(currentMouseX - xmovecoor);
double diffy = abs(currentMouseY - ymovecoor);
// If either position is set to center, force update.
if (xmovecoor == (deskRect.x() + midwidth) || ymovecoor == (deskRect.y() + midheight))
{
#if defined(Q_OS_UNIX)
BaseEventHandler *handler = EventHandlerFactory::getInstance()->handler();
if (fullSpring->screen <= -1)
{
if (handler->getIdentifier() == "xtest")
{
EventHandlerFactory::getInstance()->handler()->sendMouseAbsEvent(xmovecoor,
ymovecoor,
-1);
}
else if (handler->getIdentifier() == "uinput")
{
EventHandlerFactory::getInstance()->handler()
->sendMouseSpringEvent(xmovecoor, ymovecoor,
width + deskRect.x(), height + deskRect.y());
}
}
else
{
EventHandlerFactory::getInstance()->handler()->sendMouseEvent(xmovecoor - currentMouseX,
ymovecoor - currentMouseY);
}
#elif defined(Q_OS_WIN)
if (fullSpring->screen <= -1)
{
EventHandlerFactory::getInstance()->handler()
->sendMouseSpringEvent(xmovecoor, ymovecoor,
width + deskRect.x(), height + deskRect.y());
}
else
{
sendevent(xmovecoor - currentMouseX, ymovecoor - currentMouseY);
}
#endif
}
else if (!PadderCommon::mouseHelperObj.springMouseMoving && relativeSpring &&
(relativeSpring->displacementX >= -1.0 || relativeSpring->displacementY >= -1.0) &&
(diffx >= destRelativeWidth*.013 || diffy >= destRelativeHeight*.013))
{
PadderCommon::mouseHelperObj.springMouseMoving = true;
#if defined(Q_OS_UNIX)
BaseEventHandler *handler = EventHandlerFactory::getInstance()->handler();
if (fullSpring->screen <= -1)
{
if (handler->getIdentifier() == "xtest")
{
EventHandlerFactory::getInstance()->handler()->sendMouseAbsEvent(xmovecoor,
ymovecoor,
-1);
}
else if (handler->getIdentifier() == "uinput")
{
EventHandlerFactory::getInstance()->handler()
->sendMouseSpringEvent(xmovecoor, ymovecoor,
width + deskRect.x(), height + deskRect.y());
}
}
else
{
EventHandlerFactory::getInstance()->handler()
->sendMouseEvent(xmovecoor - currentMouseX, ymovecoor - currentMouseY);
}
#elif defined(Q_OS_WIN)
if (fullSpring->screen <= -1)
{
EventHandlerFactory::getInstance()->handler()
->sendMouseSpringEvent(xmovecoor, ymovecoor,
width + deskRect.x(), height + deskRect.y());
}
else
{
sendevent(xmovecoor - currentMouseX, ymovecoor - currentMouseY);
}
#endif
PadderCommon::mouseHelperObj.mouseTimer.start(
qMax(JoyButton::getMouseRefreshRate(),
JoyButton::getGamepadRefreshRate()) + 1);
}
else if (!PadderCommon::mouseHelperObj.springMouseMoving &&
(diffx >= destSpringWidth*.013 || diffy >= destSpringHeight*.013))
{
PadderCommon::mouseHelperObj.springMouseMoving = true;
#if defined(Q_OS_UNIX)
BaseEventHandler *handler = EventHandlerFactory::getInstance()->handler();
if (fullSpring->screen <= -1)
{
if (handler->getIdentifier() == "xtest")
{
EventHandlerFactory::getInstance()->handler()->sendMouseAbsEvent(xmovecoor,
ymovecoor,
-1);
}
else if (handler->getIdentifier() == "uinput")
{
EventHandlerFactory::getInstance()->handler()
->sendMouseSpringEvent(xmovecoor, ymovecoor,
width + deskRect.x(), height + deskRect.y());
}
}
else
{
EventHandlerFactory::getInstance()->handler()
->sendMouseEvent(xmovecoor - currentMouseX,
ymovecoor - currentMouseY);
}
#elif defined(Q_OS_WIN)
if (fullSpring->screen <= -1)
{
EventHandlerFactory::getInstance()->handler()
->sendMouseSpringEvent(xmovecoor, ymovecoor,
width + deskRect.x(), height + deskRect.y());
}
else
{
sendevent(xmovecoor - currentMouseX, ymovecoor - currentMouseY);
}
#endif
PadderCommon::mouseHelperObj.mouseTimer.start(
qMax(JoyButton::getMouseRefreshRate(),
JoyButton::getGamepadRefreshRate()) + 1);
}
else if (PadderCommon::mouseHelperObj.springMouseMoving && (diffx < 2 && diffy < 2))
{
PadderCommon::mouseHelperObj.springMouseMoving = false;
}
else if (PadderCommon::mouseHelperObj.springMouseMoving)
{
#if defined(Q_OS_UNIX)
BaseEventHandler *handler = EventHandlerFactory::getInstance()->handler();
if (fullSpring->screen <= -1)
{
if (handler->getIdentifier() == "xtest")
{
EventHandlerFactory::getInstance()->handler()->sendMouseAbsEvent(xmovecoor,
ymovecoor,
-1);
}
else if (handler->getIdentifier() == "uinput")
{
EventHandlerFactory::getInstance()->handler()
->sendMouseSpringEvent(xmovecoor, ymovecoor,
width + deskRect.x(), height + deskRect.y());
}
}
else
{
EventHandlerFactory::getInstance()->handler()
->sendMouseEvent(xmovecoor - currentMouseX,
ymovecoor - currentMouseY);
}
#elif defined(Q_OS_WIN)
if (fullSpring->screen <= -1)
{
EventHandlerFactory::getInstance()->handler()
->sendMouseSpringEvent(xmovecoor, ymovecoor,
width + deskRect.x(), height + deskRect.y());
}
else
{
sendevent(xmovecoor - currentMouseX, ymovecoor - currentMouseY);
}
#endif
PadderCommon::mouseHelperObj.mouseTimer.start(
qMax(JoyButton::getMouseRefreshRate(),
JoyButton::getGamepadRefreshRate()) + 1);
}
PadderCommon::mouseHelperObj.previousCursorLocation[0] = currentMouseX;
PadderCommon::mouseHelperObj.previousCursorLocation[1] = currentMouseY;
PadderCommon::mouseHelperObj.pivotPoint[0] = fullSpringDestX;
PadderCommon::mouseHelperObj.pivotPoint[1] = fullSpringDestY;
}
else if (PadderCommon::mouseHelperObj.previousCursorLocation[0] == xmovecoor &&
PadderCommon::mouseHelperObj.previousCursorLocation[1] == ymovecoor)
{
PadderCommon::mouseHelperObj.springMouseMoving = false;
}
else
{
PadderCommon::mouseHelperObj.previousCursorLocation[0] = currentMouseX;
PadderCommon::mouseHelperObj.previousCursorLocation[1] = currentMouseY;
PadderCommon::mouseHelperObj.pivotPoint[0] = fullSpringDestX;
PadderCommon::mouseHelperObj.pivotPoint[1] = fullSpringDestY;
PadderCommon::mouseHelperObj.mouseTimer.start(
qMax(JoyButton::getMouseRefreshRate(),
JoyButton::getGamepadRefreshRate()) + 1);
}
}
else
{
PadderCommon::mouseHelperObj.springMouseMoving = false;
PadderCommon::mouseHelperObj.pivotPoint[0] = -1;
PadderCommon::mouseHelperObj.pivotPoint[1] = -1;
}
}
int X11KeySymToKeycode(QString key)
{
int tempcode = 0;
#if defined (Q_OS_UNIX)
BaseEventHandler *handler = EventHandlerFactory::getInstance()->handler();
if (key.length() > 0)
{
#ifdef WITH_XTEST
if (handler->getIdentifier() == "xtest")
{
Display* display = X11Extras::getInstance()->display();
tempcode = XKeysymToKeycode(display, XStringToKeysym(key.toUtf8().data()));
}
#endif
#ifdef WITH_UINPUT
if (handler->getIdentifier() == "uinput")
{
tempcode = UInputHelper::getInstance()->getVirtualKey(key);
}
#endif
}
#elif defined (Q_OS_WIN)
if (key.length() > 0)
{
tempcode = WinExtras::getVirtualKey(key);
if (tempcode <= 0 && key.length() == 1)
{
//qDebug() << "KEY: " << key;
//int oridnal = key.toUtf8().constData()[0];
int ordinal = QVariant(key.toUtf8().constData()[0]).toInt();
tempcode = VkKeyScan(ordinal);
int modifiers = tempcode >> 8;
tempcode = tempcode & 0xff;
if ((modifiers & 1) != 0) tempcode |= VK_SHIFT;
if ((modifiers & 2) != 0) tempcode |= VK_CONTROL;
if ((modifiers & 4) != 0) tempcode |= VK_MENU;
//tempcode = VkKeyScan(QVariant(key.constData()).toInt());
//tempcode = OemKeyScan(key.toUtf8().toInt());
//tempcode = OemKeyScan(ordinal);
}
}
#endif
return tempcode;
}
QString keycodeToKeyString(int keycode, unsigned int alias)
{
QString newkey;
#if defined (Q_OS_UNIX)
Q_UNUSED(alias);
if (keycode <= 0)
{
newkey = "[NO KEY]";
}
else
{
BaseEventHandler *handler = EventHandlerFactory::getInstance()->handler();
#ifdef WITH_XTEST
if (handler->getIdentifier() == "xtest")
{
Display* display = X11Extras::getInstance()->display();
newkey = QString("0x%1").arg(keycode, 0, 16);
QString tempkey = XKeysymToString(XkbKeycodeToKeysym(display, keycode, 0, 0));
QString tempalias = X11Extras::getInstance()->getDisplayString(tempkey);
if (!tempalias.isEmpty())
{
newkey = tempalias;
}
else
{
XKeyPressedEvent tempevent;
tempevent.keycode = keycode;
tempevent.type = KeyPress;
tempevent.display = display;
tempevent.state = 0;
char tempstring[256];
memset(tempstring, 0, sizeof(tempstring));
int bitestoreturn = sizeof(tempstring) - 1;
int numchars = XLookupString(&tempevent, tempstring, bitestoreturn, NULL, NULL);
if (numchars > 0)
{
tempstring[numchars] = '\0';
newkey = QString::fromUtf8(tempstring);
//qDebug() << "NEWKEY:" << newkey << endl;
//qDebug() << "NEWKEY LEGNTH:" << numchars << endl;
}
else
{
newkey = tempkey;
}
}
}
#endif
#ifdef WITH_UINPUT
if (handler->getIdentifier() == "uinput")
{
QString tempalias = UInputHelper::getInstance()->getDisplayString(keycode);
if (!tempalias.isEmpty())
{
newkey = tempalias;
}
else
{
newkey = QString("0x%1").arg(keycode, 0, 16);
}
}
#endif
}
#elif defined (Q_OS_WIN)
wchar_t buffer[50] = {0};
QString tempalias = WinExtras::getDisplayString(keycode);
if (!tempalias.isEmpty())
{
newkey = tempalias;
}
else
{
int scancode = WinExtras::scancodeFromVirtualKey(keycode, alias);
if (keycode >= VK_BROWSER_BACK && keycode <= VK_LAUNCH_APP2)
{
newkey.append(QString("0x%1").arg(keycode, 0, 16));
}
else
{
int length = GetKeyNameTextW(scancode << 16, buffer, sizeof(buffer));
if (length > 0)
{
newkey = QString::fromWCharArray(buffer);
}
else
{
newkey.append(QString("0x%1").arg(keycode, 0, 16));
}
}
}
#endif
return newkey;
}
unsigned int X11KeyCodeToX11KeySym(unsigned int keycode)
{
#ifdef Q_OS_WIN
Q_UNUSED(keycode);
return 0;
#else
#ifdef WITH_X11
Display* display = X11Extras::getInstance()->display();
unsigned int tempcode = XkbKeycodeToKeysym(display, keycode, 0, 0);
return tempcode;
#else
Q_UNUSED(keycode);
return 0;
#endif
#endif
}
QString keysymToKeyString(int keysym, unsigned int alias)
{
QString newkey;
#if defined (Q_OS_UNIX)
Q_UNUSED(alias);
BaseEventHandler *handler = EventHandlerFactory::getInstance()->handler();
if (handler->getIdentifier() == "xtest")
{
Display* display = X11Extras::getInstance()->display();
unsigned int keycode = 0;
if (keysym > 0)
{
keycode = XKeysymToKeycode(display, keysym);
}
newkey = keycodeToKeyString(keycode);
}
else if (handler->getIdentifier() == "uinput")
{
newkey = keycodeToKeyString(keysym);
}
#else
newkey = keycodeToKeyString(keysym, alias);
#endif
return newkey;
}
``` | /content/code_sandbox/src/event.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 6,352 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
//#include <QDebug>
#include <QStringListIterator>
#include <QVariant>
#include <QSettings>
#include <QMapIterator>
//#include "logger.h"
#include "sdleventreader.h"
SDLEventReader::SDLEventReader(QMap<SDL_JoystickID, InputDevice *> *joysticks,
AntiMicroSettings *settings, QObject *parent) :
QObject(parent)
{
this->joysticks = joysticks;
this->settings = settings;
settings->getLock()->lock();
this->pollRate = settings->value("GamepadPollRate",
AntiMicroSettings::defaultSDLGamepadPollRate).toUInt();
settings->getLock()->unlock();
pollRateTimer.setParent(this);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
pollRateTimer.setTimerType(Qt::PreciseTimer);
#endif
initSDL();
connect(&pollRateTimer, SIGNAL(timeout()), this, SLOT(performWork()));
}
SDLEventReader::~SDLEventReader()
{
if (sdlIsOpen)
{
closeSDL();
}
}
void SDLEventReader::initSDL()
{
#ifdef USE_SDL_2
// SDL_INIT_GAMECONTROLLER should automatically initialize SDL_INIT_JOYSTICK
// but it doesn't seem to be the case with v2.0.4
SDL_Init(SDL_INIT_GAMECONTROLLER | SDL_INIT_JOYSTICK);
#else
// Video support is required to use event system in SDL 1.2.
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK);
#endif
SDL_JoystickEventState(SDL_ENABLE);
sdlIsOpen = true;
#ifdef USE_SDL_2
//QSettings settings(PadderCommon::configFilePath, QSettings::IniFormat);
settings->getLock()->lock();
settings->beginGroup("Mappings");
QStringList mappings = settings->allKeys();
QStringListIterator iter(mappings);
while (iter.hasNext())
{
QString tempstring = iter.next();
QString mappingSetting = settings->value(tempstring, QString()).toString();
if (!mappingSetting.isEmpty())
{
QByteArray temparray = mappingSetting.toUtf8();
char *mapping = temparray.data();
SDL_GameControllerAddMapping(mapping); // Let SDL take care of validation
}
}
settings->endGroup();
settings->getLock()->unlock();
//SDL_GameControllerAddMapping("03000000100800000100000010010000,Twin USB Joystick,a:b2,b:b1,x:b3,y:b0,back:b8,start:b9,leftshoulder:b6,rightshoulder:b7,leftstick:b10,rightstick:b11,leftx:a0,lefty:a1,rightx:a3,righty:a2,lefttrigger:b4,righttrigger:b5,dpup:h0.1,dpleft:h0.8,dpdown:h0.4,dpright:h0.2");
#endif
pollRateTimer.stop();
pollRateTimer.setInterval(pollRate);
//pollRateTimer.start();
//pollRateTimer.setSingleShot(true);
emit sdlStarted();
}
void SDLEventReader::closeSDL()
{
pollRateTimer.stop();
SDL_Event event;
closeDevices();
// Clear any pending events
while (SDL_PollEvent(&event) > 0)
{
}
SDL_Quit();
sdlIsOpen = false;
emit sdlClosed();
}
void SDLEventReader::performWork()
{
if (sdlIsOpen)
{
//int status = SDL_WaitEvent(NULL);
int status = CheckForEvents();
if (status)
{
pollRateTimer.stop();
emit eventRaised();
}
}
}
void SDLEventReader::stop()
{
if (sdlIsOpen)
{
SDL_Event event;
event.type = SDL_QUIT;
SDL_PushEvent(&event);
}
pollRateTimer.stop();
}
void SDLEventReader::refresh()
{
if (sdlIsOpen)
{
stop();
QTimer::singleShot(0, this, SLOT(secondaryRefresh()));
}
}
void SDLEventReader::secondaryRefresh()
{
if (sdlIsOpen)
{
closeSDL();
}
initSDL();
}
void SDLEventReader::clearEvents()
{
if (sdlIsOpen)
{
SDL_Event event;
while (SDL_PollEvent(&event) > 0)
{
}
}
}
bool SDLEventReader::isSDLOpen()
{
return sdlIsOpen;
}
int SDLEventReader::CheckForEvents()
{
int result = 0;
bool exit = false;
/*Logger::LogInfo(
QString("Gamepad Poll %1").arg(
QTime::currentTime().toString("hh:mm:ss.zzz")),
true, true);
*/
SDL_PumpEvents();
#ifdef USE_SDL_2
switch (SDL_PeepEvents(NULL, 1, SDL_GETEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT))
#else
switch (SDL_PeepEvents(NULL, 1, SDL_GETEVENT, 0xFFFF))
#endif
{
case -1:
{
Logger::LogError(QString("SDL Error: %1").
arg(QString(SDL_GetError())),
true, true);
result = 0;
exit = true;
break;
}
case 0:
{
if (!pollRateTimer.isActive())
{
pollRateTimer.start();
}
//exit = true;
//SDL_Delay(10);
break;
}
default:
{
/*Logger::LogInfo(
QString("Gamepad Poll %1").arg(
QTime::currentTime().toString("hh:mm:ss.zzz")),
true, true);
*/
result = 1;
exit = true;
break;
}
}
return result;
}
void SDLEventReader::updatePollRate(unsigned int tempPollRate)
{
if (tempPollRate >= 1 && tempPollRate <= 16)
{
bool wasActive = pollRateTimer.isActive();
pollRateTimer.stop();
this->pollRate = tempPollRate;
pollRateTimer.setInterval(pollRate);
if (wasActive)
{
pollRateTimer.start();
}
}
}
void SDLEventReader::resetJoystickMap()
{
joysticks = 0;
}
void SDLEventReader::quit()
{
if (sdlIsOpen)
{
closeSDL();
joysticks = 0;
}
}
void SDLEventReader::closeDevices()
{
if (sdlIsOpen)
{
if (joysticks)
{
QMapIterator<SDL_JoystickID, InputDevice*> iter(*joysticks);
while (iter.hasNext())
{
iter.next();
InputDevice *current = iter.value();
current->closeSDLDevice();
}
}
}
}
/**
* @brief Method to block activity on the SDLEventReader object and its thread
* event loop.
*/
void SDLEventReader::haltServices()
{
PadderCommon::lockInputDevices();
PadderCommon::unlockInputDevices();
}
``` | /content/code_sandbox/src/sdleventreader.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,640 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include "joydpadbuttonwidget.h"
JoyDPadButtonWidget::JoyDPadButtonWidget(JoyButton *button, bool displayNames, QWidget *parent) :
JoyButtonWidget(button, displayNames, parent)
{
// Ensure that JoyDPadButtonWidget::generateLabel is called.
refreshLabel();
}
/**
* @brief Generate the string that will be displayed on the button
* @return Display string
*/
QString JoyDPadButtonWidget::generateLabel()
{
QString temp;
if (!button->getActionName().isEmpty() && displayNames)
{
temp = button->getActionName();
}
else
{
temp = button->getCalculatedActiveZoneSummary();
}
temp.replace("&", "&&");
return temp;
}
``` | /content/code_sandbox/src/joydpadbuttonwidget.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 260 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include <QHash>
#include "stickpushbuttongroup.h"
#include "buttoneditdialog.h"
#include "joycontrolstickeditdialog.h"
StickPushButtonGroup::StickPushButtonGroup(JoyControlStick *stick, bool displayNames, QWidget *parent) :
QGridLayout(parent)
{
this->stick = stick;
this->displayNames = displayNames;
generateButtons();
changeButtonLayout();
connect(stick, SIGNAL(joyModeChanged()), this, SLOT(changeButtonLayout()));
}
void StickPushButtonGroup::generateButtons()
{
QHash<JoyControlStick::JoyStickDirections, JoyControlStickButton*> *stickButtons = stick->getButtons();
JoyControlStickButton *button = 0;
JoyControlStickButtonPushButton *pushbutton = 0;
button = stickButtons->value(JoyControlStick::StickLeftUp);
upLeftButton = new JoyControlStickButtonPushButton(button, displayNames, parentWidget());
pushbutton = upLeftButton;
connect(pushbutton, SIGNAL(clicked()), this, SLOT(openStickButtonDialog()));
button->establishPropertyUpdatedConnections();
connect(button, SIGNAL(slotsChanged()), this, SLOT(propogateSlotsChanged()));
addWidget(pushbutton, 0, 0);
button = stickButtons->value(JoyControlStick::StickUp);
upButton = new JoyControlStickButtonPushButton(button, displayNames, parentWidget());
pushbutton = upButton;
connect(pushbutton, SIGNAL(clicked()), this, SLOT(openStickButtonDialog()));
button->establishPropertyUpdatedConnections();
connect(button, SIGNAL(slotsChanged()), this, SLOT(propogateSlotsChanged()));
addWidget(pushbutton, 0, 1);
button = stickButtons->value(JoyControlStick::StickRightUp);
upRightButton = new JoyControlStickButtonPushButton(button, displayNames, parentWidget());
pushbutton = upRightButton;
connect(pushbutton, SIGNAL(clicked()), this, SLOT(openStickButtonDialog()));
button->establishPropertyUpdatedConnections();
connect(button, SIGNAL(slotsChanged()), this, SLOT(propogateSlotsChanged()));
addWidget(pushbutton, 0, 2);
button = stickButtons->value(JoyControlStick::StickLeft);
leftButton = new JoyControlStickButtonPushButton(button, displayNames, parentWidget());
pushbutton = leftButton;
connect(pushbutton, SIGNAL(clicked()), this, SLOT(openStickButtonDialog()));
button->establishPropertyUpdatedConnections();
connect(button, SIGNAL(slotsChanged()), this, SLOT(propogateSlotsChanged()));
addWidget(pushbutton, 1, 0);
stickWidget = new JoyControlStickPushButton(stick, displayNames, parentWidget());
stickWidget->setIcon(QIcon::fromTheme(QString::fromUtf8("games-config-options")));
connect(stickWidget, SIGNAL(clicked()), this, SLOT(showStickDialog()));
addWidget(stickWidget, 1, 1);
button = stickButtons->value(JoyControlStick::StickRight);
rightButton = new JoyControlStickButtonPushButton(button, displayNames, parentWidget());
pushbutton = rightButton;
connect(pushbutton, SIGNAL(clicked()), this, SLOT(openStickButtonDialog()));
button->establishPropertyUpdatedConnections();
connect(button, SIGNAL(slotsChanged()), this, SLOT(propogateSlotsChanged()));
addWidget(pushbutton, 1, 2);
button = stickButtons->value(JoyControlStick::StickLeftDown);
downLeftButton = new JoyControlStickButtonPushButton(button, displayNames, parentWidget());
pushbutton = downLeftButton;
connect(pushbutton, SIGNAL(clicked()), this, SLOT(openStickButtonDialog()));
button->establishPropertyUpdatedConnections();
connect(button, SIGNAL(slotsChanged()), this, SLOT(propogateSlotsChanged()));
addWidget(pushbutton, 2, 0);
button = stickButtons->value(JoyControlStick::StickDown);
downButton = new JoyControlStickButtonPushButton(button, displayNames, parentWidget());
pushbutton = downButton;
connect(pushbutton, SIGNAL(clicked()), this, SLOT(openStickButtonDialog()));
button->establishPropertyUpdatedConnections();
connect(button, SIGNAL(slotsChanged()), this, SLOT(propogateSlotsChanged()));
addWidget(pushbutton, 2, 1);
button = stickButtons->value(JoyControlStick::StickRightDown);
downRightButton = new JoyControlStickButtonPushButton(button, displayNames, parentWidget());
pushbutton = downRightButton;
connect(pushbutton, SIGNAL(clicked()), this, SLOT(openStickButtonDialog()));
button->establishPropertyUpdatedConnections();
connect(button, SIGNAL(slotsChanged()), this, SLOT(propogateSlotsChanged()));
addWidget(pushbutton, 2, 2);
}
void StickPushButtonGroup::changeButtonLayout()
{
if (stick->getJoyMode() == JoyControlStick::StandardMode ||
stick->getJoyMode() == JoyControlStick::EightWayMode ||
stick->getJoyMode() == JoyControlStick::FourWayCardinal)
{
upButton->setVisible(true);
downButton->setVisible(true);
leftButton->setVisible(true);
rightButton->setVisible(true);
}
else
{
upButton->setVisible(false);
downButton->setVisible(false);
leftButton->setVisible(false);
rightButton->setVisible(false);
}
if (stick->getJoyMode() == JoyControlStick::EightWayMode ||
stick->getJoyMode() == JoyControlStick::FourWayDiagonal)
{
upLeftButton->setVisible(true);
upRightButton->setVisible(true);
downLeftButton->setVisible(true);
downRightButton->setVisible(true);
}
else
{
upLeftButton->setVisible(false);
upRightButton->setVisible(false);
downLeftButton->setVisible(false);
downRightButton->setVisible(false);
}
}
void StickPushButtonGroup::propogateSlotsChanged()
{
emit buttonSlotChanged();
}
JoyControlStick* StickPushButtonGroup::getStick()
{
return stick;
}
void StickPushButtonGroup::openStickButtonDialog()
{
JoyControlStickButtonPushButton *pushbutton = static_cast<JoyControlStickButtonPushButton*>(sender());
ButtonEditDialog *dialog = new ButtonEditDialog(pushbutton->getButton(), parentWidget());
dialog->show();
}
void StickPushButtonGroup::showStickDialog()
{
JoyControlStickEditDialog *dialog = new JoyControlStickEditDialog(stick, parentWidget());
dialog->show();
}
void StickPushButtonGroup::toggleNameDisplay()
{
displayNames = !displayNames;
upButton->toggleNameDisplay();
downButton->toggleNameDisplay();
leftButton->toggleNameDisplay();
rightButton->toggleNameDisplay();
upLeftButton->toggleNameDisplay();
upRightButton->toggleNameDisplay();
downLeftButton->toggleNameDisplay();
downRightButton->toggleNameDisplay();
stickWidget->toggleNameDisplay();
}
``` | /content/code_sandbox/src/stickpushbuttongroup.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,553 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef GAMECONTROLLERMAPPINGDIALOG_H
#define GAMECONTROLLERMAPPINGDIALOG_H
#include <QDialog>
#include <QHash>
#include <QList>
#include <QAbstractButton>
#include "uihelpers/gamecontrollermappingdialoghelper.h"
#include "inputdevice.h"
#include "gamecontroller/gamecontroller.h"
#include "antimicrosettings.h"
namespace Ui {
class GameControllerMappingDialog;
}
class GameControllerMappingDialog : public QDialog
{
Q_OBJECT
public:
explicit GameControllerMappingDialog(InputDevice *device, AntiMicroSettings *settings, QWidget *parent = 0);
~GameControllerMappingDialog();
static QHash<int, QString> tempaliases;
static QHash<SDL_GameControllerButton, int> buttonPlacement;
static QHash<SDL_GameControllerAxis, int> axisPlacement;
protected:
void populateGameControllerBindings(GameController *controller);
void removeControllerMapping();
void enableDeviceConnections();
void disableDeviceConnections();
QString generateSDLMappingString();
void populateAxisDeadZoneComboBox();
QString bindingString(SDL_GameControllerButtonBind bind);
QList<QVariant> bindingValues(SDL_GameControllerButtonBind bind);
InputDevice *device;
AntiMicroSettings *settings;
unsigned int buttonGrabs;
QList<int> eventTriggerAxes;
QList<int> originalAxesDeadZones;
GameControllerMappingDialogHelper helper;
int currentDeadZoneValue;
bool usingGameController;
private:
Ui::GameControllerMappingDialog *ui;
signals:
void mappingUpdate(QString mapping, InputDevice *device);
private slots:
void buttonAssign(int buttonindex);
void axisAssign(int axis, int value);
void dpadAssign(int dpad, int buttonindex);
void buttonRelease(int buttonindex);
void axisRelease(int axis, int value);
void dpadRelease(int dpad, int buttonindex);
void saveChanges();
void discardMapping(QAbstractButton *button);
void enableButtonEvents(int code);
void obliterate();
void changeButtonDisplay();
void changeAxisDeadZone(int index);
void updateLastAxisLineEdit(int value);
void updateLastAxisLineEditRaw(int index, int value);
};
#endif // GAMECONTROLLERMAPPINGDIALOG_H
``` | /content/code_sandbox/src/gamecontrollermappingdialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 562 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include "qtkeymapperbase.h"
const unsigned int QtKeyMapperBase::customQtKeyPrefix;
const unsigned int QtKeyMapperBase::customKeyPrefix;
const unsigned int QtKeyMapperBase::nativeKeyPrefix;
QtKeyMapperBase::QtKeyMapperBase(QObject *parent) :
QObject(parent)
{
}
unsigned int QtKeyMapperBase::returnQtKey(unsigned int key, unsigned int scancode)
{
Q_UNUSED(scancode);
return virtualKeyToQtKey.value(key);
}
unsigned int QtKeyMapperBase::returnVirtualKey(unsigned int qkey)
{
return qtKeyToVirtualKey.value(qkey);
}
bool QtKeyMapperBase::isModifier(unsigned int qkey)
{
bool modifier = false;
unsigned int qtKeyValue = qkey & 0x0FFFFFFF;
if (qtKeyValue == Qt::Key_Shift)
{
modifier = true;
}
else if (qtKeyValue == Qt::Key_Control)
{
modifier = true;
}
else if (qtKeyValue == Qt::Key_Alt)
{
modifier = true;
}
else if (qtKeyValue == Qt::Key_Meta)
{
modifier = true;
}
return modifier;
}
QtKeyMapperBase::charKeyInformation QtKeyMapperBase::getCharKeyInformation(QChar value)
{
charKeyInformation temp;
temp.virtualkey = 0;
temp.modifiers = Qt::NoModifier;
if (virtualkeyToCharKeyInformation.contains(value.unicode()))
{
temp = virtualkeyToCharKeyInformation.value(value.unicode());
}
return temp;
}
/**
* @brief Obtain identifier string for key mapper.
* @return Identifier string.
*/
QString QtKeyMapperBase::getIdentifier()
{
return identifier;
}
``` | /content/code_sandbox/src/qtkeymapperbase.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 468 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef JOYCONTROLSTICKPUSHBUTTON_H
#define JOYCONTROLSTICKPUSHBUTTON_H
#include <QPoint>
#include "flashbuttonwidget.h"
#include "joycontrolstick.h"
class JoyControlStickPushButton : public FlashButtonWidget
{
Q_OBJECT
public:
explicit JoyControlStickPushButton(JoyControlStick *stick, bool displayNames, QWidget *parent = 0);
JoyControlStick* getStick();
void tryFlash();
protected:
virtual QString generateLabel();
JoyControlStick *stick;
signals:
public slots:
void disableFlashes();
void enableFlashes();
private slots:
void showContextMenu(const QPoint &point);
};
#endif // JOYCONTROLSTICKPUSHBUTTON_H
``` | /content/code_sandbox/src/joycontrolstickpushbutton.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 250 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include "joykeyrepeathelper.h"
#include "event.h"
JoyKeyRepeatHelper::JoyKeyRepeatHelper(QObject *parent) :
QObject(parent)
{
lastActiveKey = 0;
keyRepeatTimer.setParent(this);
connect(&keyRepeatTimer, SIGNAL(timeout()), this, SLOT(repeatKeysEvent()));
}
QTimer* JoyKeyRepeatHelper::getRepeatTimer()
{
return &keyRepeatTimer;
}
void JoyKeyRepeatHelper::repeatKeysEvent()
{
if (lastActiveKey)
{
JoyButtonSlot *slot = lastActiveKey;
// Send another key press to fake a key repeat
sendevent(slot);
keyRepeatTimer.start(keyRepeatRate);
}
else
{
keyRepeatTimer.stop();
}
}
void JoyKeyRepeatHelper::setLastActiveKey(JoyButtonSlot *slot)
{
lastActiveKey = slot;
}
JoyButtonSlot* JoyKeyRepeatHelper::getLastActiveKey()
{
return lastActiveKey;
}
/*void JoyKeyRepeatHelper::setKeyRepeatDelay(unsigned int repeatDelay)
{
if (repeatDelay > 0)
{
keyRepeatDelay = repeatDelay;
}
}
unsigned int JoyKeyRepeatHelper::getKeyRepeatDelay()
{
return keyRepeatDelay;
}
*/
void JoyKeyRepeatHelper::setKeyRepeatRate(unsigned int repeatRate)
{
if (repeatRate > 0)
{
keyRepeatRate = repeatRate;
}
}
unsigned int JoyKeyRepeatHelper::getKeyRepeatRate()
{
return keyRepeatRate;
}
``` | /content/code_sandbox/src/joykeyrepeathelper.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 421 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef SIMPLEKEYGRABBERBUTTON_H
#define SIMPLEKEYGRABBERBUTTON_H
#include <QPushButton>
#include <QKeyEvent>
#include <QMouseEvent>
#include <QMetaType>
#include "joybuttonslot.h"
class SimpleKeyGrabberButton : public QPushButton
{
Q_OBJECT
public:
explicit SimpleKeyGrabberButton(QWidget *parent = 0);
void setValue(int value, unsigned int alias, JoyButtonSlot::JoySlotInputAction mode=JoyButtonSlot::JoyKeyboard);
void setValue(int value, JoyButtonSlot::JoySlotInputAction mode=JoyButtonSlot::JoyKeyboard);
void setValue(QString value, JoyButtonSlot::JoySlotInputAction mode=JoyButtonSlot::JoyLoadProfile);
JoyButtonSlot* getValue();
bool isEdited();
bool isGrabbing();
protected:
virtual void keyPressEvent(QKeyEvent *event);
virtual bool eventFilter(QObject *obj, QEvent *event);
bool grabNextAction;
bool grabbingWheel;
bool edited;
JoyButtonSlot buttonslot;
signals:
void buttonCodeChanged(int value);
public slots:
void refreshButtonLabel();
protected slots:
};
Q_DECLARE_METATYPE(SimpleKeyGrabberButton*)
#endif // SIMPLEKEYGRABBERBUTTON_H
``` | /content/code_sandbox/src/simplekeygrabberbutton.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 357 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef JOYTABWIDGETCONTAINER_H
#define JOYTABWIDGETCONTAINER_H
#include <QTabWidget>
#include "joystick.h"
#include "joytabwidget.h"
class JoyTabWidgetContainer : public QTabWidget
{
Q_OBJECT
public:
explicit JoyTabWidgetContainer(QWidget *parent = 0);
int addTab(QWidget *widget, const QString &string);
int addTab(JoyTabWidget *widget, const QString &string);
protected:
signals:
public slots:
void disableFlashes(InputDevice *joystick);
void enableFlashes(InputDevice *joystick);
private slots:
void flash();
void unflash();
void unflashAll();
void unflashTab(JoyTabWidget *tabWidget);
};
#endif // JOYTABWIDGETCONTAINER_H
``` | /content/code_sandbox/src/joytabwidgetcontainer.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 267 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef JOYCONTROLSTICKBUTTONPUSHBUTTON_H
#define JOYCONTROLSTICKBUTTONPUSHBUTTON_H
#include <QPoint>
#include "flashbuttonwidget.h"
#include "joybuttontypes/joycontrolstickbutton.h"
class JoyControlStickButtonPushButton : public FlashButtonWidget
{
Q_OBJECT
Q_PROPERTY(bool isflashing READ isButtonFlashing)
public:
explicit JoyControlStickButtonPushButton(JoyControlStickButton *button, bool displayNames, QWidget *parent = 0);
JoyControlStickButton* getButton();
void setButton(JoyControlStickButton *button);
void tryFlash();
protected:
virtual QString generateLabel();
JoyControlStickButton *button;
signals:
public slots:
void disableFlashes();
void enableFlashes();
private slots:
void showContextMenu(const QPoint &point);
};
#endif // JOYCONTROLSTICKBUTTONPUSHBUTTON_H
``` | /content/code_sandbox/src/joycontrolstickbuttonpushbutton.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 289 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include "dpadpushbutton.h"
#include "dpadcontextmenu.h"
DPadPushButton::DPadPushButton(JoyDPad *dpad, bool displayNames, QWidget *parent) :
FlashButtonWidget(displayNames, parent)
{
this->dpad = dpad;
refreshLabel();
enableFlashes();
tryFlash();
this->setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showContextMenu(const QPoint&)));
connect(dpad, SIGNAL(dpadNameChanged()), this, SLOT(refreshLabel()));
}
JoyDPad* DPadPushButton::getDPad()
{
return dpad;
}
QString DPadPushButton::generateLabel()
{
QString temp;
if (!dpad->getDpadName().isEmpty())
{
temp.append(dpad->getName(false, displayNames));
}
else
{
temp.append(dpad->getName());
}
return temp;
}
void DPadPushButton::disableFlashes()
{
disconnect(dpad, SIGNAL(active(int)), this, SLOT(flash()));
disconnect(dpad, SIGNAL(released(int)), this, SLOT(unflash()));
this->unflash();
}
void DPadPushButton::enableFlashes()
{
connect(dpad, SIGNAL(active(int)), this, SLOT(flash()), Qt::QueuedConnection);
connect(dpad, SIGNAL(released(int)), this, SLOT(unflash()), Qt::QueuedConnection);
}
void DPadPushButton::showContextMenu(const QPoint &point)
{
QPoint globalPos = this->mapToGlobal(point);
DPadContextMenu *contextMenu = new DPadContextMenu(dpad, this);
contextMenu->buildMenu();
contextMenu->popup(globalPos);
}
void DPadPushButton::tryFlash()
{
if (dpad->getCurrentDirection() != static_cast<int>(JoyDPadButton::DpadCentered))
{
flash();
}
}
``` | /content/code_sandbox/src/dpadpushbutton.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 501 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef DPADEDITDIALOG_H
#define DPADEDITDIALOG_H
#include <QDialog>
#include "joydpad.h"
#include "uihelpers/dpadeditdialoghelper.h"
namespace Ui {
class DPadEditDialog;
}
class DPadEditDialog : public QDialog
{
Q_OBJECT
public:
explicit DPadEditDialog(JoyDPad *dpad, QWidget *parent = 0);
~DPadEditDialog();
protected:
void selectCurrentPreset();
JoyDPad *dpad;
DPadEditDialogHelper helper;
private:
Ui::DPadEditDialog *ui;
private slots:
void implementPresets(int index);
void implementModes(int index);
void openMouseSettingsDialog();
void enableMouseSettingButton();
void updateWindowTitleDPadName();
void updateDPadDelaySpinBox(int value);
void updateDPadDelaySlider(double value);
};
#endif // DPADEDITDIALOG_H
``` | /content/code_sandbox/src/dpadeditdialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 299 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include <QtGlobal>
#ifdef Q_OS_WIN
#ifdef USE_SDL_2
#include <SDL2/SDL.h>
#else
#include <SDL/SDL.h>
#endif
#undef main
#endif
#include <QApplication>
#include <QMainWindow>
#include <QMap>
#include <QMapIterator>
#include <QDir>
//#include <QDebug>
#include <QTranslator>
#include <QLibraryInfo>
#include <QTextStream>
#include <QLocalSocket>
#include <QSettings>
#include <QThread>
#ifdef Q_OS_WIN
#include <QStyle>
#include <QStyleFactory>
#include "winextras.h"
#endif
#include "inputdevice.h"
#include "joybuttonslot.h"
#include "inputdaemon.h"
#include "common.h"
#include "commandlineutility.h"
#include "mainwindow.h"
#include "autoprofileinfo.h"
#include "localantimicroserver.h"
#include "antimicrosettings.h"
#include "applaunchhelper.h"
#include "eventhandlerfactory.h"
#ifndef Q_OS_WIN
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef WITH_X11
#include "x11extras.h"
#endif
#endif
#include "antkeymapper.h"
#include "logger.h"
#ifndef Q_OS_WIN
static void termSignalTermHandler(int signal)
{
Q_UNUSED(signal);
qApp->exit(0);
}
static void termSignalIntHandler(int signal)
{
Q_UNUSED(signal);
qApp->exit(0);
}
#endif
void deleteInputDevices(QMap<SDL_JoystickID, InputDevice*> *joysticks)
{
QMapIterator<SDL_JoystickID, InputDevice*> iter(*joysticks);
while (iter.hasNext())
{
InputDevice *joystick = iter.next().value();
if (joystick)
{
delete joystick;
joystick = 0;
}
}
joysticks->clear();
}
int main(int argc, char *argv[])
{
qRegisterMetaType<JoyButtonSlot*>();
qRegisterMetaType<SetJoystick*>();
qRegisterMetaType<InputDevice*>();
qRegisterMetaType<AutoProfileInfo*>();
qRegisterMetaType<QThread*>();
qRegisterMetaType<SDL_JoystickID>("SDL_JoystickID");
qRegisterMetaType<JoyButtonSlot::JoySlotInputAction>("JoyButtonSlot::JoySlotInputAction");
#if defined(Q_OS_UNIX) && defined(WITH_X11)
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
XInitThreads();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
#endif
#endif
QFile logFile;
QTextStream logFileStream;
QTextStream outstream(stdout);
QTextStream errorstream(stderr);
// If running Win version, check if an explicit style
// was defined on the command-line. If so, make a note
// of it.
#ifdef Q_OS_WIN
bool styleChangeFound = false;
for (int i=0; i < argc && !styleChangeFound; i++)
{
char *tempchrstr = argv[i];
QString temp = QString::fromUtf8(tempchrstr);
if (temp == "-style")
{
styleChangeFound = true;
}
}
#endif
CommandLineUtility cmdutility;
QStringList cmdarguments = PadderCommon::arguments(argc, argv);
cmdarguments.removeFirst();
cmdutility.parseArguments(cmdarguments);
Logger appLogger(&outstream, &errorstream);
if (cmdutility.hasError())
{
appLogger.LogError(cmdutility.getErrorText(), true, true);
return 1;
}
else if (cmdutility.isHelpRequested())
{
appLogger.LogInfo(cmdutility.generateHelpString(), false, true);
return 0;
}
else if (cmdutility.isVersionRequested())
{
appLogger.LogInfo(cmdutility.generateVersionString(), true, true);
return 0;
}
// If a log level wasn't specified at the command-line, then use a default.
if( cmdutility.getCurrentLogLevel() == Logger::LOG_NONE ) {
appLogger.setLogLevel( Logger::LOG_WARNING );
} else if (cmdutility.getCurrentLogLevel() != appLogger.getCurrentLogLevel())
{
appLogger.setLogLevel(cmdutility.getCurrentLogLevel());
}
if( !cmdutility.getCurrentLogFile().isEmpty() ) {
appLogger.setCurrentLogFile( cmdutility.getCurrentLogFile() );
appLogger.setCurrentErrorStream(NULL);
}
Q_INIT_RESOURCE(resources);
QApplication a(argc, argv);
#if defined(Q_OS_WIN) && defined(WIN_PORTABLE_PACKAGE)
// If in portable mode, make sure the current directory is the same as the
// config directory. This is to ensure that all relative paths resolve
// correctly when loading on startup.
QDir::setCurrent( PadderCommon::configPath() );
#endif
QDir configDir(PadderCommon::configPath());
if (!configDir.exists())
{
configDir.mkpath(PadderCommon::configPath());
}
QMap<SDL_JoystickID, InputDevice*> *joysticks = new QMap<SDL_JoystickID, InputDevice*>();
QThread *inputEventThread = 0;
// Cross-platform way of performing IPC. Currently,
// only establish a connection and then disconnect.
// In the future, there might be a reason to actually send
// messages to the QLocalServer.
QLocalSocket socket;
socket.connectToServer(PadderCommon::localSocketKey);
socket.waitForConnected(1000);
if (socket.state() == QLocalSocket::ConnectedState)
{
// An instance of this program is already running.
// Save app config and exit.
AntiMicroSettings settings(PadderCommon::configFilePath(), QSettings::IniFormat);
// Update log info based on config values
if( cmdutility.getCurrentLogLevel() == Logger::LOG_NONE &&
settings.contains("LogLevel")) {
appLogger.setLogLevel( (Logger::LogLevel) settings.value("LogLevel").toInt() );
}
if( cmdutility.getCurrentLogFile().isEmpty() &&
settings.contains("LogFile")) {
appLogger.setCurrentLogFile( settings.value("LogFile").toString() );
appLogger.setCurrentErrorStream(NULL);
}
InputDaemon *joypad_worker = new InputDaemon(joysticks, &settings, false);
MainWindow w(joysticks, &cmdutility, &settings, false);
w.fillButtons();
w.alterConfigFromSettings();
if (!cmdutility.hasError() &&
(cmdutility.hasProfile() || cmdutility.hasProfileInOptions()))
{
w.saveAppConfig();
}
else if (!cmdutility.hasError() && cmdutility.isUnloadRequested())
{
w.saveAppConfig();
}
w.removeJoyTabs();
QObject::connect(&a, SIGNAL(aboutToQuit()), joypad_worker, SLOT(quit()));
QTimer::singleShot(50, &a, SLOT(quit()));
int result = a.exec();
settings.sync();
socket.disconnectFromServer();
deleteInputDevices(joysticks);
delete joysticks;
joysticks = 0;
delete joypad_worker;
joypad_worker = 0;
return result;
}
LocalAntiMicroServer *localServer = 0;
#ifndef Q_OS_WIN
if (cmdutility.launchAsDaemon())
{
pid_t pid, sid;
//Fork the Parent Process
pid = fork();
if (pid == 0)
{
appLogger.LogInfo(QObject::tr("Daemon launched"), true, true);
localServer = new LocalAntiMicroServer();
localServer->startLocalServer();
}
else if (pid < 0)
{
appLogger.LogError(QObject::tr("Failed to launch daemon"), true, true);
deleteInputDevices(joysticks);
delete joysticks;
joysticks = 0;
exit(EXIT_FAILURE);
}
//We got a good pid, Close the Parent Process
else if (pid > 0)
{
appLogger.LogInfo(QObject::tr("Launching daemon"), true, true);
deleteInputDevices(joysticks);
delete joysticks;
joysticks = 0;
exit(EXIT_SUCCESS);
}
#ifdef WITH_X11
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
if (cmdutility.getDisplayString().isEmpty())
{
X11Extras::getInstance()->syncDisplay();
}
else
{
X11Extras::setCustomDisplay(cmdutility.getDisplayString());
X11Extras::getInstance()->syncDisplay();
if (X11Extras::getInstance()->display() == NULL)
{
appLogger.LogError(QObject::tr("Display string \"%1\" is not valid.")
.arg(cmdutility.getDisplayString()), true, true);
//errorstream << QObject::tr("Display string \"%1\" is not valid.").arg(cmdutility.getDisplayString()) << endl;
deleteInputDevices(joysticks);
delete joysticks;
joysticks = 0;
delete localServer;
localServer = 0;
X11Extras::getInstance()->closeDisplay();
exit(EXIT_FAILURE);
}
}
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
#endif
#endif
//Change File Mask
umask(0);
//Create a new Signature Id for our child
sid = setsid();
if (sid < 0)
{
appLogger.LogError(QObject::tr("Failed to set a signature id for the daemon"), true, true);
//errorstream << QObject::tr("Failed to set a signature id for the daemon") << endl;
deleteInputDevices(joysticks);
delete joysticks;
joysticks = 0;
delete localServer;
localServer = 0;
#ifdef WITH_X11
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
X11Extras::getInstance()->closeDisplay();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
#endif
#endif
exit(EXIT_FAILURE);
}
if ((chdir("/")) < 0)
{
appLogger.LogError(QObject::tr("Failed to change working directory to /"), true, true);
deleteInputDevices(joysticks);
delete joysticks;
joysticks = 0;
delete localServer;
localServer = 0;
#ifdef WITH_X11
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
X11Extras::getInstance()->closeDisplay();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
#endif
#endif
exit(EXIT_FAILURE);
}
//Close Standard File Descriptors
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
}
else
{
localServer = new LocalAntiMicroServer();
localServer->startLocalServer();
#ifdef WITH_X11
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
if (!cmdutility.getDisplayString().isEmpty())
{
X11Extras::getInstance()->syncDisplay(cmdutility.getDisplayString());
if (X11Extras::getInstance()->display() == NULL)
{
appLogger.LogError(QObject::tr("Display string \"%1\" is not valid.")
.arg(cmdutility.getDisplayString()), true, true);
deleteInputDevices(joysticks);
delete joysticks;
joysticks = 0;
delete localServer;
localServer = 0;
X11Extras::getInstance()->closeDisplay();
exit(EXIT_FAILURE);
}
}
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
#endif
#endif
}
#else
localServer = new LocalAntiMicroServer();
localServer->startLocalServer();
#endif
a.setQuitOnLastWindowClosed(false);
//QString defaultStyleName = qApp->style()->objectName();
// If running Win version and no explicit style was
// defined, use the style Fusion by default. I find the
// windowsvista style a tad ugly
#ifdef Q_OS_WIN
if (!styleChangeFound)
{
qApp->setStyle(QStyleFactory::create("Fusion"));
}
QIcon::setThemeName("/");
#endif
AntiMicroSettings *settings = new AntiMicroSettings(PadderCommon::configFilePath(),
QSettings::IniFormat);
settings->importFromCommandLine(cmdutility);
// Update log info based on config values
if( cmdutility.getCurrentLogLevel() == Logger::LOG_NONE &&
settings->contains("LogLevel")) {
appLogger.setLogLevel( (Logger::LogLevel)settings->value("LogLevel").toInt() );
}
if( cmdutility.getCurrentLogFile().isEmpty() &&
settings->contains("LogFile")) {
appLogger.setCurrentLogFile( settings->value("LogFile").toString() );
appLogger.setCurrentErrorStream(NULL);
}
QString targetLang = QLocale::system().name();
if (settings->contains("Language"))
{
targetLang = settings->value("Language").toString();
}
QTranslator qtTranslator;
#if defined(Q_OS_UNIX)
qtTranslator.load(QString("qt_").append(targetLang), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
#elif defined(Q_OS_WIN)
#ifdef QT_DEBUG
qtTranslator.load(QString("qt_").append(targetLang), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
#else
qtTranslator.load(QString("qt_").append(targetLang),
QApplication::applicationDirPath().append("\\share\\qt\\translations"));
#endif
#endif
a.installTranslator(&qtTranslator);
QTranslator myappTranslator;
#if defined(Q_OS_UNIX)
myappTranslator.load(QString("antimicro_").append(targetLang), QApplication::applicationDirPath().append("/../share/antimicro/translations"));
#elif defined(Q_OS_WIN)
myappTranslator.load(QString("antimicro_").append(targetLang), QApplication::applicationDirPath().append("\\share\\antimicro\\translations"));
#endif
a.installTranslator(&myappTranslator);
#ifndef Q_OS_WIN
// Have program handle SIGTERM
struct sigaction termaction;
termaction.sa_handler = &termSignalTermHandler;
sigemptyset(&termaction.sa_mask);
termaction.sa_flags = 0;
sigaction(SIGTERM, &termaction, 0);
// Have program handle SIGINT
struct sigaction termint;
termint.sa_handler = &termSignalIntHandler;
sigemptyset(&termint.sa_mask);
termint.sa_flags = 0;
sigaction(SIGINT, &termint, 0);
#endif
if (cmdutility.shouldListControllers())
{
InputDaemon *joypad_worker = new InputDaemon(joysticks, settings, false);
AppLaunchHelper mainAppHelper(settings, false);
mainAppHelper.printControllerList(joysticks);
joypad_worker->quit();
joypad_worker->deleteJoysticks();
delete joysticks;
joysticks = 0;
delete joypad_worker;
joypad_worker = 0;
delete localServer;
localServer = 0;
#ifdef WITH_X11
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
X11Extras::getInstance()->closeDisplay();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
#endif
#endif
return 0;
}
#ifdef USE_SDL_2
else if (cmdutility.shouldMapController())
{
PadderCommon::mouseHelperObj.initDeskWid();
InputDaemon *joypad_worker = new InputDaemon(joysticks, settings);
inputEventThread = new QThread();
MainWindow *w = new MainWindow(joysticks, &cmdutility, settings);
QObject::connect(&a, SIGNAL(aboutToQuit()), w, SLOT(removeJoyTabs()));
QObject::connect(&a, SIGNAL(aboutToQuit()), joypad_worker, SLOT(quit()));
QObject::connect(&a, SIGNAL(aboutToQuit()), joypad_worker,
SLOT(deleteJoysticks()), Qt::BlockingQueuedConnection);
QObject::connect(&a, SIGNAL(aboutToQuit()), &PadderCommon::mouseHelperObj,
SLOT(deleteDeskWid()), Qt::DirectConnection);
QObject::connect(&a, SIGNAL(aboutToQuit()), joypad_worker, SLOT(deleteLater()),
Qt::BlockingQueuedConnection);
//JoyButton::establishMouseTimerConnections();
w->makeJoystickTabs();
QTimer::singleShot(0, w, SLOT(controllerMapOpening()));
joypad_worker->startWorker();
joypad_worker->moveToThread(inputEventThread);
PadderCommon::mouseHelperObj.moveToThread(inputEventThread);
inputEventThread->start(QThread::HighPriority);
int app_result = a.exec();
// Log any remaining messages if they exist.
appLogger.Log();
inputEventThread->quit();
inputEventThread->wait();
delete joysticks;
joysticks = 0;
//delete joypad_worker;
joypad_worker = 0;
delete localServer;
localServer = 0;
delete inputEventThread;
inputEventThread = 0;
#ifdef WITH_X11
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
X11Extras::getInstance()->closeDisplay();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
#endif
#endif
delete w;
w = 0;
return app_result;
}
#endif
bool status = true;
QString eventGeneratorIdentifier;
AntKeyMapper *keyMapper = 0;
EventHandlerFactory *factory = EventHandlerFactory::getInstance(cmdutility.getEventGenerator());
if (!factory)
{
status = false;
}
else
{
eventGeneratorIdentifier = factory->handler()->getIdentifier();
keyMapper = AntKeyMapper::getInstance(eventGeneratorIdentifier);
status = factory->handler()->init();
factory->handler()->printPostMessages();
}
#if (defined(Q_OS_UNIX) && defined(WITH_UINPUT) && defined(WITH_XTEST)) || \
defined(Q_OS_WIN)
// Use fallback event handler.
if (!status && cmdutility.getEventGenerator() != EventHandlerFactory::fallBackIdentifier())
{
QString eventDisplayName = EventHandlerFactory::handlerDisplayName(
EventHandlerFactory::fallBackIdentifier());
appLogger.LogInfo(QObject::tr("Attempting to use fallback option %1 for event generation.")
.arg(eventDisplayName));
if (keyMapper)
{
keyMapper->deleteInstance();
keyMapper = 0;
}
factory->deleteInstance();
factory = EventHandlerFactory::getInstance(EventHandlerFactory::fallBackIdentifier());
if (!factory)
{
status = false;
}
else
{
eventGeneratorIdentifier = factory->handler()->getIdentifier();
keyMapper = AntKeyMapper::getInstance(eventGeneratorIdentifier);
status = factory->handler()->init();
factory->handler()->printPostMessages();
}
}
#endif
if (!status)
{
appLogger.LogError(QObject::tr("Failed to open event generator. Exiting."));
appLogger.Log();
deleteInputDevices(joysticks);
delete joysticks;
joysticks = 0;
delete localServer;
localServer = 0;
if (keyMapper)
{
keyMapper->deleteInstance();
keyMapper = 0;
}
#if defined(Q_OS_UNIX) && defined(WITH_X11)
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
X11Extras::getInstance()->closeDisplay();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
#endif
#endif
return EXIT_FAILURE;
}
else
{
appLogger.LogInfo(QObject::tr("Using %1 as the event generator.")
.arg(factory->handler()->getName()));
}
PadderCommon::mouseHelperObj.initDeskWid();
InputDaemon *joypad_worker = new InputDaemon(joysticks, settings);
inputEventThread = new QThread();
MainWindow *w = new MainWindow(joysticks, &cmdutility, settings);
w->setAppTranslator(&qtTranslator);
w->setTranslator(&myappTranslator);
AppLaunchHelper mainAppHelper(settings, w->getGraphicalStatus());
QObject::connect(w, SIGNAL(joystickRefreshRequested()), joypad_worker, SLOT(refresh()));
QObject::connect(joypad_worker, SIGNAL(joystickRefreshed(InputDevice*)),
w, SLOT(fillButtons(InputDevice*)));
QObject::connect(joypad_worker,
SIGNAL(joysticksRefreshed(QMap<SDL_JoystickID, InputDevice*>*)),
w, SLOT(fillButtons(QMap<SDL_JoystickID, InputDevice*>*)));
QObject::connect(&a, SIGNAL(aboutToQuit()), localServer, SLOT(close()));
QObject::connect(&a, SIGNAL(aboutToQuit()), w, SLOT(saveAppConfig()));
QObject::connect(&a, SIGNAL(aboutToQuit()), w, SLOT(removeJoyTabs()));
QObject::connect(&a, SIGNAL(aboutToQuit()), &mainAppHelper, SLOT(revertMouseThread()));
QObject::connect(&a, SIGNAL(aboutToQuit()), joypad_worker, SLOT(quit()));
QObject::connect(&a, SIGNAL(aboutToQuit()), joypad_worker, SLOT(deleteJoysticks()));
QObject::connect(&a, SIGNAL(aboutToQuit()), joypad_worker, SLOT(deleteLater()));
QObject::connect(&a, SIGNAL(aboutToQuit()), &PadderCommon::mouseHelperObj, SLOT(deleteDeskWid()),
Qt::DirectConnection);
#ifdef Q_OS_WIN
QObject::connect(&a, SIGNAL(aboutToQuit()), &mainAppHelper, SLOT(appQuitPointerPrecision()));
#endif
QObject::connect(localServer, SIGNAL(clientdisconnect()), w, SLOT(handleInstanceDisconnect()));
#ifdef USE_SDL_2
QObject::connect(w, SIGNAL(mappingUpdated(QString,InputDevice*)),
joypad_worker, SLOT(refreshMapping(QString,InputDevice*)));
QObject::connect(joypad_worker, SIGNAL(deviceUpdated(int,InputDevice*)),
w, SLOT(testMappingUpdateNow(int,InputDevice*)));
QObject::connect(joypad_worker, SIGNAL(deviceRemoved(SDL_JoystickID)),
w, SLOT(removeJoyTab(SDL_JoystickID)));
QObject::connect(joypad_worker, SIGNAL(deviceAdded(InputDevice*)),
w, SLOT(addJoyTab(InputDevice*)));
#endif
#ifdef Q_OS_WIN
// Raise process priority. Helps reduce timer delays caused by
// the running of other processes.
bool raisedPriority = WinExtras::raiseProcessPriority();
if (!raisedPriority)
{
appLogger.LogInfo(QObject::tr("Could not raise process priority."));
}
#endif
mainAppHelper.initRunMethods();
QTimer::singleShot(0, w, SLOT(fillButtons()));
QTimer::singleShot(0, w, SLOT(alterConfigFromSettings()));
QTimer::singleShot(0, w, SLOT(changeWindowStatus()));
mainAppHelper.changeMouseThread(inputEventThread);
joypad_worker->startWorker();
joypad_worker->moveToThread(inputEventThread);
PadderCommon::mouseHelperObj.moveToThread(inputEventThread);
inputEventThread->start(QThread::HighPriority);
int app_result = a.exec();
// Log any remaining messages if they exist.
appLogger.Log();
appLogger.LogInfo(QObject::tr("Quitting Program"), true, true);
joypad_worker = 0;
delete localServer;
localServer = 0;
inputEventThread->quit();
inputEventThread->wait();
delete inputEventThread;
inputEventThread = 0;
delete joysticks;
joysticks = 0;
AntKeyMapper::getInstance()->deleteInstance();
#if defined(Q_OS_UNIX) && defined(WITH_X11)
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
X11Extras::getInstance()->closeDisplay();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
#endif
#endif
EventHandlerFactory::getInstance()->handler()->cleanup();
EventHandlerFactory::getInstance()->deleteInstance();
delete w;
w = 0;
delete settings;
settings = 0;
return app_result;
}
``` | /content/code_sandbox/src/main.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 5,607 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
//#include <QDebug>
#include "extraprofilesettingsdialog.h"
#include "ui_extraprofilesettingsdialog.h"
ExtraProfileSettingsDialog::ExtraProfileSettingsDialog(InputDevice *device, QWidget *parent) :
QDialog(parent),
ui(new Ui::ExtraProfileSettingsDialog)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
this->device = device;
ui->pressValueLabel->setText(QString::number(0.10, 'g', 3).append("").append(tr("s")));
if (device->getDeviceKeyPressTime() > 0)
{
int temppress = device->getDeviceKeyPressTime();
ui->keyPressHorizontalSlider->setValue(device->getDeviceKeyPressTime() / 10);
ui->pressValueLabel->setText(QString::number(temppress / 1000.0, 'g', 3).append("").append(tr("s")));
}
if (!device->getProfileName().isEmpty())
{
ui->profileNameLineEdit->setText(device->getProfileName());
}
connect(ui->keyPressHorizontalSlider, SIGNAL(valueChanged(int)), this, SLOT(changeDeviceKeyPress(int)));
connect(ui->profileNameLineEdit, SIGNAL(textChanged(QString)), device, SLOT(setProfileName(QString)));
}
ExtraProfileSettingsDialog::~ExtraProfileSettingsDialog()
{
delete ui;
}
void ExtraProfileSettingsDialog::changeDeviceKeyPress(int value)
{
int temppress = value * 10;
device->setDeviceKeyPressTime(temppress);
ui->pressValueLabel->setText(QString::number(temppress / 1000.0, 'g', 3).append("").append(tr("s")));
}
``` | /content/code_sandbox/src/extraprofilesettingsdialog.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 455 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef ADVANCESTICKASSIGNMENTDIALOG_H
#define ADVANCESTICKASSIGNMENTDIALOG_H
#include <QDialog>
#include "joystick.h"
namespace Ui {
class AdvanceStickAssignmentDialog;
}
class AdvanceStickAssignmentDialog : public QDialog
{
Q_OBJECT
public:
explicit AdvanceStickAssignmentDialog(Joystick *joystick, QWidget *parent = 0);
~AdvanceStickAssignmentDialog();
protected:
Joystick *joystick;
signals:
void stickConfigurationChanged();
void vdpadConfigurationChanged();
private:
Ui::AdvanceStickAssignmentDialog *ui;
private slots:
void refreshStickConfiguration();
void refreshVDPadConfiguration();
void checkForAxisAssignmentStickOne();
void checkForAxisAssignmentStickTwo();
void changeStateStickOneWidgets(bool enabled);
void changeStateStickTwoWidgets(bool enabled);
void changeStateVDPadWidgets(bool enabled);
void populateDPadComboBoxes();
void changeVDPadUpButton(int index);
void changeVDPadDownButton(int index);
void changeVDPadLeftButton(int index);
void changeVDPadRightButton(int index);
void disableVDPadComboBoxes();
void enableVDPadComboBoxes();
void openQuickAssignDialogStick1();
void openQuickAssignDialogStick2();
void quickAssignStick1Axis1();
void quickAssignStick1Axis2();
void quickAssignStick2Axis1();
void quickAssignStick2Axis2();
void openAssignVDPadUp();
void openAssignVDPadDown();
void openAssignVDPadLeft();
void openAssignVDPadRight();
void quickAssignVDPadUp();
void quickAssignVDPadDown();
void quickAssignVDPadLeft();
void quickAssignVDPadRight();
void reenableButtonEvents();
};
#endif // ADVANCESTICKASSIGNMENTDIALOG_H
``` | /content/code_sandbox/src/advancestickassignmentdialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 504 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef VDPAD_H
#define VDPAD_H
#include "joydpad.h"
#include "joybutton.h"
class VDPad : public JoyDPad
{
Q_OBJECT
public:
explicit VDPad(int index, int originset, SetJoystick *parentSet, QObject *parent = 0);
explicit VDPad(JoyButton *upButton, JoyButton *downButton, JoyButton *leftButton, JoyButton *rightButton,
int index, int originset, SetJoystick *parentSet, QObject *parent = 0);
~VDPad();
void joyEvent(bool pressed, bool ignoresets=false);
void addVButton(JoyDPadButton::JoyDPadDirections direction, JoyButton *button);
void removeVButton(JoyDPadButton::JoyDPadDirections direction);
void removeVButton(JoyButton *button);
JoyButton* getVButton(JoyDPadButton::JoyDPadDirections direction);
bool isEmpty();
virtual QString getName(bool forceFullFormat=false, bool displayName=false);
virtual QString getXmlName();
void queueJoyEvent(bool ignoresets=false);
bool hasPendingEvent();
void clearPendingEvent();
static const QString xmlName;
protected:
JoyButton *upButton;
JoyButton *downButton;
JoyButton *leftButton;
JoyButton *rightButton;
bool pendingVDPadEvent;
signals:
public slots:
void activatePendingEvent();
};
#endif // VDPAD_H
``` | /content/code_sandbox/src/vdpad.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 414 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef COMMANDLINEPARSER_H
#define COMMANDLINEPARSER_H
#include <QObject>
#include <QStringList>
#include <QRegExp>
#include <QList>
#include "logger.h"
class ControllerOptionsInfo {
public:
ControllerOptionsInfo()
{
controllerNumber = 0;
startSetNumber = 0;
unloadProfile = false;
}
bool hasProfile()
{
return !profileLocation.isEmpty();
}
QString getProfileLocation()
{
return profileLocation;
}
void setProfileLocation(QString location)
{
profileLocation = location;
}
bool hasControllerNumber()
{
return (controllerNumber > 0);
}
unsigned int getControllerNumber()
{
return controllerNumber;
}
void setControllerNumber(unsigned int temp)
{
controllerNumber = temp;
}
bool hasControllerID()
{
return !controllerIDString.isEmpty();
}
QString getControllerID()
{
return controllerIDString;
}
void setControllerID(QString temp)
{
controllerIDString = temp;
}
bool isUnloadRequested()
{
return unloadProfile;
}
void setUnloadRequest(bool status)
{
unloadProfile = status;
}
unsigned int getStartSetNumber()
{
return startSetNumber;
}
unsigned int getJoyStartSetNumber()
{
return startSetNumber - 1;
}
void setStartSetNumber(unsigned int temp)
{
if (temp >= 1 && temp <= 8)
{
startSetNumber = temp;
}
}
protected:
QString profileLocation;
unsigned int controllerNumber;
QString controllerIDString;
unsigned int startSetNumber;
bool unloadProfile;
};
class CommandLineUtility : public QObject
{
Q_OBJECT
public:
explicit CommandLineUtility(QObject *parent = 0);
void parseArguments(QStringList &arguments);
bool isLaunchInTrayEnabled();
bool isHelpRequested();
bool isVersionRequested();
bool isTrayHidden();
bool hasProfile();
bool hasControllerNumber();
bool hasControllerID();
QString getProfileLocation();
unsigned int getControllerNumber();
QString getControllerID();
bool isHiddenRequested();
bool isUnloadRequested();
bool shouldListControllers();
bool shouldMapController();
unsigned int getStartSetNumber();
unsigned int getJoyStartSetNumber();
QList<unsigned int>* getJoyStartSetNumberList();
QList<ControllerOptionsInfo>* getControllerOptionsList();
bool hasProfileInOptions();
QString getEventGenerator();
#ifdef Q_OS_UNIX
bool launchAsDaemon();
QString getDisplayString();
#endif
void printHelp();
void printVersionString();
QString generateHelpString();
QString generateVersionString();
bool hasError();
Logger::LogLevel getCurrentLogLevel();
QString getCurrentLogFile();
QString getErrorText();
protected:
bool isPossibleCommand(QString temp);
void setErrorMessage(QString temp);
bool launchInTray;
bool helpRequest;
bool versionRequest;
bool hideTrayIcon;
QString profileLocation;
unsigned int controllerNumber;
QString controllerIDString;
bool encounteredError;
bool hiddenRequest;
bool unloadProfile;
unsigned int startSetNumber;
bool daemonMode;
QString displayString;
bool listControllers;
bool mappingController;
QString eventGenerator;
QString errorText;
Logger::LogLevel currentLogLevel;
QString currentLogFile;
unsigned int currentListsIndex;
QList<ControllerOptionsInfo> controllerOptionsList;
static QRegExp trayRegexp;
static QRegExp helpRegexp;
static QRegExp versionRegexp;
static QRegExp noTrayRegexp;
static QRegExp loadProfileRegexp;
static QRegExp loadProfileForControllerRegexp;
static QRegExp hiddenRegexp;
static QRegExp unloadRegexp;
static QRegExp startSetRegexp;
static QRegExp gamepadListRegexp;
static QRegExp mappingRegexp;
static QRegExp qtStyleRegexp;
static QRegExp logLevelRegexp;
static QRegExp logFileRegexp;
static QRegExp eventgenRegexp;
static QRegExp nextRegexp;
static QStringList eventGeneratorsList;
#ifdef Q_OS_UNIX
static QRegExp daemonRegexp;
static QRegExp displayRegexp;
#endif
signals:
public slots:
};
#endif // COMMANDLINEPARSER_H
``` | /content/code_sandbox/src/commandlineutility.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,039 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef AUTOPROFILEWATCHER_H
#define AUTOPROFILEWATCHER_H
#include <QObject>
#include <QTimer>
#include <QHash>
#include <QList>
#include <QSet>
#include "autoprofileinfo.h"
#include "antimicrosettings.h"
class AutoProfileWatcher : public QObject
{
Q_OBJECT
public:
explicit AutoProfileWatcher(AntiMicroSettings *settings, QObject *parent = 0);
void startTimer();
void stopTimer();
QList<AutoProfileInfo*>* getCustomDefaults();
AutoProfileInfo* getDefaultAllProfile();
bool isGUIDLocked(QString guid);
static const int CHECKTIME = 1000; // time in ms
protected:
QString findAppLocation();
void clearProfileAssignments();
QTimer appTimer;
AntiMicroSettings *settings;
// Path, QList<AutoProfileInfo*>
QHash<QString, QList<AutoProfileInfo*> > appProfileAssignments;
// WM_CLASS, QList<AutoProfileInfo*>
QHash<QString, QList<AutoProfileInfo*> > windowClassProfileAssignments;
// WM_NAME, QList<AutoProfileInfo*>
QHash<QString, QList<AutoProfileInfo*> > windowNameProfileAssignments;
// GUID, AutoProfileInfo*
QHash<QString, AutoProfileInfo*> defaultProfileAssignments;
//QList<AutoProfileInfo*> *customDefaults;
AutoProfileInfo *allDefaultInfo;
QString currentApplication;
QString currentAppWindowTitle;
QSet<QString> guidSet;
signals:
void foundApplicableProfile(AutoProfileInfo *info);
public slots:
void syncProfileAssignment();
private slots:
void runAppCheck();
};
#endif // AUTOPROFILEWATCHER_H
``` | /content/code_sandbox/src/autoprofilewatcher.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 464 |
```objective-c
#ifndef WINAPPPROFILETIMERDIALOG_H
#define WINAPPPROFILETIMERDIALOG_H
#include <QDialog>
#include <QTimer>
namespace Ui {
class WinAppProfileTimerDialog;
}
class WinAppProfileTimerDialog : public QDialog
{
Q_OBJECT
public:
explicit WinAppProfileTimerDialog(QWidget *parent = 0);
~WinAppProfileTimerDialog();
protected:
QTimer appTimer;
//slots:
// void
private:
Ui::WinAppProfileTimerDialog *ui;
private slots:
void startTimer();
};
#endif // WINAPPPROFILETIMERDIALOG_H
``` | /content/code_sandbox/src/winappprofiletimerdialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 131 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
//#include <QDebug>
#include <QtGlobal>
#include <QStringList>
#include "antkeymapper.h"
#include "eventhandlerfactory.h"
AntKeyMapper* AntKeyMapper::_instance = 0;
static QStringList buildEventGeneratorList()
{
QStringList temp;
#ifdef Q_OS_WIN
temp.append("sendinput");
#ifdef WITH_VMULTI
temp.append("vmulti");
#endif
#else
#ifdef WITH_XTEST
temp.append("xtest");
#endif
#ifdef WITH_UINPUT
temp.append("uinput");
#endif
#endif
return temp;
}
AntKeyMapper::AntKeyMapper(QString handler, QObject *parent) :
QObject(parent)
{
internalMapper = 0;
#ifdef Q_OS_WIN
#ifdef WITH_VMULTI
if (handler == "vmulti")
{
internalMapper = &vmultiMapper;
nativeKeyMapper = &winMapper;
}
#endif
BACKEND_ELSE_IF (handler == "sendinput")
{
internalMapper = &winMapper;
nativeKeyMapper = 0;
}
#else
#ifdef WITH_XTEST
if (handler == "xtest")
{
internalMapper = &x11Mapper;
nativeKeyMapper = 0;
}
#endif
#ifdef WITH_UINPUT
if (handler == "uinput")
{
internalMapper = &uinputMapper;
#ifdef WITH_XTEST
nativeKeyMapper = &x11Mapper;
#else
nativeKeyMapper = 0;
#endif
}
#endif
#endif
}
AntKeyMapper* AntKeyMapper::getInstance(QString handler)
{
if (!_instance)
{
Q_ASSERT(!handler.isEmpty());
QStringList temp = buildEventGeneratorList();
Q_ASSERT(temp.contains(handler));
_instance = new AntKeyMapper(handler);
}
return _instance;
}
void AntKeyMapper::deleteInstance()
{
if (_instance)
{
delete _instance;
_instance = 0;
}
}
unsigned int AntKeyMapper::returnQtKey(unsigned int key, unsigned int scancode)
{
return internalMapper->returnQtKey(key, scancode);
}
unsigned int AntKeyMapper::returnVirtualKey(unsigned int qkey)
{
return internalMapper->returnVirtualKey(qkey);
}
bool AntKeyMapper::isModifierKey(unsigned int qkey)
{
return internalMapper->isModifier(qkey);
}
QtKeyMapperBase* AntKeyMapper::getNativeKeyMapper()
{
return nativeKeyMapper;
}
QtKeyMapperBase* AntKeyMapper::getKeyMapper()
{
return internalMapper;
}
bool AntKeyMapper::hasNativeKeyMapper()
{
bool result = nativeKeyMapper != 0;
return result;
}
``` | /content/code_sandbox/src/antkeymapper.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 685 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
//#include <QDebug>
#include <QHashIterator>
#include "joydpad.h"
#include "inputdevice.h"
const QString JoyDPad::xmlName = "dpad";
const unsigned int JoyDPad::DEFAULTDPADDELAY = 0;
JoyDPad::JoyDPad(int index, int originset, SetJoystick *parentSet, QObject *parent) :
QObject(parent)
{
this->index = index;
buttons = QHash<int, JoyDPadButton*> ();
activeDiagonalButton = 0;
prevDirection = JoyDPadButton::DpadCentered;
pendingDirection = prevDirection;
this->originset = originset;
currentMode = StandardMode;
this->parentSet = parentSet;
this->dpadDelay = DEFAULTDPADDELAY;
populateButtons();
pendingEvent = false;
pendingEventDirection = prevDirection;
pendingIgnoreSets = false;
directionDelayTimer.setSingleShot(true);
connect(&directionDelayTimer, SIGNAL(timeout()), this, SLOT(dpadDirectionChangeEvent()));
}
JoyDPad::~JoyDPad()
{
QHashIterator<int, JoyDPadButton*> iter(buttons);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
delete button;
button = 0;
}
buttons.clear();
}
JoyDPadButton *JoyDPad::getJoyButton(int index)
{
return buttons.value(index);
}
void JoyDPad::populateButtons()
{
JoyDPadButton* button = new JoyDPadButton (JoyDPadButton::DpadUp, originset, this, parentSet, this);
buttons.insert(JoyDPadButton::DpadUp, button);
button = new JoyDPadButton (JoyDPadButton::DpadDown, originset, this, parentSet, this);
buttons.insert(JoyDPadButton::DpadDown, button);
button = new JoyDPadButton(JoyDPadButton::DpadRight, originset, this, parentSet, this);
buttons.insert(JoyDPadButton::DpadRight, button);
button = new JoyDPadButton(JoyDPadButton::DpadLeft, originset, this, parentSet, this);
buttons.insert(JoyDPadButton::DpadLeft, button);
button = new JoyDPadButton(JoyDPadButton::DpadLeftUp, originset, this, parentSet, this);
buttons.insert(JoyDPadButton::DpadLeftUp, button);
button = new JoyDPadButton(JoyDPadButton::DpadRightUp, originset, this, parentSet, this);
buttons.insert(JoyDPadButton::DpadRightUp, button);
button = new JoyDPadButton(JoyDPadButton::DpadRightDown, originset, this, parentSet, this);
buttons.insert(JoyDPadButton::DpadRightDown, button);
button = new JoyDPadButton(JoyDPadButton::DpadLeftDown, originset, this, parentSet, this);
buttons.insert(JoyDPadButton::DpadLeftDown, button);
}
QString JoyDPad::getName(bool fullForceFormat, bool displayNames)
{
QString label;
if (!dpadName.isEmpty() && displayNames)
{
if (fullForceFormat)
{
label.append(tr("DPad")).append(" ");
}
label.append(dpadName);
}
else if (!defaultDPadName.isEmpty())
{
if (fullForceFormat)
{
label.append(tr("DPad")).append(" ");
}
label.append(defaultDPadName);
}
else
{
label.append(tr("DPad")).append(" ");
label.append(QString::number(getRealJoyNumber()));
}
return label;
}
int JoyDPad::getJoyNumber()
{
return index;
}
int JoyDPad::getIndex()
{
return index;
}
int JoyDPad::getRealJoyNumber()
{
return index + 1;
}
QString JoyDPad::getXmlName()
{
return this->xmlName;
}
void JoyDPad::readConfig(QXmlStreamReader *xml)
{
if (xml->isStartElement() && xml->name() == getXmlName())
{
xml->readNextStartElement();
while (!xml->atEnd() && (!xml->isEndElement() && xml->name() != getXmlName()))
{
bool found = readMainConfig(xml);
if (!found)
{
xml->skipCurrentElement();
}
xml->readNextStartElement();
}
}
}
bool JoyDPad::readMainConfig(QXmlStreamReader *xml)
{
bool found = false;
if (xml->name() == "dpadbutton" && xml->isStartElement())
{
found = true;
int index = xml->attributes().value("index").toString().toInt();
JoyDPadButton* button = this->getJoyButton(index);
if (button)
{
button->readConfig(xml);
}
else
{
xml->skipCurrentElement();
}
}
else if (xml->name() == "mode" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
if (temptext == "eight-way")
{
this->setJoyMode(EightWayMode);
}
else if (temptext == "four-way")
{
this->setJoyMode(FourWayCardinal);
}
else if (temptext == "diagonal")
{
this->setJoyMode(FourWayDiagonal);
}
}
else if (xml->name() == "dpadDelay" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
int tempchoice = temptext.toInt();
this->setDPadDelay(tempchoice);
}
return found;
}
void JoyDPad::writeConfig(QXmlStreamWriter *xml)
{
if (!isDefault())
{
xml->writeStartElement(getXmlName());
xml->writeAttribute("index", QString::number(index+1));
if (currentMode == EightWayMode)
{
xml->writeTextElement("mode", "eight-way");
}
else if (currentMode == FourWayCardinal)
{
xml->writeTextElement("mode", "four-way");
}
else if (currentMode == FourWayDiagonal)
{
xml->writeTextElement("mode", "diagonal");
}
if (dpadDelay > DEFAULTDPADDELAY)
{
xml->writeTextElement("dpadDelay", QString::number(dpadDelay));
}
QHashIterator<int, JoyDPadButton*> iter(buttons);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
button->writeConfig(xml);
}
xml->writeEndElement();
}
}
void JoyDPad::queuePendingEvent(int value, bool ignoresets)
{
pendingEvent = true;
pendingEventDirection = value;
pendingIgnoreSets = ignoresets;
}
void JoyDPad::activatePendingEvent()
{
if (pendingEvent)
{
joyEvent(pendingEventDirection, pendingIgnoreSets);
pendingEvent = false;
pendingEventDirection = static_cast<int>(JoyDPadButton::DpadCentered);
pendingIgnoreSets = false;
}
}
bool JoyDPad::hasPendingEvent()
{
return pendingEvent;
}
void JoyDPad::clearPendingEvent()
{
pendingEvent = false;
pendingEventDirection = static_cast<int>(JoyDPadButton::DpadCentered);
pendingIgnoreSets = false;
}
void JoyDPad::joyEvent(int value, bool ignoresets)
{
if (value != (int)pendingDirection)
{
if (value != (int)JoyDPadButton::DpadCentered)
{
if (prevDirection == JoyDPadButton::DpadCentered)
{
emit active(value);
}
pendingDirection = (JoyDPadButton::JoyDPadDirections)value;
if (ignoresets || dpadDelay == 0)
{
if (directionDelayTimer.isActive())
{
directionDelayTimer.stop();
}
createDeskEvent(ignoresets);
}
else if (pendingDirection != prevDirection)
{
if (!directionDelayTimer.isActive())
{
directionDelayTimer.start(dpadDelay);
}
}
else
{
if (directionDelayTimer.isActive())
{
directionDelayTimer.stop();
}
}
}
else
{
emit released(value);
pendingDirection = JoyDPadButton::DpadCentered;
if (ignoresets || dpadDelay == 0)
{
if (directionDelayTimer.isActive())
{
directionDelayTimer.stop();
}
createDeskEvent(ignoresets);
}
else
{
if (!directionDelayTimer.isActive())
{
directionDelayTimer.start(dpadDelay);
}
}
//directionDelayTimer.stop();
//createDeskEvent(ignoresets);
}
}
}
QHash<int, JoyDPadButton*>* JoyDPad::getJoyButtons()
{
return &buttons;
}
int JoyDPad::getCurrentDirection()
{
return prevDirection;
}
void JoyDPad::setJoyMode(JoyMode mode)
{
currentMode = mode;
emit joyModeChanged();
emit propertyUpdated();
}
JoyDPad::JoyMode JoyDPad::getJoyMode()
{
return currentMode;
}
void JoyDPad::releaseButtonEvents()
{
QHashIterator<int, JoyDPadButton*> iter(buttons);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
button->joyEvent(false, true);
}
}
QHash<int, JoyDPadButton*>* JoyDPad::getButtons()
{
return &buttons;
}
bool JoyDPad::isDefault()
{
bool value = true;
value = value && (currentMode == StandardMode);
value = value && (dpadDelay == DEFAULTDPADDELAY);
QHashIterator<int, JoyDPadButton*> iter(buttons);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
value = value && (button->isDefault());
}
return value;
}
void JoyDPad::setButtonsMouseMode(JoyButton::JoyMouseMovementMode mode)
{
QHashIterator<int, JoyDPadButton*> iter(buttons);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
button->setMouseMode(mode);
}
}
bool JoyDPad::hasSameButtonsMouseMode()
{
bool result = true;
JoyButton::JoyMouseMovementMode initialMode = JoyButton::MouseCursor;
QHash<int, JoyDPadButton*> temphash = getApplicableButtons();
QHashIterator<int, JoyDPadButton*> iter(temphash);
while (iter.hasNext())
{
if (!iter.hasPrevious())
{
JoyDPadButton *button = iter.next().value();
initialMode = button->getMouseMode();
}
else
{
JoyDPadButton *button = iter.next().value();
JoyButton::JoyMouseMovementMode temp = button->getMouseMode();
if (temp != initialMode)
{
result = false;
iter.toBack();
}
}
}
return result;
}
JoyButton::JoyMouseMovementMode JoyDPad::getButtonsPresetMouseMode()
{
JoyButton::JoyMouseMovementMode resultMode = JoyButton::MouseCursor;
QHash<int, JoyDPadButton*> temphash = getApplicableButtons();
QHashIterator<int, JoyDPadButton*> iter(temphash);
while (iter.hasNext())
{
if (!iter.hasPrevious())
{
JoyDPadButton *button = iter.next().value();
resultMode = button->getMouseMode();
}
else
{
JoyDPadButton *button = iter.next().value();
JoyButton::JoyMouseMovementMode temp = button->getMouseMode();
if (temp != resultMode)
{
resultMode = JoyButton::MouseCursor;
iter.toBack();
}
}
}
return resultMode;
}
void JoyDPad::setButtonsMouseCurve(JoyButton::JoyMouseCurve mouseCurve)
{
QHashIterator<int, JoyDPadButton*> iter(buttons);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
button->setMouseCurve(mouseCurve);
}
}
bool JoyDPad::hasSameButtonsMouseCurve()
{
bool result = true;
JoyButton::JoyMouseCurve initialCurve = JoyButton::LinearCurve;
QHash<int, JoyDPadButton*> temphash = getApplicableButtons();
QHashIterator<int, JoyDPadButton*> iter(temphash);
while (iter.hasNext())
{
if (!iter.hasPrevious())
{
JoyDPadButton *button = iter.next().value();
initialCurve = button->getMouseCurve();
}
else
{
JoyDPadButton *button = iter.next().value();
JoyButton::JoyMouseCurve temp = button->getMouseCurve();
if (temp != initialCurve)
{
result = false;
iter.toBack();
}
}
}
return result;
}
JoyButton::JoyMouseCurve JoyDPad::getButtonsPresetMouseCurve()
{
JoyButton::JoyMouseCurve resultCurve = JoyButton::LinearCurve;
QHash<int, JoyDPadButton*> temphash = getApplicableButtons();
QHashIterator<int, JoyDPadButton*> iter(temphash);
while (iter.hasNext())
{
if (!iter.hasPrevious())
{
JoyDPadButton *button = iter.next().value();
resultCurve = button->getMouseCurve();
}
else
{
JoyDPadButton *button = iter.next().value();
JoyButton::JoyMouseCurve temp = button->getMouseCurve();
if (temp != resultCurve)
{
resultCurve = JoyButton::LinearCurve;
iter.toBack();
}
}
}
return resultCurve;
}
void JoyDPad::setButtonsSpringWidth(int value)
{
QHashIterator<int, JoyDPadButton*> iter(buttons);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
button->setSpringWidth(value);
}
}
void JoyDPad::setButtonsSpringHeight(int value)
{
QHashIterator<int, JoyDPadButton*> iter(buttons);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
button->setSpringHeight(value);
}
}
int JoyDPad::getButtonsPresetSpringWidth()
{
int presetSpringWidth = 0;
QHash<int, JoyDPadButton*> temphash = getApplicableButtons();
QHashIterator<int, JoyDPadButton*> iter(temphash);
while (iter.hasNext())
{
if (!iter.hasPrevious())
{
JoyDPadButton *button = iter.next().value();
presetSpringWidth = button->getSpringWidth();
}
else
{
JoyDPadButton *button = iter.next().value();
int temp = button->getSpringWidth();
if (temp != presetSpringWidth)
{
presetSpringWidth = 0;
iter.toBack();
}
}
}
return presetSpringWidth;
}
int JoyDPad::getButtonsPresetSpringHeight()
{
int presetSpringHeight = 0;
QHash<int, JoyDPadButton*> temphash = getApplicableButtons();
QHashIterator<int, JoyDPadButton*> iter(temphash);
while (iter.hasNext())
{
if (!iter.hasPrevious())
{
JoyDPadButton *button = iter.next().value();
presetSpringHeight = button->getSpringHeight();
}
else
{
JoyDPadButton *button = iter.next().value();
int temp = button->getSpringHeight();
if (temp != presetSpringHeight)
{
presetSpringHeight = 0;
iter.toBack();
}
}
}
return presetSpringHeight;
}
void JoyDPad::setButtonsSensitivity(double value)
{
QHashIterator<int, JoyDPadButton*> iter(buttons);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
button->setSensitivity(value);
}
}
double JoyDPad::getButtonsPresetSensitivity()
{
double presetSensitivity = 1.0;
QHash<int, JoyDPadButton*> temphash = getApplicableButtons();
QHashIterator<int, JoyDPadButton*> iter(temphash);
while (iter.hasNext())
{
if (!iter.hasPrevious())
{
JoyDPadButton *button = iter.next().value();
presetSensitivity = button->getSensitivity();
}
else
{
JoyDPadButton *button = iter.next().value();
double temp = button->getSensitivity();
if (temp != presetSensitivity)
{
presetSensitivity = 1.0;
iter.toBack();
}
}
}
return presetSensitivity;
}
QHash<int, JoyDPadButton*> JoyDPad::getApplicableButtons()
{
QHash<int, JoyDPadButton*> temphash;
if (currentMode == StandardMode || currentMode == EightWayMode ||
currentMode == FourWayCardinal)
{
temphash.insert(JoyDPadButton::DpadUp, buttons.value(JoyDPadButton::DpadUp));
temphash.insert(JoyDPadButton::DpadDown, buttons.value(JoyDPadButton::DpadDown));
temphash.insert(JoyDPadButton::DpadLeft, buttons.value(JoyDPadButton::DpadLeft));
temphash.insert(JoyDPadButton::DpadRight, buttons.value(JoyDPadButton::DpadRight));
}
if (currentMode == EightWayMode || currentMode == FourWayDiagonal)
{
temphash.insert(JoyDPadButton::DpadLeftUp, buttons.value(JoyDPadButton::DpadLeftUp));
temphash.insert(JoyDPadButton::DpadRightUp, buttons.value(JoyDPadButton::DpadRightUp));
temphash.insert(JoyDPadButton::DpadRightDown, buttons.value(JoyDPadButton::DpadRightDown));
temphash.insert(JoyDPadButton::DpadLeftDown, buttons.value(JoyDPadButton::DpadLeftDown));
}
return temphash;
}
void JoyDPad::setDPadName(QString tempName)
{
if (tempName.length() <= 20 && tempName != dpadName)
{
dpadName = tempName;
emit dpadNameChanged();
emit propertyUpdated();
}
}
QString JoyDPad::getDpadName()
{
return dpadName;
}
void JoyDPad::setButtonsWheelSpeedX(int value)
{
QHashIterator<int, JoyDPadButton*> iter(buttons);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
button->setWheelSpeedX(value);
}
}
void JoyDPad::setButtonsWheelSpeedY(int value)
{
QHashIterator<int, JoyDPadButton*> iter(buttons);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
button->setWheelSpeedY(value);
}
}
void JoyDPad::setDefaultDPadName(QString tempname)
{
defaultDPadName = tempname;
emit dpadNameChanged();
}
QString JoyDPad::getDefaultDPadName()
{
return defaultDPadName;
}
SetJoystick* JoyDPad::getParentSet()
{
return parentSet;
}
void JoyDPad::establishPropertyUpdatedConnection()
{
connect(this, SIGNAL(propertyUpdated()), getParentSet()->getInputDevice(), SLOT(profileEdited()));
}
void JoyDPad::disconnectPropertyUpdatedConnection()
{
disconnect(this, SIGNAL(propertyUpdated()), getParentSet()->getInputDevice(), SLOT(profileEdited()));
}
bool JoyDPad::hasSlotsAssigned()
{
bool hasSlots = false;
QHash<int, JoyDPadButton*> temphash = getApplicableButtons();
QHashIterator<int, JoyDPadButton*> iter(temphash);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
if (button)
{
if (button->getAssignedSlots()->count() > 0)
{
hasSlots = true;
iter.toBack();
}
}
}
return hasSlots;
}
void JoyDPad::setButtonsSpringRelativeStatus(bool value)
{
QHashIterator<int, JoyDPadButton*> iter(buttons);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
button->setSpringRelativeStatus(value);
}
}
bool JoyDPad::isRelativeSpring()
{
bool relative = false;
QHash<int, JoyDPadButton*> temphash = getApplicableButtons();
QHashIterator<int, JoyDPadButton*> iter(temphash);
while (iter.hasNext())
{
if (!iter.hasPrevious())
{
JoyDPadButton *button = iter.next().value();
relative = button->isRelativeSpring();
}
else
{
JoyDPadButton *button = iter.next().value();
bool temp = button->isRelativeSpring();
if (temp != relative)
{
relative = false;
iter.toBack();
}
}
}
return relative;
}
void JoyDPad::copyAssignments(JoyDPad *destDPad)
{
destDPad->activeDiagonalButton = activeDiagonalButton;
destDPad->prevDirection = prevDirection;
destDPad->currentMode = currentMode;
destDPad->dpadDelay = dpadDelay;
QHashIterator<int, JoyDPadButton*> iter(destDPad->buttons);
while (iter.hasNext())
{
JoyDPadButton *destButton = iter.next().value();
if (destButton)
{
JoyDPadButton *sourceButton = buttons.value(destButton->getDirection());
if (sourceButton)
{
sourceButton->copyAssignments(destButton);
}
}
}
if (!destDPad->isDefault())
{
emit propertyUpdated();
}
}
void JoyDPad::createDeskEvent(bool ignoresets)
{
JoyDPadButton *curButton = 0;
JoyDPadButton *prevButton = 0;
JoyDPadButton::JoyDPadDirections value = pendingDirection;
if (pendingDirection != prevDirection)
{
if (activeDiagonalButton)
{
activeDiagonalButton->joyEvent(false, ignoresets);
activeDiagonalButton = 0;
}
else {
if (currentMode == StandardMode)
{
if ((prevDirection & JoyDPadButton::DpadUp) && (!(value & JoyDPadButton::DpadUp)))
{
prevButton = buttons.value(JoyDPadButton::DpadUp);
prevButton->joyEvent(false, ignoresets);
}
if ((prevDirection & JoyDPadButton::DpadDown) && (!(value & JoyDPadButton::DpadDown)))
{
prevButton = buttons.value(JoyDPadButton::DpadDown);
prevButton->joyEvent(false, ignoresets);
}
if ((prevDirection & JoyDPadButton::DpadLeft) && (!(value & JoyDPadButton::DpadLeft)))
{
prevButton = buttons.value(JoyDPadButton::DpadLeft);
prevButton->joyEvent(false, ignoresets);
}
if ((prevDirection & JoyDPadButton::DpadRight) && (!(value & JoyDPadButton::DpadRight)))
{
prevButton = buttons.value(JoyDPadButton::DpadRight);
prevButton->joyEvent(false, ignoresets);
}
}
else if (currentMode == EightWayMode && prevDirection)
{
prevButton = buttons.value(prevDirection);
prevButton->joyEvent(false, ignoresets);
}
else if (currentMode == FourWayCardinal && prevDirection)
{
if ((prevDirection == JoyDPadButton::DpadUp ||
prevDirection == JoyDPadButton::DpadRightUp) &&
(value != JoyDPadButton::DpadUp && value != JoyDPadButton::DpadRightUp))
{
prevButton = buttons.value(JoyDPadButton::DpadUp);
}
else if ((prevDirection == JoyDPadButton::DpadDown ||
prevDirection == JoyDPadButton::DpadLeftDown) &&
(value != JoyDPadButton::DpadDown && value != JoyDPadButton::DpadLeftDown))
{
prevButton = buttons.value(JoyDPadButton::DpadDown);
}
else if ((prevDirection == JoyDPadButton::DpadLeft ||
prevDirection == JoyDPadButton::DpadLeftUp) &&
(value != JoyDPadButton::DpadLeft && value != JoyDPadButton::DpadLeftUp))
{
prevButton = buttons.value(JoyDPadButton::DpadLeft);
}
else if ((prevDirection == JoyDPadButton::DpadRight ||
prevDirection == JoyDPadButton::DpadRightDown) &&
(value != JoyDPadButton::DpadRight && value != JoyDPadButton::DpadRightDown))
{
prevButton = buttons.value(JoyDPadButton::DpadRight);
}
if (prevButton)
{
prevButton->joyEvent(false, ignoresets);
}
}
else if (currentMode == FourWayDiagonal && prevDirection)
{
prevButton = buttons.value(prevDirection);
prevButton->joyEvent(false, ignoresets);
}
}
if (currentMode == StandardMode)
{
if ((value & JoyDPadButton::DpadUp) && (!(prevDirection & JoyDPadButton::DpadUp)))
{
curButton = buttons.value(JoyDPadButton::DpadUp);
curButton->joyEvent(true, ignoresets);
}
if ((value & JoyDPadButton::DpadDown) && (!(prevDirection & JoyDPadButton::DpadDown)))
{
curButton = buttons.value(JoyDPadButton::DpadDown);
curButton->joyEvent(true, ignoresets);
}
if ((value & JoyDPadButton::DpadLeft) && (!(prevDirection & JoyDPadButton::DpadLeft)))
{
curButton = buttons.value(JoyDPadButton::DpadLeft);
curButton->joyEvent(true, ignoresets);
}
if ((value & JoyDPadButton::DpadRight) && (!(prevDirection & JoyDPadButton::DpadRight)))
{
curButton = buttons.value(JoyDPadButton::DpadRight);
curButton->joyEvent(true, ignoresets);
}
}
else if (currentMode == EightWayMode)
{
if (value == JoyDPadButton::DpadLeftUp)
{
activeDiagonalButton = buttons.value(JoyDPadButton::DpadLeftUp);
activeDiagonalButton->joyEvent(true, ignoresets);
}
else if (value == JoyDPadButton::DpadRightUp)
{
activeDiagonalButton = buttons.value(JoyDPadButton::DpadRightUp);
activeDiagonalButton->joyEvent(true, ignoresets);
}
else if (value == JoyDPadButton::DpadRightDown)
{
activeDiagonalButton = buttons.value(JoyDPadButton::DpadRightDown);
activeDiagonalButton->joyEvent(true, ignoresets);
}
else if (value == JoyDPadButton::DpadLeftDown)
{
activeDiagonalButton = buttons.value(JoyDPadButton::DpadLeftDown);
activeDiagonalButton->joyEvent(true, ignoresets);
}
else if (value == JoyDPadButton::DpadUp)
{
curButton = buttons.value(JoyDPadButton::DpadUp);
curButton->joyEvent(true, ignoresets);
}
else if (value == JoyDPadButton::DpadDown)
{
curButton = buttons.value(JoyDPadButton::DpadDown);
curButton->joyEvent(true, ignoresets);
}
else if (value == JoyDPadButton::DpadLeft)
{
curButton = buttons.value(JoyDPadButton::DpadLeft);
curButton->joyEvent(true, ignoresets);
}
else if (value == JoyDPadButton::DpadRight)
{
curButton = buttons.value(JoyDPadButton::DpadRight);
curButton->joyEvent(true, ignoresets);
}
}
else if (currentMode == FourWayCardinal)
{
if (value == JoyDPadButton::DpadUp ||
value == JoyDPadButton::DpadRightUp)
{
curButton = buttons.value(JoyDPadButton::DpadUp);
curButton->joyEvent(true, ignoresets);
}
else if (value == JoyDPadButton::DpadDown ||
value == JoyDPadButton::DpadLeftDown)
{
curButton = buttons.value(JoyDPadButton::DpadDown);
curButton->joyEvent(true, ignoresets);
}
else if (value == JoyDPadButton::DpadLeft ||
value == JoyDPadButton::DpadLeftUp)
{
curButton = buttons.value(JoyDPadButton::DpadLeft);
curButton->joyEvent(true, ignoresets);
}
else if (value == JoyDPadButton::DpadRight ||
value == JoyDPadButton::DpadRightDown)
{
curButton = buttons.value(JoyDPadButton::DpadRight);
curButton->joyEvent(true, ignoresets);
}
}
else if (currentMode == FourWayDiagonal)
{
if (value == JoyDPadButton::DpadLeftUp)
{
activeDiagonalButton = buttons.value(JoyDPadButton::DpadLeftUp);
activeDiagonalButton->joyEvent(true, ignoresets);
}
else if (value == JoyDPadButton::DpadRightUp)
{
activeDiagonalButton = buttons.value(JoyDPadButton::DpadRightUp);
activeDiagonalButton->joyEvent(true, ignoresets);
}
else if (value == JoyDPadButton::DpadRightDown)
{
activeDiagonalButton = buttons.value(JoyDPadButton::DpadRightDown);
activeDiagonalButton->joyEvent(true, ignoresets);
}
else if (value == JoyDPadButton::DpadLeftDown)
{
activeDiagonalButton = buttons.value(JoyDPadButton::DpadLeftDown);
activeDiagonalButton->joyEvent(true, ignoresets);
}
}
prevDirection = pendingDirection;
}
}
void JoyDPad::dpadDirectionChangeEvent()
{
createDeskEvent();
}
void JoyDPad::setDPadDelay(int value)
{
if ((value >= 10 && value <= 1000) || (value == 0))
{
this->dpadDelay = value;
emit dpadDelayChanged(value);
emit propertyUpdated();
}
}
unsigned int JoyDPad::getDPadDelay()
{
return dpadDelay;
}
void JoyDPad::setButtonsEasingDuration(double value)
{
QHash<int, JoyDPadButton*> temphash = getApplicableButtons();
QHashIterator<int, JoyDPadButton*> iter(temphash);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
button->setEasingDuration(value);
}
}
double JoyDPad::getButtonsEasingDuration()
{
double result = JoyButton::DEFAULTEASINGDURATION;
QHash<int, JoyDPadButton*> temphash = getApplicableButtons();
QHashIterator<int, JoyDPadButton*> iter(temphash);
while (iter.hasNext())
{
if (!iter.hasPrevious())
{
JoyDPadButton *button = iter.next().value();
result = button->getEasingDuration();
}
else
{
JoyDPadButton *button = iter.next().value();
double temp = button->getEasingDuration();
if (temp != result)
{
result = JoyButton::DEFAULTEASINGDURATION;
iter.toBack();
}
}
}
return result;
}
void JoyDPad::setButtonsSpringDeadCircleMultiplier(int value)
{
QHash<int, JoyDPadButton*> temphash = getApplicableButtons();
QHashIterator<int, JoyDPadButton*> iter(temphash);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
button->setSpringDeadCircleMultiplier(value);
}
}
int JoyDPad::getButtonsSpringDeadCircleMultiplier()
{
int result = JoyButton::DEFAULTSPRINGRELEASERADIUS;
QHash<int, JoyDPadButton*> temphash = getApplicableButtons();
QHashIterator<int, JoyDPadButton*> iter(temphash);
while (iter.hasNext())
{
if (!iter.hasPrevious())
{
JoyDPadButton *button = iter.next().value();
result = button->getSpringDeadCircleMultiplier();
}
else
{
JoyDPadButton *button = iter.next().value();
int temp = button->getSpringDeadCircleMultiplier();
if (temp != result)
{
result = JoyButton::DEFAULTSPRINGRELEASERADIUS;
iter.toBack();
}
}
}
return result;
}
void JoyDPad::setButtonsExtraAccelerationCurve(JoyButton::JoyExtraAccelerationCurve curve)
{
QHash<int, JoyDPadButton*> temphash = getApplicableButtons();
QHashIterator<int, JoyDPadButton*> iter(temphash);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
button->setExtraAccelerationCurve(curve);
}
}
JoyButton::JoyExtraAccelerationCurve JoyDPad::getButtonsExtraAccelerationCurve()
{
JoyButton::JoyExtraAccelerationCurve result = JoyButton::LinearAccelCurve;
QHash<int, JoyDPadButton*> temphash = getApplicableButtons();
QHashIterator<int, JoyDPadButton*> iter(temphash);
while (iter.hasNext())
{
if (!iter.hasPrevious())
{
JoyDPadButton *button = iter.next().value();
result = button->getExtraAccelerationCurve();
}
else
{
JoyDPadButton *button = iter.next().value();
JoyButton::JoyExtraAccelerationCurve temp = button->getExtraAccelerationCurve();
if (temp != result)
{
result = JoyButton::LinearAccelCurve;
iter.toBack();
}
}
}
return result;
}
QHash<int, JoyDPadButton*> JoyDPad::getDirectionButtons(JoyDPadButton::JoyDPadDirections direction)
{
QHash<int, JoyDPadButton*> temphash;
if (currentMode == StandardMode)
{
if (direction & JoyDPadButton::DpadUp)
{
temphash.insert(JoyDPadButton::DpadUp, buttons.value(JoyDPadButton::DpadUp));
}
if (direction & JoyDPadButton::DpadDown)
{
temphash.insert(JoyDPadButton::DpadDown, buttons.value(JoyDPadButton::DpadDown));
}
if (direction & JoyDPadButton::DpadLeft)
{
temphash.insert(JoyDPadButton::DpadLeft, buttons.value(JoyDPadButton::DpadLeft));
}
if (direction & JoyDPadButton::DpadRight)
{
temphash.insert(JoyDPadButton::DpadRight, buttons.value(JoyDPadButton::DpadRight));
}
}
else if (currentMode == EightWayMode)
{
if (direction != JoyDPadButton::DpadCentered)
{
temphash.insert(direction, buttons.value(direction));
}
}
else if (currentMode == FourWayCardinal)
{
if (direction == JoyDPadButton::DpadUp ||
direction == JoyDPadButton::DpadDown ||
direction == JoyDPadButton::DpadLeft ||
direction == JoyDPadButton::DpadRight)
{
temphash.insert(direction, buttons.value(direction));
}
}
else if (currentMode == FourWayDiagonal)
{
if (direction == JoyDPadButton::DpadRightUp ||
direction == JoyDPadButton::DpadRightDown ||
direction == JoyDPadButton::DpadLeftDown ||
direction == JoyDPadButton::DpadLeftUp)
{
temphash.insert(direction, buttons.value(direction));
}
}
return temphash;
}
void JoyDPad::setDirButtonsUpdateInitAccel(JoyDPadButton::JoyDPadDirections direction, bool state)
{
QHash<int, JoyDPadButton*> apphash = getDirectionButtons(direction);
QHashIterator<int, JoyDPadButton*> iter(apphash);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
if (button)
{
button->setUpdateInitAccel(state);
}
}
}
void JoyDPad::copyLastDistanceValues(JoyDPad *srcDPad)
{
QHash<int, JoyDPadButton*> apphash = srcDPad->getApplicableButtons();
QHashIterator<int, JoyDPadButton*> iter(apphash);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
if (button && button->getButtonState())
{
this->buttons.value(iter.key())->copyLastAccelerationDistance(button);
this->buttons.value(iter.key())->copyLastMouseDistanceFromDeadZone(button);
}
}
}
void JoyDPad::eventReset()
{
QHash<int, JoyDPadButton*> temphash = getApplicableButtons();
QHashIterator<int, JoyDPadButton*> iter(temphash);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
button->eventReset();
}
}
``` | /content/code_sandbox/src/joydpad.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 8,580 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef JOYCONTROLSTICKEDITDIALOG_H
#define JOYCONTROLSTICKEDITDIALOG_H
#include <QDialog>
#include "joycontrolstick.h"
#include "uihelpers/joycontrolstickeditdialoghelper.h"
namespace Ui {
class JoyControlStickEditDialog;
}
class JoyControlStickEditDialog : public QDialog
{
Q_OBJECT
public:
explicit JoyControlStickEditDialog(JoyControlStick *stick, QWidget *parent = 0);
~JoyControlStickEditDialog();
protected:
void selectCurrentPreset();
JoyControlStick *stick;
JoyControlStickEditDialogHelper helper;
private:
Ui::JoyControlStickEditDialog *ui;
private slots:
void implementPresets(int index);
void implementModes(int index);
void refreshStickStats(int x, int y);
void updateMouseMode(int index);
void checkMaxZone(int value);
void openMouseSettingsDialog();
void enableMouseSettingButton();
void updateWindowTitleStickName();
void changeCircleAdjust(int value);
void updateStickDelaySpinBox(int value);
void updateStickDelaySlider(double value);
void openModifierEditDialog();
void changeModifierSummary();
};
#endif // JOYCONTROLSTICKEDITDIALOG_H
``` | /content/code_sandbox/src/joycontrolstickeditdialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 357 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include <QMenu>
#include "joybuttonwidget.h"
#include "joybuttoncontextmenu.h"
JoyButtonWidget::JoyButtonWidget(JoyButton *button, bool displayNames, QWidget *parent) :
FlashButtonWidget(displayNames, parent)
{
this->button = button;
refreshLabel();
enableFlashes();
tryFlash();
this->setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showContextMenu(const QPoint&)));
//connect(button, SIGNAL(slotsChanged()), this, SLOT(refreshLabel()));
connect(button, SIGNAL(propertyUpdated()), this, SLOT(refreshLabel()));
connect(button, SIGNAL(activeZoneChanged()), this, SLOT(refreshLabel()));
}
JoyButton* JoyButtonWidget::getJoyButton()
{
return button;
}
void JoyButtonWidget::disableFlashes()
{
disconnect(button, SIGNAL(clicked(int)), this, SLOT(flash()));
disconnect(button, SIGNAL(released(int)), this, SLOT(unflash()));
this->unflash();
}
void JoyButtonWidget::enableFlashes()
{
connect(button, SIGNAL(clicked(int)), this, SLOT(flash()), Qt::QueuedConnection);
connect(button, SIGNAL(released(int)), this, SLOT(unflash()), Qt::QueuedConnection);
}
QString JoyButtonWidget::generateLabel()
{
QString temp;
temp = button->getName(false, displayNames).replace("&", "&&");
return temp;
}
void JoyButtonWidget::showContextMenu(const QPoint &point)
{
QPoint globalPos = this->mapToGlobal(point);
JoyButtonContextMenu *contextMenu = new JoyButtonContextMenu(button, this);
contextMenu->buildMenu();
contextMenu->popup(globalPos);
}
void JoyButtonWidget::tryFlash()
{
if (button->getButtonState())
{
flash();
}
}
``` | /content/code_sandbox/src/joybuttonwidget.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 482 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
//#include <QDebug>
#include <QtGlobal>
#ifdef Q_OS_WIN
#include <qt_windows.h>
#include "winextras.h"
#else
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
#include <QApplication>
#endif
#endif
#include "buttoneditdialog.h"
#include "ui_buttoneditdialog.h"
#include "event.h"
#include "antkeymapper.h"
#include "eventhandlerfactory.h"
#include "setjoystick.h"
#include "inputdevice.h"
#include "common.h"
ButtonEditDialog::ButtonEditDialog(JoyButton *button, QWidget *parent) :
QDialog(parent, Qt::Window),
ui(new Ui::ButtonEditDialog),
helper(button)
{
ui->setupUi(this);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
setMinimumHeight(460);
#endif
setAttribute(Qt::WA_DeleteOnClose);
setWindowModality(Qt::WindowModal);
ignoreRelease = false;
helper.moveToThread(button->thread());
PadderCommon::inputDaemonMutex.lock();
this->button = button;
ui->virtualKeyMouseTabWidget->hide();
ui->virtualKeyMouseTabWidget->deleteLater();
ui->virtualKeyMouseTabWidget = new VirtualKeyboardMouseWidget(button, this);
ui->verticalLayout->insertWidget(1, ui->virtualKeyMouseTabWidget);
//ui->virtualKeyMouseTabWidget->setFocus();
ui->slotSummaryLabel->setText(button->getSlotsString());
updateWindowTitleButtonName();
ui->toggleCheckBox->setChecked(button->getToggleState());
ui->turboCheckBox->setChecked(button->isUsingTurbo());
if (!button->getActionName().isEmpty())
{
ui->actionNameLineEdit->setText(button->getActionName());
}
if (!button->getButtonName().isEmpty())
{
ui->buttonNameLineEdit->setText(button->getButtonName());
}
PadderCommon::inputDaemonMutex.unlock();
connect(qApp, SIGNAL(focusChanged(QWidget*,QWidget*)), this, SLOT(checkForKeyboardWidgetFocus(QWidget*,QWidget*)));
connect(ui->virtualKeyMouseTabWidget, SIGNAL(selectionCleared()), this, SLOT(refreshSlotSummaryLabel()));
connect(ui->virtualKeyMouseTabWidget, SIGNAL(selectionFinished()), this, SLOT(close()));
connect(this, SIGNAL(keyGrabbed(JoyButtonSlot*)), this, SLOT(processSlotAssignment(JoyButtonSlot*)));
connect(this, SIGNAL(selectionCleared()), this, SLOT(clearButtonSlots()));
connect(this, SIGNAL(selectionCleared()), this, SLOT(sendSelectionFinished()));
connect(this, SIGNAL(selectionFinished()), this, SLOT(close()));
connect(ui->toggleCheckBox, SIGNAL(clicked()), this, SLOT(changeToggleSetting()));
connect(ui->turboCheckBox, SIGNAL(clicked()), this, SLOT(changeTurboSetting()));
connect(ui->advancedPushButton, SIGNAL(clicked()), this, SLOT(openAdvancedDialog()));
connect(this, SIGNAL(advancedDialogOpened()), ui->virtualKeyMouseTabWidget, SLOT(establishVirtualKeyboardAdvancedSignalConnections()));
connect(this, SIGNAL(advancedDialogOpened()), ui->virtualKeyMouseTabWidget, SLOT(establishVirtualMouseAdvancedSignalConnections()));
//connect(ui->virtualKeyMouseTabWidget, SIGNAL(selectionMade(int)), this, SLOT(createTempSlot(int)));
connect(ui->actionNameLineEdit, SIGNAL(textEdited(QString)), button, SLOT(setActionName(QString)));
connect(ui->buttonNameLineEdit, SIGNAL(textEdited(QString)), button, SLOT(setButtonName(QString)));
connect(button, SIGNAL(toggleChanged(bool)), ui->toggleCheckBox, SLOT(setChecked(bool)));
connect(button, SIGNAL(turboChanged(bool)), this, SLOT(checkTurboSetting(bool)));
connect(button, SIGNAL(slotsChanged()), this, SLOT(refreshSlotSummaryLabel()));
connect(button, SIGNAL(buttonNameChanged()), this, SLOT(updateWindowTitleButtonName()));
}
void ButtonEditDialog::checkForKeyboardWidgetFocus(QWidget *old, QWidget *now)
{
Q_UNUSED(old);
Q_UNUSED(now);
if (ui->virtualKeyMouseTabWidget->hasFocus() &&
ui->virtualKeyMouseTabWidget->isKeyboardTabVisible())
{
grabKeyboard();
}
else
{
releaseKeyboard();
}
}
ButtonEditDialog::~ButtonEditDialog()
{
delete ui;
}
void ButtonEditDialog::keyPressEvent(QKeyEvent *event)
{
bool ignore = false;
// Ignore the following keys that might
// trigger an event in QDialog::keyPressEvent
switch(event->key())
{
case Qt::Key_Escape:
case Qt::Key_Right:
case Qt::Key_Enter:
case Qt::Key_Return:
{
ignore = true;
break;
}
}
if (!ignore)
{
QDialog::keyPressEvent(event);
}
}
void ButtonEditDialog::keyReleaseEvent(QKeyEvent *event)
{
if (ui->actionNameLineEdit->hasFocus() || ui->buttonNameLineEdit->hasFocus())
{
QDialog::keyReleaseEvent(event);
}
else if (ui->virtualKeyMouseTabWidget->isKeyboardTabVisible())
{
int controlcode = event->nativeScanCode();
int virtualactual = event->nativeVirtualKey();
BaseEventHandler *handler = EventHandlerFactory::getInstance()->handler();
#ifdef Q_OS_WIN
int finalvirtual = 0;
int checkalias = 0;
#ifdef WITH_VMULTI
if (handler->getIdentifier() == "vmulti")
{
finalvirtual = WinExtras::correctVirtualKey(controlcode, virtualactual);
checkalias = AntKeyMapper::getInstance()->returnQtKey(finalvirtual);
//unsigned int tempQtKey = nativeWinKeyMapper.returnQtKey(finalvirtual);
QtKeyMapperBase *nativeWinKeyMapper = AntKeyMapper::getInstance()->getNativeKeyMapper();
unsigned int tempQtKey = 0;
if (nativeWinKeyMapper)
{
tempQtKey = nativeWinKeyMapper->returnQtKey(finalvirtual);
}
if (tempQtKey > 0)
{
finalvirtual = AntKeyMapper::getInstance()->returnVirtualKey(tempQtKey);
checkalias = AntKeyMapper::getInstance()->returnQtKey(finalvirtual);
}
else
{
finalvirtual = AntKeyMapper::getInstance()->returnVirtualKey(event->key());
}
}
#endif
BACKEND_ELSE_IF (handler->getIdentifier() == "sendinput")
{
// Find more specific virtual key (VK_SHIFT -> VK_LSHIFT)
// by checking for extended bit in scan code.
finalvirtual = WinExtras::correctVirtualKey(controlcode, virtualactual);
checkalias = AntKeyMapper::getInstance()->returnQtKey(finalvirtual, controlcode);
}
#else
#if defined(WITH_X11)
int finalvirtual = 0;
int checkalias = 0;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
// Obtain group 1 X11 keysym. Removes effects from modifiers.
finalvirtual = X11KeyCodeToX11KeySym(controlcode);
#ifdef WITH_UINPUT
if (handler->getIdentifier() == "uinput")
{
// Find Qt Key corresponding to X11 KeySym.
//checkalias = x11KeyMapper.returnQtKey(finalvirtual);
Q_ASSERT(AntKeyMapper::getInstance()->hasNativeKeyMapper());
QtKeyMapperBase *x11KeyMapper = AntKeyMapper::getInstance()->getNativeKeyMapper();
Q_ASSERT(x11KeyMapper != NULL);
checkalias = x11KeyMapper->returnQtKey(finalvirtual);
// Find corresponding Linux input key for the Qt key.
finalvirtual = AntKeyMapper::getInstance()->returnVirtualKey(checkalias);
}
#endif
#ifdef WITH_XTEST
BACKEND_ELSE_IF (handler->getIdentifier() == "xtest")
{
// Check for alias against group 1 keysym.
checkalias = AntKeyMapper::getInstance()->returnQtKey(finalvirtual);
}
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
else
{
// Not running on xcb platform.
finalvirtual = controlcode;
checkalias = AntKeyMapper::getInstance()->returnQtKey(finalvirtual);
}
#endif
#else
int finalvirtual = 0;
int checkalias = 0;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
finalvirtual = AntKeyMapper::getInstance()->returnVirtualKey(event->key());
checkalias = AntKeyMapper::getInstance()->returnQtKey(finalvirtual);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
else
{
// Not running on xcb platform.
finalvirtual = controlcode;
checkalias = AntKeyMapper::getInstance()->returnQtKey(finalvirtual);
}
#endif
#endif
#endif
if (!ignoreRelease)
{
if ((event->modifiers() & Qt::ControlModifier) && event->key() == Qt::Key_X)
{
controlcode = 0;
ignoreRelease = true;
emit selectionCleared();
}
else if (controlcode <= 0)
{
controlcode = 0;
}
}
else
{
controlcode = 0;
ignoreRelease = false;
}
if (controlcode > 0)
{
if (checkalias > 0 && finalvirtual > 0)
{
JoyButtonSlot *tempslot = new JoyButtonSlot(finalvirtual, checkalias, JoyButtonSlot::JoyKeyboard, this);
emit keyGrabbed(tempslot);
}
else if (virtualactual > 0)
{
JoyButtonSlot *tempslot = new JoyButtonSlot(virtualactual, JoyButtonSlot::JoyKeyboard, this);
emit keyGrabbed(tempslot);
}
else
{
QDialog::keyReleaseEvent(event);
}
}
else
{
QDialog::keyReleaseEvent(event);
}
}
else
{
QDialog::keyReleaseEvent(event);
}
}
void ButtonEditDialog::refreshSlotSummaryLabel()
{
ui->slotSummaryLabel->setText(button->getSlotsString().replace("&", "&&"));
}
void ButtonEditDialog::changeToggleSetting()
{
button->setToggle(ui->toggleCheckBox->isChecked());
}
void ButtonEditDialog::changeTurboSetting()
{
button->setUseTurbo(ui->turboCheckBox->isChecked());
}
void ButtonEditDialog::openAdvancedDialog()
{
ui->advancedPushButton->setEnabled(false);
AdvanceButtonDialog *dialog = new AdvanceButtonDialog(button, this);
dialog->show();
// Disconnect event to allow for placing slot to AdvanceButtonDialog
disconnect(this, SIGNAL(keyGrabbed(JoyButtonSlot*)), 0, 0);
disconnect(this, SIGNAL(selectionCleared()), 0, 0);
disconnect(this, SIGNAL(selectionFinished()), 0, 0);
connect(dialog, SIGNAL(finished(int)), ui->virtualKeyMouseTabWidget, SLOT(establishVirtualKeyboardSingleSignalConnections()));
connect(dialog, SIGNAL(finished(int)), ui->virtualKeyMouseTabWidget, SLOT(establishVirtualMouseSignalConnections()));
connect(dialog, SIGNAL(finished(int)), this, SLOT(closedAdvancedDialog()));
connect(dialog, SIGNAL(turboButtonEnabledChange(bool)), this, SLOT(setTurboButtonEnabled(bool)));
connect(this, SIGNAL(sendTempSlotToAdvanced(JoyButtonSlot*)), dialog, SLOT(placeNewSlot(JoyButtonSlot*)));
connect(this, SIGNAL(keyGrabbed(JoyButtonSlot*)), dialog, SLOT(placeNewSlot(JoyButtonSlot*)));
connect(this, SIGNAL(selectionCleared()), dialog, SLOT(clearAllSlots()));
connect(ui->virtualKeyMouseTabWidget, SIGNAL(selectionMade(JoyButtonSlot*)), dialog, SLOT(placeNewSlot(JoyButtonSlot*)));
connect(ui->virtualKeyMouseTabWidget, SIGNAL(selectionMade(int, unsigned int)), this, SLOT(createTempSlot(int, unsigned int)));
connect(ui->virtualKeyMouseTabWidget, SIGNAL(selectionCleared()), dialog, SLOT(clearAllSlots()));
connect(this, SIGNAL(finished(int)), dialog, SLOT(close()));
emit advancedDialogOpened();
}
void ButtonEditDialog::createTempSlot(int keycode, unsigned int alias)
{
JoyButtonSlot *slot = new JoyButtonSlot(keycode, alias,
JoyButtonSlot::JoyKeyboard, this);
emit sendTempSlotToAdvanced(slot);
}
void ButtonEditDialog::checkTurboSetting(bool state)
{
if (button->containsSequence())
{
ui->turboCheckBox->setChecked(false);
ui->turboCheckBox->setEnabled(false);
}
else
{
ui->turboCheckBox->setChecked(state);
ui->turboCheckBox->setEnabled(true);
}
helper.setUseTurbo(state);
}
void ButtonEditDialog::setTurboButtonEnabled(bool state)
{
ui->turboCheckBox->setEnabled(state);
}
void ButtonEditDialog::closedAdvancedDialog()
{
ui->advancedPushButton->setEnabled(true);
disconnect(ui->virtualKeyMouseTabWidget, SIGNAL(selectionMade(int, unsigned int)), this, 0);
// Re-connect previously disconnected event
connect(this, SIGNAL(keyGrabbed(JoyButtonSlot*)), this, SLOT(processSlotAssignment(JoyButtonSlot*)));
connect(this, SIGNAL(selectionCleared()), this, SLOT(clearButtonSlots()));
connect(this, SIGNAL(selectionCleared()), this, SLOT(sendSelectionFinished()));
connect(this, SIGNAL(selectionFinished()), this, SLOT(close()));
}
void ButtonEditDialog::processSlotAssignment(JoyButtonSlot *tempslot)
{
QMetaObject::invokeMethod(&helper, "setAssignedSlot", Qt::BlockingQueuedConnection,
Q_ARG(int, tempslot->getSlotCode()),
Q_ARG(unsigned int, tempslot->getSlotCodeAlias()),
Q_ARG(JoyButtonSlot::JoySlotInputAction, tempslot->getSlotMode()));
this->close();
tempslot->deleteLater();
}
void ButtonEditDialog::clearButtonSlots()
{
QMetaObject::invokeMethod(button, "clearSlotsEventReset", Q_ARG(bool, false));
}
void ButtonEditDialog::sendSelectionFinished()
{
emit selectionFinished();
}
void ButtonEditDialog::updateWindowTitleButtonName()
{
QString temp = QString(tr("Set")).append(" ").append(button->getPartialName(false, true));
if (button->getParentSet()->getIndex() != 0)
{
unsigned int setIndex = button->getParentSet()->getRealIndex();
temp.append(" [").append(tr("Set %1").arg(setIndex));
QString setName = button->getParentSet()->getName();
if (!setName.isEmpty())
{
temp.append(": ").append(setName);
}
temp.append("]");
}
setWindowTitle(temp);
}
``` | /content/code_sandbox/src/buttoneditdialog.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 3,314 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef KEYDELAYDIALOG_H
#define KEYDELAYDIALOG_H
#include <QDialog>
#include "inputdevice.h"
namespace Ui {
class ExtraProfileSettingsDialog;
}
class ExtraProfileSettingsDialog : public QDialog
{
Q_OBJECT
public:
explicit ExtraProfileSettingsDialog(InputDevice *device, QWidget *parent = 0);
~ExtraProfileSettingsDialog();
protected:
InputDevice *device;
private:
Ui::ExtraProfileSettingsDialog *ui;
private slots:
void changeDeviceKeyPress(int value);
};
#endif // KEYDELAYDIALOG_H
``` | /content/code_sandbox/src/extraprofilesettingsdialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 212 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include <QStyle>
#include "joybuttonstatusbox.h"
JoyButtonStatusBox::JoyButtonStatusBox(JoyButton *button, QWidget *parent) :
QPushButton(parent)
{
this->button = button;
isflashing = false;
setText(QString::number(button->getRealJoyNumber()));
connect(button, SIGNAL(clicked(int)), this, SLOT(flash()));
connect(button, SIGNAL(released(int)), this, SLOT(unflash()));
}
JoyButton* JoyButtonStatusBox::getJoyButton()
{
return button;
}
bool JoyButtonStatusBox::isButtonFlashing()
{
return isflashing;
}
void JoyButtonStatusBox::flash()
{
isflashing = true;
this->style()->unpolish(this);
this->style()->polish(this);
emit flashed(isflashing);
}
void JoyButtonStatusBox::unflash()
{
isflashing = false;
this->style()->unpolish(this);
this->style()->polish(this);
emit flashed(isflashing);
}
``` | /content/code_sandbox/src/joybuttonstatusbox.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 314 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef EVENT_H
#define EVENT_H
#include <QString>
#include "joybuttonslot.h"
//#include "mousehelper.h"
#include "springmousemoveinfo.h"
#include "common.h"
void sendevent (JoyButtonSlot *slot, bool pressed=true);
void sendevent(int code1, int code2);
void sendSpringEventRefactor(PadderCommon::springModeInfo *fullSpring,
PadderCommon::springModeInfo *relativeSpring=0,
int* const mousePosX=0, int* const mousePos=0);
void sendSpringEvent(PadderCommon::springModeInfo *fullSpring,
PadderCommon::springModeInfo *relativeSpring=0,
int* const mousePosX=0, int* const mousePos=0);
int X11KeySymToKeycode(QString key);
QString keycodeToKeyString(int keycode, unsigned int alias=0);
unsigned int X11KeyCodeToX11KeySym(unsigned int keycode);
QString keysymToKeyString(int keysym, unsigned int alias=0);
#endif // EVENT_H
``` | /content/code_sandbox/src/event.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 313 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef JOYCONTROLSTICKSTATUSBOX_H
#define JOYCONTROLSTICKSTATUSBOX_H
#include <QWidget>
#include <QSize>
#include "joycontrolstick.h"
#include "joyaxis.h"
class JoyControlStickStatusBox : public QWidget
{
Q_OBJECT
public:
explicit JoyControlStickStatusBox(QWidget *parent = 0);
explicit JoyControlStickStatusBox(JoyControlStick *stick, QWidget *parent = 0);
void setStick(JoyControlStick *stick);
JoyControlStick* getStick();
virtual int heightForWidth(int width) const;
QSize sizeHint() const;
protected:
virtual void paintEvent(QPaintEvent *event);
void drawEightWayBox();
void drawFourWayCardinalBox();
void drawFourWayDiagonalBox();
JoyControlStick *stick;
signals:
public slots:
};
#endif // JOYCONTROLSTICKSTATUSBOX_H
``` | /content/code_sandbox/src/joycontrolstickstatusbox.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 290 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include <QPushButton>
#include "capturedwindowinfodialog.h"
#include "ui_capturedwindowinfodialog.h"
#ifdef Q_OS_WIN
#include "winextras.h"
#else
#include "x11extras.h"
#endif
#ifdef Q_OS_WIN
CapturedWindowInfoDialog::CapturedWindowInfoDialog(QWidget *parent) :
#else
CapturedWindowInfoDialog::CapturedWindowInfoDialog(unsigned long window, QWidget *parent) :
#endif
QDialog(parent),
ui(new Ui::CapturedWindowInfoDialog)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
selectedMatch = WindowNone;
#ifdef Q_OS_UNIX
X11Extras *info = X11Extras::getInstance();
ui->winPathChoiceComboBox->setVisible(false);
#endif
bool setRadioDefault = false;
fullWinPath = false;
#ifdef Q_OS_WIN
ui->winClassCheckBox->setVisible(false);
ui->winClassLabel->setVisible(false);
ui->winClassHeadLabel->setVisible(false);
#else
winClass = info->getWindowClass(window);
ui->winClassLabel->setText(winClass);
if (winClass.isEmpty())
{
ui->winClassCheckBox->setEnabled(false);
ui->winClassCheckBox->setChecked(false);
}
else
{
ui->winClassCheckBox->setChecked(true);
setRadioDefault = true;
}
ui->winPathChoiceComboBox->setVisible(false);
#endif
#ifdef Q_OS_WIN
winName = WinExtras::getCurrentWindowText();
#else
winName = info->getWindowTitle(window);
#endif
ui->winTitleLabel->setText(winName);
if (winName.isEmpty())
{
ui->winTitleCheckBox->setEnabled(false);
ui->winTitleCheckBox->setChecked(false);
}
else if (!setRadioDefault)
{
ui->winTitleCheckBox->setChecked(true);
setRadioDefault = true;
}
ui->winPathLabel->clear();
#ifdef Q_OS_WIN
winPath = WinExtras::getForegroundWindowExePath();
ui->winPathLabel->setText(winPath);
if (winPath.isEmpty())
{
ui->winPathCheckBox->setEnabled(false);
ui->winPathCheckBox->setChecked(false);
}
else
{
ui->winPathCheckBox->setChecked(true);
ui->winTitleCheckBox->setChecked(false);
setRadioDefault = true;
}
#elif defined(Q_OS_LINUX)
int pid = info->getApplicationPid(window);
if (pid > 0)
{
QString exepath = X11Extras::getInstance()->getApplicationLocation(pid);
if (!exepath.isEmpty())
{
ui->winPathLabel->setText(exepath);
winPath = exepath;
if (!setRadioDefault)
{
ui->winTitleCheckBox->setChecked(true);
setRadioDefault = true;
}
}
else
{
ui->winPathCheckBox->setEnabled(false);
ui->winPathCheckBox->setChecked(false);
}
}
else
{
ui->winPathCheckBox->setEnabled(false);
ui->winPathCheckBox->setChecked(false);
}
#endif
if (winClass.isEmpty() && winName.isEmpty() &&
winPath.isEmpty())
{
QPushButton *button = ui->buttonBox->button(QDialogButtonBox::Ok);
button->setEnabled(false);
}
connect(this, SIGNAL(accepted()), this, SLOT(populateOption()));
}
CapturedWindowInfoDialog::~CapturedWindowInfoDialog()
{
delete ui;
}
void CapturedWindowInfoDialog::populateOption()
{
if (ui->winClassCheckBox->isChecked())
{
selectedMatch = selectedMatch | WindowClass;
}
if (ui->winTitleCheckBox->isChecked())
{
selectedMatch = selectedMatch | WindowName;
}
if (ui->winPathCheckBox->isChecked())
{
selectedMatch = selectedMatch | WindowPath;
if (ui->winPathChoiceComboBox->currentIndex() == 0)
{
fullWinPath = true;
}
else
{
fullWinPath = false;
}
}
}
CapturedWindowInfoDialog::CapturedWindowOption CapturedWindowInfoDialog::getSelectedOptions()
{
return selectedMatch;
}
QString CapturedWindowInfoDialog::getWindowClass()
{
return winClass;
}
QString CapturedWindowInfoDialog::getWindowName()
{
return winName;
}
QString CapturedWindowInfoDialog::getWindowPath()
{
return winPath;
}
bool CapturedWindowInfoDialog::useFullWindowPath()
{
return fullWinPath;
}
``` | /content/code_sandbox/src/capturedwindowinfodialog.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,071 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef AXISVALUEBOX_H
#define AXISVALUEBOX_H
#include <QWidget>
class AxisValueBox : public QWidget
{
Q_OBJECT
public:
explicit AxisValueBox(QWidget *parent = 0);
int getDeadZone();
int getMaxZone();
int getJoyValue();
int getThrottle();
protected:
virtual void resizeEvent(QResizeEvent *event);
virtual void paintEvent(QPaintEvent *event);
int deadZone;
int maxZone;
int joyValue;
int throttle;
int boxwidth;
int boxheight;
int lboxstart;
int lboxend;
int rboxstart;
int rboxend;
int singlewidth;
int singleend;
signals:
public slots:
void setThrottle(int throttle);
void setValue(int value);
void setDeadZone(int deadZone);
void setMaxZone(int maxZone);
};
#endif // AXISVALUEBOX_H
``` | /content/code_sandbox/src/axisvaluebox.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 295 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
//#include <QDebug>
#include <typeinfo>
#include "inputdevice.h"
const int InputDevice::NUMBER_JOYSETS = 8;
const int InputDevice::DEFAULTKEYPRESSTIME = 100;
const unsigned int InputDevice::DEFAULTKEYREPEATDELAY = 660; // 660 ms
const unsigned int InputDevice::DEFAULTKEYREPEATRATE = 40; // 40 ms. 25 times per second
const int InputDevice::RAISEDDEADZONE = 20000;
QRegExp InputDevice::emptyGUID("^[0]+$");
InputDevice::InputDevice(int deviceIndex, AntiMicroSettings *settings, QObject *parent) :
QObject(parent)
{
buttonDownCount = 0;
joyNumber = deviceIndex;
active_set = 0;
joystickID = 0;
keyPressTime = 0;
deviceEdited = false;
#ifdef Q_OS_WIN
keyRepeatEnabled = true;
#else
keyRepeatEnabled = false;
#endif
keyRepeatDelay = 0;
keyRepeatRate = 0;
rawAxisDeadZone = RAISEDDEADZONE;
this->settings = settings;
}
InputDevice::~InputDevice()
{
QHashIterator<int, SetJoystick*> iter(joystick_sets);
while (iter.hasNext())
{
SetJoystick *setjoystick = iter.next().value();
if (setjoystick)
{
delete setjoystick;
setjoystick = 0;
}
}
joystick_sets.clear();
}
int InputDevice::getJoyNumber()
{
return joyNumber;
}
int InputDevice::getRealJoyNumber()
{
int joynumber = getJoyNumber();
return joynumber + 1;
}
void InputDevice::reset()
{
resetButtonDownCount();
deviceEdited = false;
profileName = "";
//cali.clear();
//buttonstates.clear();
//axesstates.clear();
//dpadstates.clear();
for (int i=0; i < NUMBER_JOYSETS; i++)
{
SetJoystick* set = joystick_sets.value(i);
set->reset();
}
}
/**
* @brief Obtain current joystick element values, create new SetJoystick objects,
* and then transfer most recent joystick element values to new
* current set.
*/
void InputDevice::transferReset()
{
// Grab current states for all elements in old set
SetJoystick *current_set = joystick_sets.value(active_set);
for (int i = 0; i < current_set->getNumberButtons(); i++)
{
JoyButton *button = current_set->getJoyButton(i);
buttonstates.append(button->getButtonState());
}
for (int i = 0; i < current_set->getNumberAxes(); i++)
{
JoyAxis *axis = current_set->getJoyAxis(i);
axesstates.append(axis->getCurrentRawValue());
}
for (int i = 0; i < current_set->getNumberHats(); i++)
{
JoyDPad *dpad = current_set->getJoyDPad(i);
dpadstates.append(dpad->getCurrentDirection());
}
reset();
}
void InputDevice::reInitButtons()
{
SetJoystick *current_set = joystick_sets.value(active_set);
for (int i = 0; i < current_set->getNumberButtons(); i++)
{
bool value = buttonstates.at(i);
JoyButton *button = current_set->getJoyButton(i);
//button->joyEvent(value);
button->queuePendingEvent(value);
}
for (int i = 0; i < current_set->getNumberAxes(); i++)
{
int value = axesstates.at(i);
JoyAxis *axis = current_set->getJoyAxis(i);
//axis->joyEvent(value);
axis->queuePendingEvent(value);
}
for (int i = 0; i < current_set->getNumberHats(); i++)
{
int value = dpadstates.at(i);
JoyDPad *dpad = current_set->getJoyDPad(i);
//dpad->joyEvent(value);
dpad->queuePendingEvent(value);
}
activatePossibleControlStickEvents();
activatePossibleAxisEvents();
activatePossibleDPadEvents();
activatePossibleVDPadEvents();
activatePossibleButtonEvents();
buttonstates.clear();
axesstates.clear();
dpadstates.clear();
}
void InputDevice::setActiveSetNumber(int index)
{
if ((index >= 0 && index < NUMBER_JOYSETS) && (index != active_set))
{
QList<bool> buttonstates;
QList<int> axesstates;
QList<int> dpadstates;
QList<JoyControlStick::JoyStickDirections> stickstates;
QList<int> vdpadstates;
// Grab current states for all elements in old set
SetJoystick *current_set = joystick_sets.value(active_set);
SetJoystick *old_set = current_set;
SetJoystick *tempSet = joystick_sets.value(index);
for (int i = 0; i < current_set->getNumberButtons(); i++)
{
JoyButton *button = current_set->getJoyButton(i);
buttonstates.append(button->getButtonState());
tempSet->getJoyButton(i)->copyLastMouseDistanceFromDeadZone(button);
tempSet->getJoyButton(i)->copyLastAccelerationDistance(button);
tempSet->getJoyButton(i)->setUpdateInitAccel(false);
}
for (int i = 0; i < current_set->getNumberAxes(); i++)
{
JoyAxis *axis = current_set->getJoyAxis(i);
axesstates.append(axis->getCurrentRawValue());
tempSet->getJoyAxis(i)->copyRawValues(axis);
tempSet->getJoyAxis(i)->copyThrottledValues(axis);
JoyAxisButton *button = tempSet->getJoyAxis(i)->getAxisButtonByValue(axis->getCurrentRawValue());
if (button)
{
button->setUpdateInitAccel(false);
}
}
for (int i = 0; i < current_set->getNumberHats(); i++)
{
JoyDPad *dpad = current_set->getJoyDPad(i);
dpadstates.append(dpad->getCurrentDirection());
JoyDPadButton::JoyDPadDirections tempDir =
static_cast<JoyDPadButton::JoyDPadDirections>(dpad->getCurrentDirection());
tempSet->getJoyDPad(i)->setDirButtonsUpdateInitAccel(tempDir, false);
tempSet->getJoyDPad(i)->copyLastDistanceValues(dpad);
}
for (int i=0; i < current_set->getNumberSticks(); i++)
{
// Last distances for elements are taken from associated axes.
// Copying is not required here.
JoyControlStick *stick = current_set->getJoyStick(i);
stickstates.append(stick->getCurrentDirection());
tempSet->getJoyStick(i)->setDirButtonsUpdateInitAccel(stick->getCurrentDirection(), false);
}
for (int i = 0; i < current_set->getNumberVDPads(); i++)
{
JoyDPad *dpad = current_set->getVDPad(i);
vdpadstates.append(dpad->getCurrentDirection());
JoyDPadButton::JoyDPadDirections tempDir =
static_cast<JoyDPadButton::JoyDPadDirections>(dpad->getCurrentDirection());
tempSet->getVDPad(i)->setDirButtonsUpdateInitAccel(tempDir, false);
tempSet->getVDPad(i)->copyLastDistanceValues(dpad);
}
// Release all current pressed elements and change set number
joystick_sets.value(active_set)->release();
active_set = index;
// Activate all buttons in the switched set
current_set = joystick_sets.value(active_set);
for (int i=0; i < current_set->getNumberSticks(); i++)
{
JoyControlStick::JoyStickDirections value = stickstates.at(i);
//bool tempignore = true;
bool tempignore = false;
QList<JoyControlStickButton*> buttonList;
QList<JoyControlStickButton*> oldButtonList;
JoyControlStick *stick = current_set->getJoyStick(i);
JoyControlStick *oldStick = old_set->getJoyStick(i);
if (stick->getJoyMode() == JoyControlStick::StandardMode && value)
{
switch (value)
{
case JoyControlStick::StickRightUp:
{
buttonList.append(stick->getDirectionButton(JoyControlStick::StickUp));
buttonList.append(stick->getDirectionButton(JoyControlStick::StickRight));
oldButtonList.append(oldStick->getDirectionButton(JoyControlStick::StickUp));
oldButtonList.append(oldStick->getDirectionButton(JoyControlStick::StickRight));
break;
}
case JoyControlStick::StickRightDown:
{
buttonList.append(stick->getDirectionButton(JoyControlStick::StickRight));
buttonList.append(stick->getDirectionButton(JoyControlStick::StickDown));
oldButtonList.append(oldStick->getDirectionButton(JoyControlStick::StickRight));
oldButtonList.append(oldStick->getDirectionButton(JoyControlStick::StickDown));
break;
}
case JoyControlStick::StickLeftDown:
{
buttonList.append(stick->getDirectionButton(JoyControlStick::StickDown));
buttonList.append(stick->getDirectionButton(JoyControlStick::StickLeft));
oldButtonList.append(oldStick->getDirectionButton(JoyControlStick::StickDown));
oldButtonList.append(oldStick->getDirectionButton(JoyControlStick::StickLeft));
break;
}
case JoyControlStick::StickLeftUp:
{
buttonList.append(stick->getDirectionButton(JoyControlStick::StickLeft));
buttonList.append(stick->getDirectionButton(JoyControlStick::StickUp));
oldButtonList.append(oldStick->getDirectionButton(JoyControlStick::StickLeft));
oldButtonList.append(oldStick->getDirectionButton(JoyControlStick::StickUp));
break;
}
default:
{
buttonList.append(stick->getDirectionButton(value));
oldButtonList.append(oldStick->getDirectionButton(value));
}
}
}
else if (value)
{
buttonList.append(stick->getDirectionButton(value));
oldButtonList.append(oldStick->getDirectionButton(value));
}
QHashIterator<JoyControlStick::JoyStickDirections, JoyControlStickButton*> iter(*stick->getButtons());
while (iter.hasNext())
{
JoyControlStickButton *tempButton = iter.next().value();
if (!buttonList.contains(tempButton))
{
tempButton->setWhileHeldStatus(false);
}
}
for (int j=0; j < buttonList.size(); j++)
{
JoyControlStickButton *button = buttonList.at(j);
JoyControlStickButton *oldButton = oldButtonList.at(j);
if (button && oldButton)
{
if (button->getChangeSetCondition() == JoyButton::SetChangeWhileHeld)
{
if (oldButton->getChangeSetCondition() == JoyButton::SetChangeWhileHeld && oldButton->getWhileHeldStatus())
{
// Button from old set involved in a while held set
// change. Carry over to new set button to ensure
// set changes are done in the proper order.
button->setWhileHeldStatus(true);
}
else if (!button->getWhileHeldStatus())
{
// Ensure that set change events are performed if needed.
tempignore = false;
}
}
}
}
}
// Activate all dpad buttons in the switched set
for (int i = 0; i < current_set->getNumberVDPads(); i++)
{
int value = vdpadstates.at(i);
//bool tempignore = true;
bool tempignore = false;
JoyDPad *dpad = current_set->getVDPad(i);
QList<JoyDPadButton*> buttonList;
QList<JoyDPadButton*> oldButtonList;
if (dpad->getJoyMode() == JoyDPad::StandardMode && value)
{
switch (value)
{
case JoyDPadButton::DpadRightUp:
{
buttonList.append(dpad->getJoyButton(JoyDPadButton::DpadUp));
buttonList.append(dpad->getJoyButton(JoyDPadButton::DpadRight));
oldButtonList.append(old_set->getVDPad(i)->getJoyButton(JoyDPadButton::DpadUp));
oldButtonList.append(old_set->getVDPad(i)->getJoyButton(JoyDPadButton::DpadRight));
break;
}
case JoyDPadButton::DpadRightDown:
{
buttonList.append(dpad->getJoyButton(JoyDPadButton::DpadRight));
buttonList.append(dpad->getJoyButton(JoyDPadButton::DpadDown));
oldButtonList.append(old_set->getVDPad(i)->getJoyButton(JoyDPadButton::DpadRight));
oldButtonList.append(old_set->getVDPad(i)->getJoyButton(JoyDPadButton::DpadDown));
break;
}
case JoyDPadButton::DpadLeftDown:
{
buttonList.append(dpad->getJoyButton(JoyDPadButton::DpadDown));
buttonList.append(dpad->getJoyButton(JoyDPadButton::DpadLeft));
oldButtonList.append(old_set->getVDPad(i)->getJoyButton(JoyDPadButton::DpadDown));
oldButtonList.append(old_set->getVDPad(i)->getJoyButton(JoyDPadButton::DpadLeft));
break;
}
case JoyDPadButton::DpadLeftUp:
{
buttonList.append(dpad->getJoyButton(JoyDPadButton::DpadLeft));
buttonList.append(dpad->getJoyButton(JoyDPadButton::DpadUp));
oldButtonList.append(old_set->getVDPad(i)->getJoyButton(JoyDPadButton::DpadLeft));
oldButtonList.append(old_set->getVDPad(i)->getJoyButton(JoyDPadButton::DpadUp));
break;
}
default:
{
buttonList.append(dpad->getJoyButton(value));
oldButtonList.append(old_set->getVDPad(i)->getJoyButton(value));
}
}
}
else if (value)
{
buttonList.append(dpad->getJoyButton(value));
oldButtonList.append(old_set->getVDPad(i)->getJoyButton(value));
}
QHashIterator<int, JoyDPadButton*> iter(*dpad->getJoyButtons());
while (iter.hasNext())
{
// Ensure that set change events are performed if needed.
JoyDPadButton *button = iter.next().value();
if (!buttonList.contains(button))
{
button->setWhileHeldStatus(false);
}
}
for (int j=0; j < buttonList.size(); j++)
{
JoyDPadButton *button = buttonList.at(j);
JoyDPadButton *oldButton = oldButtonList.at(j);
if (button && oldButton)
{
if (button->getChangeSetCondition() == JoyButton::SetChangeWhileHeld)
{
if (value)
{
if (oldButton->getChangeSetCondition() == JoyButton::SetChangeWhileHeld && oldButton->getWhileHeldStatus())
{
// Button from old set involved in a while held set
// change. Carry over to new set button to ensure
// set changes are done in the proper order.
button->setWhileHeldStatus(true);
}
else if (!button->getWhileHeldStatus())
{
// Ensure that set change events are performed if needed.
tempignore = false;
}
}
else
{
button->setWhileHeldStatus(false);
}
}
}
}
}
for (int i = 0; i < current_set->getNumberButtons(); i++)
{
bool value = buttonstates.at(i);
//bool tempignore = true;
bool tempignore = false;
JoyButton *button = current_set->getJoyButton(i);
JoyButton *oldButton = old_set->getJoyButton(i);
if (button->getChangeSetCondition() == JoyButton::SetChangeWhileHeld)
{
if (value)
{
if (oldButton->getChangeSetCondition() == JoyButton::SetChangeWhileHeld && oldButton->getWhileHeldStatus())
{
// Button from old set involved in a while held set
// change. Carry over to new set button to ensure
// set changes are done in the proper order.
button->setWhileHeldStatus(true);
}
else if (!button->getWhileHeldStatus())
{
// Ensure that set change events are performed if needed.
tempignore = false;
}
}
else
{
// Ensure that set change events are performed if needed.
button->setWhileHeldStatus(false);
//tempignore = false;
}
}
//button->joyEvent(value, tempignore);
button->queuePendingEvent(value, tempignore);
}
// Activate all axis buttons in the switched set
for (int i = 0; i < current_set->getNumberAxes(); i++)
{
int value = axesstates.at(i);
//bool tempignore = true;
bool tempignore = false;
JoyAxis *axis = current_set->getJoyAxis(i);
JoyAxisButton *oldButton = old_set->getJoyAxis(i)->getAxisButtonByValue(value);
JoyAxisButton *button = axis->getAxisButtonByValue(value);
if (button && oldButton)
{
if (button->getChangeSetCondition() == JoyButton::SetChangeWhileHeld)
{
if (oldButton->getChangeSetCondition() == JoyButton::SetChangeWhileHeld && oldButton->getWhileHeldStatus())
{
// Button from old set involved in a while held set
// change. Carry over to new set button to ensure
// set changes are done in the proper order.
button->setWhileHeldStatus(true);
}
else if (!button->getWhileHeldStatus())
{
// Ensure that set change events are performed if needed.
tempignore = false;
}
}
}
else if (!button)
{
// Ensure that set change events are performed if needed.
axis->getPAxisButton()->setWhileHeldStatus(false);
axis->getNAxisButton()->setWhileHeldStatus(false);
}
//axis->joyEvent(value, tempignore);
axis->queuePendingEvent(value, tempignore, false);
}
// Activate all dpad buttons in the switched set
for (int i = 0; i < current_set->getNumberHats(); i++)
{
int value = dpadstates.at(i);
//bool tempignore = true;
bool tempignore = false;
JoyDPad *dpad = current_set->getJoyDPad(i);
QList<JoyDPadButton*> buttonList;
QList<JoyDPadButton*> oldButtonList;
if (dpad->getJoyMode() == JoyDPad::StandardMode && value)
{
switch (value)
{
case JoyDPadButton::DpadRightUp:
{
buttonList.append(dpad->getJoyButton(JoyDPadButton::DpadUp));
buttonList.append(dpad->getJoyButton(JoyDPadButton::DpadRight));
oldButtonList.append(old_set->getJoyDPad(i)->getJoyButton(JoyDPadButton::DpadUp));
oldButtonList.append(old_set->getJoyDPad(i)->getJoyButton(JoyDPadButton::DpadRight));
break;
}
case JoyDPadButton::DpadRightDown:
{
buttonList.append(dpad->getJoyButton(JoyDPadButton::DpadRight));
buttonList.append(dpad->getJoyButton(JoyDPadButton::DpadDown));
oldButtonList.append(old_set->getJoyDPad(i)->getJoyButton(JoyDPadButton::DpadRight));
oldButtonList.append(old_set->getJoyDPad(i)->getJoyButton(JoyDPadButton::DpadDown));
break;
}
case JoyDPadButton::DpadLeftDown:
{
buttonList.append(dpad->getJoyButton(JoyDPadButton::DpadDown));
buttonList.append(dpad->getJoyButton(JoyDPadButton::DpadLeft));
oldButtonList.append(old_set->getJoyDPad(i)->getJoyButton(JoyDPadButton::DpadDown));
oldButtonList.append(old_set->getJoyDPad(i)->getJoyButton(JoyDPadButton::DpadLeft));
break;
}
case JoyDPadButton::DpadLeftUp:
{
buttonList.append(dpad->getJoyButton(JoyDPadButton::DpadLeft));
buttonList.append(dpad->getJoyButton(JoyDPadButton::DpadUp));
oldButtonList.append(old_set->getJoyDPad(i)->getJoyButton(JoyDPadButton::DpadLeft));
oldButtonList.append(old_set->getJoyDPad(i)->getJoyButton(JoyDPadButton::DpadUp));
break;
}
default:
{
buttonList.append(dpad->getJoyButton(value));
oldButtonList.append(old_set->getJoyDPad(i)->getJoyButton(value));
}
}
}
else if (value)
{
buttonList.append(dpad->getJoyButton(value));
oldButtonList.append(old_set->getJoyDPad(i)->getJoyButton(value));
}
QHashIterator<int, JoyDPadButton*> iter(*dpad->getJoyButtons());
while (iter.hasNext())
{
// Ensure that set change events are performed if needed.
JoyDPadButton *button = iter.next().value();
if (!buttonList.contains(button))
{
button->setWhileHeldStatus(false);
}
}
for (int j=0; j < buttonList.size(); j++)
{
JoyDPadButton *button = buttonList.at(j);
JoyDPadButton *oldButton = oldButtonList.at(j);
if (button && oldButton)
{
if (button->getChangeSetCondition() == JoyButton::SetChangeWhileHeld)
{
if (value)
{
if (oldButton->getChangeSetCondition() == JoyButton::SetChangeWhileHeld && oldButton->getWhileHeldStatus())
{
// Button from old set involved in a while held set
// change. Carry over to new set button to ensure
// set changes are done in the proper order.
button->setWhileHeldStatus(true);
}
else if (!button->getWhileHeldStatus())
{
// Ensure that set change events are performed if needed.
tempignore = false;
}
}
else
{
button->setWhileHeldStatus(false);
}
}
}
}
//dpad->joyEvent(value, tempignore);
dpad->queuePendingEvent(value, tempignore);
}
activatePossibleControlStickEvents();
activatePossibleAxisEvents();
activatePossibleDPadEvents();
activatePossibleVDPadEvents();
activatePossibleButtonEvents();
/*if (JoyButton::shouldInvokeMouseEvents())
{
// Run mouse events early if needed.
JoyButton::invokeMouseEvents();
}
*/
}
}
int InputDevice::getActiveSetNumber()
{
return active_set;
}
SetJoystick* InputDevice::getActiveSetJoystick()
{
return joystick_sets.value(active_set);
}
int InputDevice::getNumberButtons()
{
return getActiveSetJoystick()->getNumberButtons();
}
int InputDevice::getNumberAxes()
{
return getActiveSetJoystick()->getNumberAxes();
}
int InputDevice::getNumberHats()
{
return getActiveSetJoystick()->getNumberHats();
}
int InputDevice::getNumberSticks()
{
return getActiveSetJoystick()->getNumberSticks();
}
int InputDevice::getNumberVDPads()
{
return getActiveSetJoystick()->getNumberVDPads();
}
SetJoystick* InputDevice::getSetJoystick(int index)
{
return joystick_sets.value(index);
}
void InputDevice::propogateSetChange(int index)
{
emit setChangeActivated(index);
}
void InputDevice::changeSetButtonAssociation(int button_index, int originset, int newset, int mode)
{
JoyButton *button = joystick_sets.value(newset)->getJoyButton(button_index);
JoyButton::SetChangeCondition tempmode = (JoyButton::SetChangeCondition)mode;
button->setChangeSetSelection(originset);
button->setChangeSetCondition(tempmode, true);
}
void InputDevice::readConfig(QXmlStreamReader *xml)
{
if (xml->isStartElement() && xml->name() == getXmlName())
{
//reset();
transferReset();
xml->readNextStartElement();
while (!xml->atEnd() && (!xml->isEndElement() && xml->name() != getXmlName()))
{
if (xml->name() == "sets" && xml->isStartElement())
{
xml->readNextStartElement();
while (!xml->atEnd() && (!xml->isEndElement() && xml->name() != "sets"))
{
if (xml->name() == "set" && xml->isStartElement())
{
int index = xml->attributes().value("index").toString().toInt();
index = index - 1;
if (index >= 0 && index < joystick_sets.size())
{
joystick_sets.value(index)->readConfig(xml);
}
}
else
{
// If none of the above, skip the element
xml->skipCurrentElement();
}
xml->readNextStartElement();
}
}
else if (xml->name() == "stickAxisAssociation" && xml->isStartElement())
{
int stickIndex = xml->attributes().value("index").toString().toInt();
int xAxis = xml->attributes().value("xAxis").toString().toInt();
int yAxis = xml->attributes().value("yAxis").toString().toInt();
if (stickIndex > 0 && xAxis > 0 && yAxis > 0)
{
xAxis -= 1;
yAxis -= 1;
stickIndex -= 1;
for (int i=0; i <joystick_sets.size(); i++)
{
SetJoystick *currentset = joystick_sets.value(i);
JoyAxis *axis1 = currentset->getJoyAxis(xAxis);
JoyAxis *axis2 = currentset->getJoyAxis(yAxis);
if (axis1 && axis2)
{
JoyControlStick *stick = new JoyControlStick(axis1, axis2, stickIndex, i, this);
currentset->addControlStick(stickIndex, stick);
}
}
xml->readNext();
}
else
{
xml->skipCurrentElement();
}
}
else if (xml->name() == "vdpadButtonAssociations" && xml->isStartElement())
{
int vdpadIndex = xml->attributes().value("index").toString().toInt();
if (vdpadIndex > 0)
{
for (int i=0; i <joystick_sets.size(); i++)
{
SetJoystick *currentset = joystick_sets.value(i);
VDPad *vdpad = currentset->getVDPad(vdpadIndex-1);
if (!vdpad)
{
vdpad = new VDPad(vdpadIndex-1, i, currentset, currentset);
currentset->addVDPad(vdpadIndex-1, vdpad);
}
}
xml->readNextStartElement();
while (!xml->atEnd() && (!xml->isEndElement() && xml->name() != "vdpadButtonAssociations"))
{
if (xml->name() == "vdpadButtonAssociation" && xml->isStartElement())
{
int vdpadAxisIndex = xml->attributes().value("axis").toString().toInt();
int vdpadButtonIndex = xml->attributes().value("button").toString().toInt();
int vdpadDirection = xml->attributes().value("direction").toString().toInt();
if (vdpadAxisIndex > 0 && vdpadDirection > 0)
{
vdpadAxisIndex -= 1;
for (int i=0; i < joystick_sets.size(); i++)
{
SetJoystick *currentset = joystick_sets.value(i);
VDPad *vdpad = currentset->getVDPad(vdpadIndex-1);
if (vdpad)
{
JoyAxis *axis = currentset->getJoyAxis(vdpadAxisIndex);
if (axis)
{
JoyButton *button = 0;
if (vdpadButtonIndex == 0)
{
button = axis->getNAxisButton();
}
else if (vdpadButtonIndex == 1)
{
button = axis->getPAxisButton();
}
if (button)
{
vdpad->addVButton((JoyDPadButton::JoyDPadDirections)vdpadDirection, button);
}
}
}
}
}
else if (vdpadButtonIndex > 0 && vdpadDirection > 0)
{
vdpadButtonIndex -= 1;
for (int i=0; i < joystick_sets.size(); i++)
{
SetJoystick *currentset = joystick_sets.value(i);
VDPad *vdpad = currentset->getVDPad(vdpadIndex-1);
if (vdpad)
{
JoyButton *button = currentset->getJoyButton(vdpadButtonIndex);
if (button)
{
vdpad->addVButton((JoyDPadButton::JoyDPadDirections)vdpadDirection, button);
}
}
}
}
xml->readNext();
}
else
{
xml->skipCurrentElement();
}
xml->readNextStartElement();
}
}
for (int i=0; i < joystick_sets.size(); i++)
{
SetJoystick *currentset = joystick_sets.value(i);
for (int j=0; j < currentset->getNumberVDPads(); j++)
{
VDPad *vdpad = currentset->getVDPad(j);
if (vdpad && vdpad->isEmpty())
{
currentset->removeVDPad(j);
}
}
}
}
else if (xml->name() == "names" && xml->isStartElement())
{
xml->readNextStartElement();
while (!xml->atEnd() && (!xml->isEndElement() && xml->name() != "names"))
{
if (xml->name() == "buttonname" && xml->isStartElement())
{
int index = xml->attributes().value("index").toString().toInt();
QString temp = xml->readElementText();
index = index - 1;
if (index >= 0 && !temp.isEmpty())
{
setButtonName(index, temp);
}
}
else if (xml->name() == "axisbuttonname" && xml->isStartElement())
{
int index = xml->attributes().value("index").toString().toInt();
int buttonIndex = xml->attributes().value("button").toString().toInt();
QString temp = xml->readElementText();
index = index - 1;
buttonIndex = buttonIndex - 1;
if (index >= 0 && !temp.isEmpty())
{
setAxisButtonName(index, buttonIndex, temp);
}
}
else if (xml->name() == "controlstickbuttonname" && xml->isStartElement())
{
int index = xml->attributes().value("index").toString().toInt();
int buttonIndex = xml->attributes().value("button").toString().toInt();
QString temp = xml->readElementText();
index = index - 1;
if (index >= 0 && !temp.isEmpty())
{
setStickButtonName(index, buttonIndex, temp);
}
}
else if (xml->name() == "dpadbuttonname" && xml->isStartElement())
{
int index = xml->attributes().value("index").toString().toInt();
int buttonIndex = xml->attributes().value("button").toString().toInt();
QString temp = xml->readElementText();
index = index - 1;
if (index >= 0 && !temp.isEmpty())
{
setDPadButtonName(index, buttonIndex, temp);
}
}
else if (xml->name() == "vdpadbuttonname" && xml->isStartElement())
{
int index = xml->attributes().value("index").toString().toInt();
int buttonIndex = xml->attributes().value("button").toString().toInt();
QString temp = xml->readElementText();
index = index - 1;
if (index >= 0 && !temp.isEmpty())
{
setVDPadButtonName(index, buttonIndex, temp);
}
}
else if (xml->name() == "axisname" && xml->isStartElement())
{
int index = xml->attributes().value("index").toString().toInt();
QString temp = xml->readElementText();
index = index - 1;
if (index >= 0 && !temp.isEmpty())
{
setAxisName(index, temp);
}
}
else if (xml->name() == "controlstickname" && xml->isStartElement())
{
int index = xml->attributes().value("index").toString().toInt();
QString temp = xml->readElementText();
index = index - 1;
if (index >= 0 && !temp.isEmpty())
{
setStickName(index, temp);
}
}
else if (xml->name() == "dpadname" && xml->isStartElement())
{
int index = xml->attributes().value("index").toString().toInt();
QString temp = xml->readElementText();
index = index - 1;
if (index >= 0 && !temp.isEmpty())
{
setDPadName(index, temp);
}
}
else if (xml->name() == "vdpadname" && xml->isStartElement())
{
int index = xml->attributes().value("index").toString().toInt();
QString temp = xml->readElementText();
index = index - 1;
if (index >= 0 && !temp.isEmpty())
{
setVDPadName(index, temp);
}
}
else
{
// If none of the above, skip the element
xml->skipCurrentElement();
}
xml->readNextStartElement();
}
}
else if (xml->name() == "keyPressTime" && xml->isStartElement())
{
QString temptext = xml->readElementText();
int tempchoice = temptext.toInt();
if (tempchoice >= 10)
{
this->setDeviceKeyPressTime(tempchoice);
}
}
else if (xml->name() == "profilename" && xml->isStartElement())
{
QString temptext = xml->readElementText();
this->setProfileName(temptext);
}
else
{
// If none of the above, skip the element
xml->skipCurrentElement();
}
xml->readNextStartElement();
}
reInitButtons();
}
}
void InputDevice::writeConfig(QXmlStreamWriter *xml)
{
xml->writeStartElement(getXmlName());
xml->writeAttribute("configversion", QString::number(PadderCommon::LATESTCONFIGFILEVERSION));
xml->writeAttribute("appversion", PadderCommon::programVersion);
xml->writeComment("The SDL name for a joystick is included for informational purposes only.");
xml->writeTextElement("sdlname", getSDLName());
#ifdef USE_SDL_2
xml->writeComment("The GUID for a joystick is included for informational purposes only.");
xml->writeTextElement("guid", getGUIDString());
#endif
if (!profileName.isEmpty())
{
xml->writeTextElement("profilename", profileName);
}
for (int i=0; i < getNumberSticks(); i++)
{
JoyControlStick *stick = getActiveSetJoystick()->getJoyStick(i);
xml->writeStartElement("stickAxisAssociation");
xml->writeAttribute("index", QString::number(stick->getRealJoyIndex()));
xml->writeAttribute("xAxis", QString::number(stick->getAxisX()->getRealJoyIndex()));
xml->writeAttribute("yAxis", QString::number(stick->getAxisY()->getRealJoyIndex()));
xml->writeEndElement();
}
for (int i=0; i < getNumberVDPads(); i++)
{
VDPad *vdpad = getActiveSetJoystick()->getVDPad(i);
xml->writeStartElement("vdpadButtonAssociations");
xml->writeAttribute("index", QString::number(vdpad->getRealJoyNumber()));
JoyButton *button = vdpad->getVButton(JoyDPadButton::DpadUp);
if (button)
{
xml->writeStartElement("vdpadButtonAssociation");
if (typeid(*button) == typeid(JoyAxisButton))
{
JoyAxisButton *axisbutton = static_cast<JoyAxisButton*>(button);
xml->writeAttribute("axis", QString::number(axisbutton->getAxis()->getRealJoyIndex()));
xml->writeAttribute("button", QString::number(button->getJoyNumber()));
}
else
{
xml->writeAttribute("axis", QString::number(0));
xml->writeAttribute("button", QString::number(button->getRealJoyNumber()));
}
xml->writeAttribute("direction", QString::number(JoyDPadButton::DpadUp));
xml->writeEndElement();
}
button = vdpad->getVButton(JoyDPadButton::DpadDown);
if (button)
{
xml->writeStartElement("vdpadButtonAssociation");
if (typeid(*button) == typeid(JoyAxisButton))
{
JoyAxisButton *axisbutton = static_cast<JoyAxisButton*>(button);
xml->writeAttribute("axis", QString::number(axisbutton->getAxis()->getRealJoyIndex()));
xml->writeAttribute("button", QString::number(button->getJoyNumber()));
}
else
{
xml->writeAttribute("axis", QString::number(0));
xml->writeAttribute("button", QString::number(button->getRealJoyNumber()));
}
xml->writeAttribute("direction", QString::number(JoyDPadButton::DpadDown));
xml->writeEndElement();
}
button = vdpad->getVButton(JoyDPadButton::DpadLeft);
if (button)
{
xml->writeStartElement("vdpadButtonAssociation");
if (typeid(*button) == typeid(JoyAxisButton))
{
JoyAxisButton *axisbutton = static_cast<JoyAxisButton*>(button);
xml->writeAttribute("axis", QString::number(axisbutton->getAxis()->getRealJoyIndex()));
xml->writeAttribute("button", QString::number(button->getJoyNumber()));
}
else
{
xml->writeAttribute("axis", QString::number(0));
xml->writeAttribute("button", QString::number(button->getRealJoyNumber()));
}
xml->writeAttribute("direction", QString::number(JoyDPadButton::DpadLeft));
xml->writeEndElement();
}
button = vdpad->getVButton(JoyDPadButton::DpadRight);
if (button)
{
xml->writeStartElement("vdpadButtonAssociation");
if (typeid(*button) == typeid(JoyAxisButton))
{
JoyAxisButton *axisbutton = static_cast<JoyAxisButton*>(button);
xml->writeAttribute("axis", QString::number(axisbutton->getAxis()->getRealJoyIndex()));
xml->writeAttribute("button", QString::number(button->getJoyNumber()));
}
else
{
xml->writeAttribute("axis", QString::number(0));
xml->writeAttribute("button", QString::number(button->getRealJoyNumber()));
}
xml->writeAttribute("direction", QString::number(JoyDPadButton::DpadRight));
xml->writeEndElement();
}
xml->writeEndElement();
}
bool tempHasNames = elementsHaveNames();
if (tempHasNames)
{
xml->writeStartElement("names"); // <name>
SetJoystick *tempSet = getActiveSetJoystick();
for (int i=0; i < getNumberButtons(); i++)
{
JoyButton *button = tempSet->getJoyButton(i);
if (button && !button->getButtonName().isEmpty())
{
xml->writeStartElement("buttonname");
xml->writeAttribute("index", QString::number(button->getRealJoyNumber()));
xml->writeCharacters(button->getButtonName());
xml->writeEndElement();
}
}
for (int i=0; i < getNumberAxes(); i++)
{
JoyAxis *axis = tempSet->getJoyAxis(i);
if (axis)
{
if (!axis->getAxisName().isEmpty())
{
xml->writeStartElement("axisname");
xml->writeAttribute("index", QString::number(axis->getRealJoyIndex()));
xml->writeCharacters(axis->getAxisName());
xml->writeEndElement();
}
JoyAxisButton *naxisbutton = axis->getNAxisButton();
if (!naxisbutton->getButtonName().isEmpty())
{
xml->writeStartElement("axisbuttonname");
xml->writeAttribute("index", QString::number(axis->getRealJoyIndex()));
xml->writeAttribute("button", QString::number(naxisbutton->getRealJoyNumber()));
xml->writeCharacters(naxisbutton->getButtonName());
xml->writeEndElement();
}
JoyAxisButton *paxisbutton = axis->getPAxisButton();
if (!paxisbutton->getButtonName().isEmpty())
{
xml->writeStartElement("axisbuttonname");
xml->writeAttribute("index", QString::number(axis->getRealJoyIndex()));
xml->writeAttribute("button", QString::number(paxisbutton->getRealJoyNumber()));
xml->writeCharacters(paxisbutton->getButtonName());
xml->writeEndElement();
}
}
}
for (int i=0; i < getNumberSticks(); i++)
{
JoyControlStick *stick = tempSet->getJoyStick(i);
if (stick)
{
if (!stick->getStickName().isEmpty())
{
xml->writeStartElement("controlstickname");
xml->writeAttribute("index", QString::number(stick->getRealJoyIndex()));
xml->writeCharacters(stick->getStickName());
xml->writeEndElement();
}
QHash<JoyControlStick::JoyStickDirections, JoyControlStickButton*> *buttons = stick->getButtons();
QHashIterator<JoyControlStick::JoyStickDirections, JoyControlStickButton*> iter(*buttons);
while (iter.hasNext())
{
JoyControlStickButton *button = iter.next().value();
if (button && !button->getButtonName().isEmpty())
{
xml->writeStartElement("controlstickbuttonname");
xml->writeAttribute("index", QString::number(stick->getRealJoyIndex()));
xml->writeAttribute("button", QString::number(button->getRealJoyNumber()));
xml->writeCharacters(button->getButtonName());
xml->writeEndElement();
}
}
}
}
for (int i=0; i < getNumberHats(); i++)
{
JoyDPad *dpad = tempSet->getJoyDPad(i);
if (dpad)
{
if (!dpad->getDpadName().isEmpty())
{
xml->writeStartElement("dpadname");
xml->writeAttribute("index", QString::number(dpad->getRealJoyNumber()));
xml->writeCharacters(dpad->getDpadName());
xml->writeEndElement();
}
QHash<int, JoyDPadButton*> *temp = dpad->getButtons();
QHashIterator<int, JoyDPadButton*> iter(*temp);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
if (button && !button->getButtonName().isEmpty())
{
xml->writeStartElement("dpadbuttonname");
xml->writeAttribute("index", QString::number(dpad->getRealJoyNumber()));
xml->writeAttribute("button", QString::number(button->getRealJoyNumber()));
xml->writeCharacters(button->getButtonName());
xml->writeEndElement();
}
}
}
}
for (int i=0; i < getNumberVDPads(); i++)
{
VDPad *vdpad = getActiveSetJoystick()->getVDPad(i);
if (vdpad)
{
if (!vdpad->getDpadName().isEmpty())
{
xml->writeStartElement("vdpadname");
xml->writeAttribute("index", QString::number(vdpad->getRealJoyNumber()));
xml->writeCharacters(vdpad->getDpadName());
xml->writeEndElement();
}
QHash<int, JoyDPadButton*> *temp = vdpad->getButtons();
QHashIterator<int, JoyDPadButton*> iter(*temp);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
if (button && !button->getButtonName().isEmpty())
{
xml->writeStartElement("vdpadbutton");
xml->writeAttribute("index", QString::number(vdpad->getRealJoyNumber()));
xml->writeAttribute("button", QString::number(button->getRealJoyNumber()));
xml->writeCharacters(button->getButtonName());
xml->writeEndElement();
}
}
}
}
xml->writeEndElement(); // </names>
}
if (keyPressTime > 0 && keyPressTime != DEFAULTKEYPRESSTIME)
{
xml->writeTextElement("keyPressTime", QString::number(keyPressTime));
}
xml->writeStartElement("sets");
for (int i=0; i < joystick_sets.size(); i++)
{
joystick_sets.value(i)->writeConfig(xml);
}
xml->writeEndElement();
xml->writeEndElement();
}
void InputDevice::changeSetAxisButtonAssociation(int button_index, int axis_index, int originset, int newset, int mode)
{
JoyAxisButton *button = 0;
if (button_index == 0)
{
button = joystick_sets.value(newset)->getJoyAxis(axis_index)->getNAxisButton();
}
else if (button_index == 1)
{
button = joystick_sets.value(newset)->getJoyAxis(axis_index)->getPAxisButton();
}
JoyButton::SetChangeCondition tempmode = (JoyButton::SetChangeCondition)mode;
button->setChangeSetSelection(originset);
button->setChangeSetCondition(tempmode, true);
}
void InputDevice::changeSetStickButtonAssociation(int button_index, int stick_index, int originset, int newset, int mode)
{
JoyControlStickButton *button = joystick_sets.value(newset)->getJoyStick(stick_index)->getDirectionButton((JoyControlStick::JoyStickDirections)button_index);
JoyButton::SetChangeCondition tempmode = (JoyButton::SetChangeCondition)mode;
button->setChangeSetSelection(originset);
button->setChangeSetCondition(tempmode, true);
}
void InputDevice::changeSetDPadButtonAssociation(int button_index, int dpad_index, int originset, int newset, int mode)
{
JoyDPadButton *button = joystick_sets.value(newset)->getJoyDPad(dpad_index)->getJoyButton(button_index);
JoyButton::SetChangeCondition tempmode = (JoyButton::SetChangeCondition)mode;
button->setChangeSetSelection(originset);
button->setChangeSetCondition(tempmode, true);
}
void InputDevice::changeSetVDPadButtonAssociation(int button_index, int dpad_index, int originset, int newset, int mode)
{
JoyDPadButton *button = joystick_sets.value(newset)->getVDPad(dpad_index)->getJoyButton(button_index);
JoyButton::SetChangeCondition tempmode = (JoyButton::SetChangeCondition)mode;
button->setChangeSetSelection(originset);
button->setChangeSetCondition(tempmode, true);
}
void InputDevice::propogateSetAxisThrottleChange(int index, int originset)
{
SetJoystick *currentSet = joystick_sets.value(originset);
if (currentSet)
{
JoyAxis *axis = currentSet->getJoyAxis(index);
if (axis)
{
int throttleSetting = axis->getThrottle();
QHashIterator<int, SetJoystick*> iter(joystick_sets);
while (iter.hasNext())
{
iter.next();
SetJoystick *temp = iter.value();
// Ignore change for set axis that initiated the change
if (temp != currentSet)
{
temp->getJoyAxis(index)->setThrottle(throttleSetting);
}
}
}
}
}
void InputDevice::removeControlStick(int index)
{
for (int i=0; i < NUMBER_JOYSETS; i++)
{
SetJoystick *currentset = getSetJoystick(i);
if (currentset->getJoyStick(index))
{
currentset->removeControlStick(index);
}
}
}
bool InputDevice::isActive()
{
return buttonDownCount > 0;
}
void InputDevice::buttonDownEvent(int setindex, int buttonindex)
{
Q_UNUSED(setindex);
Q_UNUSED(buttonindex);
bool old = isActive();
buttonDownCount += 1;
if (isActive() != old)
{
emit clicked(joyNumber);
}
}
void InputDevice::buttonUpEvent(int setindex, int buttonindex)
{
Q_UNUSED(setindex);
Q_UNUSED(buttonindex);
bool old = isActive();
buttonDownCount -= 1;
if (buttonDownCount < 0)
{
buttonDownCount = 0;
}
if (isActive() != old)
{
emit released(joyNumber);
}
}
void InputDevice::buttonClickEvent(int buttonindex)
{
emit rawButtonClick(buttonindex);
}
void InputDevice::buttonReleaseEvent(int buttonindex)
{
emit rawButtonRelease(buttonindex);
}
void InputDevice::axisButtonDownEvent(int setindex, int axisindex, int buttonindex)
{
Q_UNUSED(axisindex);
buttonDownEvent(setindex, buttonindex);
}
void InputDevice::axisButtonUpEvent(int setindex, int axisindex, int buttonindex)
{
Q_UNUSED(axisindex);
buttonUpEvent(setindex, buttonindex);
}
void InputDevice::dpadButtonClickEvent(int buttonindex)
{
JoyDPadButton *dpadbutton = static_cast<JoyDPadButton*>(sender());
if (dpadbutton)
{
emit rawDPadButtonClick(dpadbutton->getDPad()->getIndex(), buttonindex);
}
}
void InputDevice::dpadButtonReleaseEvent(int buttonindex)
{
JoyDPadButton *dpadbutton = static_cast<JoyDPadButton*>(sender());
if (dpadbutton)
{
emit rawDPadButtonRelease(dpadbutton->getDPad()->getIndex(), buttonindex);
}
}
void InputDevice::dpadButtonDownEvent(int setindex, int dpadindex, int buttonindex)
{
Q_UNUSED(dpadindex);
buttonDownEvent(setindex, buttonindex);
}
void InputDevice::dpadButtonUpEvent(int setindex, int dpadindex, int buttonindex)
{
Q_UNUSED(dpadindex);
buttonUpEvent(setindex, buttonindex);
}
void InputDevice::stickButtonDownEvent(int setindex, int stickindex, int buttonindex)
{
Q_UNUSED(stickindex);
buttonDownEvent(setindex, buttonindex);
}
void InputDevice::stickButtonUpEvent(int setindex, int stickindex, int buttonindex)
{
Q_UNUSED(stickindex);
buttonUpEvent(setindex, buttonindex);
}
void InputDevice::setButtonName(int index, QString tempName)
{
QHashIterator<int, SetJoystick*> iter(joystick_sets);
while (iter.hasNext())
{
SetJoystick *tempSet = iter.next().value();
disconnect(tempSet, SIGNAL(setButtonNameChange(int)), this, SLOT(updateSetButtonNames(int)));
JoyButton *button = tempSet->getJoyButton(index);
if (button)
{
button->setButtonName(tempName);
}
connect(tempSet, SIGNAL(setButtonNameChange(int)), this, SLOT(updateSetButtonNames(int)));
}
}
void InputDevice::setAxisButtonName(int axisIndex, int buttonIndex, QString tempName)
{
QHashIterator<int, SetJoystick*> iter(joystick_sets);
while (iter.hasNext())
{
SetJoystick *tempSet = iter.next().value();
disconnect(tempSet, SIGNAL(setAxisButtonNameChange(int,int)), this, SLOT(updateSetAxisButtonNames(int,int)));
JoyAxis *axis = tempSet->getJoyAxis(axisIndex);
if (axis)
{
JoyAxisButton *button = 0;
if (buttonIndex == 0)
{
button = axis->getNAxisButton();
}
else if (buttonIndex == 1)
{
button = axis->getPAxisButton();
}
if (button)
{
button->setButtonName(tempName);
}
}
connect(tempSet, SIGNAL(setAxisButtonNameChange(int,int)), this, SLOT(updateSetAxisButtonNames(int,int)));
}
}
void InputDevice::setStickButtonName(int stickIndex, int buttonIndex, QString tempName)
{
QHashIterator<int, SetJoystick*> iter(joystick_sets);
while (iter.hasNext())
{
SetJoystick *tempSet = iter.next().value();
disconnect(tempSet, SIGNAL(setStickButtonNameChange(int,int)), this, SLOT(updateSetStickButtonNames(int,int)));
JoyControlStick *stick = tempSet->getJoyStick(stickIndex);
if (stick)
{
JoyControlStickButton *button = stick->getDirectionButton(JoyControlStick::JoyStickDirections(buttonIndex));
if (button)
{
button->setButtonName(tempName);
}
}
connect(tempSet, SIGNAL(setStickButtonNameChange(int,int)), this, SLOT(updateSetStickButtonNames(int,int)));
}
}
void InputDevice::setDPadButtonName(int dpadIndex, int buttonIndex, QString tempName)
{
QHashIterator<int, SetJoystick*> iter(joystick_sets);
while (iter.hasNext())
{
SetJoystick *tempSet = iter.next().value();
disconnect(tempSet, SIGNAL(setDPadButtonNameChange(int,int)), this, SLOT(updateSetDPadButtonNames(int,int)));
JoyDPad *dpad = tempSet->getJoyDPad(dpadIndex);
if (dpad)
{
JoyDPadButton *button = dpad->getJoyButton(buttonIndex);
if (button)
{
button->setButtonName(tempName);
}
}
connect(tempSet, SIGNAL(setDPadButtonNameChange(int,int)), this, SLOT(updateSetDPadButtonNames(int,int)));
}
}
void InputDevice::setVDPadButtonName(int vdpadIndex, int buttonIndex, QString tempName)
{
QHashIterator<int, SetJoystick*> iter(joystick_sets);
while (iter.hasNext())
{
SetJoystick *tempSet = iter.next().value();
disconnect(tempSet, SIGNAL(setVDPadButtonNameChange(int,int)), this, SLOT(updateSetVDPadButtonNames(int,int)));
VDPad *vdpad = tempSet->getVDPad(vdpadIndex);
if (vdpad)
{
JoyDPadButton *button = vdpad->getJoyButton(buttonIndex);
if (button)
{
button->setButtonName(tempName);
}
}
connect(tempSet, SIGNAL(setVDPadButtonNameChange(int,int)), this, SLOT(updateSetVDPadButtonNames(int,int)));
}
}
void InputDevice::setAxisName(int axisIndex, QString tempName)
{
QHashIterator<int, SetJoystick*> iter(joystick_sets);
while (iter.hasNext())
{
SetJoystick *tempSet = iter.next().value();
disconnect(tempSet, SIGNAL(setAxisNameChange(int)), this, SLOT(updateSetAxisNames(int)));
JoyAxis *axis = tempSet->getJoyAxis(axisIndex);
if (axis)
{
axis->setAxisName(tempName);
}
connect(tempSet, SIGNAL(setAxisNameChange(int)), this, SLOT(updateSetAxisNames(int)));
}
}
void InputDevice::setStickName(int stickIndex, QString tempName)
{
QHashIterator<int, SetJoystick*> iter(joystick_sets);
while (iter.hasNext())
{
SetJoystick *tempSet = iter.next().value();
disconnect(tempSet, SIGNAL(setStickNameChange(int)), this, SLOT(updateSetStickNames(int)));
JoyControlStick *stick = tempSet->getJoyStick(stickIndex);
if (stick)
{
stick->setStickName(tempName);
}
connect(tempSet, SIGNAL(setStickNameChange(int)), this, SLOT(updateSetStickNames(int)));
}
}
void InputDevice::setDPadName(int dpadIndex, QString tempName)
{
QHashIterator<int, SetJoystick*> iter(joystick_sets);
while (iter.hasNext())
{
SetJoystick *tempSet = iter.next().value();
disconnect(tempSet, SIGNAL(setDPadNameChange(int)), this, SLOT(updateSetDPadNames(int)));
JoyDPad *dpad = tempSet->getJoyDPad(dpadIndex);
if (dpad)
{
dpad->setDPadName(tempName);
}
connect(tempSet, SIGNAL(setDPadNameChange(int)), this, SLOT(updateSetDPadNames(int)));
}
}
void InputDevice::setVDPadName(int vdpadIndex, QString tempName)
{
QHashIterator<int, SetJoystick*> iter(joystick_sets);
while (iter.hasNext())
{
SetJoystick *tempSet = iter.next().value();
disconnect(tempSet, SIGNAL(setVDPadNameChange(int)), this, SLOT(updateSetVDPadNames(int)));
VDPad *vdpad = tempSet->getVDPad(vdpadIndex);
if (vdpad)
{
vdpad->setDPadName(tempName);
}
connect(tempSet, SIGNAL(setVDPadNameChange(int)), this, SLOT(updateSetVDPadNames(int)));
}
}
void InputDevice::updateSetButtonNames(int index)
{
JoyButton *button = getActiveSetJoystick()->getJoyButton(index);
if (button)
{
setButtonName(index, button->getButtonName());
}
}
void InputDevice::updateSetAxisButtonNames(int axisIndex, int buttonIndex)
{
JoyAxis *axis = getActiveSetJoystick()->getJoyAxis(axisIndex);
if (axis)
{
JoyAxisButton *button = 0;
if (buttonIndex == 0)
{
button = axis->getNAxisButton();
}
else if (buttonIndex == 1)
{
button = axis->getPAxisButton();
}
if (button)
{
setAxisButtonName(axisIndex, buttonIndex, button->getButtonName());
}
}
}
void InputDevice::updateSetStickButtonNames(int stickIndex, int buttonIndex)
{
JoyControlStick *stick = getActiveSetJoystick()->getJoyStick(stickIndex);
if (stick)
{
JoyControlStickButton *button = stick->getDirectionButton(JoyControlStick::JoyStickDirections(buttonIndex));
if (button)
{
setStickButtonName(stickIndex, buttonIndex, button->getButtonName());
}
}
}
void InputDevice::updateSetDPadButtonNames(int dpadIndex, int buttonIndex)
{
JoyDPad *dpad = getActiveSetJoystick()->getJoyDPad(dpadIndex);
if (dpad)
{
JoyDPadButton *button = dpad->getJoyButton(buttonIndex);
if (button)
{
setDPadButtonName(dpadIndex, buttonIndex, button->getButtonName());
}
}
}
void InputDevice::updateSetVDPadButtonNames(int vdpadIndex, int buttonIndex)
{
VDPad *vdpad = getActiveSetJoystick()->getVDPad(vdpadIndex);
if (vdpad)
{
JoyDPadButton *button = vdpad->getJoyButton(buttonIndex);
if (button)
{
setVDPadButtonName(vdpadIndex, buttonIndex, button->getButtonName());
}
}
}
void InputDevice::updateSetAxisNames(int axisIndex)
{
JoyAxis *axis = getActiveSetJoystick()->getJoyAxis(axisIndex);
if (axis)
{
setAxisName(axisIndex, axis->getAxisName());
}
}
void InputDevice::updateSetStickNames(int stickIndex)
{
JoyControlStick *stick = getActiveSetJoystick()->getJoyStick(stickIndex);
if (stick)
{
setStickName(stickIndex, stick->getStickName());
}
}
void InputDevice::updateSetDPadNames(int dpadIndex)
{
JoyDPad *dpad = getActiveSetJoystick()->getJoyDPad(dpadIndex);
if (dpad)
{
setDPadName(dpadIndex, dpad->getDpadName());
}
}
void InputDevice::updateSetVDPadNames(int vdpadIndex)
{
VDPad *vdpad = getActiveSetJoystick()->getVDPad(vdpadIndex);
if (vdpad)
{
setVDPadName(vdpadIndex, vdpad->getDpadName());
}
}
void InputDevice::resetButtonDownCount()
{
buttonDownCount = 0;
emit released(joyNumber);
}
void InputDevice::enableSetConnections(SetJoystick *setstick)
{
connect(setstick, SIGNAL(setChangeActivated(int)), this, SLOT(resetButtonDownCount()));
connect(setstick, SIGNAL(setChangeActivated(int)), this, SLOT(setActiveSetNumber(int)));
connect(setstick, SIGNAL(setChangeActivated(int)), this, SLOT(propogateSetChange(int)));
connect(setstick, SIGNAL(setAssignmentButtonChanged(int,int,int,int)), this, SLOT(changeSetButtonAssociation(int,int,int,int)));
connect(setstick, SIGNAL(setAssignmentAxisChanged(int,int,int,int,int)), this, SLOT(changeSetAxisButtonAssociation(int,int,int,int,int)));
connect(setstick, SIGNAL(setAssignmentDPadChanged(int,int,int,int,int)), this, SLOT(changeSetDPadButtonAssociation(int,int,int,int,int)));
connect(setstick, SIGNAL(setAssignmentVDPadChanged(int,int,int,int,int)), this, SLOT(changeSetVDPadButtonAssociation(int,int,int,int,int)));
connect(setstick, SIGNAL(setAssignmentStickChanged(int,int,int,int,int)), this, SLOT(changeSetStickButtonAssociation(int,int,int,int,int)));
connect(setstick, SIGNAL(setAssignmentAxisThrottleChanged(int,int)), this, SLOT(propogateSetAxisThrottleChange(int, int)));
connect(setstick, SIGNAL(setButtonClick(int,int)), this, SLOT(buttonDownEvent(int,int)));
connect(setstick, SIGNAL(setButtonRelease(int,int)), this, SLOT(buttonUpEvent(int,int)));
connect(setstick, SIGNAL(setAxisButtonClick(int,int,int)), this, SLOT(axisButtonDownEvent(int,int,int)));
connect(setstick, SIGNAL(setAxisButtonRelease(int,int,int)), this, SLOT(axisButtonUpEvent(int,int,int)));
connect(setstick, SIGNAL(setAxisActivated(int,int, int)), this, SLOT(axisActivatedEvent(int,int,int)));
connect(setstick, SIGNAL(setAxisReleased(int,int,int)), this, SLOT(axisReleasedEvent(int,int,int)));
connect(setstick, SIGNAL(setDPadButtonClick(int,int,int)), this, SLOT(dpadButtonDownEvent(int,int,int)));
connect(setstick, SIGNAL(setDPadButtonRelease(int,int,int)), this, SLOT(dpadButtonUpEvent(int,int,int)));
connect(setstick, SIGNAL(setStickButtonClick(int,int,int)), this, SLOT(stickButtonDownEvent(int,int,int)));
connect(setstick, SIGNAL(setStickButtonRelease(int,int,int)), this, SLOT(stickButtonUpEvent(int,int,int)));
connect(setstick, SIGNAL(setButtonNameChange(int)), this, SLOT(updateSetButtonNames(int)));
connect(setstick, SIGNAL(setAxisButtonNameChange(int,int)), this, SLOT(updateSetAxisButtonNames(int,int)));
connect(setstick, SIGNAL(setStickButtonNameChange(int,int)), this, SLOT(updateSetStickButtonNames(int,int)));
connect(setstick, SIGNAL(setDPadButtonNameChange(int,int)), this, SLOT(updateSetDPadButtonNames(int,int)));
connect(setstick, SIGNAL(setVDPadButtonNameChange(int,int)), this, SLOT(updateSetVDPadButtonNames(int,int)));
connect(setstick, SIGNAL(setAxisNameChange(int)), this, SLOT(updateSetAxisNames(int)));
connect(setstick, SIGNAL(setStickNameChange(int)), this, SLOT(updateSetStickNames(int)));
connect(setstick, SIGNAL(setDPadNameChange(int)), this, SLOT(updateSetDPadNames(int)));
connect(setstick, SIGNAL(setVDPadNameChange(int)), this, SLOT(updateSetVDPadNames(int)));
}
void InputDevice::axisActivatedEvent(int setindex, int axisindex, int value)
{
Q_UNUSED(setindex);
emit rawAxisActivated(axisindex, value);
}
void InputDevice::axisReleasedEvent(int setindex, int axisindex, int value)
{
Q_UNUSED(setindex);
emit rawAxisReleased(axisindex, value);
}
void InputDevice::setIndex(int index)
{
if (index >= 0)
{
joyNumber = index;
}
else
{
joyNumber = 0;
}
}
void InputDevice::setDeviceKeyPressTime(unsigned int newPressTime)
{
keyPressTime = newPressTime;
emit propertyUpdated();
}
unsigned int InputDevice::getDeviceKeyPressTime()
{
return keyPressTime;
}
void InputDevice::profileEdited()
{
if (!deviceEdited)
{
deviceEdited = true;
emit profileUpdated();
}
}
bool InputDevice::isDeviceEdited()
{
return deviceEdited;
}
void InputDevice::revertProfileEdited()
{
deviceEdited = false;
}
QString InputDevice::getStringIdentifier()
{
QString identifier;
QString tempGUID = getGUIDString();
QString tempName = getSDLName();
if (!tempGUID.isEmpty())
{
identifier = tempGUID;
}
else if (!tempName.isEmpty())
{
identifier = tempName;
}
return identifier;
}
void InputDevice::establishPropertyUpdatedConnection()
{
connect(this, SIGNAL(propertyUpdated()), this, SLOT(profileEdited()));
}
void InputDevice::disconnectPropertyUpdatedConnection()
{
disconnect(this, SIGNAL(propertyUpdated()), this, SLOT(profileEdited()));
}
void InputDevice::setKeyRepeatStatus(bool enabled)
{
keyRepeatEnabled = enabled;
}
void InputDevice::setKeyRepeatDelay(int delay)
{
if (delay >= 250 && delay <= 1000)
{
keyRepeatDelay = delay;
}
}
void InputDevice::setKeyRepeatRate(int rate)
{
if (rate >= 20 && rate <= 200)
{
keyRepeatRate = rate;
}
}
bool InputDevice::isKeyRepeatEnabled()
{
return keyRepeatEnabled;
}
int InputDevice::getKeyRepeatDelay()
{
int tempKeyRepeatDelay = DEFAULTKEYREPEATDELAY;
if (keyRepeatDelay != 0)
{
tempKeyRepeatDelay = keyRepeatDelay;
}
return tempKeyRepeatDelay;
}
int InputDevice::getKeyRepeatRate()
{
int tempKeyRepeatRate = DEFAULTKEYREPEATRATE;
if (keyRepeatRate != 0)
{
tempKeyRepeatRate = keyRepeatRate;
}
return tempKeyRepeatRate;
}
void InputDevice::setProfileName(QString value)
{
if (profileName != value)
{
if (value.size() > 50)
{
value.truncate(47);
value.append("...");
}
profileName = value;
emit propertyUpdated();
emit profileNameEdited(value);
}
}
QString InputDevice::getProfileName()
{
return profileName;
}
int InputDevice::getButtonDownCount()
{
return buttonDownCount;
}
#ifdef USE_SDL_2
QString InputDevice::getSDLPlatform()
{
QString temp = SDL_GetPlatform();
return temp;
}
#endif
/**
* @brief Check if device is using the SDL Game Controller API
* @return Status showing if device is using the Game Controller API
*/
bool InputDevice::isGameController()
{
return false;
}
bool InputDevice::hasCalibrationThrottle(int axisNum)
{
bool result = false;
if (cali.contains(axisNum))
{
result = true;
}
return result;
}
JoyAxis::ThrottleTypes InputDevice::getCalibrationThrottle(int axisNum)
{
return cali.value(axisNum);
}
void InputDevice::setCalibrationThrottle(int axisNum, JoyAxis::ThrottleTypes throttle)
{
if (!cali.contains(axisNum))
{
for (int i=0; i < NUMBER_JOYSETS; i++)
{
joystick_sets.value(i)->setAxisThrottle(axisNum, throttle);
}
cali.insert(axisNum, throttle);
}
}
void InputDevice::setCalibrationStatus(int axisNum, JoyAxis::ThrottleTypes throttle)
{
if (!cali.contains(axisNum))
{
cali.insert(axisNum, throttle);
}
}
void InputDevice::removeCalibrationStatus(int axisNum)
{
if (cali.contains(axisNum))
{
cali.remove(axisNum);
}
}
void InputDevice::sendLoadProfileRequest(QString location)
{
if (!location.isEmpty())
{
emit requestProfileLoad(location);
}
}
AntiMicroSettings* InputDevice::getSettings()
{
return settings;
}
bool InputDevice::isKnownController()
{
bool result = false;
if (isGameController())
{
result = true;
}
else
{
settings->beginGroup("Mappings");
if (settings->contains(getGUIDString()))
{
result = true;
}
else if (settings->contains(QString("%1%2").arg(getGUIDString()).arg("Disabled")))
{
result = true;
}
settings->endGroup();
}
return result;
}
void InputDevice::activatePossiblePendingEvents()
{
activatePossibleControlStickEvents();
activatePossibleAxisEvents();
activatePossibleDPadEvents();
activatePossibleVDPadEvents();
activatePossibleButtonEvents();
}
void InputDevice::activatePossibleControlStickEvents()
{
SetJoystick *currentSet = getActiveSetJoystick();
for (int i=0; i < currentSet->getNumberSticks(); i++)
{
JoyControlStick *tempStick = currentSet->getJoyStick(i);
if (tempStick && tempStick->hasPendingEvent())
{
tempStick->activatePendingEvent();
}
}
}
void InputDevice::activatePossibleAxisEvents()
{
SetJoystick *currentSet = getActiveSetJoystick();
for (int i=0; i < currentSet->getNumberAxes(); i++)
{
JoyAxis *tempAxis = currentSet->getJoyAxis(i);
if (tempAxis && tempAxis->hasPendingEvent())
{
tempAxis->activatePendingEvent();
}
}
}
void InputDevice::activatePossibleDPadEvents()
{
SetJoystick *currentSet = getActiveSetJoystick();
for (int i=0; i < currentSet->getNumberHats(); i++)
{
JoyDPad *tempDPad = currentSet->getJoyDPad(i);
if (tempDPad && tempDPad->hasPendingEvent())
{
tempDPad->activatePendingEvent();
}
}
}
void InputDevice::activatePossibleVDPadEvents()
{
SetJoystick *currentSet = getActiveSetJoystick();
for (int i=0; i < currentSet->getNumberVDPads(); i++)
{
VDPad *tempVDPad = currentSet->getVDPad(i);
if (tempVDPad && tempVDPad->hasPendingEvent())
{
tempVDPad->activatePendingEvent();
}
}
}
void InputDevice::activatePossibleButtonEvents()
{
SetJoystick *currentSet = getActiveSetJoystick();
for (int i=0; i < currentSet->getNumberButtons(); i++)
{
JoyButton *tempButton = currentSet->getJoyButton(i);
if (tempButton && tempButton->hasPendingEvent())
{
tempButton->activatePendingEvent();
}
}
}
bool InputDevice::elementsHaveNames()
{
bool result = false;
SetJoystick *tempSet = getActiveSetJoystick();
for (int i=0; i < getNumberButtons() && !result; i++)
{
JoyButton *button = tempSet->getJoyButton(i);
if (button && !button->getButtonName().isEmpty())
{
result = true;
}
}
for (int i=0; i < getNumberAxes() && !result; i++)
{
JoyAxis *axis = tempSet->getJoyAxis(i);
if (axis)
{
if (!axis->getAxisName().isEmpty())
{
result = true;
}
JoyAxisButton *naxisbutton = axis->getNAxisButton();
if (!naxisbutton->getButtonName().isEmpty())
{
result = true;
}
JoyAxisButton *paxisbutton = axis->getPAxisButton();
if (!paxisbutton->getButtonName().isEmpty())
{
result = true;
}
}
}
for (int i=0; i < getNumberSticks() && !result; i++)
{
JoyControlStick *stick = tempSet->getJoyStick(i);
if (stick)
{
if (!stick->getStickName().isEmpty())
{
result = true;
}
QHash<JoyControlStick::JoyStickDirections, JoyControlStickButton*> *buttons = stick->getButtons();
QHashIterator<JoyControlStick::JoyStickDirections, JoyControlStickButton*> iter(*buttons);
while (iter.hasNext() && !result)
{
JoyControlStickButton *button = iter.next().value();
if (button && !button->getButtonName().isEmpty())
{
result = true;
}
}
}
}
for (int i=0; i < getNumberHats() && !result; i++)
{
JoyDPad *dpad = tempSet->getJoyDPad(i);
if (dpad)
{
if (!dpad->getDpadName().isEmpty())
{
result = true;
}
QHash<int, JoyDPadButton*> *temp = dpad->getButtons();
QHashIterator<int, JoyDPadButton*> iter(*temp);
while (iter.hasNext() && !result)
{
JoyDPadButton *button = iter.next().value();
if (button && !button->getButtonName().isEmpty())
{
result = true;
}
}
}
}
for (int i=0; i < getNumberVDPads() && !result; i++)
{
VDPad *vdpad = getActiveSetJoystick()->getVDPad(i);
if (vdpad)
{
if (!vdpad->getDpadName().isEmpty())
{
result = true;
}
QHash<int, JoyDPadButton*> *temp = vdpad->getButtons();
QHashIterator<int, JoyDPadButton*> iter(*temp);
while (iter.hasNext() && !result)
{
JoyDPadButton *button = iter.next().value();
if (button && !button->getButtonName().isEmpty())
{
result = true;
}
}
}
}
return result;
}
/**
* @brief Check if the GUID passed is considered empty.
* @param GUID string
* @return if GUID is considered empty.
*/
bool InputDevice::isEmptyGUID(QString tempGUID)
{
bool result = false;
if (tempGUID.contains(emptyGUID))
{
result = true;
}
return result;
}
/**
* @brief Check if GUID passed matches the expected GUID for a device.
* Needed for xinput GUID abstraction.
* @param GUID string
* @return if GUID is considered a match.
*/
bool InputDevice::isRelevantGUID(QString tempGUID)
{
bool result = false;
if (tempGUID == getGUIDString())
{
result = true;
}
return result;
}
QString InputDevice::getRawGUIDString()
{
QString temp = getGUIDString();
return temp;
}
void InputDevice::haltServices()
{
emit requestWait();
}
void InputDevice::finalRemoval()
{
this->closeSDLDevice();
this->deleteLater();
}
void InputDevice::setRawAxisDeadZone(int deadZone)
{
if (deadZone > 0 && deadZone <= JoyAxis::AXISMAX)
{
this->rawAxisDeadZone = deadZone;
}
else
{
this->rawAxisDeadZone = RAISEDDEADZONE;
}
}
int InputDevice::getRawAxisDeadZone()
{
return rawAxisDeadZone;
}
void InputDevice::rawAxisEvent(int index, int value)
{
emit rawAxisMoved(index, value);
}
``` | /content/code_sandbox/src/inputdevice.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 17,223 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include <QTextStream>
#include <QLocalSocket>
#include "localantimicroserver.h"
#include "common.h"
LocalAntiMicroServer::LocalAntiMicroServer(QObject *parent) :
QObject(parent)
{
localServer = new QLocalServer(this);
}
void LocalAntiMicroServer::startLocalServer()
{
QLocalServer::removeServer(PadderCommon::localSocketKey);
localServer->setMaxPendingConnections(1);
if (!localServer->listen(PadderCommon::localSocketKey))
{
QTextStream errorstream(stderr);
QString message("Could not start signal server. Profiles cannot be reloaded\n");
message.append("from command-line");
errorstream << tr(message.toStdString().c_str()) << endl;
}
else
{
connect(localServer, SIGNAL(newConnection()), this, SLOT(handleOutsideConnection()));
}
}
void LocalAntiMicroServer::handleOutsideConnection()
{
QLocalSocket *socket = localServer->nextPendingConnection();
if (socket)
{
connect(socket, SIGNAL(disconnected()), this, SLOT(handleSocketDisconnect()));
connect(socket, SIGNAL(disconnected()), socket, SLOT(deleteLater()));
}
}
void LocalAntiMicroServer::handleSocketDisconnect()
{
emit clientdisconnect();
}
void LocalAntiMicroServer::close()
{
localServer->close();
}
``` | /content/code_sandbox/src/localantimicroserver.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 375 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include <linux/input.h>
#include <linux/uinput.h>
#include <QCoreApplication>
#include "uinputhelper.h"
UInputHelper* UInputHelper::_instance = 0;
UInputHelper::UInputHelper(QObject *parent) :
QObject(parent)
{
populateKnownAliases();
connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(deleteLater()));
}
UInputHelper::~UInputHelper()
{
_instance = 0;
}
void UInputHelper::populateKnownAliases()
{
if (knownAliasesX11SymVK.isEmpty())
{
knownAliasesX11SymVK.insert("a", KEY_A);
knownAliasesX11SymVK.insert("b", KEY_B);
knownAliasesX11SymVK.insert("c", KEY_C);
knownAliasesX11SymVK.insert("d", KEY_D);
knownAliasesX11SymVK.insert("e", KEY_E);
knownAliasesX11SymVK.insert("f", KEY_F);
knownAliasesX11SymVK.insert("g", KEY_G);
knownAliasesX11SymVK.insert("h", KEY_H);
knownAliasesX11SymVK.insert("i", KEY_I);
knownAliasesX11SymVK.insert("j", KEY_J);
knownAliasesX11SymVK.insert("k", KEY_K);
knownAliasesX11SymVK.insert("l", KEY_L);
knownAliasesX11SymVK.insert("m", KEY_M);
knownAliasesX11SymVK.insert("n", KEY_N);
knownAliasesX11SymVK.insert("o", KEY_O);
knownAliasesX11SymVK.insert("p", KEY_P);
knownAliasesX11SymVK.insert("q", KEY_Q);
knownAliasesX11SymVK.insert("r", KEY_R);
knownAliasesX11SymVK.insert("s", KEY_S);
knownAliasesX11SymVK.insert("t", KEY_T);
knownAliasesX11SymVK.insert("u", KEY_U);
knownAliasesX11SymVK.insert("v", KEY_V);
knownAliasesX11SymVK.insert("w", KEY_W);
knownAliasesX11SymVK.insert("x", KEY_X);
knownAliasesX11SymVK.insert("y", KEY_Y);
knownAliasesX11SymVK.insert("z", KEY_Z);
knownAliasesX11SymVK.insert("Escape", KEY_ESC);
knownAliasesX11SymVK.insert("F1", KEY_F1);
knownAliasesX11SymVK.insert("F2", KEY_F2);
knownAliasesX11SymVK.insert("F3", KEY_F3);
knownAliasesX11SymVK.insert("F4", KEY_F4);
knownAliasesX11SymVK.insert("F5", KEY_F5);
knownAliasesX11SymVK.insert("F6", KEY_F6);
knownAliasesX11SymVK.insert("F7", KEY_F7);
knownAliasesX11SymVK.insert("F8", KEY_F8);
knownAliasesX11SymVK.insert("F9", KEY_F9);
knownAliasesX11SymVK.insert("F10", KEY_F10);
knownAliasesX11SymVK.insert("F11", KEY_F11);
knownAliasesX11SymVK.insert("F12", KEY_F12);
knownAliasesX11SymVK.insert("grave", KEY_GRAVE);
knownAliasesX11SymVK.insert("1", KEY_1);
knownAliasesX11SymVK.insert("2", KEY_2);
knownAliasesX11SymVK.insert("3", KEY_3);
knownAliasesX11SymVK.insert("4", KEY_4);
knownAliasesX11SymVK.insert("5", KEY_5);
knownAliasesX11SymVK.insert("6", KEY_6);
knownAliasesX11SymVK.insert("7", KEY_7);
knownAliasesX11SymVK.insert("8", KEY_8);
knownAliasesX11SymVK.insert("9", KEY_9);
knownAliasesX11SymVK.insert("0", KEY_0);
knownAliasesX11SymVK.insert("minus", KEY_MINUS);
knownAliasesX11SymVK.insert("equal", KEY_EQUAL);
knownAliasesX11SymVK.insert("BackSpace", KEY_BACKSPACE);
knownAliasesX11SymVK.insert("Tab", KEY_TAB);
knownAliasesX11SymVK.insert("bracketleft", KEY_LEFTBRACE);
knownAliasesX11SymVK.insert("bracketright", KEY_RIGHTBRACE);
knownAliasesX11SymVK.insert("backslash", KEY_BACKSLASH);
knownAliasesX11SymVK.insert("Caps_Lock", KEY_CAPSLOCK);
knownAliasesX11SymVK.insert("semicolon", KEY_SEMICOLON);
knownAliasesX11SymVK.insert("apostrophe", KEY_APOSTROPHE);
knownAliasesX11SymVK.insert("Return", KEY_ENTER);
knownAliasesX11SymVK.insert("Shift_L", KEY_LEFTSHIFT);
knownAliasesX11SymVK.insert("comma", KEY_COMMA);
knownAliasesX11SymVK.insert("period", KEY_DOT);
knownAliasesX11SymVK.insert("slash", KEY_SLASH);
knownAliasesX11SymVK.insert("Control_L", KEY_LEFTCTRL);
knownAliasesX11SymVK.insert("Super_L", KEY_MENU);
knownAliasesX11SymVK.insert("Alt_L", KEY_LEFTALT);
knownAliasesX11SymVK.insert("space", KEY_SPACE);
knownAliasesX11SymVK.insert("Alt_R", KEY_RIGHTALT);
knownAliasesX11SymVK.insert("Menu", KEY_COMPOSE);
knownAliasesX11SymVK.insert("Control_R", KEY_RIGHTCTRL);
knownAliasesX11SymVK.insert("Shift_R", KEY_RIGHTSHIFT);
knownAliasesX11SymVK.insert("Up", KEY_UP);
knownAliasesX11SymVK.insert("Left", KEY_LEFT);
knownAliasesX11SymVK.insert("Down", KEY_DOWN);
knownAliasesX11SymVK.insert("Right", KEY_RIGHT);
knownAliasesX11SymVK.insert("Print", KEY_PRINT);
knownAliasesX11SymVK.insert("Insert", KEY_INSERT);
knownAliasesX11SymVK.insert("Delete", KEY_DELETE);
knownAliasesX11SymVK.insert("Home", KEY_HOME);
knownAliasesX11SymVK.insert("End", KEY_END);
knownAliasesX11SymVK.insert("Prior", KEY_PAGEUP);
knownAliasesX11SymVK.insert("Next", KEY_PAGEDOWN);
knownAliasesX11SymVK.insert("Num_Lock", KEY_NUMLOCK);
knownAliasesX11SymVK.insert("KP_Divide", KEY_KPSLASH);
knownAliasesX11SymVK.insert("KP_Multiply", KEY_KPASTERISK);
knownAliasesX11SymVK.insert("KP_Subtract", KEY_KPMINUS);
knownAliasesX11SymVK.insert("KP_Add", KEY_KPPLUS);
knownAliasesX11SymVK.insert("KP_Enter", KEY_KPENTER);
knownAliasesX11SymVK.insert("KP_1", KEY_KP1);
knownAliasesX11SymVK.insert("KP_2", KEY_KP2);
knownAliasesX11SymVK.insert("KP_3", KEY_KP3);
knownAliasesX11SymVK.insert("KP_4", KEY_KP4);
knownAliasesX11SymVK.insert("KP_5", KEY_KP5);
knownAliasesX11SymVK.insert("KP_6", KEY_KP6);
knownAliasesX11SymVK.insert("KP_7", KEY_KP7);
knownAliasesX11SymVK.insert("KP_8", KEY_KP8);
knownAliasesX11SymVK.insert("KP_9", KEY_KP9);
knownAliasesX11SymVK.insert("KP_0", KEY_KP0);
knownAliasesX11SymVK.insert("KP_Decimal", KEY_KPDOT);
knownAliasesX11SymVK.insert("Scroll_Lock", KEY_SCROLLLOCK);
knownAliasesX11SymVK.insert("Pause", KEY_PAUSE);
knownAliasesX11SymVK.insert("Multi_key", KEY_RIGHTALT);
}
if (knownAliasesVKStrings.isEmpty())
{
knownAliasesVKStrings.insert(KEY_A, tr("a"));
knownAliasesVKStrings.insert(KEY_B, tr("b"));
knownAliasesVKStrings.insert(KEY_C, tr("c"));
knownAliasesVKStrings.insert(KEY_D, tr("d"));
knownAliasesVKStrings.insert(KEY_E, tr("e"));
knownAliasesVKStrings.insert(KEY_F, tr("f"));
knownAliasesVKStrings.insert(KEY_G, tr("g"));
knownAliasesVKStrings.insert(KEY_H, tr("h"));
knownAliasesVKStrings.insert(KEY_I, tr("i"));
knownAliasesVKStrings.insert(KEY_J, tr("j"));
knownAliasesVKStrings.insert(KEY_K, tr("k"));
knownAliasesVKStrings.insert(KEY_L, tr("l"));
knownAliasesVKStrings.insert(KEY_M, tr("m"));
knownAliasesVKStrings.insert(KEY_N, tr("n"));
knownAliasesVKStrings.insert(KEY_O, tr("o"));
knownAliasesVKStrings.insert(KEY_P, tr("p"));
knownAliasesVKStrings.insert(KEY_Q, tr("q"));
knownAliasesVKStrings.insert(KEY_R, tr("r"));
knownAliasesVKStrings.insert(KEY_S, tr("s"));
knownAliasesVKStrings.insert(KEY_T, tr("t"));
knownAliasesVKStrings.insert(KEY_U, tr("u"));
knownAliasesVKStrings.insert(KEY_V, tr("v"));
knownAliasesVKStrings.insert(KEY_W, tr("w"));
knownAliasesVKStrings.insert(KEY_X, tr("x"));
knownAliasesVKStrings.insert(KEY_Y, tr("y"));
knownAliasesVKStrings.insert(KEY_Z, tr("z"));
knownAliasesVKStrings.insert(KEY_ESC, tr("Esc"));
knownAliasesVKStrings.insert(KEY_F1, tr("F1"));
knownAliasesVKStrings.insert(KEY_F2, tr("F2"));
knownAliasesVKStrings.insert(KEY_F3, tr("F3"));
knownAliasesVKStrings.insert(KEY_F4, tr("F4"));
knownAliasesVKStrings.insert(KEY_F5, tr("F5"));
knownAliasesVKStrings.insert(KEY_F6, tr("F6"));
knownAliasesVKStrings.insert(KEY_F7, tr("F7"));
knownAliasesVKStrings.insert(KEY_F8, tr("F8"));
knownAliasesVKStrings.insert(KEY_F9, tr("F9"));
knownAliasesVKStrings.insert(KEY_F10, tr("F10"));
knownAliasesVKStrings.insert(KEY_F11, tr("F11"));
knownAliasesVKStrings.insert(KEY_F12, tr("F12"));
knownAliasesVKStrings.insert(KEY_GRAVE, tr("`"));
knownAliasesVKStrings.insert(KEY_1, tr("1"));
knownAliasesVKStrings.insert(KEY_2, tr("2"));
knownAliasesVKStrings.insert(KEY_3, tr("3"));
knownAliasesVKStrings.insert(KEY_4, tr("4"));
knownAliasesVKStrings.insert(KEY_5, tr("5"));
knownAliasesVKStrings.insert(KEY_6, tr("6"));
knownAliasesVKStrings.insert(KEY_7, tr("7"));
knownAliasesVKStrings.insert(KEY_8, tr("8"));
knownAliasesVKStrings.insert(KEY_9, tr("9"));
knownAliasesVKStrings.insert(KEY_0, tr("0"));
knownAliasesVKStrings.insert(KEY_MINUS, tr("-"));
knownAliasesVKStrings.insert(KEY_EQUAL, tr("="));
knownAliasesVKStrings.insert(KEY_BACKSPACE, tr("BackSpace"));
knownAliasesVKStrings.insert(KEY_TAB, tr("Tab"));
knownAliasesVKStrings.insert(KEY_LEFTBRACE, tr("["));
knownAliasesVKStrings.insert(KEY_RIGHTBRACE, tr("]"));
knownAliasesVKStrings.insert(KEY_BACKSLASH, tr("\\"));
knownAliasesVKStrings.insert(KEY_CAPSLOCK, tr("CapsLock"));
knownAliasesVKStrings.insert(KEY_SEMICOLON, tr(";"));
knownAliasesVKStrings.insert(KEY_APOSTROPHE, tr("'"));
knownAliasesVKStrings.insert(KEY_ENTER, tr("Enter"));
knownAliasesVKStrings.insert(KEY_LEFTSHIFT, tr("Shift_L"));
knownAliasesVKStrings.insert(KEY_COMMA, tr(","));
knownAliasesVKStrings.insert(KEY_DOT, tr("."));
knownAliasesVKStrings.insert(KEY_SLASH, tr("/"));
knownAliasesVKStrings.insert(KEY_LEFTCTRL, tr("Ctrl_L"));
knownAliasesVKStrings.insert(KEY_MENU, tr("Super_L"));
knownAliasesVKStrings.insert(KEY_LEFTALT, tr("Alt_L"));
knownAliasesVKStrings.insert(KEY_SPACE, tr("Space"));
knownAliasesVKStrings.insert(KEY_RIGHTALT, tr("Alt_R"));
knownAliasesVKStrings.insert(KEY_COMPOSE, tr("Menu"));
knownAliasesVKStrings.insert(KEY_RIGHTCTRL, tr("Ctrl_R"));
knownAliasesVKStrings.insert(KEY_RIGHTSHIFT, tr("Shift_R"));
knownAliasesVKStrings.insert(KEY_UP, tr("Up"));
knownAliasesVKStrings.insert(KEY_LEFT, tr("Left"));
knownAliasesVKStrings.insert(KEY_DOWN, tr("Down"));
knownAliasesVKStrings.insert(KEY_RIGHT, tr("Right"));
knownAliasesVKStrings.insert(KEY_PRINT, tr("PrtSc"));
knownAliasesVKStrings.insert(KEY_INSERT, tr("Ins"));
knownAliasesVKStrings.insert(KEY_DELETE, tr("Del"));
knownAliasesVKStrings.insert(KEY_HOME, tr("Home"));
knownAliasesVKStrings.insert(KEY_END, tr("End"));
knownAliasesVKStrings.insert(KEY_PAGEUP, tr("PgUp"));
knownAliasesVKStrings.insert(KEY_PAGEDOWN, tr("PgDn"));
knownAliasesVKStrings.insert(KEY_NUMLOCK, tr("NumLock"));
knownAliasesVKStrings.insert(KEY_KPSLASH, tr("/"));
knownAliasesVKStrings.insert(KEY_KPASTERISK, tr("*"));
knownAliasesVKStrings.insert(KEY_KPMINUS, tr("-"));
knownAliasesVKStrings.insert(KEY_KPPLUS, tr("+"));
knownAliasesVKStrings.insert(KEY_KPENTER, tr("KP_Enter"));
knownAliasesVKStrings.insert(KEY_KP1, tr("KP_1"));
knownAliasesVKStrings.insert(KEY_KP2, tr("KP_2"));
knownAliasesVKStrings.insert(KEY_KP3, tr("KP_3"));
knownAliasesVKStrings.insert(KEY_KP4, tr("KP_4"));
knownAliasesVKStrings.insert(KEY_KP5, tr("KP_5"));
knownAliasesVKStrings.insert(KEY_KP6, tr("KP_6"));
knownAliasesVKStrings.insert(KEY_KP7, tr("KP_7"));
knownAliasesVKStrings.insert(KEY_KP8, tr("KP_8"));
knownAliasesVKStrings.insert(KEY_KP9, tr("KP_9"));
knownAliasesVKStrings.insert(KEY_KP0, tr("KP_0"));
knownAliasesVKStrings.insert(KEY_SCROLLLOCK, tr("SCLK"));
knownAliasesVKStrings.insert(KEY_PAUSE, tr("Pause"));
knownAliasesVKStrings.insert(KEY_KPDOT, tr("."));
knownAliasesVKStrings.insert(KEY_LEFTMETA, tr("Super_L"));
knownAliasesVKStrings.insert(KEY_RIGHTMETA, tr("Super_R"));
knownAliasesVKStrings.insert(KEY_MUTE, tr("Mute"));
knownAliasesVKStrings.insert(KEY_VOLUMEDOWN, tr("VolDn"));
knownAliasesVKStrings.insert(KEY_VOLUMEUP, tr("VolUp"));
knownAliasesVKStrings.insert(KEY_PLAYPAUSE, tr("Play"));
knownAliasesVKStrings.insert(KEY_STOPCD, tr("Stop"));
knownAliasesVKStrings.insert(KEY_PREVIOUSSONG, tr("Prev"));
knownAliasesVKStrings.insert(KEY_NEXTSONG, tr("Next"));
}
}
UInputHelper* UInputHelper::getInstance()
{
if (!_instance)
{
_instance = new UInputHelper();
}
return _instance;
}
void UInputHelper::deleteInstance()
{
if (_instance)
{
delete _instance;
_instance = 0;
}
}
QString UInputHelper::getDisplayString(unsigned int virtualkey)
{
QString temp;
if (virtualkey <= 0)
{
temp = tr("[NO KEY]");
}
else if (knownAliasesVKStrings.contains(virtualkey))
{
temp = knownAliasesVKStrings.value(virtualkey);
}
return temp;
}
unsigned int UInputHelper::getVirtualKey(QString codestring)
{
int temp = 0;
if (knownAliasesX11SymVK.contains(codestring))
{
temp = knownAliasesX11SymVK.value(codestring);
}
return temp;
}
``` | /content/code_sandbox/src/uinputhelper.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 3,609 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef SLOTITEMLISTWIDGET_H
#define SLOTITEMLISTWIDGET_H
#include <QListWidget>
#include <QKeyEvent>
class SlotItemListWidget : public QListWidget
{
Q_OBJECT
public:
explicit SlotItemListWidget(QWidget *parent = 0);
protected:
virtual void keyPressEvent(QKeyEvent *event);
signals:
public slots:
};
#endif // SLOTITEMLISTWIDGET_H
``` | /content/code_sandbox/src/slotitemlistwidget.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 181 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef INPUTDEVICESTATUSEVENT_H
#define INPUTDEVICESTATUSEVENT_H
#include <QObject>
#include <QList>
#include <QBitArray>
#include "inputdevice.h"
class InputDeviceBitArrayStatus : public QObject
{
Q_OBJECT
public:
explicit InputDeviceBitArrayStatus(InputDevice *device, bool readCurrent = true, QObject *parent = 0);
void changeAxesStatus(int axisIndex, bool value);
void changeButtonStatus(int buttonIndex, bool value);
void changeHatStatus(int hatIndex, bool value);
QBitArray generateFinalBitArray();
void clearStatusValues();
protected:
QList<bool> axesStatus;
QList<bool> hatButtonStatus;
QBitArray buttonStatus;
signals:
public slots:
};
#endif // INPUTDEVICESTATUSEVENT_H
``` | /content/code_sandbox/src/inputdevicebitarraystatus.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 271 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include <QFileInfo>
#include "autoprofileinfo.h"
AutoProfileInfo::AutoProfileInfo(QString guid, QString profileLocation,
QString exe, bool active, QObject *parent) :
QObject(parent)
{
setGUID(guid);
setProfileLocation(profileLocation);
setExe(exe);
setActive(active);
setDefaultState(false);
}
AutoProfileInfo::AutoProfileInfo(QString guid, QString profileLocation,
bool active, QObject *parent) :
QObject(parent)
{
setGUID(guid);
setProfileLocation(profileLocation);
setActive(active);
setDefaultState(false);
}
AutoProfileInfo::AutoProfileInfo(QObject *parent) :
QObject(parent)
{
setActive(true);
setDefaultState(false);
}
AutoProfileInfo::~AutoProfileInfo()
{
}
void AutoProfileInfo::setGUID(QString guid)
{
this->guid = guid;
}
QString AutoProfileInfo::getGUID()
{
return guid;
}
void AutoProfileInfo::setProfileLocation(QString profileLocation)
{
QFileInfo info(profileLocation);
if (profileLocation != this->profileLocation &&
info.exists() && info.isReadable())
{
this->profileLocation = profileLocation;
}
else if (profileLocation.isEmpty())
{
this->profileLocation = "";
}
}
QString AutoProfileInfo::getProfileLocation()
{
return profileLocation;
}
void AutoProfileInfo::setExe(QString exe)
{
if (!exe.isEmpty())
{
QFileInfo info(exe);
if (exe != this->exe && info.exists() && info.isExecutable())
{
this->exe = exe;
}
#ifdef Q_OS_WIN
else if (exe != this->exe && info.suffix() == "exe")
{
this->exe = exe;
}
#endif
}
else
{
this->exe = exe;
}
}
QString AutoProfileInfo::getExe()
{
return exe;
}
void AutoProfileInfo::setWindowClass(QString windowClass)
{
this->windowClass = windowClass;
}
QString AutoProfileInfo::getWindowClass()
{
return windowClass;
}
void AutoProfileInfo::setWindowName(QString winName)
{
this->windowName = winName;
}
QString AutoProfileInfo::getWindowName()
{
return windowName;
}
void AutoProfileInfo::setActive(bool active)
{
this->active = active;
}
bool AutoProfileInfo::isActive()
{
return active;
}
void AutoProfileInfo::setDefaultState(bool value)
{
this->defaultState = value;
}
bool AutoProfileInfo::isCurrentDefault()
{
return defaultState;
}
void AutoProfileInfo::setDeviceName(QString name)
{
this->deviceName = name;
}
QString AutoProfileInfo::getDeviceName()
{
return deviceName;
}
``` | /content/code_sandbox/src/autoprofileinfo.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 685 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef JOYBUTTONSTATUSBOX_H
#define JOYBUTTONSTATUSBOX_H
#include <QPushButton>
#include "joybutton.h"
class JoyButtonStatusBox : public QPushButton
{
Q_OBJECT
Q_PROPERTY(bool isflashing READ isButtonFlashing)
public:
explicit JoyButtonStatusBox(JoyButton *button, QWidget *parent = 0);
JoyButton* getJoyButton();
bool isButtonFlashing();
protected:
JoyButton *button;
bool isflashing;
signals:
void flashed(bool flashing);
private slots:
void flash();
void unflash();
};
#endif // JOYBUTTONSTATUSBOX_H
``` | /content/code_sandbox/src/joybuttonstatusbox.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 229 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef STICKPUSHBUTTONGROUP_H
#define STICKPUSHBUTTONGROUP_H
#include <QGridLayout>
#include "joycontrolstick.h"
#include "joycontrolstickpushbutton.h"
#include "joycontrolstickbuttonpushbutton.h"
class StickPushButtonGroup : public QGridLayout
{
Q_OBJECT
public:
explicit StickPushButtonGroup(JoyControlStick *stick, bool displayNames = false, QWidget *parent = 0);
JoyControlStick *getStick();
protected:
void generateButtons();
JoyControlStick *stick;
bool displayNames;
JoyControlStickButtonPushButton *upButton;
JoyControlStickButtonPushButton *downButton;
JoyControlStickButtonPushButton *leftButton;
JoyControlStickButtonPushButton *rightButton;
JoyControlStickButtonPushButton *upLeftButton;
JoyControlStickButtonPushButton *upRightButton;
JoyControlStickButtonPushButton *downLeftButton;
JoyControlStickButtonPushButton *downRightButton;
JoyControlStickPushButton *stickWidget;
signals:
void buttonSlotChanged();
public slots:
void changeButtonLayout();
void toggleNameDisplay();
private slots:
void propogateSlotsChanged();
void openStickButtonDialog();
void showStickDialog();
};
#endif // STICKPUSHBUTTONGROUP_H
``` | /content/code_sandbox/src/stickpushbuttongroup.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 373 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include <QDir>
#include "xmlconfigwriter.h"
XMLConfigWriter::XMLConfigWriter(QObject *parent) :
QObject(parent)
{
xml = new QXmlStreamWriter();
xml->setAutoFormatting(true);
configFile = 0;
joystick = 0;
writerError = false;
}
XMLConfigWriter::~XMLConfigWriter()
{
if (configFile)
{
if (configFile->isOpen())
{
configFile->close();
}
delete configFile;
configFile = 0;
}
if (xml)
{
delete xml;
xml = 0;
}
}
void XMLConfigWriter::write(InputDevice *joystick)
{
writerError = false;
if (!configFile->isOpen())
{
configFile->open(QFile::WriteOnly | QFile::Text);
xml->setDevice(configFile);
}
else
{
writerError = true;
writerErrorString = tr("Could not write to profile at %1.").arg(configFile->fileName());
}
if (!writerError)
{
xml->writeStartDocument();
joystick->writeConfig(xml);
xml->writeEndDocument();
}
if (configFile->isOpen())
{
configFile->close();
}
}
void XMLConfigWriter::setFileName(QString filename)
{
QFile *temp = new QFile(filename);
fileName = filename;
configFile = temp;
}
bool XMLConfigWriter::hasError()
{
return writerError;
}
QString XMLConfigWriter::getErrorString()
{
return writerErrorString;
}
``` | /content/code_sandbox/src/xmlconfigwriter.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 425 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include <QHash>
#include <QHashIterator>
#include "quicksetdialog.h"
#include "ui_quicksetdialog.h"
#include "setjoystick.h"
#include "buttoneditdialog.h"
QuickSetDialog::QuickSetDialog(InputDevice *joystick, QWidget *parent) :
QDialog(parent),
ui(new Ui::QuickSetDialog)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
this->joystick = joystick;
this->currentButtonDialog = 0;
setWindowTitle(tr("Quick Set %1").arg(joystick->getName()));
SetJoystick *currentset = joystick->getActiveSetJoystick();
currentset->release();
joystick->resetButtonDownCount();
QString temp = ui->joystickDialogLabel->text();
temp = temp.arg(joystick->getSDLName()).arg(joystick->getName());
ui->joystickDialogLabel->setText(temp);
for (int i=0; i < currentset->getNumberSticks(); i++)
{
JoyControlStick *stick = currentset->getJoyStick(i);
QHash<JoyControlStick::JoyStickDirections, JoyControlStickButton*> *stickButtons = stick->getButtons();
QHashIterator<JoyControlStick::JoyStickDirections, JoyControlStickButton*> iter(*stickButtons);
while (iter.hasNext())
{
JoyControlStickButton *stickbutton = iter.next().value();
if (stick->getJoyMode() != JoyControlStick::EightWayMode)
{
if (stickbutton->getJoyNumber() != JoyControlStick::StickLeftUp &&
stickbutton->getJoyNumber() != JoyControlStick::StickRightUp &&
stickbutton->getJoyNumber() != JoyControlStick::StickLeftDown &&
stickbutton->getJoyNumber() != JoyControlStick::StickRightDown)
{
connect(stickbutton, SIGNAL(clicked(int)), this, SLOT(showStickButtonDialog()));
}
}
else
{
connect(stickbutton, SIGNAL(clicked(int)), this, SLOT(showStickButtonDialog()));
}
if (!stickbutton->getIgnoreEventState())
{
stickbutton->setIgnoreEventState(true);
}
}
}
for (int i=0; i < currentset->getNumberAxes(); i++)
{
JoyAxis *axis = currentset->getJoyAxis(i);
if (!axis->isPartControlStick() && axis->hasControlOfButtons())
{
JoyAxisButton *naxisbutton = axis->getNAxisButton();
JoyAxisButton *paxisbutton = axis->getPAxisButton();
connect(naxisbutton, SIGNAL(clicked(int)), this, SLOT(showAxisButtonDialog()));
connect(paxisbutton, SIGNAL(clicked(int)), this, SLOT(showAxisButtonDialog()));
if (!naxisbutton->getIgnoreEventState())
{
naxisbutton->setIgnoreEventState(true);
}
if (!paxisbutton->getIgnoreEventState())
{
paxisbutton->setIgnoreEventState(true);
}
}
}
for (int i=0; i < currentset->getNumberHats(); i++)
{
JoyDPad *dpad = currentset->getJoyDPad(i);
QHash<int, JoyDPadButton*>* dpadbuttons = dpad->getButtons();
QHashIterator<int, JoyDPadButton*> iter(*dpadbuttons);
while (iter.hasNext())
{
JoyDPadButton *dpadbutton = iter.next().value();
if (dpad->getJoyMode() != JoyDPad::EightWayMode)
{
if (dpadbutton->getJoyNumber() != JoyDPadButton::DpadLeftUp &&
dpadbutton->getJoyNumber() != JoyDPadButton::DpadRightUp &&
dpadbutton->getJoyNumber() != JoyDPadButton::DpadLeftDown &&
dpadbutton->getJoyNumber() != JoyDPadButton::DpadRightDown)
{
connect(dpadbutton, SIGNAL(clicked(int)), this, SLOT(showDPadButtonDialog()));
}
}
else
{
connect(dpadbutton, SIGNAL(clicked(int)), this, SLOT(showDPadButtonDialog()));
}
if (!dpadbutton->getIgnoreEventState())
{
dpadbutton->setIgnoreEventState(true);
}
}
}
for (int i=0; i < currentset->getNumberVDPads(); i++)
{
VDPad *dpad = currentset->getVDPad(i);
if (dpad)
{
QHash<int, JoyDPadButton*>* dpadbuttons = dpad->getButtons();
QHashIterator<int, JoyDPadButton*> iter(*dpadbuttons);
while (iter.hasNext())
{
JoyDPadButton *dpadbutton = iter.next().value();
if (dpad->getJoyMode() != JoyDPad::EightWayMode)
{
if (dpadbutton->getJoyNumber() != JoyDPadButton::DpadLeftUp &&
dpadbutton->getJoyNumber() != JoyDPadButton::DpadRightUp &&
dpadbutton->getJoyNumber() != JoyDPadButton::DpadLeftDown &&
dpadbutton->getJoyNumber() != JoyDPadButton::DpadRightDown)
{
connect(dpadbutton, SIGNAL(clicked(int)), this, SLOT(showDPadButtonDialog()));
}
}
else
{
connect(dpadbutton, SIGNAL(clicked(int)), this, SLOT(showDPadButtonDialog()));
}
if (!dpadbutton->getIgnoreEventState())
{
dpadbutton->setIgnoreEventState(true);
}
}
}
}
for (int i=0; i < currentset->getNumberButtons(); i++)
{
JoyButton *button = currentset->getJoyButton(i);
if (button && !button->isPartVDPad())
{
connect(button, SIGNAL(clicked(int)), this, SLOT(showButtonDialog()));
if (!button->getIgnoreEventState())
{
button->setIgnoreEventState(true);
}
}
}
connect(this, SIGNAL(finished(int)), this, SLOT(restoreButtonStates()));
}
QuickSetDialog::~QuickSetDialog()
{
delete ui;
}
void QuickSetDialog::showAxisButtonDialog()
{
if (!currentButtonDialog)
{
JoyAxisButton *axisbutton = static_cast<JoyAxisButton*>(sender());
currentButtonDialog = new ButtonEditDialog(axisbutton, this);
currentButtonDialog->show();
connect(currentButtonDialog, SIGNAL(finished(int)), this, SLOT(nullifyDialogPointer()));
}
}
void QuickSetDialog::showButtonDialog()
{
if (!currentButtonDialog)
{
JoyButton *button = static_cast<JoyButton*>(sender());
currentButtonDialog = new ButtonEditDialog(button, this);
currentButtonDialog->show();
connect(currentButtonDialog, SIGNAL(finished(int)), this, SLOT(nullifyDialogPointer()));
}
}
void QuickSetDialog::showStickButtonDialog()
{
if (!currentButtonDialog)
{
JoyControlStickButton *stickbutton = static_cast<JoyControlStickButton*>(sender());
currentButtonDialog = new ButtonEditDialog(stickbutton, this);
currentButtonDialog->show();
connect(currentButtonDialog, SIGNAL(finished(int)), this, SLOT(nullifyDialogPointer()));
}
}
void QuickSetDialog::showDPadButtonDialog()
{
if (!currentButtonDialog)
{
JoyDPadButton *dpadbutton = static_cast<JoyDPadButton*>(sender());
currentButtonDialog = new ButtonEditDialog(dpadbutton, this);
currentButtonDialog->show();
connect(currentButtonDialog, SIGNAL(finished(int)), this, SLOT(nullifyDialogPointer()));
}
}
void QuickSetDialog::nullifyDialogPointer()
{
if (currentButtonDialog)
{
currentButtonDialog = 0;
emit buttonDialogClosed();
}
}
void QuickSetDialog::restoreButtonStates()
{
SetJoystick *currentset = joystick->getActiveSetJoystick();
for (int i=0; i < currentset->getNumberSticks(); i++)
{
JoyControlStick *stick = currentset->getJoyStick(i);
QHash<JoyControlStick::JoyStickDirections, JoyControlStickButton*> *stickButtons = stick->getButtons();
QHashIterator<JoyControlStick::JoyStickDirections, JoyControlStickButton*> iter(*stickButtons);
while (iter.hasNext())
{
JoyControlStickButton *stickbutton = iter.next().value();
if (stickbutton->getIgnoreEventState())
{
stickbutton->setIgnoreEventState(false);
}
disconnect(stickbutton, SIGNAL(clicked(int)), this, 0);
}
}
for (int i=0; i < currentset->getNumberAxes(); i++)
{
JoyAxis *axis = currentset->getJoyAxis(i);
if (!axis->isPartControlStick() && axis->hasControlOfButtons())
{
JoyAxisButton *naxisbutton = axis->getNAxisButton();
if (naxisbutton->getIgnoreEventState())
{
naxisbutton->setIgnoreEventState(false);
}
JoyAxisButton *paxisbutton = axis->getPAxisButton();
if (paxisbutton->getIgnoreEventState())
{
paxisbutton->setIgnoreEventState(false);
}
disconnect(naxisbutton, SIGNAL(clicked(int)), this, 0);
disconnect(paxisbutton, SIGNAL(clicked(int)), this, 0);
}
}
for (int i=0; i < currentset->getNumberHats(); i++)
{
JoyDPad *dpad = currentset->getJoyDPad(i);
QHash<int, JoyDPadButton*>* dpadbuttons = dpad->getButtons();
QHashIterator<int, JoyDPadButton*> iter(*dpadbuttons);
while (iter.hasNext())
{
JoyDPadButton *dpadbutton = iter.next().value();
if (dpadbutton->getIgnoreEventState())
{
dpadbutton->setIgnoreEventState(false);
}
disconnect(dpadbutton, SIGNAL(clicked(int)), this, 0);
}
}
for (int i=0; i < currentset->getNumberVDPads(); i++)
{
VDPad *dpad = currentset->getVDPad(i);
if (dpad)
{
QHash<int, JoyDPadButton*>* dpadbuttons = dpad->getButtons();
QHashIterator<int, JoyDPadButton*> iter(*dpadbuttons);
while (iter.hasNext())
{
JoyDPadButton *dpadbutton = iter.next().value();
if (dpadbutton->getIgnoreEventState())
{
dpadbutton->setIgnoreEventState(false);
}
disconnect(dpadbutton, SIGNAL(clicked(int)), this, 0);
}
}
}
for (int i=0; i < currentset->getNumberButtons(); i++)
{
JoyButton *button = currentset->getJoyButton(i);
if (button && !button->isPartVDPad())
{
if (button->getIgnoreEventState())
{
button->setIgnoreEventState(false);
}
disconnect(button, SIGNAL(clicked(int)), this, 0);
}
}
currentset->release();
}
``` | /content/code_sandbox/src/quicksetdialog.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 2,563 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include <QTextStream>
#include <QMapIterator>
#include <QDesktopWidget>
#include "applaunchhelper.h"
#ifdef Q_OS_WIN
#include <winextras.h>
#endif
AppLaunchHelper::AppLaunchHelper(AntiMicroSettings *settings, bool graphical,
QObject *parent) :
QObject(parent)
{
this->settings = settings;
this->graphical = graphical;
}
void AppLaunchHelper::initRunMethods()
{
if (graphical)
{
establishMouseTimerConnections();
enablePossibleMouseSmoothing();
changeMouseRefreshRate();
changeSpringModeScreen();
changeGamepadPollRate();
#ifdef Q_OS_WIN
checkPointerPrecision();
#endif
}
}
void AppLaunchHelper::enablePossibleMouseSmoothing()
{
bool smoothingEnabled = settings->value("Mouse/Smoothing", false).toBool();
if (smoothingEnabled)
{
int historySize = settings->value("Mouse/HistorySize", 0).toInt();
if (historySize > 0)
{
JoyButton::setMouseHistorySize(historySize);
}
double weightModifier = settings->value("Mouse/WeightModifier", 0.0).toDouble();
if (weightModifier > 0.0)
{
JoyButton::setWeightModifier(weightModifier);
}
}
}
void AppLaunchHelper::changeMouseRefreshRate()
{
int refreshRate = settings->value("Mouse/RefreshRate", 0).toInt();
if (refreshRate > 0)
{
JoyButton::setMouseRefreshRate(refreshRate);
}
}
void AppLaunchHelper::changeGamepadPollRate()
{
unsigned int pollRate = settings->value("GamepadPollRate",
AntiMicroSettings::defaultSDLGamepadPollRate).toUInt();
if (pollRate > 0)
{
JoyButton::setGamepadRefreshRate(pollRate);
}
}
void AppLaunchHelper::printControllerList(QMap<SDL_JoystickID, InputDevice *> *joysticks)
{
QTextStream outstream(stdout);
outstream << QObject::tr("# of joysticks found: %1").arg(joysticks->size()) << endl;
outstream << endl;
outstream << QObject::tr("List Joysticks:") << endl;
outstream << QObject::tr("---------------") << endl;
QMapIterator<SDL_JoystickID, InputDevice*> iter(*joysticks);
unsigned int indexNumber = 1;
while (iter.hasNext())
{
InputDevice *tempdevice = iter.next().value();
outstream << QObject::tr("Joystick %1:").arg(indexNumber) << endl;
outstream << " " << QObject::tr("Index: %1").arg(tempdevice->getRealJoyNumber()) << endl;
#ifdef USE_SDL_2
outstream << " " << QObject::tr("GUID: %1").arg(tempdevice->getGUIDString()) << endl;
#endif
outstream << " " << QObject::tr("Name: %1").arg(tempdevice->getSDLName()) << endl;
#ifdef USE_SDL_2
QString gameControllerStatus = tempdevice->isGameController() ?
QObject::tr("Yes") : QObject::tr("No");
outstream << " " << QObject::tr("Game Controller: %1").arg(gameControllerStatus) << endl;
#endif
outstream << " " << QObject::tr("# of Axes: %1").arg(tempdevice->getNumberRawAxes()) << endl;
outstream << " " << QObject::tr("# of Buttons: %1").arg(tempdevice->getNumberRawButtons()) << endl;
outstream << " " << QObject::tr("# of Hats: %1").arg(tempdevice->getNumberHats()) << endl;
if (iter.hasNext())
{
outstream << endl;
indexNumber++;
}
}
}
void AppLaunchHelper::changeSpringModeScreen()
{
QDesktopWidget deskWid;
int springScreen = settings->value("Mouse/SpringScreen",
AntiMicroSettings::defaultSpringScreen).toInt();
if (springScreen >= deskWid.screenCount())
{
springScreen = -1;
settings->setValue("Mouse/SpringScreen",
AntiMicroSettings::defaultSpringScreen);
settings->sync();
}
JoyButton::setSpringModeScreen(springScreen);
}
#ifdef Q_OS_WIN
void AppLaunchHelper::checkPointerPrecision()
{
WinExtras::grabCurrentPointerPrecision();
bool disableEnhandedPoint = settings->value("Mouse/DisableWinEnhancedPointer",
AntiMicroSettings::defaultDisabledWinEnhanced).toBool();
if (disableEnhandedPoint)
{
WinExtras::disablePointerPrecision();
}
}
void AppLaunchHelper::appQuitPointerPrecision()
{
bool disableEnhancedPoint = settings->value("Mouse/DisableWinEnhancedPointer",
AntiMicroSettings::defaultDisabledWinEnhanced).toBool();
if (disableEnhancedPoint && !WinExtras::isUsingEnhancedPointerPrecision())
{
WinExtras::enablePointerPrecision();
}
}
#endif
void AppLaunchHelper::revertMouseThread()
{
JoyButton::indirectStaticMouseThread(QThread::currentThread());
}
void AppLaunchHelper::changeMouseThread(QThread *thread)
{
JoyButton::setStaticMouseThread(thread);
}
void AppLaunchHelper::establishMouseTimerConnections()
{
JoyButton::establishMouseTimerConnections();
}
``` | /content/code_sandbox/src/applaunchhelper.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,273 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include "joyaxiswidget.h"
#include "joyaxiscontextmenu.h"
JoyAxisWidget::JoyAxisWidget(JoyAxis *axis, bool displayNames, QWidget *parent) :
FlashButtonWidget(displayNames, parent)
{
this->axis = axis;
refreshLabel();
enableFlashes();
this->setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showContextMenu(const QPoint&)));
JoyAxisButton *nAxisButton = axis->getNAxisButton();
JoyAxisButton *pAxisButton = axis->getPAxisButton();
tryFlash();
connect(axis, SIGNAL(throttleChanged()), this, SLOT(refreshLabel()));
connect(axis, SIGNAL(axisNameChanged()), this, SLOT(refreshLabel()));
//connect(nAxisButton, SIGNAL(slotsChanged()), this, SLOT(refreshLabel()));
//connect(pAxisButton, SIGNAL(slotsChanged()), this, SLOT(refreshLabel()));
connect(nAxisButton, SIGNAL(propertyUpdated()), this, SLOT(refreshLabel()));
connect(pAxisButton, SIGNAL(propertyUpdated()), this, SLOT(refreshLabel()));
connect(nAxisButton, SIGNAL(activeZoneChanged()), this, SLOT(refreshLabel()));
connect(pAxisButton, SIGNAL(activeZoneChanged()), this, SLOT(refreshLabel()));
axis->establishPropertyUpdatedConnection();
nAxisButton->establishPropertyUpdatedConnections();
pAxisButton->establishPropertyUpdatedConnections();
}
JoyAxis* JoyAxisWidget::getAxis()
{
return axis;
}
void JoyAxisWidget::disableFlashes()
{
disconnect(axis, SIGNAL(active(int)), this, SLOT(flash()));
disconnect(axis, SIGNAL(released(int)), this, SLOT(unflash()));
this->unflash();
}
void JoyAxisWidget::enableFlashes()
{
connect(axis, SIGNAL(active(int)), this, SLOT(flash()), Qt::QueuedConnection);
connect(axis, SIGNAL(released(int)), this, SLOT(unflash()), Qt::QueuedConnection);
}
/**
* @brief Generate the string that will be displayed on the button
* @return Display string
*/
QString JoyAxisWidget::generateLabel()
{
QString temp;
temp = axis->getName(false, displayNames).replace("&", "&&");
return temp;
}
void JoyAxisWidget::showContextMenu(const QPoint &point)
{
QPoint globalPos = this->mapToGlobal(point);
JoyAxisContextMenu *contextMenu = new JoyAxisContextMenu(axis, this);
contextMenu->buildMenu();
contextMenu->popup(globalPos);
}
void JoyAxisWidget::tryFlash()
{
JoyAxisButton *nAxisButton = axis->getNAxisButton();
JoyAxisButton *pAxisButton = axis->getPAxisButton();
if (nAxisButton->getButtonState() || pAxisButton->getButtonState())
{
flash();
}
}
``` | /content/code_sandbox/src/joyaxiswidget.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 693 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef LOCALANTIMICROSERVER_H
#define LOCALANTIMICROSERVER_H
#include <QObject>
#include <QLocalServer>
class LocalAntiMicroServer : public QObject
{
Q_OBJECT
public:
explicit LocalAntiMicroServer(QObject *parent = 0);
protected:
QLocalServer *localServer;
signals:
void clientdisconnect();
public slots:
void startLocalServer();
void handleOutsideConnection();
void handleSocketDisconnect();
void close();
};
#endif // LOCALANTIMICROSERVER_H
``` | /content/code_sandbox/src/localantimicroserver.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 206 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef ADDEDITAUTOPROFILEDIALOG_H
#define ADDEDITAUTOPROFILEDIALOG_H
#include <QDialog>
#include "autoprofileinfo.h"
#include "inputdevice.h"
#include "antimicrosettings.h"
namespace Ui {
class AddEditAutoProfileDialog;
}
class AddEditAutoProfileDialog : public QDialog
{
Q_OBJECT
public:
explicit AddEditAutoProfileDialog(AutoProfileInfo *info, AntiMicroSettings *settings, QList<InputDevice*> *devices,
QList<QString> &reservedGUIDS,
bool edit=false, QWidget *parent = 0);
~AddEditAutoProfileDialog();
AutoProfileInfo* getAutoProfile();
QString getOriginalGUID();
QString getOriginalExe();
QString getOriginalWindowClass();
QString getOriginalWindowName();
protected:
virtual void accept();
AutoProfileInfo *info;
QList<InputDevice*> *devices;
AntiMicroSettings *settings;
bool editForm;
bool defaultInfo;
QList<QString> reservedGUIDs;
QString originalGUID;
QString originalExe;
QString originalWindowClass;
QString originalWindowName;
private:
Ui::AddEditAutoProfileDialog *ui;
signals:
void captureFinished();
private slots:
void openProfileBrowseDialog();
void openApplicationBrowseDialog();
void saveAutoProfileInformation();
void checkForReservedGUIDs(int index);
void checkForDefaultStatus();
void windowPropAssignment();
#ifdef Q_OS_WIN
void openWinAppProfileDialog();
void captureWindowsApplicationPath();
#else
void showCaptureHelpWindow();
void checkForGrabbedWindow();
#endif
};
#endif // ADDEDITAUTOPROFILEDIALOG_H
``` | /content/code_sandbox/src/addeditautoprofiledialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 457 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef LOGGER_H
#define LOGGER_H
#include <QObject>
#include <QString>
#include <QMutex>
#include <QMutexLocker>
#include <QTextStream>
#include <QTimer>
#include <QFile>
class Logger : public QObject
{
Q_OBJECT
public:
enum LogLevel
{
LOG_NONE = 0, LOG_ERROR, LOG_WARNING, LOG_INFO, LOG_DEBUG,
LOG_MAX = LOG_DEBUG
};
typedef struct {
LogLevel level;
QString message;
bool newline;
} LogMessage;
explicit Logger(QTextStream *stream, LogLevel outputLevel = LOG_INFO, QObject *parent = 0);
explicit Logger(QTextStream *stream, QTextStream *errorStream, LogLevel outputLevel = LOG_INFO, QObject *parent = 0);
~Logger();
static void setLogLevel(LogLevel level);
LogLevel getCurrentLogLevel();
static void setCurrentStream(QTextStream *stream);
static void setCurrentLogFile(QString filename);
static QTextStream* getCurrentStream();
static void setCurrentErrorStream(QTextStream *stream);
static void setCurrentErrorLogFile(QString filename);
static QTextStream* getCurrentErrorStream();
QTimer* getLogTimer();
void stopLogTimer();
bool getWriteTime();
void setWriteTime(bool status);
static void appendLog(LogLevel level, const QString &message, bool newline=true);
static void directLog(LogLevel level, const QString &message, bool newline=true);
// Some convenience functions that will hopefully speed up
// logging operations.
inline static void LogInfo(const QString &message, bool newline=true, bool direct=false)
{
if (!direct)
{
appendLog(LOG_INFO, message, newline);
}
else
{
directLog(LOG_INFO, message, newline);
}
//Log(LOG_INFO, message, newline);
}
inline static void LogDebug(const QString &message, bool newline=true, bool direct=false)
{
if (!direct)
{
appendLog(LOG_DEBUG, message, newline);
}
else
{
directLog(LOG_DEBUG, message, newline);
}
//Log(LOG_DEBUG, message, newline);
}
inline static void LogWarning(const QString &message, bool newline=true, bool direct=false)
{
if (!direct)
{
appendLog(LOG_WARNING, message, newline);
}
else
{
directLog(LOG_WARNING, message, newline);
}
//Log(LOG_WARNING, message, newline);
}
inline static void LogError(const QString &message, bool newline=true, bool direct=false)
{
if (!direct)
{
appendLog(LOG_ERROR, message, newline);
}
else
{
directLog(LOG_ERROR, message, newline);
}
//Log(LOG_ERROR, message, newline);
}
inline static Logger* getInstance()
{
Q_ASSERT(instance != NULL);
return instance;
}
protected:
void closeLogger(bool closeStream=true);
void closeErrorLogger(bool closeStream=true);
void logMessage(LogMessage msg);
QFile outputFile;
QTextStream outFileStream;
QTextStream *outputStream;
QFile errorFile;
QTextStream outErrorFileStream;
QTextStream *errorStream;
LogLevel outputLevel;
QMutex logMutex;
QTimer pendingTimer;
QList<LogMessage> pendingMessages;
bool writeTime;
static Logger *instance;
signals:
void stringWritten(QString text);
void pendingMessage();
public slots:
void Log();
void startPendingTimer();
};
#endif // LOGGER_H
``` | /content/code_sandbox/src/logger.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 842 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#include <qt_windows.h>
//#include <QDebug>
#include <QHashIterator>
#include "winextras.h"
#include "qtwinkeymapper.h"
static QHash<unsigned int, unsigned int> initDynamicKeyMapping()
{
QHash<unsigned int, unsigned int> temp;
temp[VK_OEM_1] = 0;
//temp[VK_OEM_PLUS] = 0;
//temp[VK_OEM_COMMA] = 0;
//temp[VK_OEM_MINUS] = 0;
//temp[VK_OEM_PERIOD] = 0;
temp[VK_OEM_2] = 0;
temp[VK_OEM_3] = 0;
temp[VK_OEM_4] = 0;
temp[VK_OEM_5] = 0;
temp[VK_OEM_6] = 0;
temp[VK_OEM_7] = 0;
temp[VK_OEM_8] = 0;
temp[VK_OEM_102] = 0;
return temp;
}
static QHash<QString, unsigned int> intCharToQtKey()
{
QHash<QString, unsigned int> temp;
temp.insert(QString('!'), Qt::Key_Exclam);
temp.insert(QString('"'), Qt::Key_QuoteDbl);
temp.insert(QString('#'), Qt::Key_NumberSign);
temp.insert(QString('$'), Qt::Key_Dollar);
temp.insert(QString('\''), Qt::Key_Apostrophe);
temp.insert(QString('('), Qt::Key_ParenLeft);
temp.insert(QString(')'), Qt::Key_ParenRight);
temp.insert(QString('*'), Qt::Key_Asterisk);
temp.insert(QString('+'), Qt::Key_Plus);
temp.insert(QString(','), Qt::Key_Comma);
temp.insert(QString('-'), Qt::Key_Minus);
temp.insert(QString('.'), Qt::Key_Period);
temp.insert(QString('/'), Qt::Key_Slash);
temp.insert(QString(':'), Qt::Key_Colon);
temp.insert(QString(';'), Qt::Key_Semicolon);
temp.insert(QString('<'), Qt::Key_Less);
temp.insert(QString('='), Qt::Key_Equal);
temp.insert(QString('>'), Qt::Key_Greater);
temp.insert(QString('@'), Qt::Key_At);
temp.insert(QString('['), Qt::Key_BracketLeft);
temp.insert(QString('\\'), Qt::Key_Backslash);
temp.insert(QString(']'), Qt::Key_BracketRight);
temp.insert(QString('^'), Qt::Key_AsciiCircum);
temp.insert(QString('_'), Qt::Key_Underscore);
temp.insert(QString('`'), Qt::Key_QuoteLeft);
temp.insert(QString('{'), Qt::Key_BraceLeft);
temp.insert(QString('}'), Qt::Key_BraceRight);
temp.insert(QString::fromUtf8("\u00A1"), Qt::Key_exclamdown);
temp.insert(QString('~'), Qt::Key_AsciiTilde);
//temp.insert(QString::fromUtf8("\u20A0"), Qt::Key_)
return temp;
}
static QHash<QString, unsigned int> initDeadKeyToQtKey()
{
QHash<QString, unsigned int> temp;
//temp.insert(QString('`'), Qt::Key_Dead_Grave);
//temp.insert(QString('\''), Qt::Key_Dead_Acute);
temp.insert(QString::fromUtf8("\u00B4"), Qt::Key_Dead_Grave);
//temp.insert(QString('^'), Qt::Key_Dead_Circumflex);
//temp.insert(QString('~'), Qt::Key_Dead_Tilde);
temp.insert(QString::fromUtf8("\u02DC"), Qt::Key_Dead_Tilde);
temp.insert(QString::fromUtf8("\u00AF"), Qt::Key_Dead_Macron);
temp.insert(QString::fromUtf8("\u02D8"), Qt::Key_Dead_Breve);
temp.insert(QString::fromUtf8("\u02D9"), Qt::Key_Dead_Abovedot);
//temp.insert(QString('"'), Qt::Key_Dead_Diaeresis);
temp.insert(QString::fromUtf8("\u00A8"), Qt::Key_Dead_Diaeresis);
temp.insert(QString::fromUtf8("\u02DA"), Qt::Key_Dead_Abovering);
temp.insert(QString::fromUtf8("\u02DD"), Qt::Key_Dead_Doubleacute);
temp.insert(QString::fromUtf8("\u02C7"), Qt::Key_Dead_Caron);
//temp.insert(QString(','), Qt::Key_Dead_Cedilla);
temp.insert(QString::fromUtf8("\u00B8"), Qt::Key_Dead_Cedilla);
temp.insert(QString::fromUtf8("\u02DB"), Qt::Key_Dead_Ogonek);
temp.insert(QString::fromUtf8("\u037A"), Qt::Key_Dead_Iota);
temp.insert(QString::fromUtf8("\u309B"), Qt::Key_Dead_Voiced_Sound);
temp.insert(QString::fromUtf8("\u309C"), Qt::Key_Dead_Semivoiced_Sound);
return temp;
}
static QHash<unsigned int, unsigned int> dynamicOEMToQtKeyHash = initDynamicKeyMapping();
static QHash<QString, unsigned int> charToQtKeyHash = intCharToQtKey();
static QHash<QString, unsigned int> deadKeyToQtKeyHash = initDeadKeyToQtKey();
QtWinKeyMapper::QtWinKeyMapper(QObject *parent) :
QtKeyMapperBase(parent)
{
identifier = "sendinput";
populateMappingHashes();
populateCharKeyInformation();
}
void QtWinKeyMapper::populateMappingHashes()
{
if (qtKeyToVirtualKey.isEmpty())
{
qtKeyToVirtualKey[Qt::Key_Cancel] = VK_CANCEL;
qtKeyToVirtualKey[Qt::Key_Backspace] = VK_BACK;
qtKeyToVirtualKey[Qt::Key_Tab] = VK_TAB;
qtKeyToVirtualKey[Qt::Key_Clear] = VK_CLEAR;
qtKeyToVirtualKey[Qt::Key_Return] = VK_RETURN;
qtKeyToVirtualKey[Qt::Key_Enter] = VK_RETURN;
//qtKeyToWinVirtualKey[Qt::Key_Shift] = VK_SHIFT;
//qtKeyToWinVirtualKey[Qt::Key_Control] = VK_CONTROL;
//qtKeyToWinVirtualKey[Qt::Key_Alt] = VK_MENU;
qtKeyToVirtualKey[Qt::Key_Pause] = VK_PAUSE;
qtKeyToVirtualKey[Qt::Key_CapsLock] = VK_CAPITAL;
qtKeyToVirtualKey[Qt::Key_Escape] = VK_ESCAPE;
qtKeyToVirtualKey[Qt::Key_Mode_switch] = VK_MODECHANGE;
qtKeyToVirtualKey[Qt::Key_Space] = VK_SPACE;
qtKeyToVirtualKey[Qt::Key_PageUp] = VK_PRIOR;
qtKeyToVirtualKey[Qt::Key_PageDown] = VK_NEXT;
qtKeyToVirtualKey[Qt::Key_End] = VK_END;
qtKeyToVirtualKey[Qt::Key_Home] = VK_HOME;
qtKeyToVirtualKey[Qt::Key_Left] = VK_LEFT;
qtKeyToVirtualKey[Qt::Key_Up] = VK_UP;
qtKeyToVirtualKey[Qt::Key_Right] = VK_RIGHT;
qtKeyToVirtualKey[Qt::Key_Down] = VK_DOWN;
qtKeyToVirtualKey[Qt::Key_Select] = VK_SELECT;
qtKeyToVirtualKey[Qt::Key_Printer] = VK_PRINT;
qtKeyToVirtualKey[Qt::Key_Execute] = VK_EXECUTE;
qtKeyToVirtualKey[Qt::Key_Print] = VK_SNAPSHOT;
qtKeyToVirtualKey[Qt::Key_Insert] = VK_INSERT;
qtKeyToVirtualKey[Qt::Key_Delete] = VK_DELETE;
qtKeyToVirtualKey[Qt::Key_Help] = VK_HELP;
qtKeyToVirtualKey[Qt::Key_Meta] = VK_LWIN;
//qtKeyToWinVirtualKey[Qt::Key_Meta] = VK_RWIN;
qtKeyToVirtualKey[Qt::Key_Menu] = VK_APPS;
qtKeyToVirtualKey[Qt::Key_Sleep] = VK_SLEEP;
qtKeyToVirtualKey[AntKey_KP_Multiply] = VK_MULTIPLY;
//qtKeyToVirtualKey[Qt::Key_Asterisk] = VK_MULTIPLY;
qtKeyToVirtualKey[AntKey_KP_Add] = VK_ADD;
//qtKeyToVirtualKey[Qt::Key_Comma] = VK_SEPARATOR;
qtKeyToVirtualKey[AntKey_KP_Subtract] = VK_SUBTRACT;
qtKeyToVirtualKey[AntKey_KP_Decimal] = VK_DECIMAL;
qtKeyToVirtualKey[AntKey_KP_Divide] = VK_DIVIDE;
qtKeyToVirtualKey[Qt::Key_NumLock] = VK_NUMLOCK;
qtKeyToVirtualKey[Qt::Key_ScrollLock] = VK_SCROLL;
qtKeyToVirtualKey[Qt::Key_Massyo] = VK_OEM_FJ_MASSHOU;
qtKeyToVirtualKey[Qt::Key_Touroku] = VK_OEM_FJ_TOUROKU;
qtKeyToVirtualKey[Qt::Key_Shift] = VK_LSHIFT;
//qtKeyToWinVirtualKey[Qt::Key_Shift] = VK_RSHIFT;
qtKeyToVirtualKey[Qt::Key_Control] = VK_LCONTROL;
//qtKeyToWinVirtualKey[Qt::Key_Control] = VK_RCONTROL;
qtKeyToVirtualKey[Qt::Key_Alt] = VK_LMENU;
//qtKeyToWinVirtualKey[Qt::Key_Alt] = VK_RMENU;
qtKeyToVirtualKey[Qt::Key_Back] = VK_BROWSER_BACK;
qtKeyToVirtualKey[Qt::Key_Forward] = VK_BROWSER_FORWARD;
qtKeyToVirtualKey[Qt::Key_Refresh] = VK_BROWSER_REFRESH;
qtKeyToVirtualKey[Qt::Key_Stop] = VK_BROWSER_STOP;
qtKeyToVirtualKey[Qt::Key_Search] = VK_BROWSER_SEARCH;
qtKeyToVirtualKey[Qt::Key_Favorites] = VK_BROWSER_FAVORITES;
qtKeyToVirtualKey[Qt::Key_HomePage] = VK_BROWSER_HOME;
qtKeyToVirtualKey[Qt::Key_VolumeMute] = VK_VOLUME_MUTE;
qtKeyToVirtualKey[Qt::Key_VolumeDown] = VK_VOLUME_DOWN;
qtKeyToVirtualKey[Qt::Key_VolumeUp] = VK_VOLUME_UP;
qtKeyToVirtualKey[Qt::Key_MediaNext] = VK_MEDIA_NEXT_TRACK;
qtKeyToVirtualKey[Qt::Key_MediaPrevious] = VK_MEDIA_PREV_TRACK;
qtKeyToVirtualKey[Qt::Key_MediaStop] = VK_MEDIA_STOP;
qtKeyToVirtualKey[Qt::Key_MediaPlay] = VK_MEDIA_PLAY_PAUSE;
qtKeyToVirtualKey[Qt::Key_LaunchMail] = VK_LAUNCH_MAIL;
qtKeyToVirtualKey[Qt::Key_LaunchMedia] = VK_LAUNCH_MEDIA_SELECT;
qtKeyToVirtualKey[Qt::Key_Launch0] = VK_LAUNCH_APP1;
qtKeyToVirtualKey[Qt::Key_Launch1] = VK_LAUNCH_APP2;
qtKeyToVirtualKey[Qt::Key_Kanji] = VK_KANJI;
// The following VK_OEM_* keys are consistent across all
// keyboard layouts.
qtKeyToVirtualKey[Qt::Key_Equal] = VK_OEM_PLUS;
qtKeyToVirtualKey[Qt::Key_Minus] = VK_OEM_MINUS;
qtKeyToVirtualKey[Qt::Key_Period] = VK_OEM_PERIOD;
qtKeyToVirtualKey[Qt::Key_Comma] = VK_OEM_COMMA;
/*qtKeyToVirtualKey[Qt::Key_Semicolon] = VK_OEM_1;
qtKeyToVirtualKey[Qt::Key_Slash] = VK_OEM_2;
qtKeyToVirtualKey[Qt::Key_Equal] = VK_OEM_PLUS;
qtKeyToVirtualKey[Qt::Key_Minus] = VK_OEM_MINUS;
qtKeyToVirtualKey[Qt::Key_Period] = VK_OEM_PERIOD;
qtKeyToVirtualKey[Qt::Key_QuoteLeft] = VK_OEM_3;
qtKeyToVirtualKey[Qt::Key_BracketLeft] = VK_OEM_4;
qtKeyToVirtualKey[Qt::Key_Backslash] = VK_OEM_5;
qtKeyToVirtualKey[Qt::Key_BracketRight] = VK_OEM_6;
qtKeyToVirtualKey[Qt::Key_Apostrophe] = VK_OEM_7;*/
qtKeyToVirtualKey[Qt::Key_Play] = VK_PLAY;
qtKeyToVirtualKey[Qt::Key_Zoom] = VK_ZOOM;
//qtKeyToWinVirtualKey[Qt::Key_Clear] = VK_OEM_CLEAR;
// Map 0-9 ASCII codes
for (int i=0; i <= (0x39 - 0x30); i++)
{
qtKeyToVirtualKey[Qt::Key_0 + i] = 0x30 + i;
}
// Map A-Z ASCII codes
for (int i=0; i <= (0x5a - 0x41); i++)
{
qtKeyToVirtualKey[Qt::Key_A + i] = 0x41 + i;
}
// Map function keys
for (int i=0; i <= (VK_F24 - VK_F1); i++)
{
qtKeyToVirtualKey[Qt::Key_F1 + i] = VK_F1 + i;
}
// Map numpad keys
for (int i=0; i <= (VK_NUMPAD9 - VK_NUMPAD0); i++)
{
qtKeyToVirtualKey[AntKey_KP_0 + i] = VK_NUMPAD0 + i;
}
// Map custom keys
qtKeyToVirtualKey[AntKey_Alt_R] = VK_RMENU;
qtKeyToVirtualKey[AntKey_Meta_R] = VK_RWIN;
qtKeyToVirtualKey[AntKey_Shift_R] = VK_RSHIFT;
qtKeyToVirtualKey[AntKey_Control_R] = VK_RCONTROL;
// Go through VK_OEM_* values and find the appropriate association
// with a key defined in Qt. Association is decided based on char
// returned from Windows for the VK_OEM_* key.
QHashIterator<unsigned int, unsigned int> iterDynamic(dynamicOEMToQtKeyHash);
while (iterDynamic.hasNext())
{
iterDynamic.next();
byte ks[256];
char cbuf[2] = {'\0', '\0'};
GetKeyboardState(ks);
unsigned int oemkey = iterDynamic.key();
unsigned int scancode = MapVirtualKey(oemkey, 0);
int charlength = ToAscii(oemkey, scancode, ks, (WORD*)cbuf, 0);
if (charlength < 0)
{
charlength = ToAscii(VK_SPACE, scancode, ks, (WORD*)cbuf, 0);
QString temp = QString::fromUtf8(cbuf);
if (temp.length() > 0)
{
QHashIterator<QString, unsigned int> tempiter(charToQtKeyHash);
while (tempiter.hasNext())
{
tempiter.next();
QString currentChar = tempiter.key();
if (currentChar == temp)
{
dynamicOEMToQtKeyHash[oemkey] = tempiter.value();
tempiter.toBack();
}
}
}
}
else if (charlength == 1)
{
QString temp = QString::fromUtf8(cbuf);
QHashIterator<QString, unsigned int> tempiter(charToQtKeyHash);
while (tempiter.hasNext())
{
tempiter.next();
QString currentChar = tempiter.key();
if (currentChar == temp)
{
dynamicOEMToQtKeyHash[oemkey] = tempiter.value();
tempiter.toBack();
}
}
}
}
// Populate hash with values found for the VK_OEM_* keys.
// Values will likely be different across various keyboard
// layouts.
iterDynamic = QHashIterator<unsigned int, unsigned int>(dynamicOEMToQtKeyHash);
while (iterDynamic.hasNext())
{
iterDynamic.next();
unsigned int tempvalue = iterDynamic.value();
if (tempvalue != 0 && !qtKeyToVirtualKey.contains(tempvalue))
{
qtKeyToVirtualKey.insert(tempvalue, iterDynamic.key());
}
}
// Populate other hash. Flip key and value so mapping
// goes VK -> Qt Key.
QHashIterator<unsigned int, unsigned int> iter(qtKeyToVirtualKey);
while (iter.hasNext())
{
iter.next();
virtualKeyToQtKey[iter.value()] = iter.key();
}
// Override current item for VK_RETURN
virtualKeyToQtKey[VK_RETURN] = Qt::Key_Return;
// Insert more aliases that would have resulted in
// overwrites in other hash.
virtualKeyToQtKey[VK_SHIFT] = Qt::Key_Shift;
virtualKeyToQtKey[VK_CONTROL] = Qt::Key_Control;
virtualKeyToQtKey[VK_MENU] = Qt::Key_Alt;
}
}
unsigned int QtWinKeyMapper::returnQtKey(unsigned int key, unsigned int scancode)
{
unsigned int tempkey = virtualKeyToQtKey.value(key);
int extended = scancode & WinExtras::EXTENDED_FLAG;
if (key == VK_RETURN && extended)
{
tempkey = Qt::Key_Enter;
}
return tempkey;
}
void QtWinKeyMapper::populateCharKeyInformation()
{
virtualkeyToCharKeyInformation.clear();
unsigned int total = 0;
//BYTE ks[256];
//GetKeyboardState(ks);
/*for (int x=0; x <= 255; x++)
{
if (ks[x] != 0)
{
qDebug() << "TEST: " << QString::number(x)
<< " | " << QString::number(ks[x]);
}
}
*/
for (int i=VK_SPACE; i <= VK_OEM_CLEAR; i++)
{
unsigned int scancode = MapVirtualKey(i, 0);
for (int j=0; j <= 3; j++)
{
WCHAR cbuf[256];
BYTE tempks[256];
memset(tempks, 0, sizeof(tempks));
Qt::KeyboardModifiers dicis;
if (j >= 2)
{
dicis |= Qt::MetaModifier;
tempks[VK_LWIN] = 1 << 7;
//tempks[VK_RWIN] = 1 << 7;
}
if (j == 1 || j == 3)
{
dicis |= Qt::ShiftModifier;
tempks[VK_LSHIFT] = 1 << 7;
tempks[VK_SHIFT] = 1 << 7;
//qDebug() << "NEVER ME: ";
}
int charlength = ToUnicode(i, scancode, tempks, cbuf, 255, 0);
if (charlength == 1 || charlength < 0)
{
QString temp = QString::fromWCharArray(cbuf);
if (temp.size() > 0)
{
QChar tempchar(temp.at(0));
charKeyInformation tempinfo;
tempinfo.modifiers = dicis;
tempinfo.virtualkey = i;
if (!virtualkeyToCharKeyInformation.contains(tempchar.unicode()))
{
virtualkeyToCharKeyInformation.insert(tempchar.unicode(), tempinfo);
total++;
}
}
}
}
}
//qDebug() << "TOTAL: " << total;
}
``` | /content/code_sandbox/src/qtwinkeymapper.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 4,483 |
```c++
#include "winappprofiletimerdialog.h"
#include "ui_winappprofiletimerdialog.h"
WinAppProfileTimerDialog::WinAppProfileTimerDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::WinAppProfileTimerDialog)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
connect(&appTimer, SIGNAL(timeout()), this, SLOT(accept()));
connect(ui->capturePushButton, SIGNAL(clicked()), this, SLOT(startTimer()));
connect(ui->cancelPushButton, SIGNAL(clicked()), this, SLOT(close()));
}
WinAppProfileTimerDialog::~WinAppProfileTimerDialog()
{
delete ui;
}
void WinAppProfileTimerDialog::startTimer()
{
appTimer.start(ui->intervalSpinBox->value() * 1000);
this->setEnabled(false);
}
``` | /content/code_sandbox/src/winappprofiletimerdialog.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 172 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef JOYCONTROLSTICKDIRECTIONSTYPE_H
#define JOYCONTROLSTICKDIRECTIONSTYPE_H
class JoyStickDirectionsType {
public:
enum JoyStickDirections {
StickCentered = 0, StickUp = 1, StickRight = 3,
StickDown = 5, StickLeft = 7, StickRightUp = 2,
StickRightDown = 4, StickLeftUp = 8, StickLeftDown = 6
};
};
#endif // JOYCONTROLSTICKDIRECTIONSTYPE_H
``` | /content/code_sandbox/src/joycontrolstickdirectionstype.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 209 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef JOYDPAD_H
#define JOYDPAD_H
#include <QObject>
#include <QHash>
#include <QString>
#include <QTimer>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include "joybuttontypes/joydpadbutton.h"
class JoyDPad : public QObject
{
Q_OBJECT
public:
explicit JoyDPad(int index, int originset, SetJoystick *parentSet, QObject *parent=0);
~JoyDPad();
enum JoyMode {StandardMode=0, EightWayMode, FourWayCardinal, FourWayDiagonal};
JoyDPadButton* getJoyButton(int index);
QHash<int, JoyDPadButton*>* getJoyButtons();
int getCurrentDirection();
int getJoyNumber();
int getIndex();
int getRealJoyNumber();
virtual QString getName(bool fullForceFormat=false, bool displayNames=false);
void joyEvent(int value, bool ignoresets=false);
void queuePendingEvent(int value, bool ignoresets=false);
void activatePendingEvent();
bool hasPendingEvent();
void clearPendingEvent();
void setJoyMode(JoyMode mode);
JoyMode getJoyMode();
void releaseButtonEvents();
void setButtonsMouseMode(JoyButton::JoyMouseMovementMode mode);
bool hasSameButtonsMouseMode();
JoyButton::JoyMouseMovementMode getButtonsPresetMouseMode();
void setButtonsMouseCurve(JoyButton::JoyMouseCurve mouseCurve);
bool hasSameButtonsMouseCurve();
JoyButton::JoyMouseCurve getButtonsPresetMouseCurve();
void setButtonsSpringWidth(int value);
int getButtonsPresetSpringWidth();
void setButtonsSpringHeight(int value);
int getButtonsPresetSpringHeight();
void setButtonsSensitivity(double value);
double getButtonsPresetSensitivity();
void setButtonsWheelSpeedX(int value);
void setButtonsWheelSpeedY(int value);
QString getDpadName();
virtual bool isDefault();
QHash<int, JoyDPadButton*>* getButtons();
void readConfig(QXmlStreamReader *xml);
void writeConfig(QXmlStreamWriter *xml);
virtual QString getXmlName();
virtual void setDefaultDPadName(QString tempname);
virtual QString getDefaultDPadName();
SetJoystick* getParentSet();
bool hasSlotsAssigned();
bool isRelativeSpring();
void copyAssignments(JoyDPad *destDPad);
unsigned int getDPadDelay();
double getButtonsEasingDuration();
void setButtonsSpringDeadCircleMultiplier(int value);
int getButtonsSpringDeadCircleMultiplier();
void setButtonsExtraAccelerationCurve(JoyButton::JoyExtraAccelerationCurve curve);
JoyButton::JoyExtraAccelerationCurve getButtonsExtraAccelerationCurve();
QHash<int, JoyDPadButton*> getDirectionButtons(JoyDPadButton::JoyDPadDirections direction);
void setDirButtonsUpdateInitAccel(JoyDPadButton::JoyDPadDirections direction, bool state);
void copyLastDistanceValues(JoyDPad *srcDPad);
virtual void eventReset();
static const QString xmlName;
static const unsigned int DEFAULTDPADDELAY;
protected:
void populateButtons();
void createDeskEvent(bool ignoresets = false);
QHash<int, JoyDPadButton*> getApplicableButtons();
bool readMainConfig(QXmlStreamReader *xml);
QHash<int, JoyDPadButton*> buttons;
int index;
JoyDPadButton::JoyDPadDirections prevDirection;
JoyDPadButton::JoyDPadDirections pendingDirection;
JoyDPadButton *activeDiagonalButton;
int originset;
JoyMode currentMode;
QString dpadName;
QString defaultDPadName;
SetJoystick *parentSet;
QTimer directionDelayTimer;
unsigned int dpadDelay;
bool pendingEvent;
int pendingEventDirection;
bool pendingIgnoreSets;
signals:
void active(int value);
void released(int value);
void dpadNameChanged();
void dpadDelayChanged(int value);
void joyModeChanged();
void propertyUpdated();
public slots:
void setDPadName(QString tempName);
void setButtonsSpringRelativeStatus(bool value);
void setDPadDelay(int value);
void setButtonsEasingDuration(double value);
void establishPropertyUpdatedConnection();
void disconnectPropertyUpdatedConnection();
private slots:
void dpadDirectionChangeEvent();
};
#endif // JOYDPAD_H
``` | /content/code_sandbox/src/joydpad.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,038 |
```objective-c
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
#ifndef JOYAXISCONTEXTMENU_H
#define JOYAXISCONTEXTMENU_H
#include <QMenu>
#include "joyaxis.h"
#include "uihelpers/joyaxiscontextmenuhelper.h"
class JoyAxisContextMenu : public QMenu
{
Q_OBJECT
public:
explicit JoyAxisContextMenu(JoyAxis *axis, QWidget *parent = 0);
void buildMenu();
void buildAxisMenu();
void buildTriggerMenu();
protected:
int getPresetIndex();
int getTriggerPresetIndex();
JoyAxis *axis;
JoyAxisContextMenuHelper helper;
signals:
public slots:
private slots:
void setAxisPreset();
void setTriggerPreset();
void openMouseSettingsDialog();
};
#endif // JOYAXISCONTEXTMENU_H
``` | /content/code_sandbox/src/joyaxiscontextmenu.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 257 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
//#include <QDebug>
#include <QHashIterator>
#include "setjoystick.h"
#include "inputdevice.h"
const int SetJoystick::MAXNAMELENGTH = 30;
const int SetJoystick::RAISEDDEADZONE = 20000;
SetJoystick::SetJoystick(InputDevice *device, int index, QObject *parent) :
QObject(parent)
{
this->device = device;
this->index = index;
reset();
}
SetJoystick::SetJoystick(InputDevice *device, int index, bool runreset, QObject *parent) :
QObject(parent)
{
this->device = device;
this->index = index;
if (runreset)
{
reset();
}
}
SetJoystick::~SetJoystick()
{
deleteSticks();
deleteVDpads();
deleteButtons();
deleteAxes();
deleteHats();
}
JoyButton* SetJoystick::getJoyButton(int index)
{
return buttons.value(index);
}
JoyAxis* SetJoystick::getJoyAxis(int index)
{
return axes.value(index);
}
JoyDPad* SetJoystick::getJoyDPad(int index)
{
return hats.value(index);
}
VDPad* SetJoystick::getVDPad(int index)
{
return vdpads.value(index);
}
JoyControlStick* SetJoystick::getJoyStick(int index)
{
return sticks.value(index);
}
void SetJoystick::refreshButtons()
{
deleteButtons();
for (int i=0; i < device->getNumberRawButtons(); i++)
{
JoyButton *button = new JoyButton (i, index, this, this);
buttons.insert(i, button);
enableButtonConnections(button);
}
}
void SetJoystick::refreshAxes()
{
deleteAxes();
InputDevice *device = getInputDevice();
for (int i=0; i < device->getNumberRawAxes(); i++)
{
JoyAxis *axis = new JoyAxis(i, index, this, this);
axes.insert(i, axis);
if (device->hasCalibrationThrottle(i))
{
JoyAxis::ThrottleTypes throttle = device->getCalibrationThrottle(i);
axis->setInitialThrottle(throttle);
}
enableAxisConnections(axis);
}
}
void SetJoystick::refreshHats()
{
deleteHats();
for (int i=0; i < device->getNumberRawHats(); i++)
{
JoyDPad *dpad = new JoyDPad(i, index, this, this);
hats.insert(i, dpad);
enableHatConnections(dpad);
}
}
void SetJoystick::deleteButtons()
{
QHashIterator<int, JoyButton*> iter(buttons);
while (iter.hasNext())
{
JoyButton *button = iter.next().value();
if (button)
{
delete button;
button = 0;
}
}
buttons.clear();
}
void SetJoystick::deleteAxes()
{
QHashIterator<int, JoyAxis*> iter(axes);
while (iter.hasNext())
{
JoyAxis *axis = iter.next().value();
if (axis)
{
delete axis;
axis = 0;
}
}
axes.clear();
}
void SetJoystick::deleteSticks()
{
QHashIterator<int, JoyControlStick*> iter(sticks);
while (iter.hasNext())
{
JoyControlStick *stick = iter.next().value();
if (stick)
{
delete stick;
stick = 0;
}
}
sticks.clear();
}
void SetJoystick::deleteVDpads()
{
QHashIterator<int, VDPad*> iter(vdpads);
while (iter.hasNext())
{
VDPad *dpad = iter.next().value();
if (dpad)
{
delete dpad;
dpad = 0;
}
}
vdpads.clear();
}
void SetJoystick::deleteHats()
{
QHashIterator<int, JoyDPad*> iter(hats);
while (iter.hasNext())
{
JoyDPad *dpad = iter.next().value();
if (dpad)
{
delete dpad;
dpad = 0;
}
}
hats.clear();
}
int SetJoystick::getNumberButtons()
{
return buttons.count();
}
int SetJoystick::getNumberAxes()
{
return axes.count();
}
int SetJoystick::getNumberHats()
{
return hats.count();
}
int SetJoystick::getNumberSticks()
{
return sticks.size();
}
int SetJoystick::getNumberVDPads()
{
return vdpads.size();
}
void SetJoystick::reset()
{
deleteSticks();
deleteVDpads();
refreshAxes();
refreshButtons();
refreshHats();
name = QString();
}
void SetJoystick::propogateSetChange(int index)
{
emit setChangeActivated(index);
}
void SetJoystick::propogateSetButtonAssociation(int button, int newset, int mode)
{
if (newset != index)
{
emit setAssignmentButtonChanged(button, index, newset, mode);
}
}
void SetJoystick::propogateSetAxisButtonAssociation(int button, int axis, int newset, int mode)
{
if (newset != index)
{
emit setAssignmentAxisChanged(button, axis, index, newset, mode);
}
}
void SetJoystick::propogateSetStickButtonAssociation(int button, int stick, int newset, int mode)
{
if (newset != index)
{
emit setAssignmentStickChanged(button, stick, index, newset, mode);
}
}
void SetJoystick::propogateSetDPadButtonAssociation(int button, int dpad, int newset, int mode)
{
if (newset != index)
{
emit setAssignmentDPadChanged(button, dpad, index, newset, mode);
}
}
void SetJoystick::propogateSetVDPadButtonAssociation(int button, int dpad, int newset, int mode)
{
if (newset != index)
{
emit setAssignmentVDPadChanged(button, dpad, index, newset, mode);
}
}
/**
* @brief Perform a release of all elements of a set. Stick and vdpad
* releases will be handled by the associated button or axis.
*/
void SetJoystick::release()
{
QHashIterator<int, JoyAxis*> iterAxes(axes);
while (iterAxes.hasNext())
{
JoyAxis *axis = iterAxes.next().value();
axis->clearPendingEvent();
axis->joyEvent(axis->getCurrentThrottledDeadValue(), true);
axis->eventReset();
}
QHashIterator<int, JoyDPad*> iterDPads(hats);
while (iterDPads.hasNext())
{
JoyDPad *dpad = iterDPads.next().value();
dpad->clearPendingEvent();
dpad->joyEvent(0, true);
dpad->eventReset();
}
QHashIterator<int, JoyButton*> iterButtons(buttons);
while (iterButtons.hasNext())
{
JoyButton *button = iterButtons.next().value();
button->clearPendingEvent();
button->joyEvent(false, true);
button->eventReset();
}
}
void SetJoystick::readConfig(QXmlStreamReader *xml)
{
if (xml->isStartElement() && xml->name() == "set")
{
//reset();
xml->readNextStartElement();
while (!xml->atEnd() && (!xml->isEndElement() && xml->name() != "set"))
{
if (xml->name() == "button" && xml->isStartElement())
{
int index = xml->attributes().value("index").toString().toInt();
JoyButton *button = getJoyButton(index-1);
if (button)
{
button->readConfig(xml);
}
else
{
xml->skipCurrentElement();
}
}
else if (xml->name() == "axis" && xml->isStartElement())
{
int index = xml->attributes().value("index").toString().toInt();
JoyAxis *axis = getJoyAxis(index-1);
if (axis)
{
axis->readConfig(xml);
}
else
{
xml->skipCurrentElement();
}
}
else if (xml->name() == "dpad" && xml->isStartElement())
{
int index = xml->attributes().value("index").toString().toInt();
JoyDPad *dpad = getJoyDPad(index-1);
if (dpad)
{
dpad->readConfig(xml);
}
else
{
xml->skipCurrentElement();
}
}
else if (xml->name() == "stick" && xml->isStartElement())
{
int stickIndex = xml->attributes().value("index").toString().toInt();
if (stickIndex > 0)
{
stickIndex -= 1;
JoyControlStick *stick = getJoyStick(stickIndex);
if (stick)
{
stick->readConfig(xml);
}
else
{
xml->skipCurrentElement();
}
}
else
{
xml->skipCurrentElement();
}
}
else if (xml->name() == "vdpad" && xml->isStartElement())
{
int index = xml->attributes().value("index").toString().toInt();
VDPad *vdpad = getVDPad(index-1);
if (vdpad)
{
vdpad->readConfig(xml);
}
else
{
xml->skipCurrentElement();
}
}
else if (xml->name() == "name" && xml->isStartElement())
{
QString temptext = xml->readElementText();
if (!temptext.isEmpty())
{
setName(temptext);
}
}
else
{
// If none of the above, skip the element
xml->skipCurrentElement();
}
xml->readNextStartElement();
}
}
}
void SetJoystick::writeConfig(QXmlStreamWriter *xml)
{
if (!isSetEmpty())
{
xml->writeStartElement("set");
xml->writeAttribute("index", QString::number(index+1));
if (!name.isEmpty())
{
xml->writeTextElement("name", name);
}
for (int i=0; i < getNumberSticks(); i++)
{
JoyControlStick *stick = getJoyStick(i);
stick->writeConfig(xml);
}
for (int i=0; i < getNumberVDPads(); i++)
{
VDPad *vdpad = getVDPad(i);
if (vdpad)
{
vdpad->writeConfig(xml);
}
}
for (int i=0; i < getNumberAxes(); i++)
{
JoyAxis *axis = getJoyAxis(i);
if (!axis->isPartControlStick() && axis->hasControlOfButtons())
{
axis->writeConfig(xml);
}
}
for (int i=0; i < getNumberHats(); i++)
{
JoyDPad *dpad = getJoyDPad(i);
dpad->writeConfig(xml);
}
for (int i=0; i < getNumberButtons(); i++)
{
JoyButton *button = getJoyButton(i);
if (button && !button->isPartVDPad())
{
button->writeConfig(xml);
}
}
xml->writeEndElement();
}
}
bool SetJoystick::isSetEmpty()
{
bool result = true;
QHashIterator<int, JoyButton*> iter(buttons);
while (iter.hasNext() && result)
{
JoyButton *button = iter.next().value();
if (!button->isDefault())
{
result = false;
}
}
QHashIterator<int, JoyAxis*> iter2(axes);
while (iter2.hasNext() && result)
{
JoyAxis *axis = iter2.next().value();
if (!axis->isDefault())
{
result = false;
}
}
QHashIterator<int, JoyDPad*> iter3(hats);
while (iter3.hasNext() && result)
{
JoyDPad *dpad = iter3.next().value();
if (!dpad->isDefault())
{
result = false;
}
}
QHashIterator<int, JoyControlStick*> iter4(sticks);
while (iter4.hasNext() && result)
{
JoyControlStick *stick = iter4.next().value();
if (!stick->isDefault())
{
result = false;
}
}
QHashIterator<int, VDPad*> iter5(vdpads);
while (iter5.hasNext() && result)
{
VDPad *vdpad = iter5.next().value();
if (!vdpad->isDefault())
{
result = false;
}
}
return result;
}
void SetJoystick::propogateSetAxisThrottleSetting(int index)
{
JoyAxis *axis = axes.value(index);
if (axis)
{
emit setAssignmentAxisThrottleChanged(index, axis->getCurrentlyAssignedSet());
}
}
void SetJoystick::addControlStick(int index, JoyControlStick *stick)
{
sticks.insert(index, stick);
connect(stick, SIGNAL(stickNameChanged()), this, SLOT(propogateSetStickNameChange()));
QHashIterator<JoyStickDirectionsType::JoyStickDirections, JoyControlStickButton*> iter(*stick->getButtons());
while (iter.hasNext())
{
JoyControlStickButton *button = iter.next().value();
if (button)
{
connect(button, SIGNAL(setChangeActivated(int)), this, SLOT(propogateSetChange(int)));
connect(button, SIGNAL(setAssignmentChanged(int,int,int,int)), this, SLOT(propogateSetStickButtonAssociation(int,int,int,int)));
connect(button, SIGNAL(clicked(int)), this, SLOT(propogateSetStickButtonClick(int)), Qt::QueuedConnection);
connect(button, SIGNAL(released(int)), this, SLOT(propogateSetStickButtonRelease(int)), Qt::QueuedConnection);
connect(button, SIGNAL(buttonNameChanged()), this, SLOT(propogateSetStickButtonNameChange()));
}
}
}
void SetJoystick::removeControlStick(int index)
{
if (sticks.contains(index))
{
JoyControlStick *stick = sticks.value(index);
sticks.remove(index);
delete stick;
stick = 0;
}
}
void SetJoystick::addVDPad(int index, VDPad *vdpad)
{
vdpads.insert(index, vdpad);
connect(vdpad, SIGNAL(dpadNameChanged()), this, SLOT(propogateSetVDPadNameChange()));
QHashIterator<int, JoyDPadButton*> iter(*vdpad->getButtons());
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
if (button)
{
connect(button, SIGNAL(setChangeActivated(int)), this, SLOT(propogateSetChange(int)));
connect(button, SIGNAL(setAssignmentChanged(int,int,int,int)), this, SLOT(propogateSetVDPadButtonAssociation(int,int,int,int)));
connect(button, SIGNAL(clicked(int)), this, SLOT(propogateSetDPadButtonClick(int)), Qt::QueuedConnection);
connect(button, SIGNAL(released(int)), this, SLOT(propogateSetDPadButtonRelease(int)), Qt::QueuedConnection);
connect(button, SIGNAL(buttonNameChanged()), this, SLOT(propogateSetVDPadButtonNameChange()));
}
}
}
void SetJoystick::removeVDPad(int index)
{
if (vdpads.contains(index))
{
VDPad *vdpad = vdpads.value(index);
vdpads.remove(index);
delete vdpad;
vdpad = 0;
}
}
int SetJoystick::getIndex()
{
return index;
}
unsigned int SetJoystick::getRealIndex()
{
return index + 1;
}
void SetJoystick::propogateSetButtonClick(int button)
{
JoyButton *jButton = static_cast<JoyButton*>(sender());
if (jButton)
{
if (!jButton->getIgnoreEventState())
{
emit setButtonClick(index, button);
}
}
}
void SetJoystick::propogateSetButtonRelease(int button)
{
JoyButton *jButton = static_cast<JoyButton*>(sender());
if (jButton)
{
if (!jButton->getIgnoreEventState())
{
emit setButtonRelease(index, button);
}
}
}
void SetJoystick::propogateSetAxisButtonClick(int button)
{
JoyAxisButton *axisButton = static_cast<JoyAxisButton*>(sender());
if (axisButton)
{
JoyAxis *axis = axisButton->getAxis();
if (!axisButton->getIgnoreEventState())
{
emit setAxisButtonClick(index, axis->getIndex(), button);
}
}
}
void SetJoystick::propogateSetAxisButtonRelease(int button)
{
JoyAxisButton *axisButton = static_cast<JoyAxisButton*>(sender());
if (axisButton)
{
JoyAxis *axis = axisButton->getAxis();
if (!axisButton->getIgnoreEventState())
{
emit setAxisButtonRelease(index, axis->getIndex(), button);
}
}
}
void SetJoystick::propogateSetStickButtonClick(int button)
{
JoyControlStickButton *stickButton = static_cast<JoyControlStickButton*>(sender());
if (stickButton)
{
JoyControlStick *stick = stickButton->getStick();
if (stick && !stickButton->getIgnoreEventState())
{
emit setStickButtonClick(index, stick->getIndex(), button);
}
}
}
void SetJoystick::propogateSetStickButtonRelease(int button)
{
JoyControlStickButton *stickButton = static_cast<JoyControlStickButton*>(sender());
if (stickButton)
{
JoyControlStick *stick = stickButton->getStick();
if (!stickButton->getIgnoreEventState())
{
emit setStickButtonRelease(index, stick->getIndex(), button);
}
}
}
void SetJoystick::propogateSetDPadButtonClick(int button)
{
JoyDPadButton *dpadButton = static_cast<JoyDPadButton*>(sender());
if (dpadButton)
{
JoyDPad *dpad = dpadButton->getDPad();
if (dpad && dpadButton->getButtonState() &&
!dpadButton->getIgnoreEventState())
{
emit setDPadButtonClick(index, dpad->getIndex(), button);
}
}
}
void SetJoystick::propogateSetDPadButtonRelease(int button)
{
JoyDPadButton *dpadButton = static_cast<JoyDPadButton*>(sender());
if (dpadButton)
{
JoyDPad *dpad = dpadButton->getDPad();
if (dpad && !dpadButton->getButtonState() &&
!dpadButton->getIgnoreEventState())
{
emit setDPadButtonRelease(index, dpad->getIndex(), button);
}
}
}
void SetJoystick::propogateSetButtonNameChange()
{
JoyButton *button = static_cast<JoyButton*>(sender());
disconnect(button, SIGNAL(buttonNameChanged()), this, SLOT(propogateSetButtonNameChange()));
emit setButtonNameChange(button->getJoyNumber());
connect(button, SIGNAL(buttonNameChanged()), this, SLOT(propogateSetButtonNameChange()));
}
void SetJoystick::propogateSetAxisButtonNameChange()
{
JoyAxisButton *button = static_cast<JoyAxisButton*>(sender());
disconnect(button, SIGNAL(buttonNameChanged()), this, SLOT(propogateSetAxisButtonNameChange()));
emit setAxisButtonNameChange(button->getAxis()->getIndex(), button->getJoyNumber());
connect(button, SIGNAL(buttonNameChanged()), this, SLOT(propogateSetAxisButtonNameChange()));
}
void SetJoystick::propogateSetStickButtonNameChange()
{
JoyControlStickButton *button = static_cast<JoyControlStickButton*>(sender());
disconnect(button, SIGNAL(buttonNameChanged()), this, SLOT(propogateSetStickButtonNameChange()));
emit setStickButtonNameChange(button->getStick()->getIndex(), button->getJoyNumber());
connect(button, SIGNAL(buttonNameChanged()), this, SLOT(propogateSetStickButtonNameChange()));
}
void SetJoystick::propogateSetDPadButtonNameChange()
{
JoyDPadButton *button = static_cast<JoyDPadButton*>(sender());
disconnect(button, SIGNAL(buttonNameChanged()), this, SLOT(propogateSetDPadButtonNameChange()));
emit setDPadButtonNameChange(button->getDPad()->getIndex(), button->getJoyNumber());
connect(button, SIGNAL(buttonNameChanged()), this, SLOT(propogateSetDPadButtonNameChange()));
}
void SetJoystick::propogateSetVDPadButtonNameChange()
{
JoyDPadButton *button = static_cast<JoyDPadButton*>(sender());
disconnect(button, SIGNAL(buttonNameChanged()), this, SLOT(propogateSetVDPadButtonNameChange()));
emit setVDPadButtonNameChange(button->getDPad()->getIndex(), button->getJoyNumber());
connect(button, SIGNAL(buttonNameChanged()), this, SLOT(propogateSetVDPadButtonNameChange()));
}
void SetJoystick::propogateSetAxisNameChange()
{
JoyAxis *axis = static_cast<JoyAxis*>(sender());
disconnect(axis, SIGNAL(axisNameChanged()), this, SLOT(propogateSetAxisNameChange()));
emit setAxisNameChange(axis->getIndex());
connect(axis, SIGNAL(axisNameChanged()), this, SLOT(propogateSetAxisNameChange()));
}
void SetJoystick::propogateSetStickNameChange()
{
JoyControlStick *stick = static_cast<JoyControlStick*>(sender());
disconnect(stick, SIGNAL(stickNameChanged()), this, SLOT(propogateSetStickNameChange()));
emit setStickNameChange(stick->getIndex());
connect(stick, SIGNAL(stickNameChanged()), this, SLOT(propogateSetStickNameChange()));
}
void SetJoystick::propogateSetDPadNameChange()
{
JoyDPad *dpad = static_cast<JoyDPad*>(sender());
disconnect(dpad, SIGNAL(dpadNameChanged()), this, SLOT(propogateSetDPadButtonNameChange()));
emit setDPadNameChange(dpad->getIndex());
connect(dpad, SIGNAL(dpadNameChanged()), this, SLOT(propogateSetDPadButtonNameChange()));
}
void SetJoystick::propogateSetVDPadNameChange()
{
VDPad *vdpad = static_cast<VDPad*>(sender());
disconnect(vdpad, SIGNAL(dpadNameChanged()), this, SLOT(propogateSetVDPadNameChange()));
emit setVDPadNameChange(vdpad->getIndex());
connect(vdpad, SIGNAL(dpadNameChanged()), this, SLOT(propogateSetVDPadNameChange()));
}
void SetJoystick::setIgnoreEventState(bool ignore)
{
QHashIterator<int, JoyButton*> iter(buttons);
while (iter.hasNext())
{
JoyButton *button = iter.next().value();
if (button)
{
button->setIgnoreEventState(ignore);
}
}
QHashIterator<int, JoyAxis*> iter2(axes);
while (iter2.hasNext())
{
JoyAxis *axis = iter2.next().value();
if (axis)
{
JoyAxisButton *naxisbutton = axis->getNAxisButton();
naxisbutton->setIgnoreEventState(ignore);
JoyAxisButton *paxisbutton = axis->getPAxisButton();
paxisbutton->setIgnoreEventState(ignore);
}
}
QHashIterator<int, JoyDPad*> iter3(hats);
while (iter3.hasNext())
{
JoyDPad *dpad = iter3.next().value();
if (dpad)
{
QHash<int, JoyDPadButton*>* dpadbuttons = dpad->getButtons();
QHashIterator<int, JoyDPadButton*> iterdpadbuttons(*dpadbuttons);
while (iterdpadbuttons.hasNext())
{
JoyDPadButton *dpadbutton = iterdpadbuttons.next().value();
if (dpadbutton)
{
dpadbutton->setIgnoreEventState(ignore);
}
}
}
}
QHashIterator<int, JoyControlStick*> iter4(sticks);
while (iter4.hasNext())
{
JoyControlStick *stick = iter4.next().value();
if (stick)
{
QHash<JoyControlStick::JoyStickDirections, JoyControlStickButton*> *stickButtons = stick->getButtons();
QHashIterator<JoyControlStick::JoyStickDirections, JoyControlStickButton*> iterstickbuttons(*stickButtons);
while (iterstickbuttons.hasNext())
{
JoyControlStickButton *stickbutton = iterstickbuttons.next().value();
stickbutton->setIgnoreEventState(ignore);
}
}
}
QHashIterator<int, VDPad*> iter5(vdpads);
while (iter5.hasNext())
{
VDPad *vdpad = iter5.next().value();
if (vdpad)
{
QHash<int, JoyDPadButton*>* dpadbuttons = vdpad->getButtons();
QHashIterator<int, JoyDPadButton*> itervdpadbuttons(*dpadbuttons);
while (itervdpadbuttons.hasNext())
{
JoyDPadButton *dpadbutton = itervdpadbuttons.next().value();
dpadbutton->setIgnoreEventState(ignore);
}
}
}
}
void SetJoystick::propogateSetAxisActivated(int value)
{
JoyAxis *axis = static_cast<JoyAxis*>(sender());
emit setAxisActivated(this->index, axis->getIndex(), value);
}
void SetJoystick::propogateSetAxisReleased(int value)
{
JoyAxis *axis = static_cast<JoyAxis*>(sender());
emit setAxisReleased(this->index, axis->getIndex(), value);
}
void SetJoystick::enableButtonConnections(JoyButton *button)
{
connect(button, SIGNAL(setChangeActivated(int)), this, SLOT(propogateSetChange(int)));
connect(button, SIGNAL(setAssignmentChanged(int,int,int)), this, SLOT(propogateSetButtonAssociation(int,int,int)));
connect(button, SIGNAL(clicked(int)), this, SLOT(propogateSetButtonClick(int)), Qt::QueuedConnection);
connect(button, SIGNAL(clicked(int)), device, SLOT(buttonClickEvent(int)), Qt::QueuedConnection);
connect(button, SIGNAL(released(int)), this, SLOT(propogateSetButtonRelease(int)));
connect(button, SIGNAL(released(int)), device, SLOT(buttonReleaseEvent(int)));
connect(button, SIGNAL(buttonNameChanged()), this, SLOT(propogateSetButtonNameChange()));
}
void SetJoystick::enableAxisConnections(JoyAxis *axis)
{
connect(axis, SIGNAL(throttleChangePropogated(int)), this, SLOT(propogateSetAxisThrottleSetting(int)));
connect(axis, SIGNAL(axisNameChanged()), this, SLOT(propogateSetAxisNameChange()));
connect(axis, SIGNAL(active(int)), this, SLOT(propogateSetAxisActivated(int)));
connect(axis, SIGNAL(released(int)), this, SLOT(propogateSetAxisReleased(int)));
JoyAxisButton *button = axis->getNAxisButton();
connect(button, SIGNAL(setChangeActivated(int)), this, SLOT(propogateSetChange(int)));
connect(button, SIGNAL(setAssignmentChanged(int,int,int,int)), this, SLOT(propogateSetAxisButtonAssociation(int,int,int,int)));
connect(button, SIGNAL(clicked(int)), this, SLOT(propogateSetAxisButtonClick(int)), Qt::QueuedConnection);
connect(button, SIGNAL(released(int)), this, SLOT(propogateSetAxisButtonRelease(int)), Qt::QueuedConnection);
connect(button, SIGNAL(buttonNameChanged()), this, SLOT(propogateSetAxisButtonNameChange()));
button = axis->getPAxisButton();
connect(button, SIGNAL(setChangeActivated(int)), this, SLOT(propogateSetChange(int)));
connect(button, SIGNAL(setAssignmentChanged(int,int,int,int)), this, SLOT(propogateSetAxisButtonAssociation(int,int,int,int)));
connect(button, SIGNAL(clicked(int)), this, SLOT(propogateSetAxisButtonClick(int)), Qt::QueuedConnection);
connect(button, SIGNAL(released(int)), this, SLOT(propogateSetAxisButtonRelease(int)), Qt::QueuedConnection);
connect(button, SIGNAL(buttonNameChanged()), this, SLOT(propogateSetAxisButtonNameChange()));
}
void SetJoystick::enableHatConnections(JoyDPad *dpad)
{
connect(dpad, SIGNAL(dpadNameChanged()), this, SLOT(propogateSetDPadNameChange()));
QHash<int, JoyDPadButton*> *buttons = dpad->getJoyButtons();
QHashIterator<int, JoyDPadButton*> iter(*buttons);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
connect(button, SIGNAL(setChangeActivated(int)), this, SLOT(propogateSetChange(int)));
connect(button, SIGNAL(setAssignmentChanged(int,int,int,int)), this, SLOT(propogateSetDPadButtonAssociation(int,int,int,int)));
connect(button, SIGNAL(clicked(int)), this, SLOT(propogateSetDPadButtonClick(int)), Qt::QueuedConnection);
connect(button, SIGNAL(clicked(int)), device, SLOT(dpadButtonClickEvent(int)), Qt::QueuedConnection);
connect(button, SIGNAL(released(int)), this, SLOT(propogateSetDPadButtonRelease(int)), Qt::QueuedConnection);
connect(button, SIGNAL(released(int)), device, SLOT(dpadButtonReleaseEvent(int)), Qt::QueuedConnection);
connect(button, SIGNAL(buttonNameChanged()), this, SLOT(propogateSetDPadButtonNameChange()));
}
}
InputDevice* SetJoystick::getInputDevice()
{
return device;
}
void SetJoystick::setName(QString name)
{
if (name.length() <= MAXNAMELENGTH)
{
this->name = name;
emit propertyUpdated();
}
else if (name.length() > MAXNAMELENGTH)
{
// Truncate name to 27 characters. Add ellipsis at the end.
name.truncate(MAXNAMELENGTH-3);
this->name = QString(name).append("...");
emit propertyUpdated();
}
}
QString SetJoystick::getName()
{
return name;
}
void SetJoystick::copyAssignments(SetJoystick *destSet)
{
for (int i=0; i < device->getNumberAxes(); i++)
{
JoyAxis *sourceAxis = axes.value(i);
JoyAxis *destAxis = destSet->axes.value(i);
if (sourceAxis && destAxis)
{
sourceAxis->copyAssignments(destAxis);
}
}
QHashIterator<int, JoyControlStick*> stickIter(sticks);
while (stickIter.hasNext())
{
stickIter.next();
int index = stickIter.key();
JoyControlStick *sourceStick = stickIter.value();
JoyControlStick *destStick = destSet->sticks.value(index);
if (sourceStick && destStick)
{
sourceStick->copyAssignments(destStick);
}
}
for (int i=0; i < device->getNumberHats(); i++)
{
JoyDPad *sourceDPad = hats.value(i);
JoyDPad *destDPad = destSet->hats.value(i);
if (sourceDPad && destDPad)
{
sourceDPad->copyAssignments(destDPad);
}
}
QHashIterator<int, VDPad*> vdpadIter(vdpads);
while (vdpadIter.hasNext())
{
vdpadIter.next();
int index = vdpadIter.key();
VDPad *sourceVDpad = vdpadIter.value();
VDPad *destVDPad = destSet->vdpads.value(index);
if (sourceVDpad && destVDPad)
{
sourceVDpad->copyAssignments(destVDPad);
}
}
for (int i=0; i < device->getNumberButtons(); i++)
{
JoyButton *sourceButton = buttons.value(i);
JoyButton *destButton = destSet->buttons.value(i);
if (sourceButton && destButton)
{
sourceButton->copyAssignments(destButton);
}
}
}
QString SetJoystick::getSetLabel()
{
QString temp;
if (!name.isEmpty())
{
temp = tr("Set %1: %2").arg(index+1).arg(name);
}
else
{
temp = tr("Set %1").arg(index+1);
}
return temp;
}
void SetJoystick::establishPropertyUpdatedConnection()
{
connect(this, SIGNAL(propertyUpdated()), getInputDevice(), SLOT(profileEdited()));
}
void SetJoystick::disconnectPropertyUpdatedConnection()
{
disconnect(this, SIGNAL(propertyUpdated()), getInputDevice(), SLOT(profileEdited()));
}
/**
* @brief Raise the dead zones for axes. Used when launching
* the controller mapping window.
*/
void SetJoystick::raiseAxesDeadZones(int deadZone)
{
unsigned int tempDeadZone = deadZone;
if (deadZone <= 0 || deadZone > 32767)
{
tempDeadZone = RAISEDDEADZONE;
}
QHashIterator<int, JoyAxis*> axisIter(axes);
while (axisIter.hasNext())
{
JoyAxis *temp = axisIter.next().value();
temp->disconnectPropertyUpdatedConnection();
temp->setDeadZone(tempDeadZone);
temp->establishPropertyUpdatedConnection();
}
}
void SetJoystick::currentAxesDeadZones(QList<int> *axesDeadZones)
{
QHashIterator<int, JoyAxis*> axisIter(axes);
while (axisIter.hasNext())
{
JoyAxis *temp = axisIter.next().value();
axesDeadZones->append(temp->getDeadZone());
}
}
void SetJoystick::setAxesDeadZones(QList<int> *axesDeadZones)
{
QListIterator<int> iter(*axesDeadZones);
int axisNum = 0;
while (iter.hasNext())
{
int deadZoneValue = iter.next();
if (axes.contains(axisNum))
{
JoyAxis *temp = getJoyAxis(axisNum);
temp->disconnectPropertyUpdatedConnection();
temp->setDeadZone(deadZoneValue);
temp->establishPropertyUpdatedConnection();
}
axisNum++;
}
}
void SetJoystick::setAxisThrottle(int axisNum, JoyAxis::ThrottleTypes throttle)
{
if (axes.contains(axisNum))
{
JoyAxis *temp = axes.value(axisNum);
temp->setInitialThrottle(throttle);
}
}
``` | /content/code_sandbox/src/setjoystick.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 7,685 |
```c++
/* antimicro Gamepad to KB+M event mapper
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* along with this program. If not, see <path_to_url
*/
//#include <QDebug>
#include <QDir>
#include <QFileDialog>
#include <QLocale>
#include <QTranslator>
#include <QListIterator>
#include <QStringList>
#include <QTableWidgetItem>
#include <QMapIterator>
#include <QVariant>
#include <QMessageBox>
#include <QDesktopWidget>
#include <QComboBox>
#include <QPushButton>
#include <QLabel>
#include <QList>
#include <QListWidget>
#ifdef Q_OS_WIN
#include <QSysInfo>
#endif
#ifdef Q_OS_UNIX
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
#include <QApplication>
#endif
#include "eventhandlerfactory.h"
#endif
#include "mainsettingsdialog.h"
#include "ui_mainsettingsdialog.h"
#include "addeditautoprofiledialog.h"
#include "editalldefaultautoprofiledialog.h"
#include "common.h"
#ifdef Q_OS_WIN
#include "eventhandlerfactory.h"
#include "winextras.h"
#elif defined(Q_OS_UNIX)
#include "x11extras.h"
#endif
static const QString RUNATSTARTUPREGKEY(
"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run");
static const QString RUNATSTARTUPLOCATION(
QString("%0\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\antimicro.lnk")
.arg(QString::fromUtf8(qgetenv("AppData"))));
MainSettingsDialog::MainSettingsDialog(AntiMicroSettings *settings,
QList<InputDevice *> *devices,
QWidget *parent) :
QDialog(parent, Qt::Dialog),
ui(new Ui::MainSettingsDialog)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
ui->profileOpenDirPushButton->setIcon(QIcon::fromTheme("document-open-folder",
QIcon(":/icons/16x16/actions/document-open-folder.png")));
ui->logFilePushButton->setIcon(QIcon::fromTheme("document-open-folder",
QIcon(":/icons/16x16/actions/document-open-folder.png")));
this->settings = settings;
this->allDefaultProfile = 0;
this->connectedDevices = devices;
#ifdef USE_SDL_2
fillControllerMappingsTable();
#endif
settings->getLock()->lock();
QString defaultProfileDir = settings->value("DefaultProfileDir", "").toString();
int numberRecentProfiles = settings->value("NumberRecentProfiles", 5).toInt();
bool closeToTray = settings->value("CloseToTray", false).toBool();
if (!defaultProfileDir.isEmpty() && QDir(defaultProfileDir).exists())
{
ui->profileDefaultDirLineEdit->setText(defaultProfileDir);
}
else
{
ui->profileDefaultDirLineEdit->setText(PadderCommon::preferredProfileDir(settings));
}
ui->numberRecentProfileSpinBox->setValue(numberRecentProfiles);
if (closeToTray)
{
ui->closeToTrayCheckBox->setChecked(true);
}
changePresetLanguage();
#ifdef Q_OS_WIN
ui->autoProfileTableWidget->hideColumn(3);
#endif
ui->autoProfileTableWidget->hideColumn(7);
#ifdef Q_OS_UNIX
#if defined(USE_SDL_2) && defined(WITH_X11)
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
populateAutoProfiles();
fillAllAutoProfilesTable();
fillGUIDComboBox();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
else
{
delete ui->categoriesListWidget->item(2);
ui->stackedWidget->removeWidget(ui->page_2);
}
#endif
#elif defined(USE_SDL_2) && !defined(WITH_X11)
delete ui->categoriesListWidget->item(2);
ui->stackedWidget->removeWidget(ui->page_2);
#elif !defined(USE_SDL_2)
delete ui->categoriesListWidget->item(2);
delete ui->categoriesListWidget->item(1);
ui->stackedWidget->removeWidget(ui->controllerMappingsPage);
ui->stackedWidget->removeWidget(ui->page_2);
#endif
#else
populateAutoProfiles();
fillAllAutoProfilesTable();
fillGUIDComboBox();
#endif
QString autoProfileActive = settings->value("AutoProfiles/AutoProfilesActive", "").toString();
if (autoProfileActive == "1")
{
ui->activeCheckBox->setChecked(true);
ui->autoProfileTableWidget->setEnabled(true);
ui->autoProfileAddPushButton->setEnabled(true);
}
#ifdef Q_OS_WIN
BaseEventHandler *handler = EventHandlerFactory::getInstance()->handler();
if (QSysInfo::windowsVersion() >= QSysInfo::WV_VISTA)
{
// Handle Windows Vista and later
QFile tempFile(RUNATSTARTUPLOCATION);
if (tempFile.exists())
{
ui->launchAtWinStartupCheckBox->setChecked(true);
}
}
else
{
// Handle Windows XP
QSettings autoRunReg(RUNATSTARTUPREGKEY, QSettings::NativeFormat);
QString autoRunEntry = autoRunReg.value("antimicro", "").toString();
if (!autoRunEntry.isEmpty())
{
ui->launchAtWinStartupCheckBox->setChecked(true);
}
}
if (handler && handler->getIdentifier() == "sendinput")
{
bool keyRepeatEnabled = settings->value("KeyRepeat/KeyRepeatEnabled", true).toBool();
if (keyRepeatEnabled)
{
ui->keyRepeatEnableCheckBox->setChecked(true);
ui->keyDelayHorizontalSlider->setEnabled(true);
ui->keyDelaySpinBox->setEnabled(true);
ui->keyRateHorizontalSlider->setEnabled(true);
ui->keyRateSpinBox->setEnabled(true);
}
int keyRepeatDelay = settings->value("KeyRepeat/KeyRepeatDelay", InputDevice::DEFAULTKEYREPEATDELAY).toInt();
int keyRepeatRate = settings->value("KeyRepeat/KeyRepeatRate", InputDevice::DEFAULTKEYREPEATRATE).toInt();
ui->keyDelayHorizontalSlider->setValue(keyRepeatDelay);
ui->keyDelaySpinBox->setValue(keyRepeatDelay);
ui->keyRateHorizontalSlider->setValue(1000/keyRepeatRate);
ui->keyRateSpinBox->setValue(1000/keyRepeatRate);
}
else
{
//ui->launchAtWinStartupCheckBox->setVisible(false);
ui->keyRepeatGroupBox->setVisible(false);
}
#else
ui->launchAtWinStartupCheckBox->setVisible(false);
ui->keyRepeatGroupBox->setVisible(false);
#endif
bool useSingleProfileList = settings->value("TrayProfileList", false).toBool();
if (useSingleProfileList)
{
ui->traySingleProfileListCheckBox->setChecked(true);
}
bool minimizeToTaskBar = settings->value("MinimizeToTaskbar", false).toBool();
if (minimizeToTaskBar)
{
ui->minimizeTaskbarCheckBox->setChecked(true);
}
bool hideEmpty = settings->value("HideEmptyButtons", false).toBool();
if (hideEmpty)
{
ui->hideEmptyCheckBox->setChecked(true);
}
bool autoOpenLastProfile = settings->value("AutoOpenLastProfile", true).toBool();
if (autoOpenLastProfile)
{
ui->autoLoadPreviousCheckBox->setChecked(true);
}
else
{
ui->autoLoadPreviousCheckBox->setChecked(false);
}
bool launchInTray = settings->value("LaunchInTray", false).toBool();
if (launchInTray)
{
ui->launchInTrayCheckBox->setChecked(true);
}
#ifdef Q_OS_WIN
bool associateProfiles = settings->value("AssociateProfiles", true).toBool();
if (associateProfiles)
{
ui->associateProfilesCheckBox->setChecked(true);
}
else
{
ui->associateProfilesCheckBox->setChecked(false);
}
#else
ui->associateProfilesCheckBox->setVisible(false);
#endif
#ifdef Q_OS_WIN
bool disableEnhancedMouse = settings->value("Mouse/DisableWinEnhancedPointer", false).toBool();
if (disableEnhancedMouse)
{
ui->disableWindowsEnhancedPointCheckBox->setChecked(true);
}
#else
ui->disableWindowsEnhancedPointCheckBox->setVisible(false);
#endif
bool smoothingEnabled = settings->value("Mouse/Smoothing", false).toBool();
if (smoothingEnabled)
{
ui->smoothingEnableCheckBox->setChecked(true);
ui->historySizeSpinBox->setEnabled(true);
ui->weightModifierDoubleSpinBox->setEnabled(true);
}
int historySize = settings->value("Mouse/HistorySize", 0).toInt();
if (historySize > 0 && historySize <= JoyButton::MAXIMUMMOUSEHISTORYSIZE)
{
ui->historySizeSpinBox->setValue(historySize);
}
double weightModifier = settings->value("Mouse/WeightModifier", 0).toDouble();
if (weightModifier > 0.0 && weightModifier <= JoyButton::MAXIMUMWEIGHTMODIFIER)
{
ui->weightModifierDoubleSpinBox->setValue(weightModifier);
}
for (int i = 1; i <= JoyButton::MAXIMUMMOUSEREFRESHRATE; i++)
{
ui->mouseRefreshRateComboBox->addItem(QString("%1 ms").arg(i), i);
}
int refreshIndex = ui->mouseRefreshRateComboBox->findData(JoyButton::getMouseRefreshRate());
if (refreshIndex >= 0)
{
ui->mouseRefreshRateComboBox->setCurrentIndex(refreshIndex);
}
#ifdef Q_OS_WIN
QString tempTooltip = ui->mouseRefreshRateComboBox->toolTip();
tempTooltip.append("\n\n");
tempTooltip.append(tr("Also, Windows users who want to use a low value should also check the\n"
"\"Disable Enhance Pointer Precision\" checkbox if you haven't disabled\n"
"the option in Windows."));
ui->mouseRefreshRateComboBox->setToolTip(tempTooltip);
#endif
fillSpringScreenPresets();
for (int i=1; i <= 16; i++)
{
ui->gamepadPollRateComboBox->addItem(QString("%1 ms").arg(i), QVariant(i));
}
int gamepadPollIndex = ui->gamepadPollRateComboBox->findData(JoyButton::getGamepadRefreshRate());
if (gamepadPollIndex >= 0)
{
ui->gamepadPollRateComboBox->setCurrentIndex(gamepadPollIndex);
}
#ifdef Q_OS_UNIX
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
refreshExtraMouseInfo();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
else
{
ui->extraInfoFrame->hide();
}
#endif
#else
ui->extraInfoFrame->hide();
#endif
// Begin Advanced Tab
QString curLogFile = settings->value("LogFile", "").toString();
int logLevel = settings->value("LogLevel", Logger::LOG_NONE).toInt();
if( !curLogFile.isEmpty() ) {
ui->logFilePathEdit->setText(curLogFile);
}
ui->logLevelComboBox->setCurrentIndex( logLevel );
// End Advanced Tab
settings->getLock()->unlock();
connect(ui->categoriesListWidget, SIGNAL(currentRowChanged(int)), ui->stackedWidget, SLOT(setCurrentIndex(int)));
connect(ui->controllerMappingsTableWidget, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(mappingsTableItemChanged(QTableWidgetItem*)));
connect(ui->mappingDeletePushButton, SIGNAL(clicked()), this, SLOT(deleteMappingRow()));
connect(ui->mappngInsertPushButton, SIGNAL(clicked()), this, SLOT(insertMappingRow()));
//connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(syncMappingSettings()));
connect(this, SIGNAL(accepted()), this, SLOT(saveNewSettings()));
connect(ui->profileOpenDirPushButton, SIGNAL(clicked()), this, SLOT(selectDefaultProfileDir()));
connect(ui->activeCheckBox, SIGNAL(toggled(bool)), ui->autoProfileTableWidget, SLOT(setEnabled(bool)));
connect(ui->activeCheckBox, SIGNAL(toggled(bool)), this, SLOT(autoProfileButtonsActiveState(bool)));
//connect(ui->activeCheckBox, SIGNAL(toggled(bool)), ui->devicesComboBox, SLOT(setEnabled(bool)));
connect(ui->devicesComboBox, SIGNAL(activated(int)), this, SLOT(changeDeviceForProfileTable(int)));
connect(ui->autoProfileTableWidget, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(processAutoProfileActiveClick(QTableWidgetItem*)));
connect(ui->autoProfileAddPushButton, SIGNAL(clicked()), this, SLOT(openAddAutoProfileDialog()));
connect(ui->autoProfileDeletePushButton, SIGNAL(clicked()), this, SLOT(openDeleteAutoProfileConfirmDialog()));
connect(ui->autoProfileEditPushButton, SIGNAL(clicked()), this, SLOT(openEditAutoProfileDialog()));
connect(ui->autoProfileTableWidget, SIGNAL(itemSelectionChanged()), this, SLOT(changeAutoProfileButtonsState()));
connect(ui->keyRepeatEnableCheckBox, SIGNAL(clicked(bool)), this, SLOT(changeKeyRepeatWidgetsStatus(bool)));
connect(ui->keyDelayHorizontalSlider, SIGNAL(valueChanged(int)), ui->keyDelaySpinBox, SLOT(setValue(int)));
connect(ui->keyDelaySpinBox, SIGNAL(valueChanged(int)), ui->keyDelayHorizontalSlider, SLOT(setValue(int)));
connect(ui->keyRateHorizontalSlider, SIGNAL(valueChanged(int)), ui->keyRateSpinBox, SLOT(setValue(int)));
connect(ui->keyRateSpinBox, SIGNAL(valueChanged(int)), ui->keyRateHorizontalSlider, SLOT(setValue(int)));
connect(ui->smoothingEnableCheckBox, SIGNAL(toggled(bool)), this, SLOT(checkSmoothingWidgetStatus(bool)));
connect(ui->resetAccelPushButton, SIGNAL(clicked(bool)), this, SLOT(resetMouseAcceleration()));
// Advanced Tab
connect(ui->logFilePushButton, SIGNAL(clicked()), this, SLOT(selectLogFile()));
}
MainSettingsDialog::~MainSettingsDialog()
{
delete ui;
if (connectedDevices)
{
delete connectedDevices;
connectedDevices = 0;
}
}
void MainSettingsDialog::fillControllerMappingsTable()
{
/*QList<QVariant> tempvariant = bindingValues(bind);
QTableWidgetItem* item = new QTableWidgetItem();
ui->buttonMappingTableWidget->setItem(associatedRow, 0, item);
item->setText(temptext);
item->setData(Qt::UserRole, tempvariant);
*/
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
ui->controllerMappingsTableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
#else
ui->controllerMappingsTableWidget->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
#endif
QHash<QString, QList<QVariant> > tempHash;
settings->getLock()->lock();
settings->beginGroup("Mappings");
QStringList mappings = settings->allKeys();
QStringListIterator iter(mappings);
while (iter.hasNext())
{
QString tempkey = iter.next();
QString tempGUID;
if (tempkey.contains("Disable"))
{
bool disableGameController = settings->value(tempkey, false).toBool();
tempGUID = tempkey.remove("Disable");
insertTempControllerMapping(tempHash, tempGUID);
if (tempHash.contains(tempGUID))
{
QList<QVariant> templist = tempHash.value(tempGUID);
templist.replace(2, QVariant(disableGameController));
tempHash.insert(tempGUID, templist); // Overwrite original list
}
}
else
{
QString mappingString = settings->value(tempkey, QString()).toString();
if (!mappingString.isEmpty())
{
tempGUID = tempkey;
insertTempControllerMapping(tempHash, tempGUID);
if (tempHash.contains(tempGUID))
{
QList<QVariant> templist = tempHash.value(tempGUID);
templist.replace(1, mappingString);
tempHash.insert(tempGUID, templist); // Overwrite original list
}
}
}
}
settings->endGroup();
settings->getLock()->unlock();
QHashIterator<QString, QList<QVariant> > iter2(tempHash);
int i = 0;
while (iter2.hasNext())
{
ui->controllerMappingsTableWidget->insertRow(i);
QList<QVariant> templist = iter2.next().value();
QTableWidgetItem* item = new QTableWidgetItem(templist.at(0).toString());
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, iter2.key());
item->setToolTip(templist.at(0).toString());
ui->controllerMappingsTableWidget->setItem(i, 0, item);
item = new QTableWidgetItem(templist.at(1).toString());
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, iter2.key());
//item->setToolTip(templist.at(1).toString());
ui->controllerMappingsTableWidget->setItem(i, 1, item);
bool disableController = templist.at(2).toBool();
item = new QTableWidgetItem();
item->setCheckState(disableController ? Qt::Checked : Qt::Unchecked);
item->setData(Qt::UserRole, iter2.key());
ui->controllerMappingsTableWidget->setItem(i, 2, item);
i++;
}
}
void MainSettingsDialog::insertTempControllerMapping(QHash<QString, QList<QVariant> > &hash, QString newGUID)
{
if (!newGUID.isEmpty() && !hash.contains(newGUID))
{
QList<QVariant> templist;
templist.append(QVariant(newGUID));
templist.append(QVariant(""));
templist.append(QVariant(false));
hash.insert(newGUID, templist);
}
}
void MainSettingsDialog::mappingsTableItemChanged(QTableWidgetItem *item)
{
int column = item->column();
int row = item->row();
if (column == 0 && !item->text().isEmpty())
{
QTableWidgetItem *disableitem = ui->controllerMappingsTableWidget->item(row, column);
if (disableitem)
{
disableitem->setData(Qt::UserRole, item->text());
}
item->setData(Qt::UserRole, item->text());
}
}
void MainSettingsDialog::insertMappingRow()
{
int insertRowIndex = ui->controllerMappingsTableWidget->rowCount();
ui->controllerMappingsTableWidget->insertRow(insertRowIndex);
QTableWidgetItem* item = new QTableWidgetItem();
//item->setFlags(item->flags() & ~Qt::ItemIsEditable);
//item->setData(Qt::UserRole, iter2.key());
ui->controllerMappingsTableWidget->setItem(insertRowIndex, 0, item);
item = new QTableWidgetItem();
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
//item->setData(Qt::UserRole, iter2.key());
ui->controllerMappingsTableWidget->setItem(insertRowIndex, 1, item);
item = new QTableWidgetItem();
item->setCheckState(Qt::Unchecked);
ui->controllerMappingsTableWidget->setItem(insertRowIndex, 2, item);
}
void MainSettingsDialog::deleteMappingRow()
{
int row = ui->controllerMappingsTableWidget->currentRow();
if (row >= 0)
{
ui->controllerMappingsTableWidget->removeRow(row);
}
}
void MainSettingsDialog::syncMappingSettings()
{
settings->getLock()->lock();
settings->beginGroup("Mappings");
settings->remove("");
for (int i=0; i < ui->controllerMappingsTableWidget->rowCount(); i++)
{
QTableWidgetItem *itemGUID = ui->controllerMappingsTableWidget->item(i, 0);
QTableWidgetItem *itemMapping = ui->controllerMappingsTableWidget->item(i, 1);
QTableWidgetItem *itemDisable = ui->controllerMappingsTableWidget->item(i, 2);
if (itemGUID && !itemGUID->text().isEmpty() && itemDisable)
{
QString disableController = itemDisable->checkState() == Qt::Checked ? "1" : "0";
if (itemMapping && !itemMapping->text().isEmpty())
{
settings->setValue(itemGUID->text(), itemMapping->text());
}
settings->setValue(QString("%1Disable").arg(itemGUID->text()), disableController);
}
}
settings->endGroup();
settings->getLock()->unlock();
}
void MainSettingsDialog::saveNewSettings()
{
#if defined(USE_SDL_2)
syncMappingSettings();
#endif
settings->getLock()->lock();
QString oldProfileDir = settings->value("DefaultProfileDir", "").toString();
QString possibleProfileDir = ui->profileDefaultDirLineEdit->text();
bool closeToTray = ui->closeToTrayCheckBox->isChecked();
if (oldProfileDir != possibleProfileDir)
{
if (QFileInfo(possibleProfileDir).exists())
{
settings->setValue("DefaultProfileDir", possibleProfileDir);
}
else if (possibleProfileDir.isEmpty())
{
settings->remove("DefaultProfileDir");
}
}
int numRecentProfiles = ui->numberRecentProfileSpinBox->value();
settings->setValue("NumberRecentProfiles", numRecentProfiles);
if (closeToTray)
{
settings->setValue("CloseToTray", closeToTray ? "1" : "0");
}
else
{
settings->remove("CloseToTray");
}
settings->getLock()->unlock();
checkLocaleChange();
#ifdef Q_OS_UNIX
#if defined(USE_SDL_2) && defined(WITH_X11)
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
saveAutoProfileSettings();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
#endif
#endif
#else
saveAutoProfileSettings();
#endif
settings->getLock()->lock();
#ifdef Q_OS_WIN
if (QSysInfo::windowsVersion() >= QSysInfo::WV_VISTA)
{
// Handle Windows Vista and later
QFile tempFile(RUNATSTARTUPLOCATION);
if (ui->launchAtWinStartupCheckBox->isChecked() && !tempFile.exists())
{
if (tempFile.open(QFile::WriteOnly))
{
QFile currentAppLocation(qApp->applicationFilePath());
currentAppLocation.link(QFileInfo(tempFile).absoluteFilePath());
}
}
else if (tempFile.exists() && QFileInfo(tempFile).isWritable())
{
tempFile.remove();
}
}
else
{
// Handle Windows XP
QSettings autoRunReg(RUNATSTARTUPREGKEY, QSettings::NativeFormat);
QString autoRunEntry = autoRunReg.value("antimicro", "").toString();
if (ui->launchAtWinStartupCheckBox->isChecked())
{
QString nativeFilePath = QDir::toNativeSeparators(qApp->applicationFilePath());
autoRunReg.setValue("antimicro", nativeFilePath);
}
else if (!autoRunEntry.isEmpty())
{
autoRunReg.remove("antimicro");
}
}
BaseEventHandler *handler = EventHandlerFactory::getInstance()->handler();
if (handler && handler->getIdentifier() == "sendinput")
{
settings->setValue("KeyRepeat/KeyRepeatEnabled", ui->keyRepeatEnableCheckBox->isChecked() ? "1" : "0");
settings->setValue("KeyRepeat/KeyRepeatDelay", ui->keyDelaySpinBox->value());
settings->setValue("KeyRepeat/KeyRepeatRate", 1000/ui->keyRateSpinBox->value());
}
#endif
if (ui->traySingleProfileListCheckBox->isChecked())
{
settings->setValue("TrayProfileList", "1");
}
else
{
settings->setValue("TrayProfileList", "0");
}
bool minimizeToTaskbar = ui->minimizeTaskbarCheckBox->isChecked();
settings->setValue("MinimizeToTaskbar", minimizeToTaskbar ? "1" : "0");
bool hideEmpty = ui->hideEmptyCheckBox->isChecked();
settings->setValue("HideEmptyButtons", hideEmpty ? "1" : "0");
bool autoOpenLastProfile = ui->autoLoadPreviousCheckBox->isChecked();
settings->setValue("AutoOpenLastProfile", autoOpenLastProfile ? "1" : "0");
bool launchInTray = ui->launchInTrayCheckBox->isChecked();
settings->setValue("LaunchInTray", launchInTray ? "1" : "0");
#ifdef Q_OS_WIN
bool associateProfiles = ui->associateProfilesCheckBox->isChecked();
settings->setValue("AssociateProfiles", associateProfiles ? "1" : "0");
bool associationExists = WinExtras::containsFileAssociationinRegistry();
if (associateProfiles && !associationExists)
{
WinExtras::writeFileAssocationToRegistry();
}
else if (!associateProfiles && associationExists)
{
WinExtras::removeFileAssociationFromRegistry();
}
bool disableEnhancePoint = ui->disableWindowsEnhancedPointCheckBox->isChecked();
bool oldEnhancedValue = settings->value("Mouse/DisableWinEnhancedPointer", false).toBool();
bool usingEnhancedPointer = WinExtras::isUsingEnhancedPointerPrecision();
settings->setValue("Mouse/DisableWinEnhancedPointer", disableEnhancePoint ? "1" : "0");
if (disableEnhancePoint != oldEnhancedValue)
{
if (usingEnhancedPointer && disableEnhancePoint)
{
WinExtras::disablePointerPrecision();
}
else if (!usingEnhancedPointer && !disableEnhancePoint)
{
WinExtras::enablePointerPrecision();
}
}
#endif
PadderCommon::lockInputDevices();
if (connectedDevices->size() > 0)
{
InputDevice *tempDevice = connectedDevices->at(0);
QMetaObject::invokeMethod(tempDevice, "haltServices", Qt::BlockingQueuedConnection);
}
bool smoothingEnabled = ui->smoothingEnableCheckBox->isChecked();
int historySize = ui->historySizeSpinBox->value();
double weightModifier = ui->weightModifierDoubleSpinBox->value();
settings->setValue("Mouse/Smoothing", smoothingEnabled ? "1" : "0");
if (smoothingEnabled)
{
if (historySize > 0)
{
JoyButton::setMouseHistorySize(historySize);
}
if (weightModifier)
{
JoyButton::setWeightModifier(weightModifier);
}
}
else
{
JoyButton::setMouseHistorySize(1);
JoyButton::setWeightModifier(0.0);
}
if (historySize > 0)
{
settings->setValue("Mouse/HistorySize", historySize);
}
if (weightModifier > 0.0)
{
settings->setValue("Mouse/WeightModifier", weightModifier);
}
int refreshIndex = ui->mouseRefreshRateComboBox->currentIndex();
int mouseRefreshRate = ui->mouseRefreshRateComboBox->itemData(refreshIndex).toInt();
if (mouseRefreshRate != JoyButton::getMouseRefreshRate())
{
settings->setValue("Mouse/RefreshRate", mouseRefreshRate);
JoyButton::setMouseRefreshRate(mouseRefreshRate);
}
int springIndex = ui->springScreenComboBox->currentIndex();
int springScreen = ui->springScreenComboBox->itemData(springIndex).toInt();
JoyButton::setSpringModeScreen(springScreen);
settings->setValue("Mouse/SpringScreen", QString::number(springScreen));
int pollIndex = ui->gamepadPollRateComboBox->currentIndex();
unsigned int gamepadPollRate = ui->gamepadPollRateComboBox->itemData(pollIndex).toUInt();
if (gamepadPollRate != JoyButton::getGamepadRefreshRate())
{
JoyButton::setGamepadRefreshRate(gamepadPollRate);
settings->setValue("GamepadPollRate", QString::number(gamepadPollRate));
}
// Advanced Tab
settings->setValue("LogFile", ui->logFilePathEdit->text());
int logLevel = ui->logLevelComboBox->currentIndex();
if( logLevel < 0 ) {
logLevel = 0;
}
if( Logger::LOG_MAX < logLevel ) {
logLevel = Logger::LOG_MAX;
}
settings->setValue("LogLevel", logLevel);
// End Advanced Tab
PadderCommon::unlockInputDevices();
settings->sync();
settings->getLock()->unlock();
}
void MainSettingsDialog::selectDefaultProfileDir()
{
QString lookupDir = PadderCommon::preferredProfileDir(settings);
QString directory = QFileDialog::getExistingDirectory(this, tr("Select Default Profile Directory"), lookupDir);
if (!directory.isEmpty() && QFileInfo(directory).exists())
{
ui->profileDefaultDirLineEdit->setText(directory);
}
}
void MainSettingsDialog::checkLocaleChange()
{
settings->getLock()->lock();
int row = ui->localeListWidget->currentRow();
if (row == 0)
{
if (settings->contains("Language"))
{
settings->remove("Language");
}
settings->getLock()->unlock();
emit changeLanguage(QLocale::system().name());
}
else
{
QString newLocale = "en";
if (row == 1)
{
newLocale = "br";
}
else if (row == 2)
{
newLocale = "en";
}
else if (row == 3)
{
newLocale = "fr";
}
else if (row == 4)
{
newLocale = "de";
}
else if (row == 5)
{
newLocale = "it";
}
else if (row == 6)
{
newLocale = "ja";
}
else if (row == 7)
{
newLocale = "ru";
}
else if (row == 8)
{
newLocale = "sr";
}
else if (row == 9)
{
newLocale = "zh_CN";
}
else if (row == 10)
{
newLocale = "es";
}
else if (row == 11)
{
newLocale = "uk";
}
settings->setValue("Language", newLocale);
settings->getLock()->unlock();
emit changeLanguage(newLocale);
}
}
void MainSettingsDialog::populateAutoProfiles()
{
exeAutoProfiles.clear();
defaultAutoProfiles.clear();
settings->beginGroup("DefaultAutoProfiles");
QStringList registeredGUIDs = settings->value("GUIDs", QStringList()).toStringList();
//QStringList defaultkeys = settings->allKeys();
settings->endGroup();
QString allProfile = settings->value(QString("DefaultAutoProfileAll/Profile"), "").toString();
QString allActive = settings->value(QString("DefaultAutoProfileAll/Active"), "0").toString();
bool defaultActive = allActive == "1" ? true : false;
allDefaultProfile = new AutoProfileInfo("all", allProfile, defaultActive, this);
allDefaultProfile->setDefaultState(true);
QStringListIterator iter(registeredGUIDs);
while (iter.hasNext())
{
QString tempkey = iter.next();
QString guid = tempkey;
//QString guid = QString(tempkey).replace("GUID", "");
QString profile = settings->value(QString("DefaultAutoProfile-%1/Profile").arg(guid), "").toString();
QString active = settings->value(QString("DefaultAutoProfile-%1/Active").arg(guid), "0").toString();
QString deviceName = settings->value(QString("DefaultAutoProfile-%1/DeviceName").arg(guid), "").toString();
if (!guid.isEmpty() && !profile.isEmpty() && !deviceName.isEmpty())
{
bool profileActive = active == "1" ? true : false;
if (!defaultAutoProfiles.contains(guid) && guid != "all")
{
AutoProfileInfo *info = new AutoProfileInfo(guid, profile, profileActive, this);
info->setDefaultState(true);
info->setDeviceName(deviceName);
defaultAutoProfiles.insert(guid, info);
defaultList.append(info);
QList<AutoProfileInfo*> templist;
templist.append(info);
deviceAutoProfiles.insert(guid, templist);
}
}
}
settings->beginGroup("AutoProfiles");
bool quitSearch = false;
//QHash<QString, QList<QString> > tempAssociation;
for (int i = 1; !quitSearch; i++)
{
QString exe = settings->value(QString("AutoProfile%1Exe").arg(i), "").toString();
QString windowName = settings->value(QString("AutoProfile%1WindowName").arg(i), "").toString();
#ifdef Q_OS_UNIX
QString windowClass = settings->value(QString("AutoProfile%1WindowClass").arg(i), "").toString();
#else
QString windowClass;
#endif
QString guid = settings->value(QString("AutoProfile%1GUID").arg(i), "").toString();
QString profile = settings->value(QString("AutoProfile%1Profile").arg(i), "").toString();
QString active = settings->value(QString("AutoProfile%1Active").arg(i), 0).toString();
QString deviceName = settings->value(QString("AutoProfile%1DeviceName").arg(i), "").toString();
// Check if all required elements exist. If not, assume that the end of the
// list has been reached.
if ((!exe.isEmpty() || !windowClass.isEmpty() || !windowName.isEmpty()) &&
!guid.isEmpty())
{
bool profileActive = active == "1" ? true : false;
AutoProfileInfo *info = new AutoProfileInfo(guid, profile, exe, profileActive, this);
if (!deviceName.isEmpty())
{
info->setDeviceName(deviceName);
}
info->setWindowName(windowName);
#ifdef Q_OS_UNIX
info->setWindowClass(windowClass);
#endif
profileList.append(info);
QList<AutoProfileInfo*> templist;
if (guid != "all")
{
if (deviceAutoProfiles.contains(guid))
{
templist = deviceAutoProfiles.value(guid);
}
templist.append(info);
deviceAutoProfiles.insert(guid, templist);
}
}
/*if (!exe.isEmpty() && !guid.isEmpty())
{
bool profileActive = active == "1" ? true : false;
QList<AutoProfileInfo*> templist;
if (exeAutoProfiles.contains(exe))
{
templist = exeAutoProfiles.value(exe);
}
QList<QString> tempguids;
if (tempAssociation.contains(exe))
{
tempguids = tempAssociation.value(exe);
}
if (!tempguids.contains(guid))
{
AutoProfileInfo *info = new AutoProfileInfo(guid, profile, exe, profileActive, this);
if (!deviceName.isEmpty())
{
info->setDeviceName(deviceName);
}
tempguids.append(guid);
tempAssociation.insert(exe, tempguids);
templist.append(info);
exeAutoProfiles.insert(exe, templist);
profileList.append(info);
QList<AutoProfileInfo*> templist;
if (guid != "all")
{
if (deviceAutoProfiles.contains(guid))
{
templist = deviceAutoProfiles.value(guid);
}
templist.append(info);
deviceAutoProfiles.insert(guid, templist);
}
}
}
*/
else
{
quitSearch = true;
}
}
settings->endGroup();
}
void MainSettingsDialog::fillAutoProfilesTable(QString guid)
{
//ui->autoProfileTableWidget->clear();
for (int i = ui->autoProfileTableWidget->rowCount()-1; i >= 0; i--)
{
ui->autoProfileTableWidget->removeRow(i);
}
//QStringList tableHeader;
//tableHeader << tr("Active") << tr("GUID") << tr("Profile") << tr("Application") << tr("Default?")
// << tr("Instance");
//ui->autoProfileTableWidget->setHorizontalHeaderLabels(tableHeader);
//ui->autoProfileTableWidget->horizontalHeader()->setVisible(true);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
ui->autoProfileTableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
#else
ui->autoProfileTableWidget->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
#endif
if (defaultAutoProfiles.contains(guid) ||
deviceAutoProfiles.contains(guid))
{
int i = 0;
AutoProfileInfo *defaultForGUID = 0;
if (defaultAutoProfiles.contains(guid))
{
AutoProfileInfo *info = defaultAutoProfiles.value(guid);
defaultForGUID = info;
ui->autoProfileTableWidget->insertRow(i);
QTableWidgetItem *item = new QTableWidgetItem();
item->setCheckState(info->isActive() ? Qt::Checked : Qt::Unchecked);
ui->autoProfileTableWidget->setItem(i, 0, item);
QString deviceName = info->getDeviceName();
QString guidDisplay = info->getGUID();
if (!deviceName.isEmpty())
{
guidDisplay = QString("%1 ").arg(info->getDeviceName());
guidDisplay.append(QString("(%1)").arg(info->getGUID()));
}
item = new QTableWidgetItem(guidDisplay);
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, info->getGUID());
item->setToolTip(info->getGUID());
ui->autoProfileTableWidget->setItem(i, 1, item);
QFileInfo profilePath(info->getProfileLocation());
item = new QTableWidgetItem(profilePath.fileName());
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, info->getProfileLocation());
item->setToolTip(info->getProfileLocation());
ui->autoProfileTableWidget->setItem(i, 2, item);
item = new QTableWidgetItem(info->getWindowClass());
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, info->getWindowClass());
item->setToolTip(info->getWindowClass());
ui->autoProfileTableWidget->setItem(i, 3, item);
item = new QTableWidgetItem(info->getWindowName());
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, info->getWindowName());
item->setToolTip(info->getWindowName());
ui->autoProfileTableWidget->setItem(i, 4, item);
QFileInfo exeInfo(info->getExe());
item = new QTableWidgetItem(exeInfo.fileName());
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, info->getExe());
item->setToolTip(info->getExe());
ui->autoProfileTableWidget->setItem(i, 5, item);
item = new QTableWidgetItem("Default");
item->setData(Qt::UserRole, "default");
ui->autoProfileTableWidget->setItem(i, 6, item);
item = new QTableWidgetItem("Instance");
item->setData(Qt::UserRole, QVariant::fromValue<AutoProfileInfo*>(info));
ui->autoProfileTableWidget->setItem(i, 7, item);
i++;
}
QListIterator<AutoProfileInfo*> iter(deviceAutoProfiles.value(guid));
while (iter.hasNext())
{
AutoProfileInfo *info = iter.next();
if (!defaultForGUID || info != defaultForGUID)
{
ui->autoProfileTableWidget->insertRow(i);
QTableWidgetItem *item = new QTableWidgetItem();
item->setCheckState(info->isActive() ? Qt::Checked : Qt::Unchecked);
ui->autoProfileTableWidget->setItem(i, 0, item);
QString deviceName = info->getDeviceName();
QString guidDisplay = info->getGUID();
if (!deviceName.isEmpty())
{
guidDisplay = QString("%1 ").arg(info->getDeviceName());
guidDisplay.append(QString("(%1)").arg(info->getGUID()));
}
item = new QTableWidgetItem(guidDisplay);
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, info->getGUID());
item->setToolTip(info->getGUID());
ui->autoProfileTableWidget->setItem(i, 1, item);
QFileInfo profilePath(info->getProfileLocation());
item = new QTableWidgetItem(profilePath.fileName());
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, info->getProfileLocation());
item->setToolTip(info->getProfileLocation());
ui->autoProfileTableWidget->setItem(i, 2, item);
item = new QTableWidgetItem(info->getWindowClass());
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, info->getWindowClass());
item->setToolTip(info->getWindowClass());
ui->autoProfileTableWidget->setItem(i, 3, item);
item = new QTableWidgetItem(info->getWindowName());
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, info->getWindowName());
item->setToolTip(info->getWindowName());
ui->autoProfileTableWidget->setItem(i, 4, item);
QFileInfo exeInfo(info->getExe());
item = new QTableWidgetItem(exeInfo.fileName());
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, info->getExe());
item->setToolTip(info->getExe());
ui->autoProfileTableWidget->setItem(i, 5, item);
item = new QTableWidgetItem("Instance");
item->setData(Qt::UserRole, QVariant::fromValue<AutoProfileInfo*>(info));
ui->autoProfileTableWidget->setItem(i, 7, item);
i++;
}
}
}
}
void MainSettingsDialog::clearAutoProfileData()
{
}
void MainSettingsDialog::fillGUIDComboBox()
{
ui->devicesComboBox->clear();
ui->devicesComboBox->addItem(tr("All"), QVariant("all"));
QList<QString> guids = deviceAutoProfiles.keys();
QListIterator<QString> iter(guids);
while (iter.hasNext())
{
QString guid = iter.next();
QList<AutoProfileInfo*> temp = deviceAutoProfiles.value(guid);
if (temp.count() > 0)
{
QString deviceName = temp.first()->getDeviceName();
if (!deviceName.isEmpty())
{
ui->devicesComboBox->addItem(deviceName, QVariant(guid));
}
else
{
ui->devicesComboBox->addItem(guid, QVariant(guid));
}
}
else
{
ui->devicesComboBox->addItem(guid, QVariant(guid));
}
}
}
void MainSettingsDialog::changeDeviceForProfileTable(int index)
{
disconnect(ui->autoProfileTableWidget, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(processAutoProfileActiveClick(QTableWidgetItem*)));
if (index == 0)
{
fillAllAutoProfilesTable();
}
else
{
QString guid = ui->devicesComboBox->itemData(index).toString();
fillAutoProfilesTable(guid);
}
connect(ui->autoProfileTableWidget, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(processAutoProfileActiveClick(QTableWidgetItem*)));
}
void MainSettingsDialog::saveAutoProfileSettings()
{
settings->getLock()->lock();
settings->beginGroup("DefaultAutoProfiles");
QStringList defaultkeys = settings->allKeys();
settings->endGroup();
QStringListIterator iterDefaults(defaultkeys);
while (iterDefaults.hasNext())
{
QString tempkey = iterDefaults.next();
QString guid = QString(tempkey).replace("GUID", "");
QString testkey = QString("DefaultAutoProfile-%1").arg(guid);
settings->beginGroup(testkey);
settings->remove("");
settings->endGroup();
}
settings->beginGroup("DefaultAutoProfiles");
settings->remove("");
settings->endGroup();
settings->beginGroup("DefaultAutoProfileAll");
settings->remove("");
settings->endGroup();
settings->beginGroup("AutoProfiles");
settings->remove("");
settings->endGroup();
if (allDefaultProfile)
{
QString profile = allDefaultProfile->getProfileLocation();
QString defaultActive = allDefaultProfile->isActive() ? "1" : "0";
settings->setValue(QString("DefaultAutoProfileAll/Profile"), profile);
settings->setValue(QString("DefaultAutoProfileAll/Active"), defaultActive);
}
QMapIterator<QString, AutoProfileInfo*> iter(defaultAutoProfiles);
QStringList registeredGUIDs;
while (iter.hasNext())
{
iter.next();
QString guid = iter.key();
registeredGUIDs.append(guid);
AutoProfileInfo *info = iter.value();
QString profileActive = info->isActive() ? "1" : "0";
QString deviceName = info->getDeviceName();
//settings->setValue(QString("DefaultAutoProfiles/GUID%1").arg(guid), guid);
settings->setValue(QString("DefaultAutoProfile-%1/Profile").arg(guid), info->getProfileLocation());
settings->setValue(QString("DefaultAutoProfile-%1/Active").arg(guid), profileActive);
settings->setValue(QString("DefaultAutoProfile-%1/DeviceName").arg(guid), deviceName);
}
if (!registeredGUIDs.isEmpty())
{
settings->setValue("DefaultAutoProfiles/GUIDs", registeredGUIDs);
}
settings->beginGroup("AutoProfiles");
QString autoActive = ui->activeCheckBox->isChecked() ? "1" : "0";
settings->setValue("AutoProfilesActive", autoActive);
QListIterator<AutoProfileInfo*> iterProfiles(profileList);
int i = 1;
while (iterProfiles.hasNext())
{
AutoProfileInfo *info = iterProfiles.next();
QString defaultActive = info->isActive() ? "1" : "0";
if (!info->getExe().isEmpty())
{
settings->setValue(QString("AutoProfile%1Exe").arg(i), info->getExe());
}
if (!info->getWindowClass().isEmpty())
{
settings->setValue(QString("AutoProfile%1WindowClass").arg(i), info->getWindowClass());
}
if (!info->getWindowName().isEmpty())
{
settings->setValue(QString("AutoProfile%1WindowName").arg(i), info->getWindowName());
}
settings->setValue(QString("AutoProfile%1GUID").arg(i), info->getGUID());
settings->setValue(QString("AutoProfile%1Profile").arg(i), info->getProfileLocation());
settings->setValue(QString("AutoProfile%1Active").arg(i), defaultActive);
settings->setValue(QString("AutoProfile%1DeviceName").arg(i), info->getDeviceName());
i++;
}
settings->endGroup();
settings->getLock()->unlock();
}
void MainSettingsDialog::fillAllAutoProfilesTable()
{
for (int i = ui->autoProfileTableWidget->rowCount()-1; i >= 0; i--)
{
ui->autoProfileTableWidget->removeRow(i);
}
//QStringList tableHeader;
//tableHeader << tr("Active") << tr("GUID") << tr("Profile") << tr("Application") << tr("Default?")
// << tr("Instance");
//ui->autoProfileTableWidget->setHorizontalHeaderLabels(tableHeader);
ui->autoProfileTableWidget->horizontalHeader()->setVisible(true);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
ui->autoProfileTableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
#else
ui->autoProfileTableWidget->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
#endif
ui->autoProfileTableWidget->hideColumn(7);
int i = 0;
AutoProfileInfo *info = allDefaultProfile;
ui->autoProfileTableWidget->insertRow(i);
QTableWidgetItem *item = new QTableWidgetItem();
item->setCheckState(info->isActive() ? Qt::Checked : Qt::Unchecked);
ui->autoProfileTableWidget->setItem(i, 0, item);
QString deviceName = info->getDeviceName();
QString guidDisplay = info->getGUID();
if (!deviceName.isEmpty())
{
guidDisplay = QString("%1 ").arg(info->getDeviceName());
guidDisplay.append(QString("(%1)").arg(info->getGUID()));
}
item = new QTableWidgetItem(guidDisplay);
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, info->getGUID());
item->setToolTip(info->getGUID());
ui->autoProfileTableWidget->setItem(i, 1, item);
QFileInfo profilePath(info->getProfileLocation());
item = new QTableWidgetItem(profilePath.fileName());
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, info->getProfileLocation());
item->setToolTip(info->getProfileLocation());
ui->autoProfileTableWidget->setItem(i, 2, item);
QFileInfo exeInfo(info->getExe());
item = new QTableWidgetItem(exeInfo.fileName());
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, info->getExe());
item->setToolTip(info->getExe());
ui->autoProfileTableWidget->setItem(i, 5, item);
item = new QTableWidgetItem("Default");
item->setData(Qt::UserRole, "default");
ui->autoProfileTableWidget->setItem(i, 6, item);
item = new QTableWidgetItem("Instance");
item->setData(Qt::UserRole, QVariant::fromValue<AutoProfileInfo*>(info));
ui->autoProfileTableWidget->setItem(i, 7, item);
i++;
QListIterator<AutoProfileInfo*> iterDefaults(defaultList);
while (iterDefaults.hasNext())
{
AutoProfileInfo *info = iterDefaults.next();
ui->autoProfileTableWidget->insertRow(i);
QTableWidgetItem *item = new QTableWidgetItem();
item->setCheckState(info->isActive() ? Qt::Checked : Qt::Unchecked);
ui->autoProfileTableWidget->setItem(i, 0, item);
QString deviceName = info->getDeviceName();
QString guidDisplay = info->getGUID();
if (!deviceName.isEmpty())
{
guidDisplay = QString("%1 ").arg(info->getDeviceName());
guidDisplay.append(QString("(%1)").arg(info->getGUID()));
}
item = new QTableWidgetItem(guidDisplay);
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, info->getGUID());
item->setToolTip(info->getGUID());
ui->autoProfileTableWidget->setItem(i, 1, item);
QFileInfo profilePath(info->getProfileLocation());
item = new QTableWidgetItem(profilePath.fileName());
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, info->getProfileLocation());
item->setToolTip(info->getProfileLocation());
ui->autoProfileTableWidget->setItem(i, 2, item);
/*
QFileInfo exeInfo(info->getExe());
item = new QTableWidgetItem(exeInfo.fileName());
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, info->getExe());
item->setToolTip(info->getExe());
ui->autoProfileTableWidget->setItem(i, 3, item);
*/
item = new QTableWidgetItem("Default");
item->setData(Qt::UserRole, "default");
ui->autoProfileTableWidget->setItem(i, 6, item);
item = new QTableWidgetItem("Instance");
item->setData(Qt::UserRole, QVariant::fromValue<AutoProfileInfo*>(info));
ui->autoProfileTableWidget->setItem(i, 7, item);
i++;
}
QListIterator<AutoProfileInfo*> iter(profileList);
while (iter.hasNext())
{
AutoProfileInfo *info = iter.next();
ui->autoProfileTableWidget->insertRow(i);
QTableWidgetItem *item = new QTableWidgetItem();
item->setCheckState(info->isActive() ? Qt::Checked : Qt::Unchecked);
ui->autoProfileTableWidget->setItem(i, 0, item);
QString deviceName = info->getDeviceName();
QString guidDisplay = info->getGUID();
if (!deviceName.isEmpty())
{
guidDisplay = QString("%1 ").arg(info->getDeviceName());
guidDisplay.append(QString("(%1)").arg(info->getGUID()));
}
item = new QTableWidgetItem(guidDisplay);
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, info->getGUID());
item->setToolTip(info->getGUID());
ui->autoProfileTableWidget->setItem(i, 1, item);
QFileInfo profilePath(info->getProfileLocation());
item = new QTableWidgetItem(profilePath.fileName());
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, info->getProfileLocation());
item->setToolTip(info->getProfileLocation());
ui->autoProfileTableWidget->setItem(i, 2, item);
item = new QTableWidgetItem(info->getWindowClass());
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, info->getWindowClass());
item->setToolTip(info->getWindowClass());
ui->autoProfileTableWidget->setItem(i, 3, item);
item = new QTableWidgetItem(info->getWindowName());
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, info->getWindowName());
item->setToolTip(info->getWindowName());
ui->autoProfileTableWidget->setItem(i, 4, item);
QFileInfo exeInfo(info->getExe());
item = new QTableWidgetItem(exeInfo.fileName());
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole, info->getExe());
item->setToolTip(info->getExe());
ui->autoProfileTableWidget->setItem(i, 5, item);
item = new QTableWidgetItem();
item->setData(Qt::UserRole, "");
ui->autoProfileTableWidget->setItem(i, 6, item);
item = new QTableWidgetItem("Instance");
item->setData(Qt::UserRole, QVariant::fromValue<AutoProfileInfo*>(info));
ui->autoProfileTableWidget->setItem(i, 7, item);
i++;
}
}
void MainSettingsDialog::processAutoProfileActiveClick(QTableWidgetItem *item)
{
if (item && item->column() == 0)
{
QTableWidgetItem *infoitem = ui->autoProfileTableWidget->item(item->row(), 7);
AutoProfileInfo *info = infoitem->data(Qt::UserRole).value<AutoProfileInfo*>();
Qt::CheckState active = item->checkState();
if (active == Qt::Unchecked)
{
info->setActive(false);
}
else if (active == Qt::Checked)
{
info->setActive(true);
}
}
}
void MainSettingsDialog::openAddAutoProfileDialog()
{
QList<QString> reservedGUIDs = defaultAutoProfiles.keys();
AutoProfileInfo *info = new AutoProfileInfo(this);
AddEditAutoProfileDialog *dialog = new AddEditAutoProfileDialog(info, settings, connectedDevices, reservedGUIDs, false, this);
connect(dialog, SIGNAL(accepted()), this, SLOT(addNewAutoProfile()));
connect(dialog, SIGNAL(rejected()), info, SLOT(deleteLater()));
dialog->show();
}
void MainSettingsDialog::openEditAutoProfileDialog()
{
int selectedRow = ui->autoProfileTableWidget->currentRow();
if (selectedRow >= 0)
{
QTableWidgetItem *item = ui->autoProfileTableWidget->item(selectedRow, 7);
//QTableWidgetItem *itemDefault = ui->autoProfileTableWidget->item(selectedRow, 4);
AutoProfileInfo *info = item->data(Qt::UserRole).value<AutoProfileInfo*>();
if (info != allDefaultProfile)
{
QList<QString> reservedGUIDs = defaultAutoProfiles.keys();
if (info->getGUID() != "all")
{
AutoProfileInfo *temp = defaultAutoProfiles.value(info->getGUID());
if (info == temp)
{
reservedGUIDs.removeAll(info->getGUID());
}
}
AddEditAutoProfileDialog *dialog = new AddEditAutoProfileDialog(info, settings, connectedDevices, reservedGUIDs, true, this);
connect(dialog, SIGNAL(accepted()), this, SLOT(transferEditsToCurrentTableRow()));
dialog->show();
}
else
{
EditAllDefaultAutoProfileDialog *dialog = new EditAllDefaultAutoProfileDialog(info, settings, this);
dialog->show();
connect(dialog, SIGNAL(accepted()), this, SLOT(transferAllProfileEditToCurrentTableRow()));
}
}
}
void MainSettingsDialog::openDeleteAutoProfileConfirmDialog()
{
QMessageBox msgBox;
msgBox.setText(tr("Are you sure you want to delete the profile?"));
msgBox.setStandardButtons(QMessageBox::Discard | QMessageBox::Cancel);
msgBox.setDefaultButton(QMessageBox::Cancel);
int ret = msgBox.exec();
if (ret == QMessageBox::Discard)
{
int selectedRow = ui->autoProfileTableWidget->currentRow();
if (selectedRow >= 0)
{
QTableWidgetItem *item = ui->autoProfileTableWidget->item(selectedRow, 7);
//QTableWidgetItem *itemDefault = ui->autoProfileTableWidget->item(selectedRow, 4);
AutoProfileInfo *info = item->data(Qt::UserRole).value<AutoProfileInfo*>();
if (info->isCurrentDefault())
{
if (info->getGUID() == "all")
{
delete allDefaultProfile;
allDefaultProfile = 0;
}
else if (defaultAutoProfiles.contains(info->getGUID()))
{
defaultAutoProfiles.remove(info->getGUID());
defaultList.removeAll(info);
delete info;
info = 0;
}
}
else
{
if (deviceAutoProfiles.contains(info->getGUID()))
{
QList<AutoProfileInfo*> temp = deviceAutoProfiles.value(info->getGUID());
temp.removeAll(info);
deviceAutoProfiles.insert(info->getGUID(), temp);
}
/*if (exeAutoProfiles.contains(info->getExe()))
{
QList<AutoProfileInfo*> temp = exeAutoProfiles.value(info->getExe());
temp.removeAll(info);
exeAutoProfiles.insert(info->getExe(), temp);
}
*/
profileList.removeAll(info);
delete info;
info = 0;
}
}
ui->autoProfileTableWidget->removeRow(selectedRow);
}
}
void MainSettingsDialog::changeAutoProfileButtonsState()
{
int selectedRow = ui->autoProfileTableWidget->currentRow();
if (selectedRow >= 0)
{
QTableWidgetItem *item = ui->autoProfileTableWidget->item(selectedRow, 7);
//QTableWidgetItem *itemDefault = ui->autoProfileTableWidget->item(selectedRow, 4);
AutoProfileInfo *info = item->data(Qt::UserRole).value<AutoProfileInfo*>();
if (info == allDefaultProfile)
{
ui->autoProfileAddPushButton->setEnabled(true);
ui->autoProfileEditPushButton->setEnabled(true);
ui->autoProfileDeletePushButton->setEnabled(false);
}
else
{
ui->autoProfileAddPushButton->setEnabled(true);
ui->autoProfileEditPushButton->setEnabled(true);
ui->autoProfileDeletePushButton->setEnabled(true);
}
}
else
{
ui->autoProfileAddPushButton->setEnabled(true);
ui->autoProfileDeletePushButton->setEnabled(false);
ui->autoProfileEditPushButton->setEnabled(false);
}
}
void MainSettingsDialog::transferAllProfileEditToCurrentTableRow()
{
EditAllDefaultAutoProfileDialog *dialog = static_cast<EditAllDefaultAutoProfileDialog*>(sender());
AutoProfileInfo *info = dialog->getAutoProfile();
allDefaultProfile = info;
changeDeviceForProfileTable(0);
}
void MainSettingsDialog::transferEditsToCurrentTableRow()
{
AddEditAutoProfileDialog *dialog = static_cast<AddEditAutoProfileDialog*>(sender());
AutoProfileInfo *info = dialog->getAutoProfile();
// Delete pointers to object that might be misplaced
// due to an association change.
QString oldGUID = dialog->getOriginalGUID();
//QString originalExe = dialog->getOriginalExe();
if (oldGUID != info->getGUID())
{
if (defaultAutoProfiles.value(oldGUID) == info)
{
defaultAutoProfiles.remove(oldGUID);
}
if (info->isCurrentDefault())
{
defaultAutoProfiles.insert(info->getGUID(), info);
}
}
if (oldGUID != info->getGUID() && deviceAutoProfiles.contains(oldGUID))
{
QList<AutoProfileInfo*> temp = deviceAutoProfiles.value(oldGUID);
temp.removeAll(info);
if (temp.count() > 0)
{
deviceAutoProfiles.insert(oldGUID, temp);
}
else
{
deviceAutoProfiles.remove(oldGUID);
}
if (deviceAutoProfiles.contains(info->getGUID()))
{
QList<AutoProfileInfo*> temp2 = deviceAutoProfiles.value(oldGUID);
if (!temp2.contains(info))
{
temp2.append(info);
deviceAutoProfiles.insert(info->getGUID(), temp2);
}
}
else if (info->getGUID().toLower() != "all")
{
QList<AutoProfileInfo*> temp2;
temp2.append(info);
deviceAutoProfiles.insert(info->getGUID(), temp2);
}
}
else if (oldGUID != info->getGUID() && info->getGUID().toLower() != "all")
{
QList<AutoProfileInfo*> temp;
temp.append(info);
deviceAutoProfiles.insert(info->getGUID(), temp);
}
if (!info->isCurrentDefault())
{
defaultList.removeAll(info);
if (!profileList.contains(info))
{
profileList.append(info);
}
}
else
{
profileList.removeAll(info);
if (!defaultList.contains(info))
{
defaultList.append(info);
}
}
if (deviceAutoProfiles.contains(info->getGUID()))
{
QList<AutoProfileInfo*> temp2 = deviceAutoProfiles.value(info->getGUID());
if (!temp2.contains(info))
{
temp2.append(info);
deviceAutoProfiles.insert(info->getGUID(), temp2);
}
}
else
{
QList<AutoProfileInfo*> temp2;
temp2.append(info);
deviceAutoProfiles.insert(info->getGUID(), temp2);
}
/*if (originalExe != info->getExe() &&
exeAutoProfiles.contains(originalExe))
{
QList<AutoProfileInfo*> temp = exeAutoProfiles.value(originalExe);
temp.removeAll(info);
exeAutoProfiles.insert(originalExe, temp);
if (exeAutoProfiles.contains(info->getExe()))
{
QList<AutoProfileInfo*> temp2 = exeAutoProfiles.value(info->getExe());
if (!temp2.contains(info))
{
temp2.append(info);
exeAutoProfiles.insert(info->getExe(), temp2);
}
}
else
{
QList<AutoProfileInfo*> temp2;
temp2.append(info);
exeAutoProfiles.insert(info->getExe(), temp2);
}
if (deviceAutoProfiles.contains(info->getGUID()))
{
QList<AutoProfileInfo*> temp2 = deviceAutoProfiles.value(info->getGUID());
if (!temp2.contains(info))
{
temp2.append(info);
deviceAutoProfiles.insert(info->getGUID(), temp2);
}
}
else
{
QList<AutoProfileInfo*> temp2;
temp2.append(info);
deviceAutoProfiles.insert(info->getGUID(), temp2);
}
}
*/
fillGUIDComboBox();
int currentIndex = ui->devicesComboBox->currentIndex();
changeDeviceForProfileTable(currentIndex);
}
void MainSettingsDialog::addNewAutoProfile()
{
AddEditAutoProfileDialog *dialog = static_cast<AddEditAutoProfileDialog*>(sender());
AutoProfileInfo *info = dialog->getAutoProfile();
bool found = false;
if (info->isCurrentDefault())
{
if (defaultAutoProfiles.contains(info->getGUID()))
{
found = true;
}
}
/*else
{
QList<AutoProfileInfo*> templist;
if (exeAutoProfiles.contains(info->getExe()))
{
templist = exeAutoProfiles.value(info->getExe());
}
QListIterator<AutoProfileInfo*> iterProfiles(templist);
while (iterProfiles.hasNext())
{
AutoProfileInfo *oldinfo = iterProfiles.next();
if (info->getExe() == oldinfo->getExe() &&
info->getGUID() == oldinfo->getGUID())
{
found = true;
iterProfiles.toBack();
}
}
}
*/
if (!found)
{
if (info->isCurrentDefault())
{
if (!info->getGUID().isEmpty() && !info->getExe().isEmpty())
{
defaultAutoProfiles.insert(info->getGUID(), info);
defaultList.append(info);
}
}
else
{
if (!info->getGUID().isEmpty() &&
!info->getExe().isEmpty())
{
//QList<AutoProfileInfo*> templist;
//templist.append(info);
//exeAutoProfiles.insert(info->getExe(), templist);
profileList.append(info);
if (info->getGUID() != "all")
{
QList<AutoProfileInfo*> tempDevProfileList;
if (deviceAutoProfiles.contains(info->getGUID()))
{
tempDevProfileList = deviceAutoProfiles.value(info->getGUID());
}
tempDevProfileList.append(info);
deviceAutoProfiles.insert(info->getGUID(), tempDevProfileList);
}
}
}
fillGUIDComboBox();
changeDeviceForProfileTable(ui->devicesComboBox->currentIndex());
}
}
void MainSettingsDialog::autoProfileButtonsActiveState(bool enabled)
{
if (enabled)
{
changeAutoProfileButtonsState();
}
else
{
ui->autoProfileAddPushButton->setEnabled(false);
ui->autoProfileEditPushButton->setEnabled(false);
ui->autoProfileDeletePushButton->setEnabled(false);
}
}
void MainSettingsDialog::changeKeyRepeatWidgetsStatus(bool enabled)
{
ui->keyDelayHorizontalSlider->setEnabled(enabled);
ui->keyDelaySpinBox->setEnabled(enabled);
ui->keyRateHorizontalSlider->setEnabled(enabled);
ui->keyRateSpinBox->setEnabled(enabled);
}
void MainSettingsDialog::checkSmoothingWidgetStatus(bool enabled)
{
if (enabled)
{
ui->historySizeSpinBox->setEnabled(true);
ui->weightModifierDoubleSpinBox->setEnabled(true);
}
else
{
ui->historySizeSpinBox->setEnabled(false);
ui->weightModifierDoubleSpinBox->setEnabled(false);
}
}
void MainSettingsDialog::changePresetLanguage()
{
if (settings->contains("Language"))
{
QString targetLang = settings->value("Language").toString();
if (targetLang == "br")
{
ui->localeListWidget->setCurrentRow(1);
}
else if (targetLang == "en")
{
ui->localeListWidget->setCurrentRow(2);
}
else if (targetLang == "fr")
{
ui->localeListWidget->setCurrentRow(3);
}
else if (targetLang == "de")
{
ui->localeListWidget->setCurrentRow(4);
}
else if (targetLang == "it")
{
ui->localeListWidget->setCurrentRow(5);
}
else if (targetLang == "ja")
{
ui->localeListWidget->setCurrentRow(6);
}
else if (targetLang == "ru")
{
ui->localeListWidget->setCurrentRow(7);
}
else if (targetLang == "sr")
{
ui->localeListWidget->setCurrentRow(8);
}
else if (targetLang == "zh_CN")
{
ui->localeListWidget->setCurrentRow(9);
}
else if (targetLang == "es")
{
ui->localeListWidget->setCurrentRow(10);
}
else if (targetLang == "uk")
{
ui->localeListWidget->setCurrentRow(11);
}
else
{
ui->localeListWidget->setCurrentRow(0);
}
}
else
{
ui->localeListWidget->setCurrentRow(0);
}
}
void MainSettingsDialog::fillSpringScreenPresets()
{
ui->springScreenComboBox->clear();
ui->springScreenComboBox->addItem(tr("Default"),
QVariant(AntiMicroSettings::defaultSpringScreen));
QDesktopWidget deskWid;
for (int i=0; i < deskWid.screenCount(); i++)
{
ui->springScreenComboBox->addItem(QString(":%1").arg(i), QVariant(i));
}
int screenIndex = ui->springScreenComboBox->findData(JoyButton::getSpringModeScreen());
if (screenIndex > -1)
{
ui->springScreenComboBox->setCurrentIndex(screenIndex);
}
}
void MainSettingsDialog::refreshExtraMouseInfo()
{
#if defined(Q_OS_UNIX) && defined(WITH_X11)
QString handler = EventHandlerFactory::getInstance()->handler()->getIdentifier();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
struct X11Extras::ptrInformation temp;
if (handler == "uinput")
{
temp = X11Extras::getInstance()->getPointInformation();
}
else if (handler == "xtest")
{
temp = X11Extras::getInstance()->getPointInformation(X11Extras::xtestMouseDeviceName);
}
if (temp.id >= 0)
{
ui->accelNumLabel->setText(QString::number(temp.accelNum));
ui->accelDenomLabel->setText(QString::number(temp.accelDenom));
ui->accelThresLabel->setText(QString::number(temp.threshold));
}
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
#endif
#endif
}
void MainSettingsDialog::resetMouseAcceleration()
{
#if defined(Q_OS_UNIX) && defined(WITH_X11)
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
X11Extras::getInstance()->x11ResetMouseAccelerationChange();
refreshExtraMouseInfo();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
#endif
#endif
}
void MainSettingsDialog::selectLogFile() {
QString oldLogFile = settings->value("LogFile", "").toString();
QString newLogFile =
QFileDialog::getSaveFileName(this, tr("Save Log File As"), oldLogFile,
tr("Log Files (*.log)"));
if( !newLogFile.isEmpty() ) {
ui->logFilePathEdit->setText(newLogFile);
}
}
``` | /content/code_sandbox/src/mainsettingsdialog.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 15,629 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.