# getValue.tcl --
#
# This file defines the procedure getValue, which creates a dialog
# box containing a message, an entry, and an OK button.  Returns the entry.
#
# Derived from tk_dialog
#

#
# getValue:
#
# This procedure displays a dialog box, waits for the OK button or <Return>,
# then returns the entry contents.  The returnd value is also left in the
# global getValueReturn. If the dialog somehow gets destroyed, $fail is returned.
#
# Arguments:
# w -		Window to use for dialog top-level.
# title -	Title to display in dialog's decorative frame.
# text -	Message to display in dialog.
# width -   Width for entry.
# initial - Initial contents
# fail  -   Return on quit
# bell -    Boolean, true sounds bell
# stay -    Bollean, do not destroy if true

proc getValue {w title text width initial fail bell stay} {
    global _ok
    set _ok 0

    # 1. Create the top-level window and divide it into top
    # and bottom parts.

    if {$w != {.}} {
        catch {destroy $w}
        toplevel $w
        set base $w
    } else {
        set base {}
    }
    wm title $w $title
#    wm transient $w .
    wm protocol $w WM_DELETE_WINDOW "set _ok 0"

    frame $base.bot
    pack $base.bot -side bottom -fill both

    # 2. Fill the top part with message

    label $base.msg -text $text -anchor w
    pack $base.msg -in $w -expand 1 -fill x

    # 3. Create entry and button at the bottom of the dialog.

	button $base.button -text OK -command {set _ok 1}
	pack $base.button -in $base.bot -side right
    entry $base.entry -width $width
    $base.entry insert end $initial
    pack $base.entry -in $base.bot -expand 1 -fill both
    
    # 4. Create a binding for <Return>

	bind $base.entry <Return> "$base.button invoke"
    
    # 5. Create a <Destroy> binding for the window that sets the
    # return value to $fail;  this is needed in case something happens
    # that destroys the window, such as its parent window being destroyed.

    bind $w <Destroy> {set _ok 0}

    # 6. Withdraw the window, and de-iconify it.

    update idletasks
    wm deiconify $w

    focus $base.entry

    if $bell bell

    # 8. Wait for the user to respond.
    
    tkwait variable _ok
    if {$_ok} {
        set result [$base.entry get]
    } else {
        set result $fail
    }
    catch {
	# It's possible that the window has already been destroyed,
	# hence this "catch".  Delete the Destroy handler so that
	# getValueResult doesn't get reset by it.

	bind $w <Destroy> {}
	if {!$stay} {destroy $w}
    }

    return $result
}
