lena_pi/LenaPi/MouseEventSpy.cpp
Anika Raemer ce8ea8f582 Restart timer on mouse event.
Todo: call shut down script on timeout
2019-04-03 20:05:48 +02:00

88 lines
2 KiB
C++

#include "MouseEventSpy.h"
#include <QGuiApplication>
#include <QDebug>
/**
* @brief Initialize timer.
* @param parent Parent object
*/
MouseEventSpy::MouseEventSpy(QObject *parent) : QObject(parent)
{
initTimer(10000);
mTimer.start();
}
/**
* @brief Implements the singleton pattern
*
* If no instance has been created yet, create new instance and install it as event filter
* in QGuiApplication.
*/
MouseEventSpy* MouseEventSpy::instance()
{
static MouseEventSpy* inst;
if (inst == nullptr)
{
inst = new MouseEventSpy();
QGuiApplication* app = qGuiApp;
app->installEventFilter(inst);
}
return inst;
}
/**
* @brief Expand QObject::eventFilter to react to MouseEvents.
*
* Restart timer each time a mouse event is detected.
*/
bool MouseEventSpy::eventFilter(QObject* watched, QEvent* event)
{
QEvent::Type t = event->type();
if (isMouseEvent(t)
&& event->spontaneous() // Take only mouse events from outside of Qt
)
{
emit mouseEventDetected();
}
if(mTimer.isActive()){
mTimer.stop();
}
mTimer.start();
return QObject::eventFilter(watched, event);
}
/**
* @brief Initialize and connect timer.
* @param interval Timeout interval in millisecond.
*/
void MouseEventSpy::initTimer(int interval)
{
connect(&mTimer, &QTimer::timeout, this, &MouseEventSpy::onTimeout);
mTimer.setInterval(interval);
mTimer.setSingleShot(true);
}
/**
* @brief Checks whether the event type is a mouse event.
* @param t Event type
* @return Returns whether the event type is a mouse event.
*/
bool MouseEventSpy::isMouseEvent(QEvent::Type t)
{
return (t == QEvent::MouseButtonDblClick
|| t == QEvent::MouseButtonPress
|| t == QEvent::MouseButtonRelease
|| t == QEvent::MouseMove);
}
/**
* @brief Behavior on timeout: shut down RaspberryPi.
* @todo Call shutdown script.
*/
void MouseEventSpy::onTimeout()
{
qDebug() << "shutting down.";
}