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

set tool_id med

if {[info exists env(MED_DIR)]} {
    set tool_dir $env(MED_DIR)
} else {
    set tool_dir $env(MED_ROOT)/lib/med_gui
}
set tool_dir_cvs $env(MED_ROOT)
set tool_dir2 $tdv_library
set batch_dir [file dirname $tool_dir]/med_batch

set v3_batch_dir [file dirname $tool_dir]/v3p_batch
set vpost_batch_library [file dirname $tool_dir]/vpost_batch
set v3_gui_dir [file dirname $tool_dir]/v3p_gui

lappend source_dirs $batch_dir

set bindir $env(ICEM_ACN)/bin

set vpost_library $vpost_batch_library
if ![file exist $vpost_library] {
   set vpost_library $env(ICEM_ACN)/lib/vpost
}

set no_all_interaction_button 1
set banner_disables_menus 1
set unknown_options_are_tool_arguments 1

set env(ICEM_CASE_SENSITIVE) y
if ![info exists env(MOZILLA_HOME)] {
    set env(MOZILLA_HOME) $env(ICEM_ACN)/netscape
}

if {!$batch_mode && [file exists $tool_dir/../bwidget]} {
    lappend auto_path $tool_dir/../bwidget
    package require -exact BWidget 1.3.1
} elseif {!$batch_mode && [file exists $tool_dir_cvs/../bwidget]} {
    lappend auto_path $tool_dir_cvs/../bwidget
    package require -exact BWidget 1.3.1
}

set auto_raise_forms 1			

# This is so that the old GUI will still work
set tdv_default .v.view
set tdv_current_viewer .v.view
set tdv_last_viewer_clicked .v.view

set mode med
set script_file ""
if ![info exists va_script_file] {
set va_script_file ""
}
set initial_domain_file ""
set initial_tetin_file ""
set did_merge 0
set cart_file ""
set cartfile_visible 0
set parts_dir_local 0
set part_selected ""
set family_boco ""
set extra_med_menu_file ""
set no_standard_menus [info exists env(ICEM_NO_STANDARD_MED_MENUS)]
set ddn_part_selected_sheetnumber 1
set mulcad_type_directory 0
if $is_win {
    # There is a Tk bug on windows
    set mess_win_font variable
}

set default_project_parent mulcad
set default_subproject_name ""
#set default_subproject_name parts_mesh
#set default_project_parent icemcfd
#set default_subproject_name default

set tool_options {
    { -mode mode 1 }
    { -script script_file 1 }
    { -va va_script_file 1 }
    { -domain initial_domain_file 1 }
    { -tetin initial_tetin_file 1 }
    { -med_root med_root_ignore_value 1 }
    { -no_standard_menus no_standard_menus "" }
    { -4 version_4_mode_ignored_here "" }
    { -menus extra_med_menu_file 1 }
    { -mulcad mulcad_type_directory "" 0 }
}

set tool_files {
    file_med
    options_med
    ddn_med
    cad_trans_med
    geometry_med
    geomodify_med
    edit_med
    mesher_med
    struct_med
    glsm_med
    nspacking_med
    import_med
    unstruct_med
    uncouple_med
    smooth_med
    solution_med
    unsmap_med
    diag_med
    view_med
    disp_med
    geodisp_med
    strdisp_med
    unsdisp_med
    select_med
    select_struct
    select_unstruct
    params_med
    domain_med
    hardcopy_med
    license_med
    locking_med
    cartfile_med
    sysinfo
    prism
    pcube_med
    sparams
    domselect
    replay_med
    csystem_med
    convex_hull
    mesh_direct

    start_v3p
    
    ../rmi/rmi_params
    ../rmi/rmi_misc
    ../rmi/rmi_file
    ../rmi/rmi_app
    ../rmi/rmi_gui
    ../rmi/rmi
    
    ../vpost/anno
    ../vpost/anno3d
    ../vpost/vpost_plot
    ../vpost/anno_mg
    ../vpost/utf_misc
    ../vpost/dfile_misc
    med_ezcad
    cart3d
}

    #../vpost/bitmap_optionMenu JKA file seems not to exist
    #../vpost/anno_misc JKA file seems not to exist

set tool_files2 {
    viewer
    wb_binding
}

set guibase_files_extra {
    bocofile
    boco_solver
    family_files
    colormap
    exec_cmds
    dialog
    interrupt
    game
    flexlist
    family_boco
    makedoc
    query
    replay
    select_geom
    select_sub
    run_application
    csystem
    curve

    batch_glue
}

set options(select_mode) all

set prog_guide_files { forms exec_cmds geometry_funcs geom_vid_funcs translation_funcs display_funcs}
set no_remove_after_digest { sparams }

proc tool_command {} {
    return ""
}

# stuff for both interactive and batch mode

proc setup_common {} {
    global tool_arguments batch_mode script_file va_script_file env lm_license_file
    global data_available startup_message license_message initial_domain_file
    global file_name options licensing_flags batch_mode
    global prog_guide_files batch_dir
    
    setup_batch_interp
    
    foreach f [glob $batch_dir/*_funcs.tcl] { lappend prog_guide_files $f }
    
    file_option_read_old_modals
    
    # This resets the button active status.
    array set data_available {
	struct 0 unstruct 0 geom 0 mesh 0 none 0 geom_facet 0 
    }
    
    # First see what we can do about licenses.
    set lic $env(ICEM_ACN)/lic/license.dat
    if [info exists env(LM_LICENSE_FILE)] {
	set lm_license_file $env(LM_LICENSE_FILE)
	set lic $lm_license_file
    }
    if [catch {enable_licenses $lic $licensing_flags} err] {
	if !$batch_mode {
	    puts $err
	}
	mess $err\n red
	return
	
	if 0 {
	    this is not good
	    mess "Warning: checking license: $err\n" red
	    if [catch {license_start} res] {
		mess $res\n red
		puts $res
		return
	    }
    	}
    }
    if [info exists startup_message] {
	mess "$startup_message\n"
    }
    if [info exists license_message] {
	mess "$license_message\n"
	if !$batch_mode { puts $license_message }
    }
    
    reset_options
    ic_undo_start

    if !$batch_mode {
        #setup_v3_menu
    }
}

# There are probably too many ways to specify the menus file.

proc tool_source_extra_files {} {
    global extra_med_menu_file tool_dir no_standard_menus env
    
    if !$no_standard_menus {
	if [info exists env(ICEM_MED_MENUS_FILE)] {
	    source $env(ICEM_MED_MENUS_FILE)
	} else {
	    if [info exists env(ICEM_MED_MENUS_SUFFIX)] {
		set suff $env(ICEM_MED_MENUS_SUFFIX)
	    } else {
		set suff med
	    }
	    source $tool_dir/menus_$suff.tcl
	}
    }
    if 0 {
	# i have moved this into the condition above, since
	# the standard menu was getting used instead of it.
	# but, i'm not sure there is not more exclusion here. --jka
	if [info exists env(ICEM_MED_MENUS_FILE)] {
	    source $env(ICEM_MED_MENUS_FILE)
	}
    }
    if [file exists $env(HOME)/.icemcfd_menus] {
	source $env(HOME)/.icemcfd_menus
    }
    if [file exists ./.icemcfd_menus] {
	source ./.icemcfd_menus
    }
    if {$extra_med_menu_file != ""} {
	source $extra_med_menu_file
    }
}

proc tool_setup {} {
    global tool_arguments batch_mode script_file va_script_file env lm_license_file
    global data_available startup_message license_message initial_domain_file
    global file_name options licensing_flags select_old_style 
    global is_win tcl_console initial_tetin_file script_args
    global mulcad_type_directory solution solver_info
    
    if {[file exists ./.icemcfd_expert] || \
	    [file exists [home_directory]/.icemcfd_expert]} {
	set options(expert) 1
    }
    
    setup_common
    
    if {!$batch_mode && $is_win} {
	set tcl_console 0
	tcl_console_update
    }
    
    if {!$batch_mode} {
         last_message
         last_message_ok
    }
    
    if {[llength $tool_arguments] > 1} {
	error "Usage: med \[ options \] \[ file_name \]"
	
    } elseif {[llength $tool_arguments] > 0} {
	set arg [lindex $tool_arguments 0]
	regsub -all \\\\ $arg / arg
	
	if [file isfile $arg] {
	    if {[domain_types $arg] != "bad"} {
		open_initial_domain_file $arg
	    } else {
		file_openproject $arg 
	    }
	    
	} elseif {[string match */* $arg] &&
		  [file isdirectory [file dirname $arg]] &&
		  ([file tail $arg] == "multi")} {
	    open_initial_domain_file [file dirname $arg]
	    
	} else {
	    if ![string match */* $arg] {
		set tool_arguments [find_project $arg]
	    }
	    set select_old_style [string match mulcad/* $arg]
	    if {($script_file == "") && ($va_script_file == "")} {
	        if {$initial_domain_file != ""} {
	            open_initial_domain_file $initial_domain_file
	        }
	        if {$initial_tetin_file != ""} {
	            open_initial_tetin_file $initial_tetin_file
	        }
		file_openproject $arg
	    }
	}
    } elseif $batch_mode {
	error "No job specifed on command line."
	
    } elseif {($initial_domain_file != "") || ($initial_tetin_file != "")} {
	if {$initial_domain_file != ""} {
	    open_initial_domain_file $initial_domain_file
	}
	if {$initial_tetin_file != ""} {
	    open_initial_tetin_file $initial_tetin_file
	}
	
    } else {
	if $mulcad_type_directory { cmd_mkdir mulcad }
	if {($script_file == "") && ($va_script_file == "")} { file_openproject }
    }
#    file_replay
    if {$script_file != ""} {
	script_interp eval source $script_file
    }
    if {$va_script_file != ""} {
	source $va_script_file
    }
    if !$batch_mode {
        # Load default solver for all projects 
        if {[info exists options(default_solver)] && \
            $options(default_solver) != "" && \
            [info exists options(auto_load_default_solver)] && \
            $options(auto_load_default_solver)} {
            if {[info exists solution(solver)] && $solution(solver) == ""} {
                if ![info exists solver_info] {
                    get_solver_info
                }
                solution_set_solver $options(default_solver) 1
            }
        }
        # Load mouse bindings for all projects 
        if {[info exists options(auto_load_mouse_bind)] && \
            $options(auto_load_mouse_bind)} {
            if [file exists [home_directory]/.icemcfd_mouse_bindings] {
                if [file readable [home_directory]/.icemcfd_mouse_bindings] {
                    source [home_directory]/.icemcfd_mouse_bindings
                }
            }
        }
    }
    if {[info command va_load_init] != ""} { va_load_init }
    
    if ![ic_geo_is_loaded] ic_empty_tetin
# Old GUI default: No preview. May be turned ON in EZ-CAD 
	set ::vam_events(do_onMotion) 0
}

# Yuriy: Configure VA menu entries
proc va_load_init {} {
  global env
  
  if ![winfo exists .v.top.panel2.output.va] return
  
  set w .v.top.panel2.output.va
  
  set va_list [file join $env(ICEM_ACN) lib va va_list]
  if {![file exists $va_list] || ![file readable $va_list]} { 
    $w configure -state disabled
    return
  }
  
  set va_act_list ""
  set va_lic_list ""
  set va_dis_list ""
  set fin [open $va_list]
  while {[gets $fin txt] >= 0} {
    set name [lindex $txt 0]
    set fea  [lindex $txt 1]
    set dname [file join $env(ICEM_ACN) lib va $name]
    set fname [file join $dname src [string tolower $name]]
    if {![file exists $dname] || ![file isdirectory $dname]} {
      lappend va_dis_list $name
      continue
    }
    if {![file exists $fname] || ![file readable $fname]} {
      lappend va_dis_list $name
      continue
    }
      if 0 {
	  # This is too slow for some reason - too many round trips to the
	  # flexlm server?  We need to speed it up but for now don't do
	  # the check -Wayne
	  if {[info command verify_license_available] == ""} {
	      lappend va_act_list $name
	      continue
	  }
	  if {![verify_license_available $fea]} {
	      lappend va_lic_list $name
	      continue
	  }
      }
    lappend va_act_list $name
  }
  close $fin
  
  foreach va_name [lsort -dictionary $va_act_list] {
    $w.m add command -label [string toupper $va_name] -command "va_load_va $va_name"
  }
  foreach va_name [lsort -dictionary $va_lic_list] {
    $w.m add command -label [string toupper $va_name] -foreground pink \
                     -activeforeground red -command { beep; mess "License is not available" red }
  }
  foreach va_name [lsort -dictionary $va_dis_list] {
    $w.m add command -label [string toupper $va_name] -state disabled
  }
}

# Yuriy: Actual loading selected vertical application
proc va_load_va {va_name} {
  global env

  source [file join $env(ICEM_ACN) lib va $va_name src [string tolower $va_name]]
  if {[info command va_main] == "va_main"} {
#    .v.top.panel2.output.va configure -state disabled
    va_main
  }
}

proc do_batch_job {type} {
    global script_file file_name
    
    setup_common
    
    foreach d [array names file_name] {
	if {[string match *_dir $d] && ($file_name($d) == "")} {
	    set file_name($d) .
	}
    }
    
    if {$script_file == ""} {
	return 0 ;# don't exit
    }
    if { ! [ file exists $script_file ] } {
	mess "No such file $script_file\n"
	return 0
    }
    source $script_file
    return 1
}

proc open_initial_domain_file {file} {
    global file_name
    
    if {[file isdirectory $file] && [file exists $file/domain.1]} {
	set proj [file dirname $file]
#	set_project_dir $proj
	ic_load_struct $proj/domains $proj/mesh $proj/mesh $proj/mesh
	set_title "ANSYS ICEM CFD : multiblock"
    } else {
#	set_project_dir .
	set uns [ gui_load_domains $file 3]
	if {$uns == ""} return

	set_title "ANSYS ICEM CFD : domain $file"
    }
    tdv_home .v.view
    
    set file_name(domain) $file
    set file_name(domain_loaded) 1
    set file_name(domains_dir) [file dirname $file]
    if {$file_name(project_dir) == ""} {
	set file_name(project_dir)  [file dirname $file]
    }
}

proc open_initial_tetin_file {file} {
    global file_name
    
    set pa [tdv_active 0]
    file_do_load_tetin [list $file]
    tdv_home .v.view
    set_title "ANSYS ICEM CFD : tetin $file"
    tdv_active $pa
    mess "Done loading tetin file.\n"
    display_update geom ; #disp_new_stuff
    
    set file_name(mesh_dir) [file dirname $file]
    if {$file_name(project_dir) == ""} {
	set file_name(project_dir)  [file dirname $file]
    }
}

proc find_project {proj} {
    global default_project_parent default_subproject_name
    
    foreach p [list $proj \
		    icemcfd/$proj/default \
		    projects/$proj/default \
		    mulcad/$proj/parts_mesh \
		    icemcfd/$proj/* \
		    projects/$proj/* \
		    mulcad/$proj/*] {
	set dir [glob -nocomplain $p]
	if {[file exists $dir/mesh] || [file exists $dir/domains]} {
	    return $dir
	}
    }
    # return $default_project_parent/$proj/$default_subproject_name
    return $proj
}

proc make_tool_windows {} {
    make_display_window
}

set orient_buttons {
    { command -label "Home"         -command "tdv_home .v.view" }
    { command -label "Zoom"         -command "tdv_zoomin .v.view" }
    { command -label "Scale to fit" -command "tdv_scale_to_fit .v.view" }
    { command -label "Positive X"   -command "tdv_along_axis .v.view +x" }
    { command -label "Negative X"   -command "tdv_along_axis .v.view -x" }
    { command -label "Positive Y"   -command "tdv_along_axis .v.view +y" }
    { command -label "Negative Y"   -command "tdv_along_axis .v.view -y" }
    { command -label "Positive Z"   -command "tdv_along_axis .v.view +z" }
    { command -label "Negative Z"   -command "tdv_along_axis .v.view -z" }
    { command -label "Isometric"    -command "tdv_isoview .v.view" }
    { command -label "Reverse"      -command "tdv_reverse .v.view" }
    { command -label "Load view" -command "savedview_restore_from_file .v.view" }
    { command -label "Edit view" -command "savedview_edit .v.view" }
    { command -label "Save view" -command "savedview_save_to_file .v.view" }
}
# this does not work quite yet
#    { command -label "Direction"    -command "tdv_view_direction .v.view" }

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

# Note that the following stuff can be overridden by application-specific
# config files.

if ![info exists version] { set version 5.0 }
set tool_name "ANSYS ICEM CFD - MED"

if ![info exists whoami] {
    if [file exists $env(ICEM_ACN)/icemcfd/version] {
	set fp [open $env(ICEM_ACN)/icemcfd/version r]
	set whoami "[gets $fp] - MED"
	close $fp
    } else {
	set whoami "$tool_name version $version"
    }
} else {
    append whoami " $version (MED)"
}

if [file exists $env(ICEM_ACN)/release_date] {
    set fp [open $env(ICEM_ACN)/release_date r]
    set extra_startup_message "Release date: [gets $fp]."
    close $fp
}

set help_base med/med
set help_main_topic base

set language_text_prefix $tool_dir/language_text_med_

set tool_logotext "ANSYS ICEM CFD $version\nMesh Editor"
set tool_logotext_tiny "ANSYS ICEM CFD $version\nMesh Editor"
set tool_logo_relief flat
if ![info exists tool_logo] {
    set tool_logo "[list $tool_dir/med-logo-bits.xbm] \#0000ff \
	[list $tool_dir/med-logo-mask.xbm] \#547eff"
    set tool_logo_small "[list $tool_dir/med-smlogo-bits.xbm] \#0000ff \
	[list $tool_dir/med-smlogo-mask.xbm] \#547eff"
    set tool_logo_tiny "[list $tool_dir/med-smlogo-bits.xbm] \#0000ff \
	[list $tool_dir/med-smlogo-mask.xbm] \#547eff"
}

set enable_feature(ramm-ice) [info exists env(ICEM_RMI)]
set enable_feature(nspack) [info exists env(ICEM_NSPACK)]
set enable_feature(prism_2_3hexa) [info exists env(PRISM_2_3HEXA)]

set med_autohex [info exists env(ICEM_MED_AUTOHEX)]

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

if [info exists env(ICEM_USE_MENUBAR)] {
    lappend tool_files commands_med
    lappend guibase_files_extra commands_guibase
    lappend tool_files dispmenus_med
} else {
    lappend tool_files oldmenus_med dispmenus_med
}

if $med_autohex {
    set app_dir $tool_dir/../autohex_generic
    set auto_tool_dir $tool_dir/../autohex
    set app_init $app_dir/init_autohex_generic.tcl
    source $auto_tool_dir/med_autohex.tcl
}

array set menu_background {
    geomenu,surface \#AAAAFF
    geomenu,curve \#AAFFAA
    geomenu,point \#FFAAAA
    geomenu,material \#FFAAFF
    geomenu,loop \#AAFFFF
    geomenu,density \#FFFFAA
}

array set menu_activebackground {
    geomenu,surface \#CCCCFF
    geomenu,curve \#CCFFCC
    geomenu,point \#FFCCCC
    geomenu,material \#FFCCFF
    geomenu,loop \#CCFFFF
    geomenu,density \#FFFFCC
}

# This is not the most elegant way to do this.

set test_lic_file test_licensing
if $is_win {append test_lic_file ".exe"}
if {[file exists $env(ICEM_ACN)/bin/$test_lic_file] &&
    ![catch "exec $env(ICEM_ACN)/bin/$test_lic_file -AEA" res] &&
    ($res == 1)} {
    array set only_solvers { CFX-4 1 CFX-5 1 CFX-TASCflow 1 Plot3d 1 }
}

trace variable solution(solver) w "solution_update_buttons; list"

set tool_extra(2) {button Print file_hardcopy_med}
set tool_extra(3) {button Undo ic_undo}
set tool_extra(4) {button Redo ic_redo}
set tool_extra(6) {button Shell "file_shell ."}
set extra_position(extra6) 3,2

set no_full_msgs_buttons 1
set no_autoraise_tearoff_menus 1

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

array set menu_background {
    geomenu,surface \#AAAAFF
    geomenu,curve \#AAFFAA
    geomenu,point \#FFAAAA
    geomenu,material \#FFAAFF
    geomenu,loop \#AAFFFF
    geomenu,density \#FFFFAA
}

array set menu_activebackground {
    geomenu,surface \#CCCCFF
    geomenu,curve \#CCFFCC
    geomenu,point \#FFCCCC
    geomenu,material \#FFCCFF
    geomenu,loop \#CCFFFF
    geomenu,density \#FFFFCC
}

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

# Various variables that we use.

set background_color #000000
set display_axes 1

set some_quadratic_domains 0
set is_super 0
array set data_available {
    struct 0 unstruct 0 mesh 0 geom_facet 0
    can_run_solver 0 geom 0
}
set geo_command_mode curve
set geometry_mode surface
proc geometry_mode_update {} {}
set blank_family_color \#ff8000

trace variable geo_command_mode w "disp_geo_command_mode_update 1 ; list"
set tool_phase_command(geometry) disp_geo_command_mode_update

if [file exists $env(ICEM_ACN)/icemcfd_custom_script.tcl] {
    source $env(ICEM_ACN)/icemcfd_custom_script.tcl
}
if [file exists icemcfd_custom_script.tcl] {
    source icemcfd_custom_script.tcl
}

proc last_message {} {
    global env version last_message_option last_message_option_old

    set messf [home_directory]/.icemcfd_message

    if [file exists $messf] {
       if [catch {uplevel \#0 [list source $messf]} res] {
          mess "$res\n" red
       }
    } else {
       if ![info exists last_message_option] { set last_message_option 0 }
    }

    set last_message_option_old $last_message_option

    if {!$last_message_option} {
       catch {form_kill .last_message}

       set line1 "IMPORTANT NOTE:\n\nPlease advise that this is the LAST release of ANSYS ICEM CFD\nto offer this Interface format.\n\n"
       set line2 "This Interface is for legacy purposes only and is not fully supported.\n\n"
       set line3 "Future releases of ANSYS ICEM CFD will ONLY support\nthe new Interface format.\n\n"
       set line4 "We encourage all users to start using the new Interface."
       set message_text $line1$line2$line3$line4

       set d [form_init .last_message "ANSYS ICEM CFD $version" "" done]
       if {$d != ""} {
          form_text $d.text "" "" {0 0} "" 54x12
          $d.text.text configure -font fixed
          form_text_set $d.text $message_text 
          form_checkbutton $d.option "Don't show this message again" last_message_option {1 0 -cols 2}
	 form_finish middle 1
       }

       if ![form_wait .last_message] {
          return
       }
    }

}

proc last_message_ok {} {
    global last_message_option last_message_option_old

    if {$last_message_option != $last_message_option_old} {
       set file [home_directory]/.icemcfd_message
       set fp [open $file w]
       puts $fp "set last_message_option $last_message_option"
       close $fp
       mess "Saved option to \"$file\"\n"
    }
   
}

