Test are now working

Test are now working

#Region include for test
#include <../micro.au3>
#EndRegion

#Region Test suite definition
Local $testSuite = _testSuite_("Test Suite Test")

$testSuite.addTest(assertTruePass())

$testSuite.finish()
#EndRegion

#Region Test Functions
Func assertTruePass()
    $test = _test_("assertTrue(true) returns pass")
	$test.assertTrue("True", True)
    Return $test
EndFunc
Func assertTrueFail()
    $test = _test_("assertTrue(true) returns pass")
	$test.assertTrue("False", False)
    Return $test
EndFunc

#EndRegion

#AutoIt3Wrapper_UseX64=n

#Region include for test
#include <../micro.au3>
#EndRegion

#Region Test suite definition
Local $testSuite = _testSuite_("Test Suite Test")

$testSuite.addTest(assertTruePass())

$testSuite.finish()
#EndRegion

#Region Test Functions
Func assertTruePass()
    $test = _test_("assertTrue(true) returns pass")
	$test.assertTrue("True", True)
    Return $test
EndFunc
#EndRegion


Update Hour2Sec.au3

Update Hour2Sec.au3

Convert a time string to seconds.
Converte uma string de tempo para segundos.
"02:30:00" => 5400


send messages binaries

send messages binaries

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Icon=..\..\images\RT1.ico
#AutoIt3Wrapper_Outfile=SendTelegramSubteBA.exe
#AutoIt3Wrapper_Compression=4
#AutoIt3Wrapper_UseUpx=n
#AutoIt3Wrapper_UseX64=y
#AutoIt3Wrapper_Change2CUI=y
#AutoIt3Wrapper_Res_Comment="By Marcelo N. Saied "
#AutoIt3Wrapper_Res_Description="Send Telegram application Message"
#AutoIt3Wrapper_Res_Fileversion=1.0.0.1
#AutoIt3Wrapper_Res_ProductVersion=1.0
#AutoIt3Wrapper_Res_LegalCopyright=Marcelo N. Saied
#AutoIt3Wrapper_Res_Field=Productname|SendTelegramSubteBA.exe
#AutoIt3Wrapper_Res_Field=ProductVersion|Version 1.0
#AutoIt3Wrapper_Run_Obfuscator=y
#Obfuscator_Parameters=/mergeonly
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
; *** Start added by AutoIt3Wrapper ***
#include <FileConstants.au3>
; *** End added by AutoIt3Wrapper ***
;===================================================================
;===================================================================
;===                                                             ===
;===   Name   = SendTelegramSubteBA.exe                                 ===
;===                                                             ===
;===   Description:Send Telegram application Message             ===
;===                                                             ===
;===   Author: Marcelo N. Saied                                  ===
;===           marcelosaied@gmail.com                            ===
;===                                                             ===
;===   Automation and Scripting Language: AUTOIT  v3.3.8.1       ===
;===           http://www.autoitscript.com/site/                 ===
;===                                                             ===
;===   Created on: Jan 9 , 2016                                  ===
;===                                                             ===
;===================================================================
;===================================================================
#Region  ------------ AutoIt3Wrapper
$chatID=""
#EndRegion
#Region  ------------ Modules
	#include <File.au3>
	#include <Constants.au3>
	#include <Date.au3>
	#include <Array.au3>
	#include <date.au3>
	#include <IE.au3>
	#include <Array.au3>
	#include "..\..\udf\WinHttp.au3"
#EndRegion
#Region  -----------------------------  parse arguments ------------------------------
; Help
   $helpText="Help:                                                                     " & @crlf & _
			"                                                                           " & @crlf & _
			"      Usage:                                                               " & @crlf & _
			"          SendTelegramSubteBA.exe -m <message> -chatid chatid <optional>   " & @crlf & _
			"                                                                           " & @crlf & _
			"          -m   message                                                     " & @crlf & _
			"          -chatid  chatid  <optional>                                      " & @crlf & _
			"                                                                           " & @crlf & _
			"            Author: Saied, Marcelo                                         " & @crlf & _
			"                                                                           " & @crlf & _
			"                                      2017                                 " & @crlf & _
			"                                                                           " & @crlf & _
			"                                                                           " & @crlf & _
			"                                                                           " & @crlf & _
			"                                                                           "
;~

   if $CmdLine[0]=0 then
	  ConsoleWrite($helpText)
	   exit 1
   endif
   if StringStripWS($CmdLine[1],4)="?"   then  ; output help
	  ConsoleWrite($helpText)
	    exit 3
	endif
;~ 	ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $CmdLine[0] = ' & $CmdLine[0] & @crlf )
    if $CmdLine[0]<2 then  ; if no 3 argumentes then exit    -f filename  -u username -p password  ([-d][-nd])
	  ConsoleWrite("No enough arguments. <Usage>: SendTelegramSubteBA.exe -m <message> -chatid  chatid  <optional>  ")
	  exit 5
   endif

   for $x=1 to $CmdLine[0]-1
	  Select
		case $CmdLine[$x] = "-m"
			$x = $x + 1
			if StringLen($CmdLine[$x]) > 2 then   $mensaje=$CmdLine[$x]
		case $CmdLine[$x] = "-chatid"
			$x = $x + 1
			if StringLen($CmdLine[$x]) > 2 then   $chatID=$CmdLine[$x]
		 Case Else
			ConsoleWrite("No enough arguments <Usage>: SendTelegram.exe -m <message>  ")
			ConsoleWrite("                              SendTelegram.exe ?  for help  ")
			ConsoleWrite(@CRLF)
			exit 6
	  EndSelect
   Next
#EndRegion

SendTelegram($mensaje)
Func SendTelegram($msgtext="testeo")
	if SendTelegramexec($msgtext) Then
		sleep(3000)
		if $chatID<>"" then	SendTelegramexec($msgtext)
	endif
EndFunc

Func SendTelegramexec($msgtext="testeo harcoded")
	local $token=IniRead("..\..\secret\config.ini","bot","token","")
	$urlMSG="https://api.telegram.org/" & $token & "/sendMessage?chat_id=" & $chatid & "&text=" & $msgtext
	$sGet = HttpGet($urlMSG)

	if $sGet<>"0" then
		ConsoleWrite('Telegram Message sent = ' & $msgtext & @crlf )
		return 0
	Else
		$s_text="Error sending message to Telegram = "
		return 1
	endif
EndFunc

exit

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Icon=..\..\images\RT1.ico
#AutoIt3Wrapper_Outfile=SendTelegramSubteBA.exe
#AutoIt3Wrapper_Compression=4
#AutoIt3Wrapper_UseUpx=n
#AutoIt3Wrapper_UseX64=y
#AutoIt3Wrapper_Change2CUI=y
#AutoIt3Wrapper_Res_Comment="By Marcelo N. Saied "
#AutoIt3Wrapper_Res_Description="Send Telegram application Message"
#AutoIt3Wrapper_Res_Fileversion=1.0.0.1
#AutoIt3Wrapper_Res_ProductVersion=1.0
#AutoIt3Wrapper_Res_LegalCopyright=Marcelo N. Saied
#AutoIt3Wrapper_Res_Field=Productname|SendTelegramSubteBA.exe
#AutoIt3Wrapper_Res_Field=ProductVersion|Version 1.0
#AutoIt3Wrapper_Run_Obfuscator=y
#Obfuscator_Parameters=/mergeonly
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
; *** Start added by AutoIt3Wrapper ***
#include <FileConstants.au3>
; *** End added by AutoIt3Wrapper ***
;===================================================================
;===================================================================
;===                                                             ===
;===   Name   = SendTelegramSubteBA.exe                                 ===
;===                                                             ===
;===   Description:Send Telegram application Message             ===
;===                                                             ===
;===   Author: Marcelo N. Saied                                  ===
;===           marcelosaied@gmail.com                            ===
;===                                                             ===
;===   Automation and Scripting Language: AUTOIT  v3.3.8.1       ===
;===           http://www.autoitscript.com/site/                 ===
;===                                                             ===
;===   Created on: Jan 9 , 2016                                  ===
;===                                                             ===
;===================================================================
;===================================================================
#Region  ------------ AutoIt3Wrapper
$chatID=""
#EndRegion
#Region  ------------ Modules
   #include <File.au3>
   #include <Constants.au3>
   #include <Date.au3>
   #include <Array.au3>
	#include <date.au3>
	#include <IE.au3>
	#include <Array.au3>
	#include "..\..\udf\WinHttp.au3"
#EndRegion
#Region  -----------------------------  parse arguments ------------------------------
; Help
   $helpText="Help:                                                                     " & @crlf & _
			"                                                                           " & @crlf & _
			"      Usage:                                                               " & @crlf & _
			"          SendTelegramSubteBA.exe -m <message> -chatid chatid <optional>   " & @crlf & _
			"                                                                           " & @crlf & _
			"          -m   message                                                     " & @crlf & _
			"          -chatid  chatid  <optional>                                      " & @crlf & _
			"                                                                           " & @crlf & _
			"            Author: Saied, Marcelo                                         " & @crlf & _
			"                                                                           " & @crlf & _
			"                                      2017                                 " & @crlf & _
			"                                                                           " & @crlf & _
			"                                                                           " & @crlf & _
			"                                                                           " & @crlf & _
			"                                                                           "
;~

   if $CmdLine[0]=0 then
	  ConsoleWrite($helpText)
	   exit 1
   endif
   if StringStripWS($CmdLine[1],4)="?"   then  ; output help
	  ConsoleWrite($helpText)
	    exit 3
	endif
;~ 	ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $CmdLine[0] = ' & $CmdLine[0] & @crlf )
    if $CmdLine[0]<2 then  ; if no 3 argumentes then exit    -f filename  -u username -p password  ([-d][-nd])
	  ConsoleWrite("No enough arguments. <Usage>: SendTelegramSubteBA.exe -m <message> -chatid  chatid  <optional>  ")
	  exit 5
   endif

   for $x=1 to $CmdLine[0]-1
	  Select
		case $CmdLine[$x] = "-m"
			$x = $x + 1
			if StringLen($CmdLine[$x]) > 2 then   $mensaje=$CmdLine[$x]
		case $CmdLine[$x] = "-chatid"
			$x = $x + 1
			if StringLen($CmdLine[$x]) > 2 then   $chatID=$CmdLine[$x]
		 Case Else
			ConsoleWrite("No enough arguments <Usage>: SendTelegram.exe -m <message>  ")
			ConsoleWrite("                              SendTelegram.exe ?  for help  ")
			ConsoleWrite(@CRLF)
			exit 6
	  EndSelect
   Next
#EndRegion

SendTelegram($mensaje)
Func SendTelegram($msgtext="testeo")
	if SendTelegramexec($msgtext) Then
		sleep(3000)
		if $chatID<>"" then	SendTelegramexec($msgtext)
	endif
EndFunc

Func SendTelegramexec($msgtext="testeo harcoded")
	local $token=IniRead("..\..\secret\config.ini","bot","token","")
;~ 	local $token="bot401033255:AAGp6iC1iAOSVXIjCAZ3hFuSrtnpJo6Z8BM"   ;  @SubteBA_bot
	$urlMSG="https://api.telegram.org/" & $token & "/sendMessage?chat_id=" & $chatid & "&text=" & $msgtext
	$sGet = HttpGet($urlMSG)

	if $sGet<>"0" then
		ConsoleWrite('Telegram Message sent = ' & $msgtext & @crlf )
		return 0
	Else
		$s_text="Error sending message to Telegram = "
		return 1
	endif
EndFunc

exit


latest version

latest version

;Shift+alt
HotKeySet("+!a", "startArena")
HotKeySet("+!z", "changeArenaTier")
HotKeySet("+!s", "idle")
HotKeySet("+!d", "fight")
HotKeySet("+!f", "findMatch")
HotKeySet("+!g", "nextNode")
HotKeySet("+!h", "fightArena")
HotKeySet("+!q", "Duel")
HotKeySet("+!p", "playthegame")
HotKeySet("+!c", "calibrateWindow")
HotKeySet("+!i", "showStatus")

Global $status="ngondek"
Global $savepixel = 0
Global $screensave[6]
$screensave[0] = 0
$screensave[1] = 0
$screensave[2] = 0
$screensave[3] = 0
$screensave[4] = 0
$screensave[5] = 0

;This indicates which arena tier shall be played, possible is 2, or 3
$arena_tier = 2
$arena_continue = 1
$allstop = 0
Do
   Sleep(1)
Until False

Func showStatus()
   ToolTip(StringFormat("%s", $status),0,0)
EndFunc

Func idle()
   $status = "idle"
   $allstop = 1
   MsgBox(0, "now", "terminated", 1)
   Do
	  Sleep(1)
   Until False
EndFunc   ;==>Terminate

Func playthegame()
   MouseClick("left", 26, 750) ;window start menu
   MouseClick("left", 70, 400) ;bluestack app
   Sleep(90000)
   MsgBox(0, "now", "i will now move the bluestack window", 5)
   MouseClickDrag("left", 90, 30, 75, 15)
   Sleep(2000)
   MouseClick("left", 913, 307) ;click the game
   Sleep(60000)
   playthearena()
EndFunc
Func playthearena()
   MouseClick("left", 162, 51)
   Sleep(1000)
   MouseClick("left", 271, 135) ;fight button
   Sleep(20000)
   MouseClick("left", 535, 313) ;versus
   Sleep(20000)
   startArena()
EndFunc

Func changeArenaTier()
   if ($arena_tier==2) Then
	  $arena_tier = 3
	  MsgBox(0, "arena tier", "arena tier is now 3", 2)
   Elseif ($arena_tier==3) Then
	  $arena_tier = 4
	  MsgBox(0, "arena tier", "arena tier is now alltier(when there is no event)", 2)
   ElseIf ($arena_tier==4) Then
	  $arena_tier = 5
	  MsgBox(0, "arena tier", "arena tier is now 5, the special high lvl arena(catalyst, alpha)", 2)
   Else
	  $arena_tier = 2
	  MsgBox(0, "arena tier", "arena tier is now 2", 2)
   EndIf
EndFunc

;Starts the arena (Fight menu), and continue (tier *2)
Func startArena()
   $status = "start arena"
   $allstop = 0
   Do
	  calibrateWindow()
	  $arena_continue = 1

	  Sleep(500)
	  if ($arena_tier==5) Then
		 MouseClickDrag("left", 700, 255, 130, 255);drag right mosst for foolproof
		 Sleep(500)
		 MouseClickDrag("left", 700, 255, 130, 255);drag right mosst for foolproof
		 Sleep(500)
	  Else
		 MouseClickDrag("left", 130, 255, 700, 255);drag left mosst for foolproof
		 Sleep(500)
		 MouseClickDrag("left", 130, 255, 700, 255);drag left mosst for foolproof
	  EndIf
	  Sleep(1000)

	  checkInsideFight()

	  if (Not(getDominantColor(PixelGetColor(346,535))=="green") AND (Not($arena_tier==5))) Then
		 MsgBox(0, "fight", "inside fight menu, not arena", 1)
		 MouseClickDrag("left", 130, 255, 700, 255);drag left mosst for foolproof
		 Sleep(400)
		 MouseClick("left", 500,446)
		 Sleep(2000)
		 Local $wait = 0
		 do
			Sleep(1000)
			$wait = $wait+1
			checkInsideFight()
		 Until (getDominantColor(PixelGetColor(435,525))=="green" OR ($wait>10))
	  EndIf

	  ;check if currently in one of 3 fights
	  if (PixelGetColor(160,222)==0x2b2c30 AND PixelGetColor(816,222)==0x2b2c30) Then
		 Local $leftresult=PixelGetColor(294,280) ;lose 721a1a red, win 26552e
		 Local $rightresult=PixelGetColor(697,280)
		 if ($leftresult==0x26552e OR $leftresult==0x721a1a) Then
			if ($rightresult==0x26552e OR $rightresult==0x721a1a) Then
			   MsgBox(0, "fight", "more fight to go", 1)
			   Sleep(1000)
			   MouseClick("left", 200,200)
			   fightArena()
			   $arena_continue = 0
			EndIf
		 EndIf
	  EndIf
	  checkInsideFight()
	  if ($arena_continue==1) Then
		 if ($arena_tier==2) Then
			;Send("9")
			MouseClick("left", 386, 446)
			Sleep(5000)
			MouseClick("left", 413, 522);double check
		 Elseif ($arena_tier==3) Then
			MouseClick("left", 830, 510)
			Sleep(5000)
			MouseClick("left", 760, 508);double check
		 Elseif ($arena_tier==4) Then ;arena tier 4
			MouseClick("left", 433, 522);
			Sleep(5000);
		 Else

			if (Not(getDominantColor(PixelGetColor(595,516))=="green") AND Not(getDominantColor(PixelGetColor(438,516))=="green")) Then
			   MsgBox(0, "fight", "inside fight menu, not arena (special)", 1)
			   MouseClickDrag("left", 130, 255, 700, 255);drag left mosst for foolproof
			   Sleep(1000)
			   MouseClickDrag("left", 130, 255, 700, 255);drag left mosst for foolproof
			   Sleep(1000)
			   MouseClick("left", 500,446)
			   Local $wait = 0
			   do
				  Sleep(1000)
				  $wait = $wait+1
				  checkInsideFight()
			   Until (getDominantColor(PixelGetColor(595,516))=="green" OR ($wait>10))
			   MouseClickDrag("left", 700, 255, 130, 255);drag right mosst for foolproof
			   MouseClickDrag("left", 700, 255, 130, 255);drag right mosst for foolproof
			   Sleep(1000)
			EndIf
			checkInsideFight()
			if (getDominantColor(PixelGetColor(438,516))=="green") Then
			   MouseClick("left",438,516)
			Else
			   MouseClick("left", 674, 508);
			EndIf
			Sleep(5000);
		 EndIf
	  EndIf

	  checkInsideFight()
	  Sleep(5000)
	  Local $current_arena_tier  = $arena_tier

	  askForHelp()
	  checkInsideFight()
	  if ($arena_continue==1) Then
		 ; We have energy, continue;else change arena tier in next loop
		 addToTeam()
		 findMatch()
		 fightArena()
	  EndIf

   Until ($allstop==1)
EndFunc

Func askForHelp()
   $status = "ask for help"
   Local $carryon = 1
   Do
	  ;Detect if we can ask for help
	  Local $helpbutton = PixelGetColor(260, 175)
	  Local $red = BitShift($helpbutton, 16)
	  Local $green = BitShift(BitAND($helpbutton, 0x00FF00), 8)
	  Local $blue = BitAND($helpbutton, 0x0000FF)
	  if ($green > $red) Then
		 if ($green > $blue) Then
			Send("Q")
			Sleep(3000)
		 Else
			$carryon = 0
		 EndIf
	  Else
		 $carryon = 0
	  EndIf
   Until ($carryon==0)

   ;Detect if less than 3 champion has energy
   Local $redtag = PixelGetColor(630,188)
   Local $red = BitShift($redtag, 16)
   Local $green = BitShift(BitAND($redtag, 0x00FF00), 8)
   Local $blue = BitAND($redtag, 0x0000FF)
   if (($red-80) > $green) Then
	  if (($red-80) > $blue) Then
		 MsgBox(0, "Out of energy", "we're out of energy", 2)
		 $arena_continue = 0
		 Sleep(4000)
		 MouseClick("left", 57, 55)
		 if ($arena_tier==2) Then
			$arena_tier = 3
		 Elseif ($arena_tier==3) Then
			$arena_tier = 2
		 EndIf
		 Sleep(7000)
	  EndIf
   EndIf

   ;Detect if there are any Reconnect popup
   if (PixelGetColor(490,320)==0x2b2c30) Then
	  if (getDominantColor(PixelGetColor(490,350))=="green") Then
		 MsgBox(0, "popup", "I'll press the popup button in 5", 5)
		 Sleep(6000)
		 MouseClick("left", 490, 350)
		 Sleep(7000)
	  EndIf
   EndIf

   ;detect if we're in useless milestone info
   if (getDominantColor(PixelGetColor(934,555))=="green") Then
	  if ((PixelGetColor(492,337)==0x2b2c30)) Then
		 MsgBox(0, "milestone", "I assume we're in milestone info", 1)
		 Sleep(1000)
		 $arena_continue = 0
		 MouseClick("left", 57, 55)
		 Sleep(7000)
	  EndIf
   EndIf

   ;if we're in continue next fight
   if (getDominantColor(PixelGetColor(936,556))=="green") Then
	  if (PixelGetColor(688,436)==0x191e23) Then
		 $arena_continue = 0
		 fightArena()
	  EndIf
   EndIf
EndFunc

;arena
Func addToTeam()
   $status = "add to team"
   MouseClickDrag("left", 319, 235, 145, 135)
   sleep(500)
   MouseClickDrag("left", 319, 235, 145, 210)
   sleep(500)
   MouseClickDrag("left", 319, 235, 145, 290)
   sleep(500)
EndFunc

;Arena
Func findMatch()
   $status = "find match"
   Sleep(500)
   MouseClick("left", 109, 547)

		 checkInsideFight()
   Sleep(4000)

   PixelSearch(543,416,575,429, 0x319732)
   if (@error) Then
	  ;highest is not easy, check if mid easy
	  PixelSearch(543,280,575,294, 0x319732)
	  if (@error) Then
		 ;mid is not easy
		 MsgBox(0,"tier", "mid and high is not easy",1)
		 MouseClick("left", 600,200)
	  Else
		 ;mid is easy
		 MouseClick("left", 600,320)
	  EndIf
   Else
	  ;highest is easy
	  MouseClick("left", 687, 445)
   EndIf

		 checkInsideFight()
   Sleep(3000)
   Send("0")
   $c = PixelGetColor(841,574)
   if (GetDominantColor($c)=="green") Then
	  Sleep(3000)
   Else
	  Local $t = 0
	  Local $cont = 1
	  Do
		 Sleep(500)
		 if ($t>120) Then
			;stuck
			$cont = 0
		 EndIf
		 if (Not(PixelGetColor(841,574)==$c)) Then
			$cont = 0
		 EndIf
		 $t = $t+1
	  Until ($cont==0)
   EndIf
EndFunc

;Fight in arena
Func fightArena()
   $status = "fight arena"
   $seq = 0
   $stop = 0
   $allstop = 0

   ;stuck in something handler
   Local $somewhereoutsidecounter = 0
   Local $stuckseq = 0
   Local $startarena = TimerInit()
   Local $arenatimersecond = 0
   Do
	  $stuckseq = $stuckseq+1
	  if (Mod($stuckseq,400)==0) Then
		 $stuqseq = 1
		 ;ToolTip("check stuck")
		 if (checkStuck()) Then
			updateCapture()
			$stop = 1
			MsgBox(0, "popup", "i guess we're stuck", 2)

			;stuck in leaderboard
			if (PixelGetColor(921,138)==0x292c30) Then
			   if (PixelGetColor(939,61)==0x6c6e71) Then
				  MsgBox(0, "popup", "leaderboard, ill close it", 1)
				  Sleep(2000)
				  MouseClick("left", 939,61)
				  Sleep(3000)
			   EndIf
			EndIf
			MouseClick("left", 148, 58) ;menu
			Sleep(2000)
			MouseClick("left", 270, 132) ;fight

			Sleep(10000)
		 EndIf
		 updateCapture()

		 ;check if too long playing maybe something is not right
		 Local $dif = TimerDiff($startarena)
		 if ($dif > 30000) Then
			$startarena = TimerInit()
			$arenatimersecond = $dif/1000
		 EndIf
		 if ($arenatimersecond > 240) Then
			MsgBox(0, "popup", "too long minutes ", 3)
			Sleep(5000)
			MouseClick("left", 148, 58) ;menu
			Sleep(2000)
			MouseClick("left", 138, 58) ;menu double
			Sleep(2000)
			MouseClick("left", 270, 132) ;fight
			Sleep(10000)
		 EndIf
	  EndIf

	  Send("0")
	  Sleep(1);
	  if (Mod($seq, 4)==0) Then
		 Send("K")
	  EndIf
	  $seq = $seq + 1
	  if ($seq>15) then
		 Send("{SPACE}")
		 if ($seq>20) Then
			$seq = 0
		 EndIf
	  EndIf
	  if (getDominantColor(PixelGetColor(144,541))=="red") then
		 Send("{SPACE}")
	  EndIf

	  ;indicates fight has ended (loading screen)
	  $loading = PixelGetColor(640, 540);
	  if ($loading==0x025c00) Then
		 $loading = PixelGetColor(620, 300)
		 if ($loading==0x161a1b) Then
			$stop = 1
			MsgBox(0, "popup", "shall i press back button? (loading screen)", 2)
			Sleep(2000)
			MouseClick("left", 57, 55); back because we might ended up in 3* 4* tier arena
			Sleep(10000)
		 EndIf
	  EndIf

	  ;or chat bar has been clicked
	  if ($loading==0x161a1d) Then
		 if (PixelGetColor(136,540)==0x292c30) Then
			$stop = 1
			MsgBox(0,"chat", "this is chat window", 1)
			Sleep(1000)
			MouseClick("left", 943, 52); close
			Sleep(2000)
			MouseClick("left", 148, 58) ;menu
			Sleep(1000)
			MouseClick("left", 138, 58) ;menu double
			Sleep(1000)
			MouseClick("left", 270, 132) ;fight
			Sleep(5000)
		 EndIf
	  EndIf

	  ; or the case if we ended up in view rewards
	  $loading = PixelGetColor(480,270)
	  if ($loading==0x2b2c30) Then
		 $loading = PixelGetColor(480,330)
		 if ($loading==0x2b2c30) Then
			MsgBox(0, "popup", "(view rewards) ?(TODO)", 2)
			$stop = 1
			Sleep(300)
			MouseClick("left", 57, 55); back
			;Sleep(10000)
		 EndIf
	  ElseIf ($loading==0x000000) Then
		 ; stuck in alliance quest window; todo alliance quest window with empty quest
		 if (PixelGetColor(838,366)==0x2b2c30) Then
			$stop = 1
			MsgBox(0,"alliance q", "alliance quest cuy", 1);
			;$arena_tier = 2
			Sleep(2000)
			MouseClick("left", 57, 55);
			Sleep(10000)
		 EndIf
	  EndIf

	  ;stuck in alliance quest window
	  $loading = PixelGetColor(384,142)
	  if ($loading==0x1a1a1a) Then
		 if (PixelGetColor(551,142)==0x1a1a1a) Then
			if (Not(PixelGetColor(504,142)==0x1a1a1a)) Then
			   $stop = 1
			   MsgBox(0,"alliance q", "empty alliance quest cuy", 1);
			   ;$arena_tier = 2
			   Sleep(2000)
			   MouseClick("left", 57, 55);
			   Sleep(10000)
			EndIf
		 EndIf
	  EndIf

	  ;MsgBox(0, "dbg", StringFormat("%X", PixelGetColor(18,130)), 1)
	  ; or the case we stuck in team adding
	  if (PixelGetColor(18, 130)==0x2b2c30) Then ; the left bar team list
		 if (PixelGetColor(936,511)==0x2b2c30) Then ;the champion filter button
			MsgBox(0, "popup", "(team adding)", 2)
			$stop = 1
			Sleep(1000)
			MouseClick("left", 57, 55); back
			Sleep(10000)
		 EndIf
	  EndIf
	  if (PixelGetColor(18, 130)==0x0b0b0c) Then ; the left bar team list
		 if (PixelGetColor(936,511)==0x0b0b0c) Then ;the champion filter button
			MsgBox(0, "popup", "(team adding dark)", 2)
			$stop = 1
			Sleep(1000)
			MouseClick("left", 57, 55); back
			Sleep(10000)
		 EndIf
	  EndIf

	  ;or the case we're in somewhere outside  (menu)
	  if (PixelGetColor(955,50)==0x2b2c30) Then
		 if (PixelGetColor(955, 562)==0x1d2630) Then
			if (Not(getDominantColor(PixelGetColor(936,556))=="green")) Then
			   $somewhereoutsidecounter = $somewhereoutsidecounter+1
			   if ($somewhereoutsidecounter>20) Then
				  MsgBox(0, "popup", "(somewhere outside for too long)", 2)
				  $stop = 1
				  Sleep(1000)
				  Send("J")
				  Sleep(1000)
				  MouseClick("left", 148, 58) ;menu
				  Sleep(1000)
				  MouseClick("left", 138, 58) ;menu double
				  Sleep(1000)
				  MouseClick("left", 270, 132) ;fight
				  Sleep(5000)
			   EndIf
			EndIf
		 EndIf
	  EndIf

   Until ($stop==1 or $allstop==1)
EndFunc

;FIGHT In quest
Func fight()
   $seq = 0
   $stop = 0
   $allstop = 0
   Do
	  Send("0")
	  Sleep(30);
	  $seq = $seq + 1
	  if (Mod($seq, 4)==0) Then
		 Send("K")
	  EndIf
	  if ($seq>12) then
		 Send("{SPACE}")
		 if ($seq>20) Then
			$seq = 0
		 EndIf
	  EndIf

	  if (Mod($seq,2)==0) Then
		 $loading = PixelGetColor(958, 577);
		 if ($loading==0x1d2630) Then
		 ;indicates fight has ended
			$loading = PixelGetColor(923, 491)
			if ($loading==0xc1c1c2) Then
			   $stop = 1
			   Sleep(3000)
			   Send("J")
			EndIf
		 ElseIf ($loading==0x07090c) Then
			if (PixelGetColor(825,105)==0x2b2c30) Then
			   $stop = 1
			   Sleep(3000)
			   Send("J")
			EndIf
		 ;Elseif (PixelGetColor(486,310)==0xeeeeee) Then
			;we're in loading  screen
			;$stop = 1
			;Sleep(3000)
			;Send("J")
		 EndIf
	  EndIf
	  ;quest completed!
	  Local $ca = PixelGetColor(204,190)
	  if ($ca==0x2b2c30) Then
		 Local $cb = PixelGetColor(739,514)
			if ($cb==0x2b2c30) Then
			   if (getDominantColor(PixelGetColor(310,485))=="green" AND getDominantColor(PixelGetColor(741,485))=="green") Then
				  $stop = 1
				  Sleep(7000)
				  MsgBox(0,"finished", "finished", 2)
				  MouseClick("left", 300,475);back to quest button
				  Sleep(15000)

				  MsgBox(0,"arena", "my creator is away, i'll continue to arena to kill the time",2)
				  MouseClick("left", 148, 58) ;menu
				  Sleep(2000)
				  MouseClick("left", 148, 58) ;menu
				  Sleep(2000)
				  MouseClick("left", 270, 132) ;fight
				  Sleep(15000)
				  startArena()
			   EndIf
			EndIf
	  EndIf
   Until ($stop==1 or $allstop==1)
EndFunc

Func nextNode()
   $allstop = 0
   Do
	  Local $step = 0
	  Do
		 $step = $step + 1
		 if ($step == 10) Then
			MouseClickDrag("left", 450, 320, 642, 346)
		 ElseIf ($step == 20) Then
			MouseClickDrag("left", 450, 320, 200, 200)
			MouseClickDrag("left", 450, 320, 300, 300)
		 ElseIf ($step == 30) Then
			MouseClickDrag("left", 700, 100, 100, 400)
		 ElseIf ($step == 40) Then
			MouseClickDrag("left", 100, 400, 700, 100)
			MouseClickDrag("left", 100, 400, 700, 100)
			$step = 0
		 EndIf
		 Send("J")
		 Sleep(200)
		 $greendot = PixelSearch(80,100, 957, 530, 0x00f800)
		 if (@error) Then
			$greendot = PixelSearch(80,100, 957, 530, 0x00e400)
		 EndIf
	  Until not(@error)
	  Send("J")
	  MouseMove($greendot[0], $greendot[1])
	  MsgBox(0, "now", "i will click this in 4s", 1)
	  Sleep(4000)
	  MouseClick("left", $greendot[0], $greendot[1])
	  Sleep(500)
	  MouseClick("left", $greendot[0], $greendot[1])
	  Sleep(10000)
	  fight()
	  Sleep(4000)
	  Send("J")
   Until ($allstop==1)
EndFunc

Func getDominantColor($color)
   Local $red = BitShift($color, 16)
   Local $green = BitShift(BitAND($color, 0x00FF00), 8)
   Local $blue = BitAND($color, 0x0000FF)
   if ($red > $green And $red > $blue) Then
	  Return ("red")
   ElseIf ($green > $blue And $green > $red) Then
	  Return ("green")
   ElseIf ($blue > $red And $blue > $green) Then
	  Return ("blue")
   Else
	  if ($red > $green or $red > $blue) Then
		 Return ("red")
	  ElseIf ($green > $blue or $green > $red)  Then
		 Return ("green")
	  Else
		 Return ("blue")
	  EndIf
   EndIf
EndFunc

;Calibrate the bluestack window position
;@param $width the width of the screen to search
;@param $height the height of the screen to search
Func calibrateWindow($width=1366,$height=768)
   ;searching bluestack logo
   Local $repeat = 1
   Do
	  $icon = PixelSearch(0,0,1366,768, 0x79af1b);
	  if (@error) Then
		 MsgBox(0,"failed", "can't find bluestack window", 3)
	  Else
		 $find  = PixelSearch($icon[0]-8, $icon[1], $icon[0]+8, $icon[1]+10, 0xf6d502)
		 if (not(@error)) Then
			$find = PixelSearch($icon[0]-8,$icon[1], $icon[0]+8, $icon[1]+10, 0xdd3a17)
			if (not(@error)) Then
			   MouseClickDrag("left", $icon[0]+14, $icon[1], 30, 12)
			   $repeat = 0
			EndIf
		 EndIf
		 ;next color
	  EndIf

   Until ($repeat==0)
EndFunc

;perform check if we're stuck in a room (any current click affects nothing)
;return True if stuck, False if not
Func checkStuck()
   ; check if we're stuck in some room
   $samepixel = 0
   if (Not(PixelGetColor(100,100)==$screensave[0])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(400,100)==$screensave[1])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(700,100)==$screensave[2])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(100,500)==$screensave[3])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(498,298)==$screensave[4])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(700,500)==$screensave[5])) Then
	  Return False
   EndIf
   Return True
EndFunc

;update $screensave to current capture
Func updateCapture()
   $screensave[0] = PixelGetColor(100,100)
   if ($screensave[0]==0x2a1a4c) Then ;we don't want to save loading screen;TODO REUPDATGE THESE
	  $screensave[0] = 0
   EndIf
   $screensave[1] = PixelGetColor(400,100)
   if ($screensave[1]==0x201641) Then
	  $screensave[1] = 0
   EndIf
   $screensave[2] = PixelGetColor(700,100)
   if ($screensave[2]==0x580e2f) Then
	  $screensave[2] = 0
   EndIf
   $screensave[3] = PixelGetColor(100,500)
   if ($screensave[3]==0x2f1661) Then
	  $screensave[3] = 0
   EndIf
   $screensave[4] = PixelGetColor(498,298)
   if ($screensave[4]==0x014cbe) Then
	  $screensave[4] = 0
   EndIf
   $screensave[5] = PixelGetColor(700,500)
   if ($screensave[5]==0x7d1852) Then
	  $screensave[5] = 0
   EndIf
EndFunc

Func checkInsideFight()
   if (isInsideFight()) Then
	  MsgBox(0,"fight", "inside FIGHT!",1)
	  Sleep(500)
	  MouseClick("left",200,200)
	  $arena_continue = 0
	  fightArena()
	  return 1
   Else
	  return 0
   EndIf
EndFunc
;Check if currently in fight
;return 1 if true, 0 false
Func isInsideFight()
   ;check if there is pause button
   Local $leftborder = 0
   Local $rightborder = 0
   $leftborder = PixelGetColor(466,57)
   $rightborder = PixelGetColor(511,57)
   if ($leftborder==0x222222 OR $leftborder==0x212121) Then
	  if ($rightborder==0x222222 OR $rightborder==0x212121) Then
		 if ((PixelGetColor(483,57)==0x9cba9b AND PixelGetColor(493,57)==0x9cba9b) AND getDominantColor(PixelGetColor(488,57))=="green") Then
			return 1
		 EndIf
	  EndIf
   EndIf
   return 0
EndFunc

Func Duel()
   Local $count=5;Limit count here
   Do
	  MouseClick("left", 276,97)
	  Sleep(1000)
	  Send("rooster 210");name to search
	  Sleep(1000)
	  MouseClick("left", 772,102)
	  Sleep(5000)

	  ;2nd search position
		 MouseClick("left", 286,246)
		 Sleep(1000)
		 MouseClick("left", 445,246)
		 Sleep(4000)

	  MouseClick("left", 616,453);continue
	  Sleep(4000)
	  MouseClick("left", 103,547);start
	  fightDuel()
	  Sleep(2000)
	  $count = $count - 1
   Until ($allstop==1 OR $count==0)
EndFunc

;Fight in duel
Func fightDuel()
   $seq = 0
   $stop = 0
   $allstop = 0

   ;stuck in something handler
   Local $somewhereoutsidecounter = 0
   Local $stuckseq = 0
   Local $startarena = TimerInit()
   Local $arenatimersecond = 0
   Do
	  $stuckseq = $stuckseq+1
	  if (Mod($stuckseq,400)==0) Then
		 ;check if too long playing maybe something is not right
		 Local $dif = TimerDiff($startarena)
		 if ($dif > 30000) Then
			$startarena = TimerInit()
			$arenatimersecond = $dif/1000
		 EndIf
		 if ($arenatimersecond > 240) Then
			MsgBox(0, "popup", "too long minutes ", 3)
			Sleep(5000)
			MouseClick("left", 148, 58) ;menu
			Sleep(2000)
			MouseClick("left", 138, 58) ;menu double
			Sleep(2000)
			MouseClick("left", 270, 132) ;fight
			Sleep(10000)
		 EndIf
	  EndIf

	  Send("0")
	  Sleep(1);
	  if (Mod($seq, 4)==0) Then
		 Send("K")
	  EndIf
	  $seq = $seq + 1
	  if ($seq>15) then
		 Send("{SPACE}")
		 if ($seq>20) Then
			$seq = 0
		 EndIf
	  EndIf
	  if (getDominantColor(PixelGetColor(144,541))=="red") then
		 Send("{SPACE}")
	  EndIf
	  $loading = PixelGetColor(640, 540);
	  ;or chat bar has been clicked
	  if ($loading==0x161a1d) Then
		 if (PixelGetColor(136,540)==0x292c30) Then
			$stop = 1
			MsgBox(0,"chat", "this is chat window", 1)
			Sleep(1000)
			MouseClick("left", 943, 52); close
			Sleep(2000)
		 EndIf
	  EndIf
	  if (PixelGetColor(690,105)==0x161a1d AND PixelGetColor(800,105)==0x035d01 AND PixelGetColor(841,105)==0x515151) Then
		 MsgBox(0, "done", "done", 1)
		 Sleep(1000)
		 $stop = 1
	  EndIf
   Until ($stop==1 or $allstop==1)
EndFunc

;Shift+alt
HotKeySet("+!a", "startArena")
HotKeySet("+!z", "changeArenaTier")
HotKeySet("+!s", "idle")
HotKeySet("+!d", "fight")
HotKeySet("+!f", "findMatch")
HotKeySet("+!g", "nextNode")
HotKeySet("+!h", "fightArena")
HotKeySet("+!p", "playthegame")
HotKeySet("+!c", "calibrateWindow")

Global $savepixel = 0
Global $screensave[6]
$screensave[0] = 0
$screensave[1] = 0
$screensave[2] = 0
$screensave[3] = 0
$screensave[4] = 0
$screensave[5] = 0

;This indicates which arena tier shall be played, possible is 2, or 3
$arena_tier = 2
$arena_continue = 1
$allstop = 0
Do
   Sleep(1)
Until False

Func idle()
   $allstop = 1
   MsgBox(0, "now", "terminated", 1)
   Do
	  Sleep(1)
   Until False
EndFunc   ;==>Terminate

Func playthegame()
   MouseClick("left", 26, 750) ;window start menu
   MouseClick("left", 70, 400) ;bluestack app
   Sleep(90000)
   MsgBox(0, "now", "i will now move the bluestack window", 5)
   MouseClickDrag("left", 90, 30, 75, 15)
   Sleep(2000)
   MouseClick("left", 913, 307) ;click the game
   Sleep(60000)
   playthearena()
EndFunc
Func playthearena()
   MouseClick("left", 162, 51)
   Sleep(1000)
   MouseClick("left", 271, 135) ;fight button
   Sleep(20000)
   MouseClick("left", 535, 313) ;versus
   Sleep(20000)
   startArena()
EndFunc

Func changeArenaTier()
   if ($arena_tier==2) Then
	  $arena_tier = 3
	  MsgBox(0, "arena tier", "arena tier is now 3", 2)
   Elseif ($arena_tier==3) Then
	  $arena_tier = 4
	  MsgBox(0, "arena tier", "arena tier is now alltier(when there is no event)", 2)
   ElseIf ($arena_tier==4) Then
	  $arena_tier = 5
	  MsgBox(0, "arena tier", "arena tier is now 5, the special high lvl arena(catalyst, alpha)", 2)
   Else
	  $arena_tier = 2
	  MsgBox(0, "arena tier", "arena tier is now 2", 2)
   EndIf
EndFunc

;Starts the arena (Fight menu), and continue (tier *2)
Func startArena()
   $allstop = 0
   Do
	  calibrateWindow()
	  $arena_continue = 1

	  Sleep(500)
	  if ($arena_tier==5) Then
		 MouseClickDrag("left", 700, 255, 130, 255);drag right mosst for foolproof
		 Sleep(500)
		 MouseClickDrag("left", 700, 255, 130, 255);drag right mosst for foolproof
		 Sleep(500)
	  Else
		 MouseClickDrag("left", 130, 255, 700, 255);drag left mosst for foolproof
	  EndIf
	  Sleep(1000)

	  checkInsideFight()

	  if (Not(getDominantColor(PixelGetColor(346,535))=="green") AND (Not($arena_tier==5))) Then
		 MsgBox(0, "fight", "inside fight menu, not arena", 1)
		 MouseClick("left", 500,446)
		 Sleep(2000)
		 Local $wait = 0
		 do
			Sleep(1000)
			$wait = $wait+1
			checkInsideFight()
		 Until (getDominantColor(PixelGetColor(435,525))=="green" OR ($wait>10))
	  EndIf

	  ;check if currently in one of 3 fights
	  if (PixelGetColor(160,222)==0x2b2c30 AND PixelGetColor(816,222)==0x2b2c30) Then
		 Local $leftresult=PixelGetColor(294,280) ;lose 721a1a red, win 26552e
		 Local $rightresult=PixelGetColor(697,280)
		 if ($leftresult==0x26552e OR $leftresult==0x721a1a) Then
			if ($rightresult==0x26552e OR $rightresult==0x721a1a) Then
			   MsgBox(0, "fight", "more fight to go", 1)
			   Sleep(1000)
			   MouseClick("left", 200,200)
			   fightArena()
			   $arena_continue = 0
			EndIf
		 EndIf
	  EndIf
	  checkInsideFight()
	  if ($arena_continue==1) Then
		 if ($arena_tier==2) Then
			;Send("9")
			MouseClick("left", 386, 446)
			Sleep(5000)
			MouseClick("left", 413, 522);double check
		 Elseif ($arena_tier==3) Then
			MouseClick("left", 830, 510)
			Sleep(5000)
			MouseClick("left", 760, 508);double check
		 Elseif ($arena_tier==4) Then ;arena tier 4
			MouseClick("left", 433, 522);
			Sleep(5000);
		 Else

			if (Not(getDominantColor(PixelGetColor(595,516))=="green") AND Not(getDominantColor(PixelGetColor(438,516))=="green")) Then
			   MsgBox(0, "fight", "inside fight menu, not arena (special)", 1)
			   MouseClickDrag("left", 130, 255, 700, 255);drag left mosst for foolproof
			   Sleep(1000)
			   MouseClickDrag("left", 130, 255, 700, 255);drag left mosst for foolproof
			   Sleep(1000)
			   MouseClick("left", 500,446)
			   Local $wait = 0
			   do
				  Sleep(1000)
				  $wait = $wait+1
				  checkInsideFight()
			   Until (getDominantColor(PixelGetColor(595,516))=="green" OR ($wait>10))
			   MouseClickDrag("left", 700, 255, 130, 255);drag right mosst for foolproof
			   MouseClickDrag("left", 700, 255, 130, 255);drag right mosst for foolproof
			   Sleep(1000)
			EndIf
			checkInsideFight()
			if (getDominantColor(PixelGetColor(438,516))=="green") Then
			   MouseClick("left",438,516)
			Else
			   MouseClick("left", 674, 508);
			EndIf
			Sleep(5000);
		 EndIf
	  EndIf

	  checkInsideFight()
	  Sleep(5000)
	  Local $current_arena_tier  = $arena_tier

	  askForHelp()
	  checkInsideFight()
	  if ($arena_continue==1) Then
		 ; We have energy, continue;else change arena tier in next loop
		 addToTeam()
		 findMatch()
		 fightArena()
	  EndIf

   Until ($allstop==1)
EndFunc

Func askForHelp()
   Local $carryon = 1
   Do
	  ;Detect if we can ask for help
	  Local $helpbutton = PixelGetColor(260, 175)
	  Local $red = BitShift($helpbutton, 16)
	  Local $green = BitShift(BitAND($helpbutton, 0x00FF00), 8)
	  Local $blue = BitAND($helpbutton, 0x0000FF)
	  if ($green > $red) Then
		 if ($green > $blue) Then
			Send("Q")
			Sleep(3000)
		 Else
			$carryon = 0
		 EndIf
	  Else
		 $carryon = 0
	  EndIf
   Until ($carryon==0)

   ;Detect if less than 3 champion has energy
   Local $redtag = PixelGetColor(630,188)
   Local $red = BitShift($redtag, 16)
   Local $green = BitShift(BitAND($redtag, 0x00FF00), 8)
   Local $blue = BitAND($redtag, 0x0000FF)
   if (($red-80) > $green) Then
	  if (($red-80) > $blue) Then
		 MsgBox(0, "Out of energy", "we're out of energy", 2)
		 $arena_continue = 0
		 Sleep(4000)
		 MouseClick("left", 57, 55)
		 if ($arena_tier==2) Then
			$arena_tier = 3
		 Elseif ($arena_tier==3) Then
			$arena_tier = 2
		 EndIf
		 Sleep(7000)
	  EndIf
   EndIf

   ;Detect if there are any Reconnect popup
   if (PixelGetColor(490,320)==0x2b2c30) Then
	  if (getDominantColor(PixelGetColor(490,350))=="green") Then
		 MsgBox(0, "popup", "I'll press the popup button in 5", 5)
		 Sleep(6000)
		 MouseClick("left", 490, 350)
		 Sleep(7000)
	  EndIf
   EndIf

   ;detect if we're in useless milestone info
   if (getDominantColor(PixelGetColor(934,555))=="green") Then
	  if ((PixelGetColor(492,337)==0x2b2c30)) Then
		 MsgBox(0, "milestone", "I assume we're in milestone info", 1)
		 Sleep(1000)
		 $arena_continue = 0
		 MouseClick("left", 57, 55)
		 Sleep(7000)
	  EndIf
   EndIf

   ;if we're in continue next fight
   if (getDominantColor(PixelGetColor(936,556))=="green") Then
	  if (PixelGetColor(688,436)==0x191e23) Then
		 $arena_continue = 0
		 fightArena()
	  EndIf
   EndIf
EndFunc

;arena
Func addToTeam()
   MouseClickDrag("left", 319, 235, 145, 135)
   sleep(500)
   MouseClickDrag("left", 319, 235, 145, 210)
   sleep(500)
   MouseClickDrag("left", 319, 235, 145, 290)
   sleep(500)
EndFunc

;Arena
Func findMatch()
   Sleep(500)
   MouseClick("left", 109, 547)

		 checkInsideFight()
   Sleep(4000)

   PixelSearch(543,416,575,429, 0x319732)
   if (@error) Then
	  ;highest is not easy, check if mid easy
	  PixelSearch(543,280,575,294, 0x319732)
	  if (@error) Then
		 ;mid is not easy
		 MsgBox(0,"tier", "mid and high is not easy",1)
		 MouseClick("left", 600,200)
	  Else
		 ;mid is easy
		 MouseClick("left", 600,320)
	  EndIf
   Else
	  ;highest is easy
	  MouseClick("left", 687, 445)
   EndIf

		 checkInsideFight()
   Sleep(3000)
   Send("0")
   $c = PixelGetColor(841,574)
   if (GetDominantColor($c)=="green") Then
	  Sleep(3000)
   Else
	  Local $t = 0
	  Local $cont = 1
	  Do
		 Sleep(500)
		 if ($t>120) Then
			;stuck
			$cont = 0
		 EndIf
		 if (Not(PixelGetColor(841,574)==$c)) Then
			$cont = 0
		 EndIf
		 $t = $t+1
	  Until ($cont==0)
   EndIf
EndFunc

;Fight in arena
Func fightArena()
   $seq = 0
   $stop = 0
   $allstop = 0

   ;stuck in something handler
   Local $somewhereoutsidecounter = 0
   Local $stuckseq = 0
   Local $startarena = TimerInit()
   Local $arenatimersecond = 0
   Do
	  $stuckseq = $stuckseq+1
	  if (Mod($stuckseq,400)==0) Then
		 ;ToolTip("check stuck")
		 if (checkStuck()) Then
			updateCapture()
			$stop = 1
			MsgBox(0, "popup", "i guess we're stuck", 2)

			;stuck in leaderboard
			if (PixelGetColor(921,138)==0x292c30) Then
			   if (PixelGetColor(939,61)==0x6c6e71) Then
				  MsgBox(0, "popup", "leaderboard, ill close it", 1)
				  Sleep(2000)
				  MouseClick("left", 939,61)
				  Sleep(3000)
			   EndIf
			EndIf
			MouseClick("left", 148, 58) ;menu
			Sleep(2000)
			MouseClick("left", 270, 132) ;fight

			Sleep(10000)
		 EndIf
		 updateCapture()

		 ;check if too long playing maybe something is not right
		 Local $dif = TimerDiff($startarena)
		 if ($dif > 30000) Then
			$startarena = TimerInit()
			$arenatimersecond = $dif/1000
		 EndIf
		 if ($arenatimersecond > 240) Then
			MsgBox(0, "popup", "too long minutes ", 3)
			Sleep(5000)
			MouseClick("left", 148, 58) ;menu
			Sleep(2000)
			MouseClick("left", 138, 58) ;menu double
			Sleep(2000)
			MouseClick("left", 270, 132) ;fight
			Sleep(10000)
		 EndIf
	  EndIf

	  Send("0")
	  Sleep(1);
	  if (Mod($seq, 4)==0) Then
		 Send("K")
	  EndIf
	  $seq = $seq + 1
	  if ($seq>15) then
		 Send("{SPACE}")
		 if ($seq>20) Then
			$seq = 0
		 EndIf
	  EndIf
	  if (getDominantColor(PixelGetColor(144,541))=="red") then
		 Send("{SPACE}")
	  EndIf

	  ;indicates fight has ended (loading screen)
	  $loading = PixelGetColor(640, 540);
	  if ($loading==0x025c00) Then
		 $loading = PixelGetColor(620, 300)
		 if ($loading==0x161a1b) Then
			$stop = 1
			MsgBox(0, "popup", "shall i press back button? (loading screen)", 2)
			Sleep(2000)
			MouseClick("left", 57, 55); back because we might ended up in 3* 4* tier arena
			Sleep(10000)
		 EndIf
	  EndIf

	  ;or chat bar has been clicked
	  if ($loading==0x161a1d) Then
		 if (PixelGetColor(136,540)==0x292c30) Then
			$stop = 1
			MsgBox(0,"chat", "this is chat window", 1)
			Sleep(1000)
			MouseClick("left", 943, 52); close
			Sleep(2000)
		 EndIf
	  EndIf

	  ; or the case if we ended up in view rewards
	  $loading = PixelGetColor(480,270)
	  if ($loading==0x2b2c30) Then
		 $loading = PixelGetColor(480,330)
		 if ($loading==0x2b2c30) Then
			MsgBox(0, "popup", "(view rewards) ?(TODO)", 2)
			$stop = 1
			Sleep(300)
			MouseClick("left", 57, 55); back
			;Sleep(10000)
		 EndIf
	  ElseIf ($loading==0x000000) Then
		 ; stuck in alliance quest window; todo alliance quest window with empty quest
		 if (PixelGetColor(838,366)==0x2b2c30) Then
			$stop = 1
			MsgBox(0,"alliance q", "alliance quest cuy", 1);
			;$arena_tier = 2
			Sleep(2000)
			MouseClick("left", 57, 55);
			Sleep(10000)
		 EndIf
	  EndIf

	  ;stuck in alliance quest window
	  $loading = PixelGetColor(384,142)
	  if ($loading==0x1a1a1a) Then
		 if (PixelGetColor(551,142)==0x1a1a1a) Then
			if (Not(PixelGetColor(504,142)==0x1a1a1a)) Then
			   $stop = 1
			   MsgBox(0,"alliance q", "empty alliance quest cuy", 1);
			   ;$arena_tier = 2
			   Sleep(2000)
			   MouseClick("left", 57, 55);
			   Sleep(10000)
			EndIf
		 EndIf
	  EndIf

	  ;MsgBox(0, "dbg", StringFormat("%X", PixelGetColor(18,130)), 1)
	  ; or the case we stuck in team adding
	  if (PixelGetColor(18, 130)==0x2b2c30) Then ; the left bar team list
		 if (PixelGetColor(936,511)==0x2b2c30) Then ;the champion filter button
			MsgBox(0, "popup", "(team adding)", 2)
			$stop = 1
			Sleep(1000)
			MouseClick("left", 57, 55); back
			Sleep(10000)
		 EndIf
	  EndIf
	  if (PixelGetColor(18, 130)==0x0b0b0c) Then ; the left bar team list
		 if (PixelGetColor(936,511)==0x0b0b0c) Then ;the champion filter button
			MsgBox(0, "popup", "(team adding dark)", 2)
			$stop = 1
			Sleep(1000)
			MouseClick("left", 57, 55); back
			Sleep(10000)
		 EndIf
	  EndIf

	  ;or the case we're in somewhere outside  (menu)
	  if (PixelGetColor(955,50)==0x2b2c30) Then
		 if (PixelGetColor(955, 562)==0x1d2630) Then
			if (Not(getDominantColor(PixelGetColor(936,556))=="green")) Then
			   $somewhereoutsidecounter = $somewhereoutsidecounter+1
			   if ($somewhereoutsidecounter>20) Then
				  MsgBox(0, "popup", "(somewhere outside for too long)", 2)
				  $stop = 1
				  Sleep(1000)
				  Send("J")
				  Sleep(1000)
				  MouseClick("left", 148, 58) ;menu
				  Sleep(1000)
				  MouseClick("left", 138, 58) ;menu double
				  Sleep(1000)
				  MouseClick("left", 270, 132) ;fight
				  Sleep(5000)
			   EndIf
			EndIf
		 EndIf
	  EndIf

   Until ($stop==1 or $allstop==1)
EndFunc

;FIGHT In quest
Func fight()
   $seq = 0
   $stop = 0
   $allstop = 0
   Do
	  Send("0")
	  Sleep(30);
	  $seq = $seq + 1
	  if (Mod($seq, 4)==0) Then
		 Send("K")
	  EndIf
	  if ($seq>12) then
		 Send("{SPACE}")
		 if ($seq>20) Then
			$seq = 0
		 EndIf
	  EndIf

	  if (Mod($seq,2)==0) Then
		 $loading = PixelGetColor(958, 577);
		 if ($loading==0x1d2630) Then
		 ;indicates fight has ended
			$loading = PixelGetColor(923, 491)
			if ($loading==0xc1c1c2) Then
			   $stop = 1
			   Sleep(3000)
			   Send("J")
			EndIf
		 ElseIf ($loading==0x07090c) Then
			if (PixelGetColor(825,105)==0x2b2c30) Then
			   $stop = 1
			   Sleep(3000)
			   Send("J")
			EndIf
		 ;Elseif (PixelGetColor(486,310)==0xeeeeee) Then
			;we're in loading  screen
			;$stop = 1
			;Sleep(3000)
			;Send("J")
		 EndIf
	  EndIf
	  ;quest completed!
	  Local $ca = PixelGetColor(204,190)
	  if ($ca==0x2b2c30) Then
		 Local $cb = PixelGetColor(739,514)
			if ($cb==0x2b2c30) Then
			   if (getDominantColor(PixelGetColor(310,485))=="green" AND getDominantColor(PixelGetColor(741,485))=="green") Then
				  $stop = 1
				  Sleep(7000)
				  MsgBox(0,"finished", "finished", 2)
				  MouseClick("left", 300,475);back to quest button
				  Sleep(15000)

				  MsgBox(0,"arena", "my creator is away, i'll continue to arena to kill the time",2)
				  MouseClick("left", 148, 58) ;menu
				  Sleep(2000)
				  MouseClick("left", 148, 58) ;menu
				  Sleep(2000)
				  MouseClick("left", 270, 132) ;fight
				  Sleep(15000)
				  startArena()
			   EndIf
			EndIf
	  EndIf
   Until ($stop==1 or $allstop==1)
EndFunc

Func nextNode()
   $allstop = 0
   Do
	  Local $step = 0
	  Do
		 $step = $step + 1
		 if ($step == 10) Then
			MouseClickDrag("left", 450, 320, 642, 346)
		 ElseIf ($step == 20) Then
			MouseClickDrag("left", 450, 320, 200, 200)
			MouseClickDrag("left", 450, 320, 300, 300)
		 ElseIf ($step == 30) Then
			MouseClickDrag("left", 700, 100, 100, 400)
		 ElseIf ($step == 40) Then
			MouseClickDrag("left", 100, 400, 700, 100)
			MouseClickDrag("left", 100, 400, 700, 100)
			$step = 0
		 EndIf
		 Send("J")
		 Sleep(200)
		 $greendot = PixelSearch(80,100, 957, 530, 0x00f800)
		 if (@error) Then
			$greendot = PixelSearch(80,100, 957, 530, 0x00e400)
		 EndIf
	  Until not(@error)
	  Send("J")
	  MouseMove($greendot[0], $greendot[1])
	  MsgBox(0, "now", "i will click this in 4s", 1)
	  Sleep(4000)
	  MouseClick("left", $greendot[0], $greendot[1])
	  Sleep(500)
	  MouseClick("left", $greendot[0], $greendot[1])
	  Sleep(10000)
	  fight()
	  Sleep(4000)
	  Send("J")
   Until ($allstop==1)
EndFunc

Func getDominantColor($color)
   Local $red = BitShift($color, 16)
   Local $green = BitShift(BitAND($color, 0x00FF00), 8)
   Local $blue = BitAND($color, 0x0000FF)
   if ($red > $green And $red > $blue) Then
	  Return ("red")
   ElseIf ($green > $blue And $green > $red) Then
	  Return ("green")
   ElseIf ($blue > $red And $blue > $green) Then
	  Return ("blue")
   Else
	  if ($red > $green or $red > $blue) Then
		 Return ("red")
	  ElseIf ($green > $blue or $green > $red)  Then
		 Return ("green")
	  Else
		 Return ("blue")
	  EndIf
   EndIf
EndFunc

;Calibrate the bluestack window position
;@param $width the width of the screen to search
;@param $height the height of the screen to search
Func calibrateWindow($width=1366,$height=768)
   ;searching bluestack logo
   Local $repeat = 1
   Do
	  $icon = PixelSearch(0,0,1366,768, 0x79af1b);
	  if (@error) Then
		 MsgBox(0,"failed", "can't find bluestack window", 3)
	  Else
		 $find  = PixelSearch($icon[0]-8, $icon[1], $icon[0]+8, $icon[1]+10, 0xf6d502)
		 if (not(@error)) Then
			$find = PixelSearch($icon[0]-8,$icon[1], $icon[0]+8, $icon[1]+10, 0xdd3a17)
			if (not(@error)) Then
			   MouseClickDrag("left", $icon[0]+14, $icon[1], 30, 12)
			   $repeat = 0
			EndIf
		 EndIf
		 ;next color
	  EndIf

   Until ($repeat==0)
EndFunc

;perform check if we're stuck in a room (any current click affects nothing)
;return True if stuck, False if not
Func checkStuck()
   ; check if we're stuck in some room
   $samepixel = 0
   if (Not(PixelGetColor(100,100)==$screensave[0])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(400,100)==$screensave[1])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(700,100)==$screensave[2])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(100,500)==$screensave[3])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(498,298)==$screensave[4])) Then
	  Return False
   EndIf
   if (Not(PixelGetColor(700,500)==$screensave[5])) Then
	  Return False
   EndIf
   Return True
EndFunc

;update $screensave to current capture
Func updateCapture()
   $screensave[0] = PixelGetColor(100,100)
   if ($screensave[0]==0x2a1a4c) Then ;we don't want to save loading screen;TODO REUPDATGE THESE
	  $screensave[0] = 0
   EndIf
   $screensave[1] = PixelGetColor(400,100)
   if ($screensave[1]==0x201641) Then
	  $screensave[1] = 0
   EndIf
   $screensave[2] = PixelGetColor(700,100)
   if ($screensave[2]==0x580e2f) Then
	  $screensave[2] = 0
   EndIf
   $screensave[3] = PixelGetColor(100,500)
   if ($screensave[3]==0x2f1661) Then
	  $screensave[3] = 0
   EndIf
   $screensave[4] = PixelGetColor(498,298)
   if ($screensave[4]==0x014cbe) Then
	  $screensave[4] = 0
   EndIf
   $screensave[5] = PixelGetColor(700,500)
   if ($screensave[5]==0x7d1852) Then
	  $screensave[5] = 0
   EndIf
EndFunc

Func checkInsideFight()
   if (isInsideFight()) Then
	  MsgBox(0,"fight", "inside FIGHT!",1)
	  Sleep(500)
	  MouseClick("left",200,200)
	  $arena_continue = 0
	  fightArena()
	  return 1
   Else
	  return 0
   EndIf
EndFunc
;Check if currently in fight
;return 1 if true, 0 false
Func isInsideFight()
   ;check if there is pause button
   Local $leftborder = 0
   Local $rightborder = 0
   $leftborder = PixelGetColor(466,57)
   $rightborder = PixelGetColor(511,57)
   if ($leftborder==0x222222 OR $leftborder==0x212121) Then
	  if ($rightborder==0x222222 OR $rightborder==0x212121) Then
		 if ((PixelGetColor(483,57)==0x9cba9b AND PixelGetColor(493,57)==0x9cba9b) AND getDominantColor(PixelGetColor(488,57))=="green") Then
			return 1
		 EndIf
	  EndIf
   EndIf
   return 0
EndFunc


Cleanstring for messages

Cleanstring for messages

func clearstring($mensage)
;~   ConsoleWrite('--(' & @ScriptName & '-' & @ScriptLineNumber & ') : $mensage = ' & $mensage & @crlf )
;~    $mensage = StringReplace($mensage,"(","")
;~    $mensage = StringReplace($mensage,")","")
   $mensage = StringReplace($mensage,"'","")
   $mensage = StringReplace($mensage,"","")
   $mensage = StringReplace($mensage,"|","")
   $mensage = StringReplace($mensage,"`","")
   $mensage = StringReplace($mensage,"","")
   $mensage = _Latin_char_Remover($mensage)
;~ 	ConsoleWrite('+(' & @ScriptName & '-' & @ScriptLineNumber & ') : $mensage = ' & $mensage & @crlf )
   return $mensage
EndFunc

Func _Latin_char_Remover($string_to_change)

	 $string_to_change = StringReplace($string_to_change, '-', 'i')
	 $string_to_change = StringReplace($string_to_change, 'í', 'i')
	 $string_to_change = StringReplace($string_to_change, 'ú', 'u')
	 $string_to_change = StringReplace($string_to_change, 'i', 'u')
	 $string_to_change = StringReplace($string_to_change, 'é', 'e')
;~ 	 $string_to_change = StringReplace($string_to_change, '', 'i')

	 $string_to_change = StringReplace($string_to_change, '', 'a')
	 $string_to_change = StringReplace($string_to_change, '', 'A')
	 $string_to_change = StringReplace($string_to_change, '', 'A')
	 $string_to_change = StringReplace($string_to_change, '', 'A')

	 $string_to_change = StringReplace($string_to_change, '', 'C')

	 $string_to_change = StringReplace($string_to_change, '', 'e')
	 $string_to_change = StringReplace($string_to_change, '', 'E')
	 $string_to_change = StringReplace($string_to_change, '', 'E')

	 $string_to_change = StringReplace($string_to_change, '', 'i')
	 $string_to_change = StringReplace($string_to_change, '', 'I')
	 $string_to_change = StringReplace($string_to_change, '', 'I')

	 $string_to_change = StringReplace($string_to_change, '', 'o')
	 $string_to_change = StringReplace($string_to_change, '', 'O')
	 $string_to_change = StringReplace($string_to_change, '', 'O')
	 $string_to_change = StringReplace($string_to_change, '', 'O')

	 $string_to_change = StringReplace($string_to_change, '', 'u')
	 $string_to_change = StringReplace($string_to_change, '', 'U')
	 $string_to_change = StringReplace($string_to_change, '', 'U')

	 $string_to_change = StringReplace($string_to_change, '', 'Y')

	 $string_to_change = StringReplace($string_to_change, '', 'n')
	 $string_to_change = StringReplace($string_to_change, '', 'N')
    Return $string_to_change
EndFunc   ;==>_Latin_char_Remover

func clearstring($mensage)
   ;$mensage = StringReplace($mensage,"(","")
   ;$mensage = StringReplace($mensage,")","")
   $mensage = StringReplace($mensage,"'","")
   $mensage = StringReplace($mensage,"","")
   $mensage = StringReplace($mensage,"|","")
   $mensage = StringReplace($mensage,"`","")
   $mensage = StringReplace($mensage,"","")
   $mensage = _Latin_char_Remover($mensage)
   return $mensage
EndFunc

Func _Latin_char_Remover($string_to_change)

	$string_to_change = StringReplace($string_to_change, '', 'a')
	$string_to_change = StringReplace($string_to_change, '', 'A')
    $string_to_change = StringReplace($string_to_change, '', 'A')
    $string_to_change = StringReplace($string_to_change, '', 'A')

    $string_to_change = StringReplace($string_to_change, '', 'C')

	$string_to_change = StringReplace($string_to_change, '', 'e')
    $string_to_change = StringReplace($string_to_change, '', 'E')
    $string_to_change = StringReplace($string_to_change, '', 'E')

	$string_to_change = StringReplace($string_to_change, '', 'i')
    $string_to_change = StringReplace($string_to_change, '', 'I')
    $string_to_change = StringReplace($string_to_change, '', 'I')

	$string_to_change = StringReplace($string_to_change, '', 'o')
    $string_to_change = StringReplace($string_to_change, '', 'O')
    $string_to_change = StringReplace($string_to_change, '', 'O')
    $string_to_change = StringReplace($string_to_change, '', 'O')

	$string_to_change = StringReplace($string_to_change, '', 'u')
    $string_to_change = StringReplace($string_to_change, '', 'U')
    $string_to_change = StringReplace($string_to_change, '', 'U')

    $string_to_change = StringReplace($string_to_change, '', 'Y')

		$string_to_change = StringReplace($string_to_change, '', 'n')
	$string_to_change = StringReplace($string_to_change, '', 'N')
    Return $string_to_change
EndFunc   ;==>_Latin_char_Remover


Modify the message about hotkey to stop.

#include <Constants.au3>

Global $MyProgress_StepIndex = 0
Global $MyProgress_StepCount = 100
Global $MyProgress_MainText = ""

; NOTE: $MyProgress_SubTextSuffix must be one line text.
Global $MyProgress_SubTextSuffix = _
		"Press alt+shift+x to stop if GUI automation goes wrong."

Func MyProgress_buildSubText($subtext)
	If StringInStr($subtext, @CRLF) = 0 Then
		Return $subtext & @CRLF & @CRLF & $MyProgress_SubTextSuffix
	Else
		Return $subtext & @CRLF & $MyProgress_SubTextSuffix
	EndIf
EndFunc   ;==>MyProgress_buildSubText

; NOTE: $subtext must be one or two lines.
Func MyProgress_On($title, $maintext, $subtext = "", $x = -1, $y = -1, $opt = -1)
	If $opt = -1 Then
		$opt = $DLG_MOVEABLE
	EndIf
	$MyProgress_MainText = $maintext
	ProgressOn($title, $maintext, MyProgress_buildSubText($subtext), $x, $y, $opt)
EndFunc   ;==>MyProgress_On

Func MyProgress_Step($subtext = "", $maintext = "")
	$MyProgress_StepIndex = $MyProgress_StepIndex + 1
	Local $percent = 100 * $MyProgress_StepIndex / $MyProgress_StepCount
	If $maintext <> "" Then
		$MyProgress_MainText = $maintext
	EndIf
	ProgressSet($percent, MyProgress_buildSubText($subtext), $MyProgress_MainText)
EndFunc   ;==>MyProgress_Step

Func MyProgress_Set($percent, $subtext = "", $maintext = "")
	If $maintext <> "" Then
		$MyProgress_MainText = $maintext
	EndIf
	ProgressSet($percent, MyProgress_buildSubText($subtext), $MyProgress_MainText)
EndFunc   ;==>MyProgress_Set

Func MyProgress_Off()
	ProgressOff()
EndFunc   ;==>MyProgress_Off

#include <Constants.au3>

Global $MyProgress_StepIndex = 0
Global $MyProgress_StepCount = 100
Global $MyProgress_MainText = ""

; NOTE: $MyProgress_SubTextSuffix must be one line text.
Global $MyProgress_SubTextSuffix = _
		"If GUI automation goes wrong, press ALT+SHIFT+x to stop."

Func MyProgress_buildSubText($subtext)
	If StringInStr($subtext, @CRLF) = 0 Then
		Return $subtext & @CRLF & @CRLF & $MyProgress_SubTextSuffix
	Else
		Return $subtext & @CRLF & $MyProgress_SubTextSuffix
	EndIf
EndFunc   ;==>MyProgress_buildSubText

; NOTE: $subtext must be one or two lines.
Func MyProgress_On($title, $maintext, $subtext = "", $x = -1, $y = -1, $opt = -1)
	If $opt = -1 Then
		$opt = $DLG_MOVEABLE
	EndIf
	$MyProgress_MainText = $maintext
	ProgressOn($title, $maintext, MyProgress_buildSubText($subtext), $x, $y, $opt)
EndFunc   ;==>MyProgress_On

Func MyProgress_Step($subtext = "", $maintext = "")
	$MyProgress_StepIndex = $MyProgress_StepIndex + 1
	Local $percent = 100 * $MyProgress_StepIndex / $MyProgress_StepCount
	If $maintext <> "" Then
		$MyProgress_MainText = $maintext
	EndIf
	ProgressSet($percent, MyProgress_buildSubText($subtext), $MyProgress_MainText)
EndFunc   ;==>MyProgress_Step

Func MyProgress_Set($percent, $subtext = "", $maintext = "")
	If $maintext <> "" Then
		$MyProgress_MainText = $maintext
	EndIf
	ProgressSet($percent, MyProgress_buildSubText($subtext), $MyProgress_MainText)
EndFunc   ;==>MyProgress_Set

Func MyProgress_Off()
	ProgressOff()
EndFunc   ;==>MyProgress_Off


Changed installer window size to smaller.

--HG--
extra : convert_revision : svn%3A79c32731-664e-0410-8185-e51b9e89f9fb/trunk%401136

;;  Copyright 2008 Nokia Siemens Networks Oyj
;;
;;  Licensed under the Apache License, Version 2.0 (the "License");
;;  you may not use this file except in compliance with the License.
;;  You may obtain a copy of the License at
;;
;;      http://www.apache.org/licenses/LICENSE-2.0
;;
;;  Unless required by applicable law or agreed to in writing, software
;;  distributed under the License is distributed on an "AS IS" BASIS,
;;  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;  See the License for the specific language governing permissions and
;;  limitations under the License.

;; Robot Framework One Click Installer for Windows
;;
;; This installer installs Robot Framework and its preconditions Python and
;; Jython (optional). If installer is executed without arguments, it opens a
;; dialog explaining the options and asking the user to enter the installation
;; directory. If a command line options is given, it must be a path to an
;; existing directory and it is used as installation directory.
;;
;; For more information about this script see $USAGE below. To learn more
;; about silent Python installation, see url [1]. Silent Jython installation
;; options can be seen with command [2].
;;
;; [1] http://www.python.org/download/releases/2.5/msi/#automated
;; [2] java -jar jython_installer-2.2.x.jar --help

;;
;; Config
;;

; Expected patterns for installer names and target directory names.
$PYTHON_DIR_NAME = "Python"
$JYTHON_DIR_NAME = "Jython"
$PYTHON_PATTERN = "python-2.*.msi"
$ROBOT_PATTERN = "robotframework-2.*.exe"
$JYTHON_PATTERN = "jython_installer-2.*.jar"

$USAGE = "One Click Installer installs Robot Framework and its " & _
         "preconditions Python and Jython (optional)." & @CRLF & @CRLF & _
         "Please specify the directory where you want software to be " & _
         "installed. Also make sure that you have required Robot Framework " & _
         "and Python installers, and optionally Jython installer, in the " & _
         "same directory as this installer." & @CRLF & @CRLF & _
         "For more information see http://robotframework.org/."

;;
;; Main
;;

$base_dir = GetBaseDirectory()
$python_installer = GetRequiredInstaller($PYTHON_PATTERN, "Python")
$robot_installer = GetRequiredInstaller($ROBOT_PATTERN, "Robot Framework")
$jython_installer = GetOptionalInstaller($JYTHON_PATTERN)
$python_dir = GetPythonDir($base_dir & $PYTHON_DIR_NAME)
$jython_dir = GetJythonDir($base_dir & $JYTHON_DIR_NAME, $jython_installer)
InstallPython($python_installer, $python_dir)
InstallJython($jython_installer, $jython_dir)
SetPath($python_dir, $jython_dir)  ; This must be done before InstallRobot to always have msvcrt71.dll in PATH
InstallRobot($robot_installer)
Exit

;;
;; Functions
;;

Func GetBaseDirectory()
    If $CmdLine[0] == 0 Then
        $base = InputBox("Robot Framework One Click Installer", $USAGE, "C:\", "", 400, 250)
    ElseIf $CmdLine[0] == 1 Then
        $base = $CmdLine[1]
    Else
        Cancel("Usage: " & @ScriptName & " [basedir]")
    EndIf
    If $base == "" Then
        Cancel("Installation cancelled by user.")
    ElseIf FileExists($base) == 0 Then
        Cancel("Given directory doesn't exist.")
    ElseIf StringRight($base, 1) <> "\" Then
        $base = $base & "\"
    EndIf
    Return $base
EndFunc

Func Cancel($msg)
    MsgBox(0, "Installation Cancelled", $msg)
    Exit
EndFunc

Func GetRequiredInstaller($pattern, $name)
    $installer = GetOptionalInstaller($pattern)
    If $installer == "" Then
        Cancel("Could not find " & $name & " installer with pattern '" & $pattern & "'")
    Endif
    return $installer
EndFunc

Func GetOptionalInstaller($pattern)
    $found = FileFindFirstFile($pattern)
    If $found == -1 Then
        $installer = ""
    Else
        $installer = FileFindNextFile($found)
    EndIf
    FileClose($found)
    return $installer
EndFunc

Func GetPythonDir($dir)
    VerifyInstallationDir($dir, "Python")
    return $dir
EndFunc

Func GetJythonDir($dir, $installer)
    If $installer == "" Then
        return ""
    EndIf
    VerifyInstallationDir($dir, "Jython")
    return $dir
EndFunc

Func VerifyInstallationDir($dir, $name)
    If FileExists($dir) == 1 Then
        Cancel($name & " installation directory '" & $dir & "' already exists.")
    EndIf
EndFunc

Func InstallPython($installer, $dir)
    $cmd = "msiexec /i " & $installer & " TARGETDIR=" & $dir & " /qb!"
    RunWait($cmd)
EndFunc

Func InstallJython($installer, $dir)
    If $installer == "" Then
        return
    EndIf
    $cmd = "java -jar " & $installer & " -s -d " & $dir
    RunWait($cmd)
EndFunc

Func InstallRobot($installer)
    Run($installer)
    WaitSetupWindowAndClickEnter("This Wizard will install")
    WaitSetupWindowAndClickEnter("Select python installation")
    WaitSetupWindowAndClickEnter("Ready to install")
    WaitSetupWindowAndClickEnter("Postinstall script finished")
EndFunc

Func WaitSetupWindowAndClickEnter($exp_text)
    WinWaitActive("Setup", $exp_text)
    Send("{ENTER}")
EndFunc

Func SetPath($python, $jython)
    $update = $python & ";" & $python & "\Scripts;" & $jython
    $orig = RegRead("HKCU\Environment", "PATH")

    If $orig == "" Then
        $new = $update
    ElseIf StringRight($orig, 1) == ";" Then
        $new = $orig & $update
    Else
        $new = $orig & ";" & $update
    EndIf

    RegWrite("HKCU\Environment", "PATH", "REG_EXPAND_SZ", $new)
    EnvUpdate()
EndFunc

;;  Copyright 2008 Nokia Siemens Networks Oyj
;;
;;  Licensed under the Apache License, Version 2.0 (the "License");
;;  you may not use this file except in compliance with the License.
;;  You may obtain a copy of the License at
;;
;;      http://www.apache.org/licenses/LICENSE-2.0
;;
;;  Unless required by applicable law or agreed to in writing, software
;;  distributed under the License is distributed on an "AS IS" BASIS,
;;  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;  See the License for the specific language governing permissions and
;;  limitations under the License.

;; Robot Framework One Click Installer for Windows
;;
;; This installer installs Robot Framework and its preconditions Python and
;; Jython (optional). If installer is executed without arguments, it opens a
;; dialog explaining the options and asking the user to enter the installation
;; directory. If a command line options is given, it must be a path to an
;; existing directory and it is used as installation directory.
;;
;; For more information about this script see $USAGE below. To learn more
;; about silent Python installation, see url [1]. Silent Jython installation
;; options can be seen with command [2].
;;
;; [1] http://www.python.org/download/releases/2.5/msi/#automated
;; [2] java -jar jython_installer-2.2.x.jar --help

;;
;; Config
;;

; Expected patterns for installer names and target directory names.
$PYTHON_DIR_NAME = "Python"
$JYTHON_DIR_NAME = "Jython"
$PYTHON_PATTERN = "python-2.*.msi"
$ROBOT_PATTERN = "robotframework-2.*.exe"
$JYTHON_PATTERN = "jython_installer-2.*.jar"

$USAGE = "One Click Installer installs Robot Framework and its " & _
         "preconditions Python and Jython (optional)." & @CRLF & @CRLF & _
         "Please specify the directory where you want software to be " & _
         "installed. Also make sure that you have required Robot Framework " & _
         "and Python installers, and optionally Jython installer, in the " & _
         "same directory as this installer." & @CRLF & @CRLF & _
         "For more information see http://robotframework.org/."

;;
;; Main
;;

$base_dir = GetBaseDirectory()
$python_installer = GetRequiredInstaller($PYTHON_PATTERN, "Python")
$robot_installer = GetRequiredInstaller($ROBOT_PATTERN, "Robot Framework")
$jython_installer = GetOptionalInstaller($JYTHON_PATTERN)
$python_dir = GetPythonDir($base_dir & $PYTHON_DIR_NAME)
$jython_dir = GetJythonDir($base_dir & $JYTHON_DIR_NAME, $jython_installer)
InstallPython($python_installer, $python_dir)
InstallJython($jython_installer, $jython_dir)
SetPath($python_dir, $jython_dir)  ; This must be done before InstallRobot to always have msvcrt71.dll in PATH
InstallRobot($robot_installer)
Exit

;;
;; Functions
;;

Func GetBaseDirectory()
    If $CmdLine[0] == 0 Then
        $base = InputBox("Robot Framework One Click Installer", $USAGE, "C:\", "", 500, 470)
    ElseIf $CmdLine[0] == 1 Then
        $base = $CmdLine[1]
    Else
        Cancel("Usage: " & @ScriptName & " [basedir]")
    EndIf
    If $base == "" Then
        Cancel("Installation cancelled by user.")
    ElseIf FileExists($base) == 0 Then
        Cancel("Given directory doesn't exist.")
    ElseIf StringRight($base, 1) <> "\" Then
        $base = $base & "\"
    EndIf
    Return $base
EndFunc

Func Cancel($msg)
    MsgBox(0, "Installation Cancelled", $msg)
    Exit
EndFunc

Func GetRequiredInstaller($pattern, $name)
    $installer = GetOptionalInstaller($pattern)
    If $installer == "" Then
        Cancel("Could not find " & $name & " installer with pattern '" & $pattern & "'")
    Endif
    return $installer
EndFunc

Func GetOptionalInstaller($pattern)
    $found = FileFindFirstFile($pattern)
    If $found == -1 Then
        $installer = ""
    Else
        $installer = FileFindNextFile($found)
    EndIf
    FileClose($found)
    return $installer
EndFunc

Func GetPythonDir($dir)
    VerifyInstallationDir($dir, "Python")
    return $dir
EndFunc

Func GetJythonDir($dir, $installer)
    If $installer == "" Then
        return ""
    EndIf
    VerifyInstallationDir($dir, "Jython")
    return $dir
EndFunc

Func VerifyInstallationDir($dir, $name)
    If FileExists($dir) == 1 Then
        Cancel($name & " installation directory '" & $dir & "' already exists.")
    EndIf
EndFunc

Func InstallPython($installer, $dir)
    $cmd = "msiexec /i " & $installer & " TARGETDIR=" & $dir & " /qb!"
    RunWait($cmd)
EndFunc

Func InstallJython($installer, $dir)
    If $installer == "" Then
        return
    EndIf
    $cmd = "java -jar " & $installer & " -s -d " & $dir
    RunWait($cmd)
EndFunc

Func InstallRobot($installer)
    Run($installer)
    WaitSetupWindowAndClickEnter("This Wizard will install")
    WaitSetupWindowAndClickEnter("Select python installation")
    WaitSetupWindowAndClickEnter("Ready to install")
    WaitSetupWindowAndClickEnter("Postinstall script finished")
EndFunc

Func WaitSetupWindowAndClickEnter($exp_text)
    WinWaitActive("Setup", $exp_text)
    Send("{ENTER}")
EndFunc

Func SetPath($python, $jython)
    $update = $python & ";" & $python & "\Scripts;" & $jython
    $orig = RegRead("HKCU\Environment", "PATH")

    If $orig == "" Then
        $new = $update
    ElseIf StringRight($orig, 1) == ";" Then
        $new = $orig & $update
    Else
        $new = $orig & ";" & $update
    EndIf

    RegWrite("HKCU\Environment", "PATH", "REG_EXPAND_SZ", $new)
    EnvUpdate()
EndFunc


Fixed bug that installation was not possible to path containing spaces.

--HG--
extra : convert_revision : svn%3A79c32731-664e-0410-8185-e51b9e89f9fb/trunk%402398

;;  Copyright 2008-2009 Nokia Siemens Networks Oyj
;;
;;  Licensed under the Apache License, Version 2.0 (the "License");
;;  you may not use this file except in compliance with the License.
;;  You may obtain a copy of the License at
;;
;;      http://www.apache.org/licenses/LICENSE-2.0
;;
;;  Unless required by applicable law or agreed to in writing, software
;;  distributed under the License is distributed on an "AS IS" BASIS,
;;  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;  See the License for the specific language governing permissions and
;;  limitations under the License.

;; Robot Framework One Click Installer for Windows
;;
;; This installer installs Robot Framework and its preconditions Python and
;; Jython (optional). If installer is executed without arguments, it opens a
;; dialog explaining the options and asking the user to enter the installation
;; directory. If a command line options is given, it must be a path to an
;; existing directory and it is used as installation directory.
;;
;; For more information about this script see $USAGE below. To learn more
;; about silent Python installation, see url [1]. Silent Jython installation
;; options can be seen with command [2].
;;
;; [1] http://www.python.org/download/releases/2.5/msi/#automated
;; [2] java -jar jython_installer-2.2.x.jar --help

;;
;; Config
;;

; Expected patterns for installer names and target directory names.
$PYTHON_DIR_NAME = "Python"
$JYTHON_DIR_NAME = "Jython"
$PYTHON_PATTERN = "python-2.*.msi"
$ROBOT_PATTERN = "robotframework-2.*.exe"
$JYTHON_PATTERN = "jython_installer-2.*.jar"

$USAGE = "One Click Installer installs Robot Framework and its " & _
         "preconditions Python and Jython (optional)." & @CRLF & @CRLF & _
         "Please specify the directory where you want software to be " & _
         "installed. Also make sure that you have required Robot Framework " & _
         "and Python installers, and optionally Jython installer, in the " & _
         "same directory as this installer." & @CRLF & @CRLF & _
         "For more information see http://robotframework.org/."

;;
;; Main
;;

$base_dir = GetBaseDirectory()
$python_installer = GetRequiredInstaller($PYTHON_PATTERN, "Python")
$robot_installer = GetRequiredInstaller($ROBOT_PATTERN, "Robot Framework")
$jython_installer = GetOptionalInstaller($JYTHON_PATTERN)
$python_dir = GetPythonDir($base_dir & $PYTHON_DIR_NAME)
$jython_dir = GetJythonDir($base_dir & $JYTHON_DIR_NAME, $jython_installer)
InstallPython($python_installer, $python_dir)
InstallJython($jython_installer, $jython_dir)
SetPath($python_dir, $jython_dir)  ; This must be done before InstallRobot to always have msvcrt71.dll in PATH
InstallRobot($robot_installer)
Exit

;;
;; Functions
;;

Func GetBaseDirectory()
    If $CmdLine[0] == 0 Then
        $base = InputBox("Robot Framework One Click Installer", $USAGE, "C:\", "", 400, 250)
    ElseIf $CmdLine[0] == 1 Then
        $base = $CmdLine[1]
    Else
        Cancel("Usage: " & @ScriptName & " [basedir]")
    EndIf
    If $base == "" Then
        Cancel("Installation cancelled by user.")
    ElseIf FileExists($base) == 0 Then
        Cancel("Given directory doesn't exist.")
    ElseIf StringRight($base, 1) <> "\" Then
        $base = $base & "\"
    EndIf
    Return $base
EndFunc

Func Cancel($msg)
    MsgBox(0, "Installation Cancelled", $msg)
    Exit
EndFunc

Func GetRequiredInstaller($pattern, $name)
    $installer = GetOptionalInstaller($pattern)
    If $installer == "" Then
        Cancel("Could not find " & $name & " installer with pattern '" & $pattern & "'")
    Endif
    return $installer
EndFunc

Func GetOptionalInstaller($pattern)
    $found = FileFindFirstFile($pattern)
    If $found == -1 Then
        $installer = ""
    Else
        $installer = FileFindNextFile($found)
    EndIf
    FileClose($found)
    return $installer
EndFunc

Func GetPythonDir($dir)
    VerifyInstallationDir($dir, "Python")
    return $dir
EndFunc

Func GetJythonDir($dir, $installer)
    If $installer == "" Then
        return ""
    EndIf
    VerifyInstallationDir($dir, "Jython")
    return $dir
EndFunc

Func VerifyInstallationDir($dir, $name)
    If FileExists($dir) == 1 Then
        Cancel($name & " installation directory '" & $dir & "' already exists.")
    EndIf
EndFunc

Func InstallPython($installer, $dir)
    $cmd = "msiexec /i " & $installer & " TARGETDIR=""" & $dir & """ /qb!"
    RunWait($cmd)
EndFunc

Func InstallJython($installer, $dir)
    If $installer == "" Then
        return
    EndIf
    $cmd = "java -jar " & $installer & " -s -d """ & $dir & """"
    RunWait($cmd)
EndFunc

Func InstallRobot($installer)
    Run($installer)
    WaitSetupWindowAndClickEnter("This Wizard will install")
    WaitSetupWindowAndClickEnter("Select python installation")
    WaitSetupWindowAndClickEnter("Ready to install")
    WaitSetupWindowAndClickEnter("Postinstall script finished")
EndFunc

Func WaitSetupWindowAndClickEnter($exp_text)
    WinWaitActive("Setup", $exp_text)
    Send("{ENTER}")
EndFunc

Func SetPath($python, $jython)
    $update = $python & ";" & $python & "\Scripts;" & $jython
    $orig = RegRead("HKCU\Environment", "PATH")

    If $orig == "" Then
        $new = $update
    ElseIf StringRight($orig, 1) == ";" Then
        $new = $orig & $update
    Else
        $new = $orig & ";" & $update
    EndIf

    RegWrite("HKCU\Environment", "PATH", "REG_EXPAND_SZ", $new)
    EnvUpdate()
EndFunc

;;  Copyright 2008-2009 Nokia Siemens Networks Oyj
;;
;;  Licensed under the Apache License, Version 2.0 (the "License");
;;  you may not use this file except in compliance with the License.
;;  You may obtain a copy of the License at
;;
;;      http://www.apache.org/licenses/LICENSE-2.0
;;
;;  Unless required by applicable law or agreed to in writing, software
;;  distributed under the License is distributed on an "AS IS" BASIS,
;;  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;  See the License for the specific language governing permissions and
;;  limitations under the License.

;; Robot Framework One Click Installer for Windows
;;
;; This installer installs Robot Framework and its preconditions Python and
;; Jython (optional). If installer is executed without arguments, it opens a
;; dialog explaining the options and asking the user to enter the installation
;; directory. If a command line options is given, it must be a path to an
;; existing directory and it is used as installation directory.
;;
;; For more information about this script see $USAGE below. To learn more
;; about silent Python installation, see url [1]. Silent Jython installation
;; options can be seen with command [2].
;;
;; [1] http://www.python.org/download/releases/2.5/msi/#automated
;; [2] java -jar jython_installer-2.2.x.jar --help

;;
;; Config
;;

; Expected patterns for installer names and target directory names.
$PYTHON_DIR_NAME = "Python"
$JYTHON_DIR_NAME = "Jython"
$PYTHON_PATTERN = "python-2.*.msi"
$ROBOT_PATTERN = "robotframework-2.*.exe"
$JYTHON_PATTERN = "jython_installer-2.*.jar"

$USAGE = "One Click Installer installs Robot Framework and its " & _
         "preconditions Python and Jython (optional)." & @CRLF & @CRLF & _
         "Please specify the directory where you want software to be " & _
         "installed. Also make sure that you have required Robot Framework " & _
         "and Python installers, and optionally Jython installer, in the " & _
         "same directory as this installer." & @CRLF & @CRLF & _
         "For more information see http://robotframework.org/."

;;
;; Main
;;

$base_dir = GetBaseDirectory()
$python_installer = GetRequiredInstaller($PYTHON_PATTERN, "Python")
$robot_installer = GetRequiredInstaller($ROBOT_PATTERN, "Robot Framework")
$jython_installer = GetOptionalInstaller($JYTHON_PATTERN)
$python_dir = GetPythonDir($base_dir & $PYTHON_DIR_NAME)
$jython_dir = GetJythonDir($base_dir & $JYTHON_DIR_NAME, $jython_installer)
InstallPython($python_installer, $python_dir)
InstallJython($jython_installer, $jython_dir)
SetPath($python_dir, $jython_dir)  ; This must be done before InstallRobot to always have msvcrt71.dll in PATH
InstallRobot($robot_installer)
Exit

;;
;; Functions
;;

Func GetBaseDirectory()
    If $CmdLine[0] == 0 Then
        $base = InputBox("Robot Framework One Click Installer", $USAGE, "C:\", "", 400, 250)
    ElseIf $CmdLine[0] == 1 Then
        $base = $CmdLine[1]
    Else
        Cancel("Usage: " & @ScriptName & " [basedir]")
    EndIf
    If $base == "" Then
        Cancel("Installation cancelled by user.")
    ElseIf FileExists($base) == 0 Then
        Cancel("Given directory doesn't exist.")
    ElseIf StringRight($base, 1) <> "\" Then
        $base = $base & "\"
    EndIf
    Return $base
EndFunc

Func Cancel($msg)
    MsgBox(0, "Installation Cancelled", $msg)
    Exit
EndFunc

Func GetRequiredInstaller($pattern, $name)
    $installer = GetOptionalInstaller($pattern)
    If $installer == "" Then
        Cancel("Could not find " & $name & " installer with pattern '" & $pattern & "'")
    Endif
    return $installer
EndFunc

Func GetOptionalInstaller($pattern)
    $found = FileFindFirstFile($pattern)
    If $found == -1 Then
        $installer = ""
    Else
        $installer = FileFindNextFile($found)
    EndIf
    FileClose($found)
    return $installer
EndFunc

Func GetPythonDir($dir)
    VerifyInstallationDir($dir, "Python")
    return $dir
EndFunc

Func GetJythonDir($dir, $installer)
    If $installer == "" Then
        return ""
    EndIf
    VerifyInstallationDir($dir, "Jython")
    return $dir
EndFunc

Func VerifyInstallationDir($dir, $name)
    If FileExists($dir) == 1 Then
        Cancel($name & " installation directory '" & $dir & "' already exists.")
    EndIf
EndFunc

Func InstallPython($installer, $dir)
    $cmd = "msiexec /i " & $installer & " TARGETDIR=" & $dir & " /qb!"
    RunWait($cmd)
EndFunc

Func InstallJython($installer, $dir)
    If $installer == "" Then
        return
    EndIf
    $cmd = "java -jar " & $installer & " -s -d " & $dir
    RunWait($cmd)
EndFunc

Func InstallRobot($installer)
    Run($installer)
    WaitSetupWindowAndClickEnter("This Wizard will install")
    WaitSetupWindowAndClickEnter("Select python installation")
    WaitSetupWindowAndClickEnter("Ready to install")
    WaitSetupWindowAndClickEnter("Postinstall script finished")
EndFunc

Func WaitSetupWindowAndClickEnter($exp_text)
    WinWaitActive("Setup", $exp_text)
    Send("{ENTER}")
EndFunc

Func SetPath($python, $jython)
    $update = $python & ";" & $python & "\Scripts;" & $jython
    $orig = RegRead("HKCU\Environment", "PATH")

    If $orig == "" Then
        $new = $update
    ElseIf StringRight($orig, 1) == ";" Then
        $new = $orig & $update
    Else
        $new = $orig & ";" & $update
    EndIf

    RegWrite("HKCU\Environment", "PATH", "REG_EXPAND_SZ", $new)
    EnvUpdate()
EndFunc


updated usage

updated usage

;;  Copyright 2008 Nokia Siemens Networks Oyj
;;
;;  Licensed under the Apache License, Version 2.0 (the "License");
;;  you may not use this file except in compliance with the License.
;;  You may obtain a copy of the License at
;;
;;      http://www.apache.org/licenses/LICENSE-2.0
;;
;;  Unless required by applicable law or agreed to in writing, software
;;  distributed under the License is distributed on an "AS IS" BASIS,
;;  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;  See the License for the specific language governing permissions and
;;  limitations under the License.

;; Robot Framework One Click Installer for Windows
;;
;; This installer installs Robot Framework and its preconditions Python and
;; Jython (optional). If installer is executed without arguments, it opens a
;; dialog explaining the options and asking the user to enter the installation
;; directory. If a command line options is given, it must be a path to an
;; existing directory and it is used as installation directory.
;;
;; For more information about this script see $USAGE below. To learn more
;; about silent Python installation, see url [1]. Silent Jython installation
;; options can be seen with command [2].
;;
;; [1] http://www.python.org/download/releases/2.5/msi/#automated
;; [2] java -jar jython_installer-2.2.x.jar --help

;;
;; Config
;;

; Expected patterns for installer names and target directory names.
$PYTHON_DIR_NAME = "Python"
$JYTHON_DIR_NAME = "Jython"
$PYTHON_PATTERN = "python-2.*.msi"
$ROBOT_PATTERN = "robotframework-2.*.exe"
$JYTHON_PATTERN = "jython_installer-2.*.jar"

; Usage to show to the user. If major versions of installed software are changed update them also here!!
; Patterns and directory names above are used in the usage so that they don't need to be updated.
$USAGE = "One Click Installer installs Robot Framework and its preconditions Python and Jython (optional). " & _
         "It also sets Robot Framework start-up scripts (pybot, jybot, rebot) as well as Python and Jython executables " & _
         "into %PATH% environment variable so that they can be executed from the command line. (Note that " & _
         "you need to restart the command prompt for these changes to take effect.)" & @CRLF & @CRLF & _
         "You should use this installer ONLY if you do not previously have Python or Jython installed. " & _
         "In that case, and also if you want to have a custom installation, you need to install needed " & _
         "components separately." & @CRLF & @CRLF & _
         "One Click Installer requires that you have all the required component installers in the same directory " & _
         "with it and that they have expected names. If Robot Framework or Python installer is missing, " & _
         "installation fails. If Jython installer does not exist, Jython is simply not installed. Note that " & _
         "in order to install Jython, Java 1.4 or newer must be already installed. Minimum supported versions " & _
         "are Robot Framework 2.0, Python 2.5 and Jython 2.2, but newer versiosn are always recommened. These " & _
         "installers can be downloaded from respective project websites. Expected patterns for installer names are '" & _
         $ROBOT_PATTERN & "', '" & $PYTHON_PATTERN & "' and '" & $JYTHON_PATTERN & "'." & @CRLF & @CRLF & _
         "The only thing you need to specify is the base directory where to install Python and Jython. " & _
         "They are installed into directories '" & $PYTHON_DIR_NAME & "' and '" & $JYTHON_DIR_NAME & "', " & _
         "respectively, inside the given base directory. Robot Framework itself is installed under Python " & _
         "installation directory and its startup scripts can be found from '[PYTHON]\Scripts' and code from " & _
         "'[PYTHON]\Lib\site-packages'." & @CRLF & @CRLF & _
         "Note that the specified base directory MUST exist and Python and Jython directories inside it must not. " & _
         "It is also not recommended to use a path containing spaces. Good candidates include directories like " & _
         "'C:\' and 'C:\APPS'."

;;
;; Main
;;

$base_dir = GetBaseDirectory()
$python_installer = GetRequiredInstaller($PYTHON_PATTERN, "Python")
$robot_installer = GetRequiredInstaller($ROBOT_PATTERN, "Robot")
$jython_installer = GetOptionalInstaller($JYTHON_PATTERN)
$python_dir = GetPythonDir($base_dir & $PYTHON_DIR_NAME)
$jython_dir = GetJythonDir($base_dir & $PYTHON_DIR_NAME, $jython_installer)
InstallPython($python_installer, $python_dir)
InstallJython($jython_installer, $jython_dir)
SetPath($python_dir, $jython_dir)  ; This must be done before InstallRobot to always have msvcrt71.dll in PATH
InstallRobot($robot_installer)
Exit

;;
;; Functions
;;

Func GetBaseDirectory()
    If $CmdLine[0] == 0 Then
        $base = InputBox("Robot Framework One Click Installer", $USAGE, "C:\", "", 500, 470)
    ElseIf $CmdLine[0] == 1 Then
        $base = $CmdLine[1]
    Else
        Cancel("Usage: " & @ScriptName & " [basedir]")
    EndIf
    If $base == "" Then
        Cancel("Installation cancelled by user.")
    ElseIf FileExists($base) == 0 Then
        Cancel("Given directory doesn't exist.")
    ElseIf StringRight($base, 1) <> "\" Then
        $base = $base & "\"
    EndIf
    Return $base
EndFunc

Func Cancel($msg)
    MsgBox(0, "Installation Cancelled", $msg)
    Exit
EndFunc

Func GetRequiredInstaller($pattern, $name)
    $installer = GetOptionalInstaller($pattern)
    If $installer == "" Then
        Cancel("Could not find " & $name & " installer with pattern '" & $pattern & "'")
    Endif
    return $installer
EndFunc

Func GetOptionalInstaller($pattern)
    $found = FileFindFirstFile($pattern)
    If $found == -1 Then
        $installer = ""
    Else
        $installer = FileFindNextFile($found)
    EndIf
    FileClose($found)
    return $installer
EndFunc

Func GetPythonDir($dir)
    VerifyInstallationDir($dir, "Python")
    return $dir
EndFunc

Func GetJythonDir($dir, $installer)
    If $installer == "" Then
        return ""
    EndIf
    VerifyInstallationDir($dir, "Jython")
    return $dir
EndFunc

Func VerifyInstallationDir($dir, $name)
    If FileExists($dir) == 1 Then
        Cancel($name & " installation directory '" & $dir & "' already exists.")
    EndIf
EndFunc

Func InstallPython($installer, $dir)
    $cmd = "msiexec /i " & $installer & " TARGETDIR=" & $dir & " /qb!"
    RunWait($cmd)
EndFunc

Func InstallJython($installer, $dir)
    If $installer == "" Then
        return
    EndIf
    $cmd = "java -jar " & $installer & " -s -d " & $dir
    RunWait($cmd)
EndFunc

Func InstallRobot($installer)
    Run($installer)
    WaitSetupWindowAndClickEnter("This Wizard will install")
    WaitSetupWindowAndClickEnter("Select python installation")
    WaitSetupWindowAndClickEnter("Ready to install")
    WaitSetupWindowAndClickEnter("Postinstall script finished")
EndFunc

Func WaitSetupWindowAndClickEnter($exp_text)
    WinWaitActive("Setup", $exp_text)
    Send("{ENTER}")
EndFunc

Func SetPath($python, $jython)
    $update = $python & ";" & $python & "\Scripts;" & $jython
    $orig = RegRead("HKCU\Environment", "PATH")

    If $orig == "" Then
        $new = $update
    ElseIf StringRight($orig, 1) == ";" Then
        $new = $orig & $update
    Else
        $new = $orig & ";" & $update
    EndIf

    RegWrite("HKCU\Environment", "PATH", "REG_EXPAND_SZ", $new)
    EnvUpdate()
EndFunc

;;  Copyright 2008 Nokia Siemens Networks Oyj
;;
;;  Licensed under the Apache License, Version 2.0 (the "License");
;;  you may not use this file except in compliance with the License.
;;  You may obtain a copy of the License at
;;
;;      http://www.apache.org/licenses/LICENSE-2.0
;;
;;  Unless required by applicable law or agreed to in writing, software
;;  distributed under the License is distributed on an "AS IS" BASIS,
;;  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;  See the License for the specific language governing permissions and
;;  limitations under the License.

;; Robot Framework One Click Installer for Windows
;;
;; This installer installs Robot Framework and its preconditions Python and
;; Jython (optional). If installer is executed without arguments, it opens a
;; dialog explaining the options and asking the user to enter the installation
;; directory. If a command line options is given, it must be a path to an
;; existing directory and it is used as installation directory.
;;
;; For more information about this script see $USAGE below. To learn more
;; about silent Python installation, see url [1]. Silent Jython installation
;; options can be seen with command [2].
;;
;; [1] http://www.python.org/download/releases/2.5/msi/#automated
;; [2] java -jar jython_installer-2.2.x.jar --help

;;
;; Config
;;

; Expected patterns for installer names and target directory names.
$PYTHON_DIR_NAME = "Python"
$JYTHON_DIR_NAME = "Jython"
$PYTHON_PATTERN = "python-2.*.msi"
$ROBOT_PATTERN = "robotframework-2.*.exe"
$JYTHON_PATTERN = "jython_installer-2.*.jar"

; Usage to show to the user. If major versions of installed software are changed update them also here!!
; Patterns and directory names above are used in the usage so that they don't need to be updated.
$USAGE = "One Click Installer installs Robot Framework and its preconditions Python and Jython (optional). " & _
         "It also sets Robot Framework start-up scripts (pybot, jybot, rebot) as well as Python and Jython executables " & _
         "into %PATH% environment variable so that they can be executed from the command line. (Note that " & _
         "you need to restart the command prompt for these changes to take effect.)" & @CRLF & @CRLF & _
         "You should use this installer ONLY if you don't previously have Python or Jython installed. " & _
         "In that case, and also if you want to have a custom installation, you need to install needed " & _
         "components separately." & @CRLF & @CRLF & _
         "One Click Installer requires that you have all the required component installers in the same directory " & _
         "with it and that they have expected names. If Robot Framework or Python installer is missing, " & _
         "installation fails. If Jython installer doesn't exist, Jython is simply not installed. Note that " & _
         "in order to install Jython, Java 1.4 or newer must be already installed. Supported " & _
         "versions are Robot Framework 2.x, Python 2.5.x and Jython 2.2.x where '.x' means that any minor version " & _
         "(e.g. 2.5 or 2.5.2) is OK. These installers can be downloaded from respective project websites if " & _
         "they are missing. Expected patterns for installer names are '" & $ROBOT_PATTERN & "', '" & _
         $PYTHON_PATTERN & "' and '" & $JYTHON_PATTERN & "'." & @CRLF & @CRLF & _
         "The only thing you need to specify is the base directory where to install Python and Jython. " & _
         "They are installed into directories '" & $PYTHON_DIR_NAME & "' and '" & $JYTHON_DIR_NAME & "', " & _
         "respectively, inside the given base directory. Robot Framework itself is installed under Python " & _
         "installation directory and its startup scripts can be found from '[PYTHON]\Scripts' and code from " & _
         "'[PYTHON]\Lib\site-packages'." & @CRLF & @CRLF & _
         "Note that the specified base directory MUST exist and Python and Jython directories inside it must not. " & _
         "It is also not recommended to use a path containing spaces. Good candidates include directories like " & _
         "'C:\' and 'C:\APPS'."

;;
;; Main
;;

$base_dir = GetBaseDirectory()
$python_installer = GetRequiredInstaller($PYTHON_PATTERN, "Python")
$robot_installer = GetRequiredInstaller($ROBOT_PATTERN, "Robot")
$jython_installer = GetOptionalInstaller($JYTHON_PATTERN)
$python_dir = GetPythonDir($base_dir & $PYTHON_DIR_NAME)
$jython_dir = GetJythonDir($base_dir & $PYTHON_DIR_NAME, $jython_installer)
InstallPython($python_installer, $python_dir)
InstallJython($jython_installer, $jython_dir)
SetPath($python_dir, $jython_dir)  ; This must be done before InstallRobot to always have msvcrt71.dll in PATH
InstallRobot($robot_installer)
Exit

;;
;; Functions
;;

Func GetBaseDirectory()
    If $CmdLine[0] == 0 Then
        $base = InputBox("Robot Framework One Click Installer", $USAGE, "C:\", "", 500, 470)
    ElseIf $CmdLine[0] == 1 Then
        $base = $CmdLine[1]
    Else
        Cancel("Usage: " & @ScriptName & " [basedir]")
    EndIf
    If $base == "" Then
        Cancel("Installation cancelled by user.")
    ElseIf FileExists($base) == 0 Then
        Cancel("Given directory doesn't exist.")
    ElseIf StringRight($base, 1) <> "\" Then
        $base = $base & "\"
    EndIf
    Return $base
EndFunc

Func Cancel($msg)
    MsgBox(0, "Installation Cancelled", $msg)
    Exit
EndFunc

Func GetRequiredInstaller($pattern, $name)
    $installer = GetOptionalInstaller($pattern)
    If $installer == "" Then
        Cancel("Could not find " & $name & " installer with pattern '" & $pattern & "'")
    Endif
    return $installer
EndFunc

Func GetOptionalInstaller($pattern)
    $found = FileFindFirstFile($pattern)
    If $found == -1 Then
        $installer = ""
    Else
        $installer = FileFindNextFile($found)
    EndIf
    FileClose($found)
    return $installer
EndFunc

Func GetPythonDir($dir)
    VerifyInstallationDir($dir, "Python")
    return $dir
EndFunc

Func GetJythonDir($dir, $installer)
    If $installer == "" Then
        return ""
    EndIf
    VerifyInstallationDir($dir, "Jython")
    return $dir
EndFunc

Func VerifyInstallationDir($dir, $name)
    If FileExists($dir) == 1 Then
        Cancel($name & " installation directory '" & $dir & "' already exists.")
    EndIf
EndFunc

Func InstallPython($installer, $dir)
    $cmd = "msiexec /i " & $installer & " TARGETDIR=" & $dir & " /qb!"
    RunWait($cmd)
EndFunc

Func InstallJython($installer, $dir)
    If $installer == "" Then
        return
    EndIf
    $cmd = "java -jar " & $installer & " -s -d " & $dir
    RunWait($cmd)
EndFunc

Func InstallRobot($installer)
    Run($installer)
    WaitSetupWindowAndClickEnter("This Wizard will install")
    WaitSetupWindowAndClickEnter("Select python installation")
    WaitSetupWindowAndClickEnter("Ready to install")
    WaitSetupWindowAndClickEnter("Postinstall script finished")
EndFunc

Func WaitSetupWindowAndClickEnter($exp_text)
    WinWaitActive("Setup", $exp_text)
    Send("{ENTER}")
EndFunc

Func SetPath($python, $jython)
    $update = $python & ";" & $python & "\Scripts;" & $jython
    $orig = RegRead("HKCU\Environment", "PATH")

    If $orig == "" Then
        $new = $update
    ElseIf StringRight($orig, 1) == ";" Then
        $new = $orig & $update
    Else
        $new = $orig & ";" & $update
    EndIf

    RegWrite("HKCU\Environment", "PATH", "REG_EXPAND_SZ", $new)
    EnvUpdate()
EndFunc