/* $Id: input.c,v 1.6 2000/10/15 18:00:52 marcus Exp $
***************************************************************************

   X server for LibGGI - Handling of input devices

   Copyright (C) 1997	   Jason McMullan	[jmcc@cs.cmu.edu]
   Copyright (C) 1997	   Michael Krause	[rawstyle@ms.demo.org]
   Copyright (C) 1998-2000 Marcus Sundberg	[marcus@ggi-project.org]

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
   THE AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
   IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

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

#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 "xggi.h"


struct xggi_hotkeys {
	uint32 keys[4];
	void (*handler)(void);
	int mask;
};

static void handle_serverkill(void);

static struct xggi_hotkeys hotkeys[] = {
    {{ GIIK_Ctrl, GIIK_Alt, GIIUC_BackSpace, GIIK_VOID },
     handle_serverkill, },
};
#define NUMHANDLERS	(sizeof(hotkeys)/sizeof(struct xggi_hotkeys))


static void
MouseQueueMovement(DeviceIntPtr device, int dx, int dy, Time tm)
{
	PtrCtrl *pCtrl = &device->ptrfeed->ctrl;

	if ((abs(dx) + abs(dy)) >= pCtrl->threshold) {
		dx = (dx * pCtrl->num) / pCtrl->den;
		dy = (dy * pCtrl->num)/ pCtrl->den;
	}

	miPointerDeltaCursor(dx, dy, tm);
}

static void
xggiQueueMouseEvent(ggi_event *ev)
{
	DevicePtr pMouse;
	xEvent xev;
	static int oldx = 0, oldy = 0;
    
	pMouse = LookupPointerDevice();
	if (!pMouse->on) return;
    
	switch (ev->any.type) {
	case evPtrAbsolute:
		miPointerDeltaCursor(ev->pmove.x - oldx, ev->pmove.y - oldy,
				     TVAL2TIME(ev->any.time));
		oldx = ev->pmove.x;
		oldy = ev->pmove.y;
		return;

	case evPtrRelative:
		MouseQueueMovement((DeviceIntPtr)pMouse,
				   ev->pmove.x, ev->pmove.y,
				   TVAL2TIME(ev->any.time));
		oldx += ev->pmove.x;
		oldy += ev->pmove.y;
		return;

	case evPtrButtonPress:
		xev.u.u.type = ButtonPress;
		break;

	case evPtrButtonRelease:
		xev.u.u.type = ButtonRelease;
		break;
	default:
		/* Unknown pointer event */
		return;
	}

	switch (ev->pbutton.button) {
	case 2:
		/* Right button */
		xev.u.u.detail = 3;
		break;
	case 3:
		/* Middle button */
		xev.u.u.detail = 2;
		break;
	default:
		/* Other button */
		xev.u.u.detail = ev->pbutton.button;
		break;
	}
	xev.u.keyButtonPointer.time = TVAL2TIME(ev->any.time);
	mieqEnqueue(&xev);

	return;
}
  
static int
xggiMouseProc(DeviceIntPtr pDevice, int onoff)
{
	BYTE *map;
	int i;
	DevicePtr pDev = (DevicePtr)pDevice;

	switch (onoff) {
	case DEVICE_INIT:
		if ((map = malloc(sizeof(BYTE)*(xggiScreens[0].ptrbuttons+1)))
		    == NULL) {
			FatalError("xggiMouseProc: Cannot allocate temporary memory!\n");
		}
		for (i = 0; i <= xggiScreens[0].ptrbuttons; i++) {
			map[i] = i;
		}
		InitPointerDeviceStruct(pDev, map, xggiScreens[0].ptrbuttons,
					miPointerGetMotionEvents,
					(PtrCtrlProcPtr)NoopDDA,
					miPointerGetMotionBufferSize());
		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
hotkeys_reset(void)
{
	int i, j;

	for (i = 0; i < NUMHANDLERS; i++) {
		hotkeys[i].mask = 0;
		for (j = 0; hotkeys[i].keys[j] != GIIK_VOID; j++) {
			hotkeys[i].mask |= (1 << j);
		}
	}
}


static void
handle_serverkill(void)
{
	if (xggiInfo.allowzap) {
		FatalError("Server killed by Ctrl-Alt-Backspace\n");
	}
}


static void
handle_hotkeys(ggi_event *ev)
{
	if (ev->any.type == evKeyPress) {
		int i, j;
		for (i = 0; i < NUMHANDLERS; i++) {
			for (j = 0; hotkeys[i].keys[j] != GIIK_VOID; j++) {
				if (ev->key.sym == hotkeys[i].keys[j]) {
					hotkeys[i].mask &= ~(1 << j);
					if (hotkeys[i].mask == 0) {
						hotkeys[i].handler();
					}
				}
			}
		}
	} else {
		int i, j;
		for (i = 0; i < NUMHANDLERS; i++) {
			for (j = 0; hotkeys[i].keys[j] != GIIK_VOID; j++) {
				if (ev->key.sym == hotkeys[i].keys[j]) {
					hotkeys[i].mask |= (1 << j);
				}
			}
		}
	}
}


static void
xggiDispatchEvents(void)
{
	struct timeval tv = {0,0};
	int n;
	int screen = 0;

	if (! ggiEventPoll(MASTER_VIS, emAll, &tv)) return;

	n = ggiEventsQueued(MASTER_VIS, emAll);
	while (n--) {
		ggi_event ev;

		ggiEventRead(MASTER_VIS, &ev, emAll);
		
		switch (ev.any.type) {
		case evPtrRelative:
		case evPtrAbsolute:
		case evPtrButtonPress:
		case evPtrButtonRelease:
			xggiQueueMouseEvent(&ev);
			break;

		case evKeyPress:
		case evKeyRelease:
			handle_hotkeys(&ev);
		case evKeyRepeat:
			xggiQueueKeyboardEvent(&ev);
			break;

		case evCommand:
			if (!xggiScreens[screen].ismapped) break;

			if (ev.cmd.code == GGICMD_REQUEST_SWITCH) {
				ggi_cmddata_switchrequest *data = (void*)
					ev.cmd.data;
				if (data->request == GGI_REQSW_UNMAP) {
					ggi_event ev;

					ev.cmd.size = sizeof(gii_cmd_nodata_event);
					ev.cmd.type = evCommand;
					ev.cmd.code =GGICMD_ACKNOWLEDGE_SWITCH;

					/* Map X display away */
					xggiUnmapDisplay();
					/* Reset hotkey state */
					hotkeys_reset();
					/* Acknowledge unmap */
					ggiEventSend(MASTER_VIS, &ev);
					/* Disable pointer events */
					ggiSetEventMask(MASTER_VIS, emCommand |
							emExpose | emKeyboard);
					/* We don't want any more events now */
					goto end_of_eventloop;
				}
			}
			break;

		case evExpose:
			if (!xggiScreens[screen].ismapped) {
				xggiMapDisplay();
				/* Enable pointer events */
				ggiSetEventMask(MASTER_VIS, emCommand |
						emExpose |
						emKeyboard | emPointer);
			}
			break;

		default:
			break;
		}
	}
  end_of_eventloop:
}


static CARD32
xggiSnarf(OsTimerPtr timer, CARD32 time, pointer data)
{
	xggiDispatchEvents();

	return 20 /* Millis */;
}

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

/*****************************
 * Initailize input handlers *
 *****************************/
void
InitInput(int argc, char *argv[])
{
	ggi_event ev;

	DeviceIntPtr p, k;

	ggiSetEventMask(MASTER_VIS, emCommand | emExpose
			| emKeyboard | emPointer);

	p = AddInputDevice(xggiMouseProc, TRUE);
	k = AddInputDevice(xggiKeybdProc, TRUE);
	RegisterPointerDevice(p);
	RegisterKeyboardDevice(k);
	miRegisterPointerDevice(screenInfo.screens[0], p);
	mieqInit((DevicePtr) k, (DevicePtr) p);
	
	xggiInputTimer();

	/* Don't halt the application on unmap */
	ev.cmd.size = sizeof(gii_cmd_nodata_event);
	ev.cmd.type = evCommand;
	ev.cmd.code = GGICMD_NOHALT_ON_UNMAP;
	ggiEventSend(MASTER_VIS, &ev);

	/* Init hotkey stuff */
	hotkeys_reset();
}

