Search code examples
ceventsx11xlib

Lag using Xlib/X11 event handling in C


Beginner user of C here.

I'm trying to build a library in C using X11/Xlib so I can use it just for little projects and I'm running into a problem when trying to handle events to get input(button presses and key presses) from the user. It works fine for a while and then it starts to build up a significant lag over time.

Right now what I have is my program checking if there is an event waiting and if there is, retrieving it.

I think that my problem right now is that the events are getting stored in memory and its bogging down the program. But that's just a total guess.

Any help will be appreciated. Thank you.

EDIT: Forgot code (I knew I forgot something)

The two functions in question are:

int event_waiting()
{
    XEvent event;

    if(XCheckMaskEvent(dspy,-1,&event)) {
        if(event.type==KeyPress) {
            XPutBackEvent(dspy,&event);
            return 1;
        } else if (event.type==ButtonPress) {
            XPutBackEvent(dspy,&event);
            return 1;
        }
    } /* <<=== added missing close-curly here */
    return 0;
}

char wait()
{
    XEvent event;
    XNextEvent(dspy,&event);
    if(event.type==KeyPress) {
        saved_x = event.xkey.x;
        saved_y = event.xkey.y;
        return XLookupKeysym(&event.xkey,0);
    } else if(event.type==ButtonPress) {
        saved_x = event.xkey.x;
        saved_y = event.xkey.y;
        return event.xbutton.button;
    }
}

And then they are called in the main like so,

if (event_waiting()){
  char c = wait();
  //Switch case goes here
}

EDIT 2: UPDATED CODE

XEvent event;
if(XCheckMaskEvent(display,-1,&event)) 
{
    if(event.type==KeyPress) {
        XPutBackEvent(display,&event);
        return 1;
    } else if (event.type==ButtonPress) {
        XPutBackEvent(display,&event);
        return 1;
    }
}
XFlush(display);
return 0;

`


Solution

  • The lag, which gets worse over time, means that you have many untouched events in your event queue, which slows down XCheckMaskEvent().

    Try specifying events using XSelectInput(... ButtonPressMask | KeyPressMask), and try flushing the event queue using XFlush() if there is no event in which you are interested:

        if(event.type==KeyPress) {
            XPutBackEvent(dspy,&event);
            return 1;
        } else if (event.type==ButtonPress) {
            XPutBackEvent(dspy,&event);
            return 1;
        } else {
            XFlush(dspy); // this
        }