/* $XConsortium: xkbcfgtest.c /main/3 1996/02/05 11:44:55 kaleb $ */
/************************************************************
 Copyright (c) 1995 by Silicon Graphics Computer Systems, Inc.

 Permission to use, copy, modify, and distribute this
 software and its documentation for any purpose and without
 fee is hereby granted, 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 Silicon Graphics not be 
 used in advertising or publicity pertaining to distribution 
 of the software without specific prior written permission.
 Silicon Graphics makes no representation about the suitability 
 of this software for any purpose. It is provided "as is"
 without any express or implied warranty.
 
 SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS 
 SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY 
 AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
 GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL 
 DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, 
 DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE 
 OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION  WITH
 THE USE OR PERFORMANCE OF THIS SOFTWARE.

 ********************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <X11/Xos.h>
#include <X11/Xlib.h>
#include <X11/X.h>
#include <X11/XKBlib.h>
#include <X11/extensions/XKBfile.h>
#include <X11/extensions/XKBconfig.h>
#include <X11/Xfuncs.h>

Display	*	dpy= NULL;
static	char *	dpyName = NULL;
static	char *	inFileName = NULL;
static  char *	outFileName= NULL;
static	FILE *	inFile= stdin;
static	FILE *	outFile= stdout;
static	int	synch = 0;
static	int	debug = 0;

int
#if NeedFunctionPrototypes
parseArgs(int argc,char *argv[])
#else
parseArgs(argc,argv)
    int argc;
    char *argv[];
#endif
{
int i;

    for (i=1;i<argc;i++) {
	 if ((argv[i][0]!='-') || ((argv[i][0]=='-')&&(argv[i][1]=='-'))) {
	    if (inFileName==NULL)	inFileName= argv[i];
	    else if (outFileName==NULL)	outFileName= argv[i];
	    else {
		fprintf(stderr,"Too many files on command line, ignoring %s\n",
								      argv[i]);
	    }
	 }
	 else if ( strcmp(argv[i],"-display")==0 ) {
	    if ( ++i<argc )	dpyName= argv[i];
	    else {
		fprintf(stderr,"Must specify a display with -display option\n");
		return 0;
	    }
	}
	else if ( strcmp(argv[i],"-synch")==0 ) {
	    synch= 1;
	}
	else if ( strcmp(argv[i],"-debug")==0 ) {
	    debug= 1;
	}
	else {
	    fprintf(stderr,"Unknown option %s\n",argv[i]);
	    return 0;
	}
    }
    if ((inFileName!=NULL)&&(strcmp(inFileName,"--")!=0)) {
	inFile= fopen(inFileName,"r");
	if (!inFile) {
	    fprintf(stderr,"Couldn't open input file %s\n",inFileName);
	    fprintf(stderr,"Exiting\n");
	    exit(1);
	}
    }
    if ((outFileName!=NULL)&&(strcmp(outFileName,"--")!=0)) {
	outFile= fopen(outFileName,"w");
	if (!outFile) {
	    fprintf(stderr,"Couldn't open output file %s\n",outFileName);
	    fprintf(stderr,"Exiting\n");
	    exit(1);
	}
    }
    return 1;
}

Display *
#if NeedFunctionPrototypes
getDisplay(char *program,char *dpyName)
#else
getDisplay(program,dpyName)
    char *	program;
    char *	dpyName;
#endif
{
int	major,minor,error;
Display	*dpy;

    major= XkbMajorVersion;
    minor= XkbMinorVersion;
    dpy= XkbOpenDisplay(dpyName,NULL,NULL,&major,&minor,&error);
    if (dpy==NULL) {
	if (dpyName==NULL)
	    dpyName= "default display";
	switch (error) {
	    case XkbOD_BadLibraryVersion:
		fprintf(stderr,"%s was compiled with XKB version %d.%02d\n",
				program,XkbMajorVersion,XkbMinorVersion);
		fprintf(stderr,"X library uses incompatible version %d.%02d\n",
				major,minor);
		break;
	    case XkbOD_ConnectionRefused:
		fprintf(stderr,"Error! Cannot open display \"%s\"\n",dpyName);
		break;
	    case XkbOD_NonXkbServer:
		fprintf(stderr,"Error! XKB not present on %s\n",dpyName);
		break;
	    case XkbOD_BadServerVersion:
		fprintf(stderr,"%s was compiled with XKB version %d.%02d\n",
				program,XkbMajorVersion,XkbMinorVersion);
		fprintf(stderr,"Server %s uses incompatible version %d.%02d\n",
				dpyName,major,minor);
		break;
	    default:
		fprintf(stderr,"Unknown error %d from XkbOpenDisplay\n",error);
	}
    }
    else if (synch)
	XSynchronize(dpy,True);
    return dpy;
}

void
#if NeedFunctionPrototypes
printVirtualMods(	FILE * 			file,
    			char * 			name,
			unsigned 		what,
			XkbConfigRtrnPtr 	rtrn,
			XkbConfigModInfoPtr 	info)
#else
printVirtualMods(file,name,what,rtrn,info)
    FILE *		file;
    char *		name;
    unsigned		what;
    XkbConfigRtrnPtr	rtrn;
    XkbConfigModInfoPtr	info;
#endif
{
int			i;
Bool			first,haveClear;
XkbConfigUnboundModPtr	mod;
char			buf[30];

    sprintf(buf,"%s vmods: ",name);
    first= True;
    haveClear= False;
    for (mod=rtrn->unbound_mods,i=0;i<rtrn->num_unbound_mods;i++,mod++) {
	if ((mod->what!=what)||(mod->name==NULL))
	    continue;
	if (mod->merge==XkbCF_MergeRemove) {
	    haveClear= True;
	    continue;
	}
	if (first) {
	    if (info->replace)	fprintf(file,"%-17s%s",buf,mod->name);
	    else 		fprintf(file,"%-17sadd %s",buf,mod->name);
	    first= False;
	}
	else fprintf(file,"+%s",mod->name);
    }
    if (info->vmods!=0) {
	if (first) {
	    if (info->replace)	fprintf(file,"%-17s0x%02x",buf,info->vmods);
	    else 		fprintf(file,"%-17sadd 0x%02x",buf,info->vmods);
	}
	else fprintf(file,"+0x%02x",info->vmods);
	first= False;
    }
    if (haveClear&&(!info->replace)) {
	if (first)	fprintf(file,"%-17sclear ",buf);
	else		fprintf(file,", clear ");
	first= True;
	for (mod=rtrn->unbound_mods,i=0;i<rtrn->num_unbound_mods;i++,mod++) {
	    if ((mod->what!=what)||(mod->name==NULL)||
					(mod->merge!=XkbCF_MergeRemove)) {
		continue;
	    }
	    if (first)	fprintf(file,"%s",mod->name);
	    else	fprintf(file,"+%s",mod->name);
	    first= False;
	}
    }
    if ((!info->replace)&&(info->vmods_clear!=0)) {
	if (first)	fprintf(file,"%-17sclear 0x%02x",buf,info->vmods);
	else 		fprintf(file,"+0x%02x",info->vmods_clear);
	first= False;
    }
    if (!first)
	fprintf(file,"\n");
    return;
}

void
#if NeedFunctionPrototypes
printRealMods(FILE *file,char *name,XkbConfigModInfoPtr info)
#else
printRealMods(file,name,info)
    FILE *		file;
    char *		name;
    XkbConfigModInfoPtr	info;
#endif
{
char	buf[30];

    if (info->replace||info->mods||info->mods_clear) {
	sprintf(buf,"%s mods: ",name);
	if (info->replace) {
	    fprintf(file,"%-17s0x%02x\n",buf,info->mods);
	}
	else if (info->mods||info->mods_clear) {
	    fprintf(file,"%-17s",buf);
	    if (info->mods) {
		fprintf(file,"add 0x%02x",info->mods);
		if (info->mods_clear)
		    fprintf(file,", ");
	    }
	    if (info->mods_clear)
		 fprintf(file,"clear 0x%02x\n",info->mods_clear);
	    else fprintf(file,"\n");
	}
    }
    return;
}

void
#if NeedFunctionPrototypes
printConfig(FILE *file,XkbConfigRtrnPtr rtrn)
#else
printConfig(file,rtrn)
    FILE *		file;
    XkbConfigRtrnPtr	rtrn;
#endif
{
    if (rtrn->keymap)
	fprintf(file,"keymap:          %s\n",rtrn->keymap);
    if (rtrn->keycodes)
	fprintf(file,"keycodes:        %s\n",rtrn->keycodes);
    if (rtrn->geometry)
	fprintf(file,"geometry:        %s\n",rtrn->geometry);
    if (rtrn->phys_symbols)
	fprintf(file,"phys_symbols:    %s\n",rtrn->phys_symbols);
    if (rtrn->symbols)
	fprintf(file,"symbols:         %s\n",rtrn->symbols);
    if (rtrn->types)
	fprintf(file,"types:           %s\n",rtrn->types);
    if (rtrn->compat)
	fprintf(file,"compat:          %s\n",rtrn->compat);
    if (rtrn->replace_initial_ctrls) {
	fprintf(file,"controls:        0x%02x\n",rtrn->initial_ctrls);
    }
    else if (rtrn->initial_ctrls||rtrn->initial_ctrls_clear) {
	fprintf(file,"controls:        ");
	if (rtrn->initial_ctrls) {
	    fprintf(file,"add 0x%02x",rtrn->initial_ctrls);
	    if (rtrn->initial_ctrls_clear)
		fprintf(file,", ");
	}
	if (rtrn->initial_ctrls_clear)
	     fprintf(file,"clear 0x%02x\n",rtrn->initial_ctrls);
	else fprintf(file,"\n");
    }
    printRealMods(file,"initial",&rtrn->initial_mods);
    printVirtualMods(file,"initial",XkbCF_InitialMods,rtrn,&rtrn->initial_mods);
    printRealMods(file,"internal",&rtrn->internal_mods);
    printVirtualMods(file,"internal",XkbCF_InternalMods,rtrn,
							&rtrn->internal_mods);
    printRealMods(file,"ignore lock",&rtrn->ignore_lock_mods);
    printVirtualMods(file,"ignore lock",XkbCF_IgnoreLockMods,rtrn,
						&rtrn->ignore_lock_mods);
    
    fprintf(file,"timeout ctrls:   ignore 0x%x/on%s=0x%x/off%s=0x%x\n",
				rtrn->axt_ctrls_ignore,
				(rtrn->replace_axt_ctrls_on?"+":""),
				rtrn->axt_ctrls_on,
				(rtrn->replace_axt_ctrls_off?"+":""),
				rtrn->axt_ctrls_off);
    fprintf(file,"timeout opts:   ignore 0x%x/on%s=0x%x/off%s=0x%x\n",
				rtrn->axt_opts_ignore,
				(rtrn->replace_axt_opts_on?"+":""),
				rtrn->axt_opts_on,
				(rtrn->replace_axt_opts_off?"+":""),
				rtrn->axt_opts_off);
    if (rtrn->defined&XkbCF_GroupsWrap) {
	fprintf(file,"out-of-range groups: ");
	switch (XkbOutOfRangeGroupAction(rtrn->groups_wrap)) {
	    case XkbWrapIntoRange:
		fprintf(file,"wrap\n");
		break;
	    case XkbClampIntoRange:
		fprintf(file,"clamp\n");
		break;
	    case XkbRedirectIntoRange:
		fprintf(file,"redirect to %d\n",
				XkbOutOfRangeGroupNumber(rtrn->groups_wrap)+1);
		break;
	    default:
		fprintf(file,"ILLEGAL VALUE\n");
		break;
	}
    }
    if (rtrn->priv==NULL)
	fprintf(file,"No private fields present\n");
    else {
	XkbConfigRtrnPrivPtr	priv;
	int			count;
	for (count=0,priv=rtrn->priv;priv!=NULL;priv=priv->next,count++) {
	    /* conditional does the work */
	}
	fprintf(file,"%d private fields present\n",count);
    }
}

void
#if NeedFunctionPrototypes
printAppliedConfig(FILE *file,XkbDescPtr xkb,XkbConfigRtrnPtr rtrn)
#else
printAppliedConfig(file,xkb,rtrn)
    FILE *		file;
    XkbDescPtr		xkb;
    XkbConfigRtrnPtr	rtrn;
#endif
{
XkbNamesPtr	names;
XkbControlsPtr	ctrls;

    names= xkb->names;
    ctrls= xkb->ctrls;
    printRealMods(file,"initial",&rtrn->initial_mods);
    printVirtualMods(file,"initial",XkbCF_InitialMods,rtrn,&rtrn->initial_mods);
    fprintf(file,"Device ID:     %d\n",xkb->device_spec);
    fprintf(file,"keycodes type: %s\n",
				XkbAtomText(dpy,names->keycodes,XkbMessage));
    fprintf(file,"geometry type: %s\n",
				XkbAtomText(dpy,names->geometry,XkbMessage));
    fprintf(file,"symbols type:  %s ",
				XkbAtomText(dpy,names->symbols,XkbMessage));
    fprintf(file,"phys=%s\n",XkbAtomText(dpy,names->phys_symbols,XkbMessage));
    fprintf(file,"types:         %s\n",
				XkbAtomText(dpy,names->types,XkbMessage));
    fprintf(file,"compat:        %s\n",
				XkbAtomText(dpy,names->compat,XkbMessage));
    fprintf(file,"keycode range: %d-%d\n",xkb->min_key_code,xkb->max_key_code);
    fprintf(file,"audible bell:      %s\n",
		((ctrls->enabled_ctrls&XkbAudibleBellMask)?"on":"off"));
    fprintf(file,"internal mods:     %s\n",
			XkbVModMaskText(dpy,xkb,ctrls->internal.real_mods,
						ctrls->internal.vmods,
						XkbMessage));
    fprintf(file,"ignore lock mods:  %s\n",
			XkbVModMaskText(dpy,xkb,ctrls->ignore_lock.real_mods,
						ctrls->ignore_lock.vmods,
						XkbMessage));
    fprintf(file,"repeat keys:       %s (%d/%d)\n",
		(ctrls->enabled_ctrls&XkbRepeatKeysMask?"on":"off"),
		ctrls->repeat_delay,ctrls->repeat_interval);
    fprintf(file,"slow keys:         %s (%d)\n",
		(ctrls->enabled_ctrls&XkbSlowKeysMask?"on":"off"),
		ctrls->slow_keys_delay);
    fprintf(file,"bounce keys:       %s (%d)\n",
		(ctrls->enabled_ctrls&XkbBounceKeysMask?"on":"off"),
		ctrls->debounce_delay);
    fprintf(file,"sticky keys:       %s\n",
		(ctrls->enabled_ctrls&XkbStickyKeysMask?"on":"off"));
    fprintf(file,"mouse keys:        %s (btn=%d,accel=%d/%d/%d/%d)\n",
		(ctrls->enabled_ctrls&XkbMouseKeysMask?"on":"off"),
		ctrls->mk_dflt_btn, ctrls->mk_delay, ctrls->mk_interval,
		ctrls->mk_time_to_max, ctrls->mk_curve);
    fprintf(file,"access X keys:     %s\n",
		(ctrls->enabled_ctrls&XkbAccessXKeysMask?"on":"off"),
		ctrls->ax_timeout);
    fprintf(file,"                   ctrls: 0x%x/0x%x, opts 0x%x/0x%x\n",
		ctrls->axt_ctrls_mask,ctrls->axt_ctrls_values,
		ctrls->axt_opts_mask,ctrls->axt_opts_values);
    fprintf(file,"overlay 1:         %s\n",
		((ctrls->enabled_ctrls&XkbOverlay1Mask)?"on":"off"));
    fprintf(file,"overlay 2:         %s\n",
		((ctrls->enabled_ctrls&XkbOverlay2Mask)?"on":"off"));
    return;
}

int
#if NeedFunctionPrototypes
main(int argc,char *argv[])
#else
main(argc,argv)
    int		argc;
    char *	argv[];
#endif
{
XkbConfigRtrnRec	rtrn;
XkbDescPtr		xkb;

    if (!parseArgs(argc,argv)) {
	fprintf(stderr,"Usage: %s [<options>] infile outfile\n",argv[0]); 
	fprintf(stderr,"Where legal options are:\n");
	fprintf(stderr,"-display  <dpy>     specifies display to use\n");
	fprintf(stderr,"-synch              force synchronization\n");
	return 1;
    }
    bzero(&rtrn,sizeof(XkbConfigRtrnRec));
    if (XkbCFParse(inFile,XkbCFDflts,NULL,&rtrn)) {
	fprintf(outFile,"XKB Config interpreted successfully!\n");
	printConfig(outFile,&rtrn);
	if (dpyName!=NULL) {
	    dpy= getDisplay(argv[0],dpyName);
	    if (dpy!=NULL) {
		fprintf(outFile,"Loading from local display...map...");
		xkb= XkbGetMap(dpy,0,XkbUseCoreKbd);
		if (xkb)
		    fprintf(outFile,"ok, names...");
		else {
		    fprintf(outFile,"FAILED!\n");
		    goto BAILOUT;
		}
		if (XkbGetNames(dpy,XkbAllNamesMask,xkb)==Success)
		    fprintf(outFile,"ok, controls...");
		else {
		    fprintf(outFile,"FAILED!\n");
		    goto BAILOUT;
		}
		if (XkbGetControls(dpy,XkbAllControlsMask,xkb)==Success)
		    fprintf(outFile,"ok\n");
		else {
		    fprintf(outFile,"FAILED!\n");
		    goto BAILOUT;
		}
		fprintf(outFile,"Applying config to description...");
		if (XkbCFApplyRtrnValues(&rtrn,XkbCFDflts,xkb))
		    fprintf(outFile,"done\n");
		else {
		    fprintf(outFile,"FAILED\n");
		    goto BAILOUT;
		}
		printAppliedConfig(outFile,xkb,&rtrn);
		XCloseDisplay(dpy);
	    }
	    else {
		fprintf(outFile,"Couldn't open \"%s\", config not merged\n",
								dpyName);
	    }
	}
	return 0;
    }
    else {
	printf("Error interpreting XKB config info: ");
	XkbCFReportError(outFile,(inFile==stdin?"stdin":inFileName),
						rtrn.error,rtrn.line);
    }
    return 0;
BAILOUT:
    XCloseDisplay(dpy);
    return 1;
}
