package provide textmenu 22.11.26
#
# <20221126.1642.41>
#
############################ It all starts here ##########################

# The point of this code is to move the overhead of loading the 'textmenu'
# to when it is actually used rather than when it is called to define
# the window name/command.
# When called, we define a command with the name 'w' with all the calling
# parameters baked in.
# The first call to this function then sets up the real 'textmenu' and passes
# the callers info to it. That call will redefine the 'w' command so that the
# one here just goes away. We only do this for menu calls and not embedded. 

# In order to define the text menu as either a toplevel menu or an embedded one
# we start here and, by examination the '-toplevel' option determine 
# if we should call 'TextMenu' (gives a normal toplevel menu) of 'textMenu' which
# gives an embedded menu (i.e. it can be grid'ed or pack'ed into another lay out).

proc textmenu {w args} {
  set par [regsub -start 1 {\.?[^.]+$} $w {}]
  # First this must be a window
  set argAry(-toplevel) 1
  # set args [list {*}$args -insertwidth 10]
  array set argAry $args
  
  if {[winfo exists $par]} {
    ## frputs NOTTOP args "~[list {*}$args] "
    if {$argAry(-toplevel)} {
      # This is to be a toplevel window... i.e. a menu
      # subst will do $ and command substitution even inside of braces
      set body [subst {
        package require TextMenu
        TextMenu $w [array get argAry]
        return \[$w \{*\}\$args\]
      }]
      proc $w {args} $body

      return $w
    }
    # an embedded menu is desired
    package require TextMenu
    return [textMenu $w {*}$args -toplevel {}]
  }
  return -code error "\"$par\" is not a window."
}
