#!/home/bwelch/bin/wish -f
# Tkexample chapter
# browse0.tcl --
#	Browser for the Tcl and Tk examples in the book.
#	Version 0
#
# The directory containing all the tcl files
set browse(dir) /home/bwelch/tclbook/examples

# Set up the main display
wm minsize . 30 5
wm title . "Tcl Example Browser, v0"

frame .menubar
pack .menubar -fill x
button .menubar.quit -text Quit -command exit
pack .menubar.quit -side right

# A label identifies the current example
label .menubar.label -textvariable browse(current)
pack .menubar.label -side right -fill x -expand true

# Look through the .tcl files for the keywords
# that group the examples.
foreach f [glob $browse(dir)/*.tcl] {
	if [catch {open $f} in] {
		puts stderr "Cannot open $f: $in"
		continue
	}
	while {[gets $in line] >= 0} {
		if [regexp -nocase {^# ([^ ]+) chapter} $line \
				x keyword] {
			lappend examples($keyword) $f
			close $in
			break
		}
	}
}
# Create the menubutton and menu
menubutton .menubar.ex -text Examples -menu .menubar.ex.m
pack .menubar.ex -side left
set m [menu .menubar.ex.m]

# Create a cascaded menu for each group of examples
set i 0
foreach key [lsort [array names examples]] {
	$m add cascade -label $key -menu $m.sub$i
	set sub [menu $m.sub$i -tearoff 0]
	incr i
	foreach item [lsort $examples($key)] {
		$sub add command -label [file tail $item] \
			-command [list Browse $item]
	}
}

# Create the text to display the example
frame .body
text .body.t -setgrid true -width 80 -height 25 \
	-yscrollcommand {.body.s set}
scrollbar .body.s -command {.body.t yview} -orient vertical
pack .body.s -side left -fill y
pack .body.t -side right -fill both -expand true
pack .body -side top -fill both -expand true
set browse(text) .body.t

# Display a specified file. The label is updated to
# reflect what is displayed, and the text is left
# in a read-only mode after the example is inserted.
proc Browse { file } {
	global browse
	set browse(current) [file tail $file]
	set t $browse(text)
	$t config -state normal
	$t delete 1.0 end
	if [catch {open $file} in] {
		$t insert end $in
	} else {
		$t insert end [read $in]
		close $in
	}
	$t config -state disabled
}
