// valac --pkg x11 test.vala

public class Test
{
    public static int main (string[] args)
    {
        var display = new X.Display ();
        X.Window root = display.default_root_window ();

        // Get the list of client windows
        X.Atom list_prop = display.intern_atom ("_NET_CLIENT_LIST", false);
        X.Atom actual_type_return;
        int actual_format_return;
        ulong nitems_return;
        ulong bytes_after_return;
        uchar* prop_return;
        display.get_window_property (root, list_prop, 0, 1024, false, X.XA_WINDOW,
            out actual_type_return, out actual_format_return, out nitems_return,
            out bytes_after_return, out prop_return);

        // Find the window we are interested in (chromium)
        ulong length = nitems_return;
        ulong* windows = (ulong*) prop_return;
        for (uint i = 0; i < length; i++)
        {
            var window = (X.Window) windows[i];
            // Get the title of the window
            X.Atom name_prop = display.intern_atom ("_NET_WM_NAME", false);
            X.Atom type = display.intern_atom ("UTF8_STRING", false);
            uchar* title;
            display.get_window_property (window, name_prop, 0, 1024, false,
                type, out actual_type_return, out actual_format_return,
                out nitems_return, out bytes_after_return, out title);
            if ("chromium" in ((string) title).down())
            {
                // Found it, ask the window manager to bring it to the front
                stdout.printf("%s\n", (string) title);
                var event = X.Event ();
                event.xclient.type = 33; // ClientMessage, defined in X.h but not binded
                event.xclient.serial = 0;
                event.xclient.send_event = true;
                event.xclient.window = window;
                event.xclient.message_type = display.intern_atom ("_NET_ACTIVE_WINDOW", false);
                event.xclient.format = 32;
                long mask = X.EventMask.SubstructureRedirectMask | X.EventMask.SubstructureNotifyMask;
                display.send_event (root, false, mask, ref event);
                display.map_raised (window);
                break;
            }
        }
        //display.close();
        return 0;
    }
}
