
# This code creates the user interface for global.
#
# Copyright (c) 1993 - 1995 Pacific Marketing and Consulting, Inc,
#       and ICEM Systems, GmbH.  All rights reserved.
# Author:  Wayne A. Christopher, wayne@icemcfd.com

proc file_load {{init 0}} {
    global config_dir blocking_file save_needed
    
    set mess "Blocking has been modified -- save before loading new blocking?"
    if {[info exists save_needed] && \
	    ![tk_dialog .save "Blocking modified" $mess "" -1 "Yes" "No"]} {
	file_save
    }
    
    set files [glob -nocomplain $config_dir/mesh/*]
    set block_files ""
    foreach f $files {
	set t [file tail $f]
	set fp [open $f r]
	set line [gets $fp]
	if {$line == "MATERIALS"} {
	    lappend block_files $t
	}
	close $fp
    }
    
    if {$init && ($block_files == "")} return
    
    set mess "Please select a blocking file to load the\
	    mesh information from.  You can delete\
	    blocking files using the \"Delete\" button once you have\
	    selected them."
    set filename [choose_one $mess $block_files "" +300+300 file_delete_block]
    
    if $init {
	set blocking_file $filename
    } else {
	if {$filename == ""} {
	    mess "Cancelled load blocking.\n" red
	    return
	}
	command "restore_blocking $filename"
	set blocking_file $filename
	get_indices 1
	update_display
	catch {unset save_needed}
    }
}

proc file_delete_block {name} {
    global config_dir
    
    set path $config_dir/mesh/$name
    
    set mess "Delete blocking file \"$path\"?"
    if ![tk_dialog .delfile "Delete file" $mess "" -1 "Yes" "No"] {
	cmd_rm -f $path
	return 1
    }
    return 0
}

proc file_save {} {
}

proc file_options {} {
}

proc file_import {} {
}

proc file_dirty {} {
    global save_needed
    set save_needed 1
}

proc file_quit {} {
    if [tk_dialog .quit "Quit" "Really quit?" "" -1 "Yes" "No"] return
    global_configuration_write
    command quit
    exit 0
}

# ----------------------------------------------

proc file_super {} {
    global global_options
    
    set domdir $global_options(domdir)
    set domains ""
    foreach d [glob -nocomplain $domdir/*] {
	lappend domains [file tail $d]
    }
    
    set mess "Please select a domain file to store the super-domain mesh in,\
	    or type a new domain file name.  You can delete\
	    domain files using the \"Delete\" button once you have\
	    selected them."
    set filename [choose_one $mess $domains "" +300+300 file_delete_domain]
    
    if {$filename != ""} {
	command "super_domain $filename"
    }
}

proc file_hgrid {} {
    global global_options display_flag
    
    set domdir $global_options(domdir)
    set domains ""
    foreach d [glob -nocomplain $domdir/*] {
	lappend domains [file tail $d]
    }
    
    set mess "Please select a domain file to store the H-grid mesh in,\
	    or type a new domain file name.  You can delete\
	    domain files using the \"Delete\" button once you have\
	    selected them."
    set filename [choose_one $mess $domains "" +300+300 file_delete_domain]
    
    if {$filename != ""} {
	set cc ""
	# if $display_flag(quad_cell_centered) {
	#    set cc cell_centered
	# }
	if [check_compute_hgrid] {
	    command "write_hgrid $filename $cc [volume_string]"
	} else {
	    mess "Domain file not written.\n" red
	}
    }
}

proc check_compute_hgrid {} {
    global hgrid_computed_once
    
    if [info exists hgrid_computed_once] { return 1 }
    set mess "Compute H-grid now?"
    if [tk_dialog .compute "Compute H-grid" $mess "" -1 "Yes" "No"] {
	return 0
    }
    set hgrid_computed_once 1
    return 1
}

proc file_unstruct {what} {
    global global_options volume_mat surface_mat staircase_mat
    global families family_dims family_name family_active
    global form_done_flag botform_geo mesh_params
    
    set fams ""
    set vols ""
    set surfs ""
    
    set allnams [families_in_order]
    if {$allnams == ""} {
	mess "Error: there are no families available.\n"
	return
    }
    
    foreach desc $allnams {
	set name [lindex $desc 0]
	set f [lindex $desc 1]
	lappend fams [list $f -text $name]
	if {$family_dims($f) == 3} {
	    lappend vols [list $f -text $name]
	} else {
	    lappend surfs [list $f -text $name]
	}
    }
    
    form_kill .surface
    
    set buttons {{Accept {form_accept_hack .surface}}}
    
    set d [form_init .surface "Write surface mesh" anal $buttons]
    form_frame $d.fr sunken 3 {0 0}; set d $d.fr
    
    form_label $d.regionl " Material: " {1 1}
    form_frame $d.region ridge 2 {2 1 -fill none}
    if {$what != "surf" && $what != "bvol"} {
	form_checkbutton $d.ppd \
	    "Write Secondary Domains" global_options(ppd) {3 1}
    }
    
    if {$what == "bvol"} {
	if ![info exists volume_mat] {
	    set volume_mat [lindex [lindex $vols 0] 0]
	}
	check_box $d.region $vols 6 volume_mat 0
    } elseif {$what == "surf"} {
	catch {unset surface_mat}
	foreach ff $surfs {
	    set f [lindex $ff 0]
	    set surface_mat($f) $family_active($f)
	}
	check_box $d.region $surfs 6 surface_mat 1
    } else {
	catch {unset staircase_mat}
	foreach ff $fams {
	    set f [lindex $ff 0]
	    set staircase_mat($f) $family_active($f)
	}
	check_box $d.region $fams 6 staircase_mat 1
    }
    
    form_finish +300+300
    
    tkwait variable form_done_flag(.surface)
    if !$form_done_flag(.surface) return
    
    # puts "mats [array names staircase_mat]"
    
    # ----------------------
        
    set domdir $global_options(domdir)
    set domains ""
    foreach d [glob -nocomplain $domdir/*] {
	lappend domains [file tail $d]
    }
    
    set mess "Please select a domain file to store the mesh in,\
	    or type a new domain file name.  You can delete\
	    domain files using the \"Delete\" button once you have\
	    selected them."
    set filename [choose_one $mess $domains "" +300+300 file_delete_domain]
    if {$filename == ""} return
    
    set opts ""
    if $mesh_params(emit_triangles) { append opts "emit_tris" }
    if $mesh_params(no_mat)         { append opts " no_mat" }
	    
    if {$what == "bvol"} {
	command "write_surface_mesh -bvol $filename $opts $volume_mat"
    } else {
	
	set fams ""
	if {$what == "surf"} {
	    foreach f [array names surface_mat] {
		if $surface_mat($f) { lappend fams $f }
	    }
	} else {
	    foreach f [array names staircase_mat] {
		if $staircase_mat($f) { lappend fams $f }
	    }
	}
	
	if {$fams == ""} {
	    mess "No families selected!\n" red
	} else {
	    if $global_options(ppd) {
		set wopt "-ppd"
	    } else {
		set wopt "-noppd"
	    }
	    
	    switch $what {
		stair {
		    command "write_unstruct $filename $fams only_quads $wopt"
		}
		surf {
		    command "write_surface_mesh -surf $filename $opts $fams"
		}
		vol {
		    command "write_unstruct $filename $fams $wopt"
		}
	    }
	}
    }
}

proc file_delete_domain {name} {
    global global_options
    
    set path $global_options(domdir)/$name
        
    set mess "Delete domain file \"$path\"?"
    if ![tk_dialog .delfile "Delete file" $mess "" -1 "Yes" "No"] {
	cmd_rm -f $path
	return 1
    }
    return 0
}

proc file_read_staircase {} {
    global global_options display_flag
    
    set domdir $global_options(domdir)
    set domains ""
    foreach d [glob -nocomplain $domdir/*] {
	lappend domains [file tail $d]
    }
    
    set mess "Please select a staircase file to load. \
	    You can delete domain files using the \"Delete\" button\
	    once you have selected them."
    set filename [choose_one $mess $domains "" +300+300 file_delete_domain]
    
    if {$filename != ""} {
	
	set temp $display_flag(quad)
	set temp1 $display_flag(edge)
	set temp2 $display_flag(block)
	
	set display_flag(quad) 0
	set display_flag(edge) 0
	set display_flag(block) 0    
	
	update_display block quad edge scan
	
	command "read_staircase_file $filename"
	
	set display_flag(quad) $temp
	set display_flag(edge) $temp1
	set display_flag(block) $temp2
	
	add_new_families
	update_display block quad edge scan
	
    }
}

# ----------------------------------------------

proc file_shell {} {
    mess "Opening shell window ..."
    cmd_xterm -sb -geometry +0+0 &
}

# --------------------------------

proc file_write_AQUA {} {
    global global_options families family_dims family_name
    global family_active aqua_surf
    
    set fams ""
    foreach f $families {
	if {$family_dims($f) != 3} {
	    lappend fams [list $f -text $family_name($f)]
	}
    }
    
    if {$fams == ""} {
	mess "Error: there are no families available.\n"
	return 0
    }
    
    form_kill .surface   
    set buttons {{Accept {form_accept_hack .surface}} cancel}
    
    set d [form_init .surface "AQUA Output" anal $buttons]
    form_frame $d.fr sunken 3 {0 0}; set d $d.fr
    
    # form_label $d.regionl " Surfaces: " {1 1}
    # form_frame $d.region ridge 2 {2 1 -fill none}
    
    catch {unset aqua_surf}
    foreach ff $fams {
	set f [lindex $ff 0]
	set aqua_surf($f) $family_active($f)
    }
    
    # check_box $d.region $fams 6 aqua_surf 1
    form_label $d.filev "Volume Output File" {3 1}
    form_entry $d.filev_e global_options(aqua_vol) string {3 2}
    form_label $d.files "Surface Output File" {4 1}
    form_entry $d.files_e global_options(aqua_surf) string {4 2}
    
    form_finish +300+300
    
    if ![form_wait .surface] {
	return 0
    }
    
    set fams ""
    foreach f [array names aqua_surf] {
	if $aqua_surf($f) {
	    lappend fams $f
	}
    }
    
    set cmd [list "open_file $global_options(aqua_vol) 1 w"]
    lappend cmd "open_file $global_options(aqua_surf) 2 w"
    lappend cmd {write_volumes 1 i "%d " j "%d " k "%d " nm "%d " ni \
		     "%d\n" x "%g " y "%g " z "%g\n" vi "%d " vj "%d " \
		     vk "%d " vm "%d\n" m "%d " mn "%s " v "%g\n"}
    
    lappend cmd {write_staircase_quads 2 start "%d " vi "%d " vj "%d " \
		     vk "%d " end "\n"}

    lappend cmd "close_file 1"
    lappend cmd "close_file 2"
    
    foreach c $cmd {
	command $c
    }
}

proc file_write_gorf {} {
    global global_options families family_dims family_name
    global family_active form_done_flag last_line gorf_mat
    
    set fams ""
    set vols ""
    foreach f $families {
	lappend fams [list $f -text $family_name($f)]
    }
    
    if {$fams == ""} {
	mess "Error: there are no families available.\n"
	return 0
    }
    
    form_kill .surface   
    set buttons {{Accept {form_accept_hack .surface}}}
    
    set d [form_init .surface "Write Gorf File" anal $buttons]
    form_frame $d.fr sunken 3 {0 0}; set d $d.fr
    
    form_label $d.regionl " Material: " {1 1}
    form_frame $d.region ridge 2 {2 1 -fill none}
    
    catch {unset gorf_mat}
    foreach ff $fams {
	set f [lindex $ff 0]
	set gorf_mat($f) $family_active($f)
    }
    check_box $d.region $fams 6 gorf_mat 1
    
    form_finish +300+300
    
    if ![form_wait .surface] {
	return 0
    }
    
    set fams ""
    foreach f [array names gorf_mat] {
	if $gorf_mat($f) {
	    lappend fams $f
	}
    }
	
    set transdir $global_options(transdir)
    set files ""
    foreach d [glob -nocomplain $transdir/*] {
	lappend files [file tail $d]
    }
    
    set mess "Please select a Gorf file to store the mesh in,\
	    or type a new gorf file name.  These files are in the\
	    transfer directory."
    set filename [choose_one $mess $files "" +300+300]
    if {$filename == ""} return
    
    command "gorf $filename $fams"
}

proc file_read_gorf {read} {
    global display_flag global_options
    
    set transdir $global_options(transdir)
    set files ""
    foreach d [glob -nocomplain $transdir/*] {
	lappend files [file tail $d]
    }
    
    set mess "Please select a Gorf file to $read the mesh from. \
	    These files are in the transfer directory."
    set filename [choose_one $mess $files "" +300+300]
    if {$filename == ""} return
    
    # first delete all index boxes/planes
    
    iplane_update_families_all delete
    
    # now temporarily turn off quad, edge and block displays because
    # staircase mesh will be read in
    
    set temp $display_flag(quad)
    set temp1 $display_flag(edge)
    set temp2 $display_flag(block)
    
    set display_flag(quad) 0
    set display_flag(edge) 0
    set display_flag(block) 0    
    update_display block quad edge scan
	
    command "${read}_gorf_file $filename"
    
    set display_flag(quad) $temp
    set display_flag(edge) $temp1
    set display_flag(block) $temp2
    
    # display everything that weve got in new gorf file
    
    update_index_planes
    add_new_families
    update_display
}

proc file_write_uh3d {} {
    global global_uh3d env uh3d_mat
    global families family_dims family_name family_active
    global form_done_flag last_line global_options
    
    set fams ""
    set vols ""
    foreach f $families {
	if {$family_dims($f) != 3} {
	    lappend fams [list $f -text $family_name($f)]
	}
    }
    
    if {$fams == ""} {
	mess "Error: there are no families available.\n"
	return 0
    }
    
    form_kill .surface   
    set buttons {{Accept {form_accept_hack .surface}}}
    
    set d [form_init .surface "Write surface mesh" anal $buttons]
    form_frame $d.fr sunken 3 {0 0}; set d $d.fr
    
    form_label $d.regionl " Material: " {1 1}
    form_frame $d.region ridge 2 {2 1 -fill none}
    
    catch {unset uh3d_mat}
    foreach ff $fams {
	set f [lindex $ff 0]
	set uh3d_mat($f) $family_active($f)
    }
    check_box $d.region $fams 6 uh3d_mat 1
    
    form_finish +300+300
    
    if ![form_wait .surface] {
	return 0
    }
    
    if [info exists env(UH3D_OUTPUT)] {
	set uh3d_output_path $env(UH3D_OUTPUT)
    } else {
	set uh3d_output_path $env(ICEM_ACN)/icemcfd/output-interfaces/uh3d
    }
    set w [form_init .uh3d "Uh3d Write File" "" "accept cancel"]  
    if {$w != ""} {
	
	# set defaults
	
	set global_uh3d(file) stairm
	set global_uh3d(sc) 1
	
	set meshdir $global_options(meshdir)
	set domdir $global_options(domdir)
	set transdir $global_options(transdir)
	
	# command "get_boco_file" 0
	# if {$last_line != ""} {
	#    set global_uh3d(bf) [lindex $last_line 0]
	# }
	
	set global_uh3d(bf) $meshdir/family_boco
	set global_uh3d(pp) $meshdir/surface_pp
	
	set global_uh3d(df) $domdir/surface_domain.1
	set global_uh3d(uh3d) $transdir/surface_uh3d
	
	# put up form
	
	set row 0
	set spcheight 7
	# form_frame $w.spc0 flat 0 "$row 0 -cols 3"
	# form_rowheight $w $row $spcheight
	incr row
	
	label $w.wfl -text "Write File"
	radiobutton $w.wfsm -text "Staircase Mesh" \
	    -variable global_uh3d(file) -value stairm
	radiobutton $w.wfhg -text "H-Grid Mesh" \
	    -variable global_uh3d(file) -value hgridm
	radiobutton $w.wfpp -text "Pierce Points" \
	    -variable global_uh3d(file) -value pp
	radiobutton $w.wfsr -text "Surface Mesh" \
	    -variable global_uh3d(file) -value surfm
	
	blt_table $w $w.wfl  $row,0 -anchor w
	blt_table $w $w.wfsm $row,1 -anchor w
	blt_table $w $w.wfpp $row,2 -anchor w
	incr row
	
	foreach fe {{df "Domain File"} {pp "Global File"} {bf "Boco File"} \
			{uh3d "Uh3d Output File"}} {
	    
	    set idx [lindex $fe 0]
	    set lab [lindex $fe 1]
	    label $w.$idx -text $lab
	    entry $w.${idx}_e -width 30 -textvariable global_uh3d($idx)
	    $w.${idx}_e xview end
	    
	    set cmd "global_open_file global_uh3d($idx) \"Select a $lab\""
	    button $w.${idx}fb -text "Browse..." -command $cmd	   
	    
	    blt_table $w $w.$idx     $row,0 -anchor w
	    blt_table $w $w.${idx}_e $row,1 -anchor w
	    blt_table $w $w.${idx}fb $row,2 -anchor w
	    incr row
	}
	label $w.sc -text "Grid Size Scaling Factor (to meters)"
	entry $w.sc_e -width 30 -textvariable global_uh3d(sc)
	blt_table $w $w.sc   $row,0 -anchor w
	blt_table $w $w.sc_e $row,1 -anchor w
	incr row
 		
	form_finish +200+100
    }
    
    if [form_wait .uh3d] {
	foreach idx {df pp bf uh3d} {
	    set global_uh3d($idx) [string trim $global_uh3d($idx)]
	}
	
	set fams ""
	foreach f [array names uh3d_mat] {
	    if $uh3d_mat($f) {
		lappend fams $f
	    }
	}
	
	if ![file exists $global_uh3d(bf)] {
	    error "boco file \"$global_uh3d(bf)\" does not exist"
	}
	
	set cmd "$uh3d_output_path -b $global_uh3d(bf) $global_uh3d(uh3d)"
	if {$fams == ""} {
	    mess "No surface families selected!\n" red
	} else {
	    command "uh3d $global_uh3d(pp) 0 $fams"
	    if ![file exists $global_uh3d(pp)] {
		error "Pierce point file \"$global_uh3d(pp)\" was \
 not written."
	    }
	    append cmd " -ifile $global_uh3d(pp)"
	    
	    #set filen [file tail $global_uh3d(df)]
	    
	    set filen $global_uh3d(df)
	    set filet $global_uh3d(file)
	    switch $filet {
		pp {
		}
	
		hgridm -
		stairm -
		surfm {
		    if {$filen == ""} return
		    
		    if {$filet == "hgridm"} {
			set label "h-grid"
			
			if [check_compute_hgrid] {
			    set domcmd "write_hgrid $filen [volume_string]"
			} else {
			    mess "Domain file not written.\n" red
			    return 0
			}
		    } elseif {$filet == "stairm"} {
			set label "Staircase"
			set domcmd "write_unstruct $filen $fams"
		    } else {
			set label "Surface"
			set domcmd \
			    "write_surface_mesh -surf $filen emit_tris $fams"
		    }
		    
		    command $domcmd
		    if ![file exists $filen] {
			error "$label mesh \"$filen\" was not written."
		    }
		    append cmd " -dom $filen"
		}
		
		default {
		    error "Internal Error -- report to ICEM CFD!"
		}
	    }
	    
	    append cmd " -sc $global_uh3d(sc)"
	    eval exec $cmd
	}
    }
    return 1
}

proc global_open_file {var text} {
    upvar $var value
    
    set old_file $value
    set selected [file_select $text $old_file "File Selection" 0 \
		      1 "" "" "" ""]
    
    if {$selected != ""} {
	set value $selected
    }
}

# --------------------------------

proc file_remote {} {
    global global_options
    
    set buts [list "Ok {global_remote_option_done t}" \
		  "{Save local} {global_remote_option_done l}" \
		  "{Save global} {global_remote_option_done g}" \
		  "{Reset} {global_remote_option_done r}" \
		  "Cancel {global_remote_option_done c}"]
    
    set d [form_init .global_remote_options "Options" "" $buts]
    if {$d != ""} {
	form_frame $d.fr sunken 2 {0 0}; set d $d.fr
	form_label $d.hostl "Remote host" {0 0}
	form_label $d.userl "User on remote host" {1 0}
	form_label $d.binl  "Remote path to global" {2 0}
	form_label $d.cdirl "Remote path to current dir" {3 0}
	form_label $d.dirl  "Remote path to local geometry dir" {4 0}
	form_label $d.cartl "Cart file name" {5 0}
	form_label $d.iacml "Remote ICEM_ACN" {6 0}
	form_label $d.licl  "Remote LM_LICENSE_FILE" {7 0}
	form_label $d.exel  "Processes to Remotely Execute" {8 0}
	
	# make sure # cols matches the number of remote executes
	
	set ncols "-cols [llength $global_options(remote_executes)]"
	form_entry $d.host  global_options(remote) string "0 1 $ncols"
	form_entry $d.user  global_options(ruser) string "1 1 $ncols"
	form_entry $d.bin   global_options(bin) string "2 1 $ncols"
	form_entry $d.cdir  global_options(curdir) string "3 1 $ncols"
	form_entry $d.dir   global_options(meshdir) string "4 1 $ncols"
	form_entry $d.cart  global_options(cart_file_name) string "5 1 $ncols"
	form_entry $d.iacm  global_options(icemacn) string "6 1 $ncols"
	form_entry $d.lic   global_options(license) string "7 1 $ncols"
	
	set i 1
	foreach r $global_options(remote_executes) {
	    form_checkbutton $d.[string tolower $r] $r global_options($r) \
		"8 $i"
	    incr i
	}
	$d.host configure -width 45
	form_finish top
    }
}

proc global_remote_option_done {how} {
    global global_options
    
    switch $how {
	c {
	    form_reset .global_remote_options;
	    form_done .global_remote_options;
	    return
	}
	t { set file "" }
	l { set file .global_config }
	g { set file .global_config }
	r { global_option_defaults; return }
    }
    form_done .global_remote_options
    
    if {$file == ""} return
    
    global_configuration_write
    mess "Configuration options saved."
}
