# This code creates the user interface for the mesh editor.
#
# Copyright (c) 1999 ICEM CFD Engineering.  All rights reserved.
# Author:  Wayne A. Christopher, wayne@icemcfd.com
# Author:  Jari Spaete, jari.spaete@ansys.com

proc file_replay {} {
    global replay_file replay_dir file_name
    
    set replay_dir $file_name(mesh_dir)
    if ![info exists replay_file] {
        set replay_file replay_file
    } else {
        if {$replay_file == ""} {
            set replay_file replay_file
        }
    }
    replay_form {} 1
}

proc file_replay_batch {file} {
    replay_batch $file
}

proc replay_filter {com} {
    global dont_record_command replay_has_result_func
    
    set cc [lindex $com 0]

    return [expr {![batch_interp eval uplevel \#0 info exists dont_record_command($cc)] &&
		  ![info exists dont_record_command($cc)] &&
		  ![info exists replay_has_result_func($cc)]}]
    # don't use ([info command ${cc}_replay_result] == "")
}

proc replay_execute_command {line update_display} {
    global errorInfo env batch_mode replay_ignore_errors

    set res ""
    if [catch {uplevel #0 $line} res] {
        if {[info exists replay_ignore_errors] && $replay_ignore_errors} {
            mess "Ignoring error in replay of $line: $res\n"
            if {$update_display && !$batch_mode} {
                replay_after_commands_done
            }
            return 0           
        } else {
            mess "Error in replay of $line:\n$res\n" red
            return 1
        }
    } else {
        if {$res != ""} {
            # output warnings (if any exist)
            replay_check_command_output "$res"
        }
        if {$update_display && !$batch_mode} {
            replay_after_commands_done
        }
        return 0
    }
}

proc replay_check_command_output {res} {
    set num [string first "Warning:" $res]
    if {$num > -1} {
        mess "[string range $res $num end]\n" red
    }
}

proc replay_after_commands_done {} {
}

# This function puts the command in the replay log if necessary
# and then executes it.

proc batch_do_cmd {args} {
    global command_hook after_command_hook env
    
    if [info exists env(ICEM_REPLAY_DEBUG)] {
	puts "CMD: $args"
    }
    
    if [info exists command_hook] { $command_hook $args }
    set ret [batch_interp eval $args]
    if [info exists after_command_hook] { $after_command_hook $args }
    
    if [info exists env(ICEM_REPLAY_DEBUG)] {
	puts "RES: $ret"
    }
    
    return $ret
}

if {([info exists ai_environment]) && ($ai_environment == 0)} {
    proc aie_create_initial_assemblies {args} { 
    }
}

proc setup_batch_interp {} {
    global env whoami tdv_default replay_has_result_func
    
    foreach var {
	batch_dir
	batch_mode
	is_win
	guibase_dir
	tdv_library
	tdv_default
    use_workbench
    } {
	global $var
        if { [info exists $var] } {
            batch_interp eval [list set $var [set $var]]
        }
    }
    batch_interp eval [list source $batch_dir/med_batch.tcl]
    
    foreach cmd [batch_interp eval info commands ic_*] {
	if [string match *_replay_result $cmd] {
	    set replay_has_result_func([string range $cmd 0 end-14]) 1
	    interp alias "" $cmd batch_interp $cmd
	    continue
	}
	proc $cmd args "\
	    global command_hook after_command_hook in_$cmd errorInfo ret; \
	    if \[info exists in_$cmd\] \{ unset in_$cmd; mess \"Error: $cmd called reentrantly\n\" red; return \"\"\};\
	    if [info exists env(ICEM_REPLAY_DEBUG)] {
		puts \"CMD: $cmd \$args\" ;\
	    } ;\
	    if [info exists env(ICEM_REPLAY_DEBUG_MESS)] {
		mess \"CMD: $cmd \$args\n\" orange ;\
	    } ;\
	    if \[info exists command_hook\] { \$command_hook \"$cmd \$args\" } ;\
	    replay_write_to_journal \"$cmd \$args\" 0 ;\
            set in_$cmd 1 ;\
	    set err \[catch {batch_interp eval $cmd \$args} ret] ;\
	    catch \{ unset in_$cmd \} ;\
	    if \$err { puts \"\$ret\n\$errorInfo\"; error \"\$ret\" } ;\
	    if \[info exists after_command_hook\] { \$after_command_hook \"$cmd \$args\" } ;\
	    replay_write_to_journal \"$cmd \$args\" 1 ;\
	    if [info exists env(ICEM_REPLAY_DEBUG)] {
		puts \"RES: \$ret\" ;\
	    } ;\
	    if [info exists env(ICEM_REPLAY_DEBUG_MESS)] {
		mess \"RES: \$ret\n\" orange ;\
	    } ;\
	    return \$ret"
    }
    
    # The list of functions in the GUI interpreter that the batch interpreter
    # can call.
    set gui_functions_1 {
        busy
        update_fam_window
        update_fam_visible
        update_geom_visible
        update_geom_window
        gui_present_geometry
        gui_center_geometry
        get_fam_visible
        get_uns_type_visible
        get_geom_visible
        get_str_option
        get_quad_option
        get_etm_undo_option
        update_uns_visible
        update_uns_available
        update_uns_visible_subset
        update_uns_disp
        update_str_visible
        initialize_unstruct_visibility
        uninitialize_unstruct_visibility
        initialize_struct_visibility
        uninitialize_struct_visibility
        disp_change_overall_visible
        gui_change_visibility
        add_new_family
        disp_new_stuff
        display_update
        hex_update_display
        interrupt
        run_application_before
        run_application_after
        undo_redo_update
        fam_delete_unused_on_unload
        message_add_button
        message_remove_button
        message_enable_button
        tk_dialog
        select_families
        tdv_get_centroid
        get_famnames
        struct_comptopo_callback
        disp_update_number_list
        tdv_home
        disp_set_option_one
        question_box
        question_box_mult
        choose_multiple
        famboco_annotate_family_boco
        famboco_edit_load_param_values
        rmi_ShowMessage
        rmi_display_all_fam
        orient_command
        clear_fam_visible_prev
        fam_check_new
        erase_flood_fill_lines
        get_solver_info
        solution_set_solver
        solution_input
        check_box_form
        mg_unstruct_diag_types_list
        struct_disp_list_clear
        tdv_active
        tdv_mouse_pick
        tdv_mouse_state
        tdv_select_rbox
        tdv_configure_select_rbox
        tdv_delete_select_rbox
        tdv_fixed_text
        gui_hardcopy_create
        etm_done_smooth
        struct_close_all_open_windows
        aie_new_families_or_elem_types
        aie_create_parts_in_tree_if_needed
        aie_subset_put_in_tree
        aie_connectors_default_result_group_name
        aie_connectors_register_new_result_group
        aie_updateGeoVis
        aie_updateMeshVis
        aie_updateBlockVis
        hex_set_return_vars
        cmap_create
        cmap_adjust
        AIEWBSendToWBScript
        aie_set_global
        aie_get_global
        aie_unset_global
        aie_get_global_array_names
        aie_get_global_array
        aie_update_dez_onerror
        aie_update_dez_value
        aie_update_part_table_value
        tkerror_stacktrace
        set_project_names
        save_project_file
        aie_update_gui
        exitProgram
        aie_saveProject
        solution_set_solver
        set_anslic_client_idle
    }
    lappend gui_functions_1 $tdv_default
    # taken from list above: create_empty_tetin_if_needed
    set gui_functions_2 {
        mess
    }
    set gui_variables {
        black_and_white
        use_xwindows
        argv
        file_name
        options
        disp_options
        saved_params
        program_path
        hex_option
        prism_values
        vid_options
        savedTreeVisibility
        saved_views
        cut_info
        script_file
    }
    
    foreach cmd $gui_functions_1 {
	# These can't be reentrant
	batch_interp alias $cmd gui_$cmd
	proc gui_$cmd args "\
	    global in_$cmd errorInfo ;\
	    if \[info exists in_$cmd\] \{ unset in_$cmd ; error \"Error: $cmd called re-entrantly\" ; return \"\" \};\
	    set in_$cmd 1 ;\
	    if \[catch \{eval $cmd \$args\} ret\] \{ puts \"\$ret\n\$errorInfo\" \} ;\
	    catch \{ unset in_$cmd \} ;\
	    return \$ret"
    }
    foreach cmd $gui_functions_2 {
        # These ones we don't care if they are reentrant
        batch_interp alias $cmd $cmd
    }
    
    foreach var $gui_variables {
        global $var
        trace variable $var w batch_interp_update_var
        batch_interp_update_var $var "" w
    }
    
    # To run old hexa commands
    setup_old_hexa_commands

    batch_interp eval set whoami \"$whoami\"
    
    # ----------------
    
    # this already exists - created in main
    #interp create script_interp
    foreach var {
	    is_win
	    guibase_dir
	    tdv_library
	    small_screen_hack
	    has_blt
	    botform_geo
	    script_file
	    script_args
	    batch_mode
    } {
	    global $var
	    if [ info exists $var ] {
	        script_interp eval [list set $var [set $var]]
	    }
    }
    
    # This needs to be done better
    foreach cmd {
	    $tdv_default mess geo_select geo_select_loc
	    display_update med_home get_path
    } {
        script_interp alias $cmd $cmd
    }
    
    foreach f {exec_cmds forms formutil fileselect toplevel \
	busy bltemu questionbox} {
	script_interp eval [list source $guibase_dir/$f.tcl]
    }
    foreach f {viewer} {
	script_interp eval [list source $tdv_library/$f.tcl]
    }
    
    foreach cmd [batch_interp eval info commands ic_*] {
	interp alias script_interp $cmd batch_interp $cmd
    }
}

proc batch_interp_update_var {name sub op} {
    global $name count_interp

    if [array exists $name] {
	    if {$sub == ""} {
	        foreach sub [array names $name] {
		        set val [set ${name}($sub)]
		        batch_interp eval [list set ${name}($sub) $val]
	        }
	    } else {
	        set val [set ${name}($sub)]
	        batch_interp eval [list set ${name}($sub) $val]
	    }
    } elseif [info exists $name] {
	    set val [set $name]
	    batch_interp eval [list set $name $val]
    }
}

proc script_run {{file ""}} {
    global script_file file_name
    
    if {$file == ""} {
	if { $script_file == "" && [ info exists file_name(mesh_dir) ] } {
	    set script_file $file_name(mesh_dir)
	}
	set script_file [file_selection -message "Select a script file" \
			     -default $script_file]
	if {$script_file == ""} return
    } else {
	set script_file $file
    }
    
    mess "Starting script $script_file ...\n"
    script_interp eval [list source $script_file]
    mess "Finished script $script_file.\n"
}

proc b {args} {
    batch_interp eval $args
}

proc s {args} {
    script_interp eval $args
}

proc setup_old_hexa_commands {} {
    set hexa_commands [batch_interp eval info commands ic_hex_*]    
    foreach cmd $hexa_commands {	
	set old_cmd [string range $cmd 7 end]	
	if {[info command $old_cmd] == ""} {
	    batch_interp alias $old_cmd $cmd	
	    interp alias script_interp $old_cmd batch_interp $cmd
	    proc $old_cmd args "\
	    set err \[catch {batch_interp eval $cmd \$args} ret] ;\
	    return \$ret"
	}
    }
}

# One remaining problem is that the ic_param_* calls do not get written to the
# replay file.  This is a temporary hack (they should be moved to the batch
# interp)

proc unused__replay_patch_gui_calls {pat} {
    global dont_record_command
    
    foreach cmd [info commands $pat] {
	if [string match *_replay_result $cmd] continue
	if [info exists dont_record_command($cmd)] continue
	set cmd2 __gui_$cmd
	rename $cmd $cmd2
	proc $cmd args "\
	    global command_hook after_command_hook in_patched_gui errorInfo ; \
	    if \[info exists in_patched_gui\] \{ return \[eval $cmd2 \$args\] \} ; \
	    if [info exists env(ICEM_REPLAY_DEBUG)] {
		puts \"CMD: $cmd \$args\" ;\
	    } ;\
	    if \[info exists command_hook\] { \$command_hook \"$cmd \$args\" } ;\
	    replay_write_to_journal \"$cmd \$args\" 0 ;\
            set in_patched_gui 1 ;\
	    set err \[catch {eval $cmd2 \$args} ret] ;\
	    catch \{ unset in_patched_gui \} ;\
	    if \$err { error \"\$ret\n\$errorInfo\" } ;\
	    if \[info exists after_command_hook\] { \$after_command_hook \"$cmd \$args\" } ;\
	    replay_write_to_journal \"$cmd \$args\" 1 ;\
	    if [info exists env(ICEM_REPLAY_DEBUG)] {
		puts \"RES: \$ret\" ;\
	    } ;\
	    return \$ret"
    }
}

