
# This code creates the user interface for the hexa mesher.
#
# 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_same { path1 path2 } {
    if { [ file pathtype $path1 ] == "relative" } {
	set path1 "[ pwd ]/$path1"
    }

    if { [ file pathtype $path2 ] == "relative" } {
	set path2 "[ pwd ]/$path2"
    }
    if { $path1 == $path2 } {
	return 1
    } else {
	return 0
    }
}

proc file_load {{init 0}} {
    global mesh_dir blocking_file save_needed  index_max_limit
    
    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 0
    }
    
    set filename [select_blocking_file $init]
    if {$filename == ""} {
	if !$init {
	    mess "Cancelled load blocking.\n" red
	}
	return
    }
    if { $filename == "__no_blocking__" } {
	set blocking_file ""
	if {!$init} {
		command "initialize_mesh new_numbering"
		get_indices 1
		reset_families
		if {$index_max_limit(2) == 1} {
		    block_set_material {1 1 0} {2 2 1}
		} else {
		    block_set_material {1 1 1} {2 2 2}
		}

		update_display
		top_clear_list
		catch {unset save_needed}
		set_scan_plane_state
	}
	return
    } elseif { $filename == "-init_2d" } {
	set blocking_file "-init_2d"
	return
    }


    if { [file exists $filename] == 0 } {
	mess "no such file" red
	return
    }


    set tail [ file tail $filename ]
    if { [ file_same $filename $mesh_dir/$tail ] } {
	set filename $tail
    }


    if {!$init} {
	command "restore_blocking $filename"
	get_indices 1
	add_families
	update_display
	top_clear_list
	catch {unset save_needed}
	set_scan_plane_state
    }
    
    set blocking_file $filename
    set_title "Blocking: [file tail $blocking_file]"
}

proc select_blocking_file {start_with_no} {
    global mesh_dir blocking_file save_needed
    
    set mess2 ""
    if $start_with_no {
	set mess2 \
	"\nFor initial blocking, select Initialize 2D or Initialize 3D."
    }
    
    set mess "Please select a blocking file to load.$mess2"
    
    set nn [file_select_rel $mess $mesh_dir "Select blocking file" 0 -1 \
		file_is_blocking "" {on_side select_blocking_extra_widgets} \
		{has_suffix "Blocking (.blk)" .blk }  blocking_file_put]
    return $nn
}


proc select_blocking_extra_widgets {d} {
    global blocking_file_picture_frame
    
    form_frame $d.picture flat 0 {0 0}
    $d.picture configure -width 275 -height 175
    set blocking_file_picture_frame $d.picture
}

proc blocking_file_put {file} {
    global blocking_file_picture_frame
    
    if [ file exists $file.ppm ] {
    	set pict $file.ppm
    } else { 
	set pict [ file rootname $file].ppm
    }
    set iml $blocking_file_picture_frame.im
    if [file exists $pict] {
	if [winfo exists $iml] {
	    set im [$iml cget -image]
	    image delete $im
	} else {
	    label $iml
	    pack $iml
	}
	if ![catch {image create photo -file $pict} im] {
	    $iml configure -image $im
	} else {
	    mess "Error with image file $pict: $im\n" red
	    destroy $iml
	}
    } elseif [winfo exists $iml] {
	set im [$iml cget -image]
	image delete $im
	destroy $iml
    }
}

proc file_load_compare {ff1 ff2} {
    return [expr {[lindex $ff2 1] - [lindex $ff1 1]}]
}

proc file_delete_block {name} {
    global mesh_dir
    
    set path $mesh_dir/[lindex $name 0]
    
    set mess "Delete blocking file \"$path\"?"
    if ![tk_dialog .delfile "Delete file" $mess "" -1 "Yes" "No"] {
	cmd_rm $path
	return 1
    }
    return 0
}
proc file_delete_domain {name} {
    global domain_dir domain_name
    
    set path $domain_dir/[lindex $name 0]
    
    set mess "Delete blocking file \"$path\"?"
    if ![tk_dialog .delfile "Delete file" $mess "" -1 "Yes" "No"] {
	cmd_rm $path
	return 1
    }
    return 0
}

proc file_save {subtopo} {
    global mesh_dir blocking_file save_needed tetin_save_needed tetin_file
    global file_blocking_save_pict env famboco_save_needed
    global file_format40 last_line config_dir
    
    set sub_opt ""
    if $subtopo {
	# mess "Please select the sub-topology to save.\n"
	# set sub_opt " -sub_topo [top_select_toponame]"
	set sub_opt " -sub_topo [top_get_current]"
    }
    set files [glob -nocomplain $mesh_dir/*]
    set block_files ""
    foreach f $files {
	if {![file readable $f] || [file isdirectory $f]} continue
	set t [file tail $f]
	set fp [open $f r]
	set line [gets $fp]
	if {$line == "MATERIALS"} {
	    lappend block_files $t
	}
	close $fp
    }
    
    if { ! [ info exists file_blocking_save_pict ] } {
    	set file_blocking_save_pict 0
    }
    if { ! [ info exists file_format40 ] } {
    	set file_format40 0
    }
    set mess "Please select a blocking file to save\n\
	      to, or enter a new name."
    
	
    set filename [ file tail $blocking_file ]
    if { $filename == "" } {
	set skiplist "mulcad parts_mesh"
	if { [ file pathtype $config_dir ] == "absolute" } {
		append skiplist " [ string tolower [ file split [ pwd ] ] ]"
	}
	foreach i [ file split $config_dir ] {
		if { [ lsearch $skiplist [ string tolower $i ] ] == -1 }  {
			set filename $i
			if { [ file extension $filename ] != ".blk" } {
				set filename "${filename}.blk"
			}
			break
		}
	}
    }
    set oldname $filename
    set filename [file_select_rel $mess $mesh_dir/$filename \
			"Select blocking file" \
		      0 1 file_is_blocking "" save_blocking_extra_widgets \
			{has_suffix "Blocking (.blk)" .blk } ]
    if {$filename == ""} {
	mess "Cancelled save blocking.\n" red
	return
    }
    if { [ file tail $filename ] != $oldname && \
		[ file extension $filename ] != ".blk" } {
	mess "Saving as $filename.blk\n"
	set filename $filename.blk
    }
    
    if {[file exists $filename] && \
	    !([info exists blocking_file] && ($blocking_file == $filename))} {
	if [tk_dialog .over "Overwrite file" \
		"Overwrite existing blocking file \"$filename\"?" \
		"" -1 "Yes" "No"] return
    }
    
    if $file_blocking_save_pict {
	set pictfile [ file rootname $filename].ppm
	
# Save the picture in ppm format to this file
	command "write_ppm_file $pictfile"
	if { $last_line == "" } {
		exec $env(ICEM_ACN)/bin/pnmscale .25 < $pictfile > $pictfile.temp
		exec mv $pictfile.temp $pictfile
	} else {
		mess "picture of blocking not saved\n"
	}
		
    }

    set tail [ file tail $filename ]
    if { [ file_same $filename $mesh_dir/$tail ] } {
        set filename $tail
    }
    
    set cmd "save_blocking $filename$sub_opt"
    if { $file_format40 } {
	append cmd " format40"
    }
    command $cmd
    set blocking_file $filename
    set_title "Blocking: [file tail $blocking_file]"
    catch {unset save_needed}
    
    if [info exists tetin_save_needed] {
	set t $tetin_file
	if {$t == ""} { set t tetin1 }
	set mess "Tetin file has been modified -- save ?"
	if ![tk_dialog .save "Tetin file modified" $mess "" -1 "Yes" "No"] {
	    set t [file_select_rel $mess $mesh_dir/$t \
                        "Select tetin file" 0 1]
	    if { $t != "" } {
	    	cmd_rm $mesh_dir/$tetin_file.bak
	    	cmd_cp $mesh_dir/$tetin_file \
			$mesh_dir/$tetin_file.bak
	    	mess "Copied old tetin file to $tetin_file.bak\n"
	    	command "write_tetin_file $t"
	    	unset tetin_save_needed
		catch {unset famboco_save_needed}
	    }
	}
    } elseif [info exists famboco_save_needed] {
	set mess "Boundary conditions modified -- save ?"
	if ![tk_dialog .save "Boundary conditions modified" \
		 $mess "" -1 "Yes" "No"] {
		     command "write_family_boco"
		     unset famboco_save_needed
		 }
    }
    
    mess "Blocking saved at [cmd_date]\n" red
}

proc save_blocking_extra_widgets {d} {
    form_checkbutton $d.savepick "Save picture of blocking" \
	file_blocking_save_pict {0 0}
    form_checkbutton $d.format40 "Format 4.0" file_format40 { 1 0 }
}

proc file_options {} {
}

proc file_import {} {
}

proc file_dirty {} {
    global save_needed
    set save_needed 1
}

proc file_quit {{ask 1}} {
    global save_needed process_ident env
    
    set okay [info exists process_ident]

    if $ask {
	if [info exists save_needed] {
	    file_save 0
	}
	if [tk_dialog .quit "Quit" "Really quit?" "" -1 "Yes" "No"] return
    }

    if [info exists env(ICEM_AI_ENVIRONMENT)] {
       namespace eval ::AIEnv::GUIManagement {
         global env
         source $env(ICEM_ACN)/lib/ai_env/scripts/aie_javahelp.tcl
       }
       ::AIEnv::GUIManagement::hlp_sendcommand QUIT
    }

# turn off the replay stuff
    replay_done

# have to unlink the undo files
    command "undo stop"
    set logs [glob -nocomplain logfile.*]
    if {$logs != ""} {
	if $okay {
	    eval cmd_rm $logs
	} else {
	    puts "Logfiles saved, since there was an abnormal termination.\n"
	    puts $logs
	}
    }

# quit will kill us on the pc
    command quit

    mess "tcl exiting\n"
    exit 0
}

proc file_edit_boco {} {
    global all_lines famboco_data famboco_info famboco_save_needed
    global famboco_edit fam_visible file_name mesh_dir
    
    command "list_families bocos" 0
    catch {unset famboco_data}
    catch { unset fam_visible }
    foreach line $all_lines {
	# Do this first
	set f [lindex $line 0]
	if {$f == "__PARAMS__"} continue
	set famboco_data($f) ""
	set fam_visible($f) 1
    }
    foreach line $all_lines {
	set f [lindex $line 0]
	if {$f == "__PARAMS__"} continue
	
	set rest [lrange $line 1 end]
	if {$rest != ""} {
	    lappend famboco_data($f) [concat 1 $rest]
	}
    }
    
    if ![info exists famboco_info(solver)] {
	set sol ""
    } else {
	set sol $famboco_info(solver)
    }
    
    get_solver_info
    set file_name(mesh_dir) $mesh_dir
    
    set mod [famboco_edit $sol ""]
    
    if [info exists famboco_edit(solver)] {
	set famboco_info(solver) $famboco_edit(solver)
    }
    
    if !$mod {
	mess "Boundary conditions not modified\n" red
	return
    }
    
    command clear_bocos
    foreach f [array names famboco_data] {
	puts $f
	set any_bocos 0
	foreach b $famboco_data($f) {
	    command "add_boco $f [lrange $b 1 end]"
	    set any_bocos 1
	}
# and an empty boundary condition to create a family.
	if { $any_bocos == 0 } {
	    command "add_boco $f"
	}
    }
    set famboco_save_needed 1
}

proc old__file_edit_boco {solver} {
    global mesh_dir
    
    set boco $mesh_dir/boco
    boco_load $boco
    if $solver {
	boco_edit_sol_new_format $boco
    } else {
	if [boco_edit] {
	    boco_save $boco
	}
    }
    command "read_bocofile $boco"
}

proc file_unput {} {
    global save_needed env mesh_dir tetin_file black_and_white use_xwindows
    global config_dir
    
    if [info exists save_needed] {
	file_save 0
    }
    if [tk_dialog .unput "Quit Hexa" "Really quit hexa and start unput?" \
	    "" -1 "Yes" "No"] return
    command quit
    
    set prog $env(ICEM_ACN)/icemcfd/unput_gui
    set args "-descdir $mesh_dir -domdir $config_dir/import \
	    -desc [file tail $tetin_file]"
    set x ""; set bw ""
    if $black_and_white { set bw -bw }
    switch $use_xwindows {
	1 { set x -x }
	2 { set x -ogl }
    }
    eval exec $prog $bw $x $args &
    after 1000
    exit 0
}

proc file_multiblock {} {
    global project_type tagging_file mesh_dir use_output_blocks
    global last_line use_file_suffixes mesh_dir domain_dir domain_name
    
    mesh_up_to_date 0
    
    command mesh_dimension
	
    set only_sub ""

    set res 0
    if { $last_line == "3" } {
# for volume meshes check if only surface is wanted
        set res \
	[tk_dialog .only_sub "Multiblock" "Write out which kind of domains?" \
	    "" -1 Volume Surface Cancel]
        if {$res == 2} return
    }
    
    set cmd "multi_block [family_activename_string] proj $project_type"
    if $res { append cmd " only_subfaces" }
    if $use_output_blocks { append cmd " output_blocks" }
    if $use_file_suffixes {
	lappend cmd -family_boco family_boco.fbc \
	    -family_topo family_topo.fto \
	    -topo_mulcad_out topo_mulcad_out.top
    }
    
    command $cmd
    
    if {$tagging_file != ""} {
	mess "Warning: you should write a 2D unstructured mesh for\
		tagging.\n" red
    }
    # So leo will know that it has to recreate it ...
    catch {cmd_rm $mesh_dir/family_ref}
}

proc file_unstructured {} {
    global project_type tagging_file unstruct_ogrid_dir
    global domain_dir domain_name use_file_suffixes mesh_dir
    
    mesh_up_to_date 0
    
    set def hex.uns
    if {$domain_name != ""} {
        set def $domain_name.uns
    }
    if { [ file tail $def ] == $def } {
	set def $domain_dir/$def
    }
    set file [ file_selection -message \
		"Enter domain file to save the unstructured mesh\n\
                (in the directory $domain_dir).\n\
		Note that only the currently active volume families\n\
		will be written." \
		-default $def  \
		-new_ok 1 -warn_overwrite 2 \
		-extra_widgets file_unstructured_extra_widgets ]

#    set file [choose_one "Enter domain file to save the unstructured mesh\
#	    (in the directory $domain_dir).  Note that only the\
#	    currently active volume families will be written." \
#	    {} $def +300+300 "" file_unstructured_extra_widgets]

    if {$file == ""} return
    
    set og ""
    if {[info exists unstruct_ogrid_dir] && ($unstruct_ogrid_dir != "")} {
	set og "ogrid_dir $unstruct_ogrid_dir"
    }
    if { [ file dirname $file ] == $domain_dir  } {
	set file [ file tail $file ]
    }
#    if { [ file tail $file ] == $file } {
#	set file $domain_dir/$file
#    }
    set cmd "save $file [volume_activename_string] proj $project_type $og"
    if $use_file_suffixes { 
		append cmd " -family_boco family_boco.fbc"
    }
    
    command $cmd
    
    if {$tagging_file != ""} {
	mess "Warning: you should write a 2D unstructured mesh for\
		tagging.\n" red
    }
}

proc file_unstructured_extra_widgets {w} {
    button $w.selo -text "Select first O-grid direction" -command {
	set mess "Pick the O-grid edge that should begin the ordering;\
		$button_instructions"
	set unstruct_ogrid_dir [lindex [select_edge $mess] 1]
    }
    pack $w.selo -anchor w -padx 2 -pady 2
}

proc file_unstruct2d {} {
    global project_type tagging_file domain_dir domain_name
    
    mesh_up_to_date 0
    
    set def quad.uns
    if {$domain_name != ""} {
        set def $domain_name.uns
    }
    if {$tagging_file != ""} { set def $tagging_file }

    set def $domain_dir/[ file tail $def ]
    mess "def = \"$def\"\n"
    set file [ file_selection -message \
		"Enter domain file to save the 2D unstructured mesh\n\
            (in the directory $domain_dir).  Note that only the\n\
            	currently active IJK range and volume families will\n\
		be written." \
                -default $def  \
                -new_ok 1 -warn_overwrite 2 \
                -extra_widgets file_unstructured_extra_widgets ]
if { 0 } {
    set file [choose_one "Enter domain file to save the 2D unstructured mesh\
	    (in the directory $domain_dir).  Note that only the\
	    currently active IJK range and volume families will be written." \
	    {} $def]
}
    if {$file == ""} return
    if { [ file dirname $file ] == $domain_dir  } {
    	set file [ file tail $file ] 
    }
    
    command "save [volume_activename_string] $file proj $project_type\
  [range_string] only_quads"
}


proc file_select_unstruct { type } {
	global env tetin_file domain_dir domain_name

	set dtprog1 $env(ICEM_ACN)/icemcfd/domaintypes

	set files [glob -nocomplain $domain_dir/* ]

	set cmd \"$dtprog1\"

	cmd_rm dtypes_domain_list
	set fp [open dtypes_domain_list w]
	foreach d $files {
		puts $fp $d
	}
	close $fp

	set results [eval exec $cmd -dom_list dtypes_domain_list]

	set unstruct ""
	set num 0
	foreach file $files {
		set dtype [lindex $results $num]; incr num
		if { $dtype == "UNSTRUCTURED" }  {
			lappend unstruct [file tail $file]
		}
	}
	if { $type == "hexa" } {
		set mess "Please select an unstructured hexahedral domain file \
		    from which to load the blocking. You can delete\
		    domain files using the \"Delete\" button once you have\
		    selected them."
	} else {
		set mess "Please select an unstructured tetrahedral domain \
		    file from which to load \
		    the blocking. You can delete\
		    domain files using the \"Delete\" button once you have\
		    selected them."
	}
	set ustr_domain [choose_one $mess $unstruct "" \
            +300+300 file_delete_domain]
	return $ustr_domain
}

proc file_read_struct {} {
	global use_output_blocks

	set cmd "read_domains  [family_activename_string]"
	if { $use_output_blocks } {
		append cmd " -output_blocks"
	}
	command $cmd
	update_display mesh
}
proc file_read_unstruct {} {
	global env mesh_dir tetin_file is_win domain_dir domain_name mesh_dir

	puts "in file_read_unstruct"
	set ustr_domain [ file_select_unstruct hexa ] 

	if { $ustr_domain == "" } return

	if [ file exists $mesh_dir/topo_mulcad_out ] {
		set topo "-m $mesh_dir/topo_mulcad_out"
	} else {
		set topo ""
	}
# now translate to hexa
# ../mesh2block/mesh2block.mips4
	set command " \"$env(ICEM_ACN)/icemcfd/mesh2block\"  \
		-d $domain_dir -a $mesh_dir/$tetin_file \
		$topo \
		$domain_dir/$ustr_domain \
		$mesh_dir/__temp_blocking__"
	mess "$command\n"
	set logfile mesh2block.log
        set cmdfile mesh2block.cmd
	if $is_win {
		eval exec $command >& $logfile &
        } else {
            set fp [open $cmdfile w]
            puts $fp "\#!/bin/csh -f"
            puts $fp $command
            close $fp
            exec chmod 0755 $cmdfile
            exec ./$cmdfile >& $logfile &
        }
# Now wait for the log file.
        for {set i 0} {$i < 60} {incr i} {
            if [file exists $logfile] break
            after 1000
        }
        if {$i == 60} {
            mess "Error: mesh2block didn't start -- can't find log file\n" red
            return
        }
        mess "Mesh2block is running: logfile = [file tail $logfile].\n"

        if [file exists $logfile] {
            if ![show_logfile $logfile .mesh2block_monitor Mesh2block "mesh2block finished" ] {
                mess "Mesh2block exited abnormally\n"
                return
            }
        }

	command "restore_blocking __temp_blocking__"
	command "update_association root"
	get_indices 1
# read in the domains
	file_read_struct


	exec rm $mesh_dir/__temp_blocking__

	update_display
}
proc file_superdomain {} {
    
    set mess " To write a superdomain, please save the mesh as\n\
		Multiblock, then use the Struct -> Super utility\n\
		in the ICEM CFD Mesh Editor."
    
    tk_dialog .sup "Superdomains" $mess "" -1 Ok
    return
    
    
    global project_type tagging_file domain_dir domain_name
    
    mesh_up_to_date 0
    
    set def hex.super
    if {$domain_name != ""} {
        set def $domain_name.uns
    }
    set file [choose_one "Enter domain file to save the superdomain mesh\
	    (in the directory $domain_dir).  Note that only the\
	    currently active volume families will be written." \
	    {} $def]
    if {$file == ""} return
    command "superdomain $file proj $project_type [range_string]"
    
    if {$tagging_file != ""} {
	mess "Warning: you should write a 2D unstructured mesh for\
		tagging.\n" red
    }
}

proc file_renew {} {
    command "renew"
    update_display edge face block mesh
}


proc file_shell { dir } {
    global mesh_dir
    
    mess "Opening shell window in mesh directory ..."
    set here [pwd]
    cd $mesh_dir
    catch { cmd_xterm -sb -geometry +0+0 & }
    cd $here
}


proc get_mesh_dir { } {
	global mesh_dir
	return $mesh_dir
}
