#include <cstdio>
#include <unistd.h>

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

struct App {
    Fl_Window *window;
    Fl_Box *timer;
    Fl_Box *input;
    int seconds;
};

// Called when standard input becomes readable.
static void input_cb(int fd, void *data)
{
    App *a = static_cast<App*>(data);

    char buffer[256];
    ssize_t n = read(fd, buffer, sizeof(buffer) - 1);

    if (n > 0) {
        buffer[n] = '\0';
        a->input->copy_label(buffer);
    } else if (n == 0) {
        // EOF: standard input has been closed.
        Fl::remove_fd(fd);
        a->input->copy_label("Input closed");
    }
}

// Called after one second.
static void timer_cb(void *data)
{
    App *a = static_cast<App*>(data);

    ++a->seconds;

    char text[80];
    std::snprintf(text, sizeof(text),
                  "Elapsed: %d seconds", a->seconds);

    a->timer->copy_label(text);

    // Schedule the next invocation.
    Fl::repeat_timeout(1.0, timer_cb, data);
}

// Called when the user closes the window.
static void close_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);

    Fl::remove_fd(STDIN_FILENO);
    Fl::remove_timeout(timer_cb, data);

    a->window->hide();
}

int main()
{
    Fl_Window window(450, 200, "FLTK event loop");

    Fl_Box timer(20, 20, 410, 50, "Elapsed: 0 seconds");
    timer.box(FL_DOWN_BOX);

    Fl_Box input(20, 80, 410, 50, "Type something in the terminal");
    input.box(FL_DOWN_BOX);

    Fl_Button quit(175, 145, 100, 35, "Quit");

    window.end();

    App app = { &window, &timer, &input, 0 };

    window.callback(close_cb, &app);
    quit.callback(close_cb, &app);

    // Watch standard input (file descriptor 0).
    Fl::add_fd(STDIN_FILENO, FL_READ, input_cb, &app);

    // Schedule the first timer invocation.
    Fl::add_timeout(1.0, timer_cb, &app);

    window.show();

    return Fl::run();
}
