#
# General routines for thbind not provided by other hypertools
#


# Brings up menus on w, or erases them.
proc th_toggle_menus {w} {
  global TH
  if {[string match "*_mb*" $w]} {bell
  } elseif {[catch {set TH(Menubar,$w)}] || ![winfo exists $TH(Menubar,$w)]} {
    th_create_menu $w
  } elseif {[winfo ismapped $TH(Menubar,$w)]} {
    pack forget $TH(Menubar,$w)
  } elseif {[winfo manager $w] != "pack"} {
    pack $TH(Menubar,$w) -before [lindex [pack slaves \
	[winfo parent $TH(Menubar,$w)]] 0] -side top -anchor w
  } else {
    pack $TH(Menubar,$w) -before $w -side top -anchor w}
  return -code break
}

# Proc to first create a menu for w
proc th_create_menu {w} {
  global TH auto_index
  set c [winfo class $w]
  if {([info procs th_[set c]_menus] != "") || \
       ([lsearch [array names auto_index] th_[set c]_menus] >= 0)} {
    th_[set c]_menus $w
  } else {th_Misc_menus $w}

  if {![catch "set TH(Menu,Code,Todo,$w)"]} {
    regsub -all %M $TH(Menu,Code,Todo,$w) $w code
    uplevel #0 $code
    unset TH(Menu,Code,Todo,$w)
}}



# Code is stuff to add to the menu. Do it now, or later, depending on if the
# menus have been added yet.
proc th_add_menucode {w code} {
  global TH
  set mb $w ; append mb "_mb"
  if {[winfo exists $mb]} {
# do code now
    regsub -all %M $code $w new_code
    uplevel #0 $new_code
  } else {
# do code later
    if {[catch "set TH(Menu,Code,Todo,$w)"]} {set Elsbeth_Menu($w) ""}
    append TH(Menu,Code,Todo,$w) $code
}}

# Adding Modules

# User wants to add tool to widget w. If not given, w is the last text window
# opened.
proc th_add_module {tool {w ""}} {
# Hack for letting w be unspecified...only works for Elsbeth
  if {$w == ""} {
    set list [winfo children .]
    for {set l [llength $list]} {$l >= 0} {incr l -1} {
      if {[string match ".sym*" [lindex $list $l]]} {
        set w "[lindex $list $l].t"
  }}}

  global TH
  if {[catch "set TH(Module,Loaded,$tool,$w)"]} {set TH(Module,Loaded,$tool,$w) 0}
  if $TH(Module,Loaded,$tool,$w) {bell ; return}
  set TH(Module,Loaded,$tool,$w) 1
  regsub -all %T $TH(Module,Code,$tool) $w code

  if {[catch {llength $TH(Paint,$w)} l]} {set l 0 ; set TH(Paint,$w) ""}
  uplevel #0 $code
  if {[catch "set TH(Module,Paint,$w)"]} {set TH(Module,Paint,$w) ""}
  eval lappend TH(Module,Paint,$w) [lrange $TH(Paint,$w) $l end]
  th_flash_label $w -text "$tool loaded"
}


# Sources file '~/.th/$name', then './.$name', if they exist (and aren't
# the same file). If name is not given, uses the application name.
proc th_source_local_files {{name ""}} {
  global env errorInfo
  if {$name == ""} {set name [lindex [tk appname] 0]}
  if {[file exists $env(HOME)/.th/$name]} {
    if {[catch "source $env(HOME)/.th/$name" result]} {
      after idle error \{$result\} \{$errorInfo\}
  }}
  if {[file exists ".$name"] && ([pwd] != "$env(HOME)/.th")} {
    if {[catch "source .$name" result]} {
      after idle error \{$result\} \{$errorInfo\}
}}}

