/*
* 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:
 *   XModifierKeymap	*
 *   XGetDeviceModifierMapping(display, device)
 *   Display	*display;
 *   XDevice *device;
 */


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

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


/*
 * Arguments to the XGetDeviceModifierMapping function
 */
static Display	*display;
static XDevice *device;


extern ExtDeviceInfo Devs;


static int dgrabbed(display, dev, win)
Display *display;
XDevice *dev;
Window win;
{
int ret;
Display *client1;

/* Create client1, without causing resource registration. */
	if (config.display == NULL) {
		delete("config.display not set");
		return;
	}
	client1 = XOpenDisplay(config.display);
	if (client1 == NULL) {
		delete("Couldn't create client1.");
		return;
	}
	ret = XGrabDevice(client1, dev, win, True, 0, NULL,
	    GrabModeAsync, GrabModeAsync, CurrentTime);
	if (ret == AlreadyGrabbed)
	    {
	    XCloseDisplay(client1);
	    return(True);
	    }
	else
	    {
	    XUngrabDevice(client1, dev, CurrentTime);
	    XCloseDisplay(client1);
	    return(False);
	    }
}

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;
}

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

static void t001(){

XModifierKeymap	*mkmp;
extern struct	valname	S_modifier[];
extern int 	NS_modifier;
int 	mod;
int 	set;
int 	pass = 0, fail = 0;

 	report_purpose(1);

	report_assertion("Assertion XGetDeviceModifierMapping-1.(B)");
	report_assertion("A call to GetDeviceModifierMapping returns a pointer to a");
	report_assertion("newly created XModifierKeymap structure that contains the");
	report_assertion("KeyCodes being used as modifiers and the structure can be");
	report_assertion("freed with XFreeModifiermap.");
	report_assertion("Reason for omission: There is no known reliable test method for this assertion");

	report_strategy("Call XGetDeviceModifierMapping to get the current map.");
	report_strategy("Free map with XFreeModifiermap.");

	tpstartup();
	setargs();
	if (!Setup_Extension_DeviceInfo(KeyMask | ModMask))
	    {
	    untested("%s: No input extension device without keys.\n", TestName);
	    return;
	    }
	device = Devs.Mod;
	startcall(display);
	if (isdeleted())
		return;
	mkmp = XGetDeviceModifierMapping(display, device);
	endcall(display);
	if (geterr() != Success) {
		report("Got %s, Expecting Success", errorname(geterr()));
		FAIL;
	}

	for (mod = 0; mod < NS_modifier; mod++) {
		trace("modifier %s:", S_modifier[mod].name);
		for (set = 0; set < mkmp->max_keypermod; set++) {
			trace("  0x%x", mkmp->modifiermap[set+mod*mkmp->max_keypermod]);
		}
	}

	XFreeModifiermap(mkmp);

        CHECK;  /* Merely check and record that we reach this point. */
        CHECKPASS(1);
	tpcleanup();
	pfcount(pass, fail);
}

static void t002(){

Window win;
Display *client2;
int minkc, maxkc, numkeys;
XModifierKeymap *map;
XModifierKeymap *savemap;
int k;
int i;
int row;
int non_zero = 0;
int 	pass = 0, fail = 0;

 	report_purpose(2);

	report_assertion("Assertion XGetDeviceModifierMapping-2.(B)");
	report_assertion("When only zero values appear in the set for any modifier,");
	report_assertion("then that modifier is disabled.");
	report_assertion("Reason for omission: There is no known reliable test method for this assertion");

	report_strategy("If extension available and at least one button:");
	report_strategy("  Create a window.");
	report_strategy("  Get two copies of current modifier map using XGetDeviceModifierMapping, save one.");
	report_strategy("  Zero keycodes for Shift.");
	report_strategy("  Call XSetDeviceModiferMapping to set map to that with zeroed Shift row.");
	report_strategy("  Set passive device grab on AnyButton with Shift modifier for window.");
	report_strategy("  Warp pointer into window.");
	report_strategy("  For all keycodes");
	report_strategy("    Simulate key press.");
	report_strategy("    Simulate Button1 press.");
	report_strategy("    Check that device grab not active (i.e. key has not acted as Shift modifier).");
	report_strategy("    Release key and button.");
	report_strategy("  Restore map to saved version.");
	report_strategy("  Free maps.");
	report_strategy("else");
	report_strategy("  report untested.");

	tpstartup();
	setargs();
	if (!Setup_Extension_DeviceInfo(KeyMask | ModMask | BtnMask))
	    {
	    untested("%s: Required input extension devices not present.\n", TestName);
	    return;
	    }
	if (noext(1))
	    return;
	else
	    CHECK;
	devicerelkeys(Devs.Mod);
	devicerelbuttons(Devs.Button);
	win = defwin(display);
	client2 = opendisplay();

	MinMaxKeys(display, Devs.Mod, &minkc, &maxkc, &numkeys);
	device = Devs.Mod;
	startcall(display);
	if (isdeleted())
		return;
	savemap = XGetDeviceModifierMapping(display, device);
	endcall(display);
	if (geterr() != Success) {
		report("Got %s, Expecting Success", errorname(geterr()));
		FAIL;
	}
	startcall(display);
	if (isdeleted())
		return;
	map = XGetDeviceModifierMapping(display, device);
	endcall(display);
	if (geterr() != Success) {
		report("Got %s, Expecting Success", errorname(geterr()));
		FAIL;
	}
	if (isdeleted() || geterr() != Success || !map || !savemap) {
		delete("Could not get initial modifier key map.");
		return;
	} else
		CHECK;
	row = ShiftMapIndex * map->max_keypermod;
	for (i=0; i<map->max_keypermod; i++) {
	    if (map->modifiermap[ row+i ]) {
		trace("Shift had keycode %d.", map->modifiermap[ row+i ]);
		non_zero++;
		map->modifiermap[ row+i ] = 0;
	    }
	}
	trace("Shift had %d keycodes.", non_zero);
	if (XSetDeviceModifierMapping(display, Devs.Mod, map) != MappingSuccess || isdeleted()) {
		delete("Could not set new mapping with all zeroes for Shift.");
		XSetDeviceModifierMapping(display, Devs.Mod, savemap);
		XFreeModifiermap(map);
		XFreeModifiermap(savemap);
		return;
	} else
		CHECK;
	XGrabDeviceButton(display, Devs.Button, AnyButton, ShiftMask, Devs.Mod, win, False, 0, NULL, GrabModeAsync, GrabModeAsync);
	if (isdeleted()) {
		delete("Could not set passive button grab.");
		XSetDeviceModifierMapping(display, Devs.Mod, savemap);
		XFreeModifiermap(map);
		XFreeModifiermap(savemap);
		return;
	} else
		CHECK;
	if (dgrabbed(client2, Devs.Button, win)) {
		delete("Passive button grab erroneously triggered.");
		XSetDeviceModifierMapping(display, Devs.Mod, savemap);
		XFreeModifiermap(map);
		XFreeModifiermap(savemap);
		return;
	} else
		CHECK;
	warppointer(display, win, 2,2); /* dgrabbed restores pointer */
	for(k=minkc; k <= maxkc; k++) {
		devicekeypress(display, Devs.Mod, k);
		devicebuttonpress(display, Devs.Button, Button1);
		if (dgrabbed(client2, Devs.Button, win)) {
			report("Despite Shift being disabled keycode %d acted like Shift modifier.", k);
			FAIL;
		} else
			CHECK;
		devicekeyrel(display, Devs.Mod, k);
		devicebuttonrel(display, Devs.Button, Button1);
		devicerelkeys(Devs.Mod);
		devicerelbuttons(Devs.Button);
	}

	XUngrabDeviceButton(display, Devs.Button, AnyButton, ShiftMask, Devs.Mod, win);
	XSetDeviceModifierMapping(display, Devs.Mod, savemap);
	XFreeModifiermap(map);
	XFreeModifiermap(savemap);
	CHECKPASS(5 + maxkc - minkc + 1);

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

static void t003(){

XModifierKeymap *ret;
int 	pass = 0, fail = 0;

 	report_purpose(3);

	report_assertion("Assertion XGetDeviceModifierMapping-3.(B)");
	report_assertion("If a device with no keys is specified, a BadMatch error");
	report_assertion("occurs.");
	report_assertion("Reason for omission: There is no known reliable test method for this assertion");

	report_strategy("Specifiy a device with no keys.");

	tpstartup();
	setargs();
	if (!Setup_Extension_DeviceInfo(NKeysMask))
	    {
	    untested("%s: No input extension device without keys.\n", TestName);
	    return;
	    }
	device = Devs.NoKeys;
	startcall(display);
	if (isdeleted())
		return;
	ret = XGetDeviceModifierMapping(display, device);
	endcall(display);
	if (geterr() != BadMatch) {
		report("Got %s, Expecting BadMatch", errorname(geterr()));
		FAIL;
	}

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

static void t004(){

XModifierKeymap *ret;
int baddevice;
XDevice bogus;
int ximajor, first, err;
int 	pass = 0, fail = 0;

 	report_purpose(4);

	report_assertion("Assertion XGetDeviceModifierMapping-4.(B)");
	report_assertion("If an invalid device is specified, a BadDevice error");
	report_assertion("occurs.");
	report_assertion("Reason for omission: There is no known reliable test method for this assertion");

	report_strategy("Specifiy an invalid device.");

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

	BadDevice(display, baddevice);
	bogus.device_id = -1;
	device = &bogus;
	startcall(display);
	if (isdeleted())
		return;
	ret = XGetDeviceModifierMapping(display, device);
	endcall(display);
	if (geterr() != baddevice) {
		report("Got %s, Expecting baddevice", errorname(geterr()));
		FAIL;
	}

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

/* End of Test Cases */


struct tet_testlist tet_testlist[] = {
	{ t001, 1 },
	{ t002, 2 },
	{ t003, 3 },
	{ t004, 4 },
	{ NULL, 0 }
};

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

void	(*tet_startup)() = startup;
void	(*tet_cleanup)() = cleanup;
