/* $Id: Exp $
***************************************************************************

   X server for LibGLTEX - handling of input devices

   Copyright (C) 2002 Christopher Alexander North-Keys
                      http://www.talisman.org/~erlkonig/

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

#include <stdlib.h>
#include "X11/X.h"
#define NEED_EVENTS
#include "X11/Xproto.h"

#include "scrnintstr.h"
#include "inputstr.h"
#include "mipointer.h"
#include "input.h"
#include "mi.h"

#include "keyboard.h"    /* in this directory */
  
static int xgltexMouseProc(DeviceIntPtr pDevice, int onoff)
{
	BYTE *map;
	int i;
	DevicePtr pDev = (DevicePtr)pDevice;

	switch (onoff) {
	case DEVICE_INIT:
		/* hardcode 3 buttons for now while vestiges of the old server
		   are still being removed.
		*/
#define XGLTEX_BUTTONCOUNT (3)
		if (NULL == (map = malloc(sizeof(BYTE)*(XGLTEX_BUTTONCOUNT + 1))))
			FatalError(__FUNCTION__ ": Cannot allocate temporary memory!\n");
		for (i = 0; i <= XGLTEX_BUTTONCOUNT; i++)
			map[i] = i;
		InitPointerDeviceStruct(pDev, map, XGLTEX_BUTTONCOUNT,
								miPointerGetMotionEvents,
								(PtrCtrlProcPtr)NoopDDA,
								miPointerGetMotionBufferSize());
#undef XGLTEX_BUTTONCOUNT
		free(map);
		break;
	
	case DEVICE_ON:  pDev->on = TRUE;  break;
	case DEVICE_OFF: pDev->on = FALSE; break;
	case DEVICE_CLOSE:                 break;
	}

	return Success;
}

void ProcessInputEvents(void)
{
	mieqProcessInputEvents();
	miPointerUpdate();
}

static void xgltexDispatchEvents(void)
{
	struct timeval tv = {0,0};

	/* poll for and process events from the queue */

	/* will probably call:
	   xgltexQueueMouseEvent(&ev)
	   xgltexQueueKeybdEvent(&ev)
	   ... or the like, as well as checking for normal Z events.
	*/

	/* some events may require some reinitialization - move whatever's
	   necessary in InitInput into a special function for this and
	   call it from here when needed.
	*/
}

static CARD32 xgltexSnarf(OsTimerPtr timer, CARD32 time, pointer data)
{
/*	xgltexTestPattern(); */
	xgltexDispatchEvents();
	return 20 /* Millis */;
}

static void xgltexInputTimer(void)
{
	static OsTimerPtr timer;
	timer = TimerSet(NULL, 0, 20 /* Millis */, xgltexSnarf, NULL);
}

/*****************************
 * Initailize input handlers *
 *****************************/

void InitInput(int argc, char *argv[])
{
	DeviceIntPtr p, k;

	/* set event masks */

	p = AddInputDevice(xgltexMouseProc, TRUE);
	k = AddInputDevice(xgltexKeybdProc, TRUE);
	RegisterPointerDevice(p);
	RegisterKeyboardDevice(k);
	miRegisterPointerDevice(screenInfo.screens[0], p);
	mieqInit((DevicePtr) k, (DevicePtr) p);
	
	xgltexInputTimer();

	/* do any required special initializations (hotkey setup, etc.) */
}

