/*-
 * amigaIo.c --
 *	Functions to handle input from the keyboard and mouse.
 *
 * Copyright (c) 1987 by the Regents of the University of California
 *
 * Permission to use, copy, modify, and distribute this
 * software and its documentation for any purpose and without
 * fee is hereby granted, provided that the above copyright
 * notice appear in all copies.  The University of California
 * makes no representations about the suitability of this
 * software for any purpose.  It is provided "as is" without
 * express or implied warranty.
 *
 *
 */

/************************************************************
Copyright (c) 1995 by Daniver Limited (Gary Henderson)
Copyright 1994 by Eduardo Horvath
Copyright 1987 by Sun Microsystems, Inc. Mountain View, CA.

                    All Rights Reserved

Permission  to  use,  copy,  modify,  and  distribute   this
software  and  its documentation for any purpose and without
fee is hereby granted, provided that the above copyright no-
tice  appear  in all copies and that both that copyright no-
tice and this permission notice appear in  supporting  docu-
mentation,  and  that the names of Sun or MIT not be used in
advertising or publicity pertaining to distribution  of  the
software  without specific prior written permission. Sun and
M.I.T. make no representations about the suitability of this
software for any purpose. It is provided "as is" without any
express or implied warranty.

SUN DISCLAIMS ALL WARRANTIES WITH REGARD TO  THIS  SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FIT-
NESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SUN BE  LI-
ABLE  FOR  ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,  DATA  OR
PROFITS,  WHETHER  IN  AN  ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION  WITH
THE USE OR PERFORMANCE OF THIS SOFTWARE.

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

#ifndef	lint
static char sccsid[] = "%W %G Copyright 1987 Sun Micro";
#endif

#include    "amiga.h"
#include    "opaque.h"

int	    	lastEventTime = 0;
extern int      screenIsSaved;
extern void	SaveScreens();
Bool		amigaEmulateMiddleButton = FALSE;
Bool		amigaEmulateRightButton = FALSE;

/*-
 *-----------------------------------------------------------------------
 * TimeSinceLastInputEvent --
 *	Function used for screensaver purposes by the os module.
 *
 * Results:
 *	The time in milliseconds since there last was any
 *	input.
 *
 * Side Effects:
 *	None.
 *
 *-----------------------------------------------------------------------
 */
int
TimeSinceLastInputEvent()
{
    struct timeval	now;

    gettimeofday (&now, (struct timezone *)0);

    if (lastEventTime == 0) {
	lastEventTime = TVTOMILLI(now);
    }
    return TVTOMILLI(now) - lastEventTime;
}

/*-
 *-----------------------------------------------------------------------
 * ProcessInputEvents --
 *	Retrieve all waiting input events and pass them to DIX in their
 *	correct chronological order. Only reads from the system pointer
 *	and keyboard.
 *
 * Results:
 *	None.
 *
 * Side Effects:
 *	Events are passed to the DIX layer.
 *
 *-----------------------------------------------------------------------
 */
void
ProcessInputEvents ()
{
    mieqProcessInputEvents ();
    miPointerUpdate ();
}

/*
 *-----------------------------------------------------------------------
 * amigaEnqueueEvents
 *	When a SIGIO is received, read device hard events and
 *	enqueue them using the mi event queue
 */

amigaEnqueueEvents ()
{
    register Firm_event    *ptrEvents,    	/* Current pointer event */
			   *kbdEvents;	    	/* Current keyboard event */
    register int	    numPtrEvents, 	/* Number of remaining pointer
						 * events */
			    numKbdEvents;   	/* Number of remaining
						 * keyboard events */
    int	    	  	    nPE,    	    	/* Original number of pointer
						 * events */
			    nKE;    	    	/* Original number of
						 * keyboard events */
    Bool		    PtrAgain,		/* need to (re)read */
			    KbdAgain;		/* need to (re)read */
    DevicePtr		    pPointer;
    DevicePtr		    pKeyboard;
    register PtrPrivPtr     ptrPriv;
    register KbPrivPtr	    kbdPriv;
    Firm_event	  	    *lastEvent;	    	/* Last event processed */
    enum {
	NoneYet, Ptr, Kbd
    }			    lastType = NoneYet;	/* Type of last event */

    pPointer = LookupPointerDevice();
    pKeyboard = LookupKeyboardDevice();
    if (!pPointer->on || !pKeyboard->on)
	return;

    if ( amigaUseSunWindows() ) {
    } 
    else {
	ptrPriv = (PtrPrivPtr)pPointer->devicePrivate;
	kbdPriv = (KbPrivPtr)pKeyboard->devicePrivate;
	
	numPtrEvents = 0;
	PtrAgain = TRUE;
	numKbdEvents = 0;
	KbdAgain = TRUE;
	lastEvent = (Firm_event *)0;

	/*
	 * So long as one event from either device remains unprocess, we loop:
	 * Take the oldest remaining event and pass it to the proper module
	 * for processing. The DDXEvent will be sent to ProcessInput by the
	 * function called.
	 */
	while (1) {
	    /*
	     * Get events from both the pointer and the keyboard, storing the number
	     * of events gotten in nPE and nKE and keeping the start of both arrays
	     * in pE and kE
	     */
	    if ((numPtrEvents == 0) && PtrAgain) {
		ptrEvents = (* ptrPriv->GetEvents) (pPointer, &nPE, &PtrAgain);
		numPtrEvents = nPE;
	    }
	    if ((numKbdEvents == 0) && KbdAgain) {
		kbdEvents = (* kbdPriv->GetEvents) (pKeyboard, &nKE, &KbdAgain);
		numKbdEvents = nKE;
	    }
	    if ((numPtrEvents == 0) && (numKbdEvents == 0))
		break;
	    if (numPtrEvents && numKbdEvents) {
		if (timercmp (&kbdEvents->time, &ptrEvents->time, <)) {
		    (* kbdPriv->EnqueueEvent) (pKeyboard, kbdEvents);
		    numKbdEvents--;
		    lastEvent = kbdEvents++;
		    lastType = Kbd;
		} else {
		    (* ptrPriv->EnqueueEvent) (pPointer, ptrEvents,
					       numPtrEvents > 1 ? &ptrEvents [1] :
					       NULL);
		    numPtrEvents--;
		    lastEvent = ptrEvents++;
		    lastType = Ptr;
		}
	    } else if (numKbdEvents) {
		(* kbdPriv->EnqueueEvent) (pKeyboard, kbdEvents);
		numKbdEvents--;
		lastEvent = kbdEvents++;
		lastType = Kbd;
	    } else {
		(* ptrPriv->EnqueueEvent) (pPointer, ptrEvents,
					   numPtrEvents > 1 ? &ptrEvents [1] :
							      NULL);
		numPtrEvents--;
		lastEvent = ptrEvents++;
		lastType = Ptr;
	    }
	}
	if (lastEvent)
	    lastEventTime = TVTOMILLI(lastEvent->time);
    }
}


/*-
 *-----------------------------------------------------------------------
 * SetTimeSinceLastInputEvent --
 *	Set the lastEventTime to now.
 *
 * Results:
 *	None.
 *
 * Side Effects:
 *	lastEventTime is altered.
 *
 *-----------------------------------------------------------------------
 */
void
SetTimeSinceLastInputEvent()
{
    struct timeval now;

    gettimeofday (&now, (struct timezone *)0);
    lastEventTime = TVTOMILLI(now);
}

/*
 * DDX - specific abort routine.  Called by AbortServer().
 */
void
AbortDDX()
{
    int		i;
    ScreenPtr	pScreen;

    signal (SIGIO, SIG_IGN);
    amigaChangeKbdTranslation (LookupKeyboardDevice (), FALSE);
    amigaNonBlockConsoleOff ((char *) 0);
    for (i = 0; i < screenInfo.numScreens; i++)
    {
	pScreen = screenInfo.screens[i];
	(*pScreen->SaveScreen) (pScreen, SCREEN_SAVER_OFF);
	amigaDisableCursor (pScreen);
    }
    exit (1);
}

/* Called by GiveUp(). */
void
ddxGiveUp()
{
    AbortDDX ();
}

int
ddxProcessArgument (argc, argv, i)
    int	argc;
    char *argv[];
    int	i;
{
    extern void UseMsg();
    extern Bool FlipPixels;
    extern int displayWidth;
    extern int displayHeight;
    extern int displayDepth;
    extern int displayXOffset;
    extern int displayYOffset;
    extern Bool amigaDontZap;

    if (strcmp (argv[i], "-ar1") == 0) {	/* -ar1 int */
	if (++i >= argc) UseMsg ();
	autoRepeatInitiate = 1000 * (long)atoi(argv[i]);
	return 2;
    }
    if (strcmp (argv[i], "-ar2") == 0) {	/* -ar2 int */
	if (++i >= argc) UseMsg ();
	autoRepeatDelay = 1000 * (long)atoi(argv[i]);
	return 2;
    }
    if (strcmp (argv[i], "-debug") == 0) {	/* -debug */
	return 1;
    }
    if (strcmp (argv[i], "-flipPixels") == 0) {	/* -flipPixels */
	FlipPixels = TRUE;
	return 1;
    }
    if (strcmp (argv[i], "-W") == 0 ||
        strcmp (argv[i], "-width") == 0) {		/* -W int */
	if (++i >= argc) UseMsg ();
	displayWidth = (long)atoi(argv[i]);
	return 2;
    }
    if (strcmp (argv[i], "-H") == 0 ||
        strcmp (argv[i], "-height") == 0) {	/* -H int */
	if (++i >= argc) UseMsg ();
	displayHeight = (long)atoi(argv[i]);
	return 2;
    }
    if (strcmp (argv[i], "-D") == 0 ||
        strcmp (argv[i], "-depth") == 0) {		/* -D int */
	if (++i >= argc) UseMsg ();
	displayDepth = (long)atoi(argv[i]);
	return 2;
    }
    if (strcmp (argv[i], "-X") == 0) {		/* -X int */
	if (++i >= argc) UseMsg ();
	displayXOffset = (long)atoi(argv[i]);
	return 2;
    }
    if (strcmp (argv[i], "-Y") == 0) {		/* -Y int */
	if (++i >= argc) UseMsg ();
	displayYOffset = (long)atoi(argv[i]);
	return 2;
    }
    if (strcmp (argv[i], "-nozap") == 0 ||
        strcmp (argv[i], "-nopanickeys") == 0) {	/* -nozap */
	amigaDontZap = TRUE;
	return 1;
    }
    if (strcmp (argv[i], "-emulateright") == 0 ||
        strcmp (argv[i], "-3") == 0)
    {
	amigaEmulateRightButton = TRUE;
	return 1;
    }

    if (strcmp (argv[i], "-emulatemiddle") == 0 ||
        strcmp (argv[i], "-2") == 0)
    {
	amigaEmulateMiddleButton = TRUE;
	return 1;
    }

    return 0;
}

void
ddxUseMsg()
{
    ErrorF("-ar1 int               set autorepeat initiate time\n");
    ErrorF("-ar2 int               set autorepeat interval time\n");
    ErrorF("-debug                 disable non-blocking console mode\n");
    ErrorF("-width int             set display width in pixels\n");
    ErrorF("-height int            set display height in pixels\n");
    ErrorF("-depth int             set display depth in pixels\n");
    ErrorF("-X int                 set display X offset in pixels\n");
    ErrorF("-Y int                 set display Y offset in pixels\n");
    ErrorF("-nopanickeys           disable CTRL-ALT-BACKSPACE key sequence\n");
    ErrorF("-emulatemiddle (or -2) Emulate middle button on 2-button mouse\n");
    ErrorF("-emulateright (or -3)  Emulate right button on 2-button mouse\n");
    ErrorF("                       (Both buttons pressed together)\n");
}
