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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
|
#include <QtGui>
#include <iostream>
#include <time.h>
int keys[] = {
Qt::Key_Z, /* prev wep */
Qt::Key_X, /* next wep */
Qt::Key_Space, /* shoot */
Qt::Key_Up,
Qt::Key_Left,
Qt::Key_Down,
Qt::Key_Right,
Qt::Key_P,
Qt::Key_Backspace,
};
std::string key_names[] = {
"Z",
"X",
"Space",
"Up",
"Left",
"Down",
"Right",
"Pause",
"Backspace",
};
#define ARRAY_SIZE(a) (sizeof (a) / sizeof *(a) )
class Application: public QApplication {
public:
Application(int argc, char **argv): QApplication(argc, argv) {
setbuf(stdout, NULL); /* disable buffering */
}
~Application(){}
bool notify(QObject *object, QEvent *event) {
bool is_pressed = event->type() == QEvent::KeyPress;
if (is_pressed || event->type() == QEvent::KeyRelease) {
if (handle_key(static_cast<QKeyEvent *>(event)->key(), is_pressed))
return true;
}
return object->event(event);
}
private:
bool handle_key(int code, bool is_pressed) {
for (unsigned int i=0; i<ARRAY_SIZE(keys); ++i) {
if (keys[i] == code) {
report_key(i + 1, is_pressed);
return true;
}
}
if (code == Qt::Key_Shift) {
release_key();
return true;
}
if (code == Qt::Key_Escape) {
std::cerr << "Escape received - quitting" << std::endl;
quit();
}
return false;
}
int getMS() {
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts)) {
perror("clock_gettime");
return 0;
}
return (ts.tv_sec * 1000) + ts.tv_nsec / 1000000;
}
int last_code;
bool last_is_pressed;
//int last_time;
void release_key() {
if (last_code && last_is_pressed) {
send_key(last_code, false);
last_is_pressed = false;
}
}
bool always_send_key(int key) {
if (!key) return false;
switch (keys[key - 1]) {
case Qt::Key_Up:
case Qt::Key_Down:
case Qt::Key_Left:
case Qt::Key_Right:
return false;
}
return true;
}
void report_key(int key, bool is_pressed) {
//int timestamp = getMS();
//bool timed_out = timestamp - last_time >= 300;
if (last_code == key && !always_send_key(key)) {
if ((is_pressed == last_is_pressed) ||
(last_is_pressed && !is_pressed)) {
//if (!timed_out) {
return;
//}
}
} else {
if (!always_send_key(last_code))
release_key();
}
last_code = key;
last_is_pressed = is_pressed;
//last_time = timestamp;
send_key(key, is_pressed);
}
void send_key(int key, bool is_pressed) {
printf("%u %u\n", key, is_pressed);
if (is_pressed)
std::cerr << key_names[key - 1] << " " << (is_pressed ? "pressed" : "released") << std::endl;
}
};
int main(int argc, char **argv) {
Application app(argc, argv);
QWidget window;
window.resize(250, 150);
window.setWindowTitle("Remote keyboard");
window.show();
return app.exec();
}
|