/*
 *   SDL_poll.c - Support for polling file descriptors in the SDL plugin
 *   for Citrix Workspace.
 *   Copyright 2012-2013 Citrix Systems, Inc. All rights reserved.
 *
 *   $Id$
 */

#include "citrix.h"

#include <unistd.h>
#include <fcntl.h>
#include <time.h>

#include <SDL/SDL.h>

#include "mainloop.h"
#include "CTX_SDL_internal.h"
#include "SDL_loop.h"
#include "mlooplog.h"
#include "epoll_simple.h"

/* SDL lacks any notion of file descriptor polling, so we will do it with
 * system calls, in a separate thread.
 */

static SDL_Thread *Poller;

static int thread_func(void *data)
{
    /* Let the simplified poll loop in linux_loop.c do the work. */

    Epoll_init();
    Epoll_run();
    return 0;
}

/* Plugin function to register and remove callbacks for I/O readiness
 * in the style of select() and poll().  The mask is a set of
 * events, as defined for the poll() system call.
 * The return values are the EVT_XXXX definitions of the PAL.
 */

VPSTATUS SDL_select_fd(struct pal_event *evt_p, int fd, BOOLEAN is_write)
{
    /* Create the polling thread on first use. */

    if (!Poller)
        Poller = SDL_CreateThread(thread_func, NULL);

    /* Let the simplified poll loop in linux_loop.c do the work. */

    return Select_fd(evt_p, fd, is_write);
}

/* The poll loop will call back here when it has something.
 * Send the information to the main thread.
 */

void Poller_callback(int fd, int is_write)
{
    static SDL_UserEvent event = {SDL_USEREVENT, FD_READY, NULL, NULL};

    event.data1 = (void *)fd;
    event.data2 = (void *)is_write;
    SDL_PushEvent((union SDL_Event *)&event);
}

