/*
 * Copyright (c) 1994 Malcolm Beattie.
 * You may distribute under the terms of the GNU General Public License,
 * as specified in the README file.
 */

#ifndef lint
static char rcsid[] = "$Id: tkperl.c,v 1.3 1994/09/28 21:28:50 mbeattie Exp $";
#endif

/* $Log: tkperl.c,v $
 * Revision 1.3  1994/09/28  21:28:50  mbeattie
 * Prototype and newXS for Proxy::Tk class.
 *
 * Revision 1.2  1994/09/21  14:53:01  mbeattie
 * Stash fetches use gv_stachpv; init_widget ix loop used I32 not int;
 * trailing comma from tkpmethod.h worked around with new macro; new-style
 * XSUB prototype and newXS added.
 *
 * Revision 1.1  1994/09/05  16:03:30  mbeattie
 * Initial revision
 *
 */

#include <stdlib.h>
#include "tkConfig.h"
#include "tkInt.h"
#define TKPEXT
#include "tkperl.h"

enum { US_tcleval, US_tclevalfile, US_tclcmd, US_path };

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

/* New-style XSUBs prototypes */
void XS_Tk_xbell _((CV *));
void boot_ProxyTk _((CV *));

typedef struct
{
    char *name;
    I32 ix;
    I32 (*proc) _((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 },
*/
    { "setclass",	0,		TkpSetclassCmd,	filetkperl },
    { NULL,		0,		NULL,		NULL }
};

#define TKPMETHOD(ix, value) value,
#define TKPLASTMETHOD(ix, value) value
char *methodname[] =
{
#include "tkpmethod.h"
};
#undef TKPMETHOD
#undef TKPLASTMETHOD

void init_widget(classPtr)
WidgetClass *classPtr;
{
    char tmpbuf[128]; /* must fit largest "Widget::method" */
    I32 *ixp;
    CV *cv;
    
    (void) sprintf(tmpbuf, "%s::new", classPtr->package);
    cv = newXS(tmpbuf, (void (*)()) classPtr->newwidgetproc,
	       classPtr->filename);
    CvOLDSTYLE(cv) = TRUE;
    CvXSUBANY(cv).any_i32 = classPtr->newix;

    classPtr->stash = gv_stashpv(classPtr->package, FALSE);
    
    for (ixp = classPtr->methods; *ixp != IX_EOL; ixp++)
    {
	(void) sprintf(tmpbuf, "%s::%s", classPtr->package, methodname[*ixp]);
	cv = newXS(tmpbuf, (void (*)())classPtr->widgetcmdproc,
		   classPtr->filename);
	CvOLDSTYLE(cv) = TRUE;
	CvXSUBANY(cv).any_i32 = *ixp;
    }
}

I32 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 */
    CV *cv;
    
    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);
	cv = newXS(subname, (void (*)()) uPtr->proc, uPtr->filename);
	CvOLDSTYLE(cv) = TRUE;
	CvXSUBANY(cv).any_i32 = uPtr->ix;
    }
    
    /* Extra XSUBs that follow the new conventions */
    newXS("Tk::xbell", XS_Tk_xbell, "tkpXsubs.c");
    newXS("Proxy::Tk::bootstrap", boot_ProxyTk, "tkpProxy.c");

    /* Following keyed on Tk_Window, values are pointers to widget records */
    Tcl_InitHashTable(&widgetRecordTable, TCL_ONE_WORD_KEYS);

    /* Initialise magic user variables */
    init_uvars();

    /* Initialise standard widgets */
    bootC_Frame();
    bootC_Button();
    bootC_Entry();
    bootC_Listbox();
    bootC_Menu();
    bootC_Menubutton();
    bootC_Message();
    bootC_Scale();
    bootC_Scrollbar();
    bootC_Canvas();

    return sp;
}

I32 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 + 2, 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 */
}

I32 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_stashpv("Tk", TRUE);
    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 = gv_stashpv("Toplevel", FALSE);
    st[0] = sv_2mortal(NewWidgetRef(".", stashToplevel));
    return sp;
}

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

I32 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,
				st[3], (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 */
I32 TkpTkpackCmd(ix, sp, items)
int ix;
int sp;
int items;
{
    SV **st = stack_base + sp;
    char **argv;
    int rc;
    
    argv = StackToArgv(sp + 1, 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 */
I32 TkpWmCmd(ix, sp, items)
int ix;
int sp;
int items;
{
    SV **st = stack_base + sp;
    char **argv;
    int rc;
    
    argv = StackToArgv(sp + 1, 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;
}

I32 TkpEvWref(ix, sp, items)
int ix;
int sp;
int items;
{
    SV **st = stack_base + sp;
    extern XEvent *cacheXEvent;
    TkWindow *winPtr;
    
    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
	st[0] = sv_2mortal(NewWidgetRef(winPtr->pathName,
					gv_stashpv(winPtr->classUid, FALSE)));

    return sp;
}

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

I32 TkpSetclassCmd(ix, sp, items)
int ix;
int sp;
int items;
{
    SV **st = stack_base + sp;
    Tk_Window tkwin;
    
    if (items != 1 && items != 2)
	croak("Usage: setclass($w [, $classname])");

    if (!(tkwin = WrefToWindow(st[1], (char *) 0, 0)))
	croak("bad window argument to setclass");
    
    if (items == 1)
	st[0] = sv_2mortal(newSVpv(Tk_Class(tkwin), 0));
    else
    {
	Tk_SetClass(tkwin, Tk_GetUid(SvPV(st[2], na)));
	st[0] = st[2];
    }
    return sp;
}

