/*
* 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.
* 
* 
* Portions of this software are based on Xlib and X Protocol Test Suite.
* We have used this material under the terms of its copyright, which grants
* free use, subject to the conditions below.  Note however that those
* portions of this software that are based on the original Test Suite have
* been significantly revised and that all such revisions are copyright (c)
* 1995 Applied Testing and Technology, Inc.  Insomuch as the proprietary
* revisions cannot be separated from the freely copyable material, the net
* result is that use of this software is governed by the ApTest copyright.
* 
* 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.
* 
* 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 name of UniSoft not be
* used in advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.  UniSoft
* makes no representations about the suitability of this software for any
* purpose.  It is provided "as is" without express or implied warranty.
* 
*/
/*
 * SYNOPSIS:
 *   int
 *   XSetPointerMapping(display, map, nmap)
 *   Display	*display;
 *   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_XSetPointerMapping	1
char    *TestName = "XSetPointerMapping";

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


/*
 * Arguments to the XSetPointerMapping function
 */
static Display	*display;
static unsigned char	*map;
static int 	nmap;


static int 	ValueReturn;


/*
 * MAPSIZE must be at least one greater than the maximum number of buttons
 * allowed.  We use a much larger value.
 */
#define	MAPSIZE	32
static	unsigned char	Map[MAPSIZE];

static	int 	numbuttons;

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

/*
 * Save and restore the old map.
 */
static unsigned char	oldmap[MAPSIZE];
static void
savemap()
{
	startup();
	if(Dsp)
		numbuttons = XGetPointerMapping(Dsp, oldmap, MAPSIZE);
}

static void
restoremap()
{
	if(Dsp)
		XSetPointerMapping(Dsp, oldmap, numbuttons);
	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;
	map = Map;
	nmap = 0;
}

/*
 * 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 XSetPointerMapping-1.(A)");
	report_assertion("A successful call to XSetPointerMapping sets the pointer");
	report_assertion("mapping for the physical buttons to the nmap logical button");
	report_assertion("numbers specified in the array map and returns");
	report_assertion("MappingSuccess.");

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

	tpstartup();
	setargs();
	getnbutton();
	/*
	 * Cycle the current mapping around.
	 */
	for (i = 0; i < numbuttons; i++) {
		map[i] = map[i] + 1;
		if (map[i] > numbuttons)
			map[i] = 1;
	}

	startcall(display);
	if (isdeleted())
		return;
	ValueReturn = XSetPointerMapping(display, 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;
	}

	XGetPointerMapping(display, newmap, MAPSIZE);
	if (isdeleted()) {
		delete("Could not get pointer mapping");
		return;
	}

	for (i = 0; i < numbuttons; 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(numbuttons);
	tpcleanup();
	pfcount(pass, fail);
}

static void t002(){

XEvent	ev;
XMappingEvent	good;
int 	n;
int 	pass = 0, fail = 0;

 	report_purpose(2);

	report_assertion("Assertion XSetPointerMapping-2.(A)");
	report_assertion("When a call to XSetPointerMapping is successful, then a");
	report_assertion("MappingNotify event is generated.");

	report_strategy("Call XSetPointerMapping.");
	report_strategy("Verify that a MappingNotify event is generated.");

	tpstartup();
	setargs();
	getnbutton();
	startcall(display);
	if (isdeleted())
		return;
	ValueReturn = XSetPointerMapping(display, 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;
	}

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

	defsetevent(good, display, MappingNotify);
	good.window = None;	/* Not used */
	good.request = MappingPointer;
	if (checkevent((XEvent*)&good, &ev))
		FAIL;
	else
		CHECK;

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

static void t003(){

int	i;
unsigned char zmap[MAPSIZE];
Window	win;
int 	pass = 0, fail = 0;

 	report_purpose(3);

	report_assertion("Assertion XSetPointerMapping-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 ButtonPress on it.");
	report_strategy("  For i in 1..numbuttons");
	report_strategy("    Set map[i-1] to 0.");
	report_strategy("    Call XSetPointerMapping.");
	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 (noext(numbuttons))
		return;
	else
		CHECK;

	if (numbuttons<1 || numbuttons>MAPSIZE) {
		report("Limit of 1..%d buttons exceeded (%d).", MAPSIZE, numbuttons);
		return;
	} else
		CHECK;

	for(i=0; i<numbuttons; i++)
		zmap[i] = map[i];
	win = defwin(display);
	warppointer(display, win, 2,2);
	XSelectInput(display, win, ButtonPressMask);

	for(i=0; i<numbuttons; 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 = XSetPointerMapping(display, 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. */
		buttonpress(display, (unsigned int)i+1);
		relalldev();
		_endcall(display);
		if (geterr() != Success) {
			delete("Couldn't simulate pressing button %d.", i+1);
			return;
		} else
			CHECK;
		if (XCheckWindowEvent(display, win, ButtonPressMask, &ev)) {
			report("Got event after pressing disabled button %d.", i+1);
			FAIL;
		} else
			CHECK;
		zmap[i] = mapsave; /* restore button i+1 */
	}
	CHECKPASS(2+numbuttons*3);
	tpcleanup();
	pfcount(pass, fail);
}

static void t004(){

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

 	report_purpose(4);

	report_assertion("Assertion XSetPointerMapping-4.(A)");
	report_assertion("Elements of the map array are not restricted in value by");
	report_assertion("the number of physical buttons.");

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

	tpstartup();
	setargs();
	getnbutton();
	for (i = 0; i < numbuttons; i++)
		map[i] = i;

	map[0] = numbuttons+1;

	startcall(display);
	if (isdeleted())
		return;
	ValueReturn = XSetPointerMapping(display, 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;

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

static void t005(){

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

 	report_purpose(5);

	report_assertion("Assertion XSetPointerMapping-5.(B)");
	report_assertion("When any of the buttons to be altered are logically in the");
	report_assertion("down state, then a call to XSetPointerMapping 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 extension available:");
	report_strategy("  Set mapping to be each button to itself and save this map.");
	report_strategy("  For i in 1..numbuttons");
	report_strategy("    Cycle map so that button i is not itself.");
	report_strategy("    Simulate button i press");
	report_strategy("    Call XSetPointerMapping with cycled map so that button i is being altered.");
	report_strategy("    Release buttons etc.");
	report_strategy("    Check for MappingBusy.");
	report_strategy("    Call XGetPointerMapping to get current mapping and current numbuttons.");
	report_strategy("    Check same as original, saved, values.");
	report_strategy("else");
	report_strategy("  Report untested.");

	tpstartup();
	setargs();
	getnbutton();
	if (noext(numbuttons))
		return;
	else
		CHECK;

	if (numbuttons<1 || numbuttons>MAPSIZE) {
		delete("Limit of 1..%d buttons exceeded (%d).", MAPSIZE, numbuttons);
		return;
	} else
		CHECK;
	for(i=0; i<numbuttons; i++)
		firstmap[i] = map[i] = (unsigned char)i+1;
	startcall(display);
	if (isdeleted())
		return;
	ret = XSetPointerMapping(display, map, nmap);
	endcall(display);
	if (geterr() != Success) {
		report("Got %s, Expecting Success", errorname(geterr()));
		FAIL;
	}
	if (isdeleted() || ret != MappingSuccess) {
		delete("Couldn't set up monotonic map to start with.");
		return;
	} else
		CHECK;
	for(i=0; i<numbuttons; i++) {
		int j;
		unsigned char tmp;

		/* cycle map by one, until map[i] is not i=1 */
		do {
			for(tmp=map[0], j=0; j<(numbuttons-1); j++)
				map[j] = map[j+1];
			map[numbuttons - 1] = tmp;
		} while (map[i] == (unsigned char)i+1);

		_startcall(display);	/* set error handler etc. */
		buttonpress(display, (unsigned int)i+1);
		if (geterr() != Success) {
			delete("Couldn't simulate pressing button %d.", i+1);
			relalldev();
			_endcall(display);
			return;
		} else
			CHECK;
		_endcall(display);
		startcall(display);
		if (isdeleted())
			return;
		ret = XSetPointerMapping(display, map, nmap);
		endcall(display);
		if (geterr() != Success) {
			report("Got %s, Expecting Success", errorname(geterr()));
			FAIL;
		}
		_startcall(display);	/* set error handler etc. */
		relalldev();
		_endcall(display);
		if (ret != MappingBusy) {
			report("Expecting MappingBusy with button %d, got %s (%d).",
				i+1, (ret==MappingSuccess)?"MappingSuccess":"<unknown>", ret);
			FAIL;
		} else
			CHECK;
		nb = XGetPointerMapping(display, newmap, numbuttons);
		if (isdeleted()) {
			delete("Couldn't get current pointer map for comparison.");
			return;
		} else
			CHECK;
		if (nb != numbuttons) {
			report("Button numbers changed from %d to %d.", numbuttons, nb);
			FAIL;
		} else {
			for(j=0; j<numbuttons; j++)
				if (firstmap[j] != newmap[j]) {
					report("Maps differ for button %d, was %d now %d.", j+1, firstmap[j], newmap[j]);
					FAIL;
				} else
					CHECK;
		}
	}
	CHECKPASS(3+numbuttons*(3+numbuttons*1));
	tpcleanup();
	pfcount(pass, fail);
}

static void t006(){

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

 	report_purpose(6);

	report_assertion("Assertion XSetPointerMapping-6.(A)");
	report_assertion("When nmap is not the same as the length that");
	report_assertion("XGetPointerMapping would return, then a BadValue error");
	report_assertion("occurs.");

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

	tpstartup();
	setargs();
	getnbutton();
	nmap = numbuttons + 2;
	for (i = 0; i < nmap; i++)
		map[i] = i;	/* MAPSIZE is large enough to allow this */
	startcall(display);
	if (isdeleted())
		return;
	ValueReturn = XSetPointerMapping(display, 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 XSetPointerMapping-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 XSetPointerMapping.");
	report_strategy("Verify that a BadValue error occurs.");

	tpstartup();
	setargs();
	getnbutton();
	if (numbuttons < 2) {
		unsupported("There are less than two buttons");
		return;
	}

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

	map[0] = map[1];
	startcall(display);
	if (isdeleted())
		return;
	ValueReturn = XSetPointerMapping(display, 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);
}

/* End of Test Cases */


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

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

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