//
// 
//	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
// 
//	This program is free software; you can redistribute it 
//	and/or modify it under the terms of the GLOBALBASE 
//	Library General Public License (G-LGPL) as published by 
//
//	http://www.globalbase.org/
// 
//	This program is distributed in the hope that it will be 
//	useful, but WITHOUT ANY WARRANTY; without even the 
//	implied warranty of MERCHANTABILITY or FITNESS FOR A 
//	PARTICULAR PURPOSE.
//
//

//--------------------------------------------------------
//   EVENT_LIST Control
//--------------------------------------------------------

extern "C" {

#include	"machine/v_types.h"
#include	"memory_debug.h"
#include	"event_list.h"
#include	"task.h"

SEM			event_lock;
EVENT_LIST	EventList;

void
init_event()
{
	EventList.first = EventList.last = NULL;
	event_lock = new_lock(0);
}

EVENT * new_event()
{
	return (EVENT *)d_alloc(sizeof(EVENT));
}

int get_event(EVENT * outEvent)
{
EVENT * event = EventList.first;

	if ( ! event )
		return false;
	*outEvent = *event;
	lock_task(event_lock);
	EventList.first = event->next;
	EventList.counter--;
	if ( ! EventList.counter )
		EventList.last = NULL;
	d_f_ree(event);
	unlock_task(event_lock, "_GetEvent");
	return true;
}

void add_event(EVENT * event, Window win)
{
	lock_task(event_lock);
	if ( ! EventList.first )
		EventList.first = event;
	if ( EventList.last )
		EventList.last->next = event;
	EventList.last = event;
	event->next = NULL;
	event->win = win;
	EventList.counter++;
	unlock_task(event_lock, "_AddEvent");
	fflush(stdout);
}

int
_check_event(Window win, int type, int subtype)
{
EVENT *event;
Bool ret;
unsigned short eventMask;
EventRecord theEvent;
	if ( type == 0 ) {
		return ( EventList.first != NULL );
	}
	ret = false;
	lock_task(event_lock);
	for ( event = EventList.first;  event;  event = event->next ) {
		if ( event->win == win && event->type == type && event->subtype == subtype ) {
			ret = true;
			break;
		}
	}
	unlock_task(event_lock, "_CheckEvent");
	if ( type == VE_BUTTON && !ret ) {
		if ( subtype == VES_BUTTON_PRESS )
			eventMask = mDownMask;
		else if ( subtype == VES_BUTTON_RELEASE ) 
			eventMask = mUpMask;
		else return ret;
	}
	ret = EventAvail(eventMask, &theEvent);
	return ret;
}


} // extern "C"