#.============================================================================
#. Copyright 1999 SAS IP, Inc. Proprietary Data.
#. Unauthorized use, distribution, or duplication is prohibited.
#. All Rights Reserved.
#.============================================================================
#. $Revision: 770315 $
#. $Date: 2014-10-06 15:34:24 -0400 (Mon, 06 Oct 2014) $
#.============================================================================
#.File Name:     ansys.tcl
#.Author:        Eric P. Clevenger
#.Description:   Sets up Tcl/Tk and pulls in necessary packages for ANSYS
#.               to make use of Tcl/Tk.
#.============================================================================

# ===========================================================================
# = NAMESPACE
# ============================================================================

# ----------------------------------------------------------------------------
# GLOBAL NAMESPACE:  ::ansys
#
# Purpose:        This namespace creates an ansys context
#
# ----------------------------------------------------------------------------
namespace eval ::ansys {
   variable library [file dirname [info script]]
   variable version 1.0
   variable installdir [eval file join [lrange [file split $library] 0 end-2]]
}

         
proc ansys::init {} {
   global argc argv
   global env
   global auto_path
   global ansysRevision
   global ansysRevDot
   global ansysLanguage
   global tcl_platform
   global tk_titleheight
   global tk_borderwidth
   global tk_posinternal

   # The msgcat version 1.1.1 has a bug in it so force 1.1 this should keep any
   # other calls safe
   package require msgcat


   # Set the auto_path information so that package require and the finding
   # of the correct tclIndex files will occur. This must be the first bit
   # of code.
   # Append to the auto_path the directory for gui scripts
   lappend auto_path [file join $ansys::library]
   # Append to the auto_path the main lib directory for enhanced UIDL
   lappend auto_path [file join $ansys::installdir lib]
   # Append to the auto_path the scripts library for ANSYS
   lappend auto_path [file join $ansys::installdir lib scripts]
   # Append to the auto_path the ansinfo location for all platforms
   lappend auto_path [file join $ansys::installdir .. \
         commonfiles launcher lib]

   # On a UNIX box must know where HOME is to setup properly
   if {[string match unix $tcl_platform(platform)]} {
      if {![info exists env(HOME)]} {
         ans_senderror 4 [msgcat::mc "The environment variable HOME must be set to use the ANSYS GUI"]
         return
      }
   }

   # Determine which revision of ansys is running
   set ansysRevision [ans_getvalue ACTIVE,,REV]
   set ansysRevDot [format %0.1f $ansysRevision]
   set ansysRevision [expr int($ansysRevision * 10)]
   # In case someone uses ANSYS_REVN we will make sure it is set mainly
   # for the MS/OS side.
   if {![info exists env(ANSYS_REVN)]} {
      set env(ANSYS_REVN) $ansysRevision
   }

   # Should no longer use this directory but use the registry, there is much
   # code that needs changed to use only the registry

   if [string match windows $tcl_platform(platform)] {
      set regError 1
      # We attempt to first store the information in the USER's 
      # Shell folders.
      if {![catch {::ansys::registry keys \
            "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders"} err]} {
         if {![catch {::ansys::registry get \
            "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders" AppData} env(ANSYS_APPDATA_DIR)]} {
            set userHome $env(ANSYS_APPDATA_DIR)
            set regError 0
         }
      }

      # If the registry didn't provide information try using environment
      if {$regError} {
         if {[info exists env(HOMEDRIVE)] && [info exists env(HOMEPATH)]} {
            if {[file writable "$env(HOMEDRIVE)$env(HOMEPATH)"]} {
               set userHome $env(HOMEDRIVE)$env(HOMEPATH)
            } else {
               if {[info exists env(ANSYS_APPDATA_DIR)]} {
                  set userHome $env(ANSYS_APPDATA_DIR)
               } else {
                  # Look for a local "drive" we can write to but set a default
                  # which well may not work
                  set userHome C:/
                  foreach drive [file volume] {
                     if {[string match "A:/" $drive] \
                           || [string match "B:/" $drive]} {
                        continue
                     }
                     if {[file writable "$drive"]} {
                        set userHome $drive
                     }
                  }
               }
            }
         } else {
            if {[info exists env(ANSYS_APPDATA_DIR)]} {
               set userHome $env(ANSYS_APPDATA_DIR)
            } else {
               # Look for a local "drive" we can write to but set a default
               # which well may not work
               set userHome C:/
               foreach drive [file volume] {
                  if {[string match "A:/" $drive] \
                        || [string match "B:/" $drive]} {
                     continue
                  }
                  if {[file writable "$drive"]} {
                     set userHome $drive
                  }
               }
            }
         }
      }
   } else {
      set userHome [file nativename ~]
   }

   # Set up a directory for saving ansys data like user materials and if 
   # unix the registry

   if {[string match unix $tcl_platform(platform)]} {
      set dirName ".ansys"
   } else {
      set dirName "Ansys"
   }

   # First check if a file exists with name $dirNam
   if {[file isfile [file join $userHome $dirName]]} {
      if {[catch {file rename -force [file join $userHome $dirName] [file join $userHome $dirName.bak]}]} {
         ans_senderror 4 [msgcat::mc "The file \"%s\" must be removed to allow the ANSYS GUI to operate.  This directory is used by ANSYS to maintain settings.  You may also set the environment variable ANSYS_APPDATA_DIR to the location to create this directory." [file join $userHome $dirName]]
         return -code error
      } else {
         ans_senderror 2 [msgcat::mc "The file \"%s\" has been moved to \"%s\".  This name must be used as a directory by ANSYS to maintain settings." [file join $userHome $dirName] [file join $userHome $dirName.bak]]
      }
   }
   if {![file exists [file join $userHome $dirName ansys${ansysRevDot}]]} {
      if {[catch {file mkdir \
               [file join $userHome $dirName ansys${ansysRevDot}]}]} {
            ans_senderror 4 [msgcat::mc "The directory \"%s\" could not be created to maintain ANSYS settings.  Please set the permissions on your HOME directory to allow creation of files.  You may also set the environment variable ANSYS_APPDATA_DIR to the location to create this directory." [file join $userHome $dirName ansys${ansysRevDot}]]
      } else {
            ans_senderror 1 [msgcat::mc "The directory \"%s\" has been created to maintain ANSYS settings" [file join $userHome $dirName ansys${ansysRevDot}]]
      }
   }
   set env(EUIDL_DEFAULTS) [file join $userHome $dirName ansys${ansysRevDot}]

   # If this is UNIX O/S then set up the ansys "registry"
   if {[string match unix $tcl_platform(platform)]} {
      if {[file exists [file join $userHome $dirName ansys${ansysRevDot} ansys${ansysRevDot}.reg]]} {
         ansys::setRegistryFile \
               [file join $userHome $dirName ansys${ansysRevDot} ansys${ansysRevDot}.reg]
         ansys::readRegistry
      } else {
         ansys::setRegistryFile \
               [file join $userHome $dirName ansys${ansysRevDot} ansys${ansysRevDot}.reg]
         ansys::writeRegistry
      }
   }

   # Directory Context Initialization
   if ![string length [array names env EUIDL_DIR]] {
      set env(EUIDL_DIR) $env(ANSYS${ansysRevision}_DIR)
      set env(EUIDL_SYSTEM) $env(ANSYS_SYSDIR)
   }
   
   # EUIDL can only be used if Tk is being used
   if {![catch {package require Tk}]} {
      wm withdraw .
      wm overrideredirect . 1
      wm geometry . 1x1+2000+2000
      wm deiconify .
      package require Euidl
      #  Withdraw the global window which is to never be used
      wm withdraw .
      wm overrideredirect . 0

      wm deiconify .
      if {[string match windows $tcl_platform(platform)]} {
         update
      }
      set tk_titleheight [euidl::wm titleheight .]
      set tk_borderwidth [euidl::wm borderwidth .]
      wm geom . +0+0

      if {[string match unix $tcl_platform(platform)]} {
         update
         set tk_posinternal [expr ![winfo rooty .]]
      } else {
         set tk_posinternal 0
      }
      wm withdraw .
      wm overrideredirect . 1
      # Not sure why this was done but will take out for now 
#      wm deiconify .
   }
   package require Uidl
   package require APDL
   package require Debug
   
   # Create a list of ANSYS commands for unknown command processing
   # This probably should read a file that has the commands.
   #lappend ansysCommands !
   
   # --------------------------------------------------------------------------
   # Process the command passed during initialization
   # --------------------------------------------------------------------------
   if [info exists argv] {
      uplevel #0 $argv
      unset argv
   }

   # Determine the language to use
   set langset 0
   # This is here in case the *GET is not in this version of ANSYS
   set notavail [catch {ans_getvalue COMMON,,SYARCM,,INT,19} langset]
   if {$notavail == 0 && $langset == 1} {
      set lang1 ""
      set lang2 ""
      set lang3 ""
      set chStrt 8
      set lang1 [ans_getvalue COMMON,,SYARCC,,CHAR,[expr $chStrt+0]]
      set lang2 [ans_getvalue COMMON,,SYARCC,,CHAR,[expr $chStrt+2]]
      set lang3 [ans_getvalue COMMON,,SYARCC,,CHAR,[expr $chStrt+4]]
      set ansysLanguage [string tolower [string trim $lang1$lang2$lang3]]
      if {[string match c $ansysLanguage] | [string match default $ansysLanguage)]} {
         set ansysLanguage en-us
      }
   } else {
      set ansysLanguage en-us
   }

}

proc ::ansys::columnwrite { str numcolumns args } {
   set fid {}
   set lineprefix {}

   set endcol [expr $numcolumns - 1]

   foreach {option txt} $args {
      switch -- $option {
         -f {
            set fid $txt
         }
         -p {
            set lineprefix $txt
         }
         default {
            error "Invalid argument \"$option $txt\".  Must be -f fid -p prefix"
         }
      }
   }

   set tmpstr $str

   while { [string length $tmpstr] > 0 } {
      # Remove any white space at the beginning of the string
      set tmpstr [string trimleft $tmpstr " "]

      # Add prefix to str, if one has been defined.
      if { ![string match {} $tmpstr] && ![string match {} $lineprefix] } {
         set tmpstr "$lineprefix $tmpstr"
      }

      if { [string wordend $tmpstr $endcol] > $endcol } {
         set tmpendcol [expr [string wordstart $tmpstr $endcol] - 1]
      } else {
         set tmpendcol $endcol
      }

      # Check to see if there is a right bracket/parenthesis directly after
      # the split
      set id [expr $tmpendcol + 1]
      set tmpchr [string range $tmpstr $id $id]
      if { [string match "\}" $tmpchr] || \
           [string match "\)" $tmpchr] } {
         # Find the previous left bracket/parenthesis
         set id $tmpendcol
         set found_left_bracket 0

         while { ![list $found_left_bracket] } {
            set tmp_chr [string range $tmpstr $id $id]
            if { [string match \{ $tmp_chr] } {
               set found_left_bracket 1
            } else {
               incr id -1
            }
         }
         set tmpendcol [expr $id-1]
      }

      set found_special 1

      while { [list $found_special] } {
         set last_char [string range $tmpstr $tmpendcol $tmpendcol]
         if { [string match "\{" $last_char] || \
              [string match "\(" $last_char] } {
            incr tmpendcol -1
         } else {
            set found_special 0
         }
      }

      # Output the partial string, either to display or file
      if { [string match {} $fid] } {
         puts [string range $tmpstr 0 $tmpendcol]
      } else {
         puts $fid [string range $tmpstr 0 $tmpendcol]
      }

      # Remove the characters that were just output
      set tmpstr [string replace $tmpstr 0 $tmpendcol]
   }
}


namespace eval ansys {
   variable regSet 0
   variable regFile

   if {[string match unix $tcl_platform(platform)]} {

      # The following namespaces contain the mapping from registry root names
      # to the system predefined keys.  This allows all registry interactions
      # to theoretically work but may not make sense in a lot of cases.
      
      namespace eval ::HKEY_CURRENT_USER {
      }
      
      namespace eval ::HKEY_LOCAL_MACHINE {
      }
      
      namespace eval ::HKEY_USERS {
      }
      
      namespace eval ::HKEY_CLASSES_ROOT {
      }
      
      namespace eval ::HKEY_CURRENT_USER {
      }
      
      namespace eval ::HKEY_CURRENT_CONFIG {
      }
      
      namespace eval ::HKEY_PERFORMANCE_DATA {
      }
      
      namespace eval ::HKEY_DYN_DATA {
      }
   
      variable validRoots
   
      lappend validRoots HKEY_CURRENT_USER
      lappend validRoots HKEY_LOCAL_MACHINE
      lappend validRoots HKEY_USERS
      lappend validRoots HKEY_CLASSES_ROOT
      lappend validRoots HKEY_CURRENT_USER
      lappend validRoots HKEY_CURRENT_CONFIG
      lappend validRoots HKEY_PERFORMANCE_DATA
      lappend validRoots HKEY_DYN_DATA
   
      proc registry { option keyName args} {
         variable validRoots
   
         regexp {(HKEY_[^\\]*).*} $keyName match root
         if {[lsearch -exact $validRoots $root] == -1} {
            return -code error -errorinfo "bad root name \"$root\": must be HKEY_LOCAL_MACHINE, HKEY_USERS, HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, HKEY_CURRENT_CONFIG, HKEY_PERFORMANCE_DATA, or HKEY_DYN_DATA" "bad root name \"$root\": must be HKEY_LOCAL_MACHINE, HKEY_USERS, HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, HKEY_CURRENT_CONFIG, HKEY_PERFORMANCE_DATA, or HKEY_DYN_DATA"
         }
   
         switch -- $option {
            delete {
               regsub -all {\\} $keyName {::} nmspc
               if {[string match {} $args]} {
                  namespace delete ::$nmspc
                  writeRegistry
               } else {
                  ::${nmspc}::delValue $args
                  writeRegistry
               }
            }
            get {
               regsub -all {\\} $keyName {::} nmspc
               ::${nmspc}::getValue $args
            }
            keys {
               regsub -all {\\} $keyName {::} nmspc
               if {[catch {namespace parent ::$nmspc}]} {
                  return -code error "unable to open key: The system cannot find the file specified"
               }
               # This branch may not have any children
               set keys [list]
               foreach child [namespace child ::$nmspc] {
                  set rnmspc "::${nmspc}::"
                  regexp ${rnmspc}(.*) $child match key
                  lappend keys $key
               }
               return $keys
            }
            set {
               regsub -all {\\} $keyName {::} nmspc
               if {[string match {} $args]} {
                  # Create the new branch
                  createBranch $nmspc
                  writeRegistry
               } else {
                  set key [lindex $args 0]
                  set value [lindex $args 1]
                  set type [lindex $args 2]
                  if {[catch {::${nmspc}::setValue $key $value $type}]} {
                     # The branch didn't exist so create it
                     createBranch $nmspc
                     ::${nmspc}::setValue $key $value $type
                  }
                  writeRegistry
               }
            }
            type {
            }
            values {
               regsub -all {\\} $keyName {::} nmspc
               ::${nmspc}::getValues $args
            }
         }
      }
   
      proc createBranch { nmspc } {
         # create a new branch
         namespace eval ::$nmspc {
            variable regKey
            set regKey(keys,epc) [list]
   
            proc delValue { key } {
               variable regKey
               unset regKey($key)
            }
            proc getValue { key } {
               variable regKey
               if {[catch {set regKey($key)}]} {
                  return -code error "unable to open key: The system cannot find the file specified"
               } else {
                  return $regKey($key)
               }
            }
            proc getValues { key } {
               variable regKey
               set values [list]
               foreach {valueName value} $regKey(keys,epc) {
                  lappend values $valueName
               }
               return $values
            }
            proc setValue { key value {type sz}} {
               variable regKey
               if {[string match {} $type]} {
                  set type sz
               }
               switch -- $type {
                  sz {
                     set regKey($key) "$value"
                     set keyLoc [lsearch -exact $regKey(keys,epc) $key]
                     if {$keyLoc == -1} {
                        lappend regKey(keys,epc) $key \"$value\"
                     } else {
                        incr keyLoc
                        set regKey(keys,epc) \
                           [lreplace $regKey(keys,epc) \
                                 $keyLoc $keyLoc \"$value\"]
                     }
                  }
                  dword {
                     set regKey($key) $value
                     set keyLoc [lsearch -exact $regKey(keys,epc) $key]
                     # type dword means that the value is to be hex and must
                     # be converted
                     set value [format %08x $value]
                     if {$keyLoc == -1} {
                        lappend regKey(keys,epc) $key dword:$value
                     } else {
                        incr keyLoc
                        set regKey(keys,epc) \
                           [lreplace $regKey(keys,epc) \
                                 $keyLoc $keyLoc dword:$value]
                     }
                  }
                  default {
                     return -code error "The type \"$type\" is not supported only sz and dword"
                  }
               }
            }
         }
      }   
   
      proc readRegistry {} {
         variable regFile
   
         set fileID [open $regFile r]
         while {[gets $fileID line] >= 0} {
            if {[regexp {^\[} $line]} {
               set line [string trimleft $line "\["]
               set line [string trimright $line "\]"]
               set line "::$line"
               regsub -all {\\} $line {::} nmspc
               createBranch $nmspc
            }
            if {[regexp {^\"} $line]} {
               # This is a setting
               set valLine [split $line =]
               set key [lindex $valLine 0]
               regsub -all {"} $key {} key
               #"
               # The getValue is dependent on its type and should be handled so
               set value [lindex $valLine 1]
               if {[regexp {^\"} $value]} {
                  # type sz
                  regsub -all {"} $value {} getValue
                  #"
                  set ${nmspc}::regKey($key) $getValue
               } elseif {[regexp {^dword:(.*)} $value match getValue]} {
                  # type dword means that the value is hex and must be converted
                  scan $getValue %x getValue
                  set ${nmspc}::regKey($key) $getValue
               } else {
                  # unknown types for now
                  set ${nmspc}::regKey($key) $value
               }
               lappend  ${nmspc}::regKey(keys,epc) $key $value
            }
         }
         close $fileID
      }
      proc writeRegistry { } {
         variable regFile
   
         # We are only going to worry about HKEY_CURRENT_USER for now.
         set fileID [open $regFile w]
         puts $fileID "REGEDIT4"
         puts $fileID ""
         puts $fileID "\[HKEY_CURRENT_USER\]"
         if {![string match {} [info vars ::HKEY_CURRENT_USER::regKey]]} {
            foreach {key value} [::HKEY_CURRENT_USER::getValue keys,epc] {
               # this must check the type to see if " necessary
               puts $fileID "\"$key\"=\"$value\""
            }
         }
         # We must determine if the toplevel namespace has any children
         if {![string match {} [namespace child ::HKEY_CURRENT_USER]]} {
            writeTree ::HKEY_CURRENT_USER $fileID
            puts $fileID ""
            close $fileID
         } else {
            puts $fileID ""
            close $fileID
         }
   
         # and so forth for the others
      }
   
      proc writeTree { parent fileID} {
         #foreach child [lsort -dictionary [namespace child $parent]] {}
         foreach child [lsort [namespace child $parent]] {
            set name [string trimleft $child :]
            regsub -all {::} $name {\\} name
            puts $fileID ""
            puts $fileID "\[$name\]"
            if {![string match {} [info vars ${child}::regKey]]} {
               # This needs to not use array but rather a ordered list
               foreach {key value} [::${child}::getValue keys,epc] {
                  puts $fileID "\"$key\"=$value"
               }
            }
            if {![string match {} [namespace child $child]]} {
               writeTree $child $fileID
            }
         }
      }
      proc setRegistryFile { filename } {
         variable regFile
         set regFile $filename
         return
      }
   
   } else {
      # Make use of the windows registry
      proc registry { args } {
         variable regSet
         if {[incr regSet] == 1} {
            package require registry
            uplevel #0 rename registry ans_registry
         }
         set rtn [uplevel #0 ans_registry $args]
         return $rtn
      }
   }
}

proc ::ansys::getRelativePath {str {lvl 4}} {
   global tcl_platform

   set dirname {}
   set retval $str

   # Get the current working directory.
   set cdir [pwd]

   # Get copy of target directory
   set tdir $str

   if { [string match windows $tcl_platform(platform)] } {
      set cdir [file attributes $cdir -longname]
      catch {set tdir [file attributes $tdir -longname]}
   }

   # Check to see if target directory is already relative
   if { [string match [file pathtype $tdir] "relative"] } {
      # Replace a /./ which indicates the same directory and is not needed
      # catch { regsub -all "/\./" $retval "/" retval } de93548 use string map instead
      catch { set retval [string map {"/./" "/"} $retval]}
      # Strip out a ./ at front which indicates the current directory
      catch { regsub -all {^\./} $retval "" retval }
      # Replace a \.\ (PC case) which indicates the same directory 
      catch { regsub -all {\\\.\\} $retval {\\} retval }
      return $retval
   }

      set d1 [file split $cdir]
      set d2 [file split $tdir]

      set id 0
      # Check for matching paths between directories keeping track of list
      # index of last current match.
      while { [string match [lindex $d1 $id] [lindex $d2 $id]] } {
         incr id
         # Error check to prevent an infinite loop.
         if { $id > 100 } {
            break
         }
      }

      # Get the remaining portions of the current and target directories
      # that do not match.
      set cRemaining [lrange $d1 $id end]
      set tRemaining [lrange $d2 $id end]

      # Get how many directory levels there are in the remaining sections.
      set clen [llength $cRemaining]
      set tlen [llength $tRemaining]

      if { $tlen > $lvl || $clen >= $lvl } {
         set retval $str
      } else {
         # Using the remaining directories in the currend path, add .. for each
         # dirctory.
         set retval {}
         for { set i 0 } { $i < $clen } { incr i } {
            set retval [file join $retval ..]
         }

         if { [string match {} $retval] } {
            set retval "."
         }
         if { ![string match {} $tRemaining] } {
            set retval [eval file join $retval $tRemaining]
         }
      }
   # Replace a /./ which indicates the same directory and is not needed
   # catch { regsub -all "/\./" $retval "/" retval } de93548 use string map instead
	 catch { set retval [string map {"/./" "/"} $retval]}
   # Strip out a ./ at front which indicates the current directory
   catch { regsub -all {^\./} $retval "" retval }
   # Replace a \.\ (PC case) which indicates the same directory 
   catch { regsub -all {\\\.\\} $retval {\\} retval }

   if { [string length $str] < [string length $retval] } {
      # The relative path is longer than the original path.  Return the
      # original path
      return $str
   }
   return $retval
}

proc ::ansys::getJobname { } {
   set lennam [ans_getvalue active,,LNAM]
   # Get the jobname in sets of 8 characters
   for {set i 0} {$i <= [expr $lennam/8]} {incr i} {
      lappend jobname [ans_getvalue ACTIVE,,JOBNAM,,START,[expr ($i*8)+1]]
   }
   set jobname [string trim [join $jobname {}]]
   return $jobname
}

ansys::init
package provide ansys $ansys::version
