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

	Copyright (C) 2003-2004
	Hirohisa MORI <joshua@nichibun.ac.jp>
	Tomohito Nakajima <nakajima@zeta.co.jp>
	Tomoki Sekiyama <sekiyama@yahoo.co.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	<stdio.h>

#include "v/VLayout.h"
#include "VApplication.h"

extern HWND get_active_dialog();
extern int translate_accel(MSG *msg);

bool doing_layout = false;
DWORD current_time;

extern "C" {

#include "machine/gb_windows.h"
#include "machine/msequence.h"
#include "pri_level.h"
#include "xl.h"
#include "task.h"

extern "C" int ms_loop_1();
int v_loop_tid = 0;

int get_v_loop_tid()
{
	return v_loop_tid;
}


V_CALLBACK_D(do_layout)
{
	VLayout::layout_marked_window();
	doing_layout = false;
}

bool idle_task()
{
	static DWORD last_ms_loop=0;
	static DWORD last_layout=0;
	
	DWORD now = GetTickCount();
	
	if(last_ms_loop==0 || now > last_ms_loop + 100)
	{
		ms_loop_1();
		last_ms_loop = now;
	}
	
	if(last_layout==0 || now > last_layout + 3000)
	{
		if ( ! doing_layout && VLayout::need_layout() ) {
			doing_layout = true;
			vq_insert_callback(NULL,do_layout,0,0,0);
		}
		last_layout = now;
	}

	return false;
}

void new_v_loop()
{
	v_loop_tid = get_tid();
	
	MSG msg;
	while(TRUE){
		bool is_message_exists = (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) != 0);
		current_time = msg.time;

		if(is_message_exists){
			if(msg.message == WM_MSEQUENCE){
				ms_loop_1();
			}
			if(msg.message == WM_QUIT)
				break;
			if(msg.message >= WM_MOUSEFIRST && msg.message <= WM_MOUSELAST)
				VTrackedInfo::track_mouse(&msg);
			if ( translate_accel(&msg) )
				continue;
			HWND dlg = get_active_dialog();
			if ( dlg && IsDialogMessage(dlg, &msg) )
				continue;
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		else{
			idle_task();
			Sleep(1);
		}
	}
}

void v_loop(){
	new_v_loop();
}

} // extern "C"