#include <cstdio>
#include <cerrno>
#include <sys/select.h>

#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/x.H>

// Called once per second.
void tick(void *data)
{
    Fl_Box *box = static_cast<Fl_Box*>(data);
    static int seconds = 0;

    char text[64];
    std::sprintf(text, "Seconds: %d", ++seconds);
    box->copy_label(text);

    Fl::repeat_timeout(1.0, tick, data);
}

int main()
{
    // 1. Open the X11 connection ourselves.
    Display *display = XOpenDisplay(0);
    if (!display) {
        std::fprintf(stderr, "Cannot open X display\n");
        return 1;
    }

    // 2. Obtain the X server's socket descriptor.
    int fd = ConnectionNumber(display);

    // 3. Give the existing connection to FLTK.
    fl_open_display(display);

    Fl_Window window(300, 150, "My event loop");
    Fl_Box box(20, 40, 260, 60, "Seconds: 0");
    window.end();
    window.show();

    Fl::add_timeout(1.0, tick, &box);

    // 4. Our own main event loop.
    while (window.shown()) {
        fd_set fds;
        FD_ZERO(&fds);
        FD_SET(fd, &fds);

        timeval timeout = { 0, 50000 }; // 50 ms

        int result = select(fd + 1, &fds, 0, 0, &timeout);
        if (result < 0 && errno != EINTR)
            break;

        // 5. Let FLTK handle pending events and timers.
        Fl::wait(0.0);
    }

    Fl::remove_timeout(tick, &box);
    return 0;
}
