总体逻辑,修改发现设备和添加设备;

1、发现设备(qt-everywhere-src-5.15.6\qtbase\src\platformsupport\devicediscovery/qdevicediscovery_static.cpp)

        需要修改的逻辑是,当/dev/input/路径下发生了文件的改动,需要重新加载设备列表,然后将设备重新添加使用;

1.1、头文件中(qdevicediscovery_static_p.h)

修改内容为:

添加设备名称列表(m_devices);检测热插拔类(m_fileWatcher);检测到文件变动后的槽函数(handleHotPlugWatch);

 1.2、修改源文件(qdevicediscovery_static.cpp)

修改内容:

构造函数中初始化热插拔监听,关联信号和槽;在浏览设备文件函数中(scanConnectedDevices),将可连接设备添加到设备列表中;槽函数中,判断文件路径是否在/devinput/下,然后再发送信号(deviceRemoved)断开设备,其次是调用浏览设备文件函数(scanConnectedDevices),获取可连接设备列表,最后是将设备文件名称用信号(deviceDetected)发送过去,用于连接;

2、添加设备(qt-everywhere-src-5.15.6\qtbase\src\platformsupport\input\evdevmouse)

该目录下主要是鼠标设备管理(qevdevmousemanager)和鼠标事件处理(qevdevmousehandler)

在设备管理文件中,可以看到调用发现设备类(qdevicediscovery),关联删除设备和添加设备;

在鼠标事件处理文件(qevdevmousehandler)中,主要是在函数(readMouseData),当连接失败后,需要做重连操作;

注:触摸屏可以做相同修改,但需要保存设备文件名称,以便再次打开;

3、源码附录

3.1、qdevicediscovery_static_p.h源码:

#ifndef QDEVICEDISCOVERY_STATIC_H

#define QDEVICEDISCOVERY_STATIC_H

//

// W A R N I N G

// -------------

//

// This file is not part of the Qt API. It exists purely as an

// implementation detail. This header file may change from version to

// version without notice, or even be removed.

//

// We mean it.

//

#include "qdevicediscovery_p.h"

#include

#include

QT_BEGIN_NAMESPACE

class QDeviceDiscoveryStatic : public QDeviceDiscovery

{

Q_OBJECT

public:

QDeviceDiscoveryStatic(QDeviceTypes types, QObject *parent = 0);

QStringList scanConnectedDevices() Q_DECL_OVERRIDE;

private slots:

//重新更换设备文件,删除原有设备文件,发送新设备文件名称

void handleHotPlugWatch(const QString &path);

private:

bool checkDeviceType(const QString &device);

// 用于检测鼠标键盘热插拔

QFileSystemWatcher *m_fileWatcher;

// 原有的设备列表

QStringList m_devices;

};

QT_END_NAMESPACE

#endif // QDEVICEDISCOVERY_STATIC_H

3.2、qdevicediscovery_static.cpp源码:

#include "qdevicediscovery_static_p.h"

#include

#include

#include

#include

#include

#include

#include

#include

#include

/* android (and perhaps some other linux-derived stuff) don't define everything

* in linux/input.h, so we'll need to do that ourselves.

*/

#ifndef KEY_CNT

#define KEY_CNT (KEY_MAX+1)

#endif

#ifndef REL_CNT

#define REL_CNT (REL_MAX+1)

#endif

#ifndef ABS_CNT

#define ABS_CNT (ABS_MAX+1)

#endif

#ifndef ABS_MT_POSITION_X

#define ABS_MT_POSITION_X 0x35

#endif

#ifndef ABS_MT_POSITION_Y

#define ABS_MT_POSITION_Y 0x36

#endif

#define LONG_BITS (sizeof(long) * 8 )

#define LONG_FIELD_SIZE(bits) ((bits / LONG_BITS) + 1)

static bool testBit(long bit, const long *field)

{

return (field[bit / LONG_BITS] >> bit % LONG_BITS) & 1;

}

QT_BEGIN_NAMESPACE

Q_LOGGING_CATEGORY(lcDD, "qt.qpa.input")

QDeviceDiscovery *QDeviceDiscovery::create(QDeviceTypes types, QObject *parent)

{

return new QDeviceDiscoveryStatic(types, parent);

}

QDeviceDiscoveryStatic::QDeviceDiscoveryStatic(QDeviceTypes types, QObject *parent)

: QDeviceDiscovery(types, parent)

{

// 初始化文件监听器

m_fileWatcher = new QFileSystemWatcher(this);

m_fileWatcher->addPath(QString::fromLatin1(QT_EVDEV_DEVICE_PATH));// "dev/input/"

connect(m_fileWatcher, &QFileSystemWatcher::directoryChanged, this, &QDeviceDiscoveryStatic::handleHotPlugWatch);

qCDebug(lcDD) << "static device discovery for type" << types;

}

QStringList QDeviceDiscoveryStatic::scanConnectedDevices()

{

m_devices.clear();

QDir dir;

dir.setFilter(QDir::System);

// check for input devices

if (m_types & Device_InputMask) {

dir.setPath(QString::fromLatin1(QT_EVDEV_DEVICE_PATH));

foreach (const QString &deviceFile, dir.entryList()) {

QString absoluteFilePath = dir.absolutePath() + QLatin1Char('/') + deviceFile;

if (checkDeviceType(absoluteFilePath))

{

m_devices << absoluteFilePath;

}

}

}

// check for drm devices

if (m_types & Device_VideoMask) {

dir.setPath(QString::fromLatin1(QT_DRM_DEVICE_PATH));

foreach (const QString &deviceFile, dir.entryList()) {

QString absoluteFilePath = dir.absolutePath() + QLatin1Char('/') + deviceFile;

if (checkDeviceType(absoluteFilePath))

m_devices << absoluteFilePath;

}

}

qCDebug(lcDD) << "Found matching devices" << m_devices;

return m_devices;

}

bool QDeviceDiscoveryStatic::checkDeviceType(const QString &device)

{

int fd = QT_OPEN(device.toLocal8Bit().constData(), O_RDONLY | O_NDELAY, 0);

if (Q_UNLIKELY(fd == -1)) {

qWarning() << "Device discovery cannot open device" << device;

return false;

}

qCDebug(lcDD) << "doing static device discovery for " << device;

if ((m_types & Device_DRM) && device.contains(QString::fromLatin1(QT_DRM_DEVICE_PREFIX))) {

QT_CLOSE(fd);

return true;

}

long bitsAbs[LONG_FIELD_SIZE(ABS_CNT)];

long bitsKey[LONG_FIELD_SIZE(KEY_CNT)];

long bitsRel[LONG_FIELD_SIZE(REL_CNT)];

memset(bitsAbs, 0, sizeof(bitsAbs));

memset(bitsKey, 0, sizeof(bitsKey));

memset(bitsRel, 0, sizeof(bitsRel));

ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(bitsAbs)), bitsAbs);

ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(bitsKey)), bitsKey);

ioctl(fd, EVIOCGBIT(EV_REL, sizeof(bitsRel)), bitsRel);

QT_CLOSE(fd);

if ((m_types & Device_Keyboard)) {

if (testBit(KEY_Q, bitsKey)) {

qCDebug(lcDD) << "Found keyboard at" << device;

return true;

}

}

if ((m_types & Device_Mouse)) {

if (testBit(REL_X, bitsRel) && testBit(REL_Y, bitsRel) && testBit(BTN_MOUSE, bitsKey)) {

qCDebug(lcDD) << "Found mouse at" << device;

return true;

}

}

if ((m_types & (Device_Touchpad | Device_Touchscreen))) {

if (testBit(ABS_X, bitsAbs) && testBit(ABS_Y, bitsAbs)) {

if ((m_types & Device_Touchpad) && testBit(BTN_TOOL_FINGER, bitsKey)) {

qCDebug(lcDD) << "Found touchpad at" << device;

return true;

} else if ((m_types & Device_Touchscreen) && testBit(BTN_TOUCH, bitsKey)) {

qCDebug(lcDD) << "Found touchscreen at" << device;

return true;

} else if ((m_types & Device_Tablet) && (testBit(BTN_STYLUS, bitsKey) || testBit(BTN_TOOL_PEN, bitsKey))) {

qCDebug(lcDD) << "Found tablet at" << device;

return true;

}

} else if (testBit(ABS_MT_POSITION_X, bitsAbs) &&

testBit(ABS_MT_POSITION_Y, bitsAbs)) {

qCDebug(lcDD) << "Found new-style touchscreen at" << device;

return true;

}

}

if ((m_types & Device_Joystick)) {

if (testBit(BTN_A, bitsKey) || testBit(BTN_TRIGGER, bitsKey) || testBit(ABS_RX, bitsAbs)) {

qCDebug(lcDD) << "Found joystick/gamepad at" << device;

return true;

}

}

return false;

}

void QDeviceDiscoveryStatic::handleHotPlugWatch(const QString &path)

{

if(path.compare(QString::fromLatin1(QT_EVDEV_DEVICE_PATH)))

{

return;

}

QStringList devices;

// 先移除原来的设备

foreach (const QString &device, m_devices)

emit deviceRemoved(device);

// 获取现在的设备

// 注,这里获取的设备已经经过过滤,原因是在对该类进行实例化的时候

// 已经传进了筛选参数,如:QDeviceDiscovery::Device_Keyboard

devices = this->scanConnectedDevices();

// 重新添加设备

foreach (const QString &device, devices)

emit deviceDetected(device);

}

QT_END_NAMESPACE

3.3、qevdevmousehandler.cpp源码:

#include "qevdevmousehandler_p.h"

#include

#include

#include

#include

#include

#include

#include

#include

#include // overrides QT_OPEN

#include

#include

#ifdef Q_OS_FREEBSD

#include

#else

#include

#include

#endif

#define TEST_BIT(array, bit) (array[bit/8] & (1<<(bit%8)))

QT_BEGIN_NAMESPACE

Q_LOGGING_CATEGORY(qLcEvdevMouse, "qt.qpa.input")

std::unique_ptr QEvdevMouseHandler::create(const QString &device, const QString &specification)

{

qCDebug(qLcEvdevMouse) << "create mouse handler for" << device << specification;

bool compression = true;

int jitterLimit = 0;

int grab = 0;

bool abs = false;

const auto args = specification.splitRef(QLatin1Char(':'));

for (const QStringRef &arg : args) {

if (arg == QLatin1String("nocompress"))

compression = false;

else if (arg.startsWith(QLatin1String("dejitter=")))

jitterLimit = arg.mid(9).toInt();

else if (arg.startsWith(QLatin1String("grab=")))

grab = arg.mid(5).toInt();

else if (arg == QLatin1String("abs"))

abs = true;

}

int fd;

fd = qt_safe_open(device.toLocal8Bit().constData(), O_RDONLY | O_NDELAY, 0);

if (fd >= 0) {

::ioctl(fd, EVIOCGRAB, grab);

return std::unique_ptr(new QEvdevMouseHandler(device, fd, abs, compression, jitterLimit));

} else {

qErrnoWarning(errno, "Cannot open mouse input device %s", qPrintable(device));

return nullptr;

}

}

QEvdevMouseHandler::QEvdevMouseHandler(const QString &device, int fd, bool abs, bool compression, int jitterLimit)

: m_device(device), m_fd(fd), m_abs(abs), m_compression(compression)

{

setObjectName(QLatin1String("Evdev Mouse Handler"));

m_jitterLimitSquared = jitterLimit * jitterLimit;

// Some touch screens present as mice with absolute coordinates.

// These can not be differentiated from touchpads, so supplying abs to QT_QPA_EVDEV_MOUSE_PARAMETERS

// will force qevdevmousehandler to treat the coordinates as absolute, scaled to the hardware maximums.

// Turning this on will not affect mice as these do not report in absolute coordinates

// but will make touchpads act like touch screens

if (m_abs)

m_abs = getHardwareMaximum();

detectHiResWheelSupport();

// socket notifier for events on the mouse device

m_notify = new QSocketNotifier(m_fd, QSocketNotifier::Read, this);

connect(m_notify, &QSocketNotifier::activated,

this, &QEvdevMouseHandler::readMouseData);

}

QEvdevMouseHandler::~QEvdevMouseHandler()

{

if (m_fd >= 0)

qt_safe_close(m_fd);

}

void QEvdevMouseHandler::detectHiResWheelSupport()

{

#if defined(REL_WHEEL_HI_RES) || defined(REL_HWHEEL_HI_RES)

// Check if we can expect hires events as we will get both

// legacy and hires event and needs to know if we should

// ignore the legacy events.

unsigned char relFeatures[(REL_MAX / 8) + 1]{};

if (ioctl(m_fd, EVIOCGBIT(EV_REL, sizeof (relFeatures)), relFeatures) == -1)

return;

#if defined(REL_WHEEL_HI_RES)

m_hiResWheel = TEST_BIT(relFeatures, REL_WHEEL_HI_RES);

#endif

#if defined(REL_HWHEEL_HI_RES)

m_hiResHWheel = TEST_BIT(relFeatures, REL_HWHEEL_HI_RES);

#endif

#endif

}

// Ask touch screen hardware for information on coordinate maximums

// If any ioctls fail, revert to non abs mode

bool QEvdevMouseHandler::getHardwareMaximum()

{

unsigned char absFeatures[(ABS_MAX / 8) + 1];

memset(absFeatures, '\0', sizeof (absFeatures));

// test if ABS_X, ABS_Y are available

if (ioctl(m_fd, EVIOCGBIT(EV_ABS, sizeof (absFeatures)), absFeatures) == -1)

return false;

if ((!TEST_BIT(absFeatures, ABS_X)) || (!TEST_BIT(absFeatures, ABS_Y)))

return false;

// ask hardware for minimum and maximum values

struct input_absinfo absInfo;

if (ioctl(m_fd, EVIOCGABS(ABS_X), &absInfo) == -1)

return false;

m_hardwareWidth = absInfo.maximum - absInfo.minimum;

if (ioctl(m_fd, EVIOCGABS(ABS_Y), &absInfo) == -1)

return false;

m_hardwareHeight = absInfo.maximum - absInfo.minimum;

QScreen *primaryScreen = QGuiApplication::primaryScreen();

QRect g = QHighDpi::toNativePixels(primaryScreen->virtualGeometry(), primaryScreen);

m_hardwareScalerX = static_cast(m_hardwareWidth) / (g.right() - g.left());

m_hardwareScalerY = static_cast(m_hardwareHeight) / (g.bottom() - g.top());

qCDebug(qLcEvdevMouse) << "Absolute pointing device"

<< "hardware max x" << m_hardwareWidth

<< "hardware max y" << m_hardwareHeight

<< "hardware scalers x" << m_hardwareScalerX << 'y' << m_hardwareScalerY;

return true;

}

void QEvdevMouseHandler::sendMouseEvent()

{

int x;

int y;

if (!m_abs) {

x = m_x - m_prevx;

y = m_y - m_prevy;

}

else {

x = m_x / m_hardwareScalerX;

y = m_y / m_hardwareScalerY;

}

if (m_prevInvalid) {

x = y = 0;

m_prevInvalid = false;

}

emit handleMouseEvent(x, y, m_abs, m_buttons, m_button, m_eventType);

m_prevx = m_x;

m_prevy = m_y;

}

void QEvdevMouseHandler::readMouseData()

{

struct ::input_event buffer[32];

int n = 0;

bool posChanged = false, btnChanged = false;

bool pendingMouseEvent = false;

int eventCompressCount = 0;

forever {

int result = QT_READ(m_fd, reinterpret_cast(buffer) + n, sizeof(buffer) - n);

if (result == 0) {

qWarning("evdevmouse: Got EOF from the input device");

return;

} else if (result < 0) {

if (errno != EINTR && errno != EAGAIN) {

qErrnoWarning(errno, "evdevmouse: Could not read from input device");

// If the device got disconnected, stop reading, otherwise we get flooded

// by the above error over and over again.

if (errno == ENODEV) {

disconnect(m_notify, 0, 0, 0);

delete m_notify;

m_notify = nullptr;

qt_safe_close(m_fd);

m_fd = -1;

while(1)

{

m_fd = qt_safe_open(m_device.toLocal8Bit().constData(), O_RDONLY | O_NDELAY, 0);

if(m_fd >= 0)

{

m_notify = new QSocketNotifier(m_fd, QSocketNotifier::Read, this);

connect(m_notify, &QSocketNotifier::activated,

this, &QEvdevMouseHandler::readMouseData);

return;

}

}

}

return;

}

} else {

n += result;

if (n % sizeof(buffer[0]) == 0)

break;

}

}

n /= sizeof(buffer[0]);

for (int i = 0; i < n; ++i) {

struct ::input_event *data = &buffer[i];

if (data->type == EV_ABS) {

// Touchpads: store the absolute position for now, will calculate a relative one later.

if (data->code == ABS_X && m_x != data->value) {

m_x = data->value;

posChanged = true;

} else if (data->code == ABS_Y && m_y != data->value) {

m_y = data->value;

posChanged = true;

}

} else if (data->type == EV_REL) {

QPoint delta;

if (data->code == REL_X) {

m_x += data->value;

posChanged = true;

} else if (data->code == REL_Y) {

m_y += data->value;

posChanged = true;

} else if (!m_hiResWheel && data->code == REL_WHEEL) {

// data->value: positive == up, negative == down

delta.setY(120 * data->value);

emit handleWheelEvent(delta);

#ifdef REL_WHEEL_HI_RES

} else if (data->code == REL_WHEEL_HI_RES) {

delta.setY(data->value);

emit handleWheelEvent(delta);

#endif

} else if (!m_hiResHWheel && data->code == REL_HWHEEL) {

// data->value: positive == right, negative == left

delta.setX(-120 * data->value);

emit handleWheelEvent(delta);

#ifdef REL_HWHEEL_HI_RES

} else if (data->code == REL_HWHEEL_HI_RES) {

delta.setX(-data->value);

emit handleWheelEvent(delta);

#endif

}

} else if (data->type == EV_KEY && data->code == BTN_TOUCH) {

// We care about touchpads only, not touchscreens -> don't map to button press.

// Need to invalidate prevx/y however to get proper relative pos.

m_prevInvalid = true;

} else if (data->type == EV_KEY && data->code >= BTN_LEFT && data->code <= BTN_JOYSTICK) {

Qt::MouseButton button = Qt::NoButton;

// BTN_LEFT == 0x110 in kernel's input.h

// The range of possible mouse buttons ends just before BTN_JOYSTICK, value 0x120.

switch (data->code) {

case 0x110: button = Qt::LeftButton; break; // BTN_LEFT

case 0x111: button = Qt::RightButton; break;

case 0x112: button = Qt::MiddleButton; break;

case 0x113: button = Qt::ExtraButton1; break; // AKA Qt::BackButton

case 0x114: button = Qt::ExtraButton2; break; // AKA Qt::ForwardButton

case 0x115: button = Qt::ExtraButton3; break; // AKA Qt::TaskButton

case 0x116: button = Qt::ExtraButton4; break;

case 0x117: button = Qt::ExtraButton5; break;

case 0x118: button = Qt::ExtraButton6; break;

case 0x119: button = Qt::ExtraButton7; break;

case 0x11a: button = Qt::ExtraButton8; break;

case 0x11b: button = Qt::ExtraButton9; break;

case 0x11c: button = Qt::ExtraButton10; break;

case 0x11d: button = Qt::ExtraButton11; break;

case 0x11e: button = Qt::ExtraButton12; break;

case 0x11f: button = Qt::ExtraButton13; break;

}

m_buttons.setFlag(button, data->value);

m_button = button;

m_eventType = data->value == 0 ? QEvent::MouseButtonRelease : QEvent::MouseButtonPress;

btnChanged = true;

} else if (data->type == EV_SYN && data->code == SYN_REPORT) {

if (btnChanged) {

btnChanged = posChanged = false;

sendMouseEvent();

pendingMouseEvent = false;

} else if (posChanged) {

m_eventType = QEvent::MouseMove;

posChanged = false;

if (m_compression) {

pendingMouseEvent = true;

eventCompressCount++;

} else {

sendMouseEvent();

}

}

} else if (data->type == EV_MSC && data->code == MSC_SCAN) {

// kernel encountered an unmapped key - just ignore it

continue;

}

}

if (m_compression && pendingMouseEvent) {

int distanceSquared = (m_x - m_prevx)*(m_x - m_prevx) + (m_y - m_prevy)*(m_y - m_prevy);

if (distanceSquared > m_jitterLimitSquared)

sendMouseEvent();

}

}

QT_END_NAMESPACE

相关文章

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: