/*
 * 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: util.c,v 1.1 1994/09/05 16:03:30 mbeattie Exp $";
#endif

/* $Log: util.c,v $
 * Revision 1.1  1994/09/05  16:03:30  mbeattie
 * Initial revision
 *
 */

#include "tkperl.h"
#include "tkInt.h"

/*
 * StackToArgv takes _items_ objects from the perl stack 
 * (as strings) *starting* at stack offset _sp_, then puts
 * them into a New'd argv-style array at offset _offset_
 * and returns a pointer to that array. It is the responsibility
 * of the caller to do a Safefree() on the pointer.
 */
char **StackToArgv(sp, items, offset)
int sp;
int items;
int offset;
{
    SV **st = stack_base + sp;
    char **argv;
    int i;
    SV *sv;
    
    Newz(666, argv, items + offset + 1, char *);
    for (i = 0; i < items; i++)
    {
	sv = st[i];
	if (SvROK(sv))
	{
	    /* assume it is a widget ref and find the pathname */
	    if (!(sv = WrefToPath(sv, "Master", 6)))
		croak("bad widget ref");
	}
	argv[offset + i] = SvPV(sv_2mortal(newSVsv(sv)), na);
    }
    return argv;
}
    
SV *WrefToPath(sv, wanted, wantedlen)
SV *sv;
char *wanted;
U32 wantedlen;
{
    int gotastring = 0;
    SV **svp;
    
    while (!gotastring)
    {
	if (SvPOK(sv))
	    return sv;
	else if (SvROK(sv))
	    sv = (SV *) SvRV(sv);
	else if (SvTYPE(sv) == SVt_PVHV)
	{
	    if ((wanted
		 && (svp = hv_fetch((HV *) sv, wanted, wantedlen, FALSE)))
		|| (svp = hv_fetch((HV *) sv, "Default", 7, FALSE)))
		sv = *svp;
	    else
		return Nullsv;
	}
	else
	    return Nullsv;
    }
    /* NOTREACHED */
}


     
int WrefToWidget(sv, tkwinp, wPtrp, wanted, wantedlen)
SV *sv;
Tk_Window *tkwinp;
ClientData *wPtrp;
char *wanted;
U32 wantedlen;
{
    Tcl_HashEntry *entryp;
    Tk_Window tkwin;

    if (!(sv = WrefToPath(sv, wanted, wantedlen)))
	return 0;
    if (!(tkwin = Tk_NameToWindow(tclinterp, SvPV(sv, na), mainwin)))
	return 0;
    if (tkwinp)
	*tkwinp = tkwin;
    if (!(entryp = Tcl_FindHashEntry(&widgetRecordTable, (char *) tkwin)))
	return 0;
    *wPtrp = Tcl_GetHashValue(entryp);
    return 1;
}

Tk_Window WrefToWindow(sv, wanted, wantedlen)
SV *sv;
char *wanted;
U32 wantedlen;
{
    if (!(sv = WrefToPath(sv, wanted, wantedlen)))
	return 0;
    return Tk_NameToWindow(tclinterp, SvPV(sv, na), mainwin);
}

void TkpDeleteWidgetHash(tkwin)
Tk_Window tkwin;
{
    Tcl_HashEntry *entryp;
    
    entryp = Tcl_FindHashEntry(&widgetRecordTable, (char *) tkwin);
    assert(entryp != 0);
    Tcl_DeleteHashEntry(entryp);
}

void TkpCreateWidgetHash(tkwin, clientData)
Tk_Window tkwin;
ClientData clientData;
{
    Tcl_HashEntry *entryp;
    int newptr;
    
    entryp = Tcl_CreateHashEntry(&widgetRecordTable, (char *) tkwin, &newptr);
    assert(newptr);
    Tcl_SetHashValue(entryp, clientData);
}

char *TkpGenPathname(sv)
SV *sv;
{
    static int autocount = 0;
    static char namebuf[32];
    
    /*
     * This allow sv to be either a string (taken to be a new pathname)
     * or a blessed widget ref (in which case case we generate a new
     * pathname for a child of that widget
     */
    if (SvROK(sv))
    {
	if (!(sv = WrefToPath(sv, "Master", 6)))
	    croak("bad widget ref");
	sprintf(namebuf, ".auto%d", ++autocount);
	sv = sv_mortalcopy(sv);
	sv_catpv(sv, namebuf);
    }
    return SvPV(sv, na);
}

/*
SV *NewBlessedRef(sv, stash)
SV *sv;
HV *stash;
{
    SV *rv;
    
    SvOBJECT_on(sv);
    SvUPGRADE(sv, SVt_PVMG);
    SvSTASH(sv) = (HV*)SvREFCNT_inc(stash);
    rv = sv_newmortal();
    SvUPGRADE(rv, SVt_RV);
    SvRV(rv) = SvREFCNT_inc(sv);
    SvROK_on(rv);
    return rv;
}
*/

/*
 * NewWidgetRef takes a pathname and a stash, creates a new SV with
 * string value _pathname_ and returns a newly generated reference
 * to it blessed into class _stash_. The SV and the RV returned both
 * have a REFCNT of 1 so that when the RV is freed, the SV containing
 * the pathname is too.
 */
SV *NewWidgetRef(pathname, stash)
char *pathname;
HV *stash;
{
    SV *sv, *rv;
    
    sv = newSVpv(pathname, 0);	/* REFCNT of sv is 1 */
    SvOBJECT_on(sv);
    SvUPGRADE(sv, SVt_PVMG);
    SvSTASH(sv) = (HV*)SvREFCNT_inc(stash);
    rv = NEWSV(666,0);
    SvANY(rv) = 0;
    SvREFCNT(rv) = 1;
    SvUPGRADE(rv, SVt_RV);
    SvRV(rv) = sv;		/* Leave REFCNT of sv at 1 */
    SvROK_on(rv);
    return rv;
}

SV *PathnameToWref(pathname)
char *pathname;
{
    TkWindow *winPtr;
    static char class[256] = "::_";
    
    winPtr = (TkWindow *) Tk_NameToWindow(tclinterp, pathname, mainwin);
    strcpy(class + 3, winPtr->classUid);
    return NewWidgetRef(pathname, GvHV(gv_fetchpv(class, FALSE, SVt_PVHV)));
}

void TkpCallback(callback, extras)
struct tkpcallback *callback;
int extras;
{
    int sp;
    register CV *cv;
    SV *sv;
    GV *gv = Nullgv;
    GV *gvjunk;
    HV *hvjunk;
    
    DEBUG_o( fprintf(stderr, "TkpCallback method \"%s\" slave %s, cache %s\n",
		     callback->method ? callback->method : "(null)",
		     SvPEEK(callback->slave),
		     SvPEEK((SV *) callback->cvcache)) );

    if (!callback->method && !callback->cvcache)
	return;

    /* If the CV has not been cached yet, work it out now */
    cv = callback->cvcache;
    if (!cv)
    {
	sv = callback->slave;
	if (sv && SvOK(sv) && SvROK(sv))
	{
	    /* It's a reference: get the method from its package */
	    sv = (SV *) SvRV(sv);
	    if (SvOBJECT(sv))
		gv = gv_fetchmethod(SvSTASH(sv), callback->method);
	}

	/* If we haven't found a gv yet, fall back to assuming method
	 * is a subroutine name. If it's not fully qualified as
	 * package::subname then use the current package. */

	if (gv == Nullgv)
	    gv = gv_fetchpv(callback->method, FALSE, SVt_PVCV);

	/* If we still haven't found anything, give up */
	if (gv == Nullgv)
	    croak("method not found for callback");

	if (!(cv = sv_2cv(gv, &hvjunk, &gvjunk, FALSE)))
	    croak("sv_2cv failed on method");
	callback->cvcache = cv; /* save for future use */
    }

    /* This stuff really needs rewriting properly for the
     * new-style calling conventions. */
    
    sp = stack_sp - stack_base;
    av_store(stack, sp + 1, callback->slave ?
	     callback->slave : sv_mortalcopy(&sv_undef));
    RECOVERSTACK;
    PUSHMARK(stack_sp);
    stack_sp += extras + 1;

    (void) perl_call_sv((SV *) cv, G_DISCARD);
    return;
}

int TkpTraceOnSet(ix, sv, proc)
IV ix;
SV *sv;
I32 (*proc) _((IV, SV *));
{
    struct ufuncs *ufp;
    MAGIC *mg;

    if (!SvOK(sv))
	croak("TkpTraceOnSet attempted on bad sv");
    
    if (SvTHINKFIRST(sv)) {
	if (SvREADONLY(sv) && curcop != &compiling)
	    croak(no_modify);
    }
    if (!SvUPGRADE(sv, SVt_PVMG))
	croak("TkpTraceOnSet SvUPGRADE failed");

    /*
     * We can't use sv_magic() because it won't add in another magical struct
     * of type 'U' if there is already one there. We need multiple 'U'
     * magics hanging from one sv or else things like radiobuttons will
     * not work. That's because each radiobutton widget group needs to track
     * the same sv and update itself as necessary.
     */

    Newz(702, mg, 1, MAGIC);
    mg->mg_moremagic = SvMAGIC(sv);

    SvMAGIC(sv) = mg;
    mg->mg_obj = 0;
    mg->mg_type = 'U';
    mg->mg_len = 0;
    mg->mg_virtual = &vtbl_uvar;

    mg_magical(sv);
    New(666, ufp, 1, struct ufuncs); 
    ufp->uf_val = 0;
    ufp->uf_set = proc;
    ufp->uf_index = ix;
    SvMAGIC(sv)->mg_ptr = (char *) ufp;

    return 1;
}

int TkpUntraceOnSet(ix, sv, proc)
IV ix;
SV *sv;
I32 (*proc) _((IV, SV *));
{
    MAGIC *mg;
    MAGIC **mgp = &SvMAGIC(sv);

    for (mg = *mgp; mg; mg = *mgp) 
    {
	/*
	 * Trawl through the linked list of magic looking
	 * for the 'U' one which is our proc and ix.
	 */
	if (mg->mg_type == 'U'
	    && mg->mg_ptr
	    && ((struct ufuncs *) (mg->mg_ptr))->uf_set == proc
	    && ((struct ufuncs *) (mg->mg_ptr))->uf_index == ix)
	{
	    *mgp = mg->mg_moremagic;
	    Safefree(mg->mg_ptr);
	    Safefree(mg);
	}
	else
	    mgp = &mg->mg_moremagic;
    }
    DEBUG_o ( putc('\n', stderr) );
    return 0;
}


