/*-
 * sunTablet.c --
 *	Functions for playing with the tablet device.
 *
 * 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 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
#define NEED_EVENTS
#include    "sun.h"
#include    "mipointer.h"
#include    "XI.h"
#include    "XInput.h"
#include    "XIproto.h"
#include    "/home/dhuff/mouse/tablet/tbltio.h"
#include <fcntl.h>
#include <sys/filio.h>
#ifdef SVR4
#include <signal.h>
#include <sys/stropts.h>
#endif
#define TBLT_RES 20000
typedef struct {
    int		fd;
    int         mux_fd;         /* Descriptor to mux device */
    int         index;          /* kbd index once AddEnabledDevice has
				 * been called */
    int		bmask;	/* current button state */
    Atom    	sun_tablet_atom;
    int		x, y;
    unsigned char xAxis, yAxis;
    Bool	corePointer;
} sunTabPrivRec, *sunTabPrivPtr;
XI_eventPtr 	sunTabletGetEvents();
void 	  	sunTabletEnqueueEvent();
extern int              DeviceMotionNotify;
extern int              DeviceValuator;
extern int              DeviceButtonPress;
extern int              DeviceButtonRelease;
extern int              ProximityIn;
extern int              ProximityOut;
static void	sunTabletCtrl();
/*-
 *-----------------------------------------------------------------------
 * sunTabletProc --
 *	Handle the initialization, etc. of the tablet device.
 *
 * Results:
 *	none.
 *
 * Side Effects:
 *
 * Note:
 *	When using sunwindows, all input comes off a single fd, stored in the
 *	global windowFd.  Therefore, only one device should be enabled and
 *	disabled, even though the application still sees both tablet and
 *	keyboard.  We have arbitrarily chosen to enable and disable windowFd
 *	in the keyboard routine sunKbdProc rather than in sunMouseProc.
 *
 *-----------------------------------------------------------------------
 */
int
sunTabletProc (DevicePtr pTablet, int what)
{
    register int  fd;
    int	    	  format, i;
    static int	  oformat;
    char	  *device, *getenv ();
    extern int    sunTabletMotionProc();
    extern int	  sunTabletAxisChange();
    extern int	  sunTabletSetValuators();
    BYTE	  map[4];
    sunTabPrivPtr	  pPriv;
    switch (what) {
	case DEVICE_INIT:
	    if (pTablet->devicePrivate)
		 return(!Success);	/* DEVICE_INIT should only be
					 * called once */
	    pPriv = (sunTabPrivPtr)Xalloc(sizeof(sunTabPrivRec));
	    fd = open ("/dev/ttya", O_RDWR, 0);
	    if (fd < 0) {
	        Error ("Opening /dev/ttya");
	        return (!Success);
	    }
            if (ioctl(fd, I_POP, 0) < 0) {
                Error("Error popping ttya");
	        return (!Success);
            }
            if (ioctl(fd, I_POP, 0) < 0) {
                Error("Error popping ttya");
	        return (!Success);
            }
	    if (fcntl (fd, F_SETFL, (FNDELAY|FASYNC)) < 0) {
	        perror("sunTabletProc");
	        ErrorF("Can't set up tablet on fd %d\n", fd);
	    }
	    if (ioctl(fd, I_PUSH, "tblt") < 0) {
	        perror("sunTabletProc");
	        ErrorF("ioctl I_PUSH failed");
            }
	    pPriv->fd = fd;
	    pPriv->bmask = 0;
	    pPriv->x = 0;
	    pPriv->y = 0;
	    pPriv->xAxis = 0;
	    pPriv->yAxis = 1;
	    pPriv->corePointer = FALSE;
	    pPriv->sun_tablet_atom = MakeAtom(XI_TABLET, strlen(XI_TABLET), FALSE);
	    pTablet->devicePrivate = (pointer) pPriv;
	    pTablet->on = FALSE;
	    map[1] = 1;
	    map[2] = 2;
	    map[3] = 3;
	    InitButtonClassDeviceStruct(pTablet, 3, map);
            InitValuatorClassDeviceStruct(pTablet, 3, sunTabletMotionProc, 
		                           0, Relative);
	    InitPtrFeedbackClassDeviceStruct(pTablet, sunTabletCtrl);
	    for (i=0; i<3; i++)
	        InitValuatorAxisStruct(pTablet, i, 0, 0, TBLT_RES,
		                        TBLT_RES, TBLT_RES);
	    InitFocusClassDeviceStruct(pTablet);
	    InitProximityClassDeviceStruct(pTablet);
	
            AssignTypeAndName(pTablet, pPriv->sun_tablet_atom, XI_TABLET);
	    RegisterXPointerInterest(pTablet, TRUE, sunTabletAxisChange);
	    RegisterSetDeviceValuatorsProc(pTablet, sunTabletSetValuators);
            RegisterFdIo(pTablet, pPriv->fd, 
				  sunTabletGetEvents, sunTabletEnqueueEvent);
	    break;
	case DEVICE_ON:
	    pPriv = (sunTabPrivPtr)(pTablet->devicePrivate);
            if (ioctl(pPriv->fd, VUIDGFORMAT, &oformat) < 0) {
		 Error("sunTabletProc VUIDGFORMAT");
		 return(!Success);
            }
	    format = VUID_FIRM_EVENT;
            if (ioctl(pPriv->fd, VUIDSFORMAT,
		       &format) < 0) {
		 Error("sunTabletProc VUIDSFORMAT");
		 return(!Success);
            }
	    ioctl(pPriv->fd, I_SETSIG, S_INPUT);
	    AddEnabledDevice (pPriv->fd, &pPriv->mux_fd, &pPriv->index);
	    pTablet->on = TRUE;
	    break;
	case DEVICE_OFF:
	    RemoveEnabledDevice (((sunTabPrivPtr)pTablet->devicePrivate)->fd);
	    pTablet->on = FALSE;
	    break;
	case DEVICE_CLOSE:
	    pPriv = (sunTabPrivPtr)(pTablet->devicePrivate);
	    if (pTablet->on)
	        RemoveEnabledDevice (pPriv->fd);
	    if (ioctl (pPriv->fd, VUIDSFORMAT, &oformat) < 0)
			   Error("VUIDSFORMAT");
	    close(pPriv->fd);
	    xfree(pTablet->devicePrivate);
	    pTablet->on = FALSE;
	    break;
    }
    return (Success);
}
	    
/*-
 *-----------------------------------------------------------------------
 * sunTabletCtrl --
 *	Alter the control parameters for the tablet. Since acceleration
 *	etc. is done from the PtrCtrl record in the tablet's device record,
 *	there's nothing to do here.
 *
 * Results:
 *	None.
 *
 * Side Effects:
 *	None.
 *
 *-----------------------------------------------------------------------
 */
/*ARGSUSED*/
static void
sunTabletCtrl (DevicePtr pTablet)
{
}
/*-
 *-----------------------------------------------------------------------
 * sunTabletGetEvents --
 *	Return the events waiting in the wings for the given tablet.
 *
 * Results:
 *	A pointer to an array of Firm_events or (Firm_event *)0 if no events
 *	The number of events contained in the array.
 *	A boolean as to whether more events might be available.
 *
 * Side Effects:
 *	None.
 *-----------------------------------------------------------------------
 */
static XI_eventPtr
sunTabletGetEvents (DevicePtr pTablet, int *pNumEvents, Bool *pAgain)
{
    int	    	  i, nBytes;	    /* number of bytes of events available. */
    register sunTabPrivPtr	  pPriv;
    static Firm_event 	evBuf[MAXEVENTS];   
    static XI_event 	tabletBuf[MAXEVENTS];
    struct timeval      now;
    pPriv = (sunTabPrivPtr) pTablet->devicePrivate;
    if(ioctl(pPriv->fd, FIONREAD, &nBytes) == -1 || nBytes == 0) {
      *pNumEvents = 0;
      *pAgain = FALSE;
      return( (XI_eventPtr)NULL );
    }
    nBytes = read (pPriv->fd, (char *)evBuf, MAXEVENTS*sizeof(Firm_event));
    if (nBytes < 0) {
	if (errno == EWOULDBLOCK) {
	    *pNumEvents = 0;
	    *pAgain = FALSE;
        } else {
	    Error("Reading tablet");
	    FatalError("Could not read from tablet");
        }
    } else {
	*pNumEvents = nBytes / sizeof(Firm_event);
	*pAgain = (nBytes == sizeof(evBuf));
    }	
    for (i=0; i<(nBytes/sizeof(Firm_event)); i++) {
              tabletBuf[i].time = evBuf[i].time;
              tabletBuf[i].event = (pointer) &(evBuf[i]);
    }
    return (tabletBuf);
}
/*-
 *-----------------------------------------------------------------------
 * TabletAccelerate --
 *      Given a delta and a tablet, return the acceleration of the delta.
 *
 * Results:
 *      The corrected delta
 *
 * Side Effects:
 *      None.
 *
 *-----------------------------------------------------------------------
 */
static short
TabletAccelerate (DevicePtr pTablet, int delta)
{
    register int  sgn = sign(delta);
    register PtrCtrl *pCtrl;
    delta = abs(delta);
    pCtrl = &((DeviceIntPtr) pTablet)->ptrfeed->ctrl;
    if (delta > pCtrl->threshold) {
        return ((short) (sgn * (pCtrl->threshold +
                                ((delta - pCtrl->threshold) * pCtrl->num) /
                                pCtrl->den)));
    } else {
        return ((short) (sgn * delta));
    }
}
/*-
 *-----------------------------------------------------------------------
 * sunTabletEnqueueEvent --
 *	Given a Firm_event for a tablet, pass it off the the dix layer
 *	properly converted...
 *
 * Results:
 *	None.
 *
 * Side Effects:
 *	The cursor may be redrawn...? devPrivate/x/y will be altered.
 *
 *-----------------------------------------------------------------------
 */
static void
sunTabletEnqueueEvent (DevicePtr pTablet, XI_eventPtr Xev)
{
    register sunTabPrivPtr	pPriv;	/* Private data for pointer */
    Firm_event 		*ev = (Firm_event *) Xev->event;
    int 		x, y;
    static int		pressure = 0;
    register unsigned long time;
    register int	bmask;	/* Temporary button mask */
    pPriv = (sunTabPrivPtr)pTablet->devicePrivate;
    if (pPriv->corePointer) {
	xEvent		xE;
	time = xE.u.keyButtonPointer.time = TVTOMILLI(ev->time);
	switch(ev->id)
	{
	case TBLT_BUTTON_1:
	case TBLT_BUTTON_2:
	case TBLT_BUTTON_3:
	case TBLT_BUTTON_4:
	    xE.u.u.detail = (ev->id - TBLT_BUTTON_1) + 1;
	    bmask = 1 << xE.u.u.detail;
	    if (ev->value == VKEY_UP) {
		if (pPriv->bmask & bmask) {
		    xE.u.u.type = ButtonRelease;
		    pPriv->bmask &= ~bmask;
                } else {
		    return;
                }
            } else {
		if ((pPriv->bmask & bmask) == 0) {
		    xE.u.u.type = ButtonPress;
		    pPriv->bmask |= bmask;
                } else {
		    return;
                }
            }
	    mieqEnqueue(&xE);
	    break;
        case TBLT_PROXIMITY:
        case TBLT_PRESSURE:
	    break;
	case TBLT_X_DELTA:
	    if (pPriv->xAxis == 0)
	        miPointerDeltaCursor(TabletAccelerate(pTablet,ev->value), 0,
				     time);
            else 
	        miPointerDeltaCursor(0, TabletAccelerate(pTablet,ev->value), 
				     time);
	    break;
        case TBLT_Y_DELTA:
	    if (pPriv->yAxis == 1)
	        miPointerDeltaCursor(0, -TabletAccelerate(pTablet,ev->value),
				     time);
            else
	        miPointerDeltaCursor(-TabletAccelerate(pTablet,ev->value), 0,
				     time);
            break;
        case TBLT_X_ABSOLUTE:
	    miPointerPosition(&x, &y);
	    if (pPriv->xAxis == 0)
	        miPointerAbsoluteCursor(ev->value, y, time);
            else
	        miPointerAbsoluteCursor(x, ev->value, time);
	    break;
        case TBLT_Y_ABSOLUTE:
	    miPointerPosition(&x, &y);
	    if (pPriv->yAxis == 1)
	        miPointerAbsoluteCursor(x, ev->value, time);
            else
	        miPointerAbsoluteCursor(ev->value, y, time);
	    break;
        default:
	    FatalError("sunTabletEnqueueEvent: unrecognized id\n");
	    break;
        }
    } else {
        xEvent 	xE[2];
        deviceKeyButtonPointer *xev = (deviceKeyButtonPointer *) xE;
        deviceValuator *xv;
        xev->time = TVTOMILLI(ev->time);
        miPointerPosition(&x, &y);
        xev->root_x = x;
        xev->root_y = y;
        switch(ev->id)
        {
        case TBLT_BUTTON_1:
        case TBLT_BUTTON_2:
        case TBLT_BUTTON_3:
            xev->deviceid = (int) (((DeviceIntPtr)pTablet)->id);
            xev->detail = (ev->id - TBLT_BUTTON_1) + 1;
	    bmask = 1 << xev->detail;
	    if (ev->value == VKEY_UP) {
		if (pPriv->bmask & bmask) {
		    xev->type = DeviceButtonRelease;
		    pPriv->bmask &= ~bmask;
                } else {
		    return;
                }
            } else {
		if ((pPriv->bmask & bmask) == 0) {
		    xev->type = DeviceButtonPress;
		    pPriv->bmask |= bmask;
                } else {
		    return;
                }
            }
            mieqEnqueue(&xE[0]);
            return;
        case TBLT_X_DELTA:
            pPriv->x += ev->value;
            xev->type = DeviceMotionNotify;
            break;
        case TBLT_Y_DELTA:
            pPriv->y -= ev->value;
            xev->type = DeviceMotionNotify;
            break;
        case TBLT_X_ABSOLUTE:
            pPriv->x = ev->value;
            xev->type = DeviceMotionNotify;
            break;
        case TBLT_Y_ABSOLUTE:
            pPriv->y = ev->value;
            xev->type = DeviceMotionNotify;
            break;
        case TBLT_PRESSURE:
            pressure = ev->value;
            xev->type = DeviceMotionNotify;
            break;
        case TBLT_PROXIMITY:
            if (ev->value == 0)
                xev->type = ProximityOut;
            else
                xev->type = ProximityIn;
            break;
        default:
            FatalError ("sunTabletEnqueueEvent: unrecognized id\n");
            break;
        }
        xev->deviceid = (int) (((DeviceIntPtr)pTablet)->id) | MORE_EVENTS;
        xev->detail = 0;
    
        xv = (deviceValuator *) ++xev;
        xv->type = DeviceValuator;
        xv->deviceid = (int) (((DeviceIntPtr)pTablet)->id);
        xv->num_valuators = 3;
        xv->device_state = 0;
        xv->first_valuator = 0;
        xv->valuator0 = pPriv->x;
        xv->valuator1 = pPriv->y;
        xv->valuator2 = pressure;
    
        mieqEnqueue(&xE[0]);
        mieqEnqueue(&xE[1]);
    }
}
static int
sunTabletMotionProc(DevicePtr pPtr, xTimecoord *coords, unsigned long start,
		    unsigned long stop, ScreenPtr pScreen)
{
   return(0);
}
static int
sunTabletAxisChange(DevicePtr pTablet, Bool isCore, unsigned char x, 
		    unsigned char y)
{
    sunTabPrivPtr		pPriv;	/* Private data for pointer */
    pPriv = (sunTabPrivPtr)pTablet->devicePrivate;
    if (isCore) {
	if ((x > 1) || (y > 1) || (x == y))
	    return (!Success);
	pPriv->xAxis = x;
	pPriv->yAxis = y;
	pPriv->corePointer = TRUE;
    } else
	pPriv->corePointer = FALSE;
    return (Success);
}
static int
sunTabletSetValuators(DevicePtr pTablet, int *valuators, int first_valuator,
		      int num_valuators)
{
    sunTabPrivPtr		pPriv;	/* Private data for pointer */
    pPriv = (sunTabPrivPtr)pTablet->devicePrivate;
    /* Only allow the setting of the x and y axis (0 and 1)*/
    if (first_valuator + num_valuators > 2)
	return (!Success);
    while (num_valuators--) {
        if (first_valuator == 0) {
	    if (pPriv->xAxis == 0)
	        pPriv->x = *valuators;
            else
	        pPriv->y = *valuators;
            valuators++;
	    first_valuator++;
	    mieqUpdateKbdPtr(NULL, pTablet);
        }
    }
    return (Success);
}
