/*
* 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:
 *   XModifierKeymap *
 *   XGetModifierMapping(display)
 *   Display	*display;
 */


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

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


/*
 * Arguments to the XGetModifierMapping function
 */
static Display	*display;


static int pgrabbed(display, win)
Display *display;
Window win;
{
	PointerPlace	*p;
	XEvent		ev;
	int		result;

	XSync(display, True);
	XSelectInput(display, win, PointerMotionMask);
	p = warppointer(display, win, 0,0);
	warppointer(display, win, 10,10);
	warppointer(display, p->oroot, p->ox, p->oy);
	result = (getevent(display, &ev) == 0);
	XSync(display, True);
	return result;
}

int 	tet_thistest;

/*
 * Called at the beginning of each test purpose to reset the
 * arguments to their initial values
 */
static void
setargs()
{
	display = Dsp;
}

/*
 * 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 XGetModifierMapping-1.(A)");
	report_assertion("A call to XGetModifierMapping returns a pointer to a newly");
	report_assertion("created XModifierKeymap structure that contains the KeyCodes");
	report_assertion("being used as modifiers and the structure can be freed with");
	report_assertion("XFreeModifiermap.");

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

	tpstartup();
	setargs();
	startcall(display);
	if (isdeleted())
		return;
	mkmp = XGetModifierMapping(display);
	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;
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 XGetModifierMapping-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 XGetModifierMapping, save one.");
	report_strategy("  Zero keycodes for Shift.");
	report_strategy("  Call XSetModiferMapping to set map to that with zeroed Shift row.");
	report_strategy("  Set passive pointer 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 pointer 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 (noext(1))
		return;
	else
		CHECK;
	win = defwin(display);
	client2 = opendisplay();
	XDisplayKeycodes(display, &minkc, &maxkc);
	startcall(display);
	if (isdeleted())
		return;
	savemap = XGetModifierMapping(display);
	endcall(display);
	if (geterr() != Success) {
		report("Got %s, Expecting Success", errorname(geterr()));
		FAIL;
	}
	startcall(display);
	if (isdeleted())
		return;
	map = XGetModifierMapping(display);
	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 (XSetModifierMapping(display, map) != MappingSuccess || isdeleted()) {
		delete("Could not set new mapping with all zeroes for Shift.");
		XSetModifierMapping(display, savemap);
		XFreeModifiermap(map);
		XFreeModifiermap(savemap);
		return;
	} else
		CHECK;
	XGrabButton(display, AnyButton, ShiftMask, win, False, 0, GrabModeAsync, GrabModeAsync, None, None);
	if (isdeleted()) {
		delete("Could not set passive button grab.");
		XSetModifierMapping(display, savemap);
		XFreeModifiermap(map);
		XFreeModifiermap(savemap);
		return;
	} else
		CHECK;
	if (pgrabbed(client2, win)) {
		delete("Passive button grab erroneously triggered.");
		XSetModifierMapping(display, savemap);
		XFreeModifiermap(map);
		XFreeModifiermap(savemap);
		return;
	} else
		CHECK;
	warppointer(display, win, 2,2); /* pgrabbed restores pointer */
	for(k=minkc; k <= maxkc; k++) {
		keypress(display, k);
		buttonpress(display, Button1);
		if (pgrabbed(client2, win)) {
			report("Despite Shift being disabled keycode %d acted like Shift modifier.", k);
			FAIL;
		} else
			CHECK;
		relalldev();
	}

	XUngrabButton(display, AnyButton, AnyModifier, win);
	XSetModifierMapping(display, savemap);
	XFreeModifiermap(map);
	XFreeModifiermap(savemap);

	CHECKPASS(5 + (maxkc - minkc + 1));
	tpcleanup();
	pfcount(pass, fail);
}

/* End of Test Cases */


struct tet_testlist tet_testlist[] = {
	{ t001, 1 },
	{ t002, 2 },
	{ NULL, 0 }
};

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

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