Question

I am trying to read state from a joystick in Vala. I can read from the joystick just fine, however, my read callback seems to block my GUI drawing.

Here is some sample code that demonstrates the issue:

using Gtk;

int main(string[] args) {
    Gtk.init(ref args);
    var window = new Window();
    var button = new Button.with_label("Click Me!");
    button.clicked.connect(() => {
        stdout.printf("Click!\n");
    });
    window.add(button);
    window.show_all();

    var fd = Posix.open("/dev/input/js0", Posix.O_RDONLY);
    var stream = new UnixInputStream(fd, true);
    var source = stream.create_source();
    source.set_callback((stream) => {
        stdout.printf("Joystick button press!\n");
        return true;
    });
    source.attach(null);

    Gtk.main();

    return 0;
}

I compile it with:

valac --pkg gtk+-3.0 --pkg gio-2.0 --pkg gio-unix-2.0 --pkg posix example.vala -o example

When I run the program from my terminal, all I get is a ton of "Joystick button press!" and no GUI rendering. It is just an empty window. When I comment out the line which attachs the source callback:

source.attach(null);

and recompile, I get the GUI with the button that reacts whenever I click it.

What am I not doing correctly to get my read callback to execute in the same loop as my GUI ?

Was it helpful?

Solution

My guess is that's because you don't read the data you're notified is available. This is a pollable source, so it's polled, thus, the callback is fired continuously. Try to retrieve the data. The C documentation advises to use g_pollable_input_stream_read_nonblocking for that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top