/**********************************************************************
 
	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.

**********************************************************************/




#include <sys/time.h>
#include <stdio.h>
#include "task.h"
#include "v.h"
#include "pri_level.h"
#include "xl.h"

typedef struct {
	XEvent	new_event;
	VDISPLAY * new_d;
	int new_n;
} new_v_loop_type;


int
_pred(Display * d,XEvent * ev,void * arg)
{
	return True;
}

int
new_XNextEvent(new_v_loop_type * arg)
{

test_no(1);
	return XCheckIfEvent(arg->new_d->d,&arg->new_event,_pred,0);
}


int
new__redraw(new_v_loop_type * arg)
{
	_redraw(_get_vwin(arg->new_d,arg->new_event.xany.window),
			arg->new_event.xexpose.x,
			arg->new_event.xexpose.y,
			arg->new_event.xexpose.width,
			arg->new_event.xexpose.height);
	return 0;
}

int
new__button(new_v_loop_type * arg)
{
int * p;
	_button(_get_vwin(arg->new_d,arg->new_event.xany.window),
			arg->new_n,
			arg->new_event.xbutton.time,
			arg->new_event.xbutton.x,
			arg->new_event.xbutton.y);
	return 0;
}

int
new__null()
{
	_null();
	return 0;
}

int
new__invoke()
{
	_invoke();
	return 0;
}


void
new_v_loop(TKEY d)
{
new_v_loop_type arg;
int null_flag;
XL_INTERPRETER * xli;

	xli = new_xl_interpreter();
	xli->a_type = XLA_SELF;
	setup_i(xli);

	arg.new_d = (VDISPLAY*)GET_TKEY(d);
	fprintf(stderr,"!!!!! start new_v_loop(threadID :=  %d)\n",get_tid());
	fflush(stdout);


	null_flag = 0;
	for ( ; ; ) {

		if ( ms_do(new_XNextEvent,&arg,"<1>new_XNextEvent")
				 == False ) {
		struct timeval tm;
			if ( null_flag == 0 )
				new__null();
			null_flag = 1;
			tm.tv_sec = 0;
			tm.tv_usec = 10000;
			select(0,0,0,0,&tm);
			continue;
		}
		if ( null_flag )
			new__invoke();
		null_flag = 0;
		switch ( arg.new_event.type ) {
		case Expose:

			new__redraw(&arg);
			break;
		case ButtonPress:
			arg.new_n = VES_BUTTON_PRESS;

			new__button(&arg);
			break;
		case ButtonRelease:
			arg.new_n = VES_BUTTON_RELEASE;

			new__button(&arg);
			break;
		case MotionNotify:
			arg.new_n = VES_BUTTON_MOTION;

			new__button(&arg);
			break;
		}
	}
}

void
v_loop(VDISPLAY * d)
{
pthread_t tid;


	create_task(new_v_loop,(int)d,PRI_USER_INTERFACE);
	ms_loop();
}

