sdlterm/tests/test_sdl_events.cc
author Radek Brich <radek.brich@devl.cz>
Wed, 03 Sep 2014 08:57:24 +0200
changeset 108 11dac45bfba4
parent 72 6e0656600754
permissions -rw-r--r--
Fix cursor.

#include <SDL/SDL.h>

Uint32 timeout_callback(Uint32 interval, void *param)
{
    SDL_Event event;
    event.type = SDL_USEREVENT;
    event.user.code = 1;
    SDL_PushEvent(&event);
    return 0;
}

bool handle_events(Uint32 timeout)
{
    SDL_Event event;
    SDL_TimerID timer_id = NULL;
    bool done = false;

    if (timeout)
    {
        timer_id = SDL_AddTimer(timeout, timeout_callback, NULL);
    }

    // wait for events and handle them
    if (SDL_WaitEvent(&event))
    {
        do
        {
            switch (event.type)
            {
            case SDL_USEREVENT:
                // timeout
                if (event.user.code == 1)
                {
                    SDL_RemoveTimer(timer_id);
                    printf("timeout\n");
                }
                break; // continue loop

            case SDL_QUIT:
                printf("quit\n");
                done = true;
                break;

            case SDL_KEYUP:
                printf("keyup\n");
                if (event.key.keysym.sym == SDLK_ESCAPE)
                {
                    done = true;
                }
                break;

            case SDL_MOUSEBUTTONDOWN:
                printf("mouse button down\n");
                break;

            case SDL_MOUSEBUTTONUP:
                printf("mouse button up\n");
                break;
            }
        }
        while (SDL_PollEvent(&event));
    }
    // remove timer when other event came before timeout
    if (timeout)
    {
        SDL_RemoveTimer(timer_id);
    }
    return done;
}

int main(int argc, char **argv)
{
    SDL_Surface* screen = NULL;

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) == -1)
    {
        fprintf(stderr, "SDL_Init: %s\n", SDL_GetError());
        exit(1);
    }

    atexit(SDL_Quit);

    screen = SDL_SetVideoMode(800, 480, 16, SDL_SWSURFACE);
    if (screen == NULL)
    {
        fprintf(stderr, "SDL_SetVideoMode: %s\n", SDL_GetError());
        exit(1);
    }

    bool done = false;
    while (!done)
    {
        done = handle_events(1000);
    }

    return (0);
}