#include "xeventmonitor.h"

#define MAX_OPENDISPLAY_COUNT 10

xEventMonitor::xEventMonitor(QObject *parent) : QThread(parent)
{
    start(QThread::LowestPriority);
}

void xEventMonitor::run()
{
    int count = 0;
    while (!isOpenDisplay) {
        if(MAX_OPENDISPLAY_COUNT <= count) {
            printf("unable to open display and opendisplay is 10 timesd\n");
            break;
        }

        msleep(500 * count);
        ++count;

        Display* display = QX11Info::display();
        if (display == NULL) {
            printf( "unable to open display\n");
            continue;
        }

        // Receive from ALL clients, including future clients.
        XRecordClientSpec clients = XRecordAllClients;
        XRecordRange* range = XRecordAllocRange();
        if (range == NULL) {
            printf("unable to allocate XRecordRange\n");
            XCloseDisplay(display);
            continue;
        }

        // Receive KeyPress, KeyRelease, ButtonPress, ButtonRelease and MotionNotify events.
        memset(range, 0, sizeof(XRecordRange));
        range->device_events.first = KeyPress;
        range->device_events.last  = MotionNotify;

        // And create the XRECORD context.
        m_context = XRecordCreateContext(display, 0, &clients, 1, &range, 1);
        if (m_context == NULL) {
            printf("XRecordCreateContext failed\n");
            XFree(range);
            continue;
        }
        XFree(range);
        XSync(display, True);

        m_displayDatalink = XOpenDisplay(NULL);
        if (m_displayDatalink == NULL) {
            printf("unable to open second display\n");
            continue;
        }

        if (!XRecordEnableContext(m_displayDatalink, m_context, callback, (XPointer) this)) {
            printf("XRecordEnableContext() failed\n");
            XCloseDisplay(m_displayDatalink);
            continue;
        }

        isOpenDisplay = true;
        XCloseDisplay(m_displayDatalink);
    }

    return;
}

void xEventMonitor::callback(XPointer ptr, XRecordInterceptData *data)
{
    ((xEventMonitor *) ptr)->handleRecordEvent(data);

    return;
}

void xEventMonitor::freeXres()
{
    XRecordDisableContext(QX11Info::display(), m_context);
    XRecordFreeContext(QX11Info::display(), m_context);
    XSync(QX11Info::display(), True);

    return;
}

void xEventMonitor::handleRecordEvent(XRecordInterceptData *data)
{
    if (data->category == XRecordFromServer) {
        xEvent *event = (xEvent *)data->data;

        switch (event->u.u.type) {
        case ButtonPress:
            if (!isWheelEvent(event->u.u.detail)) {

                emit mousePress(event->u.keyButtonPointer.rootX, event->u.keyButtonPointer.rootY);
            }

            break;
        default:
            break;
        }
    }

    XRecordFreeData(data);
    return;
}

bool xEventMonitor::isWheelEvent(int detail)
{
    return !(detail != WheelUp && detail != WheelDown && detail != WheelLeft && detail != WheelRight);
}

