#include "winlib.h"

V_LOCAL arch_window_p libv_root_window = NULL; /* FIXME */

V_LOCAL char_p LIBV_ROOT_WINDOW = "libv_root_window";

/* fixme: is this stuff really needed under X ??? */

arch_window_p	V_CALL
archCreateRootWindow(void)
{
	ARCH_CALLER_NAME(archCreateRootWindow)
	char *dpy_name = getenv("DISPLAY");
	arch_window_p aw;
	aw = (arch_window_p)memAllocZ(sizeof(arch_window_t));
	INIT_COMMON_WINDOW_FIELDS(aw,NULL);
	aw->dpy = XOpenDisplay(dpy_name);
	if(!aw->dpy)
	{
		SYSCALL_FAILED_1STR("XOpenDisplay",strSafe(dpy_name));
		CLEAR_COMMON_WINDOW_FIELDS_EXCEPT_LINK(aw);
		memFree(aw);
		return NULL;
	}
	aw->scrnum = DefaultScreen(aw->dpy);
	aw->wnd /* fixme */ = aw->root_window = RootWindow(aw->dpy,aw->scrnum);
	aw->width = DisplayWidth(aw->dpy,aw->scrnum);
	aw->height = DisplayHeight(aw->dpy,aw->scrnum);
	aw->creation_time = archTickCount();
	strCopy(aw->title,LIBV_ROOT_WINDOW,MAX_WINDOW_TITLE);
#ifdef	CONFIG_XF86_VIDMODE
	aw->modelines = NULL;
#endif	/* CONFIG_XF86_VIDMODE */
	libv_root_window = aw; /* FIXME */
	return aw;
}

arch_window_p
archGetRootWindow(void)
{
	ARCH_CALLER_NAME(archGetRootWindow)
 	if(libv_root_window && !VALID_ARCH_WINDOW(libv_root_window))
 	{
 		ARCH_WARNING("pseudo-root exists, but isn't linked to LibV");
 		return NULL;
 	}
 	return libv_root_window;
}

/* fixme: platform-independent */

void	V_CALL
archTryCloseRootWindow()
{
	TREE_ITERATOR;
	int child_count = 0;
	arch_window_p root_window = archGetRootWindow();
	if(!root_window)
		return;
	TREE_FOR_EACH_CHILD(root_window)
	{
		child_count ++;
	}
	if(!child_count)
		archWinClose(root_window);
}

#ifdef	CONFIG_XF86_VIDMODE

V_LOCAL void
X_FreeModeInfo(arch_window_p aw)
{
	int i;
	if(!aw->vidmodes)
	{
		aw->num_vidmodes = 0;
		return;
	}
	if(aw->num_vidmodes)
	{
		for(i=0;i < aw->num_vidmodes;i++)
		{
			if(aw->modelines[i]->privsize)
#ifdef	__cplusplus
				XFree(modelines[i]->c_private);
#else	/* !__cplusplus */
				XFree(aw->modelines[i]->private);
#endif	/* !__cplusplus */
		}
		XFree(aw->modelines);
		aw->modelines = NULL;
	}
	aw->num_vidmodes = 0;
	memFree(aw->vidmodes);
	aw->vidmodes = NULL;
}

#endif	/* CONFIG_XF86_VIDMODE */

/*
 * Original copyright (C) Id Software.
 */
V_LOCAL void
X_CreateNullCursor(arch_window_p aw)
{
	Pixmap cursormask;
    XGCValues xgc;
    GC gc;
    XColor dummycolour;
	if(aw->need_free_null_cursor)
	{
		XFreeCursor(aw->dpy,aw->null_cursor);
		aw->need_free_null_cursor = false;
	}
    cursormask = XCreatePixmap(aw->dpy, aw->root_window, 1, 1, 1/*depth*/);
    xgc.function = GXclear;
    gc =  XCreateGC(aw->dpy, cursormask, GCFunction, &xgc);
    XFillRectangle(aw->dpy, cursormask, gc, 0, 0, 1, 1);
    dummycolour.pixel = 0;
    dummycolour.red = 0;
    dummycolour.flags = 04;
    aw->null_cursor = XCreatePixmapCursor(aw->dpy, cursormask, cursormask,
		&dummycolour,&dummycolour, 0,0);
    XFreePixmap(aw->dpy,cursormask);
    XFreeGC(aw->dpy,gc);
	aw->need_free_null_cursor = true;
}

V_LOCAL void
archWinQueryVideoModes(arch_window_p aw)
{
	ARCH_CALLER_NAME(archWinQueryVideoModes)
#ifdef	CONFIG_XF86_VIDMODE
	int i, op, event, error, mn, mj, nummodes;
	vidmode_p ptr;
	X_FreeModeInfo(aw);
	if(DefaultDepth(aw->dpy,DefaultScreen(aw->dpy)) <= 8)
	{
		ARCH_ERROR("Only Hi/True color modes supported");
		return;
	}
	if(!XQueryExtension(aw->dpy,
		"XFree86-VidModeExtension",&op,&event, &error) ||
		!XF86VidModeQueryVersion(aw->dpy,&mj,&mn))
	{
		ARCH_ERROR("XFree86-VidModeExtension not supported by X server");
		return;
	}
	if(XQueryExtension(aw->dpy,"XINERAMA",&op,&event, &error))
	{
		ARCH_ERROR("found XINERAMA; disabling mode changes.");
		return;
	}
	
	if(!XF86VidModeGetAllModeLines(aw->dpy,DefaultScreen(aw->dpy),
		&nummodes,&aw->modelines)
		|| nummodes <= 0 || !aw->modelines)
	{
		ARCH_ERROR("XF86VidModeGetAllModeLines() failed.");
		return;
	}
	aw->num_vidmodes = nummodes;
	aw->vidmodes = (vidmode_p)memAllocZ(aw->num_vidmodes * sizeof(vidmode_t));
	ptr = aw->vidmodes;
	for(i=0;i < aw->num_vidmodes;i++)
	{
		ptr->width = aw->modelines[i]->hdisplay;
		ptr->height = aw->modelines[i]->vdisplay;
		ptr->bpp = DefaultDepth(aw->dpy,DefaultScreen(aw->dpy));
		ptr->refresh = aw->modelines[i]->dotclock * 1000 / 
			(aw->modelines[i]->htotal * aw->modelines[i]->vtotal);
		ptr->modeline = i;
		if(aw->modelines[i]->flags & 0x20) /* doublescan */
			ptr->refresh /= 2;
		ptr++;
	}
#else	/* !CONFIG_XF86_VIDMODE */
	ARCH_ERROR("requires CONFIG_XF86_VIDMODE");
	return;
#endif	/* !CONFIG_XF86_VIDMODE */
}

/*
 * FIXME: common for both platforms
 */
vidmode_p	V_CALL
archWinGetVideoMode(arch_window_p aw,int mode_num)
{
	if(!aw->vidmodes)
		archWinQueryVideoModes(aw);
	if(!aw->vidmodes || mode_num < 0 || mode_num >= aw->num_vidmodes)
		return NULL;
	return aw->vidmodes + mode_num;
}

vboolean V_CALL
archWinSetVideoMode(arch_window_p aw,int new_mode)
{
	ARCH_CALLER_NAME(archWinSetVideoMode)
	int i;
#ifdef	CONFIG_XF86_VIDMODE
	if(new_mode == -1)
	{
		/* restore default mode */
		if(aw->current_vidmode != -1)
		{
			XF86VidModeSwitchToMode(aw->dpy,aw->scrnum,aw->modelines[0]);
			aw->current_vidmode = -1;
		}
	}
	else
	{
		vidmode_p mode = archWinGetVideoMode(aw,new_mode);
		if(!mode)
			return false;
		if(XF86VidModeSwitchToMode(aw->dpy,aw->scrnum,
			aw->modelines[mode->modeline]))
		{
			aw->current_vidmode = new_mode;
			XRaiseWindow(aw->dpy,aw->wnd);
		}
		else
		{
			ARCH_ERROR("XF86VidModeSwitchToMode() failed.");
			return false;
		}
	}
	return true;
#else	/* !CONFIG_XF86_VIDMODE */
	ARCH_ERROR("requires CONFIG_XF86_VIDMODE");
	return false;
#endif	/* !CONFIG_XF86_VIDMODE */
}

#if 0

/* TODO */

/*
 * Translates X keycodes into LibV key codes.
 */
V_LOCAL	s32_t
X2keycode(XEvent *event)
{
	unsigned int keycode;
	keycode_t key;
	char buf[64];
	KeySym keysym;
	XLookupString(&event->xkey,buf,sizeof(buf),&keysym,0);
    key=key_unknown;
	keycode=event->xkey.keycode;
	switch(keysym)
	{
        case XK_KP_9:
		case XK_KP_Page_Up:	key=key_kp_9; break;
		case XK_Page_Up:	key=key_pageup; break;
        case XK_KP_3:
		case XK_KP_Page_Down:	key=key_kp_3; break;
		case XK_Page_Down:	key=key_pagedown; break;
        case XK_KP_7:
		case XK_KP_Home:	key=key_kp_7; break;
		case XK_Home:		key=key_home; break;
        case XK_KP_1:
		case XK_KP_End:		key=key_kp_1; break;
		case XK_End:		key=key_end; break;
        case XK_KP_4:
		case XK_KP_Left:	key=key_kp_4; break;
		case XK_Left:		key=key_left; break;
        case XK_KP_6:
		case XK_KP_Right:	key=key_kp_6; break;
		case XK_Right:		key=key_right; break;
        case XK_KP_2:
		case XK_KP_Down:	key=key_kp_2; break;
		case XK_Down:		key=key_down; break;
        case XK_KP_8:
		case XK_KP_Up:		key=key_kp_8; break;
		case XK_Up:			key=key_up; break;
		case XK_Escape:		key=key_escape; break;
		case XK_KP_Enter:	key=key_kp_enter; break;
		case XK_Return:		key=key_enter; break;
		case XK_Tab:		key=key_tab; break;
		case XK_F1:		 	key=key_f1; break;
		case XK_F2:		 	key=key_f2; break;
		case XK_F3:		 	key=key_f3; break;
		case XK_F4:		 	key=key_f4; break;
		case XK_F5:		 	key=key_f5; break;
		case XK_F6:		 	key=key_f6; break;
		case XK_F7:			key=key_f7; break;
		case XK_F8:		 	key=key_f8;	break;
		case XK_F9:		 	key=key_f9;	break;
		case XK_F10:		key=key_f10; break;
		case XK_F11:		key=key_f11; break;
		case XK_F12:		key=key_f12; break;
		case XK_BackSpace:	key=key_backspace; break;
		case XK_KP_Delete:	key=key_kp_dot; break;
		case XK_Delete:		key=key_delete; break;
		case XK_Pause:		key=key_pause; break;
		case XK_Shift_L:	key=key_left_shift; break;
		case XK_Shift_R:	key=key_right_shift; break;
		case XK_Execute:
		case XK_Control_L:	key=key_left_control; break;
		case XK_Control_R:	key=key_right_control; break;
		case XK_Alt_L:
		case XK_Meta_L:		key=key_left_alt; break;
		case XK_Alt_R:
		case XK_Meta_R:		key=key_right_alt; break;
        case XK_KP_5:
		case XK_KP_Begin:	key=key_kp_5; break;
        case XK_KP_0:
		case XK_KP_Insert:	key=key_kp_0; break;
		case XK_Insert:		key=key_insert; break;
		case XK_KP_Multiply: key=key_kp_asterisk; break;
		case XK_KP_Add:		key=key_kp_plus; break;
		case XK_KP_Subtract: key=key_kp_minus; break;
		case XK_KP_Divide:	key=key_kp_slash; break;
        case XK_Scroll_Lock: key=key_scrolllock; break;
        case XK_Sys_Req:	key=key_printscreen; break;
        default: break;
    }
    if(key!=key_unknown)
    	return key;
	/* This is HACK: we just ignore X locale ! */
	switch(keycode)
	{
		case 10:		key=key_1; break;
		case 11:		key=key_2; break;
		case 12:		key=key_3; break;
		case 13:		key=key_4; break;
		case 14:		key=key_5; break;
		case 15:		key=key_6; break;
		case 16:		key=key_7; break;
		case 17:		key=key_8; break;
		case 18:		key=key_9; break;
		case 19:		key=key_0; break;
		case 20:		key=key_minus; break;
		case 21:		key=key_equal; break;
		case 51:		key=key_back_slash; break;
		
		case 49:		key=key_back_quote; break;
		case 24:		key=key_Q; break;
		case 25:		key=key_W; break;
		case 26:		key=key_E; break;
		case 27:		key=key_R; break;
		case 28:		key=key_T; break;
		case 29:		key=key_Y; break;
		case 30:		key=key_U; break;
		case 31:		key=key_I; break;
		case 32:		key=key_O; break;
		case 33:		key=key_P; break;
		case 34:		key=key_left_bracket; break;
		case 35:		key=key_right_bracket; break;
		case 66:		key=key_capslock; break;
		case 38:		key=key_A; break;
		case 39:		key=key_S; break;
		case 40:		key=key_D; break;
		case 41:		key=key_F; break;
		case 42:		key=key_G; break;
		case 43:		key=key_H; break;
		case 44:		key=key_J; break;
		case 45:		key=key_K; break;
		case 46:		key=key_L; break;
		case 47:		key=key_colon; break;
		case 48:		key=key_apostrophe; break;
		
		case 52:		key=key_Z; break;
		case 53:		key=key_X; break;
		case 54:		key=key_C; break;
		case 55:		key=key_V; break;
		case 56:		key=key_B; break;
		case 57:		key=key_N; break;
		case 58:		key=key_M; break;
		case 59:		key=key_comma; break;
		case 60:		key=key_dot; break;
		case 61:		key=key_slash; break;
		
		case 65:		key=key_space; break;
		case 77:		key=key_numlock; break;
		case 91:		key=key_kp_dot; break;
		case 111:		key=key_printscreen; break;
		case 115:		key=key_left_win; break;
		case 116:		key=key_right_win; break;
		case 117:		key=key_context; break;

		default:		break;
	}
	return key;
}

/*
 * Retrieves information about modifier keys.
 */

V_LOCAL	void
X_get_locale(ui_message_p msg)
{
	MSG_KEY_LOCALE(msg) = MSG_LOCALE_EN;
}

V_LOCAL void
win32_get_key_modifiers(ui_message_p msg)
{
	XQueryKeymap
	/*
	u8_t keys[256];
	memZero(keys,256);
	GetKeyboardState(keys);
	if(keys[VK_NUMLOCK] & 1)
		MSG_KEY_FLAGS(msg) |= MSG_KEY_NUM;
	else
		MSG_KEY_FLAGS(msg) &= ~MSG_KEY_NUM;
	if(keys[VK_CAPITAL] & 1)
		MSG_KEY_FLAGS(msg) |= MSG_KEY_CAPS;
	else
		MSG_KEY_FLAGS(msg) &= ~MSG_KEY_CAPS;
	if(keys[VK_SCROLL] & 1)
		MSG_KEY_FLAGS(msg) |= MSG_KEY_SCROLL;
	else
		MSG_KEY_FLAGS(msg) &= ~MSG_KEY_SCROLL;
    if(keys[VK_LCONTROL] & 0x80)
		MSG_KEY_FLAGS(msg) |= MSG_KEY_LCONTROL;
	else
		MSG_KEY_FLAGS(msg) &= ~MSG_KEY_LCONTROL;
    if(keys[VK_LSHIFT] & 0x80)
		MSG_KEY_FLAGS(msg) |= MSG_KEY_LSHIFT;
	else
		MSG_KEY_FLAGS(msg) &= ~MSG_KEY_LSHIFT;
    if(keys[VK_LMENU] & 0x80)
		MSG_KEY_FLAGS(msg) |= MSG_KEY_LMETA;
	else
		MSG_KEY_FLAGS(msg) &= ~MSG_KEY_LMETA;
    if(keys[VK_RCONTROL] & 0x80)
		MSG_KEY_FLAGS(msg) |= MSG_KEY_RCONTROL;
	else
		MSG_KEY_FLAGS(msg) &= ~MSG_KEY_RCONTROL;
    if(keys[VK_RSHIFT] & 0x80)
		MSG_KEY_FLAGS(msg) |= MSG_KEY_RSHIFT;
	else
		MSG_KEY_FLAGS(msg) &= ~MSG_KEY_RSHIFT;
    if(keys[VK_RMENU] & 0x80)
		MSG_KEY_FLAGS(msg) |= MSG_KEY_RMETA;
	else
		MSG_KEY_FLAGS(msg) &= ~MSG_KEY_RMETA;
	*/
}

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

V_LOCAL vboolean
default_proc(arch_window_p aw,ui_message_p msg)
{
	switch(msg->event)
	{
		case ui_event_activate:
			aw->active = MSG_WIN_ACTIVE(msg);
			/* Extra stuff for fullscreen windows */
			if(aw->vidmode_changed)
			{
				if(aw->active)
				{
					if(aw->need_restore_vidmode)
					{
						archSetVideoMode(&aw->last_vidmode,NULL);
						aw->need_restore_vidmode = false;
					}
					SetWindowPos(aw->wnd,HWND_TOP,0,0,0,0,
						SWP_NOSIZE|SWP_NOMOVE);
				}
				else
				{
					archSetVideoMode(&aw->first_vidmode,NULL);
					aw->need_restore_vidmode = true;
					SetWindowPos(aw->wnd,HWND_NOTOPMOST,0,0,0,0,
						SWP_NOSIZE|SWP_NOMOVE);
				}
			}
			break;
		case ui_event_close:
			if(aw->vidmode_changed)
			{
				archSetVideoMode(&aw->first_vidmode,NULL);
				aw->vidmode_changed = false;
				/*
				SetWindowPos(aw->wnd,HWND_NOTOPMOST,0,0,0,0,
					SWP_NOSIZE|SWP_NOMOVE);
				*/
			}	
			break;
		case ui_event_move:
			aw->left = MSG_WIN_LEFT(msg);
			aw->top = MSG_WIN_TOP(msg);
			break;
		case ui_event_size:
			aw->width = MSG_WIN_WIDTH(msg);
			aw->height = MSG_WIN_HEIGHT(msg);
			break;
#ifndef	CONFIG_ENABLE_AUTOREPEAT
		case ui_event_key_down:
			if(MSG_KEY_FLAGS(msg) & MSG_KEY_WAS_DOWN)
				return true;
#endif	/* !CONFIG_ENABLE_AUTOREPEAT */
		case ui_event_mouse_move:
        	if(aw->auto_warp_pointer)
            {
            	s32_t cx = aw->width / 2;
            	s32_t cy = aw->height / 2;
				/* Avoid recursion */
				if(MSG_MOUSE_X(msg) == cx && MSG_MOUSE_Y(msg) == cy)
					return true;
				/* Store deltas */
				MSG_MOUSE_X(msg) -= cx;
				MSG_MOUSE_Y(msg) -= cy;
				archWinWarpPointer(aw,cx,cy);
            }
#ifdef	DISCARD_DUPLICATE_MOUSEMOVE
			if(aw->last_mx == MSG_MOUSE_X(msg) &&
				aw->last_my == MSG_MOUSE_Y(msg))
				return true;
			aw->last_mx = MSG_MOUSE_X(msg);
			aw->last_my = MSG_MOUSE_Y(msg);
#endif	/* DISCARD_DUPLICATE_MOUSEMOVE */
			break;
		default:
			break;
	}
	return false;
}

V_LOCAL vboolean
X_window_proc(arch_window_p aw,...,DWORD time)
{
	RECT rc;
	PAINTSTRUCT ps;
	ui_message_t ui_msg;
	arch_raw_message_t raw_msg;
	vboolean in_dispatch_message, need_post_mouse_move = false;
	memZero(&ui_msg,sizeof(ui_message_t));
	if(!time)
	{
		in_dispatch_message = true;
		time = GetTickCount();
	}
	else
		in_dispatch_message = false;
	ui_msg.time = (vec_t)0.001 * (time - aw->creation_time);
	ui_msg.event = ui_event_unknown;
	switch(msg)
	{
		case WM_ACTIVATE:
			aw->active = LOWORD(wparam) != WA_INACTIVE;
			ui_msg.event = ui_event_activate;
			ui_msg.code[0] = aw->active ? 1 : 0;
			break;
		case WM_CLOSE:
			ui_msg.event = ui_event_close;
			break;
		case WM_PAINT:
			memZero(&rc,sizeof(RECT));
			ui_msg.event = ui_event_redraw;
			if(!GetUpdateRect(aw->wnd,&rc,FALSE))
				return true;
			BeginPaint(aw->wnd,&ps);
			if(aw->clears)
				PatBlt(aw->dc,rc.left,rc.top,
					rc.right - rc.left,rc.bottom-rc.top,BLACKNESS);
			EndPaint(aw->wnd,&ps);
			MSG_DRAW_LEFT(&ui_msg) = rc.left;
			MSG_DRAW_TOP(&ui_msg) = rc.top;
			MSG_DRAW_RIGHT(&ui_msg) = rc.right;
			MSG_DRAW_BOTTOM(&ui_msg) = rc.bottom;
			break;
		case WM_MOVE:
			if(GetUpdateRect(aw->wnd,&rc,FALSE))
			{
				PatBlt(aw->dc,rc.left,rc.top,
					rc.right - rc.left,rc.bottom-rc.top,BLACKNESS);
			}
			ui_msg.event = ui_event_move;
			ui_msg.code[0] = (int)LOWORD(lparam);
			ui_msg.code[1] = (int)HIWORD(lparam);
			break;
		case WM_SIZE:
			if(GetUpdateRect(aw->wnd,&rc,FALSE))
			{
				PatBlt(aw->dc,rc.left,rc.top,
					rc.right - rc.left,rc.bottom-rc.top,BLACKNESS);
			}
			ui_msg.event = ui_event_size;
			ui_msg.code[0] = (int)LOWORD(lparam);
			ui_msg.code[1] = (int)HIWORD(lparam);
			break;
		case WM_KEYDOWN:
		case WM_SYSKEYDOWN:
			ui_msg.event = ui_event_key_down;
			MSG_KEY_CODE(&ui_msg) = win32_vk2keycode(wparam,lparam);
			win32_get_key_modifiers(&ui_msg);
			win32_get_locale(&ui_msg);
			if(lparam & (1 << 30))
				MSG_KEY_FLAGS(&ui_msg) |= MSG_KEY_WAS_DOWN;
			/*
			 * FIXME: we leave global input_state untouched (should get rid of it).
			 * Implement another inputKeycodeToChar() in incodes.c.
			 */
			MSG_KEY_CHAR(&ui_msg) = inputKeycodeToChar(MSG_KEY_CODE(&ui_msg));
			break;
		case WM_KEYUP:
		case WM_SYSKEYUP:
			ui_msg.event = ui_event_key_up;
			MSG_KEY_CODE(&ui_msg) = win32_vk2keycode(wparam,lparam);
			win32_get_key_modifiers(&ui_msg);
			win32_get_locale(&ui_msg);
			MSG_KEY_CHAR(&ui_msg) = 0;
			break;
		case WM_MOUSEMOVE:
			ui_msg.event = ui_event_mouse_move;
			MSG_MOUSE_X(&ui_msg) = SIGNED_LOWORD(lparam);
			MSG_MOUSE_Y(&ui_msg) = SIGNED_HIWORD(lparam);
			win32_get_key_modifiers(&ui_msg);
			win32_get_locale(&ui_msg);
			break;
		case WM_LBUTTONDOWN:
			ui_msg.event = ui_event_key_down;
			MSG_KEY_CODE(&ui_msg) = key_left_mouse;
			win32_get_key_modifiers(&ui_msg);
			win32_get_locale(&ui_msg);
			need_post_mouse_move = true;
			break;
		case WM_MBUTTONDOWN:
			ui_msg.event = ui_event_key_down;
			MSG_KEY_CODE(&ui_msg) = key_middle_mouse;
			win32_get_key_modifiers(&ui_msg);
			win32_get_locale(&ui_msg);
			need_post_mouse_move = true;
			break;
		case WM_RBUTTONDOWN:
			ui_msg.event = ui_event_key_down;
			MSG_KEY_CODE(&ui_msg) = key_right_mouse;
			win32_get_key_modifiers(&ui_msg);
			win32_get_locale(&ui_msg);
			need_post_mouse_move = true;
			break;
		case WM_LBUTTONUP:
			ui_msg.event = ui_event_key_up;
			MSG_KEY_CODE(&ui_msg) = key_left_mouse;
			win32_get_key_modifiers(&ui_msg);
			win32_get_locale(&ui_msg);
			need_post_mouse_move = true;
			break;
		case WM_MBUTTONUP:
			ui_msg.event = ui_event_key_up;
			MSG_KEY_CODE(&ui_msg) = key_middle_mouse;
			win32_get_key_modifiers(&ui_msg);
			win32_get_locale(&ui_msg);
			need_post_mouse_move = true;
			break;
		case WM_RBUTTONUP:
			ui_msg.event = ui_event_key_up;
			MSG_KEY_CODE(&ui_msg) = key_right_mouse;
			win32_get_key_modifiers(&ui_msg);
			win32_get_locale(&ui_msg);
			need_post_mouse_move = true;
			break;
		default:
			break;
	}
	raw_msg.message = msg;
	raw_msg.wparam = wparam;
	raw_msg.lparam = lparam;
	if(aw->before_process && aw->before_process(aw,&raw_msg))
		return true;
	if(default_proc(aw,&ui_msg))
		return true;
	if(aw->after_process && aw->after_process(aw,&ui_msg))
		return true;
	if(ui_msg.event != ui_event_unknown)
	{
		fifoPush(&aw->raw_messages,&ui_msg);
		if(need_post_mouse_move)
		{
			POINT pt;
			ui_msg.event = ui_event_mouse_move;
			GetCursorPos(&pt);
			ScreenToClient(aw->wnd,&pt);
			MSG_MOUSE_X(&ui_msg) = pt.x;
			MSG_MOUSE_Y(&ui_msg) = pt.y;
			win32_get_key_modifiers(&ui_msg);
			win32_get_locale(&ui_msg);
			/* we leave ui_msg.time unmodified */
			fifoPush(&aw->raw_messages,&ui_msg);
		}
		if(!in_dispatch_message)
			return true;
	}
	return false;
}

/*
 * Default callback. All system-generated messages and messages
 * unknown to win32_window_proc() have to be processed here.
 */
V_LOCAL LRESULT CALLBACK
win32_default_window_proc(HWND wnd,UINT msg,WPARAM wparam,LPARAM lparam)
{
	arch_window_p aw = (arch_window_p)GetWindowLong(wnd,GWL_USERDATA);
	if(!VALID_ARCH_WINDOW(aw) || aw->wnd != wnd)
		aw = NULL;
	switch(msg)
	{
		case WM_CREATE:
			return 0;
		case WM_PAINT:
			if(aw && win32_window_proc(aw,msg,wparam,lparam,0))
				return 0;
			break;
		case WM_ERASEBKGND:
			return 1; /* no further erasing required */
		case WM_PALETTECHANGED:
			if(aw && aw->palette && aw->wnd != (HWND)wparam)
			{
				SelectPalette(aw->dc,aw->palette,FALSE);
				RealizePalette(aw->dc);
			}
			break;
		case WM_QUERYNEWPALETTE:
			if(aw && aw->palette)
			{
				SelectPalette(aw->dc,aw->palette,FALSE);
				RealizePalette(aw->dc);
				if(aw->vidmode_changed)
					SetSystemPaletteUse(aw->dc,SYSPAL_NOSTATIC);
				return TRUE;
			}
			return FALSE;
		/*
		 * PeekMessage() _never_ (???) retrieves these messages,
		 * so we transfer control by hand.
		 */
		case WM_ACTIVATE:
			if(aw && win32_window_proc(aw,msg,wparam,lparam,0))
				return 0;
			break;
		case WM_MOVE:
			if(aw && win32_window_proc(aw,msg,wparam,lparam,0))
				return 0;
			break;
		case WM_SIZE:
			if(aw && win32_window_proc(aw,msg,wparam,lparam,0))
				return 0;
			break;
		case WM_CLOSE:
			if(aw && win32_window_proc(aw,msg,wparam,lparam,0))
				return 0;
			break;
		default:
			break;
	}
	return DefWindowProc(wnd,msg,wparam,lparam);
}

V_LOCAL void
translate_messages(arch_window_p aw)
{
	vboolean got_resize = false, got_move = false, got_redraw = false;
	ui_message_t msg, last_resize, last_move;
	vec_t redraw_time = 0;
	s32_t left = MAXLONG, top = MAXLONG, right = 0, bottom = 0;
	while(fifoPop(&aw->raw_messages,&msg))
	{
		switch(msg.event)
		{
			case ui_event_size:
				got_resize = true;
				memCopy(&last_resize,&msg,sizeof(ui_message_t));
				break;
			case ui_event_move:
				got_move = true;
				memCopy(&last_move,&msg,sizeof(ui_message_t));
				break;
			case ui_event_redraw:
				if(left > MSG_DRAW_LEFT(&msg))
					left = MSG_DRAW_LEFT(&msg);
				if(top > MSG_DRAW_TOP(&msg))
					top = MSG_DRAW_TOP(&msg);
				if(right < MSG_DRAW_RIGHT(&msg))
					right = MSG_DRAW_RIGHT(&msg);
				if(bottom < MSG_DRAW_BOTTOM(&msg))
					bottom = MSG_DRAW_BOTTOM(&msg);
				got_redraw = true;
				redraw_time = msg.time;
				break;
			default:
				fifoPush(&aw->messages,&msg);
		}
	}
	if(got_move)
		fifoPush(&aw->messages,&last_move);
	if(got_resize)
		fifoPush(&aw->messages,&last_resize);
	if(got_redraw && left < right && top < bottom)
	{
		msg.event = ui_event_redraw;
		msg.time = redraw_time;
		MSG_DRAW_LEFT(&msg) = left;
		MSG_DRAW_TOP(&msg) = top;
		MSG_DRAW_RIGHT(&msg) = right;
		MSG_DRAW_BOTTOM(&msg) = bottom;
		fifoPush(&aw->messages,&msg);
	}
}

vboolean	V_CALL
archWinPending(arch_window_p aw)
{
	MSG msg;
	while(PeekMessage(&msg,aw->wnd,0,0,PM_REMOVE))
	{
		/*
		 * We don't process WM_CHAR message, but this call is still
		 * needed for ALT+SPACE system menu activation.
		 */
		TranslateMessage(&msg);
		if(win32_window_proc(aw,msg.message,msg.wParam,msg.lParam,msg.time))
			DefWindowProc(msg.hwnd,msg.message,msg.wParam,msg.lParam);
		else
			DispatchMessage(&msg);
		translate_messages(aw);
	}
	return fifoCount(&aw->messages) ? true : false;
}

vboolean	V_CALL
archWinNextMessage(arch_window_p aw,ui_message_p message_ret)
{
	while(!archWinPending(aw))
		WaitMessage();
	return fifoPop(&aw->messages,message_ret);
}

/* ====================================================================================== */

V_LOCAL vboolean
win32_register_window_class(arch_window_p aw,void_p icon)
{
	ARCH_CALLER_NAME(win32_register_window_class)
	return false;
}

void_p	V_CALL
archLoadWindowIcon(char_p icon_id)
{
	return (void_p)LoadIconImage(icon_id);
}

arch_window_p V_CALL
archWinOpen(arch_window_p parent,char *title,void_p icon,
	s32_t left,s32_t top,s32_t width,s32_t height,
	vboolean caption,vboolean allow_resize)
{
	ARCH_CALLER_NAME(archWinOpen)
	RECT rc;
	arch_window_p aw;
	DWORD style = WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
	if(allow_resize)
	{
		if(!caption)
		{
			ARCH_ERROR("can't create resizeable window without caption");
			return NULL;
		}
		style |= WS_OVERLAPPEDWINDOW;
	}
	else
	{
		style |= WS_POPUP;
		if(caption)
			style |= WS_CAPTION;
	}
	aw = (arch_window_p)memAlloc(sizeof(arch_window_t));
	if(!aw)
	{
		ARCH_ERROR("memAlloc() failed");
		return NULL;
	}
	INIT_COMMON_WINDOW_FIELDS(aw);
	fifoInit(&aw->raw_messages,sizeof(ui_message_t));
	if(!win32_register_window_class(aw,icon))
	{
		CLEAR_COMMON_WINDOW_FIELDS(aw);
		memFree(aw);
		return NULL;
	}
	if(title)
		strCopy(aw->title,title,MAX_WINDOW_TITLE);
	aw->creation_time = GetTickCount();
	aw->wnd = CreateWindow(aw->class_name,
		aw->title, style, left, top,
		width, height,
		parent ? parent->wnd : NULL,
		parent ? (HMENU)(1+vpsCount(&parent->children)) : NULL,
		GetModuleHandle(NULL),NULL);
	if(!aw->wnd)
	{
		SYSCALL_FAILED("CreateWindow");
		CLEAR_COMMON_WINDOW_FIELDS(aw);
		memFree(aw);
		return NULL;
	}
	SetWindowLong(aw->wnd,GWL_USERDATA,(LONG)aw);
	GetClientRect(aw->wnd,&rc);
	aw->delta_w = width - rc.right;
	aw->delta_h = height - rc.bottom;
	archWinResize(aw,width,height);
	if(parent)
	{
		vpsPush(&parent->children,aw);
		aw->child_id = vpsCount(&parent->children);
		aw->parent = parent;
	}
	aw->dc = GetDC(aw->wnd);
	aw->palette = NULL;
	return aw;
}

vboolean V_CALL
archWinVideoMode(arch_window_p aw,vidmode_p new_mode,colorquad_p palette)
{
	vboolean result = true;
	vidmode_p old_mode;
	if(!new_mode)
	{
		if(aw->vidmode_changed)
		{
			archSetVideoMode(&aw->first_vidmode,NULL);
			aw->vidmode_changed = false;
		}
		result = true;
	}
	else
	{
		if(aw->vidmode_changed)
			old_mode = NULL;
		else
			old_mode = &aw->first_vidmode;
		if(archSetVideoMode(new_mode,old_mode))
		{
			aw->vidmode_changed = true;
			result = true;
		}
		else
			result = false;
	}
	if(palette)
	{
		LOGPALETTE *lp;
		unsigned int i, n, bpp = GetDeviceCaps(aw->dc,BITSPIXEL);
		n = 1 << bpp;
		lp = (PLOGPALETTE)memAlloc(sizeof(LOGPALETTE) + n * sizeof(PALETTEENTRY));
		lp->palVersion=0x300;
		lp->palNumEntries = (unsigned short)n;
		for(i=0;i < n;i++)
		{
			lp->palPalEntry[i].peRed = palette[i].r;
			lp->palPalEntry[i].peGreen = palette[i].g;
			lp->palPalEntry[i].peBlue = palette[i].b;
			lp->palPalEntry[i].peFlags = 0;
		}
		if(aw->vidmode_changed)
			SetSystemPaletteUse(aw->dc,SYSPAL_NOSTATIC);
		if(aw->palette)
		{
			SelectObject(aw->dc,GetStockObject(DEFAULT_PALETTE));
			DeleteObject(aw->palette);
			aw->palette = NULL;
		}
		aw->palette = CreatePalette(lp);
		memFree(lp);
		SelectPalette(aw->dc,aw->palette,FALSE);
		RealizePalette(aw->dc);
	}
	return result;
}

vboolean	V_CALL
archWinShow(arch_window_p aw,vboolean show)
{
	if(show)
	{
		if(!aw->visible)
		{
			aw->visible = ShowWindow(aw->wnd,SW_SHOW) ? true : false;
			UpdateWindow(aw->wnd);
		}
		return aw->visible;
	}
	aw->visible = ShowWindow(aw->wnd,SW_HIDE) ? false : true;
	return !aw->visible;
}

void V_CALL
archWinFocus(arch_window_p aw)
{
	/*
	 * We process WM_SETFOCUS and WM_KILLFOCUS in win32_window_proc
	 */
	SetFocus(aw->wnd);
	SetActiveWindow(aw->wnd);
}

vboolean	V_CALL
archWinResize(arch_window_p aw,s32_t width,s32_t height)
{
	return SetWindowPos(aw->wnd,HWND_NOTOPMOST,
		0,0,width + aw->delta_w,height + aw->delta_h,
		SWP_NOMOVE | SWP_NOZORDER) ? true : false;
}

vboolean	V_CALL
archWinMove(arch_window_p aw,s32_t left,s32_t top)
{
	return SetWindowPos(aw->wnd,HWND_NOTOPMOST,left,top,0,0,
		SWP_NOSIZE | SWP_NOZORDER) ? true : false;
}

vboolean	V_CALL
archWinWarpPointer(arch_window_p aw,s32_t x,s32_t y)
{
	XWarpPointer(aw->dpy,None,ar->win, 0, 0, 0, 0, x, y);
}

void	V_CALL
archWinCapturePointer(arch_window_p aw,vboolean capture)
{
	if(capture)
	{
		if(!aw->pointer_captured)
		{
			XGrabPointer(aw->dpy,aw->win,True,0,GrabModeAsync,
				GrabModeAsync,aw->win,None,CurrentTime);
			aw->pointer_captured = true;
		}
	}
	else
	{
		if(aw->pointer_captured)
		{
			XUngrabPointer(aw->dpy,CurrentTime);
			aw->pointer_captured = false;
		}
	}
}

void	V_CALL
archWinShowPointer(arch_window_p aw,vboolean show)
{
	if(show)
	{
		if(aw->_hidden)
		{
			XUndefineCursor(win->dpy,win->win);
			win->cursor_hidden = false;
		}
	}
	else
	{
		if(!win->cursor_hidden)
		{
			XDefineCursor(win->dpy,win->win,win->null_cursor);
			win->cursor_hidden = true;
		}
	}



void V_CALL
archCaptureKeyboard(arch_window_p win,vboolean capture)
{
	if(capture)
	{
		if(!win->keyboard_captured)
		{
			XGrabKeyboard(win->dpy,win->win,False,GrabModeAsync,
				GrabModeAsync,CurrentTime);
			win->keyboard_captured = true;
		}
	}
	else
	{
		if(win->keyboard_captured)
		{
			XUngrabKeyboard(win->dpy,CurrentTime);
			win->keyboard_captured = false;
		}
	}
}

void	V_CALL
archWinClose(arch_window_p aw)
{
	ui_message_t msg;
	arch_window_p child;
	if(!VALID_ARCH_WINDOW(aw))
		return;
	/*
	 * Destroy all child windows
	 */
	while(vpsPop(&aw->children,(void**)(&child)))
		if(VALID_ARCH_WINDOW(child))
			archWinClose(child);
	/*
	 * If window has a parent, remove it from parent's list
	 */
	if(aw->parent)
	{
		vsize_t i;
		vp_stack_p owner_list = &(aw->parent->children);
		for(i=0;i<vpsCount(owner_list);i++)
			if(vpsGet(owner_list,i) == aw)
				vpsSet(owner_list,i,NULL);
		/* archWinPostMessage(aw->parent,ui_event_child_closed,0,0,0,0); */
	}
	if(aw->vidmode_changed)
	{
		archSetVideoMode(&aw->first_vidmode,NULL);
		aw->vidmode_changed = false;
		SetWindowPos(aw->wnd,HWND_NOTOPMOST,0,0,0,0,SWP_NOSIZE|SWP_NOMOVE);
	}	
	/* Destroy palette */
	if(aw->palette)
	{
		SelectObject(aw->dc,GetStockObject(DEFAULT_PALETTE));
		DeleteObject(aw->palette);
	}
	ReleaseDC(aw->wnd,aw->dc);
	/* Destroy window */
	DestroyWindow(aw->wnd);
	/* Process all pending messages */
	while(archWinPending(aw))
		archWinNextMessage(aw,&msg);
	/* Unregister class */
	UnregisterClass(aw->class_name,GetModuleHandle(NULL));
	CLEAR_COMMON_WINDOW_FIELDS(aw);
	fifoClear(&aw->raw_messages);
	memFree(aw);
}

#endif

int main()
{
	return 0;
}
