# Copyright (c) 1993 by Sanjay Ghemawat
#############################################################################
# File Dialog
#
# Commands
#
#	get_file_name <leader> <title> <message> <var>
#		Get file name from user.  The name is stored in <var>.
#		Returns true iff user does not cancel operation.

# Hidden global variables
#
#	file_box		File selector window
#	file_done		Is file interaction finished

set file_box {}
set file_done 0

proc get_file_name {leader title message var} {
    file_make

    set result [file_interact $leader $title $message]
    if $result {
	global file_box

	upvar $var returnVar
	set returnVar [$file_box filename]
    }
    return $result
}

proc file_make {} {
    global file_box file_done
    if {$file_box != {}} {return}

    set f .file_dialog
    toplevel $f -class Dialog
    wm title $f Dialog
    wm protocol $f WM_DELETE_WINDOW {set file_done 0}

    set file_box [FileSelector $f.box]

    frame $f.top -relief raised -bd 1
    frame $f.mid -relief raised -bd 1
    frame $f.bot -relief raised -bd 1
    frame $f.bot.default -relief sunken -bd 1

    message $f.text -aspect 400 -text {Uninitialized message}

    pack append $f.top $f.text {top expand fill padx 5m pady 5m}
    pack append $f.mid $f.box {top expand padx 5m pady 5m}

    button $f.yes -text Okay -command {set file_done 1}
    button $f.no -text Cancel -command {set file_done 0}

    pack append $f.bot.default $f.yes {left padx 3m pady 3m}

    pack append $f.bot $f.no {left expand padx 5m pady 5m}
    pack append $f.bot $f.bot.default {left expand}

    pack append $f $f.top {top expand fill}
    pack append $f $f.mid {top expand fill}
    pack append $f $f.bot {bottom fill}

    bind $f.box.entry <Control-c> {set file_done 0}
    bind $f.box.entry <Return> {set file_done 1}
    bind $f.box.children.box <Double-Button-1> {file_done_check}

    wm withdraw $f
    update
}

proc file_interact {leader title message} {
    global file_done file_box
    set f .file_dialog

    # Fix dialog contents
    $f.text configure -text $message
    wm title $f $title

    # Run dialog
    set file_done -1
    dialog_run $leader $f $f.box.entry file_done

    return $file_done
}

proc file_done_check {} {
    global file_box file_done

    if ![file isdirectory [$file_box filename]] {
	set file_done 1
    }
}
