; Script to open NX Part and excute NX Macro
; Ersteller.....:  J.Feuerstein
; Ersterstellung:  30.12.2014
; Stand.........:  25.11.2015 01:24
; Stand.........:  29.15.2015 10:00/J.Fes

;inculdes
 #include <Date.au3>
 #include <WinAPI.au3>
 #include <Constants.au3>
 #include <File.au3>
 #include <Array.au3>

 $NxTitle = "NX 8.5 -"
 $InfoTxt = "Open Part and Execute Macro"

 $NXMode = "TC"
 $NXMode = "NATIV"
 $MyAppVer = "V1.03"
 $MyAppTitel = "NX Macro (" & $MyAppVer & ")"

 $PartN =  "D:\NxData\000013\000005_A.prt"
 $NxTitlePartName = "000005_A.prt"
 $PartRev = ""
 $PartName = ""
 $NXMacro_DPNE = "V:\JobManager\ProgEntw\Ver02\JobManagerV2\90-DATA\CustomerNameShort_SettingsGlobal\10-JobScripts\NxMacroExcute\ClientScripts\NXMacros\NXMacroNativTemplate.macro"

#Region Parameter übergabe ------------------------------------------------------------------
 if $CmdLine[0] > 0 then
   $NxTitle = $CmdLine[1]
 endif

 if $CmdLine[0] > 1 then
   $InfoTxt = $CmdLine[2]
 endif

 if $CmdLine[0] > 2 then
   $NXMode = $CmdLine[3]
 endif

 if $CmdLine[0] > 3 then
   $PartN = $CmdLine[4]
 endif

 if $CmdLine[0] > 4 then
   $PartRev = $CmdLine[5]
 endif

 if $CmdLine[0] > 5 then
   $PartName = $CmdLine[6]
 endif

 if $CmdLine[0] > 6 then
   $NxTitlePartName = $CmdLine[7]
 endif

 if $CmdLine[0] > 7 then
   $NXMacro_DPNE = $CmdLine[8]
 endif
#EndRegion

; Globale Variablen !
 $NxTitleOpenTitelByAutoIt = $NxTitle & " Open:["
 $NxTitleNoPartLoaded = $NxTitle &  " [No Part]"
 $NxTitleGateway = $NxTitle & "Gateway"

 $NxTitleModeling = "- Modeling"
 $NxTitleCloseAllParts = "NX schliesse alle Teile ..."
 $NxTitleWait = $NxTitle & " do wait .. "
 $NxTitleRoutingToAppli = "Router"

 if $NXMode="TC" Then
  $NxTitleOpenDialog = "Open Part File"
  $NxTitlePartName = $PartN & "/" & $PartRev
 else
  $NxTitleOpenDialog = "Open"
 endif


 $NxTitleTimingMonitor = "UG/Manager Timing Monitor"
 $NxTitlePerformanceCmd = "TC-Nx Performance Messung"
 $NxProgExe = "ugraf.exe"
 $NxProgExe_PID = "0"
 $NxRouterProgExe = "ugs_router.exe"
 $NxTitleTimingMonitor = "UG/Manager Timing Monitor"
 ; siehe func TimeCheckRunOnFile
 $TimeCheckRunOnFile_DPNE = ""

 $ProgressOn_X=40
 $ProgressOn_Y=750

 $Debug = 1
 $Test = 1
;~  #Doc legt fest in welchem Modus NX betrieben wird N=Nativ TC=In TC Umgebung (3.10.2012)

 $Wait01_Msec = 1000
 $Wait02_Msec = 2000
 $Wait03_Msec = 500

; Bin Verzeichniss
 $Bin_DP=@ScriptDir
 $Root_DP=@ScriptDir


;-- Set Defaults --- --------------------------------------------------------------------------------
;~   Alters the method that is used to match window titles during search operations.
;~ 1 = Match the title from the start (default)
;~ 2 = Match any substring in the title
;~ 3 = Exact title match
;~ 4 = Advanced mode, see Window Titles & Text (Advanced)
;~ -1 to -4 = force lower case match according to other type of match.
;~   Opt("WinTitleMatchMode", 1) ;1=start, 2=subStr, 3=exact, 4=advanced, -1 to -4=Nocase


 $WinTitleMatchMode_1Start = 1
 $WinTitleMatchMode_2SubStr = 2
 $WinTitleMatchMode_3Exact = 3
 $WinTitleMatchMode_4Advanced = 4
 $WinTitleMatchMode_Default = $WinTitleMatchMode_1Start
 AutoItSetOption("WinTitleMatchMode", $WinTitleMatchMode_Default)

#Region #Doc: Verwendbare Routinen -----------------------------------------------------------
;~
;~ WinSetOnTop ( "title", "text", flag )
;~ $handle = WinGetHandle("Untitled - Notepad", "")
;~ WinClose($handle)
;~ Local $var = EnvGet("PATH")
;~ MsgBox(4096, "Path variable is:", $var)
;~ WinSetState ( "title", "text", flag )
;~ -----------------------------------------------------------------------------------------
#EndRegion

; ---------------------------------------
; Hauptroutine
;$NxProgExe_PID = ProcessExists($NxProgExe)
;  $ret = OpenPartAndExcuteMacro()

 $ret = -1
 $ret = NXMacroExecute()

 exit $ret

; -------------------------------------------------------------------------------------------------
Func Test()
 $NxProgExe_PID = run("notepad")
  ;~    WinActivate($NxTitle)
  Local $hWnd=WinWaitActive("[CLASS:Notepad]","",5)
    _WinAPI_SetWindowPos($hWnd, $HWND_TOP, 500,500, 400, 800, $SWP_FRAMECHANGED)
EndFunc


Func NXMacroExecute()
   Local $ret = 0
   Global $WinTitleMatchMode_Cur = Opt("WinTitleMatchMode", $WinTitleMatchMode_1Start)
   Global $NxCurrTitle = WinGetTitle($NxTitle, "")
   Global $WinActivateResult = WinActivate($NxTitle, "")
   Global $szDrive, $szDir, $szFName, $szExt, $Macro_NE
   ; Global $TestPath = _PathSplit(@ScriptFullPath, $szDrive, $szDir, $szFName, $szExt)
   Global $TestPath = _PathSplit($NXMacro_DPNE, $szDrive, $szDir, $szFName, $szExt)
   $Macro_NE = $szFName & $szExt
   $ret = MacroStart()
   Return $ret
EndFunc

;-- Descripton: Sends Start Macro to NX Session ----------------------------------------------------
;-- New.......: 28.11.2015 23:12 / J.Fes  ----------------------------------------------------------
Func MacroStart()

   Local $ret = 0
  
   ProgressOn($MyAppTitel & ":"  & $Macro_NE, "Part:", $NxTitlePartName, $ProgressOn_X, $ProgressOn_Y)

   Local $MacroStartOK = 0
   Local $MacroStartTry = 0
   Local $MacroSendEnterTry = 0
   Local $ProgressSubTitel = ""
   ;-- WinExists Doc:
   ;-- Success: Returns 1 if the window exists.
   ;-- Failure: Returns 0 otherwise.
   While WinExists("Macro Playback", "") = 0

     ;-- Init Contol Variables
     $MacroStartTry = $MacroStartTry + 1
     $ProgressSubTitel = "NX Macro Try:"  & $MacroStartTry  & "/3 max"
     ProgressSet(20 , $ProgressSubTitel, "NX Macro:" & $Macro_NE)

     ;-- #Step: sende Key to get macro dialog open ----------
     ;-- #Step: sende ESC sequezen um alle laufenden Dialog abzubrechen
     send ("{ESC}{ESC}{ESC}",0)
     Sleep($Wait01_Msec)
     ;-- #Step: Execute NX.Macro Shift + Strg + p
     Send("^+p", 0)

     If WinWaitActive("Macro Playback", "", 1) > 0 then
       ;-- wenn das "Macro Playback" Fenster gefunden wird
       ProgressSet(40 , "OK: Macro Playback Win found", "send now Macro File")

       WinActivate("Macro Playback")
       Sleep($Wait01_Msec)
       ;-- Naviagte to input filename
       Send("!n")
       WinActivate("Macro Playback")
       Send(" ")
       ;-- Update 18.08.2015
       WinActivate("Macro Playback")
       Send("{BACKSPACE 5}")
       Sleep($Wait03_Msec)

       ;-- #Step insert MacroFile
       WinActivate("Macro Playback")
       Send($NXMacro_DPNE)
       
       ;-- #Doc: WinExists() = 1 Win Exists / 0 Win NOT Exsits
       While WinExists("Macro Playback", "") = 1
         
         Sleep($Wait01_Msec)
         ;-- #Step: sende Return 
         $MacroSendEnterTry = $MacroSendEnterTry + 1
         ;-- #Step: springe zum End der Zeile
         WinActivate("Macro Playback")
         Send("{END}", 0)
         ;-- #Step: sende Enter um das Macro auszuloesen
         WinActivate("Macro Playback")
         Send("{ENTER}", 0)
         ProgressSet(60 , "Wait max 2sec after send ENTER try:" & $MacroSendEnterTry , "P.NX.Macro:" & $Macro_NE)
         ;-- #Doc: WinWaitClose() = 1 Win is closed  Exists / 0 Win NOT Exsits
         WinWaitClose("Macro Playback", "", 2) 
         
         if WinExists("Macro Playback", "") = 0 then
            ;-- #Doc: wenn jetzt der Dialog geschlossen ist alles OK
            ProgressSet(80 , "OK: send ENTER after " & $MacroSendEnterTry &  "'t try", "P.NX.Macro:" & $Macro_NE)
            $MacroStartOK = 1
            ExitLoop
           Else
            ;-- #Doc: wenn jetzt der Dialog nicht geschlossen retry
            ProgressSet(80 , "WRN: send ENTER after " & $MacroSendEnterTry &  "'t try", "P.NX.Macro:" & $Macro_NE)
            $MacroStartOK = 0
         EndIf

         if $MacroSendEnterTry >= 3 then
            ProgressSet(90 , "ERR: send ENTER after 3't try", "P.NX.Macro:" & $Macro_NE)
            $ret = 4
            ExitLoop
         EndIf
       WEnd
       
     EndIf

     ;-- Exit wenn alles OK
     if $MacroStartOK = 1 then
       ProgressSet(100 , "OK: well Done", "P.NX.Macro:" & $Macro_NE)
       $ret = 0
       ExitLoop
     EndIf

     ;-- Exist nach dem 3'tem Versuch mit $ret = 2
     if $MacroStartTry >= 3 then
       ProgressSet(100 , "ERR: MacroStart after 3'te try", "P.NX.Macro:" & $Macro_NE)
       $ret = 2
       ExitLoop
     EndIf

     ProgressSet(100 , "WRN: Wait for Next try", "P.NX.Macro:" & $Macro_NE)
     Sleep($Wait02_Msec)
   WEnd

   ;-- Close Process Dialog
   ProgressOff()
   Return $ret

EndFunc

; -------------------------------------------------------------------------------------------------
Func NXMacroExecuteXX()
  $ret = 0


  $WinTitleMatchMode_Cur = Opt("WinTitleMatchMode", $WinTitleMatchMode_1Start)
  $NxCurrTitle = WinGetTitle($NxTitle, "")
  $WinActivateResult = WinActivate($NxTitle, "")
  ; Datei öffnen "working...: [" &
  ; ProgressSet(10 ,  $NxCurrTitle & "]" & "[WinAct:" & $WinActivateResult & "]", "1.load:" & $NxTitlePartName)

  Local $szDrive, $szDir, $szFName, $szExt, $Macro_NE
  Local $TestPath = _PathSplit(@ScriptFullPath, $szDrive, $szDir, $szFName, $szExt)
  ; _ArrayDisplay($TestPath, "Demo _PathSplit()")

  $Macro_NE = $szFName & $szExt


  ProgressOn("P.NX.Macro:"  & $Macro_NE, "Part:", $NxTitlePartName, $ProgressOn_X, $ProgressOn_Y)
  ProgressSet(20 , "P.NX.Macro:" & $Macro_NE, "P.NX.Macro:" & $Macro_NE)

  send ("{ESC}{ESC}{ESC}",0)
  ;-- #Step: Execute NX.Macro Shift + Strg + p
  Sleep($Wait01_Msec)
  ; send Strg + Shift + p
  Send("^+p", 0)
  Sleep($Wait01_Msec)
  WinActivate("Macro Playback")
  Sleep($Wait02_Msec)
  WinActivate("Macro Playback")
  Send("    ")
  ;-- Update 18.08.2015
  Send("{BACKSPACE 5}")
  Sleep($Wait03_Msec)
  WinActivate("Macro Playback")
  Send($NXMacro_DPNE)
  Sleep($Wait01_Msec)

  WinActivate("Macro Playback")
  Send("{END}", 0)

  WinActivate("Macro Playback")
  Send("{ENTER}", 0)

  ProgressSet(60 , "wait:Process Macro:" & $Macro_NE, "wait:Process Macro:" & $Macro_NE)
  ;-- 25.11.2015 01:54 not in use
  ;-- ProcessWaitUntilIdel($NxProgExe,4000,80)
  Return $ret

EndFunc


; ----------------------------------------------------
Func ProcessWaitUntilIdel($Prozess, $WaitTimeOutTime,$ProzessTimeStopWhileGth)

 ; $ProzessTimeStopWhileGth sollte eigendlich immer = 0 sein !

 $pid = ProcessExists($Prozess)
 if $pid>0 then
    $ProgressTitle="Prog:" & $Prozess & " Pid:" & $pid
    ;ProgressOn("ProcessWaitIdel:" & $ProgressTitle , $ProgressTitle , "",$ProgressOn_X,$ProgressOn_Y)
    ;sleep(2000)
    $ProzessTimeL=ProcessWaitUntilIdelMeasure($pid)
    $ProzessTime=1
    $ProzessCoundM=10
    While $ProzessTime > $ProzessTimeStopWhileGth
       $ErrorRunCheck = ErrorRunCheck()
       sleep($WaitTimeOutTime)
       $ProzessTimeN=ProcessWaitUntilIdelMeasure($pid)
       $ProzessTime=$ProzessTimeN-$ProzessTimeL
       ProgressSet(50 , $Prozess & "=[" & $pid & "]" & "L=" & $ProzessTimeL & "/N=" & $ProzessTimeN & "/C=[" & $ProzessTime & "]" )
       ; ProgressSet($ProzessCoundM , "ProcessWaitUntilIdel:=" & $ProzessCoundM )
       $ProzessTimeL=$ProzessTimeN
       if $ProzessCoundM = 100 then
          $ProzessCoundM=10
       else
          $ProzessCoundM=$ProzessCoundM + 10
       endif
    WEnd
    return 1
 else
    $ErrorRunCheck = ErrorRunCheck()
    return 0
 endif
EndFunc
; ----------------------------------------------------
Func ProcessWaitUntilIdelMeasure($pid)
; Holt die aktuelle UserTime eines Prozesses
;
;Name         Pid Pri Thd  Hnd    Mem     User Time   Kernel Time   Elapsed Time
;java        2496   8  22  575  24488   0:00:14.328   0:00:04.703    2:57:22.234

 $file_DPNE=EnvGet("TEMP") & "\_CPUI.TMP"
 $file = FileOpen($File_DPNE, 0)
 RunWait("cmd /c " & $Bin_DP & "\pslist.exe " & $pid & " | findstr /i " & $pid & ">" & $file_DPNE, "",@SW_HIDE )

 $line = FileReadLine($file)
 $cpuUserTimeStr=StringMid($line,38,51-38)
 $cpuUserTimeLong=StringMid($cpuUserTimeStr,14-3,3)+ StringMid($cpuUserTimeStr,14-6,2)*1000 + StringMid($cpuUserTimeStr,14-9,2)*100000 ; + StringMid($cpuUserTimeStr,14-11,2)*10000000
 FileClose($file)
 return $cpuUserTimeLong
EndFunc
