#include <allegro.h>
#include "gui.h"
#include "gui-keyboard.h"


static volatile char kb_down[KEY_MAX];
static char kb_was_down[KEY_MAX];


static void kb_handler(int scancode)
{
    int sc = scancode & 0x7f;

    kb_down[sc] = ((scancode & 0x80) ? 0 : 1);
}
END_OF_STATIC_FUNCTION(kb_handler);

/*------------------------------------------------------------*/

void gui_update_keyboard(Widget *focus_object)
{
#define KEY_PRESSED(x)		( (kb_down[x]) && !(kb_was_down[x]))
#define KEY_HELD(x)		( (kb_down[x]) &&  (kb_was_down[x]))
#define KEY_RELEASED(x)		(!(kb_down[x]) &&  (kb_was_down[x]))
#define KEY_ALWAYS_OFF(x)	(!(kb_down[x]) && !(kb_was_down[x]))

    int i;

    for (i = 0; i < KEY_MAX; i++) {
	if (KEY_PRESSED(i))
	    [focus_object receiveMessage:MSG_KEY_PRESSED :i];
	if (KEY_HELD(i))
	    [focus_object receiveMessage:MSG_KEY_HELD :i];
	if (KEY_RELEASED(i))
	    [focus_object receiveMessage:MSG_KEY_RELEASED :i];

	kb_was_down[i] = kb_down[i];
    }

#undef KEY_PRESSED
#undef KEY_HELD
#undef KEY_RELEASED
#undef KEY_ALWAYS_OFF
}


int gui_keyboard_init(void)
{
    install_keyboard();

    LOCK_VARIABLE(kb_down);
    LOCK_VARIABLE(kb_was_down);
    LOCK_FUNCTION(kb_handler);
    keyboard_lowlevel_callback = kb_handler;

    return 0;
}


void gui_keyboard_shutdown(void)
{
    keyboard_lowlevel_callback = 0;
}
