# $Revision$ on $Date$
# The above revision line needs to be the first line for all techtk files
# Copyright (c) 2006 Ansys Inc

namespace eval ::AIEnv::GUIManagement {
}

proc ::AIEnv::GUIManagement::MainWindowInit {} {
	# Main window dimensions
	variable MainWinWidth
	variable MainWinHeight
	variable BGColor
	variable SmallScreen
	variable TopBar
	global AppName env aie_guiOpt toplevel

	set Height [winfo screenheight .]
	set Width [winfo screenwidth .]
	if [ic_wb2_is_running] {
	    set rwidth [expr int($Width * 0.99)]
	} else {
	    set rwidth [expr int($Width * 0.8)]
	}
	if {($aie_guiOpt(treeGeom) == "left") || ($aie_guiOpt(treeGeom) == "right")} {
	   set rwidth $Width
	}
	set MainWinWidth $rwidth
	if [ic_wb2_is_running] {
	    set MainWinHeight [expr int($Height * 0.94)]
	} else {
    	set MainWinHeight [expr int($Height * 0.8)]
    }
	if {$MainWinWidth > 1000} {
	  set SmallScreen 0
 	} else {
	  set SmallScreen 1
	}
    if [info exists env(AI_ENV_WINDOW)] {
        wm geometry . $env(AI_ENV_WINDOW)
        set MainWindowWidth [winfo reqwidth .]
        set MainWindowHeight [winfo reqheight .]
    } else {
        if [ic_wb2_is_running] {
            wm geometry . "${MainWinWidth}x${MainWinHeight}+0+0"
        } else {
            wm geometry . "${MainWinWidth}x${MainWinHeight}+10+10"
        }
    }
	wm title . $AppName
	wm resizable . 1 1

	set TopBar [frame .menuZone]
	set menubar [frame .menuZone.menu]

	pack $menubar -side left -pady 0 -ipady 0
    frame .menuZone.right
    pack .menuZone.right -side right -pady 0 -ipady 0
    
	set toplevel(topbar) .menuZone.right
	set BGColor [$menubar  cget -background]
	SetupWindowDestroy
}

proc ::AIEnv::GUIManagement::Layout {} {
	variable MainWinWidth
	variable MainWinHeight
	variable BGColor
	variable SmallScreen

	global mess_frame plot_frame gui_style_mode
	global tdv_default tdv_workspace tdv_current_viewer aie_guiOpt
	variable ICEMGraphics
	variable TopBar

	set mess_frame .v.console
	set plot_frame .v.plot

	set UpperIconSep [Separator .sep1 -orient horizontal]
	set LowerIconSep [Separator .sep2 -orient horizontal]
	set IconFrame [frame .iconZone -bg $BGColor]
	set CommonIconZone [frame .iconZone.common -bg $BGColor]
	set TabbedIconZone [frame .iconZone.tabbed -bg $BGColor]
	set MidIconSep [Separator .iconZone.sep3 -orient vertical]

	# Pane between the tree/dez and the graphics window/command window
	set p1 [PanedWindow .v -side top -weights available -width 6]

	if {$aie_guiOpt(treeGeom) == "left"} {
	   $p1 add -weight 1
	   $p1 add -weight 5
	   $p1 add -weight 1
	   set TreeDEZ [$p1 getframe 0]
	   set GraphicsCommand [$p1 getframe 1]
	   set DEZ [$p1 getframe 2]
	} elseif {$aie_guiOpt(treeGeom) == "right"} {
	   $p1 add -weight 1
	   $p1 add -weight 5
	   $p1 add -weight 1
	   set DEZ [$p1 getframe 0]
	   set GraphicsCommand [$p1 getframe 1]
	   set TreeDEZ [$p1 getframe 2]
	} else {
	   $p1 add -weight 2
	   $p1 add -weight 7
   	   set TreeDEZ [$p1 getframe 0]
	   set GraphicsCommand [$p1 getframe 1]
	}

	CreateConsole

	if {($aie_guiOpt(treeGeom) == "left") || ($aie_guiOpt(treeGeom) == "right")} {
	   set Tree $TreeDEZ
	} else {
	   # Pane between the DEZ and the tree
	   set p2 [PanedWindow $TreeDEZ.p2 -side left -weights available -width 6]
	   $p2 add -weight 1
	   $p2 add -weight 1
	   if {$aie_guiOpt(treeGeom) == "top"} {
	      set Tree [$p2 getframe 0]
	      set DEZ [$p2 getframe 1]
	   } else {
	      set DEZ [$p2 getframe 0]
	      set Tree [$p2 getframe 1]
	   }
	}

	# Pane between the Graphics and the command
	set p3 [PanedWindow $GraphicsCommand.p3 -side left -weights available -width 6]
	$p3 add -weight 5
	$p3 add -weight 1
	set Graphics [$p3 getframe 0]
	set Command [$p3 getframe 1]

	set tdv_workspace $Graphics
	workspace_init $Graphics

    SetupGraphicsBasic

	global aie_guiOpt tdv_background_color tdv_show_ansys_logo
	if {$aie_guiOpt(withMedGWin)} {
	   set ICEMGraphics ${Graphics}.view
	   set tdv_default $ICEMGraphics
	   set tdv_current_viewer $ICEMGraphics
	   SetupGraphics $ICEMGraphics

           if $aie_guiOpt(gradBackground) {
               if {![info exist tdv_background_color] || ($tdv_background_color == "")} {
                   tdv_background $ICEMGraphics #6688dd #ffffff
               }
           } else {
               if {![info exist tdv_background_color] || ($tdv_background_color == "")} {
                   tdv_background $ICEMGraphics #000000 #000000
               }
           }
           if {$aie_guiOpt(logoImage) != "" && $tdv_show_ansys_logo} {
              tdv_logo $ICEMGraphics $aie_guiOpt(logoImage) $aie_guiOpt(logoPos)
           }

           if {$aie_guiOpt(wbStyleAxes)} {tdv_wb_axes_toggle $ICEMGraphics}
           if {$aie_guiOpt(wbStyleCircle)} {tdv_wb_circle_toggle $ICEMGraphics}

	} else {
	   set tdv_default ""
	}

    # Pane between the Command and the Additional Pane
    set p4 [PanedWindow $Command.p4 -side top -weights available -width 6]
    if {$gui_style_mode == "wb"} {
        $p4 add -weight 999
    } else {
        $p4 add -weight 1
    }

    $p4 add -weight 1
    set ConsolePane [$p4 getframe 0]
    set AdditionalPane [$p4 getframe 1]

    if [info exist ICEMGraphics] {
        # Pack in the graphics window
        workspace_add $ICEMGraphics "Model"
        workspace_disable_close $ICEMGraphics "Close Model's Window Is Not Allowed"
    }

    grid rowconfigure $Graphics 0 -weight 1
    grid columnconfigure $Graphics 0 -weight 1
    # Pack in the console window
    pack $mess_frame -in $ConsolePane -fill both -expand yes
    pack $plot_frame -in $AdditionalPane -fill both -expand yes

    # Main frame
    grid $TopBar -row 0 -column 0 -sticky ew -padx 3 -pady 0
    grid $UpperIconSep -row 1 -column 0 -sticky ew -padx 3 -pady 3
    grid $IconFrame -row 2 -column 0 -sticky ew -padx 3
    grid $LowerIconSep -row 3 -column 0 -sticky ew -padx 3 -pady 3
    grid $p1 -row 4 -column 0 -sticky nsew -padx 3
    grid columnconfigure . 0 -weight 1
    grid rowconfigure . 0 -weight 0
    grid rowconfigure . 1 -weight 0
    grid rowconfigure . 2 -weight 0
    grid rowconfigure . 3 -weight 0
    grid rowconfigure . 4 -weight 1

	# Icon Frame
	grid $CommonIconZone -row 0 -column 0 -sticky nw -padx 4
	grid $MidIconSep -row 0 -column 1 -sticky ns -pady 1
	grid $TabbedIconZone -row 0 -column 2 -sticky nsew -padx 4
	grid columnconfigure $IconFrame 0 -weight 0
	grid columnconfigure $IconFrame 1 -weight 0
	grid columnconfigure $IconFrame 2 -weight 1

        set r_iz [expr 280.0 / $MainWinWidth]
        set r_tz1 [expr 1.0 - 500.0 / $MainWinWidth]
        if {$r_iz > $r_tz1} {set r_iz $r_tz1}
        if {$r_iz < 0.27} {set r_iz 0.27}
        if {[expr $r_iz * $MainWinWidth] > 280.0} {
	    set r_iz [expr 280.0 / $MainWinWidth]
	}
        set r_tz [expr 0.96 - $r_iz]
        set CommonIconZoneWidth [expr int($MainWinWidth * $r_iz)]
        set TabbedIconZoneWidth [expr int($MainWinWidth * $r_tz)]

      # ------- change 0.22 and 0.7 to r_iz and r_tz by Jigen
      #         to cope with smaller monitors. Here the minimum widths
      #         for the common and the tabbed zones are 200 and 500.
      #     minimum width for commmon zone are now 280. 

        global aie_guiOpt
        if {$aie_guiOpt(iconZoneStyle) == "V3StandALone"} {
           set CommonIconZoneWidth $MainWinWidth
           set TabbedIconZoneWidth 0
        }
 
 	SetIconZoneWidths $CommonIconZoneWidth $TabbedIconZoneWidth


	# Pack in the pane windows
	if {($aie_guiOpt(treeGeom) != "left") && \
		($aie_guiOpt(treeGeom) != "right")} {
	   grid $p2 -row 0 -column 0 -sticky nsew
	   grid rowconfigure $TreeDEZ 0 -weight 1
	   grid columnconfigure $TreeDEZ 0 -weight 1
	}

	grid $p3 -row 0 -column 0 -sticky nsew
	grid rowconfigure $GraphicsCommand 0 -weight 1
	grid columnconfigure $GraphicsCommand 0 -weight 1

	grid $p4 -row 0 -column 0 -sticky nsew
	grid rowconfigure $Command 0 -weight 1
	grid columnconfigure $Command 0 -weight 1

    # Set up the zones used during the building process
    variable GUIZones
    set GUIZones("MenuZone") .menuZone.menu
    set GUIZones("IconZone") $CommonIconZone
    set GUIZones("TabbedIconZone") $TabbedIconZone
    set GUIZones("DataEntryZone") $DEZ
    set GUIZones("PopupZone") .popupMen
    set GUIZones("ConsoleZone") $p4

	aie_tree init "" $Tree
}

proc ::AIEnv::GUIManagement::CreateConsole {} {
    global log_messages  
    global env small_screen_hack mess_frame plot_frame
    global AppName Version plot_window options
    variable MessageTextWidget
    variable CharacterHeight
    variable GUIZones
    
    frame .v.console
    set ScrollWin [ScrolledWindow $mess_frame.f -auto both -scrollbar both]
    set txt [text $mess_frame.text  -exportselection 1 -wrap word -padx 4 -pady 4 -relief sunken -borderwidth 2 -foreground black -background white]
	$ScrollWin setwidget $txt
	set BotFrame [frame $mess_frame.bot]
	checkbutton $mess_frame.bot.log -text Log -variable log_messages -command message_log_reopen
	button $mess_frame.bot.save -text "Save" -padx 0 -pady 2 -command message_save
	button $mess_frame.bot.clear -text "Clear" -padx 0 -pady 2 -command "$mess_frame.text delete 0.0 end"
	frame $mess_frame.bot.frame -bd 1 -relief ridge -padx 0 -pady 0
	label $mess_frame.bot.frame.status  -textvariable units_message -padx 0 -pady 2 
	set ::va_set(status_frame) $mess_frame.bot.frame
    set GUIZones("StatusMessageZone") $mess_frame.bot.frame.status

    if {[info exists env(AI_ENV_BETA)] && $env(AI_ENV_BETA)} {
        if {$::tcl_platform(platform) == "windows"} {set ext .exe} else {set ext ""}
        set wish84 [file join $env(ICEM_ACN) bin wish8.4.11$ext]
        set wish [file join $env(ICEM_ACN) bin wish$ext]
        if [file exists $wish84] {set path [list $wish84]} \
        elseif [file exists $wish] {set path [list $wish]} \
        else {set path ""}
        if {$path != ""} {
	        set fil_im [image create photo -width 2 -height 2]
	        Button $mess_frame.bot.tetris -relief link -bd 1 -image $fil_im \
		        -command "exec $path [list $env(ICEM_ACN)/lib/ai_env/resource/other/tetris.tcl] &"
	        #pack $mess_frame.bot.tetris -side right -anchor s -pady 2 -padx 0
	        #Button $mess_frame.bot.hextris -relief link -bd 1 -image $fil_im \
		        -command "exec $path [list $env(ICEM_ACN)/lib/ai_env/resource/other/hextris.tcl] &"
		        
		    Button $mess_frame.bot.hextris -relief link -bd 1 -image $fil_im \
		        -command "exec $path [list $env(MED_ROOT)/../ai_env/resource/other/hextris.tcl] &"
		        
	        #pack $mess_frame.bot.hextris -side right -anchor s -pady 2 -padx 2
	    }
    }

    if {[info exists env(AI_ENV_BETA)] && $env(AI_ENV_BETA) && 0} {
        pack $mess_frame.bot.log $mess_frame.bot.save $mess_frame.bot.clear \
             $mess_frame.bot.tetris $mess_frame.bot.hextris -side left -padx 2 -pady 0
    } else {
        if {[info exists options(enable_idle)] && $options(enable_idle) == "1"} {
            button $mess_frame.bot.idle -text " Idle " -padx 0 -pady 2 -command "ic_set_icemcfd_idle"
            pack $mess_frame.bot.log $mess_frame.bot.save $mess_frame.bot.clear -side left -padx 2 -pady 0
            pack $mess_frame.bot.log $mess_frame.bot.idle -side left -padx 12 -pady 0
        } else {
            pack $mess_frame.bot.log $mess_frame.bot.save $mess_frame.bot.clear -side left -padx 2 -pady 0
        }
        pack $mess_frame.bot.frame -side right -padx 0 -pady 0
        pack $mess_frame.bot.frame.status -side right -padx 2 -pady 0
    }
      
    grid configure $ScrollWin -row 0 -column 0 -sticky nsew
    grid configure $BotFrame -row 1 -column 0  -sticky nsew -pady 2
    grid columnconfigure $mess_frame 0 -weight 1
    grid rowconfigure $mess_frame 0 -weight 1
    set MessageTextWidget $txt
    bind $txt <Return> "message_send_line $txt"

    set plot_window [frame $plot_frame]

    if [ic_wb2_is_running] {
        mess "$AppName $Version in Workbench 2.0 Framework\n"
    } else {
        mess "$AppName $Version\n"
    }
    
    update
    set CharacterHeight 0
    set CharacterWidth 0
}


proc ::AIEnv::GUIManagement::SetupGraphicsBasic {} {
    global display_type small_screen_hack tdv_axes_var tdv_default
    global use_xwindows

    set display_vendor [winfo server .]
    set small_screen_hack 0

    switch -glob -- $display_vendor {
	    {*Silicon Graphics*}                { set display_type sgi }
	    {*Hewlett-Packard *}                { set display_type hp }
	    {*Sun Microsystems*}                { set display_type sun }
	    {*International Business Machines*} { set display_type ibm }
	    {*Digital Equipment Corporation*}   { set display_type dec }
	    default                             { set display_type other }
    }

    tdv_set_key_command F11 "make_sane" "Emergency reset"
    tdv_set_key_command F4 "make_sane" "Emergency reset"
}


proc ::AIEnv::GUIManagement::SetupGraphics {w} {
    global display_type small_screen_hack tdv_axes_var tdv_default
    global use_xwindows 

    set width 1
    set height 1

    if $use_xwindows { set gtype X11 } else { set gtype native }
    set tdv_default $w
    tdv_init $w $width $height $gtype black 0
    tdv_dynamics_bindings $w
    tdv_selection_bindings $w
    tdv_init_shortcuts 0 {s x}
    bind $w <Enter> "tdv_unfocus_entries"
    set tdv_axes_var($w) 1
}

proc ::AIEnv::GUIManagement::Redraw {w} {
    global tdv_do_redraw
    
    if [info exists tdv_do_redraw] return
    set tdv_do_redraw 1
    tdv_redraw $w
    unset tdv_do_redraw
}

proc ::AIEnv::GUIManagement::FinalGraphicsInit {} {
    global tdv_default vid_options
	
    # synchronize toggle command and may be saved option (if defined but == 0)
    if {[info exists vid_options(tdv_axes)] && $vid_options(tdv_axes) == 0} { 
        aie_toggle_tdv_axes
    }
    aie_toggle_display_origin
    bind $tdv_default <Configure> "::AIEnv::GUIManagement::Redraw $tdv_default"
}

proc ::AIEnv::GUIManagement::SendCommand {} {
	variable MessageTextWidget
	set end [$MessageTextWidget index insert]
	set line [lindex [split $end .] 0]

	set TheCommand [$MessageTextWidget get $line.0 $end]
	set TheCommand [lindex [split $TheCommand \n] 0]
	# Insert a new line
	$MessageTextWidget insert $end \n

	# Try and send the command
	if {[catch {uplevel \#0 eval \{$TheCommand\}} TheResult]} {
		OutputMessage "Error: $TheResult\n" red
		busy reset
	} else {
		OutputMessage "Result: " blue
		OutputMessage "$TheResult\n"
	}
}


proc ::AIEnv::GUIManagement::OutputMessage { Line {Color ""} {Font ""} {Update 1} {ShowTail 1}} {
	variable MessageTextWidget
	$MessageTextWidget insert end $Line
	$MessageTextWidget see end
}

proc ::AIEnv::GUIManagement::AIEnvInWB_FixEvents {} {
    global aieGUIArray useWinId tcl_platform

    if { $tcl_platform(platform) == "windows" } {
        set aw [win_get_active_window]
        set gf [win_get_focus]
    } else {
        # For UNIX/Linux, no equivalents for GetActiveWindow and GetFocus
        set aw $aieGUIArray(root_handle)
        set gf $aieGUIArray(root_handle)
    }

    set cg [grab current]

    if {$aieGUIArray(run) && [focus] == "" && $gf != 0 && $gf != ""  && \
        $aieGUIArray(root_handle) == $aw && $cg == ""} {

        # If the focus has been lost, refocus on the hidden widget
        BWidget::focus set $aieGUIArray(tlHidden)
        BWidget::focus release $aieGUIArray(tlHidden)

        # Refocus on .
        focus -force .
    }

    after 1000 ::AIEnv::GUIManagement::AIEnvInWB_FixEvents
}

proc ::AIEnv::GUIManagement::AIEnvInWB_SetupFixEvents {} {
    global aieGUIArray tcl_platform

    if { $tcl_platform(platform) != "windows" } {
        wm state . normal
    }
    set aieGUIArray(tlHidden) [toplevel .tHidden]
    wm overrideredirect $aieGUIArray(tlHidden) 1
    wm transient $aieGUIArray(tlHidden)
    wm withdraw $aieGUIArray(tlHidden)
    wm deiconify $aieGUIArray(tlHidden)
    wm geom $aieGUIArray(tlHidden) 1x1
    set aieGUIArray(run) 1

    BWidget::focus set $aieGUIArray(tlHidden)
    BWidget::focus release $aieGUIArray(tlHidden)
    focus -force .

    if { $tcl_platform(platform) == "windows" } {
        set aieGUIArray(root_handle) [win_get_ancestor [winfo id .] ROOT]
    } else {
        # For UNIX/Linux, no equivalents for GetActiveWindow and GetFocus
        set aieGUIArray(root_handle) [winfo id .]
    }

    after 2000 ::AIEnv::GUIManagement::AIEnvInWB_FixEvents
}

proc ::AIEnv::GUIManagement::InNamespaceBuildAIEnv {FullResourceFilePathName} {
    variable TreeFrame
    # Function call order is extremely important
    # Step 1. Initialize the main window (Set dimensions, menuZone, etc...)
    MainWindowInit
    # Step 1.5 for AIEnv in WorkBench:  setup the client/server connection
    global use_workbench wb_comPort wb_tcomPort
    if {[info exists use_workbench] && [info exists wb_comPort] && [info exists wb_tcomPort] } {
        # Launching med from workbench
        AIEWBComStartUp $wb_comPort $wb_tcomPort
    }
    # Step 2. Layout the main window
    Layout
    # Step 3. Initialize the GUIBuilder
    InitializeGUIBuilder
    # Step 4. Create the gui data structures from the resource file
    ParseResourceFile $FullResourceFilePathName
    # Step 5. Record where the tree frame is so that resizing works properly. Must be called
    # after the resource file is parsed, but before the gui is built so that the GUIZones
    # are properly initialized
#   SetTreeFrame $TreeFrame
    # Step 6. Actually build the gui from the description stored in the GUITree data structure
    BuildGUI

    global use_embed tcl_platform use_workbench
    #Step 6.5 for AIEnv in WorkBench: fix the keyboard events
    if {[info exists use_workbench]} {
        ::AIEnv::GUIManagement::AIEnvInWB_SetupFixEvents
    }
    update

    if { ![info exists use_embed] || $use_embed != 1 || ![info exists use_workbench] } {
        # For all non-embedded cases, or all UNIX cases, deiconify .
        wm deiconify .
    }

    raise .
    busy 1
    KillSplash
    update
    busy reset
    FinalGraphicsInit

    # On some errors "busy" may be set when focus is out of graphic window
    # Reset may be done with next global bind:
    #
    bind . <F11> make_sane
    # This binding must be created here because of a bad bwidgets interaction.
#   Commented for histogram temporarily - Ganesan
#   bind . <Destroy> { exit }

}

proc ::AIEnv::GUIManagement::DeleteWindowProtocol {} {
    if [aie_wb2_is_running] {
        aie_wb2_exit_icemcfd
    } else {
        exitProgram 1
    }
}

proc ::AIEnv::GUIManagement::SetupWindowDestroy {} {
    wm protocol . WM_DELETE_WINDOW ::AIEnv::GUIManagement::DeleteWindowProtocol

}

proc ::AIEnv::GUIManagement::ConfigureConsoleZone {on} {
    variable GUIZones
    global gui_style_mode console_zone_state

    if {[info exists console_zone_state] && $console_zone_state == $on} return
    set console_zone_state $on
    set w [winfo parent [$GUIZones("ConsoleZone") getframe 1]]
    after 100
    if $on {
        if {$on == 2} {
            $w configure -width [expr [winfo width $GUIZones("ConsoleZone")] / 1.75]
        } else {
            $w configure -width [expr [winfo width $GUIZones("ConsoleZone")] / 2]
        }
    } else {
        if {$gui_style_mode == "wb"} {
            $w configure -width 0
        }
    }
    update
}
