Tk Source Code

Artifact [3bc02a7b]
Login

Artifact 3bc02a7b6f298636359d25675f7d107117222f69:

Attachment "tmb.tcl" to ticket [1283635f] added by djarseneau 2005-09-07 14:27:37.

# timedmsgbox.tcl --
#
#	Implements messageboxes with timeouts and other features.
#
# Based on msgbox.tcl 2000/04/19 09:25:53 hobbs 
# which is ... Copyright (c) 1994-1997 Sun Microsystems, Inc.
#
# This provides a timedMessageBox like tk_messageBox, but with the
# additional features:
#
#   -buttons <list>   as an alternative to -type.  The entries must be
#                     unique, and will serve as the button labels and
#                     as the return values, including capitalization
#                     (unlike the way an OK button returns ok).  The 
#                     -buttons override the -type.  Alt-key bindings
#                     will be produced only if all button names start
#                     with different letters.
#
#   -icon  <image>    as an alternative to the standard three, if the
#                     named image exists (in timedmb or global name space).
#
#   -default <val>
#   -timeout <ms>     If no button is pressed within this many milliseconds,
#                     the default action is taken.  Wnen there is no
#                     -default provided, then the value "_timeout_" is
#                     returned. (Buttons named "_timeout_" will lead to
#                     confusion.)  If no -timeout is specified, or a
#                     value less than 1, then there is no time limit.
#                     (Note that -default has noting to do with the 
#                     -default option for buttons.)
#
#   -command <proc>   The extensions described so far lead to usage much like
#                     the original tk_messageBox (crossed with tk_dialog),
#                     but that still leaves the fundamental problem of
#                     "recursive event loops" whereby multiple overlapping
#                     message boxes must return in the reverse order they
#                     were posted.  That can lead to long delays.  With the
#                     addition of the -command option, timed_messageBox is
#                     non-blocking, and returns immediately.  When (and
#                     immediately when) a response or timeout occurs, the
#                     the callback command is invoked, with the response 
#                     as its argument.  The <proc> should take one argument.
#
# Multiple simultaneous message boxes don't clobber each other,
# and the return value is delivered properly.  To avoid too deep
# a pileup, set the variable ::timedmb::maximumNumber.  When the
# number is exceeded, the oldest existing message box is forced to
# time-out immediately (returning its default value or "_timeout_")
# even if it had no -timeout specified.  So programmers beware!
# timedMessageBox can return "_timeout_" even without "-timeout"
#
# No response is accepted until some short time after the window is
# displayed, to prevent accidental activation when the dialog grabs
# focus.  The number of milliseconds delay is ::timedmb::delay.
#
# The buttons are normally 6 characters wide, but for wider labels, widths
# of 10 or 14 will be used (for all buttons).  If a button label is wider
# than 14 characters, it will be partly hidden!
#
# Force loading of msgbox code (need its images)

if { [catch { image width ::tk::dialog::b1 }] } {

namespace eval ::tk::dialog {}

image create bitmap ::tk::dialog::b1 -foreground black \
-data "#define b1_width 32\n#define b1_height 32
static unsigned char q1_bits[] = {
   0x00, 0xf8, 0x1f, 0x00, 0x00, 0x07, 0xe0, 0x00, 0xc0, 0x00, 0x00, 0x03,
   0x20, 0x00, 0x00, 0x04, 0x10, 0x00, 0x00, 0x08, 0x08, 0x00, 0x00, 0x10,
   0x04, 0x00, 0x00, 0x20, 0x02, 0x00, 0x00, 0x40, 0x02, 0x00, 0x00, 0x40,
   0x01, 0x00, 0x00, 0x80, 0x01, 0x00, 0x00, 0x80, 0x01, 0x00, 0x00, 0x80,
   0x01, 0x00, 0x00, 0x80, 0x01, 0x00, 0x00, 0x80, 0x01, 0x00, 0x00, 0x80,
   0x01, 0x00, 0x00, 0x80, 0x02, 0x00, 0x00, 0x40, 0x02, 0x00, 0x00, 0x40,
   0x04, 0x00, 0x00, 0x20, 0x08, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x08,
   0x60, 0x00, 0x00, 0x04, 0x80, 0x03, 0x80, 0x03, 0x00, 0x0c, 0x78, 0x00,
   0x00, 0x30, 0x04, 0x00, 0x00, 0x40, 0x04, 0x00, 0x00, 0x40, 0x04, 0x00,
   0x00, 0x80, 0x04, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x06, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};"
image create bitmap ::tk::dialog::b2 -foreground white \
-data "#define b2_width 32\n#define b2_height 32
static unsigned char b2_bits[] = {
   0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x1f, 0x00, 0x00, 0xff, 0xff, 0x00,
   0xc0, 0xff, 0xff, 0x03, 0xe0, 0xff, 0xff, 0x07, 0xf0, 0xff, 0xff, 0x0f,
   0xf8, 0xff, 0xff, 0x1f, 0xfc, 0xff, 0xff, 0x3f, 0xfc, 0xff, 0xff, 0x3f,
   0xfe, 0xff, 0xff, 0x7f, 0xfe, 0xff, 0xff, 0x7f, 0xfe, 0xff, 0xff, 0x7f,
   0xfe, 0xff, 0xff, 0x7f, 0xfe, 0xff, 0xff, 0x7f, 0xfe, 0xff, 0xff, 0x7f,
   0xfe, 0xff, 0xff, 0x7f, 0xfc, 0xff, 0xff, 0x3f, 0xfc, 0xff, 0xff, 0x3f,
   0xf8, 0xff, 0xff, 0x1f, 0xf0, 0xff, 0xff, 0x0f, 0xe0, 0xff, 0xff, 0x07,
   0x80, 0xff, 0xff, 0x03, 0x00, 0xfc, 0x7f, 0x00, 0x00, 0xf0, 0x07, 0x00,
   0x00, 0xc0, 0x03, 0x00, 0x00, 0x80, 0x03, 0x00, 0x00, 0x80, 0x03, 0x00,
   0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};"
image create bitmap ::tk::dialog::q -foreground blue \
-data "#define q_width 32\n#define q_height 32
static unsigned char q_bits[] = {
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x07, 0x00,
   0x00, 0x10, 0x0f, 0x00, 0x00, 0x18, 0x1e, 0x00, 0x00, 0x38, 0x1e, 0x00,
   0x00, 0x38, 0x1e, 0x00, 0x00, 0x10, 0x0f, 0x00, 0x00, 0x80, 0x07, 0x00,
   0x00, 0xc0, 0x01, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0xe0, 0x01, 0x00,
   0x00, 0xe0, 0x01, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};"
image create bitmap ::tk::dialog::i -foreground blue \
-data "#define i_width 32\n#define i_height 32
static unsigned char i_bits[] = {
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0xe0, 0x01, 0x00, 0x00, 0xf0, 0x03, 0x00, 0x00, 0xf0, 0x03, 0x00,
   0x00, 0xe0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0xf8, 0x03, 0x00, 0x00, 0xf0, 0x03, 0x00, 0x00, 0xe0, 0x03, 0x00,
   0x00, 0xe0, 0x03, 0x00, 0x00, 0xe0, 0x03, 0x00, 0x00, 0xe0, 0x03, 0x00,
   0x00, 0xe0, 0x03, 0x00, 0x00, 0xe0, 0x03, 0x00, 0x00, 0xf0, 0x07, 0x00,
   0x00, 0xf8, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};"
image create bitmap ::tk::dialog::w1 -foreground black \
-data "#define w1_width 32\n#define w1_height 32
static unsigned char w1_bits[] = {
   0x00, 0x80, 0x01, 0x00, 0x00, 0x40, 0x02, 0x00, 0x00, 0x20, 0x04, 0x00,
   0x00, 0x10, 0x04, 0x00, 0x00, 0x10, 0x08, 0x00, 0x00, 0x08, 0x08, 0x00,
   0x00, 0x08, 0x10, 0x00, 0x00, 0x04, 0x10, 0x00, 0x00, 0x04, 0x20, 0x00,
   0x00, 0x02, 0x20, 0x00, 0x00, 0x02, 0x40, 0x00, 0x00, 0x01, 0x40, 0x00,
   0x00, 0x01, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x00, 0x01,
   0x40, 0x00, 0x00, 0x01, 0x40, 0x00, 0x00, 0x02, 0x20, 0x00, 0x00, 0x02,
   0x20, 0x00, 0x00, 0x04, 0x10, 0x00, 0x00, 0x04, 0x10, 0x00, 0x00, 0x08,
   0x08, 0x00, 0x00, 0x08, 0x08, 0x00, 0x00, 0x10, 0x04, 0x00, 0x00, 0x10,
   0x04, 0x00, 0x00, 0x20, 0x02, 0x00, 0x00, 0x20, 0x01, 0x00, 0x00, 0x40,
   0x01, 0x00, 0x00, 0x40, 0x01, 0x00, 0x00, 0x40, 0x02, 0x00, 0x00, 0x20,
   0xfc, 0xff, 0xff, 0x1f, 0x00, 0x00, 0x00, 0x00};"
image create bitmap ::tk::dialog::w2 -foreground yellow \
-data "#define w2_width 32\n#define w2_height 32
static unsigned char w2_bits[] = {
   0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x01, 0x00, 0x00, 0xc0, 0x03, 0x00,
   0x00, 0xe0, 0x03, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0xf0, 0x07, 0x00,
   0x00, 0xf0, 0x0f, 0x00, 0x00, 0xf8, 0x0f, 0x00, 0x00, 0xf8, 0x1f, 0x00,
   0x00, 0xfc, 0x1f, 0x00, 0x00, 0xfc, 0x3f, 0x00, 0x00, 0xfe, 0x3f, 0x00,
   0x00, 0xfe, 0x7f, 0x00, 0x00, 0xff, 0x7f, 0x00, 0x00, 0xff, 0xff, 0x00,
   0x80, 0xff, 0xff, 0x00, 0x80, 0xff, 0xff, 0x01, 0xc0, 0xff, 0xff, 0x01,
   0xc0, 0xff, 0xff, 0x03, 0xe0, 0xff, 0xff, 0x03, 0xe0, 0xff, 0xff, 0x07,
   0xf0, 0xff, 0xff, 0x07, 0xf0, 0xff, 0xff, 0x0f, 0xf8, 0xff, 0xff, 0x0f,
   0xf8, 0xff, 0xff, 0x1f, 0xfc, 0xff, 0xff, 0x1f, 0xfe, 0xff, 0xff, 0x3f,
   0xfe, 0xff, 0xff, 0x3f, 0xfe, 0xff, 0xff, 0x3f, 0xfc, 0xff, 0xff, 0x1f,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};"
image create bitmap ::tk::dialog::w3 -foreground black \
-data "#define w3_width 32\n#define w3_height 32
static unsigned char w3_bits[] = {
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0xc0, 0x03, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0xe0, 0x07, 0x00,
   0x00, 0xe0, 0x07, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0xe0, 0x07, 0x00,
   0x00, 0xc0, 0x03, 0x00, 0x00, 0xc0, 0x03, 0x00, 0x00, 0xc0, 0x03, 0x00,
   0x00, 0x80, 0x01, 0x00, 0x00, 0x80, 0x01, 0x00, 0x00, 0x80, 0x01, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x01, 0x00, 0x00, 0xc0, 0x03, 0x00,
   0x00, 0xc0, 0x03, 0x00, 0x00, 0x80, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};"

}
# Ensure existence of ::timedmb namespace, and set defaults
#
namespace eval ::timedmb {
    variable delay 300
    variable maximumNumber 3
    variable ident 0
    variable windows [list]
    variable defaults [list]
    variable response
    variable focus
    set focus() {}
}

# comparing initial characters of two strings, case insensitive.
proc ::timedmb::firstCharCompare { s1 s2 } {
    return [ string compare \
            [string tolower [string range $s1 0 0]] \
            [string tolower [string range $s2 0 0]] ]
}


proc timedMessageBox {args} {
    global tkPriv tcl_platform tk_strictMotif

    set w tkPrivMsgBox
    upvar \#0 $w data

    #
    # The default value of the title is space (" ") not the empty string
    # because for some window managers, a 
    #		wm title .foo ""
    # causes the window title to be "foo" instead of the empty string.
    #
    set specs {
	{-default "" "" "_timeout_"}
        {-icon "" "" "info"}
        {-message "" "" ""}
        {-parent "" "" ""}
        {-title "" "" " "}
        {-type "" "" "ok"}
        {-buttons "" "" ""}
        {-timeout "" "" 0}
        {-command "" "" ""}
    }

    tclParseConfigSpec $w $specs "" $args

    if {[lsearch -exact {info warning error question} $data(-icon)] == -1} {
        if {[catch {image width $data(-icon)}]} {
            error "bad -icon value \"$data(-icon)\": must be error, info, question, warning, or a named image"
        }
    }

    if {[string length $data(-parent)] && ![winfo exists $data(-parent)]} {
	error "bad window path name \"$data(-parent)\""
    }

    if {![string is integer -strict $data(-timeout)]} {
        error "bad timeout value \"$data(-timeout)\". Must be integer (ms)."
    }

    switch -- $data(-type) {
	abortretryignore {
	    set buttons {
		{abort  -width 6 -text Abort -under 0}
		{retry  -width 6 -text Retry -under 0}
		{ignore -width 6 -text Ignore -under 0}
	    }
	}
	ok {
	    set buttons {
		{ok -width 6 -text OK -under 0}
	    }
	}
	okcancel {
	    set buttons {
		{ok     -width 6 -text OK     -under 0}
		{cancel -width 6 -text Cancel -under 0}
	    }
	}
	retrycancel {
	    set buttons {
		{retry  -width 6 -text Retry  -under 0}
		{cancel -width 6 -text Cancel -under 0}
	    }
	}
	yesno {
	    set buttons {
		{yes    -width 6 -text Yes -under 0}
		{no     -width 6 -text No  -under 0}
	    }
	}
	yesnocancel {
	    set buttons {
		{yes    -width 6 -text Yes -under 0}
		{no     -width 6 -text No  -under 0}
		{cancel -width 6 -text Cancel -under 0}
	    }
	}
	default {
	    error "bad -type value \"$data(-type)\": must be abortretryignore, ok, okcancel, retrycancel, yesno, or yesnocancel"
	}
    }

    set und 0
    if {[set nb [llength $data(-buttons)]]} {
        # check that buttons are unique
        if { $nb > [llength [lsort -unique $data(-buttons)]] } {
	    error "bad -buttons list \"$data(-buttons)\": no duplicates allowed"
        }
        # check if initial letters are unique
        if { $nb > [llength [lsort -unique -dictionary \
                -command ::timedmb::firstCharCompare $data(-buttons) ]] } {
	    set und -1
        }

        set buttons [list]
        foreach btn $data(-buttons) {
            lappend buttons [list $btn -width 6 -text $btn -under $und]
        }
    }

    if {[string compare $data(-default) "_timeout_"]} {
	set valid 0
	foreach btn $buttons {
	    if {[string equal [lindex $btn 0] $data(-default)]} {
		set valid 1
		break
	    }
	}
	if {!$valid} {
	    error "invalid default button \"$data(-default)\""
	}
    }

    # Single-button dialog always has that button as default
    if {[llength $buttons] == 1} { 
        set data(-default) [lindex [lindex $buttons 0] 0]
    }

    # 2. Decide window name.
    #    Set the dialog to be a child window of $parent
    #    Eliminate oldest window if there are too many
    #
    if {[string length $data(-parent)]} {
	set w .timed_msgbox_[incr ::timedmb::ident]
    } else {
	set w $data(-parent).timed_msgbox_[incr ::timedmb::ident]
    }

    lappend ::timedmb::windows $w 
    lappend ::timedmb::defaults $data(-default)
    if {[llength $::timedmb::windows] > $::timedmb::maximumNumber} {
        puts "Message box number [llength $::timedmb::windows] exceeds the maximum."
        puts "close [lindex $::timedmb::windows 0]"
        ::timedmb::timeout [lindex $::timedmb::windows 0] [lindex $::timedmb::defaults 0]
    }
    
    # 3. Create the top-level window and divide it into top
    # and bottom parts.

    # Remember focus for later restoration
    set ::timedmb::focus($w) [focus]

    catch {destroy $w}

    ::transients::new_dialog $w -withdrawn

    wm title $w $data(-title)
    wm iconname $w Dialog

    frame $w.bot
    pack $w.bot -side bottom -fill both
    frame $w.top
    pack $w.top -side top -fill both -expand 1

    # 4. Fill the top part with bitmap and message (use the option
    # database for -wraplength and -font so that they can be
    # overridden by the caller), but adjust the wraplength if
    # there is too much text.

    option add *Dialog.msg.wrapLength 3i widgetDefault
    option add *Dialog.msg.font {Times 18} widgetDefault

    label $w.msg -anchor nw -justify left -text $data(-message)
    if {[string compare $data(-icon) ""]} {
	if {[string equal $tcl_platform(platform) "macintosh"] \
		|| ([winfo depth $w] < 4) || $tk_strictMotif} {
	    label $w.bitmap -bitmap $data(-icon)
	} else {
	    canvas $w.bitmap -width 32 -height 32 -highlightthickness 0
	    switch $data(-icon) {
		error {
		    $w.bitmap create oval 0 0 31 31 -fill red -outline black
		    $w.bitmap create line 9 9 23 23 -fill white -width 4
		    $w.bitmap create line 9 23 23 9 -fill white -width 4
		}
		info {
		    $w.bitmap create image 0 0 -anchor nw \
			    -image ::tk::dialog::b1
		    $w.bitmap create image 0 0 -anchor nw \
			    -image ::tk::dialog::b2
		    $w.bitmap create image 0 0 -anchor nw \
			    -image ::tk::dialog::i
		}
		question {
		    $w.bitmap create image 0 0 -anchor nw \
			    -image ::tk::dialog::b1
		    $w.bitmap create image 0 0 -anchor nw \
			    -image ::tk::dialog::b2
		    $w.bitmap create image 0 0 -anchor nw \
			    -image ::tk::dialog::q
		}
		warning {
		    $w.bitmap create image 0 0 -anchor nw \
			    -image ::tk::dialog::w1
		    $w.bitmap create image 0 0 -anchor nw \
			    -image ::tk::dialog::w2
		    $w.bitmap create image 0 0 -anchor nw \
			    -image ::tk::dialog::w3
		}
                default {
                    $w.bitmap configure -width [image width $data(-icon)] \
                            -height [image height $data(-icon)]
                    $w.bitmap create image 0 0 -anchor nw -image $data(-icon)
                }
	    }
	}
    }
    grid $w.bitmap $w.msg -in $w.top -sticky news -padx 2m -pady 2m
    grid columnconfigure $w.top 1 -weight 1
    grid rowconfigure $w.top 0 -weight 1

    # 5. Create a row of buttons at the bottom of the dialog.

    set i 0
    foreach btn $buttons {
	set name [lindex $btn 0]
        # $bwin is also used below as a sample button
        set bwin $w._$name
	set opts [lrange $btn 1 end]
	if {![llength $opts]} {
	    # For no opts (how?) make the text be $name capitalized
	    set capName [string toupper $name 0]
	    set opts [list -text $capName]
	}

	eval button [list $bwin] -default normal $opts \
            [list -command [list set ::timedmb::response($w) $name]]

	if {[string equal $name $data(-default)]} {
	    $bwin configure -default active
	}
	pack $bwin -in $w.bot -side left -expand 1 -padx 3m -pady 2m

	# create the binding for the key accelerator, based on the underline
	#
	set underIdx [$bwin cget -under]
	if {$underIdx >= 0} {
	    set key [string index [$bwin cget -text] $underIdx]
	    bind $w <Alt-[string tolower $key]>  [list $bwin invoke]
	    bind $w <Alt-[string toupper $key]>  [list $bwin invoke]
	}
	incr i
    }

    # Make bindings so default button shifts with Tab focus
    # 
#    if {[string length $data(-default)]} {
	bind $w <FocusIn> {
	    if {[string equal Button [winfo class %W]]} {
		%W configure -default active
	    }
	}
	bind $w <FocusOut> {
	    if {[string equal Button [winfo class %W]]} {
		%W configure -default normal                
	    }
	}
#    }

    # 6. Create a binding for <Return> on the dialog

    bind $w <Key-Return> {
	if {[string equal Button [winfo class %W]]} {
	    tkButtonInvoke %W
	}
    }

    # 7. The window is already withdrawn; update all the geometry information
    # so we know how wide the buttons want to be, then how big the whole
    # window wants to be. Then center the window in the display or parent
    # and de-iconify it.

    #  wm withdraw $w
    update idletasks

    set ratio 0.0
    # Find pixel width for basic button text width
    set fon [$bwin cget -font]
    set wid 6
    set pix [font measure $fon -displayof $w [string repeat "0" $wid]]
    foreach btn $buttons {
	set name [lindex $btn 0]
        set r [expr { \
                [font measure $fon -displayof $w [$w._$name cget -text]] \
                / double( $pix ) }]
        #puts "ratio for $name is $r"
        set ratio [expr { $r>$ratio? $r : $ratio}]
    }
    if { $ratio > 6.0/6.0 } { set wid 10 }
    if { $ratio > 10.0/6.0 } { set wid 14 }
    if { $wid > 6 } {
        #puts "must reset width to $wid"
        foreach btn $buttons {
            $w._[lindex $btn 0] configure -width $wid
        }
    }

    ::transients::PlaceWindow $w widget $data(-parent)
    ::transients::deiconify

    # 8. NO GRAB!  Remember focus and take it.

    if {[string compare $data(-default) "_timeout_"]} {
	set focus $w._$data(-default)
    } else {
	set focus $w
    }
    focus -force $focus

    # 9. Set up the handling of the user response, which is fed to
    # a special variable.  Method depends on whether there was a
    # -command provided (blocking).  

    # Set timeout, if any
    if { $data(-timeout) > 0 } {
        after $data(-timeout) [list ::timedmb::timeout $w $data(-default)]
    }

    # Make window-manager-close act like timeout
    wm protocol $w WM_DELETE_WINDOW [list ::timedmb::timeout $w $data(-default)]


    # With -command: set a trace on the variable to execute the user's
    # command. Without -command: wait (block) for the variable.

    set ::timedmb::response($w) {}
    trace variable ::timedmb::response($w) w \
            [list ::timedmb::activate $data(-command)]
    if { [string equal $data(-command) ""] } {
        puts "Blocking for null command"
        tkwait variable ::timedmb::response($w)
        set r $::timedmb::response($w)
        unset ::timedmb::response($w)
    } else {
        set r {}
        puts "Asynchronous with command = $data(-command)"
    }
    return $r
}

# When the user (or timeout) responds, then unset bookkeeping
# we have done for this widget (delay unsetting the response).
# Restore the focus and grab, and destroy toplevel etc using 
# proc RestoreFocusGrab.

# Argument list is determined by need to use this as a variable
# trace.  Note that the array index name is the same as the 
# window name ($w), except for the special key "_timeout_".

proc ::timedmb::activate { command arr w op } {
    ::timedmb::delist $w

    puts "********** Activate button: $command, $arr, $w, $op"
    destroy $w

    if { [info exists ::timedmb::focus($w)] } {
        if { [llength $::timedmb::windows] && \
                [winfo exists [lindex $::timedmb::windows end ]]} {
            focus -force [lindex $::timedmb::windows end]
        } elseif { [winfo exists $::timedmb::focus($w)] } {
            focus -force $::timedmb::focus($w)
        }
        unset ::timedmb::focus($w)
    }

    # Perform the command after the dialog has a chance to close,
    # to ensure stale dialogs can't stack up.  Unset the response
    # variable (after extracting the value, but before executing
    # the command).
    # 
    if {[string length $command]} {
        after idle "$command \"\$::timedmb::response($w)\[unset ::timedmb::response($w)\]\""
    }
}

proc ::timedmb::timeout { w deflt } {
    if { [info exists ::timedmb::response($w)] } {
        set ::timedmb::response($w) $deflt
    }
}

proc ::timedmb::delist { w } {
    set i [lsearch -exact $::timedmb::windows $w]
    if { $i >= 0 } {
        set ::timedmb::windows [lreplace $::timedmb::windows $i $i]
        set ::timedmb::defaults [lreplace $::timedmb::defaults $i $i]
    }
}


#############################################################

# TODO:  equivalent of restorefocusgrab (but just for focus)

# Grab does not work for multiple simultaneous dialogs (only
# one dialog will be accessible) so here is a management system
# for transient dialogs without grab. With this the user *CAN* 
# interact with regular windows while a dialog is displayed
# (the author believes that is actually better behavior than 
# grab), but all the dialogs are always stacked above all the 
# other windows. The stacking order within the dialogs and
# within regular windows can vary, but the two groups never
# interleave.
#
# The programmer should use ::transients::new_dialog instead of
# toplevel to create a new dialog window.
# 

namespace eval ::transients {
    variable transientMaster {}
    variable cover {}
    variable windows {}

}

# How can a window obscure our special window?  
# By raising, clicking, expanding, or moving.
# The latter two are signalled by a <Configure> event
# The former is accompanied by <Visibility> (not on MSWin)
# and <Expose> (Perhaps not when Backingstore is on) but
# they can occur for other reasons.  Instead, I can redefine
# the raise command to catch explicit programmatic raise.


# Open a new dialog window $w (with toplevel options $args), 
# and make it transient.  Add this window name into the list 
# ::transients::windows (unless it is already listed).
#
proc ::transients::new_dialog { w args } {
    variable windows 
    variable transientMaster

    # Create transient dialog window.  Withdraw it (and apply the
    # withdraw later with [update idletasks]) so that the transient
    # nature is applied properly.
    #
    puts "Create new dialog window $w  ====================================="

    # Extract -withdrawn option
    set i [lsearch -exact $args -withdrawn]
    if { $i < 0 } {
        set withdrawn 0
    } else {
        set withdrawn 1
        set args [lreplace $args $i $i]
    }

    # Make the toplevel, with options
    eval [linsert $args 0 toplevel $w -class Dialog]

    wm withdraw $w

    if { [lsearch -exact $windows $w] < 0 } {
        lappend windows $w
    }

    # If there is no special hidden transient, then create it.
    set exists [winfo exists ._dia_]
    if { !$exists } {
        puts "._dia_ does not yet exist"
        toplevel ._dia_ -class Dialog
        set transientMaster {}
        wm title ._dia_ "Dialog"
        wm withdraw ._dia_
        # puts "Created ._dia_"
    }
    # puts "toplevel $w -class Dialog $args"
    # puts "update idle tasks"
    update idletasks
    # puts "Did update idletasks"
    if { !$exists } {
        if { [string equal [wm state .] normal] }  {
            # puts "make ._dia_ transient to ."
	    puts  "D  ._dia_"
            wm transient ._dia_ .
	    set transientMaster .
        }
        if { !$withdrawn } {
            # puts "deiconify ._dia_"
            wm deiconify ._dia_
        }
        bind all <Configure> {::transients::win_activity %W Configure}
        bind all <FocusIn> {::transients::win_activity %W FocusIn}
        bind all <Map> {::transients::win_activity %W Map}
#        after idle "::transients::scurry_under $w \[winfo x $w\] \[winfo y $w\]"
    }
    # puts "Make $w transient to ._dia_"
    puts "W  $w  "
    wm transient $w ._dia_
    if { !$withdrawn } {
        wm deiconify $w
    }

    # Set the default deletion handler for this window.
    # Specific applications can and should override this 
    # setting (by re-setting the binding) but such external 
    # handlers must include a call to ::transients::end_dialog.
    #
    bind $w <Destroy> [list ::transients::end_dialog %W]

    # Binding so this window is used to hide the hidden ._dia_

  ##  bind $w <Configure> { ::transients::scurry_under %W %x %y }

    if { [info command ::transients::orig_raise] == "" } {
        puts "Renaming raise"
        rename ::raise ::transients::orig_raise
        rename ::transients::proc_raise ::raise
    }
    puts "Done creating $w  ==============================="
}


# Forget about one of the dialog windows.  This can be called
# explicitly before/after the window is destroyed, or called
# automatically by a binding.  By default, it is called by
# the <Destroy> binding (see new_dialog) so the programmer need
# only destroy the dialog window when finished.
#
proc ::transients::end_dialog { w } {
    variable windows

    # Because of toplevel bindings firing for all widgets, we get
    # many invocations when embedded widgets are destroyed, occurring
    # after they are destroyed.
    set i [lsearch -exact $windows $w]
    if { $i >= 0 } {
        puts "Forget dialog window $w (index $i)"   
        set windows [lreplace $windows $i $i]
    }
    if { [llength $windows] == 0 } {
        nodialogs
    } else {
	::transients::under_cover
    }
}
# Watch for any rearrangement of windows that may cause a dialog window
# to be covered.  When any happens, make the hidden dialog be transient
# to whichever window might be covering a dialog.

proc ::transients::win_activity { w {what {}} } {
    variable windows 
    variable transientMaster

    set t [winfo toplevel $w]

    puts -nonewline "."
    # Switch off this handler if there are no more dialogs
    if { ![winfo exists ._dia_] } {
        # puts "No dialogs..."
        nodialogs
        return
    }
     
    # if window is a toplevel, and not our hidden dialog, and not a real dialog
    if { [string equal $w $t] && ![string equal $w "._dia_"] } { 
	if { [lsearch -exact $windows $w] < 0 } {
        # puts "$w == $t  &&  $w != ._dia_  &&  $w not in $windows && $w != $transientMaster (?)"
        set focus [focus]
	puts "Activity with $t ($what) when master is $transientMaster, focus $focus"

        # become transient to this toplevel (Under Linux, do so even if 
        # we are already transient to it; that's in case a previous setting
        # didn't "take" fully, as seems to happen.  There's no flicker.)  Under
	# Windows, without this test, the dialog window gets lost occasionally
        # (manager failure?) and flickers terribly.
        if { ![string equal $w $transientMaster] || \
                [string equal $::tcl_platform(platform) "unix"]} {
	    # wm transient causes a bad flicker on windows (XP) but raise works
	    # fine, even in older Tk.  Therefore, only switch transient master
	    # when current master is lost.  Alternately, it is [raise] that
	    # causes long delays in certain X window managers, so we avoid raise
	    # by a withdraw-deiconify cycle.  
		
            if { [string equal $::tcl_platform(platform) "unix"]} {
		puts "Make ._dia_ be transient to master $w"
		wm transient ._dia_ $w
                puts "raise ._dia_ and send focus to $focus"
#                ::transients::orig_raise ._dia_
                wm withdraw ._dia_
                wm deiconify ._dia_
                if { [string length $focus] } { focus -force $focus }
		set transientMaster $w
            } else {# windows
		if { ![winfo exists $transientMaster] || \
			 ![winfo viewable $transientMaster] } {
		    puts "Make ._dia_ be transient to master $w"
		    wm transient ._dia_ $w
		    set transientMaster $w
		}
		# puts "Ordinary raise ._dia_"
                ::transients::orig_raise ._dia_
            }
        }
        # We need to raise the hidden master dialog window because the 
        # declaration of being transient has come too late to force ._dia_
        # (and dialogs) to be raised above $w, (they would not be raised
        # until the window manager does something with $w)
        #
        # Here we are stuck, because [raise] is very slow on KDE
        # but we need to raise.  An upgrade to Tk8.4 will solve the
        # problem in two ways: the slow-raise bug is supposedly fixed
        # and there is the new command [wm stackorder] so we can test
        # whether we need to raise.  Maybe even it will fix the bug
        # where the transient window isn't immediately raised by the
        # window manager (doubt it).
        # OK, solution: since we are transient, we can raise (without the 
        # raise-delay bug) by withdrawing and deiconifying.

        #puts "Raise ._dia_"
        #after idle [list ::transients::orig_raise ._dia_]
        #::transients::orig_raise ._dia_
#	if { [string equal $::tcl_platform(platform) "unix"]} {
##           wm transient ._dia_ .
##           wm transient ._dia_ $w
#            if { ![string equal $w $transientMaster] } {
#                wm withdraw ._dia_
#                wm deiconify ._dia_
#                focus -force $focus
#            }
#        } else {
#            ::transients::orig_raise ._dia_
#        }

        ::transients::deiconify
        }
	# Move under cover 
	::transients::under_cover
    }
    # puts "Finished activity"
    return {}
}

proc ::transients::deiconify { } {
    variable windows
    set any 0

    puts "Start deiconify"
    foreach d [concat ._dia_ $windows] {
	if {![winfo exists $d]} {
	    puts "Error in deiconify: window $w does not exist!"
	    puts "Windows are $windows"
	    return
	}
        if { [lsearch [list iconic withdrawn] [wm state $d]] >= 0 } {
            set any 1
            break
        }
    }
    if { $any } {
        foreach d [concat ._dia_ $windows] {
            puts "Deioconify $d"
            wm deiconify $d
        }
    }
}

# Procedure to notice windows being raised, and adjust the transient
# dialogs accordingly.
proc ::transients::proc_raise { w args } {
    puts "Raise $w and handle more"
    eval [list ::transients::orig_raise $w] $args
    ::transients::win_activity $w Raise
    after idle {
        if { [winfo exists ._dia_] } { 
            ::transients::orig_raise ._dia_
        }
    }
}
 
# Restore normal bindings and meaning of [raise]. This to be done
# when there are no dialogs displayed.
proc ::transients::nodialogs { } {
    variable windows
    puts "No more dialogs"
    bind all <Configure> {}
    bind all <FocusIn> {}
    bind all <Map> {}
    if { [info command orig_raise] != "" && [info proc ::raise] != "" } {
        rename ::raise ::transients::proc_raise
        rename ::transients::orig_raise ::raise
    }
    # In case there are some dialogs remaining, destroy them.
    foreach d [concat ._dia_ $windows] {
        if { [winfo exists $d] } {
            # puts "Destroy $d"
            bind $d <Destroy> {}
            destroy $d
        }
    }
}

# Hide the special dialog box under a real dialog box
proc ::transients::under_cover { } {
    variable cover
    variable windows

    # puts "Start under_cover cover: $cover, windows: $windows"
    # Don't need to do anything if ._dia_ is invisible
    if { ![winfo exists ._dia_] || ![winfo viewable ._dia_]} { return }

    # Quit if there are no dialogs
    if { [llength $windows] == 0 } {
	::transients::nodialogs
	return
    }

    # Switch covering window if necessary
    if { ![winfo exists $cover] } {
	puts "Cover window $cover does not exist"
	set cover {}
	foreach w $windows {
	    puts "Try window $w"
	    if { [winfo exists $w] } {
		set cover $w
		break
	    }
	}
    }
    if { [string equal $cover ""] } {
	puts "No windows were found to exist"
	# ::transients::nodialogs
	return
    }
    # Get current cover location 
    set wx [winfo x $cover]
    set wy [winfo y $cover]
    if { [winfo x ._dia_] != $wx || [winfo y ._dia_] != $wy } { 
	puts "Scurry under $cover at $wx,$wy"
	wm geometry ._dia_ 1x1+$wx+$wy
    }
}

proc ::transients::PlaceWindow { w place anchor } {
#    wm withdraw $w
#    update idletasks
    set checkBounds 1
    if {[string equal -len [string length $place] $place "pointer"]} {
	## place at POINTER (centered if $anchor == center)
	if {[string equal -len [string length $anchor] $anchor "center"]} {
	    set x [expr {[winfo pointerx $w]-[winfo reqwidth $w]/2}]
	    set y [expr {[winfo pointery $w]-[winfo reqheight $w]/2}]
	} else {
	    set x [winfo pointerx $w]
	    set y [winfo pointery $w]
	}
    } elseif {[string equal -len [string length $place] $place "widget"] &&  [winfo exists $anchor] && [winfo ismapped $anchor]} {
	## center about WIDGET $anchor, widget must be mapped
	set x [expr {[winfo rootx $anchor] +  ([winfo width $anchor]-[winfo reqwidth $w])/2}]
	set y [expr {[winfo rooty $anchor] +  ([winfo height $anchor]-[winfo reqheight $w])/2}]
    } else {
	set x [expr {([winfo screenwidth $w]-[winfo reqwidth $w])/2}]
	set y [expr {([winfo screenheight $w]-[winfo reqheight $w])/2}]
	set checkBounds 0
    }
    if {$checkBounds} {
	if {$x < 0} {
	    set x 0
	} elseif {$x > ([winfo screenwidth $w]-[winfo reqwidth $w])} {
	    set x [expr {[winfo screenwidth $w]-[winfo reqwidth $w]}]
	}
	if {$y < 0} {
	    set y 0
	} elseif {$y > ([winfo screenheight $w]-[winfo reqheight $w])} {
	    set y [expr {[winfo screenheight $w]-[winfo reqheight $w]}]
	}
    }
#    wm geometry $w +$x+$y
#    wm deiconify $w
}


# ensure dialogs are not iconized. Deiconize all if any are iconized


##########################################################################
#toplevel .top1
#toplevel .top2


#after 4000 ::transients::new_dialog .dia1


#after 14000 {
#     ::transients::new_dialog .dia2
#}

proc grab { args } {
    error "There aren't supposed to be grabs!"
}

set foo {timedMessageBox -buttons {Oin Gloin Gimli Doc} -message {Choose a dwarf}}

toplevel .t2

label .l -wraplength 200 -just l -text {
This is the text in the main wish window.
This is the text in the main wish window.
This is the text in the main wish window.
}
button .b -text "Main Button"
pack .l .b

label .t2.l -wraplength 200 -just l -text {
This is the text in the second toplevel window.
This is the text in the second toplevel window.
}
button .t2.b -text "surplus button"
pack .t2.l .t2.b


after 2000 $foo
after 3000 $foo
after 4000 $foo

proc fr { } { puts "focus is [focus]" ; after 2000 fr }
#fr