Sign in to follow this  
Followers 0
guestscripter

how to make my code tidy?

9 posts in this topic

As the title says. Not talking about the formatting and tabs (bless the Tidy function in Scite4AutoIt that takes care of that).

I have written a script that has gotten quite large, and I want to make/keep it tidier than it is at the moment. I´ve more-or-less used the variable prefixes descibed in the Wiki under Best_coding_practices, used correctish scopes...

Anybody have system for going through a script and improving this, without breaking it?

For example, I have thought of using Search+Replace to rename variables...

...I´m getting lost in my script!

 

please, if you have "method" of cleaning up a script that has become less readable, let me know!

Share this post


Link to post
Share on other sites



#3 ·  Posted (edited)

 

Divide it up into regions

#Region Function 1
;do stuff
#EndRegion Function 1

 

Good advice.

 

Do not be afraid, and do nested #Region

But this is first step.

Next step:

try to Change #Region into the Function

Edited by mLipok
1 person likes this

Signature beginning:   Wondering who uses AutoIT and what it can be used for ?
* GHAPI UDF - modest begining - comunication with GitHub REST API *
ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST API *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 - BETA * ADO.au3 UDF SMTP Mailer UDF *

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Best coding practices * 

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * 

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2017-06-04

Share this post


Link to post
Share on other sites

Have you gone through your globals to see which ones can be mode local to the various functions?

Also, can you post the script?  This is so that we or others can suggest strategy.

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

Thank you guys for the advice so far!

And I agree using regions is (in this case has been already) very helpful.

 

In regards to posting the current script:

here goes nothing:

 

This is the "header" part, and the "main loop":

#Region Options and Includes
Opt("SendKeyDelay", 32);16 ;5 milliseconds
Opt("SendKeyDownDelay", 2) ;1 millisecond
Opt("WinWaitDelay", 50) ;250 milliseconds
Opt("PixelCoordMode", 0) ;1=absolute, 0=relative, 2=client
Opt("MouseCoordMode", 0) ;1=absolute, 0=relative, 2=client
Opt("WinTitleMatchMode", 2) ;1=start, 2=subStr, 3=exact, 4=advanced, -1 to -4=Nocase
#include <IE.au3>
#include <Misc.au3>
#include <String.au3>
#include <Array.au3>
#include <MsgBoxConstants.au3>
;#include <ScreenCapture.au3>
#EndRegion Options and Includes
#Region Declare Descriptors, Tags and Initialise Reservations Array. Declare Global Variables and Constants.
#Region Descriptors $ixINDEX
Global Const $ixINDEX[] = ["TaRecLoc", _
        "Name", "1stName", "Title", _
        "AccNm", "Acc1stN", "AccTtl", _
        "Street", "City", "Postcode", "Country", _
        "Email", "Phone", _
        "Agent", "Company", "Group", _
        "c/i DD", "c/i MM", "c/i YYYY", _
        "c/o DD", "c/o MM", "c/o YYYY", _
        "Adults", "Children", "Rooms", _
        "RmType", "RCode", "Extras", _
        "ResType", "Market", "Source", "Origin", _
        "Payment", "CC#", "expMM", "expYYYY", _
        "Cmmnt"]
#EndRegion Descriptors $ixINDEX
#Region Enumerate Tags, Initialise Array
Global Enum $ixReservationCode, _;0
        $ixGuestSurName, $ixGuestFirstName, $ixGuestTitle, _;1,2,3
        $ixAccompGuestSurName, $ixAccompGuestFirstName, $ixAccompGuestTitle, _;4,5,6
        $ixGuestAddressStreet, $ixGuestAddressCity, $ixGuestAddressPostcode, $ixGuestAddressCountryCode, _;7,8,9,10
        $ixGuestEmail, $ixGuestPhone, _;11,12,13
        $ixAgent, $ixCompany, $ixGroup, _;14,15,16
        $ixCheckInDay, $ixCheckInMonth, $ixCheckInYear, _;17,18,19
        $ixCheckoutDay, $ixCheckoutMonth, $ixCheckoutYear, _;20,21,22
        $ixNumPersons, $ixNumChildren, $ixNumRooms, _;23,24,25
        $ixRoomType, $ixRateCode, $ixAddonPackages, _;26,27,28
        $ixResType, $ixResMarket, $ixResSource, $ixResOrigin, _;29,30,31
        $ixPaymentType, $ixCreditCardNumber, $ixCreditCardExpiryMonth, $ixCreditCardExpiryYear, _;32,33,34,35
        $ixReservationComment, _;36
        $ix;37
Global $aReservations[0][$ix] ;Sets/resets the Array
#EndRegion Enumerate Tags, Initialise Array
#Region Global Variables
#Region Strings
Global $sOperaWinTitle = "#blablabla#"
#EndRegion Strings
#Region PixelChecksum Data
Global $aCS_Misc_AllBlue[5] = [1798928452, 140, 155, 1002, 748]
Global $aCS_Misc_FensterSelectBlue[5] = [3494973848, 9, 31, 67, 35]
Global $aCS_Window_NewReservation[5] = [3176789548, 204, 191, 532, 315];or 3708915432 depending on cursor blink
Global $aCS_Misc_InFocusReservation[5] = [376151908, 205, 192, 319, 212]
Global $aCS_Misc_ProfileSearchNoResultSelected[5] = [2580066430, 202, 179, 213, 375];was:[1985600853, 202, 305, 229, 478]
Global $aCS_Misc_ProfileSearchInProgress[5] = [1713801695, 455, 164, 957, 360]
Global $aCS_Misc_ProfileSearchWithFirstResultSelected[5] = [916195880, 202, 305, 229, 478]
Global $aCS_Win_IndividualProfilInFocus[5] = [4013487749, 203, 201, 341, 240]
Global $aCS_Pop_Warn_NegotiatedRate[5] = [3663865623, 330, 358, 374, 438];might work generically
Global $aCS_Pop_General_OKButton[5] = [1541534458, 488, 421, 535, 452]
Global $aCS_Pop_Warn_DifferentRatesMayAppy[5] = [1917878847, 333, 355, 690, 456]
Global $aCS_Pop_CC_Attach_YN[5] = [2252997265, 350, 361, 676, 451]
Global $aCS_Pop_CC_Existing_OC[5] = [1066516122, 238, 303, 936, 350]
Global $aCS_Pop_Res_Conf_OK[5] = [3243176568, 485, 415, 541, 449]
Global $aCS_Win_OptionsinFocus[5] = [2976217248, 387, 240, 516, 291]
Global $aCS_Win_AccompinFocus[5] = [1441538536, 360, 348, 533, 365]
#EndRegion PixelChecksum Data
#EndRegion Global Variables
#EndRegion Declare Descriptors, Tags and Initialise Reservations Array. Declare Global Variables and Constants.
#Region Validate Correct PC
If Not (@ComputerName = "WS02") Or Not (DriveGetSerial(@HomeDrive & "\") = 3626272696) Then
    MsgBox(0, "", "Geht aktuell am Rechten PC")
    Exit
EndIf
#EndRegion Validate Correct PC
#Region CopyAndGet
HotKeySet("{ESC}", "_Exit")
Global $sSplashTextTitle = StringTrimRight(@ScriptName, 4) & " - " & "Abbrechen jederzeit mit ""Esc"" Taste möglich! -  Benutzung mit eigener Verantwortung."
SplashTextOn($sSplashTextTitle, "skript wartet bis eine ganze #blablabla# Email, oder ganzer #blablabla# PDF Text, mit Ctrl+C kopiert ist", 512 + 128 + 128, 42, -1, 1, 32 + 16)
HotKeySet("^c", "CopyAndGet")
While 1
    Sleep(64)
WEnd
Func CopyAndGet()
    SplashOff()
    SplashTextOn($sSplashTextTitle, "reservierung wird geladen...", 512 + 128, 42, -1, 1, 32 + 16)
    HotKeySet("^c")
    Send("^c")
    Parseblabla1Email(ClipGet() & @CRLF)
    Parseblabla2PDF(ClipGet() & @CRLF)
    ;Parseblabla3(ClipGet(), "username", "password", 0)
    ;Parseblabla4Email(ClipGet()&@CRLF)
    ;testreservation()
    forreservationinreservations()

    SplashTextOn($sSplashTextTitle, "skript wartet bis eine ganze #blablabla# Email, oder ganzer #blablabla# PDF Text, mit Ctrl+C kopiert ist", 512 + 128 + 128, 42, -1, 1, 32 + 16)
    HotKeySet("^c", "CopyAndGet")
EndFunc   ;==>CopyAndGet
#EndRegion CopyAndGet

There are multiple Parsing functions, maybe not post those due to passwords etc. (that´s the only part I´m not posting, otherwise this is the script, in that order, at the moment, this is one I have as a template:

#Region Parsers

#Region Template for new reservation functino
Func newreservationtemplate($sSource = "")
    Local $m = UBound($aReservations, 1)
    ReDim $aReservations[$m + 1][UBound($aReservations, 2)]
    $aReservations[$m][$ixReservationCode] = $ixINDEX[$ixReservationCode]
    #Region Profile
    $aReservations[$m][$ixGuestSurName] = $ixINDEX[$ixGuestSurName]
    $aReservations[$m][$ixGuestFirstName] = $ixINDEX[$ixGuestFirstName]
    $aReservations[$m][$ixGuestTitle] = $ixINDEX[$ixGuestTitle]

    $aReservations[$m][$ixAccompGuestSurName] = $ixINDEX[$ixAccompGuestSurName]
    $aReservations[$m][$ixAccompGuestFirstName] = $ixINDEX[$ixAccompGuestFirstName]
    $aReservations[$m][$ixAccompGuestTitle] = $ixINDEX[$ixAccompGuestTitle]

    $aReservations[$m][$ixGuestAddressStreet] = $ixINDEX[$ixGuestAddressStreet]
    $aReservations[$m][$ixGuestAddressCity] = $ixINDEX[$ixGuestAddressCity]
    $aReservations[$m][$ixGuestAddressPostcode] = $ixINDEX[$ixGuestAddressPostcode]
    $aReservations[$m][$ixGuestAddressCountryCode] = $ixINDEX[$ixGuestAddressCountryCode]

    $aReservations[$m][$ixGuestEmail] = $ixINDEX[$ixGuestEmail]
    $aReservations[$m][$ixGuestPhone] = $ixINDEX[$ixGuestPhone]
    #EndRegion Profile
    #Region Agent/Company/Group
    $aReservations[$m][$ixAgent] = $ixINDEX[$ixAgent]
    $aReservations[$m][$ixCompany] = $ixINDEX[$ixCompany]
    $aReservations[$m][$ixGroup] = $ixINDEX[$ixGroup]
    #EndRegion Agent/Company/Group
    #Region Checkin/Checkout
    $aReservations[$m][$ixCheckInDay] = $ixINDEX[$ixCheckInDay]
    $aReservations[$m][$ixCheckInMonth] = $ixINDEX[$ixCheckInMonth]
    $aReservations[$m][$ixCheckInYear] = $ixINDEX[$ixCheckInYear]

    $aReservations[$m][$ixCheckoutDay] = $ixINDEX[$ixCheckoutDay]
    $aReservations[$m][$ixCheckoutMonth] = $ixINDEX[$ixCheckoutMonth]
    $aReservations[$m][$ixCheckoutYear] = $ixINDEX[$ixCheckoutYear]
    #EndRegion Checkin/Checkout
    #Region Reseration major
    $aReservations[$m][$ixNumPersons] = $ixINDEX[$ixNumPersons]
    $aReservations[$m][$ixNumChildren] = $ixINDEX[$ixNumChildren]
    $aReservations[$m][$ixNumRooms] = $ixINDEX[$ixNumRooms]

    $aReservations[$m][$ixRoomType] = $ixINDEX[$ixRoomType]
    $aReservations[$m][$ixRateCode] = $ixINDEX[$ixRateCode]
    $aReservations[$m][$ixAddonPackages] = $ixINDEX[$ixAddonPackages]
    #EndRegion Reseration major
    #Region Statistic Fields
    $aReservations[$m][$ixResType] = $ixINDEX[$ixResType]
    $aReservations[$m][$ixResMarket] = $ixINDEX[$ixResMarket]
    $aReservations[$m][$ixResSource] = $ixINDEX[$ixResSource]
    $aReservations[$m][$ixResOrigin] = $ixINDEX[$ixResOrigin]
    #EndRegion Statistic Fields
    #Region Payment
    $aReservations[$m][$ixPaymentType] = $ixINDEX[$ixPaymentType]
    $aReservations[$m][$ixCreditCardNumber] = $ixINDEX[$ixCreditCardNumber]
    $aReservations[$m][$ixCreditCardExpiryMonth] = $ixINDEX[$ixCreditCardExpiryMonth]
    $aReservations[$m][$ixCreditCardExpiryYear] = $ixINDEX[$ixCreditCardExpiryYear]
    #EndRegion Payment
    $aReservations[$m][$ixReservationComment] = $ixINDEX[$ixReservationComment]
EndFunc   ;==>newreservationtemplate
#EndRegion Template for new reservation functino
#EndRegion Parsers

Here is the most essential and last section/chunk:

#Region Summarise and query confirmation
Func forreservationinreservations()
    Local $sSummary
    For $iReservation = 0 To UBound($aReservations, 1) - 1
        $sSummary = "++++Reservation #" & $iReservation + 1 & "/" & UBound($aReservations, 1) & ":++++++++++++++++++++++++++" & @CR
        For $index = 0 To $ix - 1
            $sSummary &= $ixINDEX[$index] & ":" & @TAB & $aReservations[$iReservation][$index] & @CR
        Next
        $sSummary &= "++++++++++++++++++++++++++++++++++++++++++"

        queryentryconfirm($sSummary, $iReservation)
    Next
    Global $aReservations[0][$ix] ;Reset the Array
    If MsgBox(262144 + 32 + 4 + 256, @ScriptName, "Fertig!" & @CRLF & @CRLF & "gleich mit der nächsten Buchung weitermachen?") <> 6 Then _Exit()
EndFunc   ;==>forreservationinreservations
Func queryentryconfirm($sSummary, $iReservation)
    SplashOff()
    Local $msg = MsgBox(262144 + 0 + 0 + 1, @ScriptName, $sSummary)
    If $msg = 2 Then ;Cancel
    ElseIf $msg = 1 Then ;OK
        SplashTextOn($sSplashTextTitle, "skript wartet bis ein OPERA geöffnet und leer ist", 512 + 128, 42, -1, 1, 32 + 16)
        EnterInOpera($iReservation)
    EndIf
EndFunc   ;==>queryentryconfirm
#EndRegion Summarise and query confirmation
#Region EnterInOpera
Func EnterInOpera($m)
    Local $iTimeOut
    Local $iTempNewProfile
    Global $wHandleOpera
    Global $cHandleOpera
    #Region Opera Start
    While 1
        Local $hTempWinList = WinList()
        For $i = 1 To $hTempWinList[0][0]
            If StringInStr(WinGetTitle($hTempWinList[$i][1]), $sOperaWinTitle) Then
                WinActivate($hTempWinList[$i][1])
                $wHandleOpera = $hTempWinList[$i][1]
                WinMove($wHandleOpera, "", Default, Default, 1024, 768, 20)
                Sleep(128)
                If CSTestInOpera($aCS_Misc_AllBlue) Then ExitLoop
            EndIf
        Next
        While Not WinActive($sOperaWinTitle) Or Not CSTestInOpera($aCS_Misc_AllBlue)
            For $i = 1 To $hTempWinList[0][0]
                If StringInStr(WinGetTitle($hTempWinList[$i][1]), $sOperaWinTitle) And Not WinActive($hTempWinList[$i][1]) Then WinFlash($hTempWinList[$i][1], "", 2, 128)
            Next
            If WinActive($sOperaWinTitle) Then
                $wHandleOpera = WinActivate($sOperaWinTitle)
                WinMove($wHandleOpera, "", Default, Default, 1024, 768, 20)
            EndIf
        WEnd
        $wHandleOpera = WinActivate($sOperaWinTitle)
        $cHandleOpera = ControlGetHandle($wHandleOpera, "", "")
        #Region Blocking
        OnAutoItExitRegister("UnDoBlockInactiveWindowsAndMouse")
        BlockInactiveWindowsAndMouse()
        AdlibRegister("AdlibCheckWinStillActive", 128)
        #EndRegion Blocking
        SplashOff()
        If MsgBox(262144 + 32 + 1, @ScriptName, "mit diesem Fenster weitermachen?") = 1 Then
            ExitLoop
        Else
            _Exit()
        EndIf
    WEnd
    BlockInactiveWindowsAndMouse(1);re-_MouseTrap because the MsgBox releases it.
    #EndRegion Opera Start
    #Region New Reservation Start
    ProgressOn($sSplashTextTitle, "skript gibt die Reservierung ein", "New Reservation", Default, 0)
    WinActivate($wHandleOpera)
    OperaSend("{F7}")
    WaitWhileCs("NOT", $aCS_Window_NewReservation, 64, 5, $aCS_Misc_InFocusReservation, "AND")

    OperaSend("!.")
    ProgressSet(5, "Guest Profile")
    WaitWhileCs("NOT", $aCS_Misc_ProfileSearchNoResultSelected, 64, 5)

    OperaSendClipTab($aReservations[$m][$ixGuestSurName])
    OperaSendClipTab($aReservations[$m][$ixGuestFirstName])
    IndividualProfileSearch()
    #EndRegion New Reservation Start
    #Region Profile Select/New
    $iTempNewProfile = 0
    If CSTestInOpera($aCS_Misc_ProfileSearchWithFirstResultSelected) = 1 Then
        Local $iProfileMsgBoxAnswer = MsgBox(262144 + 32 + 4, @ScriptName, "Selektiertes Profil verwenden?" & @CRLF & "(automatisch Ja in 7 sekunden)", 7)
        BlockInactiveWindowsAndMouse(1);re-_MouseTrap because the MsgBox releases it.
        If $iProfileMsgBoxAnswer <= 6 Then;Yes or Timeout
            OperaSend("!o")
            WaitWhileCs("NOT", $aCS_Misc_InFocusReservation, 64, 10)

            OperaTab(-4)
        ElseIf $iProfileMsgBoxAnswer = 7 Then;No
            $iTempNewProfile = 1
        EndIf
    ElseIf CSTestInOpera($aCS_Misc_ProfileSearchNoResultSelected) = 1 Then
        $iTempNewProfile = 1
    Else
        MsgBox(0, @ScriptName, "Error2. Will abort.", 2)
        Exit;#########improve error handling##############
    EndIf
    #Region Enter New Profile Details
    If $iTempNewProfile = 1 Then
        OperaSend("!n")
        WaitWhileCs("NOT", $aCS_Win_IndividualProfilInFocus, 16, 10)

        OperaTab(4)
        OperaSendClipTab($aReservations[$m][$ixGuestTitle])
        OperaSendClipTab($aReservations[$m][$ixGuestAddressStreet], 3)
        OperaSendClipTab($aReservations[$m][$ixGuestAddressCity])
        OperaSendClipTab($aReservations[$m][$ixGuestAddressPostcode], 2)
        OperaSendClip($aReservations[$m][$ixGuestAddressCountryCode])
        If StringInStr($aReservations[$m][$ixGuestEmail], "@") > 0 Or StringLen($aReservations[$m][$ixGuestPhone]) > 4 Then
            OperaTab(13)
            If StringInStr($aReservations[$m][$ixGuestEmail], "@") > 0 Then
                OperaSendClipTab("EMAIL")
                OperaSendClipTab($aReservations[$m][$ixGuestEmail])
            EndIf
            If StringLen($aReservations[$m][$ixGuestPhone]) > 4 Then
                OperaSendClipTab("HOME")
                OperaSendClipTab($aReservations[$m][$ixGuestPhone])
            EndIf
        EndIf
        OperaSend("!o")
        WaitWhileCs("NOT", $aCS_Misc_InFocusReservation, 64, 10)

        OperaTab(-4)
    EndIf
    #EndRegion Enter New Profile Details
    #EndRegion Profile Select/New
    ProgressSet(30, "Agent/Company/Group")
    #Region Agent Company Group
    If $aReservations[$m][$ixAgent] <> "" Then;#######Watch out for negotiated Rate Window!
        TakeFirstResult($aReservations[$m][$ixAgent])
    Else
        OperaTab()
    EndIf
    If $aReservations[$m][$ixCompany] <> "" Then;#######Watch out for negotiated Rate Window!
        TakeFirstResult($aReservations[$m][$ixCompany])
    Else
        OperaTab()
    EndIf
    If $aReservations[$m][$ixGroup] <> "" Then
        TakeFirstResult($aReservations[$m][$ixGroup])
    Else
        OperaTab()
    EndIf
    #EndRegion Agent Company Group
    ProgressSet(40, "TA Rec Loc, Checkin/Checkout, Persons, Children, Rooms")
    #Region Basic Reservation Data
    OperaSendClipTab($aReservations[$m][$ixReservationCode])
    OperaSendClipTab($aReservations[$m][$ixCheckInDay] & $aReservations[$m][$ixCheckInMonth] & $aReservations[$m][$ixCheckInYear], 2)
    OperaSendClipTab($aReservations[$m][$ixCheckoutDay] & $aReservations[$m][$ixCheckoutMonth] & $aReservations[$m][$ixCheckoutYear])
    OperaSendTab($aReservations[$m][$ixNumPersons])
    OperaSendTab($aReservations[$m][$ixNumChildren])
    OperaSendTab($aReservations[$m][$ixNumRooms])
    #EndRegion Basic Reservation Data
    ProgressSet(55, "Roomtype, Rate Code")
    #Region Room Rate and Packages
    OperaSendClipTab($aReservations[$m][$ixRoomType], 3)
    OperaSendRawTab($aReservations[$m][$ixRateCode])
    Sleep(350);300.06 accoring to test was minimum####################

    If CSTestInOpera($aCS_Pop_Warn_DifferentRatesMayAppy) = 1 Then
        OperaSend("{ENTER}")
        WaitWhileCs("NOT", $aCS_Misc_InFocusReservation, 64, 10)

    EndIf
    #EndRegion Room Rate and Packages
    ProgressSet(70, "Reservation Type, Market, Source, Origin")
    #Region Statistics and Categories
    OperaTab(5)
    OperaSendRawTab($aReservations[$m][$ixResType])
    OperaSendRawTab($aReservations[$m][$ixResMarket])
    OperaSendRawTab($aReservations[$m][$ixResSource])
    OperaSendRawTab($aReservations[$m][$ixResOrigin])
    #EndRegion Statistics and Categories
    ProgressSet(80, "Payment")
    #Region Payment
    If $aReservations[$m][$ixPaymentType] = "" Or $aReservations[$m][$ixPaymentType] = "CA" Then
        OperaSendRaw("CA")
    ElseIf $aReservations[$m][$ixPaymentType] = "CL" Then
        OperaSendRaw("CL")
    Else
        OperaSendRawTab($aReservations[$m][$ixPaymentType])
        WaitWhileCs("NOT", $aCS_Pop_CC_Attach_YN, 64, 10, $aCS_Pop_CC_Existing_OC, "AND")

        If CSTestInOpera($aCS_Pop_CC_Attach_YN) Then OperaSend("!y")
        If CSTestInOpera($aCS_Pop_CC_Existing_OC) Then
            OperaSend("!c")
            WaitWhileCs("NOT", $aCS_Pop_CC_Attach_YN, 64, 10)

            OperaSend("!y")
        EndIf
        WaitWhileCs("NOT", $aCS_Misc_InFocusReservation, 64, 10)

        OperaSendClipTab($aReservations[$m][$ixCreditCardNumber], 1)
        OperaSendClipTab($aReservations[$m][$ixCreditCardExpiryMonth] & $aReservations[$m][$ixCreditCardExpiryYear], 1)
    EndIf
    #EndRegion Payment
    ProgressSet(85, "Comment")
    #Region Comment
    OperaSendClip($aReservations[$m][$ixReservationComment])
    #EndRegion Comment
    ProgressSet(90, "Saving")
    #Region Confirmation
    OperaSend("!s")
    ;Can happen "Existing Reservation for same name for same dates Popup
    WaitWhileCs("NOT", $aCS_Pop_Res_Conf_OK, 16, 10)

    If CSTestInOpera($aCS_Pop_Res_Conf_OK) Then
        OperaSend("!o")
    EndIf
    #EndRegion Confirmation
    #Region Accompanying
    If $aReservations[$m][$ixAccompGuestSurName] <> "" Then
        ProgressSet(95, "Accompanying")
        WaitWhileCs("NOT", $aCS_Misc_InFocusReservation, 64, 10)
        #Region Open Accompanying Profile Search
        OperaSend("!t");Open Options
        WaitWhileCs("NOT", $aCS_Win_OptionsinFocus, 64, 5)

        OperaSend("!y");Select "accompanYing"
        WaitWhileCs("NOT", $aCS_Misc_ProfileSearchNoResultSelected, 64, 5)

        OperaSendClipTab($aReservations[$m][$ixAccompGuestSurName])
        OperaSendClipTab($aReservations[$m][$ixAccompGuestFirstName])
        IndividualProfileSearch()
        #EndRegion Open Accompanying Profile Search
        $iTempNewProfile = 0
        If CSTestInOpera($aCS_Misc_ProfileSearchWithFirstResultSelected) = 1 Then
            $iProfileMsgBoxAnswer = MsgBox(262144 + 32 + 4, @ScriptName, "Selektiertes Profil verwenden?" & @CRLF & "(automatisch Ja in 7 sekunden)", 7)
            BlockInactiveWindowsAndMouse(1);re-_MouseTrap because the MsgBox releases it.
            If $iProfileMsgBoxAnswer <= 6 Then;Yes or Timeout
                OperaSend("!o")
            ElseIf $iProfileMsgBoxAnswer = 7 Then;No
                $iTempNewProfile = 1
            EndIf
        ElseIf CSTestInOpera($aCS_Misc_ProfileSearchNoResultSelected) = 1 Then
            $iTempNewProfile = 1
        Else
            MsgBox(0, @ScriptName, "Error2. Will abort.", 2)
            Exit;#########todo: improve error handling##############
        EndIf
        If $iTempNewProfile = 1 Then
            OperaSend("!n")
            WaitWhileCs("", $aCS_Win_IndividualProfilInFocus, 16, 10)
            OperaTab(4)
            OperaSendClipTab($aReservations[$m][$ixAccompGuestTitle])
        EndIf
        OperaSend("!o")
        WaitWhileCs("NOT", $aCS_Win_AccompinFocus, 64, 7)
        OperaSend("!c")
        WaitWhileCs("NOT", $aCS_Win_OptionsinFocus, 64, 7)
        OperaSend("!c")
    EndIf
    #EndRegion Accompanying
    ProgressSet(100, "Finished!")
    #Region UnBlocking
    AdlibUnRegister("AdlibCheckWinStillActive")
    UnDoBlockInactiveWindowsAndMouse()
    OnAutoItExitUnRegister("UnDoBlockInactiveWindowsAndMouse")
    #EndRegion UnBlocking
    ProgressOff()
EndFunc   ;==>EnterInOpera
Func IndividualProfileSearch()
    OperaSendRaw("i");Individual
    OperaSend("{ENTER}")
    WaitWhileCs("", $aCS_Misc_ProfileSearchInProgress, 64, 3)
    Sleep(256)
    WaitForTheMouse()
EndFunc   ;==>IndividualProfileSearch
#Region WaitForCS Function
Func WaitWhileCs($not, $aCS, $checkeveryms = 16, $timeoutseconds = 10, $aCS2 = False, $AndOr = "OR")
    Local $iTimeOut = 0
    If $aCS2 = False Then
        If $not = "NOT" Then
            cr("NOT")
            While Not CSTestInOpera($aCS)
                Sleep($checkeveryms)
                $iTimeOut += $checkeveryms
                If $iTimeOut > (1000 * $timeoutseconds) Then TimedOut()
            WEnd
        Else
            cr("=")
            While CSTestInOpera($aCS)
                Sleep($checkeveryms)
                $iTimeOut += $checkeveryms
                If $iTimeOut > (1000 * $timeoutseconds) Then TimedOut()
            WEnd
        EndIf
    ElseIf $AndOr = "OR" Then
        If $not = "NOT" Then
            cr("OR NOT")
            While Not CSTestInOpera($aCS) Or CSTestInOpera($aCS2)
                Sleep($checkeveryms)
                $iTimeOut += $checkeveryms
                If $iTimeOut > (1000 * $timeoutseconds) Then TimedOut()
            WEnd
        Else
            cr("OR")
            While CSTestInOpera($aCS) Or CSTestInOpera($aCS2)
                Sleep($checkeveryms)
                $iTimeOut += $checkeveryms
                If $iTimeOut > (1000 * $timeoutseconds) Then TimedOut()
            WEnd
        EndIf
    ElseIf $AndOr = "AND" Then
        If $not = "NOT" Then
            cr("AND NOT")
            While Not CSTestInOpera($aCS) And Not CSTestInOpera($aCS2)
                Sleep($checkeveryms)
                $iTimeOut += $checkeveryms
                If $iTimeOut > (1000 * $timeoutseconds) Then TimedOut()
            WEnd
        Else
            cr("AND")
            While CSTestInOpera($aCS) And CSTestInOpera($aCS2)
                Sleep($checkeveryms)
                $iTimeOut += $checkeveryms
                If $iTimeOut > (1000 * $timeoutseconds) Then TimedOut()
            WEnd
        EndIf
    EndIf
EndFunc   ;==>WaitWhileCs
#EndRegion WaitForCS Function
Func TimedOut()
    _Exit()
EndFunc   ;==>TimedOut
#Region OperaSend
Func TakeFirstResult($sString)
    OperaSendClipTab($sString)
    WaitWhileCs("NOT", $aCS_Misc_ProfileSearchNoResultSelected, 64, 10)

    OperaSend("!o")
    Sleep(256)
    WaitWhileCs("NOT", $aCS_Misc_InFocusReservation, 64, 10, $aCS_Pop_General_OKButton, "AND")

    If CSTestInOpera($aCS_Pop_General_OKButton) = 1 Then
        OperaSend("!o")
        WaitWhileCs("NOT", $aCS_Misc_InFocusReservation, 64, 10)
    EndIf
EndFunc   ;==>TakeFirstResult

Func OperaSendRaw($sSend)
    OperaSend($sSend, 1)
EndFunc   ;==>OperaSendRaw
Func OperaSendRawTab($sSend, $i = 1)
    OperaSend($sSend, 1)
    OperaTab($i)
EndFunc   ;==>OperaSendRawTab

Func OperaSendClip($sSend)
    OperaSend($sSend, 2)
EndFunc   ;==>OperaSendClip
Func OperaSendClipTab($sSend, $i = 1)
    OperaSend($sSend, 2)
    OperaTab($i)
EndFunc   ;==>OperaSendClipTab

Func OperaSendTab($sSend, $i = 1)
    OperaSend($sSend)
    OperaTab($i)
EndFunc   ;==>OperaSendTab

Func OperaTab($n = 1)
    If $n = 1 Then
        OperaSend("{TAB}")
    ElseIf $n > 1 Then
        OperaSend("{TAB " & $n & "}")
    ElseIf $n < 1 Then
        OperaSend("+{TAB " & Abs($n) & "}")
    EndIf
EndFunc   ;==>OperaTab

Func OperaSend($sSend, $flag = 0)
    WaitForTheMouse()
    If $flag = 2 Then
        ClipPut("")
        ClipPut($sSend)
        Sleep(128);Must not be removed
        Do
            Local $x = ControlSend($wHandleOpera, "", $cHandleOpera, "^v")
        Until $x = 1
        ;Sleep(128)
    Else
        Sleep(64)
        Do
            $x = ControlSend($wHandleOpera, "", $cHandleOpera, $sSend, $flag)
        Until $x = 1
    EndIf
EndFunc   ;==>OperaSend

Func WaitForTheMouse()
    While MouseGetCursor() <> 2
        ;cr("WaitForTheMouse")
        Sleep(100)
    WEnd
EndFunc   ;==>WaitForTheMouse
#EndRegion OperaSend
#Region PixelChecksum
Func CSTestInOpera($aCheckSumTest, $iCheckSumStep = 1, $bCheckSumMode = 1)
    If WinExists($wHandleOpera) And UBound($aCheckSumTest) = 5 Then
        Local $aCheckSum = PixelChecksum($aCheckSumTest[1], $aCheckSumTest[2], $aCheckSumTest[3], $aCheckSumTest[4], $iCheckSumStep, $wHandleOpera, $bCheckSumMode)
        If $aCheckSum = $aCheckSumTest[0] Then
            Return True
        Else
            Return False
        EndIf
    Else
        SetError(1)
        Return False
    EndIf
EndFunc   ;==>CSTestInOpera
#EndRegion PixelChecksum
#Region Blocking
Func AdlibCheckWinStillActive()
    If Not WinActive($wHandleOpera) Then
        WinActivate($wHandleOpera)
        If @error Then
            _Exit()
        EndIf
    EndIf
EndFunc   ;==>AdlibCheckWinStillActive
Func BlockInactiveWindowsAndMouse($flag = 0);if Flag = 1 then just reblock mouse
    ;Note: Check out http://www.autoitscript.com/forum/topic/87735-blockinputex-udf/
    If $flag = 0 Then
        WinSetOnTop($wHandleOpera, "", 1)
        WinSetState($wHandleOpera, "", @SW_DISABLE)
        Global $aBlockerWinList = WinList()
        For $i = 1 To $aBlockerWinList[0][0]
            If BitAND(WinGetState($aBlockerWinList[$i][1]), 2) And BitAND(WinGetState($aBlockerWinList[$i][1]), 4) And $aBlockerWinList[$i][1] <> $wHandleOpera Then;Visible+Enabled+NotActive
                WinSetState($aBlockerWinList[$i][1], "", @SW_DISABLE)
                $aBlockerWinList[$i][0] = 1
            Else
                $aBlockerWinList[$i][0] = 0
            EndIf
        Next
        WinMove($wHandleOpera, "", Default, Default, 1024, 768)
    EndIf
    Local $aTempWinGetPos = WinGetPos($wHandleOpera)
    _MouseTrap($aTempWinGetPos[0] + Int($aTempWinGetPos[2] / 2), $aTempWinGetPos[1] + Int($aTempWinGetPos[3] / 2), $aTempWinGetPos[0] + Int($aTempWinGetPos[2] / 2), $aTempWinGetPos[1] + Int($aTempWinGetPos[3] / 2))
    If Not WinActive($wHandleOpera) Then WinActivate($wHandleOpera)
EndFunc   ;==>BlockInactiveWindowsAndMouse
Func UnDoBlockInactiveWindowsAndMouse()
    _MouseTrap()
    WinSetOnTop($wHandleOpera, "", 0)
    For $i = 1 To $aBlockerWinList[0][0]
        If $aBlockerWinList[$i][0] = 1 Then
            WinSetState($aBlockerWinList[$i][1], "", @SW_ENABLE)
        EndIf
    Next
    If Not WinActive($wHandleOpera) Then WinActivate($wHandleOpera)
    WinSetState($wHandleOpera, "", @SW_ENABLE)
EndFunc   ;==>UnDoBlockInactiveWindowsAndMouse
#EndRegion Blocking
#EndRegion EnterInOpera

#Region Basic Script Functions (Exit, CR, NA)
Func _Exit()
    Exit
EndFunc   ;==>_Exit
Func cr($text = "") ;Print to console
    ConsoleWrite($text & @CR)
    Return $text
EndFunc   ;==>cr
Func na($aArray)
    If IsArray($aArray) Then
        Return $aArray[0]
    ElseIf IsString($aArray) Then
        Return $aArray
    Else
        SetError(1)
        Return ""
    EndIf
EndFunc   ;==>na
#EndRegion Basic Script Functions (Exit, CR, NA)

This is my biggest scripting project so far.

In it´s current state the script already works and is useful.

Next step, after fixing the issue that I can´t really read it anymore, is to improve and expand it.

As you can see I´m automating the input of reservations into some software.

See an older post '?do=embed' frameborder='0' data-embedContent>> to find out what the trouble with the indirect ControlSend is about.

I had an older version that I rewrote to this, after I understood how to deal with multi-dimensional arrays and Enumeration, which I´m using heavily.

Edited by guestscripter

Share this post


Link to post
Share on other sites

#7 ·  Posted (edited)

That's not that bad.  A script doesn't become spaghetti until it begins to hit like 10,000 or 20,000 lines. 

The main things I can see are to

1) use spaces.  This helps the eye scan for logical sections.

2) The function EnterInOpera looks like a major candidate for being broken up into smaller functions.  Take your regions in that func as a starting point.

Well, good luck to you.  Please come back and ask us if you need more help.

Edited by jaberwacky
1 person likes this

Share this post


Link to post
Share on other sites

10,000 20,000 lines? 

maybe someday my stomach would have the tolerance for that amount of spaghetti :-)

That's not that bad.  A script doesn't become spaghetti until it begins to hit like 10,000 or 20,000 lines. 

The main things I can see are to

1) use spaces.  This helps the eye scan for logical sections.

2) The function EnterInOpera looks like a major candidate for being broken up into smaller functions.  Take your regions in that func as a starting point.

Well, good luck to you.  Please come back and ask us if you need more help.

Yeah that sounds like a great idea with some spaces, and some smaller functions.

That and the above #includes trick will I think, when I´ve used them, make things look a lot clearer.

Maybe I´ll also get out some paper and map out where all my variables and functions are coming from and going to somehow... unless there´s already an app that "visualises" an autoit script in 3-D or something somewhere :-D.

Anyway thanks so much guys!

I´ll get back if I somehow need more support when I´ve done the dirty work!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0