How to wait an input without stop the program in Xlib

172 views Asked by At

The problem is this, I, am writing a chip 8 emulator in C, and i am using a library that use Xlib, for writing sprites attending input etc, the method that the library have for wait an input is this:

char gfx_wait(){
XEvent event;

gfx_flush();

while(1) {
    XNextEvent(gfx_display,&event);

    if(event.type==KeyPress) {
        saved_xpos = event.xkey.x;
        saved_ypos = event.xkey.y;
        return XLookupKeysym(&event.xkey,0);
    } else if(event.type==ButtonPress) {
        saved_xpos = event.xkey.x;
        saved_ypos = event.xkey.y;
        return event.xbutton.button;
    }
}

}

when i call this method the program stops waiting for input, I, need a methods that is called just when i press or release a button.

1

There are 1 answers

0
AudioBubble On

I just solve my problem, using this function :

    int gfx_event_waiting(unsigned char *ch)
{
       XEvent event;

       gfx_flush();

       while (1) {
               if(XCheckMaskEvent(gfx_display,-1,&event)) {
                       if(event.type==KeyPress) {
                                *ch = XLookupKeysym(&event.xkey,0);
                               return 1;
                       }else if(event.type==KeyRelease){
                                return 1;
                        }else if (event.type==ButtonPress) {
                               return 1;
                       } else {
                               return 0;
                       }
               } else {
                       return 0;
               }
       }
}

and this is the main :

    int
main(int argc, char *argv[])
{
    int x;
    int i;
    unsigned char  key_pressed,key_released;
    Init();
    LoadRom(SELECTED_ROM);
    gfx_open(WIDTH,HEIGHT,"Chip 8 Emulator");
    gfx_color(255,250,250);

    for(;;){
        if(!gfx_event_waiting(&key_pressed)){
            opcode_cycle();
            key_wait(key_released,0);

            #if DEBUG
                printf("# %d | %c #",x,key_pressed);
            #endif

            key_wait(key_pressed,1);
            key_released = key_pressed;

            gfx_clear();

            if(DrawFlag)
                Draw();

            /*Big for for simulate a delay*/
            for(i = 0; i <= 100000; i++)
                ;
        }else{
            x++;
        }
    }
}

I, am sure that there is a better way for do this , but you know, It's work...