#
# Code for history hypertool
#


# Destroy button & menu if entry doesn't exist.
proc th_history_sanity_check {m e} {
  set b $m ; append b "button"
  if {![winfo exists $e]} {
	catch "destroy $b"
	catch "destroy $m"
	return 0
  } else {return 1
}}

# Adds a single menu command. m is the menubutton, e is the entry
proc th_add_history {m e menuoption event} {
  for {set c 1} {$c <= [$m.m index last]} {incr c} {
    if {[$m.m entrycget $c -label] == $menuoption} {return}}
  $m.m add command -label $menuoption -command "th_history_invoke $m $e \{$event\}"
}

# Replace contents of e with menu entry invoked.
proc th_history_invoke {m e event} {
  if {[th_history_sanity_check $m $e]} {
    $e delete 0 end
    $e insert 0 $event
}}

# Adds the contents of entry e to m's menu.
proc th_add_history_entry {m e} {
  if {[th_history_sanity_check $m $e]} {
    set event [$e get]
    th_add_history $m $e $event $event
}}

# Given an entry e, creates a menu of good entry values, and a button to
# add more. If l is specified, it is a label that the menu can replace..
# This is the only procedure you need to invoke here. (You might want to call
# th_add_history next to add some default values, but you don't have to.)
proc th_make_history_menu {e {l ""}} {
  set default_menu_name "(History)"
  if {[winfo exists $l]} {
    if {[catch {set title [$l cget -text]}]} {
      set title $default_menu_name
    }
    set m $l
    set pack_info [pack info $l]
    set pack_list [pack slaves [winfo parent $l]]
    set i [lsearch $pack_list $l] ; incr i
    if {$i == [llength $pack_list]} {set pack_before ""
    } else {set pack_before [lindex $pack_list $i]}

    destroy $l
    menubutton $m -text $title
    eval pack $m $pack_info
    if {$pack_before != ""} {pack $m -before $pack_before}
  } else {
    set m [winfo parent $e].thistory
    menubutton $m -text $default_menu_name
    pack $m -side left -before $e
  }

  menu $m.m
  $m configure -menu "$m.m"
  set b $m ; append b "button"
  if {[winfo exists $b]} {destroy $b}
  button $b -text "+" -command "th_add_history_entry $m $e"
  pack $b -side left -before $m
}
