/* $XConsortium: xkbextdev.c /main/2 1996/02/05 11:45:03 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 <unistd.h>
#include <ctype.h>
#include <string.h>
#include <X11/Xproto.h>
#include <X11/Xlib.h>
#include <X11/X.h>
#include <X11/XKBlib.h>
#include <X11/extensions/XKM.h>
#include <X11/extensions/XKBfile.h>
#include <X11/extensions/XI.h>
#include <X11/Xfuncs.h>

/***====================================================================***/

static	Display *	dpy;
static	char *		dpyName = NULL;
static	Bool		verbose= False;
static	Bool		synch = False;
static	Bool		createVMods= False;
static	int		device= XkbUseCoreKbd;
static	int		led_class= XkbAllXIClasses;
static	int		led_id= XkbAllXIIds;
static	char *		mergeFile = NULL;
static	char *		replaceFile = NULL;
static 	char *		compileCmd= "xkbcomp -w 0 - xkbextdev.xkm";
static	char *		tmpFile= "xkbextdev.xkm";

/***====================================================================***/

int
#if NeedFunctionPrototypes
ParseArgs(int argc,char *argv[])
#else
ParseArgs(argc,argv)
    int argc;
    char *argv[];
#endif
{
int 	i,tmp;
Bool	defining;

    defining= False;
    for (i=1;i<argc;i++) {
	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],"-v")==0 ) {
	    verbose++;
	}
	else if ( strcmp(argv[i],"-class")==0 ) {
	    if ( ++i>=argc ) {
		fprintf(stderr,"Must specify a class with %s option\n",argv[i]);
		return 0;
	    }
	    if (strcmp(argv[i],"kbd")==0)
		led_class= KbdFeedbackClass;
	    else if (strcmp(argv[i],"led")==0)
		led_class= LedFeedbackClass;
	    else if (strcmp(argv[i],"dflt")==0)
		led_class= XkbDfltXIClass;
	    else if (strcmp(argv[i],"all")==0)
		led_class= XkbAllXIClasses;
	    else {
		fprintf(stderr,"Class must be one of kbd, led, dflt or all\n");
		return 0;
	    }
	}
	else if ( strcmp(argv[i],"-device")==0 ) {
	    if ( ++i>=argc ) {
		fprintf(stderr,"Must specify a device id with %s option\n",
								argv[i]);
		return 0;
	    }
	    if (strcmp(argv[i],"kbd")==0) 
		device= XkbUseCoreKbd;
	    else if (strcmp(argv[i],"ptr")==0) 
		device= XkbUseCorePtr;
	    else if (sscanf(argv[i],"%i",&tmp)==1) {
		if ((tmp<0)||(tmp>255)) {
		    fprintf(stderr,"Device id must be in the range 0..255.\n");
		    return 0;
		}
		device= tmp;
	    }
	    else {
		fprintf(stderr,"Device id must be kbd, ptr, or an integer.\n");
		return 0;
	    }
	}
	else if ( strcmp(argv[i],"-id")==0 ) {
	    if ( ++i>=argc ) {
		fprintf(stderr,"Must specify a feedback id with %s option\n",
								argv[i]);
		return 0;
	    }
	    if (strcmp(argv[i],"dflt")==0)
		led_id= XkbDfltXIId;
	    else if (strcmp(argv[i],"all")==0)
		led_id= XkbAllXIIds;
	    else if (sscanf(argv[i],"%i",&tmp)==0) {
		if ((tmp<0)||(tmp>255)) {
		    fprintf(stderr,"Feedback id must be dflt, all, or in the range 0..255.\n");
		    return 0;
		}
		led_id= tmp;
	    }
	    else {
		fprintf(stderr,"Class must be one of kbd, led, dflt or all\n");
		return 0;
	    }
	}
	else if ( strcmp(argv[i],"-merge")==0 ) {
	    if ( ++i<argc )	mergeFile= argv[i];
	    else {
		fprintf(stderr,"Must specify a file with -merge option\n");
		return 0;
	    }
	    defining= True;
	}
	else if ( strcmp(argv[i],"-replace")==0 ) {
	    if ( ++i<argc )	replaceFile= argv[i];
	    else {
		fprintf(stderr,"Must specify a file with -replace option\n");
		return 0;
	    }
	}
	else if ( strcmp(argv[i],"-xkbcomp")==0 ) {
	    if ( ++i<argc )	compileCmd= argv[i];
	    else {
		fprintf(stderr,"Must specify a file with -xkbcomp option\n");
		return 0;
	    }
	    defining= True;
	}
	else if ( strcmp(argv[i],"-tmpfile")==0 ) {
	    if ( ++i<argc )	tmpFile= argv[i];
	    else {
		fprintf(stderr,"Must specify a file with -tmpfile option\n");
		return 0;
	    }
	}
	else {
	    fprintf(stderr,"Unknown option %s\n",argv[i]);
	    return 0;
	}
    }
    if (!defining)
	verbose= 1;
    return 1;
}

void
#if NeedFunctionPrototypes
ShowMaps(	Display *		dpy,
		XkbDescPtr 		xkb,
		XkbDeviceInfoPtr 	devi,
		XkbDeviceLedInfoPtr 	devli)
#else
ShowMaps(dpy,xkb,devi,devli)
    Display *		dpy;
    XkbDescPtr		xkb;
    XkbDeviceInfoPtr	devi;
    XkbDeviceLedInfoPtr	devli
#endif
{
register int 	i;
unsigned	bit;
char	*	name;
unsigned 	state;
Bool		isDflt;

    state= devli->state;
    isDflt= False;
    if (devli->led_class==LedFeedbackClass)
	 isDflt= (devli->led_id==devi->dflt_led_fb);
    else isDflt= (devli->led_id==devi->dflt_kbd_fb);
    fprintf(stderr,"Class= %s, ID= %d%s\n",
			(devli->led_class==LedFeedbackClass?"LED":"Keyboard"),
			devli->led_id,(isDflt?" (default)":""));
    for (i=0,bit=1;i<XkbNumIndicators;i++,bit<<=1) {
	unsigned	f,wm,mask,m,vm,wg,g,c;
	if (((devli->maps_present|devli->names_present)&bit)==0)
	    continue;
	f= devli->maps[i].flags;
	wm= devli->maps[i].which_mods;
	mask= devli->maps[i].mods.mask;
	m= devli->maps[i].mods.real_mods;
	vm= devli->maps[i].mods.vmods;
	wg= devli->maps[i].which_groups;
	g= devli->maps[i].groups;
	c= devli->maps[i].ctrls;
	if (devli->phys_indicators&(1<<i)) 
	     printf("    Physical ");
	else printf("    Virtual  ");
	printf("indicator %d",i+1);
	if (devli->names&& (devli->names_present&bit) &&
		(name=XkbAtomText(dpy,devli->names[i],XkbMessage))&&
		(name[0])) {
	    printf(" (%s)",name);
	}
	printf(": %s\n",(state&(1<<i)?"on":"off"));
	switch (f&(XkbIM_NoExplicit|XkbIM_NoAutomatic)) {
	    case XkbIM_NoExplicit:
		printf("        change:     automatic\n");
		break;
	    case XkbIM_NoAutomatic:
		printf("        change:     explicit\n");
		break;
	    case XkbIM_NoExplicit|XkbIM_NoAutomatic:
		printf("        change:     never\n");
		break;
	    case 0:
		printf("        change:     automatic or explicit\n");
		break;
	}
	if (f&XkbIM_LEDDrivesKB)
	    printf("        drives keyboard when changed\n");

	if ((wm!=0)&&((m!=0)||(vm!=0))) {
	    printf("        modifiers:  %s (%s)\n",
				XkbVModMaskText(dpy,xkb,m,vm,XkbMessage),
				XkbIMWhichStateMaskText(wm,XkbMessage));
	    if (mask!=m)
		printf("        mask:       %s\n",
				XkbModMaskText(mask,XkbMessage));
	}
	if ((wg!=0)&&(g!=0)) {
	    printf("        groups:     0x%x (%s)\n",devli->maps[i].groups,
				XkbIMWhichStateMaskText(wg,XkbMessage));
	}
	if (c!=0) {
	    printf("        controls:   %s\n",XkbControlsMaskText(c,XkbMessage));
	}
	fflush(stdout);
    }
    return;
}

void
#if NeedFunctionPrototypes
ShowDevice(Display *dpy,XkbDeviceInfoPtr devi,XkbDescPtr xkb)
#else
ShowDevice(dpy,devi,xkb)
    Display *		dpy;
    XkbDeviceInfoPtr	devi;
    XkbDescPtr		xkb;
#endif
{
register int i;
char *	type;

    if (devi->name)
	 printf("Device \"%s\" (id=%d)\n",devi->name,devi->device_spec);
    else printf("Device %d (no name)\n",devi->device_spec);
    if (devi->has_own_state)	printf("    Has own state\n");
    else			printf("    Uses core keyboard state\n");
    if (devi->type!=None) {
	 type= XkbAtomGetString(dpy,devi->type);
	 printf("    type: %s\n",type);
    }
    else printf("    type: (unknown)\n");
    
    if (devi->num_btns>0) {
	printf("    %d button%s\n",devi->num_btns,(devi->num_btns>1?"s":""));
	for (i=0;i<devi->num_btns;i++) {
	    if (devi->btn_acts[i].type!=XkbSA_NoAction) {
		printf("       %3d: %s\n",i+1,
			XkbActionText(dpy,xkb,&devi->btn_acts[i],XkbMessage));
	    }
	}
    }
    else {
	printf("    No buttons\n");
    }
    if (devi->num_leds>0) {
	printf("    %d feedbacks with LEDs\n",devi->num_leds,
						(devi->num_leds>1?"s":""));
	for (i=0;i<devi->num_leds;i++) {
	    ShowMaps(dpy,xkb,devi,&devi->leds[i]);
	}
    }
    else {
	printf("    No feedbacks with LEDs\n");
    }
}

void
#if NeedFunctionPrototypes
xkb_prologue (XkbEvent *eventp,char *event_name)
#else
xkb_prologue (eventp, event_name)
    XkbEvent *eventp;
    char *event_name;
#endif
{
    XkbAnyEvent *e = &eventp->any;

    printf ("\n%s event, serial %ld, synthetic %s, device %d, time %ld,\n",
	    event_name, e->serial, e->send_event ? "Yes" : "no", 
	    e->device,e->time);
    return;
}

void
#if NeedFunctionPrototypes
do_XkbExtensionDeviceNotify(XkbEvent *xkbev)
#else
do_XkbExtensionDeviceNotify(xkbev)
    XkbEvent	*xkbev;
#endif
{
    XkbExtensionDeviceNotifyEvent *edn= &xkbev->device;
    printf("    device= %d, class= %d, id= %d\n",edn->device,
						edn->led_class,edn->led_id);
    printf("    reason= 0x%0x\n",edn->reason);
    printf("    supported= 0x%0x, unsupported= 0x%0x\n",edn->supported,
							edn->unsupported);
    printf("    first button= %d, num buttons= %d\n",edn->first_btn,
							edn->num_btns);
    printf("    leds defined= 0x%08x, led state= 0x%08x\n",
					edn->leds_defined,edn->led_state);
    return;
}

Bool
#if NeedFunctionPrototypes
GetActionsFromFile(XkbDescPtr kbd,XkbDeviceInfoPtr devi,int *first,int *nBtns)
#else
GetActionsFromFile(kbd,devi,first,nBtns)
    XkbDescPtr		kbd;
    XkbDeviceInfoPtr	devi;
    int *		first;
    int *		nBtns;
#endif
{
FILE *		file,*pipe;
register int	i,ch;
XkbFileInfo	result;
unsigned	tmp;

    if (devi->num_btns<1) {
	fprintf(stderr,"Device doesn't seem to have buttons\n");
	return False;
    }
    file= fopen((replaceFile?replaceFile:mergeFile),"r");
    if (!file) {
	fprintf(stderr,"Couldn't open \"%s\" for button actions\n",
					(replaceFile?replaceFile:mergeFile));
	return False;
    }
    if (replaceFile)
	bzero((char *)devi->btn_acts,devi->num_btns*sizeof(XkbAction));
    unlink(tmpFile);
    pipe= popen(compileCmd,"w");
    if (!pipe) {
	fprintf(stderr,"Couldn't start xkbcomp.\n");
	fclose(file);
	return False;
    }
    fprintf(pipe,"xkb_layout \"bogus_device\" {\n");
    fprintf(pipe,"    xkb_keycodes \"bogus\" {\n");
    for (i=0;i<devi->num_btns;i++) {
	fprintf(pipe,"        <B%03d> = %d;\n",i+1,i+8);
    }
    fprintf(pipe,"    };\n");
    fprintf(pipe,"    xkb_types \"extra_bogus\" {  };\n");
    fprintf(pipe,"    xkb_symbols \"double_plus_bogus\" {\n");
    if (kbd && kbd->names && kbd->names->vmods[0]) {
	Bool	first= True;
	fprintf(pipe,"        virtual_modifiers ");
	for (i=0;i<XkbNumVirtualMods;i++) {
	    char *ptrn;
	    if (kbd->names->vmods[i]==None)
		break;
	    if (first)	ptrn= "%s";
	    else	ptrn= ", %s";
	    fprintf(pipe,ptrn,XkbAtomText(dpy,kbd->names->vmods[i],XkbMessage));
	    first= False;
	}
	fprintf(pipe,";\n");
    }
    while ((ch=fgetc(file))!=EOF) {
	fputc(ch,pipe);
    }
    fprintf(pipe,"    };\n");
    fprintf(pipe,"};\n");
    fclose(file);
    if (pclose(pipe)!=0) {
	fprintf(stderr,"Errors compiling button actions\n");
	return False;
    }
    file= fopen(tmpFile,"r");
    if (!file) {
	fprintf(stderr,"Couldn't open intermediate file for reading\n");
	return False;
    }
    bzero((char *)&result,sizeof(result));
    tmp= XkmReadFile(file,0,XkmLayoutLegal,&result);
    fclose(file);
    if ((!result.xkb)||(!result.xkb->server)||(!result.xkb->server->acts)) {
	fprintf(stderr,"Error reading compiled keymap\n");
	return False;
    }
    else if (tmp!=0) {
	fprintf(stderr,"Didn't get everything we asked for (0x%x).\n",tmp);
    }
    for (i=0;i<devi->num_btns;i++) {
	XkbAction *act;
	act= XkbKeyActionsPtr(result.xkb,i+8);
	devi->btn_acts[i]= *act;
    }
    *first= 0;
    *nBtns= devi->num_btns;
    return True;
}

#define	E(m)	fprintf(stderr,(m))
int
#if NeedFunctionPrototypes
main(int argc,char *argv[])
#else
main(argc,argv)
    int argc;
    char *argv[];
#endif
{
int			major,minor,why;
XkbDescPtr		xkb;
XkbDeviceInfoPtr	devi;
int			event;
XkbEvent		ev;
Bool			done;

    XkbInitAtoms(NULL);
    if (!ParseArgs(argc,argv)) {
	fprintf(stderr,"Usage: %s <options>\n",argv[0]);
	E("Where legal options are:\n");
	E("-display <dpy>         specifies display to use\n");
	E("-v                     show indicator mapping\n");
	E("-synch                 turn on synchronization\n");
	E("-device <device_spec>  specifies device to use, where\n");
	E("                       <device_spec> can be any of:\n");
	E("                       ptr,kbd,0..255\n");
	E("-class <class_spec>    specifies class of the feedback to use\n");
	E("                       <class_spec> can be any of:\n");
	E("                       kbd,led,dflt,all\n");
	E("-id <id_spec>          specifies id of the feedback to use\n");
	E("                       <id_spec> can be any of:\n");
	E("                       dflt,all,0..255\n");
	E("-merge <btn_file>      specifies file from which button actions\n");
	E("                       should be merged\n");
	E("-replace <btn_file>    specifies file from which button actions\n");
	E("                       should be copied\n");
	E("-xkbcomp <cmd>         command used to compile keyboard\n");
	E("-tmpfile <file>        name of intermediate file\n");
	return 1;
    }
    major= XkbMajorVersion;
    minor= XkbMinorVersion;
    dpy = XkbOpenDisplay(dpyName,&event,NULL,&major,&minor,&why);
    if (dpy==NULL) {
	if (dpyName==NULL)
	    dpyName= "default display";
        switch (why) {
            case XkbOD_BadLibraryVersion:
                fprintf(stderr,"%s was compiled with XKB version %d.%02d\n",
                                argv[0],XkbMajorVersion,XkbMinorVersion);
                fprintf(stderr,"Xlib supports incompatible version %d.%02d\n",
                                major,minor);
                break;
            case XkbOD_ConnectionRefused:
                fprintf(stderr,"Cannot open display \"%s\"\n",dpyName);
                break;
            case XkbOD_NonXkbServer:
                fprintf(stderr,"XKB extension not present on %s\n",dpyName);
                break;
            case XkbOD_BadServerVersion:
                fprintf(stderr,"%s was compiled with XKB version %d.%02d\n",
                                argv[0],XkbMajorVersion,XkbMinorVersion);
                fprintf(stderr,"Server %s uses incompatible version %d.%02d\n",
                                dpyName,major,minor);
                break;
            default:
                fprintf(stderr,
		    "Internal Error! Unknown error %d from XkbOpenDisplay\n",
		    why);
        }
	return 1;
    }
    if (synch)
	XSynchronize(dpy,1);
    XkbSelectEventDetails(dpy,device,XkbExtensionDeviceNotify,
					XkbAllExtensionDeviceEventsMask,
					XkbAllExtensionDeviceEventsMask);
    devi= XkbGetDeviceInfo(dpy,XkbXI_AllDeviceFeaturesMask,
				device,XkbAllXIClasses,XkbAllXIIds);
    if (!devi) {
	fprintf(stderr,"Couldn't get information about specified device\n");
	return 1;
    }

    xkb = XkbGetMap(dpy,0,(devi->has_own_state?device:XkbUseCoreKbd));
    if (!xkb) {
	fprintf(stderr,"XkbGetMap failed\n");
	goto BAIL;
    }
    if (XkbGetNames(dpy,XkbVirtualModNamesMask,xkb)!=Success) {
	fprintf(stderr,"GetNames failed\n");
	goto BAIL;
    }
    if (verbose)
	ShowDevice(dpy,devi,xkb);
    done= False;
    if (mergeFile || replaceFile) {
	int	first,nBtns;
	if (GetActionsFromFile(xkb,devi,&first,&nBtns)) {
	    if (verbose>1) {
		fprintf(stderr,"After merge...\n");
		ShowDevice(dpy,devi,xkb);
	    }
	    XkbSetDeviceButtonActions(dpy,devi,first,nBtns);
	}
	else {
	    fprintf(stderr,"Error getting button actions from file\n");
	}
    }

    if (verbose>2) {
	while (!done) {
	    XNextEvent(dpy,&ev.core);
	    if ((ev.type==event)&&(ev.any.xkb_type==XkbExtensionDeviceNotify)) {
		xkb_prologue( &ev, "XkbExtensionDeviceNotify" );
		do_XkbExtensionDeviceNotify(&ev);
	    }
	}
    }
    XCloseDisplay(dpy);
    return 0;
BAIL:
    XCloseDisplay(dpy);
    return 1;
}
