/*
 * Copyright (c) 1994 Malcolm Beattie, all rights reserved.
 */
#include <stdlib.h>
#include "tkConfig.h"
#include "tkInt.h"
#include "tkperl.h"

Tcl_Interp *tclinterp;
Tk_Window mainwin;
Tcl_HashTable widgetRecordTable;

enum { US_tcleval, US_tclevalfile, US_tclcmd, US_path };

void init_widget P((WidgetClass *));
void init_uvars P((void));
static void StructureProc P((ClientData, XEvent *));
static void DelayedMap P((ClientData));
int init P((int, int, int));
int TkpCallTcl P((int, int, int));
int tkmainloop P((int, int, int));
int TkpBindCmd P((int, int, int));
int TkpTkpackCmd P((int, int, int));
int TkpWmCmd P((int, int, int));
int TkpFocusCmd P((int, int, int));
int TkpGrabCmd P((int, int, int));
int TkpAfterCmd P((int, int, int));
int TkpDestroyCmd P((int, int, int));
int TkpRaiseLowerCmd P((int, int, int));
int TkpTkwaitCmd P((int, int, int));
int TkpUpdateCmd P((int, int, int));
int TkpAddasyncioCmd P((int, int, int));
int TkpDelasyncioCmd P((int, int, int));
int TkpEvWref P((int, int, int));
int TkpWidgetCreate P((int, int, int));
int TkpPathCmd P((int, int, int));
int TkpOptionCmd P((int, int, int));
Tk_Window TkpCreateMainWindow P((char *, char *, char *, int));

typedef struct
{
    char *name;
    I32 ix;
    int (*proc) P((int, int, int));
    char *filename;
} UsubData;

static char fileTkpGrab[] = "TkpGrab.c";
static char fileTkpFocus[] = "TkpFocus.c";
static char fileTkpCmds[] = "tkpCmds.c";
static char fileTkpIo[] = "tkpIo.c";
static char fileTkpOption[] = "tkpOption.c";
static char filetkperl[] = "tkperl.c";

static UsubData usubTable[] =
{
    { "grabcurrent",	US_GRABCURRENT, TkpGrabCmd,	fileTkpGrab },
    { "grabrelease",	US_GRABRELEASE, TkpGrabCmd,	fileTkpGrab },
    { "grab",		US_GRAB,	TkpGrabCmd,	fileTkpGrab },
    { "grabstatus",	US_GRABSTATUS,  TkpGrabCmd,	fileTkpGrab },
    { "tcleval",	US_tcleval,	TkpCallTcl,	filetkperl },
    { "tclevalfile",	US_tclevalfile,	TkpCallTcl,	filetkperl },
    { "tclcmd",		US_tclcmd,	TkpCallTcl,	filetkperl },
    { "init",		0,		init,		filetkperl },
    { "tkmainloop",	0,		tkmainloop,	filetkperl },
    { "tkbind",		0,		TkpBindCmd,	filetkperl },
    { "tkpack",		0,		TkpTkpackCmd,	filetkperl },
    { "wm",		0,		TkpWmCmd,	filetkperl },
    { "focus",		US_FOCUS,	TkpFocusCmd,	fileTkpFocus },
    { "focusdefault",	US_FOCUSDEFAULT,TkpFocusCmd,	fileTkpFocus },
    { "after",		0,		TkpAfterCmd,	fileTkpCmds },
    { "destroy",	0,		TkpDestroyCmd,	fileTkpCmds },
    { "lower",		'l',		TkpRaiseLowerCmd, fileTkpCmds },
    { "raise",		'r',		TkpRaiseLowerCmd, fileTkpCmds },
    { "waitvar",	US_WAITVAR,	TkpTkwaitCmd,	fileTkpCmds },
    { "waitvis",	US_WAITVIS,	TkpTkwaitCmd,	fileTkpCmds },
    { "waitwin",	US_WAITWIN,	TkpTkwaitCmd,	fileTkpCmds },
    { "update",		'u',		TkpUpdateCmd,	fileTkpCmds },
    { "idletasks",	'i',		TkpUpdateCmd,	fileTkpCmds },
    { "addasyncio",	0,		TkpAddasyncioCmd, fileTkpIo },
    { "delasyncio",	0,		TkpDelasyncioCmd, fileTkpIo },
    { "EvWref",		0,		TkpEvWref,	filetkperl },
    { "path",		0,		TkpPathCmd,	filetkperl },
    { "optadd",		US_OPTADD,	TkpOptionCmd,	fileTkpOption },
    { "optclear",	US_OPTCLEAR,	TkpOptionCmd,	fileTkpOption },
    { "optget",		US_OPTGET,	TkpOptionCmd,	fileTkpOption },
    { "optaddstring",	US_OPTADDSTRING,TkpOptionCmd,	fileTkpOption },
    { NULL,		0,		NULL,		NULL }
};

/* The following list needs keeping up to date with the
 * enum list of IX_ constants in tkperl.h */

char *methodname[] =
{
    NULL,			/* IX_EOL, the method list end marker */
    "activate",
    "add",
    "configure",
    "curselection",
    "deactivate",
    "tkdelete",			/* delete is already a perl keyword */
    "deselect",
    "disable",
    "enable",
    "entryconfigure",
    "flash",
    "get",
    "icursor",
    "tkindex",			/* index is already a perl keyword */
    "insert",
    "invoke",
    "nearest",
    "post",
    "scanmark",
    "scandragto",
    "tkselect",			/* select is already a perl keyword */
    "selectclear",
    "selectadjust",
    "selectfrom",
    "selectto",
    "set",
    "size",
    "toggle",
    "unpost",
    "view",
    "xview",
    "yposition",
    "yview",
};

void init_widget(classPtr)
WidgetClass *classPtr;
{
    char tmpbuf[128]; /* must fit largest "Widget::method" */
    int *ixp;
    
    (void) sprintf(tmpbuf, "%s::new", classPtr->package);
    newXSUB(tmpbuf, classPtr->newix, classPtr->newwidgetproc,
	    classPtr->filename);
    /*
     * The following mimics fetch_stash() but takes a char * argument
     * instead of an SV * for the name (and the hash already exists).
     */
    (void) sprintf(tmpbuf, "%s::", classPtr->package);
    classPtr->stash = GvHV(gv_fetchpv(tmpbuf, FALSE, SVt_PVHV));
    
    for (ixp = classPtr->methods; *ixp != IX_EOL; ixp++)
    {
	(void) sprintf(tmpbuf, "%s::%s", classPtr->package, methodname[*ixp]);
	newXSUB(tmpbuf, *ixp, classPtr->widgetcmdproc, classPtr->filename);
    }
}

int boot_Tk(ix, sp, items)
int ix;
int sp;
int items;
{    
    UsubData *uPtr;
    char *nullcharptr = 0;
    char **fakeenviron = &nullcharptr;
    char **saveenviron;
    char subname[128]; /* must fit longest Tk::subroutinename */
    
    saveenviron = environ;
    environ = fakeenviron;
    tclinterp = Tcl_CreateInterp(); /* perhaps better at boot_Tk time? */
    environ = saveenviron;

    for (uPtr = usubTable; uPtr->name; uPtr++)
    {
	(void) sprintf(subname, "Tk::%s", uPtr->name);
	newXSUB(subname, uPtr->ix, uPtr->proc, uPtr->filename);
    }
    
    /* Following keyed on Tk_Window, values are pointers to widget records */
    Tcl_InitHashTable(&widgetRecordTable, TCL_ONE_WORD_KEYS);

    /* Initialise magic user variables */
    init_uvars();
    stack_base[sp] = sv_2mortal(newSVnv((double) 1));
    return sp;
}

int TkpCallTcl(ix, sp, items)
int ix;
int sp;
int items;     
{
    SV **st = stack_base + sp;

    switch (ix)
    {
      case US_tcleval:
	if (items != 1)
	    croak("Usage: &tcleval($str)");
	if (Tcl_Eval(tclinterp, SvPV(st[1], na)) != TCL_OK)
	    croak(tclinterp->result);
	st[0] = sv_2mortal(newSVpv(tclinterp->result, 0));
	return sp;
      case US_tclevalfile:
	if (items != 1)
	    croak("Usage: &tclevalfile($filename)");
	if (Tcl_EvalFile(tclinterp, SvPV(st[1], na)) != TCL_OK)
	    croak(tclinterp->result);
	st[0] = sv_2mortal(newSVpv(tclinterp->result, 0));
	return sp;
      case US_tclcmd:
	if (items < 1)
	    croak("Usage: tclcmd($tclcommand, $arg1, $arg2, ...)");
	{
	    Tcl_CmdInfo cmdinfo;
	    char **argv;
	    char *command = SvPV(st[1], na);
	    int rc;
	    
	    if (!Tcl_GetCommandInfo(tclinterp, command, &cmdinfo))
	        croak("no such Tcl command");
	    argv = StackToArgv(sp + 1, items - 1, 1);
	    argv[0] = command;
	    rc = (*cmdinfo.proc)(cmdinfo.clientData, tclinterp, items, argv);
	    Safefree(argv);
	    if (rc != TCL_OK)
	        croak(tclinterp->result);
	    st[0] = sv_2mortal(newSVpv(tclinterp->result, 0));
	    return sp;
	}
      default:	
	croak("no usersub with that ix");
    }
    /* NOTREACHED */
}

int init(ix, sp, items)
int ix;
int sp;
int items;     
{
    SV **st = stack_base + sp;
    Tk_3DBorder border;
    char *name = 0;
    char *display = 0;
    int synchronize = 0;
    SV **svp;
    SV *svhome;
    char **saveenviron, *fakeenviron[2];
    HV *stashToplevel;
    
#ifdef TCL_MEM_DEBUG
    Tcl_InitMemory(tclinterp);
#endif

    if (items != 3)
        croak("Usage: init($name, $display, $sync)");
    name = SvPV(st[1], na);
    display = SvPV(st[2], na);
    synchronize = (SvTRUE(st[3]));

    if (!name || *name == '\0')
	croak("must specify name for init");
    if (!display || *display == '\0')
	croak("must specify display for init");
    
    /*
     * Initialize the Tk application and arrange to map the main window
     * after the startup script has been executed, if any.  This way
     * the script can withdraw the window so it isn't ever mapped at all.
     */
    
    svp = hv_fetch(GvHVn(envgv), "HOME", 4, FALSE);
    if (!svp)
	fakeenviron[0] = 0;
    else
    {
	svhome = newSVpv("HOME=", 5);
	sv_catsv(svhome, *svp);
	fakeenviron[0] = SvPV(svhome, na);
	fakeenviron[1] = 0;
    }

    saveenviron = environ;
    environ = fakeenviron;
    mainwin = TkpCreateMainWindow(display, name, "Tk", sp);
    environ = saveenviron;
    if (!mainwin)
        croak(tclinterp->result);
    (void) gv_fetchpv("::_Tk", TRUE, SVt_PVHV);
    Tk_SetClass(mainwin, "Tk");
    Tk_CreateEventHandler(mainwin, StructureNotifyMask, StructureProc,
			  (ClientData) NULL);
    if (synchronize)
	XSynchronize(Tk_Display(mainwin), True);
    Tk_GeometryRequest(mainwin, 200, 200);
    border = Tk_Get3DBorder(tclinterp, mainwin, None, "#ffe4c4");
    if (border == NULL) {
/* What is the following SetResult for? MICB */
	Tcl_SetResult(tclinterp, (char *) NULL, TCL_STATIC);
	Tk_SetWindowBackground(mainwin,
			       WhitePixelOfScreen(Tk_Screen(mainwin)));
    } else {
	Tk_SetBackgroundFromBorder(mainwin, border);
    }
    XSetForeground(Tk_Display(mainwin),
		   DefaultGCOfScreen(Tk_Screen(mainwin)),
		   BlackPixelOfScreen(Tk_Screen(mainwin)));

    stashToplevel = GvHV(gv_fetchpv("::_Toplevel", FALSE, SVt_PVHV));
    st[0] = NewBlessedRef(newSVpv(".", 1), stashToplevel);
    return sp;
}

int tkmainloop(ix, sp, items) 
int ix;
int sp;
int items;
{
    /*
     * Loop infinitely, waiting for commands to execute.  When there
     * are no windows left, tkmainloop returns and we clean up and return.
     */

    SV **st = stack_base + sp;

    if (items != 0)
	croak("Usage: &tkmainloop()");
    Tk_DoWhenIdle(DelayedMap, (ClientData) NULL);
    TkpUpdateCmd(0, sp, 0);

/* The following loop is where we spend all our time. */
    while (tk_NumMainWindows > 0) 
        Tk_DoOneEvent(0);

    Tcl_DeleteInterp(tclinterp);
    st[0] = sv_2mortal(newSVnv((double) 1));
    return sp;
}

static void StructureProc(clientData, eventPtr)
    ClientData clientData;	/* Information about window. */
    XEvent *eventPtr;		/* Information about event. */
{
    if (eventPtr->type == DestroyNotify) mainwin = NULL;
}

static void DelayedMap(clientData)
     ClientData clientData;
{
    while (Tk_DoOneEvent(TK_IDLE_EVENTS) != 0) 
    {
        /* Empty loop body. */
    }
    if (mainwin == NULL) 
        return;
    
    Tk_MapWindow(mainwin);
}

int TkpBindCmd(ix, sp, items)
int ix;
int sp;
int items;
{
    SV **st = stack_base + sp;
    TkWindow *winPtr;
    ClientData object;
    char *pathname, *pattern;
    SV *sv;

    if (items < 1 || items > 4)
	croak("wrong # args for tkbind");

    sv = st[1];
    if (!SvOK(sv))
	croak("bad target for tkbind");
    if (SvROK(sv))
    {
	winPtr = (TkWindow *) WrefToWindow(sv, "Bind", 4);
	if (!winPtr)
	    croak("bad pathname for tkbind");
	object = (ClientData) winPtr->pathName;
    }
    else
    {
	pathname = SvPV(sv, na);
	if (*pathname == '.')
	{
	    winPtr = (TkWindow *) Tk_NameToWindow(tclinterp,
						  pathname, mainwin);
	    if (!winPtr)
		croak("bad pathname for tkbind");
	    object = (ClientData) winPtr->pathName;
	}
	else
	{
	    winPtr = (TkWindow *) mainwin;
	    object = (ClientData) Tk_GetUid(pathname);
	}
    }
    
    pattern = SvPV(st[2], na);
    if (items > 2)
    {
	unsigned long mask;

	if (st[3] == &sv_undef)
	{
	    if (Tk_DeleteBinding(tclinterp, winPtr->mainPtr->bindingTable,
				 object, pattern) != TCL_OK)
		croak("no such binding to delete");
	}
	mask = TkpCreateBinding(winPtr->mainPtr->bindingTable, object, pattern,
				SvPV(st[3], na), (items == 4) ? st[4] : Nullsv);

	if (!mask)
	    croak("failed to create binding");
    }
    else if (items == 2)
    {
	croak("returning binding info not yet implemented");
    }
    else
    {
	croak("returning all binding info not yet implemented");
    }
    return sp;
}

/* At the moment, tkpack is just a wrapper around standard Tk pack */
int TkpTkpackCmd(ix, sp, items)
int ix;
int sp;
int items;
{
    SV **st = stack_base + sp;
    char **argv;
    int rc;
    
    argv = StackToArgv(sp, items, 1);
    argv[0] = "pack";
    rc = Tk_PackCmd((ClientData) mainwin, tclinterp, items + 1, argv);
    Safefree(argv);
    if (rc != TCL_OK)
	croak(tclinterp->result);
    st[0] = sv_2mortal(newSVpv(tclinterp->result, 0));
    return sp;
}

/* At the moment, wm is just a wrapper around standard Tk wm */
int TkpWmCmd(ix, sp, items)
int ix;
int sp;
int items;
{
    SV **st = stack_base + sp;
    char **argv;
    int rc;
    
    argv = StackToArgv(sp, items, 1);
    argv[0] = "wm";
    rc = Tk_WmCmd((ClientData) mainwin, tclinterp, items + 1, argv);
    Safefree(argv);
    if (rc != TCL_OK)
	croak(tclinterp->result);
    st[0] = sv_2mortal(newSVpv(tclinterp->result, 0));
    return sp;
}

int TkpEvWref(ix, sp, items)
int ix;
int sp;
int items;
{
    SV **st = stack_base + sp;
    extern XEvent *cacheXEvent;
    TkWindow *winPtr;
    SV *rv;
    static char class[256] = "::_";
    
    if (items != 0)
	croak("wrong # args for EvWref");
 
    if (!cacheXEvent || XFindContext(cacheXEvent->xany.display,
				     cacheXEvent->xany.window,
				     tkWindowContext, (caddr_t *) &winPtr))
	st[0] = sv_mortalcopy(&sv_undef);
    else
    {
	strcpy(class + 3, winPtr->classUid);
	st[0] = NewBlessedRef(newSVpv(winPtr->pathName, 0),
			      GvHV(gv_fetchpv(class, FALSE, SVt_PVHV)));
    }
    return sp;
}

int TkpPathCmd(ix, sp, items)
int ix;
int sp;
int items;
{
    SV **st = stack_base + sp;
    SV *sv;
    char *wanted = (char *) 0;
    STRLEN wantedlen = 0;

    if (items != 1 && items != 2)
	croak("Usage: path($w [, $wanted])");
    
    if (items == 2)
	wanted = SvPV(st[2], wantedlen);

    sv = WrefToPath(st[1], wanted, wantedlen);
    
    st[0] = sv_mortalcopy(sv ? sv : &sv_undef);
    return sp;
}

