summaryrefslogtreecommitdiffstats
path: root/src/input/inputEvent.cpp
blob: 9b69a3a01b6c9039ea1648e7acf7d8c581fa3721 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
 * inputEvent.cpp
 *
 *  Created on: 06.09.2010
 *      Author: brs
 */

#include <QBuffer>
#include <QByteArray>
#include <QDataStream>
#include <QKeyEvent>
#include <QMouseEvent>
#include <QString>
#include "inputEvent.h"
#include <src/util/consoleLogger.h>

// We implement operators to serialize and load an event:
QDataStream& operator <<(QDataStream& ostrm, InputEvent const& evt)
{
	ostrm << evt.type_ << evt.code_ << evt.value_;
	return ostrm;
}

QDataStream& operator >>(QDataStream& istrm, InputEvent& evt)
{
	istrm >> evt.type_ >> evt.code_ >> evt.value_;
	return istrm;
}

void eventToString(InputEvent const& evt, QString& str)
{
	QByteArray ba;
	QBuffer buf(&ba);
	buf.open(QIODevice::WriteOnly);
	QDataStream out(&buf);
	out << evt;
	str = QString::fromAscii(ba.toBase64());
}

bool eventFromString(QString const& str, InputEvent& evt)
{
	// TODO This does not do proper error checking. Only use from trusted sources!
	QByteArray ba = QByteArray::fromBase64(str.toAscii());
	QBuffer buf(&ba);
	buf.open(QIODevice::ReadOnly);
	QDataStream in(&buf);
	in >> evt;
	return true;
}

quint16 InputEvent::mouseButtonsFromQt(int b)
{
	quint16 ret = 0;
	if(b & Qt::LeftButton)
	{
		ret |= EB_LEFT;
	}
	if(b & Qt::RightButton)
	{
		ret |= EB_RIGHT;
	}
	if(b & Qt::MidButton)
	{
		ret |= EB_MIDDLE;
	}
	return ret;
}

InputEvent InputEvent::mousePressRelease(int qt_button, int qt_buttons)
{
	quint16 button = mouseButtonsFromQt(qt_button);
	quint16 buttons = mouseButtonsFromQt(qt_buttons);
	quint16 code;

	if(buttons & button)
	{
		code = EC_PRESS;
	}
	else
	{
		code = EC_RELEASE;
	}

	quint32 value = ((quint32)button << 16) | buttons;
	return InputEvent(ET_BUTTON, code, value);
}

InputEvent InputEvent::keyboardPress(int key, int mods)
{
	quint32 value = key | mods;
	return InputEvent(ET_KEY, EC_PRESS, value);
}

InputEvent InputEvent::keyboardRelease(int key, int mods)
{
	quint32 value = key | mods;
	return InputEvent(ET_KEY, EC_RELEASE, value);
}