#!/home/bwelch/bin/wish -f
# Send chapter
# Control Panel demo

wm title . Controller

# Create a frame for buttons and entry.
frame .top -borderwidth 10
pack .top -side top -fill x

# Create the command buttons.
button .top.quit -text Quit -command exit
set but [button .top.run -text "Run it" -command Run -width 6]
pack .top.quit .top.run -side right

# Create a labeled entry for the command
label .top.l -text Command: -padx 0
entry .top.cmd -width 20 -relief sunken \
	-textvariable command
pack .top.l -side left
pack .top.cmd -side left -fill x -expand true

# Set up keybinding equivalents to the buttons
bind .top.cmd <Return> Run
bind .top.cmd <Control-c> Stop
focus .top.cmd

# Fork an editor to log the output.
exec mxedit /tmp/log.[pid] &

set sendCmd [list /tilde/welch/doc/tclbook/examples/send.tcl \
		"mxedit /tmp/log.[pid]" mxInsert [winfo name .]]

# Run the program and arrange to read its input
proc Run {} {
	global command job sendCmd but
	set cmd [concat exec $command |& $sendCmd &]
	send "mxedit /tmp/log.[pid]" [list mxInsert $command\n]
	if [catch {eval $cmd} job] {
		send "mxedit /tmp/log.[pid]" [list mxInsert $job\n]
	} else {
		$but config -text Stop -command Stop
	}
}
# Stop the program and fix up the button
proc Stop {} {
	global job but
	catch {eval {exec kill} $job}
	send "mxedit /tmp/log.[pid]" [list mxInsert ABORT\n]
	$but config -text "Run it" -command Run
}
# Handle the callback from sender
proc Send_Done {} {
	global but
	send "mxedit /tmp/log.[pid]" {mxInsert DONE\n}
	$but config -text "Run it" -command Run
}
