# micro.tcl --
#	Client side microscripting.
# Copyright (c) 1996 by Sun Microsystems
#
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#

# This is set up to do substs and variable references in a safe
# interpreter.  This is a little bogus, still, because the tclvar
# form hack ties form elements to variables in the main interpreter.
# Take the use of WebTkCookie with a grain of salt.

# <tclsubst>stuff with [embedded tcl commands] and $variables</tclsubst>
# but no other markup.
proc HMtag_tclsubst {win param textVar} {
    upvar $textVar text
    set text [Micro_Subst $win $text]
}
# <webtk data="stuff to subst">
proc HMtag_webtk {win param textVar} {
    upvar #0 HM$win var
    upvar $textVar text
    if [HMextract_param $param tcl] {
	# Tag the generated text so it gets nuked
	# for output and refresh.
	set tags [HMcurrent_tags $win]
	set mid [Mark_Current $win]
	lappend tags space $mid
	Text_Insert $win $var(S_insert) [Micro_Subst $win $tcl] $tags
	set htag webtk
	$win tag bind $mid <Motion> [list Status $win <[string trim "$htag $param"]>]
	$win tag bind $mid <Button-1> [list MarkEditTag $win $mid $htag $param]
    }
}
proc MicroCreateInterp {win} {
    set interp safe$win
    interp create $interp -safe
    foreach proc [info commands *_SafeInit] {
	$proc $interp $win
    }
}
proc Micro_Reset {win} {
    set interp safe$win
    if {[lsearch [interp slaves] $interp] < 0} {
	return
    }
    foreach proc [info commands *_SafeDelete] {
	$proc $interp $win
    }
    interp delete safe$win
}
# Do the subst in a safe context
proc Micro_Subst {win text} {
    set interp safe$win
    if {[lsearch [interp slaves] $interp] < 0} {
	MicroCreateInterp $win
    }
    # Unfortunately "subst" is not in the Safe Tcl interpreter in 4.1 unpatched
    if {[string length [$interp eval info command subst]] == 0} {
	return [uplevel #0 [list subst $text]]
    } else {
	$interp eval [list subst $text]
    }
}
# Get a variable from the safe context
proc Micro_Value {win varName} {
    set interp safe$win
    if {[lsearch [interp slaves] $interp] < 0} {
	MicroCreateInterp $win
    }
    $interp eval [list set $varName]
}
