#.====================================================================
# [incr Tk] File
#.====================================================================
#. $Revision: 1.3.6.1 $
#. $Date: 2009/05/21 13:39:53 $
#.====================================================================
#. File Name:     euidltk_dialog.tcl
#. Author:        Eric Teagle
#. Description:   Wrappers for common tk dialogs.
#.
#.====================================================================
#. Copyright 1999 SAS IP, Inc. Proprietary Data.
#. Unauthorized use, distribution, or duplication is prohibited.
#. All Rights Reserved.
#.====================================================================
if {[catch {info args ::tk::dialog::file::ActivateEnt}]} {
   source [file join $tk_library tkfbox.tcl]
}
if {[catch {info args tkColorDialog_MoveSelector}]} {
   source [file join $tk_library clrpick.tcl]
}
# --------------------------------------------------------------------
# PUBLIC PROC:    getOpenFile
#
# Purpose:        Pop up a dialog box for the user to select a file to
#                 open. 
#
# Arguments:      args     -
#
# Return Value:   N/A
#
# Comments:       
#
# See Also:       N/A
#
# --------------------------------------------------------------------
proc euidl::getOpenFile { args } {
   global tk_strictMotif

   catch {ans_greygui all 0}

   set type {}
   set str {}

   set id [lsearch $args -type]
   if { $id != -1 } {
      set type [lindex $args [expr $id+1]]
      set args [lreplace $args $id [expr $id+1]]
   }
   
   if { ![catch {ans_getvalue common,,mccom,,int,16} newGUI] } {
      if { $newGUI == 0 && [info exists AnsysGUI::ansGUIArray(parent)] } {
         set id [lsearch $args -parent]
         if { $id != -1 } {
            # replace the parent with the toplevel window
            incr id
            set args [lreplace $args $id $id $AnsysGUI::ansGUIArray(parent)]
         } else {
            lappend args -parent $AnsysGUI::ansGUIArray(parent)
         }
      }
   }

   set prev_tk_strictMotif $tk_strictMotif
   set tk_strictMotif 0

   set filename [eval tk_getOpenFile $args]
   set tk_strictMotif $prev_tk_strictMotif

   after 50 [list catch {ans_greygui all 1}]
   after 50 [list catch {::AnsysGUI::keybFocus}]

   if { [string match {} $filename] } {
      return {}
   }

   switch -- $type {
      ansys {
         set str [euidl::convertFile $filename]
      }
      default {
         set str $filename
      }
   }

   return $str
}

# --------------------------------------------------------------------
# PUBLIC PROC:    getSaveFile
#
# Purpose:        Pop up a dialog box for the user to select a file to
#                 save. 
#
# Arguments:      args     -
#
# Return Value:   N/A
#
# Comments:       
#
# See Also:       N/A
#
# --------------------------------------------------------------------
proc euidl::getSaveFile { args } {
   global tk_strictMotif

   catch {ans_greygui all 0}

   set type {}
   set str {}

   set id [lsearch $args -type]
   if { $id != -1 } {
      set type [lindex $args [expr $id+1]]
      set args [lreplace $args $id [expr $id+1]]
   }

   if { ![catch {ans_getvalue common,,mccom,,int,16} newGUI] } {
      if { $newGUI == 0 && [info exists AnsysGUI::ansGUIArray(parent)] } {
         set id [lsearch $args -parent]
         if { $id != -1 } {
            # replace the parent with the toplevel window
            incr id
            set args [lreplace $args $id $id $AnsysGUI::ansGUIArray(parent)]
         } else {
            lappend args -parent $AnsysGUI::ansGUIArray(parent)
         }
      }
   }

   set prev_tk_strictMotif $tk_strictMotif
   set tk_strictMotif 0

   set filename [eval tk_getSaveFile $args]
   set tk_strictMotif $prev_tk_strictMotif

   after 50 [list catch {ans_greygui all 1}]
   after 50 [list catch {::AnsysGUI::keybFocus}]

   if { [string match {} $filename] } {
      return {}
   }

   switch -- $type {
      ansys {
         set str [euidl::convertFile $filename]
      }
      default {
         set str $filename
      }
   }

   return $str
}

# --------------------------------------------------------------------
# PUBLIC PROC:    chooseDirectory
#
# Purpose:        Pops up a dialog box for the user to select a directory.
#
# Arguments:      args     -
#
# Return Value:   N/A
#
# Comments:       
#
# See Also:       N/A
#
# --------------------------------------------------------------------
proc euidl::chooseDirectory { args } {
   global tcl_platform
   global tk_strictMotif

   catch {ans_greygui all 0}

   set type {}
   set str {}

   set id [lsearch $args -type]
   if { $id != -1 } {
      set type [lindex $args [expr $id+1]]
      set args [lreplace $args $id [expr $id+1]]
   }

   if { ![catch {ans_getvalue common,,mccom,,int,16} newGUI] } {
      if { $newGUI == 0 && [info exists AnsysGUI::ansGUIArray(parent)] } {
         set id [lsearch $args -parent]
         if { $id != -1 } {
            # replace the parent with the toplevel window
            incr id
            set args [lreplace $args $id $id $AnsysGUI::ansGUIArray(parent)]
         } else {
            lappend args -parent $AnsysGUI::ansGUIArray(parent)
         }
      }
   }

   set prev_tk_strictMotif $tk_strictMotif
   set tk_strictMotif 0

   set dirname [eval tk_chooseDirectory $args]
   set tk_strictMotif $prev_tk_strictMotif

   # If Windows platform, get the correct case of the path
   if { [string match windows $tcl_platform(platform)] } {
      catch {set dirname [file attributes $dirname -longname]}
   }

   after 50 [list catch {ans_greygui all 1}]
   after 50 [list catch {::AnsysGUI::keybFocus}]

   return $dirname
}

# --------------------------------------------------------------------
# PUBLIC PROC:    messageBox
#
# Purpose:        Pops up a message window and waits for user response.
#
# Arguments:      type     -
#
# Return Value:   N/A
#
# Comments:       
#
# See Also:       N/A
#
# --------------------------------------------------------------------
proc euidl::messageBox { args } {
   if { ![catch {ans_getvalue common,,mccom,,int,16} newGUI] } {
      if { $newGUI == 0 && [info exists AnsysGUI::ansGUIArray(parent)] } {
         set id [lsearch $args -parent]
         if { $id != -1 } {
            # replace the parent with the toplevel window
            incr id
            set args [lreplace $args $id $id $AnsysGUI::ansGUIArray(parent)]
         } else {
            lappend args -parent $AnsysGUI::ansGUIArray(parent)
         }
      }
   }

   return [eval tk_messageBox $args]
}

# --------------------------------------------------------------------
# PUBLIC PROC:    chooseColor
#
# Purpose:        Pops up a dialog box for the user to select a color.  
#
# Arguments:      type     -
#
# Return Value:   N/A
#
# Comments:       
#
# See Also:       N/A
#
# --------------------------------------------------------------------
proc euidl::chooseColor { args } {
   if { ![catch {ans_getvalue common,,mccom,,int,16} newGUI] } {
      if { $newGUI == 0 && [info exists AnsysGUI::ansGUIArray(parent)] } {
         set id [lsearch $args -parent]
         if { $id == -1 } {
            lappend args -parent $AnsysGUI::ansGUIArray(parent)
         }
      }
   }

   return [eval tk_chooseColor $args]
}

# --------------------------------------------------------------------
# PUBLIC PROC:    tk_dialogActive
#
# Purpose:        Returns 1 if tk dialog is currently active, 0 if not.
#
# Arguments:      type     - Specific type of dialog to check for.
#                            If no type is given, checks for all types.
#
# Return Value:   N/A
#
# Comments:       
#
# See Also:       N/A
#
# --------------------------------------------------------------------
proc ::euidl::tk_dialogActive { {type {}} } {
   global tkPriv
   global tkPrivMsgBox
   global tcl_platform

   set exists 0

   # On windows, the title bars are inactive.
   if { ![string match unix $tcl_platform(platform)] } {
      return 0
   }

   switch -- $type {
      dialog {
         foreach fglist [array names tkPriv fg,*] {
            set win [string trimleft $fglist "fg,"]
            if { [winfo ismapped $win] } {
               raise $win
               set exists 1
               break
            }
         }
      }
      messagebox {
        # Make sure the message dialog box was previously created before
        # trying to see if it currently exists.
        if { [info exists tkPrivMsgBox(-parent)] } {
           if { [string match $tkPrivMsgBox(-parent) .] } {
              set parent {}
           } else {
              set parent $tkPrivMsgBox(-parent)
           }

           set exists [winfo exists $parent.__tk__messagebox]

           if { $exists } {
              raise $parent.__tk__messagebox
           }
        }
      }
      color {
         set exists [info exists .__tk__color]
      }
      default {
         set exists [expr [tk_dialogActive dialog]     | \
                          [tk_dialogActive messagebox] | \
                          [tk_dialogActive color]]
      }
   }

   return $exists
}

# THIS WILL OVERRIDE THE TK PROC DEFINITION

# Gets called when user presses Return in the "File name" entry.
#
proc ::tk::dialog::file::ActivateEnt {w} {
    upvar ::tk::dialog::file::[winfo name $w] data

    set text [string trim [$data(ent) get]]
   # ANSYS ADDITION
	if { ![string equal $data(type) open] && ![string match {} $text] } {
      # check for user entered extension
      set userext [file extension $text]
      # Get the extension data from the selected filter option.
      set fileextension [$data(typeMenuBtn) cget -text]
      # find the assicated file extension for this text
      set extension {}
      foreach ft $data(-filetypes) {
         if { [string match $fileextension [lindex $ft 0]] } {
            # Found the selected string
            set extension [lindex $ft 1]
            break
         }
      }
      if { [llength $extension] == 1} {
         # Only add the extension if there is one extension listed.
         regexp {[*\.]*([^.]+)$}  $extension match ext
         if { ![string match {} $ext] && ![string match {[*]} $ext] && \
               ![string match ".$ext" $userext] } {
            set text ${text}.${ext} 
         }
      }
      
   }
   # END ANSYS ADDITION
    set list [::tk::dialog::file::ResolveFile $data(selectPath) $text \
		  $data(-defaultextension)]
    set flag [lindex $list 0]
    set path [lindex $list 1]
    set file [lindex $list 2]

    switch -- $flag {
	OK {
	    if {[string equal $file ""]} {
		# user has entered an existing (sub)directory
		set data(selectPath) $path
		$data(ent) delete 0 end
	    } else {
		::tk::dialog::file::SetPathSilently $w $path
		set data(selectFile) $file
		::tk::dialog::file::Done $w
	    }
	}
	PATTERN {
	    set data(selectPath) $path
	    set data(filter) $file
	}
	FILE {
	    if {[string equal $data(type) open]} {
		tk_messageBox -icon warning -type ok -parent $w \
		    -message "File \"[file join $path $file]\" does not exist."
		$data(ent) selection range 0 end
		$data(ent) icursor end
	    } else {
		::tk::dialog::file::SetPathSilently $w $path
		set data(selectFile) $file
		::tk::dialog::file::Done $w
	    }
	}
	PATH {
	    tk_messageBox -icon warning -type ok -parent $w \
		-message "Directory \"$path\" does not exist."
	    $data(ent) selection range 0 end
	    $data(ent) icursor end
	}
	CHDIR {
	    tk_messageBox -type ok -parent $w -message \
	       "Cannot change to the directory \"$path\".\nPermission denied."\
		-icon warning
	    $data(ent) selection range 0 end
	    $data(ent) icursor end
	}
	ERROR {
	    tk_messageBox -type ok -parent $w -message \
	       "Invalid file name \"$path\"."\
		-icon warning
	    $data(ent) selection range 0 end
	    $data(ent) icursor end
	}
    }
}

# tkColorDialog_MoveSelector --
# 
# Moves the polygon selector so that its middle point has the same
# x value as the specified x. If x is outside the bounds [0,255],
# the selector is set to the closest endpoint.
#
# Params: sel is the selector canvas, c is [red|green|blue]
#         x is a x-coordinate.
#
proc tkColorDialog_MoveSelector {w sel color x delta} {
   upvar #0 $w data

   incr x -$delta

   if { $x < 0 } {
	   set x 0
   } elseif { $x > $data(BARS_WIDTH)} {
	   set x $data(BARS_WIDTH)
   }
   set diff [expr {$x - $data($color,x)}]
   $sel move $data($color,index) $diff 0
   set data($color,x) [expr {$data($color,x) + $diff}]
    
   # Return the x value that it was actually set at
   return $x
}

proc tkColorDialog_XToRgb {w x} {
    upvar #0 $w data

    set x [expr {($x * $data(intensityIncr))/ $data(colorbarWidth)}]
    if {$x > 255} { set x 255 }
    return $x
}

