"Fossies" - the Fresh Open Source Software Archive

Member "AutoHotkey_L-1.1.33.09/source/defines.h" (8 May 2021, 54040 Bytes) of package /windows/misc/AutoHotkey_L-1.1.33.09.zip:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "defines.h" see the Fossies "Dox" file reference documentation.

    1 /*
    2 AutoHotkey
    3 
    4 Copyright 2003-2009 Chris Mallett (support@autohotkey.com)
    5 
    6 This program is free software; you can redistribute it and/or
    7 modify it under the terms of the GNU General Public License
    8 as published by the Free Software Foundation; either version 2
    9 of the License, or (at your option) any later version.
   10 
   11 This program is distributed in the hope that it will be useful,
   12 but WITHOUT ANY WARRANTY; without even the implied warranty of
   13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   14 GNU General Public License for more details.
   15 */
   16 
   17 #ifndef defines_h
   18 #define defines_h
   19 
   20 
   21 // Disable silly performance warning about converting int to bool:
   22 // Unlike other typecasts from a larger type to a smaller, I'm 99% sure
   23 // that all compilers are supposed to do something special for bool,
   24 // not just truncate.  Example:
   25 // bool x = 0xF0000000
   26 // The above should give the value "true" to x, not false which is
   27 // what would happen if:
   28 // char x = 0xF0000000
   29 //
   30 #ifdef _MSC_VER
   31 #pragma warning(disable:4800)
   32 #endif
   33 
   34 #define AHK_NAME "AutoHotkey"
   35 #include "ahkversion.h"
   36 #define AHK_WEBSITE "https://autohotkey.com"
   37 
   38 #define T_AHK_NAME          _T(AHK_NAME)
   39 #define T_AHK_VERSION       _T(AHK_VERSION)
   40 #define T_AHK_NAME_VERSION  T_AHK_NAME _T(" v") T_AHK_VERSION
   41 
   42 // Window class names: Changing these may result in new versions not being able to detect any old instances
   43 // that may be running (such as the use of FindWindow() in WinMain()).  It may also have other unwanted
   44 // effects, such as anything in the OS that relies on the class name that the user may have changed the
   45 // settings for, such as whether to hide the tray icon (though it probably doesn't use the class name
   46 // in that example).
   47 // MSDN: "Because window classes are process specific, window class names need to be unique only within
   48 // the same process. Also, because class names occupy space in the system's private atom table, you
   49 // should keep class name strings as short a possible:
   50 #define WINDOW_CLASS_MAIN _T("AutoHotkey")
   51 #define WINDOW_CLASS_SPLASH _T("AutoHotkey2")
   52 #define WINDOW_CLASS_GUI _T("AutoHotkeyGUI") // There's a section in Script::Edit() that relies on these all starting with "AutoHotkey".
   53 
   54 #define EXT_AUTOHOTKEY _T(".ahk")
   55 #define AHK_HELP_FILE _T("AutoHotkey.chm")
   56 
   57 // AutoIt2 supports lines up to 16384 characters long, and we want to be able to do so too
   58 // so that really long lines from aut2 scripts, such as a chain of IF commands, can be
   59 // brought in and parsed.  In addition, it also allows continuation sections to be long.
   60 #define LINE_SIZE (16384 + 1)  // +1 for terminator.  Don't increase LINE_SIZE above 65535 without considering ArgStruct::length's type (WORD).
   61 
   62 // Maximum length of a Unicode file path, plus null-terminator.
   63 #define MAX_WIDE_PATH 32768
   64 #ifdef UNICODE
   65 #define T_MAX_PATH MAX_WIDE_PATH
   66 #else
   67 #define T_MAX_PATH MAX_PATH
   68 #endif
   69 
   70 // The following avoid having to link to OLDNAMES.lib, but they probably don't
   71 // reduce code size at all.
   72 #define stricmp(str1, str2) _stricmp(str1, str2)
   73 #define strnicmp(str1, str2, size) _strnicmp(str1, str2, size)
   74 
   75 // Items that may be needed for VC++ 6.X:
   76 #ifndef SPI_GETFOREGROUNDLOCKTIMEOUT
   77     #define SPI_GETFOREGROUNDLOCKTIMEOUT        0x2000
   78     #define SPI_SETFOREGROUNDLOCKTIMEOUT        0x2001
   79 #endif
   80 #ifndef VK_XBUTTON1
   81     #define VK_XBUTTON1       0x05    /* NOT contiguous with L & RBUTTON */
   82     #define VK_XBUTTON2       0x06    /* NOT contiguous with L & RBUTTON */
   83     #define WM_NCXBUTTONDOWN                0x00AB
   84     #define WM_NCXBUTTONUP                  0x00AC
   85     #define WM_NCXBUTTONDBLCLK              0x00AD
   86     #define GET_WHEEL_DELTA_WPARAM(wParam)  ((short)HIWORD(wParam))
   87     #define WM_XBUTTONDOWN                  0x020B
   88     #define WM_XBUTTONUP                    0x020C
   89     #define WM_XBUTTONDBLCLK                0x020D
   90     #define GET_KEYSTATE_WPARAM(wParam)     (LOWORD(wParam))
   91     #define GET_NCHITTEST_WPARAM(wParam)    ((short)LOWORD(wParam))
   92     #define GET_XBUTTON_WPARAM(wParam)      (HIWORD(wParam))
   93     /* XButton values are WORD flags */
   94     #define XBUTTON1      0x0001
   95     #define XBUTTON2      0x0002
   96 #endif
   97 #ifndef HIMETRIC_INCH
   98     #define HIMETRIC_INCH 2540
   99 #endif
  100 
  101 
  102 #define IS_32BIT(signed_value_64) (signed_value_64 >= INT_MIN && signed_value_64 <= INT_MAX)
  103 #define GET_BIT(buf,n) (((buf) & (1 << (n))) >> (n))
  104 #define SET_BIT(buf,n,val) ((val) ? ((buf) |= (1<<(n))) : (buf &= ~(1<<(n))))
  105 
  106 // FAIL = 0 to remind that FAIL should have the value zero instead of something arbitrary
  107 // because some callers may simply evaluate the return result as true or false
  108 // (and false is a failure):
  109 enum ResultType {FAIL = 0, OK, WARN = OK, CRITICAL_ERROR  // Some things might rely on OK==1 (i.e. boolean "true")
  110     , CONDITION_TRUE, CONDITION_FALSE
  111     , LOOP_BREAK, LOOP_CONTINUE
  112     , EARLY_RETURN, EARLY_EXIT}; // EARLY_EXIT needs to be distinct from FAIL for ExitApp() and AutoExecSection().
  113 
  114 enum ExcptModeType {EXCPTMODE_NONE = 0
  115     , EXCPTMODE_TRY = 1 // Try block present.  Affects SetErrorLevelOrThrow().
  116     , EXCPTMODE_CATCH = 2 // Exception will be suppressed or caught.
  117     , EXCPTMODE_DELETE = 4}; // Unhandled exceptions will display ERR_ABORT_DELETE vs. ERR_ABORT.
  118 
  119 #define SEND_MODES { _T("Event"), _T("Input"), _T("Play"), _T("InputThenPlay") } // Must match the enum below.
  120 enum SendModes {SM_EVENT, SM_INPUT, SM_PLAY, SM_INPUT_FALLBACK_TO_PLAY, SM_INVALID}; // SM_EVENT must be zero.
  121 // In above, SM_INPUT falls back to SM_EVENT when the SendInput mode would be defeated by the presence
  122 // of a keyboard/mouse hooks in another script (it does this because SendEvent is superior to a
  123 // crippled/interruptible SendInput due to SendEvent being able to dynamically adjust to changing
  124 // conditions [such as the user releasing a modifier key during the Send]).  By contrast,
  125 // SM_INPUT_FALLBACK_TO_PLAY falls back to the SendPlay mode.  SendInput has this extra fallback behavior
  126 // because it's likely to become the most popular sending method.
  127 
  128 enum SendRawModes {SCM_NOT_RAW = FALSE, SCM_RAW, SCM_RAW_TEXT};
  129 typedef UCHAR SendRawType;
  130 
  131 enum ExitReasons {EXIT_CRITICAL = -2, EXIT_DESTROY = -1, EXIT_NONE = 0, EXIT_ERROR, EXIT_LOGOFF, EXIT_SHUTDOWN
  132     , EXIT_CLOSE, EXIT_MENU, EXIT_EXIT, EXIT_RELOAD, EXIT_SINGLEINSTANCE};
  133 #define EXITREASON_MUST_EXIT(er) (static_cast<ExitReasons>(er) <= EXIT_DESTROY)
  134 
  135 enum WarnType {WARN_USE_UNSET_LOCAL, WARN_USE_UNSET_GLOBAL, WARN_LOCAL_SAME_AS_GLOBAL, WARN_USE_ENV, WARN_CLASS_OVERWRITE, WARN_UNREACHABLE, WARN_ALL};
  136 #define WARN_TYPE_STRINGS _T("UseUnsetLocal"), _T("UseUnsetGlobal"), _T("LocalSameAsGlobal"), _T("UseEnv"), _T("ClassOverwrite"), _T("Unreachable"), _T("All")
  137 
  138 enum WarnMode {WARNMODE_OFF, WARNMODE_OUTPUTDEBUG, WARNMODE_MSGBOX, WARNMODE_STDOUT};   // WARNMODE_OFF must be zero.
  139 #define WARN_MODE_STRINGS _T("Off"), _T("OutputDebug"), _T("MsgBox"), _T("StdOut")
  140 
  141 enum SingleInstanceType {ALLOW_MULTI_INSTANCE, SINGLE_INSTANCE_PROMPT, SINGLE_INSTANCE_REPLACE
  142     , SINGLE_INSTANCE_IGNORE, SINGLE_INSTANCE_OFF}; // ALLOW_MULTI_INSTANCE must be zero.
  143 
  144 enum MenuTypeType {MENU_TYPE_NONE, MENU_TYPE_POPUP, MENU_TYPE_BAR}; // NONE must be zero.
  145 
  146 // These are used for things that can be turned on, off, or left at a
  147 // neutral default value that is neither on nor off.  INVALID must
  148 // be zero:
  149 enum ToggleValueType {TOGGLE_INVALID = 0, TOGGLED_ON, TOGGLED_OFF, ALWAYS_ON, ALWAYS_OFF, TOGGLE
  150     , TOGGLE_PERMIT, NEUTRAL, TOGGLE_SEND, TOGGLE_MOUSE, TOGGLE_SENDANDMOUSE, TOGGLE_DEFAULT
  151     , TOGGLE_MOUSEMOVE, TOGGLE_MOUSEMOVEOFF};
  152 
  153 // Some things (such as ListView sorting) rely on SCS_INSENSITIVE being zero.
  154 // In addition, BIF_InStr relies on SCS_SENSITIVE being 1:
  155 enum StringCaseSenseType {SCS_INSENSITIVE, SCS_SENSITIVE, SCS_INSENSITIVE_LOCALE, SCS_INSENSITIVE_LOGICAL, SCS_INVALID};
  156 
  157 enum RegSyntax {REG_OLD_SYNTAX, REG_NEW_SYNTAX, REG_EITHER_SYNTAX};
  158 
  159 enum SymbolType // For use with ExpandExpression() and IsPureNumeric().
  160 {
  161     // The sPrecedence array in ExpandExpression() must be kept in sync with any additions, removals,
  162     // or re-ordering of the below.  Also, IS_OPERAND() relies on all operand types being at the
  163     // beginning of the list:
  164      PURE_NOT_NUMERIC // Must be zero/false because callers rely on that.
  165     , PURE_INTEGER, PURE_FLOAT
  166     , SYM_STRING = PURE_NOT_NUMERIC, SYM_INTEGER = PURE_INTEGER, SYM_FLOAT = PURE_FLOAT // Specific operand types.
  167 #define IS_NUMERIC(symbol) ((symbol) == SYM_INTEGER || (symbol) == SYM_FLOAT) // Ordered for short-circuit performance.
  168     , SYM_MISSING // Only used in parameter lists.
  169     , SYM_VAR // An operand that is a variable's contents.
  170     , SYM_OPERAND // Generic/undetermined type of operand.
  171     , SYM_OBJECT // L31: Represents an IObject interface pointer.
  172     , SYM_DYNAMIC // An operand that needs further processing during the evaluation phase.
  173     , SYM_OPERAND_END // Marks the symbol after the last operand.  This value is used below.
  174     , SYM_BEGIN = SYM_OPERAND_END  // SYM_BEGIN is a special marker to simplify the code.
  175 #define IS_OPERAND(symbol) ((symbol) < SYM_OPERAND_END)
  176     , SYM_POST_INCREMENT, SYM_POST_DECREMENT // Kept in this position for use by YIELDS_AN_OPERAND() [helps performance].
  177     , SYM_DOT // DOT must precede SYM_OPAREN so YIELDS_AN_OPERAND(SYM_GET) == TRUE, allowing auto-concat to work for it even though it is positioned after its second operand.
  178     , SYM_CPAREN, SYM_CBRACKET, SYM_CBRACE, SYM_OPAREN, SYM_OBRACKET, SYM_OBRACE, SYM_COMMA  // CPAREN (close-paren)/CBRACKET/CBRACE must come right before OPAREN for YIELDS_AN_OPERAND.
  179 #define IS_OPAREN_LIKE(symbol) ((symbol) <= SYM_OBRACE && (symbol) >= SYM_OPAREN)
  180 #define IS_CPAREN_LIKE(symbol) ((symbol) <= SYM_CBRACE && (symbol) >= SYM_CPAREN)
  181 #define IS_OPAREN_MATCHING_CPAREN(sym_oparen, sym_cparen) ((sym_oparen - sym_cparen) == (SYM_OPAREN - SYM_CPAREN)) // Requires that (IS_OPAREN_LIKE(sym_oparen) || IS_CPAREN_LIKE(sym_cparen)) is true.
  182 #define SYM_CPAREN_FOR_OPAREN(symbol) ((symbol) - (SYM_OPAREN - SYM_CPAREN)) // Caller must confirm it is OPAREN or OBRACKET.
  183 #define SYM_OPAREN_FOR_CPAREN(symbol) ((symbol) + (SYM_OPAREN - SYM_CPAREN)) // Caller must confirm it is CPAREN or CBRACKET.
  184 #define YIELDS_AN_OPERAND(symbol) ((symbol) < SYM_OPAREN) // CPAREN also covers the tail end of a function call.  Post-inc/dec yields an operand for things like Var++ + 2.  Definitely needs the parentheses around symbol.
  185     , SYM_ASSIGN, SYM_ASSIGN_ADD, SYM_ASSIGN_SUBTRACT, SYM_ASSIGN_MULTIPLY, SYM_ASSIGN_DIVIDE, SYM_ASSIGN_FLOORDIVIDE
  186     , SYM_ASSIGN_BITOR, SYM_ASSIGN_BITXOR, SYM_ASSIGN_BITAND, SYM_ASSIGN_BITSHIFTLEFT, SYM_ASSIGN_BITSHIFTRIGHT
  187     , SYM_ASSIGN_CONCAT // THIS MUST BE KEPT AS THE LAST (AND SYM_ASSIGN THE FIRST) BECAUSE THEY'RE USED IN A RANGE-CHECK.
  188 #define IS_ASSIGNMENT_EXCEPT_POST_AND_PRE(symbol) (symbol <= SYM_ASSIGN_CONCAT && symbol >= SYM_ASSIGN) // Check upper bound first for short-circuit performance.
  189 #define IS_ASSIGNMENT_OR_POST_OP(symbol) (IS_ASSIGNMENT_EXCEPT_POST_AND_PRE(symbol) || symbol == SYM_POST_INCREMENT || symbol == SYM_POST_DECREMENT)
  190     , SYM_IFF_ELSE, SYM_IFF_THEN // THESE TERNARY OPERATORS MUST BE KEPT IN THIS ORDER AND ADJACENT TO THE BELOW.
  191     , SYM_OR, SYM_AND // MUST BE KEPT IN THIS ORDER AND ADJACENT TO THE ABOVE because infix-to-postfix is optimized to check a range rather than a series of equalities.
  192     , SYM_LOWNOT  // LOWNOT is the word "not", the low precedence counterpart of !
  193     , SYM_EQUAL, SYM_EQUALCASE, SYM_NOTEQUAL // =, ==, <> ... Keep this in sync with IS_RELATIONAL_OPERATOR() below.
  194     , SYM_GT, SYM_LT, SYM_GTOE, SYM_LTOE  // >, <, >=, <= ... Keep this in sync with IS_RELATIONAL_OPERATOR() below.
  195 #define IS_RELATIONAL_OPERATOR(symbol) (symbol >= SYM_EQUAL && symbol <= SYM_LTOE)
  196     , SYM_CONCAT
  197     , SYM_BITOR // Seems more intuitive to have these higher in prec. than the above, unlike C and Perl, but like Python.
  198     , SYM_BITXOR // SYM_BITOR (ABOVE) MUST BE KEPT FIRST AMONG THE BIT OPERATORS BECAUSE IT'S USED IN A RANGE-CHECK.
  199     , SYM_BITAND
  200     , SYM_BITSHIFTLEFT, SYM_BITSHIFTRIGHT // << >>  ALSO: SYM_BITSHIFTRIGHT MUST BE KEPT LAST AMONG THE BIT OPERATORS BECAUSE IT'S USED IN A RANGE-CHECK.
  201     , SYM_ADD, SYM_SUBTRACT
  202     , SYM_MULTIPLY, SYM_DIVIDE, SYM_FLOORDIVIDE
  203     , SYM_NEGATIVE, SYM_HIGHNOT, SYM_BITNOT, SYM_ADDRESS, SYM_DEREF  // Don't change position or order of these because Infix-to-postfix converter's special handling for SYM_POWER relies on them being adjacent to each other.
  204     , SYM_POWER    // See comments near precedence array for why this takes precedence over SYM_NEGATIVE.
  205     , SYM_PRE_INCREMENT, SYM_PRE_DECREMENT // Must be kept after the post-ops and in this order relative to each other due to a range check in the code.
  206     , SYM_FUNC     // A call to a function.
  207     , SYM_NEW      // new Class()
  208     , SYM_REGEXMATCH // L31: Experimental ~= RegExMatch operator, equivalent to a RegExMatch call in two-parameter mode.
  209     , SYM_COUNT    // Must be last because it's the total symbol count for everything above.
  210     , SYM_INVALID = SYM_COUNT // Some callers may rely on YIELDS_AN_OPERAND(SYM_INVALID)==false.
  211 };
  212 // These two are macros for maintainability (i.e. seeing them together here helps maintain them together).
  213 #define SYM_DYNAMIC_IS_DOUBLE_DEREF(token) (token.buf) // SYM_DYNAMICs other than doubles have NULL buf, at least at the stage this macro is called.
  214 #define SYM_DYNAMIC_IS_VAR_NORMAL_OR_CLIP(token) (!(token)->buf && ((token)->var->Type() == VAR_NORMAL || (token)->var->Type() == VAR_CLIPBOARD)) // i.e. it's an environment variable or the clipboard, not a built-in variable or double-deref.
  215 
  216 
  217 struct ExprTokenType; // Forward declarations for use below.
  218 struct IDebugProperties;
  219 
  220 
  221 struct DECLSPEC_NOVTABLE IObject // L31: Abstract interface for "objects".
  222     : public IDispatch
  223 {
  224     // See script_object.cpp for comments.
  225     virtual ResultType STDMETHODCALLTYPE Invoke(ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount) = 0;
  226     virtual LPTSTR Type() = 0;
  227     #define IObject_Type_Impl(name) \
  228         LPTSTR Type() { return _T(name); }
  229     
  230 #ifdef CONFIG_DEBUGGER
  231     virtual void DebugWriteProperty(IDebugProperties *, int aPage, int aPageSize, int aMaxDepth) = 0;
  232 #endif
  233 };
  234 
  235 
  236 struct DECLSPEC_NOVTABLE IObjectComCompatible : public IObject
  237 {
  238     STDMETHODIMP QueryInterface(REFIID riid, void **ppv);
  239     //STDMETHODIMP_(ULONG) AddRef() = 0;
  240     //STDMETHODIMP_(ULONG) Release() = 0;
  241     STDMETHODIMP GetTypeInfoCount(UINT *pctinfo);
  242     STDMETHODIMP GetTypeInfo(UINT itinfo, LCID lcid, ITypeInfo **pptinfo);
  243     STDMETHODIMP GetIDsOfNames(REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId);
  244     STDMETHODIMP Invoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr);
  245 };
  246 
  247 
  248 #ifdef CONFIG_DEBUGGER
  249 
  250 typedef void *DebugCookie;
  251 
  252 struct DECLSPEC_NOVTABLE IDebugProperties
  253 {
  254     // For simplicity/code size, the debugger handles failures internally
  255     // rather than returning an error code and requiring caller to handle it.
  256     virtual void WriteProperty(LPCSTR aName, ExprTokenType &aValue) = 0;
  257     virtual void WriteProperty(ExprTokenType &aKey, ExprTokenType &aValue) = 0;
  258     virtual void BeginProperty(LPCSTR aName, LPCSTR aType, int aNumChildren, DebugCookie &aCookie) = 0;
  259     virtual void EndProperty(DebugCookie aCookie) = 0;
  260 };
  261 
  262 #endif
  263 
  264 
  265 // Flags used when calling Invoke; also used by g_ObjGet etc.:
  266 #define IT_GET              0
  267 #define IT_SET              1
  268 #define IT_CALL             2 // L40: MetaObject::Invoke relies on these being mutually-exclusive bits.
  269 #define IT_BITMASK          3 // bit-mask for the above.
  270 
  271 #define IF_METAOBJ          0x10000 // Indicates 'this' is a meta-object/base of aThisToken. Restricts some functionality and causes aThisToken to be inserted into the param list of called functions.
  272 #define IF_METAFUNC         0x20000 // Indicates Invoke should call a meta-function before checking the object's fields.
  273 #define IF_META             (IF_METAOBJ | IF_METAFUNC)  // Flags for regular recursion into base object.
  274 #define IF_FUNCOBJ          0x40000 // Indicates 'this' is a function, being called via another object (aParam[0]).
  275 #define IF_NEWENUM          0x80000 // Workaround for COM objects which don't resolve "_NewEnum" to DISPID_NEWENUM.
  276 #define IF_CALL_FUNC_ONLY   0x100000 // Used by IDispatch: call only if value is a function.
  277 
  278 
  279 // Helper function for event handlers and __Delete:
  280 ResultType CallMethod(IObject *aInvokee, IObject *aThis, LPTSTR aMethodName
  281     , ExprTokenType *aParamValue = NULL, int aParamCount = 0, INT_PTR *aRetVal = NULL // For event handlers.
  282     , int aExtraFlags = 0); // For Object.__Delete().
  283 
  284 
  285 struct DerefType; // Forward declarations for use below.
  286 class Var;        //
  287 struct ExprTokenType  // Something in the compiler hates the name TokenType, so using a different name.
  288 {
  289     // Due to the presence of 8-byte members (double and __int64) this entire struct is aligned on 8-byte
  290     // vs. 4-byte boundaries.  The compiler defaults to this because otherwise an 8-byte member might
  291     // sometimes not start at an even address, which would hurt performance on Pentiums, etc.
  292     union // Which of its members is used depends on the value of symbol, below.
  293     {
  294         __int64 value_int64; // for SYM_INTEGER
  295         double value_double; // for SYM_FLOAT
  296         struct
  297         {
  298             union // These nested structs and unions minimize the token size by overlapping data.
  299             {
  300                 IObject *object;
  301                 DerefType *deref; // for SYM_FUNC, and (while parsing) SYM_ASSIGN etc.
  302                 Var *var;         // for SYM_VAR
  303                 LPTSTR marker;     // for SYM_STRING and SYM_OPERAND.
  304             };
  305             union // Due to the outermost union, this doesn't increase the total size of the struct on x86 builds (but it does on x64). It's used by SYM_FUNC (helps built-in functions), SYM_DYNAMIC, SYM_OPERAND, and perhaps other misc. purposes.
  306             {
  307                 LPTSTR buf;
  308                 size_t marker_length; // Used only with aResultToken. TODO: Move into separate ResultTokenType struct.
  309                 BOOL is_lvalue;   // for SYM_VAR
  310             };
  311         };  
  312     };
  313     // Note that marker's str-length should not be stored in this struct, even though it might be readily
  314     // available in places and thus help performance.  This is because if it were stored and the marker
  315     // or SYM_VAR's var pointed to a location that was changed as a side effect of an expression's
  316     // call to a script function, the length would then be invalid.
  317     SymbolType symbol; // Short-circuit benchmark is currently much faster with this and the next beneath the union, perhaps due to CPU optimizations for 8-byte alignment.
  318     union
  319     {
  320         ExprTokenType *circuit_token; // Facilitates short-circuit boolean evaluation.
  321         LPTSTR mem_to_free; // Used only with aResultToken. TODO: Move into separate ResultTokenType struct.
  322     };
  323     // The above two probably need to be adjacent to each other to conserve memory due to 8-byte alignment,
  324     // which is the default alignment (for performance reasons) in any struct that contains 8-byte members
  325     // such as double and __int64.
  326 
  327     ExprTokenType() {}
  328     ExprTokenType(__int64 aValue) { SetValue(aValue); }
  329     ExprTokenType(double aValue) { SetValue(aValue); }
  330     ExprTokenType(IObject *aValue) { SetValue(aValue); }
  331     ExprTokenType(LPTSTR aValue) { SetValue(aValue); }
  332     
  333     void SetValue(__int64 aValue)
  334     {
  335         symbol = SYM_INTEGER;
  336         value_int64 = aValue;
  337     }
  338     void SetValue(int aValue) { SetValue((__int64)aValue); }
  339     void SetValue(UINT aValue) { SetValue((__int64)aValue); }
  340     void SetValue(UINT64 aValue) { SetValue((__int64)aValue); }
  341     void SetValue(double aValue)
  342     {
  343         symbol = SYM_FLOAT;
  344         value_double = aValue;
  345     }
  346     void SetValue(LPTSTR aValue)
  347     {
  348         ASSERT(aValue);
  349         symbol = SYM_STRING;
  350         marker = aValue;
  351     }
  352     void SetValue(IObject *aValue)
  353     // Caller must AddRef() if appropriate.
  354     {
  355         ASSERT(aValue);
  356         symbol = SYM_OBJECT;
  357         object = aValue;
  358     }
  359 
  360     inline void CopyValueFrom(ExprTokenType &other)
  361     // Copies the value of a token (by reference where applicable).  Does not object->AddRef().
  362     {
  363         value_int64 = other.value_int64; // Union copy.
  364 #ifdef _WIN64
  365         // For simplicity/smaller code size, don't bother checking symbol == SYM_STRING.
  366         buf = other.buf; // Already covered by the above on x86.
  367 #endif
  368         symbol = other.symbol;
  369     }
  370 };
  371 #define MAX_TOKENS 512 // Max number of operators/operands.  Seems enough to handle anything realistic, while conserving call-stack space.
  372 #define STACK_PUSH(token_ptr) stack[stack_count++] = token_ptr
  373 #define STACK_POP stack[--stack_count]  // To be used as the r-value for an assignment.
  374 
  375 // But the array that goes with these actions is in globaldata.cpp because
  376 // otherwise it would be a little cumbersome to declare the extern version
  377 // of the array in here (since it's only extern to modules other than
  378 // script.cpp):
  379 enum enum_act {
  380 // Seems best to make ACT_INVALID zero so that it will be the ZeroMemory() default within
  381 // any POD structures that contain an action_type field:
  382   ACT_INVALID = FAIL  // These should both be zero for initialization and function-return-value purposes.
  383 , ACT_ASSIGN, ACT_ASSIGNEXPR, ACT_EXPRESSION, ACT_ADD, ACT_SUB, ACT_MULT, ACT_DIV
  384 , ACT_ASSIGN_FIRST = ACT_ASSIGN, ACT_ASSIGN_LAST = ACT_DIV
  385 , ACT_STATIC
  386 , ACT_IFIN, ACT_IFNOTIN, ACT_IFCONTAINS, ACT_IFNOTCONTAINS, ACT_IFIS, ACT_IFISNOT
  387 , ACT_IFBETWEEN, ACT_IFNOTBETWEEN
  388 , ACT_IFEXPR  // i.e. if (expr)
  389  // *** *** *** KEEP ALL OLD-STYLE/AUTOIT V2 IFs AFTER THIS (v1.0.20 bug fix). *** *** ***
  390  , ACT_FIRST_IF_ALLOWING_SAME_LINE_ACTION
  391  // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
  392  // ACT_IS_IF_OLD() relies upon ACT_IFEQUAL through ACT_IFLESSOREQUAL being adjacent to one another
  393  // and it relies upon the fact that ACT_IFEQUAL is first in the series and ACT_IFLESSOREQUAL last.
  394 , ACT_IFEQUAL = ACT_FIRST_IF_ALLOWING_SAME_LINE_ACTION, ACT_IFNOTEQUAL, ACT_IFGREATER, ACT_IFGREATEROREQUAL
  395 , ACT_IFLESS, ACT_IFLESSOREQUAL
  396 , ACT_FIRST_OPTIMIZED_IF = ACT_IFBETWEEN, ACT_LAST_OPTIMIZED_IF = ACT_IFLESSOREQUAL
  397 , ACT_FIRST_COMMAND // i.e the above aren't considered commands for parsing/searching purposes.
  398 , ACT_IFWINEXIST = ACT_FIRST_COMMAND
  399 , ACT_IFWINNOTEXIST, ACT_IFWINACTIVE, ACT_IFWINNOTACTIVE
  400 , ACT_IFINSTRING, ACT_IFNOTINSTRING
  401 , ACT_IFEXIST, ACT_IFNOTEXIST, ACT_IFMSGBOX
  402 , ACT_FIRST_IF = ACT_IFIN, ACT_LAST_IF = ACT_IFMSGBOX  // Keep this range updated with any new IFs that are added.
  403 , ACT_ELSE
  404 , ACT_MSGBOX, ACT_INPUTBOX, ACT_SPLASHTEXTON, ACT_SPLASHTEXTOFF, ACT_PROGRESS, ACT_SPLASHIMAGE
  405 , ACT_TOOLTIP, ACT_TRAYTIP, ACT_INPUT
  406 , ACT_TRANSFORM, ACT_STRINGLEFT, ACT_STRINGRIGHT, ACT_STRINGMID
  407 , ACT_STRINGTRIMLEFT, ACT_STRINGTRIMRIGHT, ACT_STRINGLOWER, ACT_STRINGUPPER
  408 , ACT_STRINGLEN, ACT_STRINGGETPOS, ACT_STRINGREPLACE, ACT_STRINGSPLIT, ACT_SPLITPATH, ACT_SORT
  409 , ACT_ENVGET, ACT_ENVSET, ACT_ENVUPDATE
  410 , ACT_RUNAS, ACT_RUN, ACT_RUNWAIT, ACT_URLDOWNLOADTOFILE
  411 , ACT_GETKEYSTATE
  412 , ACT_SEND, ACT_SENDRAW, ACT_SENDINPUT, ACT_SENDPLAY, ACT_SENDEVENT
  413 , ACT_CONTROLSEND, ACT_CONTROLSENDRAW, ACT_CONTROLCLICK, ACT_CONTROLMOVE, ACT_CONTROLGETPOS, ACT_CONTROLFOCUS
  414 , ACT_CONTROLGETFOCUS, ACT_CONTROLSETTEXT, ACT_CONTROLGETTEXT, ACT_CONTROL, ACT_CONTROLGET
  415 , ACT_SENDMODE, ACT_SENDLEVEL, ACT_COORDMODE, ACT_SETDEFAULTMOUSESPEED
  416 , ACT_CLICK, ACT_MOUSEMOVE, ACT_MOUSECLICK, ACT_MOUSECLICKDRAG, ACT_MOUSEGETPOS
  417 , ACT_STATUSBARGETTEXT
  418 , ACT_STATUSBARWAIT
  419 , ACT_CLIPWAIT, ACT_KEYWAIT
  420 , ACT_SLEEP, ACT_RANDOM
  421 , ACT_GOTO, ACT_GOSUB, ACT_ONEXIT, ACT_HOTKEY, ACT_SETTIMER, ACT_CRITICAL, ACT_THREAD, ACT_RETURN, ACT_EXIT
  422 , ACT_LOOP, ACT_FOR, ACT_WHILE, ACT_UNTIL, ACT_BREAK, ACT_CONTINUE // Keep LOOP, FOR, WHILE and UNTIL together and in this order for range checks in various places.
  423 , ACT_TRY, ACT_CATCH, ACT_FINALLY, ACT_THROW // Keep TRY, CATCH and FINALLY together and in this order for range checks.
  424 , ACT_SWITCH, ACT_CASE
  425 , ACT_BLOCK_BEGIN, ACT_BLOCK_END
  426 , ACT_WINACTIVATE, ACT_WINACTIVATEBOTTOM
  427 , ACT_WINWAIT, ACT_WINWAITCLOSE, ACT_WINWAITACTIVE, ACT_WINWAITNOTACTIVE
  428 , ACT_WINMINIMIZE, ACT_WINMAXIMIZE, ACT_WINRESTORE
  429 , ACT_WINHIDE, ACT_WINSHOW
  430 , ACT_WINMINIMIZEALL, ACT_WINMINIMIZEALLUNDO
  431 , ACT_WINCLOSE, ACT_WINKILL, ACT_WINMOVE, ACT_WINMENUSELECTITEM, ACT_PROCESS
  432 , ACT_WINSET, ACT_WINSETTITLE, ACT_WINGETTITLE, ACT_WINGETCLASS, ACT_WINGET, ACT_WINGETPOS, ACT_WINGETTEXT
  433 , ACT_SYSGET, ACT_POSTMESSAGE, ACT_SENDMESSAGE
  434 // Keep rarely used actions near the bottom for parsing/performance reasons:
  435 , ACT_PIXELGETCOLOR, ACT_PIXELSEARCH, ACT_IMAGESEARCH
  436 , ACT_GROUPADD, ACT_GROUPACTIVATE, ACT_GROUPDEACTIVATE, ACT_GROUPCLOSE
  437 , ACT_DRIVESPACEFREE, ACT_DRIVE, ACT_DRIVEGET
  438 , ACT_SOUNDGET, ACT_SOUNDSET, ACT_SOUNDGETWAVEVOLUME, ACT_SOUNDSETWAVEVOLUME, ACT_SOUNDBEEP, ACT_SOUNDPLAY
  439 , ACT_FILEAPPEND, ACT_FILEREAD, ACT_FILEREADLINE, ACT_FILEDELETE, ACT_FILERECYCLE, ACT_FILERECYCLEEMPTY
  440 , ACT_FILEINSTALL, ACT_FILECOPY, ACT_FILEMOVE, ACT_FILECOPYDIR, ACT_FILEMOVEDIR
  441 , ACT_FILECREATEDIR, ACT_FILEREMOVEDIR
  442 , ACT_FILEGETATTRIB, ACT_FILESETATTRIB, ACT_FILEGETTIME, ACT_FILESETTIME
  443 , ACT_FILEGETSIZE, ACT_FILEGETVERSION
  444 , ACT_SETWORKINGDIR, ACT_FILESELECTFILE, ACT_FILESELECTFOLDER, ACT_FILEGETSHORTCUT, ACT_FILECREATESHORTCUT
  445 , ACT_INIREAD, ACT_INIWRITE, ACT_INIDELETE
  446 , ACT_REGREAD, ACT_REGWRITE, ACT_REGDELETE, ACT_SETREGVIEW
  447 , ACT_OUTPUTDEBUG
  448 , ACT_SETKEYDELAY, ACT_SETMOUSEDELAY, ACT_SETWINDELAY, ACT_SETCONTROLDELAY, ACT_SETBATCHLINES
  449 , ACT_SETTITLEMATCHMODE, ACT_SETFORMAT, ACT_FORMATTIME
  450 , ACT_SUSPEND, ACT_PAUSE
  451 , ACT_AUTOTRIM, ACT_STRINGCASESENSE, ACT_DETECTHIDDENWINDOWS, ACT_DETECTHIDDENTEXT, ACT_BLOCKINPUT
  452 , ACT_SETNUMLOCKSTATE, ACT_SETSCROLLLOCKSTATE, ACT_SETCAPSLOCKSTATE, ACT_SETSTORECAPSLOCKMODE
  453 , ACT_KEYHISTORY, ACT_LISTLINES, ACT_LISTVARS, ACT_LISTHOTKEYS
  454 , ACT_EDIT, ACT_RELOAD, ACT_MENU, ACT_GUI, ACT_GUICONTROL, ACT_GUICONTROLGET
  455 , ACT_EXITAPP
  456 , ACT_SHUTDOWN
  457 , ACT_FILEENCODING
  458 , ACT_HOTKEY_IF
  459 // Make these the last ones before the count so they will be less often processed.  This helps
  460 // performance because this one doesn't actually have a keyword so will never result
  461 // in a match anyway.  UPDATE: No longer used because Run/RunWait is now required, which greatly
  462 // improves syntax checking during load:
  463 //, ACT_EXEC
  464 // It's safer to use g_ActionCount, which is calculated immediately after the array is declared
  465 // and initialized, at which time we know its true size.  However, the following lets us detect
  466 // when the size of the array doesn't match the enum (in debug mode):
  467 #ifdef _DEBUG
  468 , ACT_COUNT
  469 #endif
  470 };
  471 
  472 enum enum_act_old {
  473   OLD_INVALID = FAIL  // These should both be zero for initialization and function-return-value purposes.
  474   , OLD_SETENV, OLD_ENVADD, OLD_ENVSUB, OLD_ENVMULT, OLD_ENVDIV
  475   // ACT_IS_IF_OLD() relies on the items in this next line being adjacent to one another and in this order:
  476   , OLD_IFEQUAL, OLD_IFNOTEQUAL, OLD_IFGREATER, OLD_IFGREATEROREQUAL, OLD_IFLESS, OLD_IFLESSOREQUAL
  477   , OLD_WINGETACTIVETITLE, OLD_WINGETACTIVESTATS
  478 };
  479 
  480 // It seems best not to include ACT_SUSPEND in the below, since the user may have marked
  481 // a large number of subroutines as "Suspend, Permit".  Even PAUSE is iffy, since the user
  482 // may be using it as "Pause, off/toggle", but it seems best to support PAUSE because otherwise
  483 // hotkey such as "#z::pause" would not be able to unpause the script if its MaxThreadsPerHotkey
  484 // was 1 (the default).
  485 #define ACT_IS_ALWAYS_ALLOWED(ActionType) (ActionType == ACT_EXITAPP || ActionType == ACT_PAUSE \
  486     || ActionType == ACT_EDIT || ActionType == ACT_RELOAD || ActionType == ACT_KEYHISTORY \
  487     || ActionType == ACT_LISTLINES || ActionType == ACT_LISTVARS || ActionType == ACT_LISTHOTKEYS)
  488 #define ACT_IS_ASSIGN(ActionType) (ActionType <= ACT_ASSIGN_LAST && ActionType >= ACT_ASSIGN_FIRST) // Ordered for short-circuit performance.
  489 #define ACT_IS_IF(ActionType) (ActionType >= ACT_FIRST_IF && ActionType <= ACT_LAST_IF)
  490 #define ACT_IS_LOOP(ActionType) (ActionType >= ACT_LOOP && ActionType <= ACT_WHILE)
  491 #define ACT_IS_LINE_PARENT(ActionType) (ACT_IS_IF(ActionType) || ActionType == ACT_ELSE \
  492     || ACT_IS_LOOP(ActionType) || (ActionType >= ACT_TRY && ActionType <= ACT_FINALLY))
  493 #define ACT_IS_IF_OLD(ActionType, OldActionType) (ActionType >= ACT_FIRST_IF_ALLOWING_SAME_LINE_ACTION && ActionType <= ACT_LAST_IF) \
  494     && (ActionType < ACT_IFEQUAL || ActionType > ACT_IFLESSOREQUAL || (OldActionType >= OLD_IFEQUAL && OldActionType <= OLD_IFLESSOREQUAL))
  495     // All the checks above must be done so that cmds such as IfMsgBox (which are both "old" and "new")
  496     // can support parameters on the same line or on the next line.  For example, both of the above are allowed:
  497     // IfMsgBox, No, Gosub, XXX
  498     // IfMsgBox, No
  499     //     Gosub, XXX
  500 
  501 // Cases where arg.is_expression should always be true.
  502 // ACT_WHILE performs less than 4% faster as a non-expression in some cases, slower
  503 // in some other cases, and keeping it as an expression avoids an extra check in a
  504 // performance-sensitive spot of ExpandArgs (near mActionType <= ACT_LAST_OPTIMIZED_IF).
  505 // ACT_UNTIL is given the same treatment but wasn't tested extensively as a non-expression.
  506 // Additionally, FOR, THROW, SWITCH and CASE are kept as expressions in all cases to
  507 // simplify the code (which works around ExpandArgs() lack of support for objects).
  508 // ACT_EXPRESSION is excluded since `Saved := ClipboardAll` must be non-expression.
  509 #define ACT_IS_ALWAYS_EXPRESSION(ActionType) \
  510     ((ActionType >= ACT_FOR && ActionType <= ACT_UNTIL) \
  511     || (ActionType >= ACT_THROW && ActionType <= ACT_CASE))
  512 
  513 // Cases where the legacy rules for "numeric" params should not be applied; that is,
  514 // LegacyArgIsExpression() should not be called because ActionType is not legacy.
  515 #define ACT_NO_LEGACY_EXPRESSION(ActionType) \
  516     (ActionType == ACT_ASSIGNEXPR || ACT_IS_ALWAYS_EXPRESSION(ActionType))
  517 
  518 // For convenience in many places.  Must cast to int to avoid loss of negative values.
  519 #define BUF_SPACE_REMAINING ((int)(aBufSize - (aBuf - aBuf_orig)))
  520 
  521 // MsgBox timeout value.  This can't be zero because that is used as a failure indicator:
  522 // Also, this define is in this file to prevent problems with mutual
  523 // dependency between script.h and window.h.  Update: It can't be -1 either because
  524 // that value is used to indicate failure by DialogBox():
  525 #define AHK_TIMEOUT -2
  526 // And these to prevent mutual dependency problem between window.h and globaldata.h:
  527 #define MAX_MSGBOXES 7 // Probably best not to change this because it's used by OurTimers to set the timer IDs, which should probably be kept the same for backward compatibility.
  528 #define MAX_INPUTBOXES 4
  529 #define MAX_PROGRESS_WINDOWS 10  // Allow a lot for downloads and such.
  530 #define MAX_PROGRESS_WINDOWS_STR _T("10") // Keep this in sync with above.
  531 #define MAX_SPLASHIMAGE_WINDOWS 10
  532 #define MAX_SPLASHIMAGE_WINDOWS_STR _T("10") // Keep this in sync with above.
  533 #define MAX_MSG_MONITORS 500
  534 
  535 // IMPORTANT: Before ever changing the below, note that it will impact the IDs of menu items created
  536 // with the MENU command, as well as the number of such menu items that are possible (currently about
  537 // 65500-11000=54500). See comments at ID_USER_FIRST for details:
  538 #define GUI_CONTROL_BLOCK_SIZE 1000
  539 #define MAX_CONTROLS_PER_GUI (GUI_CONTROL_BLOCK_SIZE * 11) // Some things rely on this being less than 0xFFFF and an even multiple of GUI_CONTROL_BLOCK_SIZE.
  540 #define NO_CONTROL_INDEX MAX_CONTROLS_PER_GUI // Must be 0xFFFF or less.
  541 #define NO_EVENT_INFO 0 // For backward compatibility with documented contents of A_EventInfo, this should be kept as 0 vs. something more special like UINT_MAX.
  542 
  543 #define MAX_TOOLTIPS 20
  544 #define MAX_TOOLTIPS_STR _T("20")   // Keep this in sync with above.
  545 #define MAX_FILEDIALOGS 4
  546 #define MAX_FOLDERDIALOGS 4
  547 
  548 #define MAX_NUMBER_LENGTH 255                   // Large enough to allow custom zero or space-padding via %10.2f, etc.
  549 #define MAX_NUMBER_SIZE (MAX_NUMBER_LENGTH + 1) // But not too large because some things might rely on this being fairly small.
  550 #define MAX_INTEGER_LENGTH 20                     // Max length of a 64-bit number when expressed as decimal or
  551 #define MAX_INTEGER_SIZE (MAX_INTEGER_LENGTH + 1) // hex string; e.g. -9223372036854775808 or (unsigned) 18446744073709551616 or (hex) -0xFFFFFFFFFFFFFFFF.
  552 
  553 // Hot-strings:
  554 // memmove() and proper detection of long hotstrings rely on buf being at least this large:
  555 #define HS_BUF_SIZE (MAX_HOTSTRING_LENGTH * 2 + 10)
  556 #define HS_BUF_DELETE_COUNT (HS_BUF_SIZE / 2)
  557 #define HS_MAX_END_CHARS 100
  558 
  559 // Bitwise storage of boolean flags.  This section is kept in this file because
  560 // of mutual dependency problems between hook.h and other header files:
  561 typedef UCHAR HookType;
  562 #define HOOK_KEYBD 0x01
  563 #define HOOK_MOUSE 0x02
  564 #define HOOK_FAIL  0xFF
  565 
  566 #define EXTERN_G extern global_struct *g
  567 #define EXTERN_OSVER extern OS_Version g_os
  568 #define EXTERN_CLIPBOARD extern Clipboard g_clip
  569 #define EXTERN_SCRIPT extern Script g_script
  570 #define CLOSE_CLIPBOARD_IF_OPEN if (g_clip.mIsOpen) g_clip.Close()
  571 #define CLIPBOARD_CONTAINS_ONLY_FILES (!IsClipboardFormatAvailable(CF_NATIVETEXT) && IsClipboardFormatAvailable(CF_HDROP))
  572 
  573 
  574 // These macros used to keep app responsive during a long operation.  In v1.0.39, the
  575 // hooks have a dedicated thread.  However, mLastPeekTime is still compared to 5 rather
  576 // than some higher value for the following reasons:
  577 // 1) Want hotkeys pressed during a long operation to take effect as quickly as possible.
  578 //    For example, in games a hotkey's response time is critical.
  579 // 2) Benchmarking shows less than a 0.5% performance improvement from this comparing
  580 //    to a higher value (even one as high as 500), even when the system is under heavy
  581 //    load from other processes).
  582 //
  583 // mLastPeekTime is global/static so that recursive functions, such as FileSetAttrib(),
  584 // will sleep as often as intended even if the target files require frequent recursion.
  585 // The use of a global/static is not friendly to recursive calls to the function (i.e. calls
  586 // made as a consequence of the current script subroutine being interrupted by another during
  587 // this instance's MsgSleep()).  However, it doesn't seem to be that much of a consequence
  588 // since the exact interval/period of the MsgSleep()'s isn't that important.  It's also
  589 // pretty unlikely that the interrupting subroutine will also just happen to call the same
  590 // function rather than some other.
  591 //
  592 // Older comment that applies if there is ever again no dedicated thread for the hooks:
  593 // These macros were greatly simplified when it was discovered that PeekMessage(), when called
  594 // directly as below, is enough to prevent keyboard and mouse lag when the hooks are installed
  595 #define LONG_OPERATION_INIT MSG msg; DWORD tick_now;
  596 
  597 // MsgSleep() is used rather than SLEEP_WITHOUT_INTERRUPTION to allow other hotkeys to
  598 // launch and interrupt (suspend) the operation.  It seems best to allow that, since
  599 // the user may want to press some fast window activation hotkeys, for example, during
  600 // the operation.  The operation will be resumed after the interrupting subroutine finishes.
  601 // Notes applying to the macro:
  602 // Store tick_now for use later, in case the Peek() isn't done, though not all callers need it later.
  603 // ...
  604 // Since the Peek() will yield when there are no messages, it will often take 20ms or more to return
  605 // (UPDATE: this can't be reproduced with simple tests, so either the OS has changed through service
  606 // packs, or Peek() yields only when the OS detects that the app is calling it too often or calling
  607 // it in certain ways [PM_REMOVE vs. PM_NOREMOVE seems to make no difference: either way it doesn't yield]).
  608 // Therefore, must update tick_now again (its value is used by macro and possibly by its caller)
  609 // to avoid having to Peek() immediately after the next iteration.
  610 // ...
  611 // The code might bench faster when "g_script.mLastPeekTime = tick_now" is a separate operation rather
  612 // than combined in a chained assignment statement.
  613 #define LONG_OPERATION_UPDATE \
  614 {\
  615     tick_now = GetTickCount();\
  616     if (tick_now - g_script.mLastPeekTime > ::g->PeekFrequency)\
  617     {\
  618         if (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))\
  619             MsgSleep(-1);\
  620         tick_now = GetTickCount();\
  621         g_script.mLastPeekTime = tick_now;\
  622     }\
  623 }
  624 
  625 // Same as the above except for SendKeys() and related functions (uses SLEEP_WITHOUT_INTERRUPTION vs. MsgSleep).
  626 #define LONG_OPERATION_UPDATE_FOR_SENDKEYS \
  627 {\
  628     tick_now = GetTickCount();\
  629     if (tick_now - g_script.mLastPeekTime > ::g->PeekFrequency)\
  630     {\
  631         if (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))\
  632             SLEEP_WITHOUT_INTERRUPTION(-1) \
  633         tick_now = GetTickCount();\
  634         g_script.mLastPeekTime = tick_now;\
  635     }\
  636 }
  637 
  638 // Defining these here avoids awkwardness due to the fact that globaldata.cpp
  639 // does not (for design reasons) include globaldata.h:
  640 typedef UCHAR ActionTypeType; // If ever have more than 256 actions, will have to change this (but it would increase code size due to static data in g_act).
  641 #pragma pack(push, 1) // v1.0.45: Reduces code size a little without impacting runtime performance because this struct is hardly ever accessed during runtime.
  642 struct Action
  643 {
  644     LPTSTR Name;
  645     // Just make them int's, rather than something smaller, because the collection
  646     // of actions will take up very little memory.  Int's are probably faster
  647     // for the processor to access since they are the native word size, or something:
  648     // Update for v1.0.40.02: Now that the ARGn macros don't check mArgc, MaxParamsAu2WithHighBit
  649     // is needed to allow MaxParams to stay pure, which in turn prevents Line::Perform()
  650     // from accessing a NULL arg in the sArgDeref array (i.e. an arg that exists only for
  651     // non-AutoIt2 scripts, such as the extra ones in StringGetPos).
  652     // Also, changing these from ints to chars greatly reduces code size since this struct
  653     // is used by g_act to build static data into the code.  Testing shows that the compiler
  654     // will generate a warning even when not in debug mode in the unlikely event that a constant
  655     // larger than 127 is ever stored in one of these:
  656     char MinParams, MaxParams, MaxParamsAu2WithHighBit;
  657     // Array indicating which args must be purely numeric.  The first arg is
  658     // number 1, the second 2, etc (i.e. it doesn't start at zero).  The list
  659     // is ended with a zero, much like a string.  The compiler will notify us
  660     // (verified) if MAX_NUMERIC_PARAMS ever needs to be increased:
  661     #define MAX_NUMERIC_PARAMS 7
  662     ActionTypeType NumericParams[MAX_NUMERIC_PARAMS];
  663 };
  664 #pragma pack(pop)
  665 
  666 // Values are hard-coded for some of the below because they must not deviate from the documented, numerical
  667 // TitleMatchModes:
  668 enum TitleMatchModes {MATCHMODE_INVALID = FAIL, FIND_IN_LEADING_PART = 1, FIND_ANYWHERE = 2, FIND_EXACT = 3, FIND_REGEX, FIND_FAST, FIND_SLOW};
  669 
  670 typedef UINT GuiIndexType; // Some things rely on it being unsigned to avoid the need to check for less-than-zero.
  671 typedef UINT GuiEventType; // Made a UINT vs. enum so that illegal/underflow/overflow values are easier to detect.
  672 
  673 // The following array and enum must be kept in sync with each other:
  674 #define GUI_EVENT_NAMES {_T(""), _T("Normal"), _T("DoubleClick"), _T("RightClick"), _T("ColClick")}
  675 enum GuiEventTypes {GUI_EVENT_NONE  // NONE must be zero for any uses of ZeroMemory(), synonymous with false, etc.
  676     , GUI_EVENT_NORMAL, GUI_EVENT_DBLCLK // Try to avoid changing this and the other common ones in case anyone automates a script via SendMessage (though that does seem very unlikely).
  677     , GUI_EVENT_RCLK, GUI_EVENT_COLCLK
  678     , GUI_EVENT_FIRST_UNNAMED  // This item must always be 1 greater than the last item that has a name in the GUI_EVENT_NAMES array below.
  679     , GUI_EVENT_DROPFILES = GUI_EVENT_FIRST_UNNAMED
  680     , GUI_EVENT_CLOSE, GUI_EVENT_ESCAPE, GUI_EVENT_RESIZE, GUI_EVENT_CONTEXTMENU
  681     , GUI_EVENT_DIGIT_0 = 48}; // Here just as a reminder that this value and higher are reserved so that a single printable character or digit (mnemonic) can be sent, and also so that ListView's "I" notification can add extra data into the high-byte (which lies just to the left of the "I" character in the bitfield).
  682 
  683 typedef USHORT CoordModeType;
  684 
  685 // Bit-field offsets:
  686 #define COORD_MODE_PIXEL   0
  687 #define COORD_MODE_MOUSE   2
  688 #define COORD_MODE_TOOLTIP 4
  689 #define COORD_MODE_CARET   6
  690 #define COORD_MODE_MENU    8
  691 
  692 #define COORD_MODE_WINDOW  0
  693 #define COORD_MODE_CLIENT  1
  694 #define COORD_MODE_SCREEN  2
  695 #define COORD_MODE_MASK    3
  696 #define COORD_MODES { _T("Window"), _T("Client"), _T("Screen") }
  697 
  698 #define COORD_CENTERED (INT_MIN + 1)
  699 #define COORD_UNSPECIFIED INT_MIN
  700 #define COORD_UNSPECIFIED_SHORT SHRT_MIN  // This essentially makes coord -32768 "reserved", but it seems acceptable given usefulness and the rarity of a real coord like that.
  701 
  702 typedef UINT_PTR EventInfoType;
  703 
  704 typedef UCHAR SendLevelType;
  705 // Setting the max level to 100 is somewhat arbitrary. It seems that typical usage would only
  706 // require a few levels at most. We do want to keep the max somewhat small to keep the range
  707 // for magic values that get used in dwExtraInfo to a minimum, to avoid conflicts with other
  708 // apps that may be using the field in other ways.
  709 const SendLevelType SendLevelMax = 100;
  710 // Using int as the type for level so this can be used as validation before converting to SendLevelType.
  711 inline bool SendLevelIsValid(int level) { return level >= 0 && level <= SendLevelMax; }
  712 
  713 
  714 class Line; // Forward declaration.
  715 typedef UCHAR HotCriterionType;
  716 enum HotCriterionEnum {HOT_NO_CRITERION, HOT_IF_ACTIVE, HOT_IF_NOT_ACTIVE, HOT_IF_EXIST, HOT_IF_NOT_EXIST // HOT_NO_CRITERION must be zero.
  717     , HOT_IF_EXPR, HOT_IF_CALLBACK}; // Keep the last two in this order for the macro below.
  718 #define HOT_IF_REQUIRES_EVAL(type) ((type) >= HOT_IF_EXPR)
  719 struct HotkeyCriterion
  720 {
  721     HotCriterionType Type;
  722     LPTSTR WinTitle, WinText;
  723     union
  724     {
  725         Line *ExprLine;
  726         IObject *Callback;
  727     };
  728     HotkeyCriterion *NextCriterion;
  729 
  730     ResultType Eval(LPTSTR aHotkeyName); // For HOT_IF_EXPR and HOT_IF_CALLBACK.
  731 };
  732 
  733 
  734 // Each instance of this struct generally corresponds to a quasi-thread.  The function that creates
  735 // a new thread typically saves the old thread's struct values on its stack so that they can later
  736 // be copied back into the g struct when the thread is resumed:
  737 class Func;                 // Forward declarations
  738 class Label;                //
  739 struct RegItemStruct;       //
  740 struct LoopFilesStruct;
  741 struct LoopReadFileStruct;  //
  742 class GuiType;              //
  743 class ScriptTimer;          //
  744 struct global_struct
  745 {
  746     // 8-byte items are listed first, which might improve alignment for 64-bit processors (dubious).
  747     __int64 LinesPerCycle; // Use 64-bits for this so that user can specify really large values.
  748     __int64 mLoopIteration; // Signed, since script/ITOA64 aren't designed to handle unsigned.
  749     LoopFilesStruct *mLoopFile;  // The file of the current file-loop, if applicable.
  750     RegItemStruct *mLoopRegItem; // The registry subkey or value of the current registry enumeration loop.
  751     LoopReadFileStruct *mLoopReadFile;  // The file whose contents are currently being read by a File-Read Loop.
  752     LPTSTR mLoopField;  // The field of the current string-parsing loop.
  753     // v1.0.44.14: The above mLoop attributes were moved into this structure from the script class
  754     // because they're more appropriate as thread-attributes rather than being global to the entire script.
  755 
  756     TitleMatchModes TitleMatchMode;
  757     int IntervalBeforeRest;
  758     int UninterruptedLineCount; // Stored as a g-struct attribute in case OnExit sub interrupts it while uninterruptible.
  759     int Priority;  // This thread's priority relative to others.
  760     DWORD LastError; // The result of GetLastError() after the most recent DllCall or Run.
  761     GuiEventType GuiEvent; // This thread's triggering event, e.g. DblClk vs. normal click.
  762     EventInfoType EventInfo; // Not named "GuiEventInfo" because it applies to non-GUI events such as clipboard.
  763     POINT GuiPoint; // The position of GuiEvent. Stored as a thread vs. window attribute so that underlying threads see their original values when resumed.
  764     GuiType *GuiWindow; // The GUI window that launched this thread.
  765     GuiType *GuiDefaultWindow; // This thread's default GUI window, used except when specified "Gui, 2:Add, ..."
  766     GuiType *GuiDefaultWindowValid(); // Updates and returns GuiDefaultWindow in case "Gui, Name: Default" wasn't used or the Gui has been destroyed; returns NULL if GuiDefaultWindow is invalid.
  767     GuiType *DialogOwner; // This thread's GUI owner, if any.
  768     GuiIndexType GuiControlIndex; // The GUI control index that launched this thread.
  769     #define THREAD_DIALOG_OWNER (GuiType::ValidGui(::g->DialogOwner) ? ::g->DialogOwner->mHwnd : NULL)
  770     int WinDelay;  // negative values may be used as special flags.
  771     int ControlDelay; // negative values may be used as special flags.
  772     int KeyDelay;     //
  773     int KeyDelayPlay; //
  774     int PressDuration;     // The delay between the up-event and down-event of each keystroke.
  775     int PressDurationPlay; // 
  776     int MouseDelay;     // negative values may be used as special flags.
  777     int MouseDelayPlay; //
  778     TCHAR FormatFloat[32];
  779     Func *CurrentFunc; // v1.0.46.16: The function whose body is currently being processed at load-time, or being run at runtime (if any).
  780     Func *CurrentFuncGosub; // v1.0.48.02: Allows A_ThisFunc to work even when a function Gosubs an external subroutine.
  781     Label *CurrentLabel; // The label that is currently awaiting its matching "return" (if any).
  782     ScriptTimer *CurrentTimer; // The timer that launched this thread (if any).
  783     HWND hWndLastUsed;  // In many cases, it's better to use GetValidLastUsedWindow() when referring to this.
  784     //HWND hWndToRestore;
  785     int MsgBoxResult;  // Which button was pressed in the most recent MsgBox.
  786     HWND DialogHWND;
  787     DWORD RegView;
  788 
  789     // All these one-byte members are kept adjacent to make the struct smaller, which helps conserve stack space:
  790     SendModes SendMode;
  791     DWORD PeekFrequency; // DWORD vs. UCHAR might improve performance a little since it's checked so often.
  792     DWORD ThreadStartTime;
  793     int UninterruptibleDuration; // Must be int to preserve negative values found in g_script.mUninterruptibleTime.
  794     DWORD CalledByIsDialogMessageOrDispatchMsg; // Detects that fact that some messages (like WM_KEYDOWN->WM_NOTIFY for UpDown controls) are translated to different message numbers by IsDialogMessage (and maybe Dispatch too).
  795     bool CalledByIsDialogMessageOrDispatch; // Helps avoid launching a monitor function twice for the same message.  This would probably be okay if it were a normal global rather than in the g-struct, but due to messaging complexity, this lends peace of mind and robustness.
  796     bool TitleFindFast; // Whether to use the fast mode of searching window text, or the more thorough slow mode.
  797     bool DetectHiddenWindows; // Whether to detect the titles of hidden parent windows.
  798     bool DetectHiddenText;    // Whether to detect the text of hidden child windows.
  799     bool AllowThreadToBeInterrupted;  // Whether this thread can be interrupted by custom menu items, hotkeys, or timers.
  800     bool AllowTimers; // v1.0.40.01 Whether new timer threads are allowed to start during this thread.
  801     bool ThreadIsCritical; // Whether this thread has been marked (un)interruptible by the "Critical" command.
  802     UCHAR DefaultMouseSpeed;
  803     CoordModeType CoordMode; // Bitwise collection of flags.
  804     UCHAR StringCaseSense; // On/Off/Locale
  805     bool StoreCapslockMode;
  806     bool AutoTrim;
  807     char FormatInt;
  808     SendLevelType SendLevel;
  809     bool MsgBoxTimedOut; // Doesn't require initialization.
  810     bool IsPaused; // The latter supports better toggling via "Pause" or "Pause Toggle".
  811     bool ListLinesIsEnabled;
  812     UINT Encoding;
  813     int ExcptMode;
  814     ExprTokenType* ThrownToken;
  815     inline bool InTryBlock() { return ExcptMode & EXCPTMODE_TRY; }
  816     bool DetectWindow(HWND aWnd);
  817 };
  818 
  819 inline void global_maximize_interruptibility(global_struct &g)
  820 {
  821     g.AllowThreadToBeInterrupted = true;
  822     g.UninterruptibleDuration = 0; // 0 means uninterruptibility times out instantly.  Some callers may want this so that this "g" can be used to launch other threads (e.g. threadless callbacks) using 0 as their default.
  823     g.ThreadIsCritical = false;
  824     g.AllowTimers = true;
  825     #define PRIORITY_MINIMUM INT_MIN
  826     g.Priority = PRIORITY_MINIMUM; // Ensure minimum priority so that it can always be interrupted.
  827 }
  828 
  829 inline void global_clear_state(global_struct &g)
  830 // Reset those values that represent the condition or state created by previously executed commands
  831 // but that shouldn't be retained for future threads (e.g. SetTitleMatchMode should be retained for
  832 // future threads if it occurs in the auto-execute section, but ErrorLevel shouldn't).
  833 {
  834     g.CurrentFunc = NULL;
  835     g.CurrentFuncGosub = NULL;
  836     g.CurrentLabel = NULL;
  837     g.hWndLastUsed = NULL;
  838     //g.hWndToRestore = NULL;
  839     g.MsgBoxResult = 0;
  840     g.IsPaused = false;
  841     g.UninterruptedLineCount = 0;
  842     g.DialogOwner = NULL;
  843     g.CalledByIsDialogMessageOrDispatch = false; // CalledByIsDialogMessageOrDispatchMsg doesn't need to be cleared because it's value is only considered relevant when CalledByIsDialogMessageOrDispatch==true.
  844     g.GuiDefaultWindow = NULL;
  845     // Above line is done because allowing it to be permanently changed by the auto-exec section
  846     // seems like it would cause more confusion that it's worth.  A change to the global default
  847     // or even an override/always-use-this-window-number mode can be added if there is ever a
  848     // demand for it.
  849     g.mLoopIteration = 0; // Zero seems preferable to 1, to indicate "no loop currently running" when a thread first starts off.  This should probably be left unchanged for backward compatibility (even though script's aren't supposed to rely on it).
  850     g.mLoopFile = NULL;
  851     g.mLoopRegItem = NULL;
  852     g.mLoopReadFile = NULL;
  853     g.mLoopField = NULL;
  854     g.ThrownToken = NULL;
  855     g.ExcptMode = EXCPTMODE_NONE;
  856 }
  857 
  858 inline void global_init(global_struct &g)
  859 // This isn't made a real constructor to avoid the overhead, since there are times when we
  860 // want to declare a local var of type global_struct without having it initialized.
  861 {
  862     // Init struct with application defaults.  They're in a struct so that it's easier
  863     // to save and restore their values when one hotkey interrupts another, going into
  864     // deeper recursion.  When the interrupting subroutine returns, the former
  865     // subroutine's values for these are restored prior to resuming execution:
  866     global_clear_state(g);
  867     g.SendMode = SM_EVENT;  // v1.0.43: Default to SM_EVENT for backward compatibility.
  868     g.TitleMatchMode = FIND_IN_LEADING_PART; // Standard default for AutoIt2 and 3.
  869     g.TitleFindFast = true; // Since it's so much faster in many cases.
  870     g.DetectHiddenWindows = false;  // Same as AutoIt2 but unlike AutoIt3; seems like a more intuitive default.
  871     g.DetectHiddenText = true;  // Unlike AutoIt, which defaults to false.  This setting performs better.
  872     // Not sure what the optimal default is.  1 seems too low (scripts would be very slow by default):
  873     g.LinesPerCycle = -1;
  874     g.IntervalBeforeRest = 10;  // sleep for 10ms every 10ms
  875     #define DEFAULT_PEEK_FREQUENCY 5
  876     g.PeekFrequency = DEFAULT_PEEK_FREQUENCY; // v1.0.46. See comments in ACT_CRITICAL.
  877     g.AllowThreadToBeInterrupted = true; // Separate from g_AllowInterruption so that they can have independent values.
  878     g.UninterruptibleDuration = 0; // 0 means uninterruptibility times out instantly.  Some callers may want this so that this "g" can be used to launch other threads (e.g. threadless callbacks) using 0 as their default.
  879     g.AllowTimers = true;
  880     g.ThreadIsCritical = false;
  881     g.Priority = 0;
  882     g.LastError = 0;
  883     g.GuiEvent = GUI_EVENT_NONE;
  884     g.EventInfo = NO_EVENT_INFO;
  885     g.GuiPoint.x = COORD_UNSPECIFIED;
  886     g.GuiPoint.y = COORD_UNSPECIFIED;
  887     // For these, indexes rather than pointers are stored because handles can become invalid during the
  888     // lifetime of a thread (while it's suspended, or if it destroys the control or window that created itself):
  889     g.GuiWindow = NULL;
  890     g.GuiControlIndex = NO_CONTROL_INDEX; // Default to out-of-bounds.
  891     g.GuiDefaultWindow = NULL;
  892     g.WinDelay = 100;
  893     g.ControlDelay = 20;
  894     g.KeyDelay = 10;
  895     g.KeyDelayPlay = -1;
  896     g.PressDuration = -1;
  897     g.PressDurationPlay = -1;
  898     g.MouseDelay = 10;
  899     g.MouseDelayPlay = -1;
  900     #define DEFAULT_MOUSE_SPEED 2
  901     #define MAX_MOUSE_SPEED 100
  902     g.DefaultMouseSpeed = DEFAULT_MOUSE_SPEED;
  903     g.CoordMode = 0;  // All the flags it contains are off by default.
  904     g.StringCaseSense = SCS_INSENSITIVE;  // AutoIt2 default, and it does seem best.
  905     g.StoreCapslockMode = true;  // AutoIt2 (and probably 3's) default, and it makes a lot of sense.
  906     g.AutoTrim = true;  // AutoIt2's default, and overall the best default in most cases.
  907     _tcscpy(g.FormatFloat, _T("%0.6f"));
  908     g.FormatInt = 'D';
  909     g.SendLevel = 0;
  910     g.ListLinesIsEnabled = true;
  911     g.Encoding = CP_ACP;
  912     // For FormatFloat:
  913     // I considered storing more than 6 digits to the right of the decimal point (which is the default
  914     // for most Unices and MSVC++ it seems).  But going beyond that makes things a little weird for many
  915     // numbers, due to the inherent imprecision of floating point storage.  For example, 83648.4 divided
  916     // by 2 shows up as 41824.200000 with 6 digits, but might show up 41824.19999999999700000000 with
  917     // 20 digits.  The extra zeros could be chopped off the end easily enough, but even so, going beyond
  918     // 6 digits seems to do more harm than good for the avg. user, overall.  A default of 6 is used here
  919     // in case other/future compilers have a different default (for backward compatibility, we want
  920     // 6 to always be in effect as the default for future releases).
  921 }
  922 
  923 #define ERRORLEVEL_SAVED_SIZE 128 // The size that can be remembered (saved & restored) if a thread is interrupted. Big in case user put something bigger than a number in g_ErrorLevel.
  924 
  925 #ifdef UNICODE
  926 #define WINAPI_SUFFIX "W"
  927 #define PROCESS_API_SUFFIX "W" // used by Process32First and Process32Next
  928 #else
  929 #define WINAPI_SUFFIX "A"
  930 #define PROCESS_API_SUFFIX
  931 #endif
  932 
  933 #define _TSIZE(a) ((a)*sizeof(TCHAR))
  934 #define CP_AHKNOBOM 0x80000000
  935 #define CP_AHKCP    (~CP_AHKNOBOM)
  936 
  937 // Use #pragma message(MY_WARN(nnnn) "warning messages") to generate a warning like a compiler's warning
  938 #define __S(x) #x
  939 #define _S(x) __S(x)
  940 #define MY_WARN(n) __FILE__ "(" _S(__LINE__) ") : warning C" __S(n) ": "
  941 
  942 // These will be removed when things are done.
  943 #ifdef CONFIG_UNICODE_CHECK
  944 #define UNICODE_CHECK __declspec(deprecated(_T("Please check what you want are bytes or characters.")))
  945 UNICODE_CHECK inline size_t CHECK_SIZEOF(size_t n) { return n; }
  946 #define SIZEOF(c) CHECK_SIZEOF(sizeof(c))
  947 #pragma deprecated(memcpy, memset, memmove, malloc, realloc, _alloca, alloca, toupper, tolower)
  948 #else
  949 #define UNICODE_CHECK
  950 #endif
  951 
  952 #endif