/**
 * Launch a terminal when Ctrl-Alt-T is pressed.
 *
 * gcc -o ctrl-alt-t ctrl-alt-t.c -lX11
 *
 * Steve
 * --
 *
 * PS.  Use xbindkeys like a normal person ;)
 *
 */


#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <stdlib.h>
#include <stdio.h>


int main()
{
    Display*    dpy     = XOpenDisplay(0);
    Window      root    = DefaultRootWindow(dpy);
    XEvent      ev;

    unsigned int    modifiers       = ControlMask | Mod1Mask;
    int             keycode         = XKeysymToKeycode(dpy,XK_Q);
    Window          grab_window     = root;
    Bool            owner_events    = False;
    int             pointer_mode    = GrabModeAsync;
    int             keyboard_mode   = GrabModeAsync;


    /**
     * OK this is unpleasant but we have to cope with XGrabKey.
     *
     * XGrabKey will let us listen for "keys" with "modifiers".  But only
     * exact matches will work.
     *
     * We want to be hit by Ctrl-Alt-t but what if the user has num-lock
     * on?  That will change the modifier.
     *
     * Similarly if capslock is on then our t becomes a T.  Obviously.
     *
     *
     * So we grab the key four times:
     *
     *    Ctrl + Alt + t
     *
     *    Ctrl + Alt + t + NumLock
     *
     *    Ctrl + Alt + t + CapsLock
     *
     *    Ctrl + Alt + t + NumLock + Capslock
     *
     * And that is the difference between reliable code and bogus code.
     *
     */
    XGrabKey(dpy, keycode, modifiers, grab_window, owner_events, pointer_mode,
             keyboard_mode);
    XGrabKey(dpy, keycode, modifiers | Mod2Mask, grab_window, owner_events, pointer_mode, keyboard_mode);
    XGrabKey(dpy, keycode, modifiers | LockMask, grab_window, owner_events, pointer_mode, keyboard_mode);
    XGrabKey(dpy, keycode, modifiers | LockMask | Mod2Mask, grab_window, owner_events, pointer_mode, keyboard_mode);


    XSelectInput(dpy, root, KeyPressMask );
    while(1)
    {
        XNextEvent(dpy, &ev);
        switch(ev.type)
        {
            case KeyPress:
                /**
                 * We don't need to test the kind of key here since we've only
                 * listened to one - albeit one with multiple modifier-masks
                 */
                fprintf(stderr, "Launching terminal!\n" );
                system( "xterm" );
            default:
                break;
        }
    }

    XCloseDisplay(dpy);
    return 0;
}
