/*
* Copyright (c) 2005 X.Org Foundation L.L.C.
* 
* 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
* AUTHORS OR COPYRIGHT HOLDERS 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.
* 
* Copyright (c) Applied Testing and Technology, Inc. 1995
* All Rights Reserved.
* 
* 
* Copyright (c) 1990, 1991  X Consortium
* 
* 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
* X CONSORTIUM 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.
* 
* Except as contained in this notice, the name of the X Consortium shall not be
* used in advertising or otherwise to promote the sale, use or other dealings
* in this Software without prior written authorization from the X Consortium.
* 
* Copyright 1993 by the Hewlett-Packard Company.
* 
* Copyright 1990, 1991 UniSoft Group Limited.
* 
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and that
* both that copyright notice and this permission notice appear in
* supporting documentation, and that the names of HP, and UniSoft not be
* used in advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.  HP, and UniSoft
* make no representations about the suitability of this software for any
* purpose.  It is provided "as is" without express or implied warranty.
* 
*/
/*
 * SYNOPSIS:
 *   int
 *   XSetDeviceButtonMapping(display, device, map, nmap)
 *   Display	*display;
 *   XDevice *device;
 *   unsigned char	*map;
 *   int 	nmap;
 */


#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include	<stdlib.h>
#include	<stdio.h>
#include	<string.h>
#include	"xtest.h"
#include	"X11/Xlib.h"
#include	"X11/Xutil.h"
#include	"X11/Xresource.h"
#include	"X11/keysym.h"
#include	"tet_api.h"
#include	"xtestlib.h"
#include	"pixval.h"
#ifdef INPUTEXTENSION
#include        "X11/extensions/XInput.h"
#include        "XItest.h"
#endif

extern	Display	*Dsp;
extern	Window	Win;

extern	Window	ErrdefWindow;
extern	Drawable ErrdefDrawable;
extern	GC		ErrdefGC;
extern	Colormap ErrdefColormap;
extern	Pixmap	ErrdefPixmap;
extern	Atom	ErrdefAtom;
extern	Cursor	ErrdefCursor;
extern	Font	ErrdefFont;


#define T_XSetDeviceButtonMapping	1
char    *TestName = "XSetDeviceButtonMapping";

/*
 * Defines for different argument types
 */
#define A_DISPLAY display


/*
 * Arguments to the XSetDeviceButtonMapping function
 */
static Display	*display;
static XDevice *device;
static unsigned char	*map;
static int 	nmap;


static int 	ValueReturn;


/* Maximum button number allowed. */
#define	MAXBUTTON	255

/*
 * MAPSIZE must be at least one greater than the maximum number of buttons
 * allowed.
 */
#define	MAPSIZE	256
static	unsigned char	Map[MAPSIZE];
static 	int baddevice;

static	int 	nbtns;
extern ExtDeviceInfo Devs;

/*
 * Set up the number of buttons.  Also set the nmap value to nbtns (
 * the test may later override this).
 */
static	void
getnbutton()
{
	if (!Devs.Button)
	    return;
	device = Devs.Button;
	nbtns = XGetDeviceButtonMapping(Dsp, device, Map, MAPSIZE);
	nmap = nbtns;
	if (isdeleted())
		delete("XGetDeviceButtonMapping failed");
}

/*
 * Save and restore the old map.
 */
static unsigned char	oldmap[MAPSIZE];
static void
savemap()
{
	startup();
	if (!Setup_Extension_DeviceInfo(BtnMask))
	    {
	    return;
	    }
	device = Devs.Button;
	if(Dsp)
		nbtns = XGetDeviceButtonMapping(Dsp, device, oldmap, MAPSIZE);
}

static void
restoremap()
{
	device = Devs.Button;
	if(Dsp && Devs.Button)
		{
		XSetDeviceButtonMapping(Dsp, device, oldmap, nbtns);
		XSync(Dsp,0);
		}
	cleanup();
}


int 	tet_thistest;

/*
 * Called at the beginning of each test purpose to reset the
 * arguments to their initial values
 */
static void
setargs()
{
	display = Dsp;
	device = Devs.Button;
	map = Map;
	nmap = 255;
}

/*
 * Set the arguments to default values for error tests
 */
static void
seterrdef()
{
}

static void t001(){

unsigned char	newmap[MAPSIZE];
int 	i;
int 	pass = 0, fail = 0;

 	report_purpose(1);

	report_assertion("Assertion XSetDeviceButtonMapping-1.(B)");
	report_assertion("A successful call to XSetDeviceButtonMapping sets the");
	report_assertion("pointer mapping for the physical buttons to the nmap logical");
	report_assertion("button numbers specified in the array map and returns");
	report_assertion("MappingSuccess.");
	report_assertion("Reason for omission: There is no known reliable test method for this assertion");

	report_strategy("Get number of buttons.");
	report_strategy("Set up a pointer mapping.");
	report_strategy("Set pointer mapping with XSetDeviceButtonMapping.");
	report_strategy("Verify return value.");
	report_strategy("Get pointer mapping with XGetDeviceButtonMapping.");
	report_strategy("Verify that pointer mapping is as set.");

	tpstartup();
	setargs();
	getnbutton();
	if (!Devs.Button) {
	    untested("%s: No input extension button device.\n", TestName);
	    return;
	    }
	/*
	 * Cycle the current mapping around.
	 */
	for (i = 0; i < nbtns; i++) {
		map[i] = map[i] + 1;
		if (map[i] > MAXBUTTON)
			map[i] = 1;
	}

	device = Devs.Button;

	startcall(display);
	if (isdeleted())
		return;
	ValueReturn = XSetDeviceButtonMapping(display, device, map, nmap);
	endcall(display);
	if (ValueReturn != MappingSuccess) {
		report("Returned value was %d, expecting MappingSuccess", ValueReturn);
		FAIL;
	}
	if (geterr() != Success) {
		report("Got %s, Expecting Success", errorname(geterr()));
		FAIL;
	}

	XGetDeviceButtonMapping(display, device, newmap, MAPSIZE);
	if (isdeleted()) {
		delete("Could not get device button mapping");
		return;
	}

	for (i = 0; i < nbtns; i++) {
		if (map[i] == newmap[i])
			CHECK;
		else {
			report("Mapping not set correctly in position %d", i);
			report("  was %u, expecting %u", (unsigned)newmap[i], (unsigned)map[i]);
			FAIL;
		}
	}

	CHECKPASS(nbtns);
	tpcleanup();
	pfcount(pass, fail);
}

static void t002(){

XEvent	ev;
XDeviceMappingEvent	good;
int	n, dbmn;
XEventClass dbmnc;
int 	pass = 0, fail = 0;

 	report_purpose(2);

	report_assertion("Assertion XSetDeviceButtonMapping-2.(B)");
	report_assertion("When a call to XSetDeviceButtonMapping is successful, then");
	report_assertion("a DeviceMappingNotify event is generated.");
	report_assertion("Reason for omission: There is no known reliable test method for this assertion");

	report_strategy("Call XSetDeviceButtonMapping.");
	report_strategy("Verify that a DeviceMappingNotify event is generated.");

	tpstartup();
	setargs();
	getnbutton();
	if (!Devs.Button) {
	    untested("%s: No input extension button device.\n", TestName);
	    return;
	    }
	device = Devs.Button;
	DeviceMappingNotify(Devs.Button, dbmn, dbmnc);
	XSelectExtensionEvent (display, DefaultRootWindow(Dsp), &dbmnc, 1);
	XSync(display,0);
	startcall(display);
	if (isdeleted())
		return;
	ValueReturn = XSetDeviceButtonMapping(display, device, map, nmap);
	endcall(display);
	if (ValueReturn != MappingSuccess) {
		report("Returned value was %d, expecting MappingSuccess", ValueReturn);
		FAIL;
	}
	if (geterr() != Success) {
		report("Got %s, Expecting Success", errorname(geterr()));
		FAIL;
	}
	XSync(display,0);

	n = getevent(display, &ev);
	if (n == 0 || ev.type != dbmn) {
		report("Expecting a DeviceMappingNotify event, received %s", n? eventname(ev.type): "no event");
		FAIL;
	} else
		CHECK;

	defsetevent(good, display, dbmn);
	good.window = None;	/* Not used */
	good.request = MappingPointer;
	good.deviceid = Devs.Button->device_id;
	if (checkevent((XEvent*)&good, &ev))
		FAIL;
	else
		CHECK;

	CHECKPASS(2);
	tpcleanup();
	pfcount(pass, fail);
}

static void t003(){

int	i;
unsigned char zmap[255];
Window	win;
XID dbpclass;
int	dbp;
int 	pass = 0, fail = 0;

 	report_purpose(3);

	report_assertion("Assertion XSetDeviceButtonMapping-3.(B)");
	report_assertion("When an element of map is zero, then the corresponding");
	report_assertion("physical button is disabled.");
	report_assertion("Reason for omission: There is no known reliable test method for this assertion");

	report_strategy("If extension available:");
	report_strategy("  Create and map a window.");
	report_strategy("  Select DeviceButtonPress on it.");
	report_strategy("  For i in 1..nbtns");
	report_strategy("    Set map[i-1] to 0.");
	report_strategy("    Call XSetDeviceButtonMapping.");
	report_strategy("    Discard event queue.");
	report_strategy("    Simulate button i press with extension.");
	report_strategy("    Release all buttons etc.");
	report_strategy("    Check no button press event received.");
	report_strategy("    Restore map[i-1].");
	report_strategy("else");
	report_strategy("  Report untested.");

	tpstartup();
	setargs();
	getnbutton();
	if (!Devs.Button) {
	    untested("%s: No input extension button device.\n", TestName);
	    return;
	    }
	if (noext(nbtns))
		return;
	else
		CHECK;

	if (nbtns<1 || nbtns>255) {
		report("Protocol limit of 1..255 buttons exceeded (%d).", nbtns);
		return;
	} else
		CHECK;

	for(i=0; i<nbtns; i++)
		zmap[i] = map[i];
	win = defwin(display);
	device = Devs.Button;
	DeviceButtonPress(device, dbp, dbpclass);
	warppointer(display, win, 2,2);
	XSelectExtensionEvent(display, win, &dbpclass, 1);

	for(i=0; i<nbtns; i++) {
		unsigned char mapsave = zmap[i];
		int ret;
		XEvent ev;

		zmap[i] = 0; /* disable button i+1 */
		map = zmap;
		startcall(display);
		if (isdeleted())
			return;
		ret = XSetDeviceButtonMapping(display, device, map, nmap);
		endcall(display);
		if (geterr() != Success) {
			report("Got %s, Expecting Success", errorname(geterr()));
			FAIL;
		}

		if (ret != MappingSuccess) {
			delete("Couldn't set zero entry for button %d.", i+1);
			return;
		} else
			CHECK;

		XSync(display, True); /* discard event queue */
		_startcall(display);	/* set error handler etc. */
		devicebuttonpress(display, device, (unsigned int)i+1);
		devicebuttonrel(display, device, (unsigned int)i+1);
		XSync(display,0);
		relalldev();
		_endcall(display);
		if (geterr() != Success) {
			delete("Couldn't simulate pressing button %d.", i+1);
			return;
		} else
			CHECK;
		if (!XPending(display))
		    CHECK;
		else while(XPending(display))
			{
			XNextEvent (display, &ev);
			if (ev.type == dbp)
			    {
			    report("Got event after pressing disabled button %d.", i+1);
			    FAIL;
			    }
			}
		zmap[i] = mapsave; /* restore button i+1 */
	}
	devicerelbuttons(device);
	CHECKPASS(nbtns*3 + 2);

	tpcleanup();
	pfcount(pass, fail);
}

static void t004(){

int 	i;
int 	pass = 0, fail = 0;

 	report_purpose(4);

	report_assertion("Assertion XSetDeviceButtonMapping-4.(B)");
	report_assertion("Elements of the map array are not restricted in value by");
	report_assertion("the number of physical buttons.");
	report_assertion("Reason for omission: There is no known reliable test method for this assertion");

	report_strategy("Set up map array with button number higher than number of physical buttons.");
	report_strategy("Call XSetDeviceButtonMapping.");
	report_strategy("Verify no error.");

	tpstartup();
	setargs();
	getnbutton();
	if (!Devs.Button) {
	    untested("%s: No input extension button device.\n", TestName);
	    return;
	    }
	for (i = 0; i < nbtns; i++)
		map[i] = i;

	map[0] = nbtns+1;

	device = Devs.Button;
	startcall(display);
	if (isdeleted())
		return;
	ValueReturn = XSetDeviceButtonMapping(display, device, map, nmap);
	endcall(display);
	if (ValueReturn != MappingSuccess) {
		report("Returned value was %d, expecting MappingSuccess", ValueReturn);
		FAIL;
	}
	if (geterr() != Success) {
		report("Got %s, Expecting Success", errorname(geterr()));
		FAIL;
	}

	if (geterr() == Success)
		PASS;
	else
		FAIL;
	tpcleanup();
	pfcount(pass, fail);
}

static void t005(){

int i, ret;
int 	pass = 0, fail = 0;

 	report_purpose(5);

	report_assertion("Assertion XSetDeviceButtonMapping-5.(B)");
	report_assertion("When any of the buttons to be altered are logically in the");
	report_assertion("down state, then a call to XSetDeviceButtonMapping returns");
	report_assertion("MappingBusy, and the mapping is not changed.");
	report_assertion("Reason for omission: There is no known reliable test method for this assertion");

	report_strategy("If the xtest extension is available, press one of the buttons.  Then");
	report_strategy("try to change the map.  Verify that a status of MappingBusy was returned.");

	tpstartup();
	setargs();
	getnbutton();
	if (!Devs.Button) {
	    untested("%s: No input extension button device.\n", TestName);
	    return;
	    }
	if (noext(0))
	    return;
	getnbutton();
	/*
	 * Cycle the current mapping around.
	 */
	for (i = 0; i < nbtns; i++) {
		map[i] = map[i] + 1;
		if (map[i] > MAXBUTTON)
			map[i] = 1;
	}
	devicebuttonpress(display, Devs.Button, Button1);
	devicebuttonpress(display, Devs.Button, Button2);
	XSync(display,0);
	device = Devs.Button;
	startcall(display);
	if (isdeleted())
		return;
	ret = XSetDeviceButtonMapping(display, device, map, nmap);
	endcall(display);
	if (geterr() != Success) {
		report("Got %s, Expecting Success", errorname(geterr()));
		FAIL;
	}

	if (ret == MappingBusy)
		PASS;
	else
		FAIL;
	devicebuttonrel(display, Devs.Button, Button1);
	devicebuttonrel(display, Devs.Button, Button2);
	devicerelbuttons(device);

	tpcleanup();
	pfcount(pass, fail);
}

static void t006(){

int 	i;
int 	pass = 0, fail = 0;

 	report_purpose(6);

	report_assertion("Assertion XSetDeviceButtonMapping-6.(B)");
	report_assertion("When nmap is not the same as the length that");
	report_assertion("XGetDeviceButtonMapping would return, then a BadValue error");
	report_assertion("occurs.");
	report_assertion("Reason for omission: There is no known reliable test method for this assertion");

	report_strategy("Set nmap to incorrect value.");
	report_strategy("Call XSetDeviceButtonMapping.");
	report_strategy("Verify that a BadValue error occurs.");

	tpstartup();
	setargs();
	getnbutton();
	if (!Devs.Button) {
	    untested("%s: No input extension button device.\n", TestName);
	    return;
	    }
	if (nbtns < 254)
	    nmap = nbtns + 2;
	else if (nbtns > 1)
	    nmap = nbtns - 1;
	else
	    {
	    untested("%s: Bad # buttons on extension device.\n", TestName);
	    return;
	    }
	for (i = 0; i < nmap; i++)
		map[i] = i;	/* MAPSIZE is large enough to allow this */
	device = Devs.Button;
	startcall(display);
	if (isdeleted())
		return;
	ValueReturn = XSetDeviceButtonMapping(display, device, map, nmap);
	endcall(display);
	if (ValueReturn != MappingSuccess) {
		report("Returned value was %d, expecting MappingSuccess", ValueReturn);
		FAIL;
	}
	if (geterr() != BadValue) {
		report("Got %s, Expecting BadValue", errorname(geterr()));
		FAIL;
	}

	if (geterr() == BadValue)
		PASS;
	else
		FAIL;	/* done already */
	tpcleanup();
	pfcount(pass, fail);
}

static void t007(){

int 	i;
int 	pass = 0, fail = 0;

 	report_purpose(7);

	report_assertion("Assertion XSetDeviceButtonMapping-7.(C)");
	report_assertion("If there is more than one button: When two elements of map");
	report_assertion("have the same non-zero value, then a BadValue error occurs.");

	report_strategy("If less than two buttons");
	report_strategy("  Report unsupported.");
	report_strategy("Set up a map with two elements the same.");
	report_strategy("Call XSetDeviceButtonMapping.");
	report_strategy("Verify that a BadValue error occurs.");

	tpstartup();
	setargs();
	getnbutton();
	if (!Devs.Button) {
	    untested("%s: No input extension button device.\n", TestName);
	    return;
	    }
	getnbutton();
	if (nbtns < 2) {
		unsupported("There are less than two buttons");
		return;
	}

	for (i = 0; i < nmap; i++)
		map[i] = i;

	map[0] = map[1];
	device = Devs.Button;
	startcall(display);
	if (isdeleted())
		return;
	ValueReturn = XSetDeviceButtonMapping(display, device, map, nmap);
	endcall(display);
	if (ValueReturn != MappingSuccess) {
		report("Returned value was %d, expecting MappingSuccess", ValueReturn);
		FAIL;
	}
	if (geterr() != BadValue) {
		report("Got %s, Expecting BadValue", errorname(geterr()));
		FAIL;
	}

	if (geterr() == BadValue)
		PASS;
	else
		FAIL;

	tpcleanup();
	pfcount(pass, fail);
}

static void t008(){

XDevice nodevice;
int ximajor, first, err;
int 	pass = 0, fail = 0;

 	report_purpose(8);

	report_assertion("Assertion XSetDeviceButtonMapping-8.(B)");
	report_assertion("If XSetDeviceButtonMapping is invoked with an invalid");
	report_assertion("device, a BadDevice error will result.");
	report_assertion("Reason for omission: There is no known reliable test method for this assertion");

	report_strategy("Make the call with an invalid device.");

	tpstartup();
	setargs();
	getnbutton();
	if (!XQueryExtension (display, INAME, &ximajor, &first, &err))
	    {
	    untested("%s: Input extension not supported.\n", TestName);
	    return;
	    }

	BadDevice (display, baddevice);
	nodevice.device_id = -1;
	device = &nodevice;

	startcall(display);
	if (isdeleted())
		return;
	ValueReturn = XSetDeviceButtonMapping(display, device, map, nmap);
	endcall(display);
	if (ValueReturn != MappingSuccess) {
		report("Returned value was %d, expecting MappingSuccess", ValueReturn);
		FAIL;
	}
	if (geterr() != baddevice) {
		report("Got %s, Expecting baddevice", errorname(geterr()));
		FAIL;
	}

	if (geterr() == baddevice)
		CHECK;
	else
		FAIL;

	CHECKPASS(1);
	tpcleanup();
	pfcount(pass, fail);
}

/* End of Test Cases */


struct tet_testlist tet_testlist[] = {
	{ t001, 1 },
	{ t002, 2 },
	{ t003, 3 },
	{ t004, 4 },
	{ t005, 5 },
	{ t006, 6 },
	{ t007, 7 },
	{ t008, 8 },
	{ NULL, 0 }
};

int 	ntests = sizeof(tet_testlist)/sizeof(struct tet_testlist)-1;

void	(*tet_startup)() = savemap;
void	(*tet_cleanup)() = restoremap;
