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 COMMON_H
#define COMMON_H
#include <QtGlobal>
#include <QString>
#include <QDir>
#include <QStringList>
#include <QFileInfo>
#include <QTranslator>
#include <QWaitCondition>
#include <QMutex>
#include <QReadWriteLock>
#include <QThread>
#include <QCoreApplication>
#include "config.h"
#include "antimicrosettings.h"
#include "mousehelper.h"
#ifdef Q_OS_WIN
static QString findWinSystemConfigPath()
{
QString temp;
temp = (!qgetenv("LocalAppData").isEmpty()) ?
QString::fromUtf8(qgetenv("LocalAppData")) + "/antimicro" :
QDir::homePath() + "/.antimicro";
return temp;
}
static QString findWinLocalConfigPath()
{
QString temp = QCoreApplication::applicationDirPath();
return temp;
}
static QString findWinDefaultConfigPath()
{
QString temp = findWinLocalConfigPath();
QFileInfo dirInfo(temp);
if (!dirInfo.isWritable())
{
temp = findWinSystemConfigPath();
}
return temp;
}
static QString findWinConfigPath(QString configFileName)
{
QString temp;
QFileInfo localConfigInfo(findWinLocalConfigPath().append("/").append(configFileName));
QFileInfo systemConfigInfo(findWinSystemConfigPath().append("/").append(configFileName));
if (localConfigInfo.exists() && localConfigInfo.isWritable())
{
temp = localConfigInfo.absoluteFilePath();
}
else if (systemConfigInfo.exists() && systemConfigInfo.isWritable())
{
temp = systemConfigInfo.absoluteFilePath();
}
else
{
temp = findWinDefaultConfigPath().append("/").append(configFileName);
}
return temp;
}
#endif
namespace PadderCommon
{
inline QString configPath() {
#if defined(Q_OS_WIN) && defined(WIN_PORTABLE_PACKAGE)
return findWinLocalConfigPath();
#elif defined(Q_OS_WIN)
return findWinSystemConfigPath();
#else
return (!qgetenv("XDG_CONFIG_HOME").isEmpty()) ?
QString::fromUtf8(qgetenv("XDG_CONFIG_HOME")) + "/antimicro" :
QDir::homePath() + "/.config/antimicro";
#endif
}
const QString configFileName = "antimicro_settings.ini";
inline QString configFilePath() {
#if defined(Q_OS_WIN) && defined(WIN_PORTABLE_PACKAGE)
return QString(configPath()).append("/").append(configFileName);
#elif defined(Q_OS_WIN)
return QString(configPath()).append("/").append(configFileName);
#else
return QString(configPath()).append("/").append(configFileName);
#endif
}
const int LATESTCONFIGFILEVERSION = 19;
// Specify the last known profile version that requires a migration
// to be performed in order to be compatible with the latest version.
const int LATESTCONFIGMIGRATIONVERSION = 5;
const QString localSocketKey = "antimicroSignalListener";
const QString githubProjectPage = "path_to_url";
const QString wikiPage = QString("%1/wiki").arg(githubProjectPage);
const QString mouseDeviceName("antimicro Mouse Emulation");
const QString keyboardDeviceName("antimicro Keyboard Emulation");
const QString springMouseDeviceName("antimicro Abs Mouse Emulation");
const int ANTIMICRO_MAJOR_VERSION = PROJECT_MAJOR_VERSION;
const int ANTIMICRO_MINOR_VERSION = PROJECT_MINOR_VERSION;
const int ANTIMICRO_PATCH_VERSION = PROJECT_PATCH_VERSION;
const QString programVersion = (ANTIMICRO_PATCH_VERSION > 0) ?
QString("%1.%2.%3").arg(ANTIMICRO_MAJOR_VERSION)
.arg(ANTIMICRO_MINOR_VERSION).arg(ANTIMICRO_PATCH_VERSION) :
QString("%1.%2").arg(ANTIMICRO_MAJOR_VERSION)
.arg(ANTIMICRO_MINOR_VERSION);
extern QWaitCondition waitThisOut;
extern QMutex sdlWaitMutex;
extern QMutex inputDaemonMutex;
extern bool editingBindings;
extern QReadWriteLock editingLock;
extern MouseHelper mouseHelperObj;
QString preferredProfileDir(AntiMicroSettings *settings);
QStringList arguments(int &argc, char **argv);
QStringList parseArgumentsString(QString tempString);
void reloadTranslations(QTranslator *translator,
QTranslator *appTranslator,
QString language);
void lockInputDevices();
void unlockInputDevices();
/*!
* \brief Returns the "human-readable" name of the given profile.
*/
inline QString getProfileName(QFileInfo& profile) {
QString retVal = profile.completeBaseName();
return retVal;
}
}
Q_DECLARE_METATYPE(QThread*)
#endif // COMMON_H
``` | /content/code_sandbox/src/common.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,100 |
```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 "joystick.h"
const QString Joystick::xmlName = "joystick";
Joystick::Joystick(SDL_Joystick *joyhandle, int deviceIndex,
AntiMicroSettings *settings, QObject *parent) :
InputDevice(deviceIndex, settings, parent)
{
this->joyhandle = joyhandle;
#ifdef USE_SDL_2
joystickID = SDL_JoystickInstanceID(joyhandle);
#else
joyNumber = SDL_JoystickIndex(joyhandle);
#endif
for (int i=0; i < NUMBER_JOYSETS; i++)
{
SetJoystick *setstick = new SetJoystick(this, i, this);
joystick_sets.insert(i, setstick);
enableSetConnections(setstick);
}
}
QString Joystick::getName()
{
return QString(tr("Joystick")).append(" ").append(QString::number(getRealJoyNumber()));
}
QString Joystick::getSDLName()
{
QString temp;
#ifdef USE_SDL_2
if (joyhandle)
{
temp = SDL_JoystickName(joyhandle);
}
#else
temp = SDL_JoystickName(joyNumber);
#endif
return temp;
}
QString Joystick::getGUIDString()
{
QString temp;
#ifdef USE_SDL_2
SDL_JoystickGUID tempGUID = SDL_JoystickGetGUID(joyhandle);
char guidString[65] = {'0'};
SDL_JoystickGetGUIDString(tempGUID, guidString, sizeof(guidString));
temp = QString(guidString);
#endif
// Not available on SDL 1.2. Return empty string in that case.
return temp;
}
QString Joystick::getXmlName()
{
return this->xmlName;
}
void Joystick::closeSDLDevice()
{
#ifdef USE_SDL_2
if (joyhandle && SDL_JoystickGetAttached(joyhandle))
{
SDL_JoystickClose(joyhandle);
}
#else
if (joyhandle && SDL_JoystickOpened(joyNumber))
{
SDL_JoystickClose(joyhandle);
}
#endif
}
int Joystick::getNumberRawButtons()
{
int numbuttons = SDL_JoystickNumButtons(joyhandle);
return numbuttons;
}
int Joystick::getNumberRawAxes()
{
int numaxes = SDL_JoystickNumAxes(joyhandle);
return numaxes;
}
int Joystick::getNumberRawHats()
{
int numhats = SDL_JoystickNumHats(joyhandle);
return numhats;
}
#ifdef USE_SDL_2
SDL_JoystickID Joystick::getSDLJoystickID()
{
return joystickID;
}
#endif
``` | /content/code_sandbox/src/joystick.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 661 |
```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 SETNAMESDIALOG_H
#define SETNAMESDIALOG_H
#include <QDialog>
#include "inputdevice.h"
namespace Ui {
class SetNamesDialog;
}
class SetNamesDialog : public QDialog
{
Q_OBJECT
public:
explicit SetNamesDialog(InputDevice *device, QWidget *parent = 0);
~SetNamesDialog();
protected:
InputDevice *device;
private:
Ui::SetNamesDialog *ui;
private slots:
void saveSetNameChanges();
};
#endif // SETNAMESDIALOG_H
``` | /content/code_sandbox/src/setnamesdialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 208 |
```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 JOYBUTTONMOUSEHELPER_H
#define JOYBUTTONMOUSEHELPER_H
#include <QObject>
#include <QThread>
class JoyButtonMouseHelper : public QObject
{
Q_OBJECT
public:
explicit JoyButtonMouseHelper(QObject *parent = 0);
void resetButtonMouseDistances();
void setFirstSpringStatus(bool status);
bool getFirstSpringStatus();
void carryGamePollRateUpdate(unsigned int pollRate);
void carryMouseRefreshRateUpdate(unsigned int refreshRate);
protected:
bool firstSpringEvent;
signals:
void mouseCursorMoved(int mouseX, int mouseY, int elapsed);
void mouseSpringMoved(int mouseX, int mouseY);
void gamepadRefreshRateUpdated(unsigned int pollRate);
void mouseRefreshRateUpdated(unsigned int refreshRate);
public slots:
void moveMouseCursor();
void moveSpringMouse();
void mouseEvent();
void changeThread(QThread *thread);
};
#endif // JOYBUTTONMOUSEHELPER_H
``` | /content/code_sandbox/src/joybuttonmousehelper.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 301 |
```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 <QFileDialog>
#include <QMessageBox>
#include "editalldefaultautoprofiledialog.h"
#include "ui_editalldefaultautoprofiledialog.h"
#include "common.h"
EditAllDefaultAutoProfileDialog::EditAllDefaultAutoProfileDialog(AutoProfileInfo *info, AntiMicroSettings *settings,
QWidget *parent) :
QDialog(parent),
ui(new Ui::EditAllDefaultAutoProfileDialog)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
this->info = info;
this->settings = settings;
if (!info->getProfileLocation().isEmpty())
{
ui->profileLineEdit->setText(info->getProfileLocation());
}
connect(ui->profileBrowsePushButton, SIGNAL(clicked()), this, SLOT(openProfileBrowseDialog()));
connect(this, SIGNAL(accepted()), this, SLOT(saveAutoProfileInformation()));
}
EditAllDefaultAutoProfileDialog::~EditAllDefaultAutoProfileDialog()
{
delete ui;
}
void EditAllDefaultAutoProfileDialog::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(filename);
}
}
void EditAllDefaultAutoProfileDialog::saveAutoProfileInformation()
{
info->setGUID("all");
info->setProfileLocation(ui->profileLineEdit->text());
info->setActive(true);
}
AutoProfileInfo* EditAllDefaultAutoProfileDialog::getAutoProfile()
{
return info;
}
void EditAllDefaultAutoProfileDialog::accept()
{
bool validForm = true;
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)
{
QDialog::accept();
}
else
{
QMessageBox msgBox;
msgBox.setText(errorString);
msgBox.setStandardButtons(QMessageBox::Close);
msgBox.exec();
}
}
``` | /content/code_sandbox/src/editalldefaultautoprofiledialog.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 592 |
```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 <QThread>
#include <QStringList>
#include <cmath>
#include "setjoystick.h"
#include "inputdevice.h"
#include "joybutton.h"
#include "vdpad.h"
#include "event.h"
#include "logger.h"
#ifdef Q_OS_WIN
#include "eventhandlerfactory.h"
#endif
const QString JoyButton::xmlName = "button";
// Set default values for many properties.
const int JoyButton::ENABLEDTURBODEFAULT = 100;
const double JoyButton::DEFAULTMOUSESPEEDMOD = 1.0;
double JoyButton::mouseSpeedModifier = JoyButton::DEFAULTMOUSESPEEDMOD;
const unsigned int JoyButton::DEFAULTKEYREPEATDELAY = 600; // 600 ms
const unsigned int JoyButton::DEFAULTKEYREPEATRATE = 40; // 40 ms. 25 times per second
const JoyButton::JoyMouseCurve JoyButton::DEFAULTMOUSECURVE = JoyButton::EnhancedPrecisionCurve;
const bool JoyButton::DEFAULTTOGGLE = false;
const int JoyButton::DEFAULTTURBOINTERVAL = 0;
const bool JoyButton::DEFAULTUSETURBO = false;
const int JoyButton::DEFAULTMOUSESPEEDX = 50;
const int JoyButton::DEFAULTMOUSESPEEDY = 50;
const int JoyButton::DEFAULTSETSELECTION = -1;
const JoyButton::SetChangeCondition JoyButton::DEFAULTSETCONDITION = JoyButton::SetChangeDisabled;
const JoyButton::JoyMouseMovementMode JoyButton::DEFAULTMOUSEMODE = JoyButton::MouseCursor;
const int JoyButton::DEFAULTSPRINGWIDTH = 0;
const int JoyButton::DEFAULTSPRINGHEIGHT = 0;
const double JoyButton::DEFAULTSENSITIVITY = 1.0;
const int JoyButton::DEFAULTWHEELX = 20;
const int JoyButton::DEFAULTWHEELY = 20;
const bool JoyButton::DEFAULTCYCLERESETACTIVE = false;
const int JoyButton::DEFAULTCYCLERESET = 0;
const bool JoyButton::DEFAULTRELATIVESPRING = false;
const JoyButton::TurboMode JoyButton::DEFAULTTURBOMODE = JoyButton::NormalTurbo;
const double JoyButton::DEFAULTEASINGDURATION = 0.5;
const double JoyButton::MINIMUMEASINGDURATION = 0.2;
const double JoyButton::MAXIMUMEASINGDURATION = 5.0;
const unsigned int JoyButton::MINCYCLERESETTIME = 10;
const unsigned int JoyButton::MAXCYCLERESETTIME = 60000;
const int JoyButton::DEFAULTMOUSEHISTORYSIZE = 10;
const double JoyButton::DEFAULTWEIGHTMODIFIER = 0.2;
const int JoyButton::MAXIMUMMOUSEHISTORYSIZE = 100;
const double JoyButton::MAXIMUMWEIGHTMODIFIER = 1.0;
const int JoyButton::MAXIMUMMOUSEREFRESHRATE = 16;
int JoyButton::IDLEMOUSEREFRESHRATE = (5 * 20);
const int JoyButton::DEFAULTIDLEMOUSEREFRESHRATE = 100;
const double JoyButton::DEFAULTEXTRACCELVALUE = 2.0;
const double JoyButton::DEFAULTMINACCELTHRESHOLD = 10.0;
const double JoyButton::DEFAULTMAXACCELTHRESHOLD = 100.0;
const double JoyButton::DEFAULTSTARTACCELMULTIPLIER = 0.0;
const double JoyButton::DEFAULTACCELEASINGDURATION = 0.1;
const JoyButton::JoyExtraAccelerationCurve
JoyButton::DEFAULTEXTRAACCELCURVE = JoyButton::LinearAccelCurve;
const int JoyButton::DEFAULTSPRINGRELEASERADIUS = 0;
// Keep references to active keys and mouse buttons.
QHash<unsigned int, int> JoyButton::activeKeys;
QHash<unsigned int, int> JoyButton::activeMouseButtons;
JoyButtonSlot* JoyButton::lastActiveKey = 0;
// Keep track of active Mouse Speed Mod slots.
QList<JoyButtonSlot*> JoyButton::mouseSpeedModList;
// Lists used for cursor mode calculations.
QList<JoyButton::mouseCursorInfo> JoyButton::cursorXSpeeds;
QList<JoyButton::mouseCursorInfo> JoyButton::cursorYSpeeds;
// Lists used for spring mode calculations.
QList<PadderCommon::springModeInfo> JoyButton::springXSpeeds;
QList<PadderCommon::springModeInfo> JoyButton::springYSpeeds;
// Keeps timestamp of last mouse event.
//QElapsedTimer JoyButton::lastMouseTime;
// Temporary test object to test old mouse time behavior.
QTime JoyButton::testOldMouseTime;
// Helper object to have a single mouse event for all JoyButton
// instances.
JoyButtonMouseHelper JoyButton::mouseHelper;
QTimer JoyButton::staticMouseEventTimer;
QList<JoyButton*> JoyButton::pendingMouseButtons;
// History buffers used for mouse smoothing routine.
QList<double> JoyButton::mouseHistoryX;
QList<double> JoyButton::mouseHistoryY;
// Carry over remainder of a cursor move for the next mouse event.
double JoyButton::cursorRemainderX = 0.0;
double JoyButton::cursorRemainderY = 0.0;
double JoyButton::weightModifier = 0;
int JoyButton::mouseHistorySize = 1;
int JoyButton::mouseRefreshRate = 5;
int JoyButton::springModeScreen = -1;
int JoyButton::gamepadRefreshRate = 10;
#ifdef Q_OS_WIN
JoyKeyRepeatHelper JoyButton::repeatHelper;
#endif
static const double PI = acos(-1.0);
JoyButton::JoyButton(int index, int originset, SetJoystick *parentSet,
QObject *parent) :
QObject(parent)
{
vdpad = 0;
slotiter = 0;
turboTimer.setParent(this);
pauseTimer.setParent(this);
holdTimer.setParent(this);
pauseWaitTimer.setParent(this);
createDeskTimer.setParent(this);
releaseDeskTimer.setParent(this);
mouseWheelVerticalEventTimer.setParent(this);
mouseWheelHorizontalEventTimer.setParent(this);
setChangeTimer.setParent(this);
keyPressTimer.setParent(this);
delayTimer.setParent(this);
slotSetChangeTimer.setParent(this);
activeZoneTimer.setParent(this);
setChangeTimer.setSingleShot(true);
slotSetChangeTimer.setSingleShot(true);
this->parentSet = parentSet;
connect(&pauseWaitTimer, SIGNAL(timeout()), this, SLOT(pauseWaitEvent()));
connect(&keyPressTimer, SIGNAL(timeout()), this, SLOT(keyPressEvent()));
connect(&holdTimer, SIGNAL(timeout()), this, SLOT(holdEvent()));
connect(&delayTimer, SIGNAL(timeout()), this, SLOT(delayEvent()));
connect(&createDeskTimer, SIGNAL(timeout()), this, SLOT(waitForDeskEvent()));
connect(&releaseDeskTimer, SIGNAL(timeout()), this, SLOT(waitForReleaseDeskEvent()));
connect(&turboTimer, SIGNAL(timeout()), this, SLOT(turboEvent()));
connect(&mouseWheelVerticalEventTimer, SIGNAL(timeout()), this, SLOT(wheelEventVertical()));
connect(&mouseWheelHorizontalEventTimer, SIGNAL(timeout()), this, SLOT(wheelEventHorizontal()));
connect(&setChangeTimer, SIGNAL(timeout()), this, SLOT(checkForSetChange()));
connect(&slotSetChangeTimer, SIGNAL(timeout()), this, SLOT(slotSetChange()));
connect(&activeZoneTimer, SIGNAL(timeout()), this, SLOT(buildActiveZoneSummaryString()));
activeZoneTimer.setInterval(0);
activeZoneTimer.setSingleShot(true);
// Will only matter on the first call
establishMouseTimerConnections();
// Make sure to call before calling reset
this->resetProperties();
this->index = index;
this->originset = originset;
quitEvent = true;
}
JoyButton::~JoyButton()
{
reset();
}
void JoyButton::queuePendingEvent(bool pressed, bool ignoresets)
{
pendingEvent = false;
pendingPress = false;
pendingIgnoreSets = false;
if (this->vdpad)
{
vdpadPassEvent(pressed, ignoresets);
}
else
{
pendingEvent = true;
pendingPress = pressed;
pendingIgnoreSets = ignoresets;
}
}
void JoyButton::activatePendingEvent()
{
if (pendingEvent)
{
joyEvent(pendingPress, pendingIgnoreSets);
pendingEvent = false;
pendingPress = false;
pendingIgnoreSets = false;
}
}
bool JoyButton::hasPendingEvent()
{
return pendingEvent;
}
void JoyButton::clearPendingEvent()
{
pendingEvent = false;
pendingPress = false;
pendingIgnoreSets = false;
}
void JoyButton::vdpadPassEvent(bool pressed, bool ignoresets)
{
if (this->vdpad && pressed != isButtonPressed)
{
isButtonPressed = pressed;
if (isButtonPressed)
{
emit clicked(index);
}
else
{
emit released(index);
}
if (!ignoresets)
{
this->vdpad->queueJoyEvent(ignoresets);
}
else
{
this->vdpad->joyEvent(pressed, ignoresets);
}
}
}
void JoyButton::joyEvent(bool pressed, bool ignoresets)
{
if (this->vdpad && !pendingEvent)
{
vdpadPassEvent(pressed, ignoresets);
}
else if (ignoreEvents)
{
if (pressed != isButtonPressed)
{
isButtonPressed = pressed;
if (isButtonPressed)
{
emit clicked(index);
}
else
{
emit released(index);
}
}
}
else
{
if (pressed != isDown)
{
if (pressed)
{
emit clicked(index);
if (updateInitAccelValues)
{
oldAccelMulti = updateOldAccelMulti = 0.0;
accelTravel = 0.0;
}
}
else
{
emit released(index);
}
bool activePress = pressed;
setChangeTimer.stop();
if (toggle && pressed)
{
isDown = true;
toggleActiveState = !toggleActiveState;
if (!isButtonPressed)
{
this->ignoresets = ignoresets;
isButtonPressed = !isButtonPressed;
ignoreSetQueue.enqueue(ignoresets);
isButtonPressedQueue.enqueue(isButtonPressed);
}
else
{
activePress = false;
}
}
else if (toggle && !pressed && isDown)
{
isDown = false;
if (!toggleActiveState)
{
this->ignoresets = ignoresets;
isButtonPressed = !isButtonPressed;
ignoreSetQueue.enqueue(ignoresets);
isButtonPressedQueue.enqueue(isButtonPressed);
}
}
else
{
this->ignoresets = ignoresets;
isButtonPressed = isDown = pressed;
ignoreSetQueue.enqueue(ignoresets);
isButtonPressedQueue.enqueue(isButtonPressed);
}
if (useTurbo)
{
if (isButtonPressed && activePress && !turboTimer.isActive())
{
if (cycleResetActive &&
cycleResetHold.elapsed() >= cycleResetInterval && slotiter)
{
slotiter->toFront();
currentCycle = 0;
previousCycle = 0;
}
buttonHold.restart();
buttonHeldRelease.restart();
keyPressHold.restart();
cycleResetHold.restart();
turboTimer.start();
// Newly activated button. Just entered safe zone.
if (updateInitAccelValues)
{
initializeDistanceValues();
}
currentAccelerationDistance = getAccelerationDistance();
Logger::LogDebug(tr("Processing turbo for #%1 - %2")
.arg(parentSet->getInputDevice()->getRealJoyNumber())
.arg(getPartialName()));
turboEvent();
}
else if (!isButtonPressed && !activePress && turboTimer.isActive())
{
turboTimer.stop();
Logger::LogDebug(tr("Finishing turbo for button #%1 - %2")
.arg(parentSet->getInputDevice()->getRealJoyNumber())
.arg(getPartialName()));
if (isKeyPressed)
{
turboEvent();
}
else
{
lastDistance = getMouseDistanceFromDeadZone();
}
activeZoneTimer.start();
}
}
// Toogle is enabled and a controller button change has occurred.
// Switch to a different distance zone if appropriate
else if (toggle && !activePress && isButtonPressed)
{
bool releasedCalled = distanceEvent();
if (releasedCalled)
{
quitEvent = true;
buttonHold.restart();
buttonHeldRelease.restart();
keyPressHold.restart();
//createDeskTimer.start(0);
releaseDeskTimer.stop();
if (!keyPressTimer.isActive())
{
waitForDeskEvent();
}
}
}
else if (isButtonPressed && activePress)
{
if (cycleResetActive &&
cycleResetHold.elapsed() >= cycleResetInterval && slotiter)
{
slotiter->toFront();
currentCycle = 0;
previousCycle = 0;
}
buttonHold.restart();
buttonHeldRelease.restart();
cycleResetHold.restart();
keyPressHold.restart();
//createDeskTimer.start(0);
releaseDeskTimer.stop();
// Newly activated button. Just entered safe zone.
if (updateInitAccelValues)
{
initializeDistanceValues();
}
currentAccelerationDistance = getAccelerationDistance();
Logger::LogDebug(tr("Processing press for button #%1 - %2")
.arg(parentSet->getInputDevice()->getRealJoyNumber())
.arg(getPartialName()));
if (!keyPressTimer.isActive())
{
checkForPressedSetChange();
if (!setChangeTimer.isActive())
{
waitForDeskEvent();
}
}
}
else if (!isButtonPressed && !activePress)
{
Logger::LogDebug(tr("Processing release for button #%1 - %2")
.arg(parentSet->getInputDevice()->getRealJoyNumber())
.arg(getPartialName()));
waitForReleaseDeskEvent();
}
if (updateInitAccelValues)
{
updateLastMouseDistance = false;
updateStartingMouseDistance = false;
updateOldAccelMulti = 0.0;
}
}
else if (!useTurbo && isButtonPressed)
{
resetAccelerationDistances();
currentAccelerationDistance = getAccelerationDistance();
if (!setChangeTimer.isActive())
{
bool releasedCalled = distanceEvent();
if (releasedCalled)
{
Logger::LogDebug(tr("Distance change for button #%1 - %2")
.arg(parentSet->getInputDevice()->getRealJoyNumber())
.arg(getPartialName()));
quitEvent = true;
buttonHold.restart();
buttonHeldRelease.restart();
keyPressHold.restart();
//createDeskTimer.start(0);
releaseDeskTimer.stop();
if (!keyPressTimer.isActive())
{
waitForDeskEvent();
}
}
}
}
}
updateInitAccelValues = true;
}
/**
* @brief Get 0 indexed number of button
* @return 0 indexed button index number
*/
int JoyButton::getJoyNumber()
{
return index;
}
/**
* @brief Get a 1 indexed number of button
* @return 1 indexed button index number
*/
int JoyButton::getRealJoyNumber()
{
return index + 1;
}
void JoyButton::setJoyNumber(int index)
{
this->index = index;
}
void JoyButton::setToggle(bool toggle)
{
if (toggle != this->toggle)
{
this->toggle = toggle;
emit toggleChanged(toggle);
emit propertyUpdated();
}
}
void JoyButton::setTurboInterval(int interval)
{
if (interval >= 10 && interval != this->turboInterval)
{
this->turboInterval = interval;
emit turboIntervalChanged(interval);
emit propertyUpdated();
}
else if (interval < 10 && interval != this->turboInterval)
{
interval = 0;
this->setUseTurbo(false);
this->turboInterval = interval;
emit turboIntervalChanged(interval);
emit propertyUpdated();
}
}
void JoyButton::reset()
{
disconnectPropertyUpdatedConnections();
turboTimer.stop();
pauseWaitTimer.stop();
createDeskTimer.stop();
releaseDeskTimer.stop();
holdTimer.stop();
mouseWheelVerticalEventTimer.stop();
mouseWheelHorizontalEventTimer.stop();
setChangeTimer.stop();
keyPressTimer.stop();
delayTimer.stop();
#ifdef Q_OS_WIN
repeatHelper.getRepeatTimer()->stop();
#endif
slotSetChangeTimer.stop();
if (slotiter)
{
delete slotiter;
slotiter = 0;
}
releaseActiveSlots();
clearAssignedSlots();
isButtonPressedQueue.clear();
ignoreSetQueue.clear();
mouseEventQueue.clear();
mouseWheelVerticalEventQueue.clear();
mouseWheelHorizontalEventQueue.clear();
resetProperties(); // quitEvent changed here
}
void JoyButton::reset(int index)
{
JoyButton::reset();
this->index = index;
}
bool JoyButton::getToggleState()
{
return toggle;
}
int JoyButton::getTurboInterval()
{
return turboInterval;
}
void JoyButton::turboEvent()
{
if (!isKeyPressed)
{
if (!isButtonPressedQueue.isEmpty())
{
ignoreSetQueue.clear();
isButtonPressedQueue.clear();
ignoreSetQueue.enqueue(false);
isButtonPressedQueue.enqueue(isButtonPressed);
}
createDeskEvent();
isKeyPressed = true;
if (turboTimer.isActive())
{
int tempInterval = turboInterval / 2;
if (turboTimer.interval() != tempInterval)
{
turboTimer.start(tempInterval);
}
}
}
else
{
if (!isButtonPressedQueue.isEmpty())
{
ignoreSetQueue.enqueue(false);
isButtonPressedQueue.enqueue(!isButtonPressed);
}
releaseDeskEvent();
isKeyPressed = false;
if (turboTimer.isActive())
{
int tempInterval = turboInterval / 2;
if (turboTimer.interval() != tempInterval)
{
turboTimer.start(tempInterval);
}
}
}
}
bool JoyButton::distanceEvent()
{
bool released = false;
if (slotiter)
{
QReadLocker tempLocker(&assignmentsLock);
bool distanceFound = containsDistanceSlots();
if (distanceFound)
{
double currentDistance = getDistanceFromDeadZone();
double tempDistance = 0.0;
JoyButtonSlot *previousDistanceSlot = 0;
QListIterator<JoyButtonSlot*> iter(assignments);
if (previousCycle)
{
iter.findNext(previousCycle);
}
while (iter.hasNext())
{
JoyButtonSlot *slot = iter.next();
int tempcode = slot->getSlotCode();
if (slot->getSlotMode() == JoyButtonSlot::JoyDistance)
{
tempDistance += tempcode / 100.0;
if (currentDistance < tempDistance)
{
iter.toBack();
}
else
{
previousDistanceSlot = slot;
}
}
else if (slot->getSlotMode() == JoyButtonSlot::JoyCycle)
{
tempDistance = 0.0;
iter.toBack();
}
}
// No applicable distance slot
if (!previousDistanceSlot)
{
if (this->currentDistance)
{
// Distance slot is currently active.
// Release slots, return iterator to
// the front, and nullify currentDistance
pauseWaitTimer.stop();
holdTimer.stop();
// Release stuff
releaseActiveSlots();
currentPause = currentHold = 0;
//quitEvent = true;
slotiter->toFront();
if (previousCycle)
{
slotiter->findNext(previousCycle);
}
this->currentDistance = 0;
released = true;
}
}
// An applicable distance slot was found
else if (previousDistanceSlot)
{
if (this->currentDistance != previousDistanceSlot)
{
// Active distance slot is not the applicable slot.
// Deactive slots in previous distance range and
// activate new slots. Set currentDistance to
// new slot.
pauseWaitTimer.stop();
holdTimer.stop();
// Release stuff
releaseActiveSlots();
currentPause = currentHold = 0;
//quitEvent = true;
slotiter->toFront();
if (previousCycle)
{
slotiter->findNext(previousCycle);
}
slotiter->findNext(previousDistanceSlot);
this->currentDistance = previousDistanceSlot;
released = true;
}
}
}
}
return released;
}
void JoyButton::createDeskEvent()
{
quitEvent = false;
if (!slotiter)
{
assignmentsLock.lockForRead();
slotiter = new QListIterator<JoyButtonSlot*>(assignments);
assignmentsLock.unlock();
distanceEvent();
}
else if (!slotiter->hasPrevious())
{
distanceEvent();
}
else if (currentCycle)
{
currentCycle = 0;
distanceEvent();
}
assignmentsLock.lockForRead();
activateSlots();
assignmentsLock.unlock();
if (currentCycle)
{
quitEvent = true;
}
else if (!currentPause && !currentHold && !keyPressTimer.isActive())
{
quitEvent = true;
}
}
void JoyButton::activateSlots()
{
if (slotiter)
{
QWriteLocker tempLocker(&activeZoneLock);
bool exit = false;
//bool delaySequence = checkForDelaySequence();
bool delaySequence = false;
bool changeRepeatState = false;
while (slotiter->hasNext() && !exit)
{
JoyButtonSlot *slot = slotiter->next();
int tempcode = slot->getSlotCode();
JoyButtonSlot::JoySlotInputAction mode = slot->getSlotMode();
if (mode == JoyButtonSlot::JoyKeyboard)
{
sendevent(slot, true);
activeSlots.append(slot);
int oldvalue = activeKeys.value(tempcode, 0) + 1;
activeKeys.insert(tempcode, oldvalue);
if (!slot->isModifierKey())
{
lastActiveKey = slot;
changeRepeatState = true;
}
else
{
lastActiveKey = 0;
changeRepeatState = true;
}
}
else if (mode == JoyButtonSlot::JoyMouseButton)
{
if (tempcode == JoyButtonSlot::MouseWheelUp ||
tempcode == JoyButtonSlot::MouseWheelDown)
{
slot->getMouseInterval()->restart();
wheelVerticalTime.restart();
currentWheelVerticalEvent = slot;
activeSlots.append(slot);
wheelEventVertical();
currentWheelVerticalEvent = 0;
}
else if (tempcode == JoyButtonSlot::MouseWheelLeft ||
tempcode == JoyButtonSlot::MouseWheelRight)
{
slot->getMouseInterval()->restart();
wheelHorizontalTime.restart();
currentWheelHorizontalEvent = slot;
activeSlots.append(slot);
wheelEventHorizontal();
currentWheelHorizontalEvent = 0;
}
else
{
sendevent(slot, true);
activeSlots.append(slot);
int oldvalue = activeMouseButtons.value(tempcode, 0) + 1;
activeMouseButtons.insert(tempcode, oldvalue);
}
}
else if (mode == JoyButtonSlot::JoyMouseMovement)
{
slot->getMouseInterval()->restart();
//currentMouseEvent = slot;
activeSlots.append(slot);
//mouseEventQueue.enqueue(slot);
//mouseEvent();
if (pendingMouseButtons.size() == 0)
{
mouseHelper.setFirstSpringStatus(true);
}
pendingMouseButtons.append(this);
mouseEventQueue.enqueue(slot);
//currentMouseEvent = 0;
// Temporarily lower timer interval. Helps improve mouse control
// precision on the lower end of an axis.
if (!staticMouseEventTimer.isActive() || staticMouseEventTimer.interval() != 0)
{
if (!staticMouseEventTimer.isActive() || staticMouseEventTimer.interval() == IDLEMOUSEREFRESHRATE)
{
int tempRate = qBound(0, mouseRefreshRate - gamepadRefreshRate, MAXIMUMMOUSEREFRESHRATE);
//Logger::LogInfo(QString("STARTING OVER: %1 %2").arg(QTime::currentTime().toString("hh:mm:ss.zzz")).arg(tempRate));
staticMouseEventTimer.start(tempRate);
//lastMouseTime.restart();
testOldMouseTime.restart();
accelExtraDurationTime.restart();
}
}
}
else if (mode == JoyButtonSlot::JoyPause)
{
if (!activeSlots.isEmpty())
{
if (slotiter->hasPrevious())
{
slotiter->previous();
}
delaySequence = true;
exit = true;
}
// Segment can be ignored on a 0 interval pause
else if (tempcode > 0)
{
currentPause = slot;
pauseHold.restart();
inpauseHold.restart();
pauseWaitTimer.start(0);
exit = true;
}
}
else if (mode == JoyButtonSlot::JoyHold)
{
currentHold = slot;
holdTimer.start(0);
exit = true;
}
else if (mode == JoyButtonSlot::JoyDelay)
{
currentDelay = slot;
buttonDelay.restart();
delayTimer.start(0);
exit = true;
}
else if (mode == JoyButtonSlot::JoyCycle)
{
currentCycle = slot;
exit = true;
}
else if (mode == JoyButtonSlot::JoyDistance)
{
exit = true;
}
else if (mode == JoyButtonSlot::JoyRelease)
{
if (!currentRelease)
{
findReleaseEventEnd();
}
/*else
{
currentRelease = 0;
exit = true;
}*/
else if (currentRelease && activeSlots.isEmpty())
{
//currentRelease = 0;
exit = true;
}
else if (currentRelease && !activeSlots.isEmpty())
{
if (slotiter->hasPrevious())
{
slotiter->previous();
}
delaySequence = true;
exit = true;
}
}
else if (mode == JoyButtonSlot::JoyMouseSpeedMod)
{
mouseSpeedModifier = tempcode * 0.01;
mouseSpeedModList.append(slot);
activeSlots.append(slot);
}
else if (mode == JoyButtonSlot::JoyKeyPress)
{
if (activeSlots.isEmpty())
{
delaySequence = true;
currentKeyPress = slot;
}
else
{
if (slotiter->hasPrevious())
{
slotiter->previous();
}
delaySequence = true;
exit = true;
}
}
else if (mode == JoyButtonSlot::JoyLoadProfile)
{
releaseActiveSlots();
slotiter->toBack();
exit = true;
QString location = slot->getTextData();
if (!location.isEmpty())
{
parentSet->getInputDevice()->sendLoadProfileRequest(location);
}
}
else if (mode == JoyButtonSlot::JoySetChange)
{
activeSlots.append(slot);
}
else if (mode == JoyButtonSlot::JoyTextEntry)
{
sendevent(slot, true);
}
else if (mode == JoyButtonSlot::JoyExecute)
{
sendevent(slot, true);
}
}
#ifdef Q_OS_WIN
BaseEventHandler *handler = EventHandlerFactory::getInstance()->handler();
#endif
if (delaySequence && !activeSlots.isEmpty())
{
keyPressHold.restart();
keyPressEvent();
}
#ifdef Q_OS_WIN
else if (handler && handler->getIdentifier() == "sendinput" &&
changeRepeatState && !useTurbo)
{
InputDevice *device = getParentSet()->getInputDevice();
if (device->isKeyRepeatEnabled())
{
if (lastActiveKey && activeSlots.contains(lastActiveKey))
{
repeatHelper.setLastActiveKey(lastActiveKey);
repeatHelper.setKeyRepeatRate(device->getKeyRepeatRate());
repeatHelper.getRepeatTimer()->start(device->getKeyRepeatDelay());
}
else if (repeatHelper.getRepeatTimer()->isActive())
{
repeatHelper.setLastActiveKey(0);
repeatHelper.getRepeatTimer()->stop();
}
}
}
#endif
//emit activeZoneChanged();
activeZoneTimer.start();
}
}
void JoyButton::slotSetChange()
{
if (currentSetChangeSlot)
{
// Get set change slot and then remove reference.
unsigned int setChangeIndex = currentSetChangeSlot->getSlotCode();
currentSetChangeSlot = 0;
// Ensure that a change to the current set is not attempted.
if (setChangeIndex != originset)
{
emit released(index);
emit setChangeActivated(setChangeIndex);
}
}
}
/**
* @brief Calculate mouse movement coordinates for mouse movement slots
* currently active.
*/
void JoyButton::mouseEvent()
{
JoyButtonSlot *buttonslot = 0;
bool singleShot = false;
if (currentMouseEvent)
{
buttonslot = currentMouseEvent;
singleShot = true;
}
if (buttonslot || !mouseEventQueue.isEmpty())
{
updateLastMouseDistance = true;
updateStartingMouseDistance = true;
updateOldAccelMulti = 0.0;
QQueue<JoyButtonSlot*> tempQueue;
if (!buttonslot)
{
buttonslot = mouseEventQueue.dequeue();
}
//unsigned int timeElapsed = lastMouseTime.elapsed();
unsigned int timeElapsed = testOldMouseTime.elapsed();
//unsigned int nanoTimeElapsed = lastMouseTime.nsecsElapsed();
// Presumed initial mouse movement. Use full duration rather than
// partial.
if (staticMouseEventTimer.interval() < mouseRefreshRate)
{
//unsigned int nanoRemainder = nanoTimeElapsed - (timeElapsed * 1000000);
timeElapsed = getMouseRefreshRate() + (timeElapsed - staticMouseEventTimer.interval());
//nanoTimeElapsed = (timeElapsed * 1000000) + (nanoRemainder);
}
while (buttonslot)
{
QElapsedTimer* mouseInterval = buttonslot->getMouseInterval();
int mousedirection = buttonslot->getSlotCode();
JoyButton::JoyMouseMovementMode mousemode = getMouseMode();
int mousespeed = 0;
bool isActive = activeSlots.contains(buttonslot);
if (isActive)
{
if (mousemode == JoyButton::MouseCursor)
{
if (mousedirection == JoyButtonSlot::MouseRight)
{
mousespeed = mouseSpeedX;
}
else if (mousedirection == JoyButtonSlot::MouseLeft)
{
mousespeed = mouseSpeedX;
}
else if (mousedirection == JoyButtonSlot::MouseDown)
{
mousespeed = mouseSpeedY;
}
else if (mousedirection == JoyButtonSlot::MouseUp)
{
mousespeed = mouseSpeedY;
}
double difference = getMouseDistanceFromDeadZone();
double mouse1 = 0;
double mouse2 = 0;
double sumDist = buttonslot->getMouseDistance();
JoyMouseCurve currentCurve = getMouseCurve();
switch (currentCurve)
{
case LinearCurve:
{
break;
}
case QuadraticCurve:
{
difference = difference * difference;
break;
}
case CubicCurve:
{
difference = difference * difference * difference;
break;
}
case QuadraticExtremeCurve:
{
double temp = difference;
difference = difference * difference;
difference = (temp >= 0.95) ? (difference * 1.5) : difference;
break;
}
case PowerCurve:
{
double tempsensitive = qMin(qMax(sensitivity, 1.0e-3), 1.0e+3);
double temp = qMin(qMax(pow(difference, 1.0 / tempsensitive), 0.0), 1.0);
difference = temp;
break;
}
case EnhancedPrecisionCurve:
{
// Perform different forms of acceleration depending on
// the range of the element from its assigned dead zone.
// Useful for more precise controls with an axis.
double temp = difference;
if (temp <= 0.4)
{
// Low slope value for really slow acceleration
difference = difference * 0.37;
}
else if (temp <= 0.75)
{
// Perform Linear accleration with an appropriate
// offset.
difference = difference - 0.252;
}
else if (temp > 0.75)
{
// Perform mouse acceleration. Make up the difference
// due to the previous two segments. Maxes out at 1.0.
difference = (difference * 2.008) - 1.008;
}
break;
}
case EasingQuadraticCurve:
case EasingCubicCurve:
{
// Perform different forms of acceleration depending on
// the range of the element from its assigned dead zone.
// Useful for more precise controls with an axis.
double temp = difference;
if (temp <= 0.4)
{
// Low slope value for really slow acceleration
difference = difference * 0.38;
// Out of high end. Reset easing status.
if (buttonslot->isEasingActive())
{
buttonslot->setEasingStatus(false);
buttonslot->getEasingTime()->restart();
}
}
else if (temp <= 0.75)
{
// Perform Linear accleration with an appropriate
// offset.
difference = difference - 0.248;
// Out of high end. Reset easing status.
if (buttonslot->isEasingActive())
{
buttonslot->setEasingStatus(false);
buttonslot->getEasingTime()->restart();
}
}
else if (temp > 0.75)
{
// Gradually increase the mouse speed until the specified elapsed duration
// time has passed.
unsigned int easingElapsed = buttonslot->getEasingTime()->elapsed();
double easingDuration = this->easingDuration; // Time in seconds
if (!buttonslot->isEasingActive())
{
buttonslot->setEasingStatus(true);
buttonslot->getEasingTime()->restart();
easingElapsed = 0;
}
// Determine the multiplier to use for the current maximum mouse speed
// based on how much time has passed.
double elapsedDiff = 1.0;
if (easingDuration > 0.0 && (easingElapsed * .001) < easingDuration)
{
elapsedDiff = ((easingElapsed * .001) / easingDuration);
if (currentCurve == EasingQuadraticCurve)
{
// Range 1.0 - 1.5
elapsedDiff = (1.5 - 1.0) * elapsedDiff * elapsedDiff + 1.0;
}
else
{
// Range 1.0 - 1.5
elapsedDiff = (1.5 - 1.0) * (elapsedDiff * elapsedDiff
* elapsedDiff) + 1.0;
}
}
else
{
elapsedDiff = 1.5;
}
// Allow gradient control on the high end of an axis.
difference = elapsedDiff * difference;
// Range 0.502 - 1.5
difference = difference * 1.33067 - 0.496005;
}
break;
}
}
double distance = 0;
difference = (mouseSpeedModifier == 1.0) ? difference : (difference * mouseSpeedModifier);
double mintravel = minMouseDistanceAccelThreshold * 0.01;
double minstop = qMax(0.05, mintravel);
//double currentTravel = getAccelerationDistance() - lastAccelerationDistance;
// Last check ensures that acceleration is only applied for the same direction.
if (extraAccelerationEnabled && isPartRealAxis() &&
fabs(getAccelerationDistance() - lastAccelerationDistance) >= mintravel &&
(getAccelerationDistance() - lastAccelerationDistance >= 0) == (getAccelerationDistance() >= 0))
{
double magfactor = extraAccelerationMultiplier;
double minfactor = qMax((DEFAULTSTARTACCELMULTIPLIER * 0.001) + 1.0, magfactor * (startAccelMultiplier * 0.01));
double maxtravel = maxMouseDistanceAccelThreshold * 0.01;
double slope = (magfactor - minfactor)/(maxtravel - mintravel);
double intercept = minfactor - (slope * mintravel);
double intermediateTravel = qMin(maxtravel, fabs(getAccelerationDistance() - lastAccelerationDistance));
if (currentAccelMulti > 1.0 && oldAccelMulti == 0.0)
{
intermediateTravel = qMin(maxtravel, intermediateTravel + mintravel);
}
double currentAccelMultiTemp = (slope * intermediateTravel + intercept);
if (extraAccelCurve == EaseOutSineCurve)
{
double getMultiDiff2 = ((currentAccelMultiTemp - minfactor) / (extraAccelerationMultiplier - minfactor));
currentAccelMultiTemp = (extraAccelerationMultiplier - minfactor) * sin(getMultiDiff2 * (PI/2.0)) + minfactor;
}
else if (extraAccelCurve == EaseOutQuadAccelCurve)
{
double getMultiDiff2 = ((currentAccelMultiTemp - minfactor) / (extraAccelerationMultiplier - minfactor));
currentAccelMultiTemp = -(extraAccelerationMultiplier - minfactor) * (getMultiDiff2 * (getMultiDiff2 - 2)) + minfactor;
}
else if (extraAccelCurve == EaseOutCubicAccelCurve)
{
double getMultiDiff = ((currentAccelMultiTemp - minfactor) / (extraAccelerationMultiplier - minfactor)) - 1;
currentAccelMultiTemp = (extraAccelerationMultiplier - minfactor) * ((getMultiDiff) * (getMultiDiff) * (getMultiDiff) + 1) + minfactor;
}
difference = difference * currentAccelMultiTemp;
currentAccelMulti = currentAccelMultiTemp;
updateOldAccelMulti = currentAccelMulti;
accelTravel = intermediateTravel;
accelExtraDurationTime.restart();
}
else if (extraAccelerationEnabled && isPartRealAxis() && accelDuration > 0.0 &&
currentAccelMulti > 0.0 &&
fabs(getAccelerationDistance() - startingAccelerationDistance) < minstop)
{
//qDebug() << "Keep Trying: " << fabs(getAccelerationDistance() - lastAccelerationDistance);
//qDebug() << "MIN TRAVEL: " << mintravel;
updateStartingMouseDistance = true;
double magfactor = extraAccelerationMultiplier;
double minfactor = qMax((DEFAULTSTARTACCELMULTIPLIER * 0.001) + 1.0, magfactor * (startAccelMultiplier * 0.01));
double maxtravel = maxMouseDistanceAccelThreshold * 0.01;
double slope = (magfactor - minfactor)/(maxtravel - mintravel);
double intercept = minfactor - (slope * mintravel);
unsigned int elapsedElapsed = accelExtraDurationTime.elapsed();
double intermediateTravel = accelTravel;
if ((getAccelerationDistance() - startingAccelerationDistance >= 0) != (getAccelerationDistance() >= 0))
{
// Travelling towards dead zone. Decrease acceleration and duration.
intermediateTravel = qMax(intermediateTravel - fabs(getAccelerationDistance() - startingAccelerationDistance), mintravel);
}
// Linear case
double currentAccelMultiTemp = (slope * intermediateTravel + intercept);
double elapsedDuration = accelDuration *
((currentAccelMultiTemp - minfactor) / (extraAccelerationMultiplier - minfactor));
if (extraAccelCurve == EaseOutSineCurve)
{
double multiDiff = ((currentAccelMultiTemp - minfactor) / (extraAccelerationMultiplier - minfactor));
double temp = sin(multiDiff * (PI/2.0));
elapsedDuration = accelDuration * temp + 0;
currentAccelMultiTemp = (extraAccelerationMultiplier - minfactor) * sin(multiDiff * (PI/2.0)) + minfactor;
}
else if (extraAccelCurve == EaseOutQuadAccelCurve)
{
double getMultiDiff2 = ((currentAccelMultiTemp - minfactor) / (extraAccelerationMultiplier - minfactor));
double temp = (getMultiDiff2 * (getMultiDiff2 - 2));
elapsedDuration = -accelDuration * temp + 0;
currentAccelMultiTemp = -(extraAccelerationMultiplier - minfactor) * temp + minfactor;
}
else if (extraAccelCurve == EaseOutCubicAccelCurve)
{
double getMultiDiff = ((currentAccelMultiTemp - minfactor) / (extraAccelerationMultiplier - minfactor)) - 1;
double temp = ((getMultiDiff) * (getMultiDiff) * (getMultiDiff) + 1);
elapsedDuration = accelDuration * temp + 0;
currentAccelMultiTemp = (extraAccelerationMultiplier - minfactor) * temp + minfactor;
}
double tempAccel = currentAccelMultiTemp;
double elapsedDiff = 1.0;
if (elapsedDuration > 0.0 && (elapsedElapsed * 0.001) < elapsedDuration)
{
elapsedDiff = ((elapsedElapsed * 0.001) / elapsedDuration);
elapsedDiff = (1.0 - tempAccel) * (elapsedDiff * elapsedDiff * elapsedDiff) + tempAccel;
difference = elapsedDiff * difference;
// As acceleration is applied, do not update last
// distance values when not necessary.
updateStartingMouseDistance = false;
updateOldAccelMulti = currentAccelMulti;
}
else
{
elapsedDiff = 1.0;
currentAccelMulti = 0.0;
updateOldAccelMulti = 0.0;
accelTravel = 0.0;
}
}
else if (extraAccelerationEnabled && isPartRealAxis())
{
currentAccelMulti = 0.0;
updateStartingMouseDistance = true;
oldAccelMulti = updateOldAccelMulti = 0.0;
accelTravel = 0.0;
}
sumDist += difference * (mousespeed * JoyButtonSlot::JOYSPEED * timeElapsed) * 0.001;
//sumDist = difference * (nanoTimeElapsed * 0.000000001) * mousespeed * JoyButtonSlot::JOYSPEED;
distance = sumDist;
if (mousedirection == JoyButtonSlot::MouseRight)
{
mouse1 = distance;
}
else if (mousedirection == JoyButtonSlot::MouseLeft)
{
mouse1 = -distance;
}
else if (mousedirection == JoyButtonSlot::MouseDown)
{
mouse2 = distance;
}
else if (mousedirection == JoyButtonSlot::MouseUp)
{
mouse2 = -distance;
}
mouseCursorInfo infoX;
infoX.code = mouse1;
infoX.slot = buttonslot;
cursorXSpeeds.append(infoX);
mouseCursorInfo infoY;
infoY.code = mouse2;
infoY.slot = buttonslot;
cursorYSpeeds.append(infoY);
sumDist = 0;
buttonslot->setDistance(sumDist);
}
else if (mousemode == JoyButton::MouseSpring)
{
double mouse1 = -2.0;
double mouse2 = -2.0;
double difference = getMouseDistanceFromDeadZone();
if (mousedirection == JoyButtonSlot::MouseRight)
{
mouse1 = difference;
if (mouseHelper.getFirstSpringStatus())
{
mouse2 = 0.0;
mouseHelper.setFirstSpringStatus(false);
}
}
else if (mousedirection == JoyButtonSlot::MouseLeft)
{
mouse1 = -difference;
if (mouseHelper.getFirstSpringStatus())
{
mouse2 = 0.0;
mouseHelper.setFirstSpringStatus(false);
}
}
else if (mousedirection == JoyButtonSlot::MouseDown)
{
if (mouseHelper.getFirstSpringStatus())
{
mouse1 = 0.0;
mouseHelper.setFirstSpringStatus(false);
}
mouse2 = difference;
}
else if (mousedirection == JoyButtonSlot::MouseUp)
{
if (mouseHelper.getFirstSpringStatus())
{
mouse1 = 0.0;
mouseHelper.setFirstSpringStatus(false);
}
mouse2 = -difference;
}
PadderCommon::springModeInfo infoX;
infoX.displacementX = mouse1;
infoX.springDeadX = 0.0;
infoX.width = springWidth;
infoX.height = springHeight;
infoX.relative = relativeSpring;
infoX.screen = springModeScreen;
springXSpeeds.append(infoX);
PadderCommon::springModeInfo infoY;
infoY.displacementY = mouse2;
infoY.springDeadY = 0.0;
infoY.width = springWidth;
infoY.height = springHeight;
infoY.relative = relativeSpring;
infoY.screen = springModeScreen;
springYSpeeds.append(infoY);
mouseInterval->restart();
}
tempQueue.enqueue(buttonslot);
}
if (!mouseEventQueue.isEmpty() && !singleShot)
{
buttonslot = mouseEventQueue.dequeue();
}
else
{
buttonslot = 0;
}
}
if (!tempQueue.isEmpty())
{
while (!tempQueue.isEmpty())
{
JoyButtonSlot *tempslot = tempQueue.dequeue();
mouseEventQueue.enqueue(tempslot);
}
}
}
}
void JoyButton::wheelEventVertical()
{
JoyButtonSlot *buttonslot = 0;
if (currentWheelVerticalEvent)
{
buttonslot = currentWheelVerticalEvent;
}
if (buttonslot && wheelSpeedY != 0)
{
bool isActive = activeSlots.contains(buttonslot);
if (isActive)
{
sendevent(buttonslot, true);
sendevent(buttonslot, false);
mouseWheelVerticalEventQueue.enqueue(buttonslot);
mouseWheelVerticalEventTimer.start(1000 / wheelSpeedY);
}
else
{
mouseWheelVerticalEventTimer.stop();
}
}
else if (!mouseWheelVerticalEventQueue.isEmpty() && wheelSpeedY != 0)
{
QQueue<JoyButtonSlot*> tempQueue;
while (!mouseWheelVerticalEventQueue.isEmpty())
{
buttonslot = mouseWheelVerticalEventQueue.dequeue();
bool isActive = activeSlots.contains(buttonslot);
if (isActive)
{
sendevent(buttonslot, true);
sendevent(buttonslot, false);
tempQueue.enqueue(buttonslot);
}
}
if (!tempQueue.isEmpty())
{
mouseWheelVerticalEventQueue = tempQueue;
mouseWheelVerticalEventTimer.start(1000 / wheelSpeedY);
}
else
{
mouseWheelVerticalEventTimer.stop();
}
}
else
{
mouseWheelVerticalEventTimer.stop();
}
}
void JoyButton::wheelEventHorizontal()
{
JoyButtonSlot *buttonslot = 0;
if (currentWheelHorizontalEvent)
{
buttonslot = currentWheelHorizontalEvent;
}
if (buttonslot && wheelSpeedX != 0)
{
bool isActive = activeSlots.contains(buttonslot);
if (isActive)
{
sendevent(buttonslot, true);
sendevent(buttonslot, false);
mouseWheelHorizontalEventQueue.enqueue(buttonslot);
mouseWheelHorizontalEventTimer.start(1000 / wheelSpeedX);
}
else
{
mouseWheelHorizontalEventTimer.stop();
}
}
else if (!mouseWheelHorizontalEventQueue.isEmpty() && wheelSpeedX != 0)
{
QQueue<JoyButtonSlot*> tempQueue;
while (!mouseWheelHorizontalEventQueue.isEmpty())
{
buttonslot = mouseWheelHorizontalEventQueue.dequeue();
bool isActive = activeSlots.contains(buttonslot);
if (isActive)
{
sendevent(buttonslot, true);
sendevent(buttonslot, false);
tempQueue.enqueue(buttonslot);
}
}
if (!tempQueue.isEmpty())
{
mouseWheelHorizontalEventQueue = tempQueue;
mouseWheelHorizontalEventTimer.start(1000 / wheelSpeedX);
}
else
{
mouseWheelHorizontalEventTimer.stop();
}
}
else
{
mouseWheelHorizontalEventTimer.stop();
}
}
void JoyButton::setUseTurbo(bool useTurbo)
{
bool initialState = this->useTurbo;
if (useTurbo != this->useTurbo)
{
if (useTurbo && this->containsSequence())
{
this->useTurbo = false;
}
else
{
this->useTurbo = useTurbo;
}
if (initialState != this->useTurbo)
{
emit turboChanged(this->useTurbo);
emit propertyUpdated();
if (this->useTurbo && this->turboInterval == 0)
{
this->setTurboInterval(ENABLEDTURBODEFAULT);
}
}
}
}
bool JoyButton::isUsingTurbo()
{
return useTurbo;
}
QString JoyButton::getXmlName()
{
return this->xmlName;
}
void JoyButton::readConfig(QXmlStreamReader *xml)
{
if (xml->isStartElement() && xml->name() == getXmlName())
{
xml->readNextStartElement();
while (!xml->atEnd() && (!xml->isEndElement() && xml->name() != getXmlName()))
{
bool found = readButtonConfig(xml);
if (!found)
{
xml->skipCurrentElement();
}
else
{
buildActiveZoneSummaryString();
}
xml->readNextStartElement();
}
}
}
void JoyButton::writeConfig(QXmlStreamWriter *xml)
{
if (!isDefault())
{
xml->writeStartElement(getXmlName());
xml->writeAttribute("index", QString::number(getRealJoyNumber()));
if (toggle != DEFAULTTOGGLE)
{
xml->writeTextElement("toggle", toggle ? "true" : "false");
}
if (turboInterval != DEFAULTTURBOINTERVAL)
{
xml->writeTextElement("turbointerval", QString::number(turboInterval));
}
if (currentTurboMode != DEFAULTTURBOMODE)
{
if (currentTurboMode == GradientTurbo)
{
xml->writeTextElement("turbomode", "gradient");
}
else if (currentTurboMode == PulseTurbo)
{
xml->writeTextElement("turbomode", "pulse");
}
}
if (useTurbo != DEFAULTUSETURBO)
{
xml->writeTextElement("useturbo", useTurbo ? "true" : "false");
}
if (mouseSpeedX != DEFAULTMOUSESPEEDX)
{
xml->writeTextElement("mousespeedx", QString::number(mouseSpeedX));
}
if (mouseSpeedY != DEFAULTMOUSESPEEDY)
{
xml->writeTextElement("mousespeedy", QString::number(mouseSpeedY));
}
if (mouseMode != DEFAULTMOUSEMODE)
{
if (mouseMode == MouseCursor)
{
xml->writeTextElement("mousemode", "cursor");
}
else if (mouseMode == MouseSpring)
{
xml->writeTextElement("mousemode", "spring");
xml->writeTextElement("mousespringwidth", QString::number(springWidth));
xml->writeTextElement("mousespringheight", QString::number(springHeight));
}
}
if (mouseCurve != DEFAULTMOUSECURVE)
{
if (mouseCurve == LinearCurve)
{
xml->writeTextElement("mouseacceleration", "linear");
}
else if (mouseCurve == QuadraticCurve)
{
xml->writeTextElement("mouseacceleration", "quadratic");
}
else if (mouseCurve == CubicCurve)
{
xml->writeTextElement("mouseacceleration", "cubic");
}
else if (mouseCurve == QuadraticExtremeCurve)
{
xml->writeTextElement("mouseacceleration", "quadratic-extreme");
}
else if (mouseCurve == PowerCurve)
{
xml->writeTextElement("mouseacceleration", "power");
xml->writeTextElement("mousesensitivity", QString::number(sensitivity));
}
else if (mouseCurve == EnhancedPrecisionCurve)
{
xml->writeTextElement("mouseacceleration", "precision");
}
else if (mouseCurve == EasingQuadraticCurve)
{
xml->writeTextElement("mouseacceleration", "easing-quadratic");
}
else if (mouseCurve == EasingCubicCurve)
{
xml->writeTextElement("mouseacceleration", "easing-cubic");
}
}
if (wheelSpeedX != DEFAULTWHEELX)
{
xml->writeTextElement("wheelspeedx", QString::number(wheelSpeedX));
}
if (wheelSpeedY != DEFAULTWHEELY)
{
xml->writeTextElement("wheelspeedy", QString::number(wheelSpeedY));
}
if (!isModifierButton())
{
if (setSelectionCondition != SetChangeDisabled)
{
xml->writeTextElement("setselect", QString::number(setSelection+1));
QString temptext;
if (setSelectionCondition == SetChangeOneWay)
{
temptext = "one-way";
}
else if (setSelectionCondition == SetChangeTwoWay)
{
temptext = "two-way";
}
else if (setSelectionCondition == SetChangeWhileHeld)
{
temptext = "while-held";
}
xml->writeTextElement("setselectcondition", temptext);
}
}
if (!actionName.isEmpty())
{
xml->writeTextElement("actionname", actionName);
}
if (cycleResetActive)
{
xml->writeTextElement("cycleresetactive", "true");
}
if (cycleResetInterval >= MINCYCLERESETTIME)
{
xml->writeTextElement("cycleresetinterval", QString::number(cycleResetInterval));
}
if (relativeSpring == true)
{
xml->writeTextElement("relativespring", "true");
}
if (easingDuration != DEFAULTEASINGDURATION)
{
xml->writeTextElement("easingduration", QString::number(easingDuration));
}
if (extraAccelerationEnabled)
{
xml->writeTextElement("extraacceleration", "true");
}
if (extraAccelerationMultiplier != DEFAULTEXTRACCELVALUE)
{
xml->writeTextElement("accelerationmultiplier", QString::number(extraAccelerationMultiplier));
}
if (startAccelMultiplier != DEFAULTSTARTACCELMULTIPLIER)
{
xml->writeTextElement("startaccelmultiplier", QString::number(startAccelMultiplier));
}
if (minMouseDistanceAccelThreshold != DEFAULTMINACCELTHRESHOLD)
{
xml->writeTextElement("minaccelthreshold", QString::number(minMouseDistanceAccelThreshold));
}
if (maxMouseDistanceAccelThreshold != DEFAULTMAXACCELTHRESHOLD)
{
xml->writeTextElement("maxaccelthreshold", QString::number(maxMouseDistanceAccelThreshold));
}
if (accelDuration != DEFAULTACCELEASINGDURATION)
{
xml->writeTextElement("accelextraduration", QString::number(accelDuration));
}
if (springDeadCircleMultiplier != DEFAULTSPRINGRELEASERADIUS)
{
xml->writeTextElement("springreleaseradius", QString::number(springDeadCircleMultiplier));
}
if (extraAccelCurve != DEFAULTEXTRAACCELCURVE)
{
QString temp;
if (extraAccelCurve == LinearAccelCurve)
{
temp = "linear";
}
else if (extraAccelCurve == EaseOutSineCurve)
{
temp = "easeoutsine";
}
else if (extraAccelCurve == EaseOutQuadAccelCurve)
{
temp = "easeoutquad";
}
else if (extraAccelCurve == EaseOutCubicAccelCurve)
{
temp = "easeoutcubic";
}
if (!temp.isEmpty())
{
xml->writeTextElement("extraaccelerationcurve", temp);
}
}
// Write information about assigned slots.
if (!assignments.isEmpty())
{
xml->writeStartElement("slots");
QListIterator<JoyButtonSlot*> iter(assignments);
while (iter.hasNext())
{
JoyButtonSlot *buttonslot = iter.next();
buttonslot->writeConfig(xml);
}
xml->writeEndElement();
}
xml->writeEndElement();
}
}
bool JoyButton::readButtonConfig(QXmlStreamReader *xml)
{
bool found = false;
if (xml->name() == "toggle" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
if (temptext == "true")
{
this->setToggle(true);
}
}
else if (xml->name() == "turbointerval" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
int tempchoice = temptext.toInt();
this->setTurboInterval(tempchoice);
}
else if (xml->name() == "turbomode" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
if (temptext == "normal")
{
this->setTurboMode(NormalTurbo);
}
else if (temptext == "gradient")
{
this->setTurboMode(GradientTurbo);
}
else if (temptext == "pulse")
{
this->setTurboMode(PulseTurbo);
}
}
else if (xml->name() == "useturbo" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
if (temptext == "true")
{
this->setUseTurbo(true);
}
}
else if (xml->name() == "mousespeedx" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
int tempchoice = temptext.toInt();
this->setMouseSpeedX(tempchoice);
}
else if (xml->name() == "mousespeedy" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
int tempchoice = temptext.toInt();
this->setMouseSpeedY(tempchoice);
}
else if (xml->name() == "cycleresetactive" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
if (temptext == "true")
{
this->setCycleResetStatus(true);
}
}
else if (xml->name() == "cycleresetinterval" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
unsigned int tempchoice = temptext.toInt();
if (tempchoice >= MINCYCLERESETTIME)
{
this->setCycleResetTime(tempchoice);
}
}
else if (xml->name() == "slots" && xml->isStartElement())
{
found = true;
xml->readNextStartElement();
while (!xml->atEnd() && (!xml->isEndElement() && xml->name() != "slots"))
{
if (xml->name() == "slot" && xml->isStartElement())
{
JoyButtonSlot *buttonslot = new JoyButtonSlot(this);
buttonslot->readConfig(xml);
bool validSlot = buttonslot->isValidSlot();
if (validSlot)
{
bool inserted = insertAssignedSlot(buttonslot, false);
if (!inserted)
{
delete buttonslot;
buttonslot = 0;
}
}
else
{
delete buttonslot;
buttonslot = 0;
}
}
else
{
xml->skipCurrentElement();
}
xml->readNextStartElement();
}
}
else if (xml->name() == "setselect" && xml->isStartElement())
{
if (!isModifierButton())
{
found = true;
QString temptext = xml->readElementText();
int tempchoice = temptext.toInt();
if (tempchoice >= 0 && tempchoice <= InputDevice::NUMBER_JOYSETS)
{
this->setChangeSetSelection(tempchoice - 1, false);
}
}
}
else if (xml->name() == "setselectcondition" && xml->isStartElement())
{
if (!isModifierButton())
{
found = true;
QString temptext = xml->readElementText();
SetChangeCondition tempcondition = SetChangeDisabled;
if (temptext == "one-way")
{
tempcondition = SetChangeOneWay;
}
else if (temptext == "two-way")
{
tempcondition = SetChangeTwoWay;
}
else if (temptext == "while-held")
{
tempcondition = SetChangeWhileHeld;
}
if (tempcondition != SetChangeDisabled)
{
this->setChangeSetCondition(tempcondition, false, false);
}
}
}
else if (xml->name() == "mousemode" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
if (temptext == "cursor")
{
setMouseMode(MouseCursor);
}
else if (temptext == "spring")
{
setMouseMode(MouseSpring);
}
}
else if (xml->name() == "mouseacceleration" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
if (temptext == "linear")
{
setMouseCurve(LinearCurve);
}
else if (temptext == "quadratic")
{
setMouseCurve(QuadraticCurve);
}
else if (temptext == "cubic")
{
setMouseCurve(CubicCurve);
}
else if (temptext == "quadratic-extreme")
{
setMouseCurve(QuadraticExtremeCurve);
}
else if (temptext == "power")
{
setMouseCurve(PowerCurve);
}
else if (temptext == "precision")
{
setMouseCurve(EnhancedPrecisionCurve);
}
else if (temptext == "easing-quadratic")
{
setMouseCurve(EasingQuadraticCurve);
}
else if (temptext == "easing-cubic")
{
setMouseCurve(EasingCubicCurve);
}
}
else if (xml->name() == "mousespringwidth" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
int tempchoice = temptext.toInt();
setSpringWidth(tempchoice);
}
else if (xml->name() == "mousespringheight" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
int tempchoice = temptext.toInt();
setSpringHeight(tempchoice);
}
else if (xml->name() == "mousesensitivity" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
double tempchoice = temptext.toDouble();
setSensitivity(tempchoice);
}
else if (xml->name() == "actionname" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
if (!temptext.isEmpty())
{
setActionName(temptext);
}
}
else if (xml->name() == "wheelspeedx" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
int tempchoice = temptext.toInt();
setWheelSpeedX(tempchoice);
}
else if (xml->name() == "wheelspeedy" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
int tempchoice = temptext.toInt();
setWheelSpeedY(tempchoice);
}
else if (xml->name() == "relativespring" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
if (temptext == "true")
{
this->setSpringRelativeStatus(true);
}
}
else if (xml->name() == "easingduration" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
double tempchoice = temptext.toDouble();
setEasingDuration(tempchoice);
}
else if (xml->name() == "extraacceleration" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
if (temptext == "true")
{
setExtraAccelerationStatus(true);
}
}
else if (xml->name() == "accelerationmultiplier" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
double tempchoice = temptext.toDouble();
setExtraAccelerationMultiplier(tempchoice);
}
else if (xml->name() == "startaccelmultiplier" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
double tempchoice = temptext.toDouble();
setStartAccelMultiplier(tempchoice);
}
else if (xml->name() == "minaccelthreshold" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
double tempchoice = temptext.toDouble();
setMinAccelThreshold(tempchoice);
}
else if (xml->name() == "maxaccelthreshold" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
double tempchoice = temptext.toDouble();
setMaxAccelThreshold(tempchoice);
}
else if (xml->name() == "accelextraduration" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
double tempchoice = temptext.toDouble();
setAccelExtraDuration(tempchoice);
}
else if (xml->name() == "extraaccelerationcurve" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
JoyExtraAccelerationCurve tempcurve = DEFAULTEXTRAACCELCURVE;
if (temptext == "linear")
{
tempcurve = LinearAccelCurve;
}
else if (temptext == "easeoutsine")
{
tempcurve = EaseOutSineCurve;
}
else if (temptext == "easeoutquad")
{
tempcurve = EaseOutQuadAccelCurve;
}
else if (temptext == "easeoutcubic")
{
tempcurve = EaseOutCubicAccelCurve;
}
setExtraAccelerationCurve(tempcurve);
}
else if (xml->name() == "springreleaseradius" && xml->isStartElement())
{
found = true;
QString temptext = xml->readElementText();
int tempchoice = temptext.toInt();
if (!relativeSpring)
{
setSpringDeadCircleMultiplier(tempchoice);
}
}
return found;
}
QString JoyButton::getName(bool forceFullFormat, bool displayNames)
{
QString newlabel = getPartialName(forceFullFormat, displayNames);
newlabel.append(": ");
if (!actionName.isEmpty() && displayNames)
{
newlabel.append(actionName);
}
else
{
newlabel.append(getCalculatedActiveZoneSummary());
}
return newlabel;
}
QString JoyButton::getPartialName(bool forceFullFormat, bool displayNames)
{
QString temp;
if (!buttonName.isEmpty() && displayNames)
{
if (forceFullFormat)
{
temp.append(tr("Button")).append(" ");
}
temp.append(buttonName);
}
else if (!defaultButtonName.isEmpty())
{
if (forceFullFormat)
{
temp.append(tr("Button")).append(" ");
}
temp.append(defaultButtonName);
}
else
{
temp.append(tr("Button")).append(" ").append(QString::number(getRealJoyNumber()));
}
return temp;
}
/**
* @brief Generate a string representing a summary of the slots currently
* assigned to a button
* @return String of currently assigned slots
*/
QString JoyButton::getSlotsSummary()
{
QString newlabel;
int slotCount = assignments.size();
if (slotCount > 0)
{
QListIterator<JoyButtonSlot*> iter(assignments);
QStringList stringlist;
int i = 0;
while (iter.hasNext())
{
JoyButtonSlot *slot = iter.next();
stringlist.append(slot->getSlotString());
i++;
if (i > 4 && iter.hasNext())
{
stringlist.append(" ...");
iter.toBack();
}
}
newlabel = stringlist.join(", ");
}
else
{
newlabel = newlabel.append(tr("[NO KEY]"));
}
return newlabel;
}
/**
* @brief Generate a string that represents slots that will be activated or
* slots that are currently active if a button is pressed
* @return String of currently applicable slots for a button
*/
QString JoyButton::getActiveZoneSummary()
{
QList<JoyButtonSlot*> tempList = getActiveZoneList();
QString temp = buildActiveZoneSummary(tempList);
return temp;
}
QString JoyButton::getCalculatedActiveZoneSummary()
{
activeZoneStringLock.lockForRead();
QString temp = this->activeZoneString;
activeZoneStringLock.unlock();
return temp;
}
/**
* @brief Generate active zone string and notify other objects.
*/
void JoyButton::buildActiveZoneSummaryString()
{
activeZoneStringLock.lockForWrite();
this->activeZoneString = getActiveZoneSummary();
activeZoneStringLock.unlock();
emit activeZoneChanged();
}
/**
* @brief Generate active zone string but do not notify any other object.
*/
void JoyButton::localBuildActiveZoneSummaryString()
{
activeZoneStringLock.lockForWrite();
this->activeZoneString = getActiveZoneSummary();
activeZoneStringLock.unlock();
}
QString JoyButton::buildActiveZoneSummary(QList<JoyButtonSlot *> &tempList)
{
QString newlabel;
QListIterator<JoyButtonSlot*> iter(tempList);
QStringList stringlist;
int i = 0;
bool slotsActive = !activeSlots.isEmpty();
if (setSelectionCondition == SetChangeOneWay)
{
newlabel.append(tr("[Set %1 1W]").arg(setSelection+1));
if (iter.hasNext())
{
newlabel.append(" ");
}
}
else if (setSelectionCondition == SetChangeTwoWay)
{
newlabel = newlabel.append(tr("[Set %1 2W]").arg(setSelection+1));
if (iter.hasNext())
{
newlabel.append(" ");
}
}
if (setSelectionCondition == SetChangeWhileHeld)
{
newlabel.append(tr("[Set %1 WH]").arg(setSelection+1));
}
else if (iter.hasNext())
{
bool behindHold = false;
while (iter.hasNext())
{
JoyButtonSlot *slot = iter.next();
JoyButtonSlot::JoySlotInputAction mode = slot->getSlotMode();
switch (mode)
{
case JoyButtonSlot::JoyKeyboard:
case JoyButtonSlot::JoyMouseButton:
case JoyButtonSlot::JoyMouseMovement:
{
QString temp = slot->getSlotString();
if (behindHold)
{
temp.prepend("[H] ");
behindHold = false;
}
stringlist.append(temp);
i++;
break;
}
case JoyButtonSlot::JoyKeyPress:
{
// Skip slot if a press time slot was inserted.
break;
}
case JoyButtonSlot::JoyHold:
{
if (!slotsActive && i == 0)
{
// If button is not active and first slot is a hold,
// keep processing slots but take note of the hold.
behindHold = true;
}
else
{
// Move iter to back so loop will end.
iter.toBack();
}
break;
}
case JoyButtonSlot::JoyLoadProfile:
case JoyButtonSlot::JoySetChange:
case JoyButtonSlot::JoyTextEntry:
case JoyButtonSlot::JoyExecute:
{
QString temp = slot->getSlotString();
if (behindHold)
{
temp.prepend("[H] ");
behindHold = false;
}
stringlist.append(temp);
i++;
break;
}
/*case JoyButtonSlot::JoyRelease:
{
if (!currentRelease)
{
findReleaseEventIterEnd(iter);
}
break;
}
*/
/*case JoyButtonSlot::JoyDistance:
{
iter->toBack();
break;
}
*/
case JoyButtonSlot::JoyDelay:
{
iter.toBack();
break;
}
case JoyButtonSlot::JoyCycle:
{
iter.toBack();
break;
}
}
if (i > 4 && iter.hasNext())
{
stringlist.append(" ...");
iter.toBack();
}
}
newlabel.append(stringlist.join(", "));
}
else if (setSelectionCondition == SetChangeDisabled)
{
newlabel.append(tr("[NO KEY]"));
}
return newlabel;
}
QList<JoyButtonSlot*> JoyButton::getActiveZoneList()
{
QListIterator<JoyButtonSlot*> activeSlotsIter(activeSlots);
QListIterator<JoyButtonSlot*> assignmentsIter(assignments);
QListIterator<JoyButtonSlot*> *iter = 0;
QReadWriteLock *tempLock = 0;
activeZoneLock.lockForRead();
int numActiveSlots = activeSlots.size();
activeZoneLock.unlock();
if (numActiveSlots > 0)
{
tempLock = &activeZoneLock;
iter = &activeSlotsIter;
}
else
{
tempLock = &assignmentsLock;
iter = &assignmentsIter;
}
QReadLocker tempLocker(tempLock);
Q_UNUSED(tempLocker);
if (tempLock == &assignmentsLock)
{
if (previousCycle)
{
iter->findNext(previousCycle);
}
}
QList<JoyButtonSlot*> tempSlotList;
if (setSelectionCondition != SetChangeWhileHeld && iter->hasNext())
{
while (iter->hasNext())
{
JoyButtonSlot *slot = iter->next();
JoyButtonSlot::JoySlotInputAction mode = slot->getSlotMode();
switch (mode)
{
case JoyButtonSlot::JoyKeyboard:
case JoyButtonSlot::JoyMouseButton:
case JoyButtonSlot::JoyMouseMovement:
{
tempSlotList.append(slot);
break;
}
case JoyButtonSlot::JoyKeyPress:
case JoyButtonSlot::JoyHold:
case JoyButtonSlot::JoyLoadProfile:
case JoyButtonSlot::JoySetChange:
case JoyButtonSlot::JoyTextEntry:
case JoyButtonSlot::JoyExecute:
{
tempSlotList.append(slot);
break;
}
case JoyButtonSlot::JoyRelease:
{
if (!currentRelease)
{
findReleaseEventIterEnd(iter);
}
break;
}
case JoyButtonSlot::JoyDistance:
{
iter->toBack();
break;
}
case JoyButtonSlot::JoyCycle:
{
iter->toBack();
break;
}
}
}
}
return tempSlotList;
}
/**
* @brief Generate a string representing all the currently assigned slots for
* a button
* @return String representing all assigned slots for a button
*/
QString JoyButton::getSlotsString()
{
QString label;
if (assignments.size() > 0)
{
QListIterator<JoyButtonSlot*> iter(assignments);
QStringList stringlist;
while (iter.hasNext())
{
JoyButtonSlot *slot = iter.next();
stringlist.append(slot->getSlotString());
}
label = stringlist.join(", ");
}
else
{
label = label.append(tr("[NO KEY]"));
}
return label;
}
void JoyButton::setCustomName(QString name)
{
customName = name;
}
QString JoyButton::getCustomName()
{
return customName;
}
/**
* @brief Create new JoyButtonSlot with data provided and append the new slot
* an existing to the assignment list.
* @param Native virtual code being used.
* @param Mode of the slot.
* @return Whether the new slot was successfully added to the assignment list.
*/
bool JoyButton::setAssignedSlot(int code, JoyButtonSlot::JoySlotInputAction mode)
{
bool slotInserted = false;
JoyButtonSlot *slot = new JoyButtonSlot(code, mode, this);
if (slot->getSlotMode() == JoyButtonSlot::JoyDistance)
{
if (slot->getSlotCode() >= 1 && slot->getSlotCode() <= 100)
{
double tempDistance = getTotalSlotDistance(slot);
if (tempDistance <= 1.0)
{
assignmentsLock.lockForWrite();
assignments.append(slot);
assignmentsLock.unlock();
buildActiveZoneSummaryString();
slotInserted = true;
}
}
}
else if (slot->getSlotCode() >= 0)
{
assignmentsLock.lockForWrite();
assignments.append(slot);
assignmentsLock.unlock();
buildActiveZoneSummaryString();
slotInserted = true;
}
if (slotInserted)
{
checkTurboCondition(slot);
emit slotsChanged();
}
else
{
if (slot)
{
delete slot;
slot = 0;
}
}
return slotInserted;
}
/**
* @brief Create new JoyButtonSlot with data provided and append the new slot
* an existing to the assignment list.
* @param Native virtual code being used.
* @param Qt key alias used for abstracting native virtual code.
* @param Mode of the slot.
* @return Whether the new slot was successfully added to the assignment list.
*/
bool JoyButton::setAssignedSlot(int code, unsigned int alias,
JoyButtonSlot::JoySlotInputAction mode)
{
bool slotInserted = false;
JoyButtonSlot *slot = new JoyButtonSlot(code, alias, mode, this);
if (slot->getSlotMode() == JoyButtonSlot::JoyDistance)
{
if (slot->getSlotCode() >= 1 && slot->getSlotCode() <= 100)
{
double tempDistance = getTotalSlotDistance(slot);
if (tempDistance <= 1.0)
{
assignmentsLock.lockForWrite();
assignments.append(slot);
assignmentsLock.unlock();
buildActiveZoneSummaryString();
slotInserted = true;
}
}
}
else if (slot->getSlotCode() >= 0)
{
assignmentsLock.lockForWrite();
assignments.append(slot);
assignmentsLock.unlock();
buildActiveZoneSummaryString();
slotInserted = true;
}
if (slotInserted)
{
checkTurboCondition(slot);
emit slotsChanged();
}
else
{
if (slot)
{
delete slot;
slot = 0;
}
}
return slotInserted;
}
/**
* @brief Create new JoyButtonSlot with data provided and replace an existing
* slot in the assignment list if one exists.
* @param Native virtual code being used.
* @param Qt key alias used for abstracting native virtual code.
* @param Index number in the list.
* @param Mode of the slot.
* @return Whether the new slot was successfully added to the assignment list.
*/
bool JoyButton::setAssignedSlot(int code, unsigned int alias, int index,
JoyButtonSlot::JoySlotInputAction mode)
{
bool permitSlot = true;
JoyButtonSlot *slot = new JoyButtonSlot(code, alias, mode, this);
if (slot->getSlotMode() == JoyButtonSlot::JoyDistance)
{
if (slot->getSlotCode() >= 1 && slot->getSlotCode() <= 100)
{
double tempDistance = getTotalSlotDistance(slot);
if (tempDistance > 1.0)
{
permitSlot = false;
}
}
else
{
permitSlot = false;
}
}
else if (slot->getSlotCode() < 0)
{
permitSlot = false;
}
if (permitSlot)
{
assignmentsLock.lockForWrite();
if (index >= 0 && index < assignments.count())
{
// Insert slot and move existing slots.
JoyButtonSlot *temp = assignments.at(index);
if (temp)
{
delete temp;
temp = 0;
}
assignments.replace(index, slot);
}
else if (index >= assignments.count())
{
// Append code into a new slot
assignments.append(slot);
}
checkTurboCondition(slot);
assignmentsLock.unlock();
buildActiveZoneSummaryString();
emit slotsChanged();
}
else
{
if (slot)
{
delete slot;
slot = 0;
}
}
return permitSlot;
}
/**
* @brief Create new JoyButtonSlot with data provided and insert it into
* assignments list if it is valid.
* @param Native virtual code being used.
* @param Qt key alias used for abstracting native virtual code.
* @param Index number in the list.
* @param Mode of the slot.
* @return Whether the new slot was successfully added to the assignment list.
*/
bool JoyButton::insertAssignedSlot(int code, unsigned int alias, int index,
JoyButtonSlot::JoySlotInputAction mode)
{
bool permitSlot = true;
JoyButtonSlot *slot = new JoyButtonSlot(code, alias, mode, this);
if (slot->getSlotMode() == JoyButtonSlot::JoyDistance)
{
if (slot->getSlotCode() >= 1 && slot->getSlotCode() <= 100)
{
double tempDistance = getTotalSlotDistance(slot);
if (tempDistance > 1.0)
{
permitSlot = false;
}
}
else
{
permitSlot = false;
}
}
else if (slot->getSlotCode() < 0)
{
permitSlot = false;
}
if (permitSlot)
{
assignmentsLock.lockForWrite();
if (index >= 0 && index < assignments.count())
{
// Insert new slot into list. Move old slots if needed.
assignments.insert(index, slot);
}
else if (index >= assignments.count())
{
// Append new slot into list.
assignments.append(slot);
}
checkTurboCondition(slot);
assignmentsLock.unlock();
buildActiveZoneSummaryString();
emit slotsChanged();
}
else
{
if (slot)
{
delete slot;
slot = 0;
}
}
return permitSlot;
}
bool JoyButton::insertAssignedSlot(JoyButtonSlot *newSlot, bool updateActiveString)
{
bool permitSlot = false;
if (newSlot->getSlotMode() == JoyButtonSlot::JoyDistance)
{
if (newSlot->getSlotCode() >= 1 && newSlot->getSlotCode() <= 100)
{
double tempDistance = getTotalSlotDistance(newSlot);
if (tempDistance <= 1.0)
{
permitSlot = true;
}
}
}
else if (newSlot->getSlotMode() == JoyButtonSlot::JoyLoadProfile)
{
permitSlot = true;
}
else if (newSlot->getSlotMode() == JoyButtonSlot::JoyTextEntry &&
!newSlot->getTextData().isEmpty())
{
permitSlot = true;
}
else if (newSlot->getSlotMode() == JoyButtonSlot::JoyExecute &&
!newSlot->getTextData().isEmpty())
{
permitSlot = true;
}
else if (newSlot->getSlotCode() >= 0)
{
permitSlot = true;
}
if (permitSlot)
{
assignmentsLock.lockForWrite();
checkTurboCondition(newSlot);
assignments.append(newSlot);
assignmentsLock.unlock();
if (updateActiveString)
{
buildActiveZoneSummaryString();
}
emit slotsChanged();
}
return permitSlot;
}
bool JoyButton::setAssignedSlot(JoyButtonSlot *otherSlot, int index)
{
bool permitSlot = false;
JoyButtonSlot *newslot = new JoyButtonSlot(otherSlot, this);
if (newslot->getSlotMode() == JoyButtonSlot::JoyDistance)
{
if (newslot->getSlotCode() >= 1 && newslot->getSlotCode() <= 100)
{
double tempDistance = getTotalSlotDistance(newslot);
if (tempDistance <= 1.0)
{
permitSlot = true;
}
}
}
else if (newslot->getSlotMode() == JoyButtonSlot::JoyLoadProfile)
{
permitSlot = true;
}
else if (newslot->getSlotMode() == JoyButtonSlot::JoyTextEntry &&
!newslot->getTextData().isEmpty())
{
permitSlot = true;
}
else if (newslot->getSlotMode() == JoyButtonSlot::JoyExecute &&
!newslot->getTextData().isEmpty())
{
permitSlot = true;
}
else if (newslot->getSlotCode() >= 0)
{
permitSlot = true;
}
if (permitSlot)
{
assignmentsLock.lockForWrite();
checkTurboCondition(newslot);
if (index >= 0 && index < assignments.count())
{
// Slot already exists. Override code and place into desired slot
JoyButtonSlot *temp = assignments.at(index);
if (temp)
{
delete temp;
temp = 0;
//assignments.insert(index, temp);
}
assignments.replace(index, newslot);
}
else if (index >= assignments.count())
{
// Append code into a new slot
assignments.append(newslot);
}
assignmentsLock.unlock();
buildActiveZoneSummaryString();
emit slotsChanged();
}
else
{
delete newslot;
newslot = 0;
}
return permitSlot;
}
QList<JoyButtonSlot*>* JoyButton::getAssignedSlots()
{
QList<JoyButtonSlot*> *newassign = &assignments;
return newassign;
}
void JoyButton::setMouseSpeedX(int speed)
{
if (speed >= 1 && speed <= 300)
{
mouseSpeedX = speed;
emit propertyUpdated();
}
}
int JoyButton::getMouseSpeedX()
{
return mouseSpeedX;
}
void JoyButton::setMouseSpeedY(int speed)
{
if (speed >= 1 && speed <= 300)
{
mouseSpeedY = speed;
emit propertyUpdated();
}
}
int JoyButton::getMouseSpeedY()
{
return mouseSpeedY;
}
void JoyButton::setChangeSetSelection(int index, bool updateActiveString)
{
if (index >= -1 && index <= 7)
{
setSelection = index;
if (updateActiveString)
{
buildActiveZoneSummaryString();
}
emit propertyUpdated();
}
}
int JoyButton::getSetSelection()
{
return setSelection;
}
void JoyButton::setChangeSetCondition(SetChangeCondition condition,
bool passive, bool updateActiveString)
{
SetChangeCondition oldCondition = setSelectionCondition;
if (condition != setSelectionCondition && !passive)
{
if (condition == SetChangeWhileHeld || condition == SetChangeTwoWay)
{
// Set new condition
emit setAssignmentChanged(index, setSelection, condition);
}
else if (setSelectionCondition == SetChangeWhileHeld || setSelectionCondition == SetChangeTwoWay)
{
// Remove old condition
emit setAssignmentChanged(index, setSelection, SetChangeDisabled);
}
setSelectionCondition = condition;
}
else if (passive)
{
setSelectionCondition = condition;
}
if (setSelectionCondition == SetChangeDisabled)
{
setChangeSetSelection(-1);
}
if (setSelectionCondition != oldCondition)
{
if (updateActiveString)
{
buildActiveZoneSummaryString();
}
emit propertyUpdated();
}
}
JoyButton::SetChangeCondition JoyButton::getChangeSetCondition()
{
return setSelectionCondition;
}
bool JoyButton::getButtonState()
{
return isButtonPressed;
}
int JoyButton::getOriginSet()
{
return originset;
}
void JoyButton::pauseWaitEvent()
{
if (currentPause)
{
if (!isButtonPressedQueue.isEmpty() && createDeskTimer.isActive())
{
if (slotiter)
{
slotiter->toBack();
bool lastIgnoreSetState = ignoreSetQueue.last();
bool lastIsButtonPressed = isButtonPressedQueue.last();
ignoreSetQueue.clear();
isButtonPressedQueue.clear();
ignoreSetQueue.enqueue(lastIgnoreSetState);
isButtonPressedQueue.enqueue(lastIsButtonPressed);
currentPause = 0;
//JoyButtonSlot *oldCurrentRelease = currentRelease;
currentRelease = 0;
//createDeskTimer.stop();
releaseDeskTimer.stop();
pauseWaitTimer.stop();
slotiter->toFront();
if (previousCycle)
{
slotiter->findNext(previousCycle);
}
quitEvent = true;
keyPressHold.restart();
//waitForDeskEvent();
// Assuming that if this is the case, a pause from
// a release slot was previously active. setChangeTimer
// should not be active at this point.
//if (oldCurrentRelease && setChangeTimer.isActive())
//{
// setChangeTimer.stop();
//}
}
}
}
if (currentPause)
{
// If release timer is active, temporarily
// disable it
if (releaseDeskTimer.isActive())
{
releaseDeskTimer.stop();
}
if (inpauseHold.elapsed() < currentPause->getSlotCode())
{
int proposedInterval = currentPause->getSlotCode() - inpauseHold.elapsed();
proposedInterval = proposedInterval > 0 ? proposedInterval : 0;
int newTimerInterval = qMin(10, proposedInterval);
pauseWaitTimer.start(newTimerInterval);
}
else
{
pauseWaitTimer.stop();
createDeskTimer.stop();
currentPause = 0;
createDeskEvent();
// If release timer was disabled but if the button
// is not pressed, restart the release timer.
if (!releaseDeskTimer.isActive() && (isButtonPressedQueue.isEmpty() || !isButtonPressedQueue.last()))
{
waitForReleaseDeskEvent();
}
}
}
else
{
pauseWaitTimer.stop();
}
}
void JoyButton::checkForSetChange()
{
if (!ignoreSetQueue.isEmpty() && !isButtonPressedQueue.isEmpty())
{
bool tempFinalState = isButtonPressedQueue.last();
bool tempFinalIgnoreSetsState = ignoreSetQueue.last();
if (!tempFinalIgnoreSetsState)
{
if (!tempFinalState && setSelectionCondition == SetChangeOneWay && setSelection > -1)
{
// If either timer is currently active,
// stop the timer
if (createDeskTimer.isActive())
{
createDeskTimer.stop();
}
if (releaseDeskTimer.isActive())
{
releaseDeskTimer.stop();
}
isButtonPressedQueue.clear();
ignoreSetQueue.clear();
emit released(index);
emit setChangeActivated(setSelection);
}
else if (!tempFinalState && setSelectionCondition == SetChangeTwoWay && setSelection > -1)
{
// If either timer is currently active,
// stop the timer
if (createDeskTimer.isActive())
{
createDeskTimer.stop();
}
if (releaseDeskTimer.isActive())
{
releaseDeskTimer.stop();
}
isButtonPressedQueue.clear();
ignoreSetQueue.clear();
emit released(index);
emit setChangeActivated(setSelection);
}
else if (setSelectionCondition == SetChangeWhileHeld && setSelection > -1)
{
if (tempFinalState)
{
whileHeldStatus = true;
}
else if (!tempFinalState)
{
whileHeldStatus = false;
}
// If either timer is currently active,
// stop the timer
if (createDeskTimer.isActive())
{
createDeskTimer.stop();
}
if (releaseDeskTimer.isActive())
{
releaseDeskTimer.stop();
}
isButtonPressedQueue.clear();
ignoreSetQueue.clear();
emit released(index);
emit setChangeActivated(setSelection);
}
}
// Clear queue except for a press if it is last in
if (!isButtonPressedQueue.isEmpty())
{
isButtonPressedQueue.clear();
if (tempFinalState)
{
isButtonPressedQueue.enqueue(tempFinalState);
}
}
// Clear queue except for a press if it is last in
if (!ignoreSetQueue.isEmpty())
{
bool tempFinalIgnoreSetsState = ignoreSetQueue.last();
ignoreSetQueue.clear();
if (tempFinalState)
{
ignoreSetQueue.enqueue(tempFinalIgnoreSetsState);
}
}
}
}
void JoyButton::waitForDeskEvent()
{
if (quitEvent && !isButtonPressedQueue.isEmpty() && isButtonPressedQueue.last())
{
if (createDeskTimer.isActive())
{
keyPressTimer.stop();
createDeskTimer.stop();
releaseDeskTimer.stop();
createDeskEvent();
}
else
{
keyPressTimer.stop();
releaseDeskTimer.stop();
createDeskEvent();
}
/*else
{
createDeskTimer.start(0);
releaseDeskTimer.stop();
keyDelayHold.restart();
}*/
}
else if (!createDeskTimer.isActive())
{
#ifdef Q_CC_MSVC
createDeskTimer.start(5);
releaseDeskTimer.stop();
#else
createDeskTimer.start(0);
releaseDeskTimer.stop();
#endif
}
else if (createDeskTimer.isActive())
{
// Decrease timer interval of active timer.
createDeskTimer.start(0);
releaseDeskTimer.stop();
}
}
void JoyButton::waitForReleaseDeskEvent()
{
if (quitEvent && !keyPressTimer.isActive())
{
if (releaseDeskTimer.isActive())
{
releaseDeskTimer.stop();
}
createDeskTimer.stop();
keyPressTimer.stop();
releaseDeskEvent();
}
else if (!releaseDeskTimer.isActive())
{
#ifdef Q_CC_MSVC
releaseDeskTimer.start(1);
createDeskTimer.stop();
#else
releaseDeskTimer.start(1);
createDeskTimer.stop();
#endif
}
else if (releaseDeskTimer.isActive())
{
createDeskTimer.stop();
}
}
bool JoyButton::containsSequence()
{
bool result = false;
assignmentsLock.lockForRead();
QListIterator<JoyButtonSlot*> tempiter(assignments);
while (tempiter.hasNext())
{
JoyButtonSlot *slot = tempiter.next();
JoyButtonSlot::JoySlotInputAction mode = slot->getSlotMode();
if (mode == JoyButtonSlot::JoyPause ||
mode == JoyButtonSlot::JoyHold ||
mode == JoyButtonSlot::JoyDistance
)
{
result = true;
tempiter.toBack();
}
}
assignmentsLock.unlock();
return result;
}
void JoyButton::holdEvent()
{
if (currentHold)
{
bool currentlyPressed = false;
if (!isButtonPressedQueue.isEmpty())
{
currentlyPressed = isButtonPressedQueue.last();
}
// Activate hold event
if (currentlyPressed && buttonHold.elapsed() > currentHold->getSlotCode())
{
releaseActiveSlots();
currentHold = 0;
holdTimer.stop();
buttonHold.restart();
createDeskEvent();
}
// Elapsed time has not occurred
else if (currentlyPressed)
{
unsigned int holdTime = currentHold->getSlotCode();
int proposedInterval = holdTime - buttonHold.elapsed();
proposedInterval = proposedInterval > 0 ? proposedInterval : 0;
int newTimerInterval = qMin(10, proposedInterval);
holdTimer.start(newTimerInterval);
}
// Pre-emptive release
else
{
currentHold = 0;
holdTimer.stop();
if (slotiter)
{
findHoldEventEnd();
createDeskEvent();
}
}
}
else
{
holdTimer.stop();
}
}
void JoyButton::delayEvent()
{
if (currentDelay)
{
bool currentlyPressed = false;
if (!isButtonPressedQueue.isEmpty())
{
currentlyPressed = isButtonPressedQueue.last();
}
// Delay time has elapsed. Continue processing slots.
if (currentDelay && buttonDelay.elapsed() > currentDelay->getSlotCode())
{
currentDelay = 0;
delayTimer.stop();
buttonDelay.restart();
createDeskEvent();
}
// Elapsed time has not occurred
else if (currentlyPressed)
{
unsigned int delayTime = currentDelay->getSlotCode();
int proposedInterval = delayTime - buttonDelay.elapsed();
proposedInterval = proposedInterval > 0 ? proposedInterval : 0;
int newTimerInterval = qMin(10, proposedInterval);
delayTimer.start(newTimerInterval);
}
// Pre-emptive release
else
{
currentDelay = 0;
delayTimer.stop();
}
}
else
{
delayTimer.stop();
}
}
void JoyButton::releaseDeskEvent(bool skipsetchange)
{
quitEvent = false;
pauseWaitTimer.stop();
holdTimer.stop();
createDeskTimer.stop();
keyPressTimer.stop();
delayTimer.stop();
#ifdef Q_OS_WIN
repeatHelper.getRepeatTimer()->stop();
#endif
setChangeTimer.stop();
releaseActiveSlots();
if (!isButtonPressedQueue.isEmpty() && !currentRelease)
{
releaseSlotEvent();
}
else if (currentRelease)
{
currentRelease = 0;
}
if (!skipsetchange && setSelectionCondition != SetChangeDisabled &&
!isButtonPressedQueue.isEmpty() && !currentRelease)
{
bool tempButtonPressed = isButtonPressedQueue.last();
bool tempFinalIgnoreSetsState = ignoreSetQueue.last();
if (!tempButtonPressed && !tempFinalIgnoreSetsState)
{
if (setSelectionCondition == SetChangeWhileHeld && whileHeldStatus)
{
setChangeTimer.start(0);
}
else if (setSelectionCondition != SetChangeWhileHeld)
{
setChangeTimer.start();
}
}
else
{
bool tempFinalState = false;
if (!isButtonPressedQueue.isEmpty())
{
tempFinalState = isButtonPressedQueue.last();
isButtonPressedQueue.clear();
if (tempFinalState)
{
isButtonPressedQueue.enqueue(tempFinalState);
}
}
if (!ignoreSetQueue.isEmpty())
{
bool tempFinalIgnoreSetsState = ignoreSetQueue.last();
ignoreSetQueue.clear();
if (tempFinalState)
{
ignoreSetQueue.enqueue(tempFinalIgnoreSetsState);
}
}
}
}
else
{
bool tempFinalState = false;
if (!isButtonPressedQueue.isEmpty())
{
tempFinalState = isButtonPressedQueue.last();
isButtonPressedQueue.clear();
if (tempFinalState || currentRelease)
{
isButtonPressedQueue.enqueue(tempFinalState);
}
}
if (!ignoreSetQueue.isEmpty())
{
bool tempFinalIgnoreSetsState = ignoreSetQueue.last();
ignoreSetQueue.clear();
if (tempFinalState || currentRelease)
{
ignoreSetQueue.enqueue(tempFinalIgnoreSetsState);
}
}
}
if (!currentRelease)
{
lastAccelerationDistance = 0.0;
currentAccelMulti = 0.0;
currentAccelerationDistance = 0.0;
startingAccelerationDistance = 0.0;
oldAccelMulti = updateOldAccelMulti = 0.0;
accelTravel = 0.0;
accelExtraDurationTime.restart();
lastMouseDistance = 0.0;
currentMouseDistance = 0.0;
updateStartingMouseDistance = true;
if (slotiter && !slotiter->hasNext())
{
// At the end of the list of assignments.
currentCycle = 0;
previousCycle = 0;
slotiter->toFront();
}
else if (slotiter && slotiter->hasNext() && currentCycle)
{
// Cycle at the end of a segment.
slotiter->toFront();
slotiter->findNext(currentCycle);
}
else if (slotiter && slotiter->hasPrevious() && slotiter->hasNext() && !currentCycle)
{
// Check if there is a cycle action slot after
// current slot. Useful after dealing with pause
// actions.
JoyButtonSlot *tempslot = 0;
bool exit = false;
while (slotiter->hasNext() && !exit)
{
tempslot = slotiter->next();
if (tempslot->getSlotMode() == JoyButtonSlot::JoyCycle)
{
currentCycle = tempslot;
exit = true;
}
}
// Didn't find any cycle. Move iterator
// to the front.
if (!currentCycle)
{
slotiter->toFront();
previousCycle = 0;
}
}
if (currentCycle)
{
previousCycle = currentCycle;
currentCycle = 0;
}
else if (slotiter && slotiter->hasNext() && containsReleaseSlots())
{
currentCycle = 0;
previousCycle = 0;
slotiter->toFront();
}
this->currentDistance = 0;
this->currentKeyPress = 0;
quitEvent = true;
}
}
/**
* @brief Get the distance that an element is away from its assigned
* dead zone
* @return Normalized distance away from dead zone
*/
double JoyButton::getDistanceFromDeadZone()
{
double distance = 0.0;
if (isButtonPressed)
{
distance = 1.0;
}
return distance;
}
double JoyButton::getAccelerationDistance()
{
return this->getDistanceFromDeadZone();
}
/**
* @brief Get the distance factor that should be used for mouse movement
* @return Distance factor that should be used for mouse movement
*/
double JoyButton::getMouseDistanceFromDeadZone()
{
return this->getDistanceFromDeadZone();
}
double JoyButton::getTotalSlotDistance(JoyButtonSlot *slot)
{
double tempDistance = 0.0;
QListIterator<JoyButtonSlot*> iter(assignments);
while (iter.hasNext())
{
JoyButtonSlot *currentSlot = iter.next();
int tempcode = currentSlot->getSlotCode();
JoyButtonSlot::JoySlotInputAction mode = currentSlot->getSlotMode();
if (mode == JoyButtonSlot::JoyDistance)
{
tempDistance += tempcode / 100.0;
if (slot == currentSlot)
{
// Current slot found. Go to end of iterator
// so loop will exit
iter.toBack();
}
}
// Reset tempDistance
else if (mode == JoyButtonSlot::JoyCycle)
{
tempDistance = 0.0;
}
}
return tempDistance;
}
bool JoyButton::containsDistanceSlots()
{
bool result = false;
QListIterator<JoyButtonSlot*> iter(assignments);
while (iter.hasNext())
{
JoyButtonSlot *slot = iter.next();
if (slot->getSlotMode() == JoyButtonSlot::JoyDistance)
{
result = true;
iter.toBack();
}
}
return result;
}
void JoyButton::clearAssignedSlots(bool signalEmit)
{
QListIterator<JoyButtonSlot*> iter(assignments);
while (iter.hasNext())
{
JoyButtonSlot *slot = iter.next();
if (slot)
{
delete slot;
slot = 0;
}
}
assignments.clear();
if (signalEmit)
{
emit slotsChanged();
}
}
void JoyButton::removeAssignedSlot(int index)
{
QWriteLocker tempAssignLocker(&assignmentsLock);
if (index >= 0 && index < assignments.size())
{
JoyButtonSlot *slot = assignments.takeAt(index);
if (slot)
{
delete slot;
slot = 0;
}
tempAssignLocker.unlock();
buildActiveZoneSummaryString();
emit slotsChanged();
}
}
void JoyButton::clearSlotsEventReset(bool clearSignalEmit)
{
QWriteLocker tempAssignLocker(&assignmentsLock);
turboTimer.stop();
pauseWaitTimer.stop();
createDeskTimer.stop();
releaseDeskTimer.stop();
holdTimer.stop();
mouseWheelVerticalEventTimer.stop();
mouseWheelHorizontalEventTimer.stop();
setChangeTimer.stop();
keyPressTimer.stop();
delayTimer.stop();
activeZoneTimer.stop();
#ifdef Q_OS_WIN
repeatHelper.getRepeatTimer()->stop();
#endif
if (slotiter)
{
delete slotiter;
slotiter = 0;
}
releaseActiveSlots();
clearAssignedSlots(clearSignalEmit);
isButtonPressedQueue.clear();
ignoreSetQueue.clear();
mouseEventQueue.clear();
mouseWheelVerticalEventQueue.clear();
mouseWheelHorizontalEventQueue.clear();
currentCycle = 0;
previousCycle = 0;
currentPause = 0;
currentHold = 0;
currentDistance = 0;
currentRawValue = 0;
currentMouseEvent = 0;
currentRelease = 0;
currentWheelVerticalEvent = 0;
currentWheelHorizontalEvent = 0;
currentKeyPress = 0;
currentDelay = 0;
isKeyPressed = isButtonPressed = false;
//buildActiveZoneSummaryString();
activeZoneTimer.start();
quitEvent = true;
}
void JoyButton::eventReset()
{
QWriteLocker tempAssignLocker(&assignmentsLock);
turboTimer.stop();
pauseWaitTimer.stop();
createDeskTimer.stop();
releaseDeskTimer.stop();
holdTimer.stop();
mouseWheelVerticalEventTimer.stop();
mouseWheelHorizontalEventTimer.stop();
setChangeTimer.stop();
keyPressTimer.stop();
delayTimer.stop();
activeZoneTimer.stop();
#ifdef Q_OS_WIN
repeatHelper.getRepeatTimer()->stop();
#endif
if (slotiter)
{
delete slotiter;
slotiter = 0;
}
isButtonPressedQueue.clear();
ignoreSetQueue.clear();
mouseEventQueue.clear();
mouseWheelVerticalEventQueue.clear();
mouseWheelHorizontalEventQueue.clear();
currentCycle = 0;
previousCycle = 0;
currentPause = 0;
currentHold = 0;
currentDistance = 0;
currentRawValue = 0;
currentMouseEvent = 0;
currentRelease = 0;
currentWheelVerticalEvent = 0;
currentWheelHorizontalEvent = 0;
currentKeyPress = 0;
currentDelay = 0;
isKeyPressed = isButtonPressed = false;
releaseActiveSlots();
quitEvent = true;
}
void JoyButton::releaseActiveSlots()
{
if (!activeSlots.isEmpty())
{
QWriteLocker tempLocker(&activeZoneLock);
bool changeRepeatState = false;
QListIterator<JoyButtonSlot*> iter(activeSlots);
iter.toBack();
while (iter.hasPrevious())
{
JoyButtonSlot *slot = iter.previous();
int tempcode = slot->getSlotCode();
JoyButtonSlot::JoySlotInputAction mode = slot->getSlotMode();
if (mode == JoyButtonSlot::JoyKeyboard)
{
int referencecount = activeKeys.value(tempcode, 1) - 1;
if (referencecount <= 0)
{
sendevent(slot, false);
activeKeys.remove(tempcode);
changeRepeatState = true;
}
else
{
activeKeys.insert(tempcode, referencecount);
}
if (lastActiveKey == slot && referencecount <= 0)
{
lastActiveKey = 0;
}
}
else if (mode == JoyButtonSlot::JoyMouseButton)
{
if (tempcode != JoyButtonSlot::MouseWheelUp &&
tempcode != JoyButtonSlot::MouseWheelDown &&
tempcode != JoyButtonSlot::MouseWheelLeft &&
tempcode != JoyButtonSlot::MouseWheelRight)
{
int referencecount = activeMouseButtons.value(tempcode, 1) - 1;
if (referencecount <= 0)
{
sendevent(slot, false);
activeMouseButtons.remove(tempcode);
}
else
{
activeMouseButtons.insert(tempcode, referencecount);
}
}
else if (tempcode == JoyButtonSlot::MouseWheelUp ||
tempcode == JoyButtonSlot::MouseWheelDown)
{
mouseWheelVerticalEventQueue.removeAll(slot);
}
else if (tempcode == JoyButtonSlot::MouseWheelLeft ||
tempcode == JoyButtonSlot::MouseWheelRight)
{
mouseWheelHorizontalEventQueue.removeAll(slot);
}
slot->setDistance(0.0);
slot->getMouseInterval()->restart();
}
else if (mode == JoyButtonSlot::JoyMouseMovement)
{
JoyMouseMovementMode mousemode = getMouseMode();
if (mousemode == MouseCursor)
{
QListIterator<mouseCursorInfo> iterX(cursorXSpeeds);
unsigned int i = cursorXSpeeds.length();
QList<int> indexesToRemove;
while (iterX.hasNext())
{
mouseCursorInfo info = iterX.next();
if (info.slot == slot)
{
indexesToRemove.append(i);
}
i++;
}
QListIterator<int> removeXIter(indexesToRemove);
while (removeXIter.hasPrevious())
{
int index = removeXIter.previous();
cursorXSpeeds.removeAt(index);
}
indexesToRemove.clear();
i = cursorYSpeeds.length();
QListIterator<mouseCursorInfo> iterY(cursorYSpeeds);
while (iterY.hasNext())
{
mouseCursorInfo info = iterY.next();
if (info.slot == slot)
{
indexesToRemove.append(i);
}
i++;
}
QListIterator<int> removeYIter(indexesToRemove);
while (removeYIter.hasPrevious())
{
int index = removeYIter.previous();
cursorYSpeeds.removeAt(index);
}
indexesToRemove.clear();
slot->getEasingTime()->restart();
slot->setEasingStatus(false);
}
else if (mousemode == JoyButton::MouseSpring)
{
double mouse1 = (tempcode == JoyButtonSlot::MouseLeft ||
tempcode == JoyButtonSlot::MouseRight) ? 0.0 : -2.0;
double mouse2 = (tempcode == JoyButtonSlot::MouseUp ||
tempcode == JoyButtonSlot::MouseDown) ? 0.0 : -2.0;
double springDeadCircleX = 0.0;
if (getSpringDeadCircleMultiplier() > 0)
{
if (tempcode == JoyButtonSlot::MouseLeft)
{
double temp = getCurrentSpringDeadCircle();
if (temp > getLastMouseDistanceFromDeadZone())
{
springDeadCircleX = -getLastMouseDistanceFromDeadZone();
}
else
{
springDeadCircleX = -temp;
}
}
else if (tempcode == JoyButtonSlot::MouseRight)
{
double temp = getCurrentSpringDeadCircle();
if (temp > getLastMouseDistanceFromDeadZone())
{
springDeadCircleX = getLastMouseDistanceFromDeadZone();
}
else
{
springDeadCircleX = temp;
}
}
}
double springDeadCircleY = 0.0;
if (getSpringDeadCircleMultiplier() > 0)
{
if (tempcode == JoyButtonSlot::MouseUp)
{
double temp = getCurrentSpringDeadCircle();
if (temp > getLastMouseDistanceFromDeadZone())
{
springDeadCircleY = -getLastMouseDistanceFromDeadZone();
}
else
{
springDeadCircleY = -temp;
}
}
else if (tempcode == JoyButtonSlot::MouseDown)
{
double temp = getCurrentSpringDeadCircle();
if (temp > getLastMouseDistanceFromDeadZone())
{
springDeadCircleY = getLastMouseDistanceFromDeadZone();
}
else
{
springDeadCircleY = temp;
}
}
}
PadderCommon::springModeInfo infoX;
infoX.displacementX = mouse1;
infoX.displacementY = -2.0;
infoX.springDeadX = springDeadCircleX;
infoX.springDeadY = springDeadCircleY;
infoX.width = springWidth;
infoX.height = springHeight;
infoX.relative = relativeSpring;
infoX.screen = springModeScreen;
springXSpeeds.append(infoX);
PadderCommon::springModeInfo infoY;
infoY.displacementX = -2.0;
infoY.displacementY = mouse2;
infoY.springDeadX = springDeadCircleX;
infoY.springDeadY = springDeadCircleY;
infoY.width = springWidth;
infoY.height = springHeight;
infoY.relative = relativeSpring;
infoY.screen = springModeScreen;
springYSpeeds.append(infoY);
}
mouseEventQueue.removeAll(slot);
slot->setDistance(0.0);
slot->getMouseInterval()->restart();
}
else if (mode == JoyButtonSlot::JoyMouseSpeedMod)
{
int queueLength = mouseSpeedModList.length();
if (!mouseSpeedModList.isEmpty())
{
mouseSpeedModList.removeAll(slot);
queueLength -= 1;
}
if (queueLength <= 0)
{
mouseSpeedModifier = DEFAULTMOUSESPEEDMOD;
}
}
else if (mode == JoyButtonSlot::JoySetChange)
{
currentSetChangeSlot = slot;
slotSetChangeTimer.start();
}
}
activeSlots.clear();
currentMouseEvent = 0;
if (!mouseEventQueue.isEmpty())
{
mouseEventQueue.clear();
}
pendingMouseButtons.removeAll(this);
currentWheelVerticalEvent = 0;
currentWheelHorizontalEvent = 0;
mouseWheelVerticalEventTimer.stop();
mouseWheelHorizontalEventTimer.stop();
if (!mouseWheelVerticalEventQueue.isEmpty())
{
mouseWheelVerticalEventQueue.clear();
lastWheelVerticalDistance = getMouseDistanceFromDeadZone();
wheelVerticalTime.restart();
}
if (!mouseWheelHorizontalEventQueue.isEmpty())
{
mouseWheelHorizontalEventQueue.clear();
lastWheelHorizontalDistance = getMouseDistanceFromDeadZone();
wheelHorizontalTime.restart();
}
// Check if mouse remainder should be zero.
// Only need to check one list from cursor speeds and spring speeds
// since the correspond Y lists will be the same size.
if (pendingMouseButtons.length() == 0 && cursorXSpeeds.length() == 0 &&
springXSpeeds.length() == 0)
{
//staticMouseEventTimer.setInterval(IDLEMOUSEREFRESHRATE);
cursorRemainderX = 0;
cursorRemainderY = 0;
}
//emit activeZoneChanged();
activeZoneTimer.start();
#ifdef Q_OS_WIN
BaseEventHandler *handler = EventHandlerFactory::getInstance()->handler();
if (handler && handler->getIdentifier() == "sendinput" &&
changeRepeatState && lastActiveKey && !useTurbo)
{
InputDevice *device = getParentSet()->getInputDevice();
if (device->isKeyRepeatEnabled())
{
if (lastActiveKey)
{
repeatHelper.setLastActiveKey(lastActiveKey);
repeatHelper.setKeyRepeatRate(device->getKeyRepeatRate());
repeatHelper.getRepeatTimer()->start(device->getKeyRepeatDelay());
}
else if (repeatHelper.getRepeatTimer()->isActive())
{
repeatHelper.setLastActiveKey(0);
repeatHelper.getRepeatTimer()->stop();
}
}
}
#endif
}
}
bool JoyButton::containsReleaseSlots()
{
bool result = false;
QListIterator<JoyButtonSlot*> iter(assignments);
while (iter.hasNext())
{
JoyButtonSlot *slot = iter.next();
if (slot->getSlotMode() == JoyButtonSlot::JoyRelease)
{
result = true;
iter.toBack();
}
}
return result;
}
void JoyButton::releaseSlotEvent()
{
JoyButtonSlot *temp = 0;
int timeElapsed = buttonHeldRelease.elapsed();
int tempElapsed = 0;
if (containsReleaseSlots())
{
QListIterator<JoyButtonSlot*> iter(assignments);
if (previousCycle)
{
iter.findNext(previousCycle);
}
while (iter.hasNext())
{
JoyButtonSlot *currentSlot = iter.next();
int tempcode = currentSlot->getSlotCode();
JoyButtonSlot::JoySlotInputAction mode = currentSlot->getSlotMode();
if (mode == JoyButtonSlot::JoyRelease)
{
tempElapsed += tempcode;
if (tempElapsed <= timeElapsed)
{
temp = currentSlot;
}
else if (tempElapsed > timeElapsed)
{
iter.toBack();
}
}
else if (mode == JoyButtonSlot::JoyCycle)
{
tempElapsed = 0;
iter.toBack();
}
}
if (temp && slotiter)
{
slotiter->toFront();
slotiter->findNext(temp);
currentRelease = temp;
activateSlots();
if (!keyPressTimer.isActive() && !pauseWaitTimer.isActive())
{
releaseActiveSlots();
currentRelease = 0;
}
// Stop hold timer here to be sure that
// a hold timer that could be activated
// during a release event is stopped.
holdTimer.stop();
if (currentHold)
{
currentHold = 0;
}
}
}
}
void JoyButton::findReleaseEventEnd()
{
bool found = false;
while (!found && slotiter->hasNext())
{
JoyButtonSlot *currentSlot = slotiter->next();
JoyButtonSlot::JoySlotInputAction mode = currentSlot->getSlotMode();
if (mode == JoyButtonSlot::JoyRelease)
{
found = true;
}
else if (mode == JoyButtonSlot::JoyCycle)
{
found = true;
}
else if (mode == JoyButtonSlot::JoyHold)
{
found = true;
}
}
if (found && slotiter->hasPrevious())
{
slotiter->previous();
}
}
void JoyButton::findReleaseEventIterEnd(QListIterator<JoyButtonSlot*> *tempiter)
{
bool found = false;
if (tempiter)
{
while (!found && tempiter->hasNext())
{
JoyButtonSlot *currentSlot = tempiter->next();
JoyButtonSlot::JoySlotInputAction mode = currentSlot->getSlotMode();
if (mode == JoyButtonSlot::JoyRelease)
{
found = true;
}
else if (mode == JoyButtonSlot::JoyCycle)
{
found = true;
}
else if (mode == JoyButtonSlot::JoyHold)
{
found = true;
}
}
if (found && tempiter->hasPrevious())
{
tempiter->previous();
}
}
}
void JoyButton::findHoldEventEnd()
{
bool found = false;
while (!found && slotiter->hasNext())
{
JoyButtonSlot *currentSlot = slotiter->next();
JoyButtonSlot::JoySlotInputAction mode = currentSlot->getSlotMode();
if (mode == JoyButtonSlot::JoyRelease)
{
found = true;
}
else if (mode == JoyButtonSlot::JoyCycle)
{
found = true;
}
else if (mode == JoyButtonSlot::JoyHold)
{
found = true;
}
}
if (found && slotiter->hasPrevious())
{
slotiter->previous();
}
}
void JoyButton::setVDPad(VDPad *vdpad)
{
joyEvent(false, true);
this->vdpad = vdpad;
emit propertyUpdated();
}
bool JoyButton::isPartVDPad()
{
return (this->vdpad != 0);
}
VDPad* JoyButton::getVDPad()
{
return this->vdpad;
}
void JoyButton::removeVDPad()
{
this->vdpad = 0;
emit propertyUpdated();
}
/**
* @brief Check if button properties are at their default values
* @return Status of possible property edits
*/
bool JoyButton::isDefault()
{
bool value = true;
value = value && (toggle == DEFAULTTOGGLE);
value = value && (turboInterval == DEFAULTTURBOINTERVAL);
value = value && (currentTurboMode == NormalTurbo);
value = value && (useTurbo == DEFAULTUSETURBO);
value = value && (mouseSpeedX == DEFAULTMOUSESPEEDX);
value = value && (mouseSpeedY == DEFAULTMOUSESPEEDY);
value = value && (setSelection == DEFAULTSETSELECTION);
value = value && (setSelectionCondition == DEFAULTSETCONDITION);
value = value && (assignments.isEmpty());
value = value && (mouseMode == DEFAULTMOUSEMODE);
value = value && (mouseCurve == DEFAULTMOUSECURVE);
value = value && (springWidth == DEFAULTSPRINGWIDTH);
value = value && (springHeight == DEFAULTSPRINGHEIGHT);
value = value && (sensitivity == DEFAULTSENSITIVITY);
value = value && (actionName.isEmpty());
//value = value && (buttonName.isEmpty());
value = value && (wheelSpeedX == DEFAULTWHEELX);
value = value && (wheelSpeedY == DEFAULTWHEELY);
value = value && (cycleResetActive == DEFAULTCYCLERESETACTIVE);
value = value && (cycleResetInterval == DEFAULTCYCLERESET);
value = value && (relativeSpring == DEFAULTRELATIVESPRING);
value = value && (easingDuration == DEFAULTEASINGDURATION);
value = value && (extraAccelerationEnabled == false);
value = value && (extraAccelerationMultiplier == DEFAULTEXTRACCELVALUE);
value = value && (minMouseDistanceAccelThreshold == DEFAULTMINACCELTHRESHOLD);
value = value && (maxMouseDistanceAccelThreshold == DEFAULTMAXACCELTHRESHOLD);
value = value && (startAccelMultiplier == DEFAULTSTARTACCELMULTIPLIER);
value = value && (accelDuration == DEFAULTACCELEASINGDURATION);
value = value && (springDeadCircleMultiplier == DEFAULTSPRINGRELEASERADIUS);
value = value && (extraAccelCurve == DEFAULTEXTRAACCELCURVE);
return value;
}
void JoyButton::setIgnoreEventState(bool ignore)
{
ignoreEvents = ignore;
}
bool JoyButton::getIgnoreEventState()
{
return ignoreEvents;
}
void JoyButton::setMouseMode(JoyMouseMovementMode mousemode)
{
this->mouseMode = mousemode;
emit propertyUpdated();
}
JoyButton::JoyMouseMovementMode JoyButton::getMouseMode()
{
return mouseMode;
}
void JoyButton::setMouseCurve(JoyMouseCurve selectedCurve)
{
mouseCurve = selectedCurve;
emit propertyUpdated();
}
JoyButton::JoyMouseCurve JoyButton::getMouseCurve()
{
return mouseCurve;
}
void JoyButton::setSpringWidth(int value)
{
if (value >= 0)
{
springWidth = value;
emit propertyUpdated();
}
}
int JoyButton::getSpringWidth()
{
return springWidth;
}
void JoyButton::setSpringHeight(int value)
{
if (springHeight >= 0)
{
springHeight = value;
emit propertyUpdated();
}
}
int JoyButton::getSpringHeight()
{
return springHeight;
}
void JoyButton::setSensitivity(double value)
{
if (value >= 0.001 && value <= 1000)
{
sensitivity = value;
emit propertyUpdated();
}
}
double JoyButton::getSensitivity()
{
return sensitivity;
}
bool JoyButton::getWhileHeldStatus()
{
return whileHeldStatus;
}
void JoyButton::setWhileHeldStatus(bool status)
{
whileHeldStatus = status;
}
void JoyButton::setActionName(QString tempName)
{
if (tempName.length() <= 50 && tempName != actionName)
{
actionName = tempName;
emit actionNameChanged();
emit propertyUpdated();
}
}
QString JoyButton::getActionName()
{
return actionName;
}
void JoyButton::setButtonName(QString tempName)
{
if (tempName.length() <= 20 && tempName != buttonName)
{
buttonName = tempName;
emit buttonNameChanged();
emit propertyUpdated();
}
}
QString JoyButton::getButtonName()
{
return buttonName;
}
void JoyButton::setWheelSpeedX(int speed)
{
if (speed >= 1 && speed <= 100)
{
wheelSpeedX = speed;
emit propertyUpdated();
}
}
void JoyButton::setWheelSpeedY(int speed)
{
if (speed >= 1 && speed <= 100)
{
wheelSpeedY = speed;
emit propertyUpdated();
}
}
int JoyButton::getWheelSpeedX()
{
return wheelSpeedX;
}
int JoyButton::getWheelSpeedY()
{
return wheelSpeedY;
}
void JoyButton::setDefaultButtonName(QString tempname)
{
defaultButtonName = tempname;
}
QString JoyButton::getDefaultButtonName()
{
return defaultButtonName;
}
/**
* @brief Take cursor mouse information provided by all buttons and
* send a cursor mode mouse event to the display server.
*/
void JoyButton::moveMouseCursor(int &movedX, int &movedY, int &movedElapsed)
{
movedX = 0;
movedY = 0;
double finalx = 0.0;
double finaly = 0.0;
//int elapsedTime = lastMouseTime.elapsed();
int elapsedTime = testOldMouseTime.elapsed();
movedElapsed = elapsedTime;
if (staticMouseEventTimer.interval() < mouseRefreshRate)
{
elapsedTime = mouseRefreshRate + (elapsedTime - staticMouseEventTimer.interval());
movedElapsed = elapsedTime;
}
if (mouseHistoryX.size() >= mouseHistorySize)
{
mouseHistoryX.removeLast();
}
if (mouseHistoryY.size() >= mouseHistorySize)
{
mouseHistoryY.removeLast();
}
/*
* Combine all mouse events to find the distance to move the mouse
* along the X and Y axis. If necessary, perform mouse smoothing.
* The mouse smoothing technique used is an interpretation of the method
* outlined at path_to_url
*/
if (cursorXSpeeds.length() == cursorYSpeeds.length() &&
cursorXSpeeds.length() > 0)
{
int queueLength = cursorXSpeeds.length();
for (int i=0; i < queueLength; i++)
{
mouseCursorInfo infoX = cursorXSpeeds.takeFirst();
mouseCursorInfo infoY = cursorYSpeeds.takeFirst();
if (infoX.code != 0)
{
finalx = (infoX.code < 0) ? qMin(infoX.code, finalx) :
qMax(infoX.code, finalx);
}
if (infoY.code != 0)
{
finaly = (infoY.code < 0) ? qMin(infoY.code, finaly) :
qMax(infoY.code, finaly);
}
infoX.slot->getMouseInterval()->restart();
infoY.slot->getMouseInterval()->restart();
}
// Only apply remainder if both current displacement and remainder
// follow the same direction.
if ((cursorRemainderX >= 0) == (finalx >= 0))
{
finalx += cursorRemainderX;
}
// Cap maximum relative mouse movement.
if (abs(finalx) > 127)
{
finalx = (finalx < 0) ? -127 : 127;
}
mouseHistoryX.prepend(finalx);
// Only apply remainder if both current displacement and remainder
// follow the same direction.
if ((cursorRemainderY >= 0) == (finaly >= 0))
{
finaly += cursorRemainderY;
}
// Cap maximum relative mouse movement.
if (abs(finaly) > 127)
{
finaly = (finaly < 0) ? -127 : 127;
}
mouseHistoryY.prepend(finaly);
cursorRemainderX = 0;
cursorRemainderY = 0;
double adjustedX = 0;
double adjustedY = 0;
QListIterator<double> iterX(mouseHistoryX);
double currentWeight = 1.0;
double weightModifier = JoyButton::weightModifier;
double finalWeight = 0.0;
while (iterX.hasNext())
{
double temp = iterX.next();
adjustedX += temp * currentWeight;
finalWeight += currentWeight;
currentWeight *= weightModifier;
}
if (fabs(adjustedX) > 0)
{
adjustedX = adjustedX / static_cast<double>(finalWeight);
if (adjustedX > 0)
{
double oldX = adjustedX;
adjustedX = static_cast<int>(floor(adjustedX));
//adjustedX = (int)floor(adjustedX + 0.5); // Old rounding behavior
cursorRemainderX = oldX - adjustedX;
}
else
{
double oldX = adjustedX;
adjustedX = static_cast<int>(ceil(adjustedX));
//adjustedX = (int)ceil(adjustedX - 0.5); // Old rounding behavior
cursorRemainderX = oldX - adjustedX;
}
}
QListIterator<double> iterY(mouseHistoryY);
currentWeight = 1.0;
finalWeight = 0.0;
while (iterY.hasNext())
{
double temp = iterY.next();
adjustedY += temp * currentWeight;
finalWeight += currentWeight;
currentWeight *= weightModifier;
}
if (fabs(adjustedY) > 0)
{
adjustedY = adjustedY / static_cast<double>(finalWeight);
if (adjustedY > 0)
{
double oldY = adjustedY;
adjustedY = static_cast<int>(floor(adjustedY));
//adjustedY = (int)floor(adjustedY + 0.5); // Old rounding behavior
cursorRemainderY = oldY - adjustedY;
}
else
{
double oldY = adjustedY;
adjustedY = static_cast<int>(ceil(adjustedY));
//adjustedY = (int)ceil(adjustedY - 0.5); // Old rounding behavior
cursorRemainderY = oldY - adjustedY;
}
}
// This check is more of a precaution than anything. No need to cause
// a sync to happen when not needed.
if (adjustedX != 0 || adjustedY != 0)
{
sendevent(adjustedX, adjustedY);
}
//Logger::LogInfo(QString("FINAL X: %1").arg(adjustedX));
//Logger::LogInfo(QString("FINAL Y: %1\n").arg(adjustedY));
//Logger::LogInfo(QString("ELAPSED: %1\n").arg(elapsedTime));
//Logger::LogInfo(QString("REMAINDER X: %1").arg(cursorRemainderX));
movedX = static_cast<int>(adjustedX);
movedY = static_cast<int>(adjustedY);
}
else
{
mouseHistoryX.prepend(0);
mouseHistoryY.prepend(0);
}
//lastMouseTime.restart();
// Check if mouse event timer should use idle time.
if (pendingMouseButtons.length() == 0)
{
if (staticMouseEventTimer.interval() != IDLEMOUSEREFRESHRATE)
{
staticMouseEventTimer.start(IDLEMOUSEREFRESHRATE);
// Clear current mouse history
mouseHistoryX.clear();
mouseHistoryY.clear();
// Fill history with zeroes.
for (int i=0; i < mouseHistorySize; i++)
{
mouseHistoryX.append(0);
mouseHistoryY.append(0);
}
}
cursorRemainderX = 0;
cursorRemainderY = 0;
}
else
{
if (staticMouseEventTimer.interval() != mouseRefreshRate)
{
// Restore intended QTimer interval.
staticMouseEventTimer.start(mouseRefreshRate);
}
}
cursorXSpeeds.clear();
cursorYSpeeds.clear();
}
/**
* @brief Take spring mouse information provided by all buttons and
* send a spring mode mouse event to the display server.
*/
void JoyButton::moveSpringMouse(int &movedX, int &movedY, bool &hasMoved)
{
PadderCommon::springModeInfo fullSpring = {
-2.0, -2.0, 0, 0, false, springModeScreen, 0.0, 0.0
};
PadderCommon::springModeInfo relativeSpring = {
-2.0, -2.0, 0, 0, false, springModeScreen, 0.0, 0.0
};
int realMouseX = movedX = 0;
int realMouseY = movedY = 0;
hasMoved = false;
if (springXSpeeds.length() == springYSpeeds.length() &&
springXSpeeds.length() > 0)
{
int queueLength = springXSpeeds.length();
bool complete = false;
for (int i=queueLength-1; i >= 0 && !complete; i--)
{
double tempx = -2.0;
double tempy = -2.0;
double tempSpringDeadX = 0.0;
double tempSpringDeadY = 0.0;
PadderCommon::springModeInfo infoX;
PadderCommon::springModeInfo infoY;
infoX = springXSpeeds.takeLast();
infoY = springYSpeeds.takeLast();
tempx = infoX.displacementX;
tempy = infoY.displacementY;
tempSpringDeadX = infoX.springDeadX;
tempSpringDeadY = infoY.springDeadY;
if (infoX.relative)
{
if (relativeSpring.displacementX == -2.0)
{
relativeSpring.displacementX = tempx;
}
relativeSpring.relative = true;
// Use largest found width for spring
// mode dimensions.
relativeSpring.width = qMax(infoX.width, relativeSpring.width);
}
else
{
if (fullSpring.displacementX == -2.0)
{
fullSpring.displacementX = tempx;
}
if (fullSpring.springDeadX == 0.0)
{
fullSpring.springDeadX = tempSpringDeadX;
}
// Use largest found width for spring
// mode dimensions.
fullSpring.width = qMax(infoX.width, fullSpring.width);
}
if (infoY.relative)
{
if (relativeSpring.displacementY == -2.0)
{
relativeSpring.displacementY = tempy;
}
relativeSpring.relative = true;
// Use largest found height for spring
// mode dimensions.
relativeSpring.height = qMax(infoX.height, relativeSpring.height);
}
else
{
if (fullSpring.displacementY == -2.0)
{
fullSpring.displacementY = tempy;
}
if (fullSpring.springDeadY == 0.0)
{
fullSpring.springDeadY = tempSpringDeadY;
}
// Use largest found height for spring
// mode dimensions.
fullSpring.height = qMax(infoX.height, fullSpring.height);
}
if ((relativeSpring.displacementX != -2.0 && relativeSpring.displacementY != -2.0) &&
(fullSpring.displacementX != -2.0 && fullSpring.displacementY != -2.0))
{
complete = true;
}
else if ((relativeSpring.springDeadX != 0.0 && relativeSpring.springDeadY != 0.0) &&
(fullSpring.springDeadX != 0.0 && fullSpring.springDeadY != 0.0))
{
complete = true;
}
}
fullSpring.screen = springModeScreen;
relativeSpring.screen = springModeScreen;
if (relativeSpring.relative)
{
sendSpringEvent(&fullSpring, &relativeSpring, &realMouseX, &realMouseY);
}
else
{
if (!hasFutureSpringEvents())
{
if (fullSpring.springDeadX != 0.0)
{
fullSpring.displacementX = fullSpring.springDeadX;
}
if (fullSpring.springDeadY != 0.0)
{
fullSpring.displacementY = fullSpring.springDeadY;
}
sendSpringEvent(&fullSpring, 0, &realMouseX, &realMouseY);
}
else
{
sendSpringEvent(&fullSpring, 0, &realMouseX, &realMouseY);
}
}
movedX = realMouseX;
movedY = realMouseY;
hasMoved = true;
}
//lastMouseTime.restart();
// Check if mouse event timer should use idle time.
if (pendingMouseButtons.length() == 0)
{
staticMouseEventTimer.start(IDLEMOUSEREFRESHRATE);
}
else
{
if (staticMouseEventTimer.interval() != mouseRefreshRate)
{
// Restore intended QTimer interval.
staticMouseEventTimer.start(mouseRefreshRate);
}
}
springXSpeeds.clear();
springYSpeeds.clear();
}
void JoyButton::keyPressEvent()
{
//qDebug() << "RADIO EDIT: " << keyDelayHold.elapsed();
if (keyPressTimer.isActive() && keyPressHold.elapsed() >= getPreferredKeyPressTime())
{
currentKeyPress = 0;
keyPressTimer.stop();
keyPressHold.restart();
releaseActiveSlots();
createDeskTimer.stop();
if (currentRelease)
{
releaseDeskTimer.stop();
createDeskEvent();
waitForReleaseDeskEvent();
}
else
{
createDeskEvent();
}
}
else
{
createDeskTimer.stop();
//releaseDeskTimer.stop();
unsigned int preferredDelay = getPreferredKeyPressTime();
int proposedInterval = preferredDelay - keyPressHold.elapsed();
proposedInterval = proposedInterval > 0 ? proposedInterval : 0;
int newTimerInterval = qMin(10, proposedInterval);
keyPressTimer.start(newTimerInterval);
// If release timer is active, push next run until
// after keyDelayTimer will timeout again. Helps
// reduce CPU usage of an excessively repeating timer.
if (releaseDeskTimer.isActive())
{
releaseDeskTimer.start(proposedInterval);
}
}
}
/**
* @brief TODO: CHECK IF METHOD WOULD BE USEFUL. CURRENTLY NOT USED.
* @return Result
*/
bool JoyButton::checkForDelaySequence()
{
bool result = false;
QListIterator<JoyButtonSlot*> tempiter(assignments);
// Move iterator to start of cycle.
if (previousCycle)
{
tempiter.findNext(previousCycle);
}
while (tempiter.hasNext())
{
JoyButtonSlot *slot = tempiter.next();
JoyButtonSlot::JoySlotInputAction mode = slot->getSlotMode();
if (mode == JoyButtonSlot::JoyPause || mode == JoyButtonSlot::JoyRelease)
{
result = true;
tempiter.toBack();
}
else if (mode == JoyButtonSlot::JoyCycle)
{
result = false;
tempiter.toBack();
}
}
return result;
}
SetJoystick* JoyButton::getParentSet()
{
return parentSet;
}
void JoyButton::checkForPressedSetChange()
{
if (!isButtonPressedQueue.isEmpty())
{
bool tempButtonPressed = isButtonPressedQueue.last();
bool tempFinalIgnoreSetsState = ignoreSetQueue.last();
if (!whileHeldStatus)
{
if (tempButtonPressed && !tempFinalIgnoreSetsState &&
setSelectionCondition == SetChangeWhileHeld && !currentRelease)
{
setChangeTimer.start(0);
quitEvent = true;
}
}
}
}
/**
* @brief Obtain the appropriate key press time for the current event.
* Order of preference: active key press time slot value ->
* profile value -> program default value.
* @return Appropriate key press time for current event.
*/
unsigned int JoyButton::getPreferredKeyPressTime()
{
unsigned int tempPressTime = InputDevice::DEFAULTKEYPRESSTIME;
if (currentKeyPress && currentKeyPress->getSlotCode() > 0)
{
tempPressTime = static_cast<unsigned int>(currentKeyPress->getSlotCode());
}
else if (parentSet->getInputDevice()->getDeviceKeyPressTime() > 0)
{
tempPressTime = parentSet->getInputDevice()->getDeviceKeyPressTime();
}
return tempPressTime;
}
void JoyButton::setCycleResetTime(unsigned int interval)
{
if (interval >= MINCYCLERESETTIME)
{
unsigned int ceiling = MAXCYCLERESETTIME;
unsigned int temp = qBound(MINCYCLERESETTIME, interval, ceiling);
cycleResetInterval = temp;
emit propertyUpdated();
}
else
{
interval = 0;
cycleResetActive = false;
emit propertyUpdated();
}
}
unsigned int JoyButton::getCycleResetTime()
{
return cycleResetInterval;
}
void JoyButton::setCycleResetStatus(bool enabled)
{
cycleResetActive = enabled;
emit propertyUpdated();
}
bool JoyButton::isCycleResetActive()
{
return cycleResetActive;
}
void JoyButton::establishPropertyUpdatedConnections()
{
connect(this, SIGNAL(slotsChanged()), parentSet->getInputDevice(), SLOT(profileEdited()));
connect(this, SIGNAL(propertyUpdated()), parentSet->getInputDevice(), SLOT(profileEdited()));
}
void JoyButton::disconnectPropertyUpdatedConnections()
{
disconnect(this, SIGNAL(slotsChanged()), 0, 0);
disconnect(this, SIGNAL(propertyUpdated()), parentSet->getInputDevice(), SLOT(profileEdited()));
}
/**
* @brief Change initial settings used for mouse event timer being used by
* the application.
*/
void JoyButton::establishMouseTimerConnections()
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (staticMouseEventTimer.timerType() != Qt::PreciseTimer)
{
staticMouseEventTimer.setTimerType(Qt::PreciseTimer);
}
#endif
// Only one connection will be made for each.
connect(&staticMouseEventTimer, SIGNAL(timeout()), &mouseHelper,
SLOT(mouseEvent()), Qt::UniqueConnection);
if (staticMouseEventTimer.interval() != IDLEMOUSEREFRESHRATE)
{
staticMouseEventTimer.setInterval(IDLEMOUSEREFRESHRATE);
}
/*if (!staticMouseEventTimer.isActive())
{
lastMouseTime.start();
staticMouseEventTimer.start(IDLEMOUSEREFRESHRATE);
}
*/
}
void JoyButton::setSpringRelativeStatus(bool value)
{
if (value != relativeSpring)
{
if (value)
{
setSpringDeadCircleMultiplier(0);
}
relativeSpring = value;
emit propertyUpdated();
}
}
bool JoyButton::isRelativeSpring()
{
return relativeSpring;
}
/**
* @brief Copy assignments and properties from one button to another.
* Used for set copying.
* @param Button instance that should be modified.
*/
void JoyButton::copyAssignments(JoyButton *destButton)
{
destButton->eventReset();
destButton->assignmentsLock.lockForWrite();
destButton->assignments.clear();
destButton->assignmentsLock.unlock();
assignmentsLock.lockForWrite();
QListIterator<JoyButtonSlot*> iter(assignments);
while (iter.hasNext())
{
JoyButtonSlot *slot = iter.next();
JoyButtonSlot *newslot = new JoyButtonSlot(slot, destButton);
destButton->insertAssignedSlot(newslot, false);
}
assignmentsLock.unlock();
destButton->toggle = toggle;
destButton->turboInterval = turboInterval;
destButton->useTurbo = useTurbo;
destButton->mouseSpeedX = mouseSpeedX;
destButton->mouseSpeedY = mouseSpeedY;
destButton->wheelSpeedX = wheelSpeedX;
destButton->wheelSpeedY = wheelSpeedY;
destButton->mouseMode = mouseMode;
destButton->mouseCurve = mouseCurve;
destButton->springWidth = springWidth;
destButton->springHeight = springHeight;
destButton->sensitivity = sensitivity;
//destButton->setSelection = setSelection;
//destButton->setSelectionCondition = setSelectionCondition;
destButton->buttonName = buttonName;
destButton->actionName = actionName;
destButton->cycleResetActive = cycleResetActive;
destButton->cycleResetInterval = cycleResetInterval;
destButton->relativeSpring = relativeSpring;
destButton->currentTurboMode = currentTurboMode;
destButton->easingDuration = easingDuration;
destButton->extraAccelerationEnabled = extraAccelerationEnabled;
destButton->extraAccelerationMultiplier = extraAccelerationMultiplier;
destButton->minMouseDistanceAccelThreshold = minMouseDistanceAccelThreshold;
destButton->maxMouseDistanceAccelThreshold = maxMouseDistanceAccelThreshold;
destButton->startAccelMultiplier = startAccelMultiplier;
destButton->springDeadCircleMultiplier = springDeadCircleMultiplier;
destButton->extraAccelCurve = extraAccelCurve;
destButton->buildActiveZoneSummaryString();
if (!destButton->isDefault())
{
emit propertyUpdated();
}
}
/**
* @brief Set the turbo mode that the button should use
* @param Mode that should be used
*/
void JoyButton::setTurboMode(TurboMode mode)
{
currentTurboMode = mode;
}
/**
* @brief Get currently assigned turbo mode
* @return Currently assigned turbo mode
*/
JoyButton::TurboMode JoyButton::getTurboMode()
{
return currentTurboMode;
}
/**
* @brief Check if button should be considered a part of a real controller
* axis. Needed for some dialogs so the program won't have to resort to
* type checking.
* @return Status of being part of a real controller axis
*/
bool JoyButton::isPartRealAxis()
{
return false;
}
/**
* @brief Calculate maximum mouse speed when using a given mouse curve.
* @param Mouse curve
* @param Mouse speed value
* @return Final mouse speed
*/
int JoyButton::calculateFinalMouseSpeed(JoyMouseCurve curve, int value)
{
int result = JoyAxis::JOYSPEED * value;
switch (curve)
{
case QuadraticExtremeCurve:
case EasingQuadraticCurve:
case EasingCubicCurve:
{
result *= 1.5;
break;
}
}
return result;
}
void JoyButton::setEasingDuration(double value)
{
if (value >= MINIMUMEASINGDURATION && value <= MAXIMUMEASINGDURATION &&
value != easingDuration)
{
easingDuration = value;
emit propertyUpdated();
}
}
double JoyButton::getEasingDuration()
{
return easingDuration;
}
JoyButtonMouseHelper* JoyButton::getMouseHelper()
{
return &mouseHelper;
}
/**
* @brief Get the list of buttons that have a pending mouse movement event.
* @return QList<JoyButton*>*
*/
QList<JoyButton*>* JoyButton::getPendingMouseButtons()
{
return &pendingMouseButtons;
}
bool JoyButton::hasCursorEvents()
{
return (cursorXSpeeds.length() != 0) || (cursorYSpeeds.length() != 0);
}
bool JoyButton::hasSpringEvents()
{
return (springXSpeeds.length() != 0) || (springYSpeeds.length() != 0);
}
/**
* @brief Get the weight modifier being used for mouse smoothing.
* @return Weight modifier in the range of 0.0 - 1.0.
*/
double JoyButton::getWeightModifier()
{
return weightModifier;
}
/**
* @brief Set the weight modifier to use for mouse smoothing.
* @param Weight modifier in the range of 0.0 - 1.0.
*/
void JoyButton::setWeightModifier(double modifier)
{
if (modifier >= 0.0 && modifier <= MAXIMUMWEIGHTMODIFIER)
{
weightModifier = modifier;
}
}
/**
* @brief Get mouse history buffer size.
* @return Mouse history buffer size
*/
int JoyButton::getMouseHistorySize()
{
return mouseHistorySize;
}
/**
* @brief Set mouse history buffer size used for mouse smoothing.
* @param Mouse history buffer size
*/
void JoyButton::setMouseHistorySize(int size)
{
if (size >= 1 && size <= MAXIMUMMOUSEHISTORYSIZE)
{
mouseHistoryX.clear();
mouseHistoryY.clear();
mouseHistorySize = size;
}
}
/**
* @brief Get active mouse movement refresh rate.
* @return
*/
int JoyButton::getMouseRefreshRate()
{
return mouseRefreshRate;
}
/**
* @brief Set the mouse refresh rate when a mouse slot is active.
* @param Refresh rate in ms.
*/
void JoyButton::setMouseRefreshRate(int refresh)
{
if (refresh >= 1 && refresh <= 16)
{
mouseRefreshRate = refresh;
int temp = IDLEMOUSEREFRESHRATE;
//IDLEMOUSEREFRESHRATE = mouseRefreshRate * 20;
if (staticMouseEventTimer.isActive())
{
testOldMouseTime.restart();
//lastMouseTime.restart();
int tempInterval = staticMouseEventTimer.interval();
if (tempInterval != temp &&
tempInterval != 0)
{
QMetaObject::invokeMethod(&staticMouseEventTimer, "start",
Q_ARG(int, mouseRefreshRate));
}
else
{
// Restart QTimer to keep QTimer in line with QTime
QMetaObject::invokeMethod(&staticMouseEventTimer, "start",
Q_ARG(int, temp));
}
// Clear current mouse history
mouseHistoryX.clear();
mouseHistoryY.clear();
}
else
{
staticMouseEventTimer.setInterval(IDLEMOUSEREFRESHRATE);
}
mouseHelper.carryMouseRefreshRateUpdate(mouseRefreshRate);
}
}
/**
* @brief Get the gamepad poll rate used by the application.
* @return Poll rate in ms.
*/
int JoyButton::getGamepadRefreshRate()
{
return gamepadRefreshRate;
}
/**
* @brief Set the gamepad poll rate to be used in the application.
* @param Poll rate in ms.
*/
void JoyButton::setGamepadRefreshRate(int refresh)
{
if (refresh >= 1 && refresh <= 16)
{
gamepadRefreshRate = refresh;
mouseHelper.carryGamePollRateUpdate(gamepadRefreshRate);
}
}
/**
* @brief Check if turbo should be disabled for a slot
* @param JoyButtonSlot to check
*/
void JoyButton::checkTurboCondition(JoyButtonSlot *slot)
{
JoyButtonSlot::JoySlotInputAction mode = slot->getSlotMode();
switch (mode)
{
case JoyButtonSlot::JoyPause:
case JoyButtonSlot::JoyHold:
case JoyButtonSlot::JoyDistance:
case JoyButtonSlot::JoyRelease:
case JoyButtonSlot::JoyLoadProfile:
case JoyButtonSlot::JoySetChange:
{
setUseTurbo(false);
break;
}
}
}
void JoyButton::resetProperties()
{
currentCycle = 0;
previousCycle = 0;
currentPause = 0;
currentHold = 0;
currentDistance = 0;
currentRawValue = 0;
currentMouseEvent = 0;
currentRelease = 0;
currentWheelVerticalEvent = 0;
currentWheelHorizontalEvent = 0;
currentKeyPress = 0;
currentDelay = 0;
currentSetChangeSlot = 0;
isKeyPressed = isButtonPressed = false;
quitEvent = true;
toggle = false;
turboInterval = 0;
isDown = false;
toggleActiveState = false;
useTurbo = false;
mouseSpeedX = 50;
mouseSpeedY = 50;
wheelSpeedX = 20;
wheelSpeedY = 20;
mouseMode = MouseCursor;
mouseCurve = DEFAULTMOUSECURVE;
springWidth = 0;
springHeight = 0;
sensitivity = 1.0;
setSelection = -1;
setSelectionCondition = SetChangeDisabled;
ignoresets = false;
ignoreEvents = false;
whileHeldStatus = false;
buttonName.clear();
actionName.clear();
cycleResetActive = false;
cycleResetInterval = 0;
relativeSpring = false;
lastDistance = 0.0;
currentAccelMulti = 0.0;
lastAccelerationDistance = 0.0;
lastMouseDistance = 0.0;
currentMouseDistance = 0.0;
updateLastMouseDistance = false;
updateStartingMouseDistance = false;
updateOldAccelMulti = 0.0;
updateInitAccelValues = true;
currentAccelerationDistance = 0.0;
startingAccelerationDistance = 0.0;
lastWheelVerticalDistance = 0.0;
lastWheelHorizontalDistance = 0.0;
tempTurboInterval = 0;
//currentTurboMode = GradientTurbo;
oldAccelMulti = 0.0;
accelTravel = 0.0;
currentTurboMode = DEFAULTTURBOMODE;
easingDuration = DEFAULTEASINGDURATION;
springDeadCircleMultiplier = DEFAULTSPRINGRELEASERADIUS;
pendingEvent = false;
pendingPress = false;
pendingIgnoreSets = false;
extraAccelerationEnabled = false;
extraAccelerationMultiplier = DEFAULTEXTRACCELVALUE;
minMouseDistanceAccelThreshold = DEFAULTMINACCELTHRESHOLD;
maxMouseDistanceAccelThreshold = DEFAULTMAXACCELTHRESHOLD;
startAccelMultiplier = DEFAULTSTARTACCELMULTIPLIER;
accelDuration = DEFAULTACCELEASINGDURATION;
extraAccelCurve = LinearAccelCurve;
activeZoneStringLock.lockForWrite();
activeZoneString = tr("[NO KEY]");
activeZoneStringLock.unlock();
}
bool JoyButton::isModifierButton()
{
return false;
}
void JoyButton::resetActiveButtonMouseDistances()
{
mouseHelper.resetButtonMouseDistances();
}
void JoyButton::resetAccelerationDistances()
{
if (updateLastMouseDistance)
{
lastAccelerationDistance = currentAccelerationDistance;
lastMouseDistance = currentMouseDistance;
updateLastMouseDistance = false;
}
if (updateStartingMouseDistance)
{
startingAccelerationDistance = lastAccelerationDistance;
updateStartingMouseDistance = false;
}
if (updateOldAccelMulti >= 0.0)
{
oldAccelMulti = updateOldAccelMulti;
updateOldAccelMulti = 0.0;
}
currentAccelerationDistance = getAccelerationDistance();
currentMouseDistance = getMouseDistanceFromDeadZone();
}
void JoyButton::initializeDistanceValues()
{
lastAccelerationDistance = getLastAccelerationDistance();
currentAccelerationDistance = getAccelerationDistance();
startingAccelerationDistance = lastAccelerationDistance;
lastMouseDistance = getLastMouseDistanceFromDeadZone();
currentMouseDistance = getMouseDistanceFromDeadZone();
}
double JoyButton::getLastMouseDistanceFromDeadZone()
{
return lastMouseDistance;
}
double JoyButton::getLastAccelerationDistance()
{
return lastAccelerationDistance;
}
void JoyButton::copyLastMouseDistanceFromDeadZone(JoyButton *srcButton)
{
this->lastMouseDistance = srcButton->lastMouseDistance;
}
void JoyButton::copyLastAccelerationDistance(JoyButton *srcButton)
{
this->lastAccelerationDistance = srcButton->lastAccelerationDistance;
}
bool JoyButton::isExtraAccelerationEnabled()
{
return extraAccelerationEnabled;
}
double JoyButton::getExtraAccelerationMultiplier()
{
return extraAccelerationMultiplier;
}
void JoyButton::setExtraAccelerationStatus(bool status)
{
if (isPartRealAxis())
{
extraAccelerationEnabled = status;
emit propertyUpdated();
}
else
{
extraAccelerationEnabled = false;
}
}
void JoyButton::setExtraAccelerationMultiplier(double value)
{
if (value >= 1.0 && value <= 200.0)
{
extraAccelerationMultiplier = value;
emit propertyUpdated();
}
}
void JoyButton::setMinAccelThreshold(double value)
{
if (value >= 1.0 && value <= 100.0 && value <= maxMouseDistanceAccelThreshold)
{
minMouseDistanceAccelThreshold = value;
emit propertyUpdated();
}
}
double JoyButton::getMinAccelThreshold()
{
return minMouseDistanceAccelThreshold;
}
void JoyButton::setMaxAccelThreshold(double value)
{
if (value >= 1.0 && value <= 100.0 && value >= minMouseDistanceAccelThreshold)
{
maxMouseDistanceAccelThreshold = value;
emit propertyUpdated();
}
}
double JoyButton::getMaxAccelThreshold()
{
return maxMouseDistanceAccelThreshold;
}
void JoyButton::setStartAccelMultiplier(double value)
{
if (value >= 0.0 && value <= 100.0)
{
startAccelMultiplier = value;
emit propertyUpdated();
}
}
double JoyButton::getStartAccelMultiplier()
{
return startAccelMultiplier;
}
int JoyButton::getSpringModeScreen()
{
return springModeScreen;
}
void JoyButton::setSpringModeScreen(int screen)
{
if (screen >= -1)
{
springModeScreen = screen;
}
}
void JoyButton::setAccelExtraDuration(double value)
{
if (value >= 0.0 && value <= 5.0)
{
accelDuration = value;
emit propertyUpdated();
}
}
double JoyButton::getAccelExtraDuration()
{
return accelDuration;
}
bool JoyButton::hasFutureSpringEvents()
{
bool result = false;
QListIterator<JoyButton*> iter(pendingMouseButtons);
while (iter.hasNext())
{
JoyButton *temp = iter.next();
if (temp->getMouseMode() == MouseSpring)
{
result = true;
iter.toBack();
}
}
return result;
}
void JoyButton::setSpringDeadCircleMultiplier(int value)
{
if (value >= 0 && value <= 100)
{
springDeadCircleMultiplier = value;
emit propertyUpdated();
}
}
int JoyButton::getSpringDeadCircleMultiplier()
{
return springDeadCircleMultiplier;
}
double JoyButton::getCurrentSpringDeadCircle()
{
return (springDeadCircleMultiplier * 0.01);
}
void JoyButton::restartLastMouseTime()
{
testOldMouseTime.restart();
//lastMouseTime.restart();
}
void JoyButton::setStaticMouseThread(QThread *thread)
{
int oldInterval = staticMouseEventTimer.interval();
if (oldInterval == 0)
{
oldInterval = IDLEMOUSEREFRESHRATE;
}
staticMouseEventTimer.moveToThread(thread);
mouseHelper.moveToThread(thread);
QMetaObject::invokeMethod(&staticMouseEventTimer, "start",
Q_ARG(int, oldInterval));
//lastMouseTime.start();
testOldMouseTime.start();
#ifdef Q_OS_WIN
repeatHelper.moveToThread(thread);
#endif
}
void JoyButton::indirectStaticMouseThread(QThread *thread)
{
QMetaObject::invokeMethod(&staticMouseEventTimer, "stop");
#ifdef Q_OS_WIN
QMetaObject::invokeMethod(repeatHelper.getRepeatTimer(), "stop");
#endif
QMetaObject::invokeMethod(&mouseHelper, "changeThread",
Q_ARG(QThread*, thread));
}
bool JoyButton::shouldInvokeMouseEvents()
{
bool result = false;
if (pendingMouseButtons.size() > 0 && staticMouseEventTimer.isActive())
{
int timerInterval = staticMouseEventTimer.interval();
if (timerInterval == 0)
{
result = true;
}
//else if (lastMouseTime.elapsed() >= timerInterval)
//else if (lastMouseTime.hasExpired(timerInterval))
else if (testOldMouseTime.elapsed() >= timerInterval)
{
result = true;
}
}
return result;
}
void JoyButton::invokeMouseEvents()
{
mouseHelper.mouseEvent();
}
bool JoyButton::hasActiveSlots()
{
return !activeSlots.isEmpty();
}
void JoyButton::setExtraAccelerationCurve(JoyExtraAccelerationCurve curve)
{
extraAccelCurve = curve;
emit propertyUpdated();
}
JoyButton::JoyExtraAccelerationCurve JoyButton::getExtraAccelerationCurve()
{
return extraAccelCurve;
}
void JoyButton::copyExtraAccelerationState(JoyButton *srcButton)
{
this->currentAccelMulti = srcButton->currentAccelMulti;
this->oldAccelMulti = srcButton->oldAccelMulti;
this->accelTravel = srcButton->accelTravel;
this->startingAccelerationDistance = srcButton->startingAccelerationDistance;
this->lastAccelerationDistance = srcButton->lastAccelerationDistance;
this->lastMouseDistance = srcButton->lastMouseDistance;
this->accelExtraDurationTime.setHMS(srcButton->accelExtraDurationTime.hour(),
srcButton->accelExtraDurationTime.minute(),
srcButton->accelExtraDurationTime.second(),
srcButton->accelExtraDurationTime.msec());
this->updateOldAccelMulti = srcButton->updateOldAccelMulti;
this->updateStartingMouseDistance = srcButton->updateStartingMouseDistance;
this->updateLastMouseDistance = srcButton->lastMouseDistance;
}
void JoyButton::setUpdateInitAccel(bool state)
{
this->updateInitAccelValues = state;
}
``` | /content/code_sandbox/src/joybutton.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 36,079 |
```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 <QDataStream>
#include <X11/Xlib.h>
#include <X11/cursorfont.h> // for XGrabPointer
#include "x11extras.h"
#include "qtx11keymapper.h"
#include "unixcapturewindowutility.h"
UnixCaptureWindowUtility::UnixCaptureWindowUtility(QObject *parent) :
QObject(parent)
{
targetPath = "";
failed = false;
targetWindow = None;
}
/**
* @brief Attempt to capture window selected with the mouse
*/
void UnixCaptureWindowUtility::attemptWindowCapture()
{
// Only create instance when needed.
static QtX11KeyMapper x11KeyMapper;
targetPath = "";
targetWindow = None;
failed = false;
bool escaped = false;
Cursor cursor;
Window target_window = None;
int status = 0;
Display *display = 0;
QString potentialXDisplayString = X11Extras::getInstance()->getXDisplayString();
if (!potentialXDisplayString.isEmpty())
{
QByteArray tempByteArray = potentialXDisplayString.toLocal8Bit();
display = XOpenDisplay(tempByteArray.constData());
}
else
{
display = XOpenDisplay(NULL);
}
Window rootWin = XDefaultRootWindow(display);
cursor = XCreateFontCursor(display, XC_crosshair);
status = XGrabPointer(display, rootWin, False, ButtonPressMask,
GrabModeSync, GrabModeAsync, None,
cursor, CurrentTime);
if (status == Success)
{
XGrabKey(display, XKeysymToKeycode(display, x11KeyMapper.returnVirtualKey(Qt::Key_Escape)), 0, rootWin,
true, GrabModeAsync, GrabModeAsync);
XEvent event;
XAllowEvents(display, SyncPointer, CurrentTime);
XWindowEvent(display, rootWin, ButtonPressMask|KeyPressMask, &event);
switch (event.type)
{
case (ButtonPress):
target_window = event.xbutton.subwindow;
if (target_window == None)
{
target_window = event.xbutton.window;
}
//qDebug() << QString::number(target_window, 16);
break;
case (KeyPress):
{
escaped = true;
break;
}
}
XUngrabKey(display, XKeysymToKeycode(display, x11KeyMapper.returnVirtualKey(Qt::Key_Escape)),
0, rootWin);
XUngrabPointer(display, CurrentTime);
XFlush(display);
}
if (target_window != None)
{
targetWindow = target_window;
}
else if (!escaped)
{
failed = true;
}
XCloseDisplay(display);
emit captureFinished();
}
/**
* @brief Get the saved path for a window
* @return Program path
*/
QString UnixCaptureWindowUtility::getTargetPath()
{
return targetPath;
}
/**
* @brief Check if attemptWindowCapture failed to obtain an application
* @return Error status
*/
bool UnixCaptureWindowUtility::hasFailed()
{
return failed;
}
unsigned long UnixCaptureWindowUtility::getTargetWindow()
{
return targetWindow;
}
``` | /content/code_sandbox/src/unixcapturewindowutility.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 770 |
```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 FLASHBUTTONWIDGET_H
#define FLASHBUTTONWIDGET_H
#include <QPushButton>
#include <QPaintEvent>
class FlashButtonWidget : public QPushButton
{
Q_OBJECT
Q_PROPERTY(bool isflashing READ isButtonFlashing)
public:
explicit FlashButtonWidget(QWidget *parent = 0);
explicit FlashButtonWidget(bool displayNames, QWidget *parent = 0);
bool isButtonFlashing();
void setDisplayNames(bool display);
bool isDisplayingNames();
protected:
virtual void paintEvent(QPaintEvent *event);
virtual QString generateLabel() = 0;
virtual void retranslateUi();
bool isflashing;
bool displayNames;
bool leftAlignText;
signals:
void flashed(bool flashing);
public slots:
void refreshLabel();
void toggleNameDisplay();
virtual void disableFlashes() = 0;
virtual void enableFlashes() = 0;
protected slots:
void flash();
void unflash();
};
#endif // FLASHBUTTONWIDGET_H
``` | /content/code_sandbox/src/flashbuttonwidget.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 310 |
```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 EDITALLDEFAULTAUTOPROFILEDIALOG_H
#define EDITALLDEFAULTAUTOPROFILEDIALOG_H
#include <QDialog>
#include "autoprofileinfo.h"
#include "antimicrosettings.h"
namespace Ui {
class EditAllDefaultAutoProfileDialog;
}
class EditAllDefaultAutoProfileDialog : public QDialog
{
Q_OBJECT
public:
explicit EditAllDefaultAutoProfileDialog(AutoProfileInfo *info, AntiMicroSettings *settings,
QWidget *parent = 0);
~EditAllDefaultAutoProfileDialog();
AutoProfileInfo* getAutoProfile();
protected:
virtual void accept();
AutoProfileInfo *info;
AntiMicroSettings *settings;
private:
Ui::EditAllDefaultAutoProfileDialog *ui;
private slots:
void openProfileBrowseDialog();
void saveAutoProfileInformation();
};
#endif // EDITALLDEFAULTAUTOPROFILEDIALOG_H
``` | /content/code_sandbox/src/editalldefaultautoprofiledialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 284 |
```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 <QTime>
#include <QTimer>
#include <QEventLoop>
#include <QMapIterator>
#include "inputdaemon.h"
#include "logger.h"
#include "common.h"
//#define USE_NEW_ADD
#define USE_NEW_REFRESH
const int InputDaemon::GAMECONTROLLERTRIGGERRELEASE = 16384;
InputDaemon::InputDaemon(QMap<SDL_JoystickID, InputDevice*> *joysticks,
AntiMicroSettings *settings,
bool graphical, QObject *parent) :
QObject(parent),
pollResetTimer(this)
{
this->joysticks = joysticks;
this->stopped = false;
this->graphical = graphical;
this->settings = settings;
eventWorker = new SDLEventReader(joysticks, settings);
refreshJoysticks();
sdlWorkerThread = 0;
if (graphical)
{
sdlWorkerThread = new QThread();
eventWorker->moveToThread(sdlWorkerThread);
}
if (graphical)
{
connect(sdlWorkerThread, SIGNAL(started()), eventWorker, SLOT(performWork()));
connect(eventWorker, SIGNAL(eventRaised()), this, SLOT(run()));
connect(JoyButton::getMouseHelper(), SIGNAL(gamepadRefreshRateUpdated(uint)),
eventWorker, SLOT(updatePollRate(uint)));
connect(JoyButton::getMouseHelper(), SIGNAL(gamepadRefreshRateUpdated(uint)),
this, SLOT(updatePollResetRate(uint)));
connect(JoyButton::getMouseHelper(), SIGNAL(mouseRefreshRateUpdated(uint)),
this, SLOT(updatePollResetRate(uint)));
// Timer in case SDL does not produce an axis event during a joystick
// poll.
pollResetTimer.setSingleShot(true);
pollResetTimer.setInterval(
qMax(JoyButton::getMouseRefreshRate(),
JoyButton::getGamepadRefreshRate()) + 1);
connect(&pollResetTimer, SIGNAL(timeout()), this,
SLOT(resetActiveButtonMouseDistances()));
//sdlWorkerThread->start(QThread::HighPriority);
//QMetaObject::invokeMethod(eventWorker, "performWork", Qt::QueuedConnection);
}
}
InputDaemon::~InputDaemon()
{
if (eventWorker)
{
quit();
}
if (sdlWorkerThread)
{
sdlWorkerThread->quit();
sdlWorkerThread->wait();
delete sdlWorkerThread;
sdlWorkerThread = 0;
}
}
void InputDaemon::startWorker()
{
if (!sdlWorkerThread->isRunning())
{
sdlWorkerThread->start(QThread::HighPriority);
//pollResetTimer.start();
}
}
void InputDaemon::run ()
{
PadderCommon::inputDaemonMutex.lock();
// SDL has found events. The timeout is not necessary.
pollResetTimer.stop();
if (!stopped)
{
//Logger::LogInfo(QString("Gamepad Poll %1").arg(QTime::currentTime().toString("hh:mm:ss.zzz")));
JoyButton::resetActiveButtonMouseDistances();
QQueue<SDL_Event> sdlEventQueue;
firstInputPass(&sdlEventQueue);
#ifdef USE_SDL_2
modifyUnplugEvents(&sdlEventQueue);
#endif
secondInputPass(&sdlEventQueue);
clearBitArrayStatusInstances();
}
if (stopped)
{
if (joysticks->size() > 0)
{
emit complete(joysticks->value(0));
}
emit complete();
stopped = false;
}
else
{
QTimer::singleShot(0, eventWorker, SLOT(performWork()));
pollResetTimer.start();
}
PadderCommon::inputDaemonMutex.unlock();
}
void InputDaemon::refreshJoysticks()
{
QMapIterator<SDL_JoystickID, InputDevice*> iter(*joysticks);
while (iter.hasNext())
{
InputDevice *joystick = iter.next().value();
if (joystick)
{
delete joystick;
joystick = 0;
}
}
joysticks->clear();
#ifdef USE_SDL_2
trackjoysticks.clear();
trackcontrollers.clear();
settings->getLock()->lock();
settings->beginGroup("Mappings");
#endif
for (int i=0; i < SDL_NumJoysticks(); i++)
{
#ifdef USE_SDL_2
#ifdef USE_NEW_REFRESH
int index = i;
// Check if device is considered a Game Controller at the start.
if (SDL_IsGameController(index))
{
SDL_GameController *controller = SDL_GameControllerOpen(index);
if (controller)
{
SDL_Joystick *sdlStick = SDL_GameControllerGetJoystick(controller);
SDL_JoystickID tempJoystickID = SDL_JoystickInstanceID(sdlStick);
// Check if device has already been grabbed.
if (!joysticks->contains(tempJoystickID))
{
//settings->getLock()->lock();
//settings->beginGroup("Mappings");
QString temp;
SDL_JoystickGUID tempGUID = SDL_JoystickGetGUID(sdlStick);
char guidString[65] = {'0'};
SDL_JoystickGetGUIDString(tempGUID, guidString, sizeof(guidString));
temp = QString(guidString);
bool disableGameController = settings->value(QString("%1Disable").arg(temp), false).toBool();
//settings->endGroup();
//settings->getLock()->unlock();
// Check if user has designated device Joystick mode.
if (!disableGameController)
{
GameController *damncontroller = new GameController(controller, index, settings, this);
connect(damncontroller, SIGNAL(requestWait()), eventWorker, SLOT(haltServices()));
joysticks->insert(tempJoystickID, damncontroller);
trackcontrollers.insert(tempJoystickID, damncontroller);
emit deviceAdded(damncontroller);
}
else
{
// Check if joystick is considered connected.
/*SDL_Joystick *joystick = SDL_JoystickOpen(index);
if (joystick)
{
SDL_JoystickID tempJoystickID = SDL_JoystickInstanceID(joystick);
Joystick *curJoystick = new Joystick(joystick, index, settings, this);
joysticks->insert(tempJoystickID, curJoystick);
trackjoysticks.insert(tempJoystickID, curJoystick);
emit deviceAdded(curJoystick);
}
*/
Joystick *joystick = openJoystickDevice(index);
if (joystick)
{
emit deviceAdded(joystick);
}
}
}
else
{
// Make sure to decrement reference count
SDL_GameControllerClose(controller);
}
}
}
else
{
// Check if joystick is considered connected.
/*SDL_Joystick *joystick = SDL_JoystickOpen(index);
if (joystick)
{
SDL_JoystickID tempJoystickID = SDL_JoystickInstanceID(joystick);
Joystick *curJoystick = new Joystick(joystick, index, settings, this);
joysticks->insert(tempJoystickID, curJoystick);
trackjoysticks.insert(tempJoystickID, curJoystick);
emit deviceAdded(curJoystick);
}
*/
Joystick *joystick = openJoystickDevice(index);
if (joystick)
{
emit deviceAdded(joystick);
}
}
#else
SDL_Joystick *joystick = SDL_JoystickOpen(i);
if (joystick)
{
QString temp;
SDL_JoystickGUID tempGUID = SDL_JoystickGetGUID(joystick);
char guidString[65] = {'0'};
SDL_JoystickGetGUIDString(tempGUID, guidString, sizeof(guidString));
temp = QString(guidString);
bool disableGameController = settings->value(QString("%1Disable").arg(temp), false).toBool();
if (SDL_IsGameController(i) && !disableGameController)
{
SDL_GameController *controller = SDL_GameControllerOpen(i);
GameController *damncontroller = new GameController(controller, i, settings, this);
connect(damncontroller, SIGNAL(requestWait()), eventWorker, SLOT(haltServices()));
SDL_Joystick *sdlStick = SDL_GameControllerGetJoystick(controller);
SDL_JoystickID joystickID = SDL_JoystickInstanceID(sdlStick);
joysticks->insert(joystickID, damncontroller);
trackcontrollers.insert(joystickID, damncontroller);
}
else
{
Joystick *curJoystick = new Joystick(joystick, i, settings, this);
connect(curJoystick, SIGNAL(requestWait()), eventWorker, SLOT(haltServices()));
SDL_JoystickID joystickID = SDL_JoystickInstanceID(joystick);
joysticks->insert(joystickID, curJoystick);
trackjoysticks.insert(joystickID, curJoystick);
}
}
#endif
#else
SDL_Joystick *joystick = SDL_JoystickOpen(i);
if (joystick)
{
Joystick *curJoystick = new Joystick(joystick, i, settings, this);
connect(curJoystick, SIGNAL(requestWait()), eventWorker, SLOT(haltServices()));
joysticks->insert(i, curJoystick);
}
#endif
}
#ifdef USE_SDL_2
settings->endGroup();
settings->getLock()->unlock();
#endif
emit joysticksRefreshed(joysticks);
}
void InputDaemon::deleteJoysticks()
{
QMapIterator<SDL_JoystickID, InputDevice*> iter(*joysticks);
while (iter.hasNext())
{
InputDevice *joystick = iter.next().value();
if (joystick)
{
delete joystick;
joystick = 0;
}
}
joysticks->clear();
#ifdef USE_SDL_2
trackjoysticks.clear();
trackcontrollers.clear();
#endif
}
void InputDaemon::stop()
{
stopped = true;
pollResetTimer.stop();
}
void InputDaemon::refresh()
{
stop();
Logger::LogInfo("Refreshing joystick list");
QEventLoop q;
connect(eventWorker, SIGNAL(sdlStarted()), &q, SLOT(quit()));
QMetaObject::invokeMethod(eventWorker, "refresh", Qt::BlockingQueuedConnection);
if (eventWorker->isSDLOpen())
{
q.exec();
}
disconnect(eventWorker, SIGNAL(sdlStarted()), &q, SLOT(quit()));
pollResetTimer.stop();
// Put in an extra delay before refreshing the joysticks
QTimer temp;
connect(&temp, SIGNAL(timeout()), &q, SLOT(quit()));
temp.start(100);
q.exec();
refreshJoysticks();
QTimer::singleShot(100, eventWorker, SLOT(performWork()));
stopped = false;
}
void InputDaemon::refreshJoystick(InputDevice *joystick)
{
joystick->reset();
emit joystickRefreshed(joystick);
}
void InputDaemon::quit()
{
stopped = true;
pollResetTimer.stop();
disconnect(eventWorker, SIGNAL(eventRaised()), this, 0);
// Wait for SDL to finish. Let worker destructor close SDL.
// Let InputDaemon destructor close thread instance.
if (graphical)
{
QMetaObject::invokeMethod(eventWorker, "stop");
QMetaObject::invokeMethod(eventWorker, "quit");
QMetaObject::invokeMethod(eventWorker, "deleteLater", Qt::BlockingQueuedConnection);
//QMetaObject::invokeMethod(eventWorker, "deleteLater");
}
else
{
eventWorker->stop();
eventWorker->quit();
delete eventWorker;
}
eventWorker = 0;
}
#ifdef USE_SDL_2
void InputDaemon::refreshMapping(QString mapping, InputDevice *device)
{
bool found = false;
for (int i=0; i < SDL_NumJoysticks() && !found; i++)
{
SDL_Joystick *joystick = SDL_JoystickOpen(i);
SDL_JoystickID joystickID = SDL_JoystickInstanceID(joystick);
if (device->getSDLJoystickID() == joystickID)
{
found = true;
if (SDL_IsGameController(i))
{
// Mapping string updated. Perform basic refresh
QByteArray tempbarray = mapping.toUtf8();
SDL_GameControllerAddMapping(tempbarray.data());
}
else
{
// Previously registered as a plain joystick. Add
// mapping and check for validity. If SDL accepts it,
// close current device and re-open as
// a game controller.
SDL_GameControllerAddMapping(mapping.toUtf8().constData());
if (SDL_IsGameController(i))
{
device->closeSDLDevice();
trackjoysticks.remove(joystickID);
joysticks->remove(joystickID);
SDL_GameController *controller = SDL_GameControllerOpen(i);
GameController *damncontroller = new GameController(controller, i, settings, this);
connect(damncontroller, SIGNAL(requestWait()), eventWorker, SLOT(haltServices()));
SDL_Joystick *sdlStick = SDL_GameControllerGetJoystick(controller);
joystickID = SDL_JoystickInstanceID(sdlStick);
joysticks->insert(joystickID, damncontroller);
trackcontrollers.insert(joystickID, damncontroller);
emit deviceUpdated(i, damncontroller);
}
}
}
// Make sure to decrement reference count
SDL_JoystickClose(joystick);
}
}
void InputDaemon::removeDevice(InputDevice *device)
{
if (device)
{
SDL_JoystickID deviceID = device->getSDLJoystickID();
joysticks->remove(deviceID);
trackjoysticks.remove(deviceID);
trackcontrollers.remove(deviceID);
refreshIndexes();
emit deviceRemoved(deviceID);
}
}
void InputDaemon::refreshIndexes()
{
for (int i = 0; i < SDL_NumJoysticks(); i++)
{
SDL_Joystick *joystick = SDL_JoystickOpen(i);
SDL_JoystickID joystickID = SDL_JoystickInstanceID(joystick);
// Make sure to decrement reference count
SDL_JoystickClose(joystick);
InputDevice *tempdevice = joysticks->value(joystickID);
if (tempdevice)
{
tempdevice->setIndex(i);
}
}
}
void InputDaemon::addInputDevice(int index)
{
#ifdef USE_NEW_ADD
// Check if device is considered a Game Controller at the start.
if (SDL_IsGameController(index))
{
SDL_GameController *controller = SDL_GameControllerOpen(index);
if (controller)
{
SDL_Joystick *sdlStick = SDL_GameControllerGetJoystick(controller);
SDL_JoystickID tempJoystickID = SDL_JoystickInstanceID(sdlStick);
// Check if device has already been grabbed.
if (!joysticks->contains(tempJoystickID))
{
settings->getLock()->lock();
settings->beginGroup("Mappings");
QString temp;
SDL_JoystickGUID tempGUID = SDL_JoystickGetGUID(sdlStick);
char guidString[65] = {'0'};
SDL_JoystickGetGUIDString(tempGUID, guidString, sizeof(guidString));
temp = QString(guidString);
bool disableGameController = settings->value(QString("%1Disable").arg(temp), false).toBool();
settings->endGroup();
settings->getLock()->unlock();
// Check if user has designated device Joystick mode.
if (!disableGameController)
{
GameController *damncontroller = new GameController(controller, index, settings, this);
connect(damncontroller, SIGNAL(requestWait()), eventWorker, SLOT(haltServices()));
joysticks->insert(tempJoystickID, damncontroller);
trackcontrollers.insert(tempJoystickID, damncontroller);
Logger::LogInfo(QString("New game controller found - #%1 [%2]")
.arg(index+1)
.arg(QTime::currentTime().toString("hh:mm:ss.zzz")));
emit deviceAdded(damncontroller);
}
else
{
// Check if joystick is considered connected.
/*SDL_Joystick *joystick = SDL_JoystickOpen(index);
if (joystick)
{
SDL_JoystickID tempJoystickID = SDL_JoystickInstanceID(joystick);
Joystick *curJoystick = new Joystick(joystick, index, settings, this);
joysticks->insert(tempJoystickID, curJoystick);
trackjoysticks.insert(tempJoystickID, curJoystick);
emit deviceAdded(curJoystick);
}
*/
Joystick *joystick = openJoystickDevice(index);
if (joystick)
{
Logger::LogInfo(QString("New joystick found - #%1 [%2]")
.arg(index+1)
.arg(QTime::currentTime().toString("hh:mm:ss.zzz")));
emit deviceAdded(joystick);
}
}
}
else
{
// Make sure to decrement reference count
SDL_GameControllerClose(controller);
}
}
}
else
{
// Check if joystick is considered connected.
/*SDL_Joystick *joystick = SDL_JoystickOpen(index);
if (joystick)
{
SDL_JoystickID tempJoystickID = SDL_JoystickInstanceID(joystick);
Joystick *curJoystick = new Joystick(joystick, index, settings, this);
joysticks->insert(tempJoystickID, curJoystick);
trackjoysticks.insert(tempJoystickID, curJoystick);
emit deviceAdded(curJoystick);
}
*/
Joystick *joystick = openJoystickDevice(index);
if (joystick)
{
Logger::LogInfo(QString("New joystick found - #%1 [%2]")
.arg(index+1)
.arg(QTime::currentTime().toString("hh:mm:ss.zzz")));
emit deviceAdded(joystick);
}
}
#else
SDL_Joystick *joystick = SDL_JoystickOpen(index);
if (joystick)
{
SDL_JoystickID tempJoystickID = SDL_JoystickInstanceID(joystick);
if (!joysticks->contains(tempJoystickID))
{
settings->getLock()->lock();
settings->beginGroup("Mappings");
QString temp;
SDL_JoystickGUID tempGUID = SDL_JoystickGetGUID(joystick);
char guidString[65] = {'0'};
SDL_JoystickGetGUIDString(tempGUID, guidString, sizeof(guidString));
temp = QString(guidString);
bool disableGameController = settings->value(QString("%1Disable").arg(temp), false).toBool();
if (SDL_IsGameController(index) && !disableGameController)
{
// Make sure to decrement reference count
SDL_JoystickClose(joystick);
SDL_GameController *controller = SDL_GameControllerOpen(index);
if (controller)
{
SDL_Joystick *sdlStick = SDL_GameControllerGetJoystick(controller);
SDL_JoystickID tempJoystickID = SDL_JoystickInstanceID(sdlStick);
if (!joysticks->contains(tempJoystickID))
{
GameController *damncontroller = new GameController(controller, index, settings, this);
connect(damncontroller, SIGNAL(requestWait()), eventWorker, SLOT(haltServices()));
joysticks->insert(tempJoystickID, damncontroller);
trackcontrollers.insert(tempJoystickID, damncontroller);
settings->endGroup();
settings->getLock()->unlock();
emit deviceAdded(damncontroller);
}
}
else
{
settings->endGroup();
settings->getLock()->unlock();
}
}
else
{
Joystick *curJoystick = new Joystick(joystick, index, settings, this);
joysticks->insert(tempJoystickID, curJoystick);
trackjoysticks.insert(tempJoystickID, curJoystick);
settings->endGroup();
settings->getLock()->unlock();
emit deviceAdded(curJoystick);
}
}
else
{
// Make sure to decrement reference count
SDL_JoystickClose(joystick);
}
}
#endif
}
Joystick *InputDaemon::openJoystickDevice(int index)
{
// Check if joystick is considered connected.
SDL_Joystick *joystick = SDL_JoystickOpen(index);
Joystick *curJoystick = 0;
if (joystick)
{
SDL_JoystickID tempJoystickID = SDL_JoystickInstanceID(joystick);
curJoystick = new Joystick(joystick, index, settings, this);
joysticks->insert(tempJoystickID, curJoystick);
trackjoysticks.insert(tempJoystickID, curJoystick);
}
return curJoystick;
}
#endif
InputDeviceBitArrayStatus*
InputDaemon::createOrGrabBitStatusEntry(QHash<InputDevice *, InputDeviceBitArrayStatus *> *statusHash,
InputDevice *device, bool readCurrent)
{
InputDeviceBitArrayStatus *bitArrayStatus = 0;
if (!statusHash->contains(device))
{
bitArrayStatus = new InputDeviceBitArrayStatus(device, readCurrent);
statusHash->insert(device, bitArrayStatus);
}
else
{
bitArrayStatus = statusHash->value(device);
}
return bitArrayStatus;
}
void InputDaemon::firstInputPass(QQueue<SDL_Event> *sdlEventQueue)
{
SDL_Event event;
while (SDL_PollEvent(&event) > 0)
{
switch (event.type)
{
case SDL_JOYBUTTONDOWN:
case SDL_JOYBUTTONUP:
{
#ifdef USE_SDL_2
InputDevice *joy = trackjoysticks.value(event.jbutton.which);
#else
InputDevice *joy = joysticks->value(event.jbutton.which);
#endif
if (joy)
{
SetJoystick* set = joy->getActiveSetJoystick();
JoyButton *button = set->getJoyButton(event.jbutton.button);
if (button)
{
//InputDeviceBitArrayStatus *temp = createOrGrabBitStatusEntry(&releaseEventsGenerated, joy, false);
//temp->changeButtonStatus(event.jbutton.button, event.type == SDL_JOYBUTTONUP);
InputDeviceBitArrayStatus *pending = createOrGrabBitStatusEntry(&pendingEventValues, joy);
pending->changeButtonStatus(event.jbutton.button,
event.type == SDL_JOYBUTTONDOWN ? true : false);
sdlEventQueue->append(event);
}
}
#ifdef USE_SDL_2
else
{
sdlEventQueue->append(event);
}
#endif
break;
}
case SDL_JOYAXISMOTION:
{
#ifdef USE_SDL_2
InputDevice *joy = trackjoysticks.value(event.jaxis.which);
#else
InputDevice *joy = joysticks->value(event.jaxis.which);
#endif
if (joy)
{
SetJoystick* set = joy->getActiveSetJoystick();
JoyAxis *axis = set->getJoyAxis(event.jaxis.axis);
if (axis)
{
InputDeviceBitArrayStatus *temp = createOrGrabBitStatusEntry(&releaseEventsGenerated, joy, false);
temp->changeAxesStatus(event.jaxis.axis, event.jaxis.axis == 0);
InputDeviceBitArrayStatus *pending = createOrGrabBitStatusEntry(&pendingEventValues, joy);
pending->changeAxesStatus(event.jaxis.axis, !axis->inDeadZone(event.jaxis.value));
sdlEventQueue->append(event);
}
}
#ifdef USE_SDL_2
else
{
sdlEventQueue->append(event);
}
#endif
break;
}
case SDL_JOYHATMOTION:
{
#ifdef USE_SDL_2
InputDevice *joy = trackjoysticks.value(event.jhat.which);
#else
InputDevice *joy = joysticks->value(event.jhat.which);
#endif
if (joy)
{
SetJoystick* set = joy->getActiveSetJoystick();
JoyDPad *dpad = set->getJoyDPad(event.jhat.hat);
if (dpad)
{
//InputDeviceBitArrayStatus *temp = createOrGrabBitStatusEntry(&releaseEventsGenerated, joy, false);
//temp->changeHatStatus(event.jhat.hat, event.jhat.value == 0);
InputDeviceBitArrayStatus *pending = createOrGrabBitStatusEntry(&pendingEventValues, joy);
pending->changeHatStatus(event.jhat.hat, event.jhat.value != 0 ? true : false);
sdlEventQueue->append(event);
}
}
#ifdef USE_SDL_2
else
{
sdlEventQueue->append(event);
}
#endif
break;
}
#ifdef USE_SDL_2
case SDL_CONTROLLERAXISMOTION:
{
InputDevice *joy = trackcontrollers.value(event.caxis.which);
if (joy)
{
SetJoystick* set = joy->getActiveSetJoystick();
JoyAxis *axis = set->getJoyAxis(event.caxis.axis);
if (axis)
{
InputDeviceBitArrayStatus *temp = createOrGrabBitStatusEntry(&releaseEventsGenerated, joy, false);
if (event.caxis.axis != SDL_CONTROLLER_AXIS_TRIGGERLEFT &&
event.caxis.axis != SDL_CONTROLLER_AXIS_TRIGGERRIGHT)
{
temp->changeAxesStatus(event.caxis.axis, event.caxis.value == 0);
}
else
{
temp->changeAxesStatus(event.caxis.axis, event.caxis.value == GAMECONTROLLERTRIGGERRELEASE);
}
InputDeviceBitArrayStatus *pending = createOrGrabBitStatusEntry(&pendingEventValues, joy);
pending->changeAxesStatus(event.caxis.axis, !axis->inDeadZone(event.caxis.value));
sdlEventQueue->append(event);
}
}
break;
}
case SDL_CONTROLLERBUTTONDOWN:
case SDL_CONTROLLERBUTTONUP:
{
InputDevice *joy = trackcontrollers.value(event.cbutton.which);
if (joy)
{
SetJoystick* set = joy->getActiveSetJoystick();
JoyButton *button = set->getJoyButton(event.cbutton.button);
if (button)
{
//InputDeviceBitArrayStatus *temp = createOrGrabBitStatusEntry(&releaseEventsGenerated, joy, false);
//temp->changeButtonStatus(event.cbutton.button, event.type == SDL_CONTROLLERBUTTONUP);
InputDeviceBitArrayStatus *pending = createOrGrabBitStatusEntry(&pendingEventValues, joy);
pending->changeButtonStatus(event.cbutton.button,
event.type == SDL_CONTROLLERBUTTONDOWN ? true : false);
sdlEventQueue->append(event);
}
}
break;
}
case SDL_JOYDEVICEREMOVED:
case SDL_JOYDEVICEADDED:
{
sdlEventQueue->append(event);
break;
}
#endif
case SDL_QUIT:
{
sdlEventQueue->append(event);
break;
}
}
}
}
#ifdef USE_SDL_2
void InputDaemon::modifyUnplugEvents(QQueue<SDL_Event> *sdlEventQueue)
{
QHashIterator<InputDevice*, InputDeviceBitArrayStatus*> genIter(releaseEventsGenerated);
while (genIter.hasNext())
{
genIter.next();
InputDevice *device = genIter.key();
InputDeviceBitArrayStatus *generatedTemp = genIter.value();
QBitArray tempBitArray = generatedTemp->generateFinalBitArray();
//qDebug() << "ARRAY: " << tempBitArray;
unsigned int bitArraySize = tempBitArray.size();
//qDebug() << "ARRAY SIZE: " << bitArraySize;
if (bitArraySize > 0 && tempBitArray.count(true) == device->getNumberAxes())
{
if (pendingEventValues.contains(device))
{
InputDeviceBitArrayStatus *pendingTemp = pendingEventValues.value(device);
QBitArray pendingBitArray = pendingTemp->generateFinalBitArray();
QBitArray unplugBitArray = createUnplugEventBitArray(device);
unsigned int pendingBitArraySize = pendingBitArray.size();
if (bitArraySize == pendingBitArraySize &&
pendingBitArray == unplugBitArray)
{
QQueue<SDL_Event> tempQueue;
while (!sdlEventQueue->isEmpty())
{
SDL_Event event = sdlEventQueue->dequeue();
switch (event.type)
{
case SDL_JOYBUTTONDOWN:
case SDL_JOYBUTTONUP:
{
tempQueue.enqueue(event);
break;
}
case SDL_JOYAXISMOTION:
{
if (event.jaxis.which != device->getSDLJoystickID())
{
tempQueue.enqueue(event);
}
else
{
InputDevice *joy = trackjoysticks.value(event.jaxis.which);
if (joy)
{
JoyAxis *axis = joy->getActiveSetJoystick()->getJoyAxis(event.jaxis.axis);
if (axis)
{
if (axis->getThrottle() != JoyAxis::NormalThrottle)
{
event.jaxis.value = axis->getProperReleaseValue();
}
}
}
tempQueue.enqueue(event);
}
break;
}
case SDL_JOYHATMOTION:
{
tempQueue.enqueue(event);
break;
}
case SDL_CONTROLLERAXISMOTION:
{
if (event.caxis.which != device->getSDLJoystickID())
{
tempQueue.enqueue(event);
}
else
{
InputDevice *joy = trackcontrollers.value(event.caxis.which);
if (joy)
{
SetJoystick* set = joy->getActiveSetJoystick();
JoyAxis *axis = set->getJoyAxis(event.caxis.axis);
if (axis)
{
if (event.caxis.axis == SDL_CONTROLLER_AXIS_TRIGGERLEFT ||
event.caxis.axis == SDL_CONTROLLER_AXIS_TRIGGERRIGHT)
{
event.caxis.value = axis->getProperReleaseValue();
}
}
}
tempQueue.enqueue(event);
}
break;
}
case SDL_CONTROLLERBUTTONDOWN:
case SDL_CONTROLLERBUTTONUP:
{
tempQueue.enqueue(event);
break;
}
case SDL_JOYDEVICEREMOVED:
case SDL_JOYDEVICEADDED:
{
tempQueue.enqueue(event);
break;
}
default:
{
tempQueue.enqueue(event);
}
}
}
sdlEventQueue->swap(tempQueue);
}
}
}
}
}
#endif
#ifdef USE_SDL_2
QBitArray InputDaemon::createUnplugEventBitArray(InputDevice *device)
{
InputDeviceBitArrayStatus tempStatus(device, false);
for (int i=0; i < device->getNumberRawAxes(); i++)
{
JoyAxis *axis = device->getActiveSetJoystick()->getJoyAxis(i);
if (axis && axis->getThrottle() != JoyAxis::NormalThrottle)
{
tempStatus.changeAxesStatus(i, true);
}
}
QBitArray unplugBitArray = tempStatus.generateFinalBitArray();
return unplugBitArray;
}
#endif
void InputDaemon::secondInputPass(QQueue<SDL_Event> *sdlEventQueue)
{
QHash<SDL_JoystickID, InputDevice*> activeDevices;
while (!sdlEventQueue->isEmpty())
{
SDL_Event event = sdlEventQueue->dequeue();
switch (event.type)
{
//qDebug() << QTime::currentTime() << " :";
case SDL_JOYBUTTONDOWN:
case SDL_JOYBUTTONUP:
{
#ifdef USE_SDL_2
InputDevice *joy = trackjoysticks.value(event.jbutton.which);
#else
InputDevice *joy = joysticks->value(event.jbutton.which);
#endif
if (joy)
{
SetJoystick* set = joy->getActiveSetJoystick();
JoyButton *button = set->getJoyButton(event.jbutton.button);
if (button)
{
//button->joyEvent(event.type == SDL_JOYBUTTONDOWN ? true : false);
button->queuePendingEvent(event.type == SDL_JOYBUTTONDOWN ? true : false);
if (!activeDevices.contains(event.jbutton.which))
{
activeDevices.insert(event.jbutton.which, joy);
}
}
}
#ifdef USE_SDL_2
else if (trackcontrollers.contains(event.jbutton.which))
{
GameController *gamepad = trackcontrollers.value(event.jbutton.which);
gamepad->rawButtonEvent(event.jbutton.button, event.type == SDL_JOYBUTTONDOWN ? true : false);
}
#endif
break;
}
case SDL_JOYAXISMOTION:
{
#ifdef USE_SDL_2
InputDevice *joy = trackjoysticks.value(event.jaxis.which);
#else
InputDevice *joy = joysticks->value(event.jaxis.which);
#endif
if (joy)
{
SetJoystick* set = joy->getActiveSetJoystick();
JoyAxis *axis = set->getJoyAxis(event.jaxis.axis);
if (axis)
{
//axis->joyEvent(event.jaxis.value);
axis->queuePendingEvent(event.jaxis.value);
if (!activeDevices.contains(event.jaxis.which))
{
activeDevices.insert(event.jaxis.which, joy);
}
}
joy->rawAxisEvent(event.jaxis.which, event.jaxis.value);
}
#ifdef USE_SDL_2
else if (trackcontrollers.contains(event.jaxis.which))
{
GameController *gamepad = trackcontrollers.value(event.jaxis.which);
gamepad->rawAxisEvent(event.jaxis.axis, event.jaxis.value);
}
#endif
break;
}
case SDL_JOYHATMOTION:
{
#ifdef USE_SDL_2
InputDevice *joy = trackjoysticks.value(event.jhat.which);
#else
InputDevice *joy = joysticks->value(event.jhat.which);
#endif
if (joy)
{
SetJoystick* set = joy->getActiveSetJoystick();
JoyDPad *dpad = set->getJoyDPad(event.jhat.hat);
if (dpad)
{
//dpad->joyEvent(event.jhat.value);
dpad->joyEvent(event.jhat.value);
if (!activeDevices.contains(event.jhat.which))
{
activeDevices.insert(event.jhat.which, joy);
}
}
}
#ifdef USE_SDL_2
else if (trackcontrollers.contains(event.jhat.which))
{
GameController *gamepad = trackcontrollers.value(event.jaxis.which);
gamepad->rawDPadEvent(event.jhat.hat, event.jhat.value);
}
#endif
break;
}
#ifdef USE_SDL_2
case SDL_CONTROLLERAXISMOTION:
{
InputDevice *joy = trackcontrollers.value(event.caxis.which);
if (joy)
{
SetJoystick* set = joy->getActiveSetJoystick();
JoyAxis *axis = set->getJoyAxis(event.caxis.axis);
if (axis)
{
//qDebug() << QTime::currentTime() << ": " << "Axis " << event.caxis.axis+1
// << ": " << event.caxis.value;
//axis->joyEvent(event.caxis.value);
axis->queuePendingEvent(event.caxis.value);
if (!activeDevices.contains(event.caxis.which))
{
activeDevices.insert(event.caxis.which, joy);
}
}
}
break;
}
case SDL_CONTROLLERBUTTONDOWN:
case SDL_CONTROLLERBUTTONUP:
{
InputDevice *joy = trackcontrollers.value(event.cbutton.which);
if (joy)
{
SetJoystick* set = joy->getActiveSetJoystick();
JoyButton *button = set->getJoyButton(event.cbutton.button);
if (button)
{
//button->joyEvent(event.type == SDL_CONTROLLERBUTTONDOWN ? true : false);
button->queuePendingEvent(event.type == SDL_CONTROLLERBUTTONDOWN ? true : false);
if (!activeDevices.contains(event.cbutton.which))
{
activeDevices.insert(event.cbutton.which, joy);
}
}
}
break;
}
case SDL_JOYDEVICEREMOVED:
{
InputDevice *device = joysticks->value(event.jdevice.which);
if (device)
{
Logger::LogInfo(QString("Removing joystick #%1 [%2]")
.arg(device->getRealJoyNumber())
.arg(QTime::currentTime().toString("hh:mm:ss.zzz")));
//activeDevices.remove(event.jdevice.which);
removeDevice(device);
}
break;
}
case SDL_JOYDEVICEADDED:
{
addInputDevice(event.jdevice.which);
break;
}
#endif
case SDL_QUIT:
{
stopped = true;
break;
}
default:
break;
}
// Active possible queued events.
QHashIterator<SDL_JoystickID, InputDevice*> activeDevIter(activeDevices);
while (activeDevIter.hasNext())
{
InputDevice *tempDevice = activeDevIter.next().value();
tempDevice->activatePossibleControlStickEvents();
tempDevice->activatePossibleAxisEvents();
tempDevice->activatePossibleDPadEvents();
tempDevice->activatePossibleVDPadEvents();
tempDevice->activatePossibleButtonEvents();
}
if (JoyButton::shouldInvokeMouseEvents())
{
// Do not wait for next event loop run. Execute immediately.
JoyButton::invokeMouseEvents();
}
}
}
void InputDaemon::clearBitArrayStatusInstances()
{
QHashIterator<InputDevice*, InputDeviceBitArrayStatus*> genIter(releaseEventsGenerated);
while (genIter.hasNext())
{
InputDeviceBitArrayStatus *temp = genIter.next().value();
if (temp)
{
delete temp;
temp = 0;
}
}
releaseEventsGenerated.clear();
QHashIterator<InputDevice*, InputDeviceBitArrayStatus*> pendIter(pendingEventValues);
while (pendIter.hasNext())
{
InputDeviceBitArrayStatus *temp = pendIter.next().value();
if (temp)
{
delete temp;
temp = 0;
}
}
pendingEventValues.clear();
}
void InputDaemon::resetActiveButtonMouseDistances()
{
pollResetTimer.stop();
JoyButton::resetActiveButtonMouseDistances();
}
void InputDaemon::updatePollResetRate(unsigned int tempPollRate)
{
Q_UNUSED(tempPollRate);
bool wasActive = pollResetTimer.isActive();
pollResetTimer.stop();
pollResetTimer.setInterval(
qMax(JoyButton::getMouseRefreshRate(),
JoyButton::getGamepadRefreshRate()) + 1);
if (wasActive)
{
pollResetTimer.start();
}
}
``` | /content/code_sandbox/src/inputdaemon.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 8,455 |
```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 <QList>
#include "axiseditdialog.h"
#include "ui_axiseditdialog.h"
#include "buttoneditdialog.h"
#include "mousedialog/mouseaxissettingsdialog.h"
#include "event.h"
#include "antkeymapper.h"
#include "setjoystick.h"
#include "inputdevice.h"
#include "common.h"
AxisEditDialog::AxisEditDialog(JoyAxis *axis, QWidget *parent) :
QDialog(parent, Qt::Window),
ui(new Ui::AxisEditDialog)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
setAxisThrottleConfirm = new SetAxisThrottleDialog(axis, this);
this->axis = axis;
updateWindowTitleAxisName();
initialThrottleState = axis->getThrottle();
bool actAsTrigger = false;
if (initialThrottleState == JoyAxis::PositiveThrottle ||
initialThrottleState == JoyAxis::PositiveHalfThrottle)
{
actAsTrigger = true;
}
if (actAsTrigger)
{
buildTriggerPresetsMenu();
}
ui->horizontalSlider->setValue(axis->getDeadZone());
ui->lineEdit->setText(QString::number(axis->getDeadZone()));
ui->horizontalSlider_2->setValue(axis->getMaxZoneValue());
ui->lineEdit_2->setText(QString::number(axis->getMaxZoneValue()));
JoyAxisButton *nButton = axis->getNAxisButton();
if (!nButton->getActionName().isEmpty())
{
ui->nPushButton->setText(nButton->getActionName());
}
else
{
ui->nPushButton->setText(nButton->getSlotsSummary());
}
JoyAxisButton *pButton = axis->getPAxisButton();
if (!pButton->getActionName().isEmpty())
{
ui->pPushButton->setText(pButton->getActionName());
}
else
{
ui->pPushButton->setText(pButton->getSlotsSummary());
}
int currentThrottle = axis->getThrottle();
//ui->comboBox_2->setCurrentIndex(currentThrottle+1);
if (currentThrottle == JoyAxis::NegativeThrottle || currentThrottle == JoyAxis::NegativeHalfThrottle)
{
int tempindex = currentThrottle == JoyAxis::NegativeHalfThrottle ? 0 : 1;
ui->comboBox_2->setCurrentIndex(tempindex);
ui->nPushButton->setEnabled(true);
ui->pPushButton->setEnabled(false);
}
else if (currentThrottle == JoyAxis::PositiveThrottle || currentThrottle == JoyAxis::PositiveHalfThrottle)
{
int tempindex = currentThrottle == JoyAxis::PositiveThrottle ? 3 : 4;
ui->comboBox_2->setCurrentIndex(tempindex);
ui->pPushButton->setEnabled(true);
ui->nPushButton->setEnabled(false);
}
ui->axisstatusBox->setDeadZone(axis->getDeadZone());
ui->axisstatusBox->setMaxZone(axis->getMaxZoneValue());
ui->axisstatusBox->setThrottle(axis->getThrottle());
ui->joyValueLabel->setText(QString::number(axis->getCurrentRawValue()));
ui->axisstatusBox->setValue(axis->getCurrentRawValue());
if (!actAsTrigger)
{
selectAxisCurrentPreset();
}
else
{
selectTriggerPreset();
}
ui->axisNameLineEdit->setText(axis->getAxisName());
connect(ui->presetsComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(implementPresets(int)));
connect(ui->horizontalSlider, SIGNAL(valueChanged(int)), this, SLOT(updateDeadZoneBox(int)));
connect(ui->horizontalSlider, SIGNAL(valueChanged(int)), ui->axisstatusBox, SLOT(setDeadZone(int)));
connect(ui->horizontalSlider, SIGNAL(valueChanged(int)), axis, SLOT(setDeadZone(int)));
connect(ui->horizontalSlider_2, SIGNAL(valueChanged(int)), this, SLOT(updateMaxZoneBox(int)));
connect(ui->horizontalSlider_2, SIGNAL(valueChanged(int)), ui->axisstatusBox, SLOT(setMaxZone(int)));
connect(ui->horizontalSlider_2, SIGNAL(valueChanged(int)), axis, SLOT(setMaxZoneValue(int)));
connect(ui->comboBox_2, SIGNAL(currentIndexChanged(int)), this, SLOT(updateThrottleUi(int)));
connect(ui->comboBox_2, SIGNAL(currentIndexChanged(int)), this, SLOT(presetForThrottleChange(int)));
connect(axis, SIGNAL(moved(int)), ui->axisstatusBox, SLOT(setValue(int)));
connect(axis, SIGNAL(moved(int)), this, SLOT(updateJoyValue(int)));
connect(ui->lineEdit, SIGNAL(textEdited(QString)), this, SLOT(updateDeadZoneSlider(QString)));
connect(ui->lineEdit_2, SIGNAL(textEdited(QString)), this, SLOT(updateMaxZoneSlider(QString)));
connect(ui->nPushButton, SIGNAL(clicked()), this, SLOT(openAdvancedNDialog()));
connect(ui->pPushButton, SIGNAL(clicked()), this, SLOT(openAdvancedPDialog()));
connect(ui->mouseSettingsPushButton, SIGNAL(clicked()), this, SLOT(openMouseSettingsDialog()));
connect(ui->axisNameLineEdit, SIGNAL(textEdited(QString)), axis, SLOT(setAxisName(QString)));
connect(axis, SIGNAL(axisNameChanged()), this, SLOT(updateWindowTitleAxisName()));
connect(this, SIGNAL(finished(int)), this, SLOT(checkFinalSettings()));
}
AxisEditDialog::~AxisEditDialog()
{
delete ui;
}
void AxisEditDialog::implementPresets(int index)
{
bool actAsTrigger = false;
int currentThrottle = axis->getThrottle();
if (currentThrottle == JoyAxis::PositiveThrottle ||
currentThrottle == JoyAxis::PositiveHalfThrottle)
{
actAsTrigger = true;
}
if (actAsTrigger)
{
implementTriggerPresets(index);
}
else
{
implementAxisPresets(index);
}
}
void AxisEditDialog::implementAxisPresets(int index)
{
JoyButtonSlot *nbuttonslot = 0;
JoyButtonSlot *pbuttonslot = 0;
PadderCommon::lockInputDevices();
InputDevice *tempDevice = axis->getParentSet()->getInputDevice();
QMetaObject::invokeMethod(tempDevice, "haltServices", Qt::BlockingQueuedConnection);
if (index == 1)
{
nbuttonslot = new JoyButtonSlot(JoyButtonSlot::MouseLeft, JoyButtonSlot::JoyMouseMovement, this);
pbuttonslot = new JoyButtonSlot(JoyButtonSlot::MouseRight, JoyButtonSlot::JoyMouseMovement, this);
}
else if (index == 2)
{
nbuttonslot = new JoyButtonSlot(JoyButtonSlot::MouseRight, JoyButtonSlot::JoyMouseMovement, this);
pbuttonslot = new JoyButtonSlot(JoyButtonSlot::MouseLeft, JoyButtonSlot::JoyMouseMovement, this);
}
else if (index == 3)
{
nbuttonslot = new JoyButtonSlot(JoyButtonSlot::MouseUp, JoyButtonSlot::JoyMouseMovement, this);
pbuttonslot = new JoyButtonSlot(JoyButtonSlot::MouseDown, JoyButtonSlot::JoyMouseMovement, this);
}
else if (index == 4)
{
nbuttonslot = new JoyButtonSlot(JoyButtonSlot::MouseDown, JoyButtonSlot::JoyMouseMovement, this);
pbuttonslot = new JoyButtonSlot(JoyButtonSlot::MouseUp, JoyButtonSlot::JoyMouseMovement, this);
}
else if (index == 5)
{
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 (index == 6)
{
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 (index == 7)
{
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 (index == 8)
{
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 (index == 9)
{
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 (index == 10)
{
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 (index == 11)
{
JoyAxisButton *nbutton = axis->getNAxisButton();
JoyAxisButton *pbutton = axis->getPAxisButton();
QMetaObject::invokeMethod(nbutton, "clearSlotsEventReset");
QMetaObject::invokeMethod(pbutton, "clearSlotsEventReset", Qt::BlockingQueuedConnection);
refreshNButtonLabel();
refreshPButtonLabel();
}
if (nbuttonslot)
{
JoyAxisButton *button = axis->getNAxisButton();
QMetaObject::invokeMethod(button, "clearSlotsEventReset",
Q_ARG(bool, false));
QMetaObject::invokeMethod(button, "setAssignedSlot", Qt::BlockingQueuedConnection,
Q_ARG(int, nbuttonslot->getSlotCode()),
Q_ARG(unsigned int, nbuttonslot->getSlotCodeAlias()),
Q_ARG(JoyButtonSlot::JoySlotInputAction, nbuttonslot->getSlotMode()));
refreshNButtonLabel();
nbuttonslot->deleteLater();
}
if (pbuttonslot)
{
JoyAxisButton *button = axis->getPAxisButton();
QMetaObject::invokeMethod(button, "clearSlotsEventReset", Q_ARG(bool, false));
QMetaObject::invokeMethod(button, "setAssignedSlot", Qt::BlockingQueuedConnection,
Q_ARG(int, pbuttonslot->getSlotCode()),
Q_ARG(unsigned int, pbuttonslot->getSlotCodeAlias()),
Q_ARG(JoyButtonSlot::JoySlotInputAction, pbuttonslot->getSlotMode()));
refreshPButtonLabel();
pbuttonslot->deleteLater();
}
PadderCommon::unlockInputDevices();
}
void AxisEditDialog::updateDeadZoneBox(int value)
{
ui->lineEdit->setText(QString::number(value));
}
void AxisEditDialog::updateMaxZoneBox(int value)
{
ui->lineEdit_2->setText(QString::number(value));
}
void AxisEditDialog::updateThrottleUi(int index)
{
int tempthrottle = 0;
if (index == 0 || index == 1)
{
ui->nPushButton->setEnabled(true);
ui->pPushButton->setEnabled(false);
tempthrottle = index == 0 ? JoyAxis::NegativeHalfThrottle : JoyAxis::NegativeThrottle;
}
else if (index == 2)
{
ui->nPushButton->setEnabled(true);
ui->pPushButton->setEnabled(true);
tempthrottle = JoyAxis::NormalThrottle;
}
else if (index == 3 || index == 4)
{
ui->pPushButton->setEnabled(true);
ui->nPushButton->setEnabled(false);
tempthrottle = index == 3 ? JoyAxis::PositiveThrottle : JoyAxis::PositiveHalfThrottle;
}
axis->setThrottle(tempthrottle);
ui->axisstatusBox->setThrottle(tempthrottle);
}
void AxisEditDialog::updateJoyValue(int value)
{
ui->joyValueLabel->setText(QString::number(value));
}
void AxisEditDialog::updateDeadZoneSlider(QString value)
{
int temp = value.toInt();
if (temp >= JoyAxis::AXISMIN && temp <= JoyAxis::AXISMAX)
{
ui->horizontalSlider->setValue(temp);
}
}
void AxisEditDialog::updateMaxZoneSlider(QString value)
{
int temp = value.toInt();
if (temp >= JoyAxis::AXISMIN && temp <= JoyAxis::AXISMAX)
{
ui->horizontalSlider_2->setValue(temp);
}
}
void AxisEditDialog::openAdvancedPDialog()
{
ButtonEditDialog *dialog = new ButtonEditDialog(axis->getPAxisButton(), this);
dialog->show();
connect(dialog, SIGNAL(finished(int)), this, SLOT(refreshPButtonLabel()));
connect(dialog, SIGNAL(finished(int)), this, SLOT(refreshPreset()));
}
void AxisEditDialog::openAdvancedNDialog()
{
ButtonEditDialog *dialog = new ButtonEditDialog(axis->getNAxisButton(), this);
dialog->show();
connect(dialog, SIGNAL(finished(int)), this, SLOT(refreshNButtonLabel()));
connect(dialog, SIGNAL(finished(int)), this, SLOT(refreshPreset()));
}
void AxisEditDialog::refreshNButtonLabel()
{
/*if (!axis->getNAxisButton()->getActionName().isEmpty())
{
ui->nPushButton->setText(axis->getNAxisButton()->getActionName());
}
else
{
ui->nPushButton->setText(axis->getNAxisButton()->getSlotsSummary());
}*/
ui->nPushButton->setText(axis->getNAxisButton()->getSlotsSummary());
}
void AxisEditDialog::refreshPButtonLabel()
{
/*if (!axis->getPAxisButton()->getActionName().isEmpty())
{
ui->pPushButton->setText(axis->getPAxisButton()->getActionName());
}
else
{
ui->pPushButton->setText(axis->getPAxisButton()->getSlotsSummary());
}*/
ui->pPushButton->setText(axis->getPAxisButton()->getSlotsSummary());
}
void AxisEditDialog::checkFinalSettings()
{
if (axis->getThrottle() != initialThrottleState)
{
setAxisThrottleConfirm->exec();
}
}
void AxisEditDialog::selectAxisCurrentPreset()
{
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)
{
ui->presetsComboBox->setCurrentIndex(1);
}
else if (nslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && nslot->getSlotCode() == JoyButtonSlot::MouseRight &&
pslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && pslot->getSlotCode() == JoyButtonSlot::MouseLeft)
{
ui->presetsComboBox->setCurrentIndex(2);
}
else if (nslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && nslot->getSlotCode() == JoyButtonSlot::MouseUp &&
pslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && pslot->getSlotCode() == JoyButtonSlot::MouseDown)
{
ui->presetsComboBox->setCurrentIndex(3);
}
else if (nslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && nslot->getSlotCode() == JoyButtonSlot::MouseDown &&
pslot->getSlotMode() == JoyButtonSlot::JoyMouseMovement && pslot->getSlotCode() == JoyButtonSlot::MouseUp)
{
ui->presetsComboBox->setCurrentIndex(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))
{
ui->presetsComboBox->setCurrentIndex(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))
{
ui->presetsComboBox->setCurrentIndex(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))
{
ui->presetsComboBox->setCurrentIndex(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))
{
ui->presetsComboBox->setCurrentIndex(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))
{
ui->presetsComboBox->setCurrentIndex(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))
{
ui->presetsComboBox->setCurrentIndex(10);
}
else
{
ui->presetsComboBox->setCurrentIndex(0);
}
}
else if (naxisslots->length() == 0 && paxisslots->length() == 0)
{
ui->presetsComboBox->setCurrentIndex(11);
}
else
{
ui->presetsComboBox->setCurrentIndex(0);
}
}
void AxisEditDialog::selectTriggerPreset()
{
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)
{
ui->presetsComboBox->setCurrentIndex(1);
}
else if (pslot->getSlotMode() == JoyButtonSlot::JoyMouseButton && pslot->getSlotCode() == JoyButtonSlot::MouseRB)
{
ui->presetsComboBox->setCurrentIndex(2);
}
else
{
ui->presetsComboBox->setCurrentIndex(0);
}
}
else if (paxisslots->length() == 0)
{
ui->presetsComboBox->setCurrentIndex(3);
}
else
{
ui->presetsComboBox->setCurrentIndex(0);
}
}
void AxisEditDialog::implementTriggerPresets(int index)
{
JoyButtonSlot *pbuttonslot = 0;
if (index == 1)
{
pbuttonslot = new JoyButtonSlot(JoyButtonSlot::MouseLB, JoyButtonSlot::JoyMouseButton, this);
}
else if (index == 2)
{
pbuttonslot = new JoyButtonSlot(JoyButtonSlot::MouseRB, JoyButtonSlot::JoyMouseButton, this);
}
else if (index == 3)
{
JoyAxisButton *nbutton = axis->getNAxisButton();
JoyAxisButton *pbutton = axis->getPAxisButton();
QMetaObject::invokeMethod(nbutton, "clearSlotsEventReset");
QMetaObject::invokeMethod(pbutton, "clearSlotsEventReset", Qt::BlockingQueuedConnection);
refreshNButtonLabel();
refreshPButtonLabel();
}
if (pbuttonslot)
{
JoyAxisButton *nbutton = axis->getNAxisButton();
JoyAxisButton *pbutton = axis->getPAxisButton();
if (nbutton->getAssignedSlots()->length() > 0)
{
QMetaObject::invokeMethod(nbutton, "clearSlotsEventReset", Qt::BlockingQueuedConnection,
Q_ARG(bool, false));
refreshNButtonLabel();
}
QMetaObject::invokeMethod(pbutton, "clearSlotsEventReset",
Q_ARG(bool, false));
QMetaObject::invokeMethod(pbutton, "setAssignedSlot", Qt::BlockingQueuedConnection,
Q_ARG(int, pbuttonslot->getSlotCode()),
Q_ARG(unsigned int, pbuttonslot->getSlotCodeAlias()),
Q_ARG(JoyButtonSlot::JoySlotInputAction, pbuttonslot->getSlotMode()));
refreshPButtonLabel();
pbuttonslot->deleteLater();
}
}
void AxisEditDialog::refreshPreset()
{
// Disconnect event associated with presetsComboBox so a change in the index does not
// alter the axis buttons
disconnect(ui->presetsComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(implementPresets(int)));
selectAxisCurrentPreset();
// Reconnect the event
connect(ui->presetsComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(implementPresets(int)));
}
void AxisEditDialog::openMouseSettingsDialog()
{
ui->mouseSettingsPushButton->setEnabled(false);
MouseAxisSettingsDialog *dialog = new MouseAxisSettingsDialog(this->axis, this);
dialog->show();
connect(this, SIGNAL(finished(int)), dialog, SLOT(close()));
connect(dialog, SIGNAL(finished(int)), this, SLOT(enableMouseSettingButton()));
}
void AxisEditDialog::enableMouseSettingButton()
{
ui->mouseSettingsPushButton->setEnabled(true);
}
void AxisEditDialog::updateWindowTitleAxisName()
{
QString temp = QString(tr("Set")).append(" ");
if (!axis->getAxisName().isEmpty())
{
temp.append(axis->getPartialName(false, true));
}
else
{
temp.append(axis->getPartialName());
}
if (axis->getParentSet()->getIndex() != 0)
{
unsigned int setIndex = axis->getParentSet()->getRealIndex();
temp.append(" [").append(tr("Set %1").arg(setIndex));
QString setName = axis->getParentSet()->getName();
if (!setName.isEmpty())
{
temp.append(": ").append(setName);
}
temp.append("]");
}
setWindowTitle(temp);
}
void AxisEditDialog::buildAxisPresetsMenu()
{
ui->presetsComboBox->clear();
ui->presetsComboBox->addItem(tr(""));
ui->presetsComboBox->addItem(tr("Mouse (Horizontal)"));
ui->presetsComboBox->addItem(tr("Mouse (Inverted Horizontal)"));
ui->presetsComboBox->addItem(tr("Mouse (Vertical)"));
ui->presetsComboBox->addItem(tr("Mouse (Inverted Vertical)"));
ui->presetsComboBox->addItem(tr("Arrows: Up | Down"));
ui->presetsComboBox->addItem(tr("Arrows: Left | Right"));
ui->presetsComboBox->addItem(tr("Keys: W | S"));
ui->presetsComboBox->addItem(tr("Keys: A | D"));
ui->presetsComboBox->addItem(tr("NumPad: KP_8 | KP_2"));
ui->presetsComboBox->addItem(tr("NumPad: KP_4 | KP_6"));
ui->presetsComboBox->addItem(tr("None"));
}
void AxisEditDialog::buildTriggerPresetsMenu()
{
ui->presetsComboBox->clear();
ui->presetsComboBox->addItem(tr(""));
ui->presetsComboBox->addItem(tr("Left Mouse Button"));
ui->presetsComboBox->addItem(tr("Right Mouse Button"));
ui->presetsComboBox->addItem(tr("None"));
}
void AxisEditDialog::presetForThrottleChange(int index)
{
Q_UNUSED(index);
bool actAsTrigger = false;
int currentThrottle = axis->getThrottle();
if (currentThrottle == JoyAxis::PositiveThrottle ||
currentThrottle == JoyAxis::PositiveHalfThrottle)
{
actAsTrigger = true;
}
disconnect(ui->presetsComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(implementPresets(int)));
if (actAsTrigger)
{
buildTriggerPresetsMenu();
selectTriggerPreset();
}
else
{
buildAxisPresetsMenu();
selectAxisCurrentPreset();
}
connect(ui->presetsComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(implementPresets(int)));
}
``` | /content/code_sandbox/src/axiseditdialog.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 6,084 |
```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 UNIXWINDOWINFODIALOG_H
#define UNIXWINDOWINFODIALOG_H
#include <QDialog>
#include <QString>
namespace Ui {
class UnixWindowInfoDialog;
}
class UnixWindowInfoDialog : public QDialog
{
Q_OBJECT
public:
explicit UnixWindowInfoDialog(unsigned long window, QWidget *parent = 0);
~UnixWindowInfoDialog();
enum {
WindowClass = (1 << 0),
WindowName = (1 << 1),
WindowPath = (1 << 2)
};
typedef unsigned int DialogWindowOption;
QString getWindowClass();
QString getWindowName();
QString getWindowPath();
DialogWindowOption getSelectedOptions();
private:
Ui::UnixWindowInfoDialog *ui;
protected:
DialogWindowOption selectedMatch;
QString winClass;
QString winName;
QString winPath;
private slots:
void populateOption();
};
#endif // UNIXWINDOWINFODIALOG_H
``` | /content/code_sandbox/src/unixwindowinfodialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 291 |
```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 "joycontrolstickbuttonpushbutton.h"
#include "joybuttoncontextmenu.h"
#include "joycontrolstick.h"
JoyControlStickButtonPushButton::JoyControlStickButtonPushButton(JoyControlStickButton *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()));
connect(button->getStick()->getModifierButton(), SIGNAL(activeZoneChanged()),
this, SLOT(refreshLabel()));
}
JoyControlStickButton* JoyControlStickButtonPushButton::getButton()
{
return button;
}
void JoyControlStickButtonPushButton::setButton(JoyControlStickButton *button)
{
disableFlashes();
if (this->button)
{
//disconnect(this->button, SIGNAL(slotsChanged()), this, SLOT(refreshLabel()));
disconnect(button, SIGNAL(propertyUpdated()), this, SLOT(refreshLabel()));
disconnect(this->button, SIGNAL(activeZoneChanged()), this, SLOT(refreshLabel()));
}
this->button = button;
refreshLabel();
enableFlashes();
//connect(button, SIGNAL(slotsChanged()), this, SLOT(refreshLabel()));
connect(button, SIGNAL(propertyUpdated()), this, SLOT(refreshLabel()));
connect(button, SIGNAL(activeZoneChanged()), this, SLOT(refreshLabel()), Qt::QueuedConnection);
}
void JoyControlStickButtonPushButton::disableFlashes()
{
if (button)
{
disconnect(button, SIGNAL(clicked(int)), this, SLOT(flash()));
disconnect(button, SIGNAL(released(int)), this, SLOT(unflash()));
}
this->unflash();
}
void JoyControlStickButtonPushButton::enableFlashes()
{
if (button)
{
connect(button, SIGNAL(clicked(int)), this, SLOT(flash()), Qt::QueuedConnection);
connect(button, SIGNAL(released(int)), this, SLOT(unflash()), Qt::QueuedConnection);
}
}
/**
* @brief Generate the string that will be displayed on the button
* @return Display string
*/
QString JoyControlStickButtonPushButton::generateLabel()
{
QString temp;
if (button)
{
if (!button->getActionName().isEmpty() && displayNames)
{
temp = button->getActionName().replace("&", "&&");
}
else
{
temp = button->getCalculatedActiveZoneSummary().replace("&", "&&");
}
}
return temp;
}
void JoyControlStickButtonPushButton::showContextMenu(const QPoint &point)
{
QPoint globalPos = this->mapToGlobal(point);
JoyButtonContextMenu *contextMenu = new JoyButtonContextMenu(button, this);
contextMenu->buildMenu();
contextMenu->popup(globalPos);
}
void JoyControlStickButtonPushButton::tryFlash()
{
if (button->getButtonState())
{
flash();
}
}
``` | /content/code_sandbox/src/joycontrolstickbuttonpushbutton.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 783 |
```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 <QPainter>
#include <QPixmap>
#include <QTransform>
#include "gamecontrollerexample.h"
struct ButtonImagePlacement {
int x;
int y;
GameControllerExample::ButtonType buttontype;
};
static ButtonImagePlacement buttonLocations[] = {
{225, 98, GameControllerExample::Button}, // SDL_CONTROLLER_BUTTON_A
{252, 77, GameControllerExample::Button}, // SDL_CONTROLLER_BUTTON_B
{200, 77, GameControllerExample::Button}, // SDL_CONTROLLER_BUTTON_X
{227, 59, GameControllerExample::Button}, // SDL_CONTROLLER_BUTTON_Y
{102, 77, GameControllerExample::Button}, // SDL_CONTROLLER_BUTTON_BACK
{169, 77, GameControllerExample::Button}, // SDL_CONTROLLER_BUTTON_START
{137, 77, GameControllerExample::Button}, // SDL_CONTROLLER_BUTTON_GUIDE
{45, 23, GameControllerExample::Button}, // SDL_CONTROLLER_BUTTON_LEFTSHOULDER
{232, 21, GameControllerExample::Button}, // SDL_CONTROLLER_BUTTON_RIGHTSHOULDER
{44, 90, GameControllerExample::Button}, // SDL_CONTROLLER_BUTTON_LEFTSTICK
{179, 135, GameControllerExample::Button}, // SDL_CONTROLLER_BUTTON_RIGHTSTICK
{44, 90, GameControllerExample::AxisX}, // SDL_CONTROLLER_AXIS_LEFTX
{44, 90, GameControllerExample::AxisY}, // SDL_CONTROLLER_AXIS_LEFTY
{179, 135, GameControllerExample::AxisX}, // SDL_CONTROLLER_AXIS_RIGHTX
{179, 135, GameControllerExample::AxisY}, // SDL_CONTROLLER_AXIS_RIGHTY
{53, 0, GameControllerExample::Button}, // SDL_CONTROLLER_AXIS_TRIGGERLEFT
{220, 0, GameControllerExample::Button}, // SDL_CONTROLLER_AXIS_TRIGGERRIGHT
{90, 110, GameControllerExample::Button}, // SDL_CONTROLLER_BUTTON_DPAD_UP
{68, 127, GameControllerExample::Button}, // SDL_CONTROLLER_BUTTON_DPAD_DOWN
{90, 146, GameControllerExample::Button}, // SDL_CONTROLLER_BUTTON_DPAD_LEFT
{109, 127, GameControllerExample::Button}, // SDL_CONTROLLER_BUTTON_DPAD_RIGHT
};
GameControllerExample::GameControllerExample(QWidget *parent) :
QWidget(parent)
{
controllerimage = QImage(":/images/controllermap.png");
buttonimage = QImage(":/images/button.png");
axisimage = QImage(":/images/axis.png");
QTransform myTransform;
myTransform.rotate(90);
rotatedaxisimage = axisimage.transformed(myTransform);
currentIndex = 0;
connect(this, SIGNAL(indexUpdated(int)), this, SLOT(update()));
}
void GameControllerExample::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainter paint(this);
paint.drawImage(controllerimage.rect(), controllerimage);
ButtonImagePlacement current = buttonLocations[currentIndex];
paint.setOpacity(0.85);
if (current.buttontype == Button)
{
paint.drawImage(QRect(current.x, current.y, buttonimage.width(), buttonimage.height()), buttonimage);
}
else if (current.buttontype == AxisX)
{
paint.drawImage(QRect(current.x, current.y, axisimage.width(), axisimage.height()), axisimage);
}
else if (current.buttontype == AxisY)
{
paint.drawImage(QRect(current.x, current.y, rotatedaxisimage.width(), rotatedaxisimage.height()), rotatedaxisimage);
}
paint.setOpacity(1.0);
}
void GameControllerExample::setActiveButton(int button)
{
if (button >= 0 && button <= MAXBUTTONINDEX)
{
currentIndex = button;
emit indexUpdated(button);
}
}
``` | /content/code_sandbox/src/gamecontrollerexample.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 880 |
```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 JOYSTICK_H
#define JOYSTICK_H
#include <QObject>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include "inputdevice.h"
class Joystick : public InputDevice
{
Q_OBJECT
public:
explicit Joystick(SDL_Joystick *joyhandle, int deviceIndex, AntiMicroSettings *settings, QObject *parent=0);
virtual QString getName();
virtual QString getSDLName();
virtual QString getGUIDString(); // GUID available on SDL 2.
virtual QString getXmlName();
virtual void closeSDLDevice();
#ifdef USE_SDL_2
virtual SDL_JoystickID getSDLJoystickID();
#endif
virtual int getNumberRawButtons();
virtual int getNumberRawAxes();
virtual int getNumberRawHats();
static const QString xmlName;
protected:
SDL_Joystick *joyhandle;
signals:
public slots:
};
Q_DECLARE_METATYPE(Joystick*)
#endif // JOYSTICK_H
``` | /content/code_sandbox/src/joystick.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 293 |
```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 <QPainter>
#include <qdrawutil.h>
#include <QSizePolicy>
#include <QList>
#include <QLinearGradient>
#include "joycontrolstickstatusbox.h"
#include "common.h"
JoyControlStickStatusBox::JoyControlStickStatusBox(QWidget *parent) :
QWidget(parent)
{
this->stick = 0;
}
JoyControlStickStatusBox::JoyControlStickStatusBox(JoyControlStick *stick, QWidget *parent) :
QWidget(parent)
{
this->stick = stick;
connect(stick, SIGNAL(deadZoneChanged(int)), this, SLOT(update()));
connect(stick, SIGNAL(moved(int,int)), this, SLOT(update()));
connect(stick, SIGNAL(diagonalRangeChanged(int)), this, SLOT(update()));
connect(stick, SIGNAL(maxZoneChanged(int)), this, SLOT(update()));
connect(stick, SIGNAL(joyModeChanged()), this, SLOT(update()));
connect(stick, SIGNAL(circleAdjustChange(double)), this, SLOT(update()));
}
void JoyControlStickStatusBox::setStick(JoyControlStick *stick)
{
if (stick)
{
disconnect(stick, SIGNAL(deadZoneChanged(int)), this, 0);
disconnect(stick, SIGNAL(moved(int,int)), this, 0);
disconnect(stick, SIGNAL(diagonalRangeChanged(int)), this, 0);
disconnect(stick, SIGNAL(maxZoneChanged(int)), this, 0);
disconnect(stick, SIGNAL(joyModeChanged()), this, 0);
}
this->stick = stick;
connect(stick, SIGNAL(deadZoneChanged(int)), this, SLOT(update()));
connect(stick, SIGNAL(moved(int,int)), this, SLOT(update()));
connect(stick, SIGNAL(diagonalRangeChanged(int)), this, SLOT(update()));
connect(stick, SIGNAL(maxZoneChanged(int)), this, SLOT(update()));
connect(stick, SIGNAL(joyModeChanged()), this, SLOT(update()));
}
JoyControlStick* JoyControlStickStatusBox::getStick()
{
return stick;
}
int JoyControlStickStatusBox::heightForWidth(int width) const
{
return width;
}
QSize JoyControlStickStatusBox::sizeHint() const
{
return QSize(-1, -1);
}
void JoyControlStickStatusBox::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
PadderCommon::inputDaemonMutex.lock();
if (stick->getJoyMode() == JoyControlStick::StandardMode ||
stick->getJoyMode() == JoyControlStick::EightWayMode)
{
drawEightWayBox();
}
else if (stick->getJoyMode() == JoyControlStick::FourWayCardinal)
{
drawFourWayCardinalBox();
}
else if (stick->getJoyMode() == JoyControlStick::FourWayDiagonal)
{
drawFourWayDiagonalBox();
}
PadderCommon::inputDaemonMutex.unlock();
}
void JoyControlStickStatusBox::drawEightWayBox()
{
QPainter paint (this);
paint.setRenderHint(QPainter::Antialiasing, true);
int side = qMin(width()-2, height()-2);
QPixmap pix(side, side);
pix.fill(Qt::transparent);
QPainter painter(&pix);
painter.setRenderHint(QPainter::Antialiasing, true);
// Draw box outline
QPen penny;
penny.setColor(Qt::black);
penny.setWidth(1);
painter.setBrush(Qt::NoBrush);
painter.drawRect(0, 0, side-1, side-1);
painter.save();
painter.scale(side / (double)(JoyAxis::AXISMAX*2.0), side / (double)(JoyAxis::AXISMAX*2.0));
painter.translate(JoyAxis::AXISMAX, JoyAxis::AXISMAX);
// Draw diagonal zones
QList<double> anglesList = stick->getDiagonalZoneAngles();
/*QListIterator<double> iter(anglesList);
qDebug() << "LIST START";
qDebug() << "DIAGONAL RANGE: " << stick->getDiagonalRange();
while (iter.hasNext())
{
qDebug() << "ANGLE: " << iter.next();
}
qDebug() << "LIST END";
qDebug();
*/
penny.setWidth(0);
penny.setColor(Qt::black);
painter.setPen(penny);
painter.setBrush(QBrush(Qt::green));
painter.drawPie(-JoyAxis::AXISMAX, -JoyAxis::AXISMAX, JoyAxis::AXISMAX*2, JoyAxis::AXISMAX*2, anglesList.value(2)*16, stick->getDiagonalRange()*16);
painter.drawPie(-JoyAxis::AXISMAX, -JoyAxis::AXISMAX, JoyAxis::AXISMAX*2, JoyAxis::AXISMAX*2, anglesList.value(4)*16, stick->getDiagonalRange()*16);
painter.drawPie(-JoyAxis::AXISMAX, -JoyAxis::AXISMAX, JoyAxis::AXISMAX*2, JoyAxis::AXISMAX*2, anglesList.value(6)*16, stick->getDiagonalRange()*16);
painter.drawPie(-JoyAxis::AXISMAX, -JoyAxis::AXISMAX, JoyAxis::AXISMAX*2, JoyAxis::AXISMAX*2, anglesList.value(8)*16, stick->getDiagonalRange()*16);
// Draw deadzone circle
penny.setWidth(0);
penny.setColor(Qt::blue);
painter.setPen(penny);
painter.setBrush(QBrush(Qt::red));
painter.drawEllipse(-stick->getDeadZone(), -stick->getDeadZone(), stick->getDeadZone()*2, stick->getDeadZone()*2);
painter.restore();
painter.save();
penny.setWidth(0);
penny.setColor(Qt::gray);
painter.setPen(penny);
painter.scale(side / 2.0, side / 2.0);
painter.translate(1, 1);
// Draw Y line
painter.drawLine(0, -1, 0, 1);
// Draw X line
painter.drawLine(-1, 0, 1, 0);
painter.restore();
painter.save();
painter.scale(side / (double)(JoyAxis::AXISMAX*2.0), side / (double)(JoyAxis::AXISMAX*2.0));
painter.translate(JoyAxis::AXISMAX, JoyAxis::AXISMAX);
penny.setWidth(0);
painter.setBrush(QBrush(Qt::black));
penny.setColor(Qt::black);
painter.setPen(penny);
// Draw raw crosshair
int linexstart = stick->getXCoordinate()-1000;
int lineystart = stick->getYCoordinate()-1000;
if (linexstart < JoyAxis::AXISMIN)
{
linexstart = JoyAxis::AXISMIN;
}
if (lineystart < JoyAxis::AXISMIN)
{
lineystart = JoyAxis::AXISMIN;
}
painter.drawRect(linexstart, lineystart, 2000, 2000);
painter.setBrush(QBrush(Qt::darkBlue));
penny.setColor(Qt::darkBlue);
painter.setPen(penny);
// Draw adjusted crosshair
linexstart = stick->getCircleXCoordinate()-1000;
lineystart = stick->getCircleYCoordinate()-1000;
if (linexstart < JoyAxis::AXISMIN)
{
linexstart = JoyAxis::AXISMIN;
}
if (lineystart < JoyAxis::AXISMIN)
{
lineystart = JoyAxis::AXISMIN;
}
painter.drawRect(linexstart, lineystart, 2000, 2000);
painter.restore();
// Reset pen
penny.setColor(Qt::black);
painter.setPen(penny);
// Draw primary pixmap
painter.setCompositionMode(QPainter::CompositionMode_DestinationOver);
painter.setPen(Qt::NoPen);
painter.fillRect(0, 0, side, side, palette().background().color());
paint.drawPixmap(pix.rect(), pix);
paint.save();
paint.scale(side / (double)(JoyAxis::AXISMAX*2.0), side / (double)(JoyAxis::AXISMAX*2.0));
paint.translate(JoyAxis::AXISMAX, JoyAxis::AXISMAX);
// Draw max zone and initial inner clear circle
int maxzone = stick->getMaxZone();
int diffmaxzone = JoyAxis::AXISMAX - maxzone;
paint.setOpacity(0.5);
paint.setBrush(Qt::darkGreen);
paint.drawEllipse(-JoyAxis::AXISMAX, -JoyAxis::AXISMAX, JoyAxis::AXISMAX*2, JoyAxis::AXISMAX*2);
paint.setCompositionMode(QPainter::CompositionMode_Clear);
paint.setPen(Qt::NoPen);
paint.drawEllipse(-JoyAxis::AXISMAX+diffmaxzone, -JoyAxis::AXISMAX+diffmaxzone, JoyAxis::AXISMAX*2-(diffmaxzone*2), JoyAxis::AXISMAX*2-(diffmaxzone*2));
painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
paint.setOpacity(1.0);
paint.restore();
// Re-draw pixmap so the inner circle will be transparent
paint.setCompositionMode(QPainter::CompositionMode_DestinationOver);
paint.drawPixmap(pix.rect(), pix);
paint.setCompositionMode(QPainter::CompositionMode_SourceOver);
}
void JoyControlStickStatusBox::drawFourWayCardinalBox()
{
QPainter paint(this);
paint.setRenderHint(QPainter::Antialiasing, true);
int side = qMin(width()-2, height()-2);
QPixmap pix(side, side);
pix.fill(Qt::transparent);
QPainter painter(&pix);
painter.setRenderHint(QPainter::Antialiasing, true);
// Draw box outline
QPen penny;
penny.setColor(Qt::black);
penny.setWidth(1);
painter.setBrush(Qt::NoBrush);
painter.drawRect(0, 0, side-1, side-1);
painter.save();
painter.scale(side / (double)(JoyAxis::AXISMAX*2.0), side / (double)(JoyAxis::AXISMAX*2.0));
painter.translate(JoyAxis::AXISMAX, JoyAxis::AXISMAX);
// Draw diagonal zones
QList<int> anglesList = stick->getFourWayCardinalZoneAngles();
penny.setWidth(0);
penny.setColor(Qt::black);
painter.setPen(penny);
painter.setOpacity(0.25);
painter.setBrush(QBrush(Qt::black));
painter.drawPie(-JoyAxis::AXISMAX, -JoyAxis::AXISMAX, JoyAxis::AXISMAX*2, JoyAxis::AXISMAX*2, anglesList.value(1)*16, 90*16);
painter.drawPie(-JoyAxis::AXISMAX, -JoyAxis::AXISMAX, JoyAxis::AXISMAX*2, JoyAxis::AXISMAX*2, anglesList.value(3)*16, 90*16);
painter.setOpacity(1.0);
// Draw deadzone circle
penny.setWidth(0);
penny.setColor(Qt::blue);
painter.setPen(penny);
painter.setBrush(QBrush(Qt::red));
painter.drawEllipse(-stick->getDeadZone(), -stick->getDeadZone(), stick->getDeadZone()*2, stick->getDeadZone()*2);
painter.restore();
painter.save();
penny.setWidth(0);
penny.setColor(Qt::black);
painter.setPen(penny);
painter.setOpacity(0.5);
painter.scale(side / 2.0, side / 2.0);
painter.translate(1, 1);
// Draw Y line
painter.drawLine(0, -1, 0, 1);
// Draw X line
painter.drawLine(-1, 0, 1, 0);
painter.setOpacity(1.0);
painter.restore();
painter.save();
painter.scale(side / (double)(JoyAxis::AXISMAX*2.0), side / (double)(JoyAxis::AXISMAX*2.0));
painter.translate(JoyAxis::AXISMAX, JoyAxis::AXISMAX);
penny.setWidth(0);
painter.setBrush(QBrush(Qt::black));
penny.setColor(Qt::black);
painter.setPen(penny);
// Draw raw crosshair
int linexstart = stick->getXCoordinate()-1000;
int lineystart = stick->getYCoordinate()-1000;
if (linexstart < JoyAxis::AXISMIN)
{
linexstart = JoyAxis::AXISMIN;
}
if (lineystart < JoyAxis::AXISMIN)
{
lineystart = JoyAxis::AXISMIN;
}
painter.drawRect(linexstart, lineystart, 2000, 2000);
painter.setBrush(QBrush(Qt::darkBlue));
penny.setColor(Qt::darkBlue);
painter.setPen(penny);
// Draw adjusted crosshair
linexstart = stick->getCircleXCoordinate()-1000;
lineystart = stick->getCircleYCoordinate()-1000;
if (linexstart < JoyAxis::AXISMIN)
{
linexstart = JoyAxis::AXISMIN;
}
if (lineystart < JoyAxis::AXISMIN)
{
lineystart = JoyAxis::AXISMIN;
}
painter.drawRect(linexstart, lineystart, 2000, 2000);
painter.restore();
// Reset pen
penny.setColor(Qt::black);
painter.setPen(penny);
// Draw primary pixmap
painter.setCompositionMode(QPainter::CompositionMode_DestinationOver);
painter.setPen(Qt::NoPen);
painter.fillRect(0, 0, side, side, palette().background().color());
paint.drawPixmap(pix.rect(), pix);
paint.save();
paint.scale(side / (double)(JoyAxis::AXISMAX*2.0), side / (double)(JoyAxis::AXISMAX*2.0));
paint.translate(JoyAxis::AXISMAX, JoyAxis::AXISMAX);
// Draw max zone and initial inner clear circle
int maxzone = stick->getMaxZone();
int diffmaxzone = JoyAxis::AXISMAX - maxzone;
paint.setOpacity(0.5);
paint.setBrush(Qt::darkGreen);
paint.drawEllipse(-JoyAxis::AXISMAX, -JoyAxis::AXISMAX, JoyAxis::AXISMAX*2, JoyAxis::AXISMAX*2);
paint.setCompositionMode(QPainter::CompositionMode_Clear);
paint.setPen(Qt::NoPen);
paint.drawEllipse(-JoyAxis::AXISMAX+diffmaxzone, -JoyAxis::AXISMAX+diffmaxzone, JoyAxis::AXISMAX*2-(diffmaxzone*2), JoyAxis::AXISMAX*2-(diffmaxzone*2));
painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
paint.setOpacity(1.0);
paint.restore();
// Re-draw pixmap so the inner circle will be transparent
paint.setCompositionMode(QPainter::CompositionMode_DestinationOver);
paint.drawPixmap(pix.rect(), pix);
paint.setCompositionMode(QPainter::CompositionMode_SourceOver);
}
void JoyControlStickStatusBox::drawFourWayDiagonalBox()
{
QPainter paint(this);
paint.setRenderHint(QPainter::Antialiasing, true);
int side = qMin(width()-2, height()-2);
QPixmap pix(side, side);
pix.fill(Qt::transparent);
QPainter painter(&pix);
painter.setRenderHint(QPainter::Antialiasing, true);
// Draw box outline
QPen penny;
penny.setColor(Qt::black);
penny.setWidth(1);
painter.setBrush(Qt::NoBrush);
painter.drawRect(0, 0, side-1, side-1);
painter.save();
painter.scale(side / (double)(JoyAxis::AXISMAX*2.0), side / (double)(JoyAxis::AXISMAX*2.0));
painter.translate(JoyAxis::AXISMAX, JoyAxis::AXISMAX);
// Draw diagonal zones
QList<int> anglesList = stick->getFourWayDiagonalZoneAngles();
penny.setWidth(0);
penny.setColor(Qt::black);
painter.setPen(penny);
painter.setBrush(QBrush(Qt::black));
painter.setOpacity(0.25);
painter.drawPie(-JoyAxis::AXISMAX, -JoyAxis::AXISMAX, JoyAxis::AXISMAX*2, JoyAxis::AXISMAX*2, anglesList.value(1)*16, 90*16);
painter.drawPie(-JoyAxis::AXISMAX, -JoyAxis::AXISMAX, JoyAxis::AXISMAX*2, JoyAxis::AXISMAX*2, anglesList.value(3)*16, 90*16);
painter.setOpacity(1.0);
// Draw deadzone circle
penny.setWidth(0);
penny.setColor(Qt::blue);
painter.setPen(penny);
painter.setBrush(QBrush(Qt::red));
painter.drawEllipse(-stick->getDeadZone(), -stick->getDeadZone(), stick->getDeadZone()*2, stick->getDeadZone()*2);
painter.restore();
painter.save();
penny.setWidth(0);
penny.setColor(Qt::black);
painter.setOpacity(0.5);
painter.setPen(penny);
painter.scale(side / 2.0, side / 2.0);
painter.translate(1, 1);
// Draw Y line
painter.drawLine(0, -1, 0, 1);
// Draw X line
painter.drawLine(-1, 0, 1, 0);
painter.setOpacity(1.0);
painter.restore();
painter.save();
painter.scale(side / (double)(JoyAxis::AXISMAX*2.0), side / (double)(JoyAxis::AXISMAX*2.0));
painter.translate(JoyAxis::AXISMAX, JoyAxis::AXISMAX);
penny.setWidth(0);
painter.setBrush(QBrush(Qt::black));
penny.setColor(Qt::black);
painter.setPen(penny);
// Draw raw crosshair
int linexstart = stick->getXCoordinate()-1000;
int lineystart = stick->getYCoordinate()-1000;
if (linexstart < JoyAxis::AXISMIN)
{
linexstart = JoyAxis::AXISMIN;
}
if (lineystart < JoyAxis::AXISMIN)
{
lineystart = JoyAxis::AXISMIN;
}
painter.drawRect(linexstart, lineystart, 2000, 2000);
painter.setBrush(QBrush(Qt::darkBlue));
penny.setColor(Qt::darkBlue);
painter.setPen(penny);
// Draw adjusted crosshair
linexstart = stick->getCircleXCoordinate()-1000;
lineystart = stick->getCircleYCoordinate()-1000;
if (linexstart < JoyAxis::AXISMIN)
{
linexstart = JoyAxis::AXISMIN;
}
if (lineystart < JoyAxis::AXISMIN)
{
lineystart = JoyAxis::AXISMIN;
}
painter.drawRect(linexstart, lineystart, 2000, 2000);
painter.restore();
// Reset pen
penny.setColor(Qt::black);
painter.setPen(penny);
// Draw primary pixmap
painter.setCompositionMode(QPainter::CompositionMode_DestinationOver);
painter.setPen(Qt::NoPen);
painter.fillRect(0, 0, side, side, palette().background().color());
paint.drawPixmap(pix.rect(), pix);
paint.save();
paint.scale(side / (double)(JoyAxis::AXISMAX*2.0), side / (double)(JoyAxis::AXISMAX*2.0));
paint.translate(JoyAxis::AXISMAX, JoyAxis::AXISMAX);
// Draw max zone and initial inner clear circle
int maxzone = stick->getMaxZone();
int diffmaxzone = JoyAxis::AXISMAX - maxzone;
paint.setOpacity(0.5);
paint.setBrush(Qt::darkGreen);
paint.drawEllipse(-JoyAxis::AXISMAX, -JoyAxis::AXISMAX, JoyAxis::AXISMAX*2, JoyAxis::AXISMAX*2);
paint.setCompositionMode(QPainter::CompositionMode_Clear);
paint.setPen(Qt::NoPen);
paint.drawEllipse(-JoyAxis::AXISMAX+diffmaxzone, -JoyAxis::AXISMAX+diffmaxzone, JoyAxis::AXISMAX*2-(diffmaxzone*2), JoyAxis::AXISMAX*2-(diffmaxzone*2));
painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
paint.setOpacity(1.0);
paint.restore();
// Re-draw pixmap so the inner circle will be transparent
paint.setCompositionMode(QPainter::CompositionMode_DestinationOver);
paint.drawPixmap(pix.rect(), pix);
paint.setCompositionMode(QPainter::CompositionMode_SourceOver);
}
``` | /content/code_sandbox/src/joycontrolstickstatusbox.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 4,723 |
```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>
#include <QResource>
#include <QTextStream>
#ifdef USE_SDL_2
#include <SDL2/SDL_version.h>
#else
#include <SDL/SDL_version.h>
#endif
#include "aboutdialog.h"
#include "ui_aboutdialog.h"
#include "common.h"
#include "eventhandlerfactory.h"
AboutDialog::AboutDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::AboutDialog)
{
ui->setupUi(this);
ui->versionLabel->setText(PadderCommon::programVersion);
fillInfoTextBrowser();
}
AboutDialog::~AboutDialog()
{
delete ui;
}
void AboutDialog::fillInfoTextBrowser()
{
QStringList finalInfoText;
finalInfoText.append(tr("Program Version %1").arg(PadderCommon::programVersion));
finalInfoText.append(tr("Program Compiled on %1 at %2").arg(__DATE__).arg(__TIME__));
QString sdlCompiledVersionNumber("%1.%2.%3");
QString sdlLinkedVersionNumber("%1.%2.%3");
SDL_version compiledver;
SDL_version linkedver;
SDL_VERSION(&compiledver);
#ifdef USE_SDL_2
SDL_GetVersion(&linkedver);
#else
linkedver = *(SDL_Linked_Version());
#endif
sdlCompiledVersionNumber = sdlCompiledVersionNumber.arg(compiledver.major).arg(compiledver.minor).arg(compiledver.patch);
finalInfoText.append(tr("Built Against SDL %1").arg(sdlCompiledVersionNumber));
sdlLinkedVersionNumber = sdlLinkedVersionNumber.arg(linkedver.major).arg(linkedver.minor).arg(linkedver.patch);
finalInfoText.append(tr("Running With SDL %1").arg(sdlLinkedVersionNumber));
finalInfoText.append(tr("Using Qt %1").arg(qVersion()));
BaseEventHandler *handler = 0;
EventHandlerFactory *factory = EventHandlerFactory::getInstance();
if (factory)
{
handler = factory->handler();
}
if (handler)
{
finalInfoText.append(tr("Using Event Handler: %1").arg(handler->getName()));
}
ui->infoTextBrowser->setText(finalInfoText.join("\n"));
// Read Changelog text from resource and put text in text box.
QResource changelogFile(":/Changelog");
QFile temp(changelogFile.absoluteFilePath());
temp.open(QIODevice::Text | QIODevice::ReadOnly);
QTextStream changelogStream(&temp);
QString changelogText = changelogStream.readAll();
temp.close();
ui->changelogPlainTextEdit->setPlainText(changelogText);
}
void AboutDialog::changeEvent(QEvent *event)
{
if (event->type() == QEvent::LanguageChange)
{
retranslateUi();
}
QDialog::changeEvent(event);
}
void AboutDialog::retranslateUi()
{
ui->retranslateUi(this);
ui->versionLabel->setText(PadderCommon::programVersion);
}
``` | /content/code_sandbox/src/aboutdialog.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 718 |
```c++
#define _WIN32_WINNT 0x0600
#include <qt_windows.h>
#include <psapi.h>
//#include <QDebug>
#include <QHashIterator>
#include <QSettings>
#include <QCoreApplication>
#include <QDir>
#include "winextras.h"
#include <shlobj.h>
typedef DWORD(WINAPI *MYPROC)(HANDLE, DWORD, LPTSTR, PDWORD);
// Check if QueryFullProcessImageNameW function exists in kernel32.dll.
// Function does not exist in Windows XP.
static MYPROC pQueryFullProcessImageNameW = (MYPROC) GetProcAddress(
GetModuleHandle(TEXT("kernel32.dll")), "QueryFullProcessImageNameW");
/*static bool isWindowsVistaOrHigher()
{
OSVERSIONINFO osvi;
memset(&osvi, 0, sizeof(osvi));
osvi.dwOSVersionInfoSize = sizeof(osvi);
GetVersionEx(&osvi);
return (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT && osvi.dwMajorVersion >= 6);
}
*/
const unsigned int WinExtras::EXTENDED_FLAG = 0x100;
int WinExtras::originalMouseAccel = 0;
static const QString ROOTASSOCIATIONKEY("HKEY_CURRENT_USER\\Software\\Classes");
static const QString FILEASSOCIATIONKEY(QString("%1\\%2").arg(ROOTASSOCIATIONKEY).arg(".amgp"));
static const QString PROGRAMASSOCIATIONKEY(QString("%1\\%2").arg(ROOTASSOCIATIONKEY).arg("AntiMicro.amgp"));
WinExtras WinExtras::_instance;
WinExtras::WinExtras(QObject *parent) :
QObject(parent)
{
populateKnownAliases();
}
QString WinExtras::getDisplayString(unsigned int virtualkey)
{
QString temp;
if (virtualkey <= 0)
{
temp = tr("[NO KEY]");
}
else if (_instance.knownAliasesVKStrings.contains(virtualkey))
{
temp = _instance.knownAliasesVKStrings.value(virtualkey);
}
return temp;
}
unsigned int WinExtras::getVirtualKey(QString codestring)
{
int temp = 0;
if (_instance.knownAliasesX11SymVK.contains(codestring))
{
temp = _instance.knownAliasesX11SymVK.value(codestring);
}
return temp;
}
void WinExtras::populateKnownAliases()
{
// These aliases are needed for xstrings that would
// return empty space characters from XLookupString
if (knownAliasesX11SymVK.isEmpty())
{
knownAliasesX11SymVK.insert("Escape", VK_ESCAPE);
knownAliasesX11SymVK.insert("Tab", VK_TAB);
knownAliasesX11SymVK.insert("space", VK_SPACE);
knownAliasesX11SymVK.insert("Delete", VK_DELETE);
knownAliasesX11SymVK.insert("Return", VK_RETURN);
knownAliasesX11SymVK.insert("KP_Enter", VK_RETURN);
knownAliasesX11SymVK.insert("BackSpace", VK_BACK);
knownAliasesX11SymVK.insert("F1", VK_F1);
knownAliasesX11SymVK.insert("F2", VK_F2);
knownAliasesX11SymVK.insert("F3", VK_F3);
knownAliasesX11SymVK.insert("F4", VK_F4);
knownAliasesX11SymVK.insert("F5", VK_F5);
knownAliasesX11SymVK.insert("F6", VK_F6);
knownAliasesX11SymVK.insert("F7", VK_F7);
knownAliasesX11SymVK.insert("F8", VK_F8);
knownAliasesX11SymVK.insert("F9", VK_F9);
knownAliasesX11SymVK.insert("F10", VK_F10);
knownAliasesX11SymVK.insert("F11", VK_F11);
knownAliasesX11SymVK.insert("F12", VK_F12);
knownAliasesX11SymVK.insert("Shift_L", VK_LSHIFT);
knownAliasesX11SymVK.insert("Shift_R", VK_RSHIFT);
knownAliasesX11SymVK.insert("Insert", VK_INSERT);
knownAliasesX11SymVK.insert("Pause", VK_PAUSE);
knownAliasesX11SymVK.insert("grave", VK_OEM_3);
knownAliasesX11SymVK.insert("minus", VK_OEM_MINUS);
knownAliasesX11SymVK.insert("equal", VK_OEM_PLUS);
knownAliasesX11SymVK.insert("Caps_Lock", VK_CAPITAL);
knownAliasesX11SymVK.insert("Control_L", VK_CONTROL);
knownAliasesX11SymVK.insert("Control_R", VK_RCONTROL);
knownAliasesX11SymVK.insert("Alt_L", VK_MENU);
knownAliasesX11SymVK.insert("Alt_R", VK_RMENU);
knownAliasesX11SymVK.insert("Super_L", VK_LWIN);
knownAliasesX11SymVK.insert("Menu", VK_APPS);
knownAliasesX11SymVK.insert("Prior", VK_PRIOR);
knownAliasesX11SymVK.insert("Next", VK_NEXT);
knownAliasesX11SymVK.insert("Home", VK_HOME);
knownAliasesX11SymVK.insert("End", VK_END);
knownAliasesX11SymVK.insert("Up", VK_UP);
knownAliasesX11SymVK.insert("Down", VK_DOWN);
knownAliasesX11SymVK.insert("Left", VK_LEFT);
knownAliasesX11SymVK.insert("Right", VK_RIGHT);
knownAliasesX11SymVK.insert("bracketleft", VK_OEM_4);
knownAliasesX11SymVK.insert("bracketright", VK_OEM_6);
knownAliasesX11SymVK.insert("backslash", VK_OEM_5);
knownAliasesX11SymVK.insert("slash", VK_OEM_2);
knownAliasesX11SymVK.insert("semicolon", VK_OEM_1);
knownAliasesX11SymVK.insert("apostrophe", VK_OEM_7);
knownAliasesX11SymVK.insert("comma", VK_OEM_COMMA);
knownAliasesX11SymVK.insert("period", VK_OEM_PERIOD);
knownAliasesX11SymVK.insert("KP_0", VK_NUMPAD0);
knownAliasesX11SymVK.insert("KP_1", VK_NUMPAD1);
knownAliasesX11SymVK.insert("KP_2", VK_NUMPAD2);
knownAliasesX11SymVK.insert("KP_3", VK_NUMPAD3);
knownAliasesX11SymVK.insert("KP_4", VK_NUMPAD4);
knownAliasesX11SymVK.insert("KP_5", VK_NUMPAD5);
knownAliasesX11SymVK.insert("KP_6", VK_NUMPAD6);
knownAliasesX11SymVK.insert("KP_7", VK_NUMPAD7);
knownAliasesX11SymVK.insert("KP_8", VK_NUMPAD8);
knownAliasesX11SymVK.insert("KP_9", VK_NUMPAD9);
knownAliasesX11SymVK.insert("Num_Lock", VK_NUMLOCK);
knownAliasesX11SymVK.insert("KP_Divide", VK_DIVIDE);
knownAliasesX11SymVK.insert("KP_Multiply", VK_MULTIPLY);
knownAliasesX11SymVK.insert("KP_Subtract", VK_SUBTRACT);
knownAliasesX11SymVK.insert("KP_Add", VK_ADD);
knownAliasesX11SymVK.insert("KP_Decimal", VK_DECIMAL);
knownAliasesX11SymVK.insert("Scroll_Lock", VK_SCROLL);
knownAliasesX11SymVK.insert("Print", VK_SNAPSHOT);
knownAliasesX11SymVK.insert("Multi_key", VK_RMENU);
}
if (knownAliasesVKStrings.isEmpty())
{
knownAliasesVKStrings.insert(VK_LWIN, QObject::tr("Super"));
knownAliasesVKStrings.insert(VK_APPS, QObject::tr("Menu"));
knownAliasesVKStrings.insert(VK_VOLUME_MUTE, QObject::tr("Mute"));
knownAliasesVKStrings.insert(VK_VOLUME_UP, QObject::tr("Vol+"));
knownAliasesVKStrings.insert(VK_VOLUME_DOWN, QObject::tr("Vol-"));
knownAliasesVKStrings.insert(VK_MEDIA_PLAY_PAUSE, QObject::tr("Play/Pause"));
knownAliasesVKStrings.insert(VK_PLAY, QObject::tr("Play"));
knownAliasesVKStrings.insert(VK_PAUSE, QObject::tr("Pause"));
knownAliasesVKStrings.insert(VK_MEDIA_PREV_TRACK, QObject::tr("Prev"));
knownAliasesVKStrings.insert(VK_MEDIA_NEXT_TRACK, QObject::tr("Next"));
knownAliasesVKStrings.insert(VK_LAUNCH_MAIL, QObject::tr("Mail"));
knownAliasesVKStrings.insert(VK_HOME, QObject::tr("Home"));
knownAliasesVKStrings.insert(VK_LAUNCH_MEDIA_SELECT, QObject::tr("Media"));
knownAliasesVKStrings.insert(VK_BROWSER_SEARCH, QObject::tr("Search"));
}
}
/**
* @brief Obtain a more specific virtual key (unsigned int) for a key grab event.
* @param Scan code obtained from a key grab event
* @param Virtual key obtained from a key grab event
* @return Corrected virtual key as an unsigned int
*/
unsigned int WinExtras::correctVirtualKey(unsigned int scancode, unsigned int virtualkey)
{
int mapvirtual = MapVirtualKey(scancode, MAPVK_VSC_TO_VK_EX);
int extended = (scancode & EXTENDED_FLAG) != 0;
int finalvirtual = 0;
switch (virtualkey)
{
case VK_CONTROL:
finalvirtual = extended ? VK_RCONTROL : VK_LCONTROL;
break;
case VK_SHIFT:
finalvirtual = mapvirtual;
break;
case VK_MENU:
finalvirtual = extended ? VK_RMENU : VK_LMENU;
break;
case 0x5E:
// Ignore System Reserved VK
finalvirtual = 0;
break;
default:
finalvirtual = virtualkey;
}
return finalvirtual;
}
/**
* @brief Convert a virtual key into the corresponding keyboard scan code.
* @param Windows virtual key
* @param Qt key alias
* @return Keyboard scan code as an unsigned int
*/
unsigned int WinExtras::scancodeFromVirtualKey(unsigned int virtualkey, unsigned int alias)
{
int scancode = 0;
if (virtualkey == VK_PAUSE)
{
// MapVirtualKey does not work with VK_PAUSE
scancode = 0x45;
}
else
{
scancode = MapVirtualKey(virtualkey, MAPVK_VK_TO_VSC);
}
switch (virtualkey)
{
case VK_LEFT: case VK_UP: case VK_RIGHT: case VK_DOWN: // arrow keys
case VK_PRIOR: case VK_NEXT: // page up and page down
case VK_END: case VK_HOME:
case VK_INSERT: case VK_DELETE:
case VK_DIVIDE: // numpad slash
case VK_NUMLOCK:
case VK_RCONTROL:
case VK_RMENU:
{
scancode |= EXTENDED_FLAG; // set extended bit
break;
}
case VK_RETURN:
{
// Remove ambiguity between Enter and Numpad Enter.
// In Windows, VK_RETURN is used for both.
if (alias == Qt::Key_Enter)
{
scancode |= EXTENDED_FLAG; // set extended bit
break;
}
}
}
return scancode;
}
/**
* @brief Check foreground window (window in focus) and obtain the
* corresponding exe file path.
* @return File path of executable
*/
QString WinExtras::getForegroundWindowExePath()
{
QString exePath;
HWND foreground = GetForegroundWindow();
HANDLE windowProcess = NULL;
if (foreground)
{
DWORD processId;
GetWindowThreadProcessId(foreground, &processId);
windowProcess = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, true, processId);
}
if (windowProcess != NULL)
{
TCHAR filename[MAX_PATH];
memset(filename, 0, sizeof(filename));
//qDebug() << QString::number(sizeof(filename)/sizeof(TCHAR));
if (pQueryFullProcessImageNameW)
{
// Windows Vista and later
DWORD pathLength = MAX_PATH * sizeof(TCHAR);
pQueryFullProcessImageNameW(windowProcess, 0, filename, &pathLength);
//qDebug() << pathLength;
}
else
{
// Windows XP
GetModuleFileNameEx(windowProcess, NULL, filename, MAX_PATH * sizeof(TCHAR));
//qDebug() << pathLength;
}
exePath = QString::fromWCharArray(filename);
//qDebug() << QString::fromWCharArray(filename);
CloseHandle(windowProcess);
}
return exePath;
}
bool WinExtras::containsFileAssociationinRegistry()
{
bool result = false;
QSettings associationReg(FILEASSOCIATIONKEY, QSettings::NativeFormat);
QString temp = associationReg.value("Default", "").toString();
if (!temp.isEmpty())
{
result = true;
}
return result;
}
void WinExtras::writeFileAssocationToRegistry()
{
QSettings fileAssociationReg(FILEASSOCIATIONKEY, QSettings::NativeFormat);
fileAssociationReg.setValue("Default", "AntiMicro.amgp");
fileAssociationReg.sync();
QSettings programAssociationReg(PROGRAMASSOCIATIONKEY, QSettings::NativeFormat);
programAssociationReg.setValue("Default", tr("AntiMicro Profile"));
programAssociationReg.setValue("shell/open/command/Default", QString("\"%1\" \"%2\"").arg(QDir::toNativeSeparators(qApp->applicationFilePath())).arg("%1"));
programAssociationReg.setValue("DefaultIcon/Default", QString("%1,%2").arg(QDir::toNativeSeparators(qApp->applicationFilePath())).arg("0"));
programAssociationReg.sync();
// Required to refresh settings used in Windows Explorer
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0);
}
void WinExtras::removeFileAssociationFromRegistry()
{
QSettings fileAssociationReg(FILEASSOCIATIONKEY, QSettings::NativeFormat);
QString currentValue = fileAssociationReg.value("Default", "").toString();
if (currentValue == "AntiMicro.amgp")
{
fileAssociationReg.remove("Default");
fileAssociationReg.sync();
}
QSettings programAssociationReg(PROGRAMASSOCIATIONKEY, QSettings::NativeFormat);
programAssociationReg.remove("");
programAssociationReg.sync();
// Required to refresh settings used in Windows Explorer
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0);
}
/**
* @brief Attempt to elevate process using runas
* @return Execution status
*/
bool WinExtras::elevateAntiMicro()
{
QString antiProgramLocation = QDir::toNativeSeparators(qApp->applicationFilePath());
QByteArray temp = antiProgramLocation.toUtf8();
SHELLEXECUTEINFO sei = { sizeof(sei) };
wchar_t tempverb[6];
wchar_t tempfile[antiProgramLocation.length() + 1];
QString("runas").toWCharArray(tempverb);
antiProgramLocation.toWCharArray(tempfile);
tempverb[5] = '\0';
tempfile[antiProgramLocation.length()] = '\0';
sei.lpVerb = tempverb;
sei.lpFile = tempfile;
sei.hwnd = NULL;
sei.nShow = SW_NORMAL;
BOOL result = ShellExecuteEx(&sei);
return result;
}
/**
* @brief Check if the application is running with administrative privileges.
* @return Status indicating administrative privileges
*/
bool WinExtras::IsRunningAsAdmin()
{
BOOL isAdmin = FALSE;
PSID administratorsGroup;
SID_IDENTIFIER_AUTHORITY ntAuthority = SECURITY_NT_AUTHORITY;
isAdmin = AllocateAndInitializeSid(&ntAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0,
&administratorsGroup);
if (isAdmin)
{
if (!CheckTokenMembership(NULL, administratorsGroup, &isAdmin))
{
isAdmin = FALSE;
}
FreeSid(administratorsGroup);
}
return isAdmin;
}
/**
* @brief Temporarily disable "Enhanced Pointer Precision".
*/
void WinExtras::disablePointerPrecision()
{
int mouseInfo[3];
SystemParametersInfo(SPI_GETMOUSE, 0, &mouseInfo, 0);
if (mouseInfo[2] == 1 && mouseInfo[2] == originalMouseAccel)
{
mouseInfo[2] = 0;
SystemParametersInfo(SPI_SETMOUSE, 0, &mouseInfo, 0);
}
}
/**
* @brief If "Enhanced Pointer Precision" is currently disabled and
* the setting has not been changed explicitly by the user while
* the program has been running, re-enable "Enhanced Pointer Precision".
* Return the mouse behavior to normal.
*/
void WinExtras::enablePointerPrecision()
{
int mouseInfo[3];
SystemParametersInfo(SPI_GETMOUSE, 0, &mouseInfo, 0);
if (mouseInfo[2] == 0 && mouseInfo[2] != originalMouseAccel)
{
mouseInfo[2] = originalMouseAccel;
SystemParametersInfo(SPI_SETMOUSE, 0, &mouseInfo, 0);
}
}
/**
* @brief Used to check if the "Enhance Pointer Precision" Windows
* option is currently enabled.
* @return Status of "Enhanced Pointer Precision"
*/
bool WinExtras::isUsingEnhancedPointerPrecision()
{
bool result = false;
int mouseInfo[3];
SystemParametersInfo(SPI_GETMOUSE, 0, &mouseInfo, 0);
if (mouseInfo[2] > 0)
{
result = true;
}
return result;
}
/**
* @brief Get the value of "Enhanced Pointer Precision" when the program
* first starts. Needed to not override setting if the option has
* been disabled in Windows by the user.
*/
void WinExtras::grabCurrentPointerPrecision()
{
int mouseInfo[3];
SystemParametersInfo(SPI_GETMOUSE, 0, &mouseInfo, 0);
originalMouseAccel = mouseInfo[2];
}
/**
* @brief Get the window text of the window currently in focus.
* @return Window title of application in focus.
*/
QString WinExtras::getCurrentWindowText()
{
QString windowText;
HWND foreground = GetForegroundWindow();
if (foreground != NULL)
{
TCHAR foundWindowTitle[256];
memset(foundWindowTitle, 0, sizeof(foundWindowTitle));
GetWindowTextW(foreground, foundWindowTitle, 255);
QString temp = QString::fromWCharArray(foundWindowTitle);
if (temp.isEmpty())
{
memset(foundWindowTitle, 0, sizeof(foundWindowTitle));
SendMessageA(foreground, WM_GETTEXT, 255, (LPARAM)foundWindowTitle);
temp = QString::fromWCharArray(foundWindowTitle);
}
if (!temp.isEmpty())
{
windowText = temp;
}
}
return windowText;
}
bool WinExtras::raiseProcessPriority()
{
bool result = false;
result = SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
/*if (!result)
{
qDebug() << "COULD NOT RAISE PROCESS PRIORITY";
}
*/
return result;
}
QPoint WinExtras::getCursorPos()
{
POINT cursorPoint;
GetCursorPos(&cursorPoint);
QPoint temp(cursorPoint.x, cursorPoint.y);
return temp;
}
``` | /content/code_sandbox/src/winextras.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 4,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 <QPainter>
#include <qdrawutil.h>
#include "axisvaluebox.h"
#include "joyaxis.h"
AxisValueBox::AxisValueBox(QWidget *parent) :
QWidget(parent)
{
deadZone = 0;
maxZone = 0;
joyValue = 0;
throttle = 0;
lboxstart = 0;
lboxend = 0;
rboxstart = 0;
rboxend = 0;
}
void AxisValueBox::setThrottle(int throttle)
{
if (throttle <= JoyAxis::PositiveHalfThrottle && throttle >= JoyAxis::NegativeHalfThrottle)
{
this->throttle = throttle;
setValue(joyValue);
}
update();
}
void AxisValueBox::setValue(int value)
{
if (value >= JoyAxis::AXISMIN && value <= JoyAxis::AXISMAX)
{
if (throttle == JoyAxis::NormalThrottle)
{
this->joyValue = value;
}
else if (throttle == JoyAxis::NegativeThrottle)
{
this->joyValue = (value + JoyAxis::AXISMIN) / 2;
}
else if (throttle == JoyAxis::PositiveThrottle)
{
this->joyValue = (value + JoyAxis::AXISMAX) / 2;
}
else if (throttle == JoyAxis::NegativeHalfThrottle)
{
this->joyValue = value <= 0 ? value : -value;
}
else if (throttle == JoyAxis::PositiveHalfThrottle)
{
this->joyValue = value >= 0 ? value : -value;
}
}
update();
}
void AxisValueBox::setDeadZone(int deadZone)
{
if (deadZone >= JoyAxis::AXISMIN && deadZone <= JoyAxis::AXISMAX)
{
this->deadZone = deadZone;
}
update();
}
int AxisValueBox::getDeadZone()
{
return deadZone;
}
void AxisValueBox::setMaxZone(int maxZone)
{
if (maxZone >= JoyAxis::AXISMIN && maxZone <= JoyAxis::AXISMAX)
{
this->maxZone = maxZone;
}
update();
}
int AxisValueBox::getMaxZone()
{
return maxZone;
}
int AxisValueBox::getJoyValue()
{
return joyValue;
}
int AxisValueBox::getThrottle()
{
return throttle;
}
void AxisValueBox::resizeEvent(QResizeEvent *event)
{
Q_UNUSED(event);
boxwidth = (this->width() / 2) - 5;
boxheight = this->height() - 4;
lboxstart = 0;
lboxend = lboxstart + boxwidth;
rboxstart = lboxend + 10;
rboxend = rboxstart + boxwidth;
singlewidth = this->width();
singleend = lboxstart + singlewidth;
}
void AxisValueBox::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainter paint (this);
paint.setPen(palette().base().color());
paint.setBrush(palette().base().color());
QBrush brush(palette().light().color());
if (throttle == 0)
{
qDrawShadeRect(&paint, lboxstart, 0, lboxend, height(), palette(), true, 2, 0, &brush);
qDrawShadeRect(&paint, rboxstart, 0, rboxend, height(), palette(), true, 2, 0, &brush);
}
else
{
qDrawShadeRect(&paint, lboxstart, 0, singlewidth, height(), palette(), true, 2, 0, &brush);
}
QColor innerColor;
if (abs(joyValue) <= deadZone)
{
innerColor = Qt::gray;
}
else if (abs(joyValue) >= maxZone)
{
innerColor = Qt::red;
}
else
{
innerColor = Qt::blue;
}
paint.setPen(innerColor);
paint.setBrush(innerColor);
int barwidth = (throttle == 0) ? boxwidth : singlewidth;
int barlength = abs((barwidth - 2) * joyValue) / JoyAxis::AXISMAX;
if (joyValue > 0)
{
paint.drawRect(((throttle == 0) ? rboxstart : lboxstart) + 2, 2, barlength, boxheight);
}
else if (joyValue < 0)
{
paint.drawRect(lboxstart + barwidth - 2 - barlength, 2, barlength, boxheight);
}
// Draw marker for deadZone
int deadLine = abs((barwidth - 2) * deadZone) / JoyAxis::AXISMAX;
int maxLine = abs((barwidth - 2) * maxZone) / JoyAxis::AXISMAX;
paint.setPen(Qt::blue);
brush.setColor(Qt::blue);
QBrush maxBrush(Qt::red);
if (throttle == JoyAxis::NormalThrottle)
{
qDrawPlainRect(&paint, rboxstart + 2 + deadLine, 2, 4, boxheight + 2, Qt::black, 1, &brush);
qDrawPlainRect(&paint, lboxend - deadLine - 2, 2, 4, boxheight + 2, Qt::black, 1, &brush);
paint.setPen(Qt::red);
qDrawPlainRect(&paint, rboxstart + 2 + maxLine, 2, 4, boxheight + 2, Qt::black, 1, &maxBrush);
qDrawPlainRect(&paint, lboxend - maxLine - 2, 2, 4, boxheight + 2, Qt::black, 1, &maxBrush);
}
else if (throttle == JoyAxis::PositiveThrottle || JoyAxis::PositiveHalfThrottle)
{
qDrawPlainRect(&paint, lboxstart + deadLine - 2, 2, 4, boxheight + 2, Qt::black, 1, &brush);
paint.setPen(Qt::red);
qDrawPlainRect(&paint, lboxstart + maxLine, 2, 4, boxheight + 2, Qt::black, 1, &maxBrush);
}
else if (throttle == JoyAxis::NegativeThrottle || throttle == JoyAxis::NegativeHalfThrottle)
{
qDrawPlainRect(&paint, singleend - deadLine - 2, 2, 4, boxheight + 2, Qt::black, 1, &brush);
paint.setPen(Qt::red);
qDrawPlainRect(&paint, singleend - maxLine, 2, 4, boxheight + 2, Qt::black, 1, &maxBrush);
}
}
``` | /content/code_sandbox/src/axisvaluebox.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,633 |
```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 ABOUTDIALOG_H
#define ABOUTDIALOG_H
#include <QDialog>
namespace Ui {
class AboutDialog;
}
class AboutDialog : public QDialog
{
Q_OBJECT
public:
explicit AboutDialog(QWidget *parent = 0);
~AboutDialog();
private:
Ui::AboutDialog *ui;
protected:
void fillInfoTextBrowser();
virtual void changeEvent(QEvent *event);
void retranslateUi();
};
#endif // ABOUTDIALOG_H
``` | /content/code_sandbox/src/aboutdialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 195 |
```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 GAMECONTROLLEREXAMPLE_H
#define GAMECONTROLLEREXAMPLE_H
#include <QWidget>
#include <QPaintEvent>
class GameControllerExample : public QWidget
{
Q_OBJECT
public:
explicit GameControllerExample(QWidget *parent = 0);
enum ButtonType {
Button, AxisX, AxisY,
};
static const unsigned int MAXBUTTONINDEX = 20;
protected:
virtual void paintEvent(QPaintEvent *event);
QImage controllerimage;
QImage buttonimage;
QImage axisimage;
QImage rotatedaxisimage;
int currentIndex;
signals:
void indexUpdated(int index);
public slots:
void setActiveButton(int button);
};
#endif // GAMECONTROLLEREXAMPLE_H
``` | /content/code_sandbox/src/gamecontrollerexample.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 239 |
```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 MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QMap>
#include <QIcon>
#include <QSystemTrayIcon>
#include <QAction>
#include <QFileDialog>
#include <QHideEvent>
#include <QShowEvent>
#include <QCloseEvent>
#include <QLocalServer>
#include <QTranslator>
#include "inputdevice.h"
#include "aboutdialog.h"
#include "commandlineutility.h"
#include "antimicrosettings.h"
#include "autoprofilewatcher.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QMap<SDL_JoystickID, InputDevice*> *joysticks,
CommandLineUtility *cmdutility,
AntiMicroSettings *settings,
bool graphical=true, QWidget *parent = 0);
~MainWindow();
bool getGraphicalStatus();
void setTranslator(QTranslator *translator);
QTranslator* getTranslator();
void setAppTranslator(QTranslator *translator);
QTranslator* getAppTranslator();
protected:
virtual void showEvent(QShowEvent *event);
virtual void changeEvent(QEvent *event);
virtual void closeEvent(QCloseEvent *event);
void retranslateUi();
void loadConfigFile(QString fileLocation, int joystickIndex=0);
void loadConfigFile(QString fileLocation, QString controllerID);
void unloadCurrentConfig(int joystickIndex=0);
void unloadCurrentConfig(QString controllerID);
void changeStartSetNumber(unsigned int startSetNumber, QString controllerID);
void changeStartSetNumber(unsigned int startSetNumber, unsigned int joystickIndex=0);
QMap<SDL_JoystickID, InputDevice*> *joysticks;
QSystemTrayIcon *trayIcon;
QAction *hideAction;
QAction *restoreAction;
QAction *closeAction;
QAction *updateJoy;
QMenu *trayIconMenu;
QMap<int, QList<QAction*> > profileActions;
AboutDialog *aboutDialog;
bool signalDisconnect;
bool showTrayIcon;
bool graphical;
QLocalServer *localServer;
CommandLineUtility *cmdutility;
AntiMicroSettings *settings;
QTranslator *translator;
QTranslator *appTranslator;
AutoProfileWatcher *appWatcher;
private:
Ui::MainWindow *ui;
void updateButtonPressed();
signals:
void joystickRefreshRequested();
void readConfig(int index);
#ifdef USE_SDL_2
void mappingUpdated(QString mapping, InputDevice *device);
#endif
public slots:
void fillButtons();
void makeJoystickTabs();
void alterConfigFromSettings();
void fillButtons(InputDevice *joystick);
void fillButtons(QMap<SDL_JoystickID, InputDevice*> *joysticks);
void startJoystickRefresh();
void hideWindow();
void saveAppConfig();
void loadAppConfig(bool forceRefresh=false);
void removeJoyTabs();
void quitProgram();
void changeWindowStatus();
void refreshTabHelperThreads();
#ifdef USE_SDL_2
void controllerMapOpening();
void testMappingUpdateNow(int index, InputDevice *device);
void removeJoyTab(SDL_JoystickID deviceID);
void addJoyTab(InputDevice *device);
void selectControllerJoyTab(QString GUID);
void selectControllerJoyTab(unsigned int index);
#endif
private slots:
void refreshTrayIconMenu();
void trayIconClickAction(QSystemTrayIcon::ActivationReason reason);
void mainMenuChange();
void disableFlashActions();
void enableFlashActions();
void joystickTrayShow();
void singleTrayProfileMenuShow();
void profileTrayActionTriggered(bool checked);
void populateTrayIcon();
void openAboutDialog();
void handleInstanceDisconnect();
void openJoystickStatusWindow();
void openKeyCheckerDialog();
void openGitHubPage();
void openWikiPage();
void propogateNameDisplayStatus(bool displayNames);
void changeLanguage(QString language);
void openMainSettingsDialog();
void showStickAssignmentDialog();
void checkHideEmptyOption();
#ifdef Q_OS_WIN
void checkKeyRepeatOptions();
void restartAsElevated();
#endif
#ifdef USE_SDL_2
void openGameControllerMappingWindow(bool openAsMain=false);
void propogateMappingUpdate(QString mapping, InputDevice *device);
void autoprofileLoad(AutoProfileInfo *info);
void checkAutoProfileWatcherTimer();
void updateMenuOptions();
#endif
};
#endif // MAINWINDOW_H
``` | /content/code_sandbox/src/mainwindow.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,049 |
```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 <QList>
#include "joycontrolstickcontextmenu.h"
#include "mousedialog/mousecontrolsticksettingsdialog.h"
#include "antkeymapper.h"
#include "inputdevice.h"
#include "common.h"
JoyControlStickContextMenu::JoyControlStickContextMenu(JoyControlStick *stick, QWidget *parent) :
QMenu(parent),
helper(stick)
{
this->stick = stick;
helper.moveToThread(stick->thread());
connect(this, SIGNAL(aboutToHide()), this, SLOT(deleteLater()));
}
void JoyControlStickContextMenu::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(setStickPreset()));
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(setStickPreset()));
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(setStickPreset()));
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(setStickPreset()));
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(setStickPreset()));
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(setStickPreset()));
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(setStickPreset()));
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(setStickPreset()));
presetGroup->addAction(action);
this->addSeparator();
QActionGroup *modesGroup = new QActionGroup(this);
int mode = static_cast<int>(JoyControlStick::StandardMode);
action = this->addAction(tr("Standard"));
action->setCheckable(true);
action->setChecked(stick->getJoyMode() == JoyControlStick::StandardMode);
action->setData(QVariant(mode));
connect(action, SIGNAL(triggered()), this, SLOT(setStickMode()));
modesGroup->addAction(action);
action = this->addAction(tr("Eight Way"));
action->setCheckable(true);
action->setChecked(stick->getJoyMode() == JoyControlStick::EightWayMode);
mode = static_cast<int>(JoyControlStick::EightWayMode);
action->setData(QVariant(mode));
connect(action, SIGNAL(triggered()), this, SLOT(setStickMode()));
modesGroup->addAction(action);
action = this->addAction(tr("4 Way Cardinal"));
action->setCheckable(true);
action->setChecked(stick->getJoyMode() == JoyControlStick::FourWayCardinal);
mode = static_cast<int>(JoyControlStick::FourWayCardinal);
action->setData(QVariant(mode));
connect(action, SIGNAL(triggered()), this, SLOT(setStickMode()));
modesGroup->addAction(action);
action = this->addAction(tr("4 Way Diagonal"));
action->setCheckable(true);
action->setChecked(stick->getJoyMode() == JoyControlStick::FourWayDiagonal);
mode = static_cast<int>(JoyControlStick::FourWayDiagonal);
action->setData(QVariant(mode));
connect(action, SIGNAL(triggered()), this, SLOT(setStickMode()));
modesGroup->addAction(action);
this->addSeparator();
action = this->addAction(tr("Mouse Settings"));
action->setCheckable(false);
connect(action, SIGNAL(triggered()), this, SLOT(openMouseSettingsDialog()));
}
void JoyControlStickContextMenu::setStickMode()
{
QAction *action = static_cast<QAction*>(sender());
int item = action->data().toInt();
stick->setJoyMode(static_cast<JoyControlStick::JoyMode>(item));
}
void JoyControlStickContextMenu::setStickPreset()
{
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);
stick->setJoyMode(JoyControlStick::StandardMode);
stick->setDiagonalRange(65);
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);
stick->setJoyMode(JoyControlStick::StandardMode);
stick->setDiagonalRange(65);
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);
stick->setJoyMode(JoyControlStick::StandardMode);
stick->setDiagonalRange(65);
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);
stick->setJoyMode(JoyControlStick::StandardMode);
stick->setDiagonalRange(65);
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);
stick->setJoyMode(JoyControlStick::StandardMode);
stick->setDiagonalRange(45);
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);
stick->setJoyMode(JoyControlStick::StandardMode);
stick->setDiagonalRange(45);
PadderCommon::inputDaemonMutex.unlock();
}
else if (item == 6)
{
PadderCommon::inputDaemonMutex.lock();
if (stick->getJoyMode() == JoyControlStick::StandardMode ||
stick->getJoyMode() == JoyControlStick::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 (stick->getJoyMode() == JoyControlStick::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 (stick->getJoyMode() == JoyControlStick::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);
}
stick->setDiagonalRange(45);
PadderCommon::inputDaemonMutex.unlock();
}
else if (item == 7)
{
QMetaObject::invokeMethod(&helper, "clearButtonsSlotsEventReset");
QMetaObject::invokeMethod(stick, "setDiagonalRange", Q_ARG(int, 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);
}
int JoyControlStickContextMenu::getPresetIndex()
{
int result = 0;
PadderCommon::inputDaemonMutex.lock();
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)
{
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;
}
void JoyControlStickContextMenu::openMouseSettingsDialog()
{
MouseControlStickSettingsDialog *dialog = new MouseControlStickSettingsDialog(stick, parentWidget());
dialog->show();
}
``` | /content/code_sandbox/src/joycontrolstickcontextmenu.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 5,208 |
```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 "antimicrosettings.h"
const bool AntiMicroSettings::defaultDisabledWinEnhanced = false;
const bool AntiMicroSettings::defaultAssociateProfiles = true;
const int AntiMicroSettings::defaultSpringScreen = -1;
const unsigned int AntiMicroSettings::defaultSDLGamepadPollRate = 10;
AntiMicroSettings::AntiMicroSettings(const QString &fileName, Format format, QObject *parent) :
QSettings(fileName, format, parent)
{
}
/**
* @brief Get the currently used value such as an setting overridden
* with a command line argument.
* @param Setting key
* @param Default value to use if key does not exist
* @return Stored value or the default value passed
*/
QVariant AntiMicroSettings::runtimeValue(const QString &key, const QVariant &defaultValue) const
{
QVariant settingValue;
QString inGroup = group();
QString fullKey = QString(inGroup).append("/").append(key);
if (cmdSettings.contains(fullKey))
{
settingValue = cmdSettings.value(fullKey, defaultValue);
}
else
{
settingValue = value(key, defaultValue);
}
return settingValue;
}
/**
* @brief Import relevant options given on the command line into a QSettings
* instance. Used to override any options that might be present in the
* main settings file. Keys will have to be changed to the appropriate
* config key.
* @param Interpreted options set on the command line.
*/
void AntiMicroSettings::importFromCommandLine(CommandLineUtility &cmdutility)
{
cmdSettings.clear();
if (cmdutility.isLaunchInTrayEnabled())
{
cmdSettings.setValue("LaunchInTray", 1);
}
if (cmdutility.shouldMapController())
{
cmdSettings.setValue("DisplaySDLMapping", 1);
}
}
QMutex* AntiMicroSettings::getLock()
{
return &lock;
}
``` | /content/code_sandbox/src/antimicrosettings.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 ADVANCEBUTTONDIALOG_H
#define ADVANCEBUTTONDIALOG_H
#include <QDialog>
#include <QListWidgetItem>
#include "joybutton.h"
#include "simplekeygrabberbutton.h"
#include "uihelpers/advancebuttondialoghelper.h"
namespace Ui {
class AdvanceButtonDialog;
}
class AdvanceButtonDialog : public QDialog
{
Q_OBJECT
public:
explicit AdvanceButtonDialog(JoyButton *button, QWidget *parent=0);
~AdvanceButtonDialog();
private:
Ui::AdvanceButtonDialog *ui;
enum SlotTypeComboIndex {
KBMouseSlot = 0, CycleSlot, DelaySlot, DistanceSlot, ExecuteSlot,
HoldSlot, LoadSlot, MouseModSlot, PauseSlot, PressTimeSlot,
ReleaseSlot, SetChangeSlot, TextEntry,
};
protected:
void connectButtonEvents(SimpleKeyGrabberButton *button);
void appendBlankKeyGrabber();
int actionTimeConvert();
void changeTurboForSequences();
void fillTimeComboBoxes();
void refreshTimeComboBoxes(JoyButtonSlot *slot);
void updateWindowTitleButtonName();
void populateAutoResetInterval();
void disconnectTimeBoxesEvents();
void connectTimeBoxesEvents();
void resetTimeBoxes();
void populateSetSelectionComboBox();
void populateSlotSetSelectionComboBox();
void findTurboModeComboIndex();
int oldRow;
JoyButton *button;
AdvanceButtonDialogHelper helper;
static const int MINIMUMTURBO;
signals:
void toggleChanged(bool state);
void turboChanged(bool state);
void slotsChanged();
void turboButtonEnabledChange(bool state);
public slots:
void placeNewSlot(JoyButtonSlot *slot);
void clearAllSlots();
private slots:
void changeTurboText(int value);
void updateTurboIntervalValue(int value);
void checkTurboSetting(bool state);
void updateSlotsScrollArea(int value);
void deleteSlot();
void changeSelectedSlot();
void insertSlot();
void updateSelectedSlot(int value);
void insertPauseSlot();
void insertHoldSlot();
void insertCycleSlot();
void insertDistanceSlot();
void insertReleaseSlot();
void insertMouseSpeedModSlot();
void insertKeyPressSlot();
void insertDelaySlot();
void insertSetChangeSlot();
void insertTextEntrySlot();
void insertExecuteSlot();
void updateActionTimeLabel();
void updateSetSelection();
void checkTurboIntervalValue(int value);
void performStatsWidgetRefresh(QListWidgetItem *item);
void checkSlotTimeUpdate();
void checkSlotMouseModUpdate();
void checkSlotDistanceUpdate();
void checkSlotSetChangeUpdate();
void checkCycleResetWidgetStatus(bool enabled);
void setButtonCycleResetInterval(double value);
void setButtonCycleReset(bool enabled);
void setButtonTurboMode(int value);
void showSelectProfileWindow();
void showFindExecutableWindow(bool);
void changeSlotTypeDisplay(int index);
void changeSlotHelpText(int index);
};
#endif // ADVANCEBUTTONDIALOG_H
``` | /content/code_sandbox/src/advancebuttondialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 742 |
```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 QUICKSETDIALOG_H
#define QUICKSETDIALOG_H
#include <QDialog>
#include "inputdevice.h"
namespace Ui {
class QuickSetDialog;
}
class QuickSetDialog : public QDialog
{
Q_OBJECT
public:
explicit QuickSetDialog(InputDevice *joystick, QWidget *parent = 0);
~QuickSetDialog();
protected:
InputDevice *joystick;
QDialog *currentButtonDialog;
private:
Ui::QuickSetDialog *ui;
signals:
void buttonDialogClosed();
private slots:
void showAxisButtonDialog();
void showButtonDialog();
void showStickButtonDialog();
void showDPadButtonDialog();
void nullifyDialogPointer();
void restoreButtonStates();
};
#endif // QUICKSETDIALOG_H
``` | /content/code_sandbox/src/quicksetdialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 257 |
```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 JOYCONTROLSTICK_H
#define JOYCONTROLSTICK_H
#include <QObject>
#include <QHash>
#include <QList>
#include <QTimer>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include "joyaxis.h"
#include "joybutton.h"
#include "joycontrolstickdirectionstype.h"
#include "joybuttontypes/joycontrolstickbutton.h"
#include "joybuttontypes/joycontrolstickmodifierbutton.h"
class JoyControlStick : public QObject, public JoyStickDirectionsType
{
Q_OBJECT
public:
explicit JoyControlStick(JoyAxis *axisX, JoyAxis *axisY,
int index, int originset = 0, QObject *parent = 0);
~JoyControlStick();
enum JoyMode {StandardMode=0, EightWayMode, FourWayCardinal, FourWayDiagonal};
void joyEvent(bool ignoresets=false);
bool inDeadZone();
int getDeadZone();
int getDiagonalRange();
double getDistanceFromDeadZone();
double getDistanceFromDeadZone(int axisXValue, int axisYValue);
double getAbsoluteRawDistance();
double getAbsoluteRawDistance(int axisXValue, int axisYValue);
double getNormalizedAbsoluteDistance();
int getIndex();
void setIndex(int index);
int getRealJoyIndex();
int getMaxZone();
int getCurrentlyAssignedSet();
virtual QString getName(bool forceFullFormat=false, bool displayNames=false);
virtual QString getPartialName(bool forceFullFormat=false, bool displayNames=false);
JoyStickDirections getCurrentDirection();
int getXCoordinate();
int getYCoordinate();
int getCircleXCoordinate();
int getCircleYCoordinate();
double calculateBearing();
double calculateBearing(int axisXValue, int axisYValue);
QList<double> getDiagonalZoneAngles();
QList<int> getFourWayCardinalZoneAngles();
QList<int> getFourWayDiagonalZoneAngles();
QHash<JoyStickDirections, JoyControlStickButton*>* getButtons();
JoyControlStickModifierButton* getModifierButton();
JoyAxis* getAxisX();
JoyAxis* getAxisY();
void replaceXAxis(JoyAxis *axis);
void replaceYAxis(JoyAxis *axis);
void replaceAxes(JoyAxis *axisX, JoyAxis* axisY);
JoyControlStickButton* getDirectionButton(JoyStickDirections direction);
double calculateMouseDirectionalDistance(JoyControlStickButton *button);
double calculateDirectionalDistance();
double calculateLastDirectionalDistance();
double calculateLastMouseDirectionalDistance(JoyControlStickButton *button);
double calculateLastAccelerationButtonDistance(JoyControlStickButton *button);
double calculateAccelerationDistance(JoyControlStickButton *button);
double calculateXAxisDistance(int axisXValue);
double calculateYAxisDistance(int axisYValue);
double calculateLastAccelerationDirectionalDistance();
double getRadialDistance(int axisXValue, int axisYValue);
void setJoyMode(JoyMode mode);
JoyMode getJoyMode();
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);
void setButtonsExtraAccelerationStatus(bool enabled);
bool getButtonsExtraAccelerationStatus();
void setButtonsExtraAccelerationMultiplier(double value);
double getButtonsExtraAccelerationMultiplier();
void setButtonsStartAccelerationMultiplier(double value);
double getButtonsStartAccelerationMultiplier();
void setButtonsMinAccelerationThreshold(double value);
double getButtonsMinAccelerationThreshold();
void setButtonsMaxAccelerationThreshold(double value);
double getButtonsMaxAccelerationThreshold();
void setButtonsAccelerationExtraDuration(double value);
double getButtonsAccelerationEasingDuration();
void setButtonsSpringDeadCircleMultiplier(int value);
int getButtonsSpringDeadCircleMultiplier();
void setButtonsExtraAccelCurve(JoyButton::JoyExtraAccelerationCurve curve);
JoyButton::JoyExtraAccelerationCurve getButtonsExtraAccelerationCurve();
void releaseButtonEvents();
QString getStickName();
virtual bool isDefault();
virtual void setDefaultStickName(QString tempname);
virtual QString getDefaultStickName();
virtual void readConfig(QXmlStreamReader *xml);
virtual void writeConfig(QXmlStreamWriter *xml);
SetJoystick* getParentSet();
bool hasSlotsAssigned();
bool isRelativeSpring();
void copyAssignments(JoyControlStick *destStick);
double getCircleAdjust();
unsigned int getStickDelay();
double getButtonsEasingDuration();
void queueJoyEvent(bool ignoresets);
bool hasPendingEvent();
void activatePendingEvent();
void clearPendingEvent();
//double calculateXDistanceFromDeadZone(int axisXValue, int axisYValue, bool interpolate=false);
double getSpringDeadCircleX();
double getSpringDeadCircleY();
QHash<JoyStickDirections, JoyControlStickButton*> getButtonsForDirection(JoyControlStick::JoyStickDirections direction);
void setDirButtonsUpdateInitAccel(JoyControlStick::JoyStickDirections direction, bool state);
static const double PI;
// Define default values for stick properties.
static const int DEFAULTDEADZONE;
static const int DEFAULTMAXZONE;
static const int DEFAULTDIAGONALRANGE;
static const JoyMode DEFAULTMODE;
static const double DEFAULTCIRCLE;
static const unsigned int DEFAULTSTICKDELAY;
protected:
virtual void populateButtons();
void createDeskEvent(bool ignoresets = false);
void determineStandardModeEvent(JoyControlStickButton *&eventbutton1, JoyControlStickButton *&eventbutton2);
void determineEightWayModeEvent(JoyControlStickButton *&eventbutton1, JoyControlStickButton *&eventbutton2, JoyControlStickButton *&eventbutton3);
void determineFourWayCardinalEvent(JoyControlStickButton *&eventbutton1, JoyControlStickButton *&eventbutton2);
void determineFourWayDiagonalEvent(JoyControlStickButton *&eventbutton3);
JoyControlStick::JoyStickDirections determineStandardModeDirection();
JoyControlStick::JoyStickDirections determineStandardModeDirection(int axisXValue, int axisYValue);
JoyControlStick::JoyStickDirections determineEightWayModeDirection();
JoyControlStick::JoyStickDirections determineEightWayModeDirection(int axisXValue, int axisYValue);
JoyControlStick::JoyStickDirections determineFourWayCardinalDirection();
JoyControlStick::JoyStickDirections determineFourWayCardinalDirection(int axisXValue, int axisYValue);
JoyControlStick::JoyStickDirections determineFourWayDiagonalDirection();
JoyControlStick::JoyStickDirections determineFourWayDiagonalDirection(int axisXValue, int axisYValue);
JoyControlStick::JoyStickDirections calculateStickDirection();
JoyControlStick::JoyStickDirections calculateStickDirection(int axisXValue, int axisYValue);
void performButtonPress(JoyControlStickButton *eventbutton, JoyControlStickButton *&activebutton, bool ignoresets);
void performButtonRelease(JoyControlStickButton *&eventbutton, bool ignoresets);
void refreshButtons();
void deleteButtons();
void resetButtons();
double calculateXDistanceFromDeadZone(bool interpolate=false);
double calculateXDistanceFromDeadZone(int axisXValue, int axisYValue, bool interpolate=false);
double calculateYDistanceFromDeadZone(bool interpolate=false);
double calculateYDistanceFromDeadZone(int axisXValue, int axisYValue, bool interpolate=false);
int calculateCircleXValue(int axisXValue, int axisYValue);
int calculateCircleYValue(int axisXValue, int axisYValue);
double calculateEightWayDiagonalDistanceFromDeadZone();
double calculateEightWayDiagonalDistanceFromDeadZone(int axisXValue, int axisYValue);
double calculateEightWayDiagonalDistance(int axisXValue, int axisYValue);
inline double calculateXDiagonalDeadZone(int axisXValue, int axisYValue);
inline double calculateYDiagonalDeadZone(int axisXValue, int axisYValue);
QHash<JoyStickDirections, JoyControlStickButton*> getApplicableButtons();
void clearPendingAxisEvents();
JoyAxis *axisX;
JoyAxis *axisY;
int originset;
int deadZone;
int diagonalRange;
int maxZone;
bool isActive;
JoyControlStickButton *activeButton1;
JoyControlStickButton *activeButton2;
JoyControlStickButton *activeButton3;
bool safezone;
int index;
JoyStickDirections currentDirection;
JoyMode currentMode;
QString stickName;
QString defaultStickName;
double circle;
QTimer directionDelayTimer;
unsigned int stickDelay;
bool pendingStickEvent;
QHash<JoyStickDirections, JoyControlStickButton*> buttons;
JoyControlStickModifierButton *modifierButton;
signals:
void moved(int xaxis, int yaxis);
void active(int xaxis, int yaxis);
void released(int axis, int yaxis);
void deadZoneChanged(int value);
void diagonalRangeChanged(int value);
void maxZoneChanged(int value);
void circleAdjustChange(double circle);
void stickDelayChanged(int value);
void stickNameChanged();
void joyModeChanged();
void propertyUpdated();
public slots:
void reset();
void setDeadZone(int value);
void setMaxZone(int value);
void setDiagonalRange(int value);
void setStickName(QString tempName);
void setButtonsSpringRelativeStatus(bool value);
void setCircleAdjust(double circle);
void setStickDelay(int value);
void setButtonsEasingDuration(double value);
void establishPropertyUpdatedConnection();
void disconnectPropertyUpdatedConnection();
private slots:
void stickDirectionChangeEvent();
};
#endif // JOYCONTROLSTICK_H
``` | /content/code_sandbox/src/joycontrolstick.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 2,279 |
```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 <QKeySequence>
#include "qkeydisplaydialog.h"
#include "ui_qkeydisplaydialog.h"
#include "eventhandlerfactory.h"
#include "antkeymapper.h"
#ifdef Q_OS_WIN
#include "winextras.h"
#endif
#ifdef Q_OS_UNIX
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
#include <QApplication>
#endif
#ifdef WITH_X11
#include "x11extras.h"
#endif
#endif
QKeyDisplayDialog::QKeyDisplayDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::QKeyDisplayDialog)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
this->setFocus();
BaseEventHandler *handler = EventHandlerFactory::getInstance()->handler();
ui->eventHandlerLabel->setText(handler->getName());
#ifdef Q_OS_UNIX
#if defined(WITH_UINPUT)
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
/*ui->formLayout->removeWidget(ui->nativeTitleLabel);
ui->formLayout->removeWidget(ui->nativeKeyLabel);
ui->nativeTitleLabel->setVisible(false);
ui->nativeKeyLabel->setVisible(false);
*/
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
#endif
#endif
#else
/*ui->formLayout->removeWidget(ui->eventHandlerTitleLabel);
ui->formLayout->removeWidget(ui->eventHandlerLabel);
ui->eventHandlerTitleLabel->setVisible(false);
ui->eventHandlerLabel->setVisible(false);
*/
#endif
}
QKeyDisplayDialog::~QKeyDisplayDialog()
{
delete ui;
}
void QKeyDisplayDialog::keyPressEvent(QKeyEvent *event)
{
switch (event->key())
{
case Qt::Key_Escape:
case Qt::Key_Enter:
case Qt::Key_Return:
break;
default:
QDialog::keyPressEvent(event);
}
}
void QKeyDisplayDialog::keyReleaseEvent(QKeyEvent *event)
{
unsigned int scancode = event->nativeScanCode();
unsigned int virtualkey = event->nativeVirtualKey();
BaseEventHandler *handler = EventHandlerFactory::getInstance()->handler();
#ifdef Q_OS_WIN
unsigned int finalvirtual = WinExtras::correctVirtualKey(scancode, virtualkey);
unsigned int tempvirtual = finalvirtual;
#ifdef WITH_VMULTI
if (handler->getIdentifier() == "vmulti")
{
QtKeyMapperBase *nativeWinKeyMapper = AntKeyMapper::getInstance()->getNativeKeyMapper();
if (nativeWinKeyMapper)
{
unsigned int tempQtKey = nativeWinKeyMapper->returnQtKey(finalvirtual);
if (tempQtKey > 0)
{
tempvirtual = AntKeyMapper::getInstance()->returnVirtualKey(tempQtKey);
}
}
}
#endif
#else
unsigned int finalvirtual = 0;
#ifdef WITH_X11
#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 = X11Extras::getInstance()->getGroup1KeySym(virtualkey);
#ifdef WITH_UINPUT
unsigned int tempalias = 0;
QtKeyMapperBase *nativeKeyMapper = AntKeyMapper::getInstance()->getNativeKeyMapper();
if (nativeKeyMapper && nativeKeyMapper->getIdentifier() == "xtest")
{
tempalias = nativeKeyMapper->returnQtKey(virtualkey);
finalvirtual = AntKeyMapper::getInstance()->returnVirtualKey(tempalias);
}
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
else
{
finalvirtual = scancode;
}
#endif
#else
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
if (QApplication::platformName() == QStringLiteral("xcb"))
{
#endif
finalvirtual = AntKeyMapper::getInstance()->returnVirtualKey(event->key());
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
}
else
{
finalvirtual = scancode;
}
#endif
#endif
#endif
ui->nativeKeyLabel->setText(QString("0x%1").arg(finalvirtual, 0, 16));
ui->qtKeyLabel->setText(QString("0x%1").arg(event->key(), 0, 16));
#ifdef Q_OS_WIN
QString tempValue = QString("0x%1").arg(AntKeyMapper::getInstance()->returnQtKey(tempvirtual, scancode), 0, 16);
#else
QString tempValue = QString("0x%1").arg(AntKeyMapper::getInstance()->returnQtKey(finalvirtual), 0, 16);
#endif
ui->antimicroKeyLabel->setText(tempValue);
}
``` | /content/code_sandbox/src/qkeydisplaydialog.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,223 |
```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 X11EXTRAS_H
#define X11EXTRAS_H
#include <QObject>
#include <QString>
#include <QHash>
#include <QPoint>
#include <X11/Xlib.h>
class X11Extras : public QObject
{
Q_OBJECT
public:
struct ptrInformation {
long id;
int threshold;
int accelNum;
int accelDenom;
ptrInformation()
{
id = -1;
threshold = 0;
accelNum = 0;
accelDenom = 1;
}
};
~X11Extras();
unsigned long appRootWindow(int screen = -1);
Display* display();
bool hasValidDisplay();
QString getDisplayString(QString xcodestring);
int getApplicationPid(Window window);
QString getApplicationLocation(int pid);
Window findClientWindow(Window window);
Window findParentClient(Window window);
void closeDisplay();
void syncDisplay();
void syncDisplay(QString displayString);
static QString getXDisplayString();
QString getWindowTitle(Window window);
QString getWindowClass(Window window);
unsigned long getWindowInFocus();
unsigned int getGroup1KeySym(unsigned int virtualkey);
void x11ResetMouseAccelerationChange();
void x11ResetMouseAccelerationChange(QString pointerName);
struct ptrInformation getPointInformation();
struct ptrInformation getPointInformation(QString pointerName);
static void setCustomDisplay(QString displayString);
static X11Extras* getInstance();
static void deleteInstance();
static const QString mouseDeviceName;
static const QString keyboardDeviceName;
static const QString xtestMouseDeviceName;
protected:
explicit X11Extras(QObject *parent = 0);
void populateKnownAliases();
bool windowHasProperty(Display *display, Window window, Atom atom);
bool windowIsViewable(Display *display, Window window);
bool isWindowRelevant(Display *display, Window window);
Display *_display;
static X11Extras *_instance;
QHash<QString, QString> knownAliases;
static QString _customDisplayString;
signals:
public slots:
QPoint getPos();
};
#endif // X11EXTRAS_H
``` | /content/code_sandbox/src/x11extras.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 547 |
```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 EVENTHANDLERFACTORY_H
#define EVENTHANDLERFACTORY_H
#include <QObject>
#include <QStringList>
#ifdef Q_OS_UNIX
#ifdef WITH_UINPUT
#include "eventhandlers/uinputeventhandler.h"
#endif
#ifdef WITH_XTEST
#include "eventhandlers/xtesteventhandler.h"
#endif
#elif defined(Q_OS_WIN)
#include "eventhandlers/winsendinputeventhandler.h"
#ifdef WITH_VMULTI
#include "eventhandlers/winvmultieventhandler.h"
#endif
#endif
#ifdef Q_OS_WIN
#define ADD_SENDINPUT 1
#ifdef WITH_VMULTI
#define ADD_VMULTI 1
#else
#define ADD_VMULTI 0
#endif
#define NUM_BACKENDS (ADD_SENDINPUT + ADD_VMULTI)
#else
#ifdef WITH_XTEST
#define ADD_XTEST 1
#else
#define ADD_XTEST 0
#endif
#ifdef WITH_UINPUT
#define ADD_UINPUT 1
#else
#define ADD_UINPUT 0
#endif
#define NUM_BACKENDS (ADD_XTEST + ADD_UINPUT)
#endif
#if (NUM_BACKENDS > 1)
#define BACKEND_ELSE_IF else if
#else
#define BACKEND_ELSE_IF if
#endif
class EventHandlerFactory : public QObject
{
Q_OBJECT
public:
static EventHandlerFactory* getInstance(QString handler = "");
void deleteInstance();
BaseEventHandler* handler();
static QString fallBackIdentifier();
static QStringList buildEventGeneratorList();
static QString handlerDisplayName(QString handler);
protected:
explicit EventHandlerFactory(QString handler, QObject *parent = 0);
~EventHandlerFactory();
BaseEventHandler *eventHandler;
static EventHandlerFactory *instance;
signals:
public slots:
};
#endif // EVENTHANDLERFACTORY_H
``` | /content/code_sandbox/src/eventhandlerfactory.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 513 |
```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 <QList>
#include <QListIterator>
#include <QTableWidgetItem>
#include <QAbstractItemModel>
#include <QModelIndexList>
#include <QVariant>
#include <QStringList>
#include <QMessageBox>
#include <QTextStream>
#include "gamecontrollermappingdialog.h"
#include "ui_gamecontrollermappingdialog.h"
static QHash<int, QString> initAliases()
{
QHash<int, QString> temp;
temp.insert(0, "a");
temp.insert(1, "b");
temp.insert(2, "x");
temp.insert(3, "y");
temp.insert(4, "back");
temp.insert(5, "start");
temp.insert(6, "guide");
temp.insert(7, "leftshoulder");
temp.insert(8, "rightshoulder");
temp.insert(9, "leftstick");
temp.insert(10, "rightstick");
temp.insert(11, "leftx");
temp.insert(12, "lefty");
temp.insert(13, "rightx");
temp.insert(14, "righty");
temp.insert(15, "lefttrigger");
temp.insert(16, "righttrigger");
temp.insert(17, "dpup");
temp.insert(18, "dpleft");
temp.insert(19, "dpdown");
temp.insert(20, "dpright");
return temp;
}
static QHash<SDL_GameControllerButton, int> initButtonPlacement()
{
QHash<SDL_GameControllerButton, int> temp;
temp.insert(SDL_CONTROLLER_BUTTON_A, 0);
temp.insert(SDL_CONTROLLER_BUTTON_B, 1);
temp.insert(SDL_CONTROLLER_BUTTON_X, 2);
temp.insert(SDL_CONTROLLER_BUTTON_Y, 3);
temp.insert(SDL_CONTROLLER_BUTTON_BACK, 4);
temp.insert(SDL_CONTROLLER_BUTTON_START, 5);
temp.insert(SDL_CONTROLLER_BUTTON_GUIDE, 6);
temp.insert(SDL_CONTROLLER_BUTTON_LEFTSHOULDER, 7);
temp.insert(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER, 8);
temp.insert(SDL_CONTROLLER_BUTTON_LEFTSTICK, 9);
temp.insert(SDL_CONTROLLER_BUTTON_RIGHTSTICK, 10);
temp.insert(SDL_CONTROLLER_BUTTON_DPAD_UP, 17);
temp.insert(SDL_CONTROLLER_BUTTON_DPAD_LEFT, 18);
temp.insert(SDL_CONTROLLER_BUTTON_DPAD_DOWN, 19);
temp.insert(SDL_CONTROLLER_BUTTON_DPAD_RIGHT, 20);
return temp;
}
static QHash<SDL_GameControllerAxis, int> initAxisPlacement()
{
QHash<SDL_GameControllerAxis, int> temp;
temp.insert(SDL_CONTROLLER_AXIS_LEFTX, 11);
temp.insert(SDL_CONTROLLER_AXIS_LEFTY, 12);
temp.insert(SDL_CONTROLLER_AXIS_RIGHTX, 13);
temp.insert(SDL_CONTROLLER_AXIS_RIGHTY, 14);
temp.insert(SDL_CONTROLLER_AXIS_TRIGGERLEFT, 15);
temp.insert(SDL_CONTROLLER_AXIS_TRIGGERRIGHT, 16);
return temp;
}
QHash<int, QString> GameControllerMappingDialog::tempaliases = initAliases();
QHash<SDL_GameControllerButton, int> GameControllerMappingDialog::buttonPlacement = initButtonPlacement();
QHash<SDL_GameControllerAxis, int> GameControllerMappingDialog::axisPlacement = initAxisPlacement();
GameControllerMappingDialog::GameControllerMappingDialog(InputDevice *device,
AntiMicroSettings *settings,
QWidget *parent) :
QDialog(parent),
ui(new Ui::GameControllerMappingDialog),
helper(device)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
buttonGrabs = 0;
usingGameController = false;
this->device = device;
this->settings = settings;
helper.moveToThread(device->thread());
PadderCommon::lockInputDevices();
QMetaObject::invokeMethod(device, "haltServices");
QMetaObject::invokeMethod(&helper, "setupDeadZones", Qt::BlockingQueuedConnection);
GameController *controller = qobject_cast<GameController*>(device);
if (controller)
{
usingGameController = true;
populateGameControllerBindings(controller);
ui->mappingStringPlainTextEdit->document()->setPlainText(generateSDLMappingString());
}
QString tempWindowTitle = QString(tr("Game Controller Mapping (%1) (#%2)")).arg(device->getSDLName())
.arg(device->getRealJoyNumber());
setWindowTitle(tempWindowTitle);
enableDeviceConnections();
ui->buttonMappingTableWidget->setCurrentCell(0, 0);
ui->axisDeadZoneComboBox->clear();
populateAxisDeadZoneComboBox();
currentDeadZoneValue = 20000;
int index = ui->axisDeadZoneComboBox->findData(currentDeadZoneValue);
if (index != -1)
{
ui->axisDeadZoneComboBox->setCurrentIndex(index);
}
connect(device, SIGNAL(destroyed()), this, SLOT(obliterate()));
connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(saveChanges()));
connect(ui->buttonBox, SIGNAL(clicked(QAbstractButton*)), this, SLOT(discardMapping(QAbstractButton*)));
connect(ui->buttonMappingTableWidget, SIGNAL(itemSelectionChanged()), this, SLOT(changeButtonDisplay()));
connect(ui->axisDeadZoneComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeAxisDeadZone(int)));
connect(this, SIGNAL(finished(int)), this, SLOT(enableButtonEvents(int)));
PadderCommon::unlockInputDevices();
}
GameControllerMappingDialog::~GameControllerMappingDialog()
{
delete ui;
}
void GameControllerMappingDialog::buttonAssign(int buttonindex)
{
// Only perform assignment if no other control is currently active.
if (ui->buttonMappingTableWidget->currentRow() > -1)
{
QTableWidgetItem* item = ui->buttonMappingTableWidget->currentItem();
int column = ui->buttonMappingTableWidget->currentColumn();
int row = ui->buttonMappingTableWidget->currentRow();
if (!item)
{
item = new QTableWidgetItem(QString("Button %1").arg(buttonindex+1));
ui->buttonMappingTableWidget->setItem(row, column, item);
}
QList<QVariant> templist;
templist.append(QVariant(0));
templist.append(QVariant(buttonindex));
QAbstractItemModel *model = ui->buttonMappingTableWidget->model();
QModelIndexList matchlist = model->match(model->index(0,0), Qt::UserRole, templist, 1, Qt::MatchExactly);
foreach (const QModelIndex &index, matchlist) {
QTableWidgetItem *existingItem = ui->buttonMappingTableWidget->item(index.row(), index.column());
if (existingItem)
{
existingItem->setText("");
existingItem->setData(Qt::UserRole, QVariant());
}
}
QList<QVariant> tempvalue;
tempvalue.append(QVariant(0));
tempvalue.append(QVariant(buttonindex));
item->setData(Qt::UserRole, tempvalue);
item->setText(QString("Button %1").arg(buttonindex+1));
if (row < ui->buttonMappingTableWidget->rowCount()-1)
{
ui->buttonMappingTableWidget->setCurrentCell(row+1, column);
}
ui->mappingStringPlainTextEdit->document()->setPlainText(generateSDLMappingString());
}
}
void GameControllerMappingDialog::axisAssign(int axis, int value)
{
bool skip = false;
bool change = true;
if (usingGameController)
{
if (eventTriggerAxes.contains(axis) && value < -currentDeadZoneValue)
{
skip = true;
eventTriggerAxes.removeAll(axis);
}
}
if (!skip && ui->buttonMappingTableWidget->currentRow() > -1)
{
QTableWidgetItem* item = ui->buttonMappingTableWidget->currentItem();
int column = ui->buttonMappingTableWidget->currentColumn();
int row = ui->buttonMappingTableWidget->currentRow();
if (row < 17)
{
if (usingGameController)
{
bool considerTrigger = (row == 15 || row == 16);
if (considerTrigger && value > currentDeadZoneValue && !eventTriggerAxes.contains(axis))
{
eventTriggerAxes.append(axis);
}
else if (considerTrigger && value < currentDeadZoneValue)
{
skip = true;
}
}
if (!skip)
{
if (!item)
{
item = new QTableWidgetItem(QString("Axis %1").arg(axis+1));
ui->buttonMappingTableWidget->setItem(row, column, item);
}
QList<QVariant> templist;
templist.append(QVariant(axis+1));
templist.append(QVariant(0));
QAbstractItemModel *model = ui->buttonMappingTableWidget->model();
QModelIndexList matchlist = model->match(model->index(0,0), Qt::UserRole, templist, 1, Qt::MatchExactly);
foreach (const QModelIndex &index, matchlist) {
QTableWidgetItem *existingItem = ui->buttonMappingTableWidget->item(index.row(), index.column());
if (existingItem)
{
existingItem->setText("");
existingItem->setData(Qt::UserRole, QVariant());
}
}
QList<QVariant> tempvalue;
tempvalue.append(QVariant(axis+1));
tempvalue.append(QVariant(0));
item->setData(Qt::UserRole, tempvalue);
item->setText(QString("Axis %1").arg(axis+1));
if (row < ui->buttonMappingTableWidget->rowCount()-1)
{
ui->buttonMappingTableWidget->setCurrentCell(row+1, column);
}
ui->mappingStringPlainTextEdit->document()->setPlainText(generateSDLMappingString());
}
}
else
{
change = false;
skip = true;
}
}
}
void GameControllerMappingDialog::dpadAssign(int dpad, int buttonindex)
{
if (ui->buttonMappingTableWidget->currentRow() > -1)
{
if (buttonindex == 1 || buttonindex == 2 ||
buttonindex == 4 || buttonindex == 8)
{
QTableWidgetItem* item = ui->buttonMappingTableWidget->currentItem();
int column = ui->buttonMappingTableWidget->currentColumn();
int row = ui->buttonMappingTableWidget->currentRow();
if (row <= 10 || row >= 17)
{
if (!item)
{
item = new QTableWidgetItem(QString("Hat %1.%2").arg(dpad+1).arg(buttonindex));
ui->buttonMappingTableWidget->setItem(row, column, item);
}
QList<QVariant> templist;
templist.append(QVariant(-dpad-1));
templist.append(QVariant(buttonindex));
QAbstractItemModel *model = ui->buttonMappingTableWidget->model();
QModelIndexList matchlist = model->match(model->index(0,0), Qt::UserRole, templist, 1, Qt::MatchExactly);
foreach (const QModelIndex &index, matchlist) {
QTableWidgetItem *existingItem = ui->buttonMappingTableWidget->item(index.row(), index.column());
if (existingItem)
{
existingItem->setText("");
existingItem->setData(Qt::UserRole, QVariant());
}
}
QList<QVariant> tempvalue;
tempvalue.append(QVariant(-dpad-1));
tempvalue.append(QVariant(buttonindex));
item->setData(Qt::UserRole, tempvalue);
item->setText(QString("Hat %1.%2").arg(dpad+1).arg(buttonindex));
}
if (row < ui->buttonMappingTableWidget->rowCount()-1)
{
ui->buttonMappingTableWidget->setCurrentCell(row+1, column);
}
ui->mappingStringPlainTextEdit->document()->setPlainText(generateSDLMappingString());
}
}
}
void GameControllerMappingDialog::saveChanges()
{
QString mappingString = generateSDLMappingString();
settings->getLock()->lock();
settings->setValue(QString("Mappings/").append(device->getGUIDString()), mappingString);
settings->setValue(QString("Mappings/%1%2").arg(device->getGUIDString()).arg("Disable"), "0");
settings->sync();
bool displayMapping = settings->runtimeValue("DisplaySDLMapping", false).toBool();
settings->getLock()->unlock();
if (displayMapping)
{
QTextStream out(stdout);
out << generateSDLMappingString();
}
emit mappingUpdate(mappingString, device);
}
void GameControllerMappingDialog::populateGameControllerBindings(GameController *controller)
{
if (controller)
{
for (int i = 0; i < controller->getNumberButtons(); i++)
{
int associatedRow = buttonPlacement.value((SDL_GameControllerButton)i);
SDL_GameControllerButtonBind bind = controller->getBindForButton(i);
QString temptext = bindingString(bind);
if (!temptext.isEmpty())
{
QList<QVariant> tempvariant = bindingValues(bind);
QTableWidgetItem* item = new QTableWidgetItem();
ui->buttonMappingTableWidget->setItem(associatedRow, 0, item);
item->setText(temptext);
item->setData(Qt::UserRole, tempvariant);
}
}
for (int i = 0; i < controller->getNumberAxes(); i++)
{
int associatedRow = axisPlacement.value((SDL_GameControllerAxis)i);
SDL_GameControllerButtonBind bind = controller->getBindForAxis(i);
QString temptext = bindingString(bind);
if (!temptext.isEmpty())
{
QList<QVariant> tempvariant = bindingValues(bind);
QTableWidgetItem* item = new QTableWidgetItem();
ui->buttonMappingTableWidget->setItem(associatedRow, 0, item);
item->setText(temptext);
item->setData(Qt::UserRole, tempvariant);
}
}
}
}
QString GameControllerMappingDialog::bindingString(SDL_GameControllerButtonBind bind)
{
QString temp;
if (bind.bindType != SDL_CONTROLLER_BINDTYPE_NONE)
{
if (bind.bindType == SDL_CONTROLLER_BINDTYPE_BUTTON)
{
temp.append(QString("Button %1").arg(bind.value.button+1));
}
else if (bind.bindType == SDL_CONTROLLER_BINDTYPE_AXIS)
{
temp.append(QString("Axis %1").arg(bind.value.axis+1));
}
else if (bind.bindType == SDL_CONTROLLER_BINDTYPE_HAT)
{
temp.append(QString("Hat %1.%2").arg(bind.value.hat.hat+1)
.arg(bind.value.hat.hat_mask));
}
}
return temp;
}
QList<QVariant> GameControllerMappingDialog::bindingValues(SDL_GameControllerButtonBind bind)
{
QList<QVariant> temp;
if (bind.bindType != SDL_CONTROLLER_BINDTYPE_NONE)
{
if (bind.bindType == SDL_CONTROLLER_BINDTYPE_BUTTON)
{
temp.append(QVariant(0));
temp.append(QVariant(bind.value.button));
}
else if (bind.bindType == SDL_CONTROLLER_BINDTYPE_AXIS)
{
temp.append(QVariant(bind.value.axis+1));
temp.append(QVariant(0));
}
else if (bind.bindType == SDL_CONTROLLER_BINDTYPE_HAT)
{
temp.append(QVariant(-bind.value.hat.hat-1));
temp.append(QVariant(bind.value.hat.hat_mask));
}
}
return temp;
}
void GameControllerMappingDialog::discardMapping(QAbstractButton *button)
{
disableDeviceConnections();
QDialogButtonBox::ButtonRole currentRole = ui->buttonBox->buttonRole(button);
if (currentRole == QDialogButtonBox::DestructiveRole)
{
QMessageBox msgBox;
msgBox.setWindowTitle(tr("Discard Controller Mapping?"));
msgBox.setText(tr("Discard mapping for this controller?\n\nIf discarded, the controller will be reverted to a joystick once you refresh all joysticks."));
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
int status = msgBox.exec();
if (status == QMessageBox::Yes)
{
removeControllerMapping();
close();
}
else
{
enableDeviceConnections();
}
}
}
void GameControllerMappingDialog::removeControllerMapping()
{
settings->getLock()->lock();
settings->beginGroup("Mappings");
settings->remove(device->getGUIDString());
settings->remove(QString("%1Disable").arg(device->getGUIDString()));
settings->endGroup();
settings->sync();
settings->getLock()->unlock();
}
void GameControllerMappingDialog::enableDeviceConnections()
{
connect(device, SIGNAL(rawButtonClick(int)), this, SLOT(buttonAssign(int)));
connect(device, SIGNAL(rawButtonRelease(int)), this, SLOT(buttonRelease(int)));
connect(device, SIGNAL(rawAxisMoved(int,int)), this, SLOT(updateLastAxisLineEditRaw(int,int)));
connect(device, SIGNAL(rawAxisActivated(int,int)), this, SLOT(axisAssign(int,int)));
connect(device, SIGNAL(rawAxisReleased(int,int)), this, SLOT(axisRelease(int,int)));
connect(device, SIGNAL(rawDPadButtonClick(int,int)), this, SLOT(dpadAssign(int,int)));
connect(device, SIGNAL(rawDPadButtonRelease(int,int)), this, SLOT(dpadRelease(int,int)));
}
void GameControllerMappingDialog::disableDeviceConnections()
{
disconnect(device, SIGNAL(rawButtonClick(int)), this, 0);
disconnect(device, SIGNAL(rawButtonRelease(int)), this, 0);
disconnect(device, SIGNAL(rawAxisMoved(int,int)), this, 0);
disconnect(device, SIGNAL(rawAxisActivated(int,int)), this, 0);
disconnect(device, SIGNAL(rawAxisReleased(int,int)), this, 0);
disconnect(device, SIGNAL(rawDPadButtonClick(int,int)), this, 0);
disconnect(device, SIGNAL(rawDPadButtonRelease(int,int)), this, 0);
}
void GameControllerMappingDialog::enableButtonEvents(int code)
{
Q_UNUSED(code);
QMetaObject::invokeMethod(&helper, "restoreDeviceDeadZones", Qt::BlockingQueuedConnection);
}
QString GameControllerMappingDialog::generateSDLMappingString()
{
QStringList templist;
templist.append(device->getGUIDString());
templist.append(device->getSDLName());
templist.append(QString("platform:").append(device->getSDLPlatform()));
for (int i=0; i < ui->buttonMappingTableWidget->rowCount(); i++)
{
QTableWidgetItem *item = ui->buttonMappingTableWidget->item(i, 0);
if (item)
{
QString mapNative;
QList<QVariant> tempassociation = item->data(Qt::UserRole).toList();
if (tempassociation.size() == 2)
{
int bindingType = tempassociation.value(0).toInt();
if (bindingType == 0)
{
mapNative.append("b");
mapNative.append(QString::number(tempassociation.value(1).toInt()));
}
else if (bindingType > 0)
{
mapNative.append("a");
mapNative.append(QString::number(tempassociation.value(0).toInt()-1));
}
else if (bindingType < 0)
{
mapNative.append("h");
mapNative.append(QString::number(tempassociation.value(0).toInt()+1));
mapNative.append(".").append(QString::number(tempassociation.value(1).toInt()));
}
}
if (!mapNative.isEmpty())
{
QString sdlButtonName = tempaliases.value(i);
QString temp = QString("%1:%2").arg(sdlButtonName).arg(mapNative);
templist.append(temp);
}
}
}
return templist.join(",").append(",");
}
void GameControllerMappingDialog::obliterate()
{
this->done(QDialogButtonBox::DestructiveRole);
}
void GameControllerMappingDialog::changeButtonDisplay()
{
ui->gameControllerDisplayWidget->setActiveButton(ui->buttonMappingTableWidget->currentRow());
}
/**
* @brief TODO: Possibly remove. This was used for decrementing a reference
* count.
* @param axis
* @param value
*/
void GameControllerMappingDialog::axisRelease(int axis, int value)
{
Q_UNUSED(axis);
Q_UNUSED(value);
}
/**
* @brief TODO: Possibly remove. This was used for decrementing a reference
* count.
* @param buttonindex
*/
void GameControllerMappingDialog::buttonRelease(int buttonindex)
{
Q_UNUSED(buttonindex);
}
/**
* @brief TODO: Possibly remove. This was used for decrementing a reference
* count.
* @param dpad
* @param buttonindex
*/
void GameControllerMappingDialog::dpadRelease(int dpad, int buttonindex)
{
Q_UNUSED(dpad);
Q_UNUSED(buttonindex);
}
void GameControllerMappingDialog::populateAxisDeadZoneComboBox()
{
for (int i=0; i < 28; i++)
{
unsigned int temp = (i * 1000) + 5000;
ui->axisDeadZoneComboBox->addItem(QString::number(temp), temp);
}
}
void GameControllerMappingDialog::changeAxisDeadZone(int index)
{
unsigned int value = ui->axisDeadZoneComboBox->itemData(index).toInt();
if (value >= 5000 && value <= 32000)
{
QMetaObject::invokeMethod(&helper, "raiseDeadZones", Qt::BlockingQueuedConnection,
Q_ARG(int, value));
currentDeadZoneValue = value;
}
}
void GameControllerMappingDialog::updateLastAxisLineEdit(int value)
{
if (abs(value) >= 5000)
{
JoyAxis *tempAxis = static_cast<JoyAxis*>(sender());
QString temp;
if (device->isGameController())
{
GameController *controller = static_cast<GameController*>(device);
temp = QString("%1: %2").arg(controller->getBindStringForAxis(tempAxis->getIndex(), false))
.arg(value);
}
else
{
temp = QString("Axis %1: %2").arg(tempAxis->getRealJoyIndex())
.arg(value);
}
ui->lastAxisEventLineEdit->setText(temp);
}
}
void GameControllerMappingDialog::updateLastAxisLineEditRaw(int index, int value)
{
if (abs(value) >= 5000)
{
QString temp;
temp = QString("Axis %1: %2").arg(index)
.arg(value);
ui->lastAxisEventLineEdit->setText(temp);
}
}
``` | /content/code_sandbox/src/gamecontrollermappingdialog.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 4,847 |
```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 JOYBUTTONSLOT_H
#define JOYBUTTONSLOT_H
#include <QObject>
#include <QElapsedTimer>
#include <QTime>
#include <QMetaType>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QVariant>
class JoyButtonSlot : public QObject
{
Q_OBJECT
public:
enum JoySlotInputAction {JoyKeyboard=0, JoyMouseButton, JoyMouseMovement,
JoyPause, JoyHold, JoyCycle, JoyDistance,
JoyRelease, JoyMouseSpeedMod, JoyKeyPress, JoyDelay,
JoyLoadProfile, JoySetChange, JoyTextEntry, JoyExecute};
enum JoySlotMouseDirection {MouseUp=1, MouseDown, MouseLeft, MouseRight};
enum JoySlotMouseWheelButton {MouseWheelUp=4, MouseWheelDown=5,
MouseWheelLeft=6, MouseWheelRight=7};
enum JoySlotMouseButton {MouseLB=1, MouseMB, MouseRB};
explicit JoyButtonSlot(QObject *parent = 0);
explicit JoyButtonSlot(int code, JoySlotInputAction mode, QObject *parent=0);
explicit JoyButtonSlot(int code, unsigned int alias, JoySlotInputAction mode, QObject *parent=0);
explicit JoyButtonSlot(JoyButtonSlot *slot, QObject *parent=0);
explicit JoyButtonSlot(QString text, JoySlotInputAction mode, QObject *parent=0);
void setSlotCode(int code);
int getSlotCode();
void setSlotMode(JoySlotInputAction selectedMode);
JoySlotInputAction getSlotMode();
QString movementString();
void setMouseSpeed(int value);
void setDistance(double distance);
double getMouseDistance();
QElapsedTimer* getMouseInterval();
void restartMouseInterval();
QString getXmlName();
QString getSlotString();
void setSlotCode(int code, unsigned int alias);
unsigned int getSlotCodeAlias();
void setPreviousDistance(double distance);
double getPreviousDistance();
bool isModifierKey();
bool isEasingActive();
void setEasingStatus(bool isActive);
QTime* getEasingTime();
void setTextData(QString textData);
QString getTextData();
void setExtraData(QVariant data);
QVariant getExtraData();
bool isValidSlot();
virtual void readConfig(QXmlStreamReader *xml);
virtual void writeConfig(QXmlStreamWriter *xml);
static const int JOYSPEED;
static const QString xmlName;
protected:
int deviceCode;
unsigned int qkeyaliasCode;
JoySlotInputAction mode;
double distance;
double previousDistance;
QElapsedTimer mouseInterval;
QTime easingTime;
bool easingActive;
QString textData;
QVariant extraData;
static const int MAXTEXTENTRYDISPLAYLENGTH;
signals:
public slots:
};
Q_DECLARE_METATYPE(JoyButtonSlot*)
Q_DECLARE_METATYPE(JoyButtonSlot::JoySlotInputAction)
#endif // JOYBUTTONSLOT_H
``` | /content/code_sandbox/src/joybuttonslot.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 727 |
```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 JOYAXIS_H
#define JOYAXIS_H
#include <QObject>
#include <QTimer>
#include <QTime>
#include <QList>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include "joybuttontypes/joyaxisbutton.h"
class JoyControlStick;
class JoyAxis : public QObject
{
Q_OBJECT
public:
explicit JoyAxis(int index, int originset, SetJoystick *parentSet, QObject *parent=0);
~JoyAxis();
enum ThrottleTypes {
NegativeHalfThrottle = -2,
NegativeThrottle = -1,
NormalThrottle = 0,
PositiveThrottle = 1,
PositiveHalfThrottle = 2
};
void joyEvent(int value, bool ignoresets=false, bool updateLastValues=true);
void queuePendingEvent(int value, bool ignoresets=false, bool updateLastValues=true);
void activatePendingEvent();
bool hasPendingEvent();
void clearPendingEvent();
bool inDeadZone(int value);
virtual QString getName(bool forceFullFormat=false, bool displayNames=false);
virtual QString getPartialName(bool forceFullFormat=false, bool displayNames=false);
virtual QString getXmlName();
void setIndex(int index);
int getIndex();
int getRealJoyIndex();
JoyAxisButton *getPAxisButton();
JoyAxisButton *getNAxisButton();
int getDeadZone();
int getMaxZoneValue();
void setThrottle(int value);
void setInitialThrottle(int value);
int getThrottle();
int getCurrentThrottledValue();
int getCurrentRawValue();
//int getCurrentThrottledMin();
//int getCurrentThrottledMax();
int getCurrentThrottledDeadValue();
int getCurrentlyAssignedSet();
JoyAxisButton* getAxisButtonByValue(int value);
double getDistanceFromDeadZone();
double getDistanceFromDeadZone(int value);
double getRawDistance(int value);
virtual void readConfig(QXmlStreamReader *xml);
virtual void writeConfig(QXmlStreamWriter *xml);
void setControlStick(JoyControlStick *stick);
void removeControlStick(bool performRelease = true);
bool isPartControlStick();
JoyControlStick* getControlStick();
bool hasControlOfButtons();
void removeVDPads();
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);
double getButtonsEasingDuration();
virtual QString getAxisName();
virtual int getDefaultDeadZone();
virtual int getDefaultMaxZone();
virtual ThrottleTypes getDefaultThrottle();
virtual void setDefaultAxisName(QString tempname);
virtual QString getDefaultAxisName();
SetJoystick* getParentSet();
virtual bool isDefault();
bool isRelativeSpring();
void copyAssignments(JoyAxis *destAxis);
int getLastKnownThrottleValue();
int getLastKnownRawValue();
int getProperReleaseValue();
// Don't use direct assignment but copying from a current axis.
void copyRawValues(JoyAxis *srcAxis);
void copyThrottledValues(JoyAxis *srcAxis);
void setExtraAccelerationCurve(JoyButton::JoyExtraAccelerationCurve curve);
JoyButton::JoyExtraAccelerationCurve getExtraAccelerationCurve();
virtual void eventReset();
// Define default values for many properties.
static const int AXISMIN;
static const int AXISMAX;
static const int AXISDEADZONE;
static const int AXISMAXZONE;
static const ThrottleTypes DEFAULTTHROTTLE;
static const float JOYSPEED;
static const QString xmlName;
protected:
void createDeskEvent(bool ignoresets = false);
void adjustRange();
int calculateThrottledValue(int value);
void setCurrentRawValue(int value);
void performCalibration(int value);
void stickPassEvent(int value, bool ignoresets=false, bool updateLastValues=true);
virtual bool readMainConfig(QXmlStreamReader *xml);
virtual bool readButtonConfig(QXmlStreamReader *xml);
int index;
int deadZone;
int maxZoneValue;
bool isActive;
JoyAxisButton *paxisbutton;
JoyAxisButton *naxisbutton;
bool eventActive;
int currentThrottledValue;
int currentRawValue;
int throttle;
JoyAxisButton *activeButton;
int originset;
int currentThrottledDeadValue;
JoyControlStick *stick;
QString axisName;
QString defaultAxisName;
SetJoystick *parentSet;
int lastKnownThottledValue;
int lastKnownRawValue;
int pendingValue;
bool pendingEvent;
bool pendingIgnoreSets;
// TODO: CHECK IF PROPERTY IS NEEDED.
//bool pendingUpdateLastValues;
signals:
void active(int value);
void released(int value);
void moved(int value);
void throttleChangePropogated(int index);
void throttleChanged();
void axisNameChanged();
void propertyUpdated();
public slots:
virtual void reset();
virtual void reset(int index);
void propogateThrottleChange();
void setDeadZone(int value);
void setMaxZoneValue(int value);
void setAxisName(QString tempName);
void setButtonsSpringRelativeStatus(bool value);
void setButtonsEasingDuration(double value);
void establishPropertyUpdatedConnection();
void disconnectPropertyUpdatedConnection();
};
#endif // JOYAXIS_H
``` | /content/code_sandbox/src/joyaxis.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,378 |
```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 ANTIMICROSETTINGS_H
#define ANTIMICROSETTINGS_H
#include <QSettings>
#include <QMutex>
#include "commandlineutility.h"
class AntiMicroSettings : public QSettings
{
Q_OBJECT
public:
explicit AntiMicroSettings(const QString &fileName, Format format, QObject *parent = 0);
QVariant runtimeValue(const QString &key, const QVariant &defaultValue = QVariant()) const;
void importFromCommandLine(CommandLineUtility &cmdutility);
QMutex* getLock();
static const bool defaultDisabledWinEnhanced;
static const bool defaultAssociateProfiles;
static const int defaultSpringScreen;
static const unsigned int defaultSDLGamepadPollRate;
protected:
QSettings cmdSettings;
QMutex lock;
signals:
public slots:
};
#endif // ANTIMICROSETTINGS_H
``` | /content/code_sandbox/src/antimicrosettings.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 268 |
```objective-c
#ifndef WINEXTRAS_H
#define WINEXTRAS_H
#include <QObject>
#include <QString>
#include <QHash>
#include <QPoint>
class WinExtras : public QObject
{
Q_OBJECT
public:
static QString getDisplayString(unsigned int virtualkey);
static unsigned int getVirtualKey(QString codestring);
static unsigned int correctVirtualKey(unsigned int scancode,
unsigned int virtualkey);
static unsigned int scancodeFromVirtualKey(unsigned int virtualkey, unsigned int alias=0);
static const unsigned int EXTENDED_FLAG;
static QString getForegroundWindowExePath();
static bool containsFileAssociationinRegistry();
static void writeFileAssocationToRegistry();
static void removeFileAssociationFromRegistry();
static bool IsRunningAsAdmin();
static bool elevateAntiMicro();
static void disablePointerPrecision();
static void enablePointerPrecision();
static bool isUsingEnhancedPointerPrecision();
static void grabCurrentPointerPrecision();
static QString getCurrentWindowText();
static bool raiseProcessPriority();
static QPoint getCursorPos();
protected:
explicit WinExtras(QObject *parent = 0);
void populateKnownAliases();
static WinExtras _instance;
QHash<QString, unsigned int> knownAliasesX11SymVK;
QHash<unsigned int, QString> knownAliasesVKStrings;
static int originalMouseAccel;
signals:
public slots:
};
#endif // WINEXTRAS_H
``` | /content/code_sandbox/src/winextras.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 296 |
```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 "joytabwidgetcontainer.h"
JoyTabWidgetContainer::JoyTabWidgetContainer(QWidget *parent) :
QTabWidget(parent)
{
}
int JoyTabWidgetContainer::addTab(QWidget *widget, const QString &string)
{
return QTabWidget::addTab(widget, string);
}
int JoyTabWidgetContainer::addTab(JoyTabWidget *widget, const QString &string)
{
InputDevice *joystick = widget->getJoystick();
if (joystick)
{
enableFlashes(joystick);
connect(widget, SIGNAL(forceTabUnflash(JoyTabWidget*)), this, SLOT(unflashTab(JoyTabWidget*)));
}
return QTabWidget::addTab(widget, string);
}
void JoyTabWidgetContainer::flash()
{
InputDevice *joystick = static_cast<InputDevice*>(sender());
bool found = false;
for (int i = 0; i < tabBar()->count() && !found; i++)
{
JoyTabWidget *tab = static_cast<JoyTabWidget*>(widget(i));
if (tab && tab->getJoystick() == joystick)
{
tabBar()->setTabTextColor(i, Qt::red);
found = true;
}
}
}
void JoyTabWidgetContainer::unflash()
{
InputDevice *joystick = static_cast<InputDevice*>(sender());
bool found = false;
for (int i = 0; i < tabBar()->count() && !found; i++)
{
JoyTabWidget *tab = static_cast<JoyTabWidget*>(widget(i));
if (tab && tab->getJoystick() == joystick)
{
tabBar()->setTabTextColor(i, Qt::black);
found = true;
}
}
}
void JoyTabWidgetContainer::unflashTab(JoyTabWidget *tabWidget)
{
bool found = false;
for (int i=0; i < tabBar()->count() && !found; i++)
{
JoyTabWidget *tab = static_cast<JoyTabWidget*>(widget(i));
if (tab == tabWidget)
{
tabBar()->setTabTextColor(i, Qt::black);
}
}
}
void JoyTabWidgetContainer::unflashAll()
{
for (int i = 0; i < tabBar()->count(); i++)
{
JoyTabWidget *tab = static_cast<JoyTabWidget*>(widget(i));
if (tab)
{
tabBar()->setTabTextColor(i, Qt::black);
}
}
}
void JoyTabWidgetContainer::disableFlashes(InputDevice *joystick)
{
unflashAll();
disconnect(joystick, SIGNAL(clicked(int)), this, SLOT(flash()));
disconnect(joystick, SIGNAL(released(int)), this, SLOT(unflash()));
}
void JoyTabWidgetContainer::enableFlashes(InputDevice *joystick)
{
connect(joystick, SIGNAL(clicked(int)), this, SLOT(flash()), Qt::QueuedConnection);
connect(joystick, SIGNAL(released(int)), this, SLOT(unflash()), Qt::QueuedConnection);
}
``` | /content/code_sandbox/src/joytabwidgetcontainer.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 737 |
```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 <QListWidgetItem>
#include "slotitemlistwidget.h"
#include "simplekeygrabberbutton.h"
SlotItemListWidget::SlotItemListWidget(QWidget *parent) :
QListWidget(parent)
{
}
void SlotItemListWidget::keyPressEvent(QKeyEvent *event)
{
bool propogate = true;
QListWidgetItem *currentItem = this->item(this->currentRow());
SimpleKeyGrabberButton *tempbutton = 0;
if (currentItem)
{
tempbutton = currentItem->data(Qt::UserRole).value<SimpleKeyGrabberButton*>();
}
if (tempbutton && tempbutton->isGrabbing())
{
switch (event->key())
{
case Qt::Key_Home:
case Qt::Key_End:
{
propogate = false;
break;
}
}
}
if (propogate)
{
QListWidget::keyPressEvent(event);
}
}
``` | /content/code_sandbox/src/slotitemlistwidget.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 294 |
```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 <QListIterator>
#include <QStringListIterator>
#include <QSetIterator>
#include <QFile>
#include <QFileInfo>
#include <QDir>
#include <QApplication>
#include "autoprofilewatcher.h"
#if defined(Q_OS_UNIX) && defined(WITH_X11)
#include "x11extras.h"
#elif defined(Q_OS_WIN)
#include "winextras.h"
#endif
AutoProfileWatcher::AutoProfileWatcher(AntiMicroSettings *settings, QObject *parent) :
QObject(parent)
{
this->settings = settings;
allDefaultInfo = 0;
currentApplication = "";
syncProfileAssignment();
connect(&appTimer, SIGNAL(timeout()), this, SLOT(runAppCheck()));
}
void AutoProfileWatcher::startTimer()
{
appTimer.start(CHECKTIME);
}
void AutoProfileWatcher::stopTimer()
{
appTimer.stop();
}
void AutoProfileWatcher::runAppCheck()
{
//qDebug() << qApp->applicationFilePath();
QString appLocation;
QString baseAppFileName;
guidSet.clear();
// Check whether program path needs to be parsed. Removes processing time
// and need to run Linux specific code searching /proc.
#ifdef Q_OS_LINUX
if (!appProfileAssignments.isEmpty())
{
appLocation = findAppLocation();
}
#else
// In Windows, get program location no matter what.
appLocation = findAppLocation();
if (!appLocation.isEmpty())
{
baseAppFileName = QFileInfo(appLocation).fileName();
}
#endif
// More portable check for whether antimicro is the current application
// with focus.
QWidget *focusedWidget = qApp->activeWindow();
QString nowWindow;
QString nowWindowClass;
QString nowWindowName;
#ifdef Q_OS_WIN
nowWindowName = WinExtras::getCurrentWindowText();
#else
unsigned long currentWindow = X11Extras::getInstance()->getWindowInFocus();
if (currentWindow > 0)
{
unsigned long tempWindow = X11Extras::getInstance()->findParentClient(currentWindow);
if (tempWindow > 0)
{
currentWindow = tempWindow;
}
nowWindow = QString::number(currentWindow);
nowWindowClass = X11Extras::getInstance()->getWindowClass(currentWindow);
nowWindowName = X11Extras::getInstance()->getWindowTitle(currentWindow);
//qDebug() << nowWindowClass;
//qDebug() << nowWindowName;
}
#endif
bool checkForTitleChange = windowNameProfileAssignments.size() > 0;
#ifdef Q_OS_WIN
if (!focusedWidget && ((!appLocation.isEmpty() && appLocation != currentApplication) ||
(checkForTitleChange && nowWindowName != currentAppWindowTitle)))
#else
if (!focusedWidget && ((!nowWindow.isEmpty() && nowWindow != currentApplication) ||
(checkForTitleChange && nowWindowName != currentAppWindowTitle)))
#endif
{
#ifdef Q_OS_WIN
currentApplication = appLocation;
#else
currentApplication = nowWindow;
#endif
currentAppWindowTitle = nowWindowName;
//currentApplication = appLocation;
Logger::LogDebug(QObject::tr("Active window changed to: Title = \"%1\", "
"Class = \"%2\", Program = \"%3\" or \"%4\".").
arg(nowWindowName, nowWindowClass, appLocation, baseAppFileName));
QSet<AutoProfileInfo*> fullSet;
if (!appLocation.isEmpty() && appProfileAssignments.contains(appLocation))
{
QSet<AutoProfileInfo*> tempSet;
tempSet = appProfileAssignments.value(appLocation).toSet();
fullSet.unite(tempSet);
}
else if (!baseAppFileName.isEmpty() && appProfileAssignments.contains(baseAppFileName))
{
QSet<AutoProfileInfo*> tempSet;
tempSet = appProfileAssignments.value(baseAppFileName).toSet();
fullSet.unite(tempSet);
}
if (!nowWindowClass.isEmpty() && windowClassProfileAssignments.contains(nowWindowClass))
{
QSet<AutoProfileInfo*> tempSet;
tempSet = windowClassProfileAssignments.value(nowWindowClass).toSet();
fullSet.unite(tempSet);
}
if (!nowWindowName.isEmpty() && windowNameProfileAssignments.contains(nowWindowName))
{
QSet<AutoProfileInfo*> tempSet;
tempSet = windowNameProfileAssignments.value(nowWindowName).toSet();
fullSet = fullSet.unite(tempSet);
}
QHash<QString, int> highestMatchCount;
QHash<QString, AutoProfileInfo*> highestMatches;
QSetIterator<AutoProfileInfo*> fullSetIter(fullSet);
while (fullSetIter.hasNext())
{
AutoProfileInfo *info = fullSetIter.next();
if (info->isActive())
{
int numProps = 0;
numProps += !info->getExe().isEmpty() ? 1 : 0;
numProps += !info->getWindowClass().isEmpty() ? 1 : 0;
numProps += !info->getWindowName().isEmpty() ? 1 : 0;
int numMatched = 0;
numMatched += (!info->getExe().isEmpty() &&
(info->getExe() == appLocation ||
info->getExe() == baseAppFileName)) ? 1 : 0;
numMatched += (!info->getWindowClass().isEmpty() &&
info->getWindowClass() == nowWindowClass) ? 1 : 0;
numMatched += (!info->getWindowName().isEmpty() &&
info->getWindowName() == nowWindowName) ? 1 : 0;
if (numProps == numMatched)
{
if (highestMatchCount.contains(info->getGUID()))
{
int currentHigh = highestMatchCount.value(info->getGUID());
if (numMatched > currentHigh)
{
highestMatchCount.insert(info->getGUID(), numMatched);
highestMatches.insert(info->getGUID(), info);
}
}
else
{
highestMatchCount.insert(info->getGUID(), numMatched);
highestMatches.insert(info->getGUID(), info);
}
}
}
}
QHashIterator<QString, AutoProfileInfo*> highIter(highestMatches);
while (highIter.hasNext())
{
AutoProfileInfo *info = highIter.next().value();
guidSet.insert(info->getGUID());
emit foundApplicableProfile(info);
}
if ((!defaultProfileAssignments.isEmpty() || allDefaultInfo) && !focusedWidget)
//antiProgramLocation != appLocation)
{
if (allDefaultInfo)
{
if (allDefaultInfo->isActive() && !guidSet.contains("all"))
{
emit foundApplicableProfile(allDefaultInfo);
}
}
QHashIterator<QString, AutoProfileInfo*> iter(defaultProfileAssignments);
while (iter.hasNext())
{
iter.next();
AutoProfileInfo *info = iter.value();
if (info->isActive() && !guidSet.contains(info->getGUID()))
{
emit foundApplicableProfile(info);
}
}
}
}
}
void AutoProfileWatcher::syncProfileAssignment()
{
clearProfileAssignments();
currentApplication = "";
//QStringList assignments = settings->allKeys();
//QStringListIterator iter(assignments);
settings->getLock()->lock();
settings->beginGroup("DefaultAutoProfiles");
QString exe;
QString guid;
QString profile;
QString active;
QString windowClass;
QString windowName;
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();
// Handle overall Default profile assignment
bool defaultActive = allActive == "1" ? true : false;
if (defaultActive)
{
allDefaultInfo = new AutoProfileInfo("all", allProfile, defaultActive, this);
allDefaultInfo->setDefaultState(true);
}
// Handle device specific Default profile assignments
QStringListIterator iter(registeredGUIDs);
while (iter.hasNext())
{
QString tempkey = iter.next();
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), "").toString();
if (!guid.isEmpty() && !profile.isEmpty())
{
bool profileActive = active == "1" ? true : false;
if (profileActive && guid != "all")
{
AutoProfileInfo *info = new AutoProfileInfo(guid, profile, profileActive, this);
info->setDefaultState(true);
defaultProfileAssignments.insert(guid, info);
}
}
}
settings->beginGroup("AutoProfiles");
bool quitSearch = false;
//QHash<QString, QList<QString> > tempAssociation;
for (int i = 1; !quitSearch; i++)
{
exe = settings->value(QString("AutoProfile%1Exe").arg(i), "").toString();
exe = QDir::toNativeSeparators(exe);
guid = settings->value(QString("AutoProfile%1GUID").arg(i), "").toString();
profile = settings->value(QString("AutoProfile%1Profile").arg(i), "").toString();
active = settings->value(QString("AutoProfile%1Active").arg(i), 0).toString();
windowName = settings->value(QString("AutoProfile%1WindowName").arg(i), "").toString();
#ifdef Q_OS_UNIX
windowClass = settings->value(QString("AutoProfile%1WindowClass").arg(i), "").toString();
#else
windowClass.clear();
#endif
// 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;
if (profileActive)
{
AutoProfileInfo *info = new AutoProfileInfo(guid, profile, profileActive, this);
if (!windowClass.isEmpty())
{
info->setWindowClass(windowClass);
QList<AutoProfileInfo*> templist;
if (windowClassProfileAssignments.contains(windowClass))
{
templist = windowClassProfileAssignments.value(windowClass);
}
templist.append(info);
windowClassProfileAssignments.insert(windowClass, templist);
}
if (!windowName.isEmpty())
{
info->setWindowName(windowName);
QList<AutoProfileInfo*> templist;
if (windowNameProfileAssignments.contains(windowName))
{
templist = windowNameProfileAssignments.value(windowName);
}
templist.append(info);
windowNameProfileAssignments.insert(windowName, templist);
}
if (!exe.isEmpty())
{
info->setExe(exe);
QList<AutoProfileInfo*> templist;
if (appProfileAssignments.contains(exe))
{
templist = appProfileAssignments.value(exe);
}
templist.append(info);
appProfileAssignments.insert(exe, templist);
QString baseExe = QFileInfo(exe).fileName();
if (!baseExe.isEmpty() && baseExe != exe)
{
QList<AutoProfileInfo*> templist;
if (appProfileAssignments.contains(baseExe))
{
templist = appProfileAssignments.value(baseExe);
}
templist.append(info);
appProfileAssignments.insert(baseExe, templist);
}
}
}
}
else
{
quitSearch = true;
}
}
settings->endGroup();
settings->getLock()->unlock();
}
void AutoProfileWatcher::clearProfileAssignments()
{
QSet<AutoProfileInfo*> terminateProfiles;
QListIterator<QList<AutoProfileInfo*> > iterDelete(appProfileAssignments.values());
while (iterDelete.hasNext())
{
QList<AutoProfileInfo*> templist = iterDelete.next();
terminateProfiles.unite(templist.toSet());
}
appProfileAssignments.clear();
QListIterator<QList<AutoProfileInfo*> > iterClassDelete(windowClassProfileAssignments.values());
while (iterClassDelete.hasNext())
{
QList<AutoProfileInfo*> templist = iterClassDelete.next();
terminateProfiles.unite(templist.toSet());
}
windowClassProfileAssignments.clear();
QListIterator<QList<AutoProfileInfo*> > iterNameDelete(windowNameProfileAssignments.values());
while (iterNameDelete.hasNext())
{
QList<AutoProfileInfo*> templist = iterNameDelete.next();
terminateProfiles.unite(templist.toSet());
}
windowNameProfileAssignments.clear();
QSetIterator<AutoProfileInfo*> iterTerminate(terminateProfiles);
while (iterTerminate.hasNext())
{
AutoProfileInfo *info = iterTerminate.next();
if (info)
{
delete info;
info = 0;
}
}
QListIterator<AutoProfileInfo*> iterDefaultsDelete(defaultProfileAssignments.values());
while (iterDefaultsDelete.hasNext())
{
AutoProfileInfo *info = iterDefaultsDelete.next();
if (info)
{
delete info;
info = 0;
}
}
defaultProfileAssignments.clear();
allDefaultInfo = 0;
guidSet.clear();
}
QString AutoProfileWatcher::findAppLocation()
{
QString exepath;
#if defined(Q_OS_LINUX)
#ifdef WITH_X11
Window currentWindow = 0;
int pid = 0;
currentWindow = X11Extras::getInstance()->getWindowInFocus();
if (currentWindow)
{
pid = X11Extras::getInstance()->getApplicationPid(currentWindow);
}
if (pid > 0)
{
exepath = X11Extras::getInstance()->getApplicationLocation(pid);
}
#endif
#elif defined(Q_OS_WIN)
exepath = WinExtras::getForegroundWindowExePath();
//qDebug() << exepath;
#endif
return exepath;
}
QList<AutoProfileInfo*>* AutoProfileWatcher::getCustomDefaults()
{
QList<AutoProfileInfo*> *temp = new QList<AutoProfileInfo*>();
QHashIterator<QString, AutoProfileInfo*> iter(defaultProfileAssignments);
while (iter.hasNext())
{
iter.next();
temp->append(iter.value());
}
return temp;
}
AutoProfileInfo* AutoProfileWatcher::getDefaultAllProfile()
{
return allDefaultInfo;
}
bool AutoProfileWatcher::isGUIDLocked(QString guid)
{
return guidSet.contains(guid);
}
``` | /content/code_sandbox/src/autoprofilewatcher.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 3,304 |
```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 INPUTDAEMONTHREAD_H
#define INPUTDAEMONTHREAD_H
#include <QHash>
#include <QMap>
#include <QThread>
#include <QQueue>
#ifdef USE_SDL_2
#include <SDL2/SDL_joystick.h>
#include <SDL2/SDL_events.h>
#include "gamecontroller/gamecontroller.h"
#else
#include <SDL/SDL_joystick.h>
#include <SDL/SDL_events.h>
#endif
#include "joystick.h"
#include "sdleventreader.h"
#include "antimicrosettings.h"
#include "inputdevicebitarraystatus.h"
class InputDaemon : public QObject
{
Q_OBJECT
public:
explicit InputDaemon (QMap<SDL_JoystickID, InputDevice*> *joysticks,
AntiMicroSettings *settings, bool graphical=true,
QObject *parent=0);
~InputDaemon();
protected:
InputDeviceBitArrayStatus* createOrGrabBitStatusEntry(
QHash<InputDevice*, InputDeviceBitArrayStatus*> *statusHash,
InputDevice *device, bool readCurrent=true);
void firstInputPass(QQueue<SDL_Event> *sdlEventQueue);
void secondInputPass(QQueue<SDL_Event> *sdlEventQueue);
#ifdef USE_SDL_2
void modifyUnplugEvents(QQueue<SDL_Event> *sdlEventQueue);
QBitArray createUnplugEventBitArray(InputDevice *device);
Joystick* openJoystickDevice(int index);
#endif
void clearBitArrayStatusInstances();
QMap<SDL_JoystickID, InputDevice*> *joysticks;
#ifdef USE_SDL_2
QHash<SDL_JoystickID, Joystick*> trackjoysticks;
QHash<SDL_JoystickID, GameController*> trackcontrollers;
#endif
QHash<InputDevice*, InputDeviceBitArrayStatus*> releaseEventsGenerated;
QHash<InputDevice*, InputDeviceBitArrayStatus*> pendingEventValues;
bool stopped;
bool graphical;
SDLEventReader *eventWorker;
QThread *sdlWorkerThread;
AntiMicroSettings *settings;
QTimer pollResetTimer;
static const int GAMECONTROLLERTRIGGERRELEASE;
signals:
void joystickRefreshed (InputDevice *joystick);
void joysticksRefreshed(QMap<SDL_JoystickID, InputDevice*> *joysticks);
void complete(InputDevice *joystick);
void complete();
#ifdef USE_SDL_2
void deviceUpdated(int index, InputDevice *device);
void deviceRemoved(SDL_JoystickID deviceID);
void deviceAdded(InputDevice *device);
#endif
public slots:
void run();
void quit();
void refresh();
void refreshJoystick(InputDevice *joystick);
void refreshJoysticks();
void deleteJoysticks();
void startWorker();
#ifdef USE_SDL_2
void refreshMapping(QString mapping, InputDevice *device);
void removeDevice(InputDevice *device);
void addInputDevice(int index);
void refreshIndexes();
#endif
private slots:
void stop();
void resetActiveButtonMouseDistances();
void updatePollResetRate(unsigned int tempPollRate);
};
#endif // INPUTDAEMONTHREAD_H
``` | /content/code_sandbox/src/inputdaemon.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 766 |
```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 XMLCONFIGREADER_H
#define XMLCONFIGREADER_H
#include <QObject>
#include <QXmlStreamReader>
#include <QFile>
#include "inputdevice.h"
#include "joystick.h"
#ifdef USE_SDL_2
#include "gamecontroller/gamecontroller.h"
#endif
#include "common.h"
class XMLConfigReader : public QObject
{
Q_OBJECT
public:
explicit XMLConfigReader(QObject *parent = 0);
~XMLConfigReader();
void setJoystick(InputDevice *joystick);
void setFileName(QString filename);
QString getErrorString();
bool hasError();
bool read();
protected:
void initDeviceTypes();
QXmlStreamReader *xml;
QString fileName;
QFile *configFile;
InputDevice* joystick;
QStringList deviceTypes;
signals:
public slots:
void configJoystick(InputDevice *joystick);
};
#endif // XMLCONFIGREADER_H
``` | /content/code_sandbox/src/xmlconfigreader.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 287 |
```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 "dpadpushbuttongroup.h"
#include "buttoneditdialog.h"
#include "dpadeditdialog.h"
DPadPushButtonGroup::DPadPushButtonGroup(JoyDPad *dpad, bool displayNames, QWidget *parent) :
QGridLayout(parent)
{
this->dpad = dpad;
this->displayNames = displayNames;
generateButtons();
changeButtonLayout();
connect(dpad, SIGNAL(joyModeChanged()), this, SLOT(changeButtonLayout()));
}
void DPadPushButtonGroup::generateButtons()
{
QHash<int, JoyDPadButton*> *buttons = dpad->getJoyButtons();
JoyDPadButton *button = 0;
JoyDPadButtonWidget *pushbutton = 0;
button = buttons->value(JoyDPadButton::DpadLeftUp);
upLeftButton = new JoyDPadButtonWidget(button, displayNames, parentWidget());
pushbutton = upLeftButton;
connect(pushbutton, SIGNAL(clicked()), this, SLOT(openDPadButtonDialog()));
button->establishPropertyUpdatedConnections();
connect(button, SIGNAL(slotsChanged()), this, SLOT(propogateSlotsChanged()));
addWidget(pushbutton, 0, 0);
button = buttons->value(JoyDPadButton::DpadUp);
upButton = new JoyDPadButtonWidget(button, displayNames, parentWidget());
pushbutton = upButton;
connect(pushbutton, SIGNAL(clicked()), this, SLOT(openDPadButtonDialog()));
button->establishPropertyUpdatedConnections();
connect(button, SIGNAL(slotsChanged()), this, SLOT(propogateSlotsChanged()));
addWidget(pushbutton, 0, 1);
button = buttons->value(JoyDPadButton::DpadRightUp);
upRightButton = new JoyDPadButtonWidget(button, displayNames, parentWidget());
pushbutton = upRightButton;
connect(pushbutton, SIGNAL(clicked()), this, SLOT(openDPadButtonDialog()));
button->establishPropertyUpdatedConnections();
connect(button, SIGNAL(slotsChanged()), this, SLOT(propogateSlotsChanged()));
addWidget(pushbutton, 0, 2);
button = buttons->value(JoyDPadButton::DpadLeft);
leftButton = new JoyDPadButtonWidget(button, displayNames, parentWidget());
pushbutton = leftButton;
connect(pushbutton, SIGNAL(clicked()), this, SLOT(openDPadButtonDialog()));
button->establishPropertyUpdatedConnections();
connect(button, SIGNAL(slotsChanged()), this, SLOT(propogateSlotsChanged()));
addWidget(pushbutton, 1, 0);
dpadWidget = new DPadPushButton(dpad, displayNames, parentWidget());
dpadWidget->setIcon(QIcon::fromTheme(QString::fromUtf8("games-config-options")));
connect(dpadWidget, SIGNAL(clicked()), this, SLOT(showDPadDialog()));
addWidget(dpadWidget, 1, 1);
button = buttons->value(JoyDPadButton::DpadRight);
rightButton = new JoyDPadButtonWidget(button, displayNames, parentWidget());
pushbutton = rightButton;
connect(pushbutton, SIGNAL(clicked()), this, SLOT(openDPadButtonDialog()));
button->establishPropertyUpdatedConnections();
connect(button, SIGNAL(slotsChanged()), this, SLOT(propogateSlotsChanged()));
addWidget(pushbutton, 1, 2);
button = buttons->value(JoyDPadButton::DpadLeftDown);
downLeftButton = new JoyDPadButtonWidget(button, displayNames, parentWidget());
pushbutton = downLeftButton;
connect(pushbutton, SIGNAL(clicked()), this, SLOT(openDPadButtonDialog()));
button->establishPropertyUpdatedConnections();
connect(button, SIGNAL(slotsChanged()), this, SLOT(propogateSlotsChanged()));
addWidget(pushbutton, 2, 0);
button = buttons->value(JoyDPadButton::DpadDown);
downButton = new JoyDPadButtonWidget(button, displayNames, parentWidget());
pushbutton = downButton;
connect(pushbutton, SIGNAL(clicked()), this, SLOT(openDPadButtonDialog()));
button->establishPropertyUpdatedConnections();
connect(button, SIGNAL(slotsChanged()), this, SLOT(propogateSlotsChanged()));
addWidget(pushbutton, 2, 1);
button = buttons->value(JoyDPadButton::DpadRightDown);
downRightButton = new JoyDPadButtonWidget(button, displayNames, parentWidget());
pushbutton = downRightButton;
connect(pushbutton, SIGNAL(clicked()), this, SLOT(openDPadButtonDialog()));
button->establishPropertyUpdatedConnections();
connect(button, SIGNAL(slotsChanged()), this, SLOT(propogateSlotsChanged()));
addWidget(pushbutton, 2, 2);
}
void DPadPushButtonGroup::changeButtonLayout()
{
if (dpad->getJoyMode() == JoyDPad::StandardMode ||
dpad->getJoyMode() == JoyDPad::EightWayMode ||
dpad->getJoyMode() == JoyDPad::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 (dpad->getJoyMode() == JoyDPad::EightWayMode ||
dpad->getJoyMode() == JoyDPad::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 DPadPushButtonGroup::propogateSlotsChanged()
{
emit buttonSlotChanged();
}
JoyDPad* DPadPushButtonGroup::getDPad()
{
return dpad;
}
void DPadPushButtonGroup::openDPadButtonDialog()
{
JoyButtonWidget *buttonWidget = static_cast<JoyButtonWidget*>(sender());
JoyButton *button = buttonWidget->getJoyButton();
ButtonEditDialog *dialog = new ButtonEditDialog(button, parentWidget());
dialog->show();
}
void DPadPushButtonGroup::showDPadDialog()
{
DPadEditDialog *dialog = new DPadEditDialog(dpad, parentWidget());
dialog->show();
}
void DPadPushButtonGroup::toggleNameDisplay()
{
displayNames = !displayNames;
upButton->toggleNameDisplay();
downButton->toggleNameDisplay();
leftButton->toggleNameDisplay();
rightButton->toggleNameDisplay();
upLeftButton->toggleNameDisplay();
upRightButton->toggleNameDisplay();
downLeftButton->toggleNameDisplay();
downRightButton->toggleNameDisplay();
dpadWidget->toggleNameDisplay();
}
``` | /content/code_sandbox/src/dpadpushbuttongroup.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,590 |
```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 UNIXWINDOWINFODIALOG_H
#define UNIXWINDOWINFODIALOG_H
#include <QDialog>
#include <QString>
namespace Ui {
class CapturedWindowInfoDialog;
}
class CapturedWindowInfoDialog : public QDialog
{
Q_OBJECT
public:
#ifdef Q_OS_WIN
explicit CapturedWindowInfoDialog(QWidget *parent = 0);
#else
explicit CapturedWindowInfoDialog(unsigned long window, QWidget *parent = 0);
#endif
~CapturedWindowInfoDialog();
enum {
WindowNone = 0,
WindowClass = (1 << 0),
WindowName = (1 << 1),
WindowPath = (1 << 2),
};
typedef unsigned int CapturedWindowOption;
QString getWindowClass();
QString getWindowName();
QString getWindowPath();
bool useFullWindowPath();
CapturedWindowOption getSelectedOptions();
private:
Ui::CapturedWindowInfoDialog *ui;
protected:
CapturedWindowOption selectedMatch;
QString winClass;
QString winName;
QString winPath;
bool fullWinPath;
private slots:
void populateOption();
};
#endif // UNIXWINDOWINFODIALOG_H
``` | /content/code_sandbox/src/capturedwindowinfodialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 342 |
```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 <QString>
#include <QLabel>
#include <QDoubleSpinBox>
#include <QSpinBox>
#include <QCheckBox>
#include <QComboBox>
#include "mousesettingsdialog.h"
#include "ui_mousesettingsdialog.h"
MouseSettingsDialog::MouseSettingsDialog(QWidget *parent) :
QDialog(parent, Qt::Window),
ui(new Ui::MouseSettingsDialog)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
JoyButtonMouseHelper *mouseHelper = JoyButton::getMouseHelper();
connect(mouseHelper, SIGNAL(mouseCursorMoved(int,int,int)), this, SLOT(updateMouseCursorStatusLabels(int,int,int)));
connect(mouseHelper, SIGNAL(mouseSpringMoved(int,int)), this, SLOT(updateMouseSpringStatusLabels(int,int)));
lastMouseStatUpdate.start();
connect(ui->accelerationComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeSettingsWidgetStatus(int)));
connect(ui->accelerationComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(refreshMouseCursorSpeedValues(int)));
connect(ui->mouseModeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeSpringSectionStatus(int)));
connect(ui->mouseModeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeMouseSpeedBoxStatus(int)));
connect(ui->mouseModeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeWheelSpeedBoxStatus(int)));
connect(ui->mouseModeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeSensitivityStatusForMouseMode(int)));
connect(ui->horizontalSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateHorizontalSpeedConvertLabel(int)));
connect(ui->horizontalSpinBox, SIGNAL(valueChanged(int)), this, SLOT(moveSpeedsTogether(int)));
connect(ui->verticalSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateVerticalSpeedConvertLabel(int)));
connect(ui->verticalSpinBox, SIGNAL(valueChanged(int)), this, SLOT(moveSpeedsTogether(int)));
connect(ui->wheelVertSpeedSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateWheelVerticalSpeedLabel(int)));
connect(ui->wheelHoriSpeedSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateWheelHorizontalSpeedLabel(int)));
connect(ui->relativeSpringCheckBox, SIGNAL(clicked(bool)), this, SLOT(disableReleaseSpringBox(bool)));
connect(ui->relativeSpringCheckBox, SIGNAL(clicked(bool)), this, SLOT(resetReleaseRadius(bool)));
}
MouseSettingsDialog::~MouseSettingsDialog()
{
delete ui;
}
void MouseSettingsDialog::changeSettingsWidgetStatus(int index)
{
JoyButton::JoyMouseCurve temp = getMouseCurveForIndex(index);
int currentMouseMode = ui->mouseModeComboBox->currentIndex();
if (currentMouseMode == 1 && temp == JoyButton::PowerCurve)
{
ui->sensitivityDoubleSpinBox->setEnabled(true);
}
else
{
ui->sensitivityDoubleSpinBox->setEnabled(false);
}
if (currentMouseMode == 1 && (temp == JoyButton::EasingQuadraticCurve ||
temp == JoyButton::EasingCubicCurve))
{
ui->easingDoubleSpinBox->setEnabled(true);
}
else
{
ui->easingDoubleSpinBox->setEnabled(false);
}
}
void MouseSettingsDialog::changeSpringSectionStatus(int index)
{
if (index == 2)
{
ui->springWidthSpinBox->setEnabled(true);
ui->springHeightSpinBox->setEnabled(true);
ui->relativeSpringCheckBox->setEnabled(true);
bool enableSpringRadiusBox = !ui->relativeSpringCheckBox->isChecked();
ui->releaseSpringRadiusspinBox->setEnabled(enableSpringRadiusBox);
}
else
{
ui->springWidthSpinBox->setEnabled(false);
ui->springHeightSpinBox->setEnabled(false);
ui->relativeSpringCheckBox->setEnabled(false);
ui->releaseSpringRadiusspinBox->setEnabled(false);
}
}
void MouseSettingsDialog::updateHorizontalSpeedConvertLabel(int value)
{
QString label = QString (QString::number(value));
int currentCurveIndex = ui->accelerationComboBox->currentIndex();
JoyButton::JoyMouseCurve tempCurve = getMouseCurveForIndex(currentCurveIndex);
int finalSpeed = JoyButton::calculateFinalMouseSpeed(tempCurve, value);
label = label.append(" = ").append(QString::number(finalSpeed)).append(" pps");
ui->horizontalSpeedLabel->setText(label);
}
void MouseSettingsDialog::updateVerticalSpeedConvertLabel(int value)
{
QString label = QString (QString::number(value));
int currentCurveIndex = ui->accelerationComboBox->currentIndex();
JoyButton::JoyMouseCurve tempCurve = getMouseCurveForIndex(currentCurveIndex);
int finalSpeed = JoyButton::calculateFinalMouseSpeed(tempCurve, value);
label = label.append(" = ").append(QString::number(finalSpeed)).append(" pps");
ui->verticalSpeedLabel->setText(label);
}
void MouseSettingsDialog::moveSpeedsTogether(int value)
{
if (ui->changeMouseSpeedsTogetherCheckBox->isChecked())
{
ui->horizontalSpinBox->setValue(value);
ui->verticalSpinBox->setValue(value);
}
}
void MouseSettingsDialog::changeMouseSpeedBoxStatus(int index)
{
if (index == 2)
{
ui->horizontalSpinBox->setEnabled(false);
ui->verticalSpinBox->setEnabled(false);
ui->changeMouseSpeedsTogetherCheckBox->setEnabled(false);
ui->extraAccelerationGroupBox->setChecked(false);
ui->extraAccelerationGroupBox->setEnabled(false);
}
else
{
ui->horizontalSpinBox->setEnabled(true);
ui->verticalSpinBox->setEnabled(true);
ui->changeMouseSpeedsTogetherCheckBox->setEnabled(true);
ui->extraAccelerationGroupBox->setEnabled(true);
if (ui->extraAccelerationGroupBox->isChecked())
{
ui->extraAccelerationGroupBox->setEnabled(true);
}
}
}
void MouseSettingsDialog::changeWheelSpeedBoxStatus(int index)
{
if (index == 2)
{
ui->wheelHoriSpeedSpinBox->setEnabled(false);
ui->wheelVertSpeedSpinBox->setEnabled(false);
}
else
{
ui->wheelHoriSpeedSpinBox->setEnabled(true);
ui->wheelVertSpeedSpinBox->setEnabled(true);
}
}
void MouseSettingsDialog::updateWheelVerticalSpeedLabel(int value)
{
QString label = QString(QString::number(value));
label.append(" = ");
label.append(tr("%n notch(es)/s", "", value));
ui->wheelVertSpeedUnitsLabel->setText(label);
}
void MouseSettingsDialog::updateWheelHorizontalSpeedLabel(int value)
{
QString label = QString(QString::number(value));
label.append(" = ");
label.append(tr("%n notch(es)/s", "", value));
ui->wheelHoriSpeedUnitsLabel->setText(label);
}
void MouseSettingsDialog::updateAccelerationCurvePresetComboBox(JoyButton::JoyMouseCurve mouseCurve)
{
if (mouseCurve == JoyButton::EnhancedPrecisionCurve)
{
ui->accelerationComboBox->setCurrentIndex(1);
}
else if (mouseCurve == JoyButton::LinearCurve)
{
ui->accelerationComboBox->setCurrentIndex(2);
}
else if (mouseCurve == JoyButton::QuadraticCurve)
{
ui->accelerationComboBox->setCurrentIndex(3);
}
else if (mouseCurve == JoyButton::CubicCurve)
{
ui->accelerationComboBox->setCurrentIndex(4);
}
else if (mouseCurve == JoyButton::QuadraticExtremeCurve)
{
ui->accelerationComboBox->setCurrentIndex(5);
}
else if (mouseCurve == JoyButton::PowerCurve)
{
ui->accelerationComboBox->setCurrentIndex(6);
}
else if (mouseCurve == JoyButton::EasingQuadraticCurve)
{
ui->accelerationComboBox->setCurrentIndex(7);
}
else if (mouseCurve == JoyButton::EasingCubicCurve)
{
ui->accelerationComboBox->setCurrentIndex(8);
}
}
JoyButton::JoyMouseCurve MouseSettingsDialog::getMouseCurveForIndex(int index)
{
JoyButton::JoyMouseCurve temp = JoyButton::DEFAULTMOUSECURVE;
if (index == 1)
{
temp = JoyButton::EnhancedPrecisionCurve;
}
else if (index == 2)
{
temp = JoyButton::LinearCurve;
}
else if (index == 3)
{
temp = JoyButton::QuadraticCurve;
}
else if (index == 4)
{
temp = JoyButton::CubicCurve;
}
else if (index == 5)
{
temp = JoyButton::QuadraticExtremeCurve;
}
else if (index == 6)
{
temp = JoyButton::PowerCurve;
}
else if (index == 7)
{
temp = JoyButton::EasingQuadraticCurve;
}
else if (index == 8)
{
temp = JoyButton::EasingCubicCurve;
}
return temp;
}
void MouseSettingsDialog::changeSensitivityStatusForMouseMode(int index)
{
if (index == 2)
{
ui->sensitivityDoubleSpinBox->setEnabled(false);
}
else if (index == 1)
{
int currentCurveIndex = ui->accelerationComboBox->currentIndex();
JoyButton::JoyMouseCurve temp = getMouseCurveForIndex(currentCurveIndex);
if (temp == JoyButton::PowerCurve)
{
ui->sensitivityDoubleSpinBox->setEnabled(true);
}
}
else
{
ui->sensitivityDoubleSpinBox->setEnabled(false);
}
}
/**
* @brief Update mouse status labels with cursor mouse information provided by
* an InputDevice.
* @param X distance in pixels
* @param Y distance in pixels
* @param Time elapsed for generated event
*/
void MouseSettingsDialog::updateMouseCursorStatusLabels(int mouseX, int mouseY, int elapsed)
{
if (lastMouseStatUpdate.elapsed() >= 100 && elapsed > 0)
{
QString tempX("%1 (%2 pps) (%3 ms)");
QString tempY("%1 (%2 pps) (%3 ms)");
//QString tempPoll("%1 Hz");
ui->mouseStatusXLabel->setText(tempX.arg(mouseX).arg(mouseX * (1000/elapsed)).arg(elapsed));
ui->mouseStatusYLabel->setText(tempY.arg(mouseY).arg(mouseY * (1000/elapsed)).arg(elapsed));
//ui->mouseStatusPollLabel->setText(tempPoll.arg(1000/elapsed));
lastMouseStatUpdate.start();
}
}
/**
* @brief Update mouse status labels with spring mouse information
* provided by an InputDevice.
* @param X coordinate of cursor
* @param Y coordinate of cursor
*/
void MouseSettingsDialog::updateMouseSpringStatusLabels(int coordX, int coordY)
{
if (lastMouseStatUpdate.elapsed() >= 100)
{
QString tempX("%1");
QString tempY("%1");
ui->mouseStatusXLabel->setText(tempX.arg(coordX));
ui->mouseStatusYLabel->setText(tempY.arg(coordY));
lastMouseStatUpdate.start();
}
}
void MouseSettingsDialog::refreshMouseCursorSpeedValues(int index)
{
Q_UNUSED(index);
updateHorizontalSpeedConvertLabel(ui->horizontalSpinBox->value());
updateVerticalSpeedConvertLabel(ui->verticalSpinBox->value());
}
void MouseSettingsDialog::disableReleaseSpringBox(bool enable)
{
ui->releaseSpringRadiusspinBox->setEnabled(!enable);
}
void MouseSettingsDialog::resetReleaseRadius(bool enabled)
{
if (enabled && ui->releaseSpringRadiusspinBox->value() > 0)
{
ui->releaseSpringRadiusspinBox->setValue(0);
}
}
JoyButton::JoyExtraAccelerationCurve MouseSettingsDialog::getExtraAccelCurveForIndex(int index)
{
JoyButton::JoyExtraAccelerationCurve temp = JoyButton::LinearAccelCurve;
if (index == 1)
{
temp = JoyButton::LinearAccelCurve;
}
else if (index == 2)
{
temp = JoyButton::EaseOutSineCurve;
}
else if (index == 3)
{
temp = JoyButton::EaseOutQuadAccelCurve;
}
else if (index == 4)
{
temp = JoyButton::EaseOutCubicAccelCurve;
}
return temp;
}
void
MouseSettingsDialog::updateExtraAccelerationCurvePresetComboBox
(JoyButton::JoyExtraAccelerationCurve curve)
{
int temp = 0;
if (curve == JoyButton::LinearAccelCurve)
{
temp = 1;
}
else if (curve == JoyButton::EaseOutSineCurve)
{
temp = 2;
}
else if (curve == JoyButton::EaseOutQuadAccelCurve)
{
temp = 3;
}
else if (curve == JoyButton::EaseOutCubicAccelCurve)
{
temp = 4;
}
ui->extraAccelCurveComboBox->setCurrentIndex(temp);
}
``` | /content/code_sandbox/src/mousesettingsdialog.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 2,882 |
```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 <typeinfo>
#include <QString>
#include <QHashIterator>
#include <QMessageBox>
#include "advancestickassignmentdialog.h"
#include "ui_advancestickassignmentdialog.h"
#include "joycontrolstick.h"
AdvanceStickAssignmentDialog::AdvanceStickAssignmentDialog(Joystick *joystick, QWidget *parent) :
QDialog(parent, Qt::Window),
ui(new Ui::AdvanceStickAssignmentDialog)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
this->joystick = joystick;
joystick->getActiveSetJoystick()->setIgnoreEventState(true);
joystick->getActiveSetJoystick()->release();
joystick->resetButtonDownCount();
QString tempHeaderLabel = ui->joystickNumberLabel->text();
tempHeaderLabel = tempHeaderLabel.arg(joystick->getSDLName()).arg(joystick->getRealJoyNumber());
ui->joystickNumberLabel->setText(tempHeaderLabel);
ui->joystickNumberLabel2->setText(tempHeaderLabel);
tempHeaderLabel = ui->hatNumberLabel->text();
tempHeaderLabel = tempHeaderLabel.arg(joystick->getNumberHats());
ui->hatNumberLabel->setText(tempHeaderLabel);
ui->xAxisOneComboBox->addItem("", QVariant(0));
ui->yAxisOneComboBox->addItem("", QVariant(0));
ui->xAxisTwoComboBox->addItem("", QVariant(0));
ui->yAxisTwoComboBox->addItem("", QVariant(0));
for (int i=0; i < joystick->getNumberAxes(); i++)
{
ui->xAxisOneComboBox->addItem(tr("Axis %1").arg(i+1), QVariant(i));
ui->yAxisOneComboBox->addItem(tr("Axis %1").arg(i+1), QVariant(i));
ui->xAxisTwoComboBox->addItem(tr("Axis %1").arg(i+1), QVariant(i));
ui->yAxisTwoComboBox->addItem(tr("Axis %1").arg(i+1), QVariant(i));
}
refreshStickConfiguration();
populateDPadComboBoxes();
refreshVDPadConfiguration();
#ifndef USE_SDL_2
ui->versionTwoMessageLabel->setVisible(false);
#endif
connect(ui->enableOneCheckBox, SIGNAL(clicked(bool)), this, SLOT(changeStateStickOneWidgets(bool)));
connect(ui->enableTwoCheckBox, SIGNAL(clicked(bool)), this, SLOT(changeStateStickTwoWidgets(bool)));
connect(ui->vdpadEnableCheckBox, SIGNAL(clicked(bool)), this, SLOT(changeStateVDPadWidgets(bool)));
connect(ui->xAxisOneComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(checkForAxisAssignmentStickOne()));
connect(ui->yAxisOneComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(checkForAxisAssignmentStickOne()));
connect(ui->xAxisTwoComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(checkForAxisAssignmentStickTwo()));
connect(ui->yAxisTwoComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(checkForAxisAssignmentStickTwo()));
connect(ui->quickAssignStick1PushButton, SIGNAL(clicked()), this, SLOT(openQuickAssignDialogStick1()));
connect(ui->quickAssignStick2PushButton, SIGNAL(clicked()), this, SLOT(openQuickAssignDialogStick2()));
enableVDPadComboBoxes();
connect(this, SIGNAL(stickConfigurationChanged()), this, SLOT(disableVDPadComboBoxes()));
connect(this, SIGNAL(stickConfigurationChanged()), this, SLOT(populateDPadComboBoxes()));
connect(this, SIGNAL(stickConfigurationChanged()), this, SLOT(refreshVDPadConfiguration()));
connect(this, SIGNAL(stickConfigurationChanged()), this, SLOT(enableVDPadComboBoxes()));
connect(ui->vdpadUpPushButton, SIGNAL(clicked()), this, SLOT(openAssignVDPadUp()));
connect(ui->vdpadDownPushButton, SIGNAL(clicked()), this, SLOT(openAssignVDPadDown()));
connect(ui->vdpadLeftPushButton, SIGNAL(clicked()), this, SLOT(openAssignVDPadLeft()));
connect(ui->vdpadRightPushButton, SIGNAL(clicked()), this, SLOT(openAssignVDPadRight()));
connect(this, SIGNAL(finished(int)), this, SLOT(reenableButtonEvents()));
}
AdvanceStickAssignmentDialog::~AdvanceStickAssignmentDialog()
{
delete ui;
}
void AdvanceStickAssignmentDialog::checkForAxisAssignmentStickOne()
{
if (ui->xAxisOneComboBox->currentIndex() > 0 && ui->yAxisOneComboBox->currentIndex() > 0)
{
if (ui->xAxisOneComboBox->currentIndex() != ui->yAxisOneComboBox->currentIndex())
{
for (int i=0; i < joystick->NUMBER_JOYSETS; i++)
{
SetJoystick *currentset = joystick->getSetJoystick(i);
JoyAxis *axis1 = currentset->getJoyAxis(ui->xAxisOneComboBox->currentIndex()-1);
JoyAxis *axis2 = currentset->getJoyAxis(ui->yAxisOneComboBox->currentIndex()-1);
if (axis1 && axis2)
{
JoyControlStick *controlstick = currentset->getJoyStick(0);
if (controlstick)
{
controlstick->replaceAxes(axis1, axis2);
}
else
{
JoyControlStick *controlstick = new JoyControlStick(axis1, axis2, 0, i, currentset);
currentset->addControlStick(0, controlstick);
}
}
}
refreshStickConfiguration();
emit stickConfigurationChanged();
}
else
{
if (sender() == ui->xAxisOneComboBox)
{
ui->yAxisOneComboBox->setCurrentIndex(0);
}
else if (sender() == ui->yAxisOneComboBox)
{
ui->xAxisOneComboBox->setCurrentIndex(0);
}
}
}
}
void AdvanceStickAssignmentDialog::checkForAxisAssignmentStickTwo()
{
if (ui->xAxisTwoComboBox->currentIndex() > 0 && ui->yAxisTwoComboBox->currentIndex() > 0)
{
if (ui->xAxisTwoComboBox->currentIndex() != ui->yAxisTwoComboBox->currentIndex())
{
for (int i=0; i < joystick->NUMBER_JOYSETS; i++)
{
SetJoystick *currentset = joystick->getSetJoystick(i);
JoyAxis *axis1 = currentset->getJoyAxis(ui->xAxisTwoComboBox->currentIndex()-1);
JoyAxis *axis2 = currentset->getJoyAxis(ui->yAxisTwoComboBox->currentIndex()-1);
if (axis1 && axis2)
{
JoyControlStick *controlstick = currentset->getJoyStick(1);
if (controlstick)
{
controlstick->replaceXAxis(axis1);
controlstick->replaceYAxis(axis2);
}
else
{
JoyControlStick *controlstick = new JoyControlStick(axis1, axis2, 1, i, currentset);
currentset->addControlStick(1, controlstick);
}
}
}
refreshStickConfiguration();
emit stickConfigurationChanged();
}
else
{
if (sender() == ui->xAxisTwoComboBox)
{
ui->yAxisTwoComboBox->setCurrentIndex(0);
}
else if (sender() == ui->yAxisTwoComboBox)
{
ui->xAxisTwoComboBox->setCurrentIndex(0);
}
}
}
}
void AdvanceStickAssignmentDialog::changeStateVDPadWidgets(bool enabled)
{
if (enabled)
{
ui->vdpadUpComboBox->setEnabled(true);
ui->vdpadDownComboBox->setEnabled(true);
ui->vdpadLeftComboBox->setEnabled(true);
ui->vdpadRightComboBox->setEnabled(true);
ui->vdpadUpPushButton->setEnabled(true);
ui->vdpadDownPushButton->setEnabled(true);
ui->vdpadLeftPushButton->setEnabled(true);
ui->vdpadRightPushButton->setEnabled(true);
for (int i=0; i < joystick->NUMBER_JOYSETS; i++)
{
SetJoystick *currentset = joystick->getSetJoystick(i);
if (!currentset->getVDPad(0))
{
VDPad *vdpad = new VDPad(0, i, currentset, currentset);
currentset->addVDPad(0, vdpad);
}
}
}
else
{
ui->vdpadUpComboBox->setEnabled(false);
ui->vdpadDownComboBox->setEnabled(false);
ui->vdpadLeftComboBox->setEnabled(false);
ui->vdpadRightComboBox->setEnabled(false);
ui->vdpadUpPushButton->setEnabled(false);
ui->vdpadDownPushButton->setEnabled(false);
ui->vdpadLeftPushButton->setEnabled(false);
ui->vdpadRightPushButton->setEnabled(false);
for (int i=0; i < joystick->NUMBER_JOYSETS; i++)
{
SetJoystick *currentset = joystick->getSetJoystick(i);
if (currentset->getVDPad(0))
{
currentset->removeVDPad(0);
}
}
}
}
void AdvanceStickAssignmentDialog::changeStateStickOneWidgets(bool enabled)
{
if (enabled)
{
ui->xAxisOneComboBox->setEnabled(true);
ui->yAxisOneComboBox->setEnabled(true);
ui->enableTwoCheckBox->setEnabled(true);
ui->quickAssignStick1PushButton->setEnabled(true);
}
else
{
ui->xAxisOneComboBox->setEnabled(false);
ui->xAxisOneComboBox->setCurrentIndex(0);
ui->yAxisOneComboBox->setEnabled(false);
ui->yAxisOneComboBox->setCurrentIndex(0);
ui->xAxisTwoComboBox->setEnabled(false);
ui->yAxisTwoComboBox->setEnabled(false);
ui->xAxisTwoComboBox->setCurrentIndex(0);
ui->yAxisTwoComboBox->setCurrentIndex(0);
ui->enableTwoCheckBox->setEnabled(false);
ui->enableTwoCheckBox->setChecked(false);
ui->quickAssignStick1PushButton->setEnabled(false);
JoyControlStick *controlstick = joystick->getActiveSetJoystick()->getJoyStick(0);
JoyControlStick *controlstick2 = joystick->getActiveSetJoystick()->getJoyStick(1);
if (controlstick2)
{
joystick->removeControlStick(1);
}
if (controlstick)
{
joystick->removeControlStick(0);
}
}
}
void AdvanceStickAssignmentDialog::changeStateStickTwoWidgets(bool enabled)
{
if (enabled)
{
ui->xAxisTwoComboBox->setEnabled(true);
ui->yAxisTwoComboBox->setEnabled(true);
ui->quickAssignStick2PushButton->setEnabled(true);
}
else
{
ui->xAxisTwoComboBox->setEnabled(false);
ui->xAxisTwoComboBox->setCurrentIndex(0);
ui->yAxisTwoComboBox->setEnabled(false);
ui->yAxisTwoComboBox->setCurrentIndex(0);
ui->quickAssignStick2PushButton->setEnabled(false);
JoyControlStick *controlstick = joystick->getActiveSetJoystick()->getJoyStick(1);
if (controlstick)
{
for (int i=0; i < joystick->NUMBER_JOYSETS; i++)
{
SetJoystick *currentset = joystick->getSetJoystick(i);
currentset->removeControlStick(1);
}
}
}
}
void AdvanceStickAssignmentDialog::refreshStickConfiguration()
{
JoyControlStick *stick1 = joystick->getActiveSetJoystick()->getJoyStick(0);
JoyControlStick *stick2 = joystick->getActiveSetJoystick()->getJoyStick(1);
if (stick1)
{
JoyAxis *axisX = stick1->getAxisX();
JoyAxis *axisY = stick1->getAxisY();
if (axisX && axisY)
{
ui->xAxisOneComboBox->setCurrentIndex(axisX->getRealJoyIndex());
ui->yAxisOneComboBox->setCurrentIndex(axisY->getRealJoyIndex());
ui->xAxisOneComboBox->setEnabled(true);
ui->yAxisOneComboBox->setEnabled(true);
ui->enableOneCheckBox->setEnabled(true);
ui->enableOneCheckBox->setChecked(true);
ui->enableTwoCheckBox->setEnabled(true);
ui->quickAssignStick1PushButton->setEnabled(true);
}
}
else
{
ui->xAxisOneComboBox->setCurrentIndex(0);
ui->xAxisOneComboBox->setEnabled(false);
ui->yAxisOneComboBox->setCurrentIndex(0);
ui->yAxisOneComboBox->setEnabled(false);
ui->enableOneCheckBox->setChecked(false);
ui->enableTwoCheckBox->setEnabled(false);
ui->quickAssignStick1PushButton->setEnabled(false);
}
if (stick2)
{
JoyAxis *axisX = stick2->getAxisX();
JoyAxis *axisY = stick2->getAxisY();
if (axisX && axisY)
{
ui->xAxisTwoComboBox->setCurrentIndex(axisX->getRealJoyIndex());
ui->yAxisTwoComboBox->setCurrentIndex(axisY->getRealJoyIndex());
ui->xAxisTwoComboBox->setEnabled(true);
ui->yAxisTwoComboBox->setEnabled(true);
ui->enableTwoCheckBox->setEnabled(true);
ui->enableTwoCheckBox->setChecked(true);
ui->quickAssignStick2PushButton->setEnabled(true);
}
}
else
{
ui->xAxisTwoComboBox->setCurrentIndex(0);
ui->xAxisTwoComboBox->setEnabled(false);
ui->yAxisTwoComboBox->setCurrentIndex(0);
ui->yAxisTwoComboBox->setEnabled(false);
ui->enableTwoCheckBox->setChecked(false);
ui->quickAssignStick2PushButton->setEnabled(false);
}
}
void AdvanceStickAssignmentDialog::refreshVDPadConfiguration()
{
VDPad *vdpad = joystick->getActiveSetJoystick()->getVDPad(0);
if (vdpad)
{
ui->vdpadEnableCheckBox->setChecked(true);
ui->vdpadUpComboBox->setEnabled(true);
ui->vdpadDownComboBox->setEnabled(true);
ui->vdpadLeftComboBox->setEnabled(true);
ui->vdpadRightComboBox->setEnabled(true);
ui->vdpadUpPushButton->setEnabled(true);
ui->vdpadDownPushButton->setEnabled(true);
ui->vdpadLeftPushButton->setEnabled(true);
ui->vdpadRightPushButton->setEnabled(true);
JoyButton *upButton = vdpad->getVButton(JoyDPadButton::DpadUp);
if (upButton)
{
int buttonindex = 0;
if (typeid(*upButton) == typeid(JoyAxisButton))
{
JoyAxisButton *axisbutton = static_cast<JoyAxisButton*>(upButton);
JoyAxis *axis = axisbutton->getAxis();
QList<QVariant> templist;
templist.append(QVariant(axis->getRealJoyIndex()));
templist.append(QVariant(axisbutton->getJoyNumber()));
buttonindex = ui->vdpadUpComboBox->findData(templist);
}
else
{
QList<QVariant> templist;
templist.append(QVariant(0));
templist.append(QVariant(upButton->getRealJoyNumber()));
buttonindex = ui->vdpadUpComboBox->findData(templist);
}
if (buttonindex == -1)
{
vdpad->removeVButton(upButton);
}
else
{
ui->vdpadUpComboBox->setCurrentIndex(buttonindex);
}
}
JoyButton *downButton = vdpad->getVButton(JoyDPadButton::DpadDown);
if (downButton)
{
int buttonindex = 0;
if (typeid(*downButton) == typeid(JoyAxisButton))
{
JoyAxisButton *axisbutton = static_cast<JoyAxisButton*>(downButton);
JoyAxis *axis = axisbutton->getAxis();
QList<QVariant> templist;
templist.append(QVariant(axis->getRealJoyIndex()));
templist.append(QVariant(axisbutton->getJoyNumber()));
buttonindex = ui->vdpadDownComboBox->findData(templist);
}
else
{
QList<QVariant> templist;
templist.append(QVariant(0));
templist.append(QVariant(downButton->getRealJoyNumber()));
buttonindex = ui->vdpadDownComboBox->findData(templist);
}
if (buttonindex == -1)
{
vdpad->removeVButton(downButton);
}
else
{
ui->vdpadDownComboBox->setCurrentIndex(buttonindex);
}
}
JoyButton *leftButton = vdpad->getVButton(JoyDPadButton::DpadLeft);
if (leftButton)
{
int buttonindex = 0;
if (typeid(*leftButton) == typeid(JoyAxisButton))
{
JoyAxisButton *axisbutton = static_cast<JoyAxisButton*>(leftButton);
JoyAxis *axis = axisbutton->getAxis();
QList<QVariant> templist;
templist.append(QVariant(axis->getRealJoyIndex()));
templist.append(QVariant(axisbutton->getJoyNumber()));
buttonindex = ui->vdpadLeftComboBox->findData(templist);
}
else
{
QList<QVariant> templist;
templist.append(QVariant(0));
templist.append(QVariant(leftButton->getRealJoyNumber()));
buttonindex = ui->vdpadLeftComboBox->findData(templist);
}
if (buttonindex == -1)
{
vdpad->removeVButton(leftButton);
}
else
{
ui->vdpadLeftComboBox->setCurrentIndex(buttonindex);
}
}
JoyButton *rightButton = vdpad->getVButton(JoyDPadButton::DpadRight);
if (rightButton)
{
int buttonindex = 0;
if (typeid(*rightButton) == typeid(JoyAxisButton))
{
JoyAxisButton *axisbutton = static_cast<JoyAxisButton*>(rightButton);
JoyAxis *axis = axisbutton->getAxis();
QList<QVariant> templist;
templist.append(QVariant(axis->getRealJoyIndex()));
templist.append(QVariant(axisbutton->getJoyNumber()));
buttonindex = ui->vdpadRightComboBox->findData(templist);
}
else
{
QList<QVariant> templist;
templist.append(QVariant(0));
templist.append(QVariant(rightButton->getRealJoyNumber()));
buttonindex = ui->vdpadRightComboBox->findData(templist);
}
if (buttonindex == -1)
{
vdpad->removeVButton(rightButton);
}
else
{
ui->vdpadRightComboBox->setCurrentIndex(buttonindex);
}
}
}
else
{
ui->vdpadEnableCheckBox->setChecked(false);
ui->vdpadUpComboBox->setCurrentIndex(0);
ui->vdpadUpComboBox->setEnabled(false);
ui->vdpadDownComboBox->setCurrentIndex(0);
ui->vdpadDownComboBox->setEnabled(false);
ui->vdpadLeftComboBox->setCurrentIndex(0);
ui->vdpadLeftComboBox->setEnabled(false);
ui->vdpadRightComboBox->setCurrentIndex(0);
ui->vdpadRightComboBox->setEnabled(false);
ui->vdpadUpPushButton->setEnabled(false);
ui->vdpadDownPushButton->setEnabled(false);
ui->vdpadLeftPushButton->setEnabled(false);
ui->vdpadRightPushButton->setEnabled(false);
}
}
void AdvanceStickAssignmentDialog::populateDPadComboBoxes()
{
ui->vdpadUpComboBox->clear();
ui->vdpadDownComboBox->clear();
ui->vdpadLeftComboBox->clear();
ui->vdpadRightComboBox->clear();
ui->vdpadUpComboBox->addItem("", QVariant(0));
ui->vdpadDownComboBox->addItem("", QVariant(0));
ui->vdpadLeftComboBox->addItem("", QVariant(0));
ui->vdpadRightComboBox->addItem("", QVariant(0));
for (int i = 0; i < joystick->getNumberAxes(); i++)
{
JoyAxis *axis = joystick->getActiveSetJoystick()->getJoyAxis(i);
if (!axis->isPartControlStick())
{
QList<QVariant> templist;
templist.append(QVariant(i+1));
templist.append(QVariant(0));
ui->vdpadUpComboBox->addItem(tr("Axis %1 -").arg(QString::number(i+1)), templist);
ui->vdpadDownComboBox->addItem(tr("Axis %1 -").arg(QString::number(i+1)), templist);
ui->vdpadLeftComboBox->addItem(tr("Axis %1 -").arg(QString::number(i+1)), templist);
ui->vdpadRightComboBox->addItem(tr("Axis %1 -").arg(QString::number(i+1)), templist);
templist.clear();
templist.append(QVariant(i+1));
templist.append(QVariant(1));
ui->vdpadUpComboBox->addItem(tr("Axis %1 +").arg(QString::number(i+1)), templist);
ui->vdpadDownComboBox->addItem(tr("Axis %1 +").arg(QString::number(i+1)), templist);
ui->vdpadLeftComboBox->addItem(tr("Axis %1 +").arg(QString::number(i+1)), templist);
ui->vdpadRightComboBox->addItem(tr("Axis %1 +").arg(QString::number(i+1)), templist);
}
}
for (int i = 0; i < joystick->getNumberButtons(); i++)
{
QList<QVariant> templist;
templist.append(QVariant(0));
templist.append(QVariant(i+1));
ui->vdpadUpComboBox->addItem(tr("Button %1").arg(QString::number(i+1)), templist);
ui->vdpadDownComboBox->addItem(tr("Button %1").arg(QString::number(i+1)), templist);
ui->vdpadLeftComboBox->addItem(tr("Button %1").arg(QString::number(i+1)), templist);
ui->vdpadRightComboBox->addItem(tr("Button %1").arg(QString::number(i+1)), templist);
}
}
void AdvanceStickAssignmentDialog::changeVDPadUpButton(int index)
{
if (index > 0)
{
if (ui->vdpadDownComboBox->currentIndex() == index)
{
ui->vdpadDownComboBox->setCurrentIndex(0);
}
else if (ui->vdpadLeftComboBox->currentIndex() == index)
{
ui->vdpadLeftComboBox->setCurrentIndex(0);
}
else if (ui->vdpadRightComboBox->currentIndex() == index)
{
ui->vdpadRightComboBox->setCurrentIndex(0);
}
QVariant temp = ui->vdpadUpComboBox->itemData(index);
QList<QVariant> templist = temp.toList();
if (templist.size() == 2)
{
int axis = templist.at(0).toInt();
int button = templist.at(1).toInt();
if (axis > 0 && button >= 0)
{
for (int i=0; i < joystick->NUMBER_JOYSETS; i++)
{
SetJoystick *currentset = joystick->getSetJoystick(i);
VDPad *vdpad = currentset->getVDPad(0);
JoyAxis *currentaxis = currentset->getJoyAxis(axis-1);
JoyButton *currentbutton = 0;
if (button == 0)
{
currentbutton = currentaxis->getNAxisButton();
}
else if (button == 1)
{
currentbutton = currentaxis->getPAxisButton();
}
vdpad->addVButton(JoyDPadButton::DpadUp, currentbutton);
}
}
else if (button > 0)
{
for (int i=0; i < joystick->NUMBER_JOYSETS; i++)
{
SetJoystick *currentset = joystick->getSetJoystick(i);
VDPad *vdpad = currentset->getVDPad(0);
JoyButton *currentbutton = currentset->getJoyButton(button-1);
if (currentbutton)
{
vdpad->addVButton(JoyDPadButton::DpadUp, currentbutton);
}
}
}
}
}
else
{
for (int i=0; i < joystick->NUMBER_JOYSETS; i++)
{
SetJoystick *currentset = joystick->getSetJoystick(i);
VDPad *vdpad = currentset->getVDPad(0);
if (vdpad && vdpad->getVButton(JoyDPadButton::DpadUp))
{
vdpad->removeVButton(JoyDPadButton::DpadUp);
}
}
}
}
void AdvanceStickAssignmentDialog::changeVDPadDownButton(int index)
{
if (index > 0)
{
if (ui->vdpadUpComboBox->currentIndex() == index)
{
ui->vdpadUpComboBox->setCurrentIndex(0);
}
else if (ui->vdpadLeftComboBox->currentIndex() == index)
{
ui->vdpadLeftComboBox->setCurrentIndex(0);
}
else if (ui->vdpadRightComboBox->currentIndex() == index)
{
ui->vdpadRightComboBox->setCurrentIndex(0);
}
QVariant temp = ui->vdpadDownComboBox->itemData(index);
QList<QVariant> templist = temp.toList();
if (templist.size() == 2)
{
int axis = templist.at(0).toInt();
int button = templist.at(1).toInt();
if (axis > 0 && button >= 0)
{
for (int i=0; i < joystick->NUMBER_JOYSETS; i++)
{
SetJoystick *currentset = joystick->getSetJoystick(i);
VDPad *vdpad = currentset->getVDPad(0);
JoyAxis *currentaxis = currentset->getJoyAxis(axis-1);
JoyButton *currentbutton = 0;
if (button == 0)
{
currentbutton = currentaxis->getNAxisButton();
}
else if (button == 1)
{
currentbutton = currentaxis->getPAxisButton();
}
vdpad->addVButton(JoyDPadButton::DpadDown, currentbutton);
}
}
else if (button > 0)
{
for (int i=0; i < joystick->NUMBER_JOYSETS; i++)
{
SetJoystick *currentset = joystick->getSetJoystick(i);
VDPad *vdpad = currentset->getVDPad(0);
JoyButton *currentbutton = currentset->getJoyButton(button-1);
if (currentbutton)
{
vdpad->addVButton(JoyDPadButton::DpadDown, currentbutton);
}
}
}
}
}
else
{
for (int i=0; i < joystick->NUMBER_JOYSETS; i++)
{
SetJoystick *currentset = joystick->getSetJoystick(i);
VDPad *vdpad = currentset->getVDPad(0);
if (vdpad && vdpad->getVButton(JoyDPadButton::DpadDown))
{
vdpad->removeVButton(JoyDPadButton::DpadDown);
}
}
}
}
void AdvanceStickAssignmentDialog::changeVDPadLeftButton(int index)
{
if (index > 0)
{
if (ui->vdpadUpComboBox->currentIndex() == index)
{
ui->vdpadUpComboBox->setCurrentIndex(0);
}
else if (ui->vdpadDownComboBox->currentIndex() == index)
{
ui->vdpadDownComboBox->setCurrentIndex(0);
}
else if (ui->vdpadRightComboBox->currentIndex() == index)
{
ui->vdpadRightComboBox->setCurrentIndex(0);
}
QVariant temp = ui->vdpadLeftComboBox->itemData(index);
QList<QVariant> templist = temp.toList();
if (templist.size() == 2)
{
int axis = templist.at(0).toInt();
int button = templist.at(1).toInt();
if (axis > 0 && button >= 0)
{
for (int i=0; i < joystick->NUMBER_JOYSETS; i++)
{
SetJoystick *currentset = joystick->getSetJoystick(i);
VDPad *vdpad = currentset->getVDPad(0);
JoyAxis *currentaxis = currentset->getJoyAxis(axis-1);
JoyButton *currentbutton = 0;
if (button == 0)
{
currentbutton = currentaxis->getNAxisButton();
}
else if (button == 1)
{
currentbutton = currentaxis->getPAxisButton();
}
vdpad->addVButton(JoyDPadButton::DpadLeft, currentbutton);
}
}
else if (button > 0)
{
for (int i=0; i < joystick->NUMBER_JOYSETS; i++)
{
SetJoystick *currentset = joystick->getSetJoystick(i);
VDPad *vdpad = currentset->getVDPad(0);
JoyButton *currentbutton = currentset->getJoyButton(button-1);
if (currentbutton)
{
vdpad->addVButton(JoyDPadButton::DpadLeft, currentbutton);
}
}
}
}
}
else
{
for (int i=0; i < joystick->NUMBER_JOYSETS; i++)
{
SetJoystick *currentset = joystick->getSetJoystick(i);
VDPad *vdpad = currentset->getVDPad(0);
if (vdpad && vdpad->getVButton(JoyDPadButton::DpadLeft))
{
vdpad->removeVButton(JoyDPadButton::DpadLeft);
}
}
}
}
void AdvanceStickAssignmentDialog::changeVDPadRightButton(int index)
{
if (index > 0)
{
if (ui->vdpadUpComboBox->currentIndex() == index)
{
ui->vdpadUpComboBox->setCurrentIndex(0);
}
else if (ui->vdpadDownComboBox->currentIndex() == index)
{
ui->vdpadDownComboBox->setCurrentIndex(0);
}
else if (ui->vdpadLeftComboBox->currentIndex() == index)
{
ui->vdpadLeftComboBox->setCurrentIndex(0);
}
QVariant temp = ui->vdpadRightComboBox->itemData(index);
QList<QVariant> templist = temp.toList();
if (templist.size() == 2)
{
int axis = templist.at(0).toInt();
int button = templist.at(1).toInt();
if (axis > 0 && button >= 0)
{
for (int i=0; i < joystick->NUMBER_JOYSETS; i++)
{
SetJoystick *currentset = joystick->getSetJoystick(i);
VDPad *vdpad = currentset->getVDPad(0);
JoyAxis *currentaxis = currentset->getJoyAxis(axis-1);
JoyButton *currentbutton = 0;
if (button == 0)
{
currentbutton = currentaxis->getNAxisButton();
}
else if (button == 1)
{
currentbutton = currentaxis->getPAxisButton();
}
vdpad->addVButton(JoyDPadButton::DpadRight, currentbutton);
}
}
else if (button > 0)
{
for (int i=0; i < joystick->NUMBER_JOYSETS; i++)
{
SetJoystick *currentset = joystick->getSetJoystick(i);
VDPad *vdpad = currentset->getVDPad(0);
JoyButton *currentbutton = currentset->getJoyButton(button-1);
if (currentbutton)
{
vdpad->addVButton(JoyDPadButton::DpadRight, currentbutton);
}
}
}
}
}
else
{
for (int i=0; i < joystick->NUMBER_JOYSETS; i++)
{
SetJoystick *currentset = joystick->getSetJoystick(i);
VDPad *vdpad = currentset->getVDPad(0);
if (vdpad && vdpad->getVButton(JoyDPadButton::DpadRight))
{
vdpad->removeVButton(JoyDPadButton::DpadRight);
}
}
}
}
void AdvanceStickAssignmentDialog::enableVDPadComboBoxes()
{
connect(ui->vdpadUpComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeVDPadUpButton(int)));
connect(ui->vdpadDownComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeVDPadDownButton(int)));
connect(ui->vdpadLeftComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeVDPadLeftButton(int)));
connect(ui->vdpadRightComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeVDPadRightButton(int)));
}
void AdvanceStickAssignmentDialog::disableVDPadComboBoxes()
{
disconnect(ui->vdpadUpComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeVDPadUpButton(int)));
disconnect(ui->vdpadDownComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeVDPadDownButton(int)));
disconnect(ui->vdpadLeftComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeVDPadLeftButton(int)));
disconnect(ui->vdpadRightComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeVDPadRightButton(int)));
}
void AdvanceStickAssignmentDialog::openQuickAssignDialogStick1()
{
QMessageBox msgBox;
msgBox.setText(tr("Move stick 1 along the X axis"));
msgBox.setStandardButtons(QMessageBox::Close);
for (int i=0; i < joystick->getNumberAxes(); i++)
{
JoyAxis *axis = joystick->getActiveSetJoystick()->getJoyAxis(i);
if (axis)
{
connect(axis, SIGNAL(active(int)), &msgBox, SLOT(close()));
connect(axis, SIGNAL(active(int)), this, SLOT(quickAssignStick1Axis1()));
}
}
msgBox.exec();
msgBox.setText(tr("Move stick 1 along the Y axis"));
for (int i=0; i < joystick->getNumberAxes(); i++)
{
JoyAxis *axis = joystick->getActiveSetJoystick()->getJoyAxis(i);
if (axis)
{
disconnect(axis, SIGNAL(active(int)), &msgBox, SLOT(close()));
disconnect(axis, SIGNAL(active(int)), this, SLOT(quickAssignStick1Axis1()));
connect(axis, SIGNAL(active(int)), &msgBox, SLOT(close()));
connect(axis, SIGNAL(active(int)), this, SLOT(quickAssignStick1Axis2()));
}
}
msgBox.exec();
for (int i=0; i < joystick->getNumberAxes(); i++)
{
JoyAxis *axis = joystick->getActiveSetJoystick()->getJoyAxis(i);
if (axis)
{
disconnect(axis, SIGNAL(active(int)), &msgBox, SLOT(close()));
disconnect(axis, SIGNAL(active(int)), this, SLOT(quickAssignStick1Axis2()));
}
}
}
void AdvanceStickAssignmentDialog::openQuickAssignDialogStick2()
{
QMessageBox msgBox;
msgBox.setText(tr("Move stick 2 along the X axis"));
msgBox.setStandardButtons(QMessageBox::Close);
for (int i=0; i < joystick->getNumberAxes(); i++)
{
JoyAxis *axis = joystick->getActiveSetJoystick()->getJoyAxis(i);
if (axis)
{
connect(axis, SIGNAL(active(int)), &msgBox, SLOT(close()));
connect(axis, SIGNAL(active(int)), this, SLOT(quickAssignStick2Axis1()));
}
}
msgBox.exec();
msgBox.setText(tr("Move stick 2 along the Y axis"));
for (int i=0; i < joystick->getNumberAxes(); i++)
{
JoyAxis *axis = joystick->getActiveSetJoystick()->getJoyAxis(i);
if (axis)
{
disconnect(axis, SIGNAL(active(int)), &msgBox, SLOT(close()));
disconnect(axis, SIGNAL(active(int)), this, SLOT(quickAssignStick2Axis1()));
connect(axis, SIGNAL(active(int)), &msgBox, SLOT(close()));
connect(axis, SIGNAL(active(int)), this, SLOT(quickAssignStick2Axis2()));
}
}
msgBox.exec();
for (int i=0; i < joystick->getNumberAxes(); i++)
{
JoyAxis *axis = joystick->getActiveSetJoystick()->getJoyAxis(i);
if (axis)
{
disconnect(axis, SIGNAL(active(int)), &msgBox, SLOT(close()));
disconnect(axis, SIGNAL(active(int)), this, SLOT(quickAssignStick2Axis2()));
}
}
}
void AdvanceStickAssignmentDialog::quickAssignStick1Axis1()
{
JoyAxis *axis = static_cast<JoyAxis*>(sender());
ui->xAxisOneComboBox->setCurrentIndex(axis->getRealJoyIndex());
}
void AdvanceStickAssignmentDialog::quickAssignStick1Axis2()
{
JoyAxis *axis = static_cast<JoyAxis*>(sender());
ui->yAxisOneComboBox->setCurrentIndex(axis->getRealJoyIndex());
}
void AdvanceStickAssignmentDialog::quickAssignStick2Axis1()
{
JoyAxis *axis = static_cast<JoyAxis*>(sender());
ui->xAxisTwoComboBox->setCurrentIndex(axis->getRealJoyIndex());
}
void AdvanceStickAssignmentDialog::quickAssignStick2Axis2()
{
JoyAxis *axis = static_cast<JoyAxis*>(sender());
ui->yAxisTwoComboBox->setCurrentIndex(axis->getRealJoyIndex());
}
void AdvanceStickAssignmentDialog::reenableButtonEvents()
{
joystick->getActiveSetJoystick()->setIgnoreEventState(false);
joystick->getActiveSetJoystick()->release();
}
void AdvanceStickAssignmentDialog::openAssignVDPadUp()
{
QMessageBox msgBox;
msgBox.setText(tr("Press a button or move an axis"));
msgBox.setStandardButtons(QMessageBox::Close);
for (int i=0; i < joystick->getNumberAxes(); i++)
{
JoyAxis *axis = joystick->getActiveSetJoystick()->getJoyAxis(i);
if (axis && !axis->isPartControlStick())
{
connect(axis->getNAxisButton(), SIGNAL(clicked(int)), &msgBox, SLOT(close()));
connect(axis->getNAxisButton(), SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadUp()));
connect(axis->getPAxisButton(), SIGNAL(clicked(int)), &msgBox, SLOT(close()));
connect(axis->getPAxisButton(), SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadUp()));
}
}
for (int i=0; i < joystick->getNumberButtons(); i++)
{
JoyButton *button = joystick->getActiveSetJoystick()->getJoyButton(i);
if (button)
{
connect(button, SIGNAL(clicked(int)), &msgBox, SLOT(close()));
connect(button, SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadUp()));
}
}
msgBox.exec();
for (int i=0; i < joystick->getNumberAxes(); i++)
{
JoyAxis *axis = joystick->getActiveSetJoystick()->getJoyAxis(i);
if (axis && !axis->isPartControlStick())
{
disconnect(axis->getNAxisButton(), SIGNAL(clicked(int)), &msgBox, SLOT(close()));
disconnect(axis->getNAxisButton(), SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadUp()));
disconnect(axis->getPAxisButton(), SIGNAL(clicked(int)), &msgBox, SLOT(close()));
disconnect(axis->getPAxisButton(), SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadUp()));
}
}
for (int i=0; i < joystick->getNumberButtons(); i++)
{
JoyButton *button = joystick->getActiveSetJoystick()->getJoyButton(i);
if (button)
{
disconnect(button, SIGNAL(clicked(int)), &msgBox, SLOT(close()));
disconnect(button, SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadUp()));
}
}
}
void AdvanceStickAssignmentDialog::openAssignVDPadDown()
{
QMessageBox msgBox;
msgBox.setText(tr("Press a button or move an axis"));
msgBox.setStandardButtons(QMessageBox::Close);
for (int i=0; i < joystick->getNumberAxes(); i++)
{
JoyAxis *axis = joystick->getActiveSetJoystick()->getJoyAxis(i);
if (axis && !axis->isPartControlStick())
{
connect(axis->getNAxisButton(), SIGNAL(clicked(int)), &msgBox, SLOT(close()));
connect(axis->getNAxisButton(), SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadDown()));
connect(axis->getPAxisButton(), SIGNAL(clicked(int)), &msgBox, SLOT(close()));
connect(axis->getPAxisButton(), SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadDown()));
}
}
for (int i=0; i < joystick->getNumberButtons(); i++)
{
JoyButton *button = joystick->getActiveSetJoystick()->getJoyButton(i);
if (button)
{
connect(button, SIGNAL(clicked(int)), &msgBox, SLOT(close()));
connect(button, SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadDown()));
}
}
msgBox.exec();
for (int i=0; i < joystick->getNumberAxes(); i++)
{
JoyAxis *axis = joystick->getActiveSetJoystick()->getJoyAxis(i);
if (axis && !axis->isPartControlStick())
{
disconnect(axis->getNAxisButton(), SIGNAL(clicked(int)), &msgBox, SLOT(close()));
disconnect(axis->getNAxisButton(), SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadDown()));
disconnect(axis->getPAxisButton(), SIGNAL(clicked(int)), &msgBox, SLOT(close()));
disconnect(axis->getPAxisButton(), SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadDown()));
}
}
for (int i=0; i < joystick->getNumberButtons(); i++)
{
JoyButton *button = joystick->getActiveSetJoystick()->getJoyButton(i);
if (button)
{
disconnect(button, SIGNAL(clicked(int)), &msgBox, SLOT(close()));
disconnect(button, SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadDown()));
}
}
}
void AdvanceStickAssignmentDialog::openAssignVDPadLeft()
{
QMessageBox msgBox;
msgBox.setText(tr("Press a button or move an axis"));
msgBox.setStandardButtons(QMessageBox::Close);
for (int i=0; i < joystick->getNumberAxes(); i++)
{
JoyAxis *axis = joystick->getActiveSetJoystick()->getJoyAxis(i);
if (axis && !axis->isPartControlStick())
{
connect(axis->getNAxisButton(), SIGNAL(clicked(int)), &msgBox, SLOT(close()));
connect(axis->getNAxisButton(), SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadLeft()));
connect(axis->getPAxisButton(), SIGNAL(clicked(int)), &msgBox, SLOT(close()));
connect(axis->getPAxisButton(), SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadLeft()));
}
}
for (int i=0; i < joystick->getNumberButtons(); i++)
{
JoyButton *button = joystick->getActiveSetJoystick()->getJoyButton(i);
if (button)
{
connect(button, SIGNAL(clicked(int)), &msgBox, SLOT(close()));
connect(button, SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadLeft()));
}
}
msgBox.exec();
for (int i=0; i < joystick->getNumberAxes(); i++)
{
JoyAxis *axis = joystick->getActiveSetJoystick()->getJoyAxis(i);
if (axis && !axis->isPartControlStick())
{
disconnect(axis->getNAxisButton(), SIGNAL(clicked(int)), &msgBox, SLOT(close()));
disconnect(axis->getNAxisButton(), SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadLeft()));
disconnect(axis->getPAxisButton(), SIGNAL(clicked(int)), &msgBox, SLOT(close()));
disconnect(axis->getPAxisButton(), SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadLeft()));
}
}
for (int i=0; i < joystick->getNumberButtons(); i++)
{
JoyButton *button = joystick->getActiveSetJoystick()->getJoyButton(i);
if (button)
{
disconnect(button, SIGNAL(clicked(int)), &msgBox, SLOT(close()));
disconnect(button, SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadLeft()));
}
}
}
void AdvanceStickAssignmentDialog::openAssignVDPadRight()
{
QMessageBox msgBox;
msgBox.setText(tr("Press a button or move an axis"));
msgBox.setStandardButtons(QMessageBox::Close);
for (int i=0; i < joystick->getNumberAxes(); i++)
{
JoyAxis *axis = joystick->getActiveSetJoystick()->getJoyAxis(i);
if (axis && !axis->isPartControlStick())
{
connect(axis->getNAxisButton(), SIGNAL(clicked(int)), &msgBox, SLOT(close()));
connect(axis->getNAxisButton(), SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadRight()));
connect(axis->getPAxisButton(), SIGNAL(clicked(int)), &msgBox, SLOT(close()));
connect(axis->getPAxisButton(), SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadRight()));
}
}
for (int i=0; i < joystick->getNumberButtons(); i++)
{
JoyButton *button = joystick->getActiveSetJoystick()->getJoyButton(i);
if (button)
{
connect(button, SIGNAL(clicked(int)), &msgBox, SLOT(close()));
connect(button, SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadRight()));
}
}
msgBox.exec();
for (int i=0; i < joystick->getNumberAxes(); i++)
{
JoyAxis *axis = joystick->getActiveSetJoystick()->getJoyAxis(i);
if (axis && !axis->isPartControlStick())
{
disconnect(axis->getNAxisButton(), SIGNAL(clicked(int)), &msgBox, SLOT(close()));
disconnect(axis->getNAxisButton(), SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadRight()));
disconnect(axis->getPAxisButton(), SIGNAL(clicked(int)), &msgBox, SLOT(close()));
disconnect(axis->getPAxisButton(), SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadRight()));
}
}
for (int i=0; i < joystick->getNumberButtons(); i++)
{
JoyButton *button = joystick->getActiveSetJoystick()->getJoyButton(i);
if (button)
{
disconnect(button, SIGNAL(clicked(int)), &msgBox, SLOT(close()));
disconnect(button, SIGNAL(clicked(int)), this, SLOT(quickAssignVDPadRight()));
}
}
}
void AdvanceStickAssignmentDialog::quickAssignVDPadUp()
{
if (qobject_cast<JoyAxisButton*>(sender()) != 0)
{
JoyAxisButton *axisButton = static_cast<JoyAxisButton*>(sender());
QList<QVariant> templist;
templist.append(QVariant(axisButton->getAxis()->getRealJoyIndex()));
if (axisButton->getAxis()->getNAxisButton() == axisButton)
{
templist.append(QVariant(0));
}
else
{
templist.append(QVariant(1));
}
int index = ui->vdpadUpComboBox->findData(templist);
if (index > 0)
{
ui->vdpadUpComboBox->setCurrentIndex(index);
}
}
else
{
JoyButton *button = static_cast<JoyButton*>(sender());
QList<QVariant> templist;
templist.append(QVariant(0));
templist.append(QVariant(button->getJoyNumber()+1));
int index = ui->vdpadUpComboBox->findData(templist);
if (index > 0)
{
ui->vdpadUpComboBox->setCurrentIndex(index);
}
}
}
void AdvanceStickAssignmentDialog::quickAssignVDPadDown()
{
if (qobject_cast<JoyAxisButton*>(sender()) != 0)
{
JoyAxisButton *axisButton = static_cast<JoyAxisButton*>(sender());
QList<QVariant> templist;
templist.append(QVariant(axisButton->getAxis()->getRealJoyIndex()));
if (axisButton->getAxis()->getNAxisButton() == axisButton)
{
templist.append(QVariant(0));
}
else
{
templist.append(QVariant(1));
}
int index = ui->vdpadDownComboBox->findData(templist);
if (index > 0)
{
ui->vdpadDownComboBox->setCurrentIndex(index);
}
}
else
{
JoyButton *button = static_cast<JoyButton*>(sender());
QList<QVariant> templist;
templist.append(QVariant(0));
templist.append(QVariant(button->getJoyNumber()+1));
int index = ui->vdpadDownComboBox->findData(templist);
if (index > 0)
{
ui->vdpadDownComboBox->setCurrentIndex(index);
}
}
}
void AdvanceStickAssignmentDialog::quickAssignVDPadLeft()
{
if (qobject_cast<JoyAxisButton*>(sender()) != 0)
{
JoyAxisButton *axisButton = static_cast<JoyAxisButton*>(sender());
QList<QVariant> templist;
templist.append(QVariant(axisButton->getAxis()->getRealJoyIndex()));
if (axisButton->getAxis()->getNAxisButton() == axisButton)
{
templist.append(QVariant(0));
}
else
{
templist.append(QVariant(1));
}
int index = ui->vdpadLeftComboBox->findData(templist);
if (index > 0)
{
ui->vdpadLeftComboBox->setCurrentIndex(index);
}
}
else
{
JoyButton *button = static_cast<JoyButton*>(sender());
QList<QVariant> templist;
templist.append(QVariant(0));
templist.append(QVariant(button->getJoyNumber()+1));
int index = ui->vdpadLeftComboBox->findData(templist);
if (index > 0)
{
ui->vdpadLeftComboBox->setCurrentIndex(index);
}
}
}
void AdvanceStickAssignmentDialog::quickAssignVDPadRight()
{
if (qobject_cast<JoyAxisButton*>(sender()) != 0)
{
JoyAxisButton *axisButton = static_cast<JoyAxisButton*>(sender());
QList<QVariant> templist;
templist.append(QVariant(axisButton->getAxis()->getRealJoyIndex()));
if (axisButton->getAxis()->getNAxisButton() == axisButton)
{
templist.append(QVariant(0));
}
else
{
templist.append(QVariant(1));
}
int index = ui->vdpadRightComboBox->findData(templist);
if (index > 0)
{
ui->vdpadRightComboBox->setCurrentIndex(index);
}
}
else
{
JoyButton *button = static_cast<JoyButton*>(sender());
QList<QVariant> templist;
templist.append(QVariant(0));
templist.append(QVariant(button->getJoyNumber()+1));
int index = ui->vdpadRightComboBox->findData(templist);
if (index > 0)
{
ui->vdpadRightComboBox->setCurrentIndex(index);
}
}
}
``` | /content/code_sandbox/src/advancestickassignmentdialog.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 11,642 |
```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 GAMECONTROLLERBUTTON_H
#define GAMECONTROLLERBUTTON_H
#include <QObject>
#include <QXmlStreamReader>
#include <joybuttontypes/joyaxisbutton.h>
class GameControllerTriggerButton : public JoyAxisButton
{
Q_OBJECT
public:
explicit GameControllerTriggerButton(JoyAxis *axis, int index, int originset, SetJoystick *parentSet, QObject *parent = 0);
virtual QString getXmlName();
void readJoystickConfig(QXmlStreamReader *xml);
static const QString xmlName;
signals:
public slots:
};
#endif // GAMECONTROLLERBUTTON_H
``` | /content/code_sandbox/src/gamecontroller/gamecontrollertriggerbutton.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 221 |
```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 "gamecontrollerdpad.h"
const QString GameControllerDPad::xmlName = "dpad";
GameControllerDPad::GameControllerDPad(JoyButton *upButton, JoyButton *downButton, JoyButton *leftButton, JoyButton *rightButton,
int index, int originset, SetJoystick *parentSet, QObject *parent) :
VDPad(upButton, downButton, leftButton, rightButton, index, originset, parentSet, parent)
{
}
QString GameControllerDPad::getName(bool forceFullFormat, bool displayName)
{
QString label;
if (!dpadName.isEmpty() && displayName)
{
if (forceFullFormat)
{
label.append(tr("DPad")).append(" ");
}
label.append(dpadName);
}
else if (!defaultDPadName.isEmpty())
{
if (forceFullFormat)
{
label.append(tr("DPad")).append(" ");
}
label.append(defaultDPadName);
}
else
{
label.append(tr("DPad")).append(" ");
label.append(QString::number(getRealJoyNumber()));
}
return label;
}
QString GameControllerDPad::getXmlName()
{
return this->xmlName;
}
void GameControllerDPad::readJoystickConfig(QXmlStreamReader *xml)
{
if (xml->isStartElement() && xml->name() == VDPad::xmlName)
{
xml->readNextStartElement();
while (!xml->atEnd() && (!xml->isEndElement() && xml->name() != VDPad::xmlName))
{
bool found = readMainConfig(xml);
if (!found)
{
xml->skipCurrentElement();
}
xml->readNextStartElement();
}
}
}
``` | /content/code_sandbox/src/gamecontroller/gamecontrollerdpad.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 471 |
```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 GAMECONTROLLERTRIGGER_H
#define GAMECONTROLLERTRIGGER_H
#include <QObject>
#include <QString>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <SDL2/SDL_gamecontroller.h>
#include "gamecontrollertriggerbutton.h"
#include <joyaxis.h>
class GameControllerTrigger : public JoyAxis
{
Q_OBJECT
public:
explicit GameControllerTrigger(int index, int originset, SetJoystick *parentSet, QObject *parent = 0);
virtual QString getXmlName();
virtual QString getPartialName(bool forceFullFormat, bool displayNames);
virtual int getDefaultDeadZone();
virtual int getDefaultMaxZone();
virtual ThrottleTypes getDefaultThrottle();
void readJoystickConfig(QXmlStreamReader *xml);
virtual void writeConfig(QXmlStreamWriter *xml);
static const int AXISDEADZONE;
static const int AXISMAXZONE;
static const ThrottleTypes DEFAULTTHROTTLE;
static const QString xmlName;
protected:
void correctJoystickThrottle();
signals:
public slots:
};
#endif // GAMECONTROLLERTRIGGER_H
``` | /content/code_sandbox/src/gamecontroller/gamecontrollertrigger.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 325 |
```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 "gamecontrollertrigger.h"
const int GameControllerTrigger::AXISDEADZONE = 2000;
const int GameControllerTrigger::AXISMAXZONE = 32000;
const GameControllerTrigger::ThrottleTypes GameControllerTrigger::DEFAULTTHROTTLE = GameControllerTrigger::PositiveHalfThrottle;
const QString GameControllerTrigger::xmlName = "trigger";
GameControllerTrigger::GameControllerTrigger(int index, int originset, SetJoystick *parentSet, QObject *parent) :
JoyAxis(index, originset, parentSet, parent)
{
naxisbutton = new GameControllerTriggerButton(this, 0, originset, parentSet, this);
paxisbutton = new GameControllerTriggerButton(this, 1, originset, parentSet, this);
reset(index);
}
QString GameControllerTrigger::getXmlName()
{
return this->xmlName;
}
QString GameControllerTrigger::getPartialName(bool forceFullFormat, bool displayNames)
{
QString label;
if (!axisName.isEmpty() && displayNames)
{
label.append(axisName);
if (forceFullFormat)
{
label.append(" ").append(tr("Trigger"));
}
}
else if (!defaultAxisName.isEmpty())
{
label.append(defaultAxisName);
if (forceFullFormat)
{
label.append(" ").append(tr("Trigger"));
}
}
else
{
label.append(tr("Trigger")).append(" ");
label.append(QString::number(getRealJoyIndex() - SDL_CONTROLLER_AXIS_TRIGGERLEFT));
}
return label;
}
void GameControllerTrigger::readJoystickConfig(QXmlStreamReader *xml)
{
if (xml->isStartElement() && xml->name() == JoyAxis::xmlName)
{
xml->readNextStartElement();
while (!xml->atEnd() && (!xml->isEndElement() && xml->name() != JoyAxis::xmlName))
{
bool found = readMainConfig(xml);
if (!found && xml->name() == JoyAxisButton::xmlName && xml->isStartElement())
{
int index = xml->attributes().value("index").toString().toInt();
if (index == 1)
{
found = true;
GameControllerTriggerButton *triggerButton =
static_cast<GameControllerTriggerButton*>(naxisbutton);
triggerButton->readJoystickConfig(xml);
}
else if (index == 2)
{
found = true;
GameControllerTriggerButton *triggerButton =
static_cast<GameControllerTriggerButton*>(paxisbutton);
triggerButton->readJoystickConfig(xml);
}
}
if (!found)
{
xml->skipCurrentElement();
}
xml->readNextStartElement();
}
}
if (this->throttle != PositiveHalfThrottle)
{
this->setThrottle(PositiveHalfThrottle);
setCurrentRawValue(currentThrottledDeadValue);
currentThrottledValue = calculateThrottledValue(currentRawValue);
}
}
void GameControllerTrigger::correctJoystickThrottle()
{
if (this->throttle != PositiveHalfThrottle)
{
this->setThrottle(PositiveHalfThrottle);
setCurrentRawValue(currentThrottledDeadValue);
currentThrottledValue = calculateThrottledValue(currentRawValue);
}
}
void GameControllerTrigger::writeConfig(QXmlStreamWriter *xml)
{
bool currentlyDefault = isDefault();
xml->writeStartElement(getXmlName());
xml->writeAttribute("index", QString::number((index+1)-SDL_CONTROLLER_AXIS_TRIGGERLEFT));
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();
}
int GameControllerTrigger::getDefaultDeadZone()
{
return this->AXISDEADZONE;
}
int GameControllerTrigger::getDefaultMaxZone()
{
return this->AXISMAXZONE;
}
JoyAxis::ThrottleTypes GameControllerTrigger::getDefaultThrottle()
{
return (ThrottleTypes)this->DEFAULTTHROTTLE;
}
``` | /content/code_sandbox/src/gamecontroller/gamecontrollertrigger.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,186 |
```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 GAMECONTROLLERSET_H
#define GAMECONTROLLERSET_H
#include <QObject>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QHash>
#include <SDL2/SDL_gamecontroller.h>
#include <setjoystick.h>
#include "gamecontrollerdpad.h"
#include "gamecontrollertrigger.h"
class GameControllerSet : public SetJoystick
{
Q_OBJECT
public:
explicit GameControllerSet(InputDevice *device, int index, QObject *parent = 0);
virtual void refreshAxes();
virtual void readConfig(QXmlStreamReader *xml);
virtual void readJoystickConfig(QXmlStreamReader *xml,
QHash<unsigned int, SDL_GameControllerButton> &buttons,
QHash<unsigned int, SDL_GameControllerAxis> &axes,
QList<SDL_GameControllerButtonBind> &hatButtons);
protected:
void populateSticksDPad();
signals:
public slots:
virtual void reset();
};
#endif // GAMECONTROLLERSET_H
``` | /content/code_sandbox/src/gamecontroller/gamecontrollerset.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 298 |
```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 <setjoystick.h>
#include <inputdevice.h>
#include "gamecontrollertriggerbutton.h"
const QString GameControllerTriggerButton::xmlName = "triggerbutton";
GameControllerTriggerButton::GameControllerTriggerButton(JoyAxis *axis, int index, int originset, SetJoystick *parentSet, QObject *parent) :
JoyAxisButton(axis, index, originset, parentSet, parent)
{
}
QString GameControllerTriggerButton::getXmlName()
{
return this->xmlName;
}
void GameControllerTriggerButton::readJoystickConfig(QXmlStreamReader *xml)
{
if (xml->isStartElement() && xml->name() == JoyAxisButton::xmlName)
{
disconnect(this, SIGNAL(slotsChanged()), parentSet->getInputDevice(), SLOT(profileEdited()));
xml->readNextStartElement();
while (!xml->atEnd() && (!xml->isEndElement() && xml->name() != JoyAxisButton::xmlName))
{
bool found = readButtonConfig(xml);
if (!found)
{
xml->skipCurrentElement();
}
xml->readNextStartElement();
}
connect(this, SIGNAL(slotsChanged()), parentSet->getInputDevice(), SLOT(profileEdited()));
}
}
``` | /content/code_sandbox/src/gamecontroller/gamecontrollertriggerbutton.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 353 |
```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 GAMECONTROLLERDPAD_H
#define GAMECONTROLLERDPAD_H
#include <QObject>
#include "vdpad.h"
class GameControllerDPad : public VDPad
{
Q_OBJECT
public:
explicit GameControllerDPad(JoyButton *upButton, JoyButton *downButton, JoyButton *leftButton, JoyButton *rightButton,
int index, int originset, SetJoystick *parentSet, QObject *parent = 0);
virtual QString getName(bool forceFullFormat, bool displayName);
virtual QString getXmlName();
void readJoystickConfig(QXmlStreamReader *xml);
static const QString xmlName;
signals:
public slots:
};
#endif // GAMECONTROLLERDPAD_H
``` | /content/code_sandbox/src/gamecontroller/gamecontrollerdpad.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 245 |
```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 GAMECONTROLLER_H
#define GAMECONTROLLER_H
#include <SDL2/SDL_gamecontroller.h>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <inputdevice.h>
#include "gamecontrollerdpad.h"
#include "gamecontrollerset.h"
class GameController : public InputDevice
{
Q_OBJECT
public:
explicit GameController(SDL_GameController *controller, int deviceIndex, AntiMicroSettings *settings, QObject *parent = 0);
virtual QString getName();
virtual QString getSDLName();
// GUID available on SDL 2.
virtual QString getGUIDString();
virtual QString getRawGUIDString();
virtual QString getXmlName();
virtual bool isGameController();
virtual void closeSDLDevice();
virtual SDL_JoystickID getSDLJoystickID();
virtual int getNumberRawButtons();
virtual int getNumberRawAxes();
virtual int getNumberRawHats();
QString getBindStringForAxis(int index, bool trueIndex=true);
QString getBindStringForButton(int index, bool trueIndex=true);
SDL_GameControllerButtonBind getBindForAxis(int index);
SDL_GameControllerButtonBind getBindForButton(int index);
bool isRelevantGUID(QString tempGUID);
void rawButtonEvent(int index, bool pressed);
void rawAxisEvent(int index, int value);
void rawDPadEvent(int index, int value);
QHash<int, bool> rawbuttons;
QHash<int, int> axisvalues;
QHash<int, int> dpadvalues;
static const QString xmlName;
protected:
void readJoystickConfig(QXmlStreamReader *xml);
SDL_GameController *controller;
signals:
public slots:
virtual void readConfig(QXmlStreamReader *xml);
virtual void writeConfig(QXmlStreamWriter *xml);
protected slots:
virtual void axisActivatedEvent(int setindex, int axisindex, int value);
virtual void buttonClickEvent(int buttonindex);
virtual void buttonReleaseEvent(int buttonindex);
};
#endif // GAMECONTROLLER_H
``` | /content/code_sandbox/src/gamecontroller/gamecontroller.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 519 |
```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 "gamecontrollerset.h"
#include <inputdevice.h>
GameControllerSet::GameControllerSet(InputDevice *device, int index, QObject *parent) :
SetJoystick(device, index, false, parent)
{
reset();
}
void GameControllerSet::reset()
{
SetJoystick::reset();
populateSticksDPad();
}
void GameControllerSet::populateSticksDPad()
{
// Left Stick Assignment
JoyAxis *axisX = getJoyAxis(SDL_CONTROLLER_AXIS_LEFTX);
JoyAxis *axisY = getJoyAxis(SDL_CONTROLLER_AXIS_LEFTY);
JoyControlStick *stick1 = new JoyControlStick(axisX, axisY, 0, index, this);
//stick1->setStickDelay(10);
stick1->setDefaultStickName("L Stick");
addControlStick(0, stick1);
// Right Stick Assignment
axisX = getJoyAxis(SDL_CONTROLLER_AXIS_RIGHTX);
axisY = getJoyAxis(SDL_CONTROLLER_AXIS_RIGHTY);
JoyControlStick *stick2 = new JoyControlStick(axisX, axisY, 1, index, this);
stick2->setDefaultStickName("R Stick");
addControlStick(1, stick2);
// Assign DPad buttons as a virtual DPad. Allows rougelike controls
// to be assigned.
JoyButton *buttonUp = getJoyButton(SDL_CONTROLLER_BUTTON_DPAD_UP);
JoyButton *buttonDown = getJoyButton(SDL_CONTROLLER_BUTTON_DPAD_DOWN);
JoyButton *buttonLeft = getJoyButton(SDL_CONTROLLER_BUTTON_DPAD_LEFT);
JoyButton *buttonRight = getJoyButton(SDL_CONTROLLER_BUTTON_DPAD_RIGHT);
GameControllerDPad *controllerDPad = new GameControllerDPad(buttonUp, buttonDown, buttonLeft, buttonRight, 0, index, this, this);
controllerDPad->setDefaultDPadName("DPad");
//controllerDPad->setDPadDelay(10);
addVDPad(0, controllerDPad);
// Give default names to buttons
getJoyButton(SDL_CONTROLLER_BUTTON_A)->setDefaultButtonName("A");
getJoyButton(SDL_CONTROLLER_BUTTON_B)->setDefaultButtonName("B");
getJoyButton(SDL_CONTROLLER_BUTTON_X)->setDefaultButtonName("X");
getJoyButton(SDL_CONTROLLER_BUTTON_Y)->setDefaultButtonName("Y");
getJoyButton(SDL_CONTROLLER_BUTTON_BACK)->setDefaultButtonName(tr("Back"));
getJoyButton(SDL_CONTROLLER_BUTTON_GUIDE)->setDefaultButtonName(tr("Guide"));
getJoyButton(SDL_CONTROLLER_BUTTON_START)->setDefaultButtonName(tr("Start"));
getJoyButton(SDL_CONTROLLER_BUTTON_LEFTSTICK)->setDefaultButtonName(tr("LS Click"));
getJoyButton(SDL_CONTROLLER_BUTTON_RIGHTSTICK)->setDefaultButtonName(tr("RS Click"));
getJoyButton(SDL_CONTROLLER_BUTTON_LEFTSHOULDER)->setDefaultButtonName(tr("L Shoulder"));
getJoyButton(SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)->setDefaultButtonName(tr("R Shoulder"));
// Give default names to triggers
getJoyAxis(SDL_CONTROLLER_AXIS_TRIGGERLEFT)->setDefaultAxisName(tr("L Trigger"));
getJoyAxis(SDL_CONTROLLER_AXIS_TRIGGERRIGHT)->setDefaultAxisName(tr("R Trigger"));
}
void GameControllerSet::readJoystickConfig(QXmlStreamReader *xml,
QHash<unsigned int, SDL_GameControllerButton> &buttons,
QHash<unsigned int, SDL_GameControllerAxis> &axes,
QList<SDL_GameControllerButtonBind> &hatButtons)
{
if (xml->isStartElement() && xml->name() == "set")
{
xml->readNextStartElement();
while (!xml->atEnd() && (!xml->isEndElement() && xml->name() != "set"))
{
bool dpadExists = false;
bool vdpadExists = false;
if (xml->name() == "button" && xml->isStartElement())
{
int index = xml->attributes().value("index").toString().toInt();
JoyButton *button = 0;
if (buttons.contains(index-1))
{
SDL_GameControllerButton current = buttons.value(index-1);
button = getJoyButton(current);
}
if (button)
{
button->readConfig(xml);
}
else
{
xml->skipCurrentElement();
}
}
else if (xml->name() == "axis" && xml->isStartElement())
{
int index = xml->attributes().value("index").toString().toInt();
GameControllerTrigger *trigger = 0;
if (axes.contains(index-1))
{
SDL_GameControllerAxis current = axes.value(index-1);
trigger = static_cast<GameControllerTrigger*>(getJoyAxis((int)current));
}
if (trigger)
{
trigger->readJoystickConfig(xml);
}
else
{
xml->skipCurrentElement();
}
}
else if (xml->name() == "dpad" && xml->isStartElement())
{
int index = xml->attributes().value("index").toString().toInt();
index = index - 1;
bool found = false;
QListIterator<SDL_GameControllerButtonBind> iter(hatButtons);
SDL_GameControllerButtonBind current;
while (iter.hasNext())
{
current = iter.next();
if (current.value.hat.hat == index)
{
found = true;
iter.toBack();
}
}
VDPad *dpad = 0;
if (found)
{
dpad = getVDPad(0);
}
if (dpad && !vdpadExists)
{
dpadExists = true;
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();
index = index - 1;
bool found = false;
QListIterator<SDL_GameControllerButtonBind> iter(hatButtons);
SDL_GameControllerButtonBind current;
while (iter.hasNext())
{
current = iter.next();
if (current.value.hat.hat == index)
{
found = true;
iter.toBack();
}
}
VDPad *dpad = 0;
if (found)
{
dpad = getVDPad(0);
}
if (dpad && !dpadExists)
{
vdpadExists = true;
dpad->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 GameControllerSet::readConfig(QXmlStreamReader *xml)
{
if (xml->isStartElement() && xml->name() == "set")
{
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() == "trigger" && xml->isStartElement())
{
int index = xml->attributes().value("index").toString().toInt();
GameControllerTrigger *axis = qobject_cast<GameControllerTrigger*>(getJoyAxis((index-1) + SDL_CONTROLLER_AXIS_TRIGGERLEFT));
if (axis)
{
axis->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() == "dpad" && xml->isStartElement())
{
int index = xml->attributes().value("index").toString().toInt();
GameControllerDPad *vdpad = qobject_cast<GameControllerDPad*>(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 GameControllerSet::refreshAxes()
{
deleteAxes();
for (int i=0; i < device->getNumberRawAxes(); i++)
{
if (i == SDL_CONTROLLER_AXIS_TRIGGERLEFT ||
i == SDL_CONTROLLER_AXIS_TRIGGERRIGHT)
{
GameControllerTrigger *trigger = new GameControllerTrigger(i, index, this, this);
axes.insert(i, trigger);
enableAxisConnections(trigger);
}
else
{
JoyAxis *axis = new JoyAxis(i, index, this, this);
axes.insert(i, axis);
enableAxisConnections(axis);
}
}
}
``` | /content/code_sandbox/src/gamecontroller/gamecontrollerset.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 2,391 |
```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 VIRTUALMOUSEPUSHBUTTON_H
#define VIRTUALMOUSEPUSHBUTTON_H
#include <QPushButton>
#include <QString>
#include <joybuttonslot.h>
class VirtualMousePushButton : public QPushButton
{
Q_OBJECT
public:
explicit VirtualMousePushButton(QString displayText, int code, JoyButtonSlot::JoySlotInputAction mode, QWidget *parent = 0);
unsigned int getMouseCode();
JoyButtonSlot::JoySlotInputAction getMouseMode();
protected:
unsigned int code;
JoyButtonSlot::JoySlotInputAction mode;
signals:
void mouseSlotCreated(JoyButtonSlot *tempslot);
public slots:
private slots:
void createTempSlot();
};
#endif // VIRTUALMOUSEPUSHBUTTON_H
``` | /content/code_sandbox/src/keyboard/virtualmousepushbutton.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 252 |
```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 VIRTUALKEYBOARDMOUSEWIDGET_H
#define VIRTUALKEYBOARDMOUSEWIDGET_H
#include <QObject>
#include <QTabWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QHash>
#include <QString>
#include <QLabel>
#include <QSpinBox>
#include <QCheckBox>
#include <QComboBox>
#include <QMenu>
#include <QAction>
#include "virtualkeypushbutton.h"
#include "virtualmousepushbutton.h"
#include <joybutton.h>
#include <advancebuttondialog.h>
class VirtualKeyboardMouseWidget : public QTabWidget
{
Q_OBJECT
public:
explicit VirtualKeyboardMouseWidget(JoyButton *button, QWidget *parent = 0);
explicit VirtualKeyboardMouseWidget(QWidget *parent = 0);
bool isKeyboardTabVisible();
protected:
void setupVirtualKeyboardLayout();
QVBoxLayout* setupMainKeyboardLayout();
QVBoxLayout* setupAuxKeyboardLayout();
QVBoxLayout* setupKeyboardNumPadLayout();
void setupMouseControlLayout();
VirtualKeyPushButton* createNewKey(QString xcodestring);
QPushButton* createNoneKey();
void populateTopRowKeys();
QPushButton* createOtherKeysMenu();
virtual void resizeEvent(QResizeEvent *event);
JoyButton *button;
QWidget *keyboardTab;
QWidget *mouseTab;
//QLabel *mouseHorizSpeedLabel;
//QLabel *mouseVertSpeedLabel;
//QSpinBox *mouseHorizSpeedSpinBox;
//QSpinBox *mouseVertSpeedSpinBox;
QPushButton *noneButton;
QPushButton *mouseSettingsPushButton;
//QCheckBox *mouseChangeTogether;
//QComboBox *mouseModeComboBox;
QMenu *otherKeysMenu;
static QHash<QString, QString> topRowKeys;
signals:
void selectionFinished();
void selectionCleared();
void selectionMade(int keycode, unsigned int alias);
void selectionMade(JoyButtonSlot *slot);
public slots:
void establishVirtualKeyboardSingleSignalConnections();
void establishVirtualMouseSignalConnections();
void establishVirtualKeyboardAdvancedSignalConnections();
void establishVirtualMouseAdvancedSignalConnections();
private slots:
void processSingleKeyboardSelection(int keycode, unsigned int alias);
void processAdvancedKeyboardSelection(int keycode, unsigned int alias);
void processSingleMouseSelection(JoyButtonSlot *tempslot);
void processAdvancedMouseSelection(JoyButtonSlot *tempslot);
void clearButtonSlots();
void clearButtonSlotsFinish();
void openMouseSettingsDialog();
void enableMouseSettingButton();
void setButtonFontSizes();
void otherKeysActionSingle(bool triggered);
void otherKeysActionAdvanced(bool triggered);
};
#endif // VIRTUALKEYBOARDMOUSEWIDGET_H
``` | /content/code_sandbox/src/keyboard/virtualkeyboardmousewidget.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 661 |
```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 VIRTUALKEYPUSHBUTTON_H
#define VIRTUALKEYPUSHBUTTON_H
#include <QPushButton>
#include <QString>
#include <QHash>
#include <joybutton.h>
class VirtualKeyPushButton : public QPushButton
{
Q_OBJECT
public:
explicit VirtualKeyPushButton(JoyButton *button, QString xcodestring, QWidget *parent = 0);
int calculateFontSize();
protected:
int keycode;
unsigned int qkeyalias;
QString xcodestring;
QString displayString;
bool currentlyActive;
bool onCurrentButton;
JoyButton *button;
static QHash<QString, QString> knownAliases;
QString setDisplayString(QString xcodestring);
void populateKnownAliases();
signals:
void keycodeObtained(int code, unsigned int alias);
public slots:
private slots:
void processSingleSelection();
};
#endif // VIRTUALKEYPUSHBUTTON_H
``` | /content/code_sandbox/src/keyboard/virtualkeypushbutton.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 283 |
```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 "gamecontroller.h"
//#include "logger.h"
const QString GameController::xmlName = "gamecontroller";
GameController::GameController(SDL_GameController *controller, int deviceIndex,
AntiMicroSettings *settings, QObject *parent) :
InputDevice(deviceIndex, settings, parent)
{
this->controller = controller;
SDL_Joystick *joyhandle = SDL_GameControllerGetJoystick(controller);
joystickID = SDL_JoystickInstanceID(joyhandle);
for (int i=0; i < NUMBER_JOYSETS; i++)
{
GameControllerSet *controllerset = new GameControllerSet(this, i, this);
joystick_sets.insert(i, controllerset);
enableSetConnections(controllerset);
}
}
QString GameController::getName()
{
return QString(tr("Game Controller")).append(" ").append(QString::number(getRealJoyNumber()));
}
QString GameController::getSDLName()
{
QString temp;
if (controller)
{
temp = SDL_GameControllerName(controller);
}
return temp;
}
QString GameController::getGUIDString()
{
QString temp = getRawGUIDString();
#ifdef Q_OS_WIN
// On Windows, if device is seen as a game controller by SDL
// and the device has an empty GUID, assume that it is an XInput
// compatible device. Send back xinput as the GUID since SDL uses it
// internally anyway.
/*if (!temp.isEmpty() && temp.contains(emptyGUID))
{
temp = "xinput";
}
*/
#endif
return temp;
}
QString GameController::getRawGUIDString()
{
QString temp;
if (controller)
{
SDL_Joystick *joyhandle = SDL_GameControllerGetJoystick(controller);
if (joyhandle)
{
SDL_JoystickGUID tempGUID = SDL_JoystickGetGUID(joyhandle);
char guidString[65] = {'0'};
SDL_JoystickGetGUIDString(tempGUID, guidString, sizeof(guidString));
temp = QString(guidString);
}
}
return temp;
}
QString GameController::getXmlName()
{
return this->xmlName;
}
void GameController::closeSDLDevice()
{
if (controller && SDL_GameControllerGetAttached(controller))
{
SDL_GameControllerClose(controller);
controller = 0;
}
}
int GameController::getNumberRawButtons()
{
return SDL_CONTROLLER_BUTTON_MAX;
}
int GameController::getNumberRawAxes()
{
return SDL_CONTROLLER_AXIS_MAX;
}
int GameController::getNumberRawHats()
{
return 0;
}
void GameController::readJoystickConfig(QXmlStreamReader *xml)
{
if (xml->isStartElement() && xml->name() == "joystick")
{
//reset();
transferReset();
QHash<unsigned int, SDL_GameControllerButton> buttons;
QHash<unsigned int, SDL_GameControllerAxis> axes;
QList<SDL_GameControllerButtonBind> hatButtons;
for (int i=(int)SDL_CONTROLLER_BUTTON_A; i < (int)SDL_CONTROLLER_BUTTON_MAX; i++)
{
SDL_GameControllerButton currentButton = (SDL_GameControllerButton)i;
SDL_GameControllerButtonBind bound = SDL_GameControllerGetBindForButton(this->controller, currentButton);
if (bound.bindType == SDL_CONTROLLER_BINDTYPE_BUTTON)
{
buttons.insert(bound.value.button, currentButton);
}
else if (bound.bindType == SDL_CONTROLLER_BINDTYPE_HAT)
{
hatButtons.append(bound);
}
}
for (int i=(int)SDL_CONTROLLER_AXIS_LEFTX; i < (int)SDL_CONTROLLER_AXIS_MAX; i++)
{
SDL_GameControllerAxis currentAxis = (SDL_GameControllerAxis)i;
SDL_GameControllerButtonBind bound = SDL_GameControllerGetBindForAxis(this->controller, currentAxis);
if (bound.bindType == SDL_CONTROLLER_BINDTYPE_AXIS)
{
axes.insert(bound.value.axis, currentAxis);
}
}
xml->readNextStartElement();
while (!xml->atEnd() && (!xml->isEndElement() && xml->name() != "joystick"))
{
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())
{
GameControllerSet *currentSet = static_cast<GameControllerSet*>(joystick_sets.value(index));
currentSet->readJoystickConfig(xml, buttons, axes, hatButtons);
}
}
else
{
// If none of the above, skip the element
xml->skipCurrentElement();
}
xml->readNextStartElement();
}
}
else if (xml->name() == "names" && xml->isStartElement())
{
bool dpadNameExists = false;
bool vdpadNameExists = false;
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())
{
SDL_GameControllerButton current = buttons.value(index);
if (current)
{
setButtonName(current, 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())
{
SDL_GameControllerAxis current = axes.value(index);
if (current)
{
if (current == SDL_CONTROLLER_AXIS_LEFTX)
{
setStickButtonName(0, buttonIndex, temp);
}
else if (current == SDL_CONTROLLER_AXIS_LEFTY)
{
setStickButtonName(0, buttonIndex, temp);
}
else if (current == SDL_CONTROLLER_AXIS_RIGHTX)
{
setStickButtonName(1, buttonIndex, temp);
}
else if (current == SDL_CONTROLLER_AXIS_RIGHTY)
{
setStickButtonName(1, buttonIndex, temp);
}
else if (current == SDL_CONTROLLER_AXIS_TRIGGERLEFT)
{
setAxisName(current, temp);
}
else if (current == SDL_CONTROLLER_AXIS_TRIGGERRIGHT)
{
setAxisName(current, 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())
{
bool found = false;
QListIterator<SDL_GameControllerButtonBind> iter(hatButtons);
SDL_GameControllerButtonBind current;
while (iter.hasNext())
{
current = iter.next();
if (current.value.hat.hat == index)
{
found = true;
iter.toBack();
}
}
if (found)
{
VDPad *dpad = getActiveSetJoystick()->getVDPad(0);
if (dpad)
{
JoyDPadButton *dpadbutton = dpad->getJoyButton(buttonIndex);
if (dpad && dpadbutton->getActionName().isEmpty())
{
setVDPadButtonName(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())
{
bool found = false;
QListIterator<SDL_GameControllerButtonBind> iter(hatButtons);
SDL_GameControllerButtonBind current;
while (iter.hasNext())
{
current = iter.next();
if (current.value.hat.hat == index)
{
found = true;
iter.toBack();
}
}
if (found)
{
VDPad *dpad = getActiveSetJoystick()->getVDPad(0);
if (dpad)
{
JoyDPadButton *dpadbutton = dpad->getJoyButton(buttonIndex);
if (dpad && dpadbutton->getActionName().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())
{
if (axes.contains(index))
{
SDL_GameControllerAxis current = axes.value(index);
setAxisName((int)current, 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() && !vdpadNameExists)
{
bool found = false;
QListIterator<SDL_GameControllerButtonBind> iter(hatButtons);
SDL_GameControllerButtonBind current;
while (iter.hasNext())
{
current = iter.next();
if (current.value.hat.hat == index)
{
found = true;
iter.toBack();
}
}
if (found)
{
dpadNameExists = true;
VDPad *dpad = getActiveSetJoystick()->getVDPad(0);
if (dpad)
{
if (dpad->getDpadName().isEmpty())
{
setVDPadName(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() && !dpadNameExists)
{
bool found = false;
QListIterator<SDL_GameControllerButtonBind> iter(hatButtons);
SDL_GameControllerButtonBind current;
while (iter.hasNext())
{
current = iter.next();
if (current.value.hat.hat == index)
{
found = true;
iter.toBack();
}
}
if (found)
{
vdpadNameExists = true;
VDPad *dpad = getActiveSetJoystick()->getVDPad(0);
if (dpad)
{
if (dpad->getDpadName().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 GameController::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() == "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() == "triggerbuttonname" && 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) + SDL_CONTROLLER_AXIS_TRIGGERLEFT;
buttonIndex = buttonIndex - 1;
if ((index == SDL_CONTROLLER_AXIS_TRIGGERLEFT ||
index == SDL_CONTROLLER_AXIS_TRIGGERRIGHT) && !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())
{
setVDPadButtonName(index, buttonIndex, temp);
}
}
else if (xml->name() == "triggername" && xml->isStartElement())
{
int index = xml->attributes().value("index").toString().toInt();
QString temp = xml->readElementText();
index = (index - 1) + SDL_CONTROLLER_AXIS_TRIGGERLEFT;
if ((index == SDL_CONTROLLER_AXIS_TRIGGERLEFT ||
index == SDL_CONTROLLER_AXIS_TRIGGERRIGHT) && !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())
{
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();
}
else if (xml->isStartElement() && xml->name() == "joystick")
{
this->readJoystickConfig(xml);
}
}
void GameController::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);
}
xml->writeStartElement("names"); // <names>
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 < getNumberVDPads(); i++)
{
VDPad *vdpad = getActiveSetJoystick()->getVDPad(i);
if (vdpad)
{
if (!vdpad->getDpadName().isEmpty())
{
xml->writeStartElement("dpadname");
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("dpadbutton");
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();
}
QString GameController::getBindStringForAxis(int index, bool trueIndex)
{
QString temp;
SDL_GameControllerButtonBind bind =
SDL_GameControllerGetBindForAxis(controller,
static_cast<SDL_GameControllerAxis>(index));
if (bind.bindType != SDL_CONTROLLER_BINDTYPE_NONE)
{
int offset = trueIndex ? 0 : 1;
if (bind.bindType == SDL_CONTROLLER_BINDTYPE_BUTTON)
{
temp.append(QString("Button %1").arg(bind.value.button + offset));
}
else if (bind.bindType == SDL_CONTROLLER_BINDTYPE_AXIS)
{
temp.append(QString("Axis %1").arg(bind.value.axis + offset));
}
}
return temp;
}
QString GameController::getBindStringForButton(int index, bool trueIndex)
{
QString temp;
SDL_GameControllerButtonBind bind =
SDL_GameControllerGetBindForButton(controller,
static_cast<SDL_GameControllerButton>(index));
if (bind.bindType != SDL_CONTROLLER_BINDTYPE_NONE)
{
int offset = trueIndex ? 0 : 1;
if (bind.bindType == SDL_CONTROLLER_BINDTYPE_BUTTON)
{
temp.append(QString("Button %1").arg(bind.value.button + offset));
}
else if (bind.bindType == SDL_CONTROLLER_BINDTYPE_AXIS)
{
temp.append(QString("Axis %1").arg(bind.value.axis + offset));
}
else if (bind.bindType == SDL_CONTROLLER_BINDTYPE_HAT)
{
temp.append(QString("Hat %1.%2").arg(bind.value.hat.hat + offset)
.arg(bind.value.hat.hat_mask));
}
}
return temp;
}
SDL_GameControllerButtonBind GameController::getBindForAxis(int index)
{
SDL_GameControllerButtonBind bind = SDL_GameControllerGetBindForAxis(controller, (SDL_GameControllerAxis)index);
return bind;
}
SDL_GameControllerButtonBind GameController::getBindForButton(int index)
{
SDL_GameControllerButtonBind bind = SDL_GameControllerGetBindForButton(controller, (SDL_GameControllerButton)index);
return bind;
}
void GameController::buttonClickEvent(int buttonindex)
{
SDL_GameControllerButtonBind bind = getBindForButton(static_cast<SDL_GameControllerButton>(buttonindex));
if (bind.bindType != SDL_CONTROLLER_BINDTYPE_NONE)
{
if (bind.bindType == SDL_CONTROLLER_BINDTYPE_AXIS)
{
//emit rawAxisButtonClick(bind.value.axis, 0);
//emit rawAxisActivated(bind.value.axis, JoyAxis::AXISMAX);
}
else if (bind.bindType == SDL_CONTROLLER_BINDTYPE_BUTTON)
{
//emit rawButtonClick(bind.value.button);
}
else if (bind.bindType == SDL_CONTROLLER_BINDTYPE_HAT)
{
//emit rawDPadButtonClick(bind.value.hat.hat, bind.value.hat.hat_mask);
}
}
}
void GameController::buttonReleaseEvent(int buttonindex)
{
SDL_GameControllerButtonBind bind = getBindForButton(static_cast<SDL_GameControllerButton>(buttonindex));
if (bind.bindType != SDL_CONTROLLER_BINDTYPE_NONE)
{
if (bind.bindType == SDL_CONTROLLER_BINDTYPE_AXIS)
{
//emit rawAxisButtonRelease(bind.value.axis, 0);
}
else if (bind.bindType == SDL_CONTROLLER_BINDTYPE_BUTTON)
{
//emit rawButtonRelease(bind.value.button);
}
else if (bind.bindType == SDL_CONTROLLER_BINDTYPE_HAT)
{
//emit rawDPadButtonRelease(bind.value.hat.hat, bind.value.hat.hat_mask);
}
}
}
void GameController::axisActivatedEvent(int setindex, int axisindex, int value)
{
Q_UNUSED(setindex);
SDL_GameControllerButtonBind bind = getBindForAxis(static_cast<SDL_GameControllerButton>(axisindex));
if (bind.bindType != SDL_CONTROLLER_BINDTYPE_NONE)
{
if (bind.bindType == SDL_CONTROLLER_BINDTYPE_AXIS)
{
//emit rawAxisButtonClick(bind.value.axis, 0);
//emit rawAxisActivated(bind.value.axis, value);
}
else if (bind.bindType == SDL_CONTROLLER_BINDTYPE_BUTTON)
{
//emit rawButtonClick(bind.value.button);
}
else if (bind.bindType == SDL_CONTROLLER_BINDTYPE_HAT)
{
//emit rawDPadButtonClick(bind.value.hat.hat, bind.value.hat.hat_mask);
}
}
}
SDL_JoystickID GameController::getSDLJoystickID()
{
return joystickID;
}
/**
* @brief Check if device is using the SDL Game Controller API
* @return Status showing if device is using the Game Controller API
*/
bool GameController::isGameController()
{
return true;
}
/**
* @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 GameController::isRelevantGUID(QString tempGUID)
{
bool result = false;
if (InputDevice::isRelevantGUID(tempGUID))// || isEmptyGUID(tempGUID))
{
result = true;
}
return result;
}
void GameController::rawButtonEvent(int index, bool pressed)
{
bool knownbutton = rawbuttons.contains(index);
if (!knownbutton && pressed)
{
rawbuttons.insert(index, pressed);
emit rawButtonClick(index);
}
else if (knownbutton && !pressed)
{
rawbuttons.remove(index);
emit rawButtonRelease(index);
}
}
void GameController::rawAxisEvent(int index, int value)
{
bool knownaxis = axisvalues.contains(index);
if (!knownaxis && fabs(value) > rawAxisDeadZone)
{
axisvalues.insert(index, value);
emit rawAxisActivated(index, value);
}
else if (knownaxis && fabs(value) < rawAxisDeadZone)
{
axisvalues.remove(index);
emit rawAxisReleased(index, value);
}
emit rawAxisMoved(index, value);
}
void GameController::rawDPadEvent(int index, int value)
{
bool knowndpad = dpadvalues.contains(index);
if (!knowndpad && value != 0)
{
dpadvalues.insert(index, value);
emit rawDPadButtonClick(index, value);
}
else if (knowndpad && value == 0)
{
dpadvalues.remove(index);
emit rawDPadButtonRelease(index, value);
}
}
``` | /content/code_sandbox/src/gamecontroller/gamecontroller.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 6,856 |
```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 <QPainter>
#include "virtualkeypushbutton.h"
#include <event.h>
#include <antkeymapper.h>
#include <eventhandlerfactory.h>
QHash<QString, QString> VirtualKeyPushButton::knownAliases = QHash<QString, QString> ();
VirtualKeyPushButton::VirtualKeyPushButton(JoyButton *button, QString xcodestring, QWidget *parent) :
QPushButton(parent)
{
populateKnownAliases();
//qDebug() << "Question: " << X11KeySymToKeycode("KP_7") << endl;
//qDebug() << "Question: " << X11KeySymToKeycode(79) << endl;
this->keycode = 0;
this->qkeyalias = 0;
this->xcodestring = "";
this->displayString = "";
this->currentlyActive = false;
this->onCurrentButton = false;
this->button = button;
int temp = 0;
if (!xcodestring.isEmpty())
{
temp = X11KeySymToKeycode(xcodestring);
#ifdef Q_OS_UNIX
BaseEventHandler *handler = EventHandlerFactory::getInstance()->handler();
if (handler->getIdentifier() == "xtest")
{
temp = X11KeyCodeToX11KeySym(temp);
}
#endif
}
if (temp > 0)
{
#ifdef Q_OS_WIN
//static QtWinKeyMapper nativeWinKeyMapper;
BaseEventHandler *handler = EventHandlerFactory::getInstance()->handler();
#ifdef WITH_VMULTI
if (handler->getIdentifier() == "vmulti")
{
QtKeyMapperBase *nativeWinKeyMapper = AntKeyMapper::getInstance()->getNativeKeyMapper();
this->qkeyalias = nativeWinKeyMapper->returnQtKey(temp);
this->keycode = AntKeyMapper::getInstance()->returnVirtualKey(qkeyalias);
}
#endif
BACKEND_ELSE_IF (handler->getIdentifier() == "sendinput")
{
this->keycode = temp;
this->qkeyalias = AntKeyMapper::getInstance()->returnQtKey(this->keycode);
}
// Special exception for Numpad Enter on Windows.
if (xcodestring == "KP_Enter")
{
this->qkeyalias = Qt::Key_Enter;
}
#else
this->keycode = temp;
//this->keycode = X11KeyCodeToX11KeySym(temp);
this->qkeyalias = AntKeyMapper::getInstance()->returnQtKey(this->keycode);
//this->keycode = temp;
#endif
this->xcodestring = xcodestring;
this->displayString = setDisplayString(xcodestring);
}
this->setText(this->displayString.replace("&", "&&"));
connect(this, SIGNAL(clicked()), this, SLOT(processSingleSelection()));
}
void VirtualKeyPushButton::processSingleSelection()
{
emit keycodeObtained(keycode, qkeyalias);
}
QString VirtualKeyPushButton::setDisplayString(QString xcodestring)
{
QString temp;
if (knownAliases.contains(xcodestring))
{
temp = knownAliases.value(xcodestring);
}
else
{
temp = keycodeToKeyString(X11KeySymToKeycode(xcodestring));
//temp = keycodeToKeyString(X11KeySymToKeycode(xcodestring));
}
if (temp.isEmpty() && !xcodestring.isEmpty())
{
temp = xcodestring;
}
return temp.toUpper();
}
// Define display strings that will be used for various keys on the
// virtual keyboard.
void VirtualKeyPushButton::populateKnownAliases()
{
if (knownAliases.isEmpty())
{
knownAliases.insert("space", tr("Space"));
knownAliases.insert("Tab", tr("Tab"));
knownAliases.insert("Shift_L", tr("Shift (L)"));
knownAliases.insert("Shift_R", tr("Shift (R)"));
knownAliases.insert("Control_L", tr("Ctrl (L)"));
knownAliases.insert("Control_R", tr("Ctrl (R)"));
knownAliases.insert("Alt_L", tr("Alt (L)"));
knownAliases.insert("Alt_R", tr("Alt (R)"));
knownAliases.insert("Multi_key", tr("Alt (R)"));
knownAliases.insert("grave", tr("`"));
knownAliases.insert("asciitilde", tr("~"));
knownAliases.insert("minus", tr("-"));
knownAliases.insert("equal", tr("="));
knownAliases.insert("bracketleft", tr("["));
knownAliases.insert("bracketright", tr("]"));
knownAliases.insert("backslash", tr("\\"));
knownAliases.insert("Caps_Lock", tr("Caps"));
knownAliases.insert("semicolon", tr(";"));
knownAliases.insert("apostrophe", tr("'"));
knownAliases.insert("comma", tr(","));
knownAliases.insert("period", tr("."));
knownAliases.insert("slash", tr("/"));
knownAliases.insert("Escape", tr("ESC"));
knownAliases.insert("Print", tr("PRTSC"));
knownAliases.insert("Scroll_Lock", tr("SCLK"));
knownAliases.insert("Insert", tr("INS"));
knownAliases.insert("Prior", tr("PGUP"));
knownAliases.insert("Delete", tr("DEL"));
knownAliases.insert("Next", tr("PGDN"));
knownAliases.insert("KP_1", tr("1"));
knownAliases.insert("KP_2", tr("2"));
knownAliases.insert("KP_3", tr("3"));
knownAliases.insert("KP_4", tr("4"));
knownAliases.insert("KP_5", tr("5"));
knownAliases.insert("KP_6", tr("6"));
knownAliases.insert("KP_7", tr("7"));
knownAliases.insert("KP_8", tr("8"));
knownAliases.insert("KP_9", tr("9"));
knownAliases.insert("KP_0", tr("0"));
knownAliases.insert("Num_Lock", tr("NUM\nLK"));
knownAliases.insert("KP_Divide", tr("/"));
knownAliases.insert("KP_Multiply", tr("*"));
knownAliases.insert("KP_Subtract", tr("-"));
knownAliases.insert("KP_Add", tr("+"));
knownAliases.insert("KP_Enter", tr("E\nN\nT\nE\nR"));
knownAliases.insert("KP_Decimal", tr("."));
knownAliases.insert("asterisk", tr("*"));
knownAliases.insert("less", tr("<"));
knownAliases.insert("colon", tr(":"));
knownAliases.insert("Super_L", tr("Super (L)"));
knownAliases.insert("Menu", tr("Menu"));
knownAliases.insert("Up", tr("Up"));
knownAliases.insert("Down", tr("Down"));
knownAliases.insert("Left", tr("Left"));
knownAliases.insert("Right", tr("Right"));
}
}
int VirtualKeyPushButton::calculateFontSize()
{
QFont tempScaledFont(this->font());
tempScaledFont.setPointSize(10);
QFontMetrics fm(tempScaledFont);
while (((this->width()-4) < fm.boundingRect(this->rect(), Qt::AlignCenter, this->text()).width()) && tempScaledFont.pointSize() >= 6)
{
tempScaledFont.setPointSize(tempScaledFont.pointSize()-1);
fm = QFontMetrics(tempScaledFont);
}
return tempScaledFont.pointSize();
}
``` | /content/code_sandbox/src/keyboard/virtualkeypushbutton.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,679 |
```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 "virtualmousepushbutton.h"
VirtualMousePushButton::VirtualMousePushButton(QString displayText, int code, JoyButtonSlot::JoySlotInputAction mode, QWidget *parent) :
QPushButton(parent)
{
if (mode == JoyButtonSlot::JoyMouseButton || mode == JoyButtonSlot::JoyMouseMovement)
{
this->setText(displayText);
if (mode == JoyButtonSlot::JoyMouseMovement)
{
switch (code)
{
case JoyButtonSlot::MouseUp:
case JoyButtonSlot::MouseDown:
case JoyButtonSlot::MouseLeft:
case JoyButtonSlot::MouseRight:
{
this->code = code;
break;
}
default:
{
this->code = 0;
break;
}
}
}
else
{
this->code = code;
}
this->mode = mode;
}
else
{
this->setText(tr("INVALID"));
this->code = 0;
this->mode = JoyButtonSlot::JoyMouseButton;
}
connect(this, SIGNAL(clicked()), this, SLOT(createTempSlot()));
}
unsigned int VirtualMousePushButton::getMouseCode()
{
return code;
}
JoyButtonSlot::JoySlotInputAction VirtualMousePushButton::getMouseMode()
{
return mode;
}
void VirtualMousePushButton::createTempSlot()
{
JoyButtonSlot *tempslot = new JoyButtonSlot(this->code, this->mode, this);
emit mouseSlotCreated(tempslot);
}
``` | /content/code_sandbox/src/keyboard/virtualmousepushbutton.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 415 |
```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 <QFont>
#include <QSizePolicy>
#include <QSpacerItem>
#include <QListIterator>
#include <QLocale>
#include "virtualkeyboardmousewidget.h"
#include <mousedialog/mousebuttonsettingsdialog.h>
#include <event.h>
#include <antkeymapper.h>
QHash<QString, QString> VirtualKeyboardMouseWidget::topRowKeys = QHash<QString, QString> ();
VirtualKeyboardMouseWidget::VirtualKeyboardMouseWidget(JoyButton *button, QWidget *parent) :
QTabWidget(parent)
{
this->button = button;
keyboardTab = new QWidget(this);
mouseTab = new QWidget(this);
noneButton = createNoneKey();
populateTopRowKeys();
this->addTab(keyboardTab, tr("Keyboard"));
this->addTab(mouseTab, tr("Mouse"));
this->setTabPosition(QTabWidget::South);
setupVirtualKeyboardLayout();
setupMouseControlLayout();
establishVirtualKeyboardSingleSignalConnections();
establishVirtualMouseSignalConnections();
QTimer::singleShot(0, this, SLOT(setButtonFontSizes()));
connect(mouseSettingsPushButton, SIGNAL(clicked()), this, SLOT(openMouseSettingsDialog()));
}
VirtualKeyboardMouseWidget::VirtualKeyboardMouseWidget(QWidget *parent) :
QTabWidget(parent)
{
keyboardTab = new QWidget(this);
mouseTab = new QWidget(this);
noneButton = createNoneKey();
populateTopRowKeys();
this->addTab(keyboardTab, tr("Keyboard"));
this->addTab(mouseTab, tr("Mouse"));
this->setTabPosition(QTabWidget::South);
QTimer::singleShot(0, this, SLOT(setButtonFontSizes()));
}
void VirtualKeyboardMouseWidget::setupVirtualKeyboardLayout()
{
QVBoxLayout *finalVBoxLayout = new QVBoxLayout(keyboardTab);
QVBoxLayout *tempMainKeyLayout = setupMainKeyboardLayout();
QVBoxLayout *tempAuxKeyLayout = setupAuxKeyboardLayout();
QVBoxLayout *tempNumKeyPadLayout = setupKeyboardNumPadLayout();
QHBoxLayout *tempHBoxLayout = new QHBoxLayout();
tempHBoxLayout->addLayout(tempMainKeyLayout);
tempHBoxLayout->addLayout(tempAuxKeyLayout);
tempHBoxLayout->addLayout(tempNumKeyPadLayout);
finalVBoxLayout->addLayout(tempHBoxLayout);
}
QVBoxLayout *VirtualKeyboardMouseWidget::setupMainKeyboardLayout()
{
QHBoxLayout *tempHBoxLayout = new QHBoxLayout();
tempHBoxLayout->setSpacing(0);
QVBoxLayout *tempVBoxLayout = new QVBoxLayout();
QVBoxLayout *finalVBoxLayout = new QVBoxLayout();
tempHBoxLayout->addWidget(createNewKey("Escape"));
tempHBoxLayout->addSpacerItem(new QSpacerItem(40, 10, QSizePolicy::Expanding));
tempHBoxLayout->addWidget(createNewKey("F1"));
tempHBoxLayout->addWidget(createNewKey("F2"));
tempHBoxLayout->addWidget(createNewKey("F3"));
tempHBoxLayout->addWidget(createNewKey("F4"));
tempHBoxLayout->addSpacerItem(new QSpacerItem(40, 10, QSizePolicy::Expanding));
tempHBoxLayout->addWidget(createNewKey("F5"));
tempHBoxLayout->addWidget(createNewKey("F6"));
tempHBoxLayout->addWidget(createNewKey("F7"));
tempHBoxLayout->addWidget(createNewKey("F8"));
tempHBoxLayout->addSpacerItem(new QSpacerItem(40, 10, QSizePolicy::Expanding));
tempHBoxLayout->addWidget(createNewKey("F9"));
tempHBoxLayout->addWidget(createNewKey("F10"));
tempHBoxLayout->addWidget(createNewKey("F11"));
tempHBoxLayout->addWidget(createNewKey("F12"));
finalVBoxLayout->addLayout(tempHBoxLayout);
finalVBoxLayout->addSpacerItem(new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Fixed));
tempHBoxLayout = new QHBoxLayout();
tempHBoxLayout->setSpacing(0);
tempHBoxLayout->addWidget(createNewKey("grave"));
for (int i=1; i <= 9; i++)
{
tempHBoxLayout->addWidget(createNewKey(QString::number(i)));
}
tempHBoxLayout->addWidget(createNewKey("0"));
tempHBoxLayout->addWidget(createNewKey("minus"));
tempHBoxLayout->addWidget(createNewKey("equal"));
tempHBoxLayout->addWidget(createNewKey("BackSpace"));
tempVBoxLayout->addLayout(tempHBoxLayout);
QVBoxLayout *tempMiddleVLayout = new QVBoxLayout();
QHBoxLayout *tempMiddleHLayout = new QHBoxLayout();
tempHBoxLayout = new QHBoxLayout();
tempHBoxLayout->setSpacing(0);
tempHBoxLayout->addWidget(createNewKey("Tab"));
tempHBoxLayout->addSpacerItem(new QSpacerItem(10, 30, QSizePolicy::Fixed));
tempHBoxLayout->addWidget(createNewKey("q"));
tempHBoxLayout->addWidget(createNewKey("w"));
tempHBoxLayout->addWidget(createNewKey("e"));
tempHBoxLayout->addWidget(createNewKey("r"));
tempHBoxLayout->addWidget(createNewKey("t"));
tempHBoxLayout->addWidget(createNewKey("y"));
tempHBoxLayout->addWidget(createNewKey("u"));
tempHBoxLayout->addWidget(createNewKey("i"));
tempHBoxLayout->addWidget(createNewKey("o"));
tempHBoxLayout->addWidget(createNewKey("p"));
tempHBoxLayout->addWidget(createNewKey("bracketleft"));
tempHBoxLayout->addWidget(createNewKey("bracketright"));
if (QLocale::system().language() != QLocale::French &&
QLocale::system().language() != QLocale::German)
{
tempHBoxLayout->addWidget(createNewKey("backslash"));
}
tempMiddleVLayout->addLayout(tempHBoxLayout);
tempHBoxLayout = new QHBoxLayout();
tempHBoxLayout->setSpacing(0);
tempHBoxLayout->addWidget(createNewKey("Caps_Lock"));
tempHBoxLayout->addWidget(createNewKey("a"));
tempHBoxLayout->addWidget(createNewKey("s"));
tempHBoxLayout->addWidget(createNewKey("d"));
tempHBoxLayout->addWidget(createNewKey("f"));
tempHBoxLayout->addWidget(createNewKey("g"));
tempHBoxLayout->addWidget(createNewKey("h"));
tempHBoxLayout->addWidget(createNewKey("j"));
tempHBoxLayout->addWidget(createNewKey("k"));
tempHBoxLayout->addWidget(createNewKey("l"));
tempHBoxLayout->addWidget(createNewKey("semicolon"));
tempHBoxLayout->addWidget(createNewKey("apostrophe"));
if (QLocale::system().language() == QLocale::French ||
QLocale::system().language() == QLocale::German)
{
tempHBoxLayout->addWidget(createNewKey("asterisk"));
}
tempMiddleVLayout->addLayout(tempHBoxLayout);
tempMiddleHLayout->addLayout(tempMiddleVLayout);
tempMiddleHLayout->addWidget(createNewKey("Return"));
tempVBoxLayout->addLayout(tempMiddleHLayout);
tempHBoxLayout = new QHBoxLayout();
tempHBoxLayout->setSpacing(0);
tempHBoxLayout->addWidget(createNewKey("Shift_L"));
if (QLocale::system().language() == QLocale::French)
{
tempHBoxLayout->addWidget(createNewKey("less"));
}
tempHBoxLayout->addWidget(createNewKey("z"));
tempHBoxLayout->addWidget(createNewKey("x"));
tempHBoxLayout->addWidget(createNewKey("c"));
tempHBoxLayout->addWidget(createNewKey("v"));
tempHBoxLayout->addWidget(createNewKey("b"));
tempHBoxLayout->addWidget(createNewKey("n"));
tempHBoxLayout->addWidget(createNewKey("m"));
tempHBoxLayout->addWidget(createNewKey("comma"));
tempHBoxLayout->addWidget(createNewKey("period"));
tempHBoxLayout->addWidget(createNewKey("slash"));
tempHBoxLayout->addWidget(createNewKey("Shift_R"));
tempVBoxLayout->addLayout(tempHBoxLayout);
tempHBoxLayout = new QHBoxLayout();
tempHBoxLayout->setSpacing(0);
tempHBoxLayout->addWidget(createNewKey("Control_L"));
tempHBoxLayout->addWidget(createNewKey("Super_L"));
tempHBoxLayout->addWidget(createNewKey("Alt_L"));
tempHBoxLayout->addWidget(createNewKey("space"));
tempHBoxLayout->addWidget(createNewKey("Alt_R"));
tempHBoxLayout->addWidget(createNewKey("Menu"));
tempHBoxLayout->addWidget(createNewKey("Control_R"));
tempVBoxLayout->addLayout(tempHBoxLayout);
tempVBoxLayout->setStretch(0, 1);
tempVBoxLayout->setStretch(1, 2);
tempVBoxLayout->setStretch(2, 1);
tempVBoxLayout->setStretch(3, 1);
finalVBoxLayout->addLayout(tempVBoxLayout);
finalVBoxLayout->setStretch(0, 1);
finalVBoxLayout->setStretch(1, 0);
finalVBoxLayout->setStretch(2, 2);
return finalVBoxLayout;
}
QVBoxLayout* VirtualKeyboardMouseWidget::setupAuxKeyboardLayout()
{
QHBoxLayout *tempHBoxLayout = new QHBoxLayout();
QVBoxLayout *tempVBoxLayout = new QVBoxLayout();
QGridLayout *tempGridLayout = new QGridLayout();
tempHBoxLayout->setSpacing(0);
tempHBoxLayout->addWidget(createNewKey("Print"));
tempHBoxLayout->addWidget(createNewKey("Scroll_Lock"));
tempHBoxLayout->addWidget(createNewKey("Pause"));
tempVBoxLayout->addLayout(tempHBoxLayout);
tempVBoxLayout->addSpacerItem(new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Fixed));
tempGridLayout->setSpacing(0);
tempGridLayout->addWidget(createNewKey("Insert"), 1, 1, 1, 1);
tempGridLayout->addWidget(createNewKey("Home"), 1, 2, 1, 1);
tempGridLayout->addWidget(createNewKey("Prior"), 1, 3, 1, 1);
tempGridLayout->addWidget(createNewKey("Delete"), 2, 1, 1, 1);
tempGridLayout->addWidget(createNewKey("End"), 2, 2, 1, 1);
tempGridLayout->addWidget(createNewKey("Next"), 2, 3, 1, 1);
tempVBoxLayout->addLayout(tempGridLayout);
tempVBoxLayout->addSpacerItem(new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Fixed));
tempGridLayout = new QGridLayout();
tempGridLayout->setSpacing(0);
tempGridLayout->addWidget(createNewKey("Up"), 1, 2, 1, 1);
tempGridLayout->addWidget(createNewKey("Left"), 2, 1, 1, 1);
tempGridLayout->addWidget(createNewKey("Down"), 2, 2, 1, 1);
tempGridLayout->addWidget(createNewKey("Right"), 2, 3, 1, 1);
tempVBoxLayout->addLayout(tempGridLayout);
return tempVBoxLayout;
}
QVBoxLayout* VirtualKeyboardMouseWidget::setupKeyboardNumPadLayout()
{
QHBoxLayout *tempHBoxLayout = new QHBoxLayout();
QVBoxLayout *tempVBoxLayout = new QVBoxLayout();
QGridLayout *tempGridLayout = new QGridLayout();
QVBoxLayout *finalVBoxLayout = new QVBoxLayout();
QPushButton *othersKeysButton = createOtherKeysMenu();
//tempHBoxLayout->addWidget(othersKeysButton);
//tempHBoxLayout->addWidget(noneButton);
//finalVBoxLayout->addLayout(tempHBoxLayout);
finalVBoxLayout->addWidget(noneButton);
finalVBoxLayout->addWidget(othersKeysButton);
finalVBoxLayout->setStretchFactor(noneButton, 1);
finalVBoxLayout->setStretchFactor(othersKeysButton, 1);
finalVBoxLayout->addSpacerItem(new QSpacerItem(0, 20, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding));
tempHBoxLayout = new QHBoxLayout();
tempHBoxLayout->setSpacing(0);
tempHBoxLayout->addWidget(createNewKey("Num_Lock"));
tempHBoxLayout->addWidget(createNewKey("KP_Divide"));
tempHBoxLayout->addWidget(createNewKey("KP_Multiply"));
tempHBoxLayout->addWidget(createNewKey("KP_Subtract"));
tempVBoxLayout->addLayout(tempHBoxLayout);
tempHBoxLayout = new QHBoxLayout();
tempHBoxLayout->setSpacing(0);
tempGridLayout->addWidget(createNewKey("KP_7"), 1, 1, 1, 1);
tempGridLayout->addWidget(createNewKey("KP_8"), 1, 2, 1, 1);
tempGridLayout->addWidget(createNewKey("KP_9"), 1, 3, 1, 1);
tempGridLayout->addWidget(createNewKey("KP_4"), 2, 1, 1, 1);
tempGridLayout->addWidget(createNewKey("KP_5"), 2, 2, 1, 1);
tempGridLayout->addWidget(createNewKey("KP_6"), 2, 3, 1, 1);
tempHBoxLayout->addLayout(tempGridLayout);
tempHBoxLayout->addWidget(createNewKey("KP_Add"));
tempVBoxLayout->addLayout(tempHBoxLayout);
tempHBoxLayout = new QHBoxLayout();
tempHBoxLayout->setSpacing(0);
tempGridLayout = new QGridLayout();
tempGridLayout->setSpacing(0);
tempGridLayout->addWidget(createNewKey("KP_1"), 1, 1, 1, 1);
tempGridLayout->addWidget(createNewKey("KP_2"), 1, 2, 1, 1);
tempGridLayout->addWidget(createNewKey("KP_3"), 1, 3, 1, 1);
tempGridLayout->addWidget(createNewKey("KP_0"), 2, 1, 1, 2);
tempGridLayout->addWidget(createNewKey("KP_Decimal"), 2, 3, 1, 1);
tempHBoxLayout->addLayout(tempGridLayout);
tempHBoxLayout->addWidget(createNewKey("KP_Enter"));
tempVBoxLayout->addLayout(tempHBoxLayout);
finalVBoxLayout->addLayout(tempVBoxLayout);
finalVBoxLayout->setStretchFactor(tempVBoxLayout, 8);
return finalVBoxLayout;
}
void VirtualKeyboardMouseWidget::setupMouseControlLayout()
{
QHBoxLayout *tempHBoxLayout = new QHBoxLayout();
QVBoxLayout *tempVBoxLayout = new QVBoxLayout();
QGridLayout *tempGridLayout = new QGridLayout();
QVBoxLayout *finalVBoxLayout = new QVBoxLayout(mouseTab);
VirtualMousePushButton *pushButton = 0;
QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
pushButton = new VirtualMousePushButton(tr("Left", "Mouse"), JoyButtonSlot::MouseLeft, JoyButtonSlot::JoyMouseMovement, this);
pushButton->setSizePolicy(sizePolicy);
pushButton->setMinimumHeight(50);
tempVBoxLayout->addSpacerItem(new QSpacerItem(20, 50, QSizePolicy::Minimum, QSizePolicy::Expanding));
tempVBoxLayout->addWidget(pushButton);
tempVBoxLayout->addSpacerItem(new QSpacerItem(20, 50, QSizePolicy::Minimum, QSizePolicy::Expanding));
tempHBoxLayout->addLayout(tempVBoxLayout);
tempHBoxLayout->addSpacerItem(new QSpacerItem(10, 20, QSizePolicy::Fixed));
tempVBoxLayout = new QVBoxLayout();
pushButton = new VirtualMousePushButton(tr("Up", "Mouse"), JoyButtonSlot::MouseUp, JoyButtonSlot::JoyMouseMovement, this);
pushButton->setSizePolicy(sizePolicy);
pushButton->setMinimumHeight(50);
tempVBoxLayout->addWidget(pushButton);
tempVBoxLayout->addSpacerItem(new QSpacerItem(20, 10, QSizePolicy::Minimum, QSizePolicy::Fixed));
QHBoxLayout *tempInnerHBoxLayout = new QHBoxLayout();
pushButton = new VirtualMousePushButton(tr("Left Button", "Mouse"), 1, JoyButtonSlot::JoyMouseButton, this);
pushButton->setSizePolicy(sizePolicy);
tempInnerHBoxLayout->addWidget(pushButton);
pushButton = new VirtualMousePushButton(tr("Middle Button", "Mouse"), 2, JoyButtonSlot::JoyMouseButton, this);
pushButton->setSizePolicy(sizePolicy);
tempInnerHBoxLayout->addWidget(pushButton);
pushButton = new VirtualMousePushButton(tr("Right Button", "Mouse"), 3, JoyButtonSlot::JoyMouseButton, this);
pushButton->setSizePolicy(sizePolicy);
tempInnerHBoxLayout->addWidget(pushButton);
tempVBoxLayout->addLayout(tempInnerHBoxLayout);
tempVBoxLayout->addSpacerItem(new QSpacerItem(20, 10, QSizePolicy::Minimum, QSizePolicy::Fixed));
pushButton = new VirtualMousePushButton(tr("Wheel Up", "Mouse"), 4, JoyButtonSlot::JoyMouseButton, this);
pushButton->setSizePolicy(sizePolicy);
pushButton->setMinimumHeight(30);
tempGridLayout->addWidget(pushButton, 1, 2, 1, 1);
pushButton = new VirtualMousePushButton(tr("Wheel Left", "Mouse"), 6, JoyButtonSlot::JoyMouseButton, this);
pushButton->setSizePolicy(sizePolicy);
pushButton->setMinimumHeight(30);
tempGridLayout->addWidget(pushButton, 2, 1, 1, 1);
pushButton = new VirtualMousePushButton(tr("Wheel Right", "Mouse"), 7, JoyButtonSlot::JoyMouseButton, this);
pushButton->setSizePolicy(sizePolicy);
pushButton->setMinimumHeight(30);
tempGridLayout->addWidget(pushButton, 2, 3, 1, 1);
pushButton = new VirtualMousePushButton(tr("Wheel Down", "Mouse"), 5, JoyButtonSlot::JoyMouseButton, this);
pushButton->setSizePolicy(sizePolicy);
pushButton->setMinimumHeight(30);
tempGridLayout->addWidget(pushButton, 3, 2, 1, 1);
tempVBoxLayout->addLayout(tempGridLayout);
tempVBoxLayout->addSpacerItem(new QSpacerItem(20, 10, QSizePolicy::Minimum, QSizePolicy::Fixed));
pushButton = new VirtualMousePushButton(tr("Down", "Mouse"), JoyButtonSlot::MouseDown, JoyButtonSlot::JoyMouseMovement, this);
pushButton->setSizePolicy(sizePolicy);
pushButton->setMinimumHeight(50);
tempVBoxLayout->addWidget(pushButton);
tempVBoxLayout->setStretch(0, 1);
tempVBoxLayout->setStretch(2, 1);
tempVBoxLayout->setStretch(4, 3);
tempVBoxLayout->setStretch(6, 1);
tempHBoxLayout->addLayout(tempVBoxLayout);
tempHBoxLayout->addSpacerItem(new QSpacerItem(10, 20, QSizePolicy::Fixed));
tempVBoxLayout = new QVBoxLayout();
tempVBoxLayout->addSpacerItem(new QSpacerItem(20, 50, QSizePolicy::Minimum, QSizePolicy::Expanding));
pushButton = new VirtualMousePushButton(tr("Right", "Mouse"), JoyButtonSlot::MouseRight, JoyButtonSlot::JoyMouseMovement, this);
pushButton->setSizePolicy(sizePolicy);
pushButton->setMinimumHeight(50);
tempVBoxLayout->addWidget(pushButton);
tempVBoxLayout->addSpacerItem(new QSpacerItem(20, 50, QSizePolicy::Minimum, QSizePolicy::Expanding));
tempHBoxLayout->addLayout(tempVBoxLayout);
tempHBoxLayout->addSpacerItem(new QSpacerItem(10, 20, QSizePolicy::Fixed));
tempVBoxLayout = new QVBoxLayout();
tempVBoxLayout->setSpacing(20);
#ifdef Q_OS_WIN
pushButton = new VirtualMousePushButton(tr("Button 4", "Mouse"), 8, JoyButtonSlot::JoyMouseButton, this);
#else
pushButton = new VirtualMousePushButton(tr("Mouse 8", "Mouse"), 8, JoyButtonSlot::JoyMouseButton, this);
#endif
pushButton->setMinimumHeight(40);
tempVBoxLayout->addWidget(pushButton);
#ifdef Q_OS_WIN
pushButton = new VirtualMousePushButton(tr("Button 5", "Mouse"), 9, JoyButtonSlot::JoyMouseButton, this);
#else
pushButton = new VirtualMousePushButton(tr("Mouse 9", "Mouse"), 9, JoyButtonSlot::JoyMouseButton, this);
#endif
pushButton->setMinimumHeight(40);
tempVBoxLayout->addWidget(pushButton);
tempVBoxLayout->addSpacerItem(new QSpacerItem(20, 50, QSizePolicy::Minimum, QSizePolicy::Expanding));
tempHBoxLayout->addLayout(tempVBoxLayout);
tempHBoxLayout->addSpacerItem(new QSpacerItem(10, 20, QSizePolicy::Fixed));
tempVBoxLayout = new QVBoxLayout();
tempVBoxLayout->setSpacing(20);
tempVBoxLayout->addSpacerItem(new QSpacerItem(20, 10, QSizePolicy::Minimum, QSizePolicy::Expanding));
mouseSettingsPushButton = new QPushButton(tr("Mouse Settings"), this);
mouseSettingsPushButton->setIcon(QIcon::fromTheme(QString::fromUtf8("edit-select")));
tempVBoxLayout->addWidget(mouseSettingsPushButton);
tempHBoxLayout->addLayout(tempVBoxLayout);
finalVBoxLayout->addLayout(tempHBoxLayout);
}
VirtualKeyPushButton* VirtualKeyboardMouseWidget::createNewKey(QString xcodestring)
{
int width = 30;
int height = 30;
QFont font1;
font1.setPointSize(8);
font1.setBold(true);
VirtualKeyPushButton *pushButton = new VirtualKeyPushButton(button, xcodestring, this);
if (xcodestring == "space")
{
width = 100;
}
else if (xcodestring == "Tab")
{
width = 40;
}
else if (xcodestring == "Shift_L" || xcodestring == "Shift_R")
{
width = 84;
}
else if (xcodestring == "Control_L")
{
width = 70;
}
else if (xcodestring == "Return")
{
width = 60;
height = 60;
pushButton->setMaximumWidth(100);
}
else if (xcodestring == "BackSpace")
{
width = 72;
}
else if (topRowKeys.contains(xcodestring))
{
width = 30;
height = 36;
pushButton->setMaximumSize(100, 100);
}
else if (xcodestring == "Print" || xcodestring == "Scroll_Lock" || xcodestring == "Pause")
{
width = 40;
height = 36;
pushButton->setMaximumSize(100, 100);
font1.setPointSize(6);
}
else if (xcodestring == "KP_Add" || xcodestring == "KP_Enter")
{
width = 34;
font1.setPointSize(6);
}
else if (xcodestring == "Num_Lock")
{
font1.setPointSize(6);
}
else if (xcodestring.startsWith("KP_"))
{
width = 36;
height = 32;
}
pushButton->setObjectName(xcodestring);
pushButton->setMinimumSize(width, height);
QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
pushButton->setSizePolicy(sizePolicy);
pushButton->setFont(font1);
return pushButton;
}
QPushButton* VirtualKeyboardMouseWidget::createNoneKey()
{
QPushButton *pushButton = new QPushButton(tr("NONE"), this);
pushButton->setMinimumSize(0, 25);
//pushButton->setMaximumHeight(100);
QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
pushButton->setSizePolicy(sizePolicy);
QFont font1;
font1.setBold(true);
pushButton->setFont(font1);
return pushButton;
}
void VirtualKeyboardMouseWidget::processSingleKeyboardSelection(int keycode, unsigned int alias)
{
QMetaObject::invokeMethod(button, "clearSlotsEventReset");
//button->clearSlotsEventReset();
QMetaObject::invokeMethod(button, "setAssignedSlot", Qt::BlockingQueuedConnection,
Q_ARG(int, keycode),
Q_ARG(unsigned int, alias),
Q_ARG(int, 0),
Q_ARG(JoyButtonSlot::JoySlotInputAction, JoyButtonSlot::JoyKeyboard));
//button->setAssignedSlot(keycode, alias);
emit selectionFinished();
}
void VirtualKeyboardMouseWidget::processAdvancedKeyboardSelection(int keycode, unsigned int alias)
{
emit selectionMade(keycode, alias);
}
void VirtualKeyboardMouseWidget::processSingleMouseSelection(JoyButtonSlot *tempslot)
{
QMetaObject::invokeMethod(button, "clearSlotsEventReset");
//button->clearSlotsEventReset();
QMetaObject::invokeMethod(button, "setAssignedSlot", Qt::BlockingQueuedConnection,
Q_ARG(int, tempslot->getSlotCode()),
Q_ARG(JoyButtonSlot::JoySlotInputAction, tempslot->getSlotMode()));
//button->setAssignedSlot(tempslot->getSlotCode(), tempslot->getSlotMode());
emit selectionFinished();
}
void VirtualKeyboardMouseWidget::processAdvancedMouseSelection(JoyButtonSlot *tempslot)
{
emit selectionMade(tempslot);
}
void VirtualKeyboardMouseWidget::populateTopRowKeys()
{
if (topRowKeys.isEmpty())
{
topRowKeys.insert("Escape", "Escape");
topRowKeys.insert("F1", "F1");
topRowKeys.insert("F2", "F2");
topRowKeys.insert("F3", "F3");
topRowKeys.insert("F4", "F4");
topRowKeys.insert("F5", "F5");
topRowKeys.insert("F6", "F6");
topRowKeys.insert("F7", "F7");
topRowKeys.insert("F8", "F8");
topRowKeys.insert("F9", "F9");
topRowKeys.insert("F10", "F10");
topRowKeys.insert("F11", "F11");
topRowKeys.insert("F12", "F12");
}
}
void VirtualKeyboardMouseWidget::establishVirtualKeyboardSingleSignalConnections()
{
QList<VirtualKeyPushButton*> newlist = keyboardTab->findChildren<VirtualKeyPushButton*> ();
QListIterator<VirtualKeyPushButton*> iter(newlist);
while (iter.hasNext())
{
VirtualKeyPushButton *keybutton = iter.next();
disconnect(keybutton, SIGNAL(keycodeObtained(int, unsigned int)), 0, 0);
connect(keybutton, SIGNAL(keycodeObtained(int, unsigned int)), this, SLOT(processSingleKeyboardSelection(int, unsigned int)));
}
QListIterator<QAction*> iterActions(otherKeysMenu->actions());
while (iterActions.hasNext())
{
QAction *temp = iterActions.next();
disconnect(temp, SIGNAL(triggered(bool)), 0, 0);
connect(temp, SIGNAL(triggered(bool)), this, SLOT(otherKeysActionSingle(bool)));
}
disconnect(noneButton, SIGNAL(clicked()), 0, 0);
connect(noneButton, SIGNAL(clicked()), this, SLOT(clearButtonSlotsFinish()));
//qDebug() << "COUNT: " << newlist.count();
}
void VirtualKeyboardMouseWidget::establishVirtualKeyboardAdvancedSignalConnections()
{
QList<VirtualKeyPushButton*> newlist = keyboardTab->findChildren<VirtualKeyPushButton*> ();
QListIterator<VirtualKeyPushButton*> iter(newlist);
while (iter.hasNext())
{
VirtualKeyPushButton *keybutton = iter.next();
disconnect(keybutton, SIGNAL(keycodeObtained(int, unsigned int)), 0, 0);
connect(keybutton, SIGNAL(keycodeObtained(int, unsigned int)), this, SLOT(processAdvancedKeyboardSelection(int, unsigned int)));
}
QListIterator<QAction*> iterActions(otherKeysMenu->actions());
while (iterActions.hasNext())
{
QAction *temp = iterActions.next();
disconnect(temp, SIGNAL(triggered(bool)), 0, 0);
connect(temp, SIGNAL(triggered(bool)), this, SLOT(otherKeysActionAdvanced(bool)));
}
disconnect(noneButton, SIGNAL(clicked()), 0, 0);
connect(noneButton, SIGNAL(clicked()), this, SLOT(clearButtonSlots()));
}
void VirtualKeyboardMouseWidget::establishVirtualMouseSignalConnections()
{
QList<VirtualMousePushButton*> newlist = mouseTab->findChildren<VirtualMousePushButton*>();
QListIterator<VirtualMousePushButton*> iter(newlist);
while (iter.hasNext())
{
VirtualMousePushButton *mousebutton = iter.next();
disconnect(mousebutton, SIGNAL(mouseSlotCreated(JoyButtonSlot*)), 0, 0);
connect(mousebutton, SIGNAL(mouseSlotCreated(JoyButtonSlot*)), this, SLOT(processSingleMouseSelection(JoyButtonSlot*)));
}
}
void VirtualKeyboardMouseWidget::establishVirtualMouseAdvancedSignalConnections()
{
QList<VirtualMousePushButton*> newlist = mouseTab->findChildren<VirtualMousePushButton*>();
QListIterator<VirtualMousePushButton*> iter(newlist);
while (iter.hasNext())
{
VirtualMousePushButton *mousebutton = iter.next();
disconnect(mousebutton, SIGNAL(mouseSlotCreated(JoyButtonSlot*)), 0, 0);
connect(mousebutton, SIGNAL(mouseSlotCreated(JoyButtonSlot*)), this, SLOT(processAdvancedMouseSelection(JoyButtonSlot*)));
}
}
void VirtualKeyboardMouseWidget::clearButtonSlots()
{
QMetaObject::invokeMethod(button, "clearSlotsEventReset", Qt::BlockingQueuedConnection);
//button->clearSlotsEventReset();
emit selectionCleared();
}
void VirtualKeyboardMouseWidget::clearButtonSlotsFinish()
{
QMetaObject::invokeMethod(button, "clearSlotsEventReset", Qt::BlockingQueuedConnection);
//button->clearSlotsEventReset();
emit selectionFinished();
}
bool VirtualKeyboardMouseWidget::isKeyboardTabVisible()
{
return this->keyboardTab->isVisible();
}
void VirtualKeyboardMouseWidget::openMouseSettingsDialog()
{
mouseSettingsPushButton->setEnabled(false);
MouseButtonSettingsDialog *dialog = new MouseButtonSettingsDialog(this->button, this);
dialog->show();
QDialog *parent = static_cast<QDialog*>(this->parentWidget());
connect(parent, SIGNAL(finished(int)), dialog, SLOT(close()));
connect(dialog, SIGNAL(finished(int)), this, SLOT(enableMouseSettingButton()));
}
void VirtualKeyboardMouseWidget::enableMouseSettingButton()
{
mouseSettingsPushButton->setEnabled(true);
}
void VirtualKeyboardMouseWidget::resizeEvent(QResizeEvent *event)
{
QTabWidget::resizeEvent(event);
setButtonFontSizes();
}
// Dynamically change font size of list of push button according to the
// size of the buttons.
void VirtualKeyboardMouseWidget::setButtonFontSizes()
{
//int tempWidgetFontSize = 20;
QList<VirtualKeyPushButton*> buttonList = this->findChildren<VirtualKeyPushButton*>();
QListIterator<VirtualKeyPushButton*> iter(buttonList);
while (iter.hasNext())
{
VirtualKeyPushButton *temp = iter.next();
//widgetSizeMan = qMin(temp->calculateFontSize(), tempWidgetFontSize);
QFont tempFont(temp->font());
tempFont.setPointSize(temp->calculateFontSize());
temp->setFont(tempFont);
//temp->update();
}
/*iter.toFront();
while (iter.hasNext())
{
VirtualKeyPushButton *temp = iter.next();
QFont tempFont(temp->font());
tempFont.setPointSize(widgetSizeMan);
temp->setFont(tempFont);
}
*/
}
QPushButton* VirtualKeyboardMouseWidget::createOtherKeysMenu()
{
QPushButton *otherKeysPushbutton = new QPushButton("Others", this);
otherKeysPushbutton->setMinimumSize(0, 25);
//fuckMotherFuck->setMaximumHeight(100);
QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
otherKeysPushbutton->setSizePolicy(sizePolicy);
QFont font1;
font1.setBold(true);
otherKeysPushbutton->setFont(font1);
otherKeysMenu = new QMenu(this);
QAction *tempAction = 0;
unsigned int temp = 0;
#ifdef Q_OS_WIN
tempAction = new QAction(tr("Applications"), otherKeysMenu);
temp = AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Menu);
tempAction->setData(temp);
otherKeysMenu->addAction(tempAction);
#endif
tempAction = new QAction(tr("Browser Back"), otherKeysMenu);
temp = AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Back);
tempAction->setData(temp);
otherKeysMenu->addAction(tempAction);
tempAction = new QAction(tr("Browser Favorites"), otherKeysMenu);
temp = AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Favorites);
tempAction->setData(temp);
otherKeysMenu->addAction(tempAction);
tempAction = new QAction(tr("Browser Forward"), otherKeysMenu);
temp = AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Forward);
tempAction->setData(temp);
otherKeysMenu->addAction(tempAction);
tempAction = new QAction(tr("Browser Home"), otherKeysMenu);
temp = AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_HomePage);
tempAction->setData(temp);
otherKeysMenu->addAction(tempAction);
tempAction = new QAction(tr("Browser Refresh"), otherKeysMenu);
temp = AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Refresh);
tempAction->setData(temp);
otherKeysMenu->addAction(tempAction);
tempAction = new QAction(tr("Browser Search"), otherKeysMenu);
temp = AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Search);
tempAction->setData(temp);
otherKeysMenu->addAction(tempAction);
tempAction = new QAction(tr("Browser Stop"), otherKeysMenu);
temp = AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Stop);
tempAction->setData(temp);
otherKeysMenu->addAction(tempAction);
tempAction = new QAction(tr("Calc"), otherKeysMenu);
temp = AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Launch1);
tempAction->setData(temp);
otherKeysMenu->addAction(tempAction);
tempAction = new QAction(tr("Email"), otherKeysMenu);
temp = AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_LaunchMail);
tempAction->setData(temp);
otherKeysMenu->addAction(tempAction);
tempAction = new QAction(tr("Media"), otherKeysMenu);
temp = AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_LaunchMedia);
tempAction->setData(temp);
otherKeysMenu->addAction(tempAction);
tempAction = new QAction(tr("Media Next"), otherKeysMenu);
temp = AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_MediaNext);
tempAction->setData(temp);
otherKeysMenu->addAction(tempAction);
tempAction = new QAction(tr("Media Play"), otherKeysMenu);
temp = AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_MediaPlay);
tempAction->setData(temp);
otherKeysMenu->addAction(tempAction);
tempAction = new QAction(tr("Media Previous"), otherKeysMenu);
temp = AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_MediaPrevious);
tempAction->setData(temp);
otherKeysMenu->addAction(tempAction);
tempAction = new QAction(tr("Media Stop"), otherKeysMenu);
temp = AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_MediaStop);
tempAction->setData(temp);
otherKeysMenu->addAction(tempAction);
tempAction = new QAction(tr("Search"), otherKeysMenu);
temp = AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_Search);
tempAction->setData(temp);
otherKeysMenu->addAction(tempAction);
tempAction = new QAction(tr("Volume Down"), otherKeysMenu);
temp = AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_VolumeDown);
tempAction->setData(temp);
otherKeysMenu->addAction(tempAction);
tempAction = new QAction(tr("Volume Mute"), otherKeysMenu);
temp = AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_VolumeMute);
tempAction->setData(temp);
otherKeysMenu->addAction(tempAction);
tempAction = new QAction(tr("Volume Up"), otherKeysMenu);
temp = AntKeyMapper::getInstance()->returnVirtualKey(Qt::Key_VolumeUp);
tempAction->setData(temp);
otherKeysMenu->addAction(tempAction);
otherKeysPushbutton->setMenu(otherKeysMenu);
return otherKeysPushbutton;
}
void VirtualKeyboardMouseWidget::otherKeysActionSingle(bool triggered)
{
Q_UNUSED(triggered);
QAction *tempAction = static_cast<QAction*>(sender());
unsigned int virtualkey = tempAction->data().toInt();
processSingleKeyboardSelection(virtualkey, AntKeyMapper::getInstance()->returnQtKey(virtualkey));
}
void VirtualKeyboardMouseWidget::otherKeysActionAdvanced(bool triggered)
{
Q_UNUSED(triggered);
QAction *tempAction = static_cast<QAction*>(sender());
unsigned int virtualkey = tempAction->data().toInt();
processAdvancedKeyboardSelection(virtualkey, AntKeyMapper::getInstance()->returnQtKey(virtualkey));
}
``` | /content/code_sandbox/src/keyboard/virtualkeyboardmousewidget.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 7,887 |
```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 MOUSEDPADSETTINGSDIALOG_H
#define MOUSEDPADSETTINGSDIALOG_H
#include "mousesettingsdialog.h"
#include "springmoderegionpreview.h"
#include <joydpad.h>
#include "uihelpers/mousedpadsettingsdialoghelper.h"
class MouseDPadSettingsDialog : public MouseSettingsDialog
{
Q_OBJECT
public:
explicit MouseDPadSettingsDialog(JoyDPad *dpad, QWidget *parent = 0);
protected:
void selectCurrentMouseModePreset();
void calculateSpringPreset();
void calculateMouseSpeedPreset();
void calculateWheelSpeedPreset();
void updateWindowTitleDPadName();
void calculateReleaseSpringRadius();
void calculateExtraAccelerationCurve();
JoyDPad *dpad;
SpringModeRegionPreview *springPreviewWidget;
MouseDpadSettingsDialogHelper helper;
signals:
public slots:
void changeMouseMode(int index);
void changeMouseCurve(int index);
void updateConfigHorizontalSpeed(int value);
void updateConfigVerticalSpeed(int value);
void updateSpringWidth(int value);
void updateSpringHeight(int value);
void updateSensitivity(double value);
void updateAccelerationCurvePresetComboBox();
void updateWheelSpeedHorizontalSpeed(int value);
void updateWheelSpeedVerticalSpeed(int value);
void updateSpringRelativeStatus(bool value);
private slots:
void updateReleaseSpringRadius(int value);
void updateExtraAccelerationCurve(int index);
};
#endif // MOUSEDPADSETTINGSDIALOG_H
``` | /content/code_sandbox/src/mousedialog/mousedpadsettingsdialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 408 |
```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 <QApplication>
#include <QDesktopWidget>
#include <QPainter>
#include <QPaintEvent>
#include "springmoderegionpreview.h"
SpringModeRegionPreview::SpringModeRegionPreview(int width, int height, QWidget *parent) :
#if defined(Q_OS_WIN)
QWidget(parent, Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint)
#else
QWidget(parent, Qt::FramelessWindowHint)
#endif
{
int tempwidth = adjustSpringSizeWidth(width);
int tempheight = adjustSpringSizeHeight(height);
setAttribute(Qt::WA_NoSystemBackground);
setAttribute(Qt::WA_TranslucentBackground);
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
setAttribute(Qt::WA_PaintOnScreen);
#endif
setAttribute(Qt::WA_ShowWithoutActivating);
setWindowTitle(tr("Spring Mode Preview"));
if (tempwidth >= 2 && tempheight >= 2)
{
int cw = (qApp->desktop()->width() / 2) - (tempwidth / 2);
int ch = (qApp->desktop()->height() / 2) - (tempheight / 2);
setGeometry(cw, ch, tempwidth, tempheight);
show();
}
else
{
resize(0, 0);
move(0, 0);
}
}
void SpringModeRegionPreview::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainter p(this);
QPen border;
border.setWidth(3);
border.setColor(Qt::black);
p.setPen(border);
p.drawRect(1, 1, width()-3, height()-3);
}
int SpringModeRegionPreview::adjustSpringSizeWidth(int width)
{
int tempwidth = size().width();
if (width >= 2)
{
tempwidth = width;
}
else
{
tempwidth = 0;
}
return tempwidth;
}
int SpringModeRegionPreview::adjustSpringSizeHeight(int height)
{
int tempheight = size().height();
if (height >= 2)
{
tempheight = height;
}
else
{
tempheight = 0;
}
return tempheight;
}
void SpringModeRegionPreview::setSpringWidth(int width)
{
int tempwidth = adjustSpringSizeWidth(width);
int height = size().height();
#ifdef Q_OS_UNIX
hide();
#endif
if (tempwidth >= 2 && height >= 2)
{
int cw = (qApp->desktop()->width() / 2) - (tempwidth / 2);
int ch = (qApp->desktop()->height() / 2) - (height / 2);
setGeometry(cw, ch, tempwidth, height);
if (!isVisible())
{
show();
}
}
else
{
#ifndef Q_OS_UNIX
hide();
#endif
resize(tempwidth, height);
move(0, 0);
}
}
void SpringModeRegionPreview::setSpringHeight(int height)
{
int tempheight = adjustSpringSizeHeight(height);
int width = size().width();
#ifdef Q_OS_UNIX
hide();
#endif
if (width >= 2 && tempheight >= 2)
{
int cw = (qApp->desktop()->width() / 2) - (width / 2);
int ch = (qApp->desktop()->height() / 2) - (tempheight / 2);
setGeometry(cw, ch, width, tempheight);
if (!isVisible())
{
show();
}
}
else
{
#ifndef Q_OS_UNIX
hide();
#endif
resize(width, tempheight);
move(0, 0);
}
}
void SpringModeRegionPreview::setSpringSize(int width, int height)
{
int tempwidth = adjustSpringSizeWidth(width);
int tempheight = adjustSpringSizeHeight(height);
int cw = (qApp->desktop()->width() / 2) - (tempwidth / 2);
int ch = (qApp->desktop()->height() / 2) - (height / 2);
resize(tempwidth, tempheight);
move(cw, ch);
}
``` | /content/code_sandbox/src/mousedialog/springmoderegionpreview.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 1,020 |
```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 "mousedpadsettingsdialog.h"
#include "ui_mousesettingsdialog.h"
#include <QSpinBox>
#include <QComboBox>
#include <inputdevice.h>
#include <setjoystick.h>
MouseDPadSettingsDialog::MouseDPadSettingsDialog(JoyDPad *dpad, QWidget *parent) :
MouseSettingsDialog(parent),
helper(dpad)
{
setAttribute(Qt::WA_DeleteOnClose);
resize(size().width(), 450);
//setGeometry(geometry().x(), geometry().y(), size().width(), 450);
this->dpad = dpad;
helper.moveToThread(dpad->thread());
calculateMouseSpeedPreset();
selectCurrentMouseModePreset();
calculateSpringPreset();
if (dpad->getButtonsPresetSensitivity() > 0.0)
{
ui->sensitivityDoubleSpinBox->setValue(dpad->getButtonsPresetSensitivity());
}
updateAccelerationCurvePresetComboBox();
updateWindowTitleDPadName();
if (ui->mouseModeComboBox->currentIndex() == 2)
{
springPreviewWidget = new SpringModeRegionPreview(ui->springWidthSpinBox->value(),
ui->springHeightSpinBox->value());
}
else
{
springPreviewWidget = new SpringModeRegionPreview(0, 0);
}
calculateWheelSpeedPreset();
if (dpad->isRelativeSpring())
{
ui->relativeSpringCheckBox->setChecked(true);
}
double easingDuration = dpad->getButtonsEasingDuration();
ui->easingDoubleSpinBox->setValue(easingDuration);
ui->extraAccelerationGroupBox->setVisible(false);
calculateReleaseSpringRadius();
calculateExtraAccelerationCurve();
changeSpringSectionStatus(ui->mouseModeComboBox->currentIndex());
changeSettingsWidgetStatus(ui->accelerationComboBox->currentIndex());
connect(this, SIGNAL(finished(int)), springPreviewWidget, SLOT(deleteLater()));
connect(ui->mouseModeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeMouseMode(int)));
connect(ui->accelerationComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeMouseCurve(int)));
connect(ui->horizontalSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateConfigHorizontalSpeed(int)));
connect(ui->verticalSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateConfigVerticalSpeed(int)));
connect(ui->springWidthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateSpringWidth(int)));
connect(ui->springWidthSpinBox, SIGNAL(valueChanged(int)), springPreviewWidget, SLOT(setSpringWidth(int)));
connect(ui->springHeightSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateSpringHeight(int)));
connect(ui->springHeightSpinBox, SIGNAL(valueChanged(int)), springPreviewWidget, SLOT(setSpringHeight(int)));
connect(ui->relativeSpringCheckBox, SIGNAL(clicked(bool)), this, SLOT(updateSpringRelativeStatus(bool)));
connect(ui->sensitivityDoubleSpinBox, SIGNAL(valueChanged(double)), this, SLOT(updateSensitivity(double)));
connect(ui->wheelHoriSpeedSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateWheelSpeedHorizontalSpeed(int)));
connect(ui->wheelVertSpeedSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateWheelSpeedVerticalSpeed(int)));
connect(ui->easingDoubleSpinBox, SIGNAL(valueChanged(double)), dpad, SLOT(setButtonsEasingDuration(double)));
connect(ui->releaseSpringRadiusspinBox, SIGNAL(valueChanged(int)), this, SLOT(updateReleaseSpringRadius(int)));
connect(ui->extraAccelCurveComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(updateExtraAccelerationCurve(int)));
JoyButtonMouseHelper *mouseHelper = JoyButton::getMouseHelper();
connect(mouseHelper, SIGNAL(mouseCursorMoved(int,int,int)), this, SLOT(updateMouseCursorStatusLabels(int,int,int)));
connect(mouseHelper, SIGNAL(mouseSpringMoved(int,int)), this, SLOT(updateMouseSpringStatusLabels(int,int)));
lastMouseStatUpdate.start();
}
void MouseDPadSettingsDialog::changeMouseMode(int index)
{
if (index == 1)
{
dpad->setButtonsMouseMode(JoyButton::MouseCursor);
if (springPreviewWidget->isVisible())
{
springPreviewWidget->hide();
}
}
else if (index == 2)
{
dpad->setButtonsMouseMode(JoyButton::MouseSpring);
if (!springPreviewWidget->isVisible())
{
springPreviewWidget->setSpringWidth(ui->springWidthSpinBox->value());
springPreviewWidget->setSpringHeight(ui->springHeightSpinBox->value());
}
}
}
void MouseDPadSettingsDialog::changeMouseCurve(int index)
{
JoyButton::JoyMouseCurve temp = MouseSettingsDialog::getMouseCurveForIndex(index);
dpad->setButtonsMouseCurve(temp);
}
void MouseDPadSettingsDialog::updateConfigHorizontalSpeed(int value)
{
QHashIterator<int, JoyDPadButton*> iter(*dpad->getButtons());
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
button->setMouseSpeedX(value);
}
}
void MouseDPadSettingsDialog::updateConfigVerticalSpeed(int value)
{
QHashIterator<int, JoyDPadButton*> iter(*dpad->getButtons());
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
button->setMouseSpeedY(value);
}
}
void MouseDPadSettingsDialog::updateSpringWidth(int value)
{
dpad->setButtonsSpringWidth(value);
}
void MouseDPadSettingsDialog::updateSpringHeight(int value)
{
dpad->setButtonsSpringHeight(value);
}
void MouseDPadSettingsDialog::selectCurrentMouseModePreset()
{
bool presetDefined = dpad->hasSameButtonsMouseMode();
if (presetDefined)
{
JoyButton::JoyMouseMovementMode mode = dpad->getButtonsPresetMouseMode();
if (mode == JoyButton::MouseCursor)
{
ui->mouseModeComboBox->setCurrentIndex(1);
}
else if (mode == JoyButton::MouseSpring)
{
ui->mouseModeComboBox->setCurrentIndex(2);
}
}
else
{
ui->mouseModeComboBox->setCurrentIndex(0);
}
}
void MouseDPadSettingsDialog::calculateSpringPreset()
{
int tempWidth = dpad->getButtonsPresetSpringWidth();
int tempHeight = dpad->getButtonsPresetSpringHeight();
if (tempWidth > 0)
{
ui->springWidthSpinBox->setValue(tempWidth);
}
if (tempHeight > 0)
{
ui->springHeightSpinBox->setValue(tempHeight);
}
}
void MouseDPadSettingsDialog::calculateMouseSpeedPreset()
{
QHashIterator<int, JoyDPadButton*> iter(*dpad->getButtons());
int tempMouseSpeedX = 0;
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
tempMouseSpeedX = qMax(tempMouseSpeedX, button->getMouseSpeedX());
}
iter.toFront();
int tempMouseSpeedY = 0;
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
tempMouseSpeedY = qMax(tempMouseSpeedY, button->getMouseSpeedY());
}
ui->horizontalSpinBox->setValue(tempMouseSpeedX);
ui->verticalSpinBox->setValue(tempMouseSpeedY);
}
void MouseDPadSettingsDialog::updateSensitivity(double value)
{
dpad->setButtonsSensitivity(value);
}
void MouseDPadSettingsDialog::updateAccelerationCurvePresetComboBox()
{
JoyButton::JoyMouseCurve temp = dpad->getButtonsPresetMouseCurve();
MouseSettingsDialog::updateAccelerationCurvePresetComboBox(temp);
}
void MouseDPadSettingsDialog::calculateWheelSpeedPreset()
{
QHashIterator<int, JoyDPadButton*> iter(*dpad->getButtons());
int tempWheelSpeedX = 0;
int tempWheelSpeedY = 0;
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
tempWheelSpeedX = qMax(tempWheelSpeedX, button->getWheelSpeedX());
tempWheelSpeedY = qMax(tempWheelSpeedY, button->getWheelSpeedY());
}
ui->wheelHoriSpeedSpinBox->setValue(tempWheelSpeedX);
ui->wheelVertSpeedSpinBox->setValue(tempWheelSpeedY);
}
void MouseDPadSettingsDialog::updateWheelSpeedHorizontalSpeed(int value)
{
dpad->setButtonsWheelSpeedX(value);
}
void MouseDPadSettingsDialog::updateWheelSpeedVerticalSpeed(int value)
{
dpad->setButtonsWheelSpeedY(value);
}
void MouseDPadSettingsDialog::updateSpringRelativeStatus(bool value)
{
dpad->setButtonsSpringRelativeStatus(value);
}
void MouseDPadSettingsDialog::updateWindowTitleDPadName()
{
QString temp = QString(tr("Mouse Settings")).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);
}
void MouseDPadSettingsDialog::updateReleaseSpringRadius(int value)
{
dpad->setButtonsSpringDeadCircleMultiplier(value);
}
void MouseDPadSettingsDialog::calculateReleaseSpringRadius()
{
ui->releaseSpringRadiusspinBox->setValue(dpad->getButtonsSpringDeadCircleMultiplier());
}
void MouseDPadSettingsDialog::calculateExtraAccelerationCurve()
{
JoyButton::JoyExtraAccelerationCurve curve = dpad->getButtonsExtraAccelerationCurve();
updateExtraAccelerationCurvePresetComboBox(curve);
}
void MouseDPadSettingsDialog::updateExtraAccelerationCurve(int index)
{
JoyButton::JoyExtraAccelerationCurve temp = JoyButton::LinearAccelCurve;
if (index > 0)
{
InputDevice *device = dpad->getParentSet()->getInputDevice();
PadderCommon::lockInputDevices();
QMetaObject::invokeMethod(device, "haltServices", Qt::BlockingQueuedConnection);
temp = getExtraAccelCurveForIndex(index);
dpad->setButtonsExtraAccelerationCurve(temp);
PadderCommon::unlockInputDevices();
}
}
``` | /content/code_sandbox/src/mousedialog/mousedpadsettingsdialog.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 2,365 |
```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 MOUSEBUTTONSETTINGSDIALOG_H
#define MOUSEBUTTONSETTINGSDIALOG_H
#include "mousesettingsdialog.h"
#include "springmoderegionpreview.h"
#include <joybutton.h>
#include "uihelpers/mousebuttonsettingsdialoghelper.h"
class MouseButtonSettingsDialog : public MouseSettingsDialog
{
Q_OBJECT
public:
explicit MouseButtonSettingsDialog(JoyButton *button, QWidget *parent = 0);
protected:
void selectCurrentMouseModePreset();
void calculateSpringPreset();
void calculateMouseSpeedPreset();
void updateWindowTitleButtonName();
void calculateExtraAccelerationCurve();
JoyButton *button;
SpringModeRegionPreview *springPreviewWidget;
MouseButtonSettingsDialogHelper helper;
signals:
public slots:
void changeMouseMode(int index);
void changeMouseCurve(int index);
void updateConfigHorizontalSpeed(int value);
void updateConfigVerticalSpeed(int value);
void updateSpringWidth(int value);
void updateSpringHeight(int value);
void updateSensitivity(double value);
void updateAccelerationCurvePresetComboBox();
//void updateSpringRelativeStatus(bool value);
private slots:
void updateExtraAccelerationCurve(int index);
};
#endif // MOUSEBUTTONSETTINGSDIALOG_H
``` | /content/code_sandbox/src/mousedialog/mousebuttonsettingsdialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 351 |
```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 "mousecontrolsticksettingsdialog.h"
#include "ui_mousesettingsdialog.h"
#include <QSpinBox>
#include <QComboBox>
#include <inputdevice.h>
#include <setjoystick.h>
MouseControlStickSettingsDialog::MouseControlStickSettingsDialog(JoyControlStick *stick, QWidget *parent) :
MouseSettingsDialog(parent),
helper(stick)
{
setAttribute(Qt::WA_DeleteOnClose);
this->stick = stick;
helper.moveToThread(stick->thread());
calculateMouseSpeedPreset();
selectCurrentMouseModePreset();
calculateSpringPreset();
if (stick->getButtonsPresetSensitivity() > 0.0)
{
ui->sensitivityDoubleSpinBox->setValue(stick->getButtonsPresetSensitivity());
}
updateAccelerationCurvePresetComboBox();
updateWindowTitleStickName();
if (ui->mouseModeComboBox->currentIndex() == 2)
{
springPreviewWidget = new SpringModeRegionPreview(ui->springWidthSpinBox->value(),
ui->springHeightSpinBox->value());
}
else
{
springPreviewWidget = new SpringModeRegionPreview(0, 0);
}
calculateWheelSpeedPreset();
if (stick->isRelativeSpring())
{
ui->relativeSpringCheckBox->setChecked(true);
}
double easingDuration = stick->getButtonsEasingDuration();
ui->easingDoubleSpinBox->setValue(easingDuration);
calculateExtraAccelrationStatus();
calculateExtraAccelerationMultiplier();
calculateStartAccelerationMultiplier();
calculateMinAccelerationThreshold();
calculateMaxAccelerationThreshold();
calculateAccelExtraDuration();
calculateReleaseSpringRadius();
calculateExtraAccelerationCurve();
changeSpringSectionStatus(ui->mouseModeComboBox->currentIndex());
changeSettingsWidgetStatus(ui->accelerationComboBox->currentIndex());
connect(this, SIGNAL(finished(int)), springPreviewWidget, SLOT(deleteLater()));
connect(ui->mouseModeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeMouseMode(int)));
connect(ui->accelerationComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeMouseCurve(int)));
connect(ui->horizontalSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateConfigHorizontalSpeed(int)));
connect(ui->verticalSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateConfigVerticalSpeed(int)));
connect(ui->springWidthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateSpringWidth(int)));
connect(ui->springWidthSpinBox, SIGNAL(valueChanged(int)), springPreviewWidget, SLOT(setSpringWidth(int)));
connect(ui->springHeightSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateSpringHeight(int)));
connect(ui->springHeightSpinBox, SIGNAL(valueChanged(int)), springPreviewWidget, SLOT(setSpringHeight(int)));
connect(ui->relativeSpringCheckBox, SIGNAL(clicked(bool)), this, SLOT(updateSpringRelativeStatus(bool)));
connect(ui->sensitivityDoubleSpinBox, SIGNAL(valueChanged(double)), this, SLOT(updateSensitivity(double)));
connect(ui->wheelHoriSpeedSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateWheelSpeedHorizontalSpeed(int)));
connect(ui->wheelVertSpeedSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateWheelSpeedVerticalSpeed(int)));
connect(ui->easingDoubleSpinBox, SIGNAL(valueChanged(double)), stick, SLOT(setButtonsEasingDuration(double)));
connect(ui->extraAccelerationGroupBox, SIGNAL(clicked(bool)), &helper, SLOT(updateExtraAccelerationStatus(bool)));
connect(ui->extraAccelDoubleSpinBox, SIGNAL(valueChanged(double)), &helper, SLOT(updateExtraAccelerationMultiplier(double)));
connect(ui->minMultiDoubleSpinBox, SIGNAL(valueChanged(double)), &helper, SLOT(updateStartMultiPercentage(double)));
connect(ui->minThresholdDoubleSpinBox, SIGNAL(valueChanged(double)), &helper, SLOT(updateMinAccelThreshold(double)));
connect(ui->maxThresholdDoubleSpinBox, SIGNAL(valueChanged(double)), &helper, SLOT(updateMaxAccelThreshold(double)));
connect(ui->accelExtraDurationDoubleSpinBox, SIGNAL(valueChanged(double)), &helper, SLOT(updateAccelExtraDuration(double)));
connect(ui->releaseSpringRadiusspinBox, SIGNAL(valueChanged(int)), &helper, SLOT(updateReleaseSpringRadius(int)));
connect(ui->extraAccelCurveComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(updateExtraAccelerationCurve(int)));
}
void MouseControlStickSettingsDialog::changeMouseMode(int index)
{
if (index == 1)
{
stick->setButtonsMouseMode(JoyButton::MouseCursor);
if (springPreviewWidget->isVisible())
{
springPreviewWidget->hide();
}
}
else if (index == 2)
{
stick->setButtonsMouseMode(JoyButton::MouseSpring);
if (!springPreviewWidget->isVisible())
{
springPreviewWidget->setSpringWidth(ui->springWidthSpinBox->value());
springPreviewWidget->setSpringHeight(ui->springHeightSpinBox->value());
}
stick->setButtonsExtraAccelerationStatus(false);
}
}
void MouseControlStickSettingsDialog::changeMouseCurve(int index)
{
JoyButton::JoyMouseCurve temp = MouseSettingsDialog::getMouseCurveForIndex(index);
stick->setButtonsMouseCurve(temp);
}
void MouseControlStickSettingsDialog::updateConfigHorizontalSpeed(int value)
{
QHashIterator<JoyControlStick::JoyStickDirections, JoyControlStickButton*> iter(*stick->getButtons());
while (iter.hasNext())
{
JoyControlStickButton *button = iter.next().value();
button->setMouseSpeedX(value);
}
}
void MouseControlStickSettingsDialog::updateConfigVerticalSpeed(int value)
{
QHashIterator<JoyControlStick::JoyStickDirections, JoyControlStickButton*> iter(*stick->getButtons());
while (iter.hasNext())
{
JoyControlStickButton *button = iter.next().value();
button->setMouseSpeedY(value);
}
}
void MouseControlStickSettingsDialog::updateSpringWidth(int value)
{
stick->setButtonsSpringWidth(value);
}
void MouseControlStickSettingsDialog::updateSpringHeight(int value)
{
stick->setButtonsSpringHeight(value);
}
void MouseControlStickSettingsDialog::selectCurrentMouseModePreset()
{
bool presetDefined = stick->hasSameButtonsMouseMode();
if (presetDefined)
{
JoyButton::JoyMouseMovementMode mode = stick->getButtonsPresetMouseMode();
if (mode == JoyButton::MouseCursor)
{
ui->mouseModeComboBox->setCurrentIndex(1);
}
else if (mode == JoyButton::MouseSpring)
{
ui->mouseModeComboBox->setCurrentIndex(2);
}
}
else
{
ui->mouseModeComboBox->setCurrentIndex(0);
}
}
void MouseControlStickSettingsDialog::calculateSpringPreset()
{
int tempWidth = stick->getButtonsPresetSpringWidth();
int tempHeight = stick->getButtonsPresetSpringHeight();
if (tempWidth > 0)
{
ui->springWidthSpinBox->setValue(tempWidth);
}
if (tempHeight > 0)
{
ui->springHeightSpinBox->setValue(tempHeight);
}
}
void MouseControlStickSettingsDialog::calculateMouseSpeedPreset()
{
QHashIterator<JoyControlStick::JoyStickDirections, JoyControlStickButton*> iter(*stick->getButtons());
int tempMouseSpeedX = 0;
while (iter.hasNext())
{
JoyControlStickButton *button = iter.next().value();
tempMouseSpeedX = qMax(tempMouseSpeedX, button->getMouseSpeedX());
}
iter.toFront();
int tempMouseSpeedY = 0;
while (iter.hasNext())
{
JoyControlStickButton *button = iter.next().value();
tempMouseSpeedY = qMax(tempMouseSpeedY, button->getMouseSpeedY());
}
ui->horizontalSpinBox->setValue(tempMouseSpeedX);
ui->verticalSpinBox->setValue(tempMouseSpeedY);
}
void MouseControlStickSettingsDialog::updateSensitivity(double value)
{
stick->setButtonsSensitivity(value);
}
void MouseControlStickSettingsDialog::updateAccelerationCurvePresetComboBox()
{
JoyButton::JoyMouseCurve temp = stick->getButtonsPresetMouseCurve();
MouseSettingsDialog::updateAccelerationCurvePresetComboBox(temp);
}
void MouseControlStickSettingsDialog::calculateWheelSpeedPreset()
{
QHashIterator<JoyControlStick::JoyStickDirections, JoyControlStickButton*> iter(*stick->getButtons());
int tempWheelSpeedX = 0;
int tempWheelSpeedY = 0;
while (iter.hasNext())
{
JoyControlStickButton *button = iter.next().value();
tempWheelSpeedX = qMax(tempWheelSpeedX, button->getWheelSpeedX());
tempWheelSpeedY = qMax(tempWheelSpeedY, button->getWheelSpeedY());
}
ui->wheelHoriSpeedSpinBox->setValue(tempWheelSpeedX);
ui->wheelVertSpeedSpinBox->setValue(tempWheelSpeedY);
}
void MouseControlStickSettingsDialog::updateWheelSpeedHorizontalSpeed(int value)
{
stick->setButtonsWheelSpeedX(value);
}
void MouseControlStickSettingsDialog::updateWheelSpeedVerticalSpeed(int value)
{
stick->setButtonsWheelSpeedY(value);
}
void MouseControlStickSettingsDialog::updateSpringRelativeStatus(bool value)
{
stick->setButtonsSpringRelativeStatus(value);
}
void MouseControlStickSettingsDialog::updateWindowTitleStickName()
{
QString temp = QString(tr("Mouse Settings")).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 MouseControlStickSettingsDialog::calculateExtraAccelrationStatus()
{
if (stick->getButtonsExtraAccelerationStatus())
{
ui->extraAccelerationGroupBox->setChecked(true);
}
}
void MouseControlStickSettingsDialog::calculateExtraAccelerationMultiplier()
{
ui->extraAccelDoubleSpinBox->setValue(stick->getButtonsExtraAccelerationMultiplier());
}
void MouseControlStickSettingsDialog::calculateStartAccelerationMultiplier()
{
ui->minMultiDoubleSpinBox->setValue(stick->getButtonsStartAccelerationMultiplier());
}
void MouseControlStickSettingsDialog::calculateMinAccelerationThreshold()
{
ui->minThresholdDoubleSpinBox->setValue(stick->getButtonsMinAccelerationThreshold());
}
void MouseControlStickSettingsDialog::calculateMaxAccelerationThreshold()
{
ui->maxThresholdDoubleSpinBox->setValue(stick->getButtonsMaxAccelerationThreshold());
}
void MouseControlStickSettingsDialog::calculateAccelExtraDuration()
{
ui->accelExtraDurationDoubleSpinBox->setValue(stick->getButtonsAccelerationEasingDuration());
}
void MouseControlStickSettingsDialog::calculateReleaseSpringRadius()
{
ui->releaseSpringRadiusspinBox->setValue(stick->getButtonsSpringDeadCircleMultiplier());
}
void MouseControlStickSettingsDialog::calculateExtraAccelerationCurve()
{
JoyButton::JoyExtraAccelerationCurve curve = stick->getButtonsExtraAccelerationCurve();
updateExtraAccelerationCurvePresetComboBox(curve);
}
void MouseControlStickSettingsDialog::updateExtraAccelerationCurve(int index)
{
JoyButton::JoyExtraAccelerationCurve temp = getExtraAccelCurveForIndex(index);
if (index > 0)
{
//PadderCommon::lockInputDevices();
//InputDevice *device = stick->getParentSet()->getInputDevice();
//QMetaObject::invokeMethod(device, "haltServices", Qt::BlockingQueuedConnection);
PadderCommon::inputDaemonMutex.lock();
stick->setButtonsExtraAccelCurve(temp);
PadderCommon::inputDaemonMutex.unlock();
//PadderCommon::unlockInputDevices();
}
}
``` | /content/code_sandbox/src/mousedialog/mousecontrolsticksettingsdialog.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 2,647 |
```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 MOUSECONTROLSTICKSETTINGSDIALOG_H
#define MOUSECONTROLSTICKSETTINGSDIALOG_H
#include "mousesettingsdialog.h"
#include "springmoderegionpreview.h"
#include <joycontrolstick.h>
#include "uihelpers/mousecontrolsticksettingsdialoghelper.h"
class MouseControlStickSettingsDialog : public MouseSettingsDialog
{
Q_OBJECT
public:
explicit MouseControlStickSettingsDialog(JoyControlStick *stick, QWidget *parent=0);
protected:
void selectCurrentMouseModePreset();
void calculateSpringPreset();
void calculateMouseSpeedPreset();
void calculateWheelSpeedPreset();
void updateWindowTitleStickName();
void calculateExtraAccelrationStatus();
void calculateExtraAccelerationMultiplier();
void calculateStartAccelerationMultiplier();
void calculateMinAccelerationThreshold();
void calculateMaxAccelerationThreshold();
void calculateAccelExtraDuration();
void calculateReleaseSpringRadius();
void calculateExtraAccelerationCurve();
JoyControlStick *stick;
SpringModeRegionPreview *springPreviewWidget;
MouseControlStickSettingsDialogHelper helper;
signals:
public slots:
void changeMouseMode(int index);
void changeMouseCurve(int index);
void updateConfigHorizontalSpeed(int value);
void updateConfigVerticalSpeed(int value);
void updateSpringWidth(int value);
void updateSpringHeight(int value);
void updateSensitivity(double value);
void updateAccelerationCurvePresetComboBox();
void updateWheelSpeedHorizontalSpeed(int value);
void updateWheelSpeedVerticalSpeed(int value);
void updateSpringRelativeStatus(bool value);
private slots:
void updateExtraAccelerationCurve(int index);
};
#endif // MOUSECONTROLSTICKSETTINGSDIALOG_H
``` | /content/code_sandbox/src/mousedialog/mousecontrolsticksettingsdialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 445 |
```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 "mousebuttonsettingsdialog.h"
#include "ui_mousesettingsdialog.h"
#include <QSpinBox>
#include <QCheckBox>
#include <QComboBox>
#include <inputdevice.h>
#include <setjoystick.h>
MouseButtonSettingsDialog::MouseButtonSettingsDialog(JoyButton *button, QWidget *parent) :
MouseSettingsDialog(parent),
helper(button)
{
setAttribute(Qt::WA_DeleteOnClose);
resize(size().width(), 450);
//setGeometry(geometry().x(), geometry().y(), size().width(), 450);
this->button = button;
helper.moveToThread(button->thread());
calculateMouseSpeedPreset();
selectCurrentMouseModePreset();
calculateSpringPreset();
if (button->getSensitivity() > 0.0)
{
ui->sensitivityDoubleSpinBox->setValue(button->getSensitivity());
}
updateAccelerationCurvePresetComboBox();
updateWindowTitleButtonName();
if (ui->mouseModeComboBox->currentIndex() == 2)
{
springPreviewWidget = new SpringModeRegionPreview(ui->springWidthSpinBox->value(),
ui->springHeightSpinBox->value());
}
else
{
springPreviewWidget = new SpringModeRegionPreview(0, 0);
}
ui->wheelHoriSpeedSpinBox->setValue(button->getWheelSpeedX());
ui->wheelVertSpeedSpinBox->setValue(button->getWheelSpeedY());
if (button->isRelativeSpring())
{
ui->relativeSpringCheckBox->setChecked(true);
}
double easingDuration = button->getEasingDuration();
ui->easingDoubleSpinBox->setValue(easingDuration);
if (button->isPartRealAxis())
{
ui->extraAccelerationGroupBox->setChecked(button->isExtraAccelerationEnabled());
ui->extraAccelDoubleSpinBox->setValue(button->getExtraAccelerationMultiplier());
ui->minMultiDoubleSpinBox->setValue(button->getStartAccelMultiplier());
ui->minThresholdDoubleSpinBox->setValue(button->getMinAccelThreshold());
ui->maxThresholdDoubleSpinBox->setValue(button->getMaxAccelThreshold());
ui->accelExtraDurationDoubleSpinBox->setValue(button->getAccelExtraDuration());
}
else
{
ui->extraAccelerationGroupBox->setVisible(false);
}
ui->releaseSpringRadiusspinBox->setValue(button->getSpringDeadCircleMultiplier());
calculateExtraAccelerationCurve();
changeSpringSectionStatus(ui->mouseModeComboBox->currentIndex());
changeSettingsWidgetStatus(ui->accelerationComboBox->currentIndex());
connect(this, SIGNAL(finished(int)), springPreviewWidget, SLOT(deleteLater()));
connect(ui->mouseModeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeMouseMode(int)));
connect(ui->accelerationComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeMouseCurve(int)));
connect(ui->horizontalSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateConfigHorizontalSpeed(int)));
connect(ui->verticalSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateConfigVerticalSpeed(int)));
connect(ui->springWidthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateSpringWidth(int)));
connect(ui->springWidthSpinBox, SIGNAL(valueChanged(int)), springPreviewWidget, SLOT(setSpringWidth(int)));
connect(ui->springHeightSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateSpringHeight(int)));
connect(ui->springHeightSpinBox, SIGNAL(valueChanged(int)), springPreviewWidget, SLOT(setSpringHeight(int)));
connect(ui->relativeSpringCheckBox, SIGNAL(clicked(bool)), &helper, SLOT(updateSpringRelativeStatus(bool)));
connect(ui->sensitivityDoubleSpinBox, SIGNAL(valueChanged(double)), this, SLOT(updateSensitivity(double)));
connect(ui->wheelHoriSpeedSpinBox, SIGNAL(valueChanged(int)), button, SLOT(setWheelSpeedX(int)));
connect(ui->wheelVertSpeedSpinBox, SIGNAL(valueChanged(int)), button, SLOT(setWheelSpeedY(int)));
connect(ui->easingDoubleSpinBox, SIGNAL(valueChanged(double)), button, SLOT(setEasingDuration(double)));
connect(ui->extraAccelerationGroupBox, SIGNAL(clicked(bool)), &helper, SLOT(updateExtraAccelerationStatus(bool)));
connect(ui->extraAccelDoubleSpinBox, SIGNAL(valueChanged(double)), &helper, SLOT(updateExtraAccelerationMultiplier(double)));
connect(ui->minMultiDoubleSpinBox, SIGNAL(valueChanged(double)), &helper, SLOT(updateStartMultiPercentage(double)));
connect(ui->minThresholdDoubleSpinBox, SIGNAL(valueChanged(double)), &helper, SLOT(updateMinAccelThreshold(double)));
connect(ui->maxThresholdDoubleSpinBox, SIGNAL(valueChanged(double)), &helper, SLOT(updateMaxAccelThreshold(double)));
connect(ui->accelExtraDurationDoubleSpinBox, SIGNAL(valueChanged(double)), &helper, SLOT(updateAccelExtraDuration(double)));
connect(ui->releaseSpringRadiusspinBox, SIGNAL(valueChanged(int)), &helper, SLOT(updateReleaseSpringRadius(int)));
connect(ui->extraAccelCurveComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(updateExtraAccelerationCurve(int)));
}
void MouseButtonSettingsDialog::changeMouseMode(int index)
{
if (index == 1)
{
button->setMouseMode(JoyButton::MouseCursor);
if (springPreviewWidget->isVisible())
{
springPreviewWidget->hide();
}
}
else if (index == 2)
{
button->setMouseMode(JoyButton::MouseSpring);
if (!springPreviewWidget->isVisible())
{
springPreviewWidget->setSpringWidth(ui->springWidthSpinBox->value());
springPreviewWidget->setSpringHeight(ui->springHeightSpinBox->value());
}
if (button->isPartRealAxis())
{
button->setExtraAccelerationStatus(false);
}
}
}
void MouseButtonSettingsDialog::changeMouseCurve(int index)
{
JoyButton::JoyMouseCurve temp = MouseSettingsDialog::getMouseCurveForIndex(index);
button->setMouseCurve(temp);
}
void MouseButtonSettingsDialog::updateConfigHorizontalSpeed(int value)
{
QMetaObject::invokeMethod(button, "setMouseSpeedX", Q_ARG(int, value));
}
void MouseButtonSettingsDialog::updateConfigVerticalSpeed(int value)
{
QMetaObject::invokeMethod(button, "setMouseSpeedY", Q_ARG(int, value));
}
void MouseButtonSettingsDialog::updateSpringWidth(int value)
{
QMetaObject::invokeMethod(button, "setSpringWidth", Q_ARG(int, value));
}
void MouseButtonSettingsDialog::updateSpringHeight(int value)
{
QMetaObject::invokeMethod(button, "setSpringHeight", Q_ARG(int, value));
}
void MouseButtonSettingsDialog::selectCurrentMouseModePreset()
{
JoyButton::JoyMouseMovementMode mode = button->getMouseMode();
if (mode == JoyButton::MouseCursor)
{
ui->mouseModeComboBox->setCurrentIndex(1);
}
else if (mode == JoyButton::MouseSpring)
{
ui->mouseModeComboBox->setCurrentIndex(2);
}
}
void MouseButtonSettingsDialog::calculateSpringPreset()
{
int tempWidth = button->getSpringWidth();
int tempHeight = button->getSpringHeight();
if (tempWidth > 0)
{
ui->springWidthSpinBox->setValue(tempWidth);
}
if (tempHeight > 0)
{
ui->springHeightSpinBox->setValue(tempHeight);
}
}
void MouseButtonSettingsDialog::calculateMouseSpeedPreset()
{
int tempMouseSpeedX = button->getMouseSpeedX();
int tempMouseSpeedY = button->getMouseSpeedY();
ui->horizontalSpinBox->setValue(tempMouseSpeedX);
ui->verticalSpinBox->setValue(tempMouseSpeedY);
}
void MouseButtonSettingsDialog::updateSensitivity(double value)
{
button->setSensitivity(value);
}
void MouseButtonSettingsDialog::updateAccelerationCurvePresetComboBox()
{
JoyButton::JoyMouseCurve temp = button->getMouseCurve();
MouseSettingsDialog::updateAccelerationCurvePresetComboBox(temp);
}
/*void MouseButtonSettingsDialog::updateSpringRelativeStatus(bool value)
{
button->setSpringRelativeStatus(value);
}
*/
void MouseButtonSettingsDialog::updateWindowTitleButtonName()
{
QString temp;
temp.append(tr("Mouse Settings - ")).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);
}
void MouseButtonSettingsDialog::calculateExtraAccelerationCurve()
{
JoyButton::JoyExtraAccelerationCurve temp = button->getExtraAccelerationCurve();
updateExtraAccelerationCurvePresetComboBox(temp);
}
void MouseButtonSettingsDialog::updateExtraAccelerationCurve(int index)
{
JoyButton::JoyExtraAccelerationCurve temp = getExtraAccelCurveForIndex(index);
if (index > 0)
{
PadderCommon::inputDaemonMutex.lock();
button->setExtraAccelerationCurve(temp);
button->setExtraAccelerationCurve(temp);
PadderCommon::inputDaemonMutex.unlock();
}
}
``` | /content/code_sandbox/src/mousedialog/mousebuttonsettingsdialog.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 2,023 |
```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 SPRINGMODEREGIONPREVIEW_H
#define SPRINGMODEREGIONPREVIEW_H
#include <QWidget>
class SpringModeRegionPreview : public QWidget
{
Q_OBJECT
public:
explicit SpringModeRegionPreview(int width = 0, int height = 0, QWidget *parent = 0);
protected:
void paintEvent(QPaintEvent *event);
int adjustSpringSizeWidth(int width);
int adjustSpringSizeHeight(int height);
signals:
public slots:
void setSpringWidth(int width);
void setSpringHeight(int height);
void setSpringSize(int width, int height);
};
#endif // SPRINGMODEREGIONPREVIEW_H
``` | /content/code_sandbox/src/mousedialog/springmoderegionpreview.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 238 |
```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 MOUSEAXISSETTINGSDIALOG_H
#define MOUSEAXISSETTINGSDIALOG_H
#include "mousesettingsdialog.h"
#include "springmoderegionpreview.h"
#include <joyaxis.h>
#include "uihelpers/mouseaxissettingsdialoghelper.h"
class MouseAxisSettingsDialog : public MouseSettingsDialog
{
Q_OBJECT
public:
explicit MouseAxisSettingsDialog(JoyAxis *axis, QWidget *parent = 0);
protected:
void selectCurrentMouseModePreset();
void calculateSpringPreset();
void calculateMouseSpeedPreset();
//void selectSmoothingPreset();
void calculateWheelSpeedPreset();
void updateWindowTitleAxisName();
void calculateExtraAccelrationStatus();
void calculateExtraAccelerationMultiplier();
void calculateStartAccelerationMultiplier();
void calculateMinAccelerationThreshold();
void calculateMaxAccelerationThreshold();
void calculateAccelExtraDuration();
void calculateReleaseSpringRadius();
void calculateExtraAccelerationCurve();
JoyAxis *axis;
SpringModeRegionPreview *springPreviewWidget;
MouseAxisSettingsDialogHelper helper;
signals:
public slots:
void changeMouseMode(int index);
void changeMouseCurve(int index);
void updateConfigHorizontalSpeed(int value);
void updateConfigVerticalSpeed(int value);
void updateSpringWidth(int value);
void updateSpringHeight(int value);
void updateSensitivity(double value);
void updateAccelerationCurvePresetComboBox();
//void updateSmoothingSetting(bool clicked);
void updateWheelSpeedHorizontalSpeed(int value);
void updateWheelSpeedVerticalSpeed(int value);
void updateSpringRelativeStatus(bool value);
private slots:
void updateExtraAccelerationCurve(int index);
};
#endif // MOUSEAXISSETTINGSDIALOG_H
``` | /content/code_sandbox/src/mousedialog/mouseaxissettingsdialog.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 455 |
```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 "mousebuttonsettingsdialoghelper.h"
MouseButtonSettingsDialogHelper::MouseButtonSettingsDialogHelper(JoyButton *button, QObject *parent) :
QObject(parent)
{
Q_ASSERT(button);
this->button = button;
}
void MouseButtonSettingsDialogHelper::updateExtraAccelerationStatus(bool checked)
{
button->setExtraAccelerationStatus(checked);
}
void MouseButtonSettingsDialogHelper::updateExtraAccelerationMultiplier(double value)
{
button->setExtraAccelerationMultiplier(value);
}
void MouseButtonSettingsDialogHelper::updateStartMultiPercentage(double value)
{
button->setStartAccelMultiplier(value);
}
void MouseButtonSettingsDialogHelper::updateMinAccelThreshold(double value)
{
button->setMinAccelThreshold(value);
}
void MouseButtonSettingsDialogHelper::updateMaxAccelThreshold(double value)
{
button->setMaxAccelThreshold(value);
}
void MouseButtonSettingsDialogHelper::updateAccelExtraDuration(double value)
{
button->setAccelExtraDuration(value);
}
void MouseButtonSettingsDialogHelper::updateReleaseSpringRadius(int value)
{
button->setSpringDeadCircleMultiplier(value);
}
void MouseButtonSettingsDialogHelper::updateSpringRelativeStatus(bool value)
{
button->setSpringRelativeStatus(value);
}
``` | /content/code_sandbox/src/mousedialog/uihelpers/mousebuttonsettingsdialoghelper.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 343 |
```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 "mousedpadsettingsdialoghelper.h"
MouseDpadSettingsDialogHelper::MouseDpadSettingsDialogHelper(JoyDPad *dpad, QObject *parent) :
QObject(parent)
{
Q_ASSERT(dpad);
this->dpad = dpad;
}
``` | /content/code_sandbox/src/mousedialog/uihelpers/mousedpadsettingsdialoghelper.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 153 |
```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 MOUSECONTROLSTICKSETTINGSDIALOGHELPER_H
#define MOUSECONTROLSTICKSETTINGSDIALOGHELPER_H
#include <QObject>
#include "joycontrolstick.h"
class MouseControlStickSettingsDialogHelper : public QObject
{
Q_OBJECT
public:
explicit MouseControlStickSettingsDialogHelper(JoyControlStick *stick, QObject *parent = 0);
protected:
JoyControlStick *stick;
signals:
public slots:
void updateExtraAccelerationStatus(bool checked);
void updateExtraAccelerationMultiplier(double value);
void updateStartMultiPercentage(double value);
void updateMinAccelThreshold(double value);
void updateMaxAccelThreshold(double value);
void updateAccelExtraDuration(double value);
void updateReleaseSpringRadius(int value);
};
#endif // MOUSECONTROLSTICKSETTINGSDIALOGHELPER_H
``` | /content/code_sandbox/src/mousedialog/uihelpers/mousecontrolsticksettingsdialoghelper.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 265 |
```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 MOUSEDPADSETTINGSDIALOGHELPER_H
#define MOUSEDPADSETTINGSDIALOGHELPER_H
#include <QObject>
#include "joydpad.h"
#include "joydpadbuttonwidget.h"
class MouseDpadSettingsDialogHelper : public QObject
{
Q_OBJECT
public:
explicit MouseDpadSettingsDialogHelper(JoyDPad *dpad, QObject *parent = 0);
protected:
JoyDPad *dpad;
signals:
public slots:
};
#endif // MOUSEDPADSETTINGSDIALOGHELPER_H
``` | /content/code_sandbox/src/mousedialog/uihelpers/mousedpadsettingsdialoghelper.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 207 |
```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 MOUSEAXISSETTINGSDIALOGHELPER_H
#define MOUSEAXISSETTINGSDIALOGHELPER_H
#include <QObject>
#include "joyaxis.h"
class MouseAxisSettingsDialogHelper : public QObject
{
Q_OBJECT
public:
explicit MouseAxisSettingsDialogHelper(JoyAxis *axis, QObject *parent = 0);
protected:
JoyAxis *axis;
signals:
public slots:
void updateExtraAccelerationStatus(bool checked);
void updateExtraAccelerationMultiplier(double value);
void updateStartMultiPercentage(double value);
void updateMinAccelThreshold(double value);
void updateMaxAccelThreshold(double value);
void updateAccelExtraDuration(double value);
void updateReleaseSpringRadius(int value);
};
#endif // MOUSEAXISSETTINGSDIALOGHELPER_H
``` | /content/code_sandbox/src/mousedialog/uihelpers/mouseaxissettingsdialoghelper.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 257 |
```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 MOUSEBUTTONSETTINGSDIALOGHELPER_H
#define MOUSEBUTTONSETTINGSDIALOGHELPER_H
#include <QObject>
#include "joybutton.h"
#include "joybuttonslot.h"
class MouseButtonSettingsDialogHelper : public QObject
{
Q_OBJECT
public:
explicit MouseButtonSettingsDialogHelper(JoyButton *button, QObject *parent = 0);
protected:
JoyButton *button;
signals:
public slots:
void updateExtraAccelerationStatus(bool checked);
void updateExtraAccelerationMultiplier(double value);
void updateStartMultiPercentage(double value);
void updateMinAccelThreshold(double value);
void updateMaxAccelThreshold(double value);
void updateAccelExtraDuration(double value);
void updateReleaseSpringRadius(int value);
void updateSpringRelativeStatus(bool value);
//void updateExtraAccelerationCurve(int index);
};
#endif // MOUSEBUTTONSETTINGSDIALOGHELPER_H
``` | /content/code_sandbox/src/mousedialog/uihelpers/mousebuttonsettingsdialoghelper.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 278 |
```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 "mouseaxissettingsdialog.h"
#include "ui_mousesettingsdialog.h"
#include <QSpinBox>
#include <QComboBox>
#include <inputdevice.h>
#include <setjoystick.h>
MouseAxisSettingsDialog::MouseAxisSettingsDialog(JoyAxis *axis, QWidget *parent) :
MouseSettingsDialog(parent),
helper(axis)
{
setAttribute(Qt::WA_DeleteOnClose);
this->axis = axis;
helper.moveToThread(axis->thread());
calculateMouseSpeedPreset();
selectCurrentMouseModePreset();
calculateSpringPreset();
if (axis->getButtonsPresetSensitivity() > 0.0)
{
ui->sensitivityDoubleSpinBox->setValue(axis->getButtonsPresetSensitivity());
}
updateAccelerationCurvePresetComboBox();
updateWindowTitleAxisName();
if (ui->mouseModeComboBox->currentIndex() == 2)
{
springPreviewWidget = new SpringModeRegionPreview(ui->springWidthSpinBox->value(),
ui->springHeightSpinBox->value());
}
else
{
springPreviewWidget = new SpringModeRegionPreview(0, 0);
}
calculateWheelSpeedPreset();
if (axis->isRelativeSpring())
{
ui->relativeSpringCheckBox->setChecked(true);
}
double easingDuration = axis->getButtonsEasingDuration();
ui->easingDoubleSpinBox->setValue(easingDuration);
calculateExtraAccelrationStatus();
calculateExtraAccelerationMultiplier();
calculateStartAccelerationMultiplier();
calculateMinAccelerationThreshold();
calculateMaxAccelerationThreshold();
calculateAccelExtraDuration();
calculateReleaseSpringRadius();
calculateExtraAccelerationCurve();
changeSpringSectionStatus(ui->mouseModeComboBox->currentIndex());
changeSettingsWidgetStatus(ui->accelerationComboBox->currentIndex());
connect(this, SIGNAL(finished(int)), springPreviewWidget, SLOT(deleteLater()));
connect(ui->mouseModeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeMouseMode(int)));
connect(ui->accelerationComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeMouseCurve(int)));
connect(ui->horizontalSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateConfigHorizontalSpeed(int)));
connect(ui->verticalSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateConfigVerticalSpeed(int)));
connect(ui->springWidthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateSpringWidth(int)));
connect(ui->springWidthSpinBox, SIGNAL(valueChanged(int)), springPreviewWidget, SLOT(setSpringWidth(int)));
connect(ui->springHeightSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateSpringHeight(int)));
connect(ui->springHeightSpinBox, SIGNAL(valueChanged(int)), springPreviewWidget, SLOT(setSpringHeight(int)));
connect(ui->relativeSpringCheckBox, SIGNAL(clicked(bool)), this, SLOT(updateSpringRelativeStatus(bool)));
connect(ui->sensitivityDoubleSpinBox, SIGNAL(valueChanged(double)), this, SLOT(updateSensitivity(double)));
connect(ui->wheelHoriSpeedSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateWheelSpeedHorizontalSpeed(int)));
connect(ui->wheelVertSpeedSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateWheelSpeedVerticalSpeed(int)));
connect(ui->easingDoubleSpinBox, SIGNAL(valueChanged(double)), axis, SLOT(setButtonsEasingDuration(double)));
connect(ui->extraAccelerationGroupBox, SIGNAL(clicked(bool)), &helper, SLOT(updateExtraAccelerationStatus(bool)));
connect(ui->extraAccelDoubleSpinBox, SIGNAL(valueChanged(double)), &helper, SLOT(updateExtraAccelerationMultiplier(double)));
connect(ui->minMultiDoubleSpinBox, SIGNAL(valueChanged(double)), &helper, SLOT(updateStartMultiPercentage(double)));
connect(ui->minThresholdDoubleSpinBox, SIGNAL(valueChanged(double)), &helper, SLOT(updateMinAccelThreshold(double)));
connect(ui->maxThresholdDoubleSpinBox, SIGNAL(valueChanged(double)), &helper, SLOT(updateMaxAccelThreshold(double)));
connect(ui->accelExtraDurationDoubleSpinBox, SIGNAL(valueChanged(double)), &helper, SLOT(updateAccelExtraDuration(double)));
connect(ui->releaseSpringRadiusspinBox, SIGNAL(valueChanged(int)), &helper, SLOT(updateReleaseSpringRadius(int)));
connect(ui->extraAccelCurveComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(updateExtraAccelerationCurve(int)));
}
void MouseAxisSettingsDialog::changeMouseMode(int index)
{
if (index == 1)
{
axis->setButtonsMouseMode(JoyButton::MouseCursor);
if (springPreviewWidget->isVisible())
{
springPreviewWidget->hide();
}
}
else if (index == 2)
{
axis->setButtonsMouseMode(JoyButton::MouseSpring);
if (!springPreviewWidget->isVisible())
{
springPreviewWidget->setSpringWidth(ui->springWidthSpinBox->value());
springPreviewWidget->setSpringHeight(ui->springHeightSpinBox->value());
}
axis->getPAxisButton()->setExtraAccelerationStatus(false);
axis->getNAxisButton()->setExtraAccelerationStatus(false);
}
}
void MouseAxisSettingsDialog::changeMouseCurve(int index)
{
JoyButton::JoyMouseCurve temp = MouseSettingsDialog::getMouseCurveForIndex(index);
axis->setButtonsMouseCurve(temp);
}
void MouseAxisSettingsDialog::updateConfigHorizontalSpeed(int value)
{
axis->getPAxisButton()->setMouseSpeedX(value);
axis->getNAxisButton()->setMouseSpeedX(value);
}
void MouseAxisSettingsDialog::updateConfigVerticalSpeed(int value)
{
axis->getPAxisButton()->setMouseSpeedY(value);
axis->getNAxisButton()->setMouseSpeedY(value);
}
void MouseAxisSettingsDialog::updateSpringWidth(int value)
{
axis->setButtonsSpringWidth(value);
}
void MouseAxisSettingsDialog::updateSpringHeight(int value)
{
axis->setButtonsSpringHeight(value);
}
void MouseAxisSettingsDialog::selectCurrentMouseModePreset()
{
bool presetDefined = axis->hasSameButtonsMouseMode();
if (presetDefined)
{
JoyButton::JoyMouseMovementMode mode = axis->getButtonsPresetMouseMode();
if (mode == JoyButton::MouseCursor)
{
ui->mouseModeComboBox->setCurrentIndex(1);
}
else if (mode == JoyButton::MouseSpring)
{
ui->mouseModeComboBox->setCurrentIndex(2);
}
}
else
{
ui->mouseModeComboBox->setCurrentIndex(0);
}
}
void MouseAxisSettingsDialog::calculateSpringPreset()
{
int tempWidth = axis->getButtonsPresetSpringWidth();
int tempHeight = axis->getButtonsPresetSpringHeight();
if (tempWidth > 0)
{
ui->springWidthSpinBox->setValue(tempWidth);
}
if (tempHeight > 0)
{
ui->springHeightSpinBox->setValue(tempHeight);
}
}
void MouseAxisSettingsDialog::calculateMouseSpeedPreset()
{
int tempMouseSpeedX = 0;
tempMouseSpeedX = qMax(axis->getPAxisButton()->getMouseSpeedX(), axis->getNAxisButton()->getMouseSpeedX());
int tempMouseSpeedY = 0;
tempMouseSpeedY = qMax(axis->getPAxisButton()->getMouseSpeedY(), axis->getNAxisButton()->getMouseSpeedY());
ui->horizontalSpinBox->setValue(tempMouseSpeedX);
ui->verticalSpinBox->setValue(tempMouseSpeedY);
}
void MouseAxisSettingsDialog::updateSensitivity(double value)
{
axis->setButtonsSensitivity(value);
}
void MouseAxisSettingsDialog::updateAccelerationCurvePresetComboBox()
{
JoyButton::JoyMouseCurve temp = axis->getButtonsPresetMouseCurve();
MouseSettingsDialog::updateAccelerationCurvePresetComboBox(temp);
}
void MouseAxisSettingsDialog::calculateWheelSpeedPreset()
{
JoyAxisButton *paxisbutton = axis->getPAxisButton();
JoyAxisButton *naxisbutton = axis->getNAxisButton();
int tempWheelSpeedX = qMax(paxisbutton->getWheelSpeedX(), naxisbutton->getWheelSpeedX());
int tempWheelSpeedY = qMax(paxisbutton->getWheelSpeedY(), naxisbutton->getWheelSpeedY());
ui->wheelHoriSpeedSpinBox->setValue(tempWheelSpeedX);
ui->wheelVertSpeedSpinBox->setValue(tempWheelSpeedY);
}
void MouseAxisSettingsDialog::updateWheelSpeedHorizontalSpeed(int value)
{
axis->setButtonsWheelSpeedX(value);
}
void MouseAxisSettingsDialog::updateWheelSpeedVerticalSpeed(int value)
{
axis->setButtonsWheelSpeedY(value);
}
void MouseAxisSettingsDialog::updateSpringRelativeStatus(bool value)
{
axis->setButtonsSpringRelativeStatus(value);
}
void MouseAxisSettingsDialog::updateWindowTitleAxisName()
{
QString temp;
temp.append(tr("Mouse Settings - "));
if (!axis->getAxisName().isEmpty())
{
temp.append(axis->getPartialName(false, true));
}
else
{
temp.append(axis->getPartialName());
}
if (axis->getParentSet()->getIndex() != 0)
{
unsigned int setIndex = axis->getParentSet()->getRealIndex();
temp.append(" [").append(tr("Set %1").arg(setIndex));
QString setName = axis->getParentSet()->getName();
if (!setName.isEmpty())
{
temp.append(": ").append(setName);
}
temp.append("]");
}
setWindowTitle(temp);
}
void MouseAxisSettingsDialog::calculateExtraAccelrationStatus()
{
if (axis->getPAxisButton()->isExtraAccelerationEnabled() &&
axis->getNAxisButton()->isExtraAccelerationEnabled())
{
ui->extraAccelerationGroupBox->setChecked(true);
//ui->extraAccelCheckBox->setChecked(true);
//ui->extraAccelDoubleSpinBox->setEnabled(true);
}
else
{
ui->extraAccelerationGroupBox->setChecked(false);
}
}
void MouseAxisSettingsDialog::calculateExtraAccelerationMultiplier()
{
if (axis->getPAxisButton()->getExtraAccelerationMultiplier() ==
axis->getNAxisButton()->getExtraAccelerationMultiplier())
{
double temp = axis->getPAxisButton()->getExtraAccelerationMultiplier();
ui->extraAccelDoubleSpinBox->setValue(temp);
}
}
void MouseAxisSettingsDialog::calculateStartAccelerationMultiplier()
{
if (axis->getPAxisButton()->getStartAccelMultiplier() ==
axis->getNAxisButton()->getStartAccelMultiplier())
{
double temp = axis->getPAxisButton()->getStartAccelMultiplier();
ui->minMultiDoubleSpinBox->setValue(temp);
}
}
void MouseAxisSettingsDialog::calculateMinAccelerationThreshold()
{
if (axis->getPAxisButton()->getMinAccelThreshold() ==
axis->getNAxisButton()->getMinAccelThreshold())
{
double temp = axis->getPAxisButton()->getMinAccelThreshold();
ui->minThresholdDoubleSpinBox->setValue(temp);
}
}
void MouseAxisSettingsDialog::calculateMaxAccelerationThreshold()
{
if (axis->getPAxisButton()->getMaxAccelThreshold() ==
axis->getNAxisButton()->getMaxAccelThreshold())
{
double temp = axis->getPAxisButton()->getMaxAccelThreshold();
ui->maxThresholdDoubleSpinBox->setValue(temp);
}
}
void MouseAxisSettingsDialog::calculateAccelExtraDuration()
{
if (axis->getPAxisButton()->getAccelExtraDuration() ==
axis->getNAxisButton()->getAccelExtraDuration())
{
double temp = axis->getPAxisButton()->getAccelExtraDuration();
ui->accelExtraDurationDoubleSpinBox->setValue(temp);
}
}
void MouseAxisSettingsDialog::calculateReleaseSpringRadius()
{
int result = 0;
if (axis->getPAxisButton()->getSpringDeadCircleMultiplier() ==
axis->getNAxisButton()->getSpringDeadCircleMultiplier())
{
result = axis->getPAxisButton()->getSpringDeadCircleMultiplier();
}
ui->releaseSpringRadiusspinBox->setValue(result);
}
void MouseAxisSettingsDialog::updateExtraAccelerationCurve(int index)
{
JoyButton::JoyExtraAccelerationCurve temp = getExtraAccelCurveForIndex(index);
if (index > 0)
{
InputDevice *device = axis->getParentSet()->getInputDevice();
//PadderCommon::lockInputDevices();
//QMetaObject::invokeMethod(device, "haltServices", Qt::BlockingQueuedConnection);
PadderCommon::inputDaemonMutex.lock();
axis->getPAxisButton()->setExtraAccelerationCurve(temp);
axis->getNAxisButton()->setExtraAccelerationCurve(temp);
PadderCommon::inputDaemonMutex.unlock();
//PadderCommon::unlockInputDevices();
}
}
void MouseAxisSettingsDialog::calculateExtraAccelerationCurve()
{
if (axis->getPAxisButton()->getExtraAccelerationCurve() ==
axis->getNAxisButton()->getExtraAccelerationCurve())
{
JoyButton::JoyExtraAccelerationCurve temp = axis->getPAxisButton()->getExtraAccelerationCurve();
updateExtraAccelerationCurvePresetComboBox(temp);
}
}
``` | /content/code_sandbox/src/mousedialog/mouseaxissettingsdialog.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 2,877 |
```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 "mousecontrolsticksettingsdialoghelper.h"
MouseControlStickSettingsDialogHelper::MouseControlStickSettingsDialogHelper(JoyControlStick *stick,
QObject *parent) :
QObject(parent)
{
Q_ASSERT(stick);
this->stick = stick;
}
void MouseControlStickSettingsDialogHelper::updateExtraAccelerationStatus(bool checked)
{
stick->setButtonsExtraAccelerationStatus(checked);
}
void MouseControlStickSettingsDialogHelper::updateExtraAccelerationMultiplier(double value)
{
stick->setButtonsExtraAccelerationMultiplier(value);
}
void MouseControlStickSettingsDialogHelper::updateStartMultiPercentage(double value)
{
stick->setButtonsStartAccelerationMultiplier(value);
}
void MouseControlStickSettingsDialogHelper::updateMinAccelThreshold(double value)
{
stick->setButtonsMinAccelerationThreshold(value);
}
void MouseControlStickSettingsDialogHelper::updateMaxAccelThreshold(double value)
{
stick->setButtonsMaxAccelerationThreshold(value);
}
void MouseControlStickSettingsDialogHelper::updateAccelExtraDuration(double value)
{
stick->setButtonsAccelerationExtraDuration(value);
}
void MouseControlStickSettingsDialogHelper::updateReleaseSpringRadius(int value)
{
stick->setButtonsSpringDeadCircleMultiplier(value);
}
``` | /content/code_sandbox/src/mousedialog/uihelpers/mousecontrolsticksettingsdialoghelper.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 345 |
```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 BUTTONEDITDIALOGHELPER_H
#define BUTTONEDITDIALOGHELPER_H
#include <QObject>
#include "joybutton.h"
#include "joybuttonslot.h"
class ButtonEditDialogHelper : public QObject
{
Q_OBJECT
public:
explicit ButtonEditDialogHelper(JoyButton *button, QObject *parent = 0);
protected:
JoyButton *button;
signals:
public slots:
void setAssignedSlot(int code, unsigned int alias,
JoyButtonSlot::JoySlotInputAction mode=JoyButtonSlot::JoyKeyboard);
void setUseTurbo(bool useTurbo);
};
#endif // BUTTONEDITDIALOGHELPER_H
``` | /content/code_sandbox/src/uihelpers/buttoneditdialoghelper.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 231 |
```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 "mouseaxissettingsdialoghelper.h"
MouseAxisSettingsDialogHelper::MouseAxisSettingsDialogHelper(JoyAxis *axis, QObject *parent) :
QObject(parent)
{
Q_ASSERT(axis);
this->axis = axis;
}
void MouseAxisSettingsDialogHelper::updateExtraAccelerationStatus(bool checked)
{
axis->getPAxisButton()->setExtraAccelerationStatus(checked);
axis->getNAxisButton()->setExtraAccelerationStatus(checked);
}
void MouseAxisSettingsDialogHelper::updateExtraAccelerationMultiplier(double value)
{
axis->getPAxisButton()->setExtraAccelerationMultiplier(value);
axis->getNAxisButton()->setExtraAccelerationMultiplier(value);
}
void MouseAxisSettingsDialogHelper::updateStartMultiPercentage(double value)
{
axis->getPAxisButton()->setStartAccelMultiplier(value);
axis->getNAxisButton()->setStartAccelMultiplier(value);
}
void MouseAxisSettingsDialogHelper::updateMinAccelThreshold(double value)
{
axis->getPAxisButton()->setMinAccelThreshold(value);
axis->getNAxisButton()->setMinAccelThreshold(value);
}
void MouseAxisSettingsDialogHelper::updateMaxAccelThreshold(double value)
{
axis->getPAxisButton()->setMaxAccelThreshold(value);
axis->getNAxisButton()->setMaxAccelThreshold(value);
}
void MouseAxisSettingsDialogHelper::updateAccelExtraDuration(double value)
{
axis->getPAxisButton()->setAccelExtraDuration(value);
axis->getNAxisButton()->setAccelExtraDuration(value);
}
void MouseAxisSettingsDialogHelper::updateReleaseSpringRadius(int value)
{
axis->getPAxisButton()->setSpringDeadCircleMultiplier(value);
axis->getNAxisButton()->setSpringDeadCircleMultiplier(value);
}
``` | /content/code_sandbox/src/mousedialog/uihelpers/mouseaxissettingsdialoghelper.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 467 |
```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 ADVANCEBUTTONDIALOGHELPER_H
#define ADVANCEBUTTONDIALOGHELPER_H
#include <QObject>
#include "joybutton.h"
#include "joybuttonslot.h"
class AdvanceButtonDialogHelper : public QObject
{
Q_OBJECT
public:
explicit AdvanceButtonDialogHelper(JoyButton *button,
QObject *parent = 0);
protected:
JoyButton *button;
signals:
public slots:
void setAssignedSlot(JoyButtonSlot *otherSlot, int index);
void setAssignedSlot(int code, unsigned int alias, int index,
JoyButtonSlot::JoySlotInputAction mode=JoyButtonSlot::JoyKeyboard);
void insertAssignedSlot(int code, unsigned int alias, int index,
JoyButtonSlot::JoySlotInputAction mode=JoyButtonSlot::JoyKeyboard);
void removeAssignedSlot(int index);
};
#endif // ADVANCEBUTTONDIALOGHELPER_H
``` | /content/code_sandbox/src/uihelpers/advancebuttondialoghelper.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 284 |
```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 DPADEDITDIALOGHELPER_H
#define DPADEDITDIALOGHELPER_H
#include <QObject>
#include <QHash>
#include "joydpad.h"
#include "joybuttonslot.h"
class DPadEditDialogHelper : public QObject
{
Q_OBJECT
public:
explicit DPadEditDialogHelper(JoyDPad *dpad, QObject *parent = 0);
void setPendingSlots(QHash<JoyDPadButton::JoyDPadDirections, JoyButtonSlot*> *tempSlots);
void clearPendingSlots();
protected:
JoyDPad *dpad;
QHash<JoyDPadButton::JoyDPadDirections, JoyButtonSlot*> pendingSlots;
signals:
public slots:
void setFromPendingSlots();
void clearButtonsSlotsEventReset();
void updateJoyDPadDelay(int value);
};
#endif // DPADEDITDIALOGHELPER_H
``` | /content/code_sandbox/src/uihelpers/dpadeditdialoghelper.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 286 |
```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 JOYAXISCONTEXTMENUHELPER_H
#define JOYAXISCONTEXTMENUHELPER_H
#include <QObject>
#include "joyaxis.h"
#include "joybuttonslot.h"
class JoyAxisContextMenuHelper : public QObject
{
Q_OBJECT
public:
explicit JoyAxisContextMenuHelper(JoyAxis *axis, QObject *parent = 0);
protected:
JoyAxis *axis;
signals:
public slots:
void setNAssignedSlot(int code, unsigned int alias,
JoyButtonSlot::JoySlotInputAction mode=JoyButtonSlot::JoyKeyboard);
void setPAssignedSlot(int code, unsigned int alias,
JoyButtonSlot::JoySlotInputAction mode=JoyButtonSlot::JoyKeyboard);
void clearAndResetAxisButtons();
};
#endif // JOYAXISCONTEXTMENUHELPER_H
``` | /content/code_sandbox/src/uihelpers/joyaxiscontextmenuhelper.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 266 |
```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 "joycontrolstickcontextmenuhelper.h"
JoyControlStickContextMenuHelper::JoyControlStickContextMenuHelper(JoyControlStick *stick, QObject *parent) :
QObject(parent)
{
Q_ASSERT(stick);
this->stick = stick;
}
void JoyControlStickContextMenuHelper::setPendingSlots(QHash<JoyControlStick::JoyStickDirections,
JoyButtonSlot *> *tempSlots)
{
pendingSlots.clear();
QHashIterator<JoyControlStick::JoyStickDirections, JoyButtonSlot*> iter(*tempSlots);
while (iter.hasNext())
{
iter.next();
JoyButtonSlot *slot = iter.value();
JoyControlStick::JoyStickDirections tempDir = iter.key();
pendingSlots.insert(tempDir, slot);
}
}
void JoyControlStickContextMenuHelper::clearPendingSlots()
{
pendingSlots.clear();
}
void JoyControlStickContextMenuHelper::setFromPendingSlots()
{
if (!pendingSlots.isEmpty())
{
QHashIterator<JoyControlStick::JoyStickDirections, JoyButtonSlot*> iter(pendingSlots);
while (iter.hasNext())
{
iter.next();
JoyButtonSlot *slot = iter.value();
if (slot)
{
JoyControlStick::JoyStickDirections tempDir = iter.key();
JoyControlStickButton *button = stick->getDirectionButton(tempDir);
if (button)
{
button->clearSlotsEventReset(false);
button->setAssignedSlot(slot->getSlotCode(), slot->getSlotCodeAlias(),
slot->getSlotMode());
}
slot->deleteLater();
}
}
}
}
void JoyControlStickContextMenuHelper::clearButtonsSlotsEventReset()
{
QHash<JoyControlStick::JoyStickDirections, JoyControlStickButton*> *buttons = stick->getButtons();
QHashIterator<JoyControlStick::JoyStickDirections, JoyControlStickButton*> iter(*buttons);
while (iter.hasNext())
{
JoyControlStickButton *button = iter.next().value();
if (button)
{
button->clearSlotsEventReset();
}
}
}
``` | /content/code_sandbox/src/uihelpers/joycontrolstickcontextmenuhelper.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 534 |
```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 "gamecontrollermappingdialoghelper.h"
GameControllerMappingDialogHelper::GameControllerMappingDialogHelper(InputDevice *device,
QObject *parent) :
QObject(parent)
{
this->device = device;
}
void GameControllerMappingDialogHelper::raiseDeadZones()
{
device->setRawAxisDeadZone(InputDevice::RAISEDDEADZONE);
device->getActiveSetJoystick()->raiseAxesDeadZones();
}
void GameControllerMappingDialogHelper::raiseDeadZones(int deadZone)
{
device->getActiveSetJoystick()->raiseAxesDeadZones(deadZone);
device->setRawAxisDeadZone(deadZone);
}
void GameControllerMappingDialogHelper::setupDeadZones()
{
device->getActiveSetJoystick()->setIgnoreEventState(true);
device->getActiveSetJoystick()->release();
device->getActiveSetJoystick()->currentAxesDeadZones(&originalAxesDeadZones);
device->getActiveSetJoystick()->raiseAxesDeadZones();
device->setRawAxisDeadZone(InputDevice::RAISEDDEADZONE);
}
void GameControllerMappingDialogHelper::restoreDeviceDeadZones()
{
device->getActiveSetJoystick()->setIgnoreEventState(false);
device->getActiveSetJoystick()->release();
device->getActiveSetJoystick()->setAxesDeadZones(&originalAxesDeadZones);
device->setRawAxisDeadZone(InputDevice::RAISEDDEADZONE);
}
``` | /content/code_sandbox/src/uihelpers/gamecontrollermappingdialoghelper.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 399 |
```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 "joytabwidgethelper.h"
JoyTabWidgetHelper::JoyTabWidgetHelper(InputDevice *device, QObject *parent) :
QObject(parent)
{
Q_ASSERT(device);
this->device = device;
this->reader = 0;
this->writer = 0;
this->errorOccurred = false;
}
JoyTabWidgetHelper::~JoyTabWidgetHelper()
{
if (this->reader)
{
delete this->reader;
this->reader = 0;
}
if (this->writer)
{
delete this->writer;
this->writer = 0;
}
}
bool JoyTabWidgetHelper::hasReader()
{
return (this->reader != 0);
}
XMLConfigReader* JoyTabWidgetHelper::getReader()
{
return this->reader;
}
bool JoyTabWidgetHelper::hasWriter()
{
return (this->writer != 0);
}
XMLConfigWriter* JoyTabWidgetHelper::getWriter()
{
return this->writer;
}
bool JoyTabWidgetHelper::hasError()
{
return errorOccurred;
}
QString JoyTabWidgetHelper::getErrorString()
{
return lastErrorString;
}
bool JoyTabWidgetHelper::readConfigFile(QString filepath)
{
bool result = false;
device->disconnectPropertyUpdatedConnection();
if (device->getActiveSetNumber() != 0)
{
device->setActiveSetNumber(0);
}
device->resetButtonDownCount();
if (this->reader)
{
this->reader->deleteLater();
this->reader = 0;
}
this->reader = new XMLConfigReader;
this->reader->setFileName(filepath);
this->reader->configJoystick(device);
device->establishPropertyUpdatedConnection();
result = !this->reader->hasError();
return result;
}
bool JoyTabWidgetHelper::readConfigFileWithRevert(QString filepath)
{
bool result = false;
device->revertProfileEdited();
result = readConfigFile(filepath);
return result;
}
bool JoyTabWidgetHelper::writeConfigFile(QString filepath)
{
bool result = false;
if (this->writer)
{
this->writer->deleteLater();
this->writer = 0;
}
this->writer = new XMLConfigWriter;
this->writer->setFileName(filepath);
this->writer->write(device);
result = !this->writer->hasError();
return result;
}
void JoyTabWidgetHelper::reInitDevice()
{
device->disconnectPropertyUpdatedConnection();
if (device->getActiveSetNumber() != 0)
{
device->setActiveSetNumber(0);
}
device->transferReset();
device->resetButtonDownCount();
device->reInitButtons();
device->establishPropertyUpdatedConnection();
}
void JoyTabWidgetHelper::reInitDeviceWithRevert()
{
device->revertProfileEdited();
reInitDevice();
}
``` | /content/code_sandbox/src/uihelpers/joytabwidgethelper.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 720 |
```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 GAMECONTROLLERMAPPINGDIALOGHELPER_H
#define GAMECONTROLLERMAPPINGDIALOGHELPER_H
#include <QObject>
#include <QList>
#include "inputdevice.h"
class GameControllerMappingDialogHelper : public QObject
{
Q_OBJECT
public:
explicit GameControllerMappingDialogHelper(InputDevice *device, QObject *parent = 0);
protected:
InputDevice *device;
QList<int> originalAxesDeadZones;
signals:
public slots:
void raiseDeadZones();
void raiseDeadZones(int deadZone);
void setupDeadZones();
void restoreDeviceDeadZones();
};
#endif // GAMECONTROLLERMAPPINGDIALOGHELPER_H
``` | /content/code_sandbox/src/uihelpers/gamecontrollermappingdialoghelper.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 238 |
```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 JOYCONTROLSTICKCONTEXTMENUHELPER_H
#define JOYCONTROLSTICKCONTEXTMENUHELPER_H
#include <QObject>
#include <QHash>
#include "joycontrolstick.h"
class JoyControlStickContextMenuHelper : public QObject
{
Q_OBJECT
public:
explicit JoyControlStickContextMenuHelper(JoyControlStick *stick, QObject *parent = 0);
void setPendingSlots(QHash<JoyControlStick::JoyStickDirections, JoyButtonSlot*> *tempSlots);
void clearPendingSlots();
protected:
JoyControlStick *stick;
QHash<JoyControlStick::JoyStickDirections, JoyButtonSlot*> pendingSlots;
signals:
public slots:
void setFromPendingSlots();
void clearButtonsSlotsEventReset();
};
#endif // JOYCONTROLSTICKCONTEXTMENUHELPER_H
``` | /content/code_sandbox/src/uihelpers/joycontrolstickcontextmenuhelper.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 266 |
```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 DPADCONTEXTMENUHELPER_H
#define DPADCONTEXTMENUHELPER_H
#include <QObject>
#include <QHash>
#include "joydpad.h"
#include "joybuttonslot.h"
class DPadContextMenuHelper : public QObject
{
Q_OBJECT
public:
explicit DPadContextMenuHelper(JoyDPad *dpad, QObject *parent = 0);
void setPendingSlots(QHash<JoyDPadButton::JoyDPadDirections, JoyButtonSlot*> *tempSlots);
void clearPendingSlots();
protected:
JoyDPad *dpad;
QHash<JoyDPadButton::JoyDPadDirections, JoyButtonSlot*> pendingSlots;
signals:
public slots:
void setFromPendingSlots();
void clearButtonsSlotsEventReset();
};
#endif // DPADCONTEXTMENUHELPER_H
``` | /content/code_sandbox/src/uihelpers/dpadcontextmenuhelper.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 268 |
```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 <QListIterator>
#include "dpadcontextmenuhelper.h"
DPadContextMenuHelper::DPadContextMenuHelper(JoyDPad *dpad, QObject *parent) :
QObject(parent)
{
Q_ASSERT(dpad);
this->dpad = dpad;
}
void DPadContextMenuHelper::setPendingSlots(QHash<JoyDPadButton::JoyDPadDirections, JoyButtonSlot *> *tempSlots)
{
pendingSlots.clear();
QHashIterator<JoyDPadButton::JoyDPadDirections, JoyButtonSlot*> iter(*tempSlots);
while (iter.hasNext())
{
iter.next();
JoyButtonSlot *slot = iter.value();
JoyDPadButton::JoyDPadDirections tempDir = iter.key();
pendingSlots.insert(tempDir, slot);
}
}
void DPadContextMenuHelper::clearPendingSlots()
{
pendingSlots.clear();
}
void DPadContextMenuHelper::setFromPendingSlots()
{
if (!pendingSlots.isEmpty())
{
QHashIterator<JoyDPadButton::JoyDPadDirections, JoyButtonSlot*> iter(pendingSlots);
while (iter.hasNext())
{
iter.next();
JoyButtonSlot *slot = iter.value();
if (slot)
{
JoyDPadButton::JoyDPadDirections tempDir = iter.key();
JoyDPadButton *button = dpad->getJoyButton(tempDir);
button->clearSlotsEventReset(false);
button->setAssignedSlot(slot->getSlotCode(), slot->getSlotCodeAlias(),
slot->getSlotMode());
slot->deleteLater();
}
}
}
}
void DPadContextMenuHelper::clearButtonsSlotsEventReset()
{
QHash<int, JoyDPadButton*> *buttons = dpad->getButtons();
QHashIterator<int, JoyDPadButton*> iter(*buttons);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
button->clearSlotsEventReset();
}
}
``` | /content/code_sandbox/src/uihelpers/dpadcontextmenuhelper.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 515 |
```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 "advancebuttondialoghelper.h"
AdvanceButtonDialogHelper::AdvanceButtonDialogHelper(JoyButton *button,
QObject *parent) :
QObject(parent)
{
Q_ASSERT(button);
this->button = button;
}
void AdvanceButtonDialogHelper::insertAssignedSlot(int code, unsigned int alias, int index,
JoyButtonSlot::JoySlotInputAction mode)
{
button->eventReset();
button->insertAssignedSlot(code, alias, index, mode);
}
void AdvanceButtonDialogHelper::setAssignedSlot(JoyButtonSlot *otherSlot, int index)
{
button->eventReset();
button->setAssignedSlot(otherSlot, index);
}
void AdvanceButtonDialogHelper::setAssignedSlot(int code, unsigned int alias, int index,
JoyButtonSlot::JoySlotInputAction mode)
{
button->eventReset();
button->setAssignedSlot(code, alias, index, mode);
}
void AdvanceButtonDialogHelper::removeAssignedSlot(int index)
{
button->eventReset();
button->removeAssignedSlot(index);
}
``` | /content/code_sandbox/src/uihelpers/advancebuttondialoghelper.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 JOYTABWIDGETHELPER_H
#define JOYTABWIDGETHELPER_H
#include <QObject>
#include "inputdevice.h"
#include "joybutton.h"
#include "joybuttonslot.h"
#include "xmlconfigreader.h"
#include "xmlconfigwriter.h"
class JoyTabWidgetHelper : public QObject
{
Q_OBJECT
public:
explicit JoyTabWidgetHelper(InputDevice *device, QObject *parent = 0);
~JoyTabWidgetHelper();
bool hasReader();
XMLConfigReader* getReader();
bool hasWriter();
XMLConfigWriter* getWriter();
bool hasError();
QString getErrorString();
protected:
InputDevice *device;
XMLConfigReader *reader;
XMLConfigWriter *writer;
bool errorOccurred;
QString lastErrorString;
signals:
public slots:
bool readConfigFile(QString filepath);
bool readConfigFileWithRevert(QString filepath);
bool writeConfigFile(QString filepath);
void reInitDevice();
void reInitDeviceWithRevert();
};
#endif // JOYTABWIDGETHELPER_H
``` | /content/code_sandbox/src/uihelpers/joytabwidgethelper.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 323 |
```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 "joyaxiscontextmenuhelper.h"
JoyAxisContextMenuHelper::JoyAxisContextMenuHelper(JoyAxis *axis, QObject *parent) :
QObject(parent)
{
Q_ASSERT(axis);
this->axis = axis;
}
void JoyAxisContextMenuHelper::setNAssignedSlot(int code, unsigned int alias,
JoyButtonSlot::JoySlotInputAction mode)
{
JoyButton *button = axis->getNAxisButton();
button->clearSlotsEventReset(false);
button->setAssignedSlot(code, alias, mode);
}
void JoyAxisContextMenuHelper::setPAssignedSlot(int code, unsigned int alias,
JoyButtonSlot::JoySlotInputAction mode)
{
JoyButton *button = axis->getPAxisButton();
button->clearSlotsEventReset(false);
button->setAssignedSlot(code, alias, mode);
}
void JoyAxisContextMenuHelper::clearAndResetAxisButtons()
{
JoyAxisButton *nbutton = axis->getNAxisButton();
JoyAxisButton *pbutton = axis->getPAxisButton();
nbutton->clearSlotsEventReset();
pbutton->clearSlotsEventReset();
}
``` | /content/code_sandbox/src/uihelpers/joyaxiscontextmenuhelper.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 333 |
```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 "dpadeditdialoghelper.h"
DPadEditDialogHelper::DPadEditDialogHelper(JoyDPad *dpad, QObject *parent) :
QObject(parent)
{
Q_ASSERT(dpad);
this->dpad = dpad;
}
void DPadEditDialogHelper::setPendingSlots(QHash<JoyDPadButton::JoyDPadDirections, JoyButtonSlot *> *tempSlots)
{
pendingSlots.clear();
QHashIterator<JoyDPadButton::JoyDPadDirections, JoyButtonSlot*> iter(*tempSlots);
while (iter.hasNext())
{
iter.next();
JoyButtonSlot *slot = iter.value();
JoyDPadButton::JoyDPadDirections tempDir = iter.key();
pendingSlots.insert(tempDir, slot);
}
}
void DPadEditDialogHelper::clearPendingSlots()
{
pendingSlots.clear();
}
void DPadEditDialogHelper::setFromPendingSlots()
{
if (!pendingSlots.isEmpty())
{
QHashIterator<JoyDPadButton::JoyDPadDirections, JoyButtonSlot*> iter(pendingSlots);
while (iter.hasNext())
{
iter.next();
JoyButtonSlot *slot = iter.value();
if (slot)
{
JoyDPadButton::JoyDPadDirections tempDir = iter.key();
JoyDPadButton *button = dpad->getJoyButton(tempDir);
button->clearSlotsEventReset(false);
button->setAssignedSlot(slot->getSlotCode(), slot->getSlotCodeAlias(),
slot->getSlotMode());
slot->deleteLater();
}
}
}
}
void DPadEditDialogHelper::clearButtonsSlotsEventReset()
{
QHash<int, JoyDPadButton*> *buttons = dpad->getButtons();
QHashIterator<int, JoyDPadButton*> iter(*buttons);
while (iter.hasNext())
{
JoyDPadButton *button = iter.next().value();
button->clearSlotsEventReset();
}
}
void DPadEditDialogHelper::updateJoyDPadDelay(int value)
{
int temp = value * 10;
if (dpad->getDPadDelay() != temp)
{
dpad->setDPadDelay(temp);
}
}
``` | /content/code_sandbox/src/uihelpers/dpadeditdialoghelper.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 569 |
```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 JOYCONTROLSTICKEDITDIALOGHELPER_H
#define JOYCONTROLSTICKEDITDIALOGHELPER_H
#include <QObject>
#include <QHash>
#include "joycontrolstick.h"
class JoyControlStickEditDialogHelper : public QObject
{
Q_OBJECT
public:
explicit JoyControlStickEditDialogHelper(JoyControlStick *stick, QObject *parent = 0);
void setPendingSlots(QHash<JoyControlStick::JoyStickDirections, JoyButtonSlot*> *tempSlots);
void clearPendingSlots();
protected:
JoyControlStick *stick;
QHash<JoyControlStick::JoyStickDirections, JoyButtonSlot*> pendingSlots;
signals:
public slots:
void setFromPendingSlots();
void clearButtonsSlotsEventReset();
void updateControlStickDelay(int value);
};
#endif // JOYCONTROLSTICKEDITDIALOGHELPER_H
``` | /content/code_sandbox/src/uihelpers/joycontrolstickeditdialoghelper.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 280 |
```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 "buttoneditdialoghelper.h"
ButtonEditDialogHelper::ButtonEditDialogHelper(JoyButton *button, QObject *parent) :
QObject(parent)
{
Q_ASSERT(button);
this->button = button;
}
void ButtonEditDialogHelper::setAssignedSlot(int code, unsigned int alias,
JoyButtonSlot::JoySlotInputAction mode)
{
button->clearSlotsEventReset(false);
button->setAssignedSlot(code, alias, mode);
}
void ButtonEditDialogHelper::setUseTurbo(bool useTurbo)
{
button->setUseTurbo(useTurbo);
}
``` | /content/code_sandbox/src/uihelpers/buttoneditdialoghelper.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 220 |
```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 "joycontrolstickeditdialoghelper.h"
JoyControlStickEditDialogHelper::JoyControlStickEditDialogHelper(JoyControlStick *stick, QObject *parent) :
QObject(parent)
{
Q_ASSERT(stick);
this->stick = stick;
}
void JoyControlStickEditDialogHelper::setPendingSlots(QHash<JoyControlStick::JoyStickDirections,
JoyButtonSlot *> *tempSlots)
{
pendingSlots.clear();
QHashIterator<JoyControlStick::JoyStickDirections, JoyButtonSlot*> iter(*tempSlots);
while (iter.hasNext())
{
iter.next();
JoyButtonSlot *slot = iter.value();
JoyControlStick::JoyStickDirections tempDir = iter.key();
pendingSlots.insert(tempDir, slot);
}
}
void JoyControlStickEditDialogHelper::clearPendingSlots()
{
pendingSlots.clear();
}
void JoyControlStickEditDialogHelper::setFromPendingSlots()
{
if (!pendingSlots.isEmpty())
{
QHashIterator<JoyControlStick::JoyStickDirections, JoyButtonSlot*> iter(pendingSlots);
while (iter.hasNext())
{
iter.next();
JoyButtonSlot *slot = iter.value();
if (slot)
{
JoyControlStick::JoyStickDirections tempDir = iter.key();
JoyControlStickButton *button = stick->getDirectionButton(tempDir);
if (button)
{
button->clearSlotsEventReset(false);
button->setAssignedSlot(slot->getSlotCode(), slot->getSlotCodeAlias(),
slot->getSlotMode());
}
slot->deleteLater();
}
}
}
}
void JoyControlStickEditDialogHelper::clearButtonsSlotsEventReset()
{
QHash<JoyControlStick::JoyStickDirections, JoyControlStickButton*> *buttons = stick->getButtons();
QHashIterator<JoyControlStick::JoyStickDirections, JoyControlStickButton*> iter(*buttons);
while (iter.hasNext())
{
JoyControlStickButton *button = iter.next().value();
if (button)
{
button->clearSlotsEventReset();
}
}
}
void JoyControlStickEditDialogHelper::updateControlStickDelay(int value)
{
int temp = value * 10;
if (stick->getStickDelay() != temp)
{
stick->setStickDelay(temp);
}
}
``` | /content/code_sandbox/src/uihelpers/joycontrolstickeditdialoghelper.cpp | c++ | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 590 |
```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 BASEEVENTHANDLER_H
#define BASEEVENTHANDLER_H
#include <QObject>
#include <QString>
#include <springmousemoveinfo.h>
#include <joybuttonslot.h>
class BaseEventHandler : public QObject
{
Q_OBJECT
public:
explicit BaseEventHandler(QObject *parent = 0);
virtual bool init() = 0;
virtual bool cleanup() = 0;
virtual void sendKeyboardEvent(JoyButtonSlot *slot, bool pressed) = 0;
virtual void sendMouseButtonEvent(JoyButtonSlot *slot, bool pressed) = 0;
virtual void sendMouseEvent(int xDis, int yDis) = 0;
virtual void sendMouseAbsEvent(int xDis, int yDis, int screen);
virtual void sendMouseSpringEvent(unsigned int xDis, unsigned int yDis,
unsigned int width, unsigned int height);
virtual void sendMouseSpringEvent(int xDis, int yDis);
virtual void sendTextEntryEvent(QString maintext);
virtual QString getName() = 0;
virtual QString getIdentifier() = 0;
virtual void printPostMessages();
QString getErrorString();
protected:
QString lastErrorString;
signals:
public slots:
};
#endif // BASEEVENTHANDLER_H
``` | /content/code_sandbox/src/eventhandlers/baseeventhandler.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 356 |
```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 WINVMULTIEVENTHANDLER_H
#define WINVMULTIEVENTHANDLER_H
#include <QObject>
#include <QVector>
#include "baseeventhandler.h"
#include <joybuttonslot.h>
#include <vmulticlient.h>
#include <antkeymapper.h>
#include "winsendinputeventhandler.h"
class WinVMultiEventHandler : public BaseEventHandler
{
Q_OBJECT
public:
explicit WinVMultiEventHandler(QObject *parent = 0);
~WinVMultiEventHandler();
virtual bool init();
virtual bool cleanup();
virtual void sendKeyboardEvent(JoyButtonSlot *slot, bool pressed);
virtual void sendMouseButtonEvent(JoyButtonSlot *slot, bool pressed);
virtual void sendMouseEvent(int xDis, int yDis);
virtual void sendMouseAbsEvent(int xDis, int yDis, int screen);
virtual void sendMouseSpringEvent(unsigned int xDis, unsigned int yDis,
unsigned int width, unsigned int height);
// TODO: Implement text event using information from QtWinKeyMapper.
virtual void sendTextEntryEvent(QString maintext);
virtual QString getName();
virtual QString getIdentifier();
protected:
pvmulti_client vmulti;
BYTE mouseButtons;
BYTE shiftKeys;
BYTE multiKeys;
BYTE extraKeys;
QVector<BYTE> keyboardKeys;
WinSendInputEventHandler sendInputHandler;
QtKeyMapperBase *nativeKeyMapper;
signals:
public slots:
};
#endif // WINVMULTIEVENTHANDLER_H
``` | /content/code_sandbox/src/eventhandlers/winvmultieventhandler.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 410 |
```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 WINSENDINPUTEVENTHANDLER_H
#define WINSENDINPUTEVENTHANDLER_H
#include <QObject>
#include "baseeventhandler.h"
#include <joybuttonslot.h>
class WinSendInputEventHandler : public BaseEventHandler
{
Q_OBJECT
public:
explicit WinSendInputEventHandler(QObject *parent = 0);
virtual bool init();
virtual bool cleanup();
virtual void sendKeyboardEvent(JoyButtonSlot *slot, bool pressed);
virtual void sendMouseButtonEvent(JoyButtonSlot *slot, bool pressed);
virtual void sendMouseEvent(int xDis, int yDis);
virtual void sendMouseSpringEvent(unsigned int xDis, unsigned int yDis,
unsigned int width, unsigned int height);
virtual void sendTextEntryEvent(QString maintext);
virtual QString getName();
virtual QString getIdentifier();
signals:
public slots:
};
#endif // WINSENDINPUTEVENTHANDLER_H
``` | /content/code_sandbox/src/eventhandlers/winsendinputeventhandler.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 281 |
```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 XTESTEVENTHANDLER_H
#define XTESTEVENTHANDLER_H
#include "baseeventhandler.h"
#include <joybuttonslot.h>
class XTestEventHandler : public BaseEventHandler
{
Q_OBJECT
public:
explicit XTestEventHandler(QObject *parent = 0);
virtual bool init();
virtual bool cleanup();
virtual void sendKeyboardEvent(JoyButtonSlot *slot, bool pressed);
virtual void sendMouseButtonEvent(JoyButtonSlot *slot, bool pressed);
virtual void sendMouseEvent(int xDis, int yDis);
virtual void sendMouseAbsEvent(int xDis, int yDis, int screen);
virtual QString getName();
virtual QString getIdentifier();
virtual void sendTextEntryEvent(QString maintext);
signals:
public slots:
};
#endif // XTESTEVENTHANDLER_H
``` | /content/code_sandbox/src/eventhandlers/xtesteventhandler.h | objective-c | 2016-05-24T23:59:31 | 2024-08-11T02:46:48 | antimicro | AntiMicro/antimicro | 1,788 | 264 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.