+#include "multikbd.h"
+#include "ui_multikbd.h"
+
+#include <QX11Info>
+#include <QDebug>
+
+#include <X11/Xlib.h>
+#include <X11/extensions/XInput2.h>
+#include <X11/Xutil.h>
+
+MultiKBD::MultiKBD(QWidget *parent) :
+ QWidget(parent),
+ ui(new Ui::MultiKBD),
+ xiInited(false)
+{
+ ui->setupUi(this);
+}
+
+MultiKBD::~MultiKBD()
+{
+ delete ui;
+}
+
+void MultiKBD::showEvent ( QShowEvent * )
+{
+ if (xiInited) return;
+
+ Display *dpy = x11Info().display();
+
+ /* XInput Extension available? */
+ int eventID, errorID;
+ if (!XQueryExtension(dpy, "XInputExtension", &xiOpcode, &eventID, &errorID)) {
+ qCritical() << "X Input extension not available";
+ }
+
+ /* Which version of XI2? We support 2.0 */
+ int major = 2, minor = 0;
+ if (XIQueryVersion(dpy, &major, &minor) == BadRequest) {
+ qCritical() << "XI2 not available. Server supports" << major << "." <<
+ minor;
+ }
+
+ qDebug() << "System is sane";
+
+
+ // Now let's listen to keypress events
+ XIEventMask eventmask;
+ unsigned char mask [1] = { 0 }; // will change
+ eventmask.deviceid = XIAllMasterDevices;
+ eventmask.mask_len = sizeof (mask); // in bytes, for whatever reason...
+ eventmask.mask = mask;
+ XISetMask(mask, XI_KeyPress);
+ XISelectEvents (dpy, winId(), &eventmask, 1);
+
+ xiInited = true;
+
+ /*activateWindow();
+ raise();
+ setFocus(Qt::OtherFocusReason);*/
+}
+
+void MultiKBD::handleKeyPress(int device, const char *string)
+{
+ qDebug() << "Device" << device << "String" << string;
+}
+
+bool MultiKBD::handleX11Event(XEvent *event)
+{
+ if (!xiInited) return false;
+ Display *dpy = x11Info().display();
+
+ if (event->xcookie.type == GenericEvent && event->xcookie.extension == xiOpcode
+ && event->xcookie.evtype == XI_KeyPress && XGetEventData(dpy, &event->xcookie)) {
+
+ XIDeviceEvent *d_ev = (XIDeviceEvent*) event->xcookie.data;
+ KeyCode keycode = d_ev->detail;
+ int kbdid = d_ev->deviceid;
+
+ if (!(d_ev->flags & XIKeyRepeat)) {
+ int keysyms_per_keycode;
+ KeySym keysym = XGetKeyboardMapping (dpy, keycode, 1, &keysyms_per_keycode)[0];
+ handleKeyPress(kbdid, XKeysymToString(keysym));
+ }
+
+ XFreeEventData(dpy, &event->xcookie);
+
+ return true;
+ }
+
+ return false;
+}