/*
* 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.
* 
* Copyright (c) 2005 X.Org Foundation LLC
* 
* 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.
* 
* Copyright 1990, 1991 by 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 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:
 *   void
 *   XChangeDeviceKeyMapping(display, device, first_keycode, keysyms_per_keycode, keysyms, num_codes)
 *   Display	*display;
 *   XDevice *device;
 *   int 	first_keycode;
 *   int 	keysyms_per_keycode;
 *   KeySym	*keysyms;
 *   int 	num_codes;
 */


#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_XChangeDeviceKeyMapping	1
char    *TestName = "XChangeDeviceKeyMapping";

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


/*
 * Arguments to the XChangeDeviceKeyMapping function
 */
static Display	*display;
static XDevice *device;
static int 	first_keycode;
static int 	keysyms_per_keycode;
static KeySym	*keysyms;
static int 	num_codes;


extern ExtDeviceInfo Devs;
static int Min_KeyCode, Max_KeyCode;

#define	MAXKPK	5	/* Maximum keysyms_per_keycode we will use */
#define	MAXCODES 255	/* Max number of keycodes we will use */

static	int 	ncodes;
static	int 	kpk;	/* Keysyms per keycode */
static	KeySym	*oldkeym;

/*
 * Can't really assume that there are any particular keysym names defined so
 * we use our own arbitrary values.
 */
#define	XT_KSYM1	0x5678
#define	XT_KSYM2	0x9328

static	KeySym	Keys[MAXKPK*MAXCODES] = {
	XT_KSYM1, XT_KSYM2};

/*
 * Set startup and cleanup functions to save and restore
 * the original keyboard map.
 */
static void
savekeymap()
{
	int numkeys;

	startup();
	if(Dsp) {
		if (!Setup_Extension_DeviceInfo(KeyMask))
		    return;
		MinMaxKeys(Dsp, Devs.Key, &Min_KeyCode, &Max_KeyCode, &numkeys);
		ncodes = Max_KeyCode - Min_KeyCode;

		oldkeym = XGetDeviceKeyMapping(Dsp, Devs.Key, Min_KeyCode, ncodes, &kpk);
	}
}

static void
cleankeymap()
{
	if(Dsp) {
		if (Devs.Key)
		    XChangeDeviceKeyMapping(Dsp, Devs.Key, Min_KeyCode, kpk, oldkeym, ncodes);
		XFree((char*) oldkeym);
		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 = 0;
	first_keycode = Min_KeyCode;
	keysyms_per_keycode = 1;
	keysyms = Keys;
	num_codes = 2;
}

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

static void t001(){

int 	i, j;
int 	newkpk;
KeySym	*newmap;
int 	pass = 0, fail = 0;

 	report_purpose(1);

	report_assertion("Assertion XChangeDeviceKeyMapping-1.(B)");
	report_assertion("A call to XChangeDeviceKeyMapping associates");
	report_assertion("keysyms_per_keycode KeySyms for each of the num_codes");
	report_assertion("KeyCodes starting with first_keycode, with the KeySyms");
	report_assertion("being taken from the array keysyms.");
	report_assertion("Reason for omission: There is no known reliable test method for this assertion");

	report_strategy("Set up keysym array.");
	report_strategy("Call XChangeDeviceKeyMapping.");
	report_strategy("Verify that keyboard mapping has been changed.");

	tpstartup();
	setargs();
	if (!Devs.Key)
	    {
	    untested("%s: No input extension key device.\n", TestName);
	    return;
	    }
	device = Devs.Key;
	first_keycode = Min_KeyCode+3;
	keysyms_per_keycode = MAXKPK;
	num_codes = 6;

	for (i = 0; i < keysyms_per_keycode*num_codes; i++)
		keysyms[i] = XT_KSYM1;

	startcall(display);
	if (isdeleted())
		return;
	XChangeDeviceKeyMapping(display, device, first_keycode, keysyms_per_keycode, keysyms, num_codes);
	endcall(display);
	if (geterr() != Success) {
		report("Got %s, Expecting Success", errorname(geterr()));
		FAIL;
	}

	newmap = XGetDeviceKeyMapping(display, Devs.Key, first_keycode, num_codes, &newkpk);

	for (i = 0; i < num_codes; i++) {
		for (j = 0; j < keysyms_per_keycode; j++) {
			if (keysyms[i*keysyms_per_keycode+j] == newmap[i*newkpk+j])
				CHECK;
			else {
				report("Keysym for keycode %d was 0x%x, expecting 0x%x",
					first_keycode+i,
					newmap[i*newkpk+j], keysyms[i*keysyms_per_keycode+j]);
				FAIL;
				break;	/* probably pointless to continue */
			}
		}
	}

	CHECKPASS(keysyms_per_keycode*num_codes);

	XFree((char*)newmap);
	tpcleanup();
	pfcount(pass, fail);
}

static void t002(){

KeySym	*oldmap;
int 	oldkpk;
KeySym	*newmap;
int 	newkpk;
int 	i, j;
int 	oldind, newind;
int 	pass = 0, fail = 0;

 	report_purpose(2);

	report_assertion("Assertion XChangeDeviceKeyMapping-2.(B)");
	report_assertion("The KeySyms for KeyCodes outside the specified range remain");
	report_assertion("unchanged.");
	report_assertion("Reason for omission: There is no known reliable test method for this assertion");

	report_strategy("Get current keymap.");
	report_strategy("Call XChangeDeviceKeyMapping to change part of the map.");
	report_strategy("Verify that there is no change outside the specified range.");

	tpstartup();
	setargs();
	if (!Devs.Key)
	    {
	    untested("%s: No input extension key device.\n", TestName);
	    return;
	    }
	device = Devs.Key;
	oldmap = XGetDeviceKeyMapping(display, Devs.Key, Min_KeyCode, ncodes, &oldkpk);

	first_keycode = Min_KeyCode+2;
	startcall(display);
	if (isdeleted())
		return;
	XChangeDeviceKeyMapping(display, device, first_keycode, keysyms_per_keycode, keysyms, num_codes);
	endcall(display);
	if (geterr() != Success) {
		report("Got %s, Expecting Success", errorname(geterr()));
		FAIL;
	}

	newmap = XGetDeviceKeyMapping(display, Devs.Key, Min_KeyCode, ncodes, &newkpk);

	for (i = 0; i < ncodes; i++) {

		/* Skip the ones that were changed. */
		if (i + Min_KeyCode >= first_keycode && i + Min_KeyCode < first_keycode+num_codes)
			continue;

		/*
		 * The call may have altered the number of keysyms per keycode,
		 * so must only check that the previously set position have
		 * not changed.  Expansion should have been filled with NoSymbol.
		 */
		for (j = 0; j < oldkpk; j++) {
			oldind = i*oldkpk + j;
			newind = i*newkpk + j;
			if (oldmap[oldind] == newmap[newind])
				CHECK;
			else {
				report("Keysym outside of range altered");
				report("  keycode %d was 0x%x, expecting 0x%x",
					Min_KeyCode+i, newmap[newind], oldmap[oldind]);
				FAIL;
			}
		}
	}

	/* Number of codes that should not have been changed is ncodes-num_codes */
	CHECKPASS((ncodes - num_codes)*oldkpk);
	tpcleanup();
	pfcount(pass, fail);
}

static void t003(){

XEvent	ev;
XDeviceMappingEvent	good;
int 	n;
int dmn;
XEventClass dmnc;
int 	pass = 0, fail = 0;

 	report_purpose(3);

	report_assertion("Assertion XChangeDeviceKeyMapping-3.(B)");
	report_assertion("A call to XChangeDeviceKeyMapping generates a");
	report_assertion("DeviceMappingNotify event.");
	report_assertion("Reason for omission: There is no known reliable test method for this assertion");

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

	tpstartup();
	setargs();
	if (!Devs.Key)
	    {
	    untested("%s: No input extension key device.\n", TestName);
	    return;
	    }
	DeviceMappingNotify(Devs.Key, dmn, dmnc);
	SelectExtensionEvents (display,DefaultRootWindow(display));
	device = Devs.Key;
	first_keycode = Min_KeyCode + 2;
	num_codes = 3;
	startcall(display);
	if (isdeleted())
		return;
	XChangeDeviceKeyMapping(display, device, first_keycode, keysyms_per_keycode, keysyms, num_codes);
	endcall(display);
	if (geterr() != Success) {
		report("Got %s, Expecting Success", errorname(geterr()));
		FAIL;
	}

	defsetevent(good, display, dmn);
	good.window = None;	/* unused */
	good.request = MappingKeyboard;
	good.first_keycode = first_keycode;
	good.count = num_codes;
	good.deviceid = Devs.Key->device_id;

	n = getevent(display, &ev);
	if (n == 0) {
		report("Expecting one DeviceMappingEvent");
		FAIL;
		return;
	} else
		CHECK;

	if (checkevent((XEvent*)&good, &ev))
		FAIL;
	else
		CHECK;

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

static void t004(){

int 	pass = 0, fail = 0;

 	report_purpose(4);

	report_assertion("Assertion XChangeDeviceKeyMapping-4.(B)");
	report_assertion("It is legal for the KeySym NoSymbol to appear anywhere in");
	report_assertion("the KeySym list for a particular KeyCode.");
	report_assertion("Reason for omission: There is no known reliable test method for this assertion");

	report_strategy("Call XChangeDeviceKeyMapping with the KeySym NoSymbol in the list.");
	report_strategy("Verify that no error occurs.");

	tpstartup();
	setargs();
	if (!Devs.Key)
	    {
	    untested("%s: No input extension key device.\n", TestName);
	    return;
	    }
	device = Devs.Key;
	first_keycode = Min_KeyCode;
	Keys[0] = NoSymbol;
	startcall(display);
	if (isdeleted())
		return;
	XChangeDeviceKeyMapping(display, device, first_keycode, keysyms_per_keycode, keysyms, num_codes);
	endcall(display);
	if (geterr() != Success) {
		report("Got %s, Expecting Success", errorname(geterr()));
		FAIL;
	}

	if (geterr() == Success)
		PASS;

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

static void t005(){

int 	pass = 0, fail = 0;

 	report_purpose(5);

	report_assertion("Assertion XChangeDeviceKeyMapping-5.(B)");
	report_assertion("When first_keycode is less than the value of min_keycode");
	report_assertion("returned by XDisplayKeycodes, then a BadValue error occurs.");
	report_assertion("Reason for omission: There is no known reliable test method for this assertion");

	report_strategy("Set first_keycode to a value less than min_keycode.");
	report_strategy("Call XChangeDeviceKeyMapping.");
	report_strategy("Verify that a BadValue error occurs.");

	tpstartup();
	setargs();
	if (!Devs.Key)
	    {
	    untested("%s: No input extension key device.\n", TestName);
	    return;
	    }
	device = Devs.Key;
	first_keycode = Min_KeyCode-1;
	startcall(display);
	if (isdeleted())
		return;
	XChangeDeviceKeyMapping(display, device, first_keycode, keysyms_per_keycode, keysyms, num_codes);
	endcall(display);
	if (geterr() != BadValue) {
		report("Got %s, Expecting BadValue", errorname(geterr()));
		FAIL;
	}

	if (geterr() == BadValue)
		PASS;
	tpcleanup();
	pfcount(pass, fail);
}

static void t006(){

int 	pass = 0, fail = 0;

 	report_purpose(6);

	report_assertion("Assertion XChangeDeviceKeyMapping-6.(B)");
	report_assertion("When first_keycode+num_codes-1 is greater than the");
	report_assertion("value of max_keycode returned by XDisplayKeycodes, then a");
	report_assertion("BadValue error occurs.");
	report_assertion("Reason for omission: There is no known reliable test method for this assertion");

	report_strategy("Set end of range to beyond max_keycode.");
	report_strategy("Call XChangeDeviceKeyMapping.");
	report_strategy("Verify that a BadValue error occurs.");

	tpstartup();
	setargs();
	if (!Devs.Key)
	    {
	    untested("%s: No input extension key device.\n", TestName);
	    return;
	    }
	device = Devs.Key;
	num_codes = Max_KeyCode - Min_KeyCode;
	first_keycode = Min_KeyCode+10;

	startcall(display);
	if (isdeleted())
		return;
	XChangeDeviceKeyMapping(display, device, first_keycode, keysyms_per_keycode, keysyms, num_codes);
	endcall(display);
	if (geterr() != BadValue) {
		report("Got %s, Expecting BadValue", errorname(geterr()));
		FAIL;
	}

	if (geterr() == BadValue)
		PASS;
	tpcleanup();
	pfcount(pass, fail);
}

/* Including from file error/EAll.mc */
/* End of included file error/EAll.mc */

/* Including from file error/EAll.mc */
static void t007(){

int 	pass = 0, fail = 0;

 	report_purpose(7);

	report_assertion("Assertion XChangeDeviceKeyMapping-7.(B)");
	report_assertion("When the server fails to allocate a required resource, then");
	report_assertion("a BadAlloc error occurs.");
	report_assertion("Reason for omission: There is no known portable test method for this assertion");

	report_strategy("Report UNTESTED");

	tpstartup();
	setargs();
	report("There is no reliable method of testing that a BadAlloc error is generated");
	tet_result(TET_UNTESTED);
	tpcleanup();
	pfcount(pass, fail);
}

/* End of included file error/EAll.mc */

/* 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)() = savekeymap;
void	(*tet_cleanup)() = cleankeymap;
