#Requires AutoHotkey v2.0
; [NMS-PA-07] audit patch: force both hooks so GetKeyState("P") reports real physical state
InstallKeybdHook()
InstallMouseHook() ; [NMS-PD-04] StudioSafety is inlined below; a missing include file would break exported scripts
#SingleInstance Off
#Warn All, Off
Persistent(true)
CoordMode("Mouse", "Screen")
CoordMode("Pixel", "Screen")
CoordMode("ToolTip", "Screen")
SendMode("Input")
SetTitleMatchMode(2)
SetWorkingDir(A_ScriptDir)
DetectHiddenWindows(false)
; Attempt Per-Monitor V2 DPI Awareness for accurate multi-monitor coordinate & UI scaling
try DllCall("User32\SetProcessDpiAwarenessContext", "Ptr", -4, "Int")
catch {
try DllCall("Shcore\SetProcessDpiAwareness", "Int", 2, "Int")
catch {
try DllCall("User32\SetProcessDPIAware", "Int")
}
}
; ==============================================================================
; NICHOLS MACRO STUDIO — PRODUCTION RELEASE
; Single-File Visual Automation Studio for AutoHotkey v2, Windows UIA, & Browsers
; ==============================================================================
; Embedded icon keeps source and generated players self-contained.
class StudioBranding {
static cachedPath := ""
static bigIcon := 0
static smallIcon := 0
static IconFile() {
if this.cachedPath != "" && FileExist(this.cachedPath)
return this.cachedPath
encoded := ""
for chunk in [
"AAABAAcAEBAAAAAAIAAPAwAAdgAAABgYAAAAACAA0gUAAIUDAAAgIAAAAAAgAOcIAABXCQAAMDAAAAAAIABpEAAAPhIAAEBAAAAAACAA2hkAAKciAACAgAAAAAAgACdOAACBPAAAAAAAAAAAIACa7gAAqIoAAIlQTkcNChoKAAAADUlIRFIAAAAQAAAAEAgGAAAAH/P/YQAAAtZJREFUeJydU1tIVFEUXefcOzPOiJmNgz0mxDKJJIj+CqGij6KgF0URRA+ov74igvqIkPovEQrJfoQiIegrUHI+yiKEtKjA7J2kjnOdOw+v997z2HFmKL9rw9kfh7MWa619NmDq6lWOf64qhoGIgTHa1uO2lrPFY3453yQlgTPNhC8gtTJPyOIcSgOBsrKS4g9yd9onAGLMtObzHzaJ/JeMLmXrSfgIQonygkS8NgEtFZQi+MUSYAO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XwaWAlAAAAAASUVORK5CYII="
]
encoded .= chunk
bytes := 0
if !DllCall("Crypt32\CryptStringToBinaryW", "Str", encoded, "UInt", 0, "UInt", 1, "Ptr", 0, "UInt*", &bytes, "Ptr", 0, "Ptr", 0)
throw OSError()
data := Buffer(bytes)
if !DllCall("Crypt32\CryptStringToBinaryW", "Str", encoded, "UInt", 0, "UInt", 1, "Ptr", data, "UInt*", &bytes, "Ptr", 0, "Ptr", 0)
throw OSError()
DirCreate(StudioConstants.TempDir)
path := StudioConstants.TempDir "\Nichols Macro Studio-7269f0b4e683528f.ico"
temporary := path "." DllCall("GetCurrentProcessId") ".tmp"
try {
file := FileOpen(temporary, "w")
try file.RawWrite(data)
finally file.Close()
FileMove(temporary, path, 1)
} finally {
if FileExist(temporary)
FileDelete(temporary)
}
this.cachedPath := path
return path
}
static Apply() {
try TraySetIcon(this.IconFile())
}
static ApplyGui(window) {
try {
path := this.IconFile()
if !this.bigIcon
this.bigIcon := DllCall("LoadImageW", "Ptr", 0, "Str", path, "UInt", 1, "Int", 32, "Int", 32, "UInt", 0x10, "Ptr")
if !this.smallIcon
this.smallIcon := DllCall("LoadImageW", "Ptr", 0, "Str", path, "UInt", 1, "Int", 16, "Int", 16, "UInt", 0x10, "Ptr")
if this.bigIcon
SendMessage(0x80, 1, this.bigIcon, window.Hwnd)
if this.smallIcon
SendMessage(0x80, 0, this.smallIcon, window.Hwnd)
}
}
}
class StudioConstants {
static DataDirectory(root := A_AppData) {
current := root "\NicholsMacroStudio"
; Compatibility only: preserve existing settings and managed profiles.
legacy := root "\AHKMacroStudio"
return DirExist(current) || !DirExist(legacy) ? current : legacy
}
static __New() {
this.AppDataDir := this.DataDirectory()
this.SettingsFile := this.AppDataDir "\settings.json"
this.AutosaveFile := this.AppDataDir "\autosave_recovery.json"
this.RecoveryMetaFile := this.AppDataDir "\recovery_state.json"
this.ManagedProfilesDir := this.AppDataDir "\ManagedProfiles"
}
static AppName := "Nichols Macro Studio"
static AppVersion := "2.0.0"
static SchemaVersion := 2
static AppDataDir := A_AppData "\NicholsMacroStudio"
static SettingsFile := A_AppData "\NicholsMacroStudio\settings.json"
static AutosaveFile := A_AppData "\NicholsMacroStudio\autosave_recovery.json"
static RecoveryMetaFile := A_AppData "\NicholsMacroStudio\recovery_state.json"
static ManagedProfilesDir := A_AppData "\NicholsMacroStudio\ManagedProfiles"
static TempDir := A_Temp "\NicholsMacroStudio_Runtime"
; Application States
static StateIdle := "Idle"
static StateRecording := "Recording"
static StateAdvancedRecording := "Advanced Recording"
static StateSelecting := "Selecting"
static StateFrozenSelection := "Frozen Selection"
static StateRunning := "Running"
static StatePaused := "Paused"
static StateWaiting := "Waiting"
static StateStopping := "Stopping"
; Reliability Levels
static RelStrong := "Strong"
static RelGood := "Good"
static RelContextual := "Contextual"
static RelVisual := "Visual"
static RelFragile := "Fragile"
static RelVeryFragile := "Very Fragile"
; Target Health States (Section 50)
static HealthHealthy := "Healthy"
static HealthUntested := "Untested"
static HealthAmbiguous := "Ambiguous"
static HealthFallbackUsed := "Fallback Used"
static HealthNeedsRepair := "Needs Repair"
static HealthBroken := "Broken"
; Target Fallback Presets (Section 46)
static PresetBalanced := "Balanced"
static PresetResilient := "Resilient"
static PresetStrictSemantic := "StrictSemantic"
static PresetLegacyRecorded := "LegacyRecorded"
static PresetCustom := "Custom"
; Browser Profile Fallback Policies (Section 12)
static PolicyStrict := "Strict"
static PolicyPreferConfigured := "PreferConfiguredThenCurrent"
static PolicyPreferConfiguredDefault := "PreferConfiguredThenDefault"
static PolicyCurrentBrowser := "CurrentBrowser"
static PolicyDefaultProfile := "DefaultProfile"
static PolicyAnyCompatible := "AnyCompatibleSession"
static PolicyAsk := "AskWhenAmbiguous"
static PolicyCustomOrder := "CustomOrder"
static PolicyToFriendlyText(policyCode) {
switch policyCode {
case "Strict": return "Stop if profile unavailable (Strict)"
case "PreferConfiguredThenCurrent": return "Use current browser window if unavailable"
case "PreferConfiguredThenDefault": return "Use browser default profile if unavailable"
case "CurrentBrowser": return "Always use current active browser"
case "DefaultProfile": return "Always use browser default profile"
case "AnyCompatibleSession": return "Use any open compatible browser window"
case "AskWhenAmbiguous": return "Ask me which browser window to use"
case "CustomOrder": return "Custom fallback order"
default: return "Inherit Macro Default (" policyCode ")"
}
}
static FriendlyTextToPolicy(label) {
if InStr(label, "Stop if") || label == "Strict"
return "Strict"
if InStr(label, "current browser window if") || label == "PreferConfiguredThenCurrent"
return "PreferConfiguredThenCurrent"
if InStr(label, "default profile if") || label == "PreferConfiguredThenDefault"
return "PreferConfiguredThenDefault"
if InStr(label, "Always use current") || label == "CurrentBrowser"
return "CurrentBrowser"
if InStr(label, "Always use browser default") || label == "DefaultProfile"
return "DefaultProfile"
if InStr(label, "any open compatible") || label == "AnyCompatibleSession"
return "AnyCompatibleSession"
if InStr(label, "Ask me") || label == "AskWhenAmbiguous"
return "AskWhenAmbiguous"
if InStr(label, "Custom") || label == "CustomOrder"
return "CustomOrder"
return "Inherit"
}
}
; ==============================================================================
; PURE-AHK RFC-8259 JSON PARSER & SERIALIZER
; Supports Maps, Arrays, Objects, Strings, Escapes, Unicode (\uXXXX & surrogates),
; Numbers (Int/Float), Booleans, and Null without external dependencies.
; ==============================================================================
class JsonCodec {
static TrueVal := { __jsonType: "boolean", value: true }
static FalseVal := { __jsonType: "boolean", value: false }
static NullVal := { __jsonType: "null", value: "" }
static Dump(val, indent := " ", depth := 0) {
if !IsSet(val) || val == "" {
return '""'
}
if IsObject(val) {
if HasProp(val, "__jsonType") {
if val.__jsonType == "boolean"
return val.value ? "true" : "false"
if val.__jsonType == "null"
return "null"
}
if val is Array {
if val.Length == 0
return "[]"
out := "["
nl := indent != "" ? "`r`n" : ""
pad := indent != "" ? this._RepeatStr(indent, depth + 1) : ""
closePad := indent != "" ? this._RepeatStr(indent, depth) : ""
for idx, item in val {
if idx > 1
out .= ","
out .= nl . pad . this.Dump(item, indent, depth + 1)
}
return out . nl . closePad . "]"
}
if val is Map {
if val.Count == 0
return "{}"
out := "{"
nl := indent != "" ? "`r`n" : ""
pad := indent != "" ? this._RepeatStr(indent, depth + 1) : ""
closePad := indent != "" ? this._RepeatStr(indent, depth) : ""
sep := indent != "" ? ": " : ":"
first := true
for k, v in val {
if !first
out .= ","
first := false
out .= nl . pad . this.EscapeString(String(k)) . sep . this.Dump(v, indent, depth + 1)
}
return out . nl . closePad . "}"
}
; Generic Object / Class instance with ToMap() or OwnProps()
if HasMethod(val, "ToMap") {
return this.Dump(val.ToMap(), indent, depth)
}
m := Map()
for k, v in val.OwnProps() {
if SubStr(k, 1, 2) != "__"
m[k] := v
}
return this.Dump(m, indent, depth)
}
if val is Integer || val is Float {
return String(val)
}
return this.EscapeString(String(val))
}
static EscapeString(str) {
out := '"'
Loop Parse str {
ch := A_LoopField
code := Ord(ch)
if ch == '"'
out .= '\"'
else if ch == '\'
out .= '\\'
else if ch == '`b'
out .= '\b'
else if ch == '`f'
out .= '\f'
else if ch == '`n'
out .= '\n'
else if ch == '`r'
out .= '\r'
else if ch == '`t'
out .= '\t'
else if code < 0x20
out .= Format("\u{:04x}", code)
else
out .= ch
}
return out . '"'
}
static Load(jsonText) {
if !IsSet(jsonText)
throw ValueError("JSON input is unset")
text := Trim(String(jsonText), " `t`r`n")
if SubStr(text, 1, 1) == Chr(0xFEFF)
text := SubStr(text, 2)
if text == ""
throw ValueError("Empty JSON input")
pos := 1
len := StrLen(text)
result := this._ParseValue(&text, &pos, len)
this._SkipWhitespace(&text, &pos, len)
if pos <= len
throw ValueError("Unexpected trailing characters in JSON at position " pos)
return result
}
static _SkipWhitespace(&text, &pos, len) {
while pos <= len {
c := Ord(SubStr(text, pos, 1))
if c == 32 || c == 9 || c == 10 || c == 13
pos += 1
else
break
}
}
static _ParseValue(&text, &pos, len) {
this._SkipWhitespace(&text, &pos, len)
if pos > len
throw ValueError("Unexpected end of JSON input at position " pos)
ch := SubStr(text, pos, 1)
if ch == '"'
return this._ParseString(&text, &pos, len)
if ch == '{'
return this._ParseObject(&text, &pos, len)
if ch == '['
return this._ParseArray(&text, &pos, len)
if ch == 't' {
if SubStr(text, pos, 4) == "true" {
pos += 4
return true
}
throw ValueError("Invalid token at position " pos)
}
if ch == 'f' {
if SubStr(text, pos, 5) == "false" {
pos += 5
return false
}
throw ValueError("Invalid token at position " pos)
}
if ch == 'n' {
if SubStr(text, pos, 4) == "null" {
pos += 4
return ""
}
throw ValueError("Invalid token at position " pos)
}
if ch == '-' || (Ord(ch) >= 48 && Ord(ch) <= 57)
return this._ParseNumber(&text, &pos, len)
throw ValueError("Unexpected character '" ch "' at position " pos)
}
static _ParseString(&text, &pos, len) {
pos += 1 ; skip opening quote
out := ""
while pos <= len {
ch := SubStr(text, pos, 1)
if ch == '"' {
pos += 1
return out
}
if ch == '\' {
pos += 1
if pos > len
throw ValueError("Unterminated escape sequence in JSON string")
esc := SubStr(text, pos, 1)
if esc == '"'
out .= '"'
else if esc == '\'
out .= '\'
else if esc == '/'
out .= '/'
else if esc == 'b'
out .= '`b'
else if esc == 'f'
out .= '`f'
else if esc == 'n'
out .= '`n'
else if esc == 'r'
out .= '`r'
else if esc == 't'
out .= '`t'
else if esc == 'u' {
if pos + 4 > len
throw ValueError("Incomplete \uXXXX escape in JSON string")
hex := SubStr(text, pos + 1, 4)
if !RegExMatch(hex, "^[0-9a-fA-F]{4}$")
throw ValueError("Invalid hex in \u" hex)
code := Integer("0x" hex)
pos += 4
; Handle UTF-16 surrogate pairs
if (code >= 0xD800 && code <= 0xDBFF) && SubStr(text, pos + 1, 2) == "\u" {
hex2 := SubStr(text, pos + 3, 4)
if RegExMatch(hex2, "^[0-9a-fA-F]{4}$") {
low := Integer("0x" hex2)
if (low >= 0xDC00 && low <= 0xDFFF) {
code := 0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00)
pos += 6
}
}
}
out .= Chr(code)
} else {
throw ValueError("Invalid escape character '\" esc "' at position " pos)
}
pos += 1
} else {
if Ord(ch) < 0x20
throw ValueError("Unescaped control character in JSON string at position " pos)
out .= ch
pos += 1
}
}
throw ValueError("Unterminated string literal in JSON")
}
static _ParseNumber(&text, &pos, len) {
if !RegExMatch(text, "\G-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?", &m, pos)
throw ValueError("Invalid number at position " pos)
numStr := m[0]
pos += StrLen(numStr)
if InStr(numStr, ".") || InStr(numStr, "e") || InStr(numStr, "E")
return Float(numStr)
return Integer(numStr)
}
static _ParseArray(&text, &pos, len) {
pos += 1 ; skip '['
arr := []
this._SkipWhitespace(&text, &pos, len)
if pos <= len && SubStr(text, pos, 1) == ']' {
pos += 1
return arr
}
Loop {
val := this._ParseValue(&text, &pos, len)
arr.Push(val)
this._SkipWhitespace(&text, &pos, len)
if pos > len
throw ValueError("Unterminated array in JSON")
ch := SubStr(text, pos, 1)
if ch == ']' {
pos += 1
return arr
}
if ch != ','
throw ValueError("Expected ',' or ']' in array at position " pos)
pos += 1
}
}
static _ParseObject(&text, &pos, len) {
pos += 1 ; skip '{'
obj := Map()
obj.CaseSense := "Off"
this._SkipWhitespace(&text, &pos, len)
if pos <= len && SubStr(text, pos, 1) == '}' {
pos += 1
return obj
}
Loop {
this._SkipWhitespace(&text, &pos, len)
if pos > len || SubStr(text, pos, 1) != '"'
throw ValueError("Expected string key in object at position " pos)
key := this._ParseString(&text, &pos, len)
this._SkipWhitespace(&text, &pos, len)
if pos > len || SubStr(text, pos, 1) != ':'
throw ValueError("Expected ':' after object key at position " pos)
pos += 1
val := this._ParseValue(&text, &pos, len)
obj[key] := val
this._SkipWhitespace(&text, &pos, len)
if pos > len
throw ValueError("Unterminated object in JSON")
ch := SubStr(text, pos, 1)
if ch == '}' {
pos += 1
return obj
}
if ch != ','
throw ValueError("Expected ',' or '}' in object at position " pos)
pos += 1
}
}
static _RepeatStr(s, count) {
out := ""
Loop count
out .= s
return out
}
}
; ==============================================================================
; CORE SYSTEM UTILITIES (IDs, Atomic File I/O, DPI/Monitor Math, UIPI Elevation)
; ==============================================================================
class StudioUtils {
; GUI processes need not own a console. Never let diagnostics abort startup.
static DiagnosticWrite(message) {
try {
h := DllCall("GetStdHandle", "Int", -11, "Ptr")
if h && h != -1 && DllCall("GetFileType", "Ptr", h, "UInt") {
FileAppend(message, "*")
return
}
}
OutputDebug(message)
try FileAppend(message, StudioConstants.AppDataDir "\diagnostics.log", "UTF-8")
}
static UseTestStorage() {
StudioConstants.AppDataDir := A_ScriptDir "\qa\runtime"
StudioConstants.SettingsFile := StudioConstants.AppDataDir "\settings.json"
StudioConstants.AutosaveFile := StudioConstants.AppDataDir "\autosave.json"
StudioConstants.RecoveryMetaFile := StudioConstants.AppDataDir "\recovery.json"
StudioConstants.ManagedProfilesDir := StudioConstants.AppDataDir "\profiles"
StudioConstants.TempDir := StudioConstants.AppDataDir "\temp"
}
static _idCounter := 1000
static GenId(prefix := "id") {
this._idCounter += 1
rand := Random(100000, 999999)
return prefix "_" A_TickCount "_" this._idCounter "_" rand
}
static ToBool(val) {
if !IsSet(val)
return false
if IsObject(val) {
if HasProp(val, "__jsonType") && val.__jsonType == "boolean"
return !!val.value
return true
}
if val == "true" || val == "True" || val == "TRUE" || val == 1 || val == "1"
return true
if val == "false" || val == "False" || val == "FALSE" || val == 0 || val == "0" || val == ""
return false
return !!val
}
static AtomicWriteFile(targetPath, content, encoding := "UTF-8") {
SplitPath(targetPath, &fileName, &dirPath)
if dirPath != "" && !DirExist(dirPath)
DirCreate(dirPath)
tempPath := targetPath ".tmp_" A_TickCount "_" Random(1000, 9999)
try {
f := FileOpen(tempPath, "w", encoding)
if !f
throw Error("Unable to open temporary file for writing: " tempPath)
f.Write(content)
f.Close()
; Verify temp file exists and is non-empty when content is non-empty
if !FileExist(tempPath)
throw Error("Temporary file verification failed: " tempPath)
if StrLen(content) > 0 && FileGetSize(tempPath) == 0
throw Error("Temporary file wrote 0 bytes unexpectedly: " tempPath)
FileMove(tempPath, targetPath, 1)
return true
} catch as err {
try {
if FileExist(tempPath)
FileDelete(tempPath)
}
throw err
}
}
static SafeReadFile(filePath, defaultText := "") {
if !FileExist(filePath)
return defaultText
try return FileRead(filePath, "UTF-8")
catch
return defaultText
}
; Escapes a string for safe inclusion inside double-quoted AHK v2 string literal
static EscapeAhkString(str) {
s := String(str)
s := StrReplace(s, "``", "````")
s := StrReplace(s, '"', '``"')
s := StrReplace(s, "`r", "``r")
s := StrReplace(s, "`n", "``n")
s := StrReplace(s, "`t", "``t")
return '"' s '"'
}
; Returns Virtual Desktop bounds supporting negative monitor coordinates
static GetVirtualDesktopBounds() {
vx := SysGet(76) ; SM_XVIRTUALSCREEN
vy := SysGet(77) ; SM_YVIRTUALSCREEN
vw := SysGet(78) ; SM_CXVIRTUALSCREEN
vh := SysGet(79) ; SM_CYVIRTUALSCREEN
if vw <= 0
vw := A_ScreenWidth
if vh <= 0
vh := A_ScreenHeight
return { X: vx, Y: vy, W: vw, H: vh, R: vx + vw, B: vy + vh }
}
; Returns DPI scale factor (e.g., 1.0, 1.25, 1.5, 2.0) for a window or primary screen
static GetWindowDpiScale(hwnd := 0) {
if hwnd {
try {
dpi := DllCall("User32\GetDpiForWindow", "Ptr", hwnd, "UInt")
if dpi > 0
return dpi / 96.0
}
}
return A_ScreenDPI / 96.0
}
; Converts screen coordinates to window-relative and client-relative coordinates
static ScreenToWindowRelative(sx, sy, hwnd) {
res := { WinX: sx, WinY: sy, ClientX: sx, ClientY: sy, Valid: false }
if !hwnd || !WinExist("ahk_id " hwnd)
return res
try {
WinGetPos(&wx, &wy, &ww, &wh, "ahk_id " hwnd)
res.WinX := sx - wx
res.WinY := sy - wy
pt := Buffer(8, 0)
NumPut("Int", sx, pt, 0)
NumPut("Int", sy, pt, 4)
if DllCall("User32\ScreenToClient", "Ptr", hwnd, "Ptr", pt) {
res.ClientX := NumGet(pt, 0, "Int")
res.ClientY := NumGet(pt, 4, "Int")
}
res.Valid := true
}
return res
}
; Converts window-relative coordinates back to screen coordinates
static WindowRelativeToScreen(relX, relY, hwnd, useClient := false) {
if !hwnd || !WinExist("ahk_id " hwnd)
return { X: relX, Y: relY, Valid: false }
try {
if useClient {
pt := Buffer(8, 0)
NumPut("Int", relX, pt, 0)
NumPut("Int", relY, pt, 4)
if DllCall("User32\ClientToScreen", "Ptr", hwnd, "Ptr", pt)
return { X: NumGet(pt, 0, "Int"), Y: NumGet(pt, 4, "Int"), Valid: true }
}
WinGetPos(&wx, &wy, , , "ahk_id " hwnd)
return { X: wx + relX, Y: wy + relY, Valid: true }
}
return { X: relX, Y: relY, Valid: false }
}
; Checks if a process is running elevated (Admin) and detects UIPI mismatch
static IsProcessElevated(pid) {
if !pid
return false
hProc := DllCall("Kernel32\OpenProcess", "UInt", 0x1000, "Int", 0, "UInt", pid, "Ptr") ; PROCESS_QUERY_LIMITED_INFORMATION
if !hProc {
; If OpenProcess fails with Access Denied (5) while our process is non-admin, it is likely elevated
return !A_IsAdmin && (A_LastError == 5)
}
hToken := 0
elevated := false
try {
if DllCall("Advapi32\OpenProcessToken", "Ptr", hProc, "UInt", 0x0008, "Ptr*", &hToken) { ; TOKEN_QUERY
elevBuf := Buffer(4, 0)
retLen := 0
if DllCall("Advapi32\GetTokenInformation", "Ptr", hToken, "Int", 20, "Ptr", elevBuf, "UInt", 4, "UInt*", &retLen) { ; TokenElevation = 20
elevated := NumGet(elevBuf, 0, "UInt") != 0
}
}
} finally {
if hToken
DllCall("Kernel32\CloseHandle", "Ptr", hToken)
DllCall("Kernel32\CloseHandle", "Ptr", hProc)
}
return elevated
}
static CheckUIPIWarning(hwnd) {
if A_IsAdmin || !hwnd || !WinExist("ahk_id " hwnd)
return ""
try {
pid := WinGetPID("ahk_id " hwnd)
if this.IsProcessElevated(pid) {
exeName := ""
try exeName := WinGetProcessName("ahk_id " hwnd)
return "Privilege Mismatch (Windows UIPI): The target window (" (exeName ? exeName : "PID " pid) ") is running as Administrator while Nichols Macro Studio is running with standard permissions. Windows blocks non-elevated programs from sending input or inspecting elevated windows."
}
}
return ""
}
static FormatTimestamp(dt := "") {
if dt == ""
dt := A_Now
return FormatTime(dt, "yyyy-MM-dd HH:mm:ss")
}
static CloneMap(src) {
if !(src is Map)
return src
dst := Map()
dst.CaseSense := src.CaseSense
for k, v in src {
if v is Map
dst[k] := this.CloneMap(v)
else if v is Array
dst[k] := this.CloneArray(v)
else
dst[k] := v
}
return dst
}
static CloneArray(src) {
if !(src is Array)
return src
dst := []
for _, v in src {
if v is Map
dst.Push(this.CloneMap(v))
else if v is Array
dst.Push(this.CloneArray(v))
else
dst.Push(v)
}
return dst
}
}
; ==============================================================================
; STRUCTURED LOGGING ENGINE (WITH SECRET MASKING)
; ==============================================================================
class LoggingEngine {
entries := []
secretMaskList := []
onLogAdded := ""
RegisterSecretValue(secretText) {
if StrLen(secretText) >= 2 {
for _, existing in this.secretMaskList {
if existing == secretText
return
}
this.secretMaskList.Push(secretText)
}
}
MaskSecrets(text) {
s := String(text)
for _, sec in this.secretMaskList {
if sec != "" && InStr(s, sec)
s := StrReplace(s, sec, "••••••••")
}
return s
}
Add(level, macroName, stepIndex, actionDesc, resultStatus, durationMs := 0, retries := 0, strategy := "", browserCtx := "", message := "", details := "") {
entry := Map(
"Time", FormatTime(A_Now, "HH:mm:ss") "." Format("{:03}", Mod(A_TickCount, 1000)),
"Level", level,
"Macro", macroName,
"Step", stepIndex,
"Action", this.MaskSecrets(actionDesc),
"Result", resultStatus,
"Duration", durationMs,
"Retries", retries,
"Strategy", strategy,
"Browser", browserCtx,
"Message", this.MaskSecrets(message),
"Details", this.MaskSecrets(details)
)
this.entries.Push(entry)
if this.entries.Length > 2000
this.entries.RemoveAt(1)
if this.onLogAdded != "" && HasMethod(this.onLogAdded)
try this.onLogAdded.Call(entry)
return entry
}
Clear() {
this.entries := []
}
FormatAsText() {
out := "Time`tLevel`tMacro`tStep`tAction`tResult`tDuration(ms)`tRetries`tStrategy`tBrowser`tMessage`r`n"
for _, e in this.entries {
out .= e["Time"] "`t" e["Level"] "`t" e["Macro"] "`t" e["Step"] "`t" e["Action"] "`t" e["Result"] "`t" e["Duration"] "`t" e["Retries"] "`t" e["Strategy"] "`t" e["Browser"] "`t" e["Message"] "`r`n"
}
return out
}
}
; ==============================================================================
; PART 2: PROJECT, MACRO, ACTION, TARGET, SELECTOR, AST & UNDO/REDO MODELS
; ==============================================================================
class ScopeModel {
ScopeType := "ActiveWindow" ; VirtualDesktop, CurrentMonitor, ActiveWindow, SpecificWindow, WindowClientArea, UIAContainer, BrowserSession, BrowserWindow, CurrentBrowserTab, BrowserDocument, BrowserFrame, Region
WinTitle := ""
WinClass := ""
WinExe := ""
ContainerName := ""
ContainerType := ""
ContainerAutomationId := ""
BrowserSession := ""
FrameName := ""
RegionX := 0
RegionY := 0
RegionW := 0
RegionH := 0
RelativeToWindow := true
__New(scopeType := "ActiveWindow") {
this.ScopeType := scopeType
}
GetFriendlyText() {
switch this.ScopeType {
case "VirtualDesktop": return "Entire Virtual Desktop (All Monitors)"
case "CurrentMonitor": return "Current Monitor"
case "ActiveWindow": return "Active Window"
case "SpecificWindow":
desc := this.WinExe != "" ? this.WinExe : (this.WinTitle != "" ? this.WinTitle : this.WinClass)
return "Window: " (desc != "" ? desc : "(Unspecified)")
case "WindowClientArea": return "Window Client Area" (this.WinExe != "" ? " (" this.WinExe ")" : "")
case "UIAContainer": return "Container: " (this.ContainerName != "" ? this.ContainerName : this.ContainerType)
case "BrowserSession": return "Browser Session: " (this.BrowserSession != "" ? this.BrowserSession : "Default")
case "BrowserWindow": return "Browser Window" (this.BrowserSession != "" ? " (" this.BrowserSession ")" : "")
case "CurrentBrowserTab": return "Current Browser Tab" (this.BrowserSession != "" ? " (" this.BrowserSession ")" : "")
case "BrowserDocument": return "Web Page Document" (this.BrowserSession != "" ? " (" this.BrowserSession ")" : "")
case "BrowserFrame": return "Web Frame: " (this.FrameName != "" ? this.FrameName : "Embedded Frame")
case "Region":
return Format("Region ({1}, {2}, {3}×{4}){5}", this.RegionX, this.RegionY, this.RegionW, this.RegionH, this.RelativeToWindow ? " [Window-Relative]" : " [Screen]")
default: return this.ScopeType
}
}
ToMap() {
return Map(
"ScopeType", this.ScopeType,
"WinTitle", this.WinTitle,
"WinClass", this.WinClass,
"WinExe", this.WinExe,
"ContainerName", this.ContainerName,
"ContainerType", this.ContainerType,
"ContainerAutomationId", this.ContainerAutomationId,
"BrowserSession", this.BrowserSession,
"FrameName", this.FrameName,
"RegionX", this.RegionX,
"RegionY", this.RegionY,
"RegionW", this.RegionW,
"RegionH", this.RegionH,
"RelativeToWindow", this.RelativeToWindow ? JsonCodec.TrueVal : JsonCodec.FalseVal
)
}
static FromMap(m) {
s := ScopeModel()
if !(m is Map)
return s
if m.Has("ScopeType")
s.ScopeType := String(m["ScopeType"])
if m.Has("WinTitle")
s.WinTitle := String(m["WinTitle"])
if m.Has("WinClass")
s.WinClass := String(m["WinClass"])
if m.Has("WinExe")
s.WinExe := String(m["WinExe"])
if m.Has("ContainerName")
s.ContainerName := String(m["ContainerName"])
if m.Has("ContainerType")
s.ContainerType := String(m["ContainerType"])
if m.Has("ContainerAutomationId")
s.ContainerAutomationId := String(m["ContainerAutomationId"])
if m.Has("BrowserSession")
s.BrowserSession := String(m["BrowserSession"])
if m.Has("FrameName")
s.FrameName := String(m["FrameName"])
if m.Has("RegionX")
s.RegionX := Integer(m["RegionX"])
if m.Has("RegionY")
s.RegionY := Integer(m["RegionY"])
if m.Has("RegionW")
s.RegionW := Integer(m["RegionW"])
if m.Has("RegionH")
s.RegionH := Integer(m["RegionH"])
if m.Has("RelativeToWindow")
s.RelativeToWindow := StudioUtils.ToBool(m["RelativeToWindow"])
return s
}
Clone() => ScopeModel.FromMap(JsonCodec.Load(JsonCodec.Dump(this.ToMap(), "")))
}
class AnchorModel {
Enabled := false
Relationship := "Nearest" ; Nearest, RightOf, LeftOf, Above, Below, SameContainer
AnchorName := ""
AnchorRole := "Text"
AnchorControlType := "Text"
AnchorAutomationId := ""
MaxDistance := 450
GetFriendlyText() {
if !this.Enabled || (this.AnchorName == "" && this.AnchorAutomationId == "")
return "None"
lbl := this.AnchorName != "" ? '"' this.AnchorName '"' : this.AnchorAutomationId
return this.Relationship " " this.AnchorRole " " lbl
}
ToMap() {
return Map(
"Enabled", this.Enabled ? JsonCodec.TrueVal : JsonCodec.FalseVal,
"Relationship", this.Relationship,
"AnchorName", this.AnchorName,
"AnchorRole", this.AnchorRole,
"AnchorControlType", this.AnchorControlType,
"AnchorAutomationId", this.AnchorAutomationId,
"MaxDistance", this.MaxDistance
)
}
static FromMap(m) {
a := AnchorModel()
if !(m is Map)
return a
if m.Has("Enabled")
a.Enabled := StudioUtils.ToBool(m["Enabled"])
if m.Has("Relationship")
a.Relationship := String(m["Relationship"])
if m.Has("AnchorName")
a.AnchorName := String(m["AnchorName"])
if m.Has("AnchorRole")
a.AnchorRole := String(m["AnchorRole"])
if m.Has("AnchorControlType")
a.AnchorControlType := String(m["AnchorControlType"])
if m.Has("AnchorAutomationId")
a.AnchorAutomationId := String(m["AnchorAutomationId"])
if m.Has("MaxDistance")
a.MaxDistance := Integer(m["MaxDistance"])
return a
}
Clone() => AnchorModel.FromMap(JsonCodec.Load(JsonCodec.Dump(this.ToMap(), "")))
}
class SelectorStrategy {
Id := ""
Name := "Primary UIA"
StrategyType := "UIA_Primary" ; UIA_Primary, UIA_Alternate, AnchorRelative, BrowserCSS, ImageMatch, PixelMatch, WindowRelativeCoord, ScreenCoord
Enabled := true
AutomationId := ""
ElementName := ""
ControlType := ""
ClassName := ""
FrameworkId := ""
Value := ""
MatchMode := "Exact" ; Exact, Substring, StartsWith, Regex
CaseSensitive := false
ParentName := ""
ParentType := ""
AncestorName := ""
AncestorType := ""
TreePath := ""
CSSSelector := ""
Index := 1
LastTestStatus := "Untested"
LastMatchCount := -1
__New(name := "Primary UIA", strategyType := "UIA_Primary") {
this.Id := StudioUtils.GenId("sel")
this.Name := name
this.StrategyType := strategyType
}
GetFindUsingSummary() {
switch this.StrategyType {
case "UIA_Primary", "UIA_Alternate":
parts := []
if this.AutomationId != "" && !TargetModel.IsVolatileAutomationId(this.AutomationId)
parts.Push("AutomationId")
if this.ElementName != ""
parts.Push("Name")
if this.ControlType != ""
parts.Push("Type")
if this.ClassName != "" && parts.Length < 2
parts.Push("Class")
if this.ParentName != "" || this.ParentType != ""
parts.Push("Parent")
if parts.Length == 0
return "UIA Tree / Index"
out := ""
for i, p in parts
out .= (i > 1 ? " + " : "") . p
return out
case "AnchorRelative":
return "Anchor + Type"
case "BrowserCSS":
return "CSS (" this.CSSSelector ")"
case "ImageMatch":
return "Visual Image Match"
case "PixelMatch":
return "Pixel Color Match"
case "WindowRelativeCoord":
return "Window-Relative Point"
case "ScreenCoord":
return "Absolute Screen Point"
default:
return this.StrategyType
}
}
ToMap() {
return Map(
"Id", this.Id,
"Name", this.Name,
"StrategyType", this.StrategyType,
"Enabled", this.Enabled ? JsonCodec.TrueVal : JsonCodec.FalseVal,
"AutomationId", this.AutomationId,
"ElementName", this.ElementName,
"ControlType", this.ControlType,
"ClassName", this.ClassName,
"FrameworkId", this.FrameworkId,
"Value", this.Value,
"MatchMode", this.MatchMode,
"CaseSensitive", this.CaseSensitive ? JsonCodec.TrueVal : JsonCodec.FalseVal,
"ParentName", this.ParentName,
"ParentType", this.ParentType,
"AncestorName", this.AncestorName,
"AncestorType", this.AncestorType,
"TreePath", this.TreePath,
"CSSSelector", this.CSSSelector,
"Index", this.Index
)
}
static FromMap(m) {
s := SelectorStrategy()
if !(m is Map)
return s
for k, v in m {
if k == "Enabled" || k == "CaseSensitive"
s.%k% := StudioUtils.ToBool(v)
else if k == "Index"
s.Index := Integer(v)
else if s.HasOwnProp(k)
s.%k% := String(v)
}
return s
}
Clone() => SelectorStrategy.FromMap(JsonCodec.Load(JsonCodec.Dump(this.ToMap(), "")))
}
class TargetModel {
BackupTargets := []
BackupEnabled := true
ManualBackups := false
Id := ""
Name := ""
Role := "Button" ; Button, Textbox, Checkbox, Text, Tab, Window, Page, MenuItem, ListItem, ComboBox, Link, Pane, Region, Image, Color, Coordinate
TargetKind := "UIA" ; UIA, BrowserUIA, BrowserJS, Image, PixelColor, Region, WindowRelative, ScreenCoordinate, Window
IsReusable := false
ReusableTargetId := ""
PrimarySelector := ""
AlternateSelectors := []
Anchor := ""
Scope := ""
FallbackPreset := "Balanced" ; Balanced | Resilient | StrictSemantic | LegacyRecorded | Custom
AllowedFallbacks := ["UIA_Primary", "UIA_Alternate", "AnchorRelative", "ImageMatch", "WindowRelativeCoord"]
; Visual / Coordinate / Window properties
CapturedImageBase64 := ""
CapturedImagePath := ""
ImageVariation := 25
TransColor := ""
CapturedColorHex := "0x0078D4"
ColorTolerance := 10
ScreenX := 0
ScreenY := 0
WinRelX := 0
WinRelY := 0
ClientX := 0
ClientY := 0
OffsetX := 0
OffsetY := 0
BoundingW := 0
BoundingH := 0
WinTitle := ""
WinClass := ""
WinExe := ""
WinHwnd := 0
; Browser Context Metadata
IsWebContent := false ; True = WEB page element, False = Desktop or BROWSER UI chrome
IsBrowserChromeUI := false
BrowserType := "" ; Chrome, Edge, Firefox, Brave, Vivaldi
ProfileAlias := ""
SessionName := ""
PageTitle := ""
PageUrl := ""
FrameName := ""
SupportedPatterns := []
; Reliability, Health & Testing State (vNext Sections 32-35, 93-95)
ReliabilityRating := "Strong"
ReliabilityReason := "Uses stable semantic UIA attributes."
HealthStatus := "Untested" ; Healthy | Untested | Ambiguous | Fallback Used | Needs Repair | Broken
LastMatchCount := 1
LastTestStatus := "Untested"
LastResolvedStrategy := ""
LastSuccessCount := 0
LastFallbackCount := 0
LastFailureCount := 0
__New(name := "", role := "Button", kind := "UIA") {
this.Id := StudioUtils.GenId("tgt")
this.Name := name
this.Role := role
this.TargetKind := kind
this.PrimarySelector := SelectorStrategy("Primary UIA", "UIA_Primary")
this.AlternateSelectors := []
this.Anchor := AnchorModel()
this.Scope := ScopeModel("ActiveWindow")
this.ComputeReliability()
}
static MetricsOn := false ; [NMS-PC-02a] per-run target-resolution counters (summary is logged when a macro ends)
static MetricsData := Map()
static MetricsStart() {
TargetModel.MetricsOn := true
TargetModel.MetricsData := Map("Unique", 0, "Fallback", 0, "Coordinate", 0, "Ambiguous", 0, "NotFound", 0)
}
static MetricsStop() {
TargetModel.MetricsOn := false
return TargetModel.MetricsData
}
static MetricsNote(ok, strategyUsed, matchCount) {
if !TargetModel.MetricsOn
return
key := "NotFound"
if ok {
if IsNumber(matchCount) && matchCount > 1
key := "Ambiguous"
else if strategyUsed == "ScreenCoord" || strategyUsed == "WindowRelativeCoord"
key := "Coordinate"
else if strategyUsed != "" && strategyUsed != "UIA_Primary"
key := "Fallback"
else
key := "Unique"
}
TargetModel.MetricsData[key] += 1
}
static MetricsText(d) {
if !(d is Map)
return ""
total := 0
for _, v in d
total += v
if total = 0
return ""
return "Target lookups: " total " (unique " d["Unique"] ", fallback " d["Fallback"] ", coordinate-only " d["Coordinate"] ", AMBIGUOUS " d["Ambiguous"] ", not found " d["NotFound"] ")"
}
static IsVolatileAutomationId(aid) {
if aid == ""
return false
if RegExMatch(aid, "^\d+$")
return true
if RegExMatch(aid, "i)^[0-9a-f]{8}-[0-9a-f]{4}-")
return true
if RegExMatch(aid, "i)(^ember\d+|^react-|^:r[0-9a-z]+:|^mui-\d+|^uid_|^id_\d{4,}|_[0-9a-f]{6,}$)")
return true
return false
}
ApplyFallbackPreset(presetName) {
this.FallbackPreset := presetName
switch presetName {
case StudioConstants.PresetStrictSemantic:
this.AllowedFallbacks := ["UIA_Primary", "UIA_Alternate", "AnchorRelative"]
case StudioConstants.PresetBalanced:
this.AllowedFallbacks := ["UIA_Primary", "UIA_Alternate", "AnchorRelative", "ImageMatch"]
case StudioConstants.PresetResilient:
this.AllowedFallbacks := ["UIA_Primary", "UIA_Alternate", "AnchorRelative", "BrowserCSS", "ImageMatch", "WindowRelativeCoord"]
case StudioConstants.PresetLegacyRecorded:
this.AllowedFallbacks := ["UIA_Primary", "UIA_Alternate", "AnchorRelative", "ImageMatch", "WindowRelativeCoord", "ScreenCoord"]
}
this.EnsureDefaultAlternates()
for strategy in this.AlternateSelectors
strategy.Enabled := this.AllowsStrategy(strategy.StrategyType)
}
RecordOutcome(ok, strategyUsed := "UIA_Primary", matchCount := 1) {
this.LastMatchCount := matchCount
this.LastResolvedStrategy := strategyUsed
try TargetModel.MetricsNote(ok, strategyUsed, matchCount) ; [NMS-PC-02b]
if !ok {
this.LastFailureCount += 1
this.LastTestStatus := "Not Found"
this.HealthStatus := StudioConstants.HealthBroken
} else {
this.LastSuccessCount += 1
if matchCount > 1 && strategyUsed == "UIA_Primary" {
this.LastTestStatus := "Ambiguous (" matchCount " matches)"
this.HealthStatus := StudioConstants.HealthAmbiguous
} else if strategyUsed != "UIA_Primary" && strategyUsed != "" {
this.LastFallbackCount += 1
this.LastTestStatus := "Fallback (" strategyUsed ")"
this.HealthStatus := (this.LastFallbackCount >= 3) ? StudioConstants.HealthNeedsRepair : StudioConstants.HealthFallbackUsed
} else {
this.LastTestStatus := "Matched 1 element"
this.HealthStatus := StudioConstants.HealthHealthy
}
}
this.ComputeReliability()
return this.HealthStatus
}
CopyTargetingTo(destTarget) {
if !IsObject(destTarget)
return
cloned := this.Clone()
destTarget.Name := cloned.Name
destTarget.Role := cloned.Role
destTarget.TargetKind := cloned.TargetKind
destTarget.PrimarySelector := cloned.PrimarySelector
destTarget.BackupTargets := cloned.BackupTargets
destTarget.ManualBackups := cloned.ManualBackups
destTarget.AlternateSelectors := cloned.AlternateSelectors
destTarget.Anchor := cloned.Anchor
destTarget.Scope := cloned.Scope
destTarget.FallbackPreset := cloned.FallbackPreset
destTarget.AllowedFallbacks := cloned.AllowedFallbacks
destTarget.CapturedImageBase64 := cloned.CapturedImageBase64
destTarget.CapturedImagePath := cloned.CapturedImagePath
destTarget.ImageVariation := cloned.ImageVariation
destTarget.CapturedColorHex := cloned.CapturedColorHex
destTarget.ColorTolerance := cloned.ColorTolerance
destTarget.ScreenX := cloned.ScreenX
destTarget.ScreenY := cloned.ScreenY
destTarget.WinRelX := cloned.WinRelX
destTarget.WinRelY := cloned.WinRelY
destTarget.WinTitle := cloned.WinTitle
destTarget.WinClass := cloned.WinClass
destTarget.WinExe := cloned.WinExe
destTarget.IsWebContent := cloned.IsWebContent
destTarget.IsBrowserChromeUI := cloned.IsBrowserChromeUI
destTarget.BrowserType := cloned.BrowserType
destTarget.ProfileAlias := cloned.ProfileAlias
destTarget.SessionName := cloned.SessionName
destTarget.PageTitle := cloned.PageTitle
destTarget.PageUrl := cloned.PageUrl
for field in ["BackupEnabled", "TransColor", "ClientX", "ClientY", "OffsetX", "OffsetY", "BoundingW", "BoundingH", "FrameName", "SupportedPatterns"]
destTarget.%field% := cloned.%field%
destTarget.WinHwnd := this.WinHwnd
destTarget.ComputeReliability()
}
; Human-friendly target representation (Section 23: "Button — Submit")
GetHumanLabel() {
switch this.TargetKind {
case "ScreenCoordinate":
return Format("Coordinate ({1}, {2})", this.ScreenX, this.ScreenY)
case "WindowRelative":
return Format("Window Point ({1}, {2}) in {3}", this.WinRelX, this.WinRelY, this.WinExe != "" ? this.WinExe : "Window")
case "Image":
return "Image — " (this.Name != "" ? this.Name : "Captured Region")
case "PixelColor":
return "Color — " this.CapturedColorHex
case "Region":
return Format("Region ({1}×{2})", this.Scope.RegionW, this.Scope.RegionH)
case "Window":
return "Window — " (this.Name != "" ? this.Name : (this.WinTitle != "" ? this.WinTitle : this.WinExe))
default:
cleanName := Trim(this.Name)
if StrLen(cleanName) > 42
cleanName := SubStr(cleanName, 1, 39) "..."
return this.Role . (cleanName != "" ? " — " cleanName : "")
}
}
; Breadcrumb for Target Card "Within" (Section 25: "Edge → Work → Orders → Checkout")
GetWithinBreadcrumb() {
parts := []
if this.BrowserType != "" {
parts.Push(this.BrowserType)
if this.ProfileAlias != ""
parts.Push(this.ProfileAlias)
if this.SessionName != "" && this.SessionName != this.ProfileAlias
parts.Push(this.SessionName)
if this.PageTitle != "" {
t := RegExReplace(this.PageTitle, "\s*[-—]\s*(Microsoft\s+Edge|Google\s+Chrome|Mozilla\s+Firefox|Brave|Vivaldi).*$", "")
if StrLen(t) > 28
t := SubStr(t, 1, 25) "..."
if t != ""
parts.Push(t)
}
if this.FrameName != ""
parts.Push(this.FrameName)
} else {
if this.WinExe != ""
parts.Push(this.WinExe)
if this.WinTitle != "" {
wt := this.WinTitle
if StrLen(wt) > 32
wt := SubStr(wt, 1, 29) "..."
parts.Push(wt)
}
if this.PrimarySelector.ParentName != ""
parts.Push(this.PrimarySelector.ParentName)
}
if parts.Length == 0
return this.Scope.GetFriendlyText()
out := ""
for i, p in parts
out .= (i > 1 ? " → " : "") . p
return out
}
GetMethodLabel() {
switch this.TargetKind {
case "UIA": return "UI Automation"
case "BrowserUIA": return "Browser UI Automation"
case "BrowserJS": return "Browser CSS / JavaScript"
case "Image": return "Image Recognition"
case "PixelColor": return "Pixel / Color Match"
case "Region": return "Bounded Region"
case "WindowRelative": return "Window-Relative Coordinate"
case "ScreenCoordinate": return "Absolute Screen Coordinate"
case "Window": return "Window Handle / Criteria"
default: return this.TargetKind
}
}
ComputeReliability() {
if this.TargetKind == "ScreenCoordinate" {
this.ReliabilityRating := StudioConstants.RelVeryFragile
this.ReliabilityReason := "Very Fragile — depends on exact monitor resolution and window position."
return this.ReliabilityRating
}
if this.TargetKind == "WindowRelative" {
this.ReliabilityRating := StudioConstants.RelFragile
this.ReliabilityReason := "Fragile — depends on the window layout and size remaining unchanged."
return this.ReliabilityRating
}
if this.TargetKind == "Image" || this.TargetKind == "PixelColor" {
this.ReliabilityRating := StudioConstants.RelVisual
this.ReliabilityReason := "Visual — depends on on-screen rendering, theme, and DPI scaling."
return this.ReliabilityRating
}
if this.TargetKind == "Region" || this.TargetKind == "Window" {
this.ReliabilityRating := StudioConstants.RelGood
this.ReliabilityReason := "Good — scoped to application window criteria."
return this.ReliabilityRating
}
if this.TargetKind == "BrowserJS" {
if this.PrimarySelector.CSSSelector != "" && (InStr(this.PrimarySelector.CSSSelector, "#") || InStr(this.PrimarySelector.CSSSelector, "[")) {
this.ReliabilityRating := StudioConstants.RelStrong
this.ReliabilityReason := "Strong — uses explicit semantic CSS attribute/ID selector."
} else {
this.ReliabilityRating := StudioConstants.RelGood
this.ReliabilityReason := "Good — uses structural CSS selector."
}
return this.ReliabilityRating
}
; UIA or BrowserUIA
aid := this.PrimarySelector.AutomationId
isVolatileAid := TargetModel.IsVolatileAutomationId(aid)
hasStableAid := aid != "" && !isVolatileAid
hasName := this.PrimarySelector.ElementName != ""
hasType := this.PrimarySelector.ControlType != ""
if this.Anchor.Enabled {
this.ReliabilityRating := StudioConstants.RelStrong
this.ReliabilityReason := "Strong (Anchored) — locates target relative to anchor (" this.Anchor.GetFriendlyText() ")."
} else if hasStableAid && hasType {
this.ReliabilityRating := StudioConstants.RelStrong
this.ReliabilityReason := "Strong — uses stable AutomationId and ControlType."
} else if hasName && hasType {
if StrLen(this.PrimarySelector.ElementName) <= 60 {
this.ReliabilityRating := StudioConstants.RelStrong
this.ReliabilityReason := "Strong — uses human-readable Name and ControlType."
} else {
this.ReliabilityRating := StudioConstants.RelGood
this.ReliabilityReason := "Good — uses ControlType and long text Name that may vary."
}
} else if isVolatileAid && !hasName {
this.ReliabilityRating := StudioConstants.RelContextual
this.ReliabilityReason := "Contextual — AutomationId ('" aid "') appears dynamically generated; prefer Name or Anchor."
} else if hasType && (this.PrimarySelector.ParentName != "" || this.PrimarySelector.ClassName != "") {
this.ReliabilityRating := StudioConstants.RelContextual
this.ReliabilityReason := "Contextual — relies on parent container or class relationship."
} else {
this.ReliabilityRating := StudioConstants.RelContextual
this.ReliabilityReason := "Contextual — lacks unique Name or AutomationId; consider adding an Anchor or Fallback."
}
if this.LastMatchCount > 1 && this.ReliabilityRating == StudioConstants.RelStrong && !this.Anchor.Enabled {
this.ReliabilityRating := StudioConstants.RelGood
this.ReliabilityReason .= " [Ambiguous: " this.LastMatchCount " matches found — add Anchor or Scope]"
}
return this.ReliabilityRating
}
EnsureDefaultAlternates() {
if this.ManualBackups
return
existing := this.AlternateSelectors
this.AlternateSelectors := []
; Alternate 1: Name + ControlType + Parent
if this.PrimarySelector.ElementName != "" || this.PrimarySelector.ParentName != "" {
alt1 := SelectorStrategy("Alternate UIA (Name + Parent)", "UIA_Alternate")
alt1.ElementName := this.PrimarySelector.ElementName
alt1.ControlType := this.PrimarySelector.ControlType
alt1.ParentName := this.PrimarySelector.ParentName
alt1.ParentType := this.PrimarySelector.ParentType
alt1.MatchMode := "Exact"
alt1.ClassName := this.PrimarySelector.ClassName
alt1.FrameworkId := this.PrimarySelector.FrameworkId
alt1.AutomationId := TargetModel.IsVolatileAutomationId(this.PrimarySelector.AutomationId) ? "" : this.PrimarySelector.AutomationId
this.AlternateSelectors.Push(alt1)
}
; Alternate 2: Anchor if enabled
if this.Anchor.Enabled {
altAnchor := SelectorStrategy("Anchor Relative (" this.Anchor.GetFriendlyText() ")", "AnchorRelative")
altAnchor.ControlType := this.PrimarySelector.ControlType
this.AlternateSelectors.Push(altAnchor)
}
; Fallback: Image if captured
if this.CapturedImageBase64 != "" || this.CapturedImagePath != "" {
altImg := SelectorStrategy("Visual Image Fallback", "ImageMatch")
this.AlternateSelectors.Push(altImg)
}
; Fallback: Window-relative coordinate if valid
if this.WinRelX != 0 || this.WinRelY != 0 {
altCoord := SelectorStrategy(Format("Window-Relative ({1}, {2})", this.WinRelX, this.WinRelY), "WindowRelativeCoord")
altCoord.Enabled := (this.FallbackPreset == StudioConstants.PresetResilient || this.FallbackPreset == StudioConstants.PresetLegacyRecorded)
this.AlternateSelectors.Push(altCoord)
}
generated := this.AlternateSelectors
this.AlternateSelectors := existing
for candidate in generated {
present := false
for prior in existing
if prior.StrategyType == candidate.StrategyType
present := true
if !present
this.AlternateSelectors.Push(candidate)
}
}
AllowsStrategy(type) {
for allowed in this.AllowedFallbacks
if allowed == type
return true
return false
}
ToMap() {
backups := []
for backup in this.BackupTargets
backups.Push(backup.ToMap())
alts := []
for _, a in this.AlternateSelectors
alts.Push(a.ToMap())
return Map(
"Id", this.Id,
"Name", this.Name,
"Role", this.Role,
"TargetKind", this.TargetKind,
"IsReusable", this.IsReusable ? JsonCodec.TrueVal : JsonCodec.FalseVal,
"ReusableTargetId", this.ReusableTargetId,
"PrimarySelector", this.PrimarySelector.ToMap(),
"AlternateSelectors", alts,
"BackupTargets", backups,
"BackupEnabled", this.BackupEnabled ? JsonCodec.TrueVal : JsonCodec.FalseVal,
"ManualBackups", this.ManualBackups ? JsonCodec.TrueVal : JsonCodec.FalseVal,
"Anchor", this.Anchor.ToMap(),
"Scope", this.Scope.ToMap(),
"FallbackPreset", this.FallbackPreset,
"AllowedFallbacks", this.AllowedFallbacks,
"CapturedImageBase64", this.CapturedImageBase64,
"CapturedImagePath", this.CapturedImagePath,
"ImageVariation", this.ImageVariation,
"TransColor", this.TransColor,
"CapturedColorHex", this.CapturedColorHex,
"ColorTolerance", this.ColorTolerance,
"ScreenX", this.ScreenX,
"ScreenY", this.ScreenY,
"WinRelX", this.WinRelX,
"WinRelY", this.WinRelY,
"ClientX", this.ClientX,
"ClientY", this.ClientY,
"OffsetX", this.OffsetX,
"OffsetY", this.OffsetY,
"BoundingW", this.BoundingW,
"BoundingH", this.BoundingH,
"WinTitle", this.WinTitle,
"WinClass", this.WinClass,
"WinExe", this.WinExe,
"IsWebContent", this.IsWebContent ? JsonCodec.TrueVal : JsonCodec.FalseVal,
"IsBrowserChromeUI", this.IsBrowserChromeUI ? JsonCodec.TrueVal : JsonCodec.FalseVal,
"BrowserType", this.BrowserType,
"ProfileAlias", this.ProfileAlias,
"SessionName", this.SessionName,
"PageTitle", this.PageTitle,
"PageUrl", this.PageUrl,
"FrameName", this.FrameName,
"SupportedPatterns", this.SupportedPatterns,
"ReliabilityRating", this.ReliabilityRating,
"ReliabilityReason", this.ReliabilityReason,
"HealthStatus", this.HealthStatus,
"LastMatchCount", this.LastMatchCount,
"LastTestStatus", this.LastTestStatus,
"LastResolvedStrategy", this.LastResolvedStrategy,
"LastSuccessCount", this.LastSuccessCount,
"LastFallbackCount", this.LastFallbackCount,
"LastFailureCount", this.LastFailureCount
)
}
static FromMap(m) {
t := TargetModel()
if !(m is Map)
return t
strProps := ["Id", "Name", "Role", "TargetKind", "ReusableTargetId", "FallbackPreset", "CapturedImageBase64", "CapturedImagePath", "TransColor", "CapturedColorHex", "WinTitle", "WinClass", "WinExe", "BrowserType", "ProfileAlias", "SessionName", "PageTitle", "PageUrl", "FrameName", "ReliabilityRating", "ReliabilityReason", "HealthStatus", "LastTestStatus", "LastResolvedStrategy"]
for _, p in strProps {
if m.Has(p)
t.%p% := String(m[p])
}
intProps := ["ImageVariation", "ColorTolerance", "ScreenX", "ScreenY", "WinRelX", "WinRelY", "ClientX", "ClientY", "OffsetX", "OffsetY", "BoundingW", "BoundingH", "LastMatchCount", "LastSuccessCount", "LastFallbackCount", "LastFailureCount"]
for _, p in intProps {
if m.Has(p)
t.%p% := Integer(m[p])
}
boolProps := ["IsReusable", "IsWebContent", "IsBrowserChromeUI"]
for _, p in boolProps {
if m.Has(p)
t.%p% := StudioUtils.ToBool(m[p])
}
if m.Has("PrimarySelector") && (m["PrimarySelector"] is Map)
t.PrimarySelector := SelectorStrategy.FromMap(m["PrimarySelector"])
t.BackupEnabled := StudioUtils.ToBool(m.Get("BackupEnabled",true))
t.ManualBackups := StudioUtils.ToBool(m.Get("ManualBackups",false))
if m.Has("BackupTargets") && m["BackupTargets"] is Array {
for item in m["BackupTargets"] {
if !(item is Map)
continue
flat := StudioUtils.CloneMap(item)
if flat.Has("BackupTargets")
flat.Delete("BackupTargets")
t.BackupTargets.Push(TargetModel.FromMap(flat))
}
}
if m.Has("AlternateSelectors") && (m["AlternateSelectors"] is Array) {
t.AlternateSelectors := []
for _, am in m["AlternateSelectors"]
t.AlternateSelectors.Push(SelectorStrategy.FromMap(am))
}
if m.Has("Anchor") && (m["Anchor"] is Map)
t.Anchor := AnchorModel.FromMap(m["Anchor"])
if m.Has("Scope") && (m["Scope"] is Map)
t.Scope := ScopeModel.FromMap(m["Scope"])
if m.Has("AllowedFallbacks") && (m["AllowedFallbacks"] is Array)
t.AllowedFallbacks := StudioUtils.CloneArray(m["AllowedFallbacks"])
if m.Has("SupportedPatterns") && (m["SupportedPatterns"] is Array)
t.SupportedPatterns := StudioUtils.CloneArray(m["SupportedPatterns"])
t.ComputeReliability()
return t
}
Clone() => TargetModel.FromMap(JsonCodec.Load(JsonCodec.Dump(this.ToMap(), "")))
}
class ActionResultModel {
FailureReason := "" ; Structured transient diagnostics; never inferred from display text.
Success := true
Status := "Passed" ; Passed, Failed, Skipped, Stopped
Message := ""
DurationMs := 0
Outputs := Map()
StrategyUsed := ""
BrowserSessionUsed := ""
ProfileUsed := ""
FallbackNotice := ""
RetryCount := 0
ExceptionText := ""
DiagnosticsText := ""
__New(success := true, status := "Passed", message := "") {
this.Success := success
this.Status := status
this.Message := message
this.Outputs := Map()
}
}
class ActionModel {
Label := ""
Id := ""
Enabled := true
Type := "UIA_Click"
Category := "UI Automation"
FriendlyDescription := ""
Parameters := Map()
Target := "" ; TargetModel instance
ReusableTargetId := ""
Scope := "" ; ScopeModel instance
; Browser Context
BrowserSession := ""
BrowserType := ""
BrowserProfile := ""
BrowserFallbackPolicy := "" ; Inherit, Strict, PreferConfiguredThenCurrent, PreferConfiguredThenDefault, CurrentBrowser, DefaultProfile, AnyCompatibleSession, AskWhenAmbiguous, CustomOrder
; Timing / Retry / Actionability / Post-Action Expectation / Failure Policy (vNext Sections 58-64)
WaitMode := "Auto" ; Auto, None, TargetReady, PageLoad, Custom
TimeoutMs := 8000
RetryCount := 1
PollingIntervalMs := 200
BackoffStrategy := "Fixed" ; Fixed, Linear, Exponential
DelayBeforeMs := 0
DelayAfterMs := 100
RequireVisible := true
RequireEnabled := false
SettleTimeMs := 0 ; Optional stability check before acting
ExpectOutcome := "None" ; None | ElementAppears | ElementDisappears | URLContains | TitleContains | TextAppears | NewTabOpened
ExpectValue := ""
ExpectTimeoutMs := 5000
OnFailure := "Stop" ; Stop, Skip, Continue, UseFallback, AskRepair
; Debugging & Recording Metadata
Breakpoint := false
Notes := ""
RuntimeStatus := ""
RecordingMeta := Map()
; Structural AST Children (for If, Repeat, While, TryCatch)
Children := []
ElseChildren := []
HasElse := false
IsCollapsed := false
__New(actionType := "UIA_Click", friendlyDesc := "") {
this.Id := StudioUtils.GenId("act")
this.Type := actionType
this.Category := ActionRegistry.GetCategoryForType(actionType)
this.Parameters := ActionRegistry.GetDefaultParams(actionType)
this.Target := TargetModel()
this.Scope := ScopeModel()
this.RecordingMeta := Map()
this.Children := []
this.ElseChildren := []
this.FriendlyDescription := friendlyDesc != "" ? friendlyDesc : this.ComputeFriendlyDescription()
}
IsContainerAction() {
return this.Type == "Logic_If" || this.Type == "Logic_Repeat" || this.Type == "Logic_ForEach" || this.Type == "Logic_While" || this.Type == "Logic_TryCatch"
}
ComputeFriendlyDescription() {
return ActionRegistry.FormatDescription(this)
}
GetBadgesText() {
badges := []
if this.Target != "" {
if this.Target.IsWebContent || InStr(this.Type, "Browser_") == 1
badges.Push("WEB")
else if this.Target.IsBrowserChromeUI
badges.Push("BROWSER")
}
prof := this.BrowserProfile != "" ? this.BrowserProfile : (this.Target != "" ? this.Target.ProfileAlias : "")
sess := this.BrowserSession != "" ? this.BrowserSession : (this.Target != "" ? this.Target.SessionName : "")
if prof != ""
badges.Push(prof)
else if sess != ""
badges.Push(sess)
if ActionRegistry.UsesTarget(this.Type) && this.Target != "" {
badges.Push(this.Target.ReliabilityRating)
if this.Target.HealthStatus != "" && this.Target.HealthStatus != "Untested" && this.Target.HealthStatus != "Healthy"
badges.Push(this.Target.HealthStatus)
}
if this.ExpectOutcome != "" && this.ExpectOutcome != "None"
badges.Push("Expect:" this.ExpectOutcome)
if this.RecordingMeta.Has("UpgradeAvailable") && this.RecordingMeta["UpgradeAvailable"]
badges.Push("Upgrade")
if this.Breakpoint
badges.Push("● BP")
if !this.Enabled
badges.Push("Disabled")
out := ""
for i, b in badges
out .= (i > 1 ? " · " : "") . b
return out
}
ToMap() {
childMaps := []
for _, ch in this.Children
childMaps.Push(ch.ToMap())
elseMaps := []
for _, ech in this.ElseChildren
elseMaps.Push(ech.ToMap())
return Map(
"Id", this.Id,
"Enabled", this.Enabled ? JsonCodec.TrueVal : JsonCodec.FalseVal,
"Type", this.Type,
"Category", this.Category,
"FriendlyDescription", this.FriendlyDescription,
"Label", this.Label,
"Parameters", this.Parameters,
"Target", IsObject(this.Target) ? this.Target.ToMap() : Map(),
"ReusableTargetId", this.ReusableTargetId,
"Scope", IsObject(this.Scope) ? this.Scope.ToMap() : Map(),
"BrowserSession", this.BrowserSession,
"BrowserType", this.BrowserType,
"BrowserProfile", this.BrowserProfile,
"BrowserFallbackPolicy", this.BrowserFallbackPolicy,
"WaitMode", this.WaitMode,
"TimeoutMs", this.TimeoutMs,
"RetryCount", this.RetryCount,
"PollingIntervalMs", this.PollingIntervalMs,
"BackoffStrategy", this.BackoffStrategy,
"DelayBeforeMs", this.DelayBeforeMs,
"DelayAfterMs", this.DelayAfterMs,
"RequireVisible", this.RequireVisible ? JsonCodec.TrueVal : JsonCodec.FalseVal,
"RequireEnabled", this.RequireEnabled ? JsonCodec.TrueVal : JsonCodec.FalseVal,
"SettleTimeMs", this.SettleTimeMs,
"ExpectOutcome", this.ExpectOutcome,
"ExpectValue", this.ExpectValue,
"ExpectTimeoutMs", this.ExpectTimeoutMs,
"OnFailure", this.OnFailure,
"Breakpoint", this.Breakpoint ? JsonCodec.TrueVal : JsonCodec.FalseVal,
"Notes", this.Notes,
"RecordingMeta", this.RecordingMeta,
"Children", childMaps,
"ElseChildren", elseMaps,
"HasElse", this.HasElse ? JsonCodec.TrueVal : JsonCodec.FalseVal,
"IsCollapsed", this.IsCollapsed ? JsonCodec.TrueVal : JsonCodec.FalseVal
)
}
static FromMap(m) {
if !(m is Map)
throw ValueError("Each action must be an object.")
for key in ["Children", "ElseChildren"]
if m.Has(key) && !(m[key] is Array)
throw ValueError("Action " key " must be an array.")
if m.Has("Parameters") && !(m["Parameters"] is Map)
throw ValueError("Action Parameters must be an object.")
a := ActionModel(m.Get("Type", "UIA_Click"))
strProps := ["Id", "Type", "Category", "FriendlyDescription", "Label", "ReusableTargetId", "BrowserSession", "BrowserType", "BrowserProfile", "BrowserFallbackPolicy", "WaitMode", "BackoffStrategy", "ExpectOutcome", "ExpectValue", "OnFailure", "Notes"]
for _, p in strProps {
if m.Has(p)
a.%p% := String(m[p])
}
intProps := ["TimeoutMs", "RetryCount", "PollingIntervalMs", "DelayBeforeMs", "DelayAfterMs", "SettleTimeMs", "ExpectTimeoutMs"]
for _, p in intProps {
if m.Has(p)
a.%p% := Integer(m[p])
}
boolProps := ["Enabled", "Breakpoint", "HasElse", "IsCollapsed", "RequireVisible", "RequireEnabled"]
for _, p in boolProps {
if m.Has(p)
a.%p% := StudioUtils.ToBool(m[p])
}
if m.Has("Parameters") && (m["Parameters"] is Map)
a.Parameters := StudioUtils.CloneMap(m["Parameters"])
if m.Has("Target") && (m["Target"] is Map)
a.Target := TargetModel.FromMap(m["Target"])
if m.Has("Scope") && (m["Scope"] is Map)
a.Scope := ScopeModel.FromMap(m["Scope"])
if m.Has("RecordingMeta") && (m["RecordingMeta"] is Map)
a.RecordingMeta := StudioUtils.CloneMap(m["RecordingMeta"])
if m.Has("Children") && (m["Children"] is Array) {
a.Children := []
for _, cm in m["Children"]
a.Children.Push(ActionModel.FromMap(cm))
}
if m.Has("ElseChildren") && (m["ElseChildren"] is Array) {
a.ElseChildren := []
for _, ecm in m["ElseChildren"]
a.ElseChildren.Push(ActionModel.FromMap(ecm))
}
return a
}
Clone(regenerateIds := true) {
cloned := ActionModel.FromMap(JsonCodec.Load(JsonCodec.Dump(this.ToMap(), "")))
if regenerateIds
ActionModel._RegenTreeIds(cloned)
return cloned
}
static _RegenTreeIds(act) {
act.Id := StudioUtils.GenId("act")
if IsObject(act.Target) && !act.Target.IsReusable
act.Target.Id := StudioUtils.GenId("tgt")
for _, ch in act.Children
ActionModel._RegenTreeIds(ch)
for _, ech in act.ElseChildren
ActionModel._RegenTreeIds(ech)
}
}
; ==============================================================================
; ACTION REGISTRY (All 13 Categories & Contextual Recommendations)
; ==============================================================================
class StudioOCREngine {
static SourceLabel(p, target := 0) {
source := p.Get("OCRSource","Region")
if source == "Image file" || source == "PDF page" {
path := p.Get("OCRFile","")
SplitPath(path,&name)
return name == "" ? "Choose a file" : name (source == "PDF page" ? " · page " p.Get("PDFPage",1) : "")
}
if source == "Desktop"
return "All monitors"
if source == "Region" && IsObject(target) && target.Scope.RegionW > 0
return target.Scope.RegionW " × " target.Scope.RegionH " pixels" (target.Scope.RelativeToWindow ? " · follows window" : " · screen region")
return IsObject(target) && target.WinTitle != "" ? target.WinTitle : "Choose a " StrLower(source)
}
static Defaults() => Map("OCRSource", "Region", "OCRFile", "", "PDFPage", 1, "OCRLanguage", "Automatic", "OCRScale", 1.0, "OCRGrayscale", false, "OCRInvert", false)
static Options(p) {
scale := ActionOptions.Number(p.Get("OCRScale", 1), "OCR scale", 0.25, 4)
options := {scale:scale, grayscale:!!p.Get("OCRGrayscale", false), invertcolors:!!p.Get("OCRInvert", false)}
language := p.Get("OCRLanguage", "Automatic")
if language != "Automatic" && language != ""
options.lang := language
return options
}
static Window(target) {
if !IsObject(target)
throw TargetError("Choose the OCR window or region first.")
if target.WinHwnd && WinExist(target.WinHwnd)
return target.WinHwnd
criteria := target.WinTitle (target.WinExe != "" ? " ahk_exe " target.WinExe : "")
if Trim(criteria) == ""
throw TargetError("Choose a window for OCR; an unspecified window is not assumed to be the active app.")
windows := WinGetList(criteria)
if windows.Length != 1
throw TargetError("OCR window must resolve uniquely; found " windows.Length ". Choose a more specific window.")
return windows[1]
}
static EnsureScreenAvailable() {
foreground := DllCall("GetForegroundWindow", "Ptr"), processId := 0
if !foreground || !DllCall("GetWindowThreadProcessId", "Ptr", foreground, "UInt*", &processId) || !processId
throw TargetError("Screen OCR is unavailable on this desktop. Unlock Windows and dismiss any secure-desktop prompt before continuing.")
}
static Capture(p, target := 0) {
started := A_TickCount
options := this.Options(p)
source := p.Get("OCRSource", "Region"), hwnd := 0, screen := true
CoordMode("Pixel", "Screen")
try {
if source == "Region" || source == "Window" || source == "Desktop"
this.EnsureScreenAvailable()
switch source {
case "Image file":
file := p.Get("OCRFile", "")
if file == "" || !FileExist(file)
throw ValueError("Choose an existing image file for OCR.")
result := OCR.FromFile(file, options), screen := false
case "PDF page":
file := p.Get("OCRFile", ""), page := p.Get("PDFPage", 1)
if file == "" || !FileExist(file) || !IsInteger(page) || page < 1
throw ValueError("Choose a PDF file and a positive page number.")
result := OCR.FromPDFPage(file, Integer(page), options), screen := false
case "Desktop":
result := OCR.FromDesktop(options)
case "Window":
hwnd := this.Window(target)
if WinGetMinMax(hwnd) == -1
throw TargetError("Restore the OCR window before reading it.")
result := OCR.FromWindow(hwnd, options)
case "Region":
if !IsObject(target) || target.Scope.ScopeType != "Region" || target.Scope.RegionW <= 0 || target.Scope.RegionH <= 0
throw TargetError("Choose an OCR region with Select region, or choose another source in Action settings.")
scope := target.Scope, x := scope.RegionX, y := scope.RegionY
if scope.RelativeToWindow {
hwnd := this.Window(target)
if WinGetMinMax(hwnd) == -1
throw TargetError("Restore the window containing the OCR region.")
WinGetPos(&wx, &wy,,, hwnd)
x += wx, y += wy
}
result := OCR.FromRect(x, y, scope.RegionW, scope.RegionH, options)
default:
throw ValueError("Choose Region, Window, Desktop, Image file, or PDF page as the OCR source.")
}
} catch as err
throw Error("OCR could not read the source: " err.Message "`nCheck the selected source and installed Windows OCR language in Settings > Time & language.")
return {result:result, screen:screen, hwnd:hwnd, elapsed:A_TickCount-started}
}
static Matches(result, p) {
needle := p.Get("SearchText", "")
if Trim(needle) == ""
throw ValueError("Enter the text to find.")
mode := p.Get("OCRMatchMode", "Contains"), sensitive := !!p.Get("CaseSensitive", false)
if mode == "Exact line" {
matches := []
for line in result.Lines
if StrCompare(Trim(line.Text), Trim(needle), sensitive) == 0
matches.Push(line)
return matches
}
options := {CaseSense:sensitive, IgnoreLinebreaks:true}
if mode == "Regular expression" {
pattern := (sensitive ? "" : "i)") needle
RegExMatch("", pattern)
options.SearchFunc := (haystack, unused, &found) => this.RegexSearch(haystack, pattern, &found)
} else if mode != "Contains"
throw ValueError("Choose Contains, Exact line, or Regular expression.")
return result.FindStrings(needle, options)
}
static RegexSearch(haystack, pattern, &found) {
position := RegExMatch(haystack, pattern, &found)
if position && found.Len(0) == 0
throw ValueError("OCR search patterns must match at least one character; zero-length matches cannot be clicked or enumerated.")
return position
}
static Select(matches, p) {
if !matches.Length
throw TargetError("OCR text was not found.")
selection := p.Get("MatchSelection", "Unique")
if selection != "Unique" && selection != "First" && selection != "Occurrence"
throw ValueError("Choose Unique, First, or Occurrence for OCR matching.")
if selection == "Unique" && matches.Length != 1
throw TargetError("OCR found " matches.Length " matches. Narrow the region or choose First / Occurrence explicitly.")
index := selection == "Occurrence" ? p.Get("Occurrence", 1) : 1
if !IsInteger(index) || index < 1 || index > matches.Length
throw TargetError("The requested OCR occurrence is not available; found " matches.Length " matches.")
return matches[Integer(index)]
}
static Rows(matches) {
rows := []
for match in matches {
box := match.BoundingRect
rows.Push(Map("Text", Trim(match.Text), "X", Round(box.x), "Y", Round(box.y), "Width", Round(box.w), "Height", Round(box.h)))
}
return rows
}
static ReadValue(result, format) {
if format == "Text"
return result.Text
if format == "Words"
return this.Rows(result.Words)
if format != "Lines"
throw ValueError("Choose Text, Lines, or Words as the OCR output.")
lines := []
for line in result.Lines
lines.Push(line.Text)
return lines
}
}
class ActionOptions {
static Number(value, name, minimum := 0, maximum := 31536000000) {
if !IsNumber(value) || value < minimum || value > maximum
throw ValueError(name " must be a number from " minimum " to " maximum ".")
return Number(value)
}
static Range(low, high, name, minimum := 0) {
low := this.Number(low, name " minimum", minimum)
high := this.Number(high, name " maximum", minimum)
if high < low
throw ValueError(name ": maximum must be at least the minimum.")
return [low, high]
}
static Duration(p, sample := true) {
units := Map("Milliseconds", 1, "Seconds", 1000, "Minutes", 60000, "Hours", 3600000)
unit := p.Get("DurationUnit", "Milliseconds")
if !units.Has(unit)
throw ValueError("Choose milliseconds, seconds, minutes, or hours.")
mode := p.Get("DurationMode", "Fixed")
if mode == "Random" {
bounds := this.Range(p.Get("MinimumDuration", 1), p.Get("MaximumDuration", 2), "Wait duration")
amount := sample ? Random(Float(bounds[1]), Float(bounds[2])) : bounds[2]
} else if mode == "Fixed" {
if p.Get("DurationValue", "") == ""
return Round(this.Number(p.Get("DurationMs", 1000), "Wait duration"))
amount := this.Number(p["DurationValue"], "Wait duration")
} else
throw ValueError("Choose Fixed or Random duration.")
return Round(this.Number(amount * units[unit], "Wait duration (ms)"))
}
static Offset(p, x, y) {
mode := p.Get("OffsetMode", "None")
if mode == "None"
return [x, y]
if mode == "Fixed"
return [x+Round(this.Number(p.Get("OffsetX", 0), "X offset", -100000, 100000)), y+Round(this.Number(p.Get("OffsetY", 0), "Y offset", -100000, 100000))]
if mode != "Random"
throw ValueError("Choose None, Fixed, or Random click offset.")
bx := this.Range(p.Get("OffsetMinX", -3), p.Get("OffsetMaxX", 3), "X offset", -100000)
by := this.Range(p.Get("OffsetMinY", -3), p.Get("OffsetMaxY", 3), "Y offset", -100000)
for value in [bx[1], bx[2], by[1], by[2]]
if value != Round(value) || value > 100000
throw ValueError("Random click offsets must be whole pixels between -100000 and 100000.")
return [x+Random(Ceil(bx[1]), Floor(bx[2])), y+Random(Ceil(by[1]), Floor(by[2]))]
}
static CharacterDelay(p, sample := true) {
mode := p.Get("TypingDelayMode", "None")
if mode == "None"
return 0
if mode == "Fixed"
return this.Number(p.Get("CharacterDelayMs", 50), "Character delay", 0, 60000)
if mode != "Random"
throw ValueError("Choose None, Fixed, or Random character delay.")
bounds := this.Range(p.Get("MinimumDelayMs", 30), p.Get("MaximumDelayMs", 90), "Character delay")
if bounds[2] > 60000
throw ValueError("Character delay cannot exceed 60000 ms.")
return sample ? Random(Float(bounds[1]), Float(bounds[2])) : bounds[2]
}
static ClockDeadline(p, now := "") {
now := now == "" ? A_Now : now
if !RegExMatch(p.Get("ClockTime", ""), "^(\d{1,2}):(\d{2})(?::(\d{2}))?$", &m) || Integer(m[1]) > 23 || Integer(m[2]) > 59 || (m[3] != "" && Integer(m[3]) > 59)
throw ValueError("Enter a local time as HH:MM or HH:MM:SS (24-hour clock).")
deadline := SubStr(now, 1, 8) Format("{:02}{:02}{:02}", Integer(m[1]), Integer(m[2]), m[3] == "" ? 0 : Integer(m[3]))
if deadline < now {
switch p.Get("PastTime", "Next day") {
case "Next day": deadline := DateAdd(deadline, 1, "Days")
case "Continue": return now
case "Fail": throw ValueError("The chosen time has already passed today.")
default: throw ValueError("Choose what to do when the time has passed.")
}
}
return deadline
}
static Labels(actions) {
labels := Map()
labels.CaseSense := false
for index, act in actions {
if act.Enabled && (act.Type == "Logic_Label" || Trim(act.Label) != "") {
name := this.LabelName(act)
if name == "" || labels.Has(name)
throw ValueError("Labels must have unique, nonempty names within their block: " name)
labels[name] := index
}
}
for act in actions {
if act.Enabled && act.Type == "Logic_Goto" {
if !labels.Has(Trim(act.Parameters.Get("DestinationLabel", "")))
throw ValueError("Jump destination is missing or disabled in this block: " act.Parameters.Get("DestinationLabel", ""))
if !IsInteger(act.Parameters.Get("MaxJumps", 1000)) || act.Parameters.Get("MaxJumps", 1000) < 1
throw ValueError("Jump limit must be a positive whole number.")
}
}
return labels
}
static ValidateFlow(actions) {
this.Labels(actions)
for act in actions {
if act.Enabled {
this.ValidateFlow(act.Children)
if act.HasElse || act.Type == "Logic_TryCatch"
this.ValidateFlow(act.ElseChildren)
}
}
}
static LabelName(act) => Trim(act.Type == "Logic_Label" ? act.Parameters.Get("LabelName","") : act.Label)
static CheckLabelChange(actions,act,name) {
name := Trim(name), old := this.LabelName(act)
if StrLen(name) > 120 || RegExMatch(name,"[\r\n\t]")
throw ValueError("Use a label of at most 120 characters on one line.")
for other in actions {
if other.Id != act.Id && name != "" && StrLower(this.LabelName(other)) == StrLower(name)
throw ValueError("That label is already used in this block. Choose a unique name.")
if name == "" && old != "" && other.Type == "Logic_Goto" && StrLower(Trim(other.Parameters.Get("DestinationLabel",""))) == StrLower(old)
throw ValueError("A Go to step uses this label. Choose another destination there before clearing it.")
}
return name
}
static RenameLabel(actions,act,name) {
old := this.LabelName(act)
for other in actions
if old != "" && other.Type == "Logic_Goto" && StrLower(Trim(other.Parameters.Get("DestinationLabel",""))) == StrLower(old)
other.Parameters["DestinationLabel"] := name
if act.Type == "Logic_Label"
act.Parameters["LabelName"] := name
else
act.Label := name
}
}
; Limited specification prototype. Execution remains in the existing handlers.
; Defaults are lazy: non-OCR exports do not need to initialize OCR dependencies.
class ActionSpecifications {
static Has(type) => InStr("|App_Run|Wait_Duration|Key_DownUp|Logic_Repeat|OCR_ReadText|", "|" type "|") > 0
static Definition(type) {
switch type {
case "App_Run": return Map("Type", "App_Run", "Name", "Open Program / File / Folder", "Cat", "Window & Application", "UsesTarget", false, "Keywords", "open run launch start program app application executable exe shortcut file folder directory explorer")
case "Wait_Duration": return Map("Type", "Wait_Duration", "Name", "Wait for a duration", "Cat", "Wait", "UsesTarget", false, "Keywords", "wait sleep delay pause milliseconds seconds")
case "Key_DownUp": return Map("Type", "Key_DownUp", "Name", "Key Down / Key Up", "Cat", "Mouse & Keyboard", "UsesTarget", false, "Keywords", "key hold press release modifier")
case "Logic_Repeat": return Map("Type", "Logic_Repeat", "Name", "Repeat N Times Loop", "Cat", "Logic", "UsesTarget", false, "Keywords", "repeat loop count times iteration")
case "OCR_ReadText": return Map("Type", "OCR_ReadText", "Name", "Read text with OCR", "Cat", "OCR", "UsesTarget", true, "Keywords", "ocr text image screenshot pdf extract read lines list")
}
throw ValueError("No action specification: " type)
}
static Defaults(type) {
p := Map()
switch type {
case "App_Run":
p["TargetCmd"] := "notepad.exe"
p["WorkingDir"] := ""
p["WindowMode"] := "Normal"
case "Wait_Duration":
p := Map("DurationMs", 1000, "DurationValue", "", "DurationUnit", "Seconds", "DurationMode", "Fixed", "MinimumDuration", 1, "MaximumDuration", 2)
case "Key_DownUp":
p["Key"] := "Shift"
p["State"] := "Down"
case "Logic_Repeat":
p["CountMode"] := "Fixed"
p["Minimum"] := 1
p["Maximum"] := 5
p["Count"] := 3
p["IndexVar"] := "LoopIndex"
case "OCR_ReadText":
p := StudioOCREngine.Defaults()
p["OutputVar"] := "OCRText"
p["OutputFormat"] := "Text"
p["CopyToClipboard"] := false
default: throw ValueError("No action defaults: " type)
}
return p
}
static FieldOrder(type) {
switch type {
case "App_Run": return ["TargetCmd", "WorkingDir", "WindowMode"]
case "Wait_Duration": return ["DurationMode", "DurationUnit", "DurationValue", "MinimumDuration", "MaximumDuration"]
case "Key_DownUp": return ["Key", "State"]
case "Logic_Repeat": return ["CountMode", "Count", "Minimum", "Maximum", "IndexVar"]
case "OCR_ReadText": return ["OCRSource", "OCRFile", "PDFPage", "OCRLanguage", "OCRScale", "OCRGrayscale", "OCRInvert", "OutputFormat", "OutputVar", "CopyToClipboard"]
}
return []
}
static Contract(type) {
; Descriptive contracts link metadata to specialized validators/handlers;
; these are not a second dispatcher or migration layer.
switch type {
case "App_Run": return Map("Handler", "PlaybackEngine._DispatchAction", "Effect", "process launch", "Validation", "nonempty command; working directory and window mode", "Cancellation", "before launch; launched process remains running")
case "Wait_Duration": return Map("Handler", "PlaybackEngine._InterruptibleSleep", "Effect", "wait", "Validation", "ActionOptions.Duration", "Cancellation", "poll at most 10ms requested sleep")
case "Key_DownUp": return Map("Handler", "PlaybackEngine.SetHeldInput", "Effect", "held input", "Validation", "AHK key name and Down/Up", "Cancellation", "reject DOWN; release tracked inputs")
case "Logic_Repeat": return Map("Handler", "PlaybackEngine._ExecuteActionListCore", "Effect", "control flow", "Validation", "nonnegative integer counts; variable names", "Cancellation", "between iterations and child actions")
case "OCR_ReadText": return Map("Handler", "PlaybackEngine._ExecuteOCR", "Effect", "screen/file read; optional clipboard write", "Validation", "StudioOCREngine.Options", "Cancellation", "before and after recognition")
}
return Map()
}
}
class ActionRegistry {
static Categories := [
"Mouse & Keyboard",
"Window & Application",
"UI Automation",
"Web & Browser",
"Browser Profiles",
"Wait",
"Audio",
"Image & Pixel",
"OCR",
"Logic",
"Variables & Data",
"Clipboard",
"File & System",
"Macro Control",
"Advanced"
]
static _defs := ""
static GetDefinitions() {
if IsObject(this._defs)
return this._defs
d := []
; 1. Mouse & Keyboard
d.Push(Map("Type", "Mouse_Click", "Name", "Click Mouse", "Cat", "Mouse & Keyboard", "UsesTarget", true, "Keywords", "click left right double middle mouse coordinate"))
d.Push(Map("Type", "Mouse_Move", "Name", "Move Mouse", "Cat", "Mouse & Keyboard", "UsesTarget", true, "Keywords", "move hover cursor mouse pointer"))
d.Push(Map("Type", "Mouse_Drag", "Name", "Drag Mouse", "Cat", "Mouse & Keyboard", "UsesTarget", true, "Keywords", "drag drop mouse"))
d.Push(Map("Type", "Mouse_Wheel", "Name", "Scroll Mouse Wheel", "Cat", "Mouse & Keyboard", "UsesTarget", false, "Keywords", "scroll wheel up down"))
d.Push(Map("Type", "Mouse_DownUp", "Name", "Mouse Button Down / Up", "Cat", "Mouse & Keyboard", "UsesTarget", true, "Keywords", "hold release button down up"))
d.Push(Map("Type", "Key_TypeText", "Name", "Type Literal Text", "Cat", "Mouse & Keyboard", "UsesTarget", true, "Keywords", "type text write input string literal"))
d.Push(Map("Type", "Key_SendKeys", "Name", "Send Keys / Shortcut", "Cat", "Mouse & Keyboard", "UsesTarget", false, "Keywords", "send keys hotkey shortcut enter tab escape"))
d.Push(ActionSpecifications.Definition("Key_DownUp"))
d.Push(Map("Type", "Key_PromptSecret", "Name", "Type Secret / Password Safely", "Cat", "Mouse & Keyboard", "UsesTarget", true, "Keywords", "password secret credential secure mask"))
; 2. Window & Application
d.Push(Map("Type", "Win_Activate", "Name", "Activate Window", "Cat", "Window & Application", "UsesTarget", true, "Keywords", "activate focus bring front window"))
d.Push(Map("Type", "Win_Wait", "Name", "Wait for Window", "Cat", "Window & Application", "UsesTarget", true, "Keywords", "wait window open active appear"))
d.Push(Map("Type", "Win_MoveResize", "Name", "Move / Resize Window", "Cat", "Window & Application", "UsesTarget", true, "Keywords", "move resize position size window"))
d.Push(Map("Type", "Win_State", "Name", "Minimize / Maximize / Restore / Close Window", "Cat", "Window & Application", "UsesTarget", true, "Keywords", "minimize maximize restore close window"))
d.Push(ActionSpecifications.Definition("App_Run"))
d.Push(Map("Type", "App_OpenURL", "Name", "Open URL in Default Browser", "Cat", "Window & Application", "UsesTarget", false, "Keywords", "open url website link http"))
d.Push(Map("Type", "App_WaitProcess", "Name", "Wait for Process", "Cat", "Window & Application", "UsesTarget", false, "Keywords", "wait process exe running"))
; 3. UI Automation
d.Push(Map("Type", "UIA_Click", "Name", "Click UI Element", "Cat", "UI Automation", "UsesTarget", true, "Keywords", "click button invoke uia semantic element"))
d.Push(Map("Type", "UIA_SetValue", "Name", "Set UI Element Value / Text", "Cat", "UI Automation", "UsesTarget", true, "Keywords", "set value text edit input textbox uia"))
d.Push(Map("Type", "UIA_ReadValue", "Name", "Read UI Element Text / Value to Variable", "Cat", "UI Automation", "UsesTarget", true, "Keywords", "read get extract text value name variable uia"))
d.Push(Map("Type", "UIA_Focus", "Name", "Focus UI Element", "Cat", "UI Automation", "UsesTarget", true, "Keywords", "focus element control uia"))
d.Push(Map("Type", "UIA_Toggle", "Name", "Check / Uncheck / Toggle Control", "Cat", "UI Automation", "UsesTarget", true, "Keywords", "check uncheck toggle checkbox radio switch"))
d.Push(Map("Type", "UIA_Select", "Name", "Select Item in List / ComboBox / Tab", "Cat", "UI Automation", "UsesTarget", true, "Keywords", "select item dropdown combobox list tab"))
d.Push(Map("Type", "UIA_ExpandCollapse", "Name", "Expand / Collapse Tree or Menu", "Cat", "UI Automation", "UsesTarget", true, "Keywords", "expand collapse tree menu dropdown"))
d.Push(Map("Type", "UIA_ScrollIntoView", "Name", "Scroll Element Into View", "Cat", "UI Automation", "UsesTarget", true, "Keywords", "scroll into view element visible"))
d.Push(Map("Type", "UIA_FindWhileScrolling", "Name", "Find Element While Scrolling", "Cat", "UI Automation", "UsesTarget", true, "Keywords", "scroll until found search list page virtualized"))
; 4. Web & Browser
d.Push(Map("Type", "Browser_Navigate", "Name", "Navigate Browser to URL", "Cat", "Web & Browser", "UsesTarget", false, "Keywords", "navigate url browse go page web"))
d.Push(Map("Type", "Browser_Click", "Name", "Click Web Element", "Cat", "Web & Browser", "UsesTarget", true, "Keywords", "click web button link element page"))
d.Push(Map("Type", "Browser_ClickAndWaitNewTab", "Name", "Click Web Element & Switch to New Tab", "Cat", "Web & Browser", "UsesTarget", true, "Keywords", "click popup new tab external link target blank"))
d.Push(Map("Type", "Browser_SetValue", "Name", "Fill Web Input / Form Field", "Cat", "Web & Browser", "UsesTarget", true, "Keywords", "fill type set input form field web"))
d.Push(Map("Type", "Browser_GetText", "Name", "Extract Web Text / Value / URL", "Cat", "Web & Browser", "UsesTarget", true, "Keywords", "get read extract web text value url links"))
d.Push(Map("Type", "Browser_ExtractLinks", "Name", "Extract All Page Links to Variable", "Cat", "Web & Browser", "UsesTarget", false, "Keywords", "extract links urls hrefs scrape getalllinks"))
d.Push(Map("Type", "Browser_FindText", "Name", "Find / Verify Text On Page", "Cat", "Web & Browser", "UsesTarget", false, "Keywords", "find search verify text page getalltext"))
d.Push(Map("Type", "Browser_SelectTab", "Name", "Select / Switch Browser Tab", "Cat", "Web & Browser", "UsesTarget", false, "Keywords", "select switch tab browser title url"))
d.Push(Map("Type", "Browser_NewTab", "Name", "Open New Browser Tab", "Cat", "Web & Browser", "UsesTarget", false, "Keywords", "new tab open browser"))
d.Push(Map("Type", "Browser_CloseTab", "Name", "Close Browser Tab", "Cat", "Web & Browser", "UsesTarget", false, "Keywords", "close tab browser"))
d.Push(Map("Type", "Browser_NavButton", "Name", "Browser Back / Forward / Reload", "Cat", "Web & Browser", "UsesTarget", false, "Keywords", "back forward reload refresh browser"))
d.Push(Map("Type", "Browser_Scroll", "Name", "Scroll Web Page", "Cat", "Web & Browser", "UsesTarget", false, "Keywords", "scroll web page down up"))
d.Push(Map("Type", "Browser_Alert", "Name", "Handle Browser Alert / Dialog", "Cat", "Web & Browser", "UsesTarget", false, "Keywords", "alert confirm dialog popup close text"))
d.Push(Map("Type", "Browser_JSExecute", "Name", "Execute JavaScript / CSS Action", "Cat", "Web & Browser", "UsesTarget", false, "Keywords", "javascript js css queryselector execute"))
; 5. Browser Profiles
d.Push(Map("Type", "Profile_Launch", "Name", "Launch Browser Profile", "Cat", "Browser Profiles", "UsesTarget", false, "Keywords", "launch open browser profile work personal chrome edge firefox"))
d.Push(Map("Type", "Profile_AttachSession", "Name", "Attach to Browser Session", "Cat", "Browser Profiles", "UsesTarget", false, "Keywords", "attach connect browser session profile window"))
d.Push(Map("Type", "Profile_SwitchSession", "Name", "Set Active Browser Session", "Cat", "Browser Profiles", "UsesTarget", false, "Keywords", "switch active session source destination browser"))
d.Push(Map("Type", "Profile_CloseSession", "Name", "Close Studio-Owned Browser Session", "Cat", "Browser Profiles", "UsesTarget", false, "Keywords", "close browser session studio"))
; 6. Wait
d.Push(Map("Type", "Wait_Element", "Name", "Wait for UI / Web Element", "Cat", "Wait", "UsesTarget", true, "Keywords", "wait element appear disappear enabled text value"))
d.Push(Map("Type", "Wait_PageLoad", "Name", "Wait for Browser Page / URL / Title", "Cat", "Wait", "UsesTarget", false, "Keywords", "wait page load url title tab browser"))
d.Push(Map("Type", "Wait_NewTab", "Name", "Wait for New Browser Tab to Open", "Cat", "Wait", "UsesTarget", false, "Keywords", "wait new tab popup open switch"))
d.Push(Map("Type", "Wait_FirstMatch", "Name", "Wait for Either Outcome (First Match)", "Cat", "Wait", "UsesTarget", false, "Keywords", "wait first match either or race success error dialog"))
d.Push(Map("Type", "Wait_ImageColor", "Name", "Wait for Image or Pixel Color", "Cat", "Wait", "UsesTarget", true, "Keywords", "wait image color pixel appear gone"))
d.Push(ActionSpecifications.Definition("OCR_ReadText"))
d.Push(Map("Type", "OCR_FindText", "Name", "Find text with OCR", "Cat", "OCR", "UsesTarget", true, "Keywords", "ocr find text matches positions"))
d.Push(Map("Type", "OCR_ClickText", "Name", "Click text with OCR", "Cat", "OCR", "UsesTarget", true, "Keywords", "ocr click text visual button"))
d.Push(Map("Type", "OCR_WaitText", "Name", "Wait for text with OCR", "Cat", "OCR", "UsesTarget", true, "Keywords", "ocr wait text appear disappear change"))
d.Push(Map("Type", "Wait_Clock", "Name", "Wait until a time of day", "Cat", "Wait", "UsesTarget", false, "Keywords", "clock system time schedule"))
d.Push(Map("Type", "Wait_Condition", "Name", "Wait until a condition is true", "Cat", "Wait", "UsesTarget", false, "Keywords", "wait file variable clipboard condition"))
d.Push(Map("Type", "Logic_Label", "Name", "Label — name this location", "Cat", "Logic", "UsesTarget", false, "Keywords", "label bookmark goto jump"))
d.Push(Map("Type", "Logic_Goto", "Name", "Go to label", "Cat", "Logic", "UsesTarget", false, "Keywords", "goto jump label"))
d.Push(ActionSpecifications.Definition("Wait_Duration"))
d.Push(Map("Type", "Wait_ManualCheckpoint", "Name", "Manual Checkpoint (Wait for User)", "Cat", "Wait", "UsesTarget", false, "Keywords", "manual checkpoint user approval mfa captcha pause"))
d.Push(Map("Type", "Audio_ReadLevel", "Name", "Read Program Audio Level", "Cat", "Audio", "UsesTarget", false, "Keywords", "audio sound peak process volume meter read"))
d.Push(Map("Type", "Audio_Wait", "Name", "Wait for Program Audio", "Cat", "Audio", "UsesTarget", false, "Keywords", "audio sound silence threshold rising falling wait trigger process"))
; 7. Image & Pixel
d.Push(Map("Type", "Image_Click", "Name", "Find & Click Image", "Cat", "Image & Pixel", "UsesTarget", true, "Keywords", "image picture find search click visual"))
d.Push(Map("Type", "Pixel_Click", "Name", "Find & Click Pixel Color", "Cat", "Image & Pixel", "UsesTarget", true, "Keywords", "pixel color hex rgb search click"))
d.Push(Map("Type", "Pixel_GetColor", "Name", "Read Pixel Color at Point", "Cat", "Image & Pixel", "UsesTarget", true, "Keywords", "get read pixel color hex rgb"))
; 8. Logic
d.Push(Map("Type", "Logic_If", "Name", "If Condition Block", "Cat", "Logic", "UsesTarget", false, "Keywords", "if else condition branch check"))
d.Push(Map("Type", "Logic_ForEach", "Name", "For Each Item in List", "Cat", "Logic", "UsesTarget", false, "Keywords", "list foreach item lines array nested loop"))
d.Push(ActionSpecifications.Definition("Logic_Repeat"))
d.Push(Map("Type", "Logic_While", "Name", "While Condition Loop", "Cat", "Logic", "UsesTarget", false, "Keywords", "while loop condition until"))
d.Push(Map("Type", "Logic_Break", "Name", "Break Loop", "Cat", "Logic", "UsesTarget", false, "Keywords", "break exit loop"))
d.Push(Map("Type", "Logic_Continue", "Name", "Continue Next Iteration", "Cat", "Logic", "UsesTarget", false, "Keywords", "continue skip next loop"))
d.Push(Map("Type", "Logic_TryCatch", "Name", "Try / Recover Block", "Cat", "Logic", "UsesTarget", false, "Keywords", "try catch error recover handle"))
; 9. Variables & Data
d.Push(Map("Type", "Var_Set", "Name", "Set Variable", "Cat", "Variables & Data", "UsesTarget", false, "Keywords", "set variable value assign math string"))
d.Push(Map("Type", "Var_PromptInput", "Name", "Prompt User for Input", "Cat", "Variables & Data", "UsesTarget", false, "Keywords", "prompt ask user input dialog variable"))
; 10. Clipboard
d.Push(Map("Type", "Clip_Set", "Name", "Set Clipboard Text", "Cat", "Clipboard", "UsesTarget", false, "Keywords", "clipboard copy set text"))
d.Push(Map("Type", "Clip_Get", "Name", "Read Clipboard into Variable", "Cat", "Clipboard", "UsesTarget", false, "Keywords", "clipboard get read paste variable"))
d.Push(Map("Type", "Clip_Paste", "Name", "Paste via Clipboard", "Cat", "Clipboard", "UsesTarget", true, "Keywords", "paste clipboard fast text"))
; 11. File & System
d.Push(Map("Type", "File_Read", "Name", "Read File to Variable", "Cat", "File & System", "UsesTarget", false, "Keywords", "file read text load variable"))
d.Push(Map("Type", "File_Write", "Name", "Write / Append Text to File", "Cat", "File & System", "UsesTarget", false, "Keywords", "file write save append log text"))
d.Push(Map("Type", "File_Exists", "Name", "Check / Wait for File", "Cat", "File & System", "UsesTarget", false, "Keywords", "file exists wait folder path"))
; 12. Macro Control
d.Push(Map("Type", "Macro_Call", "Name", "Call Another Macro", "Cat", "Macro Control", "UsesTarget", false, "Keywords", "call run submacro macro reusable"))
d.Push(Map("Type", "Macro_Stop", "Name", "Stop Current Macro", "Cat", "Macro Control", "UsesTarget", false, "Keywords", "stop return exit macro"))
d.Push(Map("Type", "Macro_Comment", "Name", "Comment / Section Header", "Cat", "Macro Control", "UsesTarget", false, "Keywords", "comment note section header documentation"))
this._defs := d
return d
}
static IsKnown(actionType) {
for def in this.GetDefinitions()
if def["Type"] == actionType
return true
return false
}
static GetCategoryForType(actionType) {
for _, def in this.GetDefinitions() {
if def["Type"] == actionType
return def["Cat"]
}
return "UI Automation"
}
static UsesTarget(actionType) {
for _, def in this.GetDefinitions() {
if def["Type"] == actionType
return def["UsesTarget"]
}
return false
}
static GetDefaultParams(actionType) {
if ActionSpecifications.Has(actionType)
return ActionSpecifications.Defaults(actionType)
p := Map()
switch actionType {
case "OCR_FindText", "OCR_ClickText", "OCR_WaitText":
p := StudioOCREngine.Defaults()
p["OutputVar"] := actionType == "OCR_FindText" ? "OCRMatches" : "OCRText"
p["SearchText"] := ""
p["OCRMatchMode"] := "Contains"
p["CaseSensitive"] := false
p["FoundVar"] := "OCRFound"
p["MatchCountVar"] := "OCRMatchCount"
if actionType == "OCR_ClickText" {
p["MatchSelection"] := "Unique"
p["Occurrence"] := 1
p["Button"] := "Left"
p["ClickCount"] := 1
}
if actionType == "OCR_WaitText" {
p["OCRWaitFor"] := "Present"
p["StableForMs"] := 0
}
case "Audio_ReadLevel", "Audio_Wait":
p := Map("ProcessName", "", "AudioOutput", "All outputs", "Trigger", "Above", "ThresholdPercent", 4.0,
"HoldMs", 100, "HysteresisPercent", 1.0, "SampleMs", 50, "OutputVar", "AudioPeak")
case "Mouse_Click", "UIA_Click", "Browser_Click", "Image_Click", "Pixel_Click":
p["Button"] := "Left" ; Left, Right, Middle, Double
p["ClickCount"] := 1
p["ClickMethod"] := "Auto" ; Auto, Invoke, Physical, ControlClick, JSClick
p["CoordMode"] := "WindowRelative" ; Target, WindowRelative, Screen, Client
case "Browser_ClickAndWaitNewTab":
p["Button"] := "Left"
p["ClickMethod"] := "Auto"
p["SwitchToNewTab"] := true
case "Mouse_Move":
p["Speed"] := 2
case "Mouse_Drag":
p["Button"] := "Left"
p["ToX"] := 200
p["ToY"] := 200
p["DurationMs"] := 300
p["DestinationMode"] := "Screen"
case "Mouse_Wheel":
p["Direction"] := "Down"
p["Notches"] := 3
p["ScrollDurationMs"] := 0
case "Mouse_DownUp":
p["Button"] := "Left"
p["State"] := "Down"
case "Key_TypeText", "UIA_SetValue", "Browser_SetValue":
p["Text"] := ""
p["ClearFirst"] := true
p["SendEnterAfter"] := false
p["Method"] := "Auto" ; Auto, ValuePattern, SendText, Paste, ControlSend
case "Key_SendKeys":
p["Keys"] := "{Enter}"
p["UseControlSend"] := false
case "Key_PromptSecret":
p["SecretVarName"] := "UserPassword"
p["PromptMessage"] := "Enter secret/password for automation:"
case "Win_Activate", "Win_Wait":
p["WinTitle"] := ""
p["WinExe"] := ""
case "Win_MoveResize":
p["X"] := 100
p["Y"] := 100
p["W"] := 800
p["H"] := 600
case "Win_State":
p["StateAction"] := "Maximize" ; Minimize, Maximize, Restore, Close
case "App_OpenURL":
p["URL"] := "https://example.com"
case "App_WaitProcess":
p["ProcessName"] := "notepad.exe"
p["WaitCondition"] := "Appear"
case "UIA_ReadValue", "Browser_GetText":
p["OutputVar"] := "ExtractedText"
p["Property"] := "Auto" ; Auto, Name, Value, URL, Title, AllText, AllLinks
case "Browser_ExtractLinks":
p["OutputVar"] := "PageLinks"
p["FilterText"] := ""
case "Browser_FindText":
p["SearchText"] := ""
p["OutputVar"] := "TextFoundFlag"
p["CaseSensitive"] := false
case "UIA_Toggle":
p["ToggleState"] := "Check" ; Check, Uncheck, Toggle
case "UIA_Select":
p["ItemText"] := ""
case "UIA_ExpandCollapse":
p["State"] := "Expand" ; Expand, Collapse
case "UIA_FindWhileScrolling":
p["Direction"] := "Down"
p["MaxScrolls"] := 12
p["ScrollStep"] := 4
p["ClickWhenFound"] := false
case "Browser_Navigate":
p["URL"] := "https://example.com"
p["WaitForLoad"] := true
p["TargetTitle"] := ""
p["OpenNewTab"] := false
case "Browser_SelectTab", "Browser_CloseTab":
p["TabTitle"] := ""
p["MatchMode"] := "Contains" ; Current, Exact, Contains, StartsWith, Regex, URLContains
case "Browser_NavButton":
p["Action"] := "Reload" ; Back, Forward, Reload, Home
case "Browser_Scroll":
p["Direction"] := "Down"
p["Amount"] := 400
case "Browser_Alert":
p["AlertAction"] := "GetAndClose" ; GetAndClose, Close, GetText
p["OutputVar"] := "AlertText"
case "Browser_JSExecute":
p["JSCode"] := "document.title"
p["CSSSelector"] := ""
p["JSMode"] := "Execute" ; Execute, ReturnClipboard, ClickCSS, ControlClickCSS
p["OutputVar"] := "JSResult"
case "Profile_Launch":
p["BrowserType"] := "Edge"
p["ProfileAlias"] := "Default"
p["SessionName"] := "MainBrowser"
p["URL"] := ""
p["ReuseExisting"] := true
p["NewWindow"] := false
p["WaitForUIA"] := true
p["ExtraArgs"] := ""
case "Profile_AttachSession":
p["BrowserType"] := "Edge"
p["ProfileAlias"] := "Current"
p["SessionName"] := "MainBrowser"
p["WinTitle"] := ""
case "Profile_SwitchSession", "Profile_CloseSession":
p["SessionName"] := "MainBrowser"
case "Wait_Element":
p["WaitCondition"] := "Appear" ; Appear, Disappear, Enabled, TextContains, ValueEquals
p["ExpectedText"] := ""
case "Wait_PageLoad":
p["Condition"] := "PageReady" ; PageReady, URLContains, TitleContains, TabExists
p["ExpectedValue"] := ""
case "Wait_NewTab":
p["SwitchToNewTab"] := true
p["OutputVar"] := "NewTabTitle"
case "Wait_FirstMatch":
p["OutcomeAType"] := "ElementAppears" ; ElementAppears, TextAppears, URLContains, TitleContains
p["OutcomeAValue"] := "Dashboard"
p["OutcomeBType"] := "TextAppears"
p["OutcomeBValue"] := "Error"
p["OutputVar"] := "MatchedOutcome"
case "Wait_ImageColor":
p["Condition"] := "Appear" ; Appear, Disappear
p["OutputXVar"] := "FoundX"
p["OutputYVar"] := "FoundY"
case "Wait_Clock":
p := Map("ClockTime", "09:00:00", "PastTime", "Next day")
case "Logic_Label":
p["LabelName"] := "NewLabel"
case "Logic_Goto":
p := Map("DestinationLabel", "", "MaxJumps", 1000)
case "Wait_ManualCheckpoint":
p["PromptText"] := "Complete the manual step (e.g., MFA or verification) and click Continue to resume."
case "Pixel_GetColor":
p["OutputVar"] := "PixelHex"
case "Logic_If", "Logic_While", "Wait_Condition":
p["ConditionType"] := "UIAExists"
p["LeftOperand"] := ""
p["Operator"] := "Equals"
p["RightOperand"] := ""
p["CombineOp"] := "AND"
p["SecondConditionType"] := "None"
p["SecondLeft"] := ""
p["SecondRight"] := ""
if actionType == "Logic_While" {
p["MaxIterations"] := 10000
p["LoopMode"] := "While"
}
case "Logic_ForEach":
p["SourceMode"] := "Lines"
p["Items"] := "Banana`nApple`nCarrot`nSquare"
p["ItemVar"] := "Item"
p["IndexVar"] := "ItemIndex"
p["SkipEmpty"] := true
case "Var_Set":
p["VarName"] := "MyVar"
p["Value"] := ""
p["Operation"] := "Assign" ; Assign, Append, Add, Subtract, Multiply
case "Var_PromptInput":
p["VarName"] := "UserInput"
p["Prompt"] := "Enter value:"
p["DefaultValue"] := ""
case "Clip_Set", "Clip_Paste":
p["Text"] := ""
case "Clip_Get":
p["OutputVar"] := "ClipboardText"
case "File_Read":
p["FilePath"] := ""
p["OutputVar"] := "FileText"
case "File_Write":
p["FilePath"] := ""
p["Text"] := ""
p["Append"] := true
case "File_Exists":
p["FilePath"] := ""
p["OutputVar"] := "FileExistsFlag"
case "Macro_Call":
p["TargetMacroName"] := ""
case "Macro_Comment":
p["Comment"] := "Section"
}
if InStr("|Mouse_Click|UIA_Click|Browser_Click|Image_Click|Pixel_Click|Browser_ClickAndWaitNewTab|OCR_ClickText|", "|" actionType "|") {
p["OffsetMode"] := "None"
p["OffsetX"] := 0, p["OffsetY"] := 0
p["OffsetMinX"] := -3, p["OffsetMaxX"] := 3
p["OffsetMinY"] := -3, p["OffsetMaxY"] := 3
}
if actionType == "Win_Wait"
p["WindowCondition"] := "Exists"
if actionType == "Key_TypeText" || actionType == "UIA_SetValue" || actionType == "Browser_SetValue" {
p["TypingDelayMode"] := "None"
p["CharacterDelayMs"] := 50
p["MinimumDelayMs"] := 30, p["MaximumDelayMs"] := 90
}
return p
}
; Recommends appropriate actions given a selected TargetModel (Section 24 & vNext Section 29)
static GetRecommendedActionsForTarget(target) {
if !IsObject(target)
return ["UIA_Click", "Mouse_Click"]
if target.TargetKind == "Image"
return ["Image_Click", "Wait_ImageColor"]
if target.TargetKind == "PixelColor"
return ["Pixel_Click", "Wait_ImageColor", "Pixel_GetColor"]
if target.TargetKind == "Window"
return ["Win_Activate", "Win_Wait", "Win_State", "Win_MoveResize"]
if target.IsWebContent {
switch target.Role {
case "Textbox", "Edit", "ComboBox":
return ["Browser_SetValue", "Browser_Click", "Browser_GetText", "Wait_Element"]
case "Link":
return ["Browser_Click", "Browser_ClickAndWaitNewTab", "Browser_GetText", "Wait_Element"]
case "Text":
return ["Wait_Element", "Browser_GetText", "Browser_Click"]
default:
return ["Browser_Click", "Wait_Element", "Browser_GetText", "Browser_ClickAndWaitNewTab"]
}
}
switch target.Role {
case "Button", "MenuItem", "Link", "SplitButton":
return ["UIA_Click", "Wait_Element", "UIA_Focus", "Mouse_Click"]
case "Textbox", "Edit", "Document":
return ["UIA_SetValue", "Key_TypeText", "UIA_ReadValue", "UIA_Focus", "Wait_Element"]
case "Checkbox", "RadioButton":
return ["UIA_Toggle", "UIA_Click", "Wait_Element"]
case "ComboBox", "ListItem", "Tab", "TabItem":
return ["UIA_Select", "UIA_Click", "UIA_ExpandCollapse", "UIA_ReadValue"]
case "Text":
return ["Wait_Element", "UIA_ReadValue", "UIA_Click"]
default:
return ["UIA_Click", "Wait_Element", "UIA_ReadValue", "Mouse_Click"]
}
}
static FormatDescription(act) {
p := act.Parameters
tLabel := IsObject(act.Target) ? act.Target.GetHumanLabel() : ""
tName := (IsObject(act.Target) && act.Target.Name != "") ? '"' act.Target.Name '" ' StrLower(act.Target.Role) : tLabel
switch act.Type {
case "OCR_ReadText":
return "Read OCR " StrLower(p.Get("OutputFormat","Text")) " → ${" p.Get("OutputVar","OCRText") "}"
case "OCR_FindText", "OCR_ClickText", "OCR_WaitText":
return (act.Type == "OCR_ClickText" ? "Click OCR text: " : (act.Type == "OCR_FindText" ? "Find OCR text: " : "Wait for OCR text (" p.Get("OCRWaitFor","Present") "): ")) p.Get("SearchText", "")
case "Audio_ReadLevel":
return "Read audio level from " (p.Get("ProcessName", "") != "" ? p["ProcessName"] : "a program")
case "Audio_Wait":
return "Wait for " (p.Get("ProcessName", "") != "" ? p["ProcessName"] : "program") " audio: " p.Get("Trigger", "Above") " " p.Get("ThresholdPercent", 4) "%"
case "UIA_Click":
btn := p.Has("Button") && p["Button"] != "Left" ? p["Button"] " click " : "Click "
return btn . (tName != "" ? tName : "UI element")
case "Browser_Click":
btn := p.Has("Button") && p["Button"] != "Left" ? p["Button"] " click " : "Click "
return btn . (tName != "" ? tName : "web element")
case "Browser_ClickAndWaitNewTab":
return "Click " . (tName != "" ? tName : "web link") . " & switch to new tab"
case "Mouse_Click":
btn := p.Has("Button") && p["Button"] != "Left" ? p["Button"] " Click" : "Click"
if IsObject(act.Target) && act.Target.TargetKind == "ScreenCoordinate"
return Format("{1} at ({2}, {3})", btn, act.Target.ScreenX, act.Target.ScreenY)
if IsObject(act.Target) && act.Target.TargetKind == "WindowRelative"
return Format("{1} at ({2}, {3}) in {4}", btn, act.Target.WinRelX, act.Target.WinRelY, act.Target.WinExe != "" ? act.Target.WinExe : "window")
return btn " " tLabel
case "Mouse_Move":
return "Move mouse to " tLabel
case "Mouse_Drag":
return Format("Drag {1} to ({2}, {3})", tLabel, p.Get("ToX", 0), p.Get("ToY", 0))
case "Mouse_Wheel":
return Format("Scroll wheel {1} ({2})", p.Get("Direction", "Down"), p.Get("Notches", 3))
case "Key_TypeText", "UIA_SetValue", "Browser_SetValue":
txt := p.Get("Text", "")
if StrLen(txt) > 30
txt := SubStr(txt, 1, 27) "..."
into := (IsObject(act.Target) && act.Target.Name != "") ? " into " act.Target.Name : ""
prefix := act.Type == "Key_TypeText" ? "Type" : "Set value"
return Format('{1} "{2}"{3}', prefix, txt, into)
case "Key_SendKeys":
return "Send keys " p.Get("Keys", "")
case "Key_PromptSecret":
return "Type secret [" p.Get("SecretVarName", "Secret") "]" (IsObject(act.Target) && act.Target.Name != "" ? " into " act.Target.Name : "")
case "Win_Activate":
w := p.Get("WinTitle", "") != "" ? p["WinTitle"] : (p.Get("WinExe", "") != "" ? p["WinExe"] : tLabel)
return "Activate window " w
case "Win_Wait":
w := p.Get("WinTitle", "") != "" ? p["WinTitle"] : (p.Get("WinExe", "") != "" ? p["WinExe"] : tLabel)
return "Wait for window " w
case "Win_MoveResize":
return Format("Move/Resize window to ({1}, {2}, {3}×{4})", p.Get("X", 0), p.Get("Y", 0), p.Get("W", 800), p.Get("H", 600))
case "Win_State":
return p.Get("StateAction", "Maximize") " window " tLabel
case "App_Run":
return "Run " p.Get("TargetCmd", "")
case "App_OpenURL":
return "Open URL " p.Get("URL", "")
case "App_WaitProcess":
return "Wait for process " p.Get("ProcessName", "")
case "UIA_ReadValue", "Browser_GetText":
return Format("Read {1} from {2} → ${3}", p.Get("Property", "Auto"), tName != "" ? tName : "target", p.Get("OutputVar", "ExtractedText"))
case "Browser_ExtractLinks":
return Format("Extract all page links → ${1}", p.Get("OutputVar", "PageLinks"))
case "Browser_FindText":
return Format('Verify page text "{1}" → ${2}', p.Get("SearchText", ""), p.Get("OutputVar", "TextFoundFlag"))
case "UIA_Focus":
return "Focus " tName
case "UIA_Toggle":
return p.Get("ToggleState", "Toggle") " " tName
case "UIA_Select":
return Format('Select "{1}" in {2}', p.Get("ItemText", ""), tName)
case "UIA_ExpandCollapse":
return p.Get("State", "Expand") " " tName
case "UIA_ScrollIntoView":
return "Scroll " tName " into view"
case "UIA_FindWhileScrolling":
return Format("Scroll {1} until {2} found (max {3})", p.Get("Direction", "Down"), tName, p.Get("MaxScrolls", 12))
case "Browser_Navigate":
return "Navigate to " p.Get("URL", "") (p.Get("WaitForLoad", true) ? " and wait" : "")
case "Browser_SelectTab":
return Format('Select tab "{1}"', p.Get("TabTitle", "Current"))
case "Browser_NewTab":
return "Open new browser tab"
case "Browser_CloseTab":
return p.Get("TabTitle", "") != "" ? Format('Close tab "{1}"', p["TabTitle"]) : "Close current browser tab"
case "Browser_NavButton":
return "Browser " p.Get("Action", "Reload")
case "Browser_Scroll":
return Format("Scroll page {1} ({2}px)", p.Get("Direction", "Down"), p.Get("Amount", 400))
case "Browser_Alert":
return "Handle browser alert (" p.Get("AlertAction", "GetAndClose") ")"
case "Browser_JSExecute":
mode := p.Get("JSMode", "Execute")
if mode == "ClickCSS" || mode == "ControlClickCSS"
return Format('Click CSS selector "{1}"', p.Get("CSSSelector", ""))
return "Run JavaScript: " SubStr(p.Get("JSCode", ""), 1, 36)
case "Profile_Launch":
return Format("Launch {1} — {2} (Session: {3})", p.Get("BrowserType", "Edge"), p.Get("ProfileAlias", "Default"), p.Get("SessionName", "MainBrowser"))
case "Profile_AttachSession":
return Format("Attach Session {1} ({2} — {3})", p.Get("SessionName", "MainBrowser"), p.Get("BrowserType", "Edge"), p.Get("ProfileAlias", "Current"))
case "Profile_SwitchSession":
return "Switch active browser session to " p.Get("SessionName", "MainBrowser")
case "Profile_CloseSession":
return "Close Studio-owned session " p.Get("SessionName", "MainBrowser")
case "Wait_Element":
return Format("Wait for {1} ({2})", tName != "" ? tName : "element", p.Get("WaitCondition", "Appear"))
case "Wait_PageLoad":
return Format("Wait for browser {1} {2}", p.Get("Condition", "PageReady"), p.Get("ExpectedValue", ""))
case "Wait_NewTab":
return "Wait for new browser tab" (p.Get("SwitchToNewTab", true) ? " and switch to it" : "")
case "Wait_FirstMatch":
return Format("Wait for Either [{1}: {2}] OR [{3}: {4}] → ${5}", p.Get("OutcomeAType", "ElementAppears"), p.Get("OutcomeAValue", ""), p.Get("OutcomeBType", "TextAppears"), p.Get("OutcomeBValue", ""), p.Get("OutputVar", "MatchedOutcome"))
case "Wait_ImageColor":
return Format("Wait for {1} ({2})", tLabel, p.Get("Condition", "Appear"))
case "Wait_Duration":
return p.Get("DurationMode", "Fixed") == "Random" ? "Wait " p.Get("MinimumDuration", 1) "–" p.Get("MaximumDuration", 2) " " StrLower(p.Get("DurationUnit", "Seconds")) : "Wait " (p.Get("DurationValue", "") == "" ? p.Get("DurationMs", 1000) " ms" : p["DurationValue"] " " StrLower(p.Get("DurationUnit", "Seconds")))
case "Wait_Clock":
return "Wait until " p.Get("ClockTime", "09:00:00")
case "Wait_Condition":
return "Wait until " p.Get("ConditionType", "UIAExists")
case "Logic_Label":
return "Label: " p.Get("LabelName", "")
case "Logic_Goto":
return "Go to " p.Get("DestinationLabel", "(choose a label)")
case "Wait_ManualCheckpoint":
return "Manual Checkpoint: " SubStr(p.Get("PromptText", "Wait for user"), 1, 42)
case "Image_Click":
return "Click image " tLabel
case "Pixel_Click":
return "Click color " (IsObject(act.Target) ? act.Target.CapturedColorHex : "")
case "Pixel_GetColor":
return "Read pixel color → $" p.Get("OutputVar", "PixelHex")
case "Logic_If":
return Format("If {1} ({2} {3} {4})", p.Get("ConditionType", "UIAExists"), p.Get("LeftOperand", ""), p.Get("Operator", ""), p.Get("RightOperand", ""))
case "Logic_ForEach":
return "For each item → ${" p.Get("ItemVar", "Item") "} (" p.Get("SourceMode", "Lines") ")"
case "Logic_Repeat":
return Format("Repeat {1} times (→ ${2})", p.Get("Count", 3), p.Get("IndexVar", "LoopIndex"))
case "Logic_While":
return Format("{1} {2} ({3} {4})", p.Get("LoopMode", "While"), p.Get("ConditionType", "UIAExists"), p.Get("LeftOperand", ""), p.Get("RightOperand", ""))
case "Logic_Break":
return "Break out of loop"
case "Logic_Continue":
return "Continue to next loop iteration"
case "Logic_TryCatch":
return "Try actions (recover on error)"
case "Var_Set":
return Format("Set ${1} ({2}) = {3}", p.Get("VarName", "MyVar"), p.Get("Operation", "Assign"), p.Get("Value", ""))
case "Var_PromptInput":
return Format('Prompt user → ${1} ("{2}")', p.Get("VarName", "UserInput"), p.Get("Prompt", ""))
case "Clip_Set":
return "Set Clipboard text"
case "Clip_Get":
return "Read Clipboard → $" p.Get("OutputVar", "ClipboardText")
case "Clip_Paste":
return "Paste text via Clipboard"
case "File_Read":
return Format("Read file {1} → ${2}", p.Get("FilePath", ""), p.Get("OutputVar", "FileText"))
case "File_Write":
return Format("{1} to file {2}", p.Get("Append", true) ? "Append" : "Write", p.Get("FilePath", ""))
case "File_Exists":
return Format("Check file exists {1} → ${2}", p.Get("FilePath", ""), p.Get("OutputVar", "FileExistsFlag"))
case "Macro_Call":
return "Call macro: " p.Get("TargetMacroName", "")
case "Macro_Stop":
return "Stop macro execution"
case "Macro_Comment":
return "// " p.Get("Comment", "")
default:
return act.Type
}
}
}
; ==============================================================================
; WORKFLOW STRUCTURAL AST TREE MANAGER
; ==============================================================================
class WorkflowTree {
; Flattens hierarchical AST into display rows: [{Action, Depth, ParentArray, IndexInParent, RowKind, StepNumber}]
static Flatten(rootActions, includeCollapsedChildren := false) {
rows := []
stepNum := 0
this._FlattenRec(rootActions, 0, rows, &stepNum, includeCollapsedChildren)
return rows
}
static _FlattenRec(actArray, depth, rows, &stepNum, includeCollapsed) {
for idx, act in actArray {
stepNum += 1
rows.Push(Map(
"Action", act,
"Depth", depth,
"ParentArray", actArray,
"IndexInParent", idx,
"RowKind", "Action",
"StepNumber", stepNum
))
if act.IsContainerAction() && (includeCollapsed || !act.IsCollapsed) {
this._FlattenRec(act.Children, depth + 1, rows, &stepNum, includeCollapsed)
if (act.Type == "Logic_If" && act.HasElse) || act.Type == "Logic_TryCatch" {
rows.Push(Map(
"Action", act,
"Depth", depth,
"ParentArray", actArray,
"IndexInParent", idx,
"RowKind", "ElseMarker",
"StepNumber", "-"
))
this._FlattenRec(act.ElseChildren, depth + 1, rows, &stepNum, includeCollapsed)
}
}
}
}
static FindById(rootActions, actionId) {
for idx, act in rootActions {
if act.Id == actionId
return Map("Action", act, "ParentArray", rootActions, "Index", idx)
if act.IsContainerAction() {
res := this.FindById(act.Children, actionId)
if IsObject(res)
return res
if act.HasElse || act.Type == "Logic_TryCatch" {
res2 := this.FindById(act.ElseChildren, actionId)
if IsObject(res2)
return res2
}
}
}
return ""
}
static InsertAction(rootActions, newAction, refActionId := "", position := "After") {
if refActionId == "" {
rootActions.Push(newAction)
return true
}
loc := this.FindById(rootActions, refActionId)
if !IsObject(loc) {
rootActions.Push(newAction)
return true
}
refAct := loc["Action"]
arr := loc["ParentArray"]
idx := loc["Index"]
if position == "Inside" && refAct.IsContainerAction() {
refAct.Children.Push(newAction)
return true
}
if position == "Before"
arr.InsertAt(idx, newAction)
else
arr.InsertAt(idx + 1, newAction)
return true
}
static DeleteById(rootActions, actionId) {
loc := this.FindById(rootActions, actionId)
if !IsObject(loc)
return false
loc["ParentArray"].RemoveAt(loc["Index"])
return true
}
static MoveUp(rootActions, actionId) {
loc := this.FindById(rootActions, actionId)
if !IsObject(loc) || loc["Index"] <= 1
return false
arr := loc["ParentArray"]
idx := loc["Index"]
tmp := arr[idx - 1]
arr[idx - 1] := arr[idx]
arr[idx] := tmp
return true
}
static MoveDown(rootActions, actionId) {
loc := this.FindById(rootActions, actionId)
if !IsObject(loc)
return false
arr := loc["ParentArray"]
idx := loc["Index"]
if idx >= arr.Length
return false
tmp := arr[idx + 1]
arr[idx + 1] := arr[idx]
arr[idx] := tmp
return true
}
; Validates structural AST rules & actionable Fix-It items (Sections 75, 97, 139)
static ValidateTree(rootActions, inLoop := false, problems := "", suggestionDensity := "Normal") {
if !IsObject(problems)
problems := []
for idx, act in rootActions {
if !act.Enabled
continue
if !ActionRegistry.IsKnown(act.Type)
problems.Push(Map("Severity", "Error", "ActionId", act.Id, "FixCode", "UnknownAction", "FixLabel", "Edit Step", "Message", "Unknown action type: " act.Type))
if (act.Type == "Logic_Break" || act.Type == "Logic_Continue") && !inLoop {
problems.Push(Map(
"Severity", "Error",
"ActionId", act.Id,
"FixCode", "DeleteInvalidLoopJump",
"FixLabel", "Remove Step",
"Message", act.Type == "Logic_Break" ? "'Break Loop' is placed outside of any Repeat/While loop." : "'Continue' is placed outside of any Repeat/While loop."
))
}
if ActionRegistry.UsesTarget(act.Type) && IsObject(act.Target) {
act.Target.ComputeReliability()
if act.Target.HealthStatus == StudioConstants.HealthBroken {
problems.Push(Map(
"Severity", "Error",
"ActionId", act.Id,
"FixCode", "RepairTarget",
"FixLabel", "Repair Target",
"Message", "Target '" act.Target.GetHumanLabel() "' is marked Broken from last run/test."
))
} else if act.Target.HealthStatus == StudioConstants.HealthAmbiguous || act.Target.LastMatchCount > 1 {
problems.Push(Map(
"Severity", "Warning",
"ActionId", act.Id,
"FixCode", "RefineAmbiguous",
"FixLabel", "Add Scope / Anchor",
"Message", "Ambiguous target (" act.Target.LastMatchCount " matches) on '" act.ComputeFriendlyDescription() "'. Add an Anchor or Container scope."
))
} else if act.Target.HealthStatus == StudioConstants.HealthNeedsRepair {
problems.Push(Map(
"Severity", "Warning",
"ActionId", act.Id,
"FixCode", "RepairTarget",
"FixLabel", "Repair Target",
"Message", "Target '" act.Target.GetHumanLabel() "' relied on fallback repeatedly (" act.Target.LastFallbackCount "x)."
))
}
if suggestionDensity != "Off" {
if act.Target.ReliabilityRating == StudioConstants.RelVeryFragile || act.Target.ReliabilityRating == StudioConstants.RelFragile {
problems.Push(Map(
"Severity", "Suggestion",
"ActionId", act.Id,
"FixCode", "UpgradeToUIA",
"FixLabel", "Upgrade Target",
"Message", "Fragile coordinate target in '" act.ComputeFriendlyDescription() "'. Click 'Fix / Apply' to upgrade to UI Automation."
))
}
}
}
if suggestionDensity == "Normal" && act.Type == "Wait_Duration" && act.Parameters.Get("DurationMs", 0) >= 2500 {
problems.Push(Map(
"Severity", "Suggestion",
"ActionId", act.Id,
"FixCode", "ConvertToSmartWait",
"FixLabel", "Convert to Smart Wait",
"Message", "Static delay (" act.Parameters.Get("DurationMs", 0) " ms) can be replaced with a condition-based Smart Wait."
))
}
if act.IsContainerAction() {
childLoop := inLoop || (act.Type == "Logic_Repeat" || act.Type == "Logic_ForEach" || act.Type == "Logic_While")
this.ValidateTree(act.Children, childLoop, problems, suggestionDensity)
if act.HasElse || act.Type == "Logic_TryCatch"
this.ValidateTree(act.ElseChildren, childLoop, problems, suggestionDensity)
}
}
return problems
}
}
; ==============================================================================
; MACRO MODEL & PROJECT MODEL
; ==============================================================================
class MacroModel {
IgnoredUpgrades := Map()
Id := ""
Name := "Main Macro"
Description := ""
Enabled := true
TriggerHotkey := ""
BrowserDefault := "Edge"
DefaultProfileAlias := "Default"
DefaultSessionName := "MainBrowser"
ProfilePolicy := "PreferConfiguredThenCurrent"
DefaultTargetPreset := "Balanced"
PlaybackSpeed := 1.0
DefaultTimeoutMs := 8000
DefaultRetryCount := 1
Variables := Map()
Actions := []
CreatedAt := ""
ModifiedAt := ""
__New(name := "Main Macro") {
this.Id := StudioUtils.GenId("mac")
this.Name := name
this.Variables := Map()
this.Actions := []
this.CreatedAt := StudioUtils.FormatTimestamp()
this.ModifiedAt := this.CreatedAt
}
ToMap() {
actList := []
for _, a in this.Actions
actList.Push(a.ToMap())
return Map(
"Id", this.Id,
"Name", this.Name,
"Description", this.Description,
"IgnoredUpgrades", this.IgnoredUpgrades,
"Enabled", this.Enabled ? JsonCodec.TrueVal : JsonCodec.FalseVal,
"TriggerHotkey", this.TriggerHotkey,
"BrowserDefault", this.BrowserDefault,
"DefaultProfileAlias", this.DefaultProfileAlias,
"DefaultSessionName", this.DefaultSessionName,
"ProfilePolicy", this.ProfilePolicy,
"DefaultTargetPreset", this.DefaultTargetPreset,
"PlaybackSpeed", this.PlaybackSpeed,
"DefaultTimeoutMs", this.DefaultTimeoutMs,
"DefaultRetryCount", this.DefaultRetryCount,
"Variables", this.Variables,
"Actions", actList,
"CreatedAt", this.CreatedAt,
"ModifiedAt", this.ModifiedAt
)
}
static FromMap(m) {
if !(m is Map)
throw ValueError("Each macro must be an object.")
if m.Has("Actions") && !(m["Actions"] is Array)
throw ValueError("Macro Actions must be an array.")
mac := MacroModel()
strProps := ["Id", "Name", "Description", "TriggerHotkey", "BrowserDefault", "DefaultProfileAlias", "DefaultSessionName", "ProfilePolicy", "DefaultTargetPreset", "CreatedAt", "ModifiedAt"]
for _, p in strProps {
if m.Has(p)
mac.%p% := String(m[p])
}
if m.Has("Enabled")
mac.Enabled := StudioUtils.ToBool(m["Enabled"])
if m.Has("PlaybackSpeed")
mac.PlaybackSpeed := Float(m["PlaybackSpeed"])
if m.Has("DefaultTimeoutMs")
mac.DefaultTimeoutMs := Integer(m["DefaultTimeoutMs"])
if m.Has("DefaultRetryCount")
mac.DefaultRetryCount := Integer(m["DefaultRetryCount"])
if m.Has("Variables") && (m["Variables"] is Map)
mac.Variables := StudioUtils.CloneMap(m["Variables"])
if m.Has("Actions") && (m["Actions"] is Array) {
mac.Actions := []
for _, am in m["Actions"]
mac.Actions.Push(ActionModel.FromMap(am))
}
if m.Has("IgnoredUpgrades") && m["IgnoredUpgrades"] is Map
mac.IgnoredUpgrades := StudioUtils.CloneMap(m["IgnoredUpgrades"])
return mac
}
}
class ProjectModel {
Id := ""
Name := "Untitled Project"
SchemaVersion := 2
FilePath := ""
IsDirty := false
DefaultBrowser := "Edge"
DefaultProfilePolicy := "PreferConfiguredThenCurrent"
SuggestionDensity := "Normal" ; Normal | Minimal | Off
Variables := Map()
ProfileAliases := Map() ; Logical Alias (e.g. "Work") -> Map("Browser", "Edge", "ProfileId", "Default", "FriendlyName", "Work")
ReusableTargets := Map() ; TargetId -> TargetModel
Macros := []
ActiveMacroId := ""
__New(name := "Untitled Project") {
this.Id := StudioUtils.GenId("prj")
this.Name := name
this.Variables := Map()
this.ProfileAliases := Map(
"Work", Map("Browser", "Edge", "ProfileId", "Default", "FriendlyName", "Work"),
"Personal", Map("Browser", "Chrome", "ProfileId", "Default", "FriendlyName", "Personal")
)
this.ReusableTargets := Map()
defaultMac := MacroModel("Main Macro")
this.Macros := [defaultMac]
this.ActiveMacroId := defaultMac.Id
}
GetActiveMacro() {
for _, m in this.Macros {
if m.Id == this.ActiveMacroId
return m
}
if this.Macros.Length > 0 {
this.ActiveMacroId := this.Macros[1].Id
return this.Macros[1]
}
m := MacroModel("Main Macro")
this.Macros.Push(m)
this.ActiveMacroId := m.Id
return m
}
FindMacroByName(name) {
for _, m in this.Macros {
if m.Name = name
return m
}
return ""
}
PromoteTargetToReusable(target, customName := "") {
if !IsObject(target)
return ""
rt := target.Clone()
rt.Id := StudioUtils.GenId("rtgt")
rt.IsReusable := true
if customName != ""
rt.Name := customName
else if rt.Name == ""
rt.Name := rt.Role " Target"
this.ReusableTargets[rt.Id] := rt
target.ReusableTargetId := rt.Id
this.IsDirty := true
return rt
}
FindReusableTargetUsages(reusableId) {
usages := []
for _, mac in this.Macros {
rows := WorkflowTree.Flatten(mac.Actions, true)
for _, r in rows {
act := r["Action"]
if act.ReusableTargetId == reusableId || (IsObject(act.Target) && act.Target.ReusableTargetId == reusableId)
usages.Push(Map("Macro", mac, "Action", act, "Step", r["StepNumber"]))
}
}
return usages
}
ToMap() {
macList := []
for _, m in this.Macros
macList.Push(m.ToMap())
rtMap := Map()
for k, rt in this.ReusableTargets
rtMap[k] := rt.ToMap()
return Map(
"SchemaVersion", this.SchemaVersion,
"Id", this.Id,
"Name", this.Name,
"DefaultBrowser", this.DefaultBrowser,
"DefaultProfilePolicy", this.DefaultProfilePolicy,
"SuggestionDensity", this.SuggestionDensity,
"ActiveMacroId", this.ActiveMacroId,
"Variables", this.Variables,
"ProfileAliases", this.ProfileAliases,
"ReusableTargets", rtMap,
"Macros", macList
)
}
static FromMap(m, filePath := "") {
if !(m is Map)
throw ValueError("Invalid project root object")
if !m.Has("Macros") || !(m["Macros"] is Array)
throw ValueError("Project file is missing a valid Macros array")
p := ProjectModel()
p.FilePath := filePath
p.IsDirty := false
for _, k in ["Id", "Name", "DefaultBrowser", "DefaultProfilePolicy", "SuggestionDensity", "ActiveMacroId"] {
if m.Has(k)
p.%k% := String(m[k])
}
schemaIn := m.Get("SchemaVersion", 1)
if !IsInteger(schemaIn) || schemaIn < 1
throw ValueError("Project SchemaVersion must be a positive integer.")
schemaIn := Integer(schemaIn)
if schemaIn > 2
throw ValueError("This project was saved by a newer version of Nichols Macro Studio (schema " schemaIn "). Update the app before opening it, so nothing is lost.")
p.SchemaVersion := 2 ; Auto-upgrade v1 -> v2 seamlessly
if m.Has("Variables") && (m["Variables"] is Map)
p.Variables := StudioUtils.CloneMap(m["Variables"])
if m.Has("ProfileAliases") && (m["ProfileAliases"] is Map)
p.ProfileAliases := StudioUtils.CloneMap(m["ProfileAliases"])
if m.Has("ReusableTargets") && (m["ReusableTargets"] is Map) {
p.ReusableTargets := Map()
for k, rtm in m["ReusableTargets"]
p.ReusableTargets[k] := TargetModel.FromMap(rtm)
}
p.Macros := []
for _, mm in m["Macros"]
p.Macros.Push(MacroModel.FromMap(mm))
if p.Macros.Length == 0 {
defMac := MacroModel("Main Macro")
p.Macros.Push(defMac)
p.ActiveMacroId := defMac.Id
}
return p
}
}
; ==============================================================================
; UNDO / REDO MANAGER (Section 106)
; ==============================================================================
class UndoRedoManager {
undoStack := []
redoStack := []
maxHistory := 50
onStateChanged := ""
RecordSnapshot(project, operationLabel := "Edit") {
if !IsObject(project)
return
snap := Map(
"Label", operationLabel,
"Timestamp", A_TickCount,
"Json", JsonCodec.Dump(project.ToMap(), "")
)
this.undoStack.Push(snap)
if this.undoStack.Length > this.maxHistory
this.undoStack.RemoveAt(1)
this.redoStack := []
project.IsDirty := true
this._Notify()
}
CanUndo() => this.undoStack.Length > 0
CanRedo() => this.redoStack.Length > 0
GetUndoLabel() => this.CanUndo() ? "Undo " this.undoStack[this.undoStack.Length]["Label"] : "Undo"
GetRedoLabel() => this.CanRedo() ? "Redo " this.redoStack[this.redoStack.Length]["Label"] : "Redo"
Undo(currentProject) {
if !this.CanUndo()
return ""
; Push current state to redoStack
lastSnap := this.undoStack.Pop()
this.redoStack.Push(Map(
"Label", lastSnap["Label"],
"Timestamp", A_TickCount,
"Json", JsonCodec.Dump(currentProject.ToMap(), "")
))
restored := ProjectModel.FromMap(JsonCodec.Load(lastSnap["Json"]), currentProject.FilePath)
restored.IsDirty := true
this._Notify()
return restored
}
Redo(currentProject) {
if !this.CanRedo()
return ""
nextSnap := this.redoStack.Pop()
this.undoStack.Push(Map(
"Label", nextSnap["Label"],
"Timestamp", A_TickCount,
"Json", JsonCodec.Dump(currentProject.ToMap(), "")
))
restored := ProjectModel.FromMap(JsonCodec.Load(nextSnap["Json"]), currentProject.FilePath)
restored.IsDirty := true
this._Notify()
return restored
}
Clear() {
this.undoStack := []
this.redoStack := []
this._Notify()
}
_Notify() {
if this.onStateChanged != "" && HasMethod(this.onStateChanged)
try this.onStateChanged.Call()
}
}
; ==============================================================================
; PART 3: VARIABLE STORE, VISUAL CONDITION ENGINE, & PERSISTENCE / RECOVERY
; ==============================================================================
class VariableStore {
projectVars := Map()
macroVars := Map()
runtimeVars := Map()
secretVars := Map() ; SecretName -> SecretValue (never exposed in plain watch/logs)
logger := ""
onVarsChanged := ""
__New(logger := "") {
this.logger := logger
this.projectVars := Map()
this.projectVars.CaseSense := "Off"
this.macroVars := Map()
this.macroVars.CaseSense := "Off"
this.runtimeVars := Map()
this.runtimeVars.CaseSense := "Off"
this.secretVars := Map()
this.secretVars.CaseSense := "Off"
}
LoadFromContext(project, macro := "") {
this.projectVars.Clear()
this.macroVars.Clear()
if IsObject(project) && (project.Variables is Map) {
for k, v in project.Variables
this.projectVars[String(k)] := v
}
if IsObject(macro) && (macro.Variables is Map) {
for k, v in macro.Variables
this.macroVars[String(k)] := v
}
this._Notify()
}
SetRuntime(name, value, scope := "Runtime") {
key := Trim(String(name), " $%{}")
if key == ""
return
if scope == "Project"
this.projectVars[key] := value
else if scope == "Macro"
this.macroVars[key] := value
else
this.runtimeVars[key] := value
this._Notify()
}
SetSecret(name, secretValue) {
key := Trim(String(name), " $%{}")
if key == ""
return
this.secretVars[key] := String(secretValue)
if IsObject(this.logger)
this.logger.RegisterSecretValue(String(secretValue))
this._Notify()
}
GetSecret(name) {
key := Trim(String(name), " $%{}")
if this.secretVars.Has(key)
return this.secretVars[key]
return ""
}
HasSecret(name) {
key := Trim(String(name), " $%{}")
return this.secretVars.Has(key) && this.secretVars[key] != ""
}
Get(name, defaultVal := "") {
key := Trim(String(name), " $%{}")
if key == ""
return defaultVal
; Built-in read-only system variables
switch StrUpper(key) {
case "CLIPBOARD", "A_CLIPBOARD":
try return A_Clipboard
catch
return ""
case "NOW", "A_NOW":
return FormatTime(A_Now, "yyyy-MM-dd HH:mm:ss")
case "DATE":
return FormatTime(A_Now, "yyyy-MM-dd")
case "TIME":
return FormatTime(A_Now, "HH:mm:ss")
case "TICKCOUNT", "A_TICKCOUNT":
return A_TickCount
case "DESKTOP", "A_DESKTOP":
return A_Desktop
case "TEMP", "A_TEMP":
return A_Temp
}
if this.runtimeVars.Has(key)
return this.runtimeVars[key]
if this.macroVars.Has(key)
return this.macroVars[key]
if this.projectVars.Has(key)
return this.projectVars[key]
return defaultVal
}
; Safe interpolation supporting ${VarName}, {VarName}, and %VarName% without arbitrary code eval
Interpolate(text) {
if !IsSet(text) || text == ""
return ""
s := String(text)
; Replace ${VarName} and {VarName} (excluding AHK send keys like {Enter}, {Tab}, {LCtrl down})
pos := 1
out := ""
while regPos := RegExMatch(s, "\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\{([A-Za-z_][A-Za-z0-9_]*)\}|%([A-Za-z_][A-Za-z0-9_]*)%", &m, pos) {
out .= SubStr(s, pos, regPos - pos)
token := m[0]
varName := m[1] != "" ? m[1] : (m[2] != "" ? m[2] : m[3])
isPlainBrace := (SubStr(token, 1, 1) == "{")
if isPlainBrace && this._IsSendKeyToken(varName) && !this._IsDefinedVar(varName) {
out .= token
} else {
out .= String(this.Get(varName, token))
}
pos := regPos + StrLen(token)
}
out .= SubStr(s, pos)
return out
}
_IsDefinedVar(name) {
k := Trim(String(name))
return this.runtimeVars.Has(k) || this.macroVars.Has(k) || this.projectVars.Has(k)
|| (StrUpper(k) == "CLIPBOARD" || StrUpper(k) == "NOW" || StrUpper(k) == "DATE" || StrUpper(k) == "TIME")
}
_IsSendKeyToken(name) {
static sendKeys := Map(
"ENTER", 1, "TAB", 1, "ESC", 1, "ESCAPE", 1, "SPACE", 1, "BACKSPACE", 1, "BS", 1,
"DELETE", 1, "DEL", 1, "INSERT", 1, "INS", 1, "HOME", 1, "END", 1, "PGUP", 1, "PGDN", 1,
"UP", 1, "DOWN", 1, "LEFT", 1, "RIGHT", 1, "F1", 1, "F2", 1, "F3", 1, "F4", 1,
"F5", 1, "F6", 1, "F7", 1, "F8", 1, "F9", 1, "F10", 1, "F11", 1, "F12", 1
)
return sendKeys.Has(StrUpper(name))
}
ExecuteOperation(varName, op, rawValue) {
val := this.Interpolate(rawValue)
cur := this.Get(varName, "")
switch op {
case "Assign":
this.SetRuntime(varName, val)
case "Append":
this.SetRuntime(varName, String(cur) . String(val))
case "Add":
n1 := IsNumber(cur) ? Number(cur) : 0
n2 := IsNumber(val) ? Number(val) : 0
this.SetRuntime(varName, n1 + n2)
case "Subtract":
n1 := IsNumber(cur) ? Number(cur) : 0
n2 := IsNumber(val) ? Number(val) : 0
this.SetRuntime(varName, n1 - n2)
case "Multiply":
n1 := IsNumber(cur) ? Number(cur) : 0
n2 := IsNumber(val) ? Number(val) : 1
this.SetRuntime(varName, n1 * n2)
default:
this.SetRuntime(varName, val)
}
}
GetAllWatchEntries() {
list := []
seen := Map()
seen.CaseSense := "Off"
for k, v in this.runtimeVars {
list.Push(Map("Name", k, "Scope", "Runtime", "Value", IsObject(v) ? JsonCodec.Dump(v) : String(v)))
seen[k] := true
}
for k, v in this.macroVars {
if !seen.Has(k) {
list.Push(Map("Name", k, "Scope", "Macro", "Value", IsObject(v) ? JsonCodec.Dump(v) : String(v)))
seen[k] := true
}
}
for k, v in this.projectVars {
if !seen.Has(k) {
list.Push(Map("Name", k, "Scope", "Project", "Value", IsObject(v) ? JsonCodec.Dump(v) : String(v)))
seen[k] := true
}
}
for k, _ in this.secretVars {
list.Push(Map("Name", k, "Scope", "Secret", "Value", "•••••••• (Protected)"))
}
return list
}
ClearRuntime() {
this.runtimeVars.Clear()
this._Notify()
}
_Notify() {
if this.onVarsChanged != "" && HasMethod(this.onVarsChanged)
try this.onVarsChanged.Call()
}
}
; ==============================================================================
; VISUAL CONDITION ENGINE (Section 74)
; Supports Variable comparisons, String ops, Regex, Window/Process, UIA, Browser,
; Image/Color, File, Clipboard, and compound AND / OR logic.
; ==============================================================================
class ConditionEngine {
varStore := ""
uiaEngine := ""
browserMgr := ""
imageEngine := ""
__New(varStore, uiaEngine := "", browserMgr := "", imageEngine := "") {
this.varStore := varStore
this.uiaEngine := uiaEngine
this.browserMgr := browserMgr
this.imageEngine := imageEngine
}
EvaluateActionCondition(act) {
p := act.Parameters
cType1 := p.Get("ConditionType", "VarEquals")
left1 := p.Get("LeftOperand", "")
op1 := p.Get("Operator", "Equals")
right1 := p.Get("RightOperand", "")
res1 := this.EvaluateSingle(cType1, left1, op1, right1, act.Target, act)
cType2 := p.Get("SecondConditionType", "None")
if cType2 == "" || cType2 == "None"
return res1
combineOp := StrUpper(p.Get("CombineOp", "AND"))
if combineOp == "AND" && !res1
return false
if combineOp == "OR" && res1
return true
left2 := p.Get("SecondLeft", "")
right2 := p.Get("SecondRight", "")
res2 := this.EvaluateSingle(cType2, left2, "Equals", right2, act.Target, act)
return combineOp == "OR" ? (res1 || res2) : (res1 && res2)
}
EvaluateSingle(condType, leftRaw, operator, rightRaw, target := "", act := "") {
leftVal := IsObject(this.varStore) ? this.varStore.Interpolate(leftRaw) : String(leftRaw)
; Also allow bare variable name lookup if leftRaw is a known variable name
if IsObject(this.varStore) && RegExMatch(Trim(String(leftRaw)), "^[A-Za-z_][A-Za-z0-9_]*$") {
if this.varStore._IsDefinedVar(Trim(String(leftRaw)))
leftVal := this.varStore.Get(Trim(String(leftRaw)), leftVal)
}
rightVal := IsObject(this.varStore) ? this.varStore.Interpolate(rightRaw) : String(rightRaw)
switch condType {
case "OCRTextPresent", "OCRTextAbsent":
p := StudioOCREngine.Defaults()
if IsObject(act)
for key, value in act.Parameters
p[key] := value is String && IsObject(this.varStore) ? this.varStore.Interpolate(value) : value
p["SearchText"] := rightVal != "" ? rightVal : leftVal
capture := StudioOCREngine.Capture(p,target)
found := StudioOCREngine.Matches(capture.result,p).Length > 0
return condType == "OCRTextAbsent" ? !found : found
case "VarEquals", "StringEquals":
return String(leftVal) = String(rightVal)
case "VarNotEquals":
return String(leftVal) != String(rightVal)
case "VarGreater":
n1 := IsNumber(leftVal) ? Number(leftVal) : 0
n2 := IsNumber(rightVal) ? Number(rightVal) : 0
return n1 > n2
case "VarLess":
n1 := IsNumber(leftVal) ? Number(leftVal) : 0
n2 := IsNumber(rightVal) ? Number(rightVal) : 0
return n1 < n2
case "StringContains":
return InStr(String(leftVal), String(rightVal)) > 0
case "StringStartsWith":
s1 := String(leftVal)
s2 := String(rightVal)
return SubStr(s1, 1, StrLen(s2)) = s2
case "StringEndsWith":
s1 := String(leftVal)
s2 := String(rightVal)
if StrLen(s2) == 0
return true
return SubStr(s1, -StrLen(s2)) = s2
case "RegexMatch":
try return RegExMatch(String(leftVal), String(rightVal)) > 0
catch
return false
case "WindowExists":
crit := leftVal != "" ? leftVal : (IsObject(target) && target.WinTitle != "" ? target.WinTitle : (IsObject(target) && target.WinExe != "" ? "ahk_exe " target.WinExe : ""))
return crit != "" && WinExist(crit) != 0
case "WindowActive":
crit := leftVal != "" ? leftVal : (IsObject(target) && target.WinTitle != "" ? target.WinTitle : (IsObject(target) && target.WinExe != "" ? "ahk_exe " target.WinExe : ""))
return crit != "" && WinActive(crit) != 0
case "ProcessExists":
return leftVal != "" && ProcessExist(leftVal) != 0
case "FileExists":
return leftVal != "" && FileExist(leftVal) != ""
case "ClipboardContains":
clip := ""
try clip := A_Clipboard
return InStr(clip, leftVal != "" ? leftVal : rightVal) > 0
case "UIAExists":
if IsObject(this.uiaEngine) && IsObject(target) {
r := this.uiaEngine.TestTarget(target)
return r["Found"]
}
return false
case "UIAEnabled":
if IsObject(this.uiaEngine) && IsObject(target) {
r := this.uiaEngine.TestTarget(target)
if r["Found"] && IsObject(r["Element"]) {
try return StudioUtils.ToBool(r["Element"].IsEnabled)
catch
return true
}
}
return false
case "UIATextContains":
if IsObject(this.uiaEngine) && IsObject(target) {
r := this.uiaEngine.TestTarget(target)
if r["Found"] && IsObject(r["Element"]) {
elTxt := ""
try elTxt := r["Element"].Name
if elTxt == ""
try elTxt := r["Element"].Value
return InStr(elTxt, rightVal != "" ? rightVal : leftVal) > 0
}
}
return false
case "BrowserSessionAvailable":
if IsObject(this.browserMgr) {
sessName := leftVal != "" ? leftVal : (IsObject(act) && act.BrowserSession != "" ? act.BrowserSession : "MainBrowser")
return this.browserMgr.IsSessionConnected(sessName)
}
return false
case "BrowserTabExists":
if IsObject(this.browserMgr) {
sessName := IsObject(act) && act.BrowserSession != "" ? act.BrowserSession : "MainBrowser"
return this.browserMgr.CheckTabExists(sessName, leftVal != "" ? leftVal : rightVal)
}
return false
case "URLContains":
if IsObject(this.browserMgr) {
sessName := IsObject(act) && act.BrowserSession != "" ? act.BrowserSession : "MainBrowser"
curUrl := this.browserMgr.GetSessionURL(sessName)
return InStr(curUrl, leftVal != "" ? leftVal : rightVal) > 0
}
return false
case "TitleContains":
if IsObject(this.browserMgr) {
sessName := IsObject(act) && act.BrowserSession != "" ? act.BrowserSession : "MainBrowser"
curTitle := this.browserMgr.GetSessionTitle(sessName)
return InStr(curTitle, leftVal != "" ? leftVal : rightVal) > 0
}
return false
case "ImageFound":
if IsObject(this.imageEngine) && IsObject(target) {
ir := target.BackupTargets.Length && IsObject(this.uiaEngine) ? this.uiaEngine.TestTarget(target) : this.imageEngine.SearchTargetImage(target)
return ir["Found"]
}
return false
case "ImageNotFound":
if IsObject(this.imageEngine) && IsObject(target) {
ir := target.BackupTargets.Length && IsObject(this.uiaEngine) ? this.uiaEngine.TestTarget(target) : this.imageEngine.SearchTargetImage(target)
return !ir["Found"]
}
return true
case "ColorFound":
if IsObject(this.imageEngine) && IsObject(target) {
cr := target.BackupTargets.Length && IsObject(this.uiaEngine) ? this.uiaEngine.TestTarget(target) : this.imageEngine.SearchTargetColor(target)
return cr["Found"]
}
return false
default:
return String(leftVal) = String(rightVal)
}
}
}
; ==============================================================================
; PERSISTENCE, SETTINGS, AUTOSAVE & CRASH RECOVERY ENGINE (Sections 107–110)
; ==============================================================================
; Search only explicit/local/conventional locations, never the whole drive.
class CompilerLocator {
static IsCompiler(path) {
if path == "" || !FileExist(path) || DirExist(path)
return false
SplitPath(path, &name)
return StrLower(name) == "ahk2exe.exe"
}
static InFolder(folder) {
if !DirExist(folder)
return ""
; Enumeration also supports deliberately case-sensitive Windows folders.
Loop Files folder "\*", "F" {
if StrLower(A_LoopFileName) == "ahk2exe.exe"
return A_LoopFileFullPath
}
Loop Files folder "\*", "D" {
if StrLower(A_LoopFileName) == "compiler" {
Loop Files A_LoopFileFullPath "\*", "F" {
if StrLower(A_LoopFileName) == "ahk2exe.exe"
return A_LoopFileFullPath
}
}
}
return ""
}
static Find(root := A_ScriptDir, installed := true) {
SplitPath(RTrim(root,"\/"), , &parent)
folders := [root, parent]
if installed {
SplitPath(A_AhkPath, , &runtimeDir)
SplitPath(runtimeDir, , &runtimeParent)
folders.Push(runtimeDir, runtimeParent, A_ProgramFiles "\AutoHotkey",
"C:\Program Files\AutoHotkey", "C:\Program Files (x86)\AutoHotkey")
}
seen := Map(), seen.CaseSense := false
for folder in folders {
if folder == "" || seen.Has(folder)
continue
seen[folder] := true
if found := this.InFolder(folder)
return found
}
return ""
}
static Resolve(preferred := "", root := A_ScriptDir, installed := true) {
preferred := Trim(preferred, " `t`r`n" Chr(34))
if this.IsCompiler(preferred)
return preferred
if DirExist(preferred) && (found := this.InFolder(preferred))
return found
return this.Find(root, installed)
}
static ForExport(preferred := "", root := A_ScriptDir, chooser := 0, installed := true) {
if found := this.Resolve(preferred, root, installed)
return found
folder := IsObject(chooser) ? chooser.Call(root) : DirSelect(root, 0,
"Ahk2Exe.exe was not found. Choose a folder to check (including its Compiler subfolder).")
return folder != "" ? this.InFolder(folder) : ""
}
}
class PersistenceEngine {
settings := Map()
__New() {
if !DirExist(StudioConstants.AppDataDir)
try DirCreate(StudioConstants.AppDataDir)
if !DirExist(StudioConstants.ManagedProfilesDir)
try DirCreate(StudioConstants.ManagedProfilesDir)
if !DirExist(StudioConstants.TempDir)
try DirCreate(StudioConstants.TempDir)
this.ResetSettingsToDefault()
this.LoadSettings()
}
ResetSettingsToDefault() {
this.settings := Map(
"WindowX", -1,
"WindowY", -1,
"WindowW", 1340,
"WindowH", 820,
"WindowMaximized", false,
"LayoutMode", "Auto", ; Auto, Wide, Standard, Compact
"LeftPaneWidth", 250,
"RightPaneWidth", 360,
"BottomPaneHeight", 210,
"ShowBottomPane", true,
"LastBottomTab", 1,
"InspectorAdvancedOpen", false,
"SuggestionDensity", "Normal",
"DefaultRecordingMode", "Simple", ; Simple, Advanced
"AdvancedClickMode", "PassivePrecision", ; PassivePrecision, HoldToRefine, ConfirmSignificantClicks
"PickerWheelCycles", true,
"PickerConfirmGesture", "Alt+Click",
"DefaultClickMode", "Coordinate Window",
"RecordingTimingMode", "Natural",
"RecordingFixedDelayMs", 100,
"RecordingScrollMode", "Consolidated",
"RecordingScrollGapMs", 250,
"NavPaneWidth", 210,
"InspectorPaneWidth", 370,
"SmoothPointer", true,
"RecordingGlow", true,
"RecordingGlowColor", "D92D20",
"PlaybackGlowColor", "189B50",
"PlaybackGlow", true,
"GlowDepth", 72, "GlowSoftness", 24, "GlowEdgeAlpha", 132,
"GlowPulseMs", 3600, "GlowPulseMin", 200,
"ShowHelpTips", true,
"AmbiguousTargetPolicy", "Warn", ; [NMS-PD-03] a setting needs a default here, or the loader ignores the saved value
"ConfirmRiskyActions", false,
"Hotkey_SelectTarget", "F6",
"ShowContextPanel", false,
"LogPanelHeight", 200,
"CommonActions", "|UIA_Click|Key_TypeText|Key_SendKeys|Mouse_Click|Mouse_Wheel|Wait_Duration|Wait_Element|Win_Activate|Win_Wait|Browser_Navigate|Logic_ForEach|Logic_Repeat|Logic_If|",
"HotkeyDefaultsVersion", 2,
"CoalesceTyping", true,
"AutoAnalyzeRecording", true,
"DefaultTimeoutMs", 8000,
"DefaultRetryCount", 1,
"DefaultPollingMs", 200,
"DefaultBrowser", "Edge",
"DefaultProfilePolicy", "PreferConfiguredThenCurrent",
"CompilerPath", this.DetectCompilerPath(),
"BaseExePath", A_AhkPath,
"Hotkey_Record", "F3",
"Hotkey_Play", "F1",
"Hotkey_Pause", "F7",
"Hotkey_Stop", "F8",
"Hotkey_FreezeRefine", "^+f",
"RecentFiles", [],
"DismissedRecoveryTimestamp", ""
)
}
ClampLayoutMetrics(clientW, clientH) {
lw := Integer(this.settings.Get("LeftPaneWidth", 250))
rw := Integer(this.settings.Get("RightPaneWidth", 360))
bh := Integer(this.settings.Get("BottomPaneHeight", 210))
if clientW <= 1080 {
lw := Min(Max(lw, 155), 195)
rw := Min(Max(rw, 250), 300)
} else if clientW <= 1280 {
lw := Min(Max(lw, 175), 220)
rw := Min(Max(rw, 280), 330)
} else {
lw := Min(Max(lw, 200), 320)
rw := Min(Max(rw, 320), 460)
}
if (clientW - lw - rw) < 320 {
rw := Max(240, clientW - lw - 320)
}
bh := Min(Max(bh, 130), Max(150, Round(clientH * 0.34)))
return Map("LeftW", lw, "RightW", rw, "BottomH", bh)
}
DetectCompilerPath() => CompilerLocator.Find()
LoadSettings() {
if !FileExist(StudioConstants.SettingsFile)
return
try {
raw := FileRead(StudioConstants.SettingsFile, "UTF-8")
loaded := JsonCodec.Load(raw)
if loaded is Map {
for k, v in loaded {
if this.settings.Has(k)
this.settings[k] := v
}
if loaded.Get("HotkeyDefaultsVersion", 1) < 2 && this.settings["Hotkey_Pause"] == "F2"
this.settings["Hotkey_Pause"] := "F7"
this.settings["HotkeyDefaultsVersion"] := 2
; Upgrade only the untouched old starter list, preserving custom favorites.
if this.settings["CommonActions"] == "|UIA_Click|Key_TypeText|Key_SendKeys|Mouse_Drag|Mouse_Wheel|Wait_Duration|Wait_Element|Win_Activate|Win_Wait|Browser_Navigate|Logic_ForEach|Logic_Repeat|Logic_If|"
this.settings["CommonActions"] := "|UIA_Click|Key_TypeText|Key_SendKeys|Mouse_Click|Mouse_Wheel|Wait_Duration|Wait_Element|Win_Activate|Win_Wait|Browser_Navigate|Logic_ForEach|Logic_Repeat|Logic_If|"
if this.settings["CommonActions"] == "|UIA_Click|Key_TypeText|Wait_Duration|Win_Activate|Browser_Navigate|Logic_ForEach|Logic_Repeat|Logic_If|"
this.settings["CommonActions"] := "|UIA_Click|Key_TypeText|Key_SendKeys|Mouse_Click|Mouse_Wheel|Wait_Duration|Wait_Element|Win_Activate|Win_Wait|Browser_Navigate|Logic_ForEach|Logic_Repeat|Logic_If|"
; Validate recent files and dimensions
if !(this.settings["RecentFiles"] is Array)
this.settings["RecentFiles"] := []
cleanRecent := []
for _, rf in this.settings["RecentFiles"] {
if rf != "" && FileExist(String(rf))
cleanRecent.Push(String(rf))
}
this.settings["RecentFiles"] := cleanRecent
if Integer(this.settings["WindowW"]) < 640
this.settings["WindowW"] := 1280
if Integer(this.settings["WindowH"]) < 480
this.settings["WindowH"] := 780
if !CompilerLocator.IsCompiler(this.settings["CompilerPath"])
this.settings["CompilerPath"] := CompilerLocator.Resolve(this.settings["CompilerPath"])
}
} catch {
; Corrupt settings file: fall back to safe defaults
this.ResetSettingsToDefault()
}
}
SaveSettings() {
try {
jsonText := JsonCodec.Dump(this.settings, " ")
StudioUtils.AtomicWriteFile(StudioConstants.SettingsFile, jsonText)
return true
} catch {
return false
}
}
UpdateSettings(values) {
previous := this.settings
candidate := previous.Clone()
for key, value in values
candidate[key] := value
this.settings := candidate
try {
if !this.SaveSettings()
throw Error("Settings could not be saved. Previous settings remain active.")
} catch as err {
this.settings := previous
throw err
}
; Existing UI and integrations retain this map; preserve its identity.
for key, value in values
previous[key] := value
this.settings := previous
return true
}
AddRecentFile(filePath) {
if filePath == ""
return
arr := this.settings["RecentFiles"]
newArr := [filePath]
for _, existing in arr {
if existing != filePath && newArr.Length < 10
newArr.Push(existing)
}
this.settings["RecentFiles"] := newArr
this.SaveSettings()
}
SaveProject(project, targetPath := "") {
if targetPath == ""
targetPath := project.FilePath
if targetPath == ""
throw ValueError("Target file path is required to save project.")
jsonText := JsonCodec.Dump(project.ToMap(), " ")
; Verify round-trip parse before replacing destination
verified := JsonCodec.Load(jsonText)
if !(verified is Map) || !verified.Has("Macros")
throw Error("Project serialization verification failed.")
StudioUtils.AtomicWriteFile(targetPath, jsonText)
project.FilePath := targetPath
SplitPath(targetPath, , , , &nameNoExt)
if project.Name == "Untitled Project" && nameNoExt != ""
project.Name := nameNoExt
project.IsDirty := false
this.AddRecentFile(targetPath)
this.ClearCrashRecoveryState()
return true
}
LoadProject(filePath) {
if !FileExist(filePath)
throw TargetError("Project file does not exist: " filePath)
raw := FileRead(filePath, "UTF-8")
data := JsonCodec.Load(raw)
prj := ProjectModel.FromMap(data, filePath)
prj.IsDirty := false
this.AddRecentFile(filePath)
return prj
}
WriteAutosave(project) {
if !IsObject(project) || !project.IsDirty
return false
try {
jsonText := JsonCodec.Dump(project.ToMap(), " ")
StudioUtils.AtomicWriteFile(StudioConstants.AutosaveFile, jsonText)
meta := Map(
"SessionActive", JsonCodec.TrueVal,
"Timestamp", StudioUtils.FormatTimestamp(),
"ProjectName", project.Name,
"OriginalFilePath", project.FilePath
)
StudioUtils.AtomicWriteFile(StudioConstants.RecoveryMetaFile, JsonCodec.Dump(meta, " "))
return true
} catch {
return false
}
}
MarkCleanExit() {
this.ClearCrashRecoveryState()
}
ClearCrashRecoveryState() {
try {
if FileExist(StudioConstants.RecoveryMetaFile)
FileDelete(StudioConstants.RecoveryMetaFile)
if FileExist(StudioConstants.AutosaveFile)
FileDelete(StudioConstants.AutosaveFile)
}
}
CheckForCrashRecovery() {
if !FileExist(StudioConstants.RecoveryMetaFile) || !FileExist(StudioConstants.AutosaveFile)
return ""
try {
meta := JsonCodec.Load(FileRead(StudioConstants.RecoveryMetaFile, "UTF-8"))
if !(meta is Map) || !meta.Has("Timestamp")
return ""
ts := String(meta["Timestamp"])
if ts != "" && ts == this.settings.Get("DismissedRecoveryTimestamp", "")
return ""
; Validate that autosave file is parseable and not corrupt
rawAuto := FileRead(StudioConstants.AutosaveFile, "UTF-8")
autoMap := JsonCodec.Load(rawAuto)
recoveredPrj := ProjectModel.FromMap(autoMap, meta.Get("OriginalFilePath", ""))
recoveredPrj.IsDirty := true
return Map(
"Project", recoveredPrj,
"Timestamp", ts,
"ProjectName", meta.Get("ProjectName", "Recovered Project"),
"OriginalFilePath", meta.Get("OriginalFilePath", "")
)
} catch {
; Corrupt autosave: never overwrite known-good project; discard corrupt recovery state
this.ClearCrashRecoveryState()
return ""
}
}
DismissCrashRecovery(timestamp) {
this.settings["DismissedRecoveryTimestamp"] := String(timestamp)
this.SaveSettings()
this.ClearCrashRecoveryState()
}
}
; ==============================================================================
; PART 4: OVERLAY MANAGER, IMAGE/PIXEL ENGINE, UIA TARGET ENGINE, & SELECTION MODE
; ==============================================================================
class OverlayManager {
borderGuis := []
secondaryGuis := []
crosshairGuis := []
hudGui := ""
hudTitleCtrl := ""
hudSubCtrl := ""
hudChainCtrl := ""
hudHintCtrl := ""
overlayHwnds := Map()
autoHideTimer := ""
lastPrimaryRect := Map("X", 0, "Y", 0, "W", 0, "H", 0)
__New() {
this.borderGuis := []
this.secondaryGuis := []
this.crosshairGuis := []
this.overlayHwnds := Map()
this._InitBorderGuis()
this._InitSecondaryGuis()
this._InitCrosshairGuis()
this._InitHudGui()
}
_InitBorderGuis() {
Loop 4 {
; WS_EX_TRANSPARENT (0x20) | WS_EX_NOACTIVATE (0x08000000) | WS_EX_TOOLWINDOW (0x80)
g := Gui("-Caption +AlwaysOnTop +ToolWindow +E0x08000020")
g.BackColor := "0078D4"
this.borderGuis.Push(g)
this.overlayHwnds[g.Hwnd] := true
}
}
_InitSecondaryGuis() {
Loop 4 {
g := Gui("-Caption +AlwaysOnTop +ToolWindow +E0x08000020")
g.BackColor := "A855F7"
this.secondaryGuis.Push(g)
this.overlayHwnds[g.Hwnd] := true
}
}
_InitCrosshairGuis() {
Loop 2 {
g := Gui("-Caption +AlwaysOnTop +ToolWindow +E0x08000020")
g.BackColor := "F59E0B"
this.crosshairGuis.Push(g)
this.overlayHwnds[g.Hwnd] := true
}
}
_InitHudGui() {
g := Gui("-Caption +AlwaysOnTop +ToolWindow +Border +E0x08000020")
g.BackColor := "18181B"
g.MarginX := 10
g.MarginY := 8
g.SetFont("s9 Bold c38BDF8", "Segoe UI")
this.hudTitleCtrl := g.Add("Text", "w420", "SELECTION LENS")
g.SetFont("s10 Bold cFFFFFF", "Segoe UI")
this.hudSubCtrl := g.Add("Text", "w420 y+3", "Point at any UI or Web element")
g.SetFont("s8 Norm cA1A1AA", "Segoe UI")
this.hudChainCtrl := g.Add("Text", "w420 y+3 r2", "")
g.SetFont("s8 Norm c71717A", "Segoe UI")
this.hudHintCtrl := g.Add("Text", "w420 y+2", "F6 / Alt+Click: Select | ↑/↓: Depth | 1-7: Filter | Ctrl+Shift+F: Freeze | Esc: Cancel")
this.hudGui := g
this.overlayHwnds[g.Hwnd] := true
}
IsOverlayHwnd(hwnd) {
return this.overlayHwnds.Has(hwnd)
}
ShowHighlightRect(x, y, w, h, colorHex := "0078D4", durationMs := 0, thickness := 3) {
if w <= 0 || h <= 0 {
this.HideHighlight()
return
}
this.lastPrimaryRect := Map("X", x, "Y", y, "W", w, "H", h)
cleanColor := RegExReplace(colorHex, "^(0x|#)", "")
for _, g in this.borderGuis
g.BackColor := cleanColor
; Top, Bottom, Left, Right strips (hollow center so clicks/hovers never hit the overlay)
this.borderGuis[1].Show(Format("NA x{1} y{2} w{3} h{4}", x, y, w, thickness))
this.borderGuis[2].Show(Format("NA x{1} y{2} w{3} h{4}", x, y + h - thickness, w, thickness))
this.borderGuis[3].Show(Format("NA x{1} y{2} w{3} h{4}", x, y, thickness, h))
this.borderGuis[4].Show(Format("NA x{1} y{2} w{3} h{4}", x + w - thickness, y, thickness, h))
if this.autoHideTimer != "" {
SetTimer(this.autoHideTimer, 0)
this.autoHideTimer := ""
}
if durationMs > 0 {
this.autoHideTimer := ObjBindMethod(this, "HideHighlight")
SetTimer(this.autoHideTimer, -durationMs)
}
}
ShowSecondaryRect(x, y, w, h, colorHex := "A855F7", thickness := 2) {
if w <= 0 || h <= 0 {
this.HideSecondaryRect()
return
}
cleanColor := RegExReplace(colorHex, "^(0x|#)", "")
for _, g in this.secondaryGuis
g.BackColor := cleanColor
this.secondaryGuis[1].Show(Format("NA x{1} y{2} w{3} h{4}", x, y, w, thickness))
this.secondaryGuis[2].Show(Format("NA x{1} y{2} w{3} h{4}", x, y + h - thickness, w, thickness))
this.secondaryGuis[3].Show(Format("NA x{1} y{2} w{3} h{4}", x, y, thickness, h))
this.secondaryGuis[4].Show(Format("NA x{1} y{2} w{3} h{4}", x + w - thickness, y, thickness, h))
}
HideSecondaryRect() {
for _, g in this.secondaryGuis {
try g.Hide()
}
}
ShowCrosshair(cx, cy, colorHex := "F59E0B", size := 14) {
cleanColor := RegExReplace(colorHex, "^(0x|#)", "")
for _, g in this.crosshairGuis
g.BackColor := cleanColor
half := size // 2
this.crosshairGuis[1].Show(Format("NA x{1} y{2} w{3} h2", cx - half, cy - 1, size))
this.crosshairGuis[2].Show(Format("NA x{1} y{2} w2 h{3}", cx - 1, cy - half, size))
}
HideCrosshair() {
for _, g in this.crosshairGuis {
try g.Hide()
}
}
ShowHud(cursorX, cursorY, headerText, targetText, chainText := "", hintText := "") {
try {
this.hudTitleCtrl.Value := headerText
this.hudSubCtrl.Value := targetText
this.hudChainCtrl.Value := chainText
if hintText != ""
this.hudHintCtrl.Value := hintText
vd := StudioUtils.GetVirtualDesktopBounds()
hudW := 440
hudH := 116
pr := this.lastPrimaryRect
hx := cursorX + 24
hy := cursorY + 24
; Avoid covering the highlighted target bounding box (vNext Section 31)
if pr["W"] > 0 && pr["H"] > 0 {
if (pr["Y"] + pr["H"] + hudH + 16 <= vd.B) {
hy := Max(cursorY + 20, pr["Y"] + pr["H"] + 10)
} else if (pr["Y"] - hudH - 14 >= vd.Y) {
hy := pr["Y"] - hudH - 12
}
}
if hx + hudW > vd.R - 10
hx := cursorX - hudW - 18
if hy + hudH > vd.B - 10
hy := cursorY - hudH - 18
if hx < vd.X + 4
hx := vd.X + 4
if hy < vd.Y + 4
hy := vd.Y + 4
this.hudGui.Show(Format("NA x{1} y{2} AutoSize", hx, hy))
}
}
HideHighlight() {
for _, g in this.borderGuis {
try g.Hide()
}
this.HideSecondaryRect()
this.HideCrosshair()
this.lastPrimaryRect := Map("X", 0, "Y", 0, "W", 0, "H", 0)
}
HideHud() {
try this.hudGui.Hide()
}
HideAll() {
if this.autoHideTimer != "" {
try SetTimer(this.autoHideTimer, 0)
this.autoHideTimer := ""
}
this.HideHighlight()
this.HideHud()
}
DestroyAll() {
this.HideAll()
for _, g in this.borderGuis {
try g.Destroy()
}
for _, g in this.secondaryGuis {
try g.Destroy()
}
for _, g in this.crosshairGuis {
try g.Destroy()
}
try this.hudGui.Destroy()
}
}
; ==============================================================================
; IMAGE & PIXEL AUTOMATION ENGINE (Sections 35 & 36)
; Supports GDI/BMP screen region capture, portable Base64 storage, ImageSearch,
; PixelGetColor, PixelSearch, RGB/BGR handling, and region highlighting.
; ==============================================================================
class ImagePixelEngine {
overlayMgr := ""
__New(overlayMgr := "") {
this.overlayMgr := overlayMgr
}
; Captures a screen rectangle (x, y, w, h) to a 24-bit BMP file and returns Base64 string
CaptureScreenRegionToBmp(x, y, w, h, outFilePath := "") {
if w <= 0 || h <= 0
throw ValueError("Capture region width and height must be positive.")
if outFilePath == ""
outFilePath := StudioConstants.TempDir "\capture_" A_TickCount "_" Random(1000, 9999) ".bmp"
SplitPath(outFilePath, , &dir)
if dir != "" && !DirExist(dir)
DirCreate(dir)
hdcScreen := DllCall("User32\GetDC", "Ptr", 0, "Ptr")
hdcMem := DllCall("Gdi32\CreateCompatibleDC", "Ptr", hdcScreen, "Ptr")
; Create 24-bit DIB Section
bi := Buffer(40, 0)
NumPut("UInt", 40, bi, 0) ; biSize
NumPut("Int", w, bi, 4) ; biWidth
NumPut("Int", h, bi, 8) ; biHeight (bottom-up)
NumPut("UShort", 1, bi, 12) ; biPlanes
NumPut("UShort", 24, bi, 14) ; biBitCount
NumPut("UInt", 0, bi, 16) ; BI_RGB
stride := ((w * 3 + 3) // 4) * 4
imgSize := stride * h
NumPut("UInt", imgSize, bi, 20)
ppvBits := 0
hbm := DllCall("Gdi32\CreateDIBSection", "Ptr", hdcScreen, "Ptr", bi, "UInt", 0, "Ptr*", &ppvBits, "Ptr", 0, "UInt", 0, "Ptr")
if !hbm {
DllCall("Gdi32\DeleteDC", "Ptr", hdcMem)
DllCall("User32\ReleaseDC", "Ptr", 0, "Ptr", hdcScreen)
throw Error("Failed to create DIB section for image capture.")
}
obm := DllCall("Gdi32\SelectObject", "Ptr", hdcMem, "Ptr", hbm, "Ptr")
; SRCCOPY = 0x00CC0020 | CAPTUREBLT = 0x40000000
DllCall("Gdi32\BitBlt", "Ptr", hdcMem, "Int", 0, "Int", 0, "Int", w, "Int", h, "Ptr", hdcScreen, "Int", x, "Int", y, "UInt", 0x40CC0020)
DllCall("Gdi32\GdiFlush")
; Build BMP file buffer (14-byte BITMAPFILEHEADER + 40-byte BITMAPINFOHEADER + pixel data)
totalBytes := 54 + imgSize
bmpBuf := Buffer(totalBytes, 0)
NumPut("UShort", 0x4D42, bmpBuf, 0) ; 'BM'
NumPut("UInt", totalBytes, bmpBuf, 2)
NumPut("UInt", 54, bmpBuf, 10)
DllCall("ntdll\RtlMoveMemory", "Ptr", bmpBuf.Ptr + 14, "Ptr", bi.Ptr, "UPtr", 40)
DllCall("ntdll\RtlMoveMemory", "Ptr", bmpBuf.Ptr + 54, "Ptr", ppvBits, "UPtr", imgSize)
; Cleanup GDI handles in deterministic order
DllCall("Gdi32\SelectObject", "Ptr", hdcMem, "Ptr", obm)
DllCall("Gdi32\DeleteObject", "Ptr", hbm)
DllCall("Gdi32\DeleteDC", "Ptr", hdcMem)
DllCall("User32\ReleaseDC", "Ptr", 0, "Ptr", hdcScreen)
; Write BMP file
f := FileOpen(outFilePath, "w")
f.RawWrite(bmpBuf, totalBytes)
f.Close()
b64 := this.BufferToBase64(bmpBuf)
return Map("FilePath", outFilePath, "Base64", b64, "Width", w, "Height", h)
}
BufferToBase64(buf) {
if buf.Size == 0
return ""
chars := 0
; CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF = 0x40000001
DllCall("Crypt32\CryptBinaryToStringW", "Ptr", buf.Ptr, "UInt", buf.Size, "UInt", 0x40000001, "Ptr", 0, "UInt*", &chars)
outBuf := Buffer(chars * 2, 0)
DllCall("Crypt32\CryptBinaryToStringW", "Ptr", buf.Ptr, "UInt", buf.Size, "UInt", 0x40000001, "Ptr", outBuf.Ptr, "UInt*", &chars)
return StrGet(outBuf, "UTF-16")
}
Base64ToBuffer(b64Str) {
if b64Str == ""
return Buffer(0)
bytes := 0
; CRYPT_STRING_BASE64 = 0x01
DllCall("Crypt32\CryptStringToBinaryW", "Str", b64Str, "UInt", 0, "UInt", 1, "Ptr", 0, "UInt*", &bytes, "Ptr", 0, "Ptr", 0)
buf := Buffer(bytes, 0)
DllCall("Crypt32\CryptStringToBinaryW", "Str", b64Str, "UInt", 0, "UInt", 1, "Ptr", buf.Ptr, "UInt*", &bytes, "Ptr", 0, "Ptr", 0)
return buf
}
GetExecutableImagePath(target) {
if !IsObject(target)
return ""
if target.CapturedImagePath != "" && FileExist(target.CapturedImagePath)
return target.CapturedImagePath
if target.CapturedImageBase64 != "" {
if !DirExist(StudioConstants.TempDir)
DirCreate(StudioConstants.TempDir)
cacheFile := StudioConstants.TempDir "\img_" target.Id ".bmp"
if !FileExist(cacheFile) {
buf := this.Base64ToBuffer(target.CapturedImageBase64)
if buf.Size > 0 {
f := FileOpen(cacheFile, "w")
f.RawWrite(buf, buf.Size)
f.Close()
}
}
if FileExist(cacheFile)
return cacheFile
}
return ""
}
ResolveSearchBounds(target) {
vd := StudioUtils.GetVirtualDesktopBounds()
x1 := vd.X, y1 := vd.Y, x2 := vd.R, y2 := vd.B
if !IsObject(target) || !IsObject(target.Scope)
return Map("X1", x1, "Y1", y1, "X2", x2, "Y2", y2)
sc := target.Scope
if sc.ScopeType == "Region" && sc.RegionW > 0 && sc.RegionH > 0 {
rx := sc.RegionX
ry := sc.RegionY
if sc.RelativeToWindow {
if target.WinExe == "" || !(hwnd := WinExist("ahk_exe " target.WinExe))
throw TargetError("The region's reference window is unavailable.",, "WrongScope")
WinGetPos(&wx, &wy, , , "ahk_id " hwnd)
rx += wx
ry += wy
}
return Map("X1", rx, "Y1", ry, "X2", rx + sc.RegionW, "Y2", ry + sc.RegionH)
}
if sc.ScopeType == "ActiveWindow" && (hwnd := WinExist("A")) {
WinGetPos(&wx, &wy, &ww, &wh, "ahk_id " hwnd)
if ww > 0 && wh > 0
return Map("X1", wx, "Y1", wy, "X2", wx + ww, "Y2", wy + wh)
}
if sc.ScopeType == "SpecificWindow" {
crit := sc.WinExe != "" ? "ahk_exe " sc.WinExe : sc.WinTitle
if crit != "" && (hwnd := WinExist(crit)) {
WinGetPos(&wx, &wy, &ww, &wh, "ahk_id " hwnd)
if ww > 0 && wh > 0
return Map("X1", wx, "Y1", wy, "X2", wx + ww, "Y2", wy + wh)
}
throw TargetError("The specified search window is unavailable or has no usable bounds.",, "WrongScope")
}
if sc.ScopeType == "ActiveWindow"
throw TargetError("The active search window is unavailable or has no usable bounds.",, "WrongScope")
if sc.ScopeType == "Region"
throw ValueError("Search region width and height must be positive.")
return Map("X1", x1, "Y1", y1, "X2", x2, "Y2", y2)
}
SearchTargetImage(target) {
t0 := A_TickCount
imgPath := this.GetExecutableImagePath(target)
if imgPath == "" || !FileExist(imgPath)
return Map("Found", false, "X", 0, "Y", 0, "Reason", "StaleReference", "Message", "Captured image asset is missing.", "DurationMs", 0)
bounds := this.ResolveSearchBounds(target)
variation := Clamp(Integer(target.ImageVariation), 0, 255)
opts := "*" variation
if target.TransColor != ""
opts .= " *Trans" RegExReplace(target.TransColor, "^(0x|#)", "")
foundX := 0, foundY := 0
try {
ok := ImageSearch(&foundX, &foundY, bounds["X1"], bounds["Y1"], bounds["X2"], bounds["Y2"], opts " " imgPath)
if ok {
w := target.BoundingW > 0 ? target.BoundingW : 24
h := target.BoundingH > 0 ? target.BoundingH : 24
cx := foundX + (w // 2) + target.OffsetX
cy := foundY + (h // 2) + target.OffsetY
return Map(
"Found", true,
"X", cx,
"Y", cy,
"TopLeftX", foundX,
"TopLeftY", foundY,
"W", w,
"H", h,
"DurationMs", A_TickCount - t0,
"Message", Format("Image matched at ({1}, {2})", foundX, foundY)
)
}
} catch as err {
return Map("Found", false, "X", 0, "Y", 0, "Message", "ImageSearch error: " err.Message, "DurationMs", A_TickCount - t0)
}
return Map("Found", false, "X", 0, "Y", 0, "Reason", "NotFound", "Message", "Image not found in search region.", "DurationMs", A_TickCount - t0)
}
GetPixelColorInfo(sx, sy) {
hex := "0x000000"
try hex := PixelGetColor(sx, sy) ; In AHK v2, PixelGetColor returns RGB "0xRRGGBB" by default
val := Integer(hex)
r := (val >> 16) & 0xFF
g := (val >> 8) & 0xFF
b := val & 0xFF
return Map(
"Hex", Format("0x{:06X}", val),
"HTML", Format("#{:06X}", val),
"R", r,
"G", g,
"B", b,
"RGBText", Format("RGB({1}, {2}, {3})", r, g, b)
)
}
SearchTargetColor(target) {
t0 := A_TickCount
bounds := this.ResolveSearchBounds(target)
colorHex := target.CapturedColorHex
if SubStr(colorHex, 1, 1) == "#"
colorHex := "0x" SubStr(colorHex, 2)
else if SubStr(colorHex, 1, 2) != "0x" && SubStr(colorHex, 1, 2) != "0X"
colorHex := "0x" colorHex
colorInt := Integer(colorHex)
tol := Clamp(Integer(target.ColorTolerance), 0, 255)
foundX := 0, foundY := 0
try {
ok := PixelSearch(&foundX, &foundY, bounds["X1"], bounds["Y1"], bounds["X2"], bounds["Y2"], colorInt, tol)
if ok {
return Map(
"Found", true,
"X", foundX + target.OffsetX,
"Y", foundY + target.OffsetY,
"DurationMs", A_TickCount - t0,
"Message", Format("Color {1} matched at ({2}, {3})", target.CapturedColorHex, foundX, foundY)
)
}
} catch as err {
return Map("Found", false, "X", 0, "Y", 0, "Message", "PixelSearch error: " err.Message, "DurationMs", A_TickCount - t0)
}
return Map("Found", false, "X", 0, "Y", 0, "Reason", "NotFound", "Message", "Color not found in search region.", "DurationMs", A_TickCount - t0)
}
}
Clamp(val, minVal, maxVal) => (val < minVal ? minVal : (val > maxVal ? maxVal : val))
; ==============================================================================
; UIA TARGET ENGINE (Sections 20–35, 38)
; Candidate Discovery, Smart Promotion, Multi-Strategy Resolver, & UIA Executor
; ==============================================================================
class UIATargetEngine {
overlayMgr := ""
imageEngine := ""
browserMgr := ""
__New(overlayMgr := "", imageEngine := "", browserMgr := "") {
this.overlayMgr := overlayMgr
this.imageEngine := imageEngine
this.browserMgr := browserMgr
}
static IsBrowserExecutable(exeName) {
e := StrLower(Trim(exeName))
return e == "chrome.exe" || e == "msedge.exe" || e == "firefox.exe" || e == "brave.exe" || e == "vivaldi.exe"
}
static BrowserTypeFromExe(exeName) {
switch StrLower(Trim(exeName)) {
case "chrome.exe": return "Chrome"
case "msedge.exe": return "Edge"
case "firefox.exe": return "Firefox"
case "brave.exe": return "Brave"
case "vivaldi.exe": return "Vivaldi"
default: return ""
}
}
static FriendlyRoleFromControlType(ctName) {
switch ctName {
case "Edit": return "Textbox"
case "CheckBox": return "Checkbox"
case "Hyperlink": return "Link"
case "TabItem": return "Tab"
case "Document": return "Page"
default: return ctName != "" ? ctName : "Element"
}
}
static IsInteractiveRole(ctName, patterns := "") {
static interactiveTypes := Map(
"Button", 1, "SplitButton", 1, "Edit", 1, "CheckBox", 1, "RadioButton", 1,
"ComboBox", 1, "Hyperlink", 1, "MenuItem", 1, "TabItem", 1, "ListItem", 1,
"TreeItem", 1, "Slider", 1, "ScrollBar", 1, "DataItem", 1
)
if interactiveTypes.Has(ctName)
return true
if IsObject(patterns) {
for _, p in patterns {
if p == "Invoke" || p == "Value" || p == "Toggle" || p == "SelectionItem" || p == "ExpandCollapse"
return true
}
}
return false
}
static IsContainerRole(ctName) {
static containerTypes := Map(
"Group", 1, "Pane", 1, "Custom", 1, "Table", 1, "List", 1, "Tree", 1,
"DataGrid", 1, "ToolBar", 1, "MenuBar", 1, "Tab", 1
)
return containerTypes.Has(ctName)
}
; Inspects a point (sx, sy) and builds the full ordered Candidate Hierarchy + Recommended Target
DiscoverCandidatesAtPoint(sx, sy, studioHwnd := 0) {
result := Map(
"ScreenX", sx,
"ScreenY", sy,
"Hwnd", 0,
"WinTitle", "",
"WinClass", "",
"WinExe", "",
"UIPIWarning", "",
"IsBrowser", false,
"BrowserType", "",
"IsWebContent", false,
"Candidates", [], ; Array of Map("Label", "Role", "Target", "IsRecommended", "Rect", "ParentRect", "Kind")
"RecommendationReason", "No target evidence available",
"RecommendedIndex", 0,
"RecommendedTarget", ""
)
; Find root window under point (sx, sy)
hwnd := 0
try {
pt64 := (sx & 0xFFFFFFFF) | ((sy & 0xFFFFFFFF) << 32)
hChild := DllCall("User32\WindowFromPoint", "Int64", pt64, "Ptr")
if hChild
hwnd := DllCall("User32\GetAncestor", "Ptr", hChild, "UInt", 2, "Ptr")
}
if !hwnd {
try {
MouseGetPos(, , &mWin)
hwnd := mWin
}
}
if !hwnd
try hwnd := WinExist("A")
if !hwnd
try hwnd := DllCall("User32\GetDesktopWindow", "Ptr")
if !hwnd || (studioHwnd && hwnd == studioHwnd) || (IsObject(this.overlayMgr) && this.overlayMgr.IsOverlayHwnd(hwnd)) {
return result
}
winTitle := "", winClass := "", winExe := ""
try winTitle := WinGetTitle("ahk_id " hwnd)
try winClass := WinGetClass("ahk_id " hwnd)
try winExe := WinGetProcessName("ahk_id " hwnd)
uipi := StudioUtils.CheckUIPIWarning(hwnd)
result["Hwnd"] := hwnd
result["WinTitle"] := winTitle
result["WinClass"] := winClass
result["WinExe"] := winExe
result["UIPIWarning"] := uipi
isBrowser := UIATargetEngine.IsBrowserExecutable(winExe)
bType := UIATargetEngine.BrowserTypeFromExe(winExe)
result["IsBrowser"] := isBrowser
result["BrowserType"] := bType
rel := StudioUtils.ScreenToWindowRelative(sx, sy, hwnd)
winRect := Map("X", sx - 20, "Y", sy - 12, "W", 40, "H", 24)
try {
WinGetPos(&wx, &wy, &ww, &wh, "ahk_id " hwnd)
winRect := Map("X", wx, "Y", wy, "W", ww, "H", wh)
}
; Walk UIA element chain from point up to window
uiaChain := []
hasDocumentAncestor := false
docName := ""
try {
el := ""
try el := UIA.SmallestElementFromPoint(sx, sy)
catch {
try el := UIA.ElementFromPoint(sx, sy)
}
cur := el
visited := Map()
depth := 0
while IsObject(cur) && depth < 12 {
if this.IsCancelled()
return result
depth += 1
info := this._ExtractElementInfo(cur)
if info["ControlType"] == "Document" {
hasDocumentAncestor := true
if docName == "" && info["Name"] != ""
docName := info["Name"]
}
key := info["ControlType"] "|" info["Name"] "|" info["AutomationId"] "|" info["Rect"]["X"] "," info["Rect"]["Y"]
if !visited.Has(key) {
visited[key] := true
uiaChain.Push(info)
}
if info["ControlType"] == "Window" || (info["Hwnd"] == hwnd && depth > 1)
break
nextParent := ""
try nextParent := UIA.TreeWalkerTrue.GetParentElement(cur)
if !IsObject(nextParent)
break
cur := nextParent
}
}
result["IsWebContent"] := isBrowser && hasDocumentAncestor
; Resolve browser session/profile metadata if this is a browser window
profAlias := ""
sessName := ""
if isBrowser && IsObject(this.browserMgr) {
bMeta := this.browserMgr.IdentifyBrowserWindowMeta(hwnd, winExe)
profAlias := bMeta["ProfileAlias"]
sessName := bMeta["SessionName"]
}
; Construct candidate TargetModels from the UIA chain (Child -> Parent -> Container -> Document -> Window)
candidates := []
recommendedIdx := 0
for idx, info in uiaChain {
parentInfo := (idx < uiaChain.Length) ? uiaChain[idx + 1] : Map("Name", "", "ControlType", "", "Rect", winRect)
t := this._BuildTargetFromElementInfo(info, parentInfo, sx, sy, rel, hwnd, winTitle, winClass, winExe, isBrowser, bType, hasDocumentAncestor, profAlias, sessName, docName)
candLabel := t.GetHumanLabel()
candidates.Push(Map(
"Label", candLabel,
"Role", t.Role,
"ControlType", info["ControlType"],
"Target", t,
"IsRecommended", false,
"Rect", info["Rect"],
"ParentRect", parentInfo.Get("Rect", winRect),
"Kind", t.TargetKind
))
}
recommendation := this.RecommendCandidates(candidates)
recommendedIdx := recommendation["Index"]
result["RecommendationReason"] := recommendation["Reason"]
; Add Visual Image candidate
imgTarget := TargetModel("Visual Region at (" sx ", " sy ")", "Image", "Image")
imgTarget.ScreenX := sx, imgTarget.ScreenY := sy
imgTarget.WinRelX := rel.WinX, imgTarget.WinRelY := rel.WinY
imgTarget.WinTitle := winTitle, imgTarget.WinClass := winClass, imgTarget.WinExe := winExe, imgTarget.WinHwnd := hwnd
imgTarget.BoundingW := 48, imgTarget.BoundingH := 32
imgTarget.ComputeReliability()
candidates.Push(Map(
"Label", "Image — Visual Target at (" sx ", " sy ")",
"Role", "Image",
"ControlType", "Image",
"Target", imgTarget,
"IsRecommended", false,
"Rect", Map("X", sx - 24, "Y", sy - 16, "W", 48, "H", 32),
"ParentRect", winRect,
"Kind", "Image"
))
; Add Window-Relative Coordinate candidate
coordTarget := TargetModel(Format("({1}, {2})", rel.WinX, rel.WinY), "Coordinate", "WindowRelative")
coordTarget.ScreenX := sx, coordTarget.ScreenY := sy
coordTarget.WinRelX := rel.WinX, coordTarget.WinRelY := rel.WinY
coordTarget.ClientX := rel.ClientX, coordTarget.ClientY := rel.ClientY
coordTarget.WinTitle := winTitle, coordTarget.WinClass := winClass, coordTarget.WinExe := winExe, coordTarget.WinHwnd := hwnd
coordTarget.ComputeReliability()
candidates.Push(Map(
"Label", Format("Coordinate — Window ({1}, {2})", rel.WinX, rel.WinY),
"Role", "Coordinate",
"ControlType", "Coordinate",
"Target", coordTarget,
"IsRecommended", false,
"Rect", Map("X", sx - 12, "Y", sy - 12, "W", 24, "H", 24),
"ParentRect", winRect,
"Kind", "WindowRelative"
))
if recommendedIdx > 0 && recommendedIdx <= candidates.Length {
candidates[recommendedIdx]["IsRecommended"] := true
result["RecommendedTarget"] := candidates[recommendedIdx]["Target"]
}
result["Candidates"] := candidates
result["RecommendedIndex"] := recommendedIdx
return result
}
RecommendCandidates(candidates) {
started := A_TickCount
for idx, c in candidates {
if this.IsCancelled()
return Map("Index", 0, "Reason", "Selection canceled")
if idx > 12 || A_TickCount - started > 1500
return Map("Index", 0, "Reason", "Recommendation budget exceeded")
t := c["Target"], ps := t.PrimarySelector
if !UIATargetEngine.IsInteractiveRole(c["ControlType"]) || UIATargetEngine.IsContainerRole(c["ControlType"])
continue
if StrLower(t.WinExe) == "explorer.exe" && (ps.ControlType == "ListItem" || ps.ControlType == "DataItem" || ps.ControlType == "TreeItem")
return Map("Index", 0, "Reason", "Explorer file identity is not verified. Choose an explicit target; same-label replacement cannot be detected.")
if ps.ElementName == "" && (ps.AutomationId == "" || TargetModel.IsVolatileAutomationId(ps.AutomationId))
return Map("Index", 0, "Reason", "Intended object lacks stable identity; choose an explicit alternative")
copy := t.Clone()
copy.ManualBackups := true
copy.BackupTargets := []
resolved := this.TestTargetCore(copy)
if this.IsCancelled() || A_TickCount - started > 1500
return Map("Index", 0, "Reason", "Recommendation canceled or timed out")
if !resolved["Found"] || resolved["MatchCount"] != 1
return Map("Index", 0, "Reason", "Fresh resolution: " resolved["Message"])
c["Rect"] := resolved["Rect"]
return Map("Index", idx, "Reason", "Named or identified actionable object; fresh resolution found one visible match in recorded scope. Click behavior is unchanged.")
}
return Map("Index", 0, "Reason", "No uniquely identifiable actionable object; choose an explicit alternative")
}
_ExtractElementInfo(el) {
info := Map(
"Element", el,
"Name", "",
"AutomationId", "",
"ControlType", "Custom",
"ClassName", "",
"FrameworkId", "",
"Value", "",
"IsPassword", false,
"Hwnd", 0,
"Patterns", [],
"Rect", Map("X", 0, "Y", 0, "W", 0, "H", 0)
)
try info["Name"] := Trim(String(el.Name))
try info["AutomationId"] := Trim(String(el.AutomationId))
try {
tId := el.Type
tName := UIA.Type[tId]
if tName != ""
info["ControlType"] := String(tName)
} catch {
try if el.LocalizedType != ""
info["ControlType"] := String(el.LocalizedType)
}
try info["ClassName"] := String(el.ClassName)
try info["FrameworkId"] := String(el.FrameworkId)
try info["Value"] := String(el.Value)
try info["IsPassword"] := StudioUtils.ToBool(el.IsPassword)
try info["Hwnd"] := Integer(el.NativeWindowHandle)
try {
br := el.BoundingRectangle
info["Rect"] := Map("X", br.l, "Y", br.t, "W", br.r - br.l, "H", br.b - br.t)
}
pats := []
try {
if el.IsInvokePatternAvailable
pats.Push("Invoke")
}
try {
if el.IsValuePatternAvailable
pats.Push("Value")
}
try {
if el.IsTogglePatternAvailable
pats.Push("Toggle")
}
try {
if el.IsSelectionItemPatternAvailable
pats.Push("SelectionItem")
}
try {
if el.IsExpandCollapsePatternAvailable
pats.Push("ExpandCollapse")
}
try {
if el.IsScrollItemPatternAvailable
pats.Push("ScrollItem")
}
info["Patterns"] := pats
return info
}
_BuildTargetFromElementInfo(info, parentInfo, sx, sy, rel, hwnd, winTitle, winClass, winExe, isBrowser, bType, isWebContent, profAlias, sessName, docName) {
role := UIATargetEngine.FriendlyRoleFromControlType(info["ControlType"])
kind := (isBrowser && isWebContent) ? "BrowserUIA" : (info["ControlType"] == "Window" ? "Window" : "UIA")
name := info["Name"]
if name == "" && info["AutomationId"] != "" && !TargetModel.IsVolatileAutomationId(info["AutomationId"])
name := info["AutomationId"]
t := TargetModel(name, role, kind)
t.ScreenX := sx
t.ScreenY := sy
t.WinRelX := rel.WinX
t.WinRelY := rel.WinY
t.ClientX := rel.ClientX
t.ClientY := rel.ClientY
t.BoundingW := info["Rect"]["W"]
t.BoundingH := info["Rect"]["H"]
t.WinTitle := winTitle
t.WinClass := winClass
t.WinExe := winExe
t.WinHwnd := hwnd
t.SupportedPatterns := info["Patterns"]
t.IsWebContent := isBrowser && isWebContent && (info["ControlType"] != "TabItem")
t.IsBrowserChromeUI := isBrowser && !t.IsWebContent
t.BrowserType := bType
t.ProfileAlias := profAlias
t.SessionName := sessName
t.PageTitle := docName != "" ? docName : winTitle
; Populate PrimarySelector
ps := t.PrimarySelector
ps.StrategyType := "UIA_Primary"
ps.ElementName := info["Name"]
ps.ControlType := info["ControlType"]
ps.AutomationId := info["AutomationId"]
ps.ClassName := info["ClassName"]
ps.FrameworkId := info["FrameworkId"]
ps.ParentName := parentInfo.Get("Name", "")
ps.ParentType := parentInfo.Get("ControlType", "")
; Scope
if t.IsWebContent {
t.Scope.ScopeType := "BrowserDocument"
t.Scope.BrowserSession := sessName != "" ? sessName : "MainBrowser"
} else if isBrowser {
t.Scope.ScopeType := "BrowserWindow"
t.Scope.BrowserSession := sessName != "" ? sessName : "MainBrowser"
} else {
t.Scope.ScopeType := "SpecificWindow"
t.Scope.WinExe := winExe
t.Scope.WinClass := winClass
t.Scope.WinTitle := winTitle
}
t.EnsureDefaultAlternates()
t.ComputeReliability()
return t
}
cancelCheck := ""
scopeFailure := "WrongScope"
resolutionStarted := 0
IsCancelled() => IsObject(this.cancelCheck) && this.cancelCheck.Call()
WindowList() => WinGetList()
WindowInfo(hwnd) => Map("Title", WinGetTitle(hwnd), "Class", WinGetClass(hwnd), "Exe", WinGetProcessName(hwnd))
ResolveWindow(target) {
this.scopeFailure := "WrongScope"
title := target.Scope.WinTitle != "" ? target.Scope.WinTitle : target.WinTitle
cls := target.Scope.WinClass != "" ? target.Scope.WinClass : target.WinClass
exe := target.Scope.WinExe != "" ? target.Scope.WinExe : target.WinExe
if title == "" && cls == "" && exe == "" {
if target.Scope.ScopeType == "ActiveWindow"
return WinExist("A")
return 0
}
matches := []
for hwnd in this.WindowList() {
if this.IsCancelled()
return 0
try {
info := this.WindowInfo(hwnd)
if (title == "" || info["Title"] == title) && (cls == "" || info["Class"] == cls) && (exe == "" || StrLower(info["Exe"]) == StrLower(exe))
matches.Push(hwnd)
}
}
if matches.Length != 1 {
this.scopeFailure := matches.Length > 1 ? "AmbiguousWindow" : "WrongScope"
return 0
}
return matches[1]
}
Failure(reason, name := "", count := 0, message := "") {
return Map("Passed", false, "Found", false, "Reason", reason, "MatchCount", count,
"Element", "", "X", 0, "Y", 0, "StrategyName", name, "StrategyUsed", name,
"StrategyResults", [], "Message", message != "" ? message : reason, "DurationMs", 0)
}
ParentMatches(el, strategy) {
if strategy.ParentName == "" && strategy.ParentType == ""
return true
parent := this.ParentOf(el)
if !IsObject(parent)
return false
return (strategy.ParentName == "" || parent.Name == strategy.ParentName)
&& (strategy.ParentType == "" || UIA.Type[parent.Type] == strategy.ParentType)
}
ParentOf(el) => UIA.TreeWalkerTrue.GetParentElement(el)
IdentityBackup(primary, candidate) {
if candidate.StrategyType != "UIA_Alternate" && candidate.StrategyType != "UIA_Primary"
return false
return primary.ElementName != "" && candidate.ElementName == primary.ElementName
&& candidate.ControlType == primary.ControlType && candidate.MatchMode == "Exact"
&& candidate.CaseSensitive == primary.CaseSensitive
&& candidate.ParentName == primary.ParentName && candidate.ParentType == primary.ParentType
&& candidate.ClassName == primary.ClassName && candidate.FrameworkId == primary.FrameworkId
&& (candidate.AutomationId == primary.AutomationId
|| (TargetModel.IsVolatileAutomationId(primary.AutomationId) && candidate.AutomationId == ""))
}
; One policy shared by the backup editor, validation, preview and playback.
BackupEligibility(primary, backup) {
if !IsObject(primary) || !IsObject(backup)
return Map("Eligible", false, "Reason", "Missing target")
if primary.TargetKind != "UIA" && primary.TargetKind != "BrowserUIA" && primary.TargetKind != "Window"
return Map("Eligible", false, "Reason", "Explicit visual/coordinate modes do not use semantic-object backups")
if backup.TargetKind != primary.TargetKind
return Map("Eligible", false, "Reason", "A visual or coordinate target cannot prove the same object identity")
if !this.IdentityBackup(primary.PrimarySelector, backup.PrimarySelector)
return Map("Eligible", false, "Reason", "Must preserve exact name, role, parent, class and framework; only a volatile automation ID may be dropped")
if JsonCodec.Dump(backup.Scope.ToMap()) != JsonCodec.Dump(primary.Scope.ToMap())
|| backup.WinTitle != primary.WinTitle || backup.WinClass != primary.WinClass || backup.WinExe != primary.WinExe
return Map("Eligible", false, "Reason", "Window and container scope must exactly match the primary target")
return Map("Eligible", true, "Reason", "Same identity and scope; attempted only after not-found or stale-reference failure")
}
static FailureGuidance(reason, inputMayHaveOccurred := false) {
messages := Map(
"NotFound", "The item was not found. Make sure it is present in the selected window, then check again.",
"Ambiguous", "Multiple matching elements. Choose a more specific identity or container.",
"AmbiguousWindow", "Multiple matching windows. Close one or choose a more specific scope.",
"WrongScope", "The selected window or container is unavailable. Open it or choose the intended scope.",
"StaleReference", "The target reference is stale. Check again to acquire a fresh reference.",
"Offscreen", "The item is offscreen or has unusable bounds. Bring it into view, then check again.",
"UnsupportedCapability", "This target or action is not supported by this lookup. Choose a supported target method.",
"Timeout", "The lookup timed out. Wait for the application to respond, then check again.",
"Canceled", "The check was canceled. No retry will run automatically.",
"Covered", "Another window covers the target. Uncover it, then check again.")
message := messages.Get(reason, "The action could not complete. Inspect the technical details before trying again.")
safe := !inputMayHaveOccurred && messages.Has(reason) && reason != "Canceled" && reason != "UnsupportedCapability"
if inputMayHaveOccurred
message .= " Input may already have occurred; do not repeat this action automatically."
return Map("Message", message, "CanRetry", safe)
}
static EffectiveTarget(act, project := 0) {
if act.ReusableTargetId != "" {
if !IsObject(project) || !project.ReusableTargets.Has(act.ReusableTargetId)
return ""
return project.ReusableTargets[act.ReusableTargetId]
}
return act.Target
}
RepairedTarget(primary, picked, replacePrimary) {
if replacePrimary
draft := picked.Clone()
else {
eligible := this.BackupEligibility(primary, picked)
if !eligible["Eligible"]
throw ValueError(eligible["Reason"])
draft := primary.Clone()
if draft.ManualBackups {
backup := picked.Clone()
backup.BackupEnabled := true, backup.BackupTargets := [], backup.AlternateSelectors := []
draft.BackupTargets.InsertAt(1, backup)
} else {
alt := picked.PrimarySelector.Clone()
alt.Name := "Repaired fallback (" picked.GetHumanLabel() ")", alt.StrategyType := "UIA_Alternate"
draft.AlternateSelectors.InsertAt(1, alt)
}
}
draft.ReusableTargetId := ""
return draft
}
static PlanSummary(result) {
text := "Primary: " result.Get("PrimaryOutcome", result.Get("Message", "Not checked"))
for item in result.Get("BackupPlan", [])
text .= "`r`nBackup " item["Index"] ": " item["Status"] " — " item["Message"]
return text
}
; Resolves the root UIA element for a TargetModel's scope (supports UIAContainer scoping!)
ResolveScopeRootElement(target) {
hwnd := this.ResolveWindow(target)
if !hwnd
return ""
rootEl := ""
try rootEl := UIA.ElementFromHandle(hwnd)
catch
return ""
; If scoped to a specific UIAContainer (Section 30), narrow rootEl to that container
if IsObject(rootEl) && IsObject(target.Scope) && target.Scope.ScopeType == "UIAContainer" {
cq := {}
if target.Scope.ContainerType != ""
cq.Type := target.Scope.ContainerType
if target.Scope.ContainerName != ""
cq.Name := target.Scope.ContainerName, cq.mm := 3
if target.Scope.ContainerAutomationId != ""
cq.AutomationId := target.Scope.ContainerAutomationId
try {
containers := rootEl.FindElements(cq)
if containers.Length == 1
return containers[1]
this.scopeFailure := containers.Length > 1 ? "Ambiguous" : "WrongScope"
}
return ""
}
return rootEl
}
; Tests a single SelectorStrategy against a target scope
TestSingleStrategy(target, strategy, rootEl := "") {
t0 := A_TickCount
if this.IsCancelled()
return this.Failure("Canceled")
if !IsObject(strategy) || !strategy.Enabled
return Map("Passed", false, "MatchCount", 0, "Element", "", "X", 0, "Y", 0, "StrategyName", IsObject(strategy) ? strategy.Name : "", "Message", "Disabled", "DurationMs", 0)
switch strategy.StrategyType {
case "UIA_Primary", "UIA_Alternate":
if !IsObject(rootEl)
rootEl := this.ResolveScopeRootElement(target)
if !IsObject(rootEl)
return Map("Passed", false, "MatchCount", 0, "Element", "", "X", 0, "Y", 0, "StrategyName", strategy.Name, "Reason", this.scopeFailure, "Message", "Target scope unavailable or ambiguous", "DurationMs", A_TickCount - t0)
cond := Map()
if strategy.ControlType != "" && strategy.ControlType != "Custom" && strategy.ControlType != "Window"
cond["Type"] := strategy.ControlType
if strategy.AutomationId != ""
cond["AutomationId"] := strategy.AutomationId
if strategy.ElementName != "" {
cond["Name"] := strategy.ElementName
cond["mm"] := strategy.MatchMode == "Substring" ? 2 : (strategy.MatchMode == "StartsWith" ? 1 : (strategy.MatchMode == "Regex" ? "RegEx" : 3))
cond["cs"] := strategy.CaseSensitive
}
if strategy.ClassName != ""
cond["ClassName"] := strategy.ClassName
if strategy.FrameworkId != ""
cond["FrameworkId"] := strategy.FrameworkId
if cond.Count == 0 {
; Window root itself
if strategy.ControlType == "Window" {
br := rootEl.BoundingRectangle
return Map("Passed", true, "MatchCount", 1, "Element", rootEl, "X", (br.l + br.r) // 2, "Y", (br.t + br.b) // 2, "Rect", Map("X", br.l, "Y", br.t, "W", br.r - br.l, "H", br.b - br.t), "StrategyName", strategy.Name, "Message", "1 match (Window)", "DurationMs", A_TickCount - t0)
}
return Map("Passed", false, "MatchCount", 0, "Element", "", "X", 0, "Y", 0, "StrategyName", strategy.Name, "Message", "Empty UIA selector criteria", "DurationMs", A_TickCount - t0)
}
try {
; Convert cond Map to UIA condition object literal
q := {}
for k, v in cond
q.%k% := v
matches := rootEl.FindElements(q)
if this.IsCancelled()
return this.Failure("Canceled", strategy.Name)
if A_TickCount - t0 > 2000
return this.Failure("Timeout", strategy.Name)
if matches.Length > 512
return this.Failure("Timeout", strategy.Name, matches.Length, "Candidate limit exceeded (512)")
filtered := []
for element in matches {
if this.IsCancelled()
return this.Failure("Canceled", strategy.Name)
if this.ParentMatches(element, strategy)
filtered.Push(element)
}
cnt := filtered.Length
strategy.LastMatchCount := cnt
if cnt > 1
return this.Failure("Ambiguous", strategy.Name, cnt, "Ambiguous: " cnt " matches; no element chosen")
if cnt == 1 {
chosen := filtered[1]
if chosen.IsOffscreen
return this.Failure("Offscreen", strategy.Name, 1)
br := chosen.BoundingRectangle
if br.r <= br.l || br.b <= br.t
return this.Failure("Offscreen", strategy.Name, 1, "Target has no usable bounds")
br := chosen.BoundingRectangle
cx := (br.l + br.r) // 2 + target.OffsetX
cy := (br.t + br.b) // 2 + target.OffsetY
strategy.LastTestStatus := cnt == 1 ? "PASS" : "AMBIGUOUS"
return Map(
"Passed", true,
"MatchCount", cnt,
"Element", chosen,
"X", cx,
"Y", cy,
"Rect", Map("X", br.l, "Y", br.t, "W", br.r - br.l, "H", br.b - br.t),
"StrategyName", strategy.Name,
"Message", cnt == 1 ? "PASS — 1 unique match" : "AMBIGUOUS — " cnt " matches (add Anchor or Scope)",
"DurationMs", A_TickCount - t0
)
}
} catch as err {
strategy.LastTestStatus := "FAIL"
return Map("Passed", false, "MatchCount", 0, "Element", "", "X", 0, "Y", 0, "StrategyName", strategy.Name, "Reason", "StaleReference", "Message", "UIA lookup failed: " err.Message, "DurationMs", A_TickCount - t0)
}
strategy.LastTestStatus := "FAIL"
strategy.LastMatchCount := 0
return Map("Passed", false, "MatchCount", 0, "Element", "", "X", 0, "Y", 0, "StrategyName", strategy.Name, "Reason", "NotFound", "Message", "0 matches", "DurationMs", A_TickCount - t0)
case "AnchorRelative":
if !target.Anchor.Enabled
return Map("Passed", false, "MatchCount", 0, "Element", "", "X", 0, "Y", 0, "StrategyName", strategy.Name, "Message", "Anchor not enabled", "DurationMs", 0)
return this._ResolveAnchorRelative(target, strategy, rootEl, t0)
case "ImageMatch":
if !IsObject(this.imageEngine)
return Map("Passed", false, "MatchCount", 0, "Element", "", "X", 0, "Y", 0, "StrategyName", strategy.Name, "Reason", "UnsupportedCapability", "Message", "Image engine unavailable", "DurationMs", 0)
ir := this.imageEngine.SearchTargetImage(target)
if ir["Found"] {
return Map(
"Passed", true,
"MatchCount", 1,
"Element", "",
"X", ir["X"],
"Y", ir["Y"],
"Rect", Map("X", ir["TopLeftX"], "Y", ir["TopLeftY"], "W", ir["W"], "H", ir["H"]),
"StrategyName", strategy.Name,
"Message", "PASS — Image matched",
"DurationMs", ir["DurationMs"]
)
}
return Map("Passed", false, "MatchCount", 0, "Element", "", "X", 0, "Y", 0, "StrategyName", strategy.Name, "Reason", ir.Get("Reason", ""), "Message", ir["Message"], "DurationMs", ir["DurationMs"])
case "PixelMatch":
if !IsObject(this.imageEngine)
return Map("Passed", false, "MatchCount", 0, "Element", "", "X", 0, "Y", 0, "StrategyName", strategy.Name, "Reason", "UnsupportedCapability", "Message", "Color engine unavailable", "DurationMs", 0)
cr := this.imageEngine.SearchTargetColor(target)
if cr["Found"] {
return Map(
"Passed", true,
"MatchCount", 1,
"Element", "",
"X", cr["X"],
"Y", cr["Y"],
"Rect", Map("X", cr["X"] - 10, "Y", cr["Y"] - 10, "W", 20, "H", 20),
"StrategyName", strategy.Name,
"Message", "PASS — Color matched",
"DurationMs", cr["DurationMs"]
)
}
return Map("Passed", false, "MatchCount", 0, "Element", "", "X", 0, "Y", 0, "StrategyName", strategy.Name, "Reason", cr.Get("Reason", ""), "Message", cr["Message"], "DurationMs", cr["DurationMs"])
case "WindowRelativeCoord":
hwnd := target.WinHwnd && WinExist("ahk_id " target.WinHwnd) ? target.WinHwnd : (target.WinExe != "" ? WinExist("ahk_exe " target.WinExe) : WinExist("A"))
if hwnd {
pt := StudioUtils.WindowRelativeToScreen(target.WinRelX, target.WinRelY, hwnd, false)
if pt.Valid {
return Map(
"Passed", true,
"MatchCount", 1,
"Element", "",
"X", pt.X + target.OffsetX,
"Y", pt.Y + target.OffsetY,
"Rect", Map("X", pt.X - 12, "Y", pt.Y - 12, "W", 24, "H", 24),
"StrategyName", strategy.Name,
"Message", "Available — Window-Relative Point",
"DurationMs", A_TickCount - t0
)
}
}
return Map("Passed", false, "MatchCount", 0, "Element", "", "X", 0, "Y", 0, "StrategyName", strategy.Name, "Reason", "WrongScope", "Message", "Window not found for relative point", "DurationMs", A_TickCount - t0)
case "ScreenCoord":
return Map(
"Passed", true,
"MatchCount", 1,
"Element", "",
"X", target.ScreenX + target.OffsetX,
"Y", target.ScreenY + target.OffsetY,
"Rect", Map("X", target.ScreenX - 12, "Y", target.ScreenY - 12, "W", 24, "H", 24),
"StrategyName", strategy.Name,
"Message", "Available — Screen Coordinate",
"DurationMs", A_TickCount - t0
)
}
return Map("Passed", false, "MatchCount", 0, "Element", "", "X", 0, "Y", 0, "StrategyName", strategy.Name, "Reason", "UnsupportedCapability", "Message", "Unknown strategy", "DurationMs", 0)
}
_ResolveAnchorRelative(target, strategy, rootEl, t0) {
if !IsObject(rootEl)
rootEl := this.ResolveScopeRootElement(target)
if !IsObject(rootEl)
return Map("Passed", false, "MatchCount", 0, "Element", "", "X", 0, "Y", 0, "StrategyName", strategy.Name, "Message", "Scope window unavailable", "DurationMs", A_TickCount - t0)
anc := target.Anchor
try {
aq := {}
if anc.AnchorControlType != ""
aq.Type := anc.AnchorControlType
if anc.AnchorName != ""
aq.Name := anc.AnchorName, aq.mm := 2
if anc.AnchorAutomationId != ""
aq.AutomationId := anc.AnchorAutomationId
anchorEl := rootEl.FindElement(aq)
abr := anchorEl.BoundingRectangle
ax := (abr.l + abr.r) // 2
ay := (abr.t + abr.b) // 2
tq := {}
tType := strategy.ControlType != "" ? strategy.ControlType : target.PrimarySelector.ControlType
if tType != ""
tq.Type := tType
candidates := rootEl.FindElements(tq)
bestEl := ""
bestDist := 999999
for _, cand in candidates {
cbr := cand.BoundingRectangle
cx := (cbr.l + cbr.r) // 2
cy := (cbr.t + cbr.b) // 2
if cx == ax && cy == ay
continue
dx := cx - ax
dy := cy - ay
dist := Sqrt(dx * dx + dy * dy)
if dist > anc.MaxDistance
continue
validDir := true
switch anc.Relationship {
case "RightOf": validDir := (dx > 0 && Abs(dy) < 80)
case "LeftOf": validDir := (dx < 0 && Abs(dy) < 80)
case "Below": validDir := (dy > 0 && Abs(dx) < 150)
case "Above": validDir := (dy < 0 && Abs(dx) < 150)
}
if validDir && dist < bestDist {
bestDist := dist
bestEl := cand
}
}
if IsObject(bestEl) {
br := bestEl.BoundingRectangle
return Map(
"Passed", true,
"MatchCount", 1,
"Element", bestEl,
"X", (br.l + br.r) // 2 + target.OffsetX,
"Y", (br.t + br.b) // 2 + target.OffsetY,
"Rect", Map("X", br.l, "Y", br.t, "W", br.r - br.l, "H", br.b - br.t),
"AnchorRect", Map("X", abr.l, "Y", abr.t, "W", abr.r - abr.l, "H", abr.b - abr.t),
"StrategyName", strategy.Name,
"Message", Format("PASS — Found {1} ({2}px from anchor)", anc.Relationship, Round(bestDist)),
"DurationMs", A_TickCount - t0
)
}
}
return Map("Passed", false, "MatchCount", 0, "Element", "", "X", 0, "Y", 0, "StrategyName", strategy.Name, "Message", "Anchor or relative target not found", "DurationMs", A_TickCount - t0)
}
; Tests a TargetModel across its Primary and Alternate/Fallback strategies
TestTarget(target, testAllStrategies := false) {
this.resolutionStarted := A_TickCount
if this.IsCancelled()
return this.Failure("Canceled")
result := this.TestTargetCore(target, testAllStrategies)
primaryOutcome := result["Message"], plan := []
result["PrimaryOutcome"] := primaryOutcome, result["BackupPlan"] := plan
if !IsObject(target)
return result
attempts := result["StrategyResults"], seen := Map(), tried := 0
for index, backup in target.BackupTargets {
entry := Map("Index", index, "Status", "Skipped", "Message", "Primary or earlier backup resolved")
plan.Push(entry)
if !backup.BackupEnabled {
entry["Message"] := "Disabled"
continue
}
eligible := this.BackupEligibility(target, backup)
if !eligible["Eligible"] {
entry["Status"] := "Rejected", entry["Message"] := eligible["Reason"]
attempts.Push(this.Failure("Rejected", "Backup " index, 0, eligible["Reason"]))
continue
}
if result["Found"]
continue
if this.IsCancelled() || A_TickCount - this.resolutionStarted > 2000 {
result := this.Failure(this.IsCancelled() ? "Canceled" : "Timeout")
entry["Message"] := result["Reason"]
continue
}
if result.Get("Reason", "NotFound") != "NotFound" && result.Get("Reason", "") != "StaleReference" {
entry["Message"] := "Primary/earlier failure does not permit fallback: " result.Get("Reason", "Unknown")
continue
}
identity := backup.PrimarySelector.ToMap()
identity.Delete("Id"), identity.Delete("Name")
key := JsonCodec.Dump(identity)
if seen.Has(key) {
entry["Message"] := "Duplicate selector"
continue
}
seen[key] := true
if tried >= 3 {
entry["Message"] := "Three-backup attempt limit reached"
continue
}
tried++
candidate := this.TestTargetCore(backup, testAllStrategies)
entry["Status"] := candidate["Found"] ? "Resolved" : "Attempted"
entry["Message"] := candidate["Message"]
for detail in candidate["StrategyResults"]
attempts.Push(detail)
if candidate["Found"] {
candidate["IsFallback"] := true
candidate["StrategyUsed"] := "Backup " index ": " backup.GetHumanLabel()
candidate["ResolvedTarget"] := backup
target.RecordOutcome(true, candidate["StrategyUsed"], candidate["MatchCount"])
result := candidate
} else if candidate.Get("Reason", "NotFound") != "NotFound" && candidate.Get("Reason", "") != "StaleReference"
result := candidate
}
result["StrategyResults"] := attempts
result["PrimaryOutcome"] := primaryOutcome, result["BackupPlan"] := plan
result["DurationMs"] := A_TickCount - this.resolutionStarted
return result
}
TestTargetCore(target, testAllStrategies := false) {
t0 := A_TickCount
if !IsObject(target)
return Map("Found", false, "MatchCount", 0, "Element", "", "X", 0, "Y", 0, "StrategyUsed", "", "StrategyResults", [], "Message", "No target configured")
; Direct Coordinate / Image / Color targets
if target.TargetKind == "ScreenCoordinate" {
s := SelectorStrategy("Screen Coordinate", "ScreenCoord")
r := this.TestSingleStrategy(target, s)
target.RecordOutcome(r["Passed"], "ScreenCoord", 1)
return Map("Found", r["Passed"], "Reason", r.Get("Reason", ""), "MatchCount", 1, "Element", "", "X", r["X"], "Y", r["Y"], "Rect", r["Rect"], "StrategyUsed", "ScreenCoord", "StrategyResults", [r], "Message", r["Message"], "DurationMs", A_TickCount - t0)
}
if target.TargetKind == "WindowRelative" {
s := SelectorStrategy("Window-Relative Coordinate", "WindowRelativeCoord")
r := this.TestSingleStrategy(target, s)
target.RecordOutcome(r["Passed"], "WindowRelativeCoord", r["MatchCount"])
return Map("Found", r["Passed"], "Reason", r.Get("Reason", ""), "MatchCount", r["MatchCount"], "Element", "", "X", r["X"], "Y", r["Y"], "Rect", r.Get("Rect", ""), "StrategyUsed", "WindowRelativeCoord", "StrategyResults", [r], "Message", r["Message"], "DurationMs", A_TickCount - t0)
}
if target.TargetKind == "Image" {
s := SelectorStrategy("Visual Image", "ImageMatch")
r := this.TestSingleStrategy(target, s)
target.RecordOutcome(r["Passed"], "ImageMatch", r["MatchCount"])
return Map("Found", r["Passed"], "Reason", r.Get("Reason", ""), "MatchCount", r["MatchCount"], "Element", "", "X", r["X"], "Y", r["Y"], "Rect", r.Get("Rect", ""), "StrategyUsed", "ImageMatch", "StrategyResults", [r], "Message", r["Message"], "DurationMs", A_TickCount - t0)
}
if target.TargetKind == "PixelColor" {
s := SelectorStrategy("Pixel Color", "PixelMatch")
r := this.TestSingleStrategy(target, s)
target.RecordOutcome(r["Passed"], "PixelMatch", r["MatchCount"])
return Map("Found", r["Passed"], "Reason", r.Get("Reason", ""), "MatchCount", r["MatchCount"], "Element", "", "X", r["X"], "Y", r["Y"], "Rect", r.Get("Rect", ""), "StrategyUsed", "PixelMatch", "StrategyResults", [r], "Message", r["Message"], "DurationMs", A_TickCount - t0)
}
rootEl := this.ResolveScopeRootElement(target)
if this.IsCancelled()
return this.Failure("Canceled")
if !IsObject(rootEl)
return this.Failure(this.scopeFailure, "Scope", 0, "Expected " target.GetHumanLabel() " in " target.Scope.GetFriendlyText() ": " this.scopeFailure)
stratResults := []
winner := ""
; Object identity cannot be replaced by a coordinate/image/nearest-anchor primary.
if target.PrimarySelector.StrategyType != "UIA_Primary" && target.PrimarySelector.StrategyType != "UIA_Alternate"
return this.Failure("UnsupportedCapability", "Primary", 0, "Object targets require a semantic primary selector")
; 1. Primary Selector
rPrimary := this.TestSingleStrategy(target, target.PrimarySelector, rootEl)
stratResults.Push(rPrimary)
if rPrimary["Passed"] {
winner := rPrimary
if !testAllStrategies {
target.RecordOutcome(true, "UIA_Primary", rPrimary["MatchCount"])
return Map("Found", true, "MatchCount", rPrimary["MatchCount"], "Element", rPrimary["Element"], "X", rPrimary["X"], "Y", rPrimary["Y"], "Rect", rPrimary.Get("Rect", ""), "StrategyUsed", rPrimary["StrategyName"], "IsFallback", false, "StrategyResults", stratResults, "Message", rPrimary["Message"], "DurationMs", A_TickCount - t0)
}
}
; 2. Alternate Selectors & Fallbacks
altAttempts := 0
for _, alt in target.AlternateSelectors {
if this.IsCancelled()
return this.Failure("Canceled")
if rPrimary.Get("Reason", "NotFound") != "NotFound" && rPrimary.Get("Reason", "") != "StaleReference"
break
if target.ManualBackups
break
if !alt.Enabled || !target.AllowsStrategy(alt.StrategyType)
continue
if !this.IdentityBackup(target.PrimarySelector, alt) {
stratResults.Push(this.Failure("Rejected", alt.Name, 0, "Fallback cannot prove the same object identity"))
continue
}
altAttempts++
if altAttempts > 3 || A_TickCount - t0 > 2000
break
rAlt := this.TestSingleStrategy(target, alt, rootEl)
stratResults.Push(rAlt)
if !rAlt["Passed"] && rAlt.Get("Reason", "NotFound") != "NotFound" && rAlt.Get("Reason", "") != "StaleReference" {
rPrimary := rAlt
break
}
if rAlt["Passed"] && !IsObject(winner) {
winner := rAlt
winner["IsFallback"] := true
if !testAllStrategies
break
}
}
if IsObject(winner) {
isFb := winner.Get("IsFallback", false)
target.RecordOutcome(true, isFb ? winner["StrategyName"] : "UIA_Primary", winner["MatchCount"])
return Map(
"Found", true,
"MatchCount", winner["MatchCount"],
"Element", winner["Element"],
"X", winner["X"],
"Y", winner["Y"],
"Rect", winner.Get("Rect", ""),
"StrategyUsed", winner["StrategyName"],
"IsFallback", isFb,
"StrategyResults", stratResults,
"Message", winner["Message"],
"DurationMs", A_TickCount - t0
)
}
target.RecordOutcome(false, "None", rPrimary["MatchCount"])
return Map(
"Found", false,
"Reason", rPrimary.Get("Reason", "NotFound"),
"MatchCount", rPrimary["MatchCount"],
"Element", "",
"X", 0,
"Y", 0,
"StrategyUsed", "None",
"IsFallback", false,
"StrategyResults", stratResults,
"Message", "Expected " target.GetHumanLabel() " in " target.Scope.GetFriendlyText() ": " rPrimary["Message"],
"DurationMs", A_TickCount - t0
)
}
HighlightTarget(target, durationMs := 1800) {
res := this.TestTarget(target, false)
if durationMs > 0 && res["Found"] && res.Has("Rect") && IsObject(res["Rect"]) && IsObject(this.overlayMgr) {
r := res["Rect"]
color := res["MatchCount"] > 1 ? "F59E0B" : (res.Get("IsFallback", false) ? "38BDF8" : "22C55E")
this.overlayMgr.ShowHighlightRect(r["X"], r["Y"], r["W"], r["H"], color, durationMs, 3)
this.overlayMgr.ShowCrosshair(res["X"], res["Y"], "F59E0B", 14)
}
return res
}
; Safe non-destructive target test & preview (vNext Section 47)
ResolveOnly(target, durationMs := 2200) {
try res := this.TestTarget(target.Clone(), false)
catch as err {
res := this.Failure(err is TargetError ? err.Extra : "", "Lookup", 0, err.Message)
}
res["Status"] := res["Found"] ? "PASS" : (InStr(res.Get("Reason", ""), "Ambiguous") ? "AMBIGUOUS" : "FAIL")
res["ElapsedMs"] := res.Get("DurationMs", 0)
if durationMs > 0 && res["Found"] && res.Has("Rect") && IsObject(res["Rect"]) && IsObject(this.overlayMgr) {
r := res["Rect"]
color := res["MatchCount"] > 1 ? "F59E0B" : (res.Get("IsFallback", false) ? "38BDF8" : "22C55E")
this.overlayMgr.ShowHighlightRect(r["X"], r["Y"], r["W"], r["H"], color, durationMs, 3)
this.overlayMgr.ShowCrosshair(res["X"], res["Y"], "F59E0B", 14)
}
return res
}
; Previews an ActionModel without clicking or mutating target application state (vNext Section 47)
PreviewAction(act, durationMs := 2200, project := 0) {
if !IsObject(act)
return Map("Found", false, "Summary", "Select a step to check.")
intro := "Action: " act.ComputeFriendlyDescription() " [" act.Type "]"
button := act.Parameters.Get("Button", "n/a")
count := StrLower(button) == "double" || act.Type == "Mouse_DoubleClick" ? 2 : act.Parameters.Get("ClickCount", "n/a")
method := act.Parameters.Get("ClickMethod", act.Parameters.Get("Method", "action default"))
if act.Type == "UIA_Click" && act.Parameters.Get("OffsetMode", "None") != "None"
method := "Physical"
if button == "Double"
button := "Left"
intro .= "`r`nButton: " button " · Count: " count " · Method: " method
if !ActionRegistry.UsesTarget(act.Type) || InStr(act.Type, "Browser_") == 1 || InStr(act.Type, "OCR_") == 1
return Map("Found", false, "Summary", intro "`r`nThis action cannot be meaningfully verified by a target lookup. No step was executed.")
target := UIATargetEngine.EffectiveTarget(act, project)
if !IsObject(target)
return Map("Found", false, "Summary", intro "`r`nThe reusable target reference is unavailable. Restore or explicitly replace it.")
res := this.ResolveOnly(target, durationMs)
summary := intro "`r`nTarget: " target.GetHumanLabel() " · " target.GetMethodLabel()
. "`r`nScope: " target.GetWithinBreadcrumb() "`r`nMatches: " res["MatchCount"]
if IsObject(res.Get("Rect", "")) {
r := res["Rect"]
summary .= "`r`nResolved bounds: x=" r["X"] ", y=" r["Y"] ", width=" r["W"] ", height=" r["H"]
}
summary .= "`r`n" (res["Found"] ? "Lookup succeeded. This does not prove the action's eventual outcome." : UIATargetEngine.FailureGuidance(res.Get("Reason", ""))["Message"])
summary .= "`r`n" UIATargetEngine.PlanSummary(res) "`r`nNo click, typing, scrolling or action execution was performed."
res["Summary"] := summary
return res
}
; One-click Visual Fallback auto-capture from current resolved target bounds (vNext Section 50)
CaptureVisualFallbackForTarget(target) {
if !IsObject(target) || !IsObject(this.imageEngine)
return Map("Ok", false, "Message", "Target or ImageEngine unavailable.")
if IsObject(this.overlayMgr)
this.overlayMgr.HideAll()
Sleep(60)
res := this.TestTarget(target, false)
if !res["Found"]
return Map("Ok", false, "Message", "Resolve the target before capturing a visual fallback; saved coordinates may no longer identify it.")
rx := 0, ry := 0, rw := 0, rh := 0
if res["Found"] && res.Has("Rect") && IsObject(res["Rect"]) {
r := res["Rect"]
rx := r["X"], ry := r["Y"], rw := r["W"], rh := r["H"]
} else if target.BoundingW > 4 && target.BoundingH > 4 {
rw := target.BoundingW, rh := target.BoundingH
rx := res.Get("X", target.ScreenX) - (rw // 2)
ry := res.Get("Y", target.ScreenY) - (rh // 2)
} else if target.ScreenX > 0 && target.ScreenY > 0 {
rw := target.BoundingW > 8 ? target.BoundingW : 48
rh := target.BoundingH > 8 ? target.BoundingH : 32
rx := target.ScreenX - (rw // 2)
ry := target.ScreenY - (rh // 2)
}
if rw <= 4 || rh <= 4
return Map("Ok", false, "Message", "Could not determine valid bounding box for visual fallback capture.")
try {
cap := this.imageEngine.CaptureScreenRegionToBmp(rx, ry, Min(rw, 400), Min(rh, 300))
target.CapturedImagePath := cap["FilePath"]
target.CapturedImageBase64 := cap["Base64"]
target.BoundingW := cap["Width"]
target.BoundingH := cap["Height"]
target.EnsureDefaultAlternates()
target.ComputeReliability()
return Map("Ok", true, "Message", Format("Captured visual fallback ({1}×{2} px).", cap["Width"], cap["Height"]))
} catch as err {
return Map("Ok", false, "Message", "Capture failed: " err.Message)
}
}
}
; ==============================================================================
; UNIFIED SELECTION LENS ENGINE (vNext Sections 21–41, 136)
; Powers all target picking, Dual-Context Highlighting, Depth Rail Breadcrumb,
; Selection Intent Filters (1..7), Freeze & Refine modal with Smart Action Choice,
; and one-click Use as Scope / Use as Anchor.
; ==============================================================================
class SelectionEngine {
app := ""
overlayMgr := ""
uiaEngine := ""
imageEngine := ""
isActive := false
isFrozen := false
selectionPurpose := "UIAAction"
intentFilter := "SMART" ; SMART | CONTROL | TEXT | CONTAINER | PAGE | VISUAL | POINT
onCompleteCallback := ""
onCancelCallback := ""
hoverTimer := ""
lastHoverX := -99999
lastHoverY := -99999
currentDiscovery := ""
selectedCandidateIndex := 1
candidateManuallyChosen := false
; Region rubber-band state
isDrawingRegion := false
regionStartX := 0
regionStartY := 0
; Freeze & Refine interactive dialog
freezeGui := ""
freezeListCtrl := ""
freezeInfoCtrl := ""
freezeActionDd := ""
freezeRecommendedActions := []
__New(app, overlayMgr, uiaEngine, imageEngine) {
this.app := app
this.overlayMgr := overlayMgr
this.uiaEngine := uiaEngine
this.imageEngine := imageEngine
}
StartSelection(purpose := "UIAAction", callback := "", initialPoint := "", cancelCallback := "") {
if this.isActive
this.CancelSelection()
this.isActive := true
this.restoreEditor := false
if IsObject(this.app) && IsObject(this.app.gui.mainGui) {
this.restoreEditor := !!DllCall("IsWindowVisible", "Ptr", this.app.gui.mainGui.Hwnd)
if this.restoreEditor
this.app.gui.mainGui.Hide()
}
this.isFrozen := false
this.selectionPurpose := purpose
this.intentFilter := this.InitialIntent(purpose)
this.selectedCandidateIndex := 0
this.candidateManuallyChosen := false
this.currentDiscovery := ""
this.onCompleteCallback := callback
this.onCancelCallback := cancelCallback
this.lastHoverX := -99999
this.lastHoverY := -99999
if IsObject(this.app)
this.app.SetState(StudioConstants.StateSelecting)
this._BindSelectionHotkeys(true)
if IsObject(initialPoint) && initialPoint.Has("X") && initialPoint.Has("Y") {
this._InspectPoint(initialPoint["X"], initialPoint["Y"], true)
this.EnterFreezeAndRefine()
return
}
this.hoverTimer := ObjBindMethod(this, "_OnHoverTick")
SetTimer(this.hoverTimer, 65)
this._OnHoverTick()
}
InitialIntent(purpose) {
if purpose != "UIAAction" && purpose != "EditClick"
return "SMART"
if !IsObject(this.app) || this.app.persistence.settings.Get("DefaultClickMode", "Coordinate Window") != "Coordinate Window"
return "SMART"
action := this.app.gui.GetSelectedAction()
return !IsObject(action) || RegExMatch(action.Type, "^(Mouse_Click|UIA_Click|Browser_Click|Browser_ClickAndWaitNewTab|Image_Click|Pixel_Click)$") ? "POINT" : "SMART"
}
ConfirmGesture() {
return IsObject(this.app) ? this.app.persistence.settings.Get("PickerConfirmGesture", "Alt+Click") : "Alt+Click"
}
PrimaryConfirmKey() => IsObject(this.app) ? this.app.persistence.settings.Get("Hotkey_SelectTarget", "F6") : "F6"
ConfirmHint() => this.PrimaryConfirmKey() (InStr(this.ConfirmGesture(), "only") ? "" : " / " this.ConfirmGesture())
static GestureHotkey(gesture) {
return Map("Alt+Click", "!LButton", "Ctrl+Click", "^LButton", "Shift+Click", "+LButton", "Middle click", "*MButton", "F6 only", "", "Primary key only", "").Get(gesture, "!LButton")
}
_BindSelectionHotkeys(enable) {
state := enable ? "On" : "Off"
try Hotkey("*Escape", ObjBindMethod(this, "_OnEscapeHotkey"), state)
try Hotkey("*Up", ObjBindMethod(this, "_OnCycleUp"), state)
try Hotkey("*Down", ObjBindMethod(this, "_OnCycleDown"), state)
try Hotkey("*Tab", ObjBindMethod(this, "_OnCycleDown"), state)
if enable {
this.boundPrimaryKey := this.PrimaryConfirmKey()
this.boundFreezeKey := IsObject(this.app) ? this.app.persistence.settings.Get("Hotkey_FreezeRefine", "^+f") : "^+f"
}
if this.HasOwnProp("boundFreezeKey")
try Hotkey(this.boundFreezeKey, ObjBindMethod(this, "EnterFreezeAndRefine"), state)
if this.HasOwnProp("boundPrimaryKey")
try Hotkey(this.boundPrimaryKey, ObjBindMethod(this, "_OnLeftClickHotkey"), state)
if enable
this.boundConfirmKey := SelectionEngine.GestureHotkey(this.ConfirmGesture())
if this.HasOwnProp("boundConfirmKey") && this.boundConfirmKey != ""
try Hotkey(this.boundConfirmKey, ObjBindMethod(this, "_OnLeftClickHotkey"), state)
wheelEnabled := !IsObject(this.app) || this.app.persistence.settings.Get("PickerWheelCycles", true)
wheelState := enable && wheelEnabled ? "On" : "Off"
try Hotkey("*WheelUp", ObjBindMethod(this, "_OnCycleUp"), wheelState)
try Hotkey("*WheelDown", ObjBindMethod(this, "_OnCycleDown"), wheelState)
; Selection Intent Filter hotkeys (1..7)
try Hotkey("*1", ObjBindMethod(this, "_SetIntentFilter", "SMART"), state)
try Hotkey("*2", ObjBindMethod(this, "_SetIntentFilter", "CONTROL"), state)
try Hotkey("*3", ObjBindMethod(this, "_SetIntentFilter", "TEXT"), state)
try Hotkey("*4", ObjBindMethod(this, "_SetIntentFilter", "CONTAINER"), state)
try Hotkey("*5", ObjBindMethod(this, "_SetIntentFilter", "PAGE"), state)
try Hotkey("*6", ObjBindMethod(this, "_SetIntentFilter", "VISUAL"), state)
try Hotkey("*7", ObjBindMethod(this, "_SetIntentFilter", "POINT"), state)
}
_SetIntentFilter(mode, *) {
if !this.isActive || this.isFrozen
return
this.intentFilter := mode
this.candidateManuallyChosen := false
if IsObject(this.currentDiscovery) {
this._ApplyIntentFilterToCandidates()
this._RefreshSelectedCandidateDisplay()
}
}
_ApplyIntentFilterToCandidates() {
if !IsObject(this.currentDiscovery)
return
cands := this.currentDiscovery["Candidates"]
if cands.Length == 0
return
switch this.intentFilter {
case "SMART":
this.selectedCandidateIndex := Max(1, this.currentDiscovery["RecommendedIndex"])
case "CONTROL":
for idx, c in cands {
if UIATargetEngine.IsInteractiveRole(c["ControlType"]) {
this.selectedCandidateIndex := idx
return
}
}
case "TEXT":
for idx, c in cands {
if c["ControlType"] == "Text" || c["ControlType"] == "Edit" || c["Role"] == "Text" {
this.selectedCandidateIndex := idx
return
}
}
this.selectedCandidateIndex := 1
case "CONTAINER":
for idx, c in cands {
if UIATargetEngine.IsContainerRole(c["ControlType"]) {
this.selectedCandidateIndex := idx
return
}
}
case "PAGE":
for idx, c in cands {
if c["ControlType"] == "Document" || c["ControlType"] == "Window" {
this.selectedCandidateIndex := idx
return
}
}
case "VISUAL":
for idx, c in cands {
if c["Kind"] == "Image" {
this.selectedCandidateIndex := idx
return
}
}
case "POINT":
for idx, c in cands {
if c["Kind"] == "WindowRelative" {
this.selectedCandidateIndex := idx
return
}
}
}
}
_OnHoverTick() {
if !this.isActive || this.isFrozen
return
MouseGetPos(&mx, &my)
if this.isDrawingRegion {
rx := Min(this.regionStartX, mx)
ry := Min(this.regionStartY, my)
rw := Max(8, Abs(mx - this.regionStartX))
rh := Max(8, Abs(my - this.regionStartY))
this.overlayMgr.ShowHighlightRect(rx, ry, rw, rh, "F59E0B", 0, 2)
this.overlayMgr.ShowHud(mx, my, "DRAWING REGION", Format("Region ({1}, {2}) — {3}×{4} px", rx, ry, rw, rh), "Select again to finish region capture", this.ConfirmHint() ": Finish Region | Esc: Cancel")
return
}
if Abs(mx - this.lastHoverX) < 3 && Abs(my - this.lastHoverY) < 3
return
this.lastHoverX := mx
this.lastHoverY := my
this._InspectPoint(mx, my, false)
}
_BuildDepthRailBreadcrumb(cands, activeIdx) {
rail := ""
maxShow := Min(cands.Length, 5)
for idx, c in cands {
if idx > maxShow
break
shortLbl := c["Role"]
if c["Target"].Name != "" && StrLen(c["Target"].Name) <= 14
shortLbl .= ' "' c["Target"].Name '"'
if idx == activeIdx {
star := c["IsRecommended"] ? " ★" : ""
rail .= (idx > 1 ? " › " : "") . "[" . shortLbl . star . "]"
} else {
rail .= (idx > 1 ? " › " : "") . shortLbl
}
}
return rail
}
_InspectPoint(mx, my, resetIndex := false) {
if this.selectionPurpose == "PixelColorSelection" {
cInfo := this.imageEngine.GetPixelColorInfo(mx, my)
this.overlayMgr.ShowHighlightRect(mx - 8, my - 8, 16, 16, SubStr(cInfo["Hex"], 3), 0, 2)
this.overlayMgr.ShowCrosshair(mx, my, "F59E0B", 12)
this.overlayMgr.ShowHud(mx, my, "COLOR PICKER", cInfo["Hex"] " " cInfo["RGBText"], Format("Screen: ({1}, {2})", mx, my), this.ConfirmHint() ": Use Color | Esc: Cancel")
return
}
if this.selectionPurpose == "RegionCapture" || this.selectionPurpose == "ImageCapture" {
modeTitle := this.selectionPurpose == "ImageCapture" ? "IMAGE CAPTURE — CLICK START CORNER" : "REGION SELECTION — CLICK START CORNER"
this.overlayMgr.ShowHud(mx, my, modeTitle, Format("Cursor at ({1}, {2})", mx, my), "Select first corner, move cursor, then select the opposite corner.", this.ConfirmHint() ": Start Corner | Esc: Cancel")
return
}
studioHwnd := (IsObject(this.app) && IsObject(this.app.gui)) ? this.app.gui.GetMainHwnd() : 0
disc := this.uiaEngine.DiscoverCandidatesAtPoint(mx, my, studioHwnd)
this.currentDiscovery := disc
cands := disc["Candidates"]
if cands.Length == 0
return
if resetIndex || this.selectedCandidateIndex > cands.Length || this.selectedCandidateIndex < 1 || (this.intentFilter == "POINT" && !this.candidateManuallyChosen) {
this._ApplyIntentFilterToCandidates()
}
this._RefreshSelectedCandidateDisplay()
}
_OnCycleUp(*) {
if !this.isActive || !IsObject(this.currentDiscovery)
return
cands := this.currentDiscovery["Candidates"]
if cands.Length <= 1
return
this.candidateManuallyChosen := true
this.selectedCandidateIndex := (this.selectedCandidateIndex <= 1) ? cands.Length : (this.selectedCandidateIndex - 1)
this._RefreshSelectedCandidateDisplay()
}
_OnCycleDown(*) {
if !this.isActive || !IsObject(this.currentDiscovery)
return
cands := this.currentDiscovery["Candidates"]
if cands.Length <= 1
return
this.candidateManuallyChosen := true
this.selectedCandidateIndex := (this.selectedCandidateIndex >= cands.Length) ? 1 : (this.selectedCandidateIndex + 1)
this._RefreshSelectedCandidateDisplay()
}
_RefreshSelectedCandidateDisplay() {
if !IsObject(this.currentDiscovery)
return
disc := this.currentDiscovery
cands := disc["Candidates"]
if cands.Length == 0
return
idx := Clamp(this.selectedCandidateIndex, 1, cands.Length)
this.selectedCandidateIndex := idx
curCand := cands[idx]
t := curCand["Target"]
r := curCand["Rect"]
pr := curCand.Get("ParentRect", "")
; Line 1: Context + Intent Filter + Reliability
badge := t.IsWebContent ? "WEB · " : (t.IsBrowserChromeUI ? "BROWSER · " : "DESKTOP · ")
ctxHeader := badge . (t.BrowserType != "" ? t.BrowserType : disc["WinExe"])
if t.ProfileAlias != ""
ctxHeader .= " · " t.ProfileAlias
ctxHeader .= " [" this.intentFilter "] (" t.ReliabilityRating ")"
; Line 2: Active Candidate
recSuffix := curCand["IsRecommended"] ? " ★ Recommended" : Format(" (Depth {1}/{2})", idx, cands.Length)
line2 := curCand["Label"] . recSuffix
; Line 3: Compact Depth Rail Breadcrumb
railStr := disc["RecommendedIndex"] > 0 ? "Depth: " . this._BuildDepthRailBreadcrumb(cands, idx) : "Recommended unavailable: " disc.Get("RecommendationReason", "No unique identity")
; Dual-Context Highlighting: Primary Target + Secondary Scope/Container + Crosshair
color := curCand["IsRecommended"] ? "0078D4" : (t.IsWebContent ? "10B981" : "38BDF8")
this.overlayMgr.ShowHighlightRect(r["X"], r["Y"], Max(12, r["W"]), Max(12, r["H"]), color, 0, 3)
if IsObject(pr) && pr["W"] > 0 && pr["H"] > 0 && (pr["W"] != r["W"] || pr["H"] != r["H"]) {
this.overlayMgr.ShowSecondaryRect(pr["X"], pr["Y"], pr["W"], pr["H"], "A855F7", 2)
} else {
this.overlayMgr.HideSecondaryRect()
}
this.overlayMgr.ShowCrosshair(disc["ScreenX"], disc["ScreenY"], "F59E0B", 12)
this.overlayMgr.ShowHud(disc["ScreenX"], disc["ScreenY"], ctxHeader, line2, railStr, this.ConfirmHint() " selects | ↑/↓: Depth | 1: Recommended | Esc: Cancel")
}
_OnLeftClickHotkey(*) {
if !this.isActive || this.isFrozen
return
MouseGetPos(&mx, &my)
; Handle 2-click Region / Image capture
if this.selectionPurpose == "RegionCapture" || this.selectionPurpose == "ImageCapture" {
if !this.isDrawingRegion {
this.isDrawingRegion := true
this.regionStartX := mx
this.regionStartY := my
return
} else {
this.isDrawingRegion := false
rx := Min(this.regionStartX, mx)
ry := Min(this.regionStartY, my)
rw := Max(12, Abs(mx - this.regionStartX))
rh := Max(12, Abs(my - this.regionStartY))
this.overlayMgr.HideAll()
t := this._BuildRegionOrImageTarget(rx, ry, rw, rh, this.selectionPurpose == "ImageCapture")
this._CompleteWithTarget(t)
return
}
}
; Handle Pixel Color capture
if this.selectionPurpose == "PixelColorSelection" {
cInfo := this.imageEngine.GetPixelColorInfo(mx, my)
t := TargetModel("Color " cInfo["Hex"], "Color", "PixelColor")
t.CapturedColorHex := cInfo["Hex"]
t.ScreenX := mx
t.ScreenY := my
t.ComputeReliability()
this._CompleteWithTarget(t)
return
}
; Standard UIA / Browser / Window / Upgrade selection
if !IsObject(this.currentDiscovery) || this.currentDiscovery["Candidates"].Length == 0
this._InspectPoint(mx, my, true)
if IsObject(this.currentDiscovery) && this.currentDiscovery["Candidates"].Length > 0 {
cands := this.currentDiscovery["Candidates"]
idx := Clamp(this.selectedCandidateIndex, 1, cands.Length)
chosenTarget := cands[idx]["Target"]
this._CompleteWithTarget(chosenTarget)
} else {
this.CancelSelection()
}
}
_BuildRegionOrImageTarget(rx, ry, rw, rh, captureBmp := false) {
hwnd := DllCall("User32\GetAncestor", "Ptr", DllCall("User32\WindowFromPoint", "Int64", (rx & 0xFFFFFFFF) | (ry << 32), "Ptr"), "UInt", 2, "Ptr")
winExe := "", winTitle := ""
if hwnd {
try winExe := WinGetProcessName("ahk_id " hwnd)
try winTitle := WinGetTitle("ahk_id " hwnd)
}
if captureBmp {
cap := this.imageEngine.CaptureScreenRegionToBmp(rx, ry, rw, rh)
t := TargetModel(Format("Captured Image ({1}×{2})", rw, rh), "Image", "Image")
t.CapturedImagePath := cap["FilePath"]
t.CapturedImageBase64 := cap["Base64"]
t.BoundingW := rw
t.BoundingH := rh
t.ScreenX := rx + (rw // 2)
t.ScreenY := ry + (rh // 2)
t.WinExe := winExe
t.WinTitle := winTitle
t.Scope.ScopeType := winExe != "" ? "SpecificWindow" : "VirtualDesktop"
t.Scope.WinExe := winExe
t.ComputeReliability()
return t
} else {
t := TargetModel(Format("Region ({1}×{2})", rw, rh), "Region", "Region")
t.WinExe := winExe
t.WinTitle := winTitle
t.Scope.ScopeType := "Region"
t.Scope.WinExe := winExe
if hwnd {
WinGetPos(&wx, &wy, , , "ahk_id " hwnd)
t.Scope.RegionX := rx - wx
t.Scope.RegionY := ry - wy
t.Scope.RelativeToWindow := true
} else {
t.Scope.RegionX := rx
t.Scope.RegionY := ry
t.Scope.RelativeToWindow := false
}
t.Scope.RegionW := rw
t.Scope.RegionH := rh
t.ComputeReliability()
return t
}
}
; FREEZE & REFINE (vNext Sections 28–30):
; Visually freezes the candidate hierarchy at the current pointer with Exact Target Preview,
; Smart Action Choice, and one-click Use as Scope / Use as Anchor.
EnterFreezeAndRefine(*) {
if !this.isActive
return
this.isFrozen := true
if this.hoverTimer != "" {
SetTimer(this.hoverTimer, 0)
this.hoverTimer := ""
}
this._BindSelectionHotkeys(false)
try Hotkey("*Escape", ObjBindMethod(this, "_OnEscapeHotkey"), "On")
this.overlayMgr.HideHud()
if !IsObject(this.currentDiscovery) || this.currentDiscovery["Candidates"].Length == 0 {
MouseGetPos(&mx, &my)
studioHwnd := (IsObject(this.app) && IsObject(this.app.gui)) ? this.app.gui.GetMainHwnd() : 0
this.currentDiscovery := this.uiaEngine.DiscoverCandidatesAtPoint(mx, my, studioHwnd)
}
if IsObject(this.app)
this.app.SetState(StudioConstants.StateFrozenSelection)
this._ShowFreezeRefineDialog()
}
_ShowFreezeRefineDialog() {
if IsObject(this.freezeGui) {
try this.freezeGui.Destroy()
this.freezeGui := ""
}
disc := this.currentDiscovery
cands := disc["Candidates"]
g := Gui("+AlwaysOnTop +ToolWindow +Owner", "Freeze & Refine Target — (" disc["ScreenX"] ", " disc["ScreenY"] ")")
g.SetFont("s9", "Segoe UI")
g.MarginX := 14
g.MarginY := 12
hdrBadge := disc["IsWebContent"] ? "WEB PAGE TARGET" : (disc["IsBrowser"] ? "BROWSER CHROME UI" : "DESKTOP UI TARGET")
g.SetFont("s10 Bold", "Segoe UI")
g.Add("Text", "w560", "Frozen Target Hierarchy — " hdrBadge " (" disc["WinExe"] ")")
g.SetFont("s8 Norm", "Segoe UI")
g.Add("Text", "w560 y+3", "Choose exact depth level, preview target properties, or apply an ancestor/label as a Container Scope or Anchor:")
lv := g.Add("ListView", "w560 r7 y+6 Grid -Multi AltSubmit", ["Depth", "Candidate Target", "Method", "Reliability"])
lv.ModifyCol(1, 100)
lv.ModifyCol(2, 260)
lv.ModifyCol(3, 105)
lv.ModifyCol(4, 85)
for idx, c in cands {
lvl := c["IsRecommended"] ? "★ Recommended" : ((idx == 1) ? "Smallest Child" : (c["Kind"] == "Image" || c["Kind"] == "WindowRelative" ? "Fallback" : "Ancestor " (idx - 1)))
t := c["Target"]
lv.Add(idx == this.selectedCandidateIndex ? "Select Focus" : "", lvl, c["Label"], t.GetMethodLabel(), t.ReliabilityRating)
}
g.SetFont("s8 Bold", "Segoe UI")
g.Add("Text", "w560 y+8", "EXACT TARGET PREVIEW")
g.SetFont("s9 Norm", "Segoe UI")
this.freezeInfoCtrl := g.Add("Edit", "w560 r5 y+3 ReadOnly", "")
this.freezeListCtrl := lv
lv.OnEvent("ItemSelect", ObjBindMethod(this, "_OnFreezeCandidateSelect"))
lv.OnEvent("DoubleClick", ObjBindMethod(this, "_OnFreezeConfirm"))
g.Add("Text", "xm y+8 w130", "Smart Action Choice:")
this.freezeActionDd := g.Add("DropDownList", "x+6 yp-3 w230", ["(Keep Current / Default)"])
btnUseScope := g.Add("Button", "x+8 yp-1 w90 h25", "Use as Scope")
btnUseScope.OnEvent("Click", ObjBindMethod(this, "_OnFreezeUseAsScope"))
btnUseAnchor := g.Add("Button", "x+6 yp w90 h25", "Use as Anchor")
btnUseAnchor.OnEvent("Click", ObjBindMethod(this, "_OnFreezeUseAsAnchor"))
btnRow := g.Add("Button", "xm w145 h30 y+10 Default", "Use Selected Target")
btnRow.OnEvent("Click", ObjBindMethod(this, "_OnFreezeConfirm"))
btnTest := g.Add("Button", "x+8 w120 h30", "Test & Highlight")
btnTest.OnEvent("Click", ObjBindMethod(this, "_OnFreezeHighlight"))
btnVisual := g.Add("Button", "x+8 w135 h30", "+ Visual Fallback")
btnVisual.OnEvent("Click", ObjBindMethod(this, "_OnFreezeCaptureVisual"))
btnCancel := g.Add("Button", "x+8 w110 h30", "Cancel (Esc)")
btnCancel.OnEvent("Click", ObjBindMethod(this, "CancelSelection"))
g.OnEvent("Close", ObjBindMethod(this, "CancelSelection"))
g.OnEvent("Escape", ObjBindMethod(this, "CancelSelection"))
this.freezeGui := g
this._UpdateFreezeDetails(this.selectedCandidateIndex)
g.Show("AutoSize Center")
}
_OnFreezeCandidateSelect(ctrl, item, selected) {
if !selected || item < 1
return
this.selectedCandidateIndex := item
this._UpdateFreezeDetails(item)
}
_UpdateFreezeDetails(idx) {
if !IsObject(this.currentDiscovery)
return
cands := this.currentDiscovery["Candidates"]
if idx < 1 || idx > cands.Length
return
c := cands[idx]
t := c["Target"]
r := c["Rect"]
pr := c.Get("ParentRect", "")
; Highlight candidate + parent container
this.overlayMgr.ShowHighlightRect(r["X"], r["Y"], Max(12, r["W"]), Max(12, r["H"]), "22C55E", 0, 3)
if IsObject(pr) && pr["W"] > 0 && pr["H"] > 0 && (pr["W"] != r["W"] || pr["H"] != r["H"])
this.overlayMgr.ShowSecondaryRect(pr["X"], pr["Y"], pr["W"], pr["H"], "A855F7", 2)
; Populate Exact Target Preview (Section 28)
browserLine := t.BrowserType != "" ? (t.BrowserType . (t.ProfileAlias != "" ? " — " t.ProfileAlias : "") . (t.SessionName != "" ? " (" t.SessionName ")" : "")) : (t.WinExe != "" ? t.WinExe : "Desktop")
details := "What: " t.GetHumanLabel() " | Where: " t.GetWithinBreadcrumb() "`r`n"
details .= "Browser/App: " browserLine " | Page/Window: " (t.PageTitle != "" ? t.PageTitle : t.WinTitle) "`r`n"
details .= "Method: " t.GetMethodLabel() " (" t.PrimarySelector.GetFindUsingSummary() ") | ControlType: " t.PrimarySelector.ControlType "`r`n"
details .= "Scope: " t.Scope.GetFriendlyText() " | Anchor: " t.Anchor.GetFriendlyText() "`r`n"
details .= "Recommendation: " this.currentDiscovery.Get("RecommendationReason", "Not validated")
details .= "`r`nBackups: exact semantic identity and scope only; coordinates, generic images and nearest-anchor guesses are rejected for objects."
details .= "`r`nRecommended target and suggested action are separate choices."
if IsObject(this.freezeInfoCtrl)
this.freezeInfoCtrl.Value := details
; Populate Smart Action Choice dropdown (Section 29)
if IsObject(this.freezeActionDd) {
recs := ActionRegistry.GetRecommendedActionsForTarget(t)
this.freezeRecommendedActions := recs
items := ["(Default: " recs[1] ")"]
for _, rType in recs
items.Push(rType)
this.freezeActionDd.Delete()
this.freezeActionDd.Add(items)
this.freezeActionDd.Choose(1)
}
}
_OnFreezeUseAsScope(*) {
if !IsObject(this.currentDiscovery)
return
cands := this.currentDiscovery["Candidates"]
idx := Clamp(this.selectedCandidateIndex, 1, cands.Length)
scopeCand := cands[idx]["Target"]
; Apply selected element as UIAContainer scope to the recommended target!
recIdx := this.currentDiscovery["RecommendedIndex"]
if recIdx < 1
return
recTarget := cands[recIdx]["Target"]
recTarget.Scope.ScopeType := "UIAContainer"
recTarget.Scope.ContainerName := scopeCand.PrimarySelector.ElementName
recTarget.Scope.ContainerType := scopeCand.PrimarySelector.ControlType
recTarget.Scope.ContainerAutomationId := scopeCand.PrimarySelector.AutomationId
recTarget.ComputeReliability()
this.selectedCandidateIndex := recIdx
if IsObject(this.freezeListCtrl)
this.freezeListCtrl.Modify(recIdx, "Select Focus")
this._UpdateFreezeDetails(recIdx)
}
_OnFreezeUseAsAnchor(*) {
if !IsObject(this.currentDiscovery)
return
cands := this.currentDiscovery["Candidates"]
idx := Clamp(this.selectedCandidateIndex, 1, cands.Length)
ancCand := cands[idx]["Target"]
recIdx := this.currentDiscovery["RecommendedIndex"]
if recIdx < 1
return
recTarget := cands[recIdx]["Target"]
recTarget.Anchor.Enabled := true
recTarget.Anchor.AnchorName := ancCand.Name != "" ? ancCand.Name : ancCand.PrimarySelector.ElementName
recTarget.Anchor.AnchorRole := ancCand.Role
recTarget.Anchor.AnchorControlType := ancCand.PrimarySelector.ControlType
recTarget.Anchor.AnchorAutomationId := ancCand.PrimarySelector.AutomationId
recTarget.EnsureDefaultAlternates()
recTarget.ComputeReliability()
this.selectedCandidateIndex := recIdx
if IsObject(this.freezeListCtrl)
this.freezeListCtrl.Modify(recIdx, "Select Focus")
this._UpdateFreezeDetails(recIdx)
}
_OnFreezeCaptureVisual(*) {
if !IsObject(this.currentDiscovery)
return
cands := this.currentDiscovery["Candidates"]
idx := Clamp(this.selectedCandidateIndex, 1, cands.Length)
t := cands[idx]["Target"]
res := this.uiaEngine.CaptureVisualFallbackForTarget(t)
this._UpdateFreezeDetails(idx)
if IsObject(this.app)
this.app.ShowToast(res["Message"])
}
_OnFreezeHighlight(*) {
if !IsObject(this.currentDiscovery)
return
cands := this.currentDiscovery["Candidates"]
idx := Clamp(this.selectedCandidateIndex, 1, cands.Length)
t := cands[idx]["Target"]
selectedAction := IsObject(this.freezeActionDd) ? this.freezeActionDd.Value : 1
res := this.uiaEngine.ResolveOnly(t)
this._UpdateFreezeDetails(idx)
if IsObject(this.freezeActionDd)
this.freezeActionDd.Choose(selectedAction)
this.freezeInfoCtrl.Value .= "`r`n" (res["Found"] ? "PASS" : "FAILED") " · " res["MatchCount"] " match(es) · " res["ElapsedMs"] " ms · " res["StrategyUsed"]
}
_OnFreezeConfirm(*) {
if !IsObject(this.currentDiscovery)
return
cands := this.currentDiscovery["Candidates"]
idx := Clamp(this.selectedCandidateIndex, 1, cands.Length)
chosen := cands[idx]["Target"]
if IsObject(this.freezeActionDd) && this.freezeActionDd.Value > 1 {
chosenActionType := this.freezeActionDd.Text
chosen.SupportedPatterns.Push("PreferredAction:" chosenActionType)
}
if IsObject(this.freezeGui) {
try this.freezeGui.Destroy()
this.freezeGui := ""
}
this._CompleteWithTarget(chosen)
}
_OnEscapeHotkey(*) {
this.CancelSelection()
}
_CompleteWithTarget(target) {
cb := this.onCompleteCallback
purpose := this.selectionPurpose
this._CleanupSelectionState()
if cb != "" && HasMethod(cb)
cb.Call(target, purpose)
}
CancelSelection(*) {
cb := this.isActive ? this.onCancelCallback : ""
this._CleanupSelectionState()
if IsObject(this.app)
this.app.ShowToast("Selection cancelled.")
if IsObject(cb) && HasMethod(cb)
cb.Call()
}
_CleanupSelectionState() {
this.onCancelCallback := ""
if this.HasOwnProp("restoreEditor") && this.restoreEditor {
this.restoreEditor := false
try this.app.gui.mainGui.Show()
}
this.isActive := false
this.isFrozen := false
this.isDrawingRegion := false
if this.hoverTimer != "" {
try SetTimer(this.hoverTimer, 0)
this.hoverTimer := ""
}
this._BindSelectionHotkeys(false)
if IsObject(this.app) && this.app.recorder.isRecording && this.app.recorder.HasOwnProp("boundFreezeKey")
try Hotkey(this.app.recorder.boundFreezeKey, ObjBindMethod(this.app.recorder, "TriggerFreezeAndRefineDuringRecord"), "On")
if IsObject(this.freezeGui) {
try this.freezeGui.Destroy()
this.freezeGui := ""
}
this.overlayMgr.HideAll()
if IsObject(this.app) && (this.app.currentState == StudioConstants.StateSelecting || this.app.currentState == StudioConstants.StateFrozenSelection)
this.app.SetState(StudioConstants.StateIdle)
}
}
; ==============================================================================
; PART 5: BROWSER CAPABILITY MATRIX, PROFILE MANAGER, & MULTI-SESSION ENGINE
; ==============================================================================
class BrowserCapabilityMatrix {
static GetCapabilities(browserType) {
b := StrLower(Trim(browserType))
if b == "mozilla"
b := "firefox"
switch b {
case "chrome", "edge", "brave":
return Map(
"ProfileDiscovery", true,
"ProfileLaunch", true,
"Attach", true,
"Document", true,
"URL", true,
"Navigate", true,
"PageWait", true,
"Tabs", true,
"BrowserChromeUIA", true,
"PageUIA", true,
"JavaScript", true,
"CSSAction", true,
"Alerts", true
)
case "vivaldi":
return Map(
"ProfileDiscovery", true,
"ProfileLaunch", true,
"Attach", true,
"Document", true,
"URL", true,
"Navigate", true,
"PageWait", true,
"Tabs", true,
"BrowserChromeUIA", true,
"PageUIA", true,
"JavaScript", true,
"CSSAction", true,
"Alerts", false
)
case "firefox":
return Map(
"ProfileDiscovery", true,
"ProfileLaunch", true,
"Attach", true,
"Document", true,
"URL", true,
"Navigate", true,
"PageWait", true,
"Tabs", true,
"BrowserChromeUIA", true,
"PageUIA", true,
"JavaScript", true,
"CSSAction", true,
"Alerts", true
)
default:
return Map(
"ProfileDiscovery", false,
"ProfileLaunch", false,
"Attach", false,
"Document", false,
"URL", false,
"Navigate", false,
"PageWait", false,
"Tabs", false,
"BrowserChromeUIA", false,
"PageUIA", false,
"JavaScript", false,
"CSSAction", false,
"Alerts", false
)
}
}
static IsSupported(browserType, capability) {
caps := this.GetCapabilities(browserType)
return caps.Has(capability) && caps[capability]
}
static GetUnsupportedReason(browserType, capability) {
if this.IsSupported(browserType, capability)
return ""
return Format("Capability '{1}' is not supported for browser '{2}'.", capability, browserType)
}
}
; ==============================================================================
; BROWSER PROFILE MANAGER (Sections 46–54 & vNext Sections 7–14)
; Safe discovery of Chrome, Edge, Brave, Vivaldi, and Firefox profiles,
; logical alias mapping, Studio-managed isolated profiles, and safe launching.
; ==============================================================================
class BrowserProfileManager {
discoveredProfiles := [] ; Array of Maps
installedBrowsers := Map() ; BrowserType -> ExePath
aliasMappings := Map() ; Alias -> Map("Browser", "ProfileId", "FriendlyName", "UserDataRoot", "IsStudioManaged")
logger := ""
__New(logger := "") {
this.logger := logger
this.discoveredProfiles := []
this.installedBrowsers := Map()
this.installedBrowsers.CaseSense := "Off"
this.aliasMappings := Map()
this.aliasMappings.CaseSense := "Off"
this.RefreshProfiles()
}
DiscoverInstalledBrowsers() {
this.installedBrowsers.Clear()
localAppData := EnvGet("LOCALAPPDATA")
progFiles := A_ProgramFiles
progFiles86 := EnvGet("ProgramFiles(x86)")
candidates := Map(
"Edge", [
progFiles86 "\Microsoft\Edge\Application\msedge.exe",
progFiles "\Microsoft\Edge\Application\msedge.exe",
localAppData "\Microsoft\Edge\Application\msedge.exe"
],
"Chrome", [
progFiles "\Google\Chrome\Application\chrome.exe",
progFiles86 "\Google\Chrome\Application\chrome.exe",
localAppData "\Google\Chrome\Application\chrome.exe"
],
"Firefox", [
progFiles "\Mozilla Firefox\firefox.exe",
progFiles86 "\Mozilla Firefox\firefox.exe",
localAppData "\Mozilla Firefox\firefox.exe"
],
"Brave", [
progFiles "\BraveSoftware\Brave-Browser\Application\brave.exe",
progFiles86 "\BraveSoftware\Brave-Browser\Application\brave.exe",
localAppData "\BraveSoftware\Brave-Browser\Application\brave.exe"
],
"Vivaldi", [
localAppData "\Vivaldi\Application\vivaldi.exe",
progFiles "\Vivaldi\Application\vivaldi.exe"
]
)
for bType, pathList in candidates {
for _, p in pathList {
if p != "" && FileExist(p) {
this.installedBrowsers[bType] := p
break
}
}
}
return this.installedBrowsers
}
RefreshProfiles() {
this.DiscoverInstalledBrowsers()
this.discoveredProfiles := []
localAppData := EnvGet("LOCALAPPDATA")
roamingAppData := A_AppData
; 1. Chromium-family browsers (Edge, Chrome, Brave, Vivaldi)
chromiumRoots := Map(
"Edge", localAppData "\Microsoft\Edge\User Data",
"Chrome", localAppData "\Google\Chrome\User Data",
"Brave", localAppData "\BraveSoftware\Brave-Browser\User Data",
"Vivaldi", localAppData "\Vivaldi\User Data"
)
for bType, userDataRoot in chromiumRoots {
if !this.installedBrowsers.Has(bType)
continue
exePath := this.installedBrowsers[bType]
localStatePath := userDataRoot "\Local State"
foundAny := false
if FileExist(localStatePath) {
try {
rawJson := FileRead(localStatePath, "UTF-8")
lsObj := JsonCodec.Load(rawJson)
if (lsObj is Map) && lsObj.Has("profile") && (lsObj["profile"] is Map) {
profSec := lsObj["profile"]
lastUsed := profSec.Get("last_used", "Default")
if profSec.Has("info_cache") && (profSec["info_cache"] is Map) {
infoCache := profSec["info_cache"]
for profDir, meta in infoCache {
friendly := profDir
if (meta is Map) {
if meta.Has("name") && meta["name"] != ""
friendly := String(meta["name"])
else if meta.Has("shortcut_name") && meta["shortcut_name"] != ""
friendly := String(meta["shortcut_name"])
}
isDef := (profDir = lastUsed) || (profDir = "Default" && lastUsed == "")
this.discoveredProfiles.Push(Map(
"Browser", bType,
"FriendlyName", friendly,
"StudioAlias", this._FindAliasFor(bType, profDir),
"ProfileId", profDir,
"Executable", exePath,
"UserDataRoot", userDataRoot,
"IsDefault", isDef,
"IsStudioManaged", false,
"LastUsedByStudio", ""
))
foundAny := true
}
}
}
}
}
if !foundAny && DirExist(userDataRoot "\Default") {
this.discoveredProfiles.Push(Map(
"Browser", bType,
"FriendlyName", "Default",
"StudioAlias", this._FindAliasFor(bType, "Default"),
"ProfileId", "Default",
"Executable", exePath,
"UserDataRoot", userDataRoot,
"IsDefault", true,
"IsStudioManaged", false,
"LastUsedByStudio", ""
))
}
}
; 2. Mozilla Firefox (profiles.ini)
if this.installedBrowsers.Has("Firefox") {
exePath := this.installedBrowsers["Firefox"]
ffRoot := roamingAppData "\Mozilla\Firefox"
iniPath := ffRoot "\profiles.ini"
if FileExist(iniPath) {
this._DiscoverFirefoxProfiles(iniPath, ffRoot, exePath)
}
}
; 3. Studio-Managed Isolated Automation Profiles
if DirExist(StudioConstants.ManagedProfilesDir) {
Loop Files StudioConstants.ManagedProfilesDir "\*", "D" {
dirName := A_LoopFileName
metaFile := A_LoopFileFullPath "\studio_profile.json"
bType := "Edge"
alias := dirName
if FileExist(metaFile) {
try {
pm := JsonCodec.Load(FileRead(metaFile, "UTF-8"))
bType := pm.Get("Browser", "Edge")
alias := pm.Get("Alias", dirName)
}
}
exePath := this.installedBrowsers.Get(bType, "")
this.discoveredProfiles.Push(Map(
"Browser", bType,
"FriendlyName", alias " (Studio Managed)",
"StudioAlias", alias,
"ProfileId", "Default",
"Executable", exePath,
"UserDataRoot", A_LoopFileFullPath,
"IsDefault", false,
"IsStudioManaged", true,
"LastUsedByStudio", ""
))
}
}
this._EnsureDefaultAliases()
return this.discoveredProfiles
}
_DiscoverFirefoxProfiles(iniPath, ffRoot, exePath) {
try {
content := FileRead(iniPath, "UTF-8")
installDefaultPath := ""
sections := Map()
curSec := ""
Loop Parse content, "`n", "`r" {
line := Trim(A_LoopField)
if line == "" || SubStr(line, 1, 1) == ";" || SubStr(line, 1, 1) == "#"
continue
if RegExMatch(line, "^\[(.+)\]$", &m) {
curSec := m[1]
sections[curSec] := Map()
continue
}
if curSec != "" && RegExMatch(line, "^([^=]+)=(.*)$", &kv) {
k := Trim(kv[1])
v := Trim(kv[2])
sections[curSec][k] := v
if InStr(curSec, "Install") == 1 && k = "Default" && v != ""
installDefaultPath := v
}
}
for secName, secMap in sections {
if InStr(secName, "Profile") != 1
continue
pName := secMap.Get("Name", secName)
pPath := secMap.Get("Path", "")
isRel := secMap.Get("IsRelative", "1") == "1"
fullPath := isRel ? (ffRoot "\" StrReplace(pPath, "/", "\")) : pPath
isDef := (installDefaultPath != "" && pPath = installDefaultPath) || (installDefaultPath == "" && secMap.Get("Default", "0") == "1")
this.discoveredProfiles.Push(Map(
"Browser", "Firefox",
"FriendlyName", pName,
"StudioAlias", this._FindAliasFor("Firefox", pName),
"ProfileId", pName,
"Executable", exePath,
"UserDataRoot", fullPath,
"IsDefault", isDef,
"IsStudioManaged", false,
"LastUsedByStudio", ""
))
}
}
}
_EnsureDefaultAliases() {
; Populate convenient logical aliases ("Work", "Personal", "Default") if not mapped
if !this.aliasMappings.Has("Work") {
p := this.GetDefaultProfileForBrowser("Edge")
if IsObject(p)
this.MapLogicalAlias("Work", p["Browser"], p["ProfileId"], p["FriendlyName"], p["UserDataRoot"], p["IsStudioManaged"])
}
if !this.aliasMappings.Has("Personal") {
p := this.GetDefaultProfileForBrowser("Chrome")
if !IsObject(p)
p := this.GetDefaultProfileForBrowser("Edge")
if IsObject(p)
this.MapLogicalAlias("Personal", p["Browser"], p["ProfileId"], p["FriendlyName"], p["UserDataRoot"], p["IsStudioManaged"])
}
}
_FindAliasFor(browserType, profileId) {
for alias, m in this.aliasMappings {
if m["Browser"] = browserType && m["ProfileId"] = profileId
return alias
}
return ""
}
MapLogicalAlias(aliasName, browserType, profileId, friendlyName := "", userDataRoot := "", isManaged := false) {
cleanAlias := Trim(aliasName)
if cleanAlias == ""
return false
this.aliasMappings[cleanAlias] := Map(
"Alias", cleanAlias,
"Browser", browserType,
"ProfileId", profileId,
"FriendlyName", friendlyName != "" ? friendlyName : profileId,
"UserDataRoot", userDataRoot,
"IsStudioManaged", isManaged ? true : false
)
for _, p in this.discoveredProfiles {
if p["Browser"] = browserType && p["ProfileId"] = profileId && (userDataRoot == "" || p["UserDataRoot"] = userDataRoot)
p["StudioAlias"] := cleanAlias
}
return true
}
GetDefaultProfileForBrowser(browserType := "Edge") {
for _, p in this.discoveredProfiles {
if p["Browser"] = browserType && p["IsDefault"]
return p
}
for _, p in this.discoveredProfiles {
if p["Browser"] = browserType
return p
}
return ""
}
ResolveProfileByAliasOrId(browserType, aliasOrId) {
q := Trim(aliasOrId)
if q == "" || q = "Default" {
def := this.GetDefaultProfileForBrowser(browserType)
if IsObject(def)
return def
}
; 1. Check Logical Alias table
if this.aliasMappings.Has(q) {
am := this.aliasMappings[q]
for _, p in this.discoveredProfiles {
if p["Browser"] = am["Browser"] && p["ProfileId"] = am["ProfileId"] && (am.Get("UserDataRoot", "") == "" || p["UserDataRoot"] = am["UserDataRoot"])
return p
}
}
; 2. Check discovered profiles by StudioAlias, ProfileId, or FriendlyName
for _, p in this.discoveredProfiles {
if (browserType == "" || p["Browser"] = browserType) {
if p["StudioAlias"] = q || p["ProfileId"] = q || p["FriendlyName"] = q
return p
}
}
return ""
}
; Creates an isolated Studio-managed automation profile (Section 50)
; Never copies cookies, saved passwords, or auth tokens from user profiles.
CreateStudioManagedProfile(browserType, aliasName) {
cleanAlias := RegExReplace(Trim(aliasName), "[^\w\- ]", "_")
if cleanAlias == ""
throw ValueError("Profile alias name cannot be empty.")
targetDir := StudioConstants.ManagedProfilesDir "\" browserType "_" StrReplace(cleanAlias, " ", "_")
if !DirExist(targetDir)
DirCreate(targetDir)
meta := Map(
"Browser", browserType,
"Alias", cleanAlias,
"CreatedAt", StudioUtils.FormatTimestamp(),
"StudioManaged", JsonCodec.TrueVal
)
StudioUtils.AtomicWriteFile(targetDir "\studio_profile.json", JsonCodec.Dump(meta, " "))
this.RefreshProfiles()
this.MapLogicalAlias(cleanAlias, browserType, "Default", cleanAlias " (Studio Managed)", targetDir, true)
return targetDir
}
; Builds the safe command line and launches a browser profile (Section 54)
LaunchProfile(browserType, profileAliasOrId := "Default", url := "", newWindow := false, extraArgs := "") {
prof := this.ResolveProfileByAliasOrId(browserType, profileAliasOrId)
effectiveBrowser := IsObject(prof) ? prof["Browser"] : (browserType != "" ? browserType : "Edge")
if !this.installedBrowsers.Has(effectiveBrowser)
throw TargetError("Browser executable not found for " effectiveBrowser)
exePath := this.installedBrowsers[effectiveBrowser]
args := ""
if effectiveBrowser = "Firefox" {
if IsObject(prof) {
if prof["IsStudioManaged"] && prof["UserDataRoot"] != ""
args .= ' -profile "' prof["UserDataRoot"] '" -no-remote'
else if prof["ProfileId"] != ""
args .= ' -P "' prof["ProfileId"] '"'
}
if newWindow
args .= " -new-window"
} else {
; Chromium family: Chrome, Edge, Brave, Vivaldi
if IsObject(prof) {
if prof["IsStudioManaged"] && prof["UserDataRoot"] != "" {
args .= ' --user-data-dir="' prof["UserDataRoot"] '"'
} else {
if prof["UserDataRoot"] != ""
args .= ' --user-data-dir="' prof["UserDataRoot"] '"'
if prof["ProfileId"] != ""
args .= ' --profile-directory="' prof["ProfileId"] '"'
}
}
args .= " --force-renderer-accessibility"
if newWindow
args .= " --new-window"
}
if extraArgs != ""
args .= " " extraArgs
if url != ""
args .= ' "' url '"'
cmdLine := '"' exePath '"' args
pid := 0
Run(cmdLine, , , &pid)
if IsObject(prof)
prof["LastUsedByStudio"] := StudioUtils.FormatTimestamp()
return Map(
"PID", pid,
"Browser", effectiveBrowser,
"ProfileId", IsObject(prof) ? prof["ProfileId"] : profileAliasOrId,
"FriendlyName", IsObject(prof) ? prof["FriendlyName"] : profileAliasOrId,
"Executable", exePath,
"CommandLine", cmdLine
)
}
}
; ==============================================================================
; BROWSER SESSION MANAGER & FALLBACK RESOLUTION ENGINE (vNext Sections 7–20)
; Manages named runtime browser sessions, enforces identity/fallback policies,
; discovers running browser windows, checks session health, and invalidates stale
; document caches after navigation/tab transitions.
; ==============================================================================
class BrowserSessionManager {
profileMgr := ""
logger := ""
app := ""
sessions := Map() ; SessionName -> Map(SessionName, BrowserType, RequestedProfile, EffectiveProfile, Hwnd, PID, LaunchedByStudio, UIABrowser, Connected, LastURL, LastTitle)
activeSessionName := "MainBrowser"
__New(profileMgr, logger := "", app := "") {
this.profileMgr := profileMgr
this.logger := logger
this.app := app
this.sessions := Map()
this.sessions.CaseSense := "Off"
}
; Discovers all currently running browser windows for the Choose Browser Session dialog (vNext Section 13)
DiscoverRunningBrowserWindows() {
list := []
exeMap := Map(
"Edge", "msedge.exe",
"Chrome", "chrome.exe",
"Firefox", "firefox.exe",
"Brave", "brave.exe",
"Vivaldi", "vivaldi.exe"
)
for bType, exe in exeMap {
winList := []
try winList := WinGetList("ahk_exe " exe)
for _, hwnd in winList {
title := ""
try title := WinGetTitle("ahk_id " hwnd)
if title == ""
continue
meta := this.IdentifyBrowserWindowMeta(hwnd, exe)
url := ""
tabCount := 1
try {
ub := UIA_Browser("ahk_id " hwnd)
try url := ub.GetCurrentURL(true)
try {
tNames := ub.GetAllTabNames()
tabCount := Max(1, tNames.Length)
}
}
list.Push(Map(
"Hwnd", hwnd,
"BrowserType", bType,
"Exe", exe,
"ProfileAlias", meta["ProfileAlias"],
"SessionName", meta["SessionName"],
"Title", title,
"URL", url,
"TabCount", tabCount
))
}
}
return list
}
; Simulates how a Browser + Profile + Fallback Policy resolves right now (vNext Section 12: Test Browser Resolution)
SimulatePolicyResolution(sessionName, requestedBrowser, requestedProfile, policy, customOrder := "Configured,Current,Default") {
sName := Trim(sessionName) != "" ? Trim(sessionName) : "MainBrowser"
bType := Trim(requestedBrowser) != "" ? Trim(requestedBrowser) : "Edge"
reqProf := Trim(requestedProfile) != "" ? Trim(requestedProfile) : "Default"
effPolicy := Trim(policy) != "" ? Trim(policy) : StudioConstants.PolicyPreferConfigured
; 1. Check if requested profile window is currently open
matchedHwnd := this._FindCompatibleBrowserWindow(bType, reqProf)
if matchedHwnd && effPolicy != StudioConstants.PolicyCurrentBrowser {
title := ""
try title := WinGetTitle("ahk_id " matchedHwnd)
return Map(
"WouldSucceed", true,
"ResolvedMode", "Exact Match (Open Window)",
"EffectiveBrowser", bType,
"EffectiveProfile", reqProf,
"Hwnd", matchedHwnd,
"Summary", Format("PASS — Requested profile '{1} — {2}' is currently open (Window: {3}).", bType, reqProf, SubStr(title, 1, 45))
)
}
; 2. Evaluate policy when requested profile window is not currently open
curHwnd := this._FindCompatibleBrowserWindow(bType, "")
if !curHwnd
curHwnd := this._FindCompatibleBrowserWindow("", "")
defProf := this.profileMgr.GetDefaultProfileForBrowser(bType)
defId := IsObject(defProf) ? defProf["ProfileId"] : "Default"
defHwnd := this._FindCompatibleBrowserWindow(bType, defId)
switch effPolicy {
case StudioConstants.PolicyStrict:
return Map(
"WouldSucceed", false,
"ResolvedMode", "Blocked by Strict Policy",
"EffectiveBrowser", bType,
"EffectiveProfile", "None",
"Hwnd", 0,
"Summary", Format("FAIL — '{1} — {2}' is not open, and policy is Strict (Require this exact profile).", bType, reqProf)
)
case StudioConstants.PolicyPreferConfigured:
if curHwnd {
actualExe := WinGetProcessName("ahk_id " curHwnd)
actualType := UIATargetEngine.BrowserTypeFromExe(actualExe)
return Map(
"WouldSucceed", true,
"ResolvedMode", "Fallback to Current Browser",
"EffectiveBrowser", actualType,
"EffectiveProfile", "Current " actualType " Session",
"Hwnd", curHwnd,
"Summary", Format("FALLBACK — '{1} — {2}' is closed; will use currently open {3} window with a transparent notice.", bType, reqProf, actualType)
)
}
return Map(
"WouldSucceed", false,
"ResolvedMode", "No Open Browser Found",
"EffectiveBrowser", bType,
"EffectiveProfile", "None",
"Hwnd", 0,
"Summary", Format("FAIL — Neither '{1} — {2}' nor any current browser window is open.", bType, reqProf)
)
case StudioConstants.PolicyPreferConfiguredDefault, StudioConstants.PolicyDefaultProfile:
if defHwnd {
return Map(
"WouldSucceed", true,
"ResolvedMode", "Fallback to Default Profile",
"EffectiveBrowser", bType,
"EffectiveProfile", defId,
"Hwnd", defHwnd,
"Summary", Format("FALLBACK — Will use {1} Default profile ({2}).", bType, defId)
)
}
return Map(
"WouldSucceed", false,
"ResolvedMode", "Default Profile Not Open",
"EffectiveBrowser", bType,
"EffectiveProfile", defId,
"Hwnd", 0,
"Summary", Format("FAIL — {1} Default profile ({2}) is not currently open (use Launch Profile step to start it).", bType, defId)
)
case StudioConstants.PolicyCurrentBrowser, StudioConstants.PolicyAnyCompatible:
if curHwnd {
actualExe := WinGetProcessName("ahk_id " curHwnd)
actualType := UIATargetEngine.BrowserTypeFromExe(actualExe)
return Map(
"WouldSucceed", true,
"ResolvedMode", "Current / Compatible Browser",
"EffectiveBrowser", actualType,
"EffectiveProfile", "Current " actualType,
"Hwnd", curHwnd,
"Summary", Format("PASS — Will attach to currently open {1} window.", actualType)
)
}
return Map(
"WouldSucceed", false,
"ResolvedMode", "No Compatible Browser Open",
"EffectiveBrowser", bType,
"EffectiveProfile", "None",
"Hwnd", 0,
"Summary", "FAIL — No compatible browser window is currently open."
)
case StudioConstants.PolicyAsk:
return Map(
"WouldSucceed", curHwnd != 0,
"ResolvedMode", "Interactive Prompt",
"EffectiveBrowser", bType,
"EffectiveProfile", "User Choice",
"Hwnd", curHwnd,
"Summary", curHwnd ? "PROMPT — Will ask user whether to use the currently open browser window." : "FAIL — No open browser window to prompt for."
)
default:
return Map(
"WouldSucceed", curHwnd != 0,
"ResolvedMode", "Custom Order (" customOrder ")",
"EffectiveBrowser", bType,
"EffectiveProfile", curHwnd ? "Fallback Session" : "None",
"Hwnd", curHwnd,
"Summary", curHwnd ? "PASS — Custom fallback order resolved an open browser window." : "FAIL — Custom fallback order found no open browser."
)
}
}
; Returns clear Browser Session Health state & recovery advice (vNext Section 14)
GetSessionHealth(sessionName := "") {
sName := Trim(sessionName) != "" ? Trim(sessionName) : this.activeSessionName
if !this.sessions.Has(sName) {
anyOpen := this._FindCompatibleBrowserWindow("", "")
return Map(
"Status", anyOpen ? "Needs Reconnect" : "Browser Closed",
"SessionName", sName,
"Detail", anyOpen ? "Session '" sName "' is not yet attached, but a browser window is open." : "No browser window is currently connected for '" sName "'."
)
}
s := this.sessions[sName]
hwnd := s["Hwnd"]
if !hwnd || !WinExist("ahk_id " hwnd) {
s["Connected"] := false
return Map(
"Status", "Browser Closed",
"SessionName", sName,
"Detail", "Browser window for session '" sName "' was closed. Use Launch or Choose Session to reconnect."
)
}
this._RefreshSessionState(s)
if !IsObject(s["UIABrowser"]) {
return Map(
"Status", "UIA Unavailable",
"SessionName", sName,
"Detail", "Browser window is open, but UIA_Browser accessibility tree is not yet ready."
)
}
return Map(
"Status", "Connected",
"SessionName", sName,
"BrowserType", s["BrowserType"],
"Profile", s["EffectiveProfile"],
"Title", s["CurrentTitle"],
"URL", s["CurrentURL"],
"Detail", Format("Connected to {1} ({2}) — {3}", s["BrowserType"], s["EffectiveProfile"], SubStr(s["CurrentTitle"], 1, 45))
)
}
; Invalidates stale DocumentElement cache after navigation, reload, or tab switches (vNext Section 18)
InvalidateDocumentCache(sessionName := "") {
sName := Trim(sessionName) != "" ? Trim(sessionName) : this.activeSessionName
if !this.sessions.Has(sName)
return
s := this.sessions[sName]
if s["Hwnd"] && WinExist("ahk_id " s["Hwnd"]) {
try s["UIABrowser"] := UIA_Browser("ahk_id " s["Hwnd"])
this._RefreshSessionState(s)
}
}
; Identifies browser metadata for a window HWND during recording or selection
IdentifyBrowserWindowMeta(hwnd, winExe := "") {
if !hwnd
return Map("BrowserType", "", "ProfileAlias", "Profile unknown", "SessionName", "MainBrowser")
; Check if HWND is already bound to a named session
for sName, sess in this.sessions {
if sess["Hwnd"] == hwnd {
return Map(
"BrowserType", sess["BrowserType"],
"ProfileAlias", sess["EffectiveProfile"] != "" ? sess["EffectiveProfile"] : "Profile unknown",
"SessionName", sName
)
}
}
bType := UIATargetEngine.BrowserTypeFromExe(winExe)
title := ""
try title := WinGetTitle("ahk_id " hwnd)
; Edge often includes profile name in window title e.g. "Page - Work - Microsoft Edge"
detectedProf := "Profile unknown"
if RegExMatch(title, "-\s*([^-—]+?)\s*-\s*Microsoft\b", &m)
detectedProf := Trim(m[1])
else {
defProf := this.profileMgr.GetDefaultProfileForBrowser(bType)
if IsObject(defProf) && defProf["StudioAlias"] != ""
detectedProf := defProf["StudioAlias"]
}
return Map("BrowserType", bType, "ProfileAlias", detectedProf, "SessionName", this.activeSessionName)
}
IsSessionConnected(sessionName) {
if !this.sessions.Has(sessionName)
return false
s := this.sessions[sessionName]
return s["Hwnd"] != 0 && WinExist("ahk_id " s["Hwnd"]) != 0
}
; Resolves or acquires a browser session according to the 10-step Profile & Fallback Policy (Sections 51–53 & vNext Section 10)
_WindowExists(hwnd) => hwnd && WinExist("ahk_id " hwnd)
_WindowPID(hwnd) => WinGetPID("ahk_id " hwnd)
_CloseWindow(hwnd) => WinClose("ahk_id " hwnd)
_OwnsLaunchedWindow(hwnd, pid) {
if !hwnd || !pid
return false
try return this._WindowPID(hwnd) == pid
return false
}
ResolveSession(sessionName := "", requestedBrowser := "", requestedProfile := "", policy := "PreferConfiguredThenCurrent", allowLaunch := false, initialUrl := "") {
sName := Trim(sessionName) != "" ? Trim(sessionName) : (this.activeSessionName != "" ? this.activeSessionName : "MainBrowser")
effPolicy := Trim(policy) != "" ? Trim(policy) : StudioConstants.PolicyPreferConfigured
; Step 1: Explicit Session already connected & valid
if this.sessions.Has(sName) {
existing := this.sessions[sName]
if this._WindowExists(existing["Hwnd"]) && this._OwnsLaunchedWindow(existing["Hwnd"], existing.Get("PID", 0)) {
browserMatches := requestedBrowser == "" || existing["BrowserType"] = requestedBrowser
profileMatches := requestedProfile == "" || existing["RequestedProfile"] = requestedProfile || existing["EffectiveProfile"] = requestedProfile
strictMatches := effPolicy != StudioConstants.PolicyStrict || existing.Get("ProfileVerified", false)
if (browserMatches && profileMatches && strictMatches) || effPolicy == StudioConstants.PolicyCurrentBrowser || effPolicy == StudioConstants.PolicyAnyCompatible {
this._RefreshSessionState(existing)
return existing
}
}
}
bType := Trim(requestedBrowser) != "" ? Trim(requestedBrowser) : "Edge"
reqProf := Trim(requestedProfile) != "" ? Trim(requestedProfile) : "Default"
; Step 2: If Policy is CurrentBrowser from the outset, attach to current compatible browser without warning
if effPolicy == StudioConstants.PolicyCurrentBrowser {
hwnd := this._FindCompatibleBrowserWindow(bType, "")
if hwnd {
return this.AttachToWindow(sName, hwnd, bType, "Current Browser", "Current Browser", false, "")
}
}
; Never identify a managed profile merely by a generic browser window title.
requested := this.profileMgr.ResolveProfileByAliasOrId(bType, reqProf)
managed := IsObject(requested) && requested["IsStudioManaged"]
matchedHwnd := (managed || effPolicy == StudioConstants.PolicyStrict) ? 0 : this._FindCompatibleBrowserWindow(bType, reqProf)
if matchedHwnd {
return this.AttachToWindow(sName, matchedHwnd, bType, reqProf, reqProf, false, "")
}
; Step 4: Launch requested profile if allowLaunch is true
if allowLaunch {
if !IsObject(requested) && effPolicy == StudioConstants.PolicyStrict
throw TargetError("Requested browser profile does not exist: " reqProf)
previousWindows := Map()
for oldHwnd in WinGetList()
previousWindows[oldHwnd] := true
launchInfo := this.profileMgr.LaunchProfile(bType, reqProf, initialUrl, true)
hwnd := this._WaitForBrowserWindow(bType, launchInfo["PID"], 8000, previousWindows)
if hwnd {
owned := this._OwnsLaunchedWindow(hwnd, launchInfo["PID"])
if !owned
throw TargetError("The launched browser window could not be verified. No unrelated window was attached.")
verified := IsObject(requested) && requested["Browser"] = launchInfo["Browser"] && requested["ProfileId"] = launchInfo["ProfileId"]
return this.AttachToWindow(sName, hwnd, launchInfo["Browser"], reqProf, launchInfo["FriendlyName"], owned, "", verified)
}
}
; Step 5: Handle Unavailable Requested Profile according to Fallback Policy (Section 51 & vNext Section 10)
switch effPolicy {
case StudioConstants.PolicyStrict:
throw TargetError(Format("{1} — {2} is unavailable (Fallback Policy: Strict).", bType, reqProf))
case StudioConstants.PolicyPreferConfigured, StudioConstants.PolicyCustomOrder:
fallbackHwnd := this._FindCompatibleBrowserWindow(bType, "")
if !fallbackHwnd
fallbackHwnd := this._FindCompatibleBrowserWindow("", "")
if fallbackHwnd {
actualExe := WinGetProcessName("ahk_id " fallbackHwnd)
actualType := UIATargetEngine.BrowserTypeFromExe(actualExe)
notice := Format("{1} unavailable — using current {2} session according to macro fallback policy.", reqProf, actualType)
if IsObject(this.logger)
this.logger.Add("WARN", "Browser", "-", "Profile Fallback", "Fallback", 0, 0, effPolicy, sName, notice)
if IsObject(this.app)
this.app.ShowToast(notice)
return this.AttachToWindow(sName, fallbackHwnd, actualType, reqProf, "Current " actualType " Session", false, notice)
}
throw TargetError(Format("Requested profile '{1} — {2}' is unavailable and no current compatible browser window is open.", bType, reqProf))
case StudioConstants.PolicyPreferConfiguredDefault, StudioConstants.PolicyDefaultProfile:
defProf := this.profileMgr.GetDefaultProfileForBrowser(bType)
defId := IsObject(defProf) ? defProf["ProfileId"] : "Default"
fallbackHwnd := this._FindCompatibleBrowserWindow(bType, defId)
if fallbackHwnd {
notice := Format("{1} unavailable — using {2} Default profile ({3}) according to fallback policy.", reqProf, bType, defId)
if IsObject(this.logger)
this.logger.Add("WARN", "Browser", "-", "Profile Fallback", "Fallback", 0, 0, effPolicy, sName, notice)
if IsObject(this.app)
this.app.ShowToast(notice)
return this.AttachToWindow(sName, fallbackHwnd, bType, reqProf, defId, false, notice)
}
throw TargetError(Format("Default profile for {1} is not currently open.", bType))
case StudioConstants.PolicyAnyCompatible, StudioConstants.PolicyCurrentBrowser:
anyHwnd := this._FindCompatibleBrowserWindow(bType, "")
if !anyHwnd
anyHwnd := this._FindCompatibleBrowserWindow("", "")
if anyHwnd {
actualExe := WinGetProcessName("ahk_id " anyHwnd)
actualType := UIATargetEngine.BrowserTypeFromExe(actualExe)
return this.AttachToWindow(sName, anyHwnd, actualType, reqProf, "Compatible " actualType, false, "")
}
throw TargetError("No compatible browser window is currently open.")
case StudioConstants.PolicyAsk:
anyHwnd := this._FindCompatibleBrowserWindow(bType, "")
if anyHwnd {
ans := MsgBox(Format("Browser profile '{1} — {2}' is not currently open.`n`nUse the currently open {1} window for session '{3}'?", bType, reqProf, sName), "Browser Profile Resolution", "YesNo Icon?")
if ans == "Yes"
return this.AttachToWindow(sName, anyHwnd, bType, reqProf, "User-Approved Current Window", false, "User approved current window fallback.")
}
throw TargetError(Format("Browser profile '{1} — {2}' was not available.", bType, reqProf))
}
throw TargetError(Format("Unable to resolve browser session '{1}' ({2} — {3}).", sName, bType, reqProf))
}
_FindCompatibleBrowserWindow(browserType := "", profileHint := "") {
exeMap := Map(
"Edge", "msedge.exe",
"Chrome", "chrome.exe",
"Firefox", "firefox.exe",
"Brave", "brave.exe",
"Vivaldi", "vivaldi.exe"
)
searchOrder := []
if browserType != "" && exeMap.Has(browserType)
searchOrder.Push(exeMap[browserType])
else {
for _, exe in exeMap
searchOrder.Push(exe)
}
for _, exe in searchOrder {
winList := WinGetList("ahk_exe " exe)
for _, hwnd in winList {
title := ""
try title := WinGetTitle("ahk_id " hwnd)
if title == ""
continue
if profileHint != "" && profileHint != "Default" && profileHint != "Current" {
if InStr(title, profileHint)
return hwnd
} else {
return hwnd
}
}
}
return 0
}
_WaitForBrowserWindow(browserType, pid, timeoutMs := 8000, previousWindows := "") {
t0 := A_TickCount
while (A_TickCount - t0) < timeoutMs {
for hwnd in WinGetList() {
if IsObject(previousWindows) && previousWindows.Has(hwnd)
continue
try {
if this._OwnsLaunchedWindow(hwnd, pid) && UIATargetEngine.BrowserTypeFromExe(WinGetProcessName(hwnd)) == browserType && WinGetTitle(hwnd) != ""
return hwnd
}
}
Sleep(150)
}
return 0
}
AttachToWindow(sessionName, hwnd, browserType := "", requestedProfile := "", effectiveProfile := "", launchedByStudio := false, fallbackNotice := "", profileVerified := false) {
if !hwnd || !WinExist("ahk_id " hwnd)
throw TargetError("Cannot attach to invalid browser window handle.")
sName := Trim(sessionName) != "" ? Trim(sessionName) : "MainBrowser"
winExe := ""
try winExe := WinGetProcessName("ahk_id " hwnd)
bType := browserType != "" ? browserType : UIATargetEngine.BrowserTypeFromExe(winExe)
pid := 0
try pid := WinGetPID("ahk_id " hwnd)
uiaBrowserObj := ""
try uiaBrowserObj := UIA_Browser("ahk_id " hwnd)
catch as err
this.logger.Add("WARN", "", 0, "Browser UIA attach", "Unavailable", 0, 0, "", bType, err.Message)
title := ""
try title := WinGetTitle("ahk_id " hwnd)
url := ""
if IsObject(uiaBrowserObj) {
try url := uiaBrowserObj.GetCurrentURL(true)
}
sess := Map(
"SessionName", sName,
"BrowserType", bType,
"RequestedProfile", requestedProfile != "" ? requestedProfile : "Default",
"EffectiveProfile", effectiveProfile != "" ? effectiveProfile : "Profile unknown",
"Hwnd", hwnd,
"PID", pid,
"Executable", winExe,
"LaunchedByStudio", launchedByStudio ? true : false,
"ProfileVerified", profileVerified ? true : false,
"UIABrowser", uiaBrowserObj,
"CurrentURL", url,
"CurrentTitle", title,
"FallbackNotice", fallbackNotice,
"Connected", true
)
this.sessions[sName] := sess
this.activeSessionName := sName
return sess
}
_RefreshSessionState(sess) {
hwnd := sess["Hwnd"]
if !hwnd || !WinExist("ahk_id " hwnd) {
sess["Connected"] := false
return false
}
sess["Connected"] := true
try sess["CurrentTitle"] := WinGetTitle("ahk_id " hwnd)
if !IsObject(sess["UIABrowser"]) {
try sess["UIABrowser"] := UIA_Browser("ahk_id " hwnd)
}
if IsObject(sess["UIABrowser"]) {
try sess["CurrentURL"] := sess["UIABrowser"].GetCurrentURL(true)
}
return true
}
GetSessionURL(sessionName) {
if !this.sessions.Has(sessionName)
return ""
s := this.sessions[sessionName]
this._RefreshSessionState(s)
return s["CurrentURL"]
}
GetSessionTitle(sessionName) {
if !this.sessions.Has(sessionName)
return ""
s := this.sessions[sessionName]
this._RefreshSessionState(s)
return s["CurrentTitle"]
}
GetSessionTabs(sessionName) {
tabs := []
if !this.sessions.Has(sessionName)
return tabs
s := this.sessions[sessionName]
this._RefreshSessionState(s)
curTitle := s["CurrentTitle"]
curUrl := s["CurrentURL"]
if IsObject(s["UIABrowser"]) {
try {
names := s["UIABrowser"].GetAllTabNames()
for idx, n in names {
isActive := (n != "" && InStr(curTitle, n) > 0)
tabs.Push(Map("Index", idx, "Title", n, "URL", isActive ? curUrl : "", "IsActive", isActive, "Session", sessionName))
}
return tabs
}
}
; Fallback via UIA TabItem search on Browser window
if s["Hwnd"] && WinExist("ahk_id " s["Hwnd"]) {
try {
root := UIA.ElementFromHandle(s["Hwnd"])
tabEls := root.FindElements({Type: "TabItem"})
for idx, tel in tabEls {
tName := tel.Name
isActive := (tName != "" && InStr(curTitle, tName) > 0)
tabs.Push(Map("Index", idx, "Title", tName, "URL", isActive ? curUrl : "", "IsActive", isActive, "Session", sessionName))
}
}
}
return tabs
}
CheckTabExists(sessionName, searchPhrase, matchMode := "Contains") {
tabs := this.GetSessionTabs(sessionName)
for _, t in tabs {
if matchMode == "Exact" ? (t["Title"] = searchPhrase) : InStr(t["Title"], searchPhrase)
return true
}
return false
}
CloseStudioOwnedSession(sessionName) {
if !this.sessions.Has(sessionName)
return false
s := this.sessions[sessionName]
; Invariant: Never kill user-owned browsers unexpectedly (Section 55 & 135)
if !s["LaunchedByStudio"]
throw Error("Session '" sessionName "' was not launched by Nichols Macro Studio. Refusing to close user-owned browser window.")
if this._WindowExists(s["Hwnd"]) {
if !this._OwnsLaunchedWindow(s["Hwnd"], s["PID"])
throw TargetError("The browser window no longer belongs to the launched process. Refusing to close it.")
this._CloseWindow(s["Hwnd"])
}
this.sessions.Delete(sessionName)
return true
}
}
; ==============================================================================
; PART 6: RECORDER, UPGRADE ANALYZER, PLAYBACK, AHK EXPORTER, EXE BUILDER, & DIAGNOSTICS
; ==============================================================================
; Non-activating activity display. Edge bands avoid tinting the working surface.
class ActivityDisplay {
; Visual approximation: a broad, soft halo with a slow breathing rhythm.
; Kept together so the appearance can be tuned against a reference capture.
static GlowDepth := 72
static GlowSoftness := 24
static GlowEdgeAlpha := 132
static PulsePeriodMs := 3600
static PulseMinAlpha := 200
static PulseMaxAlpha := 255
windows := []
glowSurfaces := []
pulseTimer := ""
mode := ""
restoreMain := false
__New(app) => this.app := app
Clear(restore := true) {
if this.pulseTimer != ""
SetTimer(this.pulseTimer, 0)
for surface in this.glowSurfaces {
DllCall("SelectObject", "Ptr", surface.dc, "Ptr", surface.old)
DllCall("DeleteObject", "Ptr", surface.bitmap)
DllCall("DeleteDC", "Ptr", surface.dc)
}
this.glowSurfaces := []
for g in this.windows {
this.app.overlayMgr.overlayHwnds.Delete(g.Hwnd)
try g.Destroy()
}
this.windows := []
this.mode := ""
if restore && this.restoreMain {
this.restoreMain := false
try this.app.gui.mainGui.Show()
}
}
Update() {
recording := this.app.recorder.isRecording
playing := this.app.playback.isRunning
mode := recording ? "Recording" : (playing ? (this.app.playback.isPaused ? "Paused" : "Playing") : "")
if mode == this.mode
return
if mode == "" {
this.Clear()
return
}
this.Clear(false)
this.mode := mode
if !this.restoreMain && IsObject(this.app.gui.mainGui) {
this.restoreMain := !!DllCall("IsWindowVisible", "Ptr", this.app.gui.mainGui.Hwnd)
if this.restoreMain
this.app.gui.mainGui.Hide()
}
this.glowDepth := Clamp(this.app.persistence.settings.Get("GlowDepth", 72), 8, 160)
this.glowSoftness := Clamp(this.app.persistence.settings.Get("GlowSoftness", 24), 4, 64)
this.glowEdgeAlpha := Clamp(this.app.persistence.settings.Get("GlowEdgeAlpha", 132), 20, 220)
this.glowPulseMs := Clamp(this.app.persistence.settings.Get("GlowPulseMs", 3600), 1200, 12000)
this.glowPulseMin := Clamp(this.app.persistence.settings.Get("GlowPulseMin", 200), 80, 255)
color := this.app.persistence.settings.Get(recording ? "RecordingGlowColor" : "PlaybackGlowColor", recording ? "D92D20" : "189B50")
if !RegExMatch(color, "i)^[0-9a-f]{6}$")
color := recording ? "D92D20" : "189B50"
this.glowColor := color
settings := this.app.persistence.settings
if settings.Get(recording ? "RecordingGlow" : "PlaybackGlow", true) {
Loop MonitorGetCount() {
MonitorGet(A_Index, &l, &t, &r, &b)
this.DrawGlow(l, t, r-l, b-t, color)
}
}
if this.glowSurfaces.Length && mode != "Paused" {
this.pulseStarted := A_TickCount
if this.pulseTimer == ""
this.pulseTimer := ObjBindMethod(this, "Pulse")
SetTimer(this.pulseTimer, 33)
}
MonitorGetWorkArea(MonitorGetPrimary(), &l, &t, &r, &b)
badge := this.MakeWindow(color)
badge.MarginX := 18, badge.MarginY := 10
rgb := Integer("0x" color)
luminance := 0.2126*((rgb >> 16) & 255) + 0.7152*((rgb >> 8) & 255) + 0.0722*(rgb & 255)
badge.SetFont("s10 c" (luminance > 160 ? "111111" : "FFFFFF"), "Segoe UI")
if this.HasOwnProp("preview") && this.preview {
badge.AddText("Center", "Glow preview · " (recording ? "Recording glow" : "Playback glow") " · Close settings to stop")
} else {
badge.AddText("", recording ? "● Recording" : (mode == "Paused" ? "Ⅱ Paused" : "▶ Playing"))
badge.SetFont("Bold")
stopHint := badge.AddText("x+12 yp", "Press " settings.Get("Hotkey_Record", "F3") " to stop")
badge.SetFont("Norm")
if !recording
badge.AddText("x+12 yp", settings.Get("Hotkey_Pause", "F7") (mode == "Paused" ? " resume" : " pause"))
}
badge.Show("NA AutoSize x" l " y" (t+16))
WinGetPos(,, &bw, &bh, badge.Hwnd)
WinMove(l + (r-l-bw)//2, t+16,,, badge.Hwnd)
region := DllCall("CreateRoundRectRgn", "Int", 0, "Int", 0, "Int", bw+1, "Int", bh+1, "Int", 18, "Int", 18, "Ptr")
if !DllCall("SetWindowRgn", "Ptr", badge.Hwnd, "Ptr", region, "Int", true)
DllCall("DeleteObject", "Ptr", region)
}
Pulse() {
; Cosine easing has no abrupt change at either end of the breath.
; Reuse the existing pixels; only overall intensity changes each frame.
breath := (1 + Cos((A_TickCount-this.pulseStarted)*6.283185307/this.glowPulseMs))/2
alpha := Round(this.glowPulseMin + (255-this.glowPulseMin)*breath)
for surface in this.glowSurfaces {
NumPut("UChar", alpha, surface.blend, 2)
DllCall("UpdateLayeredWindow", "Ptr", surface.hwnd, "Ptr", 0, "Ptr", surface.dst, "Ptr", surface.size,
"Ptr", surface.dc, "Ptr", surface.src, "UInt", 0, "Ptr", surface.blend, "UInt", 2)
}
}
DrawGlow(x, y, w, h, color) {
; A single per-pixel-alpha surface gives a continuous feathered glow.
; Paint only edge pixels; the entire central work area stays transparent.
g := this.MakeWindow(color)
g.Opt("+E0x80000")
dc := DllCall("CreateCompatibleDC", "Ptr", 0, "Ptr")
info := Buffer(40, 0)
NumPut("UInt", 40, "Int", w, "Int", -h, "UShort", 1, "UShort", 32, info)
bits := 0
bitmap := DllCall("CreateDIBSection", "Ptr", dc, "Ptr", info, "UInt", 0, "Ptr*", &bits, "Ptr", 0, "UInt", 0, "Ptr")
if !bitmap || !dc {
if bitmap
DllCall("DeleteObject", "Ptr", bitmap)
if dc
DllCall("DeleteDC", "Ptr", dc)
throw OSError()
}
old := DllCall("SelectObject", "Ptr", dc, "Ptr", bitmap, "Ptr")
retained := false
try {
rgb := Integer("0x" color)
depth := Min(this.glowDepth, w//2, h//2)
Loop depth {
d := A_Index-1
alpha := Round(this.glowEdgeAlpha * Exp(-0.5 * (d / this.glowSoftness)**2))
pixel := (alpha << 24) | (Round(((rgb >> 16) & 255)*alpha/255) << 16)
| (Round(((rgb >> 8) & 255)*alpha/255) << 8) | Round((rgb & 255)*alpha/255)
Loop w-2*d {
col := d+A_Index-1
NumPut("UInt", pixel, bits+(d*w+col)*4)
NumPut("UInt", pixel, bits+((h-1-d)*w+col)*4)
}
Loop h-2*d-2 {
row := d+A_Index
NumPut("UInt", pixel, bits+(row*w+d)*4)
NumPut("UInt", pixel, bits+(row*w+w-1-d)*4)
}
}
dst := Buffer(8), size := Buffer(8), src := Buffer(8, 0), blend := Buffer(4, 0)
NumPut("Int", x, "Int", y, dst)
NumPut("Int", w, "Int", h, size)
NumPut("UChar", 255, blend, 2), NumPut("UChar", 1, blend, 3)
if !DllCall("UpdateLayeredWindow", "Ptr", g.Hwnd, "Ptr", 0, "Ptr", dst, "Ptr", size,
"Ptr", dc, "Ptr", src, "UInt", 0, "Ptr", blend, "UInt", 2)
throw OSError()
g.Show(Format("NA x{} y{} w{} h{}", x, y, w, h))
this.glowSurfaces.Push({hwnd:g.Hwnd, dc:dc, bitmap:bitmap, old:old, dst:dst, size:size, src:src, blend:blend})
retained := true
} finally {
if !retained {
DllCall("SelectObject", "Ptr", dc, "Ptr", old)
DllCall("DeleteObject", "Ptr", bitmap)
DllCall("DeleteDC", "Ptr", dc)
}
}
}
MakeWindow(color) {
g := Gui("-Caption +AlwaysOnTop +ToolWindow -DPIScale +E0x08000020", "Nichols Macro Studio Activity")
g.BackColor := color
this.windows.Push(g)
this.app.overlayMgr.overlayHwnds[g.Hwnd] := true
return g
}
}
; Opt-in bounded logical trace. Never retain typed text or secret parameters.
class EngineTrace {
static enabled := false
static rows := []
static limit := 100000
static dropped := 0
static Now() {
static frequency := 0
if !frequency
DllCall("QueryPerformanceFrequency", "Int64*", &frequency)
DllCall("QueryPerformanceCounter", "Int64*", &counter := 0)
return counter * 1000 / frequency
}
static Add(kind, id := "", detail := "", due := 0) {
if !this.enabled
return
if this.rows.Length >= this.limit {
this.dropped++
return
}
now := this.Now()
this.rows.Push(Map("seq",this.rows.Length+1,"timeMs",now,"kind",kind,
"id",id,"detail",detail,"dueMs",due,"lateMs",due ? now-due : 0,"hwnd",WinExist("A")))
}
}
class RecorderEngine {
app := ""
uiaEngine := ""
overlayMgr := ""
browserMgr := ""
logger := ""
isRecording := false
recordingMode := "Simple" ; Simple, Advanced
advancedClickMode := "PassivePrecision" ; PassivePrecision, HoldToRefine, ConfirmSignificantClicks
insertTargetMacro := ""
insertAfterActionId := ""
hMouseHook := 0
hKeyHook := 0
textHook := ""
recordedModifiers := Map()
pendingTextEndTick := 0
mouseDowns := Map()
mouseHookProc := 0
keyHookProc := 0
rawEventQueue := []
queueProcessing := false
finishRecordingPending := false
queueTimer := ""
advHoverTimer := ""
lastAdvHoverX := -99999
lastAdvHoverY := -99999
currentAdvDiscovery := ""
recordedActions := []
pendingKeyBuffer := ""
pendingKeyHwnd := 0
pendingKeyTarget := ""
pendingKeyIsSecret := false
lastEventTick := 0
currentEventTick := 0
wheelBurst := ""
pendingTextTick := 0
__New(app, uiaEngine, overlayMgr, browserMgr, logger) {
this.app := app
this.uiaEngine := uiaEngine
this.overlayMgr := overlayMgr
this.browserMgr := browserMgr
this.logger := logger
}
StartRecording(mode := "Simple", targetMacro := "", insertAfterId := "") {
if this.isRecording || this.queueProcessing || this.finishRecordingPending
return false
if IsObject(this.app) && (this.app.currentState == StudioConstants.StateRunning || this.app.currentState == StudioConstants.StatePaused || this.app.currentState == StudioConstants.StateStopping) {
this.app.ShowToast("Cannot start recording while macro playback is active.")
return false
}
this.recordingMode := (mode == "Advanced") ? "Advanced" : "Simple"
if IsObject(this.app) && IsObject(this.app.persistence)
this.advancedClickMode := this.app.persistence.settings.Get("AdvancedClickMode", "PassivePrecision")
this.insertTargetMacro := IsObject(targetMacro) ? targetMacro : (IsObject(this.app) ? this.app.project.GetActiveMacro() : MacroModel())
this.insertAfterActionId := insertAfterId
this.rawEventQueue := []
this.wheelBurst := ""
this.mouseDowns := Map()
this.recordedActions := []
this.pendingKeyBuffer := ""
this.pendingKeyHwnd := 0
this.pendingKeyTarget := ""
this.pendingKeyIsSecret := false
this.lastEventTick := A_TickCount
this.currentEventTick := this.lastEventTick
this.pendingTextTick := 0
this._InstallHooks()
this.isRecording := true
if IsObject(this.app) {
this.app.SetState(this.recordingMode == "Advanced" ? StudioConstants.StateAdvancedRecording : StudioConstants.StateRecording)
}
this.queueTimer := ObjBindMethod(this, "_ProcessQueueTick")
SetTimer(this.queueTimer, 45)
if this.recordingMode == "Advanced" {
this.advHoverTimer := ObjBindMethod(this, "_OnAdvancedHoverTick")
this.lastAdvHoverX := -99999, this.lastAdvHoverY := -99999
this.overlayMgr.ShowHud(20, 20, "ADVANCED RECORDING", "Move over a target to inspect it", "Recording remains active", this.RecordHint())
SetTimer(this.advHoverTimer, 75)
this.boundFreezeKey := IsObject(this.app) ? this.app.persistence.settings.Get("Hotkey_FreezeRefine", "^+f") : "^+f"
try Hotkey(this.boundFreezeKey, ObjBindMethod(this, "TriggerFreezeAndRefineDuringRecord"), "On")
}
return true
}
StopRecording() {
if !this.isRecording
return []
this.isRecording := false
this._UninstallHooks()
if this.queueTimer != "" {
try SetTimer(this.queueTimer, 0)
this.queueTimer := ""
}
if this.advHoverTimer != "" {
try SetTimer(this.advHoverTimer, 0)
this.advHoverTimer := ""
}
if this.HasOwnProp("boundFreezeKey")
try Hotkey(this.boundFreezeKey, "Off")
this.overlayMgr.HideAll()
; A stop hotkey may interrupt target discovery inside the queue consumer.
; Let that consumer finish in event order before inserting the result.
if this.queueProcessing {
this.finishRecordingPending := true
return []
}
this._ProcessQueueTick()
return this._FinishRecording()
}
_FinishRecording() {
this.finishRecordingPending := false
this._FlushPendingKeys()
if IsObject(this.app)
this.app.SetState(StudioConstants.StateIdle)
; Insert recorded actions into the target macro (undoable)
count := this.recordedActions.Length
if count > 0 && IsObject(this.insertTargetMacro) {
if IsObject(this.app) && IsObject(this.app.undoMgr)
this.app.undoMgr.RecordSnapshot(this.app.project, "Record " count " Actions")
refId := this.insertAfterActionId
for _, act in this.recordedActions {
WorkflowTree.InsertAction(this.insertTargetMacro.Actions, act, refId, "After")
refId := act.Id
}
if IsObject(this.app) {
this.app.project.IsDirty := true
this.app.OnRecordingFinished(this.recordedActions)
}
} else if IsObject(this.app) {
this.app.ShowToast("Recording stopped (0 actions captured).")
}
return this.recordedActions
}
_InstallHooks() {
this._UninstallHooks()
this.mouseHookProc := CallbackCreate(ObjBindMethod(this, "_LowLevelMouseProc"), "Fast", 3)
hMod := DllCall("Kernel32\GetModuleHandle", "Ptr", 0, "Ptr")
try {
this.hMouseHook := DllCall("User32\SetWindowsHookEx", "Int", 14, "Ptr", this.mouseHookProc, "Ptr", hMod, "UInt", 0, "Ptr")
if !this.hMouseHook
throw OSError()
; InputHook supplies translated characters (layout, Caps Lock, punctuation, Unicode).
; Stream translated text without the default 1023-character stop limit.
this.textHook := InputHook("V I1 L0 B")
this.textHook.KeyOpt("{All}", "N")
; These belong exclusively to the key-command stream. Otherwise Enter
; arrives both as OnKeyDown and an OnChar newline (likewise Tab).
this.textHook.KeyOpt("{Enter}{NumpadEnter}{Tab}{Backspace}{Escape}", "I")
this.recordedModifiers := Map()
for vk in [0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0x5B,0x5C]
this.recordedModifiers[vk] := GetKeyState(Format("vk{:02X}",vk),"P")
this.textHook.OnChar := ObjBindMethod(this, "_QueueChars")
this.textHook.OnKeyDown := ObjBindMethod(this, "_QueueKey")
this.textHook.OnKeyUp := ObjBindMethod(this, "_QueueKeyUp")
this.textHook.Start()
} catch {
this._UninstallHooks()
throw
}
}
_UninstallHooks() {
if IsObject(this.textHook) {
this.textHook.Stop()
this.textHook := ""
}
if this.hMouseHook {
try DllCall("User32\UnhookWindowsHookEx", "Ptr", this.hMouseHook)
this.hMouseHook := 0
}
if this.hKeyHook {
try DllCall("User32\UnhookWindowsHookEx", "Ptr", this.hKeyHook)
this.hKeyHook := 0
}
if this.mouseHookProc {
try CallbackFree(this.mouseHookProc)
this.mouseHookProc := 0
}
if this.keyHookProc {
try CallbackFree(this.keyHookProc)
this.keyHookProc := 0
}
}
; Low-level mouse hook callback: O(1) push to queue, zero blocking UIA work (Section 11)
_LowLevelMouseProc(nCode, wParam, lParam) {
if nCode >= 0 && this.isRecording {
; WM_LBUTTONDOWN = 0x0201, WM_RBUTTONDOWN = 0x0204, WM_MBUTTONDOWN = 0x0207, WM_MOUSEWHEEL = 0x020A
if wParam == 0x0201 || wParam == 0x0202 || wParam == 0x0204 || wParam == 0x0205 || wParam == 0x0207 || wParam == 0x0208 || wParam == 0x020A {
mx := NumGet(lParam, 0, "Int")
my := NumGet(lParam, 4, "Int")
mouseData := NumGet(lParam, 8, "Int")
flags := NumGet(lParam, 12, "UInt")
; Ignore injected events (LLMHF_INJECTED = 1) so playback never records itself!
if !(flags & 1) {
this.rawEventQueue.Push(Map(
"Kind", "Mouse",
"Msg", wParam,
"X", mx,
"Y", my,
"MouseData", mouseData,
"Tick", A_TickCount
))
}
}
}
return DllCall("User32\CallNextHookEx", "Ptr", 0, "Int", nCode, "UPtr", wParam, "Ptr", lParam, "Ptr")
}
_QueueChars(ih, chars) {
if this.isRecording && ih == this.textHook && !this.RecordedModifier("Ctrl") && !this.RecordedModifier("Win")
this.rawEventQueue.Push(Map("Kind", "Chars", "Text", chars, "Hwnd", WinExist("A"), "Tick", A_TickCount))
}
_TrackModifier(vk, down) {
if (vk >= 0x10 && vk <= 0x12) || (vk >= 0xA0 && vk <= 0xA5) || vk == 0x5B || vk == 0x5C {
this.recordedModifiers[vk] := down
return true
}
return false
}
_QueueKeyUp(ih,vk,sc) {
if this.isRecording && ih == this.textHook
this._TrackModifier(vk,false)
}
RecordedModifier(name) {
keys := Map("Shift",[0x10,0xA0,0xA1],"Ctrl",[0x11,0xA2,0xA3],"Alt",[0x12,0xA4,0xA5],"Win",[0x5B,0x5C])
for vk in keys[name]
if this.recordedModifiers.Get(vk,false)
return true
return false
}
_QueueKey(ih, vk, sc) {
if !this.isRecording || ih != this.textHook
return
; Callbacks can run after a modifier is physically released. Reconstruct
; its event-order state rather than sampling today's GetKeyState here.
if this._TrackModifier(vk,true)
return
name := GetKeyName(Format("vk{:02X}sc{:03X}", vk, sc))
for setting in ["Hotkey_Record", "Hotkey_Play", "Hotkey_Pause", "Hotkey_Stop", "Hotkey_FreezeRefine", "Hotkey_SelectTarget"] {
if IsObject(this.app) && name == RegExReplace(this.app.persistence.settings.Get(setting, ""), "[#!^+~*$<>]")
return
}
if name == "F3" || name == "F8"
return
ctrl := this.RecordedModifier("Ctrl"), alt := this.RecordedModifier("Alt")
win := this.RecordedModifier("Win")
if !ctrl && !alt && !win && !InStr("|Enter|NumpadEnter|Tab|Escape|Backspace|Delete|Insert|Home|End|PgUp|PgDn|Up|Down|Left|Right|F1|F2|F4|F5|F6|F7|F9|F10|F11|F12|", "|" name "|")
return
this.rawEventQueue.Push(Map("Kind", "Key", "VK", vk, "SC", sc, "Ctrl", ctrl, "Alt", alt,
"Win", win, "Shift", this.RecordedModifier("Shift"), "Hwnd", WinExist("A"), "Tick", A_TickCount))
}
_HandleChars(ev) {
hwnd := ev["Hwnd"]
if !hwnd || (IsObject(this.app) && hwnd == this.app.gui.GetMainHwnd())
return
if this.pendingKeyHwnd != hwnd || (this.pendingKeyBuffer != "" && ev["Tick"] - this.pendingTextEndTick > 1500) {
this._FlushPendingKeys()
this.pendingKeyTarget := ""
}
if this.pendingKeyBuffer == "" {
this.pendingTextTick := ev["Tick"]
; Fail closed when focus cannot be verified; never retain unknown password text.
this.pendingKeyIsSecret := true
try {
el := UIA.GetFocusedElement()
this.pendingKeyIsSecret := el.IsPassword || RegExMatch(el.Name, "i)password|passcode|secret|token|security.?code")
}
}
this.pendingKeyHwnd := hwnd
this.pendingTextEndTick := ev["Tick"]
this.pendingKeyBuffer .= this.pendingKeyIsSecret ? "*" : ev["Text"]
}
RecordHint() {
settings := IsObject(this.app) ? this.app.persistence.settings : Map()
return settings.Get("Hotkey_Record", "F3") ": Stop | " settings.Get("Hotkey_FreezeRefine", "^+f") ": Refine"
}
_OnAdvancedHoverTick() {
if !this.isRecording || this.recordingMode != "Advanced"
return
if IsObject(this.app) && this.app.selectionEngine.isActive {
this.lastAdvHoverX := -99999, this.lastAdvHoverY := -99999
return ; The refinement picker owns the same floating information panel.
}
MouseGetPos(&mx, &my, &mHwnd)
studioHwnd := (IsObject(this.app) && IsObject(this.app.gui)) ? this.app.gui.GetMainHwnd() : 0
if (studioHwnd && mHwnd == studioHwnd) || this.overlayMgr.IsOverlayHwnd(mHwnd) {
this.overlayMgr.HideHighlight()
this.overlayMgr.hudGui.Show("NA")
return
}
if Abs(mx - this.lastAdvHoverX) < 4 && Abs(my - this.lastAdvHoverY) < 4 {
this.overlayMgr.hudGui.Show("NA")
return
}
this.lastAdvHoverX := mx
this.lastAdvHoverY := my
disc := this.uiaEngine.DiscoverCandidatesAtPoint(mx, my, studioHwnd)
this.currentAdvDiscovery := disc
cands := disc["Candidates"]
if cands.Length == 0 {
this.overlayMgr.ShowHud(mx, my, "ADVANCED RECORDING", "Move over a target to inspect it", "Recording remains active", this.RecordHint())
return
}
recIdx := disc["RecommendedIndex"]
recCand := cands[Max(1, recIdx)]
r := recCand["Rect"]
pr := recCand.Get("ParentRect", "")
badge := disc["IsWebContent"] ? "WEB · " : (disc["IsBrowser"] ? "BROWSER · " : "DESKTOP · ")
chainStr := "Depth: "
for idx, c in cands {
if idx > 4
break
chainStr .= (idx > 1 ? " › " : "") . (idx == recIdx ? "[" c["Role"] " ★]" : c["Role"])
}
this.overlayMgr.ShowHighlightRect(r["X"], r["Y"], Max(12, r["W"]), Max(12, r["H"]), "10B981", 0, 3)
if IsObject(pr) && pr["W"] > 0 && pr["H"] > 0 && (pr["W"] != r["W"] || pr["H"] != r["H"])
this.overlayMgr.ShowSecondaryRect(pr["X"], pr["Y"], pr["W"], pr["H"], "A855F7", 2)
this.overlayMgr.ShowCrosshair(mx, my, "F59E0B", 12)
this.overlayMgr.ShowHud(mx, my, "ADVANCED RECORDING — " badge disc["WinExe"] " [" this.advancedClickMode "]", recCand["Label"] (recIdx > 0 ? " ★ Recommended" : " — Recommended unavailable"), chainStr, (this.UseCoordinateClicks() ? "Click: Record Window Coordinates" : "Click: Record Semantic Target") " | " this.RecordHint())
}
TriggerFreezeAndRefineDuringRecord(*) {
if !this.isRecording
return
MouseGetPos(&mx, &my)
if IsObject(this.app) && IsObject(this.app.selectionEngine) {
this.app.selectionEngine.StartSelection("UIAAction", ObjBindMethod(this, "_OnFrozenRecordTargetChosen"), Map("X", mx, "Y", my))
}
}
_OnFrozenRecordTargetChosen(target, purpose) {
if !IsObject(target)
return
this._FlushPendingKeys()
recActions := ActionRegistry.GetRecommendedActionsForTarget(target)
actType := recActions.Length > 0 ? recActions[1] : "UIA_Click"
act := ActionModel(actType)
act.Target := target
act.Scope := target.Scope.Clone()
if target.BrowserType != "" {
act.BrowserType := target.BrowserType
act.BrowserProfile := target.ProfileAlias
act.BrowserSession := target.SessionName != "" ? target.SessionName : "MainBrowser"
}
act.FriendlyDescription := act.ComputeFriendlyDescription()
this._AppendRecorded(act)
if IsObject(this.app)
this.app.ShowToast("Recorded refined target: " act.FriendlyDescription)
}
_ProcessQueueTick() {
if this.queueProcessing
return
this.queueProcessing := true
try {
while this.rawEventQueue.Length {
; Swap once per batch: removing index 1 for every event was O(n²).
batch := this.rawEventQueue
this.rawEventQueue := []
for ev in batch {
if ev["Kind"] != "Mouse" || ev["Msg"] != 0x020A
this.wheelBurst := ""
this.currentEventTick := ev["Tick"]
if ev["Kind"] == "Mouse"
this._HandleMouseEvent(ev)
else if ev["Kind"] == "Chars"
this._HandleChars(ev)
else if ev["Kind"] == "Key"
this._HandleKeyEvent(ev)
}
}
} catch as err {
; Capture failure stops acquisition; never silently keep recording a
; corrupted stream or leave its hook/timers installed.
this.isRecording := false
this._UninstallHooks()
for name in ["queueTimer", "advHoverTimer"] {
if this.%name% != ""
SetTimer(this.%name%, 0)
this.%name% := ""
}
this.finishRecordingPending := false
this.rawEventQueue := []
if IsObject(this.app)
this.app.SetState(StudioConstants.StateIdle)
EngineTrace.Add("record-error", "", err.Message)
throw
} finally {
this.queueProcessing := false
}
if this.finishRecordingPending
this._FinishRecording()
}
UseCoordinateClicks() {
return IsObject(this.app) && this.app.persistence.settings.Get("DefaultClickMode", "Coordinate Window") == "Coordinate Window"
}
_HandleMouseEvent(ev) {
msg := ev["Msg"]
button := (msg == 0x204 || msg == 0x205) ? "Right" : ((msg == 0x207 || msg == 0x208) ? "Middle" : "Left")
if msg == 0x201 || msg == 0x204 || msg == 0x207 {
this._FlushPendingKeys()
this.mouseDowns[button] := ev
return
}
endEvent := ""
if msg == 0x202 || msg == 0x205 || msg == 0x208 {
if !this.mouseDowns.Has(button)
return
endEvent := ev
ev := this.mouseDowns[button]
this.mouseDowns.Delete(button)
this.currentEventTick := ev["Tick"]
}
mx := ev["X"], my := ev["Y"]
studioHwnd := (IsObject(this.app) && IsObject(this.app.gui)) ? this.app.gui.GetMainHwnd() : 0
hwnd := DllCall("User32\GetAncestor", "Ptr", DllCall("User32\WindowFromPoint", "Int64", (mx & 0xFFFFFFFF) | (my << 32), "Ptr"), "UInt", 2, "Ptr")
if !hwnd || (studioHwnd && hwnd == studioHwnd) || this.overlayMgr.IsOverlayHwnd(hwnd)
return
this._FlushPendingKeys()
if IsObject(endEvent) && (Abs(endEvent["X"]-mx) > 4 || Abs(endEvent["Y"]-my) > 4) {
target := TargetModel("Recorded drag", "Coordinate", "ScreenCoordinate")
target.ScreenX := mx, target.ScreenY := my
target.WinHwnd := hwnd
act := ActionModel("Mouse_Drag")
act.Target := target
act.Parameters["Button"] := button
act.Parameters["DestinationMode"] := "Screen"
act.Parameters["ToX"] := endEvent["X"], act.Parameters["ToY"] := endEvent["Y"]
act.Parameters["DurationMs"] := Max(15, endEvent["Tick"]-ev["Tick"])
this._AppendRecorded(act)
this.lastEventTick := endEvent["Tick"]
return
}
if IsObject(endEvent) && this.recordedActions.Length {
prev := this.recordedActions[-1]
if (prev.Type == "Mouse_Click" || prev.Type == "UIA_Click") && prev.Parameters.Get("Button", "Left") == button
&& prev.Parameters.Get("ClickCount", 1) == 1 && ev["Tick"]-this.lastEventTick <= DllCall("GetDoubleClickTime", "UInt")
&& Abs(prev.RecordingMeta.Get("RawX", -99999)-mx) <= 4 && Abs(prev.RecordingMeta.Get("RawY", -99999)-my) <= 4 {
prev.Parameters["ClickCount"] := 2
this.lastEventTick := ev["Tick"]
return
}
}
; Mouse wheel event
if ev["Msg"] == 0x020A {
delta := (ev["MouseData"] >> 16) & 0xFFFF
if delta > 32767
delta -= 65536
control := DllCall("User32\WindowFromPoint", "Int64", (mx & 0xFFFFFFFF) | (my << 32), "Ptr")
this.RecordWheel(delta,ev["Tick"],hwnd,control,mx,my)
return
}
; Click event: discover semantic candidates at (mx, my)
btn := (ev["Msg"] == 0x0204) ? "Right" : (ev["Msg"] == 0x0207 ? "Middle" : "Left")
coordinateClick := this.UseCoordinateClicks()
disc := this.DiscoverRecordedClick(mx, my, studioHwnd, hwnd, coordinateClick)
recTarget := disc["RecommendedTarget"]
; Check if target is a password input (Section 43: Secret-Safe Recording)
isSecretField := false
if IsObject(recTarget) {
n := StrLower(recTarget.Name " " recTarget.PrimarySelector.AutomationId)
if RegExMatch(n, "(password|passwd|passcode|secret|pin|token|apikey)")
isSecretField := true
}
for _, cand in disc["Candidates"] {
if cand["Target"].PrimarySelector.ControlType == "Edit" && InStr(StrLower(cand["Target"].Name), "password")
isSecretField := true
}
coordinateClick := this.UseCoordinateClicks()
if !coordinateClick && IsObject(recTarget) && (recTarget.ReliabilityRating == StudioConstants.RelStrong || recTarget.ReliabilityRating == StudioConstants.RelGood || this.recordingMode == "Advanced") {
actType := recTarget.IsWebContent ? "Browser_Click" : (recTarget.PrimarySelector.ControlType == "TabItem" && disc["IsBrowser"] ? "Browser_SelectTab" : "UIA_Click")
act := ActionModel(actType)
act.Target := recTarget
act.Scope := recTarget.Scope.Clone()
act.Parameters["Button"] := btn
if actType == "Browser_SelectTab"
act.Parameters["TabTitle"] := recTarget.Name
if disc["IsBrowser"] {
act.BrowserType := disc["BrowserType"]
act.BrowserProfile := recTarget.ProfileAlias
act.BrowserSession := recTarget.SessionName != "" ? recTarget.SessionName : "MainBrowser"
}
act.RecordingMeta["RawX"] := mx
act.RecordingMeta["RawY"] := my
act.RecordingMeta["UpgradeAvailable"] := false
act.FriendlyDescription := act.ComputeFriendlyDescription()
this._AppendRecorded(act)
this.pendingKeyTarget := recTarget
this.pendingKeyHwnd := hwnd
this.pendingKeyIsSecret := isSecretField
} else {
; Preferred window coordinates, or the existing low-confidence fallback; retain the semantic upgrade proposal.
rel := StudioUtils.ScreenToWindowRelative(mx, my, hwnd)
t := TargetModel(coordinateClick ? Format("({1}, {2})", rel.WinX, rel.WinY) : Format("({1}, {2})", mx, my), "Coordinate", coordinateClick ? "WindowRelative" : "ScreenCoordinate")
t.ScreenX := mx, t.ScreenY := my
t.WinRelX := rel.WinX, t.WinRelY := rel.WinY
t.WinTitle := disc["WinTitle"], t.WinClass := disc["WinClass"], t.WinExe := disc["WinExe"], t.WinHwnd := hwnd
t.ComputeReliability()
act := ActionModel("Mouse_Click")
act.Target := t
act.Parameters["Button"] := btn
act.RecordingMeta["RawX"] := mx
act.RecordingMeta["RawY"] := my
act.RecordingMeta["UpgradeAvailable"] := true
act.RecordingMeta["UpgradeReason"] := "Can be upgraded to a resilient UI Automation target."
if IsObject(recTarget)
act.RecordingMeta["ProposedTarget"] := recTarget.ToMap()
act.Scope := t.Scope.Clone()
act.FriendlyDescription := act.ComputeFriendlyDescription()
this._AppendRecorded(act)
this.pendingKeyTarget := recTarget
this.pendingKeyHwnd := hwnd
this.pendingKeyIsSecret := isSecretField
}
}
DiscoverRecordedClick(mx, my, studioHwnd, hwnd, coordinateClick) {
if !coordinateClick
return this.uiaEngine.DiscoverCandidatesAtPoint(mx, my, studioHwnd)
d := Map("RecommendedTarget", "", "Candidates", [], "WinTitle", "", "WinClass", "", "WinExe", "")
try d["WinTitle"] := WinGetTitle(hwnd)
try d["WinClass"] := WinGetClass(hwnd)
try d["WinExe"] := WinGetProcessName(hwnd)
return d
}
RecordWheel(delta,tick,hwnd,control,x,y) {
if !delta
return
settings := IsObject(this.app) ? this.app.persistence.settings : Map()
merge := settings.Get("RecordingScrollMode","Consolidated") == "Consolidated"
gap := settings.Get("RecordingScrollGapMs",250)
dir := delta > 0 ? "Up" : "Down", burst := this.wheelBurst
if merge && IsObject(burst) && this.recordedActions.Length && this.recordedActions[-1] == burst.Action
&& burst.Direction == dir && burst.Window == hwnd && burst.Control == control
&& tick >= burst.Last && tick-burst.Last <= gap && tick-burst.Start <= 10000
&& Abs(x-burst.X) <= 12 && Abs(y-burst.Y) <= 12 {
burst.Delta += Abs(delta), burst.Last := tick
burst.Action.Parameters["Notches"] := burst.Delta/120
burst.Action.Parameters["ScrollDurationMs"] := tick-burst.Start
burst.Action.FriendlyDescription := burst.Action.ComputeFriendlyDescription()
this.lastEventTick := tick
return
}
act := ActionModel("Mouse_Wheel")
act.Parameters["Direction"] := dir
act.Parameters["Notches"] := Abs(delta)/120
act.FriendlyDescription := act.ComputeFriendlyDescription()
this._AppendRecorded(act,tick)
this.wheelBurst := {Action:act,Direction:dir,Window:hwnd,Control:control,X:x,Y:y,Start:tick,Last:tick,Delta:Abs(delta)}
}
_HandleKeyEvent(ev) {
vk := ev["VK"]
; Ignore standalone modifier key presses
if (vk >= 0x10 && vk <= 0x12) || (vk >= 0xA0 && vk <= 0xA5) || vk == 0x5B || vk == 0x5C
return
activeHwnd := ev.Get("Hwnd", WinExist("A"))
studioHwnd := (IsObject(this.app) && IsObject(this.app.gui)) ? this.app.gui.GetMainHwnd() : 0
if studioHwnd && activeHwnd == studioHwnd
return
this._FlushPendingKeys()
keyName := GetKeyName(Format("vk{:02X}sc{:03X}", vk, ev["SC"]))
combo := (ev["Ctrl"] ? "^" : "") (ev["Alt"] ? "!" : "") (ev.Get("Win", false) ? "#" : "") (ev["Shift"] ? "+" : "") "{" keyName "}"
act := ActionModel("Key_SendKeys")
act.Parameters["Keys"] := combo
act.FriendlyDescription := "Send keys " combo
this._AppendRecorded(act)
}
_AppendRecorded(act, tick := 0) {
tick := tick ? tick : (this.currentEventTick ? this.currentEventTick : A_TickCount)
act.DelayBeforeMs := Max(0, tick - this.lastEventTick)
if IsObject(this.app) && this.app.persistence.settings.Get("RecordingTimingMode","Natural") == "Fixed"
act.DelayBeforeMs := Max(0, this.app.persistence.settings.Get("RecordingFixedDelayMs",100))
act.DelayAfterMs := 0
this.lastEventTick := tick
this.recordedActions.Push(act)
EngineTrace.Add("record", act.Id, act.Type)
}
_FlushPendingKeys() {
if this.pendingKeyBuffer == ""
return
if this.pendingKeyIsSecret {
; Section 43: Secret-Safe Recording — replace with Prompt for Secret
act := ActionModel("Key_PromptSecret")
act.Parameters["SecretVarName"] := "UserPassword"
if IsObject(this.pendingKeyTarget)
act.Target := this.pendingKeyTarget.Clone()
act.FriendlyDescription := act.ComputeFriendlyDescription()
this._AppendRecorded(act, this.pendingTextTick)
} else {
act := ActionModel("Key_TypeText")
act.Parameters["Text"] := this.pendingKeyBuffer
if IsObject(this.pendingKeyTarget) {
act.Target := this.pendingKeyTarget.Clone()
if this.pendingKeyTarget.Role == "Textbox" {
act.RecordingMeta["UpgradeAvailable"] := true
act.RecordingMeta["UpgradeReason"] := "Can be upgraded to semantic 'Set Value' on " this.pendingKeyTarget.GetHumanLabel()
}
}
act.FriendlyDescription := act.ComputeFriendlyDescription()
this._AppendRecorded(act, this.pendingTextTick)
}
this.lastEventTick := Max(this.lastEventTick, this.pendingTextEndTick)
this.pendingKeyBuffer := ""
this.pendingKeyIsSecret := false
}
}
; ==============================================================================
; RECORDING REVIEW & BROWSER UPGRADE ENGINE (vNext Sections 13, 66–69, 139)
; Non-destructively analyzes a macro workflow and proposes undoable upgrades.
; ==============================================================================
class RecordingAnalyzer {
static AnalyzeMacro(macro, uiaEngine := "", browserMgr := "") {
proposals := []
if !IsObject(macro)
return proposals
actions := macro.Actions
i := 1
while i <= actions.Length {
act := actions[i]
; 1. Detect Ctrl+L -> Type URL -> Enter (+ optional Sleep) => Browser_Navigate (Section 13 & 68)
if i + 2 <= actions.Length {
a1 := actions[i], a2 := actions[i + 1], a3 := actions[i + 2]
if a1.Type == "Key_SendKeys" && InStr(StrLower(a1.Parameters.Get("Keys", "")), "^l")
&& (a2.Type == "Key_TypeText" || a2.Type == "UIA_SetValue")
&& a3.Type == "Key_SendKeys" && InStr(StrLower(a3.Parameters.Get("Keys", "")), "enter") {
urlText := a2.Parameters.Get("Text", "")
spanCount := (i + 3 <= actions.Length && actions[i + 3].Type == "Wait_Duration") ? 4 : 3
proposals.Push(Map(
"Id", StudioUtils.GenId("upg"),
"Kind", "BrowserSequenceToNavigate",
"Category", "Browser Navigation",
"ActionId", a1.Id,
"SpanCount", spanCount,
"Before", Format("Ctrl+L → Type '{1}' → Enter{2}", urlText, spanCount == 4 ? " → Sleep" : ""),
"Proposed", Format("Navigate to {1} and wait for page load", urlText),
"Reason", "Replaces fragile address-bar keystrokes and static delay with a single resilient Browser Navigate & Wait step.",
"URL", urlText
))
i += spanCount
continue
}
}
; 2. Detect Repeated Mouse_Wheel + Click => UIA_FindWhileScrolling (vNext Section 68)
if i + 2 <= actions.Length {
a1 := actions[i], a2 := actions[i + 1], a3 := actions[i + 2]
if a1.Type == "Mouse_Wheel" && a2.Type == "Mouse_Wheel" && (a3.Type == "UIA_Click" || a3.Type == "Browser_Click" || a3.Type == "Mouse_Click") {
proposals.Push(Map(
"Id", StudioUtils.GenId("upg"),
"Kind", "ScrollsToFindWhileScrolling",
"Category", "Smart Scrolling",
"ActionId", a1.Id,
"SpanCount", 3,
"Before", Format("Scroll ({1}) → Scroll ({2}) → {3}", a1.Parameters.Get("Direction", "Down"), a2.Parameters.Get("Direction", "Down"), a3.ComputeFriendlyDescription()),
"Proposed", Format("Find '{1}' While Scrolling & Click", IsObject(a3.Target) ? a3.Target.GetHumanLabel() : "Target"),
"Reason", "Replaces manual wheel ticks with bounded Smart Scrolling that adapts to dynamic list lengths.",
"ClickAction", a3
))
i += 3
continue
}
}
; 3. Detect Raw Coordinate Click -> UIA / Browser Semantic Target (Section 13 & 139)
if act.Type == "Mouse_Click" && IsObject(act.Target) && (act.Target.TargetKind == "ScreenCoordinate" || act.Target.TargetKind == "WindowRelative") {
proposals.Push(Map(
"Id", StudioUtils.GenId("upg"),
"Kind", "CoordToSemantic",
"Category", "Semantic Target",
"ActionId", act.Id,
"SpanCount", 1,
"Before", act.ComputeFriendlyDescription(),
"Proposed", act.RecordingMeta.Has("ProposedTarget") ? "Click semantic UIA target" : "Upgrade coordinate to UI Automation Target",
"Reason", "Coordinate clicks break when windows move or resize. Semantic UIA targets locate controls by Role and Name."
))
}
; 4. Detect Click on Text Child inside Interactive Parent -> Promote to Parent Button/Link (vNext Section 68)
if (act.Type == "UIA_Click" || act.Type == "Browser_Click") && IsObject(act.Target) && act.Target.PrimarySelector.ControlType == "Text" && (act.Target.PrimarySelector.ParentType == "Button" || act.Target.PrimarySelector.ParentType == "Hyperlink" || act.Target.PrimarySelector.ParentType == "MenuItem" || act.Target.PrimarySelector.ParentType == "TabItem") {
proposals.Push(Map(
"Id", StudioUtils.GenId("upg"),
"Kind", "TextChildToParentControl",
"Category", "Target Depth",
"ActionId", act.Id,
"SpanCount", 1,
"Before", act.ComputeFriendlyDescription(),
"Proposed", Format("Promote target to parent {1} ('{2}')", act.Target.PrimarySelector.ParentType, act.Target.PrimarySelector.ParentName != "" ? act.Target.PrimarySelector.ParentName : act.Target.Name),
"Reason", "Targeting the interactive parent Button/Link is more resilient than targeting its inner text node."
))
}
; 5. Detect Click on Browser TabItem -> Browser_SelectTab (vNext Section 68)
if act.Type == "UIA_Click" && IsObject(act.Target) && act.Target.PrimarySelector.ControlType == "TabItem" && act.Target.BrowserType != "" {
proposals.Push(Map(
"Id", StudioUtils.GenId("upg"),
"Kind", "TabClickToSelectTab",
"Category", "Browser Tabs",
"ActionId", act.Id,
"SpanCount", 1,
"Before", act.ComputeFriendlyDescription(),
"Proposed", Format('Select Browser Tab "{1}"', act.Target.Name),
"Reason", "Uses UIA_Browser tab selection by title instead of raw UIA tab bar click."
))
}
; 6. Detect Key_TypeText into a UIA Textbox -> UIA_SetValue / Browser_SetValue (Section 13)
if act.Type == "Key_TypeText" && IsObject(act.Target) && (act.Target.Role == "Textbox" || act.Target.PrimarySelector.ControlType == "Edit") {
newType := act.Target.IsWebContent ? "Browser_SetValue" : "UIA_SetValue"
proposals.Push(Map(
"Id", StudioUtils.GenId("upg"),
"Kind", "TypeToSetValue",
"Category", "Input Reliability",
"ActionId", act.Id,
"SpanCount", 1,
"Before", act.ComputeFriendlyDescription(),
"Proposed", Format('Set Value "{1}" on {2}', act.Parameters.Get("Text", ""), act.Target.GetHumanLabel()),
"Reason", "Directly sets the control's Value pattern without depending on keyboard focus timing.",
"NewType", newType
))
}
; 7. Detect Static Sleep (Wait_Duration >= 1500ms) -> Smart Wait for next target (Section 13 & 68)
if act.Type == "Wait_Duration" && act.Parameters.Get("DurationMs", 0) >= 1500 {
nextTargetDesc := "next UI element"
nextTarget := ""
if i + 1 <= actions.Length && ActionRegistry.UsesTarget(actions[i + 1].Type) && IsObject(actions[i + 1].Target) && actions[i + 1].Target.Name != "" {
nextTarget := actions[i + 1].Target
nextTargetDesc := nextTarget.GetHumanLabel()
}
proposals.Push(Map(
"Id", StudioUtils.GenId("upg"),
"Kind", "SleepToSmartWait",
"Category", "Smart Wait",
"ActionId", act.Id,
"SpanCount", 1,
"Before", Format("Sleep {1} ms", act.Parameters.Get("DurationMs", 0)),
"Proposed", "Wait for " nextTargetDesc " (Smart Wait)",
"Reason", "Proceeds immediately when the target is ready instead of waiting a fixed duration.",
"NextTarget", nextTarget
))
}
; 8. Detect Unbound Browser Steps -> Inherit Macro Default Session / Profile (Section 13 & 68)
if (InStr(act.Type, "Browser_") == 1 || (IsObject(act.Target) && act.Target.IsWebContent)) && act.BrowserSession == "" {
defSess := macro.DefaultSessionName != "" ? macro.DefaultSessionName : "MainBrowser"
defProf := macro.DefaultProfileAlias != "" ? macro.DefaultProfileAlias : "Work"
proposals.Push(Map(
"Id", StudioUtils.GenId("upg"),
"Kind", "BindBrowserSession",
"Category", "Browser Session Affinity",
"ActionId", act.Id,
"SpanCount", 1,
"Before", act.ComputeFriendlyDescription() " (Unbound session)",
"Proposed", Format("Bind to session '{1}' ({2} — {3})", defSess, macro.BrowserDefault, defProf),
"Reason", "Ensures browser automation targets the intended profile/session reliably.",
"SessionName", defSess,
"ProfileAlias", defProf,
"BrowserType", macro.BrowserDefault
))
}
i += 1
}
visible := []
for proposal in proposals
if !macro.IgnoredUpgrades.Has(proposal["Kind"] "|" proposal["ActionId"])
visible.Push(proposal)
return visible
}
static ApplyProposal(macro, proposal, uiaEngine := "") {
loc := WorkflowTree.FindById(macro.Actions, proposal["ActionId"])
if !IsObject(loc)
return false
act := loc["Action"]
arr := loc["ParentArray"]
idx := loc["Index"]
switch proposal["Kind"] {
case "BrowserSequenceToNavigate":
navAct := ActionModel("Browser_Navigate")
navAct.Parameters["URL"] := proposal["URL"]
navAct.Parameters["WaitForLoad"] := true
navAct.BrowserType := macro.BrowserDefault
navAct.BrowserProfile := macro.DefaultProfileAlias
navAct.BrowserSession := macro.DefaultSessionName
navAct.FriendlyDescription := navAct.ComputeFriendlyDescription()
span := proposal.Get("SpanCount", 3)
Loop span {
if idx <= arr.Length
arr.RemoveAt(idx)
}
arr.InsertAt(idx, navAct)
return true
case "ScrollsToFindWhileScrolling":
clickAct := proposal["ClickAction"]
scrollAct := ActionModel("UIA_FindWhileScrolling")
scrollAct.Target := IsObject(clickAct.Target) ? clickAct.Target.Clone() : TargetModel("Target", "Button", "UIA")
scrollAct.Parameters["Direction"] := act.Parameters.Get("Direction", "Down")
scrollAct.Parameters["MaxScrolls"] := 10
scrollAct.Parameters["ClickWhenFound"] := true
scrollAct.FriendlyDescription := scrollAct.ComputeFriendlyDescription()
Loop 3 {
if idx <= arr.Length
arr.RemoveAt(idx)
}
arr.InsertAt(idx, scrollAct)
return true
case "TextChildToParentControl":
pType := act.Target.PrimarySelector.ParentType
pName := act.Target.PrimarySelector.ParentName != "" ? act.Target.PrimarySelector.ParentName : act.Target.Name
act.Target.PrimarySelector.ControlType := pType
act.Target.PrimarySelector.ElementName := pName
act.Target.Role := UIATargetEngine.FriendlyRoleFromControlType(pType)
act.Target.Name := pName
act.Target.ComputeReliability()
act.FriendlyDescription := act.ComputeFriendlyDescription()
return true
case "TabClickToSelectTab":
tTitle := act.Target.Name
act.Type := "Browser_SelectTab"
act.Category := "Web & Browser"
act.Parameters := ActionRegistry.GetDefaultParams("Browser_SelectTab")
act.Parameters["TabTitle"] := tTitle
act.FriendlyDescription := act.ComputeFriendlyDescription()
return true
case "CoordToSemantic":
if act.RecordingMeta.Has("ProposedTarget") && (act.RecordingMeta["ProposedTarget"] is Map) {
newT := TargetModel.FromMap(act.RecordingMeta["ProposedTarget"])
act.Target := newT
} else if IsObject(uiaEngine) && act.Target.ScreenX != 0 {
disc := uiaEngine.DiscoverCandidatesAtPoint(act.Target.ScreenX, act.Target.ScreenY)
if !IsObject(disc["RecommendedTarget"])
return false
act.Target := disc["RecommendedTarget"]
} else
return false
act.Type := act.Target.IsWebContent ? "Browser_Click" : "UIA_Click"
act.Category := ActionRegistry.GetCategoryForType(act.Type)
act.RecordingMeta["UpgradeAvailable"] := false
act.FriendlyDescription := act.ComputeFriendlyDescription()
return true
case "TypeToSetValue":
act.Type := proposal.Get("NewType", "UIA_SetValue")
act.Category := ActionRegistry.GetCategoryForType(act.Type)
act.RecordingMeta["UpgradeAvailable"] := false
act.FriendlyDescription := act.ComputeFriendlyDescription()
return true
case "SleepToSmartWait":
dur := act.Parameters.Get("DurationMs", 5000)
act.Type := "Wait_Element"
act.Category := "Wait"
act.TimeoutMs := Max(3000, dur)
act.Parameters := ActionRegistry.GetDefaultParams("Wait_Element")
if IsObject(proposal.Get("NextTarget", "")) {
act.Target := proposal["NextTarget"].Clone()
} else {
act.Target := TargetModel("Confirmation", "Text", "UIA")
act.Target.PrimarySelector.ElementName := "Confirmation"
act.Target.PrimarySelector.ControlType := "Text"
act.Target.ComputeReliability()
}
act.FriendlyDescription := act.ComputeFriendlyDescription()
return true
case "BindBrowserSession":
act.BrowserSession := proposal["SessionName"]
act.BrowserProfile := proposal["ProfileAlias"]
act.BrowserType := proposal["BrowserType"]
if IsObject(act.Target) {
act.Target.SessionName := proposal["SessionName"]
act.Target.ProfileAlias := proposal["ProfileAlias"]
act.Target.BrowserType := proposal["BrowserType"]
}
act.FriendlyDescription := act.ComputeFriendlyDescription()
return true
}
return false
}
}
; ==============================================================================
; PLAYBACK ENGINE, DRY-RUN PREFLIGHT & INTERACTIVE TARGET REPAIR
; (Sections 58–64, 69–75, 98–105, 138–142)
; ==============================================================================
class PlaybackEngine {
playbackSpeed := 1.0
app := ""
varStore := ""
condEngine := ""
uiaEngine := ""
browserMgr := ""
imageEngine := ""
logger := ""
heldInputs := Map()
pausedInputs := Map()
pauseStarted := 0
pausedTotal := 0
catchDepth := 0
isRunning := false
isPaused := false
isSingleStepping := false
stopRequested := false
callDepth := 0
maxCallDepth := 16
currentStepNumber := 0
onStepHighlight := ""
__New(app, varStore, condEngine, uiaEngine, browserMgr, imageEngine, logger) {
this.app := app
this.varStore := varStore
this.condEngine := condEngine
this.uiaEngine := uiaEngine
if uiaEngine is UIATargetEngine
uiaEngine.cancelCheck := (*) => this.stopRequested && this.isRunning
this.browserMgr := browserMgr
this.imageEngine := imageEngine
this.logger := logger
}
; Non-destructive Dry Run / Target & Browser Preflight (vNext Sections 19 & 98)
DryRunTargets(macro, project := "") {
report := []
rows := WorkflowTree.Flatten(macro.Actions, true)
hasPreviousDynamicStep := false
for _, r in rows {
act := r["Action"]
stepNum := r["StepNumber"]
if !act.Enabled
continue
; Browser preflight check
if InStr(act.Type, "Browser_") == 1 || InStr(act.Type, "Profile_") == 1 {
sName := act.BrowserSession != "" ? act.BrowserSession : macro.DefaultSessionName
bType := act.BrowserType != "" ? act.BrowserType : macro.BrowserDefault
prof := act.BrowserProfile != "" ? act.BrowserProfile : macro.DefaultProfileAlias
pol := (act.BrowserFallbackPolicy != "" && act.BrowserFallbackPolicy != "Inherit") ? act.BrowserFallbackPolicy : macro.ProfilePolicy
sim := this.browserMgr.SimulatePolicyResolution(sName, bType, prof, pol)
if act.Type == "Browser_Navigate" || act.Type == "Profile_Launch"
hasPreviousDynamicStep := true
if !ActionRegistry.UsesTarget(act.Type) {
report.Push(Map(
"Step", stepNum,
"ActionId", act.Id,
"Description", act.ComputeFriendlyDescription(),
"State", sim["WouldSucceed"] ? "Available now" : (act.Type == "Profile_Launch" ? "Will launch on run" : "Session unavailable"),
"Detail", sim["Summary"]
))
continue
}
}
if ActionRegistry.UsesTarget(act.Type) && IsObject(act.Target) {
tr := this.uiaEngine.TestTarget(act.Target, false)
if tr["Found"] {
state := (tr["MatchCount"] > 1) ? "Ambiguous (" tr["MatchCount"] " matches)" : "Available now"
report.Push(Map(
"Step", stepNum,
"ActionId", act.Id,
"Description", act.ComputeFriendlyDescription(),
"State", state,
"Detail", tr["Message"] " [" tr["StrategyUsed"] "]"
))
} else {
state := hasPreviousDynamicStep ? "Not currently expected (appears after earlier step)" : "Broken / Not currently visible"
report.Push(Map(
"Step", stepNum,
"ActionId", act.Id,
"Description", act.ComputeFriendlyDescription(),
"State", state,
"Detail", tr["Message"]
))
}
if act.Type == "UIA_Click" || act.Type == "Browser_Click" || act.Type == "Browser_ClickAndWaitNewTab"
hasPreviousDynamicStep := true
} else {
report.Push(Map(
"Step", stepNum,
"ActionId", act.Id,
"Description", act.ComputeFriendlyDescription(),
"State", "Ready",
"Detail", "No external UI target required"
))
}
}
return report
}
PlayMacro(macro, startIndex := 1, endIndex := 0, singleStep := false) {
if this.isRunning {
if this.stopRequested
return false
if this.isPaused {
this.Resume()
return true
}
return false
}
if IsObject(this.app) && (this.app.currentState == StudioConstants.StateRecording || this.app.currentState == StudioConstants.StateAdvancedRecording) {
this.app.ShowToast("Stop recording before starting playback.")
return false
}
; Validate AST before playback (Section 75)
problems := WorkflowTree.ValidateTree(macro.Actions)
for _, pr in problems {
if pr["Severity"] == "Error" && (pr.Get("FixCode", "") == "DeleteInvalidLoopJump" || pr.Get("FixCode", "") == "UnknownAction") {
MsgBox("Cannot start playback due to workflow error:`n`n" pr["Message"], "Workflow Validation Error", "Iconx")
return false
}
}
if macro.PlaybackSpeed <= 0 || macro.PlaybackSpeed > 100
throw ValueError("Playback speed must be greater than zero and at most 100.")
ActionOptions.ValidateFlow(macro.Actions)
this.playbackSpeed := macro.PlaybackSpeed
this.isRunning := true
this.isPaused := false
this.isSingleStepping := singleStep
this.stopRequested := false
this.callDepth := 0
this.catchDepth := 0
this.currentStepNumber := 0
this.jumpCounts := Map()
try TargetModel.MetricsStart() ; [NMS-PC-02c]
failed := false
try {
this.pausedInputs.Clear()
this.pausedTotal := 0
if IsObject(this.app) {
this.app.SetState(StudioConstants.StateRunning)
this.varStore.LoadFromContext(this.app.project, macro)
} else {
this.varStore.LoadFromContext("", macro)
}
this.logger.Add("INFO", macro.Name, 0, "Macro Start", "Running", 0, 0, "", "", "Starting playback of '" macro.Name "'")
slice := []
for idx, act in macro.Actions {
if idx >= startIndex && (endIndex <= 0 || idx <= endIndex)
slice.Push(act)
}
flowSignal := this._ExecuteActionList(macro, slice)
failed := flowSignal == "ERROR"
} catch as err {
failed := true
this.logger.Add("ERROR", macro.Name, this.currentStepNumber, "Unhandled Exception", "Failed", 0, 0, "", "", err.Message)
} finally {
this.ReleaseHeldInputs()
try { ; [NMS-PC-02d] one-line summary of how targets resolved during this run
mTxt := TargetModel.MetricsText(TargetModel.MetricsStop())
if mTxt != ""
this.logger.Add("INFO", macro.Name, this.currentStepNumber, "Target resolution summary", "Info", 0, 0, "", "", mTxt)
}
this.isRunning := false
this.isPaused := false
this.isSingleStepping := false
if IsObject(this.app)
this.app.SetState(StudioConstants.StateIdle)
this.logger.Add("INFO", macro.Name, this.currentStepNumber, "Macro Complete", failed ? "Failed" : (this.stopRequested ? "Stopped" : "Finished"), 0, 0, "", "", failed ? "Playback failed; see the action error above." : (this.stopRequested ? "Playback stopped by user." : "Playback completed."))
}
return !this.stopRequested && !failed
}
SetHeldInput(key, down, kind := "Key") {
if !RegExMatch(key, "^[A-Za-z0-9_]+$") || (!GetKeyVK(key) && !GetKeySC(key))
throw ValueError("Invalid input key: " key)
prior := A_IsCritical
Critical("On")
try {
if down && this.stopRequested
return false
; Register before dispatch, so an exception cannot orphan a DOWN.
if down
this.heldInputs[key] := kind
StudioSafety.Sender.Call("{Blind}{" key (down ? " down}" : " up}"))
if !down && this.heldInputs.Has(key)
this.heldInputs.Delete(key)
EngineTrace.Add(down ? "down" : "up", key, kind)
} finally Critical(prior)
return true
}
ReleaseHeldInputs(clearPaused := true) {
prior := A_IsCritical
Critical("On")
try {
result := StudioSafety.ReleaseAll(this.heldInputs, clearPaused)
for key in result["Released"]
EngineTrace.Add("cleanup-up", key)
if clearPaused
this.pausedInputs.Clear()
return result
} finally Critical(prior)
}
Pause() {
if !this.isRunning || this.isPaused || this.stopRequested
return
this.pauseStarted := EngineTrace.Now()
this.isPaused := true
this.pausedInputs := this.heldInputs.Clone()
this.ReleaseHeldInputs(false)
EngineTrace.Add("pause")
if IsObject(this.app)
this.app.SetState(StudioConstants.StatePaused)
}
Resume() {
if !this.isRunning || !this.isPaused || this.stopRequested
return
this.pausedTotal += EngineTrace.Now() - this.pauseStarted
for key, kind in this.pausedInputs.Clone() {
if this.stopRequested
break
this.SetHeldInput(key, true, kind)
}
this.pausedInputs.Clear()
this.isPaused := false
this.isSingleStepping := false
EngineTrace.Add("resume")
if IsObject(this.app) && !this.stopRequested
this.app.SetState(StudioConstants.StateRunning)
}
StepNext() {
if !this.isRunning || this.stopRequested
return
this.Resume()
this.isSingleStepping := true
}
EmergencyStop(*) {
this.stopRequested := true
this.isPaused := false
this.ReleaseHeldInputs()
EngineTrace.Add("stop")
if IsObject(this.app) && this.isRunning
this.app.SetState(StudioConstants.StateStopping)
}
_WaitIfPausedOrStepping(act) {
if act.Breakpoint && !this.isPaused {
this.Pause()
if IsObject(this.app) {
this.app.ShowToast("Paused at breakpoint: " act.ComputeFriendlyDescription())
}
}
while this.isPaused && !this.stopRequested {
Sleep(50)
}
}
flowDepth := 0
_ExecuteActionList(macro, actList) {
if this.flowDepth >= 64
throw ValueError("Workflow nesting exceeds 64 levels.")
this.flowDepth++
try return this._ExecuteActionListCore(macro, actList)
finally this.flowDepth--
}
_LoopCondition(act) {
met := this.condEngine.EvaluateActionCondition(act)
return act.Parameters.Get("LoopMode", "While") == "Until" ? !met : met
}
ResolvedOptions(p) {
resolved := Map()
for key, value in p
resolved[key] := value is String ? this.varStore.Interpolate(value) : value
return resolved
}
_ExecuteActionListCore(macro, actList) {
labels := ActionOptions.Labels(actList)
nextIndex := 1
while nextIndex <= actList.Length {
act := actList[nextIndex]
nextIndex += 1
if this.stopRequested
return "STOP"
if !act.Enabled
continue
this.currentStepNumber += 1
if this.onStepHighlight != "" && HasMethod(this.onStepHighlight)
try this.onStepHighlight.Call(act.Id)
this._WaitIfPausedOrStepping(act)
if this.stopRequested
return "STOP"
if act.DelayBeforeMs > 0
this._InterruptibleSleep(act.DelayBeforeMs / this.playbackSpeed)
if this.stopRequested
return "STOP"
; Handle structural control flow actions (Section 75)
switch act.Type {
case "Logic_Label":
continue
case "Logic_Goto":
count := this.jumpCounts.Get(act.Id, 0)+1
if count > act.Parameters.Get("MaxJumps", 1000)
throw Error("Jump limit reached for " act.Parameters["DestinationLabel"] ". Use a structured loop for repeated work.")
this.jumpCounts[act.Id] := count
nextIndex := labels[Trim(act.Parameters["DestinationLabel"])]
this._InterruptibleSleep(10)
continue
case "Logic_Break":
this.logger.Add("INFO", macro.Name, this.currentStepNumber, act.ComputeFriendlyDescription(), "Passed", 0, 0, "", "", "Break loop")
return "BREAK"
case "Logic_Continue":
this.logger.Add("INFO", macro.Name, this.currentStepNumber, act.ComputeFriendlyDescription(), "Passed", 0, 0, "", "", "Continue loop")
return "CONTINUE"
case "Macro_Stop":
this.logger.Add("INFO", macro.Name, this.currentStepNumber, act.ComputeFriendlyDescription(), "Passed", 0, 0, "", "", "Macro stop action")
this.stopRequested := true
return "STOP"
case "Logic_If":
t0 := A_TickCount
condMet := this.condEngine.EvaluateActionCondition(act)
this.logger.Add("INFO", macro.Name, this.currentStepNumber, act.ComputeFriendlyDescription(), "Passed", A_TickCount - t0, 0, "Condition", "", "Evaluated to " (condMet ? "TRUE" : "FALSE"))
branch := condMet ? act.Children : (act.HasElse ? act.ElseChildren : [])
if branch.Length > 0 {
sig := this._ExecuteActionList(macro, branch)
if sig != ""
return sig
}
continue
case "Logic_Repeat", "Logic_ForEach":
p := act.Parameters
idxVar := Trim(p.Get("IndexVar", "LoopIndex"))
itemVar := act.Type == "Logic_ForEach" ? Trim(p.Get("ItemVar", "Item")) : ""
if !RegExMatch(idxVar, "^[A-Za-z_][A-Za-z0-9_]*$") || (act.Type == "Logic_ForEach" && (!RegExMatch(itemVar, "^[A-Za-z_][A-Za-z0-9_]*$") || StrLower(itemVar) == StrLower(idxVar)))
throw ValueError("Use distinct item/index names containing letters, numbers and underscores, starting with a letter or underscore.")
saved := Map()
for name in [idxVar, itemVar] {
if name != ""
saved[name] := [this.varStore.runtimeVars.Has(name), this.varStore.runtimeVars.Get(name, "")]
}
if act.Type == "Logic_ForEach" {
mode := p.Get("SourceMode", "Lines")
if mode != "Lines" && mode != "Variable" && mode != "JSON"
throw ValueError("Unknown list source mode: " mode)
raw := mode == "Variable" ? this.varStore.Get(p.Get("Items", "")) : this.varStore.Interpolate(p.Get("Items", ""))
items := raw is Array ? raw.Clone() : (mode == "JSON" ? JsonCodec.Load(raw) : StrSplit(StrReplace(String(raw), "`r"), "`n"))
if !(items is Array)
throw ValueError("List loop requires an array or one item per line.")
if p.Get("SkipEmpty", true) {
filtered := []
for item in items {
if IsObject(item) || item != ""
filtered.Push(item)
}
items := filtered
}
cnt := items.Length
} else {
if p.Get("CountMode", "Fixed") == "Random" {
low := this.varStore.Interpolate(p.Get("Minimum", 1))
high := this.varStore.Interpolate(p.Get("Maximum", 5))
if !IsInteger(low) || !IsInteger(high)
throw ValueError("Random repeat limits must be whole numbers.")
low := Integer(low), high := Integer(high)
if low < 0 || high < low
throw ValueError("Random repeat needs 0 <= minimum <= maximum.")
cnt := Random(low, high)
} else {
value := this.varStore.Interpolate(p.Get("Count", 1))
if !IsInteger(value)
throw ValueError("Repeat count must be a whole number.")
cnt := Integer(value)
}
if cnt < 0
throw ValueError("Repeat count cannot be negative.")
}
try {
Loop cnt {
if this.stopRequested
return "STOP"
while this.isPaused && !this.stopRequested
Sleep(40)
this.varStore.SetRuntime(idxVar, A_Index)
if itemVar != ""
this.varStore.SetRuntime(itemVar, items[A_Index])
sig := this._ExecuteActionList(macro, act.Children)
if sig == "BREAK"
break
if sig == "STOP" || sig == "ERROR"
return sig
}
} finally {
for name, prior in saved {
if prior[1]
this.varStore.runtimeVars[name] := prior[2]
else if this.varStore.runtimeVars.Has(name)
this.varStore.runtimeVars.Delete(name)
}
}
continue
case "Logic_While":
maxIter := Integer(this.varStore.Interpolate(act.Parameters.Get("MaxIterations", 10000)))
if maxIter < 1
throw ValueError("While-loop maximum iterations must be positive.")
iter := 0, broke := false
while !this.stopRequested && iter < maxIter && this._LoopCondition(act) {
iter += 1
this._InterruptibleSleep(10)
sig := this._ExecuteActionList(macro, act.Children)
if sig == "BREAK" {
broke := true
break
}
if sig == "STOP" || sig == "ERROR"
return sig
}
if !this.stopRequested && !broke && iter >= maxIter && this._LoopCondition(act)
throw Error("Loop reached its maximum of " maxIter " iterations before its exit condition was met.")
continue
case "Logic_TryCatch":
this.catchDepth += 1
try sig := this._ExecuteActionList(macro, act.Children)
catch as err {
this.logger.Add("ERROR", macro.Name, this.currentStepNumber, "Try block", "Failed", 0, 0, "", "", err.Message)
sig := "ERROR"
} finally {
this.catchDepth -= 1
}
if sig == "ERROR" {
this.ReleaseHeldInputs()
sig := this._ExecuteActionList(macro, act.ElseChildren)
}
if sig != ""
return sig
continue
case "Macro_Call":
targetName := this.varStore.Interpolate(act.Parameters.Get("TargetMacroName", ""))
if this.callDepth >= this.maxCallDepth {
this.logger.Add("ERROR", macro.Name, this.currentStepNumber, act.ComputeFriendlyDescription(), "Failed", 0, 0, "", "", "Maximum macro call recursion depth (" this.maxCallDepth ") exceeded.")
return "ERROR"
}
if IsObject(this.app) && IsObject(this.app.project) {
subMac := this.app.project.FindMacroByName(targetName)
if IsObject(subMac) {
ActionOptions.ValidateFlow(subMac.Actions)
this.callDepth += 1
try sig := this._ExecuteActionList(subMac, subMac.Actions)
finally this.callDepth -= 1
if sig != ""
return sig
} else {
throw TargetError("Called macro not found: " targetName)
}
} else {
throw TargetError("Macro calls require a project context.")
}
continue
}
; Execute standard action with Retry / Backoff / Interactive Target Repair
res := this._ExecuteSingleActionWithPolicy(macro, act)
act.RuntimeStatus := res.Status
if !res.Success {
if act.OnFailure == "Skip" || act.OnFailure == "Continue" {
continue
}
return "ERROR"
}
if act.DelayAfterMs > 0
this._InterruptibleSleep(act.DelayAfterMs / this.playbackSpeed)
if this.isSingleStepping && !this.stopRequested
this.Pause()
}
return ""
}
_InterruptibleSleep(ms) {
if !IsNumber(ms) || ms < 0 || ms > 2147483647
throw ValueError("Wait must be between 0 and 2147483647 milliseconds.")
origin := EngineTrace.Now(), pauseBase := this.pausedTotal
Loop {
while this.isPaused && !this.stopRequested
Sleep(10)
if this.stopRequested
return
due := origin + ms + this.pausedTotal - pauseBase
remaining := due - EngineTrace.Now()
if remaining <= 0
break
; Recheck elapsed QPC time, never subtract a requested sleep duration.
Sleep(Max(1, Min(10, Floor(remaining))))
}
EngineTrace.Add("wait", "", ms, due)
}
_ExecuteSingleActionWithPolicy(macro, act) { ; [NMS-PC-04h] optional confirmation before risky steps
riskWhy := this._RiskyActionReason(act)
if riskWhy != "" {
riskChoice := this._ConfirmRiskyAction(macro, act, riskWhy)
if riskChoice != "Run" {
riskSkip := (riskChoice == "Skip")
if !riskSkip
this.stopRequested := true
riskMsg := riskSkip ? "Skipped at risky-step confirmation." : "Stopped at risky-step confirmation."
this.logger.Add("WARN", macro.Name, this.currentStepNumber, act.ComputeFriendlyDescription(), riskSkip ? "Skipped" : "Stopped", 0, 0, "", "", riskMsg)
return ActionResultModel(riskSkip, riskSkip ? "Skipped" : "Stopped", riskMsg)
}
}
maxRetries := Max(0, act.RetryCount)
pollMs := Max(50, act.PollingIntervalMs)
timeoutMs := Max(200, act.TimeoutMs)
Loop {
attempt := 0
lastResult := ActionResultModel(false, "Stopped", "Playback cancelled")
tStart := A_TickCount
while attempt <= maxRetries && !this.stopRequested {
if attempt > 0 {
delay := pollMs
if act.BackoffStrategy == "Linear"
delay := pollMs * attempt
else if act.BackoffStrategy == "Exponential"
delay := pollMs * (2 ** (attempt - 1))
this._InterruptibleSleep(Min(delay, 3000))
}
if this.stopRequested
break
actedButUnverified := false ; [NMS-PB-01] action RAN but its post-check failed: never re-run a non-repeatable action
this.inputMayHaveOccurred := false
lastResult := this._DispatchAction(macro, act)
actedButUnverified := this.inputMayHaveOccurred && !lastResult.Success
if lastResult.Success && act.ExpectOutcome != "" && act.ExpectOutcome != "None" {
expOk := this._VerifyPostActionExpectation(macro, act)
if !expOk {
actedButUnverified := true
lastResult.Success := false
lastResult.Status := "Failed"
lastResult.Message .= " [Post-action expectation '" act.ExpectOutcome "' (" act.ExpectValue ") timed out]"
}
}
lastResult.RetryCount := attempt
if lastResult.Success
break
if actedButUnverified {
lastResult.Message .= " [Not retried: the action already ran and repeating it could duplicate its effect]"
break
}
attempt += 1
}
this.logger.Add(
lastResult.Success ? "INFO" : "ERROR",
macro.Name,
this.currentStepNumber,
act.ComputeFriendlyDescription(),
lastResult.Status,
lastResult.DurationMs,
lastResult.RetryCount,
lastResult.StrategyUsed,
lastResult.BrowserSessionUsed,
lastResult.Message,
lastResult.DiagnosticsText
)
if lastResult.Success || this.stopRequested
return lastResult
; Interactive Target Repair when target resolution fails (Sections 99, 100, 142)
if this.catchDepth == 0 && InStr(act.Type, "OCR_") != 1 && ActionRegistry.UsesTarget(act.Type) && IsObject(this.app) && IsObject(this.app.gui) && act.OnFailure != "Skip" && act.OnFailure != "Continue" && !(IsSet(actedButUnverified) && actedButUnverified) { ; [NMS-PC-06] no "Retry" offer for a step that already ran
userChoice := this._PromptInteractiveTargetRepair(macro, act, lastResult)
if userChoice == "Retry"
continue
if userChoice == "Skip" {
lastResult.Status := "Skipped"
lastResult.Success := true
return lastResult
}
}
return lastResult
}
}
; [NMS-PC-03] ---- target ambiguity policy and risky-step confirmation ----
_NmsSetting(name, defaultValue) {
try {
if IsObject(this.app) && this.app.HasOwnProp("persistence")
return this.app.persistence.settings.Get(name, defaultValue)
}
return defaultValue
}
_AmbiguityPolicy() {
p := this._NmsSetting("AmbiguousTargetPolicy", "Warn")
return (p = "Stop" || p = "UseFirst") ? p : "Warn"
}
; Result of resolving a target: if more than one element matched, apply the policy
; Warn (default) = log and use the first match, Stop = refuse, UseFirst = old silent behavior.
_ApplyAmbiguityPolicy(act, target, r) {
try {
if !(r is Map) || !r.Get("Found", false)
return r
n := target.LastMatchCount
if !IsNumber(n) || n <= 1
return r
if StudioUtils.ToBool(act.Parameters.Get("AllowAmbiguousTarget", false))
return r
policy := this._AmbiguityPolicy()
if policy = "UseFirst"
return r
what := target.GetHumanLabel() " matched " n " elements"
if policy = "Stop" {
r["Found"] := false
r["Message"] := "Ambiguous target: " what ". Stopped so a different element is not acted on by mistake. Add an Anchor or Scope to make it unique, or allow ambiguity for this step."
return r
}
this.logger.Add("WARN", "", this.currentStepNumber, act.ComputeFriendlyDescription(), "Ambiguous", 0, 0, "", "", "Ambiguous target: " what ". Used the first match.")
}
return r
}
_RiskyActionReason(act) {
if StudioUtils.ToBool(act.Parameters.Get("ConfirmBeforeRun", false))
return "this step is marked 'confirm before run'"
if !StudioUtils.ToBool(this._NmsSetting("ConfirmRiskyActions", false))
return ""
if InStr("|File_Write|App_Run|Win_State|Browser_CloseTab|Profile_CloseSession|Browser_JSExecute|", "|" act.Type "|")
return "it can change or close things that cannot be undone (" act.Type ")"
return ""
}
; Returns "Run", "Skip" or "Stop". Stop key, window close or a 2 minute timeout all mean Stop.
_ConfirmRiskyAction(macro, act, why) {
choice := ""
g := Gui("+AlwaysOnTop +ToolWindow", "Confirm risky step")
g.SetFont("s10", "Segoe UI")
g.MarginX := 16
g.MarginY := 14
g.Add("Text", "w460", "Step " this.currentStepNumber " in '" macro.Name "' needs confirmation because " why ".")
g.Add("Text", "w460 y+8", act.ComputeFriendlyDescription())
btnRun := g.Add("Button", "w130 h30 y+14", "Run this step")
btnSkip := g.Add("Button", "x+8 w130 h30 Default", "Skip this step")
btnStop := g.Add("Button", "x+8 w130 h30", "Stop macro")
btnRun.OnEvent("Click", (*) => (choice := "Run", g.Destroy()))
btnSkip.OnEvent("Click", (*) => (choice := "Skip", g.Destroy()))
btnStop.OnEvent("Click", (*) => (choice := "Stop", g.Destroy()))
g.OnEvent("Close", (*) => (choice := "Stop", g.Destroy()))
g.OnEvent("Escape", (*) => (choice := "Stop", g.Destroy()))
g.Show("AutoSize Center")
riskHwnd := g.Hwnd
deadline := A_TickCount + 120000
while WinExist("ahk_id " riskHwnd) {
if this.stopRequested || A_TickCount > deadline {
choice := "Stop"
try g.Destroy()
break
}
Sleep(50)
}
return choice == "" ? "Stop" : choice
}
; Verifies Post-Action Expectations ("Success looks like...", vNext Section 60)
_VerifyPostActionExpectation(macro, act) {
expType := act.ExpectOutcome
expVal := this.varStore.Interpolate(act.ExpectValue)
deadline := A_TickCount + Max(300, act.ExpectTimeoutMs)
sName := act.BrowserSession != "" ? act.BrowserSession : macro.DefaultSessionName
while A_TickCount < deadline && !this.stopRequested {
switch expType {
case "URLContains":
if InStr(this.browserMgr.GetSessionURL(sName), expVal)
return true
case "TitleContains":
if InStr(this.browserMgr.GetSessionTitle(sName), expVal) || (expVal != "" && WinExist(expVal))
return true
case "ElementDisappears":
if IsObject(act.Target) {
tr := this.uiaEngine.TestTarget(act.Target, false)
if !tr["Found"]
return true
}
case "ElementAppears", "TextAppears":
if expVal == ""
return true
tCheck := TargetModel(expVal, "Text", "UIA")
tCheck.PrimarySelector.ElementName := expVal
tCheck.PrimarySelector.MatchMode := "Substring"
tr := this.uiaEngine.TestTarget(tCheck, false)
if tr["Found"]
return true
case "NewTabOpened":
tabs := this.browserMgr.GetSessionTabs(sName)
if tabs.Length > 1
return true
default:
return true
}
Sleep(100)
}
return false
}
_DispatchAction(macro, act) {
EngineTrace.Add("dispatch", act.Id, act.Type)
t0 := A_TickCount
p := act.Parameters
target := UIATargetEngine.EffectiveTarget(act, IsObject(this.app) && this.app.HasOwnProp("project") ? this.app.project : 0)
if ActionRegistry.UsesTarget(act.Type) && !IsObject(target) {
missing := ActionResultModel(false, "Failed", "The reusable target reference is unavailable.")
missing.FailureReason := "StaleReference"
return missing
}
try {
if this.stopRequested
return ActionResultModel(false, "Stopped", "Playback cancelled")
if !ActionRegistry.IsKnown(act.Type)
throw ValueError("Unknown action type: " act.Type)
switch act.Type {
case "OCR_ReadText", "OCR_FindText", "OCR_ClickText", "OCR_WaitText":
return this._ExecuteOCR(act, target, t0)
case "Macro_Comment":
return ActionResultModel(true, "Passed", p.Get("Comment", ""))
case "Wait_Duration":
dur := ActionOptions.Duration(this.ResolvedOptions(p))
this._InterruptibleSleep(dur / this.playbackSpeed)
r := ActionResultModel(true, "Passed", "Waited " dur " ms")
r.DurationMs := A_TickCount - t0
return r
case "Wait_Clock":
deadline := ActionOptions.ClockDeadline(this.ResolvedOptions(p))
while A_Now < deadline && !this.stopRequested
this._InterruptibleSleep(Min(250, Max(1, DateDiff(deadline, A_Now, "Seconds")*1000)))
return ActionResultModel(!this.stopRequested, this.stopRequested ? "Stopped" : "Passed", "Clock wait: " p["ClockTime"])
case "Wait_Condition":
deadline := A_TickCount+act.TimeoutMs
while !this.stopRequested {
this._InterruptibleSleep(0)
if this.stopRequested
break
if this.condEngine.EvaluateActionCondition(act)
return ActionResultModel(true, "Passed", "Condition met")
if A_TickCount >= deadline
return ActionResultModel(false, "Failed", "Condition wait timed out")
this._InterruptibleSleep(Max(20, act.PollingIntervalMs))
}
return ActionResultModel(false, "Stopped", "Condition wait cancelled")
case "Wait_FirstMatch":
return this._ExecuteWaitFirstMatch(macro, act, t0)
case "Wait_NewTab":
return this._ExecuteBrowserAction(macro, act, target, t0)
case "Wait_ManualCheckpoint":
msg := this.varStore.Interpolate(p.Get("PromptText", "Complete manual step and click OK to continue."))
ans := MsgBox(msg, "Manual Checkpoint — " macro.Name, "OKCancel Iconi AlwaysOnTop")
if ans == "Cancel" {
this.stopRequested := true
return ActionResultModel(false, "Stopped", "User cancelled at Manual Checkpoint.")
}
r := ActionResultModel(true, "Passed", "User confirmed manual checkpoint.")
r.DurationMs := A_TickCount - t0
return r
case "Var_Set":
this.varStore.ExecuteOperation(p.Get("VarName", "MyVar"), p.Get("Operation", "Assign"), p.Get("Value", ""))
val := this.varStore.Get(p.Get("VarName", "MyVar"))
r := ActionResultModel(true, "Passed", Format("${1} = {2}", p.Get("VarName", "MyVar"), val))
r.DurationMs := A_TickCount - t0
return r
case "Var_PromptInput":
vName := p.Get("VarName", "UserInput")
ib := InputBox(this.varStore.Interpolate(p.Get("Prompt", "Enter value:")), macro.Name, "w360 h140", this.varStore.Interpolate(p.Get("DefaultValue", "")))
if ib.Result == "Cancel"
return ActionResultModel(false, "Stopped", "User cancelled input prompt.")
this.varStore.SetRuntime(vName, ib.Value)
return ActionResultModel(true, "Passed", "Captured input into $" vName)
case "Clip_Set":
A_Clipboard := this.varStore.Interpolate(p.Get("Text", ""))
return ActionResultModel(true, "Passed", "Clipboard updated")
case "Clip_Get":
outVar := p.Get("OutputVar", "ClipboardText")
txt := ""
try txt := A_Clipboard
this.varStore.SetRuntime(outVar, txt)
return ActionResultModel(true, "Passed", "Saved Clipboard to $" outVar)
case "Clip_Paste":
if IsObject(target) && target.Name != "" {
tr := this.uiaEngine.TestTarget(target)
if !tr["Found"]
throw TargetError(tr["Message"])
if IsObject(tr["Element"])
tr["Element"].SetFocus()
else
this.ClickInput(tr["X"] " " tr["Y"])
}
this.PasteText(this.varStore.Interpolate(p.Get("Text", "")))
return ActionResultModel(true, "Passed", "Pasted via Clipboard")
case "Audio_ReadLevel", "Audio_Wait":
return this._ExecuteAudioAction(act)
case "File_Read":
fp := this.varStore.Interpolate(p.Get("FilePath", ""))
if !FileExist(fp)
return ActionResultModel(false, "Failed", "File not found: " fp)
txt := FileRead(fp, "UTF-8")
this.varStore.SetRuntime(p.Get("OutputVar", "FileText"), txt)
return ActionResultModel(true, "Passed", "Read " StrLen(txt) " chars from " fp)
case "File_Write":
fp := this.varStore.Interpolate(p.Get("FilePath", ""))
txt := this.varStore.Interpolate(p.Get("Text", ""))
if StudioUtils.ToBool(p.Get("Append", true))
FileAppend(txt, fp, "UTF-8")
else
StudioUtils.AtomicWriteFile(fp, txt)
return ActionResultModel(true, "Passed", "Wrote to " fp)
case "File_Exists":
fp := this.varStore.Interpolate(p.Get("FilePath", ""))
ex := FileExist(fp) != ""
this.varStore.SetRuntime(p.Get("OutputVar", "FileExistsFlag"), ex ? 1 : 0)
return ActionResultModel(true, "Passed", "FileExists(" fp ") = " (ex ? "true" : "false"))
case "App_Run":
cmd := this.varStore.Interpolate(p.Get("TargetCmd", ""))
wDir := this.varStore.Interpolate(p.Get("WorkingDir", ""))
mode := p.Get("WindowMode", "Normal")
Run(cmd, wDir != "" ? wDir : unset, mode == "Normal" ? "" : mode)
return ActionResultModel(true, "Passed", "Launched " cmd)
case "App_OpenURL":
url := this.varStore.Interpolate(p.Get("URL", ""))
Run(url)
return ActionResultModel(true, "Passed", "Opened URL " url)
case "App_WaitProcess":
proc := this.varStore.Interpolate(p.Get("ProcessName", ""))
cond := p.Get("WaitCondition", "Appear")
deadline := A_TickCount + act.TimeoutMs
while A_TickCount < deadline && !this.stopRequested {
exists := ProcessExist(proc) != 0
if (cond == "Appear" && exists) || (cond != "Appear" && !exists)
return ActionResultModel(true, "Passed", "Process " proc " condition met")
Sleep(100)
}
return ActionResultModel(false, "Failed", "Timed out waiting for process " proc)
case "Win_Activate", "Win_Wait", "Win_MoveResize", "Win_State":
return this._ExecuteWindowAction(act, target, t0)
case "Mouse_Click", "Mouse_Move", "Mouse_Drag", "Mouse_Wheel", "Mouse_DownUp":
return this._ExecuteMouseAction(act, target, t0)
case "Key_TypeText", "Key_SendKeys", "Key_DownUp", "Key_PromptSecret":
return this._ExecuteKeyAction(macro, act, target, t0)
case "Image_Click", "Pixel_Click", "Pixel_GetColor", "Wait_ImageColor":
return this._ExecuteImagePixelAction(act, target, t0)
case "Profile_Launch", "Profile_AttachSession", "Profile_SwitchSession", "Profile_CloseSession",
"Browser_Navigate", "Browser_Click", "Browser_ClickAndWaitNewTab", "Browser_SetValue",
"Browser_GetText", "Browser_ExtractLinks", "Browser_FindText",
"Browser_SelectTab", "Browser_NewTab", "Browser_CloseTab", "Browser_NavButton",
"Browser_Scroll", "Browser_Alert", "Browser_JSExecute", "Wait_PageLoad":
return this._ExecuteBrowserAction(macro, act, target, t0)
default:
; Desktop / Semantic UIA actions & Wait_Element
return this._ExecuteDesktopUIAAction(act, target, t0)
}
} catch as err {
r := ActionResultModel(false, "Failed", err.Message)
r.DurationMs := A_TickCount - t0
r.ExceptionText := err.Message
if err is TargetError
r.FailureReason := err.Extra
return r
}
}
; Wait for First Match (Either / Or synchronization, vNext Section 61)
_ExecuteWaitFirstMatch(macro, act, t0) {
p := act.Parameters
aType := p.Get("OutcomeAType", "ElementAppears")
aVal := this.varStore.Interpolate(p.Get("OutcomeAValue", ""))
bType := p.Get("OutcomeBType", "TextAppears")
bVal := this.varStore.Interpolate(p.Get("OutcomeBValue", ""))
outVar := p.Get("OutputVar", "MatchedOutcome")
sName := act.BrowserSession != "" ? act.BrowserSession : macro.DefaultSessionName
deadline := A_TickCount + Max(300, act.TimeoutMs)
while A_TickCount <= deadline && !this.stopRequested {
if this._CheckOutcomeCondition(sName, aType, aVal) {
this.varStore.SetRuntime(outVar, "A")
r := ActionResultModel(true, "Passed", Format("Matched Outcome A ({1}: '{2}') → ${3}='A'", aType, aVal, outVar))
r.DurationMs := A_TickCount - t0
return r
}
if this._CheckOutcomeCondition(sName, bType, bVal) {
this.varStore.SetRuntime(outVar, "B")
r := ActionResultModel(true, "Passed", Format("Matched Outcome B ({1}: '{2}') → ${3}='B'", bType, bVal, outVar))
r.DurationMs := A_TickCount - t0
return r
}
Sleep(Max(60, act.PollingIntervalMs))
}
this.varStore.SetRuntime(outVar, "Timeout")
r := ActionResultModel(false, "Failed", Format("Wait_FirstMatch timed out after {1} ms waiting for A ('{2}') or B ('{3}')", act.TimeoutMs, aVal, bVal))
r.DurationMs := A_TickCount - t0
return r
}
_CheckOutcomeCondition(sName, oType, oVal) {
if oVal == ""
return false
switch oType {
case "URLContains":
return InStr(this.browserMgr.GetSessionURL(sName), oVal) > 0
case "TitleContains":
return InStr(this.browserMgr.GetSessionTitle(sName), oVal) > 0 || WinExist(oVal) != 0
case "VarEquals":
return String(this.varStore.Get(oVal, "")) != ""
default: ; ElementAppears or TextAppears
if this.varStore.Get(oVal, "") == "1" || this.varStore.Get(oVal, "") == "true"
return true
t := TargetModel(oVal, "Text", "UIA")
t.PrimarySelector.ElementName := oVal
t.PrimarySelector.MatchMode := "Substring"
tr := this.uiaEngine.TestTarget(t, false)
return tr["Found"]
}
}
_ExecuteWindowAction(act, target, t0) {
p := act.Parameters
crit := p.Get("WinTitle", "") != "" ? this.varStore.Interpolate(p["WinTitle"]) : (p.Get("WinExe", "") != "" ? "ahk_exe " p["WinExe"] : (IsObject(target) && target.WinExe != "" ? "ahk_exe " target.WinExe : (IsObject(target) ? target.WinTitle : "A")))
if crit == ""
crit := "A"
switch act.Type {
case "Win_Activate":
if !WinExist(crit)
return ActionResultModel(false, "Failed", "Window not found: " crit)
WinActivate(crit)
if !WinWaitActive(crit, , Max(0.1, act.TimeoutMs / 1000))
return ActionResultModel(false, "Failed", "Window did not become active: " crit)
return ActionResultModel(true, "Passed", "Activated " crit)
case "Win_Wait":
condition := p.Get("WindowCondition", "Exists")
if !InStr("|Exists|Closed|Active|Inactive|", "|" condition "|")
throw ValueError("Choose Exists, Closed, Active or Inactive for the window wait.")
deadline := A_TickCount+act.TimeoutMs
while !this.stopRequested {
this._InterruptibleSleep(0)
if this.stopRequested
break
exists := !!WinExist(crit), active := !!WinActive(crit)
met := condition == "Exists" ? exists : (condition == "Closed" ? !exists : (condition == "Active" ? active : !active))
if met
return ActionResultModel(true, "Passed", "Window " condition ": " crit)
if A_TickCount >= deadline
return ActionResultModel(false, "Failed", "Timed out waiting for window: " crit)
this._InterruptibleSleep(Max(20, act.PollingIntervalMs))
}
return ActionResultModel(false, "Stopped", "Window wait cancelled")
case "Win_MoveResize":
if !WinExist(crit)
return ActionResultModel(false, "Failed", "Window not found: " crit)
WinMove(Integer(p.Get("X", 100)), Integer(p.Get("Y", 100)), Integer(p.Get("W", 800)), Integer(p.Get("H", 600)), crit)
return ActionResultModel(true, "Passed", "Moved/Resized " crit)
case "Win_State":
if !WinExist(crit)
return ActionResultModel(false, "Failed", "Window not found: " crit)
st := p.Get("StateAction", "Maximize")
if st == "Minimize"
WinMinimize(crit)
else if st == "Maximize"
WinMaximize(crit)
else if st == "Restore"
WinRestore(crit)
else if st == "Close"
WinClose(crit)
return ActionResultModel(true, "Passed", st " " crit)
}
return ActionResultModel(true, "Passed", "Window action complete")
}
_SmoothMove(x, y) {
this.CheckInputReady()
enabled := !IsObject(this.app) || !this.app.HasOwnProp("persistence") || this.app.persistence.settings.Get("SmoothPointer", true)
if !enabled
return
cursor := Buffer(8, 0)
if !DllCall("GetCursorPos", "Ptr", cursor)
throw Error("The interactive desktop cursor is unavailable; pointer movement was not sent.")
sx := NumGet(cursor, 0, "Int"), sy := NumGet(cursor, 4, "Int")
distance := Sqrt((x-sx)**2 + (y-sy)**2)
steps := Max(1, Ceil(Min(420, Max(90, distance*0.35)) / this.playbackSpeed / 15))
Loop steps {
while this.isPaused && !this.stopRequested
Sleep(40)
if this.stopRequested
throw Error("Pointer movement cancelled")
t := A_Index/steps, eased := t*t*(3-2*t)
MouseMove(Round(sx+(x-sx)*eased), Round(sy+(y-sy)*eased), 0)
this._InterruptibleSleep(15)
}
}
_ExecuteAudioAction(act) {
p := StudioUtils.CloneMap(act.Parameters)
for key, value in p
if value is String
p[key] := this.varStore.Interpolate(value)
ProgramAudio.Validate(p)
detector := AudioTrigger(p), started := A_TickCount, pausedMs := 0
last := Map("Found", false, "Peak", 0), name := p["ProcessName"]
Loop {
if this.stopRequested
return ActionResultModel(false, "Stopped", "Audio wait cancelled")
if this.isPaused {
pauseStart := A_TickCount
while this.isPaused && !this.stopRequested
Sleep(30)
pausedMs += A_TickCount-pauseStart
detector.Reset()
continue
}
last := ProgramAudio.Read(name, p["AudioOutput"])
elapsed := A_TickCount-started-pausedMs
if act.Type == "Audio_ReadLevel" {
if !last["Found"]
return ActionResultModel(false, "Failed", "No audio session for " name ". Start sound in this program and retry.")
this.varStore.SetRuntime(p["OutputVar"], last["Peak"])
return ActionResultModel(true, "Passed", name " peak: " Round(last["Peak"], 2) "%")
}
if detector.Sample(last["Found"], last["Peak"], elapsed) {
this.varStore.SetRuntime(p["OutputVar"], last["Peak"])
return ActionResultModel(true, "Passed", "Audio " p["Trigger"] " condition met for " name " at " Round(last["Peak"], 2) "%")
}
if elapsed >= act.TimeoutMs
return ActionResultModel(false, "Failed", "Audio wait timed out for " name (last["Found"] ? "; last peak " Round(last["Peak"], 2) "%" : "; no matching audio session"))
nextSample := A_TickCount + Min(Integer(p["SampleMs"]), Max(1, act.TimeoutMs-elapsed))
while A_TickCount < nextSample && !this.stopRequested && !this.isPaused
Sleep(Min(30, Max(1, nextSample-A_TickCount)))
}
}
_ExecuteOCR(act, target, t0) {
p := this.ResolvedOptions(act.Parameters)
for key in ["OutputVar", "FoundVar", "MatchCountVar"]
if p.Has(key) && !RegExMatch(p[key], "^[A-Za-z_][A-Za-z0-9_]*$")
throw ValueError("Choose a variable name for " key " using letters, numbers and underscores.")
source := p.Get("OCRSource", "Region")
if act.Type == "OCR_ClickText" {
if source == "Image file" || source == "PDF page"
throw ValueError("Click text needs a screen region, window, or desktop source. File coordinates cannot be clicked on screen.")
if source == "Window" || (source == "Region" && target.Scope.RelativeToWindow) {
hwnd := StudioOCREngine.Window(target)
WinActivate(hwnd)
if !WinWaitActive(hwnd,, Max(0.2,act.TimeoutMs/1000))
throw TargetError("OCR click window could not be activated.")
}
}
deadline := A_TickCount+act.TimeoutMs, stableSince := -1, baseline := "", first := true
waiting := act.Type == "OCR_WaitText"
waitFor := p.Get("OCRWaitFor", "Present")
if waiting && !InStr("|Present|Absent|Changes|", "|" waitFor "|")
throw ValueError("Choose Present, Absent, or Changes for the OCR wait.")
stable := waiting ? ActionOptions.Number(p.Get("StableForMs", 0), "OCR stable time", 0, 3600000) : 0
loop {
this._InterruptibleSleep(0)
if this.stopRequested
return ActionResultModel(false, "Stopped", "OCR cancelled")
capture := StudioOCREngine.Capture(p, target)
if this.stopRequested
return ActionResultModel(false, "Stopped", "OCR cancelled after recognition")
result := capture.result
if act.Type == "OCR_ReadText" {
value := StudioOCREngine.ReadValue(result,p.Get("OutputFormat","Text"))
this.varStore.SetRuntime(p.Get("OutputVar","OCRText"),value)
if p.Get("CopyToClipboard",false)
A_Clipboard := result.Text
return ActionResultModel(true,"Passed","OCR read " result.Words.Length " words in " capture.elapsed " ms")
}
matches := waiting && waitFor == "Changes" ? [] : StudioOCREngine.Matches(result,p)
this.varStore.SetRuntime(p.Get("FoundVar","OCRFound"),!!matches.Length)
this.varStore.SetRuntime(p.Get("MatchCountVar","OCRMatchCount"),matches.Length)
this.varStore.SetRuntime(p.Get("OutputVar","OCRText"),act.Type == "OCR_FindText" ? StudioOCREngine.Rows(matches) : result.Text)
if act.Type == "OCR_FindText"
return ActionResultModel(true,"Passed","OCR found " matches.Length " matches in " capture.elapsed " ms")
if act.Type == "OCR_ClickText" {
match := StudioOCREngine.Select(matches,p), box := match.BoundingRect
point := ActionOptions.Offset(p,Round(box.x+box.w/2),Round(box.y+box.h/2))
if capture.hwnd && !WinActive(capture.hwnd)
throw TargetError("OCR window lost focus before the click.")
this._SmoothMove(point[1],point[2])
this._InterruptibleSleep(0)
if this.stopRequested
return ActionResultModel(false,"Stopped","OCR click cancelled")
if capture.hwnd && !WinActive(capture.hwnd)
throw TargetError("OCR window lost focus before the click.")
count := Integer(p.Get("ClickCount",1)), button := p.Get("Button","Left")
if count < 1 || count > 100 || !InStr("|Left|Right|Middle|", "|" button "|")
throw ValueError("Use Left, Right, or Middle and 1–100 clicks.")
this.ClickInput(Format("{1} {2} {3} {4}",point[1],point[2],button,count))
return ActionResultModel(true,"Passed","Clicked OCR match: " Trim(match.Text))
}
if first
baseline := result.Text
met := waitFor == "Changes" ? (!first && result.Text != baseline) : (waitFor == "Absent" ? !matches.Length : !!matches.Length)
first := false
if met {
if stableSince < 0
stableSince := A_TickCount
if A_TickCount-stableSince >= stable
return ActionResultModel(true,"Passed","OCR wait satisfied: " waitFor)
} else
stableSince := -1
if A_TickCount >= deadline
return ActionResultModel(false,"Failed","OCR wait timed out (" waitFor ")")
this._InterruptibleSleep(Max(100,act.PollingIntervalMs))
}
}
_ExecuteMouseAction(act, target, t0) {
p := act.Parameters
if act.Type == "Mouse_Wheel" {
dir := p.Get("Direction", "Down")
notches := p.Get("Notches",3), duration := p.Get("ScrollDurationMs",0)
if !IsNumber(notches) || notches < 0 || notches > 100000 || !IsNumber(duration) || duration < 0 || duration > 2147483647 || (dir != "Up" && dir != "Down")
throw ValueError("Choose Up or Down, 0–100000 wheel notches, and a nonnegative scroll duration.")
remaining := Round(notches*120), steps := Ceil(remaining/120)
interval := steps > 1 ? duration/(steps-1)/this.playbackSpeed : 0
Loop steps {
this._InterruptibleSleep(0)
if this.stopRequested
return ActionResultModel(false,"Stopped","Scroll stopped")
amount := Min(120,remaining), remaining -= amount
DllCall("mouse_event","UInt",0x0800,"UInt",0,"UInt",0,"Int",dir == "Up" ? amount : -amount,"UPtr",0)
if A_Index < steps && interval > 0
this._InterruptibleSleep(interval)
}
if steps <= 1 && duration > 0
this._InterruptibleSleep(duration/this.playbackSpeed)
if this.stopRequested
return ActionResultModel(false,"Stopped","Scroll stopped")
return ActionResultModel(true, "Passed", "Scrolled wheel " dir " ×" notches)
}
tr := this.uiaEngine.TestTarget(target)
if !tr["Found"]
return ActionResultModel(false, "Failed", tr["Message"])
point := act.Type == "Mouse_Click" ? ActionOptions.Offset(this.ResolvedOptions(p), tr["X"], tr["Y"]) : [tr["X"], tr["Y"]]
cx := point[1], cy := point[2]
btn := p.Get("Button", "Left")
this._SmoothMove(cx, cy)
this.CheckInputReady()
switch act.Type {
case "Mouse_Move":
MouseMove(cx, cy, Integer(p.Get("Speed", 2)))
case "Mouse_Click":
cnt := (btn == "Double") ? 2 : Integer(p.Get("ClickCount", 1))
if cnt < 1 || cnt > 100
throw ValueError("Click count must be between 1 and 100")
bName := (btn == "Double") ? "Left" : btn
this.ClickInput(Format("{1} {2} {3} {4}", cx, cy, bName, cnt))
case "Mouse_Drag":
duration := Max(0, Integer(p.Get("DurationMs", 300))) / this.playbackSpeed
dx := Integer(this.varStore.Interpolate(p.Get("ToX", cx + 50)))
dy := Integer(this.varStore.Interpolate(p.Get("ToY", cy + 50)))
mode := p.Get("DestinationMode", "Screen")
if mode == "Relative" {
dx += cx, dy += cy
} else if mode == "WindowRelative" || mode == "Client" {
hwnd := target.WinHwnd && WinExist("ahk_id " target.WinHwnd) ? target.WinHwnd : (target.WinExe != "" ? WinExist("ahk_exe " target.WinExe) : WinExist(target.WinTitle != "" ? target.WinTitle : "A"))
if !hwnd
throw TargetError("Drag destination window is unavailable")
pt := StudioUtils.WindowRelativeToScreen(dx, dy, hwnd, mode == "Client")
dx := pt.X, dy := pt.Y
} else if mode != "Screen"
throw ValueError("Invalid drag destination mode: " mode)
if btn != "Left" && btn != "Right" && btn != "Middle"
throw ValueError("Drag button must be Left, Right, or Middle")
MouseMove(cx, cy, 0)
try {
key := btn == "Left" ? "LButton" : (btn == "Right" ? "RButton" : "MButton")
this.SetHeldInput(key, true, "Mouse")
steps := Max(1, Ceil(duration / 15))
Loop steps {
if this.stopRequested
return ActionResultModel(false, "Stopped", "Drag cancelled")
MouseMove(Round(cx + (dx-cx)*A_Index/steps), Round(cy + (dy-cy)*A_Index/steps), 0)
this._InterruptibleSleep(duration / steps)
}
} finally {
this.SetHeldInput(key, false, "Mouse")
}
case "Mouse_DownUp":
st := p.Get("State", "Down")
if st != "Down" && st != "Up"
throw ValueError("Mouse state must be Down or Up")
if btn != "Left" && btn != "Right" && btn != "Middle"
throw ValueError("Mouse button must be Left, Right, or Middle")
MouseMove(cx, cy, 0)
key := btn == "Left" ? "LButton" : (btn == "Right" ? "RButton" : "MButton")
this.SetHeldInput(key, st == "Down", "Mouse")
}
r := ActionResultModel(true, "Passed", Format("{1} at ({2}, {3})", act.Type, cx, cy))
r.StrategyUsed := tr["StrategyUsed"]
r.DurationMs := A_TickCount - t0
return r
}
SendPacedText(text, options, nativeEdit := 0) {
options := this.ResolvedOptions(options)
ActionOptions.CharacterDelay(options, false)
expectedWindow := nativeEdit ? 0 : WinExist("A")
pos := 1
while pos <= StrLen(text) {
this._InterruptibleSleep(0)
if this.stopRequested
throw Error("Typing cancelled")
if !nativeEdit && !WinActive(expectedWindow)
throw TargetError("Typing window lost focus; remaining text was not sent.")
length := 1
code := Ord(SubStr(text, pos, 1))
if code >= 0xD800 && code <= 0xDBFF && pos < StrLen(text)
length := 2
character := SubStr(text, pos, length)
if nativeEdit
SendMessage(0xC2, 1, StrPtr(character), nativeEdit)
else
this.SendLiteral(character)
pos += length
if pos <= StrLen(text)
this._InterruptibleSleep(ActionOptions.CharacterDelay(options)/this.playbackSpeed)
}
}
CheckInputReady() {
this._InterruptibleSleep(0)
if this.stopRequested
throw Error("Input cancelled before dispatch")
}
inputMayHaveOccurred := false
ClickInput(options) {
this.CheckInputReady()
this.inputMayHaveOccurred := true
StudioSafety.Clicker.Call(options)
}
SendInputKeys(keys) {
this.CheckInputReady()
StudioSafety.KeySender.Call(keys)
}
SendLiteral(text) {
this.CheckInputReady()
StudioSafety.TextSender.Call(text)
}
PasteText(text) {
if text == ""
return
saved := ClipboardAll()
try {
A_Clipboard := text
if !ClipWait(1)
throw Error("Clipboard text was not available within one second")
this.CheckInputReady()
this.SendInputKeys("^v")
Sleep(150)
} finally {
A_Clipboard := saved
}
}
_ExecuteKeyAction(macro, act, target, t0) {
p := act.Parameters
switch act.Type {
case "Key_TypeText":
txt := this.varStore.Interpolate(p.Get("Text", ""))
method := p.Get("Method", "Auto")
paced := p.Get("TypingDelayMode", "None") != "None"
if paced
method := "Auto"
nativeEdit := 0
if IsObject(target) && target.Name != "" {
tr := this.uiaEngine.TestTarget(target)
if !tr["Found"]
throw TargetError("Typing target unavailable: " tr["Message"])
if IsObject(tr["Element"]) {
try {
handle := tr["Element"].NativeWindowHandle
if handle && RegExMatch(WinGetClass(handle), "i)^(Edit|RichEdit)")
nativeEdit := handle
}
}
}
this.CheckInputReady()
if method == "Auto" && nativeEdit {
; Literal targeted delivery avoids typing into a foreground window
; that the user or another application activated during playback.
if paced
this.SendPacedText(txt, p, nativeEdit)
else
SendMessage(0xC2, 1, StrPtr(txt), nativeEdit) ; EM_REPLACESEL, with undo
} else if method == "ValuePattern" {
if !IsSet(tr) || !IsObject(tr["Element"])
throw TargetError("ValuePattern input requires a UIA target")
tr["Element"].Value := txt
} else if method == "Auto" || method == "SendText" || method == "Paste" {
if IsSet(tr) {
target := tr.Get("ResolvedTarget",target)
hwnd := nativeEdit ? DllCall("GetAncestor", "Ptr", nativeEdit, "UInt", 2, "Ptr") : target.WinHwnd
if !hwnd && (target.WinTitle != "" || target.WinExe != "")
hwnd := WinExist(target.WinTitle (target.WinExe != "" ? " ahk_exe " target.WinExe : ""))
if hwnd && WinExist(hwnd) {
WinActivate(hwnd)
if !WinWaitActive(hwnd,, Max(0.2, act.TimeoutMs/1000))
throw TargetError("Typing window could not be activated. No text was sent.")
}
if nativeEdit {
ControlFocus(nativeEdit)
focused := ControlGetFocus(hwnd)
if focused == "" || ControlGetHwnd(focused, hwnd) != nativeEdit
throw TargetError("Typing field could not receive focus. No text was sent.")
} else if IsObject(tr["Element"])
tr["Element"].SetFocus()
else {
this.CheckInputReady()
this.ClickInput(tr["X"] " " tr["Y"])
}
if hwnd && !WinActive(hwnd)
throw TargetError("Typing window lost focus. No text was sent.")
}
this.CheckInputReady()
if paced
this.SendPacedText(txt, p)
else if method == "Paste"
this.PasteText(txt)
else
this.SendLiteral(txt)
} else
throw ValueError("Unsupported text input method: " method)
if StudioUtils.ToBool(p.Get("SendEnterAfter", false)) {
this.CheckInputReady()
if method == "Auto" && nativeEdit
SendMessage(0xC2, 1, StrPtr("`r`n"), nativeEdit)
else
this.SendInputKeys("{Enter}")
}
return ActionResultModel(true, "Passed", "Typed text (" StrLen(txt) " chars)")
case "Key_SendKeys":
keys := this.varStore.Interpolate(p.Get("Keys", ""))
if RegExMatch(keys, "i)\{[^}]*\s(?:down(?:temp|r)?|up)\s*\}")
throw ValueError("Use Key Down / Key Up actions for held inputs; Send Keys accepts complete keystrokes only.")
this.CheckInputReady()
if StudioUtils.ToBool(p.Get("UseControlSend", false)) {
hwnd := target.WinHwnd && WinExist("ahk_id " target.WinHwnd) ? target.WinHwnd : WinExist(target.WinTitle != "" ? target.WinTitle : "A")
if !hwnd
throw TargetError("ControlSend target window is unavailable")
ControlSend(keys, , "ahk_id " hwnd)
} else
this.SendInputKeys(keys)
return ActionResultModel(true, "Passed", "Sent keys " keys)
case "Key_DownUp":
k := p.Get("Key", "Shift")
st := StrLower(p.Get("State", "Down"))
if st != "down" && st != "up"
throw ValueError("Key state must be Down or Up")
this.SetHeldInput(k, st == "down")
return ActionResultModel(true, "Passed", k " " st)
case "Key_PromptSecret":
secName := p.Get("SecretVarName", "UserPassword")
if !this.varStore.HasSecret(secName) {
ib := InputBox(p.Get("PromptMessage", "Enter secret/password for '" secName "':"), "Protected Secret Input — " macro.Name, "Password w360 h140")
if ib.Result == "Cancel"
return ActionResultModel(false, "Stopped", "User cancelled secret prompt.")
this.varStore.SetSecret(secName, ib.Value)
}
this.CheckInputReady()
secVal := this.varStore.GetSecret(secName)
if IsObject(target) && target.Name != "" {
tr := this.uiaEngine.TestTarget(target)
if !tr["Found"]
throw TargetError("Typing target unavailable: " tr["Message"])
this.CheckInputReady()
if IsObject(tr["Element"])
tr["Element"].SetFocus()
else
this.ClickInput(tr["X"] " " tr["Y"])
}
this.CheckInputReady()
this.SendLiteral(secVal)
return ActionResultModel(true, "Passed", "Typed protected secret [" secName "]")
}
return ActionResultModel(true, "Passed", "Keyboard action complete")
}
_ExecuteImagePixelAction(act, target, t0) {
p := act.Parameters
switch act.Type {
case "Image_Click":
ir := target.BackupTargets.Length ? this.uiaEngine.TestTarget(target) : this.imageEngine.SearchTargetImage(target)
if !ir["Found"]
return ActionResultModel(false, "Failed", ir["Message"])
btn := p.Get("Button", "Left")
point := ActionOptions.Offset(this.ResolvedOptions(p), ir["X"], ir["Y"])
count := btn == "Double" ? 2 : Integer(p.Get("ClickCount", 1))
if count < 1 || count > 100
throw ValueError("Click count must be between 1 and 100")
this._SmoothMove(point[1], point[2])
this.ClickInput(Format("{1} {2} {3} {4}", point[1], point[2], btn == "Double" ? "Left" : btn, count))
r := ActionResultModel(true, "Passed", ir["Message"])
r.StrategyUsed := "ImageMatch"
r.DurationMs := A_TickCount - t0
return r
case "Pixel_Click":
cr := target.BackupTargets.Length ? this.uiaEngine.TestTarget(target) : this.imageEngine.SearchTargetColor(target)
if !cr["Found"]
return ActionResultModel(false, "Failed", cr["Message"])
btn := p.Get("Button", "Left")
point := ActionOptions.Offset(this.ResolvedOptions(p), cr["X"], cr["Y"])
count := btn == "Double" ? 2 : Integer(p.Get("ClickCount", 1))
if count < 1 || count > 100
throw ValueError("Click count must be between 1 and 100")
this._SmoothMove(point[1], point[2])
this.ClickInput(Format("{1} {2} {3} {4}", point[1], point[2], btn == "Double" ? "Left" : btn, count))
r := ActionResultModel(true, "Passed", cr["Message"])
r.StrategyUsed := "PixelMatch"
r.DurationMs := A_TickCount - t0
return r
case "Pixel_GetColor":
sx := target.ScreenX, sy := target.ScreenY
cInfo := this.imageEngine.GetPixelColorInfo(sx, sy)
this.varStore.SetRuntime(p.Get("OutputVar", "PixelHex"), cInfo["Hex"])
return ActionResultModel(true, "Passed", "Read color " cInfo["Hex"])
case "Wait_ImageColor":
cond := p.Get("Condition", "Appear")
deadline := A_TickCount + act.TimeoutMs
while A_TickCount < deadline && !this.stopRequested {
sr := target.BackupTargets.Length ? this.uiaEngine.TestTarget(target) : ((target.TargetKind == "PixelColor") ? this.imageEngine.SearchTargetColor(target) : this.imageEngine.SearchTargetImage(target))
if (cond == "Appear" && sr["Found"]) || (cond == "Disappear" && !sr["Found"]) {
if sr["Found"] {
this.varStore.SetRuntime(p.Get("OutputXVar", "FoundX"), sr["X"])
this.varStore.SetRuntime(p.Get("OutputYVar", "FoundY"), sr["Y"])
}
return ActionResultModel(true, "Passed", sr["Message"])
}
this._InterruptibleSleep(Max(80, act.PollingIntervalMs))
}
return ActionResultModel(false, "Failed", "Timed out waiting for visual target (" cond ").")
}
return ActionResultModel(false, "Failed", "Unknown visual action")
}
VerifyObjectClickPoint(target, x, y) {
if target.TargetKind != "UIA" && target.TargetKind != "BrowserUIA" && target.TargetKind != "Window"
return
hwnd := this.uiaEngine.ResolveWindow(target)
point := (x & 0xFFFFFFFF) | ((y & 0xFFFFFFFF) << 32)
child := DllCall("User32\WindowFromPoint", "Int64", point, "Ptr")
under := child ? DllCall("User32\GetAncestor", "Ptr", child, "UInt", 2, "Ptr") : 0
if !hwnd
throw TargetError("Target scope changed; no click sent",, "WrongScope")
if under != hwnd
throw TargetError("Target point is covered by another window; no click sent",, "Covered")
}
_ExecuteDesktopUIAAction(act, target, t0) {
p := act.Parameters
; Smart Wait / Wait_Element loop
if act.Type == "Wait_Element" {
wCond := p.Get("WaitCondition", "Appear")
expected := this.varStore.Interpolate(p.Get("ExpectedText", ""))
deadline := A_TickCount + act.TimeoutMs
while A_TickCount < deadline && !this.stopRequested {
tr := this.uiaEngine.TestTarget(target)
if wCond == "Appear" && tr["Found"]
return this._BuildUIAResult(true, "Element appeared", tr, t0)
if wCond == "Disappear" && !tr["Found"]
return this._BuildUIAResult(true, "Element disappeared", tr, t0)
if tr["Found"] && IsObject(tr["Element"]) {
el := tr["Element"]
if wCond == "Enabled" {
try if el.IsEnabled
return this._BuildUIAResult(true, "Element is enabled", tr, t0)
} else if wCond == "TextContains" {
try if InStr(el.Name, expected) || InStr(el.Value, expected)
return this._BuildUIAResult(true, "Element text matched '" expected "'", tr, t0)
} else if wCond == "ValueEquals" {
try if el.Value = expected
return this._BuildUIAResult(true, "Element value matched '" expected "'", tr, t0)
}
}
Sleep(Max(80, act.PollingIntervalMs))
}
return this._BuildUIAResult(false, "Timed out waiting for " target.GetHumanLabel() " (" wCond ")", this.uiaEngine.TestTarget(target, true), t0)
}
; Find While Scrolling (vNext Section 64: bounded loop with progress display)
if act.Type == "UIA_FindWhileScrolling" {
maxScrolls := Clamp(Integer(p.Get("MaxScrolls", 12)), 1, 100)
dir := p.Get("Direction", "Down")
step := Clamp(Integer(p.Get("ScrollStep", 4)), 1, 20)
Loop maxScrolls {
if this.stopRequested
break
if IsObject(this.app)
this.app.ShowToast(Format("Searching for {1} — scroll {2}/{3}", target.GetHumanLabel(), A_Index, maxScrolls))
tr := this.uiaEngine.TestTarget(target)
this.CheckInputReady()
if tr["Found"] {
if StudioUtils.ToBool(p.Get("ClickWhenFound", false)) {
this.VerifyObjectClickPoint(target, tr["X"], tr["Y"])
this.ClickInput(tr["X"] " " tr["Y"] " Left 1")
}
return this._BuildUIAResult(true, "Found target after " (A_Index - 1) " scroll(s)", tr, t0)
}
this.CheckInputReady()
return this._BuildUIAResult(false, "Scoped scroll discovery is unavailable; no wheel input was sent to the foreground window.", tr, t0)
}
return this._BuildUIAResult(false, "Target not found within maximum scroll limit (" maxScrolls ")", this.uiaEngine.TestTarget(target, true), t0)
}
; Resolve target (with auto-wait & SettleTimeMs stability check if configured)
tr := this._WaitForTargetResolution(act, target)
this.CheckInputReady()
if !tr["Found"]
return this._BuildUIAResult(false, tr["Message"], tr, t0)
if act.SettleTimeMs > 0 {
r1 := tr.Get("Rect", "")
this._InterruptibleSleep(Min(act.SettleTimeMs, 1000))
this.CheckInputReady()
tr2 := this.uiaEngine.TestTarget(target, false)
if !tr2["Found"]
return this._BuildUIAResult(false, "Target changed during settling: " tr2["Message"], tr2, t0)
tr := tr2
}
this.CheckInputReady()
el := tr["Element"]
switch act.Type {
case "UIA_Click":
point := ActionOptions.Offset(this.ResolvedOptions(p), tr["X"], tr["Y"])
this._SmoothMove(point[1], point[2])
this.CheckInputReady()
method := p.Get("OffsetMode", "None") == "None" ? p.Get("ClickMethod", "Auto") : "Physical"
btn := StrLower(p.Get("Button", "Left"))
count := btn == "double" ? 2 : Integer(p.Get("ClickCount", 1))
if count < 1 || count > 100
throw ValueError("Click count must be between 1 and 100")
if method == "Invoke" {
if !IsObject(el)
throw TargetError("Invoke requires a UIA element")
Loop count {
this.CheckInputReady()
this.inputMayHaveOccurred := true
el.InvokePattern.Invoke()
}
return this._BuildUIAResult(true, "Invoked " target.GetHumanLabel(), tr, t0)
}
if method == "ControlClick" {
if !IsObject(el) || btn != "left" || count != 1
throw TargetError("ControlClick requires one left click on a UIA element")
this.CheckInputReady()
this.inputMayHaveOccurred := true
el.ControlClick()
return this._BuildUIAResult(true, "ControlClicked " target.GetHumanLabel(), tr, t0)
}
if method != "Auto" && method != "Physical" && method != "ControlClick"
throw ValueError("Unsupported desktop click method: " method)
this.VerifyObjectClickPoint(target, point[1], point[2])
this.ClickInput(Format("{1} {2} {3} {4}", point[1], point[2], btn == "double" ? "Left" : btn, count))
return this._BuildUIAResult(true, "Clicked " target.GetHumanLabel(), tr, t0)
case "UIA_SetValue":
if p.Get("TypingDelayMode", "None") != "None" {
if !IsObject(el)
throw TargetError("Paced Set Value needs an accessible input target. Use Type Text for coordinate-only typing.")
nativeEdit := 0
try {
handle := el.NativeWindowHandle
if handle && RegExMatch(WinGetClass(handle), "i)^(Edit|RichEdit)")
nativeEdit := handle
}
if nativeEdit {
if p.Get("ClearFirst", true) {
SendMessage(0xB1, 0, -1, nativeEdit)
SendMessage(0xC2, 1, StrPtr(""), nativeEdit)
}
} else {
hwnd := target.WinHwnd
if !hwnd
hwnd := WinExist(target.WinTitle (target.WinExe != "" ? " ahk_exe " target.WinExe : ""))
if !hwnd
throw TargetError("Paced typing requires a known target window.")
WinActivate(hwnd)
if !WinWaitActive(hwnd,, Max(0.2, act.TimeoutMs/1000))
throw TargetError("Typing window could not be activated.")
el.SetFocus()
if p.Get("ClearFirst", true)
this.SendInputKeys("^a{Backspace}")
}
this.SendPacedText(this.varStore.Interpolate(p.Get("Text", "")), p, nativeEdit)
if p.Get("SendEnterAfter", false) {
if nativeEdit
SendMessage(0xC2, 1, StrPtr("`r`n"), nativeEdit)
else
this.SendInputKeys("{Enter}")
}
return this._BuildUIAResult(true, "Typed value with character pacing", tr, t0)
}
txt := this.varStore.Interpolate(p.Get("Text", ""))
if IsObject(el) {
try {
el.Value := txt
if StudioUtils.ToBool(p.Get("SendEnterAfter", false))
this.SendInputKeys("{Enter}")
return this._BuildUIAResult(true, 'Set value on ' target.GetHumanLabel(), tr, t0)
} catch {
try el.SetFocus()
}
}
this.ClickInput(tr["X"] " " tr["Y"])
Sleep(40)
if StudioUtils.ToBool(p.Get("ClearFirst", true))
this.SendInputKeys("^a{Backspace}")
method := p.Get("Method", "Auto")
if method == "Paste"
this.PasteText(txt)
else if method == "ValuePattern" {
if !IsSet(tr) || !IsObject(tr["Element"])
throw TargetError("ValuePattern input requires a UIA target")
tr["Element"].Value := txt
} else if method == "Auto" || method == "SendText"
this.SendLiteral(txt)
else
throw ValueError("Unsupported text input method: " method)
if StudioUtils.ToBool(p.Get("SendEnterAfter", false))
this.SendInputKeys("{Enter}")
return this._BuildUIAResult(true, 'Typed value into ' target.GetHumanLabel(), tr, t0)
case "UIA_ReadValue":
outVar := p.Get("OutputVar", "ExtractedText")
prop := p.Get("Property", "Auto")
val := ""
if IsObject(el) {
if prop == "Value" || prop == "Auto"
try val := el.Value
if val == "" && (prop == "Name" || prop == "Auto")
try val := el.Name
}
this.varStore.SetRuntime(outVar, val)
return this._BuildUIAResult(true, Format("Read '{1}' → ${2}", SubStr(val, 1, 30), outVar), tr, t0)
case "UIA_Focus":
if !IsObject(el)
throw TargetError("Focus requires an accessible UI Automation element")
el.SetFocus()
return this._BuildUIAResult(true, "Focused " target.GetHumanLabel(), tr, t0)
case "UIA_Toggle":
if !IsObject(el)
throw TargetError("Toggle requires a UIA element supporting TogglePattern")
desired := p.Get("ToggleState", "Toggle")
tp := el.TogglePattern
curState := tp.ToggleState
if desired == "Toggle" || (desired == "Check" && curState != 1) || (desired == "Uncheck" && curState != 0)
tp.Toggle()
else if desired != "Check" && desired != "Uncheck"
throw ValueError("Invalid toggle state: " desired)
return this._BuildUIAResult(true, desired " " target.GetHumanLabel(), tr, t0)
case "UIA_Select":
if !IsObject(el)
throw TargetError("Select requires a UIA element")
itemTxt := this.varStore.Interpolate(p.Get("ItemText", ""))
selected := itemTxt != "" ? el.FindElement({Name: itemTxt, mm: 2}) : el
selected.SelectionItemPattern.Select()
return this._BuildUIAResult(true, "Selected " target.GetHumanLabel(), tr, t0)
case "UIA_ExpandCollapse":
if !IsObject(el)
throw TargetError("Expand/collapse requires a UIA element")
st := p.Get("State", "Expand")
if st == "Expand"
el.ExpandCollapsePattern.Expand()
else if st == "Collapse"
el.ExpandCollapsePattern.Collapse()
else
throw ValueError("Invalid expand/collapse state: " st)
return this._BuildUIAResult(true, st " " target.GetHumanLabel(), tr, t0)
case "UIA_ScrollIntoView":
if !IsObject(el)
throw TargetError("Scroll into view requires a UIA element")
el.ScrollItemPattern.ScrollIntoView()
return this._BuildUIAResult(true, "Scrolled into view: " target.GetHumanLabel(), tr, t0)
}
return this._BuildUIAResult(false, "Unsupported UIA action: " act.Type, tr, t0)
}
_WaitForTargetResolution(act, target) { ; [NMS-PC-03h] resolve, then apply the ambiguity policy
return this._ApplyAmbiguityPolicy(act, target, this._WaitForTargetResolutionCore(act, target))
}
_WaitForTargetResolutionCore(act, target) {
if act.WaitMode == "None"
return this.uiaEngine.TestTarget(target, true)
deadline := A_TickCount + Max(400, act.TimeoutMs)
lastRes := ""
while A_TickCount < deadline && !this.stopRequested {
lastRes := this.uiaEngine.TestTarget(target, false)
if lastRes["Found"] {
if act.RequireEnabled && IsObject(lastRes["Element"]) {
try if !lastRes["Element"].IsEnabled {
this._InterruptibleSleep(Max(80, act.PollingIntervalMs))
continue
}
}
return lastRes
}
Sleep(Max(80, act.PollingIntervalMs))
}
if this.stopRequested
return Map("Found", false, "Message", "Playback cancelled", "StrategyUsed", "")
return this.uiaEngine.TestTarget(target, true)
}
_BuildUIAResult(ok, msg, testRes, t0) {
r := ActionResultModel(ok, ok ? "Passed" : "Failed", msg)
r.DurationMs := A_TickCount - t0
r.StrategyUsed := testRes.Get("StrategyUsed", "")
r.FailureReason := ok ? "" : testRes.Get("Reason", "")
if testRes.Get("IsFallback", false) && ok {
r.Message .= " [Used fallback: " r.StrategyUsed "]"
}
diag := ""
if testRes.Has("StrategyResults") && (testRes["StrategyResults"] is Array) {
for _, sr in testRes["StrategyResults"]
diag .= sr["StrategyName"] ": " sr["Message"] "`r`n"
}
r.DiagnosticsText := diag
return r
}
ResolveTabTitle(tabs, text, mode) {
if mode == "Current"
return ""
if Trim(text) == ""
throw ValueError("Enter a tab title/address, use Select, or choose Current.")
matches := []
for tab in tabs {
title := tab["Title"]
match := false
switch mode {
case "Exact": match := StrCompare(title,text,false) == 0
case "Contains": match := InStr(title,text,false) > 0
case "StartsWith": match := InStr(title,text,false) == 1
case "Regex": match := RegExMatch(title,"i)" text) > 0
case "URLContains": match := tab.Get("URL","") != "" && InStr(tab["URL"],text,false) > 0
default: throw ValueError("Choose a supported tab match mode.")
}
if match
matches.Push(title)
}
if matches.Length != 1
throw TargetError(matches.Length ? "More than one tab matches. Use an exact, unique title." : "No tab matches. URL matching only covers addresses exposed by the browser; choose a title for inactive tabs.")
; Selection by name must still be unique even after a URL-based match.
count := 0
for tab in tabs
if StrCompare(tab["Title"],matches[1],false) == 0
count++
if count != 1
throw TargetError("Tabs share this title. Give the desired tab a unique title or use Current.")
return matches[1]
}
_ExecuteBrowserAction(macro, act, target, t0) {
p := act.Parameters
sName := act.BrowserSession != "" ? act.BrowserSession : (p.Get("SessionName", "") != "" ? p["SessionName"] : (macro.DefaultSessionName != "" ? macro.DefaultSessionName : "MainBrowser"))
bType := act.BrowserType != "" ? act.BrowserType : (p.Get("BrowserType", "") != "" ? p["BrowserType"] : macro.BrowserDefault)
prof := act.BrowserProfile != "" ? act.BrowserProfile : (p.Get("ProfileAlias", "") != "" ? p["ProfileAlias"] : macro.DefaultProfileAlias)
pol := (act.BrowserFallbackPolicy != "" && act.BrowserFallbackPolicy != "Inherit") ? act.BrowserFallbackPolicy : macro.ProfilePolicy
switch act.Type {
case "Profile_Launch":
url := this.varStore.Interpolate(p.Get("URL", ""))
sess := this.browserMgr.ResolveSession(sName, bType, prof, pol, true, url)
r := ActionResultModel(true, "Passed", Format("Session '{1}' connected ({2} — {3})", sName, sess["BrowserType"], sess["EffectiveProfile"]))
r.BrowserSessionUsed := sName
r.ProfileUsed := sess["EffectiveProfile"]
r.DurationMs := A_TickCount - t0
return r
case "Profile_AttachSession":
sess := this.browserMgr.ResolveSession(sName, bType, prof, pol, false)
r := ActionResultModel(true, "Passed", Format("Attached session '{1}' ({2} — {3})", sName, sess["BrowserType"], sess["EffectiveProfile"]))
r.BrowserSessionUsed := sName
r.ProfileUsed := sess["EffectiveProfile"]
r.DurationMs := A_TickCount - t0
return r
case "Profile_SwitchSession":
if !this.browserMgr.IsSessionConnected(sName)
throw TargetError("Browser session is not connected: " sName)
this.browserMgr.activeSessionName := sName
r := ActionResultModel(true, "Passed", "Active browser session set to " sName)
r.BrowserSessionUsed := sName
return r
case "Profile_CloseSession":
if !this.browserMgr.CloseStudioOwnedSession(sName)
throw TargetError("Browser session does not exist: " sName)
r := ActionResultModel(true, "Passed", "Closed Studio-owned session " sName)
r.BrowserSessionUsed := sName
return r
}
; Acquire session for web actions
sess := this.browserMgr.ResolveSession(sName, bType, prof, pol, false)
this.CheckInputReady()
cUIA := sess["UIABrowser"]
if !IsObject(cUIA)
throw TargetError("Browser UI Automation is unavailable. Reconnect this browser session and retry.")
hwnd := sess["Hwnd"]
if hwnd && IsObject(target)
target.WinHwnd := hwnd
switch act.Type {
case "Browser_Navigate":
url := this.varStore.Interpolate(p.Get("URL", ""))
if IsObject(cUIA) {
if StudioUtils.ToBool(p.Get("OpenNewTab",false)) {
previousCount := cUIA.GetAllTabNames().Length
cUIA.NewTab()
deadline := A_TickCount+act.TimeoutMs
while cUIA.GetAllTabNames().Length <= previousCount && A_TickCount < deadline && !this.stopRequested
this._InterruptibleSleep(50)
if this.stopRequested || cUIA.GetAllTabNames().Length <= previousCount
throw TargetError("The new browser tab did not open; navigation was cancelled.")
}
try {
if StudioUtils.ToBool(p.Get("WaitForLoad",true))
cUIA.Navigate(url, this.varStore.Interpolate(p.Get("TargetTitle", "")), act.TimeoutMs)
else
cUIA.SetURL(url,true)
}
catch {
this.CheckInputReady()
WinActivate("ahk_id " hwnd)
this.SendInputKeys("^l")
this._InterruptibleSleep(80)
this.SendLiteral(url)
this.SendInputKeys("{Enter}")
}
}
; Invalidate stale DocumentElement cache and reacquire document after navigation (vNext Section 18)
this.browserMgr.InvalidateDocumentCache(sName)
r := ActionResultModel(true, "Passed", "Navigated to " url)
r.BrowserSessionUsed := sName
r.DurationMs := A_TickCount - t0
return r
case "Browser_Click", "Browser_SetValue":
subAct := act.Clone(false)
subAct.Type := (act.Type == "Browser_Click") ? "UIA_Click" : "UIA_SetValue"
res := this._ExecuteDesktopUIAAction(subAct, target, t0)
res.BrowserSessionUsed := sName
res.ProfileUsed := sess["EffectiveProfile"]
return res
case "Browser_ClickAndWaitNewTab":
beforeTabs := this.browserMgr.GetSessionTabs(sName)
beforeCount := beforeTabs.Length
subAct := act.Clone(false)
subAct.Type := "UIA_Click"
res := this._ExecuteDesktopUIAAction(subAct, target, t0)
if !res.Success
return res
deadline := A_TickCount + act.TimeoutMs
while A_TickCount < deadline && !this.stopRequested {
Sleep(150)
nowTabs := this.browserMgr.GetSessionTabs(sName)
if nowTabs.Length > beforeCount {
newTabTitle := nowTabs[nowTabs.Length]["Title"]
if StudioUtils.ToBool(p.Get("SwitchToNewTab", true)) && IsObject(cUIA) && newTabTitle != ""
try cUIA.SelectTab(newTabTitle, 2, false)
this.browserMgr.InvalidateDocumentCache(sName)
res.Message := Format("Clicked & switched to new tab '{1}'", newTabTitle)
res.BrowserSessionUsed := sName
return res
}
}
this.browserMgr.InvalidateDocumentCache(sName)
res.Success := false
res.Status := this.stopRequested ? "Stopped" : "Failed"
res.Message := "No new browser tab opened before the timeout"
res.BrowserSessionUsed := sName
return res
case "Wait_NewTab":
beforeTabs := this.browserMgr.GetSessionTabs(sName)
beforeCount := beforeTabs.Length
deadline := A_TickCount + act.TimeoutMs
while A_TickCount < deadline && !this.stopRequested {
nowTabs := this.browserMgr.GetSessionTabs(sName)
if nowTabs.Length > beforeCount {
newTabTitle := nowTabs[nowTabs.Length]["Title"]
if StudioUtils.ToBool(p.Get("SwitchToNewTab", true)) && IsObject(cUIA) && newTabTitle != ""
try cUIA.SelectTab(newTabTitle, 2, false)
this.browserMgr.InvalidateDocumentCache(sName)
this.varStore.SetRuntime(p.Get("OutputVar", "NewTabTitle"), newTabTitle)
r := ActionResultModel(true, "Passed", "New tab opened: " newTabTitle)
r.BrowserSessionUsed := sName
r.DurationMs := A_TickCount - t0
return r
}
Sleep(150)
}
return ActionResultModel(false, "Failed", "Timed out waiting for new browser tab.")
case "Browser_ExtractLinks":
outVar := p.Get("OutputVar", "PageLinks")
filterTxt := this.varStore.Interpolate(p.Get("FilterText", ""))
linksStr := ""
if IsObject(cUIA) {
try {
linkEls := cUIA.GetAllLinks()
for _, lel in linkEls {
lName := ""
lUrl := ""
try lName := lel.Name
try lUrl := lel.Value
line := lName . (lUrl != "" ? " (" lUrl ")" : "")
if filterTxt == "" || InStr(line, filterTxt)
linksStr .= (linksStr != "" ? "`r`n" : "") . line
}
}
}
this.varStore.SetRuntime(outVar, linksStr)
r := ActionResultModel(true, "Passed", Format("Extracted page links → ${1}", outVar))
r.BrowserSessionUsed := sName
r.DurationMs := A_TickCount - t0
return r
case "Browser_FindText":
searchTxt := this.varStore.Interpolate(p.Get("SearchText", ""))
outVar := p.Get("OutputVar", "TextFoundFlag")
found := false
if IsObject(cUIA) {
try {
allTxt := cUIA.GetAllText()
found := InStr(allTxt, searchTxt, StudioUtils.ToBool(p.Get("CaseSensitive", false))) > 0
}
}
this.varStore.SetRuntime(outVar, found ? 1 : 0)
r := ActionResultModel(true, "Passed", Format("SearchText('{1}') = {2} → ${3}", searchTxt, found ? "Found" : "Not Found", outVar))
r.BrowserSessionUsed := sName
r.DurationMs := A_TickCount - t0
return r
case "Browser_GetText":
outVar := p.Get("OutputVar", "ExtractedText")
prop := p.Get("Property", "Auto")
val := ""
if prop == "URL" && IsObject(cUIA) {
try val := cUIA.GetCurrentURL(true)
} else if prop == "Title" {
try val := WinGetTitle("ahk_id " hwnd)
} else if prop == "AllText" && IsObject(cUIA) {
try val := cUIA.GetAllText()
} else {
tr := this._WaitForTargetResolution(act, target)
if tr["Found"] && IsObject(tr["Element"]) {
try val := tr["Element"].Name
if val == ""
try val := tr["Element"].Value
}
}
this.varStore.SetRuntime(outVar, val)
r := ActionResultModel(true, "Passed", Format("Extracted '{1}' → ${2}", SubStr(val, 1, 30), outVar))
r.BrowserSessionUsed := sName
r.DurationMs := A_TickCount - t0
return r
case "Browser_SelectTab":
tabTitle := this.varStore.Interpolate(p.Get("TabTitle", ""))
tabTitle := this.ResolveTabTitle(this.browserMgr.GetSessionTabs(sName),tabTitle,p.Get("MatchMode","Contains"))
if IsObject(cUIA) && tabTitle != ""
cUIA.SelectTab(tabTitle, 3, false)
this.browserMgr.InvalidateDocumentCache(sName)
r := ActionResultModel(true, "Passed", "Selected tab '" tabTitle "'")
r.BrowserSessionUsed := sName
return r
case "Browser_NewTab":
if IsObject(cUIA)
cUIA.NewTab()
this.browserMgr.InvalidateDocumentCache(sName)
r := ActionResultModel(true, "Passed", "Opened new tab")
r.BrowserSessionUsed := sName
return r
case "Browser_CloseTab":
tabTitle := this.varStore.Interpolate(p.Get("TabTitle", ""))
tabTitle := this.ResolveTabTitle(this.browserMgr.GetSessionTabs(sName),tabTitle,tabTitle == "" ? "Current" : p.Get("MatchMode","Contains"))
if IsObject(cUIA)
cUIA.CloseTab(tabTitle, 3, false)
this.browserMgr.InvalidateDocumentCache(sName)
r := ActionResultModel(true, "Passed", "Closed tab")
r.BrowserSessionUsed := sName
return r
case "Browser_NavButton":
navAct := p.Get("Action", "Reload")
if IsObject(cUIA) {
if navAct == "Back"
cUIA.Back()
else if navAct == "Forward"
cUIA.Forward()
else
cUIA.Reload()
}
this.browserMgr.InvalidateDocumentCache(sName)
r := ActionResultModel(true, "Passed", "Browser " navAct)
r.BrowserSessionUsed := sName
return r
case "Browser_Scroll":
dir := p.Get("Direction", "Down")
notches := Max(1, Integer(p.Get("Amount", 400)) // 100)
WinActivate("ahk_id " hwnd)
this.ClickInput(dir == "Up" ? "WheelUp " notches : "WheelDown " notches)
r := ActionResultModel(true, "Passed", "Scrolled web page " dir)
r.BrowserSessionUsed := sName
return r
case "Browser_Alert":
aMode := p.Get("AlertAction", "GetAndClose")
if IsObject(cUIA) {
if aMode == "Close"
cUIA.CloseAlert()
else {
txt := cUIA.GetAlertText(aMode == "GetAndClose", act.TimeoutMs)
this.varStore.SetRuntime(p.Get("OutputVar", "AlertText"), txt)
}
}
r := ActionResultModel(true, "Passed", "Handled browser alert")
r.BrowserSessionUsed := sName
return r
case "Browser_JSExecute":
jsMode := p.Get("JSMode", "Execute")
css := this.varStore.Interpolate(p.Get("CSSSelector", ""))
js := this.varStore.Interpolate(p.Get("JSCode", ""))
if IsObject(cUIA) {
if jsMode == "ClickCSS"
cUIA.JSClickElement(css)
else if jsMode == "ControlClickCSS"
cUIA.ControlClickJSElement(css)
else if jsMode == "ReturnClipboard" {
ret := cUIA.JSReturnThroughClipboard(js)
this.varStore.SetRuntime(p.Get("OutputVar", "JSResult"), ret)
} else {
cUIA.JSExecute(js)
}
}
r := ActionResultModel(true, "Passed", "Executed Browser JS/CSS (" jsMode ")")
r.BrowserSessionUsed := sName
return r
case "Wait_PageLoad":
cond := p.Get("Condition", "PageReady")
exp := this.varStore.Interpolate(p.Get("ExpectedValue", ""))
if cond == "PageReady" && IsObject(cUIA) {
cUIA.WaitPageLoad(exp, act.TimeoutMs)
this.browserMgr.InvalidateDocumentCache(sName)
return ActionResultModel(true, "Passed", "Page load complete")
}
deadline := A_TickCount + act.TimeoutMs
while A_TickCount < deadline && !this.stopRequested {
if cond == "URLContains" && InStr(this.browserMgr.GetSessionURL(sName), exp)
return ActionResultModel(true, "Passed", "URL matched '" exp "'")
if cond == "TitleContains" && InStr(this.browserMgr.GetSessionTitle(sName), exp)
return ActionResultModel(true, "Passed", "Title matched '" exp "'")
if cond == "TabExists" && this.browserMgr.CheckTabExists(sName, exp)
return ActionResultModel(true, "Passed", "Tab '" exp "' exists")
Sleep(150)
}
return ActionResultModel(false, "Failed", "Timed out waiting for browser condition: " cond " " exp)
}
return ActionResultModel(true, "Passed", "Browser action complete")
}
; Interactive Target Repair Dialog (Sections 99, 100, 142)
_PromptInteractiveTargetRepair(macro, act, failedResult) {
choice := "Stop"
guidance := UIATargetEngine.FailureGuidance(failedResult.FailureReason, this.inputMayHaveOccurred)
g := Gui("+AlwaysOnTop +ToolWindow", "Target check — recovery")
g.SetFont("s10 Bold", "Segoe UI")
g.MarginX := 16
g.MarginY := 14
t := UIATargetEngine.EffectiveTarget(act, this.app.project)
if !IsObject(t)
t := act.Target
g.Add("Text", "w480", guidance["Message"])
g.SetFont("s9 Norm", "Segoe UI")
g.Add("Text", "w480 y+6", Format("Step {1} in '{2}' could not complete for `{3}` inside:`r`n{4}", this.currentStepNumber, macro.Name, t.GetHumanLabel(), t.GetWithinBreadcrumb()))
g.SetFont("s9 Bold", "Segoe UI")
g.Add("Text", "w480 y+10", "Strategies Tried:")
g.SetFont("s9 Norm", "Segoe UI")
triedText := failedResult.DiagnosticsText != "" ? failedResult.DiagnosticsText : failedResult.Message
g.Add("Edit", "w480 r4 y+4 ReadOnly", triedText)
btnRetry := g.Add("Button", "w95 h30 y+12", "Retry")
btnPick := g.Add("Button", "x+8 w135 h30", "Pick Replacement")
btnSkip := g.Add("Button", "x+8 w85 h30", "Skip Step")
btnStop := g.Add("Button", "x+8 w85 h30", "Stop")
btnDetails := g.Add("Button", "x+8 w75 h30", "Details")
btnRetry.Enabled := guidance["CanRetry"]
btnPick.Enabled := guidance["CanRetry"]
btnRetry.OnEvent("Click", (*) => (choice := "Retry", g.Destroy()))
btnSkip.OnEvent("Click", (*) => (choice := "Skip", g.Destroy()))
btnStop.OnEvent("Click", (*) => (choice := "Stop", g.Destroy()))
btnDetails.OnEvent("Click", (*) => MsgBox("Step: " act.ComputeFriendlyDescription() "`nMessage: " failedResult.Message "`nUIPI Check: " StudioUtils.CheckUIPIWarning(t.WinHwnd), "Diagnostic Details", "Iconi"))
btnPick.OnEvent("Click", (*) => (choice := "Pick", g.Destroy()))
g.OnEvent("Close", (*) => (choice := "Stop", g.Destroy()))
g.OnEvent("Escape", (*) => (choice := "Stop", g.Destroy()))
g.Show("AutoSize Center")
repairHwnd := g.Hwnd ; [NMS-PC-05] the Stop key must be able to close this dialog (it used to wait forever)
while WinExist("ahk_id " repairHwnd) {
if this.stopRequested {
choice := "Stop"
try g.Destroy()
break
}
Sleep(50)
}
if choice == "Pick" && IsObject(this.app) && IsObject(this.app.selectionEngine) {
pickedTarget := ""
donePicking := false
this.app.selectionEngine.StartSelection("UpgradeTarget", (newT, *) => (pickedTarget := newT, donePicking := true))
while !donePicking && this.app.selectionEngine.isActive && !this.stopRequested
Sleep(60)
if this.stopRequested {
this.app.selectionEngine.CancelSelection()
return "Stop"
}
if IsObject(pickedTarget) && !this.stopRequested {
ans := MsgBox("Replacement target captured: " pickedTarget.GetHumanLabel() "`n`nEdits apply only to this step and detach its shared target.`nYes = Replace Primary Target`nNo = Add as Alternate Fallback Selector", "Apply Target Repair", "YesNoCancel Icon?")
if this.stopRequested
return "Stop"
if ans != "Cancel" {
if ans == "No" && !this.uiaEngine.BackupEligibility(t, pickedTarget)["Eligible"] {
MsgBox("Replacement does not preserve the primary identity and scope. No change was made.", "Backup rejected")
return "Stop"
}
if IsObject(this.app.undoMgr)
this.app.undoMgr.RecordSnapshot(this.app.project, "Repair Target")
act.Target := this.uiaEngine.RepairedTarget(t, pickedTarget, ans == "Yes")
act.ReusableTargetId := "", act.Target.ReusableTargetId := ""
this.app.project.IsDirty := true
act.FriendlyDescription := act.ComputeFriendlyDescription()
return "Retry"
}
}
}
return choice
}
}
; ==============================================================================
; STANDALONE AHK v2 EXPORTER & EXE BUILDER (Sections 112–115, 134 & vNext Section 11)
; Generates clean, human-readable, 100% standalone AutoHotkey v2 scripts
; with inline vendored UIA-v2 runtime when UIA/Browser steps are used.
; ==============================================================================
class StandaloneRuntime {
gui := "" ; Export failures never open the Studio repair editor.
currentState := StudioConstants.StateIdle
panel := ""
sessionActive := false
loopEnabled := false
completedRuns := 0
cyclePaused := false
lastTargetHwnd := 0
closing := false
__New(data, mode := "Once", needsBrowser := true, shortcuts := 0) {
if mode != "Once" && mode != "Menu"
throw ValueError("Unknown export mode: " mode)
this.mode := mode
StudioBranding.Apply()
shortcuts := shortcuts is Map ? shortcuts : Map()
this.playKey := shortcuts.Get("Hotkey_Play", "F1")
this.pauseKey := shortcuts.Get("Hotkey_Pause", "F7")
this.stopKey := shortcuts.Get("Hotkey_Stop", "F8")
this.project := ProjectModel.FromMap(data)
this.logger := LoggingEngine()
this.varStore := VariableStore(this.logger)
this.profileMgr := needsBrowser ? BrowserProfileManager(this.logger) : ""
this.browserMgr := needsBrowser ? BrowserSessionManager(this.profileMgr, this.logger, this) : ""
this.imageEngine := ImagePixelEngine()
this.uiaEngine := UIATargetEngine("", this.imageEngine, this.browserMgr)
this.condEngine := ConditionEngine(this.varStore, this.uiaEngine, this.browserMgr, this.imageEngine)
this.playback := PlaybackEngine(this, this.varStore, this.condEngine, this.uiaEngine, this.browserMgr, this.imageEngine, this.logger)
this.cycleCallback := ObjBindMethod(this, "RunCycle")
this.logPath := A_ScriptFullPath ".run.log"
OnExit((*) => this.playback.ReleaseHeldInputs())
}
SetState(state) {
this.currentState := state
if IsObject(this.panel) {
this.playButton.Text := state == StudioConstants.StatePaused ? "▶ Resume (" this.pauseKey ")" : (state == StudioConstants.StateRunning ? "Ⅱ Pause (" this.pauseKey ")" : "▶ Play (" this.playKey ")")
this.statusText.Text := state == StudioConstants.StatePaused ? "Paused" : (state == StudioConstants.StateRunning ? "Playing…" : "Ready")
}
}
ShowToast(message) => OutputDebug(message)
WriteLog() {
try StudioUtils.AtomicWriteFile(this.logPath, JsonCodec.Dump(this.logger.entries))
catch {
; A read-only distribution folder must not interrupt playback.
try StudioUtils.AtomicWriteFile(A_Temp "\" A_ScriptName ".run.log", JsonCodec.Dump(this.logger.entries))
}
}
RunMacro(macro, *) {
try return this.playback.PlayMacro(macro)
catch as err {
this.logger.Add("ERROR", macro.Name, 0, "Export playback", "Failed", 0, 0, "", "", err.Message)
return false
} finally this.WriteLog()
}
Start() {
Hotkey("*" this.stopKey, (*) => this.Stop())
Hotkey(this.pauseKey, (*) => this.TogglePause())
if this.mode == "Once" {
this.RunOnce()
return
}
Hotkey(this.playKey, (*) => (!this.playback.isRunning || this.playback.isPaused) ? this.PlayPause() : 0)
this.BuildPanel()
}
TogglePause() {
if this.sessionActive
this.PlayPause()
}
RunOnce() {
if this.sessionActive
return
this.sessionActive := true
primary := this.project.GetActiveMacro()
ok := !primary.Enabled || this.RunMacro(primary)
ExitApp(this.playback.stopRequested ? 2 : (ok ? 0 : 1))
}
BuildPanel() {
this.lastTargetHwnd := WinExist("A")
this.foregroundCallback := ObjBindMethod(this, "RememberTargetWindow")
SetTimer(this.foregroundCallback, 100)
this.panel := Gui("+AlwaysOnTop", "Nichols Macro Studio Player — " this.project.GetActiveMacro().Name)
StudioBranding.ApplyGui(this.panel)
g := this.panel
g.SetFont("s10", "Segoe UI")
g.BackColor := "F5F7FA"
g.AddText("x16 y14 w390 h24", this.project.GetActiveMacro().Name)
this.playButton := g.AddButton("x16 y48 w180 h36", "▶ Play (" this.playKey ")")
this.playButton.OnEvent("Click", (*) => this.PlayPause())
g.AddButton("x208 y48 w180 h36", "■ Stop (" this.stopKey ")").OnEvent("Click", (*) => this.Stop())
this.loopButton := g.AddCheckBox("x16 y100 w180 h25", "Loop until stopped")
this.loopButton.OnEvent("Click", (*) => this.loopEnabled := !!this.loopButton.Value)
this.statusText := g.AddText("x16 y136 w380 h40", "Ready — " this.playKey " play · " this.pauseKey " pause/resume · " this.stopKey " stop")
g.OnEvent("Close", (*) => this.Close())
g.OnEvent("Escape", (*) => this.Close())
g.Show("NoActivate w410 h190")
}
RememberTargetWindow() {
hwnd := WinExist("A")
if hwnd && (!IsObject(this.panel) || hwnd != this.panel.Hwnd)
this.lastTargetHwnd := hwnd
}
RestoreTargetWindow() {
if IsObject(this.panel) && WinActive(this.panel.Hwnd) && this.lastTargetHwnd && WinExist(this.lastTargetHwnd) {
WinActivate(this.lastTargetHwnd)
if !WinWaitActive(this.lastTargetHwnd, , 1)
throw TargetError("The previous target window could not be activated.")
}
}
PlayPause() {
if this.closing
return
if !this.playback.isRunning || this.playback.isPaused {
try this.RestoreTargetWindow()
catch as err {
this.statusText.Text := err.Message
return
}
}
if this.playback.isRunning {
if this.playback.isPaused
this.playback.Resume()
else
this.playback.Pause()
return
}
if this.sessionActive {
this.cyclePaused := !this.cyclePaused
SetTimer(this.cycleCallback, this.cyclePaused ? 0 : -1)
this.SetState(this.cyclePaused ? StudioConstants.StatePaused : StudioConstants.StateRunning)
return
}
this.cyclePaused := false
this.sessionActive := true
this.completedRuns := 0
this.playback.stopRequested := false
SetTimer(this.cycleCallback, -1)
}
RunCycle() {
if !this.sessionActive || this.closing || this.cyclePaused
return
macro := this.project.GetActiveMacro()
if !macro.Enabled {
this.sessionActive := false
this.statusText.Text := "This macro is disabled. Enable it in Studio and export again."
return
}
ok := this.RunMacro(macro)
if this.closing
ExitApp(0)
if !this.sessionActive || this.playback.stopRequested {
this.sessionActive := false
this.statusText.Text := "Stopped — " this.playKey " restarts from the beginning."
return
}
if !ok {
this.sessionActive := false
message := "Playback failed. See the .run.log beside this file."
for entry in this.logger.entries
if entry["Level"] == "ERROR"
message := entry["Message"]
this.statusText.Text := "Failed: " message
return
}
this.completedRuns++
this.statusText.Text := "Completed " this.completedRuns " run(s)."
if this.loopEnabled {
; Yield between runs so Stop works even for an empty/instant macro.
if this.cyclePaused
this.SetState(StudioConstants.StatePaused)
else
SetTimer(this.cycleCallback, -50)
} else
this.sessionActive := false
}
Stop() {
if this.mode == "Once" && !this.playback.isRunning
ExitApp(2)
this.sessionActive := false
this.cyclePaused := false
SetTimer(this.cycleCallback, 0)
this.playback.EmergencyStop()
if IsObject(this.panel)
this.statusText.Text := "Stopped — " this.playKey " restarts from the beginning."
}
Close() {
this.closing := true
SetTimer(this.foregroundCallback, 0)
this.Stop()
if !this.playback.isRunning
ExitApp(0)
this.panel.Hide()
}
}
class AHKExporter {
; Filled only in the compiled staging file. The shipped resource is the exact
; canonical production source, never a second handwritten playback engine.
static ExpectedRuntimeSHA256 := ""
static AcquireSource(compiled := A_IsCompiled, runtimePath := "", expectedHash := "") {
if !compiled
return FileRead(A_ScriptFullPath, "UTF-8")
if runtimePath == ""
runtimePath := A_ScriptDir "\ExportRuntime.ahk"
if expectedHash == ""
expectedHash := this.ExpectedRuntimeSHA256
if !RegExMatch(expectedHash, "i)^[0-9a-f]{64}$")
throw Error("This build has no compatible export runtime identifier. Reinstall the complete Studio package.")
if !FileExist(runtimePath) || DirExist(runtimePath)
throw Error("ExportRuntime.ahk is missing. Extract the complete Studio package beside the executable, then export again.")
try data := FileRead(runtimePath, "RAW")
catch
throw Error("ExportRuntime.ahk cannot be read. Check file permissions or extract a fresh complete Studio package.")
if this.SHA256(data) != StrLower(expectedHash)
throw Error("ExportRuntime.ahk is corrupted or belongs to a different build. Restore it from this Studio build's complete package.")
src := StrGet(data, data.Size, "UTF-8")
if SubStr(src, 1, 1) == Chr(0xFEFF)
src := SubStr(src, 2)
if !InStr(src, "; APPLICATION " . "ENTRY POINT") || !InStr(src, "class PlaybackEngine {")
throw Error("The export runtime format is incompatible. Restore the complete Studio package.")
return src
}
static SHA256(data) {
algorithm := 0, hash := 0
try {
if DllCall("bcrypt\BCryptOpenAlgorithmProvider", "Ptr*", &algorithm, "WStr", "SHA256", "Ptr", 0, "UInt", 0, "UInt")
throw Error("Cannot initialize export runtime verification.")
if DllCall("bcrypt\BCryptCreateHash", "Ptr", algorithm, "Ptr*", &hash, "Ptr", 0, "UInt", 0, "Ptr", 0, "UInt", 0, "UInt", 0, "UInt")
throw Error("Cannot create export runtime verification hash.")
if DllCall("bcrypt\BCryptHashData", "Ptr", hash, "Ptr", data, "UInt", data.Size, "UInt", 0, "UInt")
throw Error("Cannot verify export runtime data.")
digest := Buffer(32)
if DllCall("bcrypt\BCryptFinishHash", "Ptr", hash, "Ptr", digest, "UInt", digest.Size, "UInt", 0, "UInt")
throw Error("Cannot finish export runtime verification.")
result := ""
Loop digest.Size
result .= Format("{:02x}", NumGet(digest, A_Index-1, "UChar"))
return result
} finally {
if hash
DllCall("bcrypt\BCryptDestroyHash", "Ptr", hash)
if algorithm
DllCall("bcrypt\BCryptCloseAlgorithmProvider", "Ptr", algorithm, "UInt", 0)
}
}
static CheckInteractiveExportWarnings(project) {
warnings := []
if project.DefaultProfilePolicy == StudioConstants.PolicyAsk
warnings.Push("Project Default Profile Policy is set to 'AskWhenAmbiguous' (prompts user during unattended playback).")
for _, mac in project.Macros {
if mac.ProfilePolicy == StudioConstants.PolicyAsk
warnings.Push("Macro '" mac.Name "' uses 'AskWhenAmbiguous' profile fallback policy.")
rows := WorkflowTree.Flatten(mac.Actions, true)
for _, r in rows {
act := r["Action"]
if act.BrowserFallbackPolicy == StudioConstants.PolicyAsk
warnings.Push("Step " r["StepNumber"] " in '" mac.Name "' uses 'AskWhenAmbiguous' policy.")
if act.Type == "Wait_ManualCheckpoint" || act.Type == "Var_PromptInput" || act.Type == "Key_PromptSecret"
warnings.Push("Step " r["StepNumber"] " in '" mac.Name "' (" act.Type ") requires interactive user input.")
}
}
return warnings
}
static ExportProjectToAhk(project, includeVendoredUIA := "Auto", exportMode := "Once", shortcuts := 0) {
shortcuts := shortcuts is Map ? shortcuts : Map()
; Export the actual execution engine and full model. A second handwritten
; dispatcher previously dropped unsupported actions and changed semantics.
src := this.AcquireSource()
entry := InStr(src, "; APPLICATION " . "ENTRY POINT")
vendor := this._ExtractVendoredUIABlock(src)
if !entry || vendor == ""
throw Error("Cannot locate the embedded standalone runtime in the source file.")
if exportMode != "Once" && exportMode != "Menu"
throw ValueError("Export mode must be Once or Menu.")
features := this.RequiredFeatures(project)
if includeVendoredUIA == "Always"
features["UIA"] := true
if !features["UIA"]
vendor := ""
runtime := this.PlaybackSource(SubStr(src, 1, entry-1), features)
data := JsonCodec.Dump(project.ToMap(), "")
; Bounded source lines also support large workflows and long literal text.
boot := "`r`nglobal g_ExportData := ''`r`n"
pos := 1
while pos <= StrLen(data) {
count := Min(2000, StrLen(data)-pos+1)
last := Ord(SubStr(data, pos+count-1, 1))
if last >= 0xD800 && last <= 0xDBFF
count-- ; Never split a UTF-16 surrogate pair across source literals.
boot .= "g_ExportData .= " StudioUtils.EscapeAhkString(SubStr(data, pos, count)) "`r`n"
pos += count
}
boot .= "global g_ExportRuntime := StandaloneRuntime(JsonCodec.Load(g_ExportData), " StudioUtils.EscapeAhkString(exportMode) ", " (features["Browser"] ? "true" : "false") ", " "JsonCodec.Load(" StudioUtils.EscapeAhkString(JsonCodec.Dump(shortcuts)) ")" ")`r`n"
boot .= "g_ExportData := ''`r`n"
boot .= "g_ExportRuntime.Start()`r`n"
if features["OCR"] {
beginMarker := "; ==================== BEGIN " . "VENDORED OCR ===================="
endMarker := "; ==================== END " . "VENDORED OCR ===================="
first := InStr(src, beginMarker), last := InStr(src, endMarker)
if !first || last <= first
throw Error("Bundled OCR source is missing; cannot export OCR actions.")
vendor .= "`r`n" SubStr(src, first, last-first+StrLen(endMarker))
}
return runtime . boot . vendor
}
static RequiredFeatures(project) {
f := Map("UIA", false, "Browser", false, "OCR", false)
for macro in project.Macros {
for row in WorkflowTree.Flatten(macro.Actions, true) {
a := row["Action"]
if InStr(a.Type, "OCR_") == 1 || InStr(a.Parameters.Get("ConditionType", ""), "OCR") == 1 || InStr(a.Parameters.Get("SecondConditionType", ""), "OCR") == 1
f["OCR"] := true
if RegExMatch(a.Type, "^(Browser_|Profile_|Wait_PageLoad|Wait_NewTab|Wait_FirstMatch)") || a.BrowserSession != "" || a.ExpectOutcome != "None"
f["Browser"] := true
if InStr(a.Type, "UIA_") == 1 || a.Type == "Wait_Element"
f["UIA"] := true
target := a.Target
if a.ReusableTargetId != "" && project.ReusableTargets.Has(a.ReusableTargetId)
target := project.ReusableTargets[a.ReusableTargetId]
if IsObject(target) {
targets := [target]
for backup in target.BackupTargets
targets.Push(backup)
for item in targets {
if InStr("|UIA|BrowserUIA|BrowserJS|", "|" item.TargetKind "|")
f["UIA"] := true
if item.IsWebContent || item.TargetKind == "BrowserJS"
f["Browser"] := true
}
}
for key in ["ConditionType", "SecondConditionType"] {
condition := a.Parameters.Get(key, "")
if InStr(condition, "UIA") == 1
f["UIA"] := true
if condition == "URLContains" || condition == "TitleContains"
f["Browser"] := true
}
}
}
if f["Browser"]
f["UIA"] := true
return f
}
static PlaybackSource(src, features) {
headerEnd := InStr(src, "class StudioBranding {")
if !headerEnd
headerEnd := InStr(src, "class StudioConstants {")
out := SubStr(src, 1, headerEnd-1)
out := StrReplace(out, "; NICHOLS MACRO STUDIO — PRODUCTION RELEASE", "; Nichols Macro Studio standalone playback export")
out := StrReplace(out, "; Single-File Visual Automation Studio for AutoHotkey v2, Windows UIA, & Browsers", "; Playback runtime only. Studio editor and recorder are not included.")
names := ["StudioBranding", "EngineTrace", "StudioConstants", "JsonCodec", "StudioUtils", "LoggingEngine", "ScopeModel", "AnchorModel", "SelectorStrategy", "TargetModel", "ActionResultModel", "ActionModel", "ActionRegistry", "ActionSpecifications", "ActionOptions", "WorkflowTree", "MacroModel", "ProjectModel", "VariableStore", "ConditionEngine", "ImagePixelEngine", "UIATargetEngine", "PlaybackEngine", "StudioSafety", "StandaloneRuntime", "ProgramAudio", "AudioTrigger"]
if features.Get("OCR", false)
names.Push("StudioOCREngine")
if features["Browser"]
names.Push("BrowserCapabilityMatrix", "BrowserProfileManager", "BrowserSessionManager")
for name in names {
if !RegExMatch(src, "ms)^class " name " \{.*?^}", &found)
throw Error("Missing playback component: " name)
out .= "`r`n" found[0] "`r`n"
}
out .= "`r`nClamp(val, minVal, maxVal) => (val < minVal ? minVal : (val > maxVal ? maxVal : val))`r`n"
return out
}
static _SanitizeIdentifier(str) {
clean := RegExReplace(Trim(str), "[^A-Za-z0-9_]", "_")
if clean == "" || RegExMatch(clean, "^\d")
clean := "Macro_" clean
return clean
}
static _GenerateActionBlockCode(mac, actions, indent := " ") {
out := ""
for _, act in actions {
if !act.Enabled
continue
p := act.Parameters
t := act.Target
out .= indent "; Step: " StrReplace(act.ComputeFriendlyDescription(), "`n", " ") "`r`n"
if act.DelayBeforeMs > 0
out .= indent "Sleep(" act.DelayBeforeMs ")`r`n"
switch act.Type {
case "Macro_Comment":
; Comment already emitted above
case "Wait_Duration":
out .= indent "Sleep(" Integer(p.Get("DurationMs", 1000)) ")`r`n"
case "Wait_FirstMatch":
out .= indent Format("MacroVariables[{1}] := Studio_WaitFirstMatch({2}, Studio_Interpolate({3}), {4}, Studio_Interpolate({5}), {6})`r`n",
StudioUtils.EscapeAhkString(p.Get("OutputVar", "MatchedOutcome")),
StudioUtils.EscapeAhkString(p.Get("OutcomeAType", "ElementAppears")),
StudioUtils.EscapeAhkString(p.Get("OutcomeAValue", "")),
StudioUtils.EscapeAhkString(p.Get("OutcomeBType", "TextAppears")),
StudioUtils.EscapeAhkString(p.Get("OutcomeBValue", "")),
act.TimeoutMs)
case "Wait_ManualCheckpoint":
out .= indent Format("if MsgBox({1}, 'Manual Checkpoint', 'OKCancel Iconi') == 'Cancel'`r`n{2} ExitApp()`r`n", StudioUtils.EscapeAhkString(p.Get("PromptText", "Continue?")), indent)
case "Key_TypeText":
out .= indent Format("SendText(Studio_Interpolate({1}))`r`n", StudioUtils.EscapeAhkString(p.Get("Text", "")))
case "Key_SendKeys":
out .= indent Format("Send(Studio_Interpolate({1}))`r`n", StudioUtils.EscapeAhkString(p.Get("Keys", "")))
case "Key_PromptSecret":
sVar := p.Get("SecretVarName", "UserPassword")
out .= indent Format("Studio_TypeSecret({1}, {2})`r`n", StudioUtils.EscapeAhkString(sVar), StudioUtils.EscapeAhkString(p.Get("PromptMessage", "Enter secret:")))
case "Mouse_Click", "Mouse_DoubleClick", "Mouse_RightClick":
btn := act.Type == "Mouse_RightClick" ? "Right" : p.Get("Button", "Left")
cnt := act.Type == "Mouse_DoubleClick" ? 2 : Integer(p.Get("ClickCount", 1))
out .= indent Format("Click('{1} {2} {3} {4}')`r`n", t.ScreenX, t.ScreenY, btn, cnt)
case "Mouse_Drag":
out .= indent Format("MouseClickDrag('Left', {1}, {2}, {3}, {4}, {5})`r`n", Integer(p.Get("StartX", t.ScreenX)), Integer(p.Get("StartY", t.ScreenY)), Integer(p.Get("EndX", t.ScreenX + 50)), Integer(p.Get("EndY", t.ScreenY + 50)), Integer(p.Get("Speed", 5)))
case "Mouse_Move":
out .= indent Format("MouseMove({1}, {2}, {3})`r`n", t.ScreenX, t.ScreenY, Integer(p.Get("Speed", 2)))
case "Mouse_Wheel":
dir := p.Get("Direction", "Down") == "Up" ? "WheelUp" : "WheelDown"
out .= indent Format("Click('{1} {2}')`r`n", dir, Integer(p.Get("Notches", 3)))
case "App_Run":
out .= indent Format("Run(Studio_Interpolate({1}), Studio_Interpolate({2}), {3})`r`n", StudioUtils.EscapeAhkString(p.Get("TargetCmd", "")), StudioUtils.EscapeAhkString(p.Get("WorkingDir", "")), StudioUtils.EscapeAhkString(p.Get("WindowMode", "Normal") == "Normal" ? "" : p["WindowMode"]))
case "App_OpenURL":
out .= indent Format("Run(Studio_Interpolate({1}))`r`n", StudioUtils.EscapeAhkString(p.Get("URL", "")))
case "Win_Activate":
crit := p.Get("WinTitle", "") != "" ? p["WinTitle"] : (t.WinExe != "" ? "ahk_exe " t.WinExe : t.WinTitle)
out .= indent Format("if WinExist({1})`r`n{2} WinActivate({1})`r`n", StudioUtils.EscapeAhkString(crit), indent)
case "Win_Wait":
crit := p.Get("WinTitle", "") != "" ? p["WinTitle"] : (t.WinExe != "" ? "ahk_exe " t.WinExe : t.WinTitle)
out .= indent Format("WinWait({1}, , {2})`r`n", StudioUtils.EscapeAhkString(crit), Max(1, act.TimeoutMs // 1000))
case "Var_Set":
out .= indent Format("MacroVariables[{1}] := Studio_Interpolate({2})`r`n", StudioUtils.EscapeAhkString(p.Get("VarName", "MyVar")), StudioUtils.EscapeAhkString(p.Get("Value", "")))
case "Clip_Set":
out .= indent Format("A_Clipboard := Studio_Interpolate({1})`r`n", StudioUtils.EscapeAhkString(p.Get("Text", "")))
case "Clip_Get":
out .= indent Format("MacroVariables[{1}] := A_Clipboard`r`n", StudioUtils.EscapeAhkString(p.Get("OutputVar", "ClipboardText")))
case "Clip_Clear":
out .= indent "A_Clipboard := ''`r`n"
case "File_Write":
out .= indent Format("try FileDelete(Studio_Interpolate({1}))`r`n{2}FileAppend(Studio_Interpolate({3}), Studio_Interpolate({1}), 'UTF-8')`r`n", StudioUtils.EscapeAhkString(p.Get("FilePath", "")), indent, StudioUtils.EscapeAhkString(p.Get("Content", "")))
case "File_Append":
out .= indent Format("FileAppend(Studio_Interpolate({1}), Studio_Interpolate({2}), 'UTF-8')`r`n", StudioUtils.EscapeAhkString(p.Get("Content", "")), StudioUtils.EscapeAhkString(p.Get("FilePath", "")))
case "File_Read":
out .= indent Format("MacroVariables[{1}] := FileRead(Studio_Interpolate({2}), 'UTF-8')`r`n", StudioUtils.EscapeAhkString(p.Get("OutputVar", "FileText")), StudioUtils.EscapeAhkString(p.Get("FilePath", "")))
case "Image_Click", "Image_Find":
out .= indent Format("Studio_ClickImage({1}, {2}, {3}, {4}, {5})`r`n", StudioUtils.EscapeAhkString(t.CapturedImagePath), t.ImageVariation, t.ScreenX, t.ScreenY, act.Type == "Image_Click" ? "true" : "false")
case "Pixel_Click":
out .= indent Format("Studio_ClickColor({1}, {2}, {3}, {4})`r`n", StudioUtils.EscapeAhkString(t.CapturedColorHex), t.ColorTolerance, t.ScreenX, t.ScreenY)
case "Pixel_GetColor":
out .= indent Format("MacroVariables[{1}] := PixelGetColor({2}, {3}, 'RGB')`r`n", StudioUtils.EscapeAhkString(p.Get("OutputVar", "SampledColor")), t.ScreenX, t.ScreenY)
case "Wait_ImageColor":
out .= indent Format("Studio_WaitImageOrColor({1}, {2}, {3}, {4}, {5}, {6})`r`n", StudioUtils.EscapeAhkString(p.Get("WaitMode", "Color")), StudioUtils.EscapeAhkString(t.CapturedImagePath), t.ImageVariation, StudioUtils.EscapeAhkString(t.CapturedColorHex), t.ColorTolerance, act.TimeoutMs)
case "Profile_Launch", "Profile_AttachSession":
sName := act.BrowserSession != "" ? act.BrowserSession : p.Get("SessionName", "MainBrowser")
bType := act.BrowserType != "" ? act.BrowserType : p.Get("BrowserType", mac.BrowserDefault)
prof := act.BrowserProfile != "" ? act.BrowserProfile : p.Get("ProfileAlias", mac.DefaultProfileAlias)
pol := (act.BrowserFallbackPolicy != "" && act.BrowserFallbackPolicy != "Inherit") ? act.BrowserFallbackPolicy : mac.ProfilePolicy
out .= indent Format("Studio_AcquireBrowserSession({1}, {2}, {3}, {4}, {5}, {6})`r`n",
StudioUtils.EscapeAhkString(sName),
StudioUtils.EscapeAhkString(bType),
StudioUtils.EscapeAhkString(prof),
StudioUtils.EscapeAhkString(pol),
act.Type == "Profile_Launch" ? "true" : "false",
StudioUtils.EscapeAhkString(p.Get("URL", "")))
case "Profile_SwitchSession":
sName := act.BrowserSession != "" ? act.BrowserSession : p.Get("SessionName", "MainBrowser")
out .= indent Format("if ActiveBrowserSessions.Has({1}) && WinExist('ahk_id ' ActiveBrowserSessions[{1}])`r`n{2} WinActivate('ahk_id ' ActiveBrowserSessions[{1}])`r`n", StudioUtils.EscapeAhkString(sName), indent)
case "Browser_Navigate":
sName := act.BrowserSession != "" ? act.BrowserSession : mac.DefaultSessionName
out .= indent Format("Studio_BrowserNavigate({1}, Studio_Interpolate({2}), {3})`r`n",
StudioUtils.EscapeAhkString(sName),
StudioUtils.EscapeAhkString(p.Get("URL", "")),
act.TimeoutMs)
case "Wait_PageLoad":
sName := act.BrowserSession != "" ? act.BrowserSession : mac.DefaultSessionName
out .= indent Format("Studio_BrowserWaitPageLoad({1}, {2})`r`n", StudioUtils.EscapeAhkString(sName), act.TimeoutMs)
case "Browser_SelectTab", "Wait_NewTab":
sName := act.BrowserSession != "" ? act.BrowserSession : mac.DefaultSessionName
out .= indent Format("Studio_BrowserSelectTab({1}, Studio_Interpolate({2}))`r`n",
StudioUtils.EscapeAhkString(sName),
StudioUtils.EscapeAhkString(p.Get("TabTitle", "")))
case "Browser_GetURL":
sName := act.BrowserSession != "" ? act.BrowserSession : mac.DefaultSessionName
out .= indent Format("MacroVariables[{1}] := Studio_BrowserGetMeta({2}, 'URL')`r`n", StudioUtils.EscapeAhkString(p.Get("OutputVar", "CurrentURL")), StudioUtils.EscapeAhkString(sName))
case "Browser_GetTitle":
sName := act.BrowserSession != "" ? act.BrowserSession : mac.DefaultSessionName
out .= indent Format("MacroVariables[{1}] := Studio_BrowserGetMeta({2}, 'Title')`r`n", StudioUtils.EscapeAhkString(p.Get("OutputVar", "PageTitle")), StudioUtils.EscapeAhkString(sName))
case "Browser_JSExecute":
sName := act.BrowserSession != "" ? act.BrowserSession : mac.DefaultSessionName
out .= indent Format("Studio_BrowserJSExec({1}, Studio_Interpolate({2}))`r`n", StudioUtils.EscapeAhkString(sName), StudioUtils.EscapeAhkString(p.Get("Expression", "")))
case "UIA_Click", "Browser_Click", "Browser_ClickAndWaitNewTab":
out .= indent Format("Studio_UIAClick({1}, {2}, {3}, {4}, {5}, {6}, {7})`r`n",
StudioUtils.EscapeAhkString(t.WinExe != "" ? "ahk_exe " t.WinExe : t.WinTitle),
StudioUtils.EscapeAhkString(t.PrimarySelector.ControlType),
StudioUtils.EscapeAhkString(t.PrimarySelector.ElementName),
StudioUtils.EscapeAhkString(t.PrimarySelector.AutomationId),
t.WinRelX, t.WinRelY, act.TimeoutMs)
case "UIA_SetValue", "Browser_SetValue", "UIA_SelectItem", "Browser_SelectDropdown":
valStr := p.Has("ItemText") ? p["ItemText"] : p.Get("Text", "")
out .= indent Format("Studio_UIASetValue({1}, {2}, {3}, {4}, Studio_Interpolate({5}), {6})`r`n",
StudioUtils.EscapeAhkString(t.WinExe != "" ? "ahk_exe " t.WinExe : t.WinTitle),
StudioUtils.EscapeAhkString(t.PrimarySelector.ControlType),
StudioUtils.EscapeAhkString(t.PrimarySelector.ElementName),
StudioUtils.EscapeAhkString(t.PrimarySelector.AutomationId),
StudioUtils.EscapeAhkString(valStr),
act.TimeoutMs)
case "UIA_ReadValue", "Browser_ReadText", "Browser_GetText", "Browser_ExtractLinks", "Browser_FindText":
out .= indent Format("MacroVariables[{1}] := Studio_UIAReadValue({2}, {3}, {4}, {5}, {6})`r`n",
StudioUtils.EscapeAhkString(p.Get("OutputVar", "ElementValue")),
StudioUtils.EscapeAhkString(t.WinExe != "" ? "ahk_exe " t.WinExe : t.WinTitle),
StudioUtils.EscapeAhkString(t.PrimarySelector.ControlType),
StudioUtils.EscapeAhkString(t.PrimarySelector.ElementName),
StudioUtils.EscapeAhkString(t.PrimarySelector.AutomationId),
act.TimeoutMs)
case "UIA_Toggle", "Browser_ToggleCheckbox":
out .= indent Format("Studio_UIAToggle({1}, {2}, {3}, {4}, {5})`r`n",
StudioUtils.EscapeAhkString(t.WinExe != "" ? "ahk_exe " t.WinExe : t.WinTitle),
StudioUtils.EscapeAhkString(t.PrimarySelector.ControlType),
StudioUtils.EscapeAhkString(t.PrimarySelector.ElementName),
StudioUtils.EscapeAhkString(t.PrimarySelector.AutomationId),
act.TimeoutMs)
case "Wait_Element":
out .= indent Format("Studio_UIAWait({1}, {2}, {3}, {4}, {5})`r`n",
StudioUtils.EscapeAhkString(t.WinExe != "" ? "ahk_exe " t.WinExe : t.WinTitle),
StudioUtils.EscapeAhkString(t.PrimarySelector.ControlType),
StudioUtils.EscapeAhkString(t.PrimarySelector.ElementName),
StudioUtils.EscapeAhkString(t.PrimarySelector.AutomationId),
act.TimeoutMs)
case "Logic_If":
out .= indent Format("if (Studio_EvalCond({1}, {2}, {3})) {`r`n",
StudioUtils.EscapeAhkString(p.Get("ConditionType", "VarEquals")),
StudioUtils.EscapeAhkString(p.Get("LeftOperand", "")),
StudioUtils.EscapeAhkString(p.Get("RightOperand", "")))
out .= this._GenerateActionBlockCode(mac, act.Children, indent " ")
if act.HasElse && act.ElseChildren.Length > 0 {
out .= indent "} else {`r`n"
out .= this._GenerateActionBlockCode(mac, act.ElseChildren, indent " ")
}
out .= indent "}`r`n"
case "Logic_Repeat":
cnt := Integer(p.Get("Count", 3))
idxVar := p.Get("IndexVar", "LoopIndex")
out .= indent "Loop " cnt " {`r`n"
out .= indent Format(" MacroVariables[{1}] := A_Index`r`n", StudioUtils.EscapeAhkString(idxVar))
out .= this._GenerateActionBlockCode(mac, act.Children, indent " ")
out .= indent "}`r`n"
case "Logic_While":
out .= indent Format("while (Studio_EvalCond({1}, {2}, {3})) {`r`n",
StudioUtils.EscapeAhkString(p.Get("ConditionType", "VarEquals")),
StudioUtils.EscapeAhkString(p.Get("LeftOperand", "")),
StudioUtils.EscapeAhkString(p.Get("RightOperand", "")))
out .= this._GenerateActionBlockCode(mac, act.Children, indent " ")
out .= indent "}`r`n"
case "Logic_TryCatch":
errVar := p.Get("ErrorVar", "LastError")
out .= indent "try {`r`n"
out .= this._GenerateActionBlockCode(mac, act.Children, indent " ")
out .= indent "} catch as err {`r`n"
out .= indent Format(" MacroVariables[{1}] := err.Message`r`n", StudioUtils.EscapeAhkString(errVar))
if act.ElseChildren.Length > 0
out .= this._GenerateActionBlockCode(mac, act.ElseChildren, indent " ")
out .= indent "}`r`n"
case "Logic_Break":
out .= indent "break`r`n"
case "Logic_Continue":
out .= indent "continue`r`n"
case "Macro_Call":
subFn := this._SanitizeIdentifier("RunMacro_" p.Get("TargetMacroName", ""))
out .= indent subFn "()`r`n"
case "Macro_Stop":
out .= indent "return`r`n"
}
if act.DelayAfterMs > 0
out .= indent "Sleep(" act.DelayAfterMs ")`r`n"
}
return out
}
static _GetStandaloneRuntimeHelpers(hasUIA) {
h := "; ==============================================================================`r`n"
h .= "; Standalone Runtime Helpers`r`n"
h .= "; ==============================================================================`r`n"
h .= "Studio_Interpolate(str) {`r`n"
h .= " global MacroVariables`r`n"
h .= " s := String(str)`r`n"
h .= " for k, v in MacroVariables {`r`n"
h .= " s := StrReplace(s, '${' k '}', String(v))`r`n"
h .= " s := StrReplace(s, '%' k '%', String(v))`r`n"
h .= " }`r`n"
h .= " return s`r`n"
h .= "}`r`n`r`n"
h .= "Studio_EvalCond(condType, leftRaw, rightRaw) {`r`n"
h .= " global MacroVariables`r`n"
h .= " l := MacroVariables.Has(leftRaw) ? MacroVariables[leftRaw] : Studio_Interpolate(leftRaw)`r`n"
h .= " r := Studio_Interpolate(rightRaw)`r`n"
h .= " if (condType == 'VarGreater')`r`n"
h .= " return Number(l) > Number(r)`r`n"
h .= " if (condType == 'VarLess')`r`n"
h .= " return Number(l) < Number(r)`r`n"
h .= " if (condType == 'StringContains')`r`n"
h .= " return InStr(String(l), String(r)) > 0`r`n"
h .= " if (condType == 'WindowExists')`r`n"
h .= " return WinExist(String(l)) != 0`r`n"
h .= " return String(l) = String(r)`r`n"
h .= "}`r`n`r`n"
h .= "Studio_TypeSecret(secName, promptMsg) {`r`n"
h .= " ib := InputBox(promptMsg, 'Protected Secret — ' secName, 'Password w340 h140')`r`n"
h .= " if (ib.Result != 'Cancel' && ib.Value != '')`r`n"
h .= " SendText(ib.Value)`r`n"
h .= "}`r`n`r`n"
h .= "Studio_ClickImage(imgPath, variation, fallbackX, fallbackY, doClick := true) {`r`n"
h .= " fx := 0, fy := 0`r`n"
h .= " if (imgPath != '' && FileExist(imgPath)) {`r`n"
h .= " if ImageSearch(&fx, &fy, 0, 0, A_ScreenWidth, A_ScreenHeight, '*' variation ' ' imgPath) {`r`n"
h .= " if doClick`r`n"
h .= " Click(fx ' ' fy)`r`n"
h .= " return true`r`n"
h .= " }`r`n"
h .= " }`r`n"
h .= " if doClick`r`n"
h .= " Click(fallbackX ' ' fallbackY)`r`n"
h .= " return false`r`n"
h .= "}`r`n`r`n"
h .= "Studio_ClickColor(colorHex, tol, fallbackX, fallbackY) {`r`n"
h .= " fx := 0, fy := 0`r`n"
h .= " if PixelSearch(&fx, &fy, 0, 0, A_ScreenWidth, A_ScreenHeight, Integer(colorHex), tol)`r`n"
h .= " Click(fx ' ' fy)`r`n"
h .= " else`r`n"
h .= " Click(fallbackX ' ' fallbackY)`r`n"
h .= "}`r`n`r`n"
h .= "Studio_WaitImageOrColor(waitMode, imgPath, variation, colorHex, tol, timeoutMs) {`r`n"
h .= " fx := 0, fy := 0`r`n"
h .= " deadline := A_TickCount + Max(100, timeoutMs)`r`n"
h .= " while (A_TickCount <= deadline) {`r`n"
h .= " if (waitMode == 'Image' && imgPath != '' && FileExist(imgPath)) {`r`n"
h .= " if ImageSearch(&fx, &fy, 0, 0, A_ScreenWidth, A_ScreenHeight, '*' variation ' ' imgPath)`r`n"
h .= " return true`r`n"
h .= " } else {`r`n"
h .= " if PixelSearch(&fx, &fy, 0, 0, A_ScreenWidth, A_ScreenHeight, Integer(colorHex), tol)`r`n"
h .= " return true`r`n"
h .= " }`r`n"
h .= " Sleep(100)`r`n"
h .= " }`r`n"
h .= " return false`r`n"
h .= "}`r`n`r`n"
h .= "Studio_AcquireBrowserSession(sessionName, browserType, profileAlias, policy, allowLaunch, url) {`r`n"
h .= " global ActiveBrowserSessions`r`n"
h .= " exe := (browserType = 'Chrome') ? 'chrome.exe' : (browserType = 'Firefox') ? 'firefox.exe' : 'msedge.exe'`r`n"
h .= " hwnd := WinExist('ahk_exe ' exe)`r`n"
h .= " if (!hwnd && policy != 'Strict')`r`n"
h .= " hwnd := WinExist('ahk_exe msedge.exe') ? WinExist('ahk_exe msedge.exe') : WinExist('ahk_exe chrome.exe')`r`n"
h .= " if (hwnd)`r`n"
h .= " ActiveBrowserSessions[sessionName] := hwnd`r`n"
h .= " return hwnd`r`n"
h .= "}`r`n`r`n"
if hasUIA {
h .= "Studio_WaitFirstMatch(aType, aVal, bType, bVal, timeoutMs) {`r`n"
h .= " deadline := A_TickCount + Max(200, timeoutMs)`r`n"
h .= " while (A_TickCount <= deadline) {`r`n"
h .= " if (aVal != '' && WinExist(aVal))`r`n"
h .= " return 'A'`r`n"
h .= " if (bVal != '' && WinExist(bVal))`r`n"
h .= " return 'B'`r`n"
h .= " Sleep(100)`r`n"
h .= " }`r`n"
h .= " return 'Timeout'`r`n"
h .= "}`r`n`r`n"
h .= "Studio_BrowserNavigate(sessionName, url, timeoutMs) {`r`n"
h .= " global ActiveBrowserSessions`r`n"
h .= " hwnd := ActiveBrowserSessions.Has(sessionName) ? ActiveBrowserSessions[sessionName] : WinExist('A')`r`n"
h .= " try {`r`n"
h .= " cUIA := UIA_Browser('ahk_id ' hwnd)`r`n"
h .= " cUIA.Navigate(url, '', timeoutMs)`r`n"
h .= " } catch {`r`n"
h .= " if hwnd`r`n"
h .= " WinActivate('ahk_id ' hwnd)`r`n"
h .= " Send('^l')`r`n"
h .= " Sleep(60)`r`n"
h .= " SendText(url)`r`n"
h .= " Send('{Enter}')`r`n"
h .= " }`r`n"
h .= "}`r`n`r`n"
h .= "Studio_BrowserWaitPageLoad(sessionName, timeoutMs) {`r`n"
h .= " global ActiveBrowserSessions`r`n"
h .= " hwnd := ActiveBrowserSessions.Has(sessionName) ? ActiveBrowserSessions[sessionName] : WinExist('A')`r`n"
h .= " try UIA_Browser('ahk_id ' hwnd).WaitPageLoad('', timeoutMs)`r`n"
h .= "}`r`n`r`n"
h .= "Studio_BrowserSelectTab(sessionName, tabTitle) {`r`n"
h .= " global ActiveBrowserSessions`r`n"
h .= " hwnd := ActiveBrowserSessions.Has(sessionName) ? ActiveBrowserSessions[sessionName] : WinExist('A')`r`n"
h .= " try UIA_Browser('ahk_id ' hwnd).SelectTab(tabTitle, 2, false)`r`n"
h .= "}`r`n`r`n"
h .= "Studio_BrowserGetMeta(sessionName, metaType) {`r`n"
h .= " global ActiveBrowserSessions`r`n"
h .= " hwnd := ActiveBrowserSessions.Has(sessionName) ? ActiveBrowserSessions[sessionName] : WinExist('A')`r`n"
h .= " if (metaType == 'Title')`r`n"
h .= " return hwnd ? WinGetTitle('ahk_id ' hwnd) : ''`r`n"
h .= " try return UIA_Browser('ahk_id ' hwnd).GetCurrentURL()`r`n"
h .= " return ''`r`n"
h .= "}`r`n`r`n"
h .= "Studio_BrowserJSExec(sessionName, jsExpr) {`r`n"
h .= " global ActiveBrowserSessions`r`n"
h .= " hwnd := ActiveBrowserSessions.Has(sessionName) ? ActiveBrowserSessions[sessionName] : WinExist('A')`r`n"
h .= " try return UIA_Browser('ahk_id ' hwnd).JSExecute(jsExpr)`r`n"
h .= "}`r`n`r`n"
h .= "Studio_UIAClick(winCrit, ctrlType, elName, autoId, relX, relY, timeoutMs) {`r`n"
h .= " hwnd := (winCrit != '') ? WinExist(winCrit) : WinExist('A')`r`n"
h .= " if hwnd {`r`n"
h .= " try {`r`n"
h .= " root := UIA.ElementFromHandle(hwnd)`r`n"
h .= " q := {}`r`n"
h .= " if (ctrlType != '')`r`n"
h .= " q.Type := ctrlType`r`n"
h .= " if (elName != '')`r`n"
h .= " q.Name := elName, q.mm := 2`r`n"
h .= " if (autoId != '')`r`n"
h .= " q.AutomationId := autoId`r`n"
h .= " el := root.WaitElement(q, timeoutMs)`r`n"
h .= " if IsObject(el) {`r`n"
h .= " el.Click()`r`n"
h .= " return true`r`n"
h .= " }`r`n"
h .= " }`r`n"
h .= " WinGetPos(&wx, &wy, , , 'ahk_id ' hwnd)`r`n"
h .= " Click((wx + relX) ' ' (wy + relY))`r`n"
h .= " }`r`n"
h .= "}`r`n`r`n"
h .= "Studio_UIASetValue(winCrit, ctrlType, elName, autoId, textVal, timeoutMs) {`r`n"
h .= " hwnd := (winCrit != '') ? WinExist(winCrit) : WinExist('A')`r`n"
h .= " if hwnd {`r`n"
h .= " try {`r`n"
h .= " root := UIA.ElementFromHandle(hwnd)`r`n"
h .= " q := {}`r`n"
h .= " if (ctrlType != '')`r`n"
h .= " q.Type := ctrlType`r`n"
h .= " if (elName != '')`r`n"
h .= " q.Name := elName, q.mm := 2`r`n"
h .= " el := root.WaitElement(q, timeoutMs)`r`n"
h .= " if IsObject(el) {`r`n"
h .= " el.Value := textVal`r`n"
h .= " return true`r`n"
h .= " }`r`n"
h .= " }`r`n"
h .= " }`r`n"
h .= " SendText(textVal)`r`n"
h .= "}`r`n`r`n"
h .= "Studio_UIAReadValue(winCrit, ctrlType, elName, autoId, timeoutMs) {`r`n"
h .= " hwnd := (winCrit != '') ? WinExist(winCrit) : WinExist('A')`r`n"
h .= " if hwnd {`r`n"
h .= " try {`r`n"
h .= " root := UIA.ElementFromHandle(hwnd)`r`n"
h .= " q := {}`r`n"
h .= " if (ctrlType != '')`r`n"
h .= " q.Type := ctrlType`r`n"
h .= " if (elName != '')`r`n"
h .= " q.Name := elName, q.mm := 2`r`n"
h .= " el := root.WaitElement(q, timeoutMs)`r`n"
h .= " if IsObject(el) {`r`n"
h .= " try return el.Value`r`n"
h .= " try return el.Name`r`n"
h .= " }`r`n"
h .= " }`r`n"
h .= " }`r`n"
h .= " return ''`r`n"
h .= "}`r`n`r`n"
h .= "Studio_UIAToggle(winCrit, ctrlType, elName, autoId, timeoutMs) {`r`n"
h .= " hwnd := (winCrit != '') ? WinExist(winCrit) : WinExist('A')`r`n"
h .= " if hwnd {`r`n"
h .= " try {`r`n"
h .= " root := UIA.ElementFromHandle(hwnd)`r`n"
h .= " q := {}`r`n"
h .= " if (ctrlType != '')`r`n"
h .= " q.Type := ctrlType`r`n"
h .= " if (elName != '')`r`n"
h .= " q.Name := elName, q.mm := 2`r`n"
h .= " el := root.WaitElement(q, timeoutMs)`r`n"
h .= " if IsObject(el) {`r`n"
h .= " try return el.Toggle()`r`n"
h .= " el.Click()`r`n"
h .= " return true`r`n"
h .= " }`r`n"
h .= " }`r`n"
h .= " }`r`n"
h .= " return false`r`n"
h .= "}`r`n`r`n"
h .= "Studio_UIAWait(winCrit, ctrlType, elName, autoId, timeoutMs) {`r`n"
h .= " hwnd := (winCrit != '') ? WinWait(winCrit, , Max(1, timeoutMs // 1000)) : WinExist('A')`r`n"
h .= " if hwnd {`r`n"
h .= " try {`r`n"
h .= " root := UIA.ElementFromHandle(hwnd)`r`n"
h .= " q := {}`r`n"
h .= " if (ctrlType != '')`r`n"
h .= " q.Type := ctrlType`r`n"
h .= " if (elName != '')`r`n"
h .= " q.Name := elName, q.mm := 2`r`n"
h .= " return IsObject(root.WaitElement(q, timeoutMs))`r`n"
h .= " }`r`n"
h .= " }`r`n"
h .= " return false`r`n"
h .= "}`r`n"
}
return h
}
static _ExtractVendoredUIABlock(src := "") {
if src == ""
src := this.AcquireSource()
mStart := "; ==================== BEGIN " . "VENDORED UIA-v2 ===================="
mEnd := "; ==================== END " . "VENDORED UIA-v2 ===================="
p1 := InStr(src, mStart), p2 := InStr(src, mEnd)
return p1 > 0 && p2 > p1 ? SubStr(src, p1, p2-p1+StrLen(mEnd)) : ""
}
}
class EXEBuilder {
static building := false
static IsInterpreterBase(path) {
module := 0
try {
if !RegExMatch(FileGetVersion(path), "^2\.")
return false
; Read resources as data only: never load executable code or run a candidate.
module := DllCall("LoadLibraryExW", "WStr", path, "Ptr", 0, "UInt", 2, "Ptr")
if !module || DllCall("FindResourceW", "Ptr", module, "WStr", ">AUTOHOTKEY SCRIPT<", "Ptr", 10, "Ptr")
return false
size := DllCall("Version\GetFileVersionInfoSizeW", "WStr", path, "Ptr", 0, "UInt")
if !size
return false
info := Buffer(size), translations := 0, length := 0
if !DllCall("Version\GetFileVersionInfoW", "WStr", path, "UInt", 0, "UInt", size, "Ptr", info)
return false
if !DllCall("Version\VerQueryValueW", "Ptr", info, "WStr", "\VarFileInfo\Translation", "Ptr*", &translations, "UInt*", &length)
return false
Loop length // 4 {
offset := (A_Index-1)*4
key := Format("\StringFileInfo\{:04x}{:04x}\ProductName", NumGet(translations, offset, "UShort"), NumGet(translations, offset+2, "UShort"))
value := 0, chars := 0
if DllCall("Version\VerQueryValueW", "Ptr", info, "WStr", key, "Ptr*", &value, "UInt*", &chars) && chars > 1 && StrGet(value, "UTF-16") == "AutoHotkey"
return true
}
} catch {
return false
} finally {
if module
DllCall("FreeLibrary", "Ptr", module)
}
return false
}
static ResolveBasePath(preferred := "", compiled := A_IsCompiled, root := A_ScriptDir) {
if this.IsInterpreterBase(preferred)
return preferred
fallback := compiled ? root "\Compiler\AutoHotkey64.exe" : A_AhkPath
return this.IsInterpreterBase(fallback) ? fallback : ""
}
static BuildExe(project, outExePath, compilerPath := "", baseExePath := "", exportMode := "Once", shortcuts := 0) {
priorCritical := A_IsCritical
Critical("On")
try {
if this.building
return Map("Success", false, "Message", "An EXE build is already in progress. Wait for it to finish.")
this.building := true
} finally Critical(priorCritical)
try return this._BuildExe(project, outExePath, compilerPath, baseExePath, exportMode, shortcuts)
finally this.building := false
}
static _BuildExe(project, outExePath, compilerPath := "", baseExePath := "", exportMode := "Once", shortcuts := 0) {
compilerPath := CompilerLocator.Resolve(compilerPath)
if compilerPath == "" {
return Map("Success", false, "Message", "Ahk2Exe compiler was not found. Select it in Tools → Settings, or choose AHK script in Export macro to export without a compiler.")
}
; Invalid old saved paths must not mask the valid packaged interpreter.
baseExePath := this.ResolveBasePath(baseExePath)
if baseExePath == ""
return Map("Success", false, "Message", "A clean AutoHotkey v2 compiler base is required; a compiled macro or Studio EXE cannot be used. Restore Compiler\AutoHotkey64.exe from the complete Studio package. You can still choose AHK script in Export macro.")
if !DirExist(StudioConstants.TempDir)
DirCreate(StudioConstants.TempDir)
buildId := StudioUtils.GenId("build")
tempAhk := StudioConstants.TempDir "\" buildId ".ahk"
try {
ahkCode := AHKExporter.ExportProjectToAhk(project, "Auto", exportMode, shortcuts)
StudioUtils.AtomicWriteFile(tempAhk, ahkCode)
stagedExe := outExePath ".building-" buildId ".exe"
cmd := Format('"{1}" /in "{2}" /out "{3}" /base "{4}" /icon "{5}" /silent verbose', compilerPath, tempAhk, stagedExe, baseExePath, StudioBranding.IconFile())
exitCode := RunWait(cmd, , "Hide")
if exitCode == 0 && FileExist(stagedExe) && FileGetSize(stagedExe) > 0 {
FileMove(stagedExe, outExePath, 1)
return Map("Success", true, "Message", "Successfully compiled standalone executable: " outExePath, "ExePath", outExePath)
}
return Map("Success", false, "Message", "Ahk2Exe returned exit code " exitCode ". Verify compiler and base executable settings.")
} catch as err {
return Map("Success", false, "Message", "EXE compilation failed: " err.Message)
} finally {
try if FileExist(tempAhk)
FileDelete(tempAhk)
try if IsSet(stagedExe) && FileExist(stagedExe)
FileDelete(stagedExe)
}
}
}
; ==============================================================================
; BUILT-IN SELF-TEST DIAGNOSTICS & LOCAL HTML FIXTURE (Sections 124–126 & vNext Section 119)
; ==============================================================================
class DiagnosticsEngine {
app := ""
__New(app := "") {
this.app := app
}
static CreateDisposableHtmlFixture() {
if !DirExist(StudioConstants.TempDir)
DirCreate(StudioConstants.TempDir)
htmlPath := StudioConstants.TempDir "\studio_browser_fixture.html"
html := "`r`n
Nichols Macro Studio Test Fixture"
html .= ""
html .= "
Order Checkout Fixture
"
html .= "
:
"
html .= ""
html .= ""
html .= "
Ready
"
html .= "
Scroll Down
"
html .= ""
html .= ""
StudioUtils.AtomicWriteFile(htmlPath, html)
return htmlPath
}
static CleanupHtmlFixture() {
htmlPath := StudioConstants.TempDir "\studio_browser_fixture.html"
try if FileExist(htmlPath)
FileDelete(htmlPath)
}
RunAllDiagnostics(runIntegration := true) {
; Recovery checks must never replace the user's real autosave snapshot.
saved := Map()
for key in ["AppDataDir", "SettingsFile", "AutosaveFile", "RecoveryMetaFile", "ManagedProfilesDir", "TempDir"]
saved[key] := StudioConstants.%key%
testRoot := A_Temp "\NicholsMacroStudio_Diagnostics_" DllCall("GetCurrentProcessId") "_" A_TickCount
try {
StudioConstants.AppDataDir := testRoot
StudioConstants.SettingsFile := testRoot "\settings.json"
StudioConstants.AutosaveFile := testRoot "\autosave.json"
StudioConstants.RecoveryMetaFile := testRoot "\recovery.json"
StudioConstants.ManagedProfilesDir := testRoot "\profiles"
StudioConstants.TempDir := testRoot "\temp"
DirCreate(StudioConstants.TempDir)
return this._RunAllDiagnostics(runIntegration)
} finally {
for key, value in saved
StudioConstants.%key% := value
}
}
_RunAllDiagnostics(runIntegration := true) {
results := []
; 1. JSON Serialization, Escaping, & Unicode/Emoji
try {
m := Map("str", "Quote `" Backslash \ Tab `t Newline `n Emoji 🚀", "num", 12345, "flt", 19.95, "bool", JsonCodec.TrueVal, "arr", [1, "two", Map("k", "v")])
dumped := JsonCodec.Dump(m)
loaded := JsonCodec.Load(dumped)
ok := (loaded["str"] == "Quote `" Backslash \ Tab `t Newline `n Emoji 🚀" && loaded["num"] == 12345 && loaded["arr"][3]["k"] == "v")
results.Push(Map("Test", "JSON Serialization, Escapes & Unicode", "Status", ok ? "PASS" : "FAIL", "Detail", ok ? "Verified round-trip of escapes, Unicode, and nested structures" : "Mismatch"))
} catch as err {
results.Push(Map("Test", "JSON Serialization, Escapes & Unicode", "Status", "FAIL", "Detail", err.Message))
}
; 2. Invalid / Corrupt Project Handling
try {
caughtCorrupt := false
try JsonCodec.Load("{corrupt_json: [1, 2")
catch
caughtCorrupt := true
results.Push(Map("Test", "Corrupt Project / JSON Rejection", "Status", caughtCorrupt ? "PASS" : "FAIL", "Detail", "Gracefully rejected malformed JSON without crashing"))
} catch as err {
results.Push(Map("Test", "Corrupt Project / JSON Rejection", "Status", "FAIL", "Detail", err.Message))
}
; 3. Project & Action Tree Round-Trip + AST Validation
try {
prj := ProjectModel("Diag Project")
mac := prj.GetActiveMacro()
brk := ActionModel("Logic_Break")
WorkflowTree.InsertAction(mac.Actions, brk)
probs := WorkflowTree.ValidateTree(mac.Actions)
hasBreakErr := probs.Length > 0 && probs[1]["Severity"] == "Error"
results.Push(Map("Test", "Action AST Validation (Break Outside Loop)", "Status", hasBreakErr ? "PASS" : "FAIL", "Detail", hasBreakErr ? probs[1]["Message"] : "Failed to catch invalid Break"))
} catch as err {
results.Push(Map("Test", "Action AST Validation (Break Outside Loop)", "Status", "FAIL", "Detail", err.Message))
}
; 4. Variable Interpolation & Secret Masking
try {
lg := LoggingEngine()
vs := VariableStore(lg)
vs.SetRuntime("InvoiceId", "INV-900")
vs.SetSecret("MyPass", "TopSecretValue123")
s := vs.Interpolate("Processing ${InvoiceId} {Enter}")
lg.Add("INFO", "Diag", 1, "Test Secret TopSecretValue123", "Passed", 0, 0, "", "", "Secret=TopSecretValue123")
maskedOk := (s == "Processing INV-900 {Enter}") && !InStr(lg.entries[1]["Message"], "TopSecretValue123")
results.Push(Map("Test", "Variable Interpolation & Secret Masking", "Status", maskedOk ? "PASS" : "FAIL", "Detail", "Verified ${Var} interpolation and password redaction in logs"))
} catch as err {
results.Push(Map("Test", "Variable Interpolation & Secret Masking", "Status", "FAIL", "Detail", err.Message))
}
; 5. Condition Evaluation (AND/OR)
try {
vs := VariableStore()
vs.SetRuntime("Total", 150)
ce := ConditionEngine(vs)
ifAct := ActionModel("Logic_If")
ifAct.Parameters["ConditionType"] := "VarGreater"
ifAct.Parameters["LeftOperand"] := "Total"
ifAct.Parameters["RightOperand"] := "100"
ifAct.Parameters["CombineOp"] := "AND"
ifAct.Parameters["SecondConditionType"] := "StringContains"
ifAct.Parameters["SecondLeft"] := "Order-ABC"
ifAct.Parameters["SecondRight"] := "ABC"
cOk := ce.EvaluateActionCondition(ifAct)
results.Push(Map("Test", "Compound Condition Evaluation (AND/OR)", "Status", cOk ? "PASS" : "FAIL", "Detail", "Evaluated compound numeric + string condition"))
} catch as err {
results.Push(Map("Test", "Compound Condition Evaluation (AND/OR)", "Status", "FAIL", "Detail", err.Message))
}
; 6. Target Serialization, Reliability Rating & Selector Strategies
try {
t := TargetModel("Submit", "Button", "UIA")
t.PrimarySelector.AutomationId := "btnSubmit"
t.PrimarySelector.ControlType := "Button"
t.PrimarySelector.ElementName := "Submit"
t.EnsureDefaultAlternates()
t.ComputeReliability()
tClone := TargetModel.FromMap(t.ToMap())
ok := (tClone.ReliabilityRating == "Strong" && tClone.AlternateSelectors.Length >= 1)
results.Push(Map("Test", "Target Serialization & Selector Alternatives", "Status", ok ? "PASS" : "FAIL", "Detail", "Reliability=" tClone.ReliabilityRating ", Alternates=" tClone.AlternateSelectors.Length))
} catch as err {
results.Push(Map("Test", "Target Serialization & Selector Alternatives", "Status", "FAIL", "Detail", err.Message))
}
; 7. Undo / Redo Manager
try {
prj := ProjectModel("Undo Test")
ur := UndoRedoManager()
ur.RecordSnapshot(prj, "Add Action")
prj.GetActiveMacro().Actions.Push(ActionModel("UIA_Click"))
prj := ur.Undo(prj)
uOk := (prj.GetActiveMacro().Actions.Length == 0)
prj := ur.Redo(prj)
rOk := (prj.GetActiveMacro().Actions.Length == 1)
results.Push(Map("Test", "Undo / Redo Manager", "Status", (uOk && rOk) ? "PASS" : "FAIL", "Detail", "Verified Undo and Redo state restoration"))
} catch as err {
results.Push(Map("Test", "Undo / Redo Manager", "Status", "FAIL", "Detail", err.Message))
}
; 8. Recording Review & Browser Upgrade Analyzer
try {
mac := MacroModel("Upgrade Test")
a1 := ActionModel("Key_SendKeys"), a1.Parameters["Keys"] := "^l"
a2 := ActionModel("Key_TypeText"), a2.Parameters["Text"] := "https://example.com"
a3 := ActionModel("Key_SendKeys"), a3.Parameters["Keys"] := "{Enter}"
a4 := ActionModel("Wait_Duration"), a4.Parameters["DurationMs"] := 4000
mac.Actions := [a1, a2, a3, a4]
props := RecordingAnalyzer.AnalyzeMacro(mac)
applied := props.Length > 0 && RecordingAnalyzer.ApplyProposal(mac, props[1])
ok := applied && mac.Actions.Length == 1 && mac.Actions[1].Type == "Browser_Navigate"
results.Push(Map("Test", "Browser Upgrade Analyzer (Ctrl+L → Navigate)", "Status", ok ? "PASS" : "FAIL", "Detail", "Converted 4-step Ctrl+L sequence into Browser_Navigate"))
} catch as err {
results.Push(Map("Test", "Browser Upgrade Analyzer (Ctrl+L → Navigate)", "Status", "FAIL", "Detail", err.Message))
}
; 9. Browser Installation & Profile Discovery
try {
bpm := BrowserProfileManager()
bCount := bpm.installedBrowsers.Count
pCount := bpm.discoveredProfiles.Length
bpm.MapLogicalAlias("Work", "Edge", "Default", "Work Profile")
resProf := bpm.ResolveProfileByAliasOrId("Edge", "Work")
ok := (bCount > 0 && pCount > 0 && IsObject(resProf))
results.Push(Map("Test", "Browser & Profile Discovery + Logical Alias", "Status", ok ? "PASS" : "FAIL", "Detail", Format("{1} browsers, {2} profiles discovered", bCount, pCount)))
} catch as err {
results.Push(Map("Test", "Browser & Profile Discovery + Logical Alias", "Status", "FAIL", "Detail", err.Message))
}
; 10. Browser Fallback Policy Enforcement (Strict vs PreferConfigured)
try {
bpm := BrowserProfileManager()
bsm := BrowserSessionManager(bpm)
strictBlocked := false
try bsm.ResolveSession("StrictSess", "Edge", "NonExistentProfile_9999", "Strict", false)
catch
strictBlocked := true
results.Push(Map("Test", "Browser Strict Policy Enforcement", "Status", strictBlocked ? "PASS" : "FAIL", "Detail", "Strict policy refused unavailable profile as required"))
} catch as err {
results.Push(Map("Test", "Browser Strict Policy Enforcement", "Status", "FAIL", "Detail", err.Message))
}
; 11. UIA Initialize & Desktop Root
try {
root := UIA.GetRootElement()
ver := UIA.Version
ok := IsObject(root) && ver != ""
results.Push(Map("Test", "Vendored UIA-v2 Initialization", "Status", ok ? "PASS" : "FAIL", "Detail", "UIA v" ver " initialized; desktop root acquired"))
} catch as err {
results.Push(Map("Test", "Vendored UIA-v2 Initialization", "Status", "FAIL", "Detail", err.Message))
}
; 12. Image Capture, Portable Base64 Storage, & Pixel/Color Engine
try {
imgEng := ImagePixelEngine()
cap := imgEng.CaptureScreenRegionToBmp(20, 20, 28, 28)
cInfo := imgEng.GetPixelColorInfo(25, 25)
ok := (cap["Base64"] != "" && FileExist(cap["FilePath"]) && SubStr(cInfo["Hex"], 1, 2) == "0x")
try FileDelete(cap["FilePath"])
results.Push(Map("Test", "Image Capture (BMP/Base64) & Pixel Color", "Status", ok ? "PASS" : "FAIL", "Detail", "Captured 28×28 BMP, encoded Base64, read " cInfo["Hex"]))
} catch as err {
results.Push(Map("Test", "Image Capture (BMP/Base64) & Pixel Color", "Status", "FAIL", "Detail", err.Message))
}
; 13. Disposable Local HTML Fixture Generation & Cleanup
try {
fixPath := DiagnosticsEngine.CreateDisposableHtmlFixture()
ex := FileExist(fixPath) != ""
DiagnosticsEngine.CleanupHtmlFixture()
cleaned := !FileExist(fixPath)
results.Push(Map("Test", "Disposable Local HTML Browser Fixture", "Status", (ex && cleaned) ? "PASS" : "FAIL", "Detail", "Created and cleaned disposable test fixture"))
} catch as err {
results.Push(Map("Test", "Disposable Local HTML Browser Fixture", "Status", "FAIL", "Detail", err.Message))
}
; 14. Standalone AHK v2 Export Generation & Syntax Verification
try {
prj := ProjectModel("Export Verification")
mac := prj.GetActiveMacro()
act := ActionModel("UIA_Click")
act.Target.Name := "Submit"
act.Target.PrimarySelector.ControlType := "Button"
act.Target.PrimarySelector.ElementName := "Submit"
mac.Actions.Push(act)
exportedCode := AHKExporter.ExportProjectToAhk(prj, "Always")
hasReq := InStr(exportedCode, "#Requires AutoHotkey v2.0") > 0
hasUIA := InStr(exportedCode, "class UIA") > 0
results.Push(Map("Test", "Standalone AHK v2 Exporter (Inline UIA)", "Status", (hasReq && hasUIA) ? "PASS" : "FAIL", "Detail", "Exported " StrLen(exportedCode) " chars with inline UIA runtime"))
} catch as err {
results.Push(Map("Test", "Standalone AHK v2 Exporter (Inline UIA)", "Status", "FAIL", "Detail", err.Message))
}
; 15. Ahk2Exe Compiler Detection
try {
pe := PersistenceEngine()
comp := pe.DetectCompilerPath()
if comp != "" && FileExist(comp)
results.Push(Map("Test", "Ahk2Exe Compiler Detection", "Status", "PASS", "Detail", "Found at " comp))
else
results.Push(Map("Test", "Ahk2Exe Compiler Detection", "Status", "SKIPPED — Ahk2Exe not installed in standard paths", "Detail", "Use Browse in Tools → Options"))
} catch as err {
results.Push(Map("Test", "Ahk2Exe Compiler Detection", "Status", "FAIL", "Detail", err.Message))
}
; 16. Low-Level Hook Install & Deterministic Cleanup Cycle
try {
ov := OverlayManager()
ut := UIATargetEngine(ov)
bpm := BrowserProfileManager()
bsm := BrowserSessionManager(bpm)
rec := RecorderEngine("", ut, ov, bsm, LoggingEngine())
rec._InstallHooks()
hooksInstalled := (IsObject(rec.textHook) && rec.textHook.InProgress && rec.hMouseHook != 0)
rec._UninstallHooks()
hooksCleaned := (!IsObject(rec.textHook) && rec.hMouseHook == 0 && rec.mouseHookProc == 0)
ov.DestroyAll()
results.Push(Map("Test", "Recorder Hook Install & Cleanup Invariant", "Status", (hooksInstalled && hooksCleaned) ? "PASS" : "FAIL", "Detail", "Installed InputHook and WH_MOUSE_LL; verified stopped input and released mouse hook/callback"))
} catch as err {
results.Push(Map("Test", "Recorder Hook Install & Cleanup Invariant", "Status", "FAIL", "Detail", err.Message))
}
; 17. Selection Overlay Self-Exclusion & Dual-Context Highlighting Verification
try {
ov := OverlayManager()
ov.ShowHighlightRect(100, 100, 120, 40)
ov.ShowSecondaryRect(80, 80, 220, 120)
ov.ShowCrosshair(160, 120)
ov.ShowHud(100, 100, "SELECTION LENS", "Button 'Test'", "Depth: [Button ★] › Group")
selfExcluded := ov.overlayHwnds.Count >= 11
for hwndKey, _ in ov.overlayHwnds {
if !ov.IsOverlayHwnd(hwndKey)
selfExcluded := false
}
ov.DestroyAll()
results.Push(Map("Test", "Dual-Context Overlay & Self-Exclusion", "Status", selfExcluded ? "PASS" : "FAIL", "Detail", "Verified primary, secondary container, crosshair, and HUD HWNDs (" ov.overlayHwnds.Count " total) are self-excluded"))
} catch as err {
results.Push(Map("Test", "Dual-Context Overlay & Self-Exclusion", "Status", "FAIL", "Detail", err.Message))
}
; 18. Live Windows UIA Inspection (Taskbar / Desktop ElementFromPoint)
try {
ov := OverlayManager()
ut := UIATargetEngine(ov)
disc := ut.DiscoverCandidatesAtPoint(A_ScreenWidth // 2, A_ScreenHeight // 2, 0)
cands := disc["Candidates"]
ok := IsObject(cands) && cands.Length > 0 && IsObject(cands[1]["Target"])
ov.DestroyAll()
results.Push(Map("Test", "Live Windows UIA Point Inspection", "Status", ok ? "PASS" : "FAIL", "Detail", ok ? ("Inspected live element (" cands.Length " candidates): " cands[1]["Target"].GetHumanLabel()) : "No target returned"))
} catch as err {
results.Push(Map("Test", "Live Windows UIA Point Inspection", "Status", "FAIL", "Detail", err.Message))
}
; 19. Multi-Session Browser Isolation (Source vs Destination Affinity)
try {
bpm := BrowserProfileManager()
bsm := BrowserSessionManager(bpm)
bsm.sessions["Source"] := Map("SessionName", "Source", "BrowserType", "Edge", "EffectiveProfile", "Default", "Hwnd", 1001, "PID", 101, "CurrentURL", "https://source.example")
bsm.sessions["Destination"] := Map("SessionName", "Destination", "BrowserType", "Chrome", "EffectiveProfile", "Profile 1", "Hwnd", 2002, "PID", 202, "CurrentURL", "https://dest.example")
s1 := bsm.sessions["Source"]
s2 := bsm.sessions["Destination"]
ok := (s1["Hwnd"] == 1001 && s2["Hwnd"] == 2002 && s1["BrowserType"] != s2["BrowserType"])
results.Push(Map("Test", "Multi-Session Browser Isolation (Source/Dest)", "Status", ok ? "PASS" : "FAIL", "Detail", "Verified independent HWND/Profile bindings across named sessions"))
} catch as err {
results.Push(Map("Test", "Multi-Session Browser Isolation (Source/Dest)", "Status", "FAIL", "Detail", err.Message))
}
; 20. Crash Recovery Snapshot Save, Detection & Cleanup
try {
pe := PersistenceEngine()
prj := ProjectModel("Recovery Verification")
prj.IsDirty := true
pe.WriteAutosave(prj)
recInfo := pe.CheckForCrashRecovery()
hasRec := IsObject(recInfo) && recInfo.Has("Project") && recInfo["Project"].Name == "Recovery Verification"
pe.ClearCrashRecoveryState()
cleared := (pe.CheckForCrashRecovery() == "")
ok := (hasRec && cleared)
results.Push(Map("Test", "Crash Recovery Snapshot & Cleanup", "Status", ok ? "PASS" : "FAIL", "Detail", "Saved, detected, reloaded, and cleared crash recovery snapshot"))
} catch as err {
results.Push(Map("Test", "Crash Recovery Snapshot & Cleanup", "Status", "FAIL", "Detail", err.Message))
}
; 21. 1,000-Step Workflow AST Flatten/Validate/Serialize Stress Test (Section 131)
try {
t0 := A_TickCount
mac := MacroModel("1000-Step Stress")
loop 1000 {
a := ActionModel("Wait_Duration")
a.Parameters["DurationMs"] := 10
mac.Actions.Push(a)
}
flat := WorkflowTree.Flatten(mac.Actions)
probs := WorkflowTree.ValidateTree(mac.Actions)
elapsed := A_TickCount - t0
ok := (flat.Length == 1000 && probs.Length == 0)
results.Push(Map("Test", "1,000-Step Workflow AST Stress Test", "Status", ok ? "PASS" : "FAIL", "Detail", Format("Flattened & validated 1,000 actions in {1} ms", elapsed)))
} catch as err {
results.Push(Map("Test", "1,000-Step Workflow AST Stress Test", "Status", "FAIL", "Detail", err.Message))
}
; 22. vNext Target Health State Machine, Ambiguity Detection & Volatile AutomationId Penalty
try {
t := TargetModel("DynamicControl", "Button", "UIA")
t.PrimarySelector.AutomationId := "react-987654"
t.PrimarySelector.ControlType := "Button"
t.ComputeReliability()
volOk := TargetModel.IsVolatileAutomationId("react-987654") && (t.ReliabilityRating == "Contextual")
t.PrimarySelector.ElementName := "Save"
t.RecordOutcome(true, "UIA_Primary", 4)
ambOk := (t.HealthStatus == StudioConstants.HealthAmbiguous && t.LastMatchCount == 4)
t.ApplyFallbackPreset(StudioConstants.PresetStrictSemantic)
presetOk := (t.FallbackPreset == StudioConstants.PresetStrictSemantic && t.AllowedFallbacks.Length == 3)
ok := volOk && ambOk && presetOk
results.Push(Map("Test", "vNext Target Health, Ambiguity & Volatile ID Penalty", "Status", ok ? "PASS" : "FAIL", "Detail", Format("VolatileID={1}, Health={2}, Preset={3}", volOk, t.HealthStatus, t.FallbackPreset)))
} catch as err {
results.Push(Map("Test", "vNext Target Health, Ambiguity & Volatile ID Penalty", "Status", "FAIL", "Detail", err.Message))
}
; 23. vNext Browser Policy Resolution Simulator & Friendly Policy Labels
try {
bpm := BrowserProfileManager()
bsm := BrowserSessionManager(bpm)
simStrict := bsm.SimulatePolicyResolution("MainBrowser", "Edge", "NonExistent_99", StudioConstants.PolicyStrict)
lbl := StudioConstants.PolicyToFriendlyText(StudioConstants.PolicyPreferConfiguredDefault)
codeBack := StudioConstants.FriendlyTextToPolicy(lbl)
ok := (!simStrict["WouldSucceed"] && codeBack == StudioConstants.PolicyPreferConfiguredDefault)
results.Push(Map("Test", "vNext Browser Policy Simulator & Friendly Labels", "Status", ok ? "PASS" : "FAIL", "Detail", "Verified SimulatePolicyResolution and human-readable policy round-trip"))
} catch as err {
results.Push(Map("Test", "vNext Browser Policy Simulator & Friendly Labels", "Status", "FAIL", "Detail", err.Message))
}
; 24. vNext Wait_FirstMatch (Either / Or) & Responsive Layout Clamping (1366x768, 1080p, 4K)
try {
pe := PersistenceEngine()
mLow := pe.ClampLayoutMetrics(1024, 680)
m1080 := pe.ClampLayoutMetrics(1920, 1080)
m4K := pe.ClampLayoutMetrics(3840, 2160)
clampOk := (mLow["LeftW"] <= 195 && m1080["LeftW"] >= 200 && m4K["RightW"] <= 460)
lg := LoggingEngine()
vs := VariableStore(lg)
vs.SetRuntime("ReadyFlag", "1")
pb := PlaybackEngine("", vs, ConditionEngine(vs), UIATargetEngine(), BrowserSessionManager(BrowserProfileManager()), ImagePixelEngine(), lg)
wAct := ActionModel("Wait_FirstMatch")
wAct.Parameters["OutcomeAType"] := "VarEquals"
wAct.Parameters["OutcomeAValue"] := "ReadyFlag"
wAct.Parameters["OutcomeBType"] := "TitleContains"
wAct.Parameters["OutcomeBValue"] := "NonExistentWindow_999"
wAct.Parameters["OutputVar"] := "WinnerBranch"
wRes := pb._ExecuteWaitFirstMatch(MacroModel("Test"), wAct, A_TickCount)
ok := clampOk && wRes.Success && vs.Get("WinnerBranch") == "A"
results.Push(Map("Test", "vNext Wait_FirstMatch & Responsive Layout Clamping", "Status", ok ? "PASS" : "FAIL", "Detail", Format("Wait_FirstMatch Winner={1}, Clamped LowRes LeftW={2}", vs.Get("WinnerBranch"), mLow["LeftW"])))
} catch as err {
results.Push(Map("Test", "vNext Wait_FirstMatch & Responsive Layout Clamping", "Status", "FAIL", "Detail", err.Message))
}
return results
}
}
; ==============================================================================
; PART 7: DESIGN SYSTEM TOKENS, RESPONSIVE LAYOUT MANAGER, MAIN GUI, & INSPECTORS
; ==============================================================================
; Seven intentional logo clicks in one About session reveal this local vignette.
; Text follows About's encoded-copy convention; no visible discovery hint.
class NicholsWorkshop {
__New(owner, schedule := "") {
this.owner := owner
this.schedule := IsObject(schedule) ? schedule : (callback, period) => SetTimer(callback, period)
this.timer := ""
this.gui := "", this.clicks := 0, this.frame := 0, this.running := false
}
LogoClick(*) {
if this.Busy() || IsObject(this.gui)
return
this.clicks += 1
if this.clicks == 7 {
this.clicks := 0
this.Open()
}
}
Busy() {
a := this.owner.app
return a.recorder.isRecording || a.playback.isRunning || a.selectionEngine.isActive
}
Open() {
if IsObject(this.gui) || this.Busy()
return
t := this.owner._AboutDecode.Bind(this.owner)
d := Gui("+Owner" this.owner.aboutDialog.Hwnd, t("TmljaG9sc+KAmSBXb3Jrc2hvcA=="))
this.gui := d
d.BackColor := "F4F6FA"
d.SetFont("s11 c243247", DesignTokens.FontUI)
d.AddText("x20 y18 w420 h26", t("TmljaG9sc+KAmSBXb3Jrc2hvcA=="))
d.SetFont("s9 c526178", DesignTokens.FontUI)
d.AddText("x20 y50 w420 h36", t("Rm9yIHBlb3BsZSB3aG8gd291bGQgcmF0aGVyIGJ1aWxkIHRoYW4gcmVwZWF0Lg=="))
d.AddText("x20 y96 w420 h124 BackgroundE5EAF2", "")
this.blocks := []
for i, label in ["1 Find", "2 Work", "3 Finish"]
this.blocks.Push(d.AddText("x" (36 + (i-1)*132) " y130 w116 h36 Center +0x200 BackgroundD6DCE5", label))
this.play := d.AddText("x174 y180 w112 h28 Center +0x200 BackgroundD6DCE5", "▶ Play")
d.SetFont("s20 c243247", DesignTokens.FontUI)
this.cursor := d.AddText("x38 y100 w30 h34 BackgroundTrans", "➤")
d.SetFont("s10 c243247", DesignTokens.FontUI)
this.status := d.AddText("x20 y234 w420 h24 Center", "")
this.signature := d.AddText("x20 y266 w420 h44 Center", "")
this.signatureText := t("TWFkZSBieSBDaGFybGVzIE5pY2hvbHMgwrcgbmljaG9scy5haS4=")
this.staticView := d.AddCheckbox("x20 y326 w176 h28", "Static presentation")
this.staticView.OnEvent("Click", (*) => this.Replay())
d.AddButton("x220 y326 w100 h28", "Replay").OnEvent("Click", (*) => this.Replay())
d.AddButton("x340 y326 w100 h28 Default", "Close").OnEvent("Click", (*) => this.Close())
d.OnEvent("Close", (*) => this.Close())
d.OnEvent("Escape", (*) => this.Close())
d.Show("w460 h374")
this.Replay()
}
Replay() {
this.StopTimer()
if !IsObject(this.gui)
return
this.frame := this.staticView.Value ? 10 : 0
this.Render()
if this.frame < 10 {
this.running := true
this.timer := ObjBindMethod(this, "Tick")
this.schedule.Call(this.timer, 650)
}
}
Tick(*) {
if !this.running || !IsObject(this.gui)
return
if this.Busy() {
this.Close()
return
}
this.frame := Min(10, this.frame + 1)
this.Render()
if this.frame == 10
this.StopTimer()
}
Render() {
f := this.frame
this.status.Text := f < 4 ? "Assembling a little macro…" : f < 6 ? "Ready. Set. Play." : f < 10 ? "A little workflow at work…" : "Built once. Ready for the next idea."
for i, block in this.blocks {
block.Visible := f >= i || f == 10
block.Opt("Background" (f >= i+6 ? "BCE4D5" : "D6DCE5"))
}
this.play.Text := (f == 5 ? "● Play" : "▶ Play")
positions := [[38,100],[68,110],[200,110],[332,110],[238,170],[238,180],[68,110],[200,110],[332,110],[346,248],[346,248]]
p := positions[f+1]
this.cursor.Move(p[1], p[2])
this.cursor.Visible := f < 10
this.signature.Text := f >= 9 ? this.signatureText : ""
}
StopTimer() {
this.running := false
if IsObject(this.timer)
this.schedule.Call(this.timer, 0)
this.timer := ""
}
Close(*) {
this.StopTimer()
if IsObject(this.gui) {
d := this.gui
this.gui := ""
d.Destroy()
}
this.blocks := [], this.cursor := "", this.play := "", this.status := "", this.signature := "", this.staticView := ""
}
EndSession() {
this.Close()
this.clicks := 0
}
}
class DesignTokens {
static GapXS := 4
static GapSM := 8
static GapMD := 12
static GapLG := 16
static ToolbarH := 40
static BannerH := 34
static BottomTabH := 200
static NavWidthWide := 240
static NavWidthStandard := 190
static InspectorWidthWide := 370
static InspectorWidthStandard := 320
static MinWorkflowWidth := 380
static MinClientW := 680
static MinClientH := 500
static FontUI := "Segoe UI"
static FontMono := "Consolas"
}
class ResponsiveLayoutManager {
guiOwner := ""
currentMode := "Wide" ; Wide, Standard, Compact
forcedMode := "Auto"
isLayingOut := false
__New(guiOwner) {
this.guiOwner := guiOwner
}
ComputeLayoutMode(clientW, clientH) {
if this.forcedMode != "Auto" && this.forcedMode != ""
return this.forcedMode
if clientW >= 1140
return "Wide"
if clientW >= 820
return "Standard"
return "Compact"
}
ApplyLayout(clientW, clientH) {
if this.isLayingOut || clientW <= 0 || clientH <= 0
return
this.isLayingOut := true
hwnd := this.guiOwner.mainGui.Hwnd
visible := DllCall("IsWindowVisible", "Ptr", hwnd)
if visible
SendMessage(0xB, 0, 0, hwnd) ; Batch control moves into one paint.
try {
mode := this.ComputeLayoutMode(clientW, clientH)
this.currentMode := mode
this.guiOwner.PerformResponsiveLayout(clientW, clientH, mode)
} finally {
if visible {
SendMessage(0xB, 1, 0, hwnd)
DllCall("RedrawWindow", "Ptr", hwnd, "Ptr", 0, "Ptr", 0, "UInt", 0x185)
}
this.isLayingOut := false
}
}
}
; ==============================================================================
; MAIN STUDIO GUI & BUILT-IN INSPECTORS / DIALOGS
; ==============================================================================
; Guided editor generated from each action's actual parameter model.
; Windows Core Audio session metering. COM references are owned by each snapshot.
class ProgramAudio {
static Guid(value) {
buf := Buffer(16, 0)
if DllCall("ole32\CLSIDFromString", "WStr", value, "Ptr", buf, "Int") < 0
throw ValueError("Invalid audio interface identifier")
return buf
}
static Snapshot(output := "All outputs") {
if output != "All outputs" && output != "Default output"
throw ValueError("Choose All outputs or Default output.")
enumerator := ComObject("{BCDE0395-E52F-467C-8E3D-C4579291692E}", "{A95664D2-9614-4F35-A746-DE8DB63617E6}")
rows := [], devices := 0, device := 0
try {
if output == "Default output" {
ComCall(4, enumerator, "Int", 0, "Int", 1, "Ptr*", &device)
this.DeviceSessions(device, rows)
} else {
ComCall(3, enumerator, "Int", 0, "UInt", 1, "Ptr*", &devices)
ComCall(3, devices, "UInt*", &count := 0)
if !count
throw Error("No active audio output device is available.")
Loop count {
ComCall(4, devices, "UInt", A_Index-1, "Ptr*", &device)
try this.DeviceSessions(device, rows)
finally {
ObjRelease(device)
device := 0
}
}
}
} finally {
if device
ObjRelease(device)
if devices
ObjRelease(devices)
}
return rows
}
static DeviceSessions(device, rows) {
manager := 0, sessions := 0
try {
iid := this.Guid("{77AA99A0-1BD6-484F-8BC7-2C654C9A9B6F}")
ComCall(3, device, "Ptr", iid, "UInt", 23, "Ptr", 0, "Ptr*", &manager)
ComCall(5, manager, "Ptr*", &sessions)
ComCall(3, sessions, "Int*", &count := 0)
Loop count {
session := 0, pid := 0
try {
ComCall(4, sessions, "Int", A_Index-1, "Ptr*", &session)
control := ComObjQuery(session, "{BFB7FF88-7239-4FC9-8FA2-07C950BE9C6D}")
ComCall(14, control, "UInt*", &pid := 0)
ComCall(3, control, "Int*", &state := 0)
if !pid || state == 2
continue
name := ProcessGetName(pid)
meter := ComObjQuery(session, "{C02216F6-8C67-4B5B-9D00-D008E73E0064}")
ComCall(3, meter, "Float*", &peak := 0.0)
rows.Push(Map("Process", name, "PID", pid, "Peak", peak * 100, "Active", state == 1))
} catch as err {
; A process can exit while enumerating. Other sessions remain usable.
if pid && ProcessExist(pid)
rows.Push(Map("Process", "", "PID", pid, "Error", err.Message))
} finally {
if session
ObjRelease(session)
}
}
} finally {
if sessions
ObjRelease(sessions)
if manager
ObjRelease(manager)
}
}
static Read(exe, output := "All outputs") {
exe := Trim(exe)
if exe == "" || InStr(exe, "\") || InStr(exe, "/") || !RegExMatch(exe, "i)\.exe$")
throw ValueError("Enter a program filename such as notepad.exe (without a path).")
peak := 0.0, count := 0
for row in this.Snapshot(output) {
if StrLower(row["Process"]) == StrLower(exe) {
count++
peak := Max(peak, row["Peak"])
}
}
return Map("Found", count > 0, "Peak", peak, "Sessions", count)
}
static Validate(p) {
for key in ["ThresholdPercent", "HysteresisPercent"] {
if !IsNumber(p.Get(key, "")) || p[key] < 0 || p[key] > 100
throw ValueError(key " must be between 0 and 100.")
}
for key in ["HoldMs", "SampleMs"] {
if !IsInteger(p.Get(key, "")) || p[key] < (key == "SampleMs" ? 20 : 0) || p[key] > 600000
throw ValueError(key " must be a whole number; sampling must be at least 20 ms.")
}
if !RegExMatch(p.Get("OutputVar", ""), "^[A-Za-z_][A-Za-z0-9_]*$")
throw ValueError("Choose a valid output variable name without spaces.")
if !RegExMatch(p.Get("Trigger", ""), "^(Above|Below|Rising|Falling)$")
throw ValueError("Choose an audio trigger from the list.")
threshold := p["ThresholdPercent"], gap := p["HysteresisPercent"]
if (p["Trigger"] == "Rising" && threshold < gap) || (p["Trigger"] == "Falling" && threshold + gap > 100)
throw ValueError("The crossing reset threshold must remain between 0 and 100%.")
}
}
; Pure state machine, also exercised with deterministic audio samples in QA.
class AudioTrigger {
__New(p) {
ProgramAudio.Validate(p)
this.mode := p["Trigger"], this.threshold := p["ThresholdPercent"]
this.gap := p["HysteresisPercent"], this.hold := p["HoldMs"]
this.Reset()
}
Reset() {
this.armed := false, this.since := -1
}
Sample(found, peak, now) {
if !found {
this.Reset()
return false
}
rising := this.mode == "Rising", falling := this.mode == "Falling"
if (rising && peak <= this.threshold-this.gap) || (falling && peak >= this.threshold+this.gap)
this.armed := true
met := (this.mode == "Above" || rising) ? peak > this.threshold : peak < this.threshold
if (rising || falling) && !this.armed
met := false
if !met {
this.since := -1
return false
}
if this.since < 0
this.since := now
return now-this.since >= this.hold
}
}
class AudioMonitorUI {
__New(editor) {
this.editor := editor
this.ownerHwnd := editor.dialog.Hwnd
this.gui := Gui("+Owner" editor.dialog.Hwnd, "Choose program and tune audio")
g := this.gui
g.SetFont("s10", "Segoe UI")
g.AddText("x18 y16 w580 h44", "Play sound in the desired program, then choose its audio session. Levels are signal peaks (0-100%), not the Windows volume slider.")
this.list := g.AddListView("x18 y70 w580 h140 -Multi", ["Program", "PID", "Peak %"])
this.list.ModifyCol(1, 310), this.list.ModifyCol(2, 100), this.list.ModifyCol(3, 120)
this.process := g.AddEdit("x18 y225 w300", this.Field("ProcessName").Value)
g.AddButton("x330 y223 w125 h28", "Refresh list").OnEvent("Click", (*) => this.Refresh())
this.bar := g.AddProgress("x18 y270 w580 h24 Range0-100", 0)
this.status := g.AddText("x18 y305 w580 h55", "Choose a program to view its level.")
g.AddButton("x18 y375 w180 h32 Default", "Use this program").OnEvent("Click", (*) => this.Use())
g.AddButton("x210 y375 w120 h32", "Close").OnEvent("Click", (*) => this.Close())
this.list.OnEvent("ItemSelect", (lv, row, selected) => selected ? this.Select(row) : 0)
g.OnEvent("Close", (*) => this.Close()), g.OnEvent("Escape", (*) => this.Close())
this.tick := ObjBindMethod(this, "Update")
this.Refresh()
g.Show("w620 h425")
SetTimer(this.tick, 150)
}
Field(key) {
for field in this.editor.fields
if field.key == key
return field.control
throw Error("Missing audio setting: " key)
}
Refresh() {
this.list.Delete()
try {
seen := Map()
for row in ProgramAudio.Snapshot(this.Field("AudioOutput").Text) {
if row.Has("Error") || seen.Has(row["PID"])
continue
seen[row["PID"]] := true
this.list.Add(, row["Process"], row["PID"], Round(row["Peak"], 2))
}
} catch as err
this.status.Text := "Audio unavailable: " err.Message
}
Select(row) {
this.process.Value := this.list.GetText(row, 1)
}
Update() {
if !DllCall("IsWindow", "Ptr", this.ownerHwnd) {
this.Close()
return
}
try {
value := ProgramAudio.Read(this.process.Value, this.Field("AudioOutput").Text)
this.bar.Value := value["Peak"]
this.status.Text := value["Found"] ? Round(value["Peak"], 2) "% peak across " value["Sessions"] " session(s). Set a threshold above background activity."
: "No matching audio session. Start sound in the program, then refresh. Missing sessions are not silence."
} catch as err {
this.bar.Value := 0
this.status.Text := err.Message
}
}
Use() {
try {
ProgramAudio.Read(this.process.Value, this.Field("AudioOutput").Text)
this.Field("ProcessName").Value := Trim(this.process.Value)
this.Close()
} catch as err
this.status.Text := err.Message
}
Close() {
SetTimer(this.tick, 0)
this.gui.Destroy()
}
}
class BackupTargetsUI {
closed := false
testing := false
Close(*) {
this.closed := true
try this.dialog.Destroy()
}
CreateTestEngine() {
e := UIATargetEngine("", this.ui.app.imageEngine, this.ui.app.browserMgr)
e.cancelCheck := (*) => this.closed
return e
}
ShowPlanResult(result) {
if this.closed
return
this.status.Text := result["Found"] ? "Plan resolved. See complete outcomes." : UIATargetEngine.FailureGuidance(result.Get("Reason", ""))["Message"]
MsgBox(UIATargetEngine.PlanSummary(result) "`r`nNo input was sent.", "Complete backup plan — no clicks", "Iconi")
}
__New(ui,act,show := true) {
this.ui := ui, this.act := act, this.ownerProject := ui.app.project
effective := UIATargetEngine.EffectiveTarget(act, ui.app.project)
if !IsObject(effective)
throw ValueError("Restore the missing reusable target before editing backups.")
this.target := effective.Clone()
t := this.target
if !t.ManualBackups {
for alt in t.AlternateSelectors {
copy := t.Clone(), copy.BackupTargets := [], copy.AlternateSelectors := []
copy.PrimarySelector := alt.Clone(), copy.ManualBackups := true
copy.BackupEnabled := alt.Enabled && t.AllowsStrategy(alt.StrategyType)
copy.Name := alt.Name
kinds := Map("ImageMatch","Image","PixelMatch","PixelColor","WindowRelativeCoord","WindowRelative","ScreenCoord","ScreenCoordinate")
copy.TargetKind := kinds.Get(alt.StrategyType,"UIA")
t.BackupTargets.Push(copy)
}
}
t.ManualBackups := true, t.AlternateSelectors := []
this.dialog := d := Gui("+Owner" ui.mainGui.Hwnd,"Backup targets")
d.SetFont("s10",DesignTokens.FontUI)
d.AddText("x16 y16 w690 h64","Try the primary target first, then each enabled backup in order until one is found. Backups must preserve exact object identity and scope. Visual/coordinate modes are separate targets.")
this.list := d.AddListView("x16 y88 w690 h235 -Multi",["Order","Target","Eligibility / reason","Use"])
this.list.ModifyCol(1,70),this.list.ModifyCol(2,180),this.list.ModifyCol(3,350),this.list.ModifyCol(4,70)
d.AddButton("x16 y338 w130 h30","+ Add target…").OnEvent("Click",(*) => this.AddMenu())
d.AddButton("x154 y338 w100 h30","Remove").OnEvent("Click",(*) => this.Remove())
d.AddButton("x262 y338 w90 h30","Move up").OnEvent("Click",(*) => this.Move(-1))
d.AddButton("x360 y338 w90 h30","Move down").OnEvent("Click",(*) => this.Move(1))
d.AddButton("x458 y338 w120 h30","Enable / disable").OnEvent("Click",(*) => this.Toggle())
d.AddButton("x470 y464 w236 h32","Test complete backup plan").OnEvent("Click",(*) => this.Test())
this.status := d.AddText("x16 y382 w690 h64","Edits are local to this step. Saving detaches its shared reusable target; other steps remain unchanged. Rejected enabled entries must be disabled or removed before saving; legacy entries are retained until you choose.")
d.AddButton("x16 y464 w150 h32 Default","Save backups").OnEvent("Click",(*) => this.Save())
d.AddButton("x178 y464 w110 h32","Cancel").OnEvent("Click",(*) => this.Close())
d.OnEvent("Escape",(*) => this.Close())
d.OnEvent("Close",(*) => this.Close())
this.Refresh()
if show
d.Show("w722 h514")
}
Refresh(row := 1) {
this.list.Delete()
this.list.Add("", "Primary",this.target.GetHumanLabel(),this.target.GetMethodLabel(),"Always")
for index, target in this.target.BackupTargets {
eligible := this.ui.app.uiaEngine.BackupEligibility(this.target, target)
this.list.Add("", index, target.GetHumanLabel(), (eligible["Eligible"] ? "Eligible: " : "REJECTED: ") eligible["Reason"], target.BackupEnabled ? "Enabled" : "Disabled")
}
this.list.Modify(Min(Max(1,row),this.list.GetCount()),"Select Focus")
}
AddMenu() {
choices := Menu()
for item in [["Choose element or coordinate layer…","UIAAction"],["Capture image…","ImageCapture"],["Choose pixel color…","PixelColorSelection"]]
choices.Add(item[1],ObjBindMethod(this,"Pick",item[2]))
choices.Show()
}
Pick(mode,*) {
this.dialog.Hide()
this.ui.app.selectionEngine.StartSelection(mode,ObjBindMethod(this,"Picked"),"",(*) => this.dialog.Show())
}
Picked(target,*) {
if IsObject(target)
this.AddTarget(target)
this.dialog.Show()
}
AddTarget(target) {
copy := target.Clone()
copy.BackupTargets := [], copy.AlternateSelectors := [], copy.ManualBackups := true, copy.BackupEnabled := true
this.target.BackupTargets.Push(copy)
this.Refresh(this.target.BackupTargets.Length+1)
}
Remove() {
row := this.list.GetNext()
if row <= 1 {
this.status.Text := "Select a backup to remove. Change the primary target from the action inspector."
return
}
this.target.BackupTargets.RemoveAt(row-1)
this.Refresh(row)
}
Move(direction) {
row := this.list.GetNext(), index := row-1, next := index+direction
if index < 1 || next < 1 || next > this.target.BackupTargets.Length
return
target := this.target.BackupTargets.RemoveAt(index)
this.target.BackupTargets.InsertAt(next,target)
this.Refresh(next+1)
}
Toggle() {
row := this.list.GetNext()
if row <= 1
return
this.target.BackupTargets[row-1].BackupEnabled := !this.target.BackupTargets[row-1].BackupEnabled
this.Refresh(row)
}
Test() {
if this.closed || this.testing || !this.ui.app._CanReplaceProject()
return
this.testing := true
try {
result := this.CreateTestEngine().ResolveOnly(this.target, 0)
if !this.closed
this.ShowPlanResult(result)
} catch as err {
if !this.closed
this.status.Text := "Check could not complete: " err.Message
} finally
this.testing := false
}
OwnerIsCurrent() {
if this.ui.app.project != this.ownerProject
return false
for macro in this.ownerProject.Macros {
location := WorkflowTree.FindById(macro.Actions, this.act.Id)
if IsObject(location) && location["Action"] == this.act
return true
}
return false
}
Save() {
if this.testing || this.closed
return
if !this.OwnerIsCurrent() {
this.status.Text := "This step or project has changed. Close this editor and reopen backups from the current step. No changes were saved."
return
}
for index, backup in this.target.BackupTargets {
eligibility := this.ui.app.uiaEngine.BackupEligibility(this.target, backup)
if backup.BackupEnabled && !eligibility["Eligible"] {
this.status.Text := "Cannot save enabled backup " index ": " eligibility["Reason"] " Disable or remove it explicitly."
return
}
}
this.ui.app.undoMgr.RecordSnapshot(this.ui.app.project,"Edit backup targets")
this.act.Target := this.target.Clone()
this.act.ReusableTargetId := "", this.act.Target.ReusableTargetId := ""
this.act.Target.FallbackPreset := "Custom"
this.ui.app.project.IsDirty := true
this.ui.RefreshAll()
this.Close()
}
}
class ActionDiscovery {
static Matches(def, query) {
if def["Type"] == "Logic_Label"
return false ; Keep legacy project support, but author labels on actions now.
hay := StrLower(def["Name"] " " def["Cat"] " " def["Type"] " " def["Keywords"] " " this.Description(def["Type"]))
for term in StrSplit(StrLower(Trim(query)), " ")
if term != "" && !InStr(hay, term)
return false
return true
}
static Description(type) {
specific := Map(
"App_Run","Open a program, document, shortcut, or folder. Browse for a file or folder; optionally add command-line arguments, a working folder, and a window mode.",
"App_OpenURL","Open a website using your default browser. Use Navigate Browser to URL to control a specific browser session.",
"Wait_Duration","Pause for a fixed duration or a random range. Choose milliseconds, seconds, minutes, or hours. No target needed.",
"Wait_Clock","Wait until a local time of day. Choose what happens if that time has already passed.",
"Wait_Element","Wait for an element to appear, disappear, become enabled, or contain text. Choose the element on the Target tab.",
"Win_Wait","Wait for a window to open, close, become active, or become inactive.",
"Wait_ImageColor","Wait for a screenshot image or pixel color to appear or disappear. Capture its target, then configure the wait.",
"Wait_Condition","Wait for a guided check involving a variable, clipboard, file, screen target, or other condition.",
"Logic_If","Run nested steps only when a condition is true. Optional Else steps handle the other outcome.",
"Logic_Repeat","Repeat nested steps a fixed number of times, or choose a random count within a range.",
"Logic_ForEach","Process each item in a list. Enter one item per line or use a list variable; child steps use ${Item}.",
"Logic_While","Repeat nested steps while a condition is true, or until it becomes true. Includes an iteration limit.",
"Key_TypeText","Type literal text at the current caret. Supports optional Enter and a delay between characters.",
"UIA_SetValue","Replace the value of a chosen input. Useful for filling a specific text field.",
"OCR_ReadText","Read text from a screen region, window, image, or PDF. Save text, lines for a list loop, or structured words.",
"OCR_FindText","Find recognized text and save matches, their count, and whether any were found. Does not click.",
"OCR_ClickText","Find text on screen, then click it. Unique match is the safe default when text repeats.",
"OCR_WaitText","Wait until recognized text appears, disappears, or changes. Use Test OCR to inspect recognition.",
"Audio_Wait","Wait for sound or silence from a chosen program. Includes a live meter for choosing thresholds.")
if specific.Has(type)
return specific[type]
for def in ActionRegistry.GetDefinitions()
if def["Type"] == type
return def["Name"] ". " (def["UsesTarget"] ? "Configure the action, then choose its target using the Target controls." : "Configure this step's options. No screen target is required.")
return "Configure this action's settings."
}
}
class ActionSettingsUI {
fields := []
static Choices(key, type) {
if key == "OCRSource" && type == "OCR_ClickText"
return ["Region","Window","Desktop"]
if key == "State" && type == "UIA_ExpandCollapse"
return ["Expand", "Collapse"]
if key == "MatchMode" && (type == "Browser_SelectTab" || type == "Browser_CloseTab")
return ["Current", "Exact", "Contains", "StartsWith", "Regex", "URLContains"]
if key == "Condition"
return type == "Wait_ImageColor" ? ["Appear", "Disappear"] : ["PageReady", "URLContains", "TitleContains", "TabExists"]
if key == "OutcomeAType" || key == "OutcomeBType"
return ["ElementAppears", "TextAppears", "URLContains", "TitleContains"]
if key == "SecondConditionType" {
values := this.Choices("ConditionType", type)
values.InsertAt(1, "None")
return values
}
if key == "Button" && type != "Mouse_Click" && type != "UIA_Click" && type != "Browser_Click"
return ["Left", "Right", "Middle"]
if key == "WaitCondition" && type == "App_WaitProcess"
return ["Appear", "Disappear"]
if key == "OCRLanguage" {
languages := ["Automatic"]
try {
for language in StrSplit(Trim(OCR.GetAvailableLanguages(), "`r`n"), "`n", "`r")
if language != ""
languages.Push(language)
}
return languages
}
options := Map(
"OCRSource", ["Region", "Window", "Desktop", "Image file", "PDF page"],
"OCRMatchMode", ["Contains", "Exact line", "Regular expression"], "MatchSelection", ["Unique", "First", "Occurrence"],
"OCRWaitFor", ["Present", "Absent", "Changes"], "OutputFormat", ["Text", "Lines", "Words"],
"WindowCondition", ["Exists", "Closed", "Active", "Inactive"],
"DurationMode", ["Fixed", "Random"], "DurationUnit", ["Milliseconds", "Seconds", "Minutes", "Hours"],
"OffsetMode", ["None", "Fixed", "Random"], "TypingDelayMode", ["None", "Fixed", "Random"],
"LoopMode", ["While", "Until"], "PastTime", ["Next day", "Continue", "Fail"],
"AudioOutput", ["All outputs", "Default output"], "Trigger", ["Above", "Below", "Rising", "Falling"],
"WindowMode", ["Normal", "Min", "Max", "Hide"],
"Property", ["Auto", "Name", "Value", "URL", "Title", "AllText", "AllLinks"],
"ToggleState", ["Check", "Uncheck", "Toggle"], "Action", ["Back", "Forward", "Reload", "Home"],
"AlertAction", ["GetAndClose", "Close", "GetText"], "JSMode", ["Execute", "ReturnClipboard", "ClickCSS", "ControlClickCSS"],
"State", ["Down", "Up"], "CoordMode", ["Target", "WindowRelative", "Screen", "Client"],
"SourceMode", ["Lines", "Variable", "JSON"], "CountMode", ["Fixed", "Random"],
"Button", ["Left", "Right", "Middle", "Double"], "ClickMethod", ["Auto", "Physical", "Invoke", "ControlClick"],
"DestinationMode", ["Screen", "Relative", "WindowRelative", "Client"],
"StateAction", ["Minimize", "Maximize", "Restore", "Close"], "Direction", ["Down", "Up"],
"OnFailure", ["Stop", "Skip", "Continue", "UseFallback", "AskRepair"],
"WaitMode", ["Auto", "None", "TargetReady", "PageLoad", "Custom"],
"BackoffStrategy", ["Fixed", "Linear", "Exponential"],
"BrowserType", ["", "Edge", "Chrome", "Firefox", "Brave"],
"ExpectOutcome", ["None", "ElementAppears", "ElementDisappears", "URLContains", "TitleContains", "TextAppears", "NewTabOpened"],
"BrowserFallbackPolicy", ["", "Strict", "PreferConfiguredThenCurrent", "PreferConfiguredThenDefault", "CurrentBrowser", "DefaultProfile", "AnyCompatibleSession", "AskWhenAmbiguous", "CustomOrder"], "MatchMode", ["Exact", "Substring", "Regex"],
"CombineOp", ["AND", "OR"],
"WaitCondition", ["Appear", "Disappear", "Enabled", "TextContains", "ValueEquals"],
"Method", ["Auto", "SendText", "Paste", "ValuePattern"],
"Operation", ["Assign", "Append", "Add", "Subtract", "Multiply"],
"ConditionType", ["OCRTextPresent", "OCRTextAbsent", "VarEquals", "VarNotEquals", "VarGreater", "VarLess", "StringContains", "WindowExists", "WindowActive", "UIAExists", "UIAEnabled", "UIATextContains", "URLContains", "TitleContains", "FileExists", "ClipboardContains"])
return options.Get(key, [])
}
__New(ui, act, advanced := false, show := true, initialTab := "") {
this.ui := ui, this.act := act
this.fields := []
this.helpHandles := []
this.fieldPage := 1
this.draft := ActionModel.FromMap(act.ToMap())
actionName := act.Type
for definition in ActionRegistry.GetDefinitions()
if definition["Type"] == act.Type
actionName := definition["Name"]
d := Gui("+Owner" ui.mainGui.Hwnd, "Action settings — " actionName)
this.dialog := d
d.BackColor := "F5F7FA"
d.SetFont("s10", "Segoe UI")
d.AddText("x20 y16 w660 h26", act.ComputeFriendlyDescription())
d.SetFont("s9")
hint := act.Type == "Logic_ForEach" ? "One item per line. Inside this loop use ${Item}; nested loops can use different variable names."
: (act.Type == "Logic_Repeat" ? "Fixed repeats use Count. Random repeats choose one count between Minimum and Maximum."
: "Choose the options for this step. Text accepts variables such as ${Item}. Advanced JSON remains available.")
if InStr(act.Type, "Audio_") == 1
hint := "Program audio peaks: 0–100%. Missing sessions do not mean silence. Rising/Falling waits first observe the opposite side."
if act.Type == "App_Run"
hint := "Browse for a program, file, or folder. Browsed paths are quoted automatically; add arguments after the closing quote. Working folder is optional. Use Wait for Process or Wait for Window for readiness."
if act.Type == "Wait_Duration"
hint := "Choose Fixed or a Random range, then the unit. Decimals are welcome: 1.5 minutes = 90 seconds. Playback speed scales duration waits."
if act.Type == "Wait_Clock"
hint := "Wait until local system time (24-hour HH:MM:SS). Choose what happens if today's time has passed. This wait is not scaled by playback speed."
if InStr(act.Type, "Click")
hint := "Offsets are pixels from the resolved target point. Fixed / Random offsets use physical clicks; None preserves the normal click method."
if InStr("|Key_TypeText|UIA_SetValue|Browser_SetValue|", "|" act.Type "|")
hint := "Character delay is optional (None by default). Fixed / Random pacing types one character at a time; playback speed also scales the delay."
if act.Type == "Logic_Goto" || act.Type == "Logic_Label"
hint := "Labels are unique within their block. Go to label can only jump within that same block. A per-run jump limit prevents runaway workflows."
if InStr(act.Type,"OCR_") == 1
hint := "Choose a source, then Test OCR to inspect recognized text without clicking or changing variables. Lines output feeds a For Each loop. Clicks require a screen source; Unique avoids ambiguous matches."
d.AddText("x20 y48 w660 h40", hint)
tabs := [], params := []
editParams := ActionRegistry.GetDefaultParams(act.Type)
for key, value in act.Parameters
editParams[key] := value
if InStr(act.Parameters.Get("ConditionType",""),"OCR") == 1 || InStr(act.Parameters.Get("SecondConditionType",""),"OCR") == 1
for key, value in StudioOCREngine.Defaults()
if !editParams.Has(key)
editParams[key] := value
if act.Type == "Wait_Duration" && editParams.Get("DurationValue", "") == "" {
unitScale := Map("Milliseconds", 1, "Seconds", 1000, "Minutes", 60000, "Hours", 3600000)
editParams["DurationValue"] := editParams.Get("DurationMs", 1000)/unitScale.Get(editParams.Get("DurationUnit", "Seconds"), 1000)
}
if advanced {
for key in ["WaitMode", "PollingIntervalMs", "BackoffStrategy", "RequireVisible", "RequireEnabled", "SettleTimeMs", "ExpectOutcome", "ExpectValue", "ExpectTimeoutMs", "BrowserType", "BrowserSession", "BrowserProfile", "BrowserFallbackPolicy", "Breakpoint", "Notes"]
params.Push([key, act.%key%, "Action"])
} else {
order := act.Type == "Logic_ForEach" ? ["SourceMode", "Items", "ItemVar", "IndexVar", "SkipEmpty"]
: (act.Type == "Key_TypeText" ? ["Text", "Method", "SendEnterAfter"] : [])
if InStr("|Mouse_Click|UIA_Click|Browser_Click|Image_Click|Pixel_Click|", "|" act.Type "|")
order := ["Button", "ClickCount", "ClickMethod", "CoordMode", "OffsetMode", "OffsetX", "OffsetY", "OffsetMinX", "OffsetMaxX", "OffsetMinY", "OffsetMaxY"]
if InStr("|Key_TypeText|UIA_SetValue|Browser_SetValue|", "|" act.Type "|")
order := ["Text", "Method", "SendEnterAfter", "TypingDelayMode", "CharacterDelayMs", "MinimumDelayMs", "MaximumDelayMs", "ClearFirst"]
if ActionSpecifications.Has(act.Type)
order := ActionSpecifications.FieldOrder(act.Type)
if act.Type == "Logic_While"
order := ["LoopMode", "MaxIterations"]
if InStr(act.Type, "Audio_") == 1
order := ["ProcessName", "AudioOutput", "Trigger", "ThresholdPercent", "HoldMs", "HysteresisPercent", "SampleMs", "OutputVar"]
added := Map()
for key in order {
if act.Type == "Key_TypeText" && key == "ClearFirst"
continue
if editParams.Has(key) {
params.Push([key, editParams[key], "Parameters"])
added[key] := true
}
}
for key, value in editParams {
; Literal typing inserts at the caret. ClearFirst belongs to Set Value;
; preserve the legacy shared parameter without advertising an ignored switch.
if (act.Type == "Key_TypeText" && key == "ClearFirst") || (act.Type == "Wait_Duration" && key == "DurationMs")
continue
if !added.Has(key)
params.Push([key, value, "Parameters"])
}
}
pages := [], pageTitles := [], extraFields := [], basicFields := []
extraTitle := ""
for field in params {
isExtra := !advanced && field[3] == "Parameters" && (InStr(field[1], "Offset") == 1 || InStr("|TypingDelayMode|CharacterDelayMs|MinimumDelayMs|MaximumDelayMs|", "|" field[1] "|"))
if isExtra {
extraFields.Push(field)
extraTitle := InStr(field[1], "Offset") == 1 ? "Click offsets" : "Typing pace"
} else
basicFields.Push(field)
}
Loop Max(1, Ceil(basicFields.Length/5)) {
page := []
Loop 5 {
index := pages.Length*5+A_Index
if index <= basicFields.Length
page.Push(basicFields[index])
}
pages.Push(page)
pageTitles.Push(InStr(act.Type, "Audio_") == 1 && !advanced ? (pages.Length == 1 ? "Program & trigger" : "Sampling & output") : (pages.Length == 1 ? "Action" : "More " pages.Length))
}
if extraFields.Length {
pages.Push(extraFields)
pageTitles.Push(extraTitle)
}
if !advanced && InStr(act.Type,"OCR_") == 1 {
pages := [], pageTitles := []
groups := [["Action", ["SearchText","OCRMatchMode","CaseSensitive","OCRWaitFor","StableForMs","MatchSelection","Occurrence","Button","ClickCount","OutputFormat","CopyToClipboard"]],
["Source", ["OCRSource","OCRFile","PDFPage"]], ["OCR tuning", ["OCRLanguage","OCRScale","OCRGrayscale","OCRInvert"]],
["Output", ["OutputVar","FoundVar","MatchCountVar"]], ["Offsets", ["OffsetMode","OffsetX","OffsetY","OffsetMinX","OffsetMaxX","OffsetMinY","OffsetMaxY"]]]
for group in groups {
page := []
for key in group[2]
if editParams.Has(key)
page.Push([key,editParams[key],"Parameters"])
if page.Length {
pages.Push(page), pageTitles.Push(group[1])
}
}
}
if !advanced && RegExMatch(act.Type,"^(Browser_|Wait_PageLoad|Wait_NewTab|Wait_FirstMatch|Profile_)") {
pages.Push([["BrowserType",act.BrowserType,"Action"],["BrowserProfile",act.BrowserProfile,"Action"],["BrowserSession",act.BrowserSession,"Action"],["BrowserFallbackPolicy",act.BrowserFallbackPolicy,"Action"]])
pageTitles.Push("Browser")
}
pageCount := pages.Length
for title in pageTitles
tabs.Push(title)
usesTarget := ActionRegistry.UsesTarget(act.Type) || act.Type == "Logic_If" || act.Type == "Logic_While" || act.Type == "Wait_Condition" || (act.Type == "Key_SendKeys" && act.Parameters.Get("UseControlSend", false))
if usesTarget
tabs.Push("Target")
tabs.Push("Timing & recovery")
tabs.Push("Label")
tab := d.AddTab3("x16 y94 w688 h430", tabs)
this.tabControl := tab
for pageIndex, page in pages {
tab.UseTab(pageIndex)
this.fieldPage := pageIndex
rowHeight := Min(74, Floor(350/Max(1,page.Length)))
for index, field in page
this.AddField(field[1], field[2], field[3], 132+(index-1)*rowHeight)
if !page.Length
d.AddText("x34 y140 w630", "This step has no additional action options.")
}
if !advanced && RegExMatch(act.Type,"^(Browser_|Wait_PageLoad|Wait_NewTab|Wait_FirstMatch|Profile_)") {
tab.UseTab(pageCount)
d.AddButton("x34 y350 w220 h32","Choose an open browser…").OnEvent("Click",(*) => this.ChooseBrowserValue("BrowserSession"))
d.AddText("x34 y398 w630 h82","Browser, profile and session identify where this step runs. Empty values inherit the macro defaults. Choose an open window to bind it explicitly, or use Launch Browser Profile to start one. Navigate uses the current tab unless Open a new tab is selected.")
}
if !advanced && InStr(act.Type,"OCR_") == 1 {
tab.UseTab(2)
this.ocrChoose := d.AddButton("x34 y360 w190 h32", "Select region / window…")
this.ocrChoose.OnEvent("Click", (*) => this.ChooseTarget())
d.AddButton("x234 y360 w180 h32", "Test OCR…").OnEvent("Click", (*) => this.TestOCR())
d.AddText("x34 y410 w630 h70", "Region follows its selected window. Desktop reads all monitors. File/PDF results use image coordinates and cannot be clicked. OCR tuning lists installed languages; recognition runs locally on this PC.")
}
if usesTarget {
tab.UseTab(pageCount+1)
this.fieldPage := pageCount+1
d.AddText("x34 y132 w630 h40", ui.HasTarget(act) ? act.Target.GetHumanLabel() : "No target chosen. Choose a target before testing a click or UI action.")
if InStr(act.Type,"OCR_") == 1 {
d.AddButton("x34 y180 w190 h30", "Select region / window…").OnEvent("Click", (*) => this.ChooseTarget())
d.AddButton("x234 y180 w170 h30", "Test OCR…").OnEvent("Click", (*) => this.TestOCR())
d.AddText("x34 y230 w630 h130", "Choose Region or Window on the Source tab, then use the picker. Regions follow their selected window. Pick again to adjust the capture area. Desktop and file sources do not need a target.`n`nOCR reads pixels instead of an accessibility selector. Use a small, distinctive region for faster and more reliable matching.")
} else {
d.AddButton("x34 y180 w165 h30", "⌖ Choose target…").OnEvent("Click", (*) => this.ChooseTarget())
d.AddButton("x+10 w235 h30", "Check this step — no clicks").OnEvent("Click", (*) => ui.CmdPreviewCurrentStep())
d.AddButton("x+10 w145 h30", "Backup targets…").OnEvent("Click", (*) => ui.ShowSelectorStrategiesDialog())
for i, key in ["WinTitle", "WinExe", "ScreenX", "ScreenY"]
this.AddField(key, act.Target.%key%, "Target", 225+(i-1)*64)
}
}
tab.UseTab(pageCount+(usesTarget ? 2 : 1))
this.fieldPage := pageCount+(usesTarget ? 2 : 1)
for i, key in ["TimeoutMs", "RetryCount", "DelayBeforeMs", "DelayAfterMs", "OnFailure"]
this.AddField(key, act.%key%, "Action", 132+(i-1)*74)
tab.UseTab(tabs.Length)
this.fieldPage := tabs.Length
this.AddField("Label",act.Label,"Action",132)
d.AddText("x34 y200 w630 h90","Optional: give this action a memorable name, then choose it in a Go to action. Leave blank if unused. Names must be unique in the same block; jumps stay within that block to preserve loop and condition structure. Renaming updates Go to destinations in this block.")
if InStr(act.Type, "Audio_") == 1 && !advanced {
tab.UseTab(2)
d.AddButton("x220 y370 w260 h32", "Choose program / live meter…").OnEvent("Click", (*) => AudioMonitorUI(this))
}
tab.UseTab()
d.AddButton("x20 y540 w150 h32 Default", "&Save settings").OnEvent("Click", (*) => this.Save())
d.AddButton("x+10 w100 h32", "Cancel").OnEvent("Click", (*) => this.Close())
if !advanced
d.AddButton("x+10 w180 h32", "Save && advanced…").OnEvent("Click", (*) => this.OpenAdvanced())
d.AddButton("x+10 w170 h32", "Save && edit JSON…").OnEvent("Click", (*) => this.OpenJSON())
d.OnEvent("Escape", (*) => this.Close())
d.OnEvent("Close", (*) => this.Close())
tab.OnEvent("Change", (*) => this.UpdateConditionalFields())
this.UpdateConditionalFields()
if initialTab != ""
for index,title in tabs
if title == initialTab {
tab.Choose(index)
this.UpdateConditionalFields()
break
}
if show
d.Show("w720 h590")
}
TestOCR() {
candidate := this.Save(false, false)
if IsObject(candidate)
this.ui.ShowOCRPreview(candidate)
}
UpdateConditionalFields() {
countMode := "Fixed", sourceMode := "Lines", audioMode := "Above"
for field in this.fields {
if field.key == "Trigger"
audioMode := field.control.Text
if field.key == "CountMode"
countMode := field.control.Text
if field.key == "SourceMode"
sourceMode := field.control.Text
}
modes := Map()
for field in this.fields
if InStr("|DurationMode|OffsetMode|TypingDelayMode|OCRSource|OCRWaitFor|MatchSelection|WaitCondition|Condition|ExpectOutcome|WaitMode|MatchMode|WaitForLoad|", "|" field.key "|")
modes[field.key] := field.kind == "bool" ? field.control.Value : field.control.Text
if this.HasOwnProp("ocrChoose")
this.ocrChoose.Enabled := modes.Get("OCRSource","Region") == "Region" || modes.Get("OCRSource","Region") == "Window"
if this.HasOwnProp("ocrFileBrowse")
this.ocrFileBrowse.Enabled := modes.Get("OCRSource","Region") == "Image file" || modes.Get("OCRSource","Region") == "PDF page"
for field in this.fields {
if field.key == "TabTitle"
field.control.Enabled := modes.Get("MatchMode","Contains") != "Current"
if field.key == "TargetTitle"
field.control.Enabled := !!modes.Get("WaitForLoad",true)
if this.act.Type == "Wait_Element" && field.key == "ExpectedText"
field.control.Enabled := InStr("|TextContains|ValueEquals|", "|" modes.Get("WaitCondition","Appear") "|") > 0
if this.act.Type == "Wait_PageLoad" && field.key == "ExpectedValue"
field.control.Enabled := modes.Get("Condition","PageReady") != "PageReady"
if field.key == "ExpectValue" || field.key == "ExpectTimeoutMs"
field.control.Enabled := modes.Get("ExpectOutcome","None") != "None"
if field.key == "OCRFile"
field.control.Enabled := modes.Get("OCRSource","Region") == "Image file" || modes.Get("OCRSource","Region") == "PDF page"
if field.key == "PDFPage"
field.control.Enabled := modes.Get("OCRSource","Region") == "PDF page"
if field.key == "Occurrence"
field.control.Enabled := modes.Get("MatchSelection","Unique") == "Occurrence"
if field.key == "SearchText" || field.key == "OCRMatchMode" || field.key == "CaseSensitive"
field.control.Enabled := modes.Get("OCRWaitFor","Present") != "Changes"
if field.key == "DurationValue"
field.control.Enabled := modes.Get("DurationMode", "Fixed") == "Fixed"
if field.key == "MinimumDuration" || field.key == "MaximumDuration"
field.control.Enabled := modes.Get("DurationMode", "Fixed") == "Random"
if field.key == "OffsetX" || field.key == "OffsetY"
field.control.Enabled := modes.Get("OffsetMode", "None") == "Fixed"
if InStr("|OffsetMinX|OffsetMaxX|OffsetMinY|OffsetMaxY|", "|" field.key "|")
field.control.Enabled := modes.Get("OffsetMode", "None") == "Random"
if field.key == "CharacterDelayMs"
field.control.Enabled := modes.Get("TypingDelayMode", "None") == "Fixed"
if field.key == "MinimumDelayMs" || field.key == "MaximumDelayMs"
field.control.Enabled := modes.Get("TypingDelayMode", "None") == "Random"
if this.act.Type == "Logic_Repeat" && field.key == "Count"
field.control.Enabled := countMode == "Fixed"
if this.act.Type == "Logic_Repeat" && (field.key == "Minimum" || field.key == "Maximum")
field.control.Enabled := countMode == "Random"
if InStr(this.act.Type, "Audio_") == 1 {
if field.key == "Trigger" || field.key == "ThresholdPercent" || field.key == "HoldMs" || field.key == "SampleMs" || field.key == "HysteresisPercent"
field.control.Enabled := this.act.Type == "Audio_Wait" && (field.key != "HysteresisPercent" || audioMode == "Rising" || audioMode == "Falling")
}
if field.key == "Items"
field.label.Text := sourceMode == "Variable" ? "List variable name:" : (sourceMode == "JSON" ? "JSON array:" : "One item per line:")
field.active := !!field.control.Enabled
}
if this.HasOwnProp("ocrChoose")
this.ocrChoose.Visible := this.tabControl.Value == 2 && this.ocrChoose.Enabled
positions := Map()
for field in this.fields {
visible := field.active && field.page == this.tabControl.Value
field.control.Visible := visible
field.label.Visible := visible
for extra in field.extras
extra.Visible := visible
if !field.active
continue
if !positions.Has(field.page)
positions[field.page] := field.group == "Target" ? 225 : 132
y := positions[field.page]
field.control.GetPos(&cx,&cy,&cw,&ch)
field.control.Move(,y-3)
field.label.Move(,y)
for extra in field.extras
extra.Move(,y-3)
positions[field.page] := y+Max(46,ch+12)
}
}
static FieldHelp(key) {
if key == "ScrollDurationMs"
return "Overall scroll duration in milliseconds. Consolidated recordings retain their burst duration and spread the scroll evenly. Zero scrolls immediately. Playback speed scales this duration."
if key == "Notches"
return "Total wheel amount. One notch is 120 Windows wheel units. Fractional values preserve high-resolution wheel input."
return Map(
"TargetTitle","Optional title expected after navigation finishes, not the destination tab. Leave blank for ordinary page loading. Select lists currently open tab titles as examples; the destination may have a different title.",
"TabTitle","Select lists open tabs. Exact requires the full title; Contains accepts part of it. Current uses the active tab. URLContains matches addresses exposed by the browser (usually the active tab); use titles for inactive tabs. Multiple matches are rejected rather than guessed.",
"BrowserType","Choose the browser on the Browser tab. Empty inherits the macro default. Choose an open browser binds a specific running window.",
"BrowserFallbackPolicy","Controls whether another session may be used when the requested one is unavailable. Strict prevents using another browser/profile; empty inherits the macro policy.",
"DurationMode","Fixed waits the same duration each time. Random chooses a new duration between your minimum and maximum on each run.",
"DurationUnit","Applies to every duration on this page. Decimals are supported: 1.5 minutes is 90 seconds.",
"OffsetMode","None uses the resolved target point. Fixed adds horizontal/vertical pixels. Random chooses offsets within your bounds for each click. Offsets use physical clicks.",
"TypingDelayMode","None uses the normal text delivery. Fixed or Random inserts a delay between characters. Playback speed also scales this delay.",
"CountMode","Fixed repeats the specified number of times. Random chooses one repeat count within the inclusive minimum and maximum.",
"SourceMode","Lines: type one item per line. Variable: enter the name of a list variable, such as OCRLines. JSON: enter an array, such as [1,2,3].",
"ItemVar","Inside the loop, use ${Item} (or your chosen name) to access the current item. Use different names for nested loops.",
"IndexVar","The current item's position, starting at 1. Use a different variable name from the item variable.",
"MatchSelection","Unique stops if more than one match exists. First uses the first result. Occurrence lets you choose a specific numbered result.",
"OCRWaitFor","Present waits for matching text. Absent waits for no match. Changes compares recognized text with the first scan; no search phrase is required.",
"OCRScale","Enlarge small text before recognition, or shrink oversized captures. 1 uses original size. The best value depends on the source; use Test OCR.",
"OCRLanguage","Automatic uses Windows language selection. This list contains installed OCR languages; additional languages require Windows settings.",
"TimeoutMs","Maximum time to wait for this action's target or condition, in milliseconds. 1000 ms = 1 second. Duration waits use their own duration.",
"RetryCount","Additional attempts after a failed action. Retrying actions with side effects may repeat those effects.",
"OnFailure","Stop ends playback. Skip/Continue proceed after failure. UseFallback tries targeting alternatives. AskRepair requests help repairing the target.",
"WaitMode","Auto uses the action's normal readiness checks. None skips optional readiness checks. Advanced modes control target/page/custom waits.",
"MaxIterations","Upper limit for a conditional loop. This protects against a condition that never changes; Break can exit earlier.",
"LoopMode","While repeats while the condition is true. Until repeats while it is false. Both check before each iteration.",
"OutputFormat","Text returns one string. Lines returns a list for For Each. Words returns records containing text and coordinates.").Get(key, "")
}
AddField(key, value, group, y) {
d := this.dialog
label := RegExReplace(key, "([a-z])([A-Z])", "$1 $2")
if key == "ThresholdPercent"
label := "Threshold (%)"
if key == "HysteresisPercent"
label := "Crossing reset gap (%)"
if key == "HoldMs"
label := "Must last (ms)"
if key == "SampleMs"
label := "Sample every (ms)"
if key == "ItemVar"
label := "Item variable"
if key == "IndexVar"
label := "Index variable"
if key == "DurationValue"
label := "Duration"
friendly := Map("DurationMode", "Wait style", "DurationUnit", "Time unit", "MinimumDuration", "Minimum duration", "MaximumDuration", "Maximum duration", "OffsetMode", "Click position", "OffsetX", "Horizontal offset (px)", "OffsetY", "Vertical offset (px)", "OffsetMinX", "Horizontal minimum (px)", "OffsetMaxX", "Horizontal maximum (px)", "OffsetMinY", "Vertical minimum (px)", "OffsetMaxY", "Vertical maximum (px)", "TypingDelayMode", "Character delay", "CharacterDelayMs", "Delay per character (ms)", "MinimumDelayMs", "Minimum delay (ms)", "MaximumDelayMs", "Maximum delay (ms)", "DestinationLabel", "Jump to", "MaxJumps", "Maximum jumps per run", "PastTime", "If time already passed", "ClockTime", "Local time (24-hour)", "WindowCondition", "Wait until window is")
for name, caption in Map("OCRSource","Read from","OCRFile","Image / PDF file","PDFPage","PDF page number","OCRLanguage","Recognition language","OCRScale","Image scale (0.25–4×)","OCRGrayscale","Grayscale","OCRInvert","Invert colors","OCRMatchMode","Match text by","OCRWaitFor","Wait until text is","StableForMs","Condition holds (ms)","MatchSelection","When text repeats","Occurrence","Occurrence number","FoundVar","Found variable","MatchCountVar","Match count variable","OutputFormat","Return as","OutputVar","Save result to","SearchText","Text to find")
friendly[name] := caption
for name, caption in Map("TargetTitle","Expected page title","TabTitle","Tab title or address","OpenNewTab","Open a new tab","BrowserType","Browser","BrowserProfile","Profile","BrowserSession","Session name","BrowserFallbackPolicy","If unavailable")
friendly[name] := caption
for name, caption in Map("TargetCmd", "Program / file / command", "WorkingDir", "Working folder", "WindowMode", "Window mode")
friendly[name] := caption
if friendly.Has(key)
label := friendly[key]
labelControl := d.AddText("x34 y" y " w180 h25", label)
choices := ActionSettingsUI.Choices(key, this.act.Type)
if key == "DestinationLabel" {
found := WorkflowTree.FindById(this.ui.app.project.GetActiveMacro().Actions, this.act.Id)
if IsObject(found)
for sibling in found["ParentArray"]
if sibling.Enabled && ActionOptions.LabelName(sibling) != ""
choices.Push(ActionOptions.LabelName(sibling))
}
isBool := RegExMatch(key, "i)^(Enabled|ReuseExisting|NewWindow|WaitForUIA|ClearFirst|RequireVisible|RequireEnabled|Breakpoint|SkipEmpty|Append|Overwrite|WaitForLoad|OpenNewTab|SendEnterAfter|UseControlSend|SwitchToNewTab|ClickWhenFound|Check|Recursive|CaseSensitive|OCRGrayscale|OCRInvert|CopyToClipboard)$")
if choices.Length {
found := false
for option in choices {
if option == String(value)
found := true
}
if !found
choices.Push(String(value))
c := d.AddDropDownList("x220 y" (y-3) " w450", choices)
this.ui._SetDdlItems(c, choices, String(value))
kind := "choice"
} else if isBool {
c := d.AddCheckBox("x220 y" y " w450", "Enabled")
c.Value := !!value, kind := "bool"
} else {
multiline := key == "Items" || key == "Text" || key == "Comment"
c := d.AddEdit("x220 y" (y-3) " w450 h" (multiline ? 70 : 27) (multiline ? " Multi WantTab" : ""), IsObject(value) ? JsonCodec.Dump(value) : String(value))
kind := IsObject(value) ? "json" : "text"
}
extras := []
if key == "TargetCmd" {
c.Move(,,240)
for item in [["File…", "TargetCmd"], ["Folder…", "LaunchFolder"]] {
browse := d.AddButton("x" (item[2] == "TargetCmd" ? 470 : 570) " y" (y-3) " w95 h27", item[1])
browse.OnEvent("Click", ObjBindMethod(this, "BrowsePath", c, item[2]))
extras.Push(browse)
}
}
if key == "FilePath" || key == "WorkingDir" || key == "OCRFile" {
c.Move(, , 340)
browse := d.AddButton("x570 y" (y-3) " w100 h27", "Browse…")
browse.OnEvent("Click", ObjBindMethod(this, "BrowsePath", c, key))
extras.Push(browse)
if key == "OCRFile"
this.ocrFileBrowse := browse
}
if key == "TargetTitle" || key == "TabTitle" {
c.Move(,,310)
choose := d.AddButton("x538 y" (y-3) " w100 h27","Select…")
choose.OnEvent("Click",ObjBindMethod(this,"ChooseBrowserValue",key))
extras.Push(choose)
}
hint := ActionSettingsUI.FieldHelp(key)
if hint != "" {
c.GetPos(&cx,&cy,&cw,&ch)
c.Move(,,Min(cw,420))
help := d.AddButton("x648 y" (y-3) " w22 h22", "?")
help.OnEvent("Click", ObjBindMethod(this,"ShowFieldHelp",hint,help))
this.ui.helpTips[help.Hwnd] := hint
this.helpHandles.Push(help.Hwnd)
extras.Push(help)
}
this.fields.Push({key:key, group:group, control:c, kind:kind, original:value, label:labelControl, extras:extras, page:this.fieldPage, y:y, active:true})
if InStr("|CountMode|SourceMode|Trigger|DurationMode|OffsetMode|TypingDelayMode|OCRSource|OCRWaitFor|MatchSelection|WaitCondition|Condition|ExpectOutcome|WaitMode|MatchMode|WaitForLoad|", "|" key "|")
c.OnEvent(kind == "bool" ? "Click" : "Change", (*) => this.UpdateConditionalFields())
}
Field(key) {
for field in this.fields
if field.key == key
return field.control
return 0
}
ChooseBrowserValue(key,*) {
d := Gui("+Owner" this.dialog.Hwnd,key == "BrowserSession" ? "Choose an open browser" : "Choose an open tab title")
d.SetFont("s10",DesignTokens.FontUI)
d.AddText("w700 h48",key == "TargetTitle" ? "This copies a title to expect AFTER navigation; it does not select a destination tab. Leave this field blank if the destination title is unknown." : "Choose a running window or tab. This does not navigate, switch tabs or close anything. The choice applies when you save the action.")
list := d.AddListView("w700 r10 -Multi",["Browser","Window / tab title","Profile"])
list.ModifyCol(1,95),list.ModifyCol(2,460),list.ModifyCol(3,120)
rows := []
for info in this.ui.app.browserMgr.DiscoverRunningBrowserWindows() {
if key == "BrowserSession" {
rows.Push([info,info["Title"]])
list.Add("",info["BrowserType"],info["Title"],info["ProfileAlias"])
} else {
try {
browser := UIA_Browser("ahk_id " info["Hwnd"])
for element in browser.GetAllTabs() {
title := element.Name
rows.Push([info,title])
list.Add("",info["BrowserType"],title,info["ProfileAlias"])
}
}
}
}
if rows.Length
list.Modify(1,"Select Focus")
else
d.AddText("w700","No accessible browser tabs found. Open a supported browser or enter a title manually.")
choose := (*) => Use()
d.AddButton("w150 h30 Default","Use selection").OnEvent("Click",choose)
list.OnEvent("DoubleClick",choose)
d.AddButton("x+10 w100 h30","Cancel").OnEvent("Click",(*) => d.Destroy())
d.OnEvent("Escape",(*) => d.Destroy())
d.Show()
Use() {
row := list.GetNext()
if !row || row > rows.Length
return
info := rows[row][1]
if key != "BrowserSession"
this.Field(key).Value := rows[row][2]
if key != "TargetTitle" {
this.pendingBrowser := info
this.Field("BrowserSession").Value := "Window_" info["Hwnd"]
this.ui._SetDdlItems(this.Field("BrowserType"),ActionSettingsUI.Choices("BrowserType",this.act.Type),info["BrowserType"])
this.Field("BrowserProfile").Value := info["ProfileAlias"]
this.ui._SetDdlItems(this.Field("BrowserFallbackPolicy"),ActionSettingsUI.Choices("BrowserFallbackPolicy",this.act.Type),"Strict")
}
d.Destroy()
}
}
ShowFieldHelp(text, control, *) {
this.dialog.Opt("+OwnDialogs")
MsgBox(text,"Option help","Iconi")
if DllCall("IsWindow","Ptr",this.dialog.Hwnd) {
WinActivate(this.dialog.Hwnd)
control.Focus()
}
}
BrowsePath(control, key, *) {
this.dialog.Opt("+OwnDialogs")
path := (key == "WorkingDir" || key == "LaunchFolder") ? DirSelect(, 0, "Choose folder")
: FileSelect(this.act.Type == "File_Write" ? "S16" : "3", , "Choose file", "All files (*.*)")
if path != ""
control.Value := (key == "TargetCmd" || key == "LaunchFolder") ? Chr(34) path Chr(34) : path
}
Save(close := true, commit := true) {
try {
draft := ActionModel.FromMap(this.act.ToMap())
for field in this.fields {
if !field.active
continue
value := field.kind == "choice" ? field.control.Text : field.control.Value
if field.kind == "json"
value := JsonCodec.Load(value)
else if field.kind == "bool"
value := !!value
else if field.group == "Action" && (field.original is Integer || field.original is Float) {
if !IsInteger(value) || Integer(value) < 0
throw ValueError(field.key " must be a nonnegative whole number.")
value := Integer(value)
} else if field.group == "Target" && (field.key == "ScreenX" || field.key == "ScreenY")
value := Integer(value)
if field.group == "Parameters" {
if field.original is Integer && IsInteger(value)
value := Integer(value)
else if field.original is Float && IsNumber(value)
value := Float(value)
draft.Parameters[field.key] := value
}
else if field.group == "Target"
draft.Target.%field.key% := value
else
draft.%field.key% := value
}
if draft.Type == "Logic_ForEach" {
itemName := Trim(draft.Parameters["ItemVar"]), indexName := Trim(draft.Parameters["IndexVar"])
if !RegExMatch(itemName, "^[A-Za-z_][A-Za-z0-9_]*$") || !RegExMatch(indexName, "^[A-Za-z_][A-Za-z0-9_]*$") || StrLower(itemName) == StrLower(indexName)
throw ValueError("Use different item and index names, starting with a letter and containing no spaces.")
}
if draft.Type == "Logic_Repeat" && draft.Parameters.Get("CountMode", "Fixed") == "Random" {
low := draft.Parameters["Minimum"], high := draft.Parameters["Maximum"]
if IsNumber(low) && IsNumber(high) && (low < 0 || high < low)
throw ValueError("Random repeats require 0 <= minimum <= maximum.")
}
if InStr(draft.Type, "Audio_") == 1 {
check := StudioUtils.CloneMap(draft.Parameters)
hasVariables := false
for key, value in check
if value is String && InStr(value, "${")
hasVariables := true
if !hasVariables
ProgramAudio.Validate(check)
}
hasVariables := false
for key, value in draft.Parameters
if value is String && InStr(value, "${")
hasVariables := true
if !hasVariables {
if draft.Type == "Wait_Duration" {
duration := ActionOptions.Duration(draft.Parameters, false)
if draft.Parameters.Get("DurationMode", "Fixed") == "Fixed"
draft.Parameters["DurationMs"] := duration
}
if draft.Type == "Wait_Clock"
ActionOptions.ClockDeadline(draft.Parameters)
ActionOptions.Offset(draft.Parameters, 0, 0)
ActionOptions.CharacterDelay(draft.Parameters, false)
if InStr(draft.Type,"OCR_") == 1 {
StudioOCREngine.Options(draft.Parameters)
if draft.Parameters.Get("OCRSource","Region") == "PDF page" && (!IsInteger(draft.Parameters.Get("PDFPage",1)) || draft.Parameters.Get("PDFPage",1) < 1)
throw ValueError("PDF page must be a positive whole number.")
if draft.Type == "OCR_ClickText" && (draft.Parameters.Get("OCRSource","Region") == "Image file" || draft.Parameters.Get("OCRSource","Region") == "PDF page")
throw ValueError("OCR clicks need Region, Window, or Desktop. Use Read / Find text for files.")
}
}
if draft.Type == "Logic_Label" && Trim(draft.Parameters.Get("LabelName", "")) == ""
throw ValueError("Give this label a name.")
if draft.Type == "Logic_Goto" {
if Trim(draft.Parameters.Get("DestinationLabel", "")) == ""
throw ValueError("Give an action in this block a label first, then choose it as the destination.")
if !IsInteger(draft.Parameters.Get("MaxJumps", 1000)) || draft.Parameters.Get("MaxJumps", 1000) < 1
throw ValueError("Jump limit must be a positive whole number.")
}
found := WorkflowTree.FindById(this.ui.app.project.GetActiveMacro().Actions, this.act.Id)
siblings := IsObject(found) ? found["ParentArray"] : [this.act]
newLabel := ActionOptions.CheckLabelChange(siblings,this.act,ActionOptions.LabelName(draft))
if draft.Type == "Logic_Goto" {
oldLabel := ActionOptions.LabelName(this.act)
if oldLabel != "" && StrLower(Trim(draft.Parameters["DestinationLabel"])) == StrLower(oldLabel)
draft.Parameters["DestinationLabel"] := newLabel
destination := Trim(draft.Parameters["DestinationLabel"]), exists := false
for sibling in siblings
if sibling.Enabled && StrLower(sibling.Id == this.act.Id ? newLabel : ActionOptions.LabelName(sibling)) == StrLower(destination)
exists := true
if !exists
throw ValueError("Choose an enabled labeled action from this same block. Give an action a label first if the list is empty.")
}
if !commit
return draft
if this.HasOwnProp("pendingBrowser") {
info := this.pendingBrowser
this.ui.app.browserMgr.AttachToWindow(draft.BrowserSession,info["Hwnd"],info["BrowserType"],info["ProfileAlias"],info["ProfileAlias"],false,"")
}
this.ui.app.undoMgr.RecordSnapshot(this.ui.app.project, "Edit action settings")
ActionOptions.RenameLabel(siblings,this.act,newLabel)
draft.Label := Trim(draft.Label)
this.act.Parameters := draft.Parameters, this.act.Target := draft.Target
for field in this.fields {
if field.group == "Action"
this.act.%field.key% := draft.%field.key%
}
this.act.FriendlyDescription := this.act.ComputeFriendlyDescription()
this.ui.app.project.IsDirty := true
this.ui.RefreshAll()
if close
this.Close()
return true
} catch as err {
MsgBox(err.Message, "Check settings", "Icon!")
return false
}
}
Close() {
for hwnd in this.helpHandles
if this.ui.helpTips.Has(hwnd)
this.ui.helpTips.Delete(hwnd)
ToolTip()
this.dialog.Destroy()
}
OpenJSON() {
if this.Save()
this.ui.ShowRawActionJSON()
}
OpenAdvanced() {
if this.Save()
this.ui.settingsEditor := ActionSettingsUI(this.ui, this.act, true)
}
ChooseTarget() {
if this.Save()
this.ui.CmdPickTargetForCurrent(this.act.Type == "Wait_ImageColor" ? (this.act.Target.TargetKind == "PixelColor" ? "PixelColorSelection" : "ImageCapture") : "UIAAction")
}
}
class ActionLabelUI {
__New(ui,act,show := true) {
this.ui := ui, this.act := act
this.dialog := d := Gui("+Owner" ui.mainGui.Hwnd,"Action label")
d.SetFont("s10",DesignTokens.FontUI)
d.AddText("x18 y18 w440 h58","Name this action so a Go to step can jump here. Optional; leave blank if unused. Labels are unique within the same block.")
this.input := d.AddEdit("x18 y88 w440 h28",ActionOptions.LabelName(act))
d.AddText("x18 y132 w440 h50","Renaming updates existing Go to destinations in this block. Clear a label only after redirecting steps that use it.")
this.error := d.AddText("x18 y190 w440 h50 cB00020","")
d.AddButton("x18 y252 w120 h30 Default","Save label").OnEvent("Click",(*) => this.Save())
d.AddButton("x150 y252 w100 h30","Cancel").OnEvent("Click",(*) => d.Destroy())
d.OnEvent("Close",(*) => d.Destroy()),d.OnEvent("Escape",(*) => d.Destroy())
if show {
d.Show("w478 h300")
this.input.Focus()
}
}
Save() {
try {
found := WorkflowTree.FindById(this.ui.app.project.GetActiveMacro().Actions,this.act.Id)
if !IsObject(found)
throw ValueError("This action is no longer in the macro.")
siblings := found["ParentArray"]
name := ActionOptions.CheckLabelChange(siblings,this.act,this.input.Value)
if this.act.Type == "Logic_Label" && name == ""
throw ValueError("Legacy label markers require a name.")
this.ui.app.undoMgr.RecordSnapshot(this.ui.app.project,"Edit action label")
ActionOptions.RenameLabel(siblings,this.act,name)
this.ui.app.project.IsDirty := true
this.ui.RefreshAll()
this.dialog.Destroy()
return true
} catch as err {
this.error.Text := err.Message
return false
}
}
}
class DurationInput {
static Units := ["Milliseconds", "Seconds", "Minutes", "Hours"]
static Factor(unit) => Map("Milliseconds",1,"Seconds",1000,"Minutes",60000,"Hours",3600000)[unit]
static ToMs(value,unit) {
if !IsNumber(Trim(value)) || value < 0
throw ValueError("Enter a nonnegative duration. Decimals are welcome; use 0 for no wait.")
ms := Float(value)*this.Factor(unit)
if ms > 2147483647
throw ValueError("Choose a duration of at most 2,147,483,647 milliseconds (about 24 days).")
return Round(ms)
}
static BestUnit(ms) => ms >= 3600000 ? "Hours" : ms >= 60000 ? "Minutes" : ms >= 1000 ? "Seconds" : "Milliseconds"
__New(dialog,ms,x,y) {
this.currentUnit := DurationInput.BestUnit(ms)
this.value := dialog.AddEdit("x" x " y" y " w150 h28",Format("{:.12g}",ms/DurationInput.Factor(this.currentUnit)))
this.unit := dialog.AddDropDownList("x" (x+162) " y" y " w170",DurationInput.Units)
for i,unit in DurationInput.Units
if unit == this.currentUnit
this.unit.Choose(i)
this.unit.OnEvent("Change",(*) => this.ChangeUnit())
}
ChangeUnit() {
; Changing units changes the presentation, not the selected duration.
if IsNumber(this.value.Value) && this.value.Value >= 0
this.value.Value := Format("{:.12g}",Float(this.value.Value)*DurationInput.Factor(this.currentUnit)/DurationInput.Factor(this.unit.Text))
this.currentUnit := this.unit.Text
}
Read() => DurationInput.ToMs(this.value.Value,this.unit.Text)
Show(visible) {
this.value.Visible := visible, this.unit.Visible := visible
}
}
class StepDelayUI {
static Display(ms) {
unit := DurationInput.BestUnit(ms)
return Format("{:.12g}",ms/DurationInput.Factor(unit)) " " Map("Milliseconds","ms","Seconds","s","Minutes","min","Hours","h")[unit]
}
__New(ui,actions,field,show := true) {
this.ui := ui, this.actions := actions, this.field := field
label := field == "DelayBeforeMs" ? "Wait before" : "Wait after"
this.dialog := d := Gui("+Owner" ui.mainGui.Hwnd,label)
d.SetFont("s10",DesignTokens.FontUI)
d.AddText("x18 y18 w410 h42",actions.Length == 1 ? label " this step. Enter 0 to continue without a delay." : label " each of the " actions.Length " selected steps. Saving replaces their existing values.")
this.duration := DurationInput(d,actions[1].%field%,18,72)
d.AddText("x18 y118 w410 h42","Decimals are supported. Changing units keeps the same duration. Playback speed scales this wait.")
this.error := d.AddText("x18 y166 w410 h45 cB00020","")
d.AddButton("x18 y218 w110 h30 Default","Save wait").OnEvent("Click",(*) => this.Save())
d.AddButton("x140 y218 w100 h30","Cancel").OnEvent("Click",(*) => d.Destroy())
d.OnEvent("Close",(*) => d.Destroy()), d.OnEvent("Escape",(*) => d.Destroy())
if show {
d.Show("w446 h266")
this.duration.value.Focus()
SendMessage(0xB1,0,-1,this.duration.value.Hwnd)
}
}
Save() {
try ms := this.duration.Read()
catch as err {
this.error.Text := err.Message
this.duration.value.Focus()
return false
}
this.ui.app.undoMgr.RecordSnapshot(this.ui.app.project,"Adjust step wait")
for action in this.actions
action.%this.field% := ms
this.ui.app.project.IsDirty := true
this.ui.RefreshAll()
this.dialog.Destroy()
return true
}
}
class StudioOptionsUI {
static Hotkeys := [["Hotkey_Record", "Record / stop", "F3"], ["Hotkey_Play", "Play", "F1"], ["Hotkey_Pause", "Pause / resume", "F7"], ["Hotkey_Stop", "Emergency stop", "F8"], ["Hotkey_FreezeRefine", "Freeze / refine", "^+f"], ["Hotkey_SelectTarget", "Primary selector", "F6"]]
__New(ui) {
this.ui := ui, this.fields := Map(), this.tips := []
s := ui.app.persistence.settings
this.dialog := d := Gui("+Owner" ui.mainGui.Hwnd, "Settings")
d.SetFont("s10", DesignTokens.FontUI)
tabs := d.AddTab3("x12 y12 w600 h420", ["Hotkeys", "Recording & picking", "Appearance & export", "Recording timing", "Scrolling"])
tabs.UseTab(1)
d.AddText("x28 y50 w560 h42", "Click Bind, then press your shortcut. Default restores just that binding. Changes apply when you save settings.")
for n, def in StudioOptionsUI.Hotkeys {
y := 102+(n-1)*42
d.AddText("x28 y" y " w160 h26", def[2])
field := d.AddEdit("x194 y" y " w180 h27", s.Get(def[1], def[3]))
this.fields[def[1]] := field
d.AddButton("x384 y" y " w90 h28", "Bind…").OnEvent("Click", ObjBindMethod(this, "BindKey", field))
d.AddButton("x484 y" y " w100 h28", "Default").OnEvent("Click", ObjBindMethod(this, "ResetField", field, def[3]))
}
d.AddText("x28 y356 w550 h70", "AHK syntax: ^ = Ctrl, ! = Alt, + = Shift, # = Windows. Example: ^!k = Ctrl+Alt+K.`nThe primary selector confirms a target; Escape cancels picking. Shift + Record starts advanced recording when Record does not already use Shift.")
tabs.UseTab(2)
d.AddText("x28 y56 w180 h24", "Default click mode")
f := d.AddDropDownList("x220 y52 w360", ["Coordinate Window", "Smart Recommended"])
ui._SetDdlItems(f, ["Coordinate Window", "Smart Recommended"], s["DefaultClickMode"])
this.fields["DefaultClickMode"] := f
this.Tip(f, "Coordinate Window starts click picking and recording with window-relative coordinates. Smart Recommended starts with the recommended semantic target. You can still cycle every target layer and review upgrades in either mode.")
d.AddText("x28 y100 w180 h24", "Mouse confirmation")
f := d.AddDropDownList("x220 y96 w360", ["Alt+Click", "Ctrl+Click", "Shift+Click", "Middle click", "Primary key only"])
ui._SetDdlItems(f, ["Alt+Click", "Ctrl+Click", "Shift+Click", "Middle click", "Primary key only"], s["PickerConfirmGesture"] == "F6 only" ? "Primary key only" : s["PickerConfirmGesture"])
this.fields["PickerConfirmGesture"] := f
this.Tip(f, "Optional mouse gesture to confirm a target. The configurable primary selector key also works. Ordinary clicks remain available to open menus.")
f := d.AddCheckbox("x28 y144 w550", "Mouse wheel cycles target layers"), f.Value := s["PickerWheelCycles"], this.fields["PickerWheelCycles"] := f
this.Tip(f, "Turn off to let the wheel scroll the application during picking. Up and Down still change target layers.")
f := d.AddCheckbox("x28 y184 w550", "Smooth pointer movement during playback"), f.Value := s["SmoothPointer"], this.fields["SmoothPointer"] := f
this.Tip(f, "Moves the pointer smoothly between click destinations instead of jumping instantly.")
d.AddText("x28 y230 w180", "Default timeout (ms)")
f := d.AddEdit("x220 y226 w120", s["DefaultTimeoutMs"]), this.fields["DefaultTimeoutMs"] := f
this.Tip(f, "How long an action normally waits for its target. Default: 8000 ms (8 seconds). Individual steps can override it.")
d.AddText("x28 y274 w180", "Suggestions")
f := d.AddDropDownList("x220 y270 w180", ["Normal", "Minimal", "Off"])
ui._SetDdlItems(f, ["Normal", "Minimal", "Off"], s["SuggestionDensity"]), this.fields["SuggestionDensity"] := f
this.Tip(f, "Controls how much recommendation guidance Studio displays. Normal is the default.")
d.AddText("x28 y318 w180 h24", "If several elements match") ; [NMS-PD-01] ambiguity policy and risky-step confirmation settings
f := d.AddDropDownList("x220 y314 w330", ["Warn: use the first match and log it", "Stop: refuse the step", "Use the first match silently"])
polNow := s.Get("AmbiguousTargetPolicy", "Warn")
f.Choose(polNow = "Stop" ? 2 : (polNow = "UseFirst" ? 3 : 1))
this.fields["AmbiguousTargetPolicy"] := f
this.Tip(f, "What playback does when a step's target matches more than one element. Warn (default) uses the first match and records a warning in the log. Stop refuses the step so a wrong element is never acted on. Use the first match silently is the old behavior. A single step can override this with its own allow-ambiguity setting.")
f := d.AddCheckbox("x28 y362 w550", "Ask before risky steps (write file, run program, close window or tab)")
f.Value := StudioUtils.ToBool(s.Get("ConfirmRiskyActions", false)) ? 1 : 0
this.fields["ConfirmRiskyActions"] := f
this.Tip(f, "When on, playback asks Run, Skip or Stop before steps that can change or close things that cannot be undone. Off by default.")
tabs.UseTab(3)
f := d.AddCheckbox("x28 y56 w550", "Show hover explanations"), f.Value := s.Get("ShowHelpTips", true), this.fields["ShowHelpTips"] := f
this.Tip(f, "Enable explanations on help icons in Settings and supported workspace controls. Click a help icon to read its explanation at any time.")
d.AddButton("x28 y104 w260 h32", "Screen-edge glow settings…").OnEvent("Click", (*) => this.OpenGlow())
d.AddText("x28 y148 w550 h46", "Tune glow width, softness, brightness, and pulse timing. Includes customizable colors, a live preview and a restore-defaults button.")
d.AddText("x28 y210 w550", "Ahk2Exe compiler path")
f := d.AddEdit("x28 y240 w430 r2 Multi -WantReturn", s["CompilerPath"]), this.fields["CompilerPath"] := f
this.Tip(f, "Path to Ahk2Exe.exe, used only when building an EXE. Exporting an AHK script does not need a compiler.")
d.AddButton("x470 y240 w110 h30", "Browse…").OnEvent("Click", (*) => this.BrowseCompiler())
tabs.UseTab(4)
d.AddText("x28 y56 w550 h62","Choose how future recordings capture the time between actions. Existing macros keep their saved waits; you can edit them in the Wait Before and Wait After columns.")
d.AddText("x28 y132 w180","Timing mode")
this.timingMode := d.AddDropDownList("x220 y128 w350",["Natural — use recorded timings", "Fixed — same wait before each action"])
this.timingMode.Choose(s.Get("RecordingTimingMode","Natural") == "Fixed" ? 2 : 1)
this.fixedLabel := d.AddText("x28 y184 w180","Wait before each action")
this.fixedDuration := DurationInput(d,s.Get("RecordingFixedDelayMs",100),220,180)
d.AddText("x28 y242 w550 h100","Natural is the default: a 4.20-second gap records a 4.20-second wait. Fixed replaces captured gaps, including the wait before the first action. It adds no wait after actions. Explicit Wait steps and target-readiness checks remain unchanged.")
this.timingMode.OnEvent("Change",(*) => this.UpdateTimingMode())
this.UpdateTimingMode()
tabs.UseTab(5)
d.AddText("x28 y56 w550 h62","Choose how future recordings store wheel input. Consolidated keeps a scroll burst in one editable step. Detailed keeps each wheel event as its own step.")
d.AddText("x28 y132 w180","Scroll recording")
this.scrollMode := d.AddDropDownList("x220 y128 w350",["Consolidated bursts (default)","Detailed — every wheel event"])
this.scrollMode.Choose(s.Get("RecordingScrollMode","Consolidated") == "Detailed" ? 2 : 1)
this.scrollGapLabel := d.AddText("x28 y184 w180","Maximum gap in a burst")
this.scrollGap := DurationInput(d,s.Get("RecordingScrollGapMs",250),220,180)
d.AddText("x28 y242 w550 h120","Default: 250 ms. Only nearby wheel events over the same window/control, in the same direction, are combined. Typing, clicks, direction changes, pointer movement, or longer gaps start a new step. The scroll amount and overall burst duration are retained; playback spreads the scroll evenly. Choose Detailed for individual event timing.")
this.scrollMode.OnEvent("Change",(*) => this.UpdateScrollMode())
this.UpdateScrollMode()
tabs.UseTab()
d.AddButton("x12 y448 w150 h32 Default", "Save settings").OnEvent("Click", (*) => this.Save())
d.AddButton("x174 y448 w100 h32", "Cancel").OnEvent("Click", (*) => this.Close())
d.OnEvent("Close", (*) => this.Close()), d.OnEvent("Escape", (*) => this.Close())
d.Show("w624 h496")
}
Tip(control, text) {
control.GetPos(&x, &y, &w, &h)
; Keep an eight-pixel gap after the input and reserve space inside the tab.
w := Min(w, 550-x)
control.Move(,, w)
hx := x == 28 && control.Type == "Edit" ? 196 : x+w+8
hy := x == 28 && control.Type == "Edit" ? y-32 : y
icon := this.dialog.AddButton("x" hx " y" hy " w22 h22", "?")
icon.OnEvent("Click", (*) => MsgBox(text, "Setting help", "Iconi"))
this.ui.helpTips[icon.Hwnd] := text
this.tips.Push(icon.Hwnd)
}
UpdateTimingMode() {
fixed := this.timingMode.Value == 2
this.fixedLabel.Visible := fixed
this.fixedDuration.Show(fixed)
}
UpdateScrollMode() {
consolidated := this.scrollMode.Value == 1
this.scrollGapLabel.Visible := consolidated
this.scrollGap.Show(consolidated)
}
ResetField(field, value, *) => field.Value := value
OpenGlow() => this.glowEditor := GlowSettingsUI(this.ui, this.dialog.Hwnd)
BrowseCompiler() {
path := FileSelect(1, this.fields["CompilerPath"].Value, "Choose Ahk2Exe.exe", "Executables (*.exe)")
if path != ""
this.fields["CompilerPath"].Value := path
}
BindKey(field, *) {
if this.HasOwnProp("bindingDialog")
return
if !this.ui.app._CanReplaceProject() {
this.ui.app.ShowToast("Stop playback, recording and selection before binding a shortcut.")
return
}
this.ui.app.UnregisterGlobalStudioHotkeys()
this.dialog.Opt("+Disabled")
this.bindingDialog := d := Gui("+Owner" this.dialog.Hwnd, "Bind shortcut")
d.SetFont("s10", DesignTokens.FontUI)
d.AddText("w400", "Press the shortcut you want. Studio hotkeys are suspended while this dialog is open.")
key := d.AddHotkey("w400 y+14")
d.AddText("w400 y+10", "Ctrl, Alt, Shift, and function keys are supported. Cancel keeps the existing shortcut.")
d.AddButton("w120 y+16 Default", "Use shortcut").OnEvent("Click", (*) => Accept())
d.AddButton("x+10 w100", "Cancel").OnEvent("Click", (*) => Done())
d.OnEvent("Close", (*) => Done()), d.OnEvent("Escape", (*) => Done())
d.Show(), key.Focus()
Accept() {
if key.Value == ""
return
field.Value := key.Value
Done()
}
Done() {
d.Destroy()
this.DeleteProp("bindingDialog")
this.dialog.Opt("-Disabled")
this.dialog.Show()
this.ui.app.RegisterGlobalStudioHotkeys()
}
}
static NormalizeKey(hk) {
hk := Trim(hk)
if !RegExMatch(hk, "^([\^!+#]*)([A-Za-z0-9]+)$", &m) || !GetKeyVK(m[2])
throw ValueError("Use a key or modifier shortcut, such as F6 or Ctrl+Alt+K (syntax ^!k).")
modifiers := ""
for symbol in ["^", "!", "+", "#"]
if InStr(m[1], symbol)
modifiers .= symbol
return modifiers StrUpper(GetKeyName(m[2]))
}
Save() {
try {
values := Map(), seen := Map()
for def in StudioOptionsUI.Hotkeys {
key := StudioOptionsUI.NormalizeKey(this.fields[def[1]].Value)
if seen.Has(key)
throw ValueError(def[2] " shares a shortcut with " seen[key] ". Choose different shortcuts.")
seen[key] := def[2], values[def[1]] := key
}
reserved := "|ESCAPE|UP|DOWN|TAB|1|2|3|4|5|6|7|"
for name in ["Hotkey_SelectTarget", "Hotkey_FreezeRefine"]
if InStr(reserved, "|" values[name] "|")
throw ValueError("The picker already uses that key for navigation or cancellation. Choose another shortcut.")
if !InStr(values["Hotkey_Record"], "+") && seen.Has(StudioOptionsUI.NormalizeKey("+" values["Hotkey_Record"]))
throw ValueError("Shift + Record is reserved for advanced recording. Choose a different shortcut.")
stopBase := RegExReplace(values["Hotkey_Stop"], "^[\^!+#]+")
for name, key in values
if name != "Hotkey_Stop" && RegExReplace(key, "^[\^!+#]+") == stopBase
throw ValueError("Emergency Stop must use a different base key from other shortcuts, because it also catches extra modifiers.")
for mac in this.ui.app.project.Macros {
if mac.TriggerHotkey == ""
continue
try macroKey := StudioOptionsUI.NormalizeKey(RegExReplace(mac.TriggerHotkey, "^[~*$]+"))
catch
continue
if seen.Has(macroKey)
throw ValueError("A macro trigger already uses that shortcut: " mac.Name)
}
timeout := this.fields["DefaultTimeoutMs"].Value
if !IsInteger(timeout) || timeout < 0
throw ValueError("Timeout must be a nonnegative number of milliseconds.")
values["DefaultTimeoutMs"] := Integer(timeout)
values["RecordingTimingMode"] := this.timingMode.Value == 2 ? "Fixed" : "Natural"
if values["RecordingTimingMode"] == "Fixed"
values["RecordingFixedDelayMs"] := this.fixedDuration.Read()
values["RecordingScrollMode"] := this.scrollMode.Value == 2 ? "Detailed" : "Consolidated"
if values["RecordingScrollMode"] == "Consolidated" {
gap := this.scrollGap.Read()
if gap < 50 || gap > 2000
throw ValueError("Choose a scroll burst gap between 50 ms and 2 seconds.")
values["RecordingScrollGapMs"] := gap
}
for name in ["DefaultClickMode", "PickerConfirmGesture", "SuggestionDensity"]
values[name] := this.fields[name].Text
for name in ["PickerWheelCycles", "SmoothPointer", "ShowHelpTips"]
values[name] := !!this.fields[name].Value
polIdx := this.fields["AmbiguousTargetPolicy"].Value ; [NMS-PD-02]
values["AmbiguousTargetPolicy"] := (polIdx = 2) ? "Stop" : ((polIdx = 3) ? "UseFirst" : "Warn")
values["ConfirmRiskyActions"] := !!this.fields["ConfirmRiskyActions"].Value
values["CompilerPath"] := Trim(StrReplace(StrReplace(this.fields["CompilerPath"].Value, "`r", ""), "`n", ""))
this.ui.app.persistence.UpdateSettings(values)
this.ui.app.RegisterGlobalStudioHotkeys()
this.ui.ShowToast("Settings saved.")
this.Close()
return true
} catch as err
MsgBox(err.Message, "Check settings", "Icon!")
return false
}
Close() {
if this.HasOwnProp("glowEditor")
this.glowEditor.Close()
for hwnd in this.tips
if this.ui.helpTips.Has(hwnd)
this.ui.helpTips.Delete(hwnd)
ToolTip()
this.dialog.Destroy()
}
}
class GlowSettingsUI {
static Specs := [["GlowDepth", "Width (pixels)", 72, 8, 160, "How far the halo reaches inward. Default: 72 px."], ["GlowSoftness", "Softness (pixels)", 24, 4, 64, "Higher values spread the light more gently. Default: 24 px."], ["GlowEdgeAlpha", "Edge intensity (20–220)", 132, 20, 220, "Peak edge opacity out of 255. Default: 132. Lower is less distracting."], ["GlowPulseMs", "Pulse cycle (ms)", 3600, 1200, 12000, "One full breath. Default: 3600 ms (3.6 seconds). Higher is slower."], ["GlowPulseMin", "Minimum intensity (80–255)", 200, 80, 255, "Brightness at the softest point of the pulse. Default: 200. Set 255 for a steady glow."]]
__New(ui, owner := 0) {
this.ui := ui, this.fields := Map(), this.tips := [], this.closed := false
this.dialog := d := Gui("+Owner" (owner ? owner : ui.mainGui.Hwnd), "Screen-edge glow")
d.SetFont("s10", DesignTokens.FontUI)
this.rec := d.AddCheckbox("x18 y18 w230", "Recording glow")
this.rec.Value := ui.app.persistence.settings["RecordingGlow"]
this.play := d.AddCheckbox("x18 y50 w230", "Playback glow")
this.play.Value := ui.app.persistence.settings["PlaybackGlow"]
this.colors := Map(), this.colorButtons := Map(), this.colorSwatches := Map()
for n, pair in [["RecordingGlowColor", "D92D20"], ["PlaybackGlowColor", "189B50"]] {
key := pair[1], color := ui.app.persistence.settings.Get(key, pair[2])
this.colors[key] := RegExMatch(color, "i)^[0-9a-f]{6}$") ? StrUpper(color) : pair[2]
this.colorSwatches[key] := d.AddProgress("x264 y" (14+(n-1)*34) " w28 h28 -Theme +Border c" this.colors[key] " Background" this.colors[key], 100)
button := d.AddButton("x300 y" (14+(n-1)*34) " w150 h28", "Color · #" this.colors[key])
button.OnEvent("Click", ObjBindMethod(this, "ChooseColor", key))
this.colorButtons[key] := button
}
for n, spec in GlowSettingsUI.Specs {
y := 94+(n-1)*70
d.AddText("x18 y" y " w270 h24", spec[2])
f := d.AddEdit("x300 y" y " w150 h26", ui.app.persistence.settings.Get(spec[1], spec[3]))
d.AddUpDown("+0x80 Range" spec[4] "-" spec[5], f.Value)
this.fields[spec[1]] := f
d.AddText("x18 y" (y+29) " w520 h32", spec[6])
icon := d.AddButton("x458 y" y " w22 h22", "?")
icon.OnEvent("Click", ShowHelp.Bind(spec[6]))
ui.helpTips[icon.Hwnd] := spec[6], this.tips.Push(icon.Hwnd)
f.OnEvent("Change", (*) => this.QueuePreview())
}
this.previewCheck := d.AddCheckbox("x18 y452 w200", "Live preview")
this.previewMode := d.AddDropDownList("x240 y448 w210 Choose1", ["Recording glow", "Playback glow"])
this.previewCheck.OnEvent("Click", (*) => this.QueuePreview())
this.previewMode.OnEvent("Change", (*) => this.QueuePreview())
this.status := d.AddText("x18 y490 w520 h38", "Preview changes only the glow; it does not record or run a macro.")
d.AddButton("x18 y542 w140 h32 Default", "Save glow settings").OnEvent("Click", (*) => this.Save())
d.AddButton("x168 y542 w140 h32", "Restore defaults").OnEvent("Click", (*) => this.Defaults())
d.AddButton("x318 y542 w110 h32", "Cancel").OnEvent("Click", (*) => this.Close())
this.refreshTimer := ObjBindMethod(this, "Preview")
this.guardTimer := ObjBindMethod(this, "GuardPreview")
d.OnEvent("Close", (*) => this.Close()), d.OnEvent("Escape", (*) => this.Close())
d.Show("w558 h592")
ShowHelp(message, *) => MsgBox(message, "Glow setting help", "Iconi")
}
ChooseColor(key, *) {
; CHOOSECOLORW uses COLORREF (BGR); our saved colors use RGB hex.
rgb := Integer("0x" this.colors[key])
bgr := ((rgb & 255) << 16) | (rgb & 0xFF00) | ((rgb >> 16) & 255)
custom := Buffer(64, 0), cc := Buffer(A_PtrSize == 8 ? 72 : 36, 0)
NumPut("UInt", cc.Size, cc, 0)
NumPut("Ptr", this.dialog.Hwnd, cc, A_PtrSize == 8 ? 8 : 4)
NumPut("UInt", bgr, cc, A_PtrSize == 8 ? 24 : 12)
NumPut("Ptr", custom.Ptr, cc, A_PtrSize == 8 ? 32 : 16)
NumPut("UInt", 3, cc, A_PtrSize == 8 ? 40 : 20)
if !DllCall("comdlg32\ChooseColorW", "Ptr", cc, "Int")
return
bgr := NumGet(cc, A_PtrSize == 8 ? 24 : 12, "UInt")
rgb := ((bgr & 255) << 16) | (bgr & 0xFF00) | ((bgr >> 16) & 255)
this.SetColor(key, Format("{:06X}", rgb))
this.QueuePreview()
}
SetColor(key, color) {
this.colors[key] := color
this.colorButtons[key].Text := "Color · #" color
this.colorSwatches[key].Opt("c" color " Background" color)
this.colorSwatches[key].Redraw()
}
Values() {
values := Map()
for key, color in this.colors
values[key] := color
for spec in GlowSettingsUI.Specs {
v := this.fields[spec[1]].Value
if !IsInteger(v) || v < spec[4] || v > spec[5]
throw ValueError(spec[2] " must be between " spec[4] " and " spec[5] ".")
values[spec[1]] := Integer(v)
}
return values
}
Defaults() {
for spec in GlowSettingsUI.Specs
this.fields[spec[1]].Value := spec[3]
this.rec.Value := true, this.play.Value := true
for key, color in Map("RecordingGlowColor", "D92D20", "PlaybackGlowColor", "189B50") {
this.SetColor(key, color)
}
this.QueuePreview()
}
QueuePreview() {
if !this.closed
SetTimer(this.refreshTimer, -160)
}
StopPreview() {
SetTimer(this.guardTimer, 0)
if this.HasOwnProp("previewDisplay")
this.previewDisplay.Clear(false)
}
GuardPreview() {
if this.ui.app.recorder.isRecording || this.ui.app.playback.isRunning || this.ui.app.selectionEngine.isActive {
this.previewCheck.Value := false
this.StopPreview()
this.status.Text := "Preview stopped while Studio is active."
}
}
Preview() {
this.StopPreview()
if this.closed || !this.previewCheck.Value
return
this.GuardPreview()
if !this.previewCheck.Value
return
try {
values := this.Values()
values["RecordingGlow"] := true, values["PlaybackGlow"] := true
mock := {persistence:{settings:values}, recorder:{isRecording:this.previewMode.Value == 1}, playback:{isRunning:this.previewMode.Value == 2, isPaused:false}, gui:{mainGui:""}, overlayMgr:this.ui.app.overlayMgr}
this.previewDisplay := ActivityDisplay(mock)
this.previewDisplay.preview := true
this.previewDisplay.Update()
this.status.Text := "Live preview — settings remain unchanged until you save."
SetTimer(this.guardTimer, 100)
} catch as err
this.status.Text := err.Message
}
Save() {
try {
values := this.Values()
values["RecordingGlow"] := !!this.rec.Value, values["PlaybackGlow"] := !!this.play.Value
this.ui.app.persistence.UpdateSettings(values)
this.Close()
return true
} catch as err
this.status.Text := err.Message
return false
}
Close() {
if this.closed
return
this.closed := true
SetTimer(this.refreshTimer, 0)
this.StopPreview()
for hwnd in this.tips
if this.ui.helpTips.Has(hwnd)
this.ui.helpTips.Delete(hwnd)
ToolTip()
this.dialog.Destroy()
}
}
class GuidedConditionEditor {
static Specs() => [
["OCRTextPresent", "Text is visible (OCR)", "", "Text to find", "Read pixels in a selected region. Save & pick target selects the region; Advanced settings offers language and other sources."],
["OCRTextAbsent", "Text is absent (OCR)", "", "Text to find", "Only true after successful OCR finds no match. Capture/language errors remain errors."],
["UIAExists", "An element is present", "", "", "Choose the button, field, or other element to look for."],
["UIAEnabled", "An element is ready to use", "", "", "Checks whether the chosen element is enabled."],
["UIATextContains", "An element contains text", "", "Text to find", "For example: Complete. Choose the element whose text to check."],
["WindowExists", "A window is open", "Window title or ahk_exe name", "", "For example: Untitled - Notepad or ahk_exe notepad.exe."],
["WindowActive", "A window is in front", "Window title or ahk_exe name", "", "Only true when that window is active."],
["FileExists", "A file or folder exists", "File or folder path", "", "Enter a full path, or use Browse for a file."],
["ClipboardContains", "The clipboard contains text", "Text to find", "", "Checks copied text without changing your clipboard."],
["StringEquals", "Text equals exactly", "Text or variable name", "Expected text", "Compares the whole text value."],
["VarEquals", "A value equals something", "Value or variable name", "Expected value", "Example: Item equals Banana. Use a loop variable name or literal text."],
["VarNotEquals", "A value is different", "Value or variable name", "Value to exclude", "Example: Status is different from Done."],
["VarGreater", "A number is greater than", "Number or variable name", "Compare with number", "Example: Count is greater than 10."],
["VarLess", "A number is less than", "Number or variable name", "Compare with number", "Example: Count is less than 10."],
["StringContains", "Text contains a phrase", "Text or variable name", "Phrase to find", "Example: Item contains Apple. Variables can also use ${Item}."],
["StringStartsWith", "Text starts with", "Text or variable name", "Starting text", "Example: Filename starts with Report."],
["StringEndsWith", "Text ends with", "Text or variable name", "Ending text", "Example: Filename ends with .csv."],
["ProcessExists", "A program is running", "Process name", "", "For example: notepad.exe."],
["BrowserSessionAvailable", "A browser session is connected", "Session name", "", "Leave blank to use this action's browser session."],
["BrowserTabExists", "A browser tab exists", "Tab title to find", "", "Uses the browser session configured for this action."],
["URLContains", "The browser address contains", "Address text to find", "", "For example: /reports. Uses this action's browser session."],
["TitleContains", "The browser title contains", "Title text to find", "", "For example: Dashboard. Uses this action's browser session."],
["ImageFound", "A saved image is visible", "", "", "Requires an image target captured in the target inspector."],
["ImageNotFound", "A saved image is absent", "", "", "Requires an image target captured in the target inspector."],
["ColorFound", "A saved color is visible", "", "", "Requires a color target captured in the target inspector."],
["RegexMatch", "Text matches a pattern (advanced)", "Text or variable name", "Regular expression", "Advanced example: ^Report.*\.csv$."]
]
__New(ui, act) {
this.ui := ui, this.act := act, this.specs := GuidedConditionEditor.Specs(), this.rows := []
d := Gui("+Owner" ui.mainGui.Hwnd, act.Type == "Wait_Condition" ? "Wait until a condition is true" : (act.Type == "Logic_While" ? "Repeat " StrLower(act.Parameters.Get("LoopMode", "While")) " a condition is true" : "Only run these steps if…"))
this.dialog := d
d.SetFont("s10", DesignTokens.FontUI)
d.AddText("x16 y14 w600 h44", act.Type == "Wait_Condition" ? "Wait for this check to become true. Configure the timeout and polling interval in Action settings." : (act.Type == "Logic_While" ? "Check before each repeat. Mode: " act.Parameters.Get("LoopMode", "While") ". Until stops when true; While stops when false. Change mode and iteration limit in Advanced settings." : "When true, run IF steps. Otherwise, run ELSE steps if present, then continue."))
labels := [], second := ["No second check"]
for spec in this.specs
labels.Push(spec[2]), second.Push(spec[2])
p := act.Parameters
Loop 2 {
n := A_Index, y := 68+(n-1)*180
d.AddText("x16 y" y " w600 h22", n == 1 ? "What would you like to check?" : "Optional: add another check")
choice := d.AddDropDownList("x16 y" (y+26) " w600", n == 1 ? labels : second)
kind := p.Get(n == 1 ? "ConditionType" : "SecondConditionType", n == 1 ? "UIAExists" : "None")
selected := 1
for i, spec in this.specs
if spec[1] == kind
selected := i+(n == 2 ? 1 : 0)
choice.Choose(selected)
leftLabel := d.AddText("x16 y" (y+62) " w285 h22", "")
rightLabel := d.AddText("x326 y" (y+62) " w290 h22", "")
left := d.AddEdit("x16 y" (y+86) " w285 h26", p.Get(n == 1 ? "LeftOperand" : "SecondLeft", ""))
right := d.AddEdit("x326 y" (y+86) " w290 h26", p.Get(n == 1 ? "RightOperand" : "SecondRight", ""))
hint := d.AddText("x16 y" (y+120) " w600 h48", "")
if kind == "UIATextContains" && right.Value == ""
right.Value := left.Value
if InStr("|ClipboardContains|BrowserTabExists|URLContains|TitleContains|", "|" kind "|") && left.Value == ""
left.Value := right.Value
this.rows.Push({choice:choice, left:left, right:right, leftLabel:leftLabel, rightLabel:rightLabel, hint:hint})
choice.OnEvent("Change", ObjBindMethod(this, "Adapt"))
}
this.combine := d.AddDropDownList("x16 y432 w290", ["Both checks must be true (AND)", "Either check can be true (OR)"])
this.combine.Choose(p.Get("CombineOp", "AND") == "OR" ? 2 : 1)
this.browseButton := d.AddButton("x326 y430 w140 h28", "Browse file…")
this.browseButton.OnEvent("Click", ObjBindMethod(this, "Browse"))
this.targetButton := d.AddButton("x476 y430 w140 h28", "Save && pick target")
this.targetButton.OnEvent("Click", (*) => this.OpenTarget())
this.feedback := d.AddText("x16 y472 w600 h52", "Test checks the condition without running the steps inside the block.")
d.AddButton("x16 y536 w140 h32", "Test condition").OnEvent("Click", (*) => this.Test())
d.AddButton("x166 y536 w140 h32 Default", "Save condition").OnEvent("Click", (*) => this.Save())
d.AddButton("x316 y536 w160 h32", "Advanced settings…").OnEvent("Click", (*) => this.Advanced())
d.AddButton("x486 y536 w130 h32", "Cancel").OnEvent("Click", (*) => d.Destroy())
d.OnEvent("Escape", (*) => d.Destroy())
this.Adapt()
d.Show("w634 h586")
}
Kind(n) => n == 2 && this.rows[n].choice.Value == 1 ? "None" : this.specs[this.rows[n].choice.Value-(n == 2 ? 1 : 0)][1]
Adapt(*) {
for n, row in this.rows {
kind := this.Kind(n)
if kind == "None" {
row.left.Visible := false, row.right.Visible := false
row.leftLabel.Visible := false, row.rightLabel.Visible := false
row.hint.Text := "One check is enough for most workflows. Add another only when you need it."
continue
}
spec := this.specs[row.choice.Value-(n == 2 ? 1 : 0)]
row.left.Visible := spec[3] != "", row.leftLabel.Visible := spec[3] != ""
row.right.Visible := spec[4] != "", row.rightLabel.Visible := spec[4] != ""
row.leftLabel.Text := spec[3], row.rightLabel.Text := spec[4]
row.hint.Text := spec[5] (spec[3] == "" ? "`nTarget: " (this.ui.HasTarget(this.act) ? this.act.Target.GetHumanLabel() : "not chosen — use Target setup") : "")
}
this.combine.Enabled := this.Kind(2) != "None"
this.combine.Visible := this.combine.Enabled
this.browseButton.Visible := this.Kind(1) == "FileExists" || this.Kind(2) == "FileExists"
targetKinds := "|UIAExists|UIAEnabled|UIATextContains|ImageFound|ImageNotFound|ColorFound|OCRTextPresent|OCRTextAbsent|"
this.targetButton.Visible := InStr(targetKinds,"|" this.Kind(1) "|") || InStr(targetKinds,"|" this.Kind(2) "|")
}
Candidate() {
candidate := ActionModel.FromMap(this.act.ToMap()), p := candidate.Parameters
for n, row in this.rows {
p[n == 1 ? "ConditionType" : "SecondConditionType"] := this.Kind(n)
p[n == 1 ? "LeftOperand" : "SecondLeft"] := row.left.Visible ? row.left.Value : ""
p[n == 1 ? "RightOperand" : "SecondRight"] := row.right.Visible ? row.right.Value : ""
}
p["CombineOp"] := this.combine.Value == 2 ? "OR" : "AND"
return candidate
}
Validate(candidate) {
p := candidate.Parameters
for n, row in this.rows {
kind := this.Kind(n)
if kind == "None"
continue
left := p[n == 1 ? "LeftOperand" : "SecondLeft"], right := p[n == 1 ? "RightOperand" : "SecondRight"]
if kind == "VarGreater" || kind == "VarLess" {
if right != "" && !IsNumber(right) && !InStr(right, "${")
throw ValueError("Enter a number to compare with, such as 10, or a variable such as ${Limit}.")
}
if kind == "RegexMatch" && !InStr(right, "${") {
try RegExMatch("", right)
catch
throw ValueError("The regular expression is invalid. Use a simpler text check or correct the pattern.")
}
if InStr("|UIAExists|UIAEnabled|UIATextContains|ImageFound|ImageNotFound|ColorFound|", "|" kind "|") && !this.ui.HasTarget(this.act)
throw ValueError("Choose a target first with Save & pick target. Image and color checks use visual targets configured in the inspector.")
if InStr("|ClipboardContains|BrowserTabExists|URLContains|TitleContains|ProcessExists|FileExists|", "|" kind "|") && Trim(left) == ""
throw ValueError("Enter the " StrLower(row.leftLabel.Text) " before testing.")
}
}
Test() {
try {
candidate := this.Candidate()
this.Validate(candidate)
started := A_TickCount
result := this.ui.app.condEngine.EvaluateActionCondition(candidate)
effect := result ? "The IF steps would run." : "The IF steps would be skipped."
if this.act.Type == "Wait_Condition"
effect := result ? "The wait would finish." : "The wait would continue until the condition is true or the timeout is reached."
if this.act.Type == "Logic_While" {
repeat := this.act.Parameters.Get("LoopMode", "While") == "Until" ? !result : result
effect := repeat ? "The loop would run another iteration." : "The loop would finish."
}
this.feedback.Text := (result ? "True — " : "False — ") effect "`nChecked in " (A_TickCount-started) " ms. No steps ran."
} catch as err
this.feedback.Text := "Could not check: " err.Message
}
Save() {
candidate := this.Candidate()
this.ui.app.undoMgr.RecordSnapshot(this.ui.app.project, "Edit condition")
this.act.Parameters := candidate.Parameters
this.act.FriendlyDescription := this.act.ComputeFriendlyDescription()
this.ui.app.project.IsDirty := true
this.ui.RefreshAll()
this.dialog.Destroy()
return true
}
Advanced() {
this.Save()
this.ui.ToggleAdvancedInspector()
}
OpenTarget() {
kind := this.Kind(1)
this.Save()
this.ui.CmdPickTargetForCurrent(InStr(kind,"OCR") == 1 ? "RegionCapture" : (kind == "ColorFound" ? "PixelColorSelection" : (kind == "ImageFound" || kind == "ImageNotFound" ? "ImageCapture" : "UIAAction")))
}
Browse(*) {
n := this.Kind(2) == "FileExists" ? 2 : 1
if this.Kind(n) != "FileExists" {
this.feedback.Text := "Choose 'A file or folder exists' first. You can also enter a folder path directly."
return
}
path := FileSelect(1, , "Choose a file to check")
if path != ""
this.rows[n].left.Value := path
}
}
class ShortcutCaptureUI {
static Open(app, owner, field, onChange := 0) {
if app.recorder.isRecording || app.playback.isRunning || app.selectionEngine.isActive {
MsgBox("Stop recording, playback, or target selection before binding a shortcut.", "Bind shortcut")
return
}
app.UnregisterGlobalStudioHotkeys()
owner.Opt("+Disabled")
d := Gui("+Owner" owner.Hwnd, "Bind shortcut")
d.SetFont("s10", "Segoe UI")
d.AddText("w400", "Press a key with optional Ctrl, Alt, or Shift. Studio shortcuts are suspended while binding.")
key := d.AddHotkey("w400 y+12")
d.AddButton("w130 y+14 Default", "Use shortcut").OnEvent("Click", (*) => Finish(true))
d.AddButton("x+8 w100", "Cancel").OnEvent("Click", (*) => Finish(false))
d.OnEvent("Close", (*) => Finish(false)), d.OnEvent("Escape", (*) => Finish(false))
d.Show(), key.Focus()
Finish(accept) {
if accept && key.Value == ""
return
if accept {
field.Value := key.Value
if IsObject(onChange)
onChange.Call()
}
d.Destroy()
owner.Opt("-Disabled")
owner.Show()
app.RegisterGlobalStudioHotkeys()
}
}
}
class ExportOptionsUI {
__New(app, initialFormat := "AHK") {
this.app := app
d := Gui("+Owner" app.gui.mainGui.Hwnd, "Export macro")
this.dialog := d
d.SetFont("s10", "Segoe UI")
d.BackColor := "F5F7FA"
d.AddText("x20 y18 w570 h30", "Export: " app.project.GetActiveMacro().Name)
d.AddText("x20 y58 w120", "Player")
this.mode := d.AddDropDownList("x150 y54 w420 Choose1", ["Run once, then exit", "Mini menu — Play / Pause / Stop / Loop"])
d.AddText("x20 y100 w120", "File format")
this.format := d.AddDropDownList("x150 y96 w420", ["AHK script", "Windows EXE"])
this.format.Choose(initialFormat == "EXE" ? 2 : 1)
this.details := d.AddText("x20 y142 w550 h70", "")
this.format.OnEvent("Change", (*) => this.Refresh())
this.mode.OnEvent("Change", (*) => this.Refresh())
this.compilerLabel := d.AddText("x20 y224 w120", "EXE compiler")
compiler := CompilerLocator.Resolve(app.persistence.settings.Get("CompilerPath", ""))
this.compiler := d.AddEdit("x150 y220 w315 h27", compiler)
this.browse := d.AddButton("x475 y220 w95 h27", "Browse…")
this.browse.OnEvent("Click", (*) => this.BrowseCompiler())
this.keyHint := d.AddText("x20 y264 w550 h64", "Shortcuts are inherited from Settings when you export. Change them there before creating a new export.")
warnings := AHKExporter.CheckInteractiveExportWarnings(app.project)
note := "The active macro runs; called submacros and project variables are included. Studio trigger hotkeys are not exported."
if warnings.Length
note .= "`nThis project contains " warnings.Length " interactive prompt/policy setting(s); those steps may still ask for input."
d.AddText("x20 y350 w550 h66", note)
this.exportButton := d.AddButton("x20 y426 w170 h34 Default", "Export…")
this.exportButton.OnEvent("Click", (*) => this.Export())
d.AddButton("x200 y426 w100 h34", "Cancel").OnEvent("Click", (*) => d.Destroy())
this.status := d.AddText("x20 y474 w550 h44", "")
d.OnEvent("Escape", (*) => d.Destroy())
this.Refresh()
d.Show("w595 h530")
}
Refresh() {
exe := this.format.Value == 2
this.compiler.Enabled := exe, this.browse.Enabled := exe
this.compiler.Visible := exe, this.browse.Visible := exe, this.compilerLabel.Visible := exe
this.keyHint.Move(,exe ? 264 : 224)
keys := this.app.persistence.settings
this.details.Text := (this.mode.Value == 1 ? "Runs immediately, once, then exits." : "Opens a small player without starting. Loop repeats until stopped.")
. "`n" keys.Get("Hotkey_Play", "F1") " play · " keys.Get("Hotkey_Pause", "F7") " pause/resume · " keys.Get("Hotkey_Stop", "F8") " stop"
. "`n" (exe ? "Standalone Windows application." : "Requires AutoHotkey v2.")
this.exportButton.Text := exe ? "Build EXE…" : "Export AHK…"
}
BrowseCompiler() {
path := FileSelect(1, this.compiler.Value, "Choose Ahk2Exe compiler", "Executable (*.exe)")
if path != ""
this.compiler.Value := path
}
Export() {
exe := this.format.Value == 2
mode := this.mode.Value == 1 ? "Once" : "Menu"
shortcuts := Map()
for key in ["Hotkey_Play", "Hotkey_Pause", "Hotkey_Stop"]
shortcuts[key] := this.app.persistence.settings[key]
extension := exe ? ".exe" : ".ahk"
if exe {
compiler := CompilerLocator.ForExport(this.compiler.Value)
if compiler == "" {
this.status.Text := "No compiler found. Choose a folder containing Ahk2Exe.exe, or select AHK script above to export without a compiler."
return
}
this.compiler.Value := compiler
this.app.persistence.settings["CompilerPath"] := compiler
this.app.persistence.SaveSettings()
}
name := RegExReplace(this.app.project.GetActiveMacro().Name, "[^\w\- ]", "_") . (mode == "Once" ? "_Once" : "_Player") . extension
path := FileSelect("S16", name, exe ? "Build exported macro" : "Export standalone macro", exe ? "Windows executable (*.exe)" : "AutoHotkey script (*.ahk)")
if path == ""
return
if StrLower(SubStr(path, -StrLen(extension))) != extension
path .= extension
this.exportButton.Enabled := false
this.status.Text := exe ? "Building executable…" : "Writing standalone script…"
try {
if exe {
result := EXEBuilder.BuildExe(this.app.project, path, this.compiler.Value, this.app.persistence.settings.Get("BaseExePath", A_AhkPath), mode, shortcuts)
if !result["Success"]
throw Error(result["Message"])
} else
StudioUtils.AtomicWriteFile(path, AHKExporter.ExportProjectToAhk(this.app.project, "Auto", mode, shortcuts))
this.status.Text := "Created: " path
this.app.ShowToast("Export complete: " path)
} catch as err
this.status.Text := "Export failed: " err.Message
finally this.exportButton.Enabled := true
}
}
class StudioGui {
app := ""
mainGui := ""
layoutMgr := ""
statusBar := ""
; Toolbar controls
btnNew := "", btnOpen := "", btnSave := ""
btnRecord := "", btnAdvRecord := ""
btnPlay := "", btnPause := "", btnStop := ""
btnAddAction := "", btnPickTarget := "", btnReview := "", btnExport := ""
stateBadgeCtrl := "", toastCtrl := ""
; Left Navigation Pane
leftTab := ""
lvMacros := "", btnAddMacro := "", btnMacroCfg := "", btnDelMacro := ""
lvReusableTargets := "", btnAddReusable := "", btnTestReusable := "", btnRepairReusable := ""
lvLeftSessions := "", btnLaunchProfLeft := "", btnAttachLeft := ""
; Center Workflow Pane
emptyBannerText := "", reviewBannerBtn := ""
edtSearchWorkflow := "", ddlFilterCat := ""
btnQuickClick := "", btnQuickType := "", btnQuickWait := "", btnQuickBrowser := "", btnQuickLogic := ""
lvWorkflow := ""
flattenedRows := []
clipboardActions := []
clipboardTarget := ""
selectedActionId := ""
; Right Inspector Pane
grpInspector := ""
lblInspStepTitle := ""
ddlInspActionType := ""
chkInspEnabled := "", chkInspBreakpoint := ""
; Target Card Controls (Section 25)
grpTargetCard := ""
lblTargetHeading := "", lblTargetRole := ""
lblTargetWithin := "", lblTargetMethod := "", lblTargetFindUsing := ""
lblTargetMatches := "", lblTargetReliability := "", lblTargetRelReason := ""
btnTargetTest := "", btnTargetHighlight := "", btnTargetChange := ""
btnTargetUpgrade := "", btnTargetFallbacks := "", btnTargetAnchor := "", btnTargetPromote := ""
; Primary Action Parameter Controls
lblParam1 := "", edtParam1 := "", ddlParam1 := ""
lblParam2 := "", edtParam2 := "", ddlParam2 := ""
lblBrowserCtx := "", ddlBrowserSession := "", ddlBrowserProfile := "", ddlBrowserPolicy := ""
btnCondBuilder := ""
; Progressive Disclosure Advanced Section (Section 9 & 91)
btnToggleAdvanced := ""
isAdvancedOpen := false
lblAdvScope := "", ddlAdvScope := "", btnPickRegion := ""
lblAdvTimeout := "", edtAdvTimeout := "", lblAdvRetries := "", edtAdvRetries := ""
lblAdvFail := "", ddlAdvFail := "", btnApplyInspector := ""
; Bottom Panel
bottomTab := ""
lvLogs := "", btnCopyLogs := "", btnClearLogs := ""
lvProblems := "", btnRefreshProblems := "", btnFixProblem := ""
currentProblems := []
lvVariables := "", btnAddVar := "", btnClearRuntimeVars := ""
lvBottomSessions := "", btnMgrProfiles := "", btnInspectBrowser := ""
lvDiagnostics := "", btnRunDiag := ""
toastClearTimer := ""
suppressInspectorEvents := false
__New(app) {
this.app := app
this.layoutMgr := ResponsiveLayoutManager(this)
}
GetMainHwnd() {
return IsObject(this.mainGui) ? this.mainGui.Hwnd : 0
}
Build() {
if this.HasOwnProp("pointerDownCallback")
OnMessage(0x201, this.pointerDownCallback, 0)
for timerName in ["resizeTimer","paneDragTimer","workflowDragTimer"]
if this.HasOwnProp(timerName)
SetTimer(this.%timerName%,0)
if this.HasOwnProp("inspectorHelp")
this.DeleteProp("inspectorHelp")
if this.HasOwnProp("helpCallback")
OnMessage(0x200, this.helpCallback, 0)
g := Gui("+Resize +MinSize320x240", StudioConstants.AppName " — Untitled Project")
StudioBranding.ApplyGui(g)
g.SetFont("s9", DesignTokens.FontUI)
g.MarginX := 8
g.MarginY := 6
this.mainGui := g
this._BuildMenuBar(g)
this._BuildToolbar(g)
this._BuildLeftPane(g)
this._BuildCenterWorkflowPane(g)
this._BuildRightInspectorPane(g)
this._BuildBottomPane(g)
this.leftSplitter := g.AddText("x0 y0 w6 h100 +0x100 BackgroundD6DCE5", "")
this.logSplitter := g.AddText("x0 y0 w100 h6 +0x100 BackgroundD6DCE5", "")
this.rightSplitter := g.AddText("x0 y0 w6 h100 +0x100 BackgroundD6DCE5", "")
this.pointerDownCallback := ObjBindMethod(this, "_OnPanePointerDown")
OnMessage(0x201, this.pointerDownCallback)
this.lvWorkflow.OnNotify(-109, ObjBindMethod(this, "_BeginWorkflowDrag"))
this.statusBar := g.Add("StatusBar")
this.statusBar.SetParts(220, 360, 260)
this.statusBar.SetText(" State: Idle", 1)
this.statusBar.SetText(" F3: Record | F1: Play | F7: Pause | F8: Stop", 2)
this.statusBar.SetText(" Layout: Wide", 3)
this.statusBar.SetText(" Ready", 4)
g.OnEvent("Size", ObjBindMethod(this, "_OnMainGuiSize"))
g.OnEvent("Close", ObjBindMethod(this, "_OnMainGuiClose"))
g.OnEvent("ContextMenu", ObjBindMethod(this, "_OnMainGuiContextMenu"))
this.ShowWithinWorkArea()
if this.app.persistence.settings.Get("InspectorAdvancedOpen", false) {
this.isAdvancedOpen := true
this.btnToggleAdvanced.Text := "Advanced settings..."
this._SetAdvancedControlsVisible(true)
}
this.InstallHelpTips()
for entry in this.app.logger.entries
this.OnLogEntryAdded(entry)
this.RefreshAll()
}
ShowWithinWorkArea() {
g := this.mainGui
settings := this.app.persistence.settings
scale := A_ScreenDPI / 96
mx := settings.Get("WindowX", -1), my := settings.Get("WindowY", -1)
monitor := MonitorGetPrimary()
Loop MonitorGetCount() {
MonitorGetWorkArea(A_Index, &l, &t, &r, &b)
if mx >= l && mx < r && my >= t && my < b {
monitor := A_Index
break
}
}
MonitorGetWorkArea(monitor, &l, &t, &r, &b)
w := Max(320, Min(Integer(settings.Get("WindowW", 1340)), Floor((r-l-20)/scale)))
h := Max(240, Min(Integer(settings.Get("WindowH", 820)), Floor((b-t-90)/scale)))
g.Opt("+MinSize320x240")
g.Show(Format("Hide w{1} h{2}", w, h))
prevHidden := DetectHiddenWindows(true)
WinGetPos(, , &ow, &oh, "ahk_id " g.Hwnd)
ow := Min(ow, r-l), oh := Min(oh, b-t)
x := mx == -1 ? l + (r-l-ow)//2 : Max(l, Min(mx, r-ow))
y := my == -1 ? t + (b-t-oh)//2 : Max(t, Min(my, b-oh))
WinMove(x, y, ow, oh, "ahk_id " g.Hwnd)
g.Show()
DetectHiddenWindows(prevHidden)
g.GetClientPos(, , &cw, &ch)
this.layoutMgr.ApplyLayout(cw, ch)
}
InstallHelpTips() {
this.helpTips := Map(
this.btnPickTarget.Hwnd, "Pick a target. Window-relative coordinates follow the window; semantic targets can also survive layout changes.",
this.btnExport.Hwnd, "Export the active macro as a standalone script or mini player.",
this.btnStop.Hwnd, "Requests cancellation and releases inputs held by playback.")
this.helpTips[this.btnTargetAnchor.Hwnd] := "Find this target relative to a nearby label or landmark when several controls look alike."
this.helpTips[this.btnTargetPromote.Hwnd] := "Save the selected target for reuse in other steps."
this.helpTips[this.btnTargetTest.Hwnd] := "Choose a target if none is set; otherwise check whether it can be found without executing the action."
this.helpTips[this.btnTargetHighlight.Hwnd] := "Highlight where this step will act without clicking or typing."
this.helpTips[this.btnTargetChange.Hwnd] := "Choose a different target for this step."
this.helpTips[this.btnCondBuilder.Hwnd] := "Edit this block's condition, or wrap the selected steps in an If block so they run only when your condition is met."
this.inspectorHelp := Map()
hints := Map(
"pause", "Pause here is a breakpoint: playback pauses before this step so you can inspect the target and variables.",
"mode", "Choose the action-specific input option. Auto uses the action's normal delivery method; full settings offer more controls.",
"value", "This value depends on the selected action: text, keys, a window, or a click method. Text is literal; keys use AHK shortcuts such as ^c and {Enter}. Auto click method lets Studio choose delivery. Full action settings provide additional controls.",
"session", "A named browser connection, such as MainBrowser. Steps using the same session share a connected browser window. An empty step value inherits the macro default.",
"profile", "A browser identity such as Default, Work, or Personal. Configure these aliases under Tools > Browser Profiles. Empty step values inherit the macro default.")
for name, hint in hints {
icon := this.mainGui.AddButton("Hidden w22 h22", "?")
icon.OnEvent("Click", ShowInspectorHelp.Bind(hint))
this.inspectorHelp[name] := icon
this.helpTips[icon.Hwnd] := hint
}
this.helpCallback := ObjBindMethod(this, "_OnHelpHover")
OnMessage(0x200, this.helpCallback)
ShowInspectorHelp(message, *) => MsgBox(message, "Action help", "Iconi")
}
_OnHelpHover(wParam, lParam, msg, hwnd) {
static last := 0
if hwnd == last
return
last := hwnd
ToolTip()
tipHwnd := this.helpTips.Has(hwnd) ? hwnd : DllCall("GetParent", "Ptr", hwnd, "Ptr")
if this.app.persistence.settings.Get("ShowHelpTips", true) && this.helpTips.Has(tipHwnd)
ToolTip(this.helpTips[tipHwnd])
}
_BuildMenuBar(g) {
mb := MenuBar()
mFile := Menu()
mFile.Add("&New Project`tCtrl+N", (*) => this.app.CmdNewProject())
mFile.Add("&Open Project...`tCtrl+O", (*) => this.app.CmdOpenProject())
mFile.Add("&Save Project`tCtrl+S", (*) => this.app.CmdSaveProject(false))
mFile.Add("Save Project &As...`tCtrl+Shift+S", (*) => this.app.CmdSaveProject(true))
mFile.Add()
mFile.Add("&Export Standalone AHK Script...`tCtrl+E", (*) => this.app.CmdExportAhk())
mFile.Add("&Build Standalone EXE...`tCtrl+B", (*) => this.app.CmdBuildExe())
mFile.Add()
mFile.Add("E&xit", (*) => this._OnMainGuiClose(g))
mEdit := Menu()
mEdit.Add("Action &settings…", (*) => this.ToggleAdvancedInspector())
mEdit.Add()
mEdit.Add("&Undo`tCtrl+Z", (*) => this.app.CmdUndo())
mEdit.Add("&Redo`tCtrl+Y", (*) => this.app.CmdRedo())
mEdit.Add()
mEdit.Add("Select &All Steps`tCtrl+A", (*) => this._RunWorkflowShortcut("SelectAll"))
mEdit.Add("Cu&t Step`tCtrl+X", (*) => this._RunWorkflowShortcut("CmdCutStep"))
mEdit.Add("&Copy Step`tCtrl+C", (*) => this._RunWorkflowShortcut("CmdCopyStep"))
mEdit.Add("&Paste Step`tCtrl+V", (*) => this._RunWorkflowShortcut("CmdPasteStep"))
mEdit.Add("&Duplicate Step`tCtrl+D", (*) => this.CmdDuplicateStep())
mEdit.Add("Duplicate && &Change Target...", (*) => this.CmdDuplicateAndChangeTarget())
mEdit.Add("De&lete Step`tDelete", (*) => this.CmdDeleteStep())
mEdit.Add()
mEdit.Add("Copy &Target Only", (*) => this.CmdCopyTargetOnly())
mEdit.Add("Paste Target Into Step", (*) => this.CmdPasteTargetOnly())
mEdit.Add()
mEdit.Add("Move Step &Up`tAlt+Up", (*) => this.CmdMoveStepUp())
mEdit.Add("Move Step &Down`tAlt+Down", (*) => this.CmdMoveStepDown())
mEdit.Add("Enable / Disable Step", (*) => this.CmdToggleStepEnabled())
mRecord := Menu()
mRecord.Add("Start / Stop &Simple Recording`tF3", (*) => this.app.CmdToggleRecord("Simple"))
mRecord.Add("Start &Advanced Recording (Live Targeting)`tShift+F3", (*) => this.app.CmdToggleRecord("Advanced"))
mRecord.Add("&Freeze && Refine Target`tCtrl+Shift+F", (*) => this.app.recorder.TriggerFreezeAndRefineDuringRecord())
mRecord.Add()
mRecord.Add("Record &Here (Insert After Selected Step)", (*) => this.app.CmdRecordAfterSelected())
mRecord.Add("&Review && Upgrade Recorded Steps...", (*) => this.ShowRecordingReviewDialog())
mRun := Menu()
mRun.Add("&Play Macro`tF1", (*) => this.app.CmdPlay())
mRun.Add("P&ause / Resume`tF7", (*) => this.app.CmdPauseResume())
mRun.Add("&Emergency Stop`tF8", (*) => this.app.CmdEmergencyStop())
mRun.Add()
mRun.Add("&Test Selected Step (Resolve Only)`tCtrl+Enter", (*) => this.CmdTestSelectedStep())
mRun.Add("Check this step — no clicks", (*) => this.CmdPreviewCurrentStep())
mRun.Add("Run &Selected Step Only", (*) => this.app.CmdRunSelectedStep())
mRun.Add("Run &From Here", (*) => this.app.CmdRunFromHere())
mRun.Add("Run &To Here", (*) => this.app.CmdRunToHere())
mRun.Add("Single &Step Next`tF10", (*) => this.app.CmdStepNext())
mRun.Add("Toggle &Breakpoint`tF9", (*) => this.CmdToggleBreakpoint())
mRun.Add()
mRun.Add("&Validate && Dry-Run Targets (Preflight)...", (*) => this.ShowDryRunPreflightDialog())
mInsert := Menu()
mInsert.Add("&Find an action…`tCtrl+Shift+A", (*) => this.ShowAddActionPalette())
mInsert.Add()
input := Menu()
input.Add("Click an element…", (*) => this.QuickInsertAction("UIA_Click", true))
input.Add("Type text…", (*) => this.QuickInsertAction("Key_TypeText"))
input.Add("Set an input's value…", (*) => this.QuickInsertAction("UIA_SetValue"))
input.Add("Find and click an image…", (*) => this.QuickInsertAction("Image_Click"))
mInsert.Add("Click and type", input)
apps := Menu()
apps.Add("Open program / file / folder…", (*) => this.QuickInsertAction("App_Run"))
apps.Add("Open website in default browser…", (*) => this.QuickInsertAction("App_OpenURL"))
apps.Add("Activate a window…", (*) => this.QuickInsertAction("Win_Activate"))
apps.Add("Minimize / maximize / restore / close…", (*) => this.QuickInsertAction("Win_State"))
apps.Add("Wait for a program to start / close…", (*) => this.QuickInsertAction("App_WaitProcess"))
mInsert.Add("Programs and windows", apps)
web := Menu()
web.Add("Launch browser profile…", (*) => this.QuickInsertAction("Profile_Launch"))
web.Add("Navigate to an address…", (*) => this.QuickInsertAction("Browser_Navigate"))
web.Add("Click link and wait for a new tab…", (*) => this.QuickInsertAction("Browser_ClickAndWaitNewTab", true))
web.Add("Select an existing tab…", (*) => this.QuickInsertAction("Browser_SelectTab"))
web.Add("Close a matching tab…", (*) => this.QuickInsertAction("Browser_CloseTab"))
web.Add("Extract page links…", (*) => this.QuickInsertAction("Browser_ExtractLinks"))
mInsert.Add("Browser", web)
mInsert.Add("Read / find / click text (OCR)", (*) => this.ShowOCRMenu())
mInsert.Add("Wait for…", (*) => this.ShowWaitMenu())
logic := Menu()
logic.Add("If a condition is true…", (*) => this.QuickInsertAction("Logic_If"))
logic.Add("For each item in a list…", (*) => this.QuickInsertAction("Logic_ForEach"))
logic.Add("Repeat a number of times…", (*) => this.QuickInsertAction("Logic_Repeat"))
logic.Add("Repeat while a condition is true…", (*) => this.QuickInsertAction("Logic_While"))
logic.Add("Repeat until a condition is true…", (*) => this.QuickInsertAction("Logic_While", false, Map("LoopMode", "Until")))
logic.Add()
logic.Add("Go to label…", (*) => this.QuickInsertAction("Logic_Goto"))
mInsert.Add("Conditions and loops", logic)
mTools := Menu()
mTools.Add("&Choose Browser Session (Running Windows)...", (*) => this.ShowChooseBrowserSessionDialog())
mTools.Add("&Browser Inspector && Tab Picker...", (*) => this.ShowBrowserInspectorDialog())
mTools.Add("Browser &Profiles Manager...", (*) => this.ShowBrowserProfilesDialog())
mTools.Add("&Window Inspector...", (*) => this.ShowWindowInspectorDialog())
mTools.Add("Live &Color Picker...", (*) => this.ShowColorPickerDialog())
mTools.Add("&Capture Image Target", (*) => this.CmdPickTargetForCurrent("ImageCapture"))
mTools.Add()
mTools.Add("Batch Target &Repair Queue...", (*) => this.ShowBatchRepairQueueDialog())
mTools.Add("&Validate && Dry-Run Targets (Preflight)...", (*) => this.ShowDryRunPreflightDialog())
mTools.Add("&Analyze && Upgrade Browser Steps...", (*) => this.ShowRecordingReviewDialog())
mTools.Add("&Settings…", (*) => this.ShowOptionsDialog())
mTools.Add("Screen-edge glow settings…", (*) => GlowSettingsUI(this))
mTools.Add("&Reset Settings to Default", (*) => this.app.CmdResetSettings())
mInsert.Add()
wrap := Menu()
wrap.Add("Wrap selected in list loop", (*) => this.WrapSelected("Logic_ForEach"))
wrap.Add("Wrap selected in repeat loop", (*) => this.WrapSelected("Logic_Repeat"))
wrap.Add("Wrap selected in while loop", (*) => this.WrapSelected("Logic_While"))
wrap.Add("Wrap selected in until loop", (*) => this.WrapSelected("Logic_While", "Until"))
wrap.Add("Wrap selected in IF", (*) => this.WrapSelected("Logic_If"))
mInsert.Add("Wrap selected steps", wrap)
mView := Menu()
mView.Add("Reset layout to default", (*) => this.ResetLayout())
mView.Add()
mView.Add("Show Hide &Log Panel", (*) => this.ToggleContextPanel())
mView.Add("Action &settings…", (*) => this.ToggleAdvancedInspector())
mHelp := Menu()
mHelp.Add("&Nichols Macro Studio User Guide...", (*) => this.ShowHelpDialog())
mHelp.Add("Run Self-Test &Diagnostics...", (*) => this.CmdRunDiagnosticsUI())
mHelp.Add()
mHelp.Add("&About", (*) => this.ShowAboutDialog())
mb.Add("&File", mFile)
mb.Add("&Edit", mEdit)
mb.Add("&Record", mRecord)
mb.Add("R&un", mRun)
mb.Add("&Insert", mInsert)
mb.Add("&Tools", mTools)
mb.Add("&View", mView)
mb.Add("&Help", mHelp)
g.MenuBar := mb
}
_BuildToolbar(g) {
this.btnRecord := g.Add("Button", "x8 y6 w96 h28", "● Record (F3)")
this.btnRecord.OnEvent("Click", (*) => this.app.CmdToggleRecord("Simple"))
this.btnPlay := g.Add("Button", "x+10 y6 w82 h28", "▶ Play (F1)")
this.btnPlay.OnEvent("Click", (*) => (this.app.playback.isRunning ? this.app.CmdPauseResume() : this.app.CmdPlay()))
this.btnUndo := g.Add("Button", "x+4 y6 w70 h28", "↶ Undo")
this.btnUndo.OnEvent("Click", (*) => this.app.CmdUndo())
this.btnRedo := g.Add("Button", "x+4 y6 w70 h28", "↷ Redo")
this.btnRedo.OnEvent("Click", (*) => this.app.CmdRedo())
this.btnStop := g.Add("Button", "x+4 y6 w76 h28", "■ Stop (F8)")
this.btnStop.OnEvent("Click", (*) => this.app.CmdEmergencyStop())
this.btnAddAction := g.Add("Button", "x+10 y6 w92 h28", "+ Add Action")
this.btnAddAction.OnEvent("Click", (*) => this.ShowAddActionPalette())
this.btnPickTarget := g.Add("Button", "x+4 y6 w90 h28", "⌖ Pick Target")
this.btnPickTarget.OnEvent("Click", (*) => this.CmdPickTargetForCurrent("UIAAction"))
this.btnReview := g.Add("Button", "x+4 y6 w82 h28", "✨ Review")
this.btnReview.OnEvent("Click", (*) => this.ShowRecordingReviewDialog())
this.btnExport := g.Add("Button", "x+4 y6 w118 h28", "↗ Export Script")
this.btnExport.OnEvent("Click", (*) => this.app.CmdExportAhk())
this.btnToggleLog := g.AddButton("x+4 y6 w100 h28", "▤ Show log")
this.btnToggleLog.OnEvent("Click", (*) => this.ToggleContextPanel())
g.SetFont("s9 Bold", DesignTokens.FontUI)
this.stateBadgeCtrl := g.Add("Text", "x+12 y10 w160 h22 +0x200", "STATE: IDLE")
g.SetFont("s9 Norm", DesignTokens.FontUI)
this.toastCtrl := g.Add("Text", "x+8 y10 w260 h22 +0x200", "Ready")
}
_BuildLeftPane(g) {
this.leftTab := g.Add("Tab3", "x8 y42 w240 h480", ["Macros", "Targets", "Sessions"])
this.leftTab.UseTab(1)
this.lvMacros := g.Add("ListView", "x16 y72 w224 h355 -Multi Grid AltSubmit", ["Macro", "Trigger", "Browser"])
this.lvMacros.OnEvent("ContextMenu", ObjBindMethod(this, "_OnNavigationContextMenu"))
this.lvMacros.ModifyCol(1, 105)
this.lvMacros.ModifyCol(2, 55)
this.lvMacros.ModifyCol(3, 55)
this.lvMacros.OnEvent("ItemSelect", ObjBindMethod(this, "_OnMacroSelect"))
this.btnAddMacro := g.Add("Button", "x16 y432 w70 h26", "+ Macro")
this.btnAddMacro.OnEvent("Click", (*) => this.CmdAddMacro())
this.btnMacroCfg := g.Add("Button", "x+4 y432 w76 h26", "⚙ Setup")
this.btnMacroCfg.OnEvent("Click", (*) => this.ShowMacroConfigDialog())
this.btnDelMacro := g.Add("Button", "x+4 y432 w68 h26", "× Delete")
this.btnDelMacro.OnEvent("Click", (*) => this.CmdDeleteMacro())
this.leftTab.UseTab(2)
this.lvReusableTargets := g.Add("ListView", "x16 y72 w224 h355 -Multi Grid AltSubmit", ["Target Name", "Role", "Reliability"])
this.lvReusableTargets.OnEvent("ContextMenu", ObjBindMethod(this, "_OnNavigationContextMenu"))
this.lvReusableTargets.ModifyCol(1, 105)
this.lvReusableTargets.ModifyCol(2, 55)
this.lvReusableTargets.ModifyCol(3, 55)
this.lvReusableTargets.OnEvent("DoubleClick", (*) => this.CmdFindReusableTargetUsages())
this.btnAddReusable := g.Add("Button", "x16 y432 w76 h26", "+ Capture")
this.btnAddReusable.OnEvent("Click", (*) => this.CmdCaptureNewReusableTarget())
this.btnTestReusable := g.Add("Button", "x+4 y432 w68 h26", "✓ Test")
this.btnTestReusable.OnEvent("Click", (*) => this.CmdTestSelectedReusableTarget())
this.btnRepairReusable := g.Add("Button", "x+4 y432 w70 h26", "↻ Repair")
this.btnRepairReusable.OnEvent("Click", (*) => this.CmdRepairSelectedReusableTarget())
this.leftTab.UseTab(3)
this.lvLeftSessions := g.Add("ListView", "x16 y72 w224 h355 -Multi Grid", ["Session", "Browser / Profile", "Status"])
this.lvLeftSessions.OnEvent("ContextMenu", ObjBindMethod(this, "_OnNavigationContextMenu"))
this.lvLeftSessions.ModifyCol(1, 75)
this.lvLeftSessions.ModifyCol(2, 90)
this.lvLeftSessions.ModifyCol(3, 55)
this.btnLaunchProfLeft := g.Add("Button", "x16 y432 w108 h26", "Launch Profile...")
this.btnLaunchProfLeft.OnEvent("Click", (*) => this.ShowBrowserProfilesDialog())
this.btnAttachLeft := g.Add("Button", "x+6 y432 w108 h26", "Choose Window...")
this.btnAttachLeft.OnEvent("Click", (*) => this.ShowChooseBrowserSessionDialog())
this.leftTab.UseTab()
}
_BuildCenterWorkflowPane(g) {
; Empty-state / Welcome / Review banner
this.emptyBannerText := g.Add("Text", "x256 y42 w480 h26 +0x200", "Create automation: Press F3 to Record naturally, click '+ Add Action', or Open Project.")
this.reviewBannerBtn := g.Add("Button", "x742 y40 w180 h26", "✨ 0 recommended upgrades")
this.reviewBannerBtn.OnEvent("Click", (*) => this.ShowRecordingReviewDialog())
; Search, Category filter, and Quick-Add strip
; Filters are positioned by the responsive layout.
this.edtSearchWorkflow := g.Add("Edit", "x304 y72 w140 h24", "")
this.edtSearchWorkflow.OnEvent("Change", (*) => this.RefreshWorkflowList())
catOptions := ["All Categories"]
for _, c in ActionRegistry.Categories
catOptions.Push(c)
this.ddlFilterCat := g.Add("DropDownList", "x450 y72 w135 Choose1", catOptions)
this.ddlFilterCat.OnEvent("Change", (*) => this.RefreshWorkflowList())
this.btnQuickClick := g.Add("Button", "x592 y71 w58 h25", "+ Click")
this.btnQuickClick.OnEvent("Click", (*) => this.QuickInsertAction("UIA_Click", true))
this.btnQuickType := g.Add("Button", "x+4 y71 w56 h25", "+ Type")
this.btnQuickType.OnEvent("Click", (*) => this.QuickInsertAction("UIA_SetValue", false))
this.btnQuickWait := g.Add("Button", "x+4 y71 w56 h25", "+ Wait")
this.btnQuickWait.OnEvent("Click", (*) => this.ShowWaitMenu())
this.btnQuickBrowser := g.Add("Button", "x+4 y71 w64 h25", "+ Web")
this.btnQuickBrowser.OnEvent("Click", (*) => this.QuickInsertAction("Browser_Navigate", false))
this.btnQuickLogic := g.Add("Button", "x+4 y71 w60 h25", "+ Logic")
this.btnQuickLogic.OnEvent("Click", (*) => this.QuickInsertAction("Logic_If", false))
; Main Workflow ListView (Section 89)
this.lvWorkflow := g.Add("ListView", "x256 y102 w660 h420 Grid AltSubmit", ["#", "Action", "Target", "Details", "Wait Before", "Wait After", "Label", "Timeout", "Status"])
this.lvWorkflow.ModifyCol(1, 38)
this.lvWorkflow.ModifyCol(2, 225)
this.lvWorkflow.ModifyCol(3, 165)
this.lvWorkflow.ModifyCol(4, 155)
this.lvWorkflow.ModifyCol(5, 95)
this.lvWorkflow.ModifyCol(6, 95)
this.lvWorkflow.ModifyCol(7, 120)
this.lvWorkflow.ModifyCol(8, 110)
this.lvWorkflow.ModifyCol(9, 65)
this.lvWorkflow.OnEvent("ItemSelect", ObjBindMethod(this, "_OnWorkflowItemSelect"))
this.lvWorkflow.OnNotify(-3, ObjBindMethod(this,"OnWorkflowDoubleClick"))
}
_BuildActionStarter(g) {
this.starterTitle := g.AddText("Hidden", "What would you like to do?")
this.starterTitle.SetFont("s10 Bold")
this.starterHint := g.AddText("Hidden", "Add a step here. Right-click an action to customize Common actions.")
this.starterSearch := g.AddEdit("Hidden")
SendMessage(0x1501, true, StrPtr("Search actions…"), this.starterSearch.Hwnd)
this.starterClear := g.AddButton("Hidden", "Clear")
this.starterClear.OnEvent("Click", (*) => (this.starterSearch.Value := "", this.PopulateActionStarter(), this.starterSearch.Focus()))
categories := ["Common actions", "All actions"]
for category in ActionRegistry.Categories
categories.Push(category)
this.starterCategory := g.AddDropDownList("Hidden Choose1", categories)
this.starterList := g.AddListView("Hidden -Multi -Hdr", ["Action"])
this.starterAdd := g.AddButton("Hidden", "+ Add selected action")
this.starterControls := [this.starterTitle, this.starterHint, this.starterSearch, this.starterClear, this.starterCategory, this.starterList, this.starterAdd]
this.starterSearch.OnEvent("Change", (*) => this.PopulateActionStarter())
this.starterCategory.OnEvent("Change", (*) => this.PopulateActionStarter())
this.starterList.OnEvent("ContextMenu", (ctrl, row, right, x, y) => this.ShowCommonActionMenu(ctrl, row, right, true))
this.starterList.OnEvent("DoubleClick", (*) => this.AddStarterAction())
this.starterAdd.OnEvent("Click", (*) => this.AddStarterAction())
this.PopulateActionStarter()
}
PopulateActionStarter() {
this.starterList.Delete()
this.starterTypes := []
this.starterClear.Enabled := this.starterSearch.Value != ""
query := StrLower(Trim(this.starterSearch.Value))
category := this.starterCategory.Text
common := this.app.persistence.settings["CommonActions"]
for def in ActionRegistry.GetDefinitions() {
if category == "Common actions" && query == "" && !InStr(common, "|" def["Type"] "|")
continue
if category != "Common actions" && category != "All actions" && category != def["Cat"]
continue
if !ActionDiscovery.Matches(def, query)
continue
this.starterTypes.Push(def["Type"])
this.starterList.Add(this.starterTypes.Length == 1 ? "Select Focus" : "", def["Name"])
}
this.starterAdd.Enabled := this.starterTypes.Length > 0
this.starterAdd.Text := this.starterTypes.Length ? "+ Add selected action" : "No matches — try another search"
}
ToggleCommonAction(actionType) {
if !ActionRegistry.IsKnown(actionType)
return
common := this.app.persistence.settings["CommonActions"]
needle := "|" actionType "|"
this.app.persistence.settings["CommonActions"] := InStr(common, needle) ? StrReplace(common, needle, "|") : common actionType "|"
this.app.persistence.SaveSettings()
this.PopulateActionStarter()
this.ShowToast(InStr(this.app.persistence.settings["CommonActions"], needle) ? "Added to Common actions." : "Removed from Common actions.")
}
ShowCommonActionMenu(control, row, rightClick, starter := false) {
if rightClick {
hit := Buffer(24, 0)
DllCall("GetCursorPos", "Ptr", hit)
DllCall("ScreenToClient", "Ptr", control.Hwnd, "Ptr", hit)
row := SendMessage(0x1039, 0, hit.Ptr, control.Hwnd)+1
} else
row := control.GetNext(0, "F")
if row < 1 || row > control.GetCount()
return
actionType := starter ? this.starterTypes[row] : control.GetText(row, 3)
actionMenu := Menu()
common := InStr(this.app.persistence.settings["CommonActions"], "|" actionType "|")
actionMenu.Add(common ? "Remove from Common actions" : "Add to Common actions", (*) => this.ToggleCommonAction(actionType))
actionMenu.Show()
}
ResetLayout() {
this.layoutMgr.forcedMode := "Auto"
s := this.app.persistence.settings
s["LayoutMode"] := "Auto", s["NavPaneWidth"] := 210, s["InspectorPaneWidth"] := 370
s["ShowContextPanel"] := false, s["LogPanelHeight"] := 200
this._TriggerRelayout()
this.app.persistence.SaveSettings()
this.ShowToast("Default layout restored. Panels adapt to the available window space.")
}
AddStarterAction() {
row := this.starterList.GetNext()
if row < 1 || row > this.starterTypes.Length
return
this.selectedActionId := ""
this.QuickInsertAction(this.starterTypes[row], false)
}
_OnNavigationContextMenu(control, item, isRightClick, x, y) {
if control == this.lvMacros || control == this.lvReusableTargets || control == this.lvLeftSessions {
row := control.GetNext(0, "F")
if isRightClick {
hit := Buffer(24, 0)
DllCall("GetCursorPos", "Ptr", hit)
DllCall("ScreenToClient", "Ptr", control.Hwnd, "Ptr", hit)
row := SendMessage(0x1039, 0, hit.Ptr, control.Hwnd) + 1
}
if row > 0 {
control.Modify(0, "-Select")
control.Modify(row, "Select Focus")
if control == this.lvMacros
this._OnMacroSelect(control, row, true)
}
this.BuildNavigationMenu(control, row).Show()
return
}
}
BuildNavigationMenu(control, row) {
navMenu := Menu()
if control == this.lvMacros {
navMenu.Add("New macro…", (*) => this.CmdAddMacro())
if row > 0 {
navMenu.Add("Rename / configure…", (*) => this.ShowMacroConfigDialog())
navMenu.Add("Duplicate macro", (*) => this.DuplicateNavigationMacro())
navMenu.Add()
navMenu.Add("Play macro", (*) => this.app.CmdPlay())
navMenu.Add("Export Script…", (*) => this.app.CmdExportAhk())
navMenu.Add("Build EXE…", (*) => this.app.CmdBuildExe())
navMenu.Add()
navMenu.Add("Delete macro", (*) => this.CmdDeleteMacro())
if this.app.project.Macros.Length <= 1
navMenu.Disable("Delete macro")
}
} else if control == this.lvReusableTargets {
navMenu.Add("Capture new target…", (*) => this.CmdCaptureNewReusableTarget())
if row > 0 {
navMenu.Add("Test target", (*) => this.CmdTestSelectedReusableTarget())
navMenu.Add("Repair / recapture…", (*) => this.CmdRepairSelectedReusableTarget())
navMenu.Add("Find usages / assign…", (*) => this.CmdFindReusableTargetUsages())
}
} else {
navMenu.Add("Choose browser window…", (*) => this.ShowChooseBrowserSessionDialog())
navMenu.Add("Browser profiles…", (*) => this.ShowBrowserProfilesDialog())
if row > 0 {
name := control.GetText(row, 1)
navMenu.Add("Bring browser to front", (*) => this.FocusNavigationSession(name))
navMenu.Add("Copy session name", (*) => A_Clipboard := name)
}
navMenu.Add()
navMenu.Add("Refresh status", (*) => this.RefreshSessionsPanels())
}
return navMenu
}
DuplicateNavigationMacro() {
original := this.app.project.GetActiveMacro()
copy := MacroModel.FromMap(original.ToMap())
copy.Id := StudioUtils.GenId("mac")
copy.Name .= " copy"
copy.TriggerHotkey := ""
copy.Actions := []
for action in original.Actions
copy.Actions.Push(action.Clone(true))
this.app.undoMgr.RecordSnapshot(this.app.project, "Duplicate Macro")
this.app.project.Macros.Push(copy)
this.app.project.ActiveMacroId := copy.Id
this.selectedActionId := ""
this.RefreshAll()
}
FocusNavigationSession(name) {
if !this.app.browserMgr.sessions.Has(name)
return this.ShowToast("Session is no longer available. Refresh the session list.")
hwnd := this.app.browserMgr.sessions[name]["Hwnd"]
if !WinExist(hwnd)
return this.ShowToast("Browser window has closed. Choose a window to reconnect.")
try WinActivate(hwnd)
catch as err
this.ShowToast(err.Message)
}
_BuildRightInspectorPane(g) {
previousControls := Map()
for control in g
previousControls[control.Hwnd] := true
ix := 926
iw := 365
this.grpInspector := g.Add("GroupBox", Format("x{1} y42 w{2} h480", ix, iw), "Action & Target Inspector")
g.SetFont("s9 Bold", DesignTokens.FontUI)
this.lblInspStepTitle := g.Add("Text", Format("x{1} y62 w{2} h20", ix + 12, iw - 24), "No Step Selected")
g.SetFont("s9 Norm", DesignTokens.FontUI)
allTypes := []
for _, def in ActionRegistry.GetDefinitions()
allTypes.Push(def["Name"])
this.ddlInspActionType := g.Add("DropDownList", Format("x{1} y84 w{2} Choose1", ix + 12, iw - 140), allTypes)
this.ddlInspActionType.OnEvent("Change", ObjBindMethod(this, "_OnInspectorActionTypeChange"))
this.chkInspEnabled := g.Add("CheckBox", Format("x{1} y86 w58 Checked", ix + iw - 122), "Enable")
this.chkInspEnabled.OnEvent("Click", ObjBindMethod(this, "_OnInspectorImmediateChange"))
this.chkInspBreakpoint := g.Add("CheckBox", Format("x{1} y86 w48", ix + iw - 60), "BP")
this.chkInspBreakpoint.OnEvent("Click", ObjBindMethod(this, "_OnInspectorImmediateChange"))
; TARGET CARD (Section 25)
this.grpTargetCard := g.Add("GroupBox", Format("x{1} y112 w{2} h182", ix + 10, iw - 20), "Target Card")
g.SetFont("s10 Bold", DesignTokens.FontUI)
this.lblTargetHeading := g.Add("Text", Format("x{1} y130 w{2} h20", ix + 20, iw - 40), "Target: (None)")
g.SetFont("s8 Norm", DesignTokens.FontUI)
this.lblTargetWithin := g.Add("Text", Format("x{1} y152 w{2} h18", ix + 20, iw - 40), "Within: Active Window")
this.lblTargetMethod := g.Add("Text", Format("x{1} y170 w{2} h18", ix + 20, iw - 40), "Method: UI Automation | Find using: Name + Type")
this.lblTargetReliability := g.Add("Text", Format("x{1} y188 w{2} h18", ix + 20, iw - 40), "Reliability: Strong | Matches now: 1")
this.lblTargetRelReason := g.Add("Text", Format("x{1} y206 w{2} h26", ix + 20, iw - 40), "Uses stable semantic UIA attributes.")
g.SetFont("s9 Norm", DesignTokens.FontUI)
; Prominent Target Card Action Buttons (Test, Preview, Change, Upgrade, Fallbacks, Anchor)
this.btnTargetTest := g.Add("Button", Format("x{1} y234 w56 h25", ix + 18), "Test")
this.btnTargetTest.OnEvent("Click", (*) => this.CmdTestCurrentTarget())
this.btnTargetHighlight := g.Add("Button", "x+4 y234 w230 h25", "Check this step — no clicks")
this.btnTargetHighlight.OnEvent("Click", (*) => this.CmdPreviewCurrentStep())
this.btnTargetChange := g.Add("Button", "x+4 y234 w64 h25", "Change")
this.btnTargetChange.OnEvent("Click", (*) => this.CmdPickTargetForCurrent("EditClick"))
this.btnTargetUpgrade := g.Add("Button", "x+4 y234 w68 h25", "Upgrade")
this.btnTargetUpgrade.OnEvent("Click", (*) => this.CmdUpgradeCurrentTarget())
this.btnTargetFallbacks := g.Add("Button", "x+4 y234 w68 h25", "Fallbacks")
this.btnTargetFallbacks.OnEvent("Click", (*) => this.ShowSelectorStrategiesDialog())
this.btnTargetAnchor := g.Add("Button", Format("x{1} y262 w166 h24", ix + 18), "Use an anchor…")
this.btnTargetAnchor.OnEvent("Click", (*) => this.ShowAnchorConfigDialog())
this.btnTargetPromote := g.Add("Button", "x+6 y262 w166 h24", "Save reusable target…")
this.btnTargetPromote.OnEvent("Click", (*) => this.CmdPromoteCurrentTarget())
; Primary Action Parameters (Contextual — Section 91)
this.lblParam1 := g.Add("Text", Format("x{1} y302 w95 h20 +0x200", ix + 12), "Click / Action:")
this.ddlParam1 := g.Add("DropDownList", Format("x{1} y300 w110 Choose1", ix + 110), ["Left", "Right", "Double", "Middle"])
this.ddlParam1.OnEvent("Change", ObjBindMethod(this, "_OnInspectorImmediateChange"))
this.btnCondBuilder := g.Add("Button", "x+6 y300 w125 h24", "Condition Builder...")
this.btnCondBuilder.OnEvent("Click", (*) => this.ShowConditionBuilderDialog())
this.lblParam2 := g.Add("Text", Format("x{1} y330 w95 h20 +0x200", ix + 12), "Text / Value:")
this.edtParam2 := g.Add("Edit", Format("x{1} y328 w{2} h24", ix + 110, iw - 122), "")
this.edtParam2.OnEvent("Change", ObjBindMethod(this, "_OnInspectorImmediateChange"))
this.lblBrowserProfile := g.AddText("Hidden", "Profile")
this.lblBrowserCtx := g.Add("Text", Format("x{1} y358 w95 h20 +0x200", ix + 12), "Session / Prof:")
this.ddlBrowserSession := g.Add("ComboBox", Format("x{1} y356 w115", ix + 110), ["MainBrowser", "Orders", "Source", "Destination"])
this.ddlBrowserSession.OnEvent("Change", ObjBindMethod(this, "_OnInspectorImmediateChange"))
this.ddlBrowserProfile := g.Add("ComboBox", "x+6 y356 w120", ["Default", "Work", "Personal", "Current"])
this.ddlBrowserProfile.OnEvent("Change", ObjBindMethod(this, "_OnInspectorImmediateChange"))
; Progressive Disclosure: Advanced ▸ (Sections 9 & 91)
this.btnToggleAdvanced := g.Add("Button", Format("x{1} y386 w{2} h24", ix + 12, iw - 24), "Advanced ▸ (Scope, Timeouts, Retries, Failure Policy)")
this.btnToggleAdvanced.OnEvent("Click", (*) => this.ToggleAdvancedInspector())
this.lblAdvScope := g.Add("Text", Format("x{1} y416 w60 h20 +0x200", ix + 12), "Scope:")
this.ddlAdvScope := g.Add("DropDownList", Format("x{1} y414 w185 Choose3", ix + 75), ["VirtualDesktop", "CurrentMonitor", "ActiveWindow", "SpecificWindow", "BrowserDocument", "BrowserWindow", "UIAContainer", "Region"])
this.ddlAdvScope.OnEvent("Change", ObjBindMethod(this, "_OnInspectorImmediateChange"))
this.btnPickRegion := g.Add("Button", "x+4 y414 w85 h24", "Pick Region")
this.btnPickRegion.OnEvent("Click", (*) => this.CmdPickTargetForCurrent("RegionCapture"))
this.lblAdvTimeout := g.Add("Text", Format("x{1} y444 w60 h20 +0x200", ix + 12), "Timeout:")
this.edtAdvTimeout := g.Add("Edit", Format("x{1} y442 w65 h22", ix + 75), "8000")
this.edtAdvTimeout.OnEvent("Change", ObjBindMethod(this, "_OnInspectorImmediateChange"))
this.lblAdvRetries := g.Add("Text", "x+8 y444 w48 h20 +0x200", "Retries:")
this.edtAdvRetries := g.Add("Edit", "x+2 y442 w42 h22", "1")
this.edtAdvRetries.OnEvent("Change", ObjBindMethod(this, "_OnInspectorImmediateChange"))
this.lblAdvFail := g.Add("Text", Format("x{1} y470 w75 h20 +0x200", ix + 12), "If this fails:")
this.ddlAdvFail := g.Add("DropDownList", Format("x{1} y468 w135 Choose1", ix + 90), ["Stop", "Skip", "Continue", "UseFallback", "AskRepair"])
this.ddlAdvFail.OnEvent("Change", ObjBindMethod(this, "_OnInspectorImmediateChange"))
this.btnApplyInspector := g.Add("Button", "x+6 y467 w115 h25", "Run Step Now")
this.btnApplyInspector.OnEvent("Click", (*) => this.app.CmdRunSelectedStep())
this.inspectorEditorControls := []
for control in g
if !previousControls.Has(control.Hwnd) && control != this.grpInspector
this.inspectorEditorControls.Push(control)
this._BuildActionStarter(g)
this._SetAdvancedControlsVisible(false)
}
_BuildBottomPane(g) {
this.bottomTab := g.Add("Tab3", "x8 y530 w1284 h215", ["Execution Log", "Problems & Suggestions", "Variables / Watch", "Browser Sessions", "Diagnostics"])
this.bottomTab.UseTab(1)
this.lvLogs := g.Add("ListView", "x16 y558 w1150 h175 Grid", ["Time", "Level", "Macro", "Step", "Action", "Result", "ms", "Retries", "Strategy", "Browser", "Message"])
this.lvLogs.ModifyCol(1, 75), this.lvLogs.ModifyCol(2, 48), this.lvLogs.ModifyCol(3, 85), this.lvLogs.ModifyCol(4, 38)
this.lvLogs.ModifyCol(5, 195), this.lvLogs.ModifyCol(6, 65), this.lvLogs.ModifyCol(7, 45), this.lvLogs.ModifyCol(8, 48)
this.lvLogs.ModifyCol(9, 110), this.lvLogs.ModifyCol(10, 95), this.lvLogs.ModifyCol(11, 310)
this.btnCopyLogs := g.Add("Button", "x1174 y558 w105 h28", "Copy Log")
this.btnCopyLogs.OnEvent("Click", (*) => (A_Clipboard := this.app.logger.FormatAsText(), this.ShowToast("Execution log copied to Clipboard.")))
this.btnClearLogs := g.Add("Button", "x1174 y592 w105 h28", "Clear Log")
this.btnClearLogs.OnEvent("Click", (*) => (this.app.logger.Clear(), this.lvLogs.Delete(), this.ShowToast("Log cleared.")))
this.bottomTab.UseTab(2)
this.lvProblems := g.Add("ListView", "x16 y558 w1150 h175 Grid -Multi AltSubmit", ["Severity", "Action ID", "Quick Fix", "Description (Select & click 'Fix / Apply' or double-click)"])
this.lvProblems.ModifyCol(1, 80), this.lvProblems.ModifyCol(2, 115), this.lvProblems.ModifyCol(3, 145), this.lvProblems.ModifyCol(4, 780)
this.lvProblems.OnEvent("ItemSelect", ObjBindMethod(this, "_OnProblemClick"))
this.lvProblems.OnEvent("DoubleClick", (*) => this.CmdFixSelectedProblem())
this.btnRefreshProblems := g.Add("Button", "x1174 y558 w105 h28", "Analyze Now")
this.btnRefreshProblems.OnEvent("Click", (*) => this.RefreshProblemsPanel())
this.btnFixProblem := g.Add("Button", "x1174 y592 w105 h28", "✨ Fix / Apply")
this.btnFixProblem.OnEvent("Click", (*) => this.CmdFixSelectedProblem())
this.bottomTab.UseTab(3)
this.lvVariables := g.Add("ListView", "x16 y558 w1150 h175 Grid -Multi", ["Variable Name", "Scope", "Current Value"])
this.lvVariables.ModifyCol(1, 220), this.lvVariables.ModifyCol(2, 110), this.lvVariables.ModifyCol(3, 780)
this.btnAddVar := g.Add("Button", "x1174 y558 w105 h28", "+ Set Variable")
this.btnAddVar.OnEvent("Click", (*) => this.ShowAddVariableDialog())
this.btnClearRuntimeVars := g.Add("Button", "x1174 y592 w105 h28", "Reset Runtime")
this.btnClearRuntimeVars.OnEvent("Click", (*) => (this.app.varStore.ClearRuntime(), this.RefreshVariablesPanel()))
this.bottomTab.UseTab(4)
this.lvBottomSessions := g.Add("ListView", "x16 y558 w1150 h175 Grid -Multi", ["Session Name", "Browser", "Requested Profile", "Effective Profile", "HWND", "Title / URL", "Status"])
this.lvBottomSessions.ModifyCol(1, 120), this.lvBottomSessions.ModifyCol(2, 80), this.lvBottomSessions.ModifyCol(3, 130)
this.lvBottomSessions.ModifyCol(4, 150), this.lvBottomSessions.ModifyCol(5, 85), this.lvBottomSessions.ModifyCol(6, 420), this.lvBottomSessions.ModifyCol(7, 90)
this.btnMgrProfiles := g.Add("Button", "x1174 y558 w105 h28", "Profiles...")
this.btnMgrProfiles.OnEvent("Click", (*) => this.ShowBrowserProfilesDialog())
this.btnInspectBrowser := g.Add("Button", "x1174 y592 w105 h28", "Choose / Tabs...")
this.btnInspectBrowser.OnEvent("Click", (*) => this.ShowBrowserInspectorDialog())
this.bottomTab.UseTab(5)
this.lvDiagnostics := g.Add("ListView", "x16 y558 w1150 h175 Grid -Multi", ["Status", "Diagnostic Check", "Details"])
this.lvDiagnostics.ModifyCol(1, 140), this.lvDiagnostics.ModifyCol(2, 340), this.lvDiagnostics.ModifyCol(3, 640)
this.btnRunDiag := g.Add("Button", "x1174 y558 w105 h32", "Run Diagnostics")
this.btnRunDiag.OnEvent("Click", (*) => this.CmdRunDiagnosticsUI())
this.bottomTab.UseTab()
}
; ==========================================================================
; RESPONSIVE ADAPTIVE LAYOUT ENGINE (Sections 80–84)
; Adapts cleanly to Wide (>=1140), Standard (820–1139), and Compact (<820)
; ==========================================================================
_OnMainGuiSize(guiObj, minMax, clientW, clientH) {
if minMax == -1 ; Minimized
return
if minMax == 0 {
guiObj.GetPos(&wx, &wy)
this.app.persistence.settings["WindowX"] := wx
this.app.persistence.settings["WindowY"] := wy
}
this.app.persistence.settings["WindowW"] := clientW
this.app.persistence.settings["WindowH"] := clientH
this.app.persistence.ClampLayoutMetrics(clientW, clientH)
this.pendingLayoutSize := [clientW, clientH]
if !this.HasOwnProp("resizeTimer")
this.resizeTimer := ObjBindMethod(this, "_ApplyPendingResize")
if !this.HasOwnProp("resizePending") || !this.resizePending {
this.resizePending := true
SetTimer(this.resizeTimer, -33)
}
}
HasLiveMainWindow() {
try return IsObject(this.mainGui) && DllCall("IsWindow","Ptr",this.mainGui.Hwnd)
catch
return false
}
_ApplyPendingResize() {
this.resizePending := false
if !this.HasLiveMainWindow()
return
this.layoutMgr.ApplyLayout(this.pendingLayoutSize[1], this.pendingLayoutSize[2])
}
_OnPanePointerDown(wParam, lParam, msg, hwnd) {
if !this.HasLiveMainWindow() || DllCall("GetAncestor","Ptr",hwnd,"UInt",2,"Ptr") != this.mainGui.Hwnd
return
if hwnd == this.logSplitter.Hwnd {
MouseGetPos(&x, &y)
this.bottomTab.GetPos(,,, &height)
this.paneDrag := {key:"LogPanelHeight", start:y, width:height, lastWidth:height}
this.paneDragTimer := ObjBindMethod(this, "_PaneDragTick")
SetTimer(this.paneDragTimer, 33)
return
}
if hwnd != this.leftSplitter.Hwnd && hwnd != this.rightSplitter.Hwnd
return
MouseGetPos(&x, &y)
key := hwnd == this.leftSplitter.Hwnd ? "NavPaneWidth" : "InspectorPaneWidth"
control := key == "NavPaneWidth" ? this.leftTab : this.grpInspector
control.GetPos(,, &width)
this.paneDrag := {key:key, start:x, width:width, lastWidth:width}
this.paneDragTimer := ObjBindMethod(this, "_PaneDragTick")
SetTimer(this.paneDragTimer, 33)
}
_PaneDragTick() {
if !this.HasLiveMainWindow() {
SetTimer(this.paneDragTimer,0)
return
}
MouseGetPos(&x, &y)
delta := ((this.paneDrag.key == "LogPanelHeight" ? y : x)-this.paneDrag.start)*96/A_ScreenDPI
width := Round(this.paneDrag.width + (this.paneDrag.key == "NavPaneWidth" ? delta : -delta))
if width != this.paneDrag.lastWidth {
this.paneDrag.lastWidth := width
this.app.persistence.settings[this.paneDrag.key] := width
this._TriggerRelayout()
}
if !GetKeyState("LButton", "P") || GetKeyState("Escape", "P") {
SetTimer(this.paneDragTimer, 0)
this.app.persistence.SaveSettings()
}
}
_BeginWorkflowDrag(control, info) {
if this.HasOwnProp("workflowDragActive") && this.workflowDragActive
return
if this.edtSearchWorkflow.Value != "" || this.ddlFilterCat.Text != "All Categories" {
this.ShowToast("Clear workflow filters before dragging steps.")
return
}
row := NumGet(info, A_PtrSize*3, "Int")+1
if row < 1 || row > this.flattenedRows.Length || this.flattenedRows[row]["RowKind"] != "Action"
return
this.workflowDragActive := true
DllCall("SetCapture", "Ptr", this.lvWorkflow.Hwnd)
this.workflowDragId := this.flattenedRows[row]["Action"].Id
this.workflowDropId := ""
if !this.HasOwnProp("workflowDragTimer")
this.workflowDragTimer := ObjBindMethod(this, "_WorkflowDragTick")
SetTimer(this.workflowDragTimer, 20)
}
_WorkflowDragTick() {
if !this.HasLiveMainWindow() {
SetTimer(this.workflowDragTimer,0)
this.workflowDragActive := false
DllCall("ReleaseCapture")
return
}
if !this.workflowDragActive
return
marker := Buffer(16, 0), NumPut("UInt", 16, marker)
hit := Buffer(24, 0)
DllCall("GetCursorPos", "Ptr", hit)
DllCall("ScreenToClient", "Ptr", this.lvWorkflow.Hwnd, "Ptr", hit)
index := SendMessage(0x1039, 0, hit.Ptr, this.lvWorkflow.Hwnd)
this.workflowDropId := ""
if index >= 0 && index < this.flattenedRows.Length {
row := this.flattenedRows[index+1]
if row["RowKind"] == "Action" {
rect := Buffer(16, 0)
SendMessage(0x100E, index, rect.Ptr, this.lvWorkflow.Hwnd)
this.workflowDropAfter := NumGet(hit, 4, "Int") > (NumGet(rect, 4, "Int")+NumGet(rect, 12, "Int"))/2
this.workflowDropId := row["Action"].Id
NumPut("UInt", this.workflowDropAfter ? 1 : 0, marker, 4)
NumPut("Int", index, marker, 8)
}
}
if !GetKeyState("LButton", "P") || GetKeyState("Escape", "P") {
SetTimer(this.workflowDragTimer, 0)
this.workflowDragActive := false
DllCall("ReleaseCapture")
NumPut("Int", -1, marker, 8)
SendMessage(0x10A6, 0, marker.Ptr, this.lvWorkflow.Hwnd)
if !GetKeyState("Escape", "P") && this.workflowDropId != ""
this.DropWorkflowAction(this.workflowDragId, this.workflowDropId, this.workflowDropAfter)
return
}
if this.workflowDropId == ""
NumPut("Int", -1, marker, 8)
SendMessage(0x10A6, 0, marker.Ptr, this.lvWorkflow.Hwnd)
}
DropWorkflowAction(sourceId, destinationId, after := false) {
actions := this.app.project.GetActiveMacro().Actions
source := WorkflowTree.FindById(actions, sourceId)
destination := WorkflowTree.FindById(actions, destinationId)
if !IsObject(source) || !IsObject(destination) || sourceId == destinationId
return false
action := source["Action"]
if IsObject(WorkflowTree.FindById(action.Children, destinationId)) || IsObject(WorkflowTree.FindById(action.ElseChildren, destinationId)) {
this.ShowToast("A block cannot be moved inside itself.")
return false
}
this.app.undoMgr.RecordSnapshot(this.app.project, "Drag reorder action")
source["ParentArray"].RemoveAt(source["Index"])
destination := WorkflowTree.FindById(actions, destinationId)
destination["ParentArray"].InsertAt(destination["Index"] + (after ? 1 : 0), action)
this.selectedActionId := action.Id
this.app.project.IsDirty := true
this.RefreshAll()
return true
}
_TriggerRelayout() {
this.mainGui.GetClientPos(, , &cw, &ch)
this.layoutMgr.ApplyLayout(cw, ch)
}
ToggleContextPanel() {
s := this.app.persistence.settings
s["ShowContextPanel"] := !s.Get("ShowContextPanel", false)
this.app.persistence.SaveSettings()
this._TriggerRelayout()
}
PerformResponsiveLayout(clientW, clientH, mode) {
pad := DesignTokens.GapSM
toolbar := [this.btnRecord, this.btnPlay, this.btnUndo, this.btnRedo, this.btnStop, this.btnAddAction, this.btnPickTarget, this.btnReview, this.btnExport, this.btnToggleLog]
tx := pad, ty := 6
for ctrl in toolbar {
ctrl.GetPos(, , &tw)
if tx + tw > clientW - pad {
tx := pad, ty += 32
}
ctrl.Move(tx, ty)
tx += tw + 4
}
this.stateBadgeCtrl.Visible := false
this.toastCtrl.Visible := false
topY := ty + 34
contextVisible := this.app.persistence.settings.Get("ShowContextPanel", false)
this.bottomTab.Visible := contextVisible
bottomH := contextVisible ? Clamp(this.app.persistence.settings.Get("LogPanelHeight", 200), 96, Max(96, clientH-topY-250)) : 0
this.btnToggleLog.Text := contextVisible ? "▤ Hide log" : "▤ Show log"
this.logSplitter.Visible := contextVisible
mainH := Max(120, clientH - topY - bottomH - 36)
bottomY := topY + mainH + 6
if contextVisible
this.logSplitter.Move(pad, bottomY-6, clientW-2*pad, 6)
if mode == "Wide" {
leftW := Clamp(this.app.persistence.settings.Get("NavPaneWidth", DesignTokens.NavWidthWide), 150, Max(150, clientW-600))
rightW := Clamp(this.app.persistence.settings.Get("InspectorPaneWidth", DesignTokens.InspectorWidthWide), 280, Max(280, clientW-leftW-320))
centerX := pad + leftW + pad
centerW := Max(DesignTokens.MinWorkflowWidth, clientW - leftW - rightW - (pad * 4))
rightX := centerX + centerW + pad
this._SetLeftPaneVisible(true, pad, topY, leftW, mainH)
} else if mode == "Standard" {
leftW := Clamp(this.app.persistence.settings.Get("NavPaneWidth", DesignTokens.NavWidthStandard), 150, Max(150, clientW-600))
rightW := Clamp(this.app.persistence.settings.Get("InspectorPaneWidth", DesignTokens.InspectorWidthStandard), 280, Max(280, clientW-leftW-300))
centerX := pad + leftW + pad
centerW := Max(120, clientW - leftW - rightW - (pad * 4))
rightX := centerX + centerW + pad
this._SetLeftPaneVisible(true, pad, topY, leftW, mainH)
} else {
; Compact Mode: Hide left navigation column so Workflow & Inspector are never crushed
this._SetLeftPaneVisible(false, 0, 0, 0, 0)
rightW := Clamp(this.app.persistence.settings.Get("InspectorPaneWidth", 310), 260, Max(260, clientW-310))
centerX := pad
centerW := Max(280, clientW - rightW - (pad * 3))
rightX := centerX + centerW + pad
}
this.leftSplitter.Visible := mode != "Compact"
if mode != "Compact"
this.leftSplitter.Move(centerX-pad+1, topY, 6, mainH)
this.rightSplitter.Move(rightX-pad+1, topY, 6, mainH)
; Reposition Center Workflow controls
reviewW := 215
try {
this.emptyBannerText.Move(centerX, topY + 2, Max(120, centerW - reviewW - 6), 24)
this.reviewBannerBtn.Move(centerX + centerW - reviewW, topY, reviewW, 26)
this.edtSearchWorkflow.Move(centerX, topY + 28, Max(90, centerW//2-4))
this.ddlFilterCat.Move(centerX + centerW//2, topY + 28, Max(90, centerW//2))
quick := [this.btnQuickClick, this.btnQuickType, this.btnQuickWait, this.btnQuickBrowser, this.btnQuickLogic]
for i, ctrl in quick
ctrl.Move(centerX+(i-1)*centerW//5, topY+56, Max(40, centerW//5-3), 25)
this.lvWorkflow.Move(centerX, topY + 86, centerW, Max(30, mainH - 86))
}
; Reposition Right Inspector controls
this.inspectorBounds := [rightX, topY, rightW, mainH]
this._MoveInspectorPane(rightX, topY, rightW, mainH)
; Reposition Bottom Pane
totalBottomW := clientW - (pad * 2)
lvBottomW := Max(300, totalBottomW - 135)
lvBottomH := Max(25, bottomH - 36)
btnX := pad + lvBottomW + 10
try {
this.bottomTab.Move(pad, bottomY, totalBottomW, bottomH)
for _, lv in [this.lvLogs, this.lvProblems, this.lvVariables, this.lvBottomSessions, this.lvDiagnostics]
lv.Move(pad + 8, bottomY + 28, lvBottomW, lvBottomH)
this.btnCopyLogs.Move(btnX, bottomY + 28)
this.btnClearLogs.Move(btnX, bottomY + 62)
this.btnRefreshProblems.Move(btnX, bottomY + 28)
this.btnFixProblem.Move(btnX, bottomY + 62)
this.btnAddVar.Move(btnX, bottomY + 28)
this.btnClearRuntimeVars.Move(btnX, bottomY + 62)
this.btnMgrProfiles.Move(btnX, bottomY + 28)
this.btnInspectBrowser.Move(btnX, bottomY + 62)
this.btnRunDiag.Move(btnX, bottomY + 28)
this.statusBar.SetText(" Layout: " mode " (" clientW "×" clientH ")", 3)
}
}
FitLastColumn(list) {
count := list.GetCount("Column")
if count < 1
return
rect := Buffer(16,0)
DllCall("GetClientRect","Ptr",list.Hwnd,"Ptr",rect)
available := NumGet(rect,8,"Int")-4
Loop count-1
available -= SendMessage(0x101D,A_Index-1,0,list.Hwnd)
list.ModifyCol(count,Max(55,Floor(available/(A_ScreenDPI/96))))
}
_SetLeftPaneVisible(vis, x, y, w, h) {
ctrls := [this.leftTab, this.lvMacros, this.btnAddMacro, this.btnMacroCfg, this.btnDelMacro,
this.lvReusableTargets, this.btnAddReusable, this.btnTestReusable, this.btnRepairReusable,
this.lvLeftSessions, this.btnLaunchProfLeft, this.btnAttachLeft]
for _, c in ctrls
try c.Visible := vis
if !vis
return
try {
this.leftTab.Move(x, y, w, h)
lvW := Max(120, w - 16)
lvH := Max(100, h - 68)
for _, lv in [this.lvMacros, this.lvReusableTargets, this.lvLeftSessions]
lv.Move(x + 8, y + 30, lvW, lvH)
for lv in [this.lvMacros,this.lvReusableTargets,this.lvLeftSessions]
this.FitLastColumn(lv)
btnY := y + h - 32
bw3 := (lvW - 8) // 3
this.btnAddMacro.Move(x + 8, btnY, bw3, 25)
this.btnMacroCfg.Move(x + 8 + bw3 + 4, btnY, bw3, 25)
this.btnDelMacro.Move(x + 8 + (bw3 + 4) * 2, btnY, bw3, 25)
this.btnAddReusable.Move(x + 8, btnY, bw3, 25)
this.btnTestReusable.Move(x + 8 + bw3 + 4, btnY, bw3, 25)
this.btnRepairReusable.Move(x + 8 + (bw3 + 4) * 2, btnY, bw3, 25)
bw2 := (lvW - 6) // 2
this.btnLaunchProfLeft.Move(x + 8, btnY, bw2, 25)
this.btnAttachLeft.Move(x + 8 + bw2 + 6, btnY, bw2, 25)
}
}
_MoveInspectorPane(ix, iy, iw, ih) {
if this.HasOwnProp("inspectorHelp")
for icon in this.inspectorHelp
this.inspectorHelp[icon].Visible := false
if this.HasOwnProp("starterControls") {
empty := !IsObject(this.GetSelectedAction())
for control in this.starterControls
control.Visible := empty
for control in this.inspectorEditorControls
control.Visible := !empty
this._SetAdvancedControlsVisible(false)
this.grpInspector.Text := empty ? "Add an action" : "Action & Target Inspector"
if empty {
this.grpInspector.Move(ix, iy, iw, ih)
this.starterTitle.Move(ix+12, iy+22, iw-24, 22)
this.starterHint.Move(ix+12, iy+48, iw-24, 34)
this.starterSearch.Move(ix+12, iy+86, iw-88, 25)
this.starterClear.Move(ix+iw-70, iy+86, 58, 25)
this.starterCategory.Move(ix+12, iy+116, iw-24)
this.starterList.Move(ix+12, iy+148, iw-24, Max(48, ih-194))
this.starterList.ModifyCol(1, Max(120, iw-48))
this.starterAdd.Move(ix+12, iy+ih-38, iw-24, 28)
return
}
}
compact := ih < 450
details := [this.grpTargetCard, this.lblTargetWithin, this.lblTargetMethod, this.lblTargetReliability, this.lblTargetRelReason, this.btnTargetUpgrade, this.btnTargetFallbacks, this.btnTargetAnchor, this.btnTargetPromote, this.lblParam1, this.ddlParam1, this.btnCondBuilder, this.lblParam2, this.edtParam2, this.lblBrowserCtx, this.ddlBrowserSession, this.ddlBrowserProfile, this.lblBrowserProfile]
for ctrl in details
ctrl.Visible := !compact
if compact {
this.grpInspector.Move(ix, iy, iw, ih)
this.lblInspStepTitle.Move(ix+12, iy+20, iw-24, 20)
this.ddlInspActionType.Move(ix+12, iy+44, iw-24)
this.chkInspEnabled.Move(ix+12, iy+76)
this.chkInspBreakpoint.Text := "Pause here"
this.chkInspBreakpoint.Move(ix+100, iy+76, 90)
if this.HasOwnProp("inspectorHelp") {
this.inspectorHelp["pause"].Move(ix+194, iy+74, 22, 22)
this.inspectorHelp["pause"].Visible := true
}
this.lblTargetHeading.Move(ix+12, iy+104, iw-24, 38)
bw := (iw-30)//3
this.btnTargetTest.Move(ix+12, iy+148, bw, 25)
this.btnTargetTest.Visible := false
this.btnTargetHighlight.Move(ix+12, iy+148, bw*2+3, 25)
this.btnTargetChange.Move(ix+18+2*bw, iy+148, bw, 25)
this.btnToggleAdvanced.Move(ix+12, iy+182, iw-24, 30)
return
}
try {
this.grpInspector.Move(ix, iy, iw, ih)
this.lblInspStepTitle.Move(ix + 12, iy + 20, iw - 24, 20)
this.ddlInspActionType.Move(ix + 12, iy + 42, iw - 24)
this.chkInspEnabled.Move(ix + 12, iy + 74, 70)
this.chkInspBreakpoint.Text := "Pause here"
this.chkInspBreakpoint.Move(ix + 100, iy + 74, 90)
this.grpTargetCard.Move(ix + 10, iy + 100, iw - 20, 182)
this.lblTargetHeading.Move(ix + 18, iy + 118, iw - 36, 20)
this.lblTargetWithin.Move(ix + 18, iy + 140, iw - 36, 18)
this.lblTargetMethod.Move(ix + 18, iy + 158, iw - 36, 18)
this.lblTargetReliability.Move(ix + 18, iy + 176, iw - 36, 18)
this.lblTargetRelReason.Move(ix + 18, iy + 194, iw - 36, 26)
btnW := Max(48, (iw - 40) // 3)
by1 := iy + 222
this.btnTargetTest.Visible := false
this.btnTargetHighlight.Move(ix + 16, by1, iw - 110, 24)
this.btnTargetChange.Move(ix + iw - 90, by1, 72, 24)
this.btnTargetUpgrade.Visible := false
this.btnTargetFallbacks.Visible := false
halfW := Max(90, (iw - 38) // 2)
this.btnTargetAnchor.Move(ix + 16, iy + 250, halfW, 24)
this.btnTargetPromote.Move(ix + 16 + halfW + 6, iy + 250, halfW, 24)
this.lblParam1.Move(ix + 12, iy + 290, 88, 20)
this.ddlParam1.Move(ix + 102, iy + 288, iw-142)
this.btnCondBuilder.Move(ix+iw-120, iy+406, 108, 28)
selected := this.GetSelectedAction()
this.btnCondBuilder.Text := IsObject(selected) && InStr("|Logic_If|Logic_While|Wait_Condition|", "|" selected.Type "|") ? "Edit condition…" : "Add condition…"
this.lblParam2.Move(ix + 12, iy + 318, 88, 20)
this.edtParam2.Move(ix + 102, iy + 316, Max(60, iw - 142), 24)
this.lblBrowserCtx.Move(ix+12, iy+346, 88, 20)
this.ddlBrowserSession.Move(ix+102, iy+344, iw-142)
this.lblBrowserProfile.Move(ix+12, iy+376, 88, 20)
this.ddlBrowserProfile.Move(ix+102, iy+374, iw-142)
this.btnToggleAdvanced.Move(ix+12, iy+406, iw-138, 28)
if this.HasOwnProp("inspectorHelp") {
positions := Map("pause", [ix+194, iy+72], "mode", [ix+iw-34, iy+288], "value", [ix+iw-34, iy+316], "session", [ix+iw-34, iy+344], "profile", [ix+iw-34, iy+374])
for name, point in positions {
this.inspectorHelp[name].Move(point[1], point[2], 22, 22)
this.inspectorHelp[name].Visible := true
}
}
this.lblAdvScope.Move(ix + 12, iy + 404, 55, 20)
this.ddlAdvScope.Move(ix + 70, iy + 402, Max(110, iw - 165))
this.btnPickRegion.Move(ix + iw - 90, iy + 402, 78, 24)
this.lblAdvTimeout.Move(ix + 12, iy + 432, 55, 20)
this.edtAdvTimeout.Move(ix + 70, iy + 430, 62, 22)
this.lblAdvRetries.Move(ix + 140, iy + 432, 48, 20)
this.edtAdvRetries.Move(ix + 190, iy + 430, 42, 22)
this.lblAdvFail.Move(ix + 12, iy + 458, 70, 20)
this.ddlAdvFail.Move(ix + 85, iy + 456, 120)
this.btnApplyInspector.Move(ix + 210, iy + 455, Max(90, iw - 222), 25)
if IsObject(selected) && (InStr(selected.Type,"OCR_") == 1 || InStr("|Wait_Duration|Wait_Clock|Logic_ForEach|Logic_Repeat|Key_TypeText|Macro_Comment|Logic_Label|Logic_Goto|", "|" selected.Type "|")) {
for control in [this.lblBrowserCtx,this.ddlBrowserSession,this.lblBrowserProfile,this.ddlBrowserProfile]
control.Visible := false
this.inspectorHelp["session"].Visible := false
this.inspectorHelp["profile"].Visible := false
this.btnToggleAdvanced.Move(ix+12,iy+350,iw-138,28)
this.btnCondBuilder.Move(ix+iw-120,iy+350,108,28)
}
}
}
OnWorkflowDoubleClick(ctrl, notification) {
; NMITEMACTIVATE begins with NMHDR, then zero-based item/subitem indexes.
this.EditWorkflowRow(ctrl, NumGet(notification,A_PtrSize*3,"Int")+1, NumGet(notification,A_PtrSize*3+4,"Int")+1)
}
EditWorkflowRow(ctrl, row, column := 0) {
if row < 1 || row > this.flattenedRows.Length || this.flattenedRows[row]["RowKind"] != "Action"
return
this.selectedActionId := this.flattenedRows[row]["Action"].Id
act := this.GetSelectedAction()
if column == 5 || column == 6 {
this.delayEditor := StepDelayUI(this,[act],column == 5 ? "DelayBeforeMs" : "DelayAfterMs")
return
}
if column == 7 {
this.labelEditor := ActionLabelUI(this,act)
return
}
if column == 3 || column == 8 {
this.settingsEditor := ActionSettingsUI(this,act,false,true,column == 3 ? "Target" : "Timing & recovery")
return
}
if InStr("|Logic_If|Logic_While|Wait_Condition|", "|" act.Type "|")
this.ShowConditionBuilderDialog()
else
this.ToggleAdvancedInspector()
}
ToggleAdvancedInspector() {
act := this.GetSelectedAction()
if IsObject(act)
this.settingsEditor := ActionSettingsUI(this, act)
else
this.ShowToast("Select a step first.")
}
AdjustSelectedDelay(field) {
actions := [], row := 0
while row := this.lvWorkflow.GetNext(row)
if row <= this.flattenedRows.Length && this.flattenedRows[row]["RowKind"] == "Action"
actions.Push(this.flattenedRows[row]["Action"])
if !actions.Length {
this.ShowToast("Select a step first.")
return
}
this.delayEditor := StepDelayUI(this,actions,field)
}
ShowRawActionJSON() {
act := this.GetSelectedAction()
if !IsObject(act) {
this.ShowToast("Select a step first.")
return
}
dlg := Gui("+Resize +Owner" this.mainGui.Hwnd, "Edit all action settings — " act.Type)
dlg.Add("Text", "x12 y12 w600 h44", "Advanced step settings (JSON): Parameters holds action values; Target holds coordinates/selectors. TimeoutMs, RetryCount, OnFailure and delays control execution. Keep quoted strings and valid JSON.")
edit := dlg.Add("Edit", "x12 y60 w600 h320 Multi WantTab HScroll", JsonCodec.Dump(act.ToMap()))
save := dlg.Add("Button", "x12 y392 w140 h28", "Apply settings")
save.OnEvent("Click", (*) => Apply())
dlg.OnEvent("Size", (g, state, w, h) => (edit.Move(12, 60, Max(100,w-24), Max(60,h-112)), save.Move(12, Max(125,h-40))))
dlg.Show("w624 h432")
Apply() {
try {
params := JsonCodec.Load(edit.Value)
if !(params is Map)
throw ValueError("Settings must be a JSON object.")
this.app.undoMgr.RecordSnapshot(this.app.project, "Edit all action settings")
edited := ActionModel.FromMap(params)
if !ActionRegistry.IsKnown(edited.Type)
throw ValueError("Unknown action type: " edited.Type)
if edited.TimeoutMs < 0 || edited.RetryCount < 0 || edited.DelayBeforeMs < 0 || edited.DelayAfterMs < 0
throw ValueError("Timing and retry settings must not be negative")
for key, value in edited.OwnProps() {
if key != "Id"
act.%key% := value
}
this.app.project.IsDirty := true
this.RefreshAll()
dlg.Destroy()
} catch as err {
MsgBox(err.Message, "Invalid action settings", "Iconx")
}
}
}
_SetAdvancedControlsVisible(vis) {
for c in [this.lblAdvScope, this.ddlAdvScope, this.btnPickRegion, this.lblAdvTimeout, this.edtAdvTimeout, this.lblAdvRetries, this.edtAdvRetries, this.lblAdvFail, this.ddlAdvFail, this.btnApplyInspector]
c.Visible := false
this.btnToggleAdvanced.Text := "⚙ Action settings…"
}
; ==========================================================================
; STATE, TOAST, & DATA REFRESH METHODS
; ==========================================================================
UpdateStateIndicator(newState) {
try {
this.stateBadgeCtrl.Value := "STATE: " StrUpper(newState)
this.statusBar.SetText(" State: " newState, 1)
this.btnRecord.Text := (newState == StudioConstants.StateRecording) ? "■ Stop Rec (F3)" : "● Record (F3)"
this.btnPlay.Text := newState == StudioConstants.StatePaused ? "▶ Resume" : (newState == StudioConstants.StateRunning ? "Ⅱ Pause" : "▶ Play (F1)")
}
}
ShowToast(msg, durationMs := 4500) {
try {
this.toastCtrl.Value := msg
this.statusBar.SetText(" " msg, 4)
}
}
RefreshAll() {
this.RefreshTitleBar()
this.RefreshMacrosList()
this.RefreshReusableTargetsList()
this.RefreshWorkflowList()
this.RefreshInspector()
this.RefreshProblemsPanel()
this.RefreshVariablesPanel()
this.RefreshSessionsPanels()
}
RefreshTitleBar() {
if !IsObject(this.mainGui) || !IsObject(this.app.project)
return
dirtyMark := this.app.project.IsDirty ? " *" : ""
pathInfo := this.app.project.FilePath != "" ? " (" this.app.project.FilePath ")" : ""
this.mainGui.Title := StudioConstants.AppName " — " this.app.project.Name . dirtyMark . pathInfo
}
RefreshMacrosList() {
if !IsObject(this.lvMacros)
return
this.lvMacros.Delete()
prj := this.app.project
for idx, m in prj.Macros {
sel := (m.Id == prj.ActiveMacroId) ? "Select Focus" : ""
this.lvMacros.Add(sel, m.Name, m.TriggerHotkey != "" ? m.TriggerHotkey : "(None)", m.BrowserDefault " · " m.DefaultProfileAlias)
}
}
RefreshReusableTargetsList() {
if !IsObject(this.lvReusableTargets)
return
this.lvReusableTargets.Delete()
for _, rt in this.app.project.ReusableTargets {
this.lvReusableTargets.Add("", rt.Name, rt.Role, rt.ReliabilityRating)
}
}
RefreshWorkflowList() {
if !IsObject(this.lvWorkflow)
return
mac := this.app.project.GetActiveMacro()
this.flattenedRows := WorkflowTree.Flatten(mac.Actions, false)
; Update Review / Upgrade banner count
upgrades := RecordingAnalyzer.AnalyzeMacro(mac, this.app.uiaEngine, this.app.browserMgr)
this.reviewBannerBtn.Text := Format("✨ {1} recommended upgrades", upgrades.Length)
if mac.Actions.Length == 0 {
this.emptyBannerText.Value := "Create your first automation: Press F3 to Record naturally, click '+ Add Action', or Open Project."
} else {
this.emptyBannerText.Value := Format("Macro '{1}' — {2} action(s) | Browser: {3} ({4}) | Policy: {5}", mac.Name, mac.Actions.Length, mac.BrowserDefault, mac.DefaultProfileAlias, mac.ProfilePolicy)
}
q := StrLower(Trim(this.edtSearchWorkflow.Value))
catFilter := this.ddlFilterCat.Text
displayedRows := []
this.lvWorkflow.Opt("-Redraw")
try {
this.lvWorkflow.Delete()
selectedRowIdx := 0
displayIdx := 0
for _, row in this.flattenedRows {
act := row["Action"]
if row["RowKind"] == "ElseMarker" {
displayIdx += 1
indent := ""
Loop row["Depth"]
indent .= " "
displayedRows.Push(row)
this.lvWorkflow.Add("", "-", indent (act.Type == "Logic_TryCatch" ? "↳ On error" : "↳ Else"), "", "", "", "", "", "", "")
continue
}
desc := act.ComputeFriendlyDescription()
tCtx := ActionRegistry.UsesTarget(act.Type) && IsObject(act.Target) ? act.Target.GetWithinBreadcrumb() : ""
badges := act.GetBadgesText()
if InStr(act.Type,"OCR_") == 1 {
tCtx := StudioOCREngine.SourceLabel(act.Parameters,act.Target)
badges := act.Parameters.Get("OCRSource","Region")
}
if catFilter != "" && catFilter != "All Categories" && act.Category != catFilter
continue
if q != "" && !InStr(StrLower(desc " " tCtx " " badges " " act.Type " " ActionOptions.LabelName(act)), q)
continue
displayIdx += 1
indent := ""
Loop row["Depth"]
indent .= " "
prefix := act.IsContainerAction() ? (act.IsCollapsed ? "[+] " : "[-] ") : ""
waitInfo := act.WaitMode " (" (act.TimeoutMs // 1000) "s) / " act.OnFailure
selOpt := (act.Id == this.selectedActionId) ? "Select Focus" : ""
if selOpt != ""
selectedRowIdx := displayIdx
displayedRows.Push(row)
this.lvWorkflow.Add(selOpt, row["StepNumber"], indent . prefix . desc, tCtx, badges, StepDelayUI.Display(act.DelayBeforeMs), StepDelayUI.Display(act.DelayAfterMs), ActionOptions.LabelName(act), waitInfo, act.RuntimeStatus)
}
this.flattenedRows := displayedRows
if selectedRowIdx == 0
this.selectedActionId := ""
} finally {
this.lvWorkflow.Opt("+Redraw")
}
}
GetSelectedAction() {
mac := this.app.project.GetActiveMacro()
if this.selectedActionId != "" {
loc := WorkflowTree.FindById(mac.Actions, this.selectedActionId)
if IsObject(loc)
return loc["Action"]
}
return ""
}
RefreshInspector() {
previousCritical := A_IsCritical
Critical("On")
this.suppressInspectorEvents := true
try {
act := this.GetSelectedAction()
mac := this.app.project.GetActiveMacro()
usesTarget := IsObject(act) && (ActionRegistry.UsesTarget(act.Type) || InStr("|Logic_If|Logic_While|Wait_Condition|", "|" act.Type "|"))
this.btnTargetTest.Text := usesTarget && !this.HasTarget(act) ? "⌖ Choose target" : "Test target"
this.btnTargetPromote.Enabled := IsObject(act) && this.HasTarget(act)
this.btnTargetAnchor.Enabled := usesTarget && this.HasTarget(act) && InStr(act.Type,"OCR_") != 1
this.btnTargetTest.Enabled := usesTarget
this.btnTargetChange.Enabled := usesTarget
this.btnTargetChange.Text := IsObject(act) && SubStr(act.Type, 1, 4) == "Win_" ? "Choose window" : "Change target"
this.edtParam2.Enabled := true
this.ddlParam1.Enabled := true
this.btnTargetHighlight.Enabled := IsObject(act) && this.HasTarget(act)
if IsObject(act) && InStr(act.Type,"OCR_") == 1 {
source := act.Parameters.Get("OCRSource","Region")
needsTarget := source == "Region" || source == "Window"
this.btnTargetTest.Text := needsTarget && !this.HasTarget(act) ? "Choose " StrLower(source) "…" : "Test OCR…"
this.btnTargetTest.Enabled := true
this.btnTargetHighlight.Enabled := !needsTarget || this.HasTarget(act)
}
if !IsObject(act) {
this.lblInspStepTitle.Value := "No Step Selected"
this.lblTargetHeading.Value := "Select or add a step to inspect"
this.lblTargetWithin.Value := ""
this.lblTargetMethod.Value := ""
this.lblTargetReliability.Value := ""
this.lblTargetRelReason.Value := ""
return
}
this.lblInspStepTitle.Value := act.ComputeFriendlyDescription()
this.chkInspEnabled.Value := act.Enabled ? 1 : 0
this.chkInspBreakpoint.Value := act.Breakpoint ? 1 : 0
; Sync Action Type dropdown
for idx, def in ActionRegistry.GetDefinitions() {
if def["Type"] == act.Type {
this.ddlInspActionType.Choose(idx)
break
}
}
; Sync Target Card (Sections 25, 42, 48)
t := act.Target
if ActionRegistry.UsesTarget(act.Type) && IsObject(t) {
t.ComputeReliability()
this.lblTargetHeading.Value := t.GetHumanLabel()
this.lblTargetWithin.Value := "Within: " t.GetWithinBreadcrumb()
this.lblTargetMethod.Value := "Method: " t.GetMethodLabel() " | " (t.ManualBackups ? t.BackupTargets.Length " backup target(s)" : "Find: " t.PrimarySelector.GetFindUsingSummary())
matchStr := t.LastMatchCount >= 0 ? String(t.LastMatchCount) : "Untested"
this.lblTargetReliability.Value := "Reliability: " t.ReliabilityRating " | Health: " t.HealthStatus " | Matches: " matchStr
this.lblTargetRelReason.Value := t.ReliabilityReason
} else {
this.lblTargetHeading.Value := "No UI/Visual Target Required"
this.lblTargetWithin.Value := "Category: " act.Category
this.lblTargetMethod.Value := "Action Type: " act.Type
this.lblTargetReliability.Value := "Status: Configured"
this.lblTargetRelReason.Value := "Configure action parameters below."
}
; Sync Contextual Primary Parameters
p := act.Parameters
if InStr(act.Type,"OCR_") == 1 {
this.lblParam1.Value := "Read from:"
this._SetDdlItems(this.ddlParam1,act.Type == "OCR_ClickText" ? ["Region","Window","Desktop"] : ["Region","Window","Desktop","Image file","PDF page"],p.Get("OCRSource","Region"))
this.lblParam2.Value := act.Type == "OCR_ReadText" ? "Save to:" : "Find text:"
this.edtParam2.Value := act.Type == "OCR_ReadText" ? p.Get("OutputVar","OCRText") : p.Get("SearchText","")
this.lblTargetHeading.Value := "OCR source: " p.Get("OCRSource","Region")
this.lblTargetWithin.Value := StudioOCREngine.SourceLabel(p,act.Target)
this.lblTargetReliability.Value := "Test OCR to inspect actual recognition and matches."
this.lblTargetMethod.Value := "OCR · " p.Get("OCRLanguage","Automatic") " language · " p.Get("OCRSource","Region")
this.lblTargetRelReason.Value := "Use Test OCR to inspect recognition; Action settings includes matching and output options."
this.btnTargetChange.Text := p.Get("OCRSource","Region") == "Region" ? "Select region" : (p.Get("OCRSource","Region") == "Window" ? "Choose window" : "Source settings")
} else if act.Type == "Browser_ClickAndWaitNewTab" {
this.lblParam1.Value := "Switch Tab:"
this._SetDdlItems(this.ddlParam1, ["Yes", "No"], p.Get("SwitchToNewTab", true) ? "Yes" : "No")
this.lblParam2.Value := "URL Filter:"
this.edtParam2.Value := p.Get("ExpectedUrlContains", "")
} else if InStr(act.Type, "Click") {
this.lblParam1.Value := "Click Button:"
this._SetDdlItems(this.ddlParam1, ["Left", "Right", "Double", "Middle"], p.Get("Button", "Left"))
this.lblParam2.Value := "Click Method:"
this.edtParam2.Value := p.Get("ClickMethod", "Auto")
} else if act.Type == "Key_TypeText" || act.Type == "UIA_SetValue" || act.Type == "Browser_SetValue" {
this.lblParam1.Value := "Input Mode:"
this._SetDdlItems(this.ddlParam1, ["Auto", "ValuePattern", "SendText", "Paste"], p.Get("Method", "Auto"))
this.lblParam2.Value := "Text / Value:"
this.edtParam2.Value := p.Get("Text", "")
} else if act.Type == "Key_SendKeys" {
this.lblParam1.Value := "Send Mode:"
this._SetDdlItems(this.ddlParam1, ["Send", "ControlSend"], p.Get("UseControlSend", false) ? "ControlSend" : "Send")
this.lblParam2.Value := "Keys Syntax:"
this.edtParam2.Value := p.Get("Keys", "{Enter}")
} else if act.Type == "Browser_Navigate" || act.Type == "App_OpenURL" {
this.lblParam1.Value := "Wait Load:"
this._SetDdlItems(this.ddlParam1, ["Yes", "No"], p.Get("WaitForLoad", true) ? "Yes" : "No")
this.lblParam2.Value := "Target URL:"
this.edtParam2.Value := p.Get("URL", "https://example.com")
} else if act.Type == "Browser_SelectTab" || act.Type == "Browser_CloseTab" {
this.lblParam1.Value := "Match Mode:"
this._SetDdlItems(this.ddlParam1, ["Contains", "Exact", "StartsWith", "Regex"], p.Get("MatchMode", "Contains"))
this.lblParam2.Value := "Tab Title:"
this.edtParam2.Value := p.Get("TabTitle", "")
} else if act.Type == "Browser_ExtractLinks" {
this.lblParam1.Value := "Output Var:"
this._SetDdlItems(this.ddlParam1, ["PageLinks", "ExtractedLinks", "LinksList"], p.Get("OutputVar", "PageLinks"))
this.lblParam2.Value := "Filter Text:"
this.edtParam2.Value := p.Get("FilterText", "")
} else if act.Type == "Browser_FindText" {
this.lblParam1.Value := "Result Var:"
this._SetDdlItems(this.ddlParam1, ["FoundText", "MatchStatus"], p.Get("OutputVar", "FoundText"))
this.lblParam2.Value := "Find Text:"
this.edtParam2.Value := p.Get("SearchText", "")
} else if act.Type == "Wait_Duration" {
this.lblParam1.Value := "Wait Type:"
this._SetDdlItems(this.ddlParam1, [p.Get("DurationMode", "Fixed")], p.Get("DurationMode", "Fixed"))
this.ddlParam1.Enabled := false
this.lblParam2.Value := "Duration:"
this.edtParam2.Value := act.ComputeFriendlyDescription()
this.edtParam2.Enabled := false
} else if act.Type == "Wait_Element" {
this.lblParam1.Value := "Condition:"
this._SetDdlItems(this.ddlParam1, ["Appear", "Disappear", "Enabled", "TextContains", "ValueEquals"], p.Get("WaitCondition", "Appear"))
this.lblParam2.Value := "Expected Text:"
this.edtParam2.Value := p.Get("ExpectedText", "")
} else if act.Type == "Wait_FirstMatch" {
this.lblParam1.Value := "Outcome A:"
this._SetDdlItems(this.ddlParam1, ["ElementAppears", "TextAppears", "URLContains", "TitleContains"], p.Get("OutcomeAType", "ElementAppears"))
this.lblParam2.Value := "Or Text/URL B:"
this.edtParam2.Value := p.Get("OutcomeBValue", "Error")
} else if act.Type == "Wait_NewTab" {
this.lblParam1.Value := "Switch Tab:"
this._SetDdlItems(this.ddlParam1, ["Yes", "No"], p.Get("SwitchToNewTab", true) ? "Yes" : "No")
this.lblParam2.Value := "Title/URL Filter:"
this.edtParam2.Value := p.Get("TitleContains", "")
} else if act.Type == "Logic_If" || act.Type == "Logic_While" || act.Type == "Wait_Condition" {
this.lblParam1.Value := "Check:"
label := p.Get("ConditionType", "UIAExists")
for spec in GuidedConditionEditor.Specs()
if spec[1] == label {
label := spec[2]
break
}
this._SetDdlItems(this.ddlParam1, [label], label)
this.ddlParam1.Enabled := false
this.lblParam2.Value := "Edit check:"
this.edtParam2.Value := "Use Condition Builder →"
this.edtParam2.Enabled := false
} else if act.Type == "Logic_Repeat" {
this.lblParam1.Value := "Index Var:"
this._SetDdlItems(this.ddlParam1, ["LoopIndex", "i", "rowIdx"], p.Get("IndexVar", "LoopIndex"))
this.lblParam2.Value := "Repeat Count:"
this.edtParam2.Value := String(p.Get("Count", 3))
} else if SubStr(act.Type, 1, 4) == "Win_" {
this.lblParam1.Value := "Operation:"
this._SetDdlItems(this.ddlParam1, act.Type == "Win_State" ? ["Minimize", "Maximize", "Restore", "Close"] : [act.Type == "Win_Wait" ? "Wait" : (act.Type == "Win_MoveResize" ? "Move / resize" : "Activate")], p.Get("StateAction", "Activate"))
this.lblParam2.Value := "Window:"
this.edtParam2.Value := p.Get("WinTitle", "")
} else if act.Type == "Var_Set" {
this.lblParam1.Value := "Operation:"
this._SetDdlItems(this.ddlParam1, ["Assign", "Append", "Add", "Subtract", "Multiply"], p.Get("Operation", "Assign"))
this.lblParam2.Value := "$" p.Get("VarName", "MyVar") " = "
this.edtParam2.Value := String(p.Get("Value", ""))
} else {
this.lblParam1.Value := "Option:"
this._SetDdlItems(this.ddlParam1, ["Default"], "Default")
this.lblParam2.Value := "Settings:"
this.edtParam2.Value := "Open Action settings below"
this.edtParam2.Enabled := false
}
effSess := act.BrowserSession != "" ? act.BrowserSession : (IsObject(t) && t.SessionName != "" ? t.SessionName : mac.DefaultSessionName)
effProf := act.BrowserProfile != "" ? act.BrowserProfile : (IsObject(t) && t.ProfileAlias != "" ? t.ProfileAlias : mac.DefaultProfileAlias)
isInherited := (act.BrowserSession == "" || act.BrowserSession == mac.DefaultSessionName) && (act.BrowserProfile == "" || act.BrowserProfile == mac.DefaultProfileAlias)
this.lblBrowserCtx.Value := "Session:"
this.ddlBrowserSession.Text := effSess
this.ddlBrowserProfile.Text := effProf
if IsObject(act.Scope)
this._SetDdlItems(this.ddlAdvScope, ["VirtualDesktop", "CurrentMonitor", "ActiveWindow", "SpecificWindow", "BrowserDocument", "BrowserWindow", "UIAContainer", "Region"], act.Scope.ScopeType)
this.edtAdvTimeout.Value := String(act.TimeoutMs)
this.edtAdvRetries.Value := String(act.RetryCount)
this._SetDdlItems(this.ddlAdvFail, ["Stop", "Skip", "Continue", "UseFallback", "AskRepair"], act.OnFailure)
} finally {
if this.HasOwnProp("inspectorBounds")
this._MoveInspectorPane(this.inspectorBounds*)
else {
this.grpInspector.GetPos(&ix, &iy, &iw, &ih)
this._MoveInspectorPane(ix, iy, iw, ih)
}
this.suppressInspectorEvents := false
Critical(previousCritical)
}
}
_SetDdlItems(ddl, items, selectedVal) {
ddl.Delete()
ddl.Add(items)
chosen := 1
for i, item in items {
if item = selectedVal {
chosen := i
break
}
}
ddl.Choose(chosen)
}
_RunWorkflowShortcut(command) {
focused := DllCall("GetFocus", "Ptr")
if focused == this.lvWorkflow.Hwnd {
if command == "SelectAll"
this.lvWorkflow.Modify(0, "Select")
else
this.%command%()
this.lvWorkflow.Focus()
return
}
; Menu accelerators also fire in text inputs: preserve native editing.
if focused && RegExMatch(WinGetClass("ahk_id " focused), "i)^(Edit|RichEdit)") {
switch command {
case "SelectAll": SendMessage(0xB1, 0, -1, focused) ; EM_SETSEL
case "CmdCutStep": SendMessage(0x300, 0, 0, focused)
case "CmdCopyStep": SendMessage(0x301, 0, 0, focused)
case "CmdPasteStep": SendMessage(0x302, 0, 0, focused)
}
}
}
_OnWorkflowItemSelect(ctrl, item, selected) {
if !selected {
if !this.HasOwnProp("deselectTimer")
this.deselectTimer := ObjBindMethod(this, "_RefreshDeselectedInspector")
SetTimer(this.deselectTimer, -65)
return
}
if this.HasOwnProp("deselectTimer")
SetTimer(this.deselectTimer, 0)
if item < 1 || item > this.flattenedRows.Length
return
row := this.flattenedRows[item]
if row["RowKind"] == "ElseMarker"
return
this.selectedActionId := row["Action"].Id
this.RefreshInspector()
}
_RefreshDeselectedInspector() {
if !this.lvWorkflow.GetNext() {
this.selectedActionId := ""
this.RefreshInspector()
}
}
_OnInspectorActionTypeChange(ctrl, *) {
if this.suppressInspectorEvents
return
act := this.GetSelectedAction()
if !IsObject(act)
return
index := this.ddlInspActionType.Value
definitions := ActionRegistry.GetDefinitions()
if index >= 1 && index <= definitions.Length {
newType := definitions[index]["Type"]
if newType != act.Type {
this.app.undoMgr.RecordSnapshot(this.app.project, "Change Action Type")
act.Type := newType
act.Category := ActionRegistry.GetCategoryForType(newType)
act.Parameters := ActionRegistry.GetDefaultParams(newType)
act.FriendlyDescription := act.ComputeFriendlyDescription()
this.RefreshWorkflowList()
this.RefreshInspector()
}
}
}
_OnInspectorImmediateChange(ctrl, *) {
if this.suppressInspectorEvents
return
act := this.GetSelectedAction()
if !IsObject(act)
return
act.Enabled := this.chkInspEnabled.Value == 1
act.Breakpoint := this.chkInspBreakpoint.Value == 1
p := act.Parameters
p1 := this.ddlParam1.Text
p2 := this.edtParam2.Value
if InStr(act.Type,"OCR_") == 1 {
p["OCRSource"] := p1
p[act.Type == "OCR_ReadText" ? "OutputVar" : "SearchText"] := p2
} else if act.Type == "Browser_ClickAndWaitNewTab" {
p["SwitchToNewTab"] := (p1 == "Yes")
p["ExpectedUrlContains"] := p2
} else if InStr(act.Type, "Click") {
p["Button"] := p1
p["ClickMethod"] := p2 != "" ? p2 : "Auto"
} else if act.Type == "Key_TypeText" || act.Type == "UIA_SetValue" || act.Type == "Browser_SetValue" {
p["Method"] := p1
p["Text"] := p2
} else if act.Type == "Key_SendKeys" {
p["UseControlSend"] := (p1 == "ControlSend")
p["Keys"] := p2
} else if act.Type == "Browser_Navigate" || act.Type == "App_OpenURL" {
p["WaitForLoad"] := (p1 == "Yes")
p["URL"] := p2
} else if act.Type == "Browser_SelectTab" || act.Type == "Browser_CloseTab" {
p["MatchMode"] := p1
p["TabTitle"] := p2
} else if act.Type == "Browser_ExtractLinks" {
p["OutputVar"] := p1
p["FilterText"] := p2
} else if act.Type == "Browser_FindText" {
p["OutputVar"] := p1
p["SearchText"] := p2
} else if act.Type == "Wait_Duration" {
; Duration mode, range and units are edited together in Action settings.
} else if act.Type == "Wait_Element" {
p["WaitCondition"] := p1
p["ExpectedText"] := p2
} else if act.Type == "Wait_FirstMatch" {
p["OutcomeAType"] := p1
p["OutcomeBValue"] := p2
} else if act.Type == "Wait_NewTab" {
p["SwitchToNewTab"] := (p1 == "Yes")
p["TitleContains"] := p2
} else if act.Type == "Logic_If" || act.Type == "Logic_While" || act.Type == "Wait_Condition" {
; Guided condition editor owns these parameters. Other inspector edits must preserve them.
} else if act.Type == "Logic_Repeat" {
p["IndexVar"] := p1
if IsInteger(p2)
p["Count"] := Integer(p2)
} else if SubStr(act.Type, 1, 4) == "Win_" {
p["WinTitle"] := p2
if act.Type == "Win_State"
p["StateAction"] := p1
} else if act.Type == "Var_Set" {
p["Operation"] := p1
p["Value"] := p2
}
act.BrowserSession := Trim(this.ddlBrowserSession.Text)
act.BrowserProfile := Trim(this.ddlBrowserProfile.Text)
if IsObject(act.Scope)
act.Scope.ScopeType := this.ddlAdvScope.Text
if IsInteger(this.edtAdvTimeout.Value)
act.TimeoutMs := Integer(this.edtAdvTimeout.Value)
if IsInteger(this.edtAdvRetries.Value)
act.RetryCount := Integer(this.edtAdvRetries.Value)
act.OnFailure := this.ddlAdvFail.Text
act.FriendlyDescription := act.ComputeFriendlyDescription()
this.lblInspStepTitle.Value := act.FriendlyDescription
this.app.project.IsDirty := true
this.RefreshWorkflowList()
this.RefreshTitleBar()
}
; ==========================================================================
; WORKFLOW STEP EDIT COMMANDS
; ==========================================================================
ShowOCRMenu() {
menu := Menu()
for item in [["Read text → variable or list…","OCR_ReadText"],["Find text → matches…","OCR_FindText"],["Click text…","OCR_ClickText"],["Wait for text…","OCR_WaitText"]]
menu.Add(item[1],ObjBindMethod(this,"InsertWait",item[2]))
menu.Show()
}
ShowOCRPreview(act) {
try {
p := this.app.playback.ResolvedOptions(act.Parameters)
capture := StudioOCREngine.Capture(p,act.Target)
matches := p.Get("SearchText","") != "" ? StudioOCREngine.Matches(capture.result,p) : []
d := Gui("+Owner" this.mainGui.Hwnd,"OCR preview — no actions executed")
d.SetFont("s10", "Segoe UI")
d.AddText("x16 y16 w620 h40", capture.result.Words.Length " words · " matches.Length " matches · " capture.elapsed " ms · " (capture.screen ? "Screen coordinates" : "Image coordinates") ". Variables and clipboard are unchanged.")
d.AddEdit("x16 y64 w620 h260 Multi ReadOnly",capture.result.Text)
list := d.AddListView("x16 y340 w620 h150",["Match","X","Y","Width","Height"])
for row in StudioOCREngine.Rows(matches)
list.Add("",row["Text"],row["X"],row["Y"],row["Width"],row["Height"])
list.ModifyCol(1,290)
if capture.screen && matches.Length
d.AddButton("x16 y506 w160 h30","Highlight matches").OnEvent("Click",(*) => Highlight())
d.AddButton("x476 y506 w160 h30 Default","Close").OnEvent("Click",(*) => d.Destroy())
d.OnEvent("Escape",(*) => d.Destroy())
d.Show("w654 h552")
Highlight(*) {
for index, match in matches {
if index > 30
break
match.Highlight(1500)
}
}
} catch as err
MsgBox(err.Message,"OCR preview","Icon!")
}
ShowWaitMenu() => this.BuildWaitMenu().Show()
BuildWaitMenu() {
waitMenu := Menu()
waitMenu.Add("Duration… (fixed or random)", ObjBindMethod(this, "InsertWait", "Wait_Duration"))
waitMenu.Add("Time of day…", ObjBindMethod(this, "InsertWait", "Wait_Clock"))
waitMenu.Add()
screen := Menu()
for item in [["Element / text / enabled state…", "Wait_Element"], ["Window opens / closes / becomes active…", "Win_Wait"], ["Image appears / disappears…", "Wait_ImageColor"], ["Pixel color appears / disappears…", "PixelWait"]]
screen.Add(item[1], ObjBindMethod(this, "InsertWait", item[2]))
screen.Add("Text appears / disappears / changes (OCR)…", ObjBindMethod(this,"InsertWait","OCR_WaitText"))
waitMenu.Add("Screen or window", screen)
browser := Menu()
for item in [["Page ready / URL / title…", "Wait_PageLoad"], ["New tab…", "Wait_NewTab"], ["Either of two outcomes…", "Wait_FirstMatch"]]
browser.Add(item[1], ObjBindMethod(this, "InsertWait", item[2]))
waitMenu.Add("Browser", browser)
system := Menu()
for item in [["File exists…", "FileWait"], ["Process starts / closes…", "App_WaitProcess"], ["Program audio / silence…", "Audio_Wait"]]
system.Add(item[1], ObjBindMethod(this, "InsertWait", item[2]))
waitMenu.Add("Files, processes or audio", system)
waitMenu.Add()
waitMenu.Add("Custom condition… (variables, clipboard and more)", ObjBindMethod(this, "InsertWait", "Wait_Condition"))
waitMenu.Add("User confirmation…", ObjBindMethod(this, "InsertWait", "Wait_ManualCheckpoint"))
return waitMenu
}
InsertWait(type, *) {
if type == "FileWait"
return this.QuickInsertAction("Wait_Condition", false, Map("ConditionType", "FileExists"))
if type == "PixelWait"
return this.QuickInsertAction("Wait_ImageColor", false, Map("VisualKind", "PixelColor"))
return this.QuickInsertAction(type)
}
QuickInsertAction(actionType, pickTargetImmediately := false, initialParams := 0, browserContext := 0) {
mac := this.app.project.GetActiveMacro()
this.app.undoMgr.RecordSnapshot(this.app.project, "Add " actionType)
act := ActionModel(actionType)
if initialParams is Map
for key, value in initialParams
act.Parameters[key] := value
act.BrowserType := mac.BrowserDefault
act.BrowserProfile := mac.DefaultProfileAlias
act.BrowserSession := mac.DefaultSessionName
if browserContext is Map
for field in ["BrowserType", "BrowserProfile", "BrowserSession"]
if browserContext.Has(field)
act.%field% := browserContext[field]
if InStr(actionType,"OCR_") == 1
act.BrowserType := "", act.BrowserProfile := "", act.BrowserSession := ""
if initialParams is Map && initialParams.Get("VisualKind", "") != "" {
act.Target.TargetKind := initialParams["VisualKind"]
act.Parameters.Delete("VisualKind")
}
act.FriendlyDescription := act.ComputeFriendlyDescription()
WorkflowTree.InsertAction(mac.Actions, act, this.selectedActionId, "After")
this.selectedActionId := act.Id
this.RefreshAll()
if pickTargetImmediately
this.CmdPickTargetForCurrent("UIAAction")
else if act.Type == "Logic_If" || act.Type == "Logic_While" || act.Type == "Wait_Condition"
this.ShowConditionBuilderDialog()
else
this.ToggleAdvancedInspector()
return act
}
SelectedRootActions() {
actions := [], row := 0, skipDepth := -1
while row := this.lvWorkflow.GetNext(row) {
if row > this.flattenedRows.Length || this.flattenedRows[row]["RowKind"] != "Action"
continue
entry := this.flattenedRows[row]
if skipDepth >= 0 && entry["Depth"] > skipDepth
continue
actions.Push(entry["Action"])
skipDepth := entry["Action"].IsContainerAction() ? entry["Depth"] : -1
}
if !actions.Length && IsObject(act := this.GetSelectedAction())
actions.Push(act)
return actions
}
CmdDeleteStep() {
actions := this.SelectedRootActions()
if !actions.Length
return
this.app.undoMgr.RecordSnapshot(this.app.project, "Delete selected steps")
for act in actions
WorkflowTree.DeleteById(this.app.project.GetActiveMacro().Actions, act.Id)
this.app.project.IsDirty := true
this.selectedActionId := ""
this.RefreshAll()
this.ShowToast("Deleted " actions.Length " selected step(s), including their nested steps. Undo restores them.")
}
CmdDuplicateStep() {
act := this.GetSelectedAction()
if !IsObject(act)
return
this.app.undoMgr.RecordSnapshot(this.app.project, "Duplicate Step")
dup := act.Clone(true)
WorkflowTree.InsertAction(this.app.project.GetActiveMacro().Actions, dup, act.Id, "After")
this.selectedActionId := dup.Id
this.RefreshAll()
this.ShowToast("Duplicated step.")
}
CmdDuplicateAndChangeTarget() {
act := this.GetSelectedAction()
if !IsObject(act)
return
this.app.undoMgr.RecordSnapshot(this.app.project, "Duplicate & Change Target")
dup := act.Clone(true)
WorkflowTree.InsertAction(this.app.project.GetActiveMacro().Actions, dup, act.Id, "After")
this.selectedActionId := dup.Id
this.RefreshAll()
this.CmdPickTargetForCurrent("EditClick")
}
CmdCopyTargetOnly() {
act := this.GetSelectedAction()
if !IsObject(act) || !IsObject(act.Target)
return
this.clipboardTarget := act.Target.Clone()
this.ShowToast("Copied target '" act.Target.GetHumanLabel() "' to clipboard.")
}
CmdPasteTargetOnly() {
if !IsObject(this.clipboardTarget) {
this.ShowToast("No target copied yet. Use 'Copy Target Only' first.")
return
}
act := this.GetSelectedAction()
if !IsObject(act)
return
this.app.undoMgr.RecordSnapshot(this.app.project, "Paste Target")
this.clipboardTarget.CopyTargetingTo(act.Target)
act.ReusableTargetId := ""
act.Scope := act.Target.Scope.Clone()
act.FriendlyDescription := act.ComputeFriendlyDescription()
this.RefreshAll()
this.ShowToast("Pasted target '" act.Target.GetHumanLabel() "' into step.")
}
CmdCopyStep() {
this.clipboardActions := []
for act in this.SelectedRootActions()
this.clipboardActions.Push(act.Clone(true))
this.ShowToast("Copied " this.clipboardActions.Length " step(s).")
}
CmdCutStep() {
this.CmdCopyStep()
if this.clipboardActions.Length
this.CmdDeleteStep()
}
CmdPasteStep() {
if this.clipboardActions.Length == 0
return
this.app.undoMgr.RecordSnapshot(this.app.project, "Paste Step")
mac := this.app.project.GetActiveMacro()
for _, item in this.clipboardActions {
pasted := item.Clone(true)
WorkflowTree.InsertAction(mac.Actions, pasted, this.selectedActionId, "After")
this.selectedActionId := pasted.Id
}
this.RefreshAll()
this.ShowToast("Pasted step.")
}
CmdMoveStepUp() {
act := this.GetSelectedAction()
if !IsObject(act)
return
this.app.undoMgr.RecordSnapshot(this.app.project, "Move Step Up")
if WorkflowTree.MoveUp(this.app.project.GetActiveMacro().Actions, act.Id)
this.RefreshAll()
}
CmdMoveStepDown() {
act := this.GetSelectedAction()
if !IsObject(act)
return
this.app.undoMgr.RecordSnapshot(this.app.project, "Move Step Down")
if WorkflowTree.MoveDown(this.app.project.GetActiveMacro().Actions, act.Id)
this.RefreshAll()
}
CmdToggleStepEnabled() {
act := this.GetSelectedAction()
if !IsObject(act)
return
this.app.undoMgr.RecordSnapshot(this.app.project, "Toggle Step Enabled")
act.Enabled := !act.Enabled
this.RefreshAll()
}
CmdToggleBreakpoint() {
act := this.GetSelectedAction()
if !IsObject(act)
return
this.app.undoMgr.RecordSnapshot(this.app.project, "Toggle Breakpoint")
act.Breakpoint := !act.Breakpoint
this.app.project.IsDirty := true
this.RefreshAll()
this.ShowToast(act.Breakpoint ? "Breakpoint set." : "Breakpoint cleared.")
}
; ==========================================================================
; TARGET CARD OPERATIONS (Test, Preview, Highlight, Change, Upgrade, Promote)
; ==========================================================================
HasTarget(act) {
t := act.Target
return IsObject(t) && (t.WinHwnd || t.WinTitle != "" || t.WinExe != "" || t.ScreenX || t.ScreenY
|| t.PrimarySelector.AutomationId != "" || t.PrimarySelector.ElementName != "" || t.CapturedImagePath != "" || (t.Scope.ScopeType == "Region" && t.Scope.RegionW > 0 && t.Scope.RegionH > 0))
}
WrapSelected(type, loopMode := "While") {
ids := [], row := 0, skipDepth := -1
while row := this.lvWorkflow.GetNext(row) {
if row > this.flattenedRows.Length || this.flattenedRows[row]["RowKind"] != "Action"
continue
selected := this.flattenedRows[row]
if skipDepth >= 0 && selected["Depth"] > skipDepth
continue
skipDepth := selected["Action"].IsContainerAction() ? selected["Depth"] : -1
ids.Push(selected["Action"].Id)
}
if !ids.Length {
this.ShowToast("Select consecutive steps with Shift-click or Ctrl-click first.")
return
}
try {
root := this.app.project.GetActiveMacro().Actions
locations := []
for id in ids
locations.Push(WorkflowTree.FindById(root, id))
parent := locations[1]["ParentArray"], first := locations[1]["Index"]
for i, loc in locations {
if ObjPtr(loc["ParentArray"]) != ObjPtr(parent) || loc["Index"] != first+i-1
throw ValueError("Select consecutive steps at the same indentation level. A selected block includes all its children.")
}
this.app.undoMgr.RecordSnapshot(this.app.project, "Wrap selected steps")
block := ActionModel(type)
if type == "Logic_While"
block.Parameters["LoopMode"] := loopMode
Loop locations.Length
block.Children.Push(parent.RemoveAt(first))
parent.InsertAt(first, block)
this.selectedActionId := block.Id
this.app.project.IsDirty := true
this.RefreshAll()
if type == "Logic_If" || type == "Logic_While"
this.ShowConditionBuilderDialog()
else
this.ToggleAdvancedInspector()
} catch as err
MsgBox(err.Message, "Wrap steps", "Icon!")
}
CmdTestCurrentTarget() {
act := this.GetSelectedAction()
if IsObject(act) && InStr(act.Type,"OCR_") == 1 {
source := act.Parameters.Get("OCRSource","Region")
if (source == "Region" || source == "Window") && !this.HasTarget(act)
return this.CmdPickTargetForCurrent()
return this.ShowOCRPreview(act)
}
if IsObject(act) && !this.HasTarget(act) {
this.CmdPickTargetForCurrent()
return
}
if !IsObject(act) || !IsObject(act.Target)
return
res := this.app.uiaEngine.ResolveOnly(act.Target, 1800)
this.RefreshInspector()
this.RefreshProblemsPanel()
this.ShowToast(res["Found"] ? ("Target Test " res["Status"] " (" res["StrategyUsed"] " — " res["MatchCount"] " match, " res["ElapsedMs"] " ms)") : ("Target Test FAILED: " res["Message"]))
}
CmdPreviewCurrentStep() {
if !this.app._CanReplaceProject()
return this.ShowToast("Stop recording or playback before checking a step.")
act := this.GetSelectedAction()
if !IsObject(act)
return this.ShowToast("Select a step to check.")
canceled := false
d := Gui("+Owner" this.mainGui.Hwnd, "Check this step — no clicks")
d.SetFont("s10", DesignTokens.FontUI)
output := d.AddEdit("w650 r15 ReadOnly", "Checking target without executing the step…")
d.AddButton("w160 h30", "Cancel / Close").OnEvent("Click", (*) => (canceled := true, d.Destroy()))
d.OnEvent("Close", (*) => (canceled := true, d.Destroy()))
d.OnEvent("Escape", (*) => (canceled := true, d.Destroy()))
engine := UIATargetEngine("", this.app.imageEngine, this.app.browserMgr)
engine.cancelCheck := (*) => canceled
d.Show("NoActivate")
try {
result := engine.PreviewAction(act, 0, this.app.project)
if !canceled
output.Value := result["Summary"]
} catch as err {
if !canceled
output.Value := "The check could not complete: " err.Message "`r`nNo step was executed."
}
}
CmdHighlightCurrentTarget() {
act := this.GetSelectedAction()
if !IsObject(act) || !IsObject(act.Target)
return
res := this.app.uiaEngine.HighlightTarget(act.Target, 2200)
this.RefreshInspector()
this.ShowToast(res["Found"] ? "Highlighted target on screen." : "Could not highlight target: " res["Message"])
}
CmdAddVisualFallbackCurrent() {
act := this.GetSelectedAction()
if !IsObject(act) || !IsObject(act.Target)
return
this.app.undoMgr.RecordSnapshot(this.app.project, "Add Visual Fallback")
res := this.app.uiaEngine.CaptureVisualFallbackForTarget(act.Target)
this.RefreshAll()
this.ShowToast(res["Message"])
}
CmdTestSelectedStep() {
this.CmdTestCurrentTarget()
}
static OpenWindowChoices() {
choices := []
for hwnd in WinGetList() {
try {
title := WinGetTitle(hwnd)
if title == "" || WinGetPID(hwnd) == DllCall("GetCurrentProcessId")
continue
choices.Push(Map("Hwnd", hwnd, "Title", title, "Exe", WinGetProcessName(hwnd), "Class", WinGetClass(hwnd)))
}
}
return choices
}
ApplyWindowChoice(act, choice) {
hwnd := choice["Hwnd"]
if !WinExist("ahk_id " hwnd)
throw TargetError("That window has closed. Refresh the list and choose again.")
this.app.undoMgr.RecordSnapshot(this.app.project, "Choose window")
target := TargetModel(WinGetTitle(hwnd), "Window", "Window")
target.WinHwnd := hwnd
target.WinTitle := WinGetTitle(hwnd)
target.WinExe := WinGetProcessName(hwnd)
target.WinClass := WinGetClass(hwnd)
act.Target := target
act.Parameters["WinTitle"] := target.WinTitle " ahk_exe " target.WinExe " ahk_class " target.WinClass
act.FriendlyDescription := act.ComputeFriendlyDescription()
this.app.project.IsDirty := true
this.RefreshAll()
}
ShowOpenWindowChooser(act) {
d := Gui("+Owner" this.mainGui.Hwnd " +ToolWindow", "Choose an open window")
d.SetFont("s10", "Segoe UI")
d.AddText("w640", "Choose the application window for this step. Double-click a row to select it.")
list := d.AddListView("w640 r14 -Multi", ["Window", "Application"])
choices := []
refresh(*) {
choices := StudioGui.OpenWindowChoices()
list.Delete()
for choice in choices
list.Add("", choice["Title"], choice["Exe"])
list.ModifyCol(1, 440), list.ModifyCol(2, 180)
}
choose(*) {
row := list.GetNext()
if !row
return
try {
this.ApplyWindowChoice(act, choices[row])
d.Destroy()
} catch as err
MsgBox(err.Message, "Window unavailable", "Icon!")
}
list.OnEvent("DoubleClick", choose)
d.AddButton("w110 Default", "Choose").OnEvent("Click", choose)
d.AddButton("x+8 w110", "Refresh").OnEvent("Click", refresh)
d.AddButton("x+8 w110", "Cancel").OnEvent("Click", (*) => d.Destroy())
d.OnEvent("Escape", (*) => d.Destroy())
refresh()
d.Show()
}
CmdPickTargetForCurrent(purpose := "UIAAction") {
act := this.GetSelectedAction()
isOCR := IsObject(act) && (InStr(act.Type,"OCR_") == 1 || InStr(act.Parameters.Get("ConditionType",""),"OCR") == 1 || InStr(act.Parameters.Get("SecondConditionType",""),"OCR") == 1)
if isOCR {
source := act.Parameters.Get("OCRSource","Region")
if source == "Window"
return this.ShowOpenWindowChooser(act)
if source != "Region"
return this.ToggleAdvancedInspector()
purpose := "RegionCapture"
}
if IsObject(act) && SubStr(act.Type, 1, 4) == "Win_" {
this.ShowOpenWindowChooser(act)
return
}
this.app.selectionEngine.StartSelection(purpose, ObjBindMethod(this, "_OnTargetPickedForCurrent"))
}
_OnTargetPickedForCurrent(newTarget, purpose) {
if !IsObject(newTarget)
return
act := this.GetSelectedAction()
this.app.undoMgr.RecordSnapshot(this.app.project, "Pick Target")
if !IsObject(act) {
recTypes := ActionRegistry.GetRecommendedActionsForTarget(newTarget)
actType := recTypes.Length > 0 ? recTypes[1] : "UIA_Click"
act := ActionModel(actType)
WorkflowTree.InsertAction(this.app.project.GetActiveMacro().Actions, act)
this.selectedActionId := act.Id
}
if purpose == "RegionCapture" && IsObject(newTarget.Scope) {
act.Scope := newTarget.Scope.Clone()
act.Target.Scope := newTarget.Scope.Clone()
if InStr(act.Type,"OCR_") == 1 || InStr(act.Parameters.Get("ConditionType",""),"OCR") == 1 || InStr(act.Parameters.Get("SecondConditionType",""),"OCR") == 1
act.Target := newTarget
} else {
act.Target := newTarget
act.Scope := newTarget.Scope.Clone()
if act.Type == "Mouse_Click" && (newTarget.TargetKind == "UIA" || newTarget.TargetKind == "BrowserUIA") {
act.Type := newTarget.IsWebContent ? "Browser_Click" : "UIA_Click"
act.Category := ActionRegistry.GetCategoryForType(act.Type)
}
if newTarget.TargetKind == "Image" && InStr(act.Type,"Wait_") != 1 && !act.IsContainerAction() && InStr(act.Type,"OCR_") != 1 {
act.Type := "Image_Click"
act.Category := "Image & Pixel"
} else if newTarget.TargetKind == "PixelColor" && InStr(act.Type,"Wait_") != 1 && !act.IsContainerAction() && InStr(act.Type,"OCR_") != 1 {
act.Type := "Pixel_Click"
act.Category := "Image & Pixel"
}
}
for pattern in newTarget.SupportedPatterns {
if InStr(act.Type,"OCR_") == 1 || InStr(act.Type,"Wait_") == 1 || act.IsContainerAction()
continue
if InStr(pattern, "PreferredAction:") == 1 {
chosenType := SubStr(pattern, 17)
if ActionRegistry.IsKnown(chosenType) && act.Type != chosenType {
act.Type := chosenType
act.Category := ActionRegistry.GetCategoryForType(chosenType)
act.Parameters := ActionRegistry.GetDefaultParams(chosenType)
}
}
}
this.app.project.IsDirty := true
act.RecordingMeta["UpgradeAvailable"] := false
act.FriendlyDescription := act.ComputeFriendlyDescription()
this.RefreshAll()
this.ShowToast("Target updated: " newTarget.GetHumanLabel())
}
; Upgrade Target workflow (Section 27 & 139)
CmdUpgradeCurrentTarget() {
act := this.GetSelectedAction()
if !IsObject(act) || !IsObject(act.Target)
return
t := act.Target
initPt := (t.ScreenX != 0 || t.ScreenY != 0) ? Map("X", t.ScreenX, "Y", t.ScreenY) : ""
this.app.selectionEngine.StartSelection("UpgradeTarget", ObjBindMethod(this, "_OnTargetPickedForCurrent"), initPt)
}
CmdPromoteCurrentTarget() {
act := this.GetSelectedAction()
if !IsObject(act) || !IsObject(act.Target)
return
ib := InputBox("Enter a reusable name for this target:", "Save Reusable Target", "w340 h130", act.Target.Name != "" ? act.Target.Name : act.Target.GetHumanLabel())
if ib.Result == "Cancel" || Trim(ib.Value) == ""
return
this.app.undoMgr.RecordSnapshot(this.app.project, "Promote Reusable Target")
rt := this.app.project.PromoteTargetToReusable(act.Target, Trim(ib.Value))
act.ReusableTargetId := rt.Id
this.RefreshAll()
this.ShowToast("Saved reusable target '" rt.Name "'.")
}
; ==========================================================================
; RIGHT-CLICK CONTEXT MENU (Section 94)
; ==========================================================================
_OnMainGuiContextMenu(guiObj, ctrlObj, item, isRightClick, x, y) {
if ctrlObj != this.lvWorkflow
return
ctx := Menu()
ctx.Add("Action settings…", (*) => this.ToggleAdvancedInspector())
ctx.Add("Adjust wait before…", (*) => this.AdjustSelectedDelay("DelayBeforeMs"))
ctx.Add("Adjust wait after…", (*) => this.AdjustSelectedDelay("DelayAfterMs"))
wrap := Menu()
wrap.Add("Wrap selected in list loop", (*) => this.WrapSelected("Logic_ForEach"))
wrap.Add("Wrap selected in repeat loop", (*) => this.WrapSelected("Logic_Repeat"))
wrap.Add("Wrap selected in while loop", (*) => this.WrapSelected("Logic_While"))
wrap.Add("Wrap selected in until loop", (*) => this.WrapSelected("Logic_While", "Until"))
wrap.Add("Wrap selected in IF", (*) => this.WrapSelected("Logic_If"))
wrap.Add("Upgrade target", (*) => this.CmdUpgradeCurrentTarget())
wrap.Add("Test Step / Target (Resolve Only)`tCtrl+Enter", (*) => this.CmdTestSelectedStep())
wrap.Add("Check this step — no clicks", (*) => this.CmdPreviewCurrentStep())
wrap.Add("Change / Pick Target...", (*) => this.CmdPickTargetForCurrent("EditClick"))
wrap.Add("Upgrade Target to Semantic UIA...", (*) => this.CmdUpgradeCurrentTarget())
wrap.Add("+ Capture Visual Fallback for Target", (*) => this.CmdAddVisualFallbackCurrent())
ctx.Add("Wrap selected steps", wrap)
ctx.Add()
ctx.Add("Copy Target Only", (*) => this.CmdCopyTargetOnly())
ctx.Add("Paste Target Into Step", (*) => this.CmdPasteTargetOnly())
ctx.Add("Duplicate Step && Change Target...", (*) => this.CmdDuplicateAndChangeTarget())
ctx.Add("Batch Target Repair Queue...", (*) => this.ShowBatchRepairQueueDialog())
ctx.Add()
ctx.Add("Run This Step Only", (*) => this.app.CmdRunSelectedStep())
ctx.Add("Run From Here", (*) => this.app.CmdRunFromHere())
ctx.Add("Run To Here", (*) => this.app.CmdRunToHere())
ctx.Add()
ctx.Add("Record After This Step", (*) => this.app.CmdRecordAfterSelected())
ctx.Add("Insert Action After...", (*) => this.ShowAddActionPalette())
ctx.Add()
ctx.Add("Export Script…", (*) => this.app.CmdExportAhk())
ctx.Add("Build EXE…", (*) => this.app.CmdBuildExe())
ctx.Add()
ctx.Add("Duplicate`tCtrl+D", (*) => this.CmdDuplicateStep())
ctx.Add("Enable / Disable", (*) => this.CmdToggleStepEnabled())
ctx.Add("Toggle Breakpoint`tF9", (*) => this.CmdToggleBreakpoint())
ctx.Add()
ctx.Add("Cut`tCtrl+X", (*) => this.CmdCutStep())
ctx.Add("Copy`tCtrl+C", (*) => this.CmdCopyStep())
ctx.Add("Paste`tCtrl+V", (*) => this.CmdPasteStep())
ctx.Add("Delete`tDelete", (*) => this.CmdDeleteStep())
ctx.Show(x, y)
}
; ==========================================================================
; BOTTOM PANEL REFRESHERS & FIX-IT SURFACE (Sections 57, 68, 86)
; ==========================================================================
OnLogEntryAdded(entry) {
if !IsObject(this.lvLogs)
return
try {
this.lvLogs.Add("", entry["Time"], entry["Level"], entry["Macro"], entry["Step"], entry["Action"], entry["Result"], entry["Duration"], entry["Retries"], entry["Strategy"], entry["Browser"], entry["Message"])
cnt := this.lvLogs.GetCount()
if cnt > 0
this.lvLogs.Modify(cnt, "Vis")
}
}
RefreshProblemsPanel() {
if !IsObject(this.lvProblems)
return
this.lvProblems.Delete()
mac := this.app.project.GetActiveMacro()
density := this.app.persistence.settings.Get("SuggestionDensity", "Normal")
probs := WorkflowTree.ValidateTree(mac.Actions, density)
this.currentProblems := probs
for idx, pr in probs {
this.lvProblems.Add(idx == 1 ? "Select" : "", pr["Severity"], pr["ActionId"], pr.Get("FixLabel", "Inspect"), pr["Message"])
}
}
_OnProblemClick(ctrl, item, selected) {
if !selected || item < 1
return
actId := this.lvProblems.GetText(item, 2)
if actId != "" {
this.selectedActionId := actId
this.RefreshWorkflowList()
this.RefreshInspector()
}
}
CmdFixSelectedProblem() {
row := this.lvProblems.GetNext()
if row < 1 || row > this.currentProblems.Length {
this.ShowToast("Select a problem or suggestion in the Problems panel first.")
return
}
pr := this.currentProblems[row]
actId := pr["ActionId"]
fixCode := pr.Get("FixCode", "")
if actId != "" {
this.selectedActionId := actId
this.RefreshWorkflowList()
this.RefreshInspector()
}
act := this.GetSelectedAction()
if !IsObject(act)
return
if fixCode == "UpgradeToUIA" {
this.CmdUpgradeCurrentTarget()
} else if fixCode == "ConvertToSmartWait" {
this.app.undoMgr.RecordSnapshot(this.app.project, "Convert Sleep to Smart Wait")
dur := act.Parameters.Get("DurationMs", 3000)
act.Type := "Wait_Element"
act.Category := "Waits & Synchronization"
act.Parameters := ActionRegistry.GetDefaultParams("Wait_Element")
act.TimeoutMs := Max(3000, Integer(dur))
act.FriendlyDescription := act.ComputeFriendlyDescription()
this.RefreshAll()
this.ShowToast("Converted fixed sleep into Smart Wait_Element. Pick target if needed.")
} else if fixCode == "RepairTarget" {
this.CmdPickTargetForCurrent("EditClick")
} else if fixCode == "RefineAmbiguous" {
this.ShowAnchorConfigDialog()
} else if fixCode == "DeleteInvalidLoopJump" {
this.CmdDeleteStep()
} else if fixCode == "PromoteRepeatedTarget" {
this.CmdPromoteCurrentTarget()
} else {
this.ShowToast("Navigated to step for inspection.")
}
}
RefreshVariablesPanel() {
if !IsObject(this.lvVariables)
return
this.lvVariables.Delete()
entries := this.app.varStore.GetAllWatchEntries()
for _, e in entries {
this.lvVariables.Add("", e["Name"], e["Scope"], e["Value"])
}
}
RefreshSessionsPanels() {
if IsObject(this.lvLeftSessions)
this.lvLeftSessions.Delete()
if IsObject(this.lvBottomSessions)
this.lvBottomSessions.Delete()
for sName, sess in this.app.browserMgr.sessions {
health := this.app.browserMgr.GetSessionHealth(sName)
st := health["Status"]
if IsObject(this.lvLeftSessions)
this.lvLeftSessions.Add("", sName, sess["BrowserType"] " · " sess["EffectiveProfile"], st)
if IsObject(this.lvBottomSessions)
this.lvBottomSessions.Add("", sName, sess["BrowserType"], sess["RequestedProfile"], sess["EffectiveProfile"], sess["Hwnd"], sess["CurrentTitle"], st)
}
}
; ==========================================================================
; MACRO & REUSABLE TARGET PANEL HANDLERS
; ==========================================================================
_OnMacroSelect(ctrl, item, selected) {
if !selected || item < 1 || item > this.app.project.Macros.Length
return
chosenMac := this.app.project.Macros[item]
if chosenMac.Id != this.app.project.ActiveMacroId {
this.app.project.ActiveMacroId := chosenMac.Id
this.selectedActionId := ""
this.RefreshWorkflowList()
this.RefreshInspector()
this.RefreshProblemsPanel()
}
}
CmdAddMacro() {
ib := InputBox("Enter name for new macro:", "New Macro", "w320 h130", "Macro " (this.app.project.Macros.Length + 1))
if ib.Result == "Cancel" || Trim(ib.Value) == ""
return
this.app.undoMgr.RecordSnapshot(this.app.project, "Add Macro")
m := MacroModel(Trim(ib.Value))
this.app.project.Macros.Push(m)
this.app.project.ActiveMacroId := m.Id
this.RefreshAll()
this.ShowToast("Created macro '" m.Name "'.")
}
CmdDeleteMacro() {
if this.app.project.Macros.Length <= 1 {
this.ShowToast("Project must contain at least one macro.")
return
}
this.app.undoMgr.RecordSnapshot(this.app.project, "Delete Macro")
curId := this.app.project.ActiveMacroId
for idx, m in this.app.project.Macros {
if m.Id == curId {
this.app.project.Macros.RemoveAt(idx)
break
}
}
this.app.project.ActiveMacroId := this.app.project.Macros[1].Id
this.RefreshAll()
}
ShowMacroConfigDialog() {
mac := this.app.project.GetActiveMacro()
d := Gui("+Owner" this.mainGui.Hwnd " +ToolWindow", "Configure Macro & Browser Context — " mac.Name)
d.SetFont("s9", DesignTokens.FontUI)
d.MarginX := 14, d.MarginY := 12
d.Add("Text", "w145", "Macro Name:")
edtName := d.Add("Edit", "x+8 yp-2 w275", mac.Name)
d.Add("Text", "x14 y+10 w145", "Trigger Hotkey:")
hkCtrl := d.Add("Edit", "x+8 yp-2 w135", mac.TriggerHotkey)
d.AddButton("x+6 yp w64 h24", "Bind…").OnEvent("Click", (*) => ShortcutCaptureUI.Open(this.app, d, hkCtrl))
d.AddButton("x+6 yp w64 h24", "Clear").OnEvent("Click", (*) => hkCtrl.Value := "")
d.AddText("x14 y+8 w428 h32", "Runs this macro while Studio is open. Export run hotkeys are separate. AHK syntax: ^ Ctrl, ! Alt, + Shift, # Windows.")
d.Add("Text", "x14 y+10 w145", "Default Browser:")
ddlBrow := d.Add("DropDownList", "x+8 yp-2 w275", ["Edge", "Chrome", "Firefox", "Brave", "Vivaldi"])
this._SetDdlItems(ddlBrow, ["Edge", "Chrome", "Firefox", "Brave", "Vivaldi"], mac.BrowserDefault)
d.Add("Text", "x14 y+10 w145", "Default Profile Alias:")
cbProf := d.Add("ComboBox", "x+8 yp-2 w275", ["Default", "Work", "Personal", "Accounting", "QA", "Current"])
cbProf.Text := mac.DefaultProfileAlias
d.Add("Text", "x14 y+10 w145", "Default Session Name:")
edtSess := d.Add("Edit", "x+8 yp-2 w275", mac.DefaultSessionName)
d.Add("Text", "x14 y+10 w145", "If profile isn't available:")
policyCodes := ["PreferConfiguredThenCurrent", "PreferConfiguredThenDefault", "Strict", "CurrentBrowser", "DefaultProfile", "AnyCompatibleSession", "AskWhenAmbiguous", "CustomOrder"]
friendlyPolicies := []
for _, pc in policyCodes
friendlyPolicies.Push(StudioConstants.PolicyToFriendlyText(pc))
ddlPol := d.Add("DropDownList", "x+8 yp-2 w275", friendlyPolicies)
this._SetDdlItems(ddlPol, friendlyPolicies, StudioConstants.PolicyToFriendlyText(mac.ProfilePolicy))
btnTestRes := d.Add("Button", "x14 y+14 w150 h28", "Test Resolution")
btnChooseWin := d.Add("Button", "x+6 w155 h28", "Choose Live Window...")
btnOk := d.Add("Button", "x14 y+10 w110 h28 Default", "Save")
btnCancel := d.Add("Button", "x+8 w90 h28", "Cancel")
btnTestRes.OnEvent("Click", (*) => (
polCode := StudioConstants.FriendlyTextToPolicy(ddlPol.Text),
sim := this.app.browserMgr.SimulatePolicyResolution(Trim(edtSess.Value), ddlBrow.Text, Trim(cbProf.Text), polCode),
MsgBox(Format("Simulated Browser Resolution:`n`nOutcome : {1}`nBrowser : {2}`nProfile : {3}`nSession : {4}`n`nExplanation:`n{5}",
sim["ResolvedMode"], sim["EffectiveBrowser"], sim["EffectiveProfile"], Trim(edtSess.Value), sim["Summary"]), "Test Browser Resolution", "Iconi")
))
btnChooseWin.OnEvent("Click", (*) => (
d.Destroy(),
this.ShowChooseBrowserSessionDialog()
))
btnOk.OnEvent("Click", (*) => SaveMacro())
SaveMacro() {
try {
key := Trim(hkCtrl.Value)
if key != "" {
key := StudioOptionsUI.NormalizeKey(key)
for def in StudioOptionsUI.Hotkeys {
used := StudioOptionsUI.NormalizeKey(this.app.persistence.settings.Get(def[1], def[3]))
if key == used || (def[1] == "Hotkey_Stop" && RegExReplace(key, "^[\^!+#]+") == RegExReplace(used, "^[\^!+#]+"))
throw ValueError("That shortcut is used by Studio: " def[2])
}
recordKey := this.app.persistence.settings["Hotkey_Record"]
if !InStr(recordKey, "+") && key == StudioOptionsUI.NormalizeKey("+" recordKey)
throw ValueError("Shift + Record is reserved for advanced recording.")
for other in this.app.project.Macros
if other.Id != mac.Id && other.TriggerHotkey != "" && key == StudioOptionsUI.NormalizeKey(other.TriggerHotkey)
throw ValueError("That shortcut is used by macro: " other.Name)
}
this.app.undoMgr.RecordSnapshot(this.app.project, "Configure Macro")
mac.Name := Trim(edtName.Value) != "" ? Trim(edtName.Value) : mac.Name
mac.TriggerHotkey := key
mac.BrowserDefault := ddlBrow.Text
mac.DefaultProfileAlias := Trim(cbProf.Text)
mac.DefaultSessionName := Trim(edtSess.Value) != "" ? Trim(edtSess.Value) : "MainBrowser"
mac.ProfilePolicy := StudioConstants.FriendlyTextToPolicy(ddlPol.Text)
this.app.project.IsDirty := true
this.app.RegisterGlobalStudioHotkeys()
this.RefreshAll()
d.Destroy()
} catch as err
MsgBox(err.Message, "Check macro shortcut", "Icon!")
}
btnCancel.OnEvent("Click", (*) => d.Destroy())
d.Show("AutoSize Center")
}
CmdCaptureNewReusableTarget() {
this.app.selectionEngine.StartSelection("UIAAction", (t, *) => (
IsObject(t) ? (this.app.project.PromoteTargetToReusable(t), this.RefreshReusableTargetsList(), this.ShowToast("Captured reusable target: " t.Name)) : ""
))
}
SelectedReusableTargetId() {
selected := this.lvReusableTargets.GetNext()
index := 0
for id, target in this.app.project.ReusableTargets {
index++
if index == selected
return id
}
return ""
}
CmdTestSelectedReusableTarget() {
row := this.lvReusableTargets.GetNext()
if row < 1
return
selectedId := this.SelectedReusableTargetId()
tName := this.lvReusableTargets.GetText(row, 1)
for _, rt in this.app.project.ReusableTargets {
if rt.Id == selectedId {
res := this.app.uiaEngine.ResolveOnly(rt, 1800)
this.RefreshReusableTargetsList()
this.ShowToast(res["Found"] ? "Reusable target '" rt.Name "' PASSED (" res["MatchCount"] " match)." : "Reusable target FAILED: " res["Message"])
return
}
}
}
CmdRepairSelectedReusableTarget() {
row := this.lvReusableTargets.GetNext()
if row < 1
return
selectedId := this.SelectedReusableTargetId()
tName := this.lvReusableTargets.GetText(row, 1)
for id, rt in this.app.project.ReusableTargets {
if rt.Id == selectedId {
this.app.selectionEngine.StartSelection("UpgradeTarget", (newT, *) => (
IsObject(newT) ? (this.app.undoMgr.RecordSnapshot(this.app.project, "Repair Reusable Target"), newT.Id := id, newT.Name := tName, newT.IsReusable := true, this.app.project.ReusableTargets[id] := newT, this.app.project.IsDirty := true, this.RefreshAll(), this.ShowToast("Repaired reusable target '" tName "'.")) : ""
))
return
}
}
}
CmdFindReusableTargetUsages() {
row := this.lvReusableTargets.GetNext()
if row < 1
return
selectedId := this.SelectedReusableTargetId()
tName := this.lvReusableTargets.GetText(row, 1)
targetObj := ""
for _, rt in this.app.project.ReusableTargets {
if rt.Id == selectedId {
targetObj := rt
break
}
}
if !IsObject(targetObj)
return
usages := []
for _, mac in this.app.project.Macros {
flat := WorkflowTree.Flatten(mac.Actions, true)
for _, r in flat {
if r["RowKind"] != "Action"
continue
a := r["Action"]
if a.ReusableTargetId == targetObj.Id || (IsObject(a.Target) && a.Target.Name == targetObj.Name)
usages.Push(mac.Name " — Step #" r["StepNumber"] ": " a.ComputeFriendlyDescription())
}
}
usageTxt := usages.Length > 0 ? "" : "(Not currently referenced by any steps)"
for _, u in usages
usageTxt .= "• " u "`r`n"
ans := MsgBox("Reusable Target: " targetObj.Name "`nRole: " targetObj.Role " (" targetObj.ReliabilityRating ")`n`nUsages (" usages.Length "):`n" usageTxt "`nAssign this reusable target to the currently selected step?", "Reusable Target Usages", "YesNo Iconi")
if ans == "Yes" {
act := this.GetSelectedAction()
if IsObject(act) {
this.app.undoMgr.RecordSnapshot(this.app.project, "Assign Reusable Target")
targetObj.CopyTargetingTo(act.Target)
act.ReusableTargetId := targetObj.Id
act.FriendlyDescription := act.ComputeFriendlyDescription()
this.RefreshAll()
this.ShowToast("Assigned reusable target '" targetObj.Name "' to step.")
}
}
}
CmdQuickAttachBrowser() {
try {
sess := this.app.browserMgr.ResolveSession("MainBrowser", "Edge", "Current", "AnyCompatibleSession", false)
this.RefreshSessionsPanels()
this.ShowToast("Attached session '" sess["SessionName"] "' to " sess["BrowserType"] " (HWND " sess["Hwnd"] ").")
} catch as err {
MsgBox(err.Message, "Attach Browser Session", "Icon!")
}
}
; ==========================================================================
; DIALOG 1: SEARCHABLE ADD ACTION COMMAND PALETTE (Sections 92 & 93)
; ==========================================================================
ShowAddActionPalette() {
d := Gui("+Owner" this.mainGui.Hwnd " +ToolWindow", "Add an action")
d.SetFont("s9", DesignTokens.FontUI)
d.MarginX := 14, d.MarginY := 12
d.Add("Text", "w540", "Search actions. Right-click a result to add or remove it from Common actions.")
edtQ := d.Add("Edit", "w540 y+4 h26", "")
lv := d.Add("ListView", "w540 r14 y+8 Grid -Multi AltSubmit", ["Action Name", "Category", "Action ID"])
lv.ModifyCol(1, 335), lv.ModifyCol(2, 180), lv.ModifyCol(3, 0)
populate := (*) => (
lv.Delete(),
q := StrLower(Trim(edtQ.Value)),
this._PopulateActionPaletteList(lv, q)
)
edtQ.OnEvent("Change", populate)
populate.Call()
detail := d.AddText("w540 h64 y+8", "")
chkPickNow := d.Add("CheckBox", "w540 y+8", "Choose a target immediately (target-based actions only)")
describe := (*) => (
detail.Text := lv.GetNext() ? ActionDiscovery.Description(lv.GetText(lv.GetNext(),3)) : "No matching actions. Try a shorter phrase, such as wait, type, list, or screenshot.",
chkPickNow.Visible := lv.GetNext() && ActionRegistry.UsesTarget(lv.GetText(lv.GetNext(),3))
)
lv.OnEvent("ItemSelect", (*) => describe.Call())
edtQ.OnEvent("Change", (*) => describe.Call())
describe.Call()
btnAdd := d.Add("Button", "x14 y+10 w140 h30 Default", "Add Selected Action")
btnCancel := d.Add("Button", "x+8 w100 h30", "Cancel")
doInsert := (*) => (
row := lv.GetNext(),
row > 0 ? (
aType := lv.GetText(row, 3),
needPick := (chkPickNow.Value == 1) && ActionRegistry.UsesTarget(aType),
d.Destroy(),
this.QuickInsertAction(aType, needPick)
) : ""
)
btnAdd.OnEvent("Click", doInsert)
lv.OnEvent("ContextMenu", (ctrl, row, right, x, y) => this.ShowCommonActionMenu(ctrl, row, right))
lv.OnEvent("DoubleClick", doInsert)
btnCancel.OnEvent("Click", (*) => d.Destroy())
d.OnEvent("Escape", (*) => d.Destroy())
d.Show("AutoSize Center")
edtQ.Focus()
}
_PopulateActionPaletteList(lv, q) {
curAct := this.GetSelectedAction()
preferCat := IsObject(curAct) ? curAct.Category : ""
defs := ActionRegistry.GetDefinitions()
; Contextual ranking: show preferred category matches first when query is empty
for pass in [1, 2] {
for _, def in defs {
isPref := (preferCat != "" && def["Cat"] == preferCat)
if (pass == 1 && !isPref) || (pass == 2 && isPref)
continue
hay := StrLower(def["Name"] " " def["Cat"] " " def["Type"] " " def["Keywords"])
if ActionDiscovery.Matches(def, q)
lv.Add(lv.GetCount() == 0 ? "Select Focus" : "", def["Name"], def["Cat"], def["Type"])
}
}
}
; ==========================================================================
; DIALOG 2: RECORDING REVIEW & BROWSER UPGRADE ENGINE (Sections 13 & 68)
; ==========================================================================
ShowRecordingReviewDialog() {
mac := this.app.project.GetActiveMacro()
proposals := RecordingAnalyzer.AnalyzeMacro(mac, this.app.uiaEngine, this.app.browserMgr)
d := Gui("+Owner" this.mainGui.Hwnd " +ToolWindow", "Recording Review & Smart Upgrade Analyzer — " mac.Name)
d.SetFont("s9", DesignTokens.FontUI)
d.MarginX := 14, d.MarginY := 12
d.SetFont("s10 Bold", DesignTokens.FontUI)
d.Add("Text", "w660", proposals.Length " Smart Improvement(s) Available")
d.SetFont("s9 Norm", DesignTokens.FontUI)
d.Add("Text", "w660 y+4", "Review non-destructive upgrades for recorded coordinates, static sleeps, address-bar navigation, and browser sessions. All changes are Undoable (Ctrl+Z).")
lv := d.Add("ListView", "w660 r9 y+8 Checked Grid -Multi AltSubmit", ["Category", "Recorded (Before)", "Proposed Upgrade", "Reason"])
lv.ModifyCol(1, 130), lv.ModifyCol(2, 165), lv.ModifyCol(3, 185), lv.ModifyCol(4, 170)
for _, p in proposals {
lv.Add("Check", p["Category"], p["Before"], p["Proposed"], p["Reason"])
}
btnApplyChecked := d.Add("Button", "w170 h30 y+10 Default", "Apply Checked Upgrades")
btnApplyAll := d.Add("Button", "x+8 w130 h30", "Apply All")
btnKeep := d.Add("Button", "x+8 w130 h30", "Close")
btnIgnore := d.AddButton("x14 y+10 w170 h30", "Ignore checked")
btnRestore := d.AddButton("x+8 w180 h30", "Restore ignored (" mac.IgnoredUpgrades.Count ")")
btnRestore.Enabled := mac.IgnoredUpgrades.Count > 0
d.AddText("x14 y+8 w660 h36", "Ignored suggestions stay hidden for these steps until restored. Ignoring never changes playback; Undo can restore them.")
btnIgnore.OnEvent("Click", (*) => (this.IgnoreReviewProposals(mac,proposals,lv), d.Destroy()))
btnRestore.OnEvent("Click", (*) => (this.RestoreReviewProposals(mac),d.Destroy(),this.ShowRecordingReviewDialog()))
btnApplyChecked.OnEvent("Click", (*) => (
this._ApplyReviewProposals(mac, proposals, lv, false),
d.Destroy()
))
btnApplyAll.OnEvent("Click", (*) => (
this._ApplyReviewProposals(mac, proposals, lv, true),
d.Destroy()
))
btnKeep.OnEvent("Click", (*) => d.Destroy())
d.Show("AutoSize Center")
}
IgnoreReviewProposals(mac, proposals, list) {
this.app.undoMgr.RecordSnapshot(this.app.project,"Ignore recommendations")
for index, proposal in proposals
if list.GetNext(index-1,"C") == index
mac.IgnoredUpgrades[proposal["Kind"] "|" proposal["ActionId"]] := true
this.app.project.IsDirty := true
this.RefreshAll()
}
RestoreReviewProposals(mac) {
this.app.undoMgr.RecordSnapshot(this.app.project,"Restore recommendations")
mac.IgnoredUpgrades := Map()
this.app.project.IsDirty := true
this.RefreshAll()
}
_ApplyReviewProposals(mac, proposals, lv, applyAll := false) {
if proposals.Length == 0
return
this.app.undoMgr.RecordSnapshot(this.app.project, "Apply Recording Review Upgrades")
appliedCount := 0
for idx, p in proposals {
isChecked := applyAll || (lv.GetNext(idx - 1, "C") == idx)
if isChecked {
if RecordingAnalyzer.ApplyProposal(mac, p, this.app.uiaEngine)
appliedCount += 1
}
}
this.RefreshAll()
this.ShowToast("Applied " appliedCount " smart upgrade(s). Press Ctrl+Z to Undo.")
}
; ==========================================================================
; DIALOG 3: SELECTOR STRATEGIES, FALLBACK PRESETS & VISUAL FALLBACK (Sections 30–35, 45)
; ==========================================================================
ShowSelectorStrategiesDialog() {
act := this.GetSelectedAction()
if IsObject(act) && IsObject(act.Target)
this.backupEditor := BackupTargetsUI(this,act)
}
SetSelectorEnabled(target, row, enabled) {
selector := row == 1 ? target.PrimarySelector : target.AlternateSelectors[row-1]
if selector.Enabled == !!enabled && (!enabled || target.AllowsStrategy(selector.StrategyType))
return
this.app.undoMgr.RecordSnapshot(this.app.project, "Change selector strategy")
selector.Enabled := !!enabled
if enabled && !target.AllowsStrategy(selector.StrategyType)
target.AllowedFallbacks.Push(selector.StrategyType)
target.FallbackPreset := "Custom"
this.app.project.IsDirty := true
this.RefreshInspector()
}
_PopulateAlternateSelectorsLV(lv, t) {
for idx, alt in t.AlternateSelectors {
lv.Add((alt.Enabled && t.AllowsStrategy(alt.StrategyType)) ? "Check" : "", String(idx + 1), alt.Name, alt.StrategyType, alt.GetFindUsingSummary(), alt.LastTestStatus)
}
}
_EnableCoordFallbackOnTarget(t) {
this.app.undoMgr.RecordSnapshot(this.app.project, "Enable coordinate fallback")
if !t.AllowsStrategy("WindowRelativeCoord")
t.AllowedFallbacks.Push("WindowRelativeCoord")
t.FallbackPreset := "Custom"
this.app.project.IsDirty := true
for _, alt in t.AlternateSelectors {
if alt.StrategyType == "WindowRelativeCoord"
alt.Enabled := true
}
this.ShowToast("Enabled Window-Relative Coordinate fallback.")
}
ShowStepWaitAndExpectDialog() {
act := this.GetSelectedAction()
if !IsObject(act)
return
d := Gui("+Owner" this.mainGui.Hwnd " +ToolWindow", "Smart Wait, Actionability & Post-Action Expectation")
d.SetFont("s9", DesignTokens.FontUI)
d.MarginX := 14, d.MarginY := 12
d.SetFont("s9 Bold", DesignTokens.FontUI)
d.Add("Text", "w440", "Pre-Action Actionability & Stability Checks")
d.SetFont("s9 Norm", DesignTokens.FontUI)
chkVis := d.Add("CheckBox", "w210 y+6 Checked" (act.RequireVisible ? 1 : 0), "Require element visible on screen")
chkEn := d.Add("CheckBox", "x+10 yp w210 Checked" (act.RequireEnabled ? 1 : 0), "Require element enabled")
d.Add("Text", "x14 y+10 w165", "Position Settle Time (ms):")
edtSettle := d.Add("Edit", "x+8 yp-2 w90", String(act.SettleTimeMs))
d.SetFont("s9 Bold", DesignTokens.FontUI)
d.Add("Text", "x14 y+14 w440", "Post-Action Expectation ('Success looks like...')")
d.SetFont("s9 Norm", DesignTokens.FontUI)
d.Add("Text", "x14 y+6 w165", "Verify After Action:")
outcomes := ["None", "ElementAppears", "ElementDisappears", "URLContains", "TitleContains", "TextAppears", "NewTabOpened"]
ddlOut := d.Add("DropDownList", "x+8 yp-2 w220", outcomes)
this._SetDdlItems(ddlOut, outcomes, act.ExpectOutcome != "" ? act.ExpectOutcome : "None")
d.Add("Text", "x14 y+10 w165", "Expected Text / URL / Name:")
edtVal := d.Add("Edit", "x+8 yp-2 w220", act.ExpectValue)
d.Add("Text", "x14 y+10 w165", "Expectation Timeout (ms):")
edtExpTo := d.Add("Edit", "x+8 yp-2 w90", String(act.ExpectTimeoutMs))
btnSave := d.Add("Button", "x14 y+14 w120 h28 Default", "Save Rules")
btnCancel := d.Add("Button", "x+8 w90 h28", "Cancel")
btnSave.OnEvent("Click", (*) => (
this.app.undoMgr.RecordSnapshot(this.app.project, "Configure Step Expectations"),
act.RequireVisible := chkVis.Value == 1,
act.RequireEnabled := chkEn.Value == 1,
act.SettleTimeMs := IsInteger(edtSettle.Value) ? Integer(edtSettle.Value) : 0,
act.ExpectOutcome := ddlOut.Text,
act.ExpectValue := Trim(edtVal.Value),
act.ExpectTimeoutMs := IsInteger(edtExpTo.Value) ? Integer(edtExpTo.Value) : 5000,
this.RefreshAll(),
this.ShowToast("Updated smart wait & post-action expectation rules."),
d.Destroy()
))
btnCancel.OnEvent("Click", (*) => d.Destroy())
d.Show("AutoSize Center")
}
; ==========================================================================
; DIALOG 4: ANCHOR CONFIGURATOR ("Find this relative to..." — Section 32)
; ==========================================================================
ShowAnchorConfigDialog() {
act := this.GetSelectedAction()
if !IsObject(act) || !IsObject(act.Target)
return
t := act.Target
anc := t.Anchor
d := Gui("+Owner" this.mainGui.Hwnd " +ToolWindow", "Find This Relative To (Anchor) — " t.GetHumanLabel())
d.SetFont("s9", DesignTokens.FontUI)
d.MarginX := 14, d.MarginY := 12
chkEn := d.Add("CheckBox", "w420 Checked" (anc.Enabled ? 1 : 0), "Enable relative anchor targeting ('Find this relative to...')")
d.Add("Text", "w130 y+10", "Relationship:")
rels := ["Nearest", "RightOf", "LeftOf", "Below", "Above", "SameContainer"]
ddlRel := d.Add("DropDownList", "x+8 yp-2 w220", rels)
this._SetDdlItems(ddlRel, rels, anc.Relationship)
d.Add("Text", "x14 y+10 w130", "Anchor Text / Name:")
edtName := d.Add("Edit", "x+8 yp-2 w220", anc.AnchorName)
d.Add("Text", "x14 y+10 w130", "Anchor ControlType:")
types := ["Text", "Button", "Edit", "CheckBox", "Pane", "Group", "Custom"]
ddlType := d.Add("ComboBox", "x+8 yp-2 w220", types)
ddlType.Text := anc.AnchorControlType != "" ? anc.AnchorControlType : "Text"
d.Add("Text", "x14 y+10 w130", "Max Distance (px):")
edtDist := d.Add("Edit", "x+8 yp-2 w100", String(anc.MaxDistance))
btnPickAnc := d.Add("Button", "x14 y+12 w150 h28", "⌖ Pick Anchor on Screen")
btnSave := d.Add("Button", "x+8 w110 h28 Default", "Save Anchor")
btnCancel := d.Add("Button", "x+8 w85 h28", "Cancel")
btnPickAnc.OnEvent("Click", (*) => (
d.Hide(),
this.app.selectionEngine.StartSelection("AnchorSelection", (pickedAnc, *) => (
IsObject(pickedAnc) ? (
edtName.Value := pickedAnc.Name,
ddlType.Text := pickedAnc.PrimarySelector.ControlType,
chkEn.Value := 1
) : "",
d.Show()
))
))
btnSave.OnEvent("Click", (*) => (
this.app.undoMgr.RecordSnapshot(this.app.project, "Configure Anchor"),
anc.Enabled := chkEn.Value == 1,
anc.Relationship := ddlRel.Text,
anc.AnchorName := Trim(edtName.Value),
anc.AnchorControlType := Trim(ddlType.Text),
anc.AnchorRole := UIATargetEngine.FriendlyRoleFromControlType(anc.AnchorControlType),
anc.MaxDistance := IsInteger(edtDist.Value) ? Integer(edtDist.Value) : 450,
t.EnsureDefaultAlternates(),
t.ComputeReliability(),
this.RefreshAll(),
d.Destroy()
))
btnCancel.OnEvent("Click", (*) => d.Destroy())
d.Show("AutoSize Center")
}
; ==========================================================================
; DIALOG 5: VISUAL CONDITION BUILDER (Section 74)
; ==========================================================================
ShowConditionBuilderDialog() {
act := this.GetSelectedAction()
if !IsObject(act)
return
if act.Type != "Logic_If" && act.Type != "Logic_While" && act.Type != "Wait_Condition"
return this.WrapSelected("Logic_If")
this.conditionEditor := GuidedConditionEditor(this, act)
}
; ==========================================================================
; DIALOG 6: BROWSER PROFILE MANAGER (Sections 46–54)
; ==========================================================================
ShowBrowserProfilesDialog() {
bpm := this.app.profileMgr
bpm.RefreshProfiles()
d := Gui("+Owner" this.mainGui.Hwnd " +ToolWindow", "Browser Profile Manager & Logical Alias Mapping")
d.SetFont("s9", DesignTokens.FontUI)
d.MarginX := 14, d.MarginY := 12
d.SetFont("s10 Bold", DesignTokens.FontUI)
d.Add("Text", "w740", "Discovered Browser Profiles & Studio Logical Aliases")
d.SetFont("s9 Norm", DesignTokens.FontUI)
d.Add("Text", "w740 y+4", "Nichols Macro Studio reads only safe profile names/directories. Never modifies user profile data, lock files, cookies, or saved passwords.")
lv := d.Add("ListView", "w740 r9 y+8 Grid -Multi", ["Browser", "Friendly Name", "Studio Alias", "Profile ID", "Default", "Managed", "User-Data / Path"])
lv.ModifyCol(1, 75), lv.ModifyCol(2, 130), lv.ModifyCol(3, 100), lv.ModifyCol(4, 115), lv.ModifyCol(5, 58), lv.ModifyCol(6, 68), lv.ModifyCol(7, 185)
populate := (*) => (
lv.Delete(),
this._PopulateProfilesDialogLV(lv, bpm)
)
populate.Call()
btnRefresh := d.Add("Button", "x14 y+10 w90 h28", "Refresh")
btnMapAlias := d.Add("Button", "x+6 w130 h28 Default", "Map Logical Alias...")
btnLaunch := d.Add("Button", "x+6 w115 h28", "Launch Profile")
btnAttach := d.Add("Button", "x+6 w115 h28", "Attach Session")
btnManaged := d.Add("Button", "x+6 w175 h28", "+ Create Studio Profile...")
btnClose := d.Add("Button", "x+6 w80 h28", "Close")
btnRefresh.OnEvent("Click", (*) => (bpm.RefreshProfiles(), populate.Call()))
btnMapAlias.OnEvent("Click", (*) => (
row := lv.GetNext(),
row > 0 ? (
bType := lv.GetText(row, 1),
fName := lv.GetText(row, 2),
pId := lv.GetText(row, 4),
ib := InputBox("Enter logical alias name (e.g., Work, Personal, Accounting, QA) to map to " bType " — " fName " (" pId "):", "Map Logical Profile Alias", "w360 h140", "Work"),
(ib.Result != "Cancel" && Trim(ib.Value) != "") ? (
bpm.MapLogicalAlias(Trim(ib.Value), bType, pId, fName),
this.app.project.ProfileAliases[Trim(ib.Value)] := Map("Browser", bType, "ProfileId", pId, "FriendlyName", fName),
populate.Call(),
this.ShowToast("Mapped alias '" Trim(ib.Value) "' → " bType " (" pId ")")
) : ""
) : MsgBox("Select a profile row first.", "Map Alias", "Iconi")
))
btnLaunch.OnEvent("Click", (*) => (
row := lv.GetNext(),
row > 0 ? (
bType := lv.GetText(row, 1),
pId := lv.GetText(row, 4),
bpm.LaunchProfile(bType, pId, "about:blank"),
this.ShowToast("Launched " bType " profile '" pId "'.")
) : MsgBox("Select a profile row to launch.", "Launch Profile", "Iconi")
))
btnAttach.OnEvent("Click", (*) => (
row := lv.GetNext(),
row > 0 ? (
bType := lv.GetText(row, 1),
pId := lv.GetText(row, 4),
sess := this.app.browserMgr.ResolveSession("MainBrowser", bType, pId, "PreferConfiguredThenCurrent", false),
this.RefreshSessionsPanels(),
this.ShowToast("Attached session to " sess["BrowserType"] " (" sess["EffectiveProfile"] ").")
) : this.CmdQuickAttachBrowser()
))
btnManaged.OnEvent("Click", (*) => (
ib := InputBox("Enter alias name for new isolated Studio-managed Edge profile:", "Create Studio-Managed Profile", "w360 h140", "AutomationClean"),
(ib.Result != "Cancel" && Trim(ib.Value) != "") ? (
dir := bpm.CreateStudioManagedProfile("Edge", Trim(ib.Value)),
populate.Call(),
this.ShowToast("Created isolated Studio profile at " dir)
) : ""
))
btnClose.OnEvent("Click", (*) => d.Destroy())
d.Show("AutoSize Center")
}
_PopulateProfilesDialogLV(lv, bpm) {
for idx, p in bpm.discoveredProfiles {
lv.Add(idx == 1 ? "Select Focus" : "", p["Browser"], p["FriendlyName"], p["StudioAlias"], p["ProfileId"], p["IsDefault"] ? "Yes" : "No", p["IsStudioManaged"] ? "Studio" : "User", p["UserDataRoot"])
}
}
; ==========================================================================
; DIALOG 7: UIA TARGET INSPECTOR (Section 116)
; ==========================================================================
ShowTargetInspectorDialog() {
d := Gui("+Owner" this.mainGui.Hwnd " +ToolWindow", "UIA Target Inspector")
d.SetFont("s9", DesignTokens.FontUI)
d.MarginX := 14, d.MarginY := 12
d.Add("Text", "w540", "Inspect live UI Automation properties, ancestor hierarchy, and supported patterns:")
btnPick := d.Add("Button", "w150 h28 y+6 Default", "⌖ Pick Element")
btnHi := d.Add("Button", "x+8 w120 h28", "Highlight")
btnSendToStep := d.Add("Button", "x+8 w175 h28", "Use in Selected Step")
edtProps := d.Add("Edit", "x14 y+10 w540 r12 ReadOnly Font" DesignTokens.FontMono, "Click '⌖ Pick Element' to inspect any desktop or web control.")
inspectedTarget := ""
btnPick.OnEvent("Click", (*) => (
d.Hide(),
this.app.selectionEngine.StartSelection("UIAAction", (t, *) => (
IsObject(t) ? (
inspectedTarget := t,
edtProps.Value := this._FormatTargetInspectionReport(t)
) : "",
d.Show()
))
))
btnHi.OnEvent("Click", (*) => (IsObject(inspectedTarget) ? this.app.uiaEngine.HighlightTarget(inspectedTarget, 1800) : ""))
btnSendToStep.OnEvent("Click", (*) => (
IsObject(inspectedTarget) ? (
this._OnTargetPickedForCurrent(inspectedTarget, "UIAAction"),
d.Destroy()
) : ""
))
d.Show("AutoSize Center")
}
_FormatTargetInspectionReport(t) {
out := "Human Label : " t.GetHumanLabel() "`r`n"
out .= "Target Kind : " t.TargetKind " (" (t.IsWebContent ? "WEB CONTENT" : (t.IsBrowserChromeUI ? "BROWSER UI" : "DESKTOP")) ")`r`n"
out .= "Within Breadcrumb: " t.GetWithinBreadcrumb() "`r`n"
out .= "Reliability : " t.ReliabilityRating " (" t.HealthStatus ") — " t.ReliabilityReason "`r`n"
out .= "------------------------------------------------------------`r`n"
out .= "ControlType : " t.PrimarySelector.ControlType "`r`n"
out .= "Name : " t.PrimarySelector.ElementName "`r`n"
out .= "AutomationId : " t.PrimarySelector.AutomationId "`r`n"
out .= "ClassName : " t.PrimarySelector.ClassName "`r`n"
out .= "FrameworkId : " t.PrimarySelector.FrameworkId "`r`n"
out .= "Parent : " t.PrimarySelector.ParentType " '" t.PrimarySelector.ParentName "'`r`n"
pats := ""
for i, p in t.SupportedPatterns
pats .= (i > 1 ? ", " : "") . p
out .= "Patterns : " (pats != "" ? pats : "(Default)") "`r`n"
out .= Format("Coordinates : Screen ({1}, {2}) | Window-Relative ({3}, {4}) | Size {5}×{6}`r`n", t.ScreenX, t.ScreenY, t.WinRelX, t.WinRelY, t.BoundingW, t.BoundingH)
out .= "Window : " t.WinTitle " [ahk_exe " t.WinExe " | ahk_class " t.WinClass "]"
return out
}
; ==========================================================================
; DIALOG 8: BROWSER INSPECTOR, SESSION PICKER & TAB PICKER (Sections 12–20, 66, 117)
; ==========================================================================
ShowChooseBrowserSessionDialog() {
d := Gui("+Owner" this.mainGui.Hwnd " +ToolWindow", "Choose Browser Session — Running Browser Windows")
d.SetFont("s9", DesignTokens.FontUI)
d.MarginX := 14, d.MarginY := 12
d.SetFont("s10 Bold", DesignTokens.FontUI)
d.Add("Text", "w680", "Select a Running Browser Window (Profile › Session › Page/Tab)")
d.SetFont("s9 Norm", DesignTokens.FontUI)
d.Add("Text", "w680 y+4", "Bind a running browser window to the selected step, macro default, or a named session (e.g., Orders, Source, Destination):")
lv := d.Add("ListView", "w680 r8 y+8 Grid -Multi", ["Browser", "Detected Profile", "Page Title", "Current URL", "Tabs", "HWND"])
lv.ModifyCol(1, 75), lv.ModifyCol(2, 115), lv.ModifyCol(3, 185), lv.ModifyCol(4, 175), lv.ModifyCol(5, 45), lv.ModifyCol(6, 70)
winList := []
populate := (*) => (
lv.Delete(),
winList := this.app.browserMgr.DiscoverRunningBrowserWindows(),
this._PopulateRunningBrowserWindowsLV(lv, winList)
)
populate.Call()
btnRefresh := d.Add("Button", "x14 y+10 w90 h28", "Refresh")
btnUseStep := d.Add("Button", "x+6 w145 h28 Default", "Use for Selected Step")
btnUseMac := d.Add("Button", "x+6 w145 h28", "Set as Macro Default")
btnNamed := d.Add("Button", "x+6 w155 h28", "Bind Named Session...")
btnClose := d.Add("Button", "x+6 w80 h28", "Close")
btnRefresh.OnEvent("Click", populate)
btnUseStep.OnEvent("Click", (*) => (
row := lv.GetNext(),
(row > 0 && row <= winList.Length) ? (
wInfo := winList[row],
sess := this.app.browserMgr.AttachToWindow("MainBrowser", wInfo["Hwnd"], wInfo["BrowserType"], wInfo["ProfileAlias"], wInfo["ProfileAlias"], false, ""),
act := this.GetSelectedAction(),
IsObject(act) ? (
this.app.undoMgr.RecordSnapshot(this.app.project, "Bind Step Browser Session"),
act.BrowserType := wInfo["BrowserType"],
act.BrowserProfile := wInfo["ProfileAlias"],
act.BrowserSession := "MainBrowser",
this.RefreshAll()
) : this.RefreshSessionsPanels(),
this.ShowToast("Bound 'MainBrowser' to " wInfo["BrowserType"] " (" wInfo["ProfileAlias"] ")."),
d.Destroy()
) : MsgBox("Select a running browser window first.", "Choose Browser Session", "Iconi")
))
btnUseMac.OnEvent("Click", (*) => (
row := lv.GetNext(),
(row > 0 && row <= winList.Length) ? (
wInfo := winList[row],
mac := this.app.project.GetActiveMacro(),
this.app.undoMgr.RecordSnapshot(this.app.project, "Set Macro Default Browser"),
mac.BrowserDefault := wInfo["BrowserType"],
mac.DefaultProfileAlias := wInfo["ProfileAlias"],
this.app.browserMgr.AttachToWindow(mac.DefaultSessionName, wInfo["Hwnd"], wInfo["BrowserType"], wInfo["ProfileAlias"], wInfo["ProfileAlias"], false, ""),
this.RefreshAll(),
this.ShowToast("Set macro default browser to " wInfo["BrowserType"] " (" wInfo["ProfileAlias"] ")."),
d.Destroy()
) : MsgBox("Select a running browser window first.", "Choose Browser Session", "Iconi")
))
btnNamed.OnEvent("Click", (*) => (
row := lv.GetNext(),
(row > 0 && row <= winList.Length) ? (
wInfo := winList[row],
ib := InputBox("Enter a session name for this window (e.g., MainBrowser, Orders, Source, Destination):", "Bind Named Browser Session", "w360 h135", "Orders"),
(ib.Result != "Cancel" && Trim(ib.Value) != "") ? (
sName := Trim(ib.Value),
this.app.browserMgr.AttachToWindow(sName, wInfo["Hwnd"], wInfo["BrowserType"], wInfo["ProfileAlias"], wInfo["ProfileAlias"], false, ""),
this.RefreshSessionsPanels(),
this.ShowToast("Bound session '" sName "' to HWND " wInfo["Hwnd"] ".")
) : ""
) : MsgBox("Select a running browser window first.", "Bind Named Session", "Iconi")
))
btnClose.OnEvent("Click", (*) => d.Destroy())
d.Show("AutoSize Center")
}
_PopulateRunningBrowserWindowsLV(lv, winList) {
for idx, w in winList {
lv.Add(idx == 1 ? "Select Focus" : "", w["BrowserType"], w["ProfileAlias"], w["Title"], w["URL"], w["TabCount"], w["Hwnd"])
}
}
ShowBrowserInspectorDialog() {
d := Gui("+Owner" this.mainGui.Hwnd " +ToolWindow", "Browser Inspector, Health & Live Tab Picker")
d.SetFont("s9", DesignTokens.FontUI)
d.MarginX := 14, d.MarginY := 12
d.Add("Text", "w600", "Inspect active Browser Sessions, Session Health, Capabilities, URL, and Enumerated Tabs:")
edtInfo := d.Add("Edit", "w600 r7 y+6 ReadOnly", "")
d.Add("Text", "w600 y+8", "Live Browser Tabs (Double-click or click 'Use Selected Tab' to create Select Tab action):")
lvTabs := d.Add("ListView", "w600 r6 y+4 Grid -Multi", ["#", "Active", "Tab Title", "Session"])
lvTabs.ModifyCol(1, 40), lvTabs.ModifyCol(2, 55), lvTabs.ModifyCol(3, 370), lvTabs.ModifyCol(4, 115)
refreshBrowser := (*) => this._RefreshBrowserInspectorData(edtInfo, lvTabs)
refreshBrowser.Call()
btnAttach := d.Add("Button", "w125 h28 y+10 Default", "Attach / Refresh")
btnChooseWin := d.Add("Button", "x+6 w145 h28", "Choose Window...")
btnUseTab := d.Add("Button", "x+6 w135 h28", "Use Selected Tab")
btnTestFixture := d.Add("Button", "x+6 w115 h28", "Test Fixture")
btnClose := d.Add("Button", "x+6 w65 h28", "Close")
btnAttach.OnEvent("Click", (*) => (this.CmdQuickAttachBrowser(), refreshBrowser.Call()))
btnChooseWin.OnEvent("Click", (*) => (d.Destroy(), this.ShowChooseBrowserSessionDialog()))
useTabFn := (*) => (
row := lvTabs.GetNext(),
row > 0 ? (
tTitle := lvTabs.GetText(row, 3),
this.InsertBrowserTab(tTitle, lvTabs.GetText(row, 4)),
d.Destroy()
) : ""
)
btnUseTab.OnEvent("Click", useTabFn)
lvTabs.OnEvent("DoubleClick", useTabFn)
btnTestFixture.OnEvent("Click", (*) => (
fixPath := DiagnosticsEngine.CreateDisposableHtmlFixture(),
Run(fixPath),
this.ShowToast("Opened disposable local HTML test fixture.")
))
btnClose.OnEvent("Click", (*) => d.Destroy())
d.Show("AutoSize Center")
}
InsertBrowserTab(title, sessionName) {
if !this.app.browserMgr.sessions.Has(sessionName) {
this.ShowToast("The selected browser session is no longer available. Refresh the inspector.")
return ""
}
session := this.app.browserMgr.sessions[sessionName]
context := Map("BrowserSession", sessionName, "BrowserType", session["BrowserType"], "BrowserProfile", session["RequestedProfile"])
return this.QuickInsertAction("Browser_SelectTab", false, Map("TabTitle", title, "MatchMode", "Exact"), context)
}
_RefreshBrowserInspectorData(edtInfo, lvTabs) {
lvTabs.Delete()
if this.app.browserMgr.sessions.Count == 0 {
try this.app.browserMgr.ResolveSession("MainBrowser", "Edge", "Current", "AnyCompatibleSession", false)
}
infoTxt := ""
for sName, sess in this.app.browserMgr.sessions {
health := this.app.browserMgr.GetSessionHealth(sName)
caps := BrowserCapabilityMatrix.GetCapabilities(sess["BrowserType"])
capList := ""
for ck, cv in caps {
if cv
capList .= ck " "
}
infoTxt .= Format("Session: {1} | Health: {2} | Browser: {3} | HWND: {4}`r`n", sName, health["Status"], sess["BrowserType"], sess["Hwnd"])
infoTxt .= Format("Profile: {1} (Requested: {2}) | Detail: {3}`r`n", sess["EffectiveProfile"], sess["RequestedProfile"], health["Detail"])
infoTxt .= Format("Title : {1}`r`nURL : {2}`r`n", sess["CurrentTitle"], sess["CurrentURL"])
infoTxt .= "Capabilities: " capList "`r`n"
tabs := this.app.browserMgr.GetSessionTabs(sName)
for _, t in tabs
lvTabs.Add("", t["Index"], t.Get("IsActive", false) ? "★ Yes" : "", t["Title"], sName)
}
if infoTxt == ""
infoTxt := "No active browser session attached. Open Edge, Chrome, or Firefox and click 'Attach / Refresh' or 'Choose Window...'."
edtInfo.Value := infoTxt
}
; ==========================================================================
; DIALOG 8B: DRY-RUN PREFLIGHT & BATCH TARGET REPAIR QUEUE (Sections 51 & 85)
; ==========================================================================
ShowDryRunPreflightDialog() {
mac := this.app.project.GetActiveMacro()
d := Gui("+Owner" this.mainGui.Hwnd " +ToolWindow", "Validate & Dry-Run Targets (Preflight) — " mac.Name)
d.SetFont("s9", DesignTokens.FontUI)
d.MarginX := 14, d.MarginY := 12
d.SetFont("s10 Bold", DesignTokens.FontUI)
lblSummary := d.Add("Text", "w660", "Running non-destructive target resolution across macro steps...")
d.SetFont("s9 Norm", DesignTokens.FontUI)
lv := d.Add("ListView", "w660 r10 y+8 Grid -Multi", ["Step #", "Step Description", "State", "Resolution Detail"])
lv.ModifyCol(1, 55), lv.ModifyCol(2, 235), lv.ModifyCol(3, 130), lv.ModifyCol(4, 225)
runDry := (*) => (
lv.Delete(),
results := this.app.playback.DryRunTargets(mac),
passCnt := 0, failCnt := 0, ambCnt := 0,
this._PopulateDryRunLV(lv, results, &passCnt, &failCnt, &ambCnt),
lblSummary.Value := Format("Dry-Run Complete: {1} Available/Ready, {2} Ambiguous, {3} Unavailable (Zero clicks or keystrokes sent)", passCnt, ambCnt, failCnt),
this.RefreshAll()
)
runDry.Call()
btnReRun := d.Add("Button", "x14 y+10 w130 h28 Default", "Re-Run Dry Run")
btnRepairQ := d.Add("Button", "x+8 w185 h28", "Open Batch Repair Queue...")
btnClose := d.Add("Button", "x+8 w90 h28", "Close")
btnReRun.OnEvent("Click", runDry)
btnRepairQ.OnEvent("Click", (*) => (d.Destroy(), this.ShowBatchRepairQueueDialog()))
btnClose.OnEvent("Click", (*) => d.Destroy())
d.Show("AutoSize Center")
}
_PopulateDryRunLV(lv, results, &passCnt, &failCnt, &ambCnt) {
for _, r in results {
st := r["State"]
if InStr(st, "Available") || st == "Ready"
passCnt += 1
else if InStr(st, "Ambiguous")
ambCnt += 1
else
failCnt += 1
lv.Add("", r["Step"], r["Description"], st, r["Detail"])
}
}
ShowBatchRepairQueueDialog() {
mac := this.app.project.GetActiveMacro()
queue := []
flat := WorkflowTree.Flatten(mac.Actions, true)
for _, r in flat {
if r["RowKind"] != "Action"
continue
a := r["Action"]
if !ActionRegistry.UsesTarget(a.Type) || !IsObject(a.Target)
continue
t := a.Target
t.ComputeReliability()
if t.HealthStatus == StudioConstants.HealthBroken || t.HealthStatus == StudioConstants.HealthNeedsRepair || t.HealthStatus == StudioConstants.HealthAmbiguous || t.ReliabilityRating == StudioConstants.RelFragile || t.ReliabilityRating == StudioConstants.RelVeryFragile {
queue.Push(Map("StepNumber", r["StepNumber"], "Action", a))
}
}
if queue.Length == 0 {
MsgBox("All target-based steps in '" mac.Name "' currently have strong/healthy semantic or visual targets!", "Batch Target Repair Queue", "Iconi")
return
}
curIdx := 1
d := Gui("+Owner" this.mainGui.Hwnd " +ToolWindow", "Batch Target Repair Queue — " mac.Name)
d.SetFont("s9", DesignTokens.FontUI)
d.MarginX := 14, d.MarginY := 12
d.SetFont("s10 Bold", DesignTokens.FontUI)
lblHeader := d.Add("Text", "w540", "")
d.SetFont("s9 Norm", DesignTokens.FontUI)
edtDetail := d.Add("Edit", "w540 r6 y+6 ReadOnly", "")
syncQueueItem := (*) => (
item := queue[curIdx],
act := item["Action"],
t := act.Target,
this.selectedActionId := act.Id,
this.RefreshWorkflowList(),
this.RefreshInspector(),
lblHeader.Value := Format("Repair Item {1} of {2} — Step #{3}: {4}", curIdx, queue.Length, item["StepNumber"], act.ComputeFriendlyDescription()),
edtDetail.Value := Format("Current Target : {1}`r`nWithin : {2}`r`nMethod : {3} | Find using: {4}`r`nReliability : {5} | Health: {6} | Matches: {7}`r`nReason : {8}",
t.GetHumanLabel(), t.GetWithinBreadcrumb(), t.GetMethodLabel(), t.PrimarySelector.GetFindUsingSummary(),
t.ReliabilityRating, t.HealthStatus, t.LastMatchCount, t.ReliabilityReason)
)
syncQueueItem.Call()
btnPick := d.Add("Button", "x14 y+10 w145 h28 Default", "⌖ Pick Replacement")
btnPreview := d.Add("Button", "x+6 w95 h28", "Preview")
btnVisual := d.Add("Button", "x+6 w130 h28", "+ Visual Fallback")
btnPrev := d.Add("Button", "x14 y+8 w95 h26", "◀ Previous")
btnNext := d.Add("Button", "x+6 w95 h26", "Next / Skip ▶")
btnFinish := d.Add("Button", "x+180 w95 h26", "Finish")
btnPick.OnEvent("Click", (*) => (
d.Hide(),
this.app.selectionEngine.StartSelection("UpgradeTarget", (newT, *) => (
IsObject(newT) ? (
this._OnTargetPickedForCurrent(newT, "UpgradeTarget"),
syncQueueItem.Call()
) : "",
d.Show()
))
))
btnPreview.OnEvent("Click", (*) => (this.CmdPreviewCurrentStep(), syncQueueItem.Call()))
btnVisual.OnEvent("Click", (*) => (this.CmdAddVisualFallbackCurrent(), syncQueueItem.Call()))
btnPrev.OnEvent("Click", (*) => (curIdx := Max(1, curIdx - 1), syncQueueItem.Call()))
btnNext.OnEvent("Click", (*) => (curIdx := Min(queue.Length, curIdx + 1), syncQueueItem.Call()))
btnFinish.OnEvent("Click", (*) => d.Destroy())
d.Show("AutoSize Center")
}
; ==========================================================================
; DIALOG 9: WINDOW INSPECTOR & LIVE COLOR PICKER (Sections 118 & 119)
; ==========================================================================
ShowWindowInspectorDialog() {
d := Gui("+Owner" this.mainGui.Hwnd " +ToolWindow", "Window Inspector")
d.SetFont("s9", DesignTokens.FontUI)
d.MarginX := 14, d.MarginY := 12
edt := d.Add("Edit", "w480 r8 ReadOnly", "")
btnPick := d.Add("Button", "w150 h28 y+10 Default", "⌖ Pick Window")
btnUse := d.Add("Button", "x+8 w165 h28", "Add Activate Window")
btnClose := d.Add("Button", "x+8 w90 h28", "Close")
pickedT := ""
btnPick.OnEvent("Click", (*) => (
d.Hide(),
this.app.selectionEngine.StartSelection("WindowSelection", (t, *) => (
IsObject(t) ? (
pickedT := t,
WinGetPos(&wx, &wy, &ww, &wh, "ahk_id " t.WinHwnd),
edt.Value := Format("Title : {1}`r`nExecutable: {2}`r`nClass : {3}`r`nHWND : {4}`r`nPosition : ({5}, {6}) Size: {7}×{8}`r`nUIPI Check: {9}",
t.WinTitle, t.WinExe, t.WinClass, t.WinHwnd, wx, wy, ww, wh,
StudioUtils.CheckUIPIWarning(t.WinHwnd) != "" ? StudioUtils.CheckUIPIWarning(t.WinHwnd) : "Standard Privilege OK")
) : "",
d.Show()
))
))
btnUse.OnEvent("Click", (*) => (
IsObject(pickedT) ? (
this.QuickInsertAction("Win_Activate", false),
act := this.GetSelectedAction(),
act.Target := pickedT,
act.Parameters["WinTitle"] := pickedT.WinTitle,
act.Parameters["WinExe"] := pickedT.WinExe,
act.FriendlyDescription := act.ComputeFriendlyDescription(),
this.RefreshAll(),
d.Destroy()
) : ""
))
btnClose.OnEvent("Click", (*) => d.Destroy())
d.Show("AutoSize Center")
}
ShowColorPickerDialog() {
this.CmdPickTargetForCurrent("PixelColorSelection")
}
ShowAddVariableDialog() {
ibName := InputBox("Variable Name:", "Set Variable", "w320 h130", "MyVar")
if ibName.Result == "Cancel" || Trim(ibName.Value) == ""
return
ibVal := InputBox("Value for $" Trim(ibName.Value) ":", "Set Variable Value", "w320 h130", "")
if ibVal.Result == "Cancel"
return
this.app.undoMgr.RecordSnapshot(this.app.project, "Set Project Variable")
this.app.varStore.SetRuntime(Trim(ibName.Value), ibVal.Value, "Project")
this.app.project.Variables[Trim(ibName.Value)] := ibVal.Value
this.app.project.IsDirty := true
this.RefreshVariablesPanel()
this.ShowToast("Set project variable $" Trim(ibName.Value))
}
; ==========================================================================
; DIALOG 10: HOTKEY MANAGER & OPTIONS (Sections 87, 98, 110, 115)
; ==========================================================================
ShowOptionsDialog() {
if this.app.recorder.isRecording || this.app.playback.isRunning || this.app.selectionEngine.isActive
return this.ShowToast("Stop recording, playback, or target selection before changing settings.")
this.optionsEditor := StudioOptionsUI(this)
}
; ==========================================================================
; DIALOG 11: BUILT-IN HELP & DIAGNOSTICS RUNNER (Sections 123 & 124)
; ==========================================================================
ShowHelpDialog() {
d := Gui("+Owner" this.mainGui.Hwnd " +ToolWindow", "Nichols Macro Studio v" StudioConstants.AppVersion " — User & Engineering Guide")
d.SetFont("s9", DesignTokens.FontUI)
d.MarginX := 14, d.MarginY := 12
helpText := "NICHOLS MACRO STUDIO v" StudioConstants.AppVersion " — COMPLETE QUICK REFERENCE`r`n"
helpText .= "============================================================`r`n"
helpText .= "1. SIMPLE RECORDING (F3)`r`n"
helpText .= " Press F3, perform your task naturally, and press F3 to stop.`r`n"
helpText .= " Nichols Macro Studio captures semantic UI Automation targets opportunistically`r`n"
helpText .= " outside low-level hooks, coalesces typing into readable 'Type Text'`r`n"
helpText .= " steps, protects password fields automatically, and offers non-destructive`r`n"
helpText .= " smart upgrades afterward.`r`n`r`n"
helpText .= "2. SELECTION LENS, INTENT FILTERS & FREEZE & REFINE (Shift+F3 / Ctrl+Shift+F)`r`n"
helpText .= " • Dual-context live highlighting shows Primary Target + Container Scope + Click Point (+).`r`n"
helpText .= " • Press keys 1..7 during selection to filter intent (1:Smart, 2:Control, 3:Text,`r`n"
helpText .= " 4:Container, 5:Page, 6:Visual, 7:Point) or MouseWheel / [ / ] to step depth.`r`n"
helpText .= " • Press Space or Ctrl+Shift+F for Freeze & Refine with Exact Target Preview,`r`n"
helpText .= " Smart Action Choice, Use as Scope, Use as Anchor, and + Visual Fallback.`r`n`r`n"
helpText .= "3. TARGET RELIABILITY, PRESETS, HEALTH & BATCH REPAIR`r`n"
helpText .= " • Presets: Balanced, Resilient, StrictSemantic, LegacyRecorded.`r`n"
helpText .= " • Health: Healthy, Untested, Ambiguous, Fallback Used, Needs Repair, Broken.`r`n"
helpText .= " • Tools → Validate & Dry-Run Targets tests all steps without clicking.`r`n"
helpText .= " • Tools → Batch Target Repair Queue steps through fragile/broken targets.`r`n`r`n"
helpText .= "4. BROWSER PROFILES, SESSIONS, HEALTH & FALLBACK POLICIES`r`n"
helpText .= " • Mental Model: Profile › Session › Page/Tab › Target › Action.`r`n"
helpText .= " • Tools → Choose Browser Session binds live running windows with 1 click.`r`n"
helpText .= " • Test Resolution simulates fallback policies before running.`r`n`r`n"
helpText .= "5. STANDALONE EXPORT & EXE COMPILATION`r`n"
helpText .= " • File → Export Standalone AHK generates readable AutoHotkey v2 code`r`n"
helpText .= " with inline UIA-v2 runtime and zero external dependencies.`r`n"
helpText .= " • File → Build Standalone EXE compiles via Ahk2Exe.`r`n`r`n"
helpText .= "6. ATTRIBUTION`r`n"
helpText .= " Includes inline vendored UIA-v2 (UIA.ahk & UIA_Browser.ahk) by Descolada`r`n"
helpText .= " under the MIT License (https://github.com/Descolada/UIA-v2)."
d.Add("Edit", "w620 r22 ReadOnly", helpText)
btnOk := d.Add("Button", "w100 h28 y+10 Default", "Close")
btnOk.OnEvent("Click", (*) => d.Destroy())
d.Show("AutoSize Center")
}
_AboutDecode(s) {
n:=0
DllCall("Crypt32\CryptStringToBinaryW","Str",s,"UInt",0,"UInt",1,"Ptr",0,"UIntP",&n,"Ptr",0,"Ptr",0)
b:=Buffer(n+1,0)
DllCall("Crypt32\CryptStringToBinaryW","Str",s,"UInt",0,"UInt",1,"Ptr",b,"UIntP",&n,"Ptr",0,"Ptr",0)
return StrGet(b,"UTF-8")
}
ShowAboutDialog() {
this.CloseAboutDialog()
t:=this._AboutDecode.Bind(this), d:=Gui("+Owner" this.mainGui.Hwnd,t("QWJvdXQg") StudioConstants.AppName)
this.aboutDialog := d
this.workshop := NicholsWorkshop(this)
d.AddPicture("w48 h48 +0x100", StudioBranding.IconFile()).OnEvent("Click", this.workshop.LogoClick.Bind(this.workshop))
d.SetFont("s11",DesignTokens.FontUI), d.AddText("w460",StudioConstants.AppName " v" StudioConstants.AppVersion)
d.AddText("w460 y+18",t("QnVpbHQgZnJlZWx5IGZvciB0aG9zZSB3aG8gYnVpbGQgLSBDaGFybGVzIE5pY2hvbHM="))
d.AddLink("w460 y+10",t("PGEgaHJlZj0iaHR0cHM6Ly9OaWNob2xzLkFJIj7CqSA=") A_YYYY t("IE5pY2hvbHMuQUk8L2E+"))
d.SetFont("s9",DesignTokens.FontUI), d.AddText("w460 y+24",t("VUlBIEF0dHJpYnV0aW9u"))
d.AddText("w460 y+8",t("SW5jbHVkZXMgRGVzY29sYWRhL1VJQS12MiwgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBMaWNlbnNlLiBPcmlnaW5hbCBsaWJyYXJ5IGNvcHlyaWdodCBhbmQgbGljZW5zZSBub3RpY2VzIGFyZSBwcmVzZXJ2ZWQgaW4gdGhlIGJ1bmRsZWQgc291cmNlLg=="))
d.AddLink("w460 y+10",t("PGEgaHJlZj0iaHR0cHM6Ly9naXRodWIuY29tL0Rlc2NvbGFkYS9VSUEtdjIiPlVJQS12MiBzb3VyY2UgYW5kIGxpY2Vuc2U8L2E+"))
d.AddText("w460 y+18",t("T0NSIEF0dHJpYnV0aW9uOiBEZXNjb2xhZGEvT0NSIChNSVQpLCBiYXNlZCBvbiBtYWxjZXYncyBXaW5kb3dzIE9DUiB3b3JrLiBDb3B5cmlnaHQgYW5kIGxpY2Vuc2UgYXJlIHByZXNlcnZlZCBpbiB0aGUgYnVuZGxlZCBzb3VyY2Uu"))
d.AddLink("w460 y+10",t("PGEgaHJlZj0iaHR0cHM6Ly9naXRodWIuY29tL0Rlc2NvbGFkYS9PQ1IiPk9DUiBzb3VyY2UgYW5kIGxpY2Vuc2U8L2E+"))
d.AddButton("w100 y+20 Default",t("Q2xvc2U=")).OnEvent(t("Q2xpY2s="),(*)=>this.CloseAboutDialog())
d.OnEvent(t("RXNjYXBl"),(*)=>this.CloseAboutDialog()), d.OnEvent("Close", (*)=>this.CloseAboutDialog()), d.Show()
}
CloseAboutDialog(*) {
if this.HasOwnProp("workshop") && IsObject(this.workshop) {
this.workshop.EndSession()
this.workshop := ""
}
if this.HasOwnProp("aboutDialog") && IsObject(this.aboutDialog) {
d := this.aboutDialog
this.aboutDialog := ""
d.Destroy()
}
}
CmdRunDiagnosticsUI() {
this.bottomTab.Choose(5)
this.lvDiagnostics.Delete()
this.ShowToast("Running self-test diagnostics...")
results := this.app.diagnostics.RunAllDiagnostics(true)
passCnt := 0, failCnt := 0, skipCnt := 0
for _, r in results {
st := r["Status"]
if st == "PASS"
passCnt += 1
else if st == "FAIL"
failCnt += 1
else
skipCnt += 1
this.lvDiagnostics.Add("", st, r["Test"], r["Detail"])
}
this.ShowToast(Format("Diagnostics complete: {1} PASS, {2} FAIL, {3} SKIPPED.", passCnt, failCnt, skipCnt))
}
_OnMainGuiClose(guiObj) {
if this.app.project.IsDirty {
ans := MsgBox("Save changes to '" this.app.project.Name "' before closing?", StudioConstants.AppName, "YesNoCancel Icon?")
if ans == "Cancel"
return 1 ; Prevent close
if ans == "Yes" {
if !this.app.CmdSaveProject(false)
return 1
}
}
this.app.ShutdownAndExit()
}
}
; ==============================================================================
; PART 8: STUDIO APPLICATION CONTROLLER, HOTKEY DISPATCHER, & LIFECYCLE MANAGER
; ==============================================================================
class StudioApp {
currentState := StudioConstants.StateIdle
project := ""
persistence := ""
undoMgr := ""
logger := ""
varStore := ""
overlayMgr := ""
imageEngine := ""
profileMgr := ""
browserMgr := ""
uiaEngine := ""
selectionEngine := ""
condEngine := ""
recorder := ""
playback := ""
diagnostics := ""
gui := ""
autosaveTimer := ""
registeredHotkeys := []
__New() {
this.persistence := PersistenceEngine()
this.logger := LoggingEngine()
this.undoMgr := UndoRedoManager()
this.varStore := VariableStore(this.logger)
this.overlayMgr := OverlayManager()
this.imageEngine := ImagePixelEngine(this.overlayMgr)
this.profileMgr := BrowserProfileManager(this.logger)
this.browserMgr := BrowserSessionManager(this.profileMgr, this.logger, this)
this.uiaEngine := UIATargetEngine(this.overlayMgr, this.imageEngine, this.browserMgr)
this.selectionEngine := SelectionEngine(this, this.overlayMgr, this.uiaEngine, this.imageEngine)
this.condEngine := ConditionEngine(this.varStore, this.uiaEngine, this.browserMgr, this.imageEngine)
this.recorder := RecorderEngine(this, this.uiaEngine, this.overlayMgr, this.browserMgr, this.logger)
this.playback := PlaybackEngine(this, this.varStore, this.condEngine, this.uiaEngine, this.browserMgr, this.imageEngine, this.logger)
this.diagnostics := DiagnosticsEngine(this)
this.project := ProjectModel("Untitled Project")
this.gui := StudioGui(this)
this.activityDisplay := ActivityDisplay(this)
this.logger.onLogAdded := ObjBindMethod(this.gui, "OnLogEntryAdded")
this.varStore.onVarsChanged := ObjBindMethod(this.gui, "RefreshVariablesPanel")
this.playback.onStepHighlight := ObjBindMethod(this, "_OnPlaybackStepHighlight")
OnExit(ObjBindMethod(this, "_OnProcessExit"))
}
Start(cliArgs := "") {
this.logger.Add("INFO", "", 0, "Startup", "Ready", 0, 0, "", "", "AutoHotkey " A_AhkVersion " / " (A_PtrSize * 8) "-bit / DPI " A_ScreenDPI)
try {
root := UIA.GetRootElement()
this.logger.Add("INFO", "", 0, "UI Automation", "Ready", 0, 0, "", "", "UIA " UIA.Version " desktop root initialized")
} catch as err {
this.logger.Add("ERROR", "", 0, "UI Automation", "Unavailable", 0, 0, "", "", err.Message)
}
; Support headless CLI diagnostics & smoke testing
if IsObject(cliArgs) {
for _, arg in cliArgs {
if arg == "--run-diagnostics" || arg == "/diagnostics" {
this._RunCliDiagnostics()
return
}
if arg == "--nms-selftest" { ; [NMS-PC-07] candidate-build self-test (mock objects, no real input)
NMS_SelfTest_Run()
return
}
if arg == "--nms-e2e" { ; [NMS-PD-06] automated end-to-end checks (replace the manual tests)
NMS_E2E_Run()
return
}
if arg == "--nms-export-test" {
NMS_ExportTest_Run()
return
}
if arg == "--nms-exit-test" {
NMS_ExitTest_Run()
return
}
if arg == "--smoke-test" {
this._RunGuiSmokeTest()
return
}
}
}
this.gui.Build()
this.RegisterGlobalStudioHotkeys()
this._CheckCrashRecoveryOnStartup()
this.autosaveTimer := ObjBindMethod(this, "_OnAutosaveTick")
SetTimer(this.autosaveTimer, 20000)
}
_RunCliDiagnostics() {
resList := this.diagnostics.RunAllDiagnostics(true)
failCnt := 0
for _, r in resList {
StudioUtils.DiagnosticWrite(r["Status"] " | " r["Test"] " | " r["Detail"] "`r`n")
if r["Status"] == "FAIL"
failCnt += 1
}
this.CleanupAllResources()
ExitApp(failCnt > 0 ? 1 : 0)
}
_RunGuiSmokeTest() {
this.gui.Build()
this.RegisterGlobalStudioHotkeys()
this._TestWorkflowShortcuts()
; Test responsive layout across multiple resolutions/breakpoints including 1366x768, 1080p, 4K, and Compact (Sections 77–80)
testSizes := [
[1366, 768],
[1920, 1080],
[3840, 2160],
[960, 700],
[720, 560],
[1280, 800]
]
for _, sz in testSizes {
this.persistence.ClampLayoutMetrics(sz[1], sz[2])
this.gui.layoutMgr.ApplyLayout(sz[1], sz[2])
Sleep(25)
}
this.gui.CmdRunDiagnosticsUI()
Sleep(100)
StudioUtils.DiagnosticWrite("SMOKE_TEST_GUI_OK`r`n")
this.ShutdownAndExit()
}
_TestWorkflowShortcuts() {
macro := this.project.GetActiveMacro()
previous := macro.Actions
savedClipboard := ClipboardAll()
try {
macro.Actions := [ActionModel("Wait_Duration"), ActionModel("Wait_Duration"), ActionModel("Wait_Duration")]
this.gui.RefreshAll()
lv := this.gui.lvWorkflow
WinActivate("ahk_id " this.gui.mainGui.Hwnd)
WinWaitActive("ahk_id " this.gui.mainGui.Hwnd,, 3)
lv.Focus()
lv.Modify(0, "-Select")
SendEvent("{Ctrl down}a")
Sleep(100)
SendEvent("{Ctrl up}")
Sleep(150)
if lv.GetCount("Selected") != 3
throw Error("Ctrl+A selected " lv.GetCount("Selected") " of " lv.GetCount())
SendEvent("{Ctrl down}a")
Sleep(100)
SendEvent("{Ctrl up}")
Sleep(100)
if lv.GetCount("Selected") != 3
throw Error("Repeated Ctrl+A changed the selection")
lv.Modify(0, "-Select")
this.gui.edtSearchWorkflow.Value := "shortcut text fixture"
this.gui.edtSearchWorkflow.Focus()
SendEvent("{Ctrl down}a")
Sleep(100)
SendEvent("{Ctrl up}")
Sleep(100)
if lv.GetCount("Selected") != 0
throw Error("Ctrl+A escaped the focused text field")
SendEvent("^c")
Sleep(100)
if A_Clipboard != "shortcut text fixture"
throw Error("Text-field Ctrl+A/C failed")
SendEvent("^x")
Sleep(100)
if this.gui.edtSearchWorkflow.Value != ""
throw Error("Text-field Ctrl+X failed")
SendEvent("^v")
Sleep(100)
if this.gui.edtSearchWorkflow.Value != "shortcut text fixture"
throw Error("Text-field Ctrl+V failed")
this.gui.edtSearchWorkflow.Value := ""
macro.Actions := []
this.gui.RefreshAll()
lv.Focus()
SendEvent("{Ctrl down}a")
Sleep(100)
SendEvent("{Ctrl up}")
Sleep(100)
if lv.GetCount("Selected") != 0
throw Error("Empty workflow selection failed")
macro.Actions := [ActionModel("Wait_Duration"), ActionModel("Wait_Duration")]
this.gui.RefreshAll()
lv.Focus()
SendEvent("{Ctrl down}a")
Sleep(100)
SendEvent("{Ctrl up}")
Sleep(100)
SendEvent("{Ctrl down}c")
Sleep(100)
SendEvent("{Ctrl up}")
Sleep(100)
if this.gui.clipboardActions.Length != 2 || macro.Actions.Length != 2
throw Error("Ctrl+C did not copy both steps")
SendEvent("{Ctrl down}v")
Sleep(100)
SendEvent("{Ctrl up}")
Sleep(150)
if macro.Actions.Length != 4
throw Error("Ctrl+V did not paste both steps")
SendEvent("{Ctrl down}a")
Sleep(100)
SendEvent("{Ctrl up}")
Sleep(100)
SendEvent("{Ctrl down}x")
Sleep(100)
SendEvent("{Ctrl up}")
Sleep(150)
if macro.Actions.Length != 0 || this.gui.clipboardActions.Length != 4
throw Error("Ctrl+X did not cut all steps")
SendEvent("{Ctrl down}v")
Sleep(100)
SendEvent("{Ctrl up}")
Sleep(150)
if macro.Actions.Length != 4
throw Error("Ctrl+V could not restore cut steps")
StudioUtils.DiagnosticWrite("WORKFLOW_SHORTCUTS_OK`r`n")
} catch as err {
StudioUtils.DiagnosticWrite("WORKFLOW_SHORTCUTS_FAILED: " err.Message " @ " err.Line "`r`n")
SendEvent("{Ctrl up}")
A_Clipboard := savedClipboard
ExitApp(1)
} finally {
SendEvent("{Ctrl up}")
A_Clipboard := savedClipboard
macro.Actions := previous
this.gui.RefreshAll()
}
}
SetState(newState) {
this.currentState := newState
if this.HasOwnProp("activityDisplay") {
try this.activityDisplay.Update()
catch as err {
this.activityDisplay.Clear()
this.logger.Add("WARN", "", 0, "Activity display", "Unavailable", 0, 0, "", "", err.Message)
}
}
if IsObject(this.gui)
this.gui.UpdateStateIndicator(newState)
}
ShowToast(msg) {
if IsObject(this.gui)
this.gui.ShowToast(msg)
}
_OnPlaybackStepHighlight(actionId) {
if IsObject(this.gui) {
this.gui.selectedActionId := actionId
; Refresh once at completion; rebuilding the tree here distorts recorded timing.
}
}
_OnAutosaveTick() {
if IsObject(this.project) && this.project.IsDirty
this.persistence.WriteAutosave(this.project)
}
_CheckCrashRecoveryOnStartup() {
rec := this.persistence.CheckForCrashRecovery()
if !IsObject(rec)
return
ans := MsgBox(Format("Nichols Macro Studio detected an unsaved project from a previous session:`n`nProject: {1}`nSaved at: {2}`n`nWould you like to recover this project?`n(Click 'No' to dismiss recovery permanently for this snapshot.)", rec["ProjectName"], rec["Timestamp"]), "Crash Recovery Available", "YesNo Icon?")
if ans == "Yes" {
this.project := rec["Project"]
this.gui.RefreshAll()
this.ShowToast("Recovered unsaved project '" this.project.Name "'.")
} else {
this.persistence.DismissCrashRecovery(rec["Timestamp"])
}
}
; ==========================================================================
; GLOBAL & MACRO HOTKEY MANAGEMENT (Sections 87, 111, 135)
; ==========================================================================
RegisterGlobalStudioHotkeys() {
this.UnregisterGlobalStudioHotkeys()
s := this.persistence.settings
hkRec := s.Get("Hotkey_Record", "F3")
hkPlay := s.Get("Hotkey_Play", "F1")
hkPause := s.Get("Hotkey_Pause", "F7")
hkStop := s.Get("Hotkey_Stop", "F8")
this._BindHotkeySafe(hkRec, (*) => this.CmdToggleRecord("Simple"))
if !InStr(hkRec, "+")
this._BindHotkeySafe("+" hkRec, (*) => this.CmdToggleRecord("Advanced"))
this._BindHotkeySafe(hkPlay, (*) => this.CmdPlay())
this._BindHotkeySafe(hkPause, (*) => this.CmdPauseResume())
stopHk := (SubStr(hkStop, 1, 1) = "*") ? hkStop : "*" hkStop ; [NMS-PA-04] never leave the user without a stop key
stopCb := (*) => this.CmdEmergencyStop()
if !this._BindHotkeySafe(stopHk, stopCb) {
if (stopHk != "*F8" && this._BindHotkeySafe("*F8", stopCb)) {
try this.ShowToast("Stop hotkey '" hkStop "' could not be registered. Using F8 instead.")
} else {
try this.ShowToast("WARNING: no Emergency Stop hotkey could be registered. Use the Stop button.")
}
}
this.BindMacroTriggerHotkeys()
}
BindMacroTriggerHotkeys() {
if !IsObject(this.project)
return
seen := Map()
for _, mac in this.project.Macros {
hk := Trim(mac.TriggerHotkey) ; [NMS-PB-03] a macro trigger must never shadow the Emergency Stop key
if hk == "" || !mac.Enabled
continue
stopBaseHk := RegExReplace(this.persistence.settings.Get("Hotkey_Stop", "F8"), "^[\^!+#*~$<>]+")
if StrUpper(RegExReplace(hk, "^[\^!+#*~$<>]+")) == StrUpper(stopBaseHk) {
try this.ShowToast("Macro '" mac.Name "' trigger '" hk "' conflicts with the Stop key and was not registered.")
continue
}
if seen.Has(StrUpper(hk))
continue
seen[StrUpper(hk)] := true
this._BindHotkeySafe(hk, ObjBindMethod(this, "_PlayTriggeredMacro", mac.Id))
}
}
_PlayTriggeredMacro(macroId, *) {
for macro in this.project.Macros {
if macro.Id == macroId && macro.Enabled {
this.playback.PlayMacro(macro)
return
}
}
}
_BindHotkeySafe(hkStr, callback) { ; [NMS-PA-01] returns true/false; failures are traced, not swallowed
if hkStr == ""
return false
try {
Hotkey(hkStr, callback, "On")
this.registeredHotkeys.Push(hkStr)
return true
} catch as hkErr {
try EngineTrace.Add("hotkey-fail", hkStr, hkErr.Message)
return false
}
}
UnregisterGlobalStudioHotkeys() {
for _, hk in this.registeredHotkeys {
try Hotkey(hk, "Off")
}
this.registeredHotkeys := []
}
; ==========================================================================
; TOP-LEVEL USER COMMANDS
; ==========================================================================
_CanReplaceProject() {
if this.currentState != StudioConstants.StateIdle
return false
if IsObject(this.playback) && this.playback.isRunning
return false
if IsObject(this.recorder) && (this.recorder.isRecording || this.recorder.queueProcessing || this.recorder.finishRecordingPending)
return false
return !IsObject(this.selectionEngine) || !this.selectionEngine.isActive
}
_AskSaveChanges() {
return MsgBox("Save changes to '" this.project.Name "' before replacing this project?", StudioConstants.AppName, "YesNoCancel Icon?")
}
_ConfirmProjectReplacement() {
if !this._CanReplaceProject() {
this.ShowToast("Stop playback, recording and selection before replacing the project.")
return false
}
if this.project.IsDirty {
answer := this._AskSaveChanges()
if answer == "Cancel" || (answer == "Yes" && !this.CmdSaveProject(false))
return false
}
; A dialog/file operation may have allowed another hotkey thread to run.
return this._CanReplaceProject()
}
_ReplaceProject(project) {
this.project := project
this.undoMgr.Clear()
this.gui.selectedActionId := ""
this.RegisterGlobalStudioHotkeys()
this.gui.RefreshAll()
}
CmdNewProject() {
if !this._ConfirmProjectReplacement()
return false
this._ReplaceProject(ProjectModel("Untitled Project"))
this.ShowToast("Created new project.")
return true
}
CmdOpenProject(filePath := "") {
if !this._CanReplaceProject() {
this.ShowToast("Stop playback, recording and selection before opening a project.")
return false
}
if filePath == "" {
filePath := FileSelect(1, , "Open Nichols Macro Studio Project", "Nichols Macro Studio Project (*.json; *.ahkproj)")
if filePath == ""
return false
}
try {
if !this._ConfirmProjectReplacement()
return false
candidate := this.persistence.LoadProject(filePath)
if !this._CanReplaceProject()
return false
this._ReplaceProject(candidate)
this.ShowToast("Opened project: " this.project.Name)
return true
} catch as err {
MsgBox("Could not open project file:`n`n" err.Message, "Open Project Error", "Iconx")
return false
}
}
CmdSaveProject(saveAs := false) {
targetPath := this.project.FilePath
if saveAs || targetPath == "" {
defaultName := RegExReplace(this.project.Name, "[^\w\- ]", "_") ".json"
targetPath := FileSelect("S16", defaultName, "Save Nichols Macro Studio Project", "Nichols Macro Studio Project (*.json)")
if targetPath == ""
return false
}
try {
this.persistence.SaveProject(this.project, targetPath)
this.gui.RefreshTitleBar()
; Non-modal status feedback (Section 98: No routine MessageBox on Save)
this.ShowToast("Saved project to " targetPath)
return true
} catch as err {
MsgBox("Failed to save project:`n`n" err.Message, "Save Error", "Iconx")
return false
}
}
CmdUndo() {
if !this._CanReplaceProject()
return
if !this.undoMgr.CanUndo() {
this.ShowToast("Nothing to Undo.")
return
}
lbl := this.undoMgr.GetUndoLabel()
restored := this.undoMgr.Undo(this.project)
if IsObject(restored) {
this.project := restored
this.RegisterGlobalStudioHotkeys()
this.gui.RefreshAll()
this.ShowToast(lbl)
}
}
CmdRedo() {
if !this._CanReplaceProject()
return
if !this.undoMgr.CanRedo() {
this.ShowToast("Nothing to Redo.")
return
}
lbl := this.undoMgr.GetRedoLabel()
restored := this.undoMgr.Redo(this.project)
if IsObject(restored) {
this.project := restored
this.RegisterGlobalStudioHotkeys()
this.gui.RefreshAll()
this.ShowToast(lbl)
}
}
CmdToggleRecord(mode := "Simple") {
if this.playback.isRunning {
this.playback.EmergencyStop()
return
}
if this.recorder.isRecording {
this.recorder.StopRecording()
} else {
mac := this.project.GetActiveMacro()
this.recorder.StartRecording(mode, mac, "")
this.ShowToast(mode " Recording started — Perform actions naturally, then press F3 to stop.")
}
}
CmdRecordAfterSelected() {
if this.recorder.isRecording {
this.recorder.StopRecording()
return
}
mac := this.project.GetActiveMacro()
this.recorder.StartRecording("Simple", mac, this.gui.selectedActionId)
this.ShowToast("Recording after selected step — Press F3 when done.")
}
OnRecordingFinished(recordedActions) {
this.gui.RefreshAll()
mac := this.project.GetActiveMacro()
upgrades := RecordingAnalyzer.AnalyzeMacro(mac, this.uiaEngine, this.browserMgr)
if upgrades.Length > 0
this.ShowToast(Format("{1} actions recorded ({2} smart improvements available — click '✨ Review').", recordedActions.Length, upgrades.Length))
else
this.ShowToast(Format("{1} actions recorded.", recordedActions.Length))
}
CmdPlay() {
if this.recorder.isRecording {
this.ShowToast("Stop recording (F3) before starting playback.")
return
}
mac := this.project.GetActiveMacro()
this.playback.PlayMacro(mac, 1, 0, false)
this.gui.RefreshWorkflowList()
this.gui.RefreshVariablesPanel()
this.gui.RefreshSessionsPanels()
}
CmdPauseResume() {
if !this.playback.isRunning
return
if this.playback.isPaused {
this.playback.Resume()
this.ShowToast("Playback resumed.")
} else {
this.playback.Pause()
this.ShowToast("Playback paused.")
}
}
CmdEmergencyStop() { ; [NMS-PA-03] stop EVERYTHING that is active (no early return), then always release inputs
stopNotes := []
wasRunning := false
try wasRunning := !!this.playback.isRunning
if wasRunning {
try {
this.playback.EmergencyStop()
stopNotes.Push("playback halted")
}
}
try {
if this.selectionEngine.isActive {
this.selectionEngine.CancelSelection()
stopNotes.Push("selection cancelled")
}
}
try {
if this.recorder.isRecording {
this.recorder.StopRecording()
stopNotes.Push("recording stopped")
}
}
try this.playback.ReleaseHeldInputs()
try this.overlayMgr.HideAll()
if !wasRunning
try this.SetState(StudioConstants.StateIdle)
stopMsg := ""
for stopItem in stopNotes
stopMsg .= (stopMsg = "" ? "" : "; ") stopItem
if stopMsg = ""
stopMsg := "all operations idle"
try this.ShowToast("Emergency Stop: " stopMsg ".")
}
CmdRunSelectedStep() {
act := this.gui.GetSelectedAction()
if !IsObject(act)
return
mac := this.project.GetActiveMacro()
tempMac := MacroModel.FromMap(mac.ToMap())
tempMac.Actions := [act]
this.playback.PlayMacro(tempMac)
res := ActionResultModel(!this.playback.stopRequested, act.RuntimeStatus, "Selected step finished; see log.")
act.RuntimeStatus := res.Status
this.gui.RefreshWorkflowList()
this.gui.RefreshVariablesPanel()
this.ShowToast("Step Result: " res.Status " — " res.Message)
}
CmdRunFromHere() {
act := this.gui.GetSelectedAction()
mac := this.project.GetActiveMacro()
startIdx := 1
if IsObject(act) {
for idx, topAct in mac.Actions {
if topAct.Id == act.Id {
startIdx := idx
break
}
}
}
this.playback.PlayMacro(mac, startIdx, 0, false)
this.gui.RefreshWorkflowList()
}
CmdRunToHere() {
act := this.gui.GetSelectedAction()
mac := this.project.GetActiveMacro()
endIdx := mac.Actions.Length
if IsObject(act) {
for idx, topAct in mac.Actions {
if topAct.Id == act.Id {
endIdx := idx
break
}
}
}
this.playback.PlayMacro(mac, 1, endIdx, false)
this.gui.RefreshWorkflowList()
}
CmdStepNext() {
if this.playback.isRunning {
this.playback.StepNext()
} else {
mac := this.project.GetActiveMacro()
this.playback.PlayMacro(mac, 1, 0, true)
}
}
_ConfirmInteractiveExportIfNeeded() {
warns := AHKExporter.CheckInteractiveExportWarnings(this.project)
if warns.Length == 0
return true
wTxt := ""
for _, w in warns
wTxt .= "• " w "`r`n"
ans := MsgBox("Unattended Export Notice:`n`nThe project uses interactive policies or checkpoints that may pause for user input during unattended runs:`n`n" wTxt "`nContinue exporting anyway?", "Interactive Policy Warning", "YesNo Icon!")
return ans == "Yes"
}
CmdExportAhk() => ExportOptionsUI(this, "AHK")
CmdBuildExe() => ExportOptionsUI(this, "EXE")
CmdResetSettings() {
ans := MsgBox("Reset all application preferences and hotkeys to factory defaults?", "Reset Settings", "YesNo Icon?")
if ans == "Yes" {
this.persistence.ResetSettingsToDefault()
this.persistence.SaveSettings()
this.RegisterGlobalStudioHotkeys()
this.ShowToast("Settings reset to defaults.")
}
}
; ==========================================================================
; DETERMINISTIC GLOBAL RESOURCE CLEANUP (Section 135)
; Cleans hooks, timers, overlays, dynamic hotkeys, and disposable fixtures.
; ==========================================================================
CleanupAllResources() {
if IsObject(this.gui)
this.gui.CloseAboutDialog()
if IsObject(this.playback) {
this.playback.stopRequested := true
this.playback.isPaused := false
this.playback.ReleaseHeldInputs()
}
if IsObject(this.recorder) {
this.recorder.isRecording := false
this.recorder._UninstallHooks()
for name in ["queueTimer", "advHoverTimer"] {
if this.recorder.%name% != ""
SetTimer(this.recorder.%name%, 0)
this.recorder.%name% := ""
}
}
if this.HasOwnProp("activityDisplay")
this.activityDisplay.Clear(false)
if IsObject(this.gui) && this.gui.HasOwnProp("helpCallback")
OnMessage(0x200, this.gui.helpCallback, 0)
if IsObject(this.gui) && this.gui.HasOwnProp("pointerDownCallback")
OnMessage(0x201, this.gui.pointerDownCallback, 0)
if IsObject(this.gui) {
for timerName in ["paneDragTimer", "workflowDragTimer", "resizeTimer", "deselectTimer"]
if this.gui.HasOwnProp(timerName)
SetTimer(this.gui.%timerName%, 0)
}
ToolTip()
if this.autosaveTimer != "" {
try SetTimer(this.autosaveTimer, 0)
this.autosaveTimer := ""
}
if IsObject(this.recorder) {
this.recorder.isRecording := false
this.recorder._UninstallHooks()
}
if IsObject(this.selectionEngine) {
this.selectionEngine._CleanupSelectionState()
}
if IsObject(this.playback) {
this.playback.stopRequested := true
this.playback.isPaused := false
this.playback.ReleaseHeldInputs()
}
this.UnregisterGlobalStudioHotkeys()
if IsObject(this.overlayMgr) {
this.overlayMgr.DestroyAll()
}
DiagnosticsEngine.CleanupHtmlFixture()
if IsObject(this.persistence) {
this.persistence.SaveSettings()
this.persistence.MarkCleanExit()
}
}
ShutdownAndExit() { ; [NMS-PA-05] cleanup failure must not block exit; always release inputs first
try {
if this.playback.isRunning
this.playback.EmergencyStop()
}
try this.playback.ReleaseHeldInputs()
try this.CleanupAllResources()
ExitApp(0)
}
_OnProcessExit(exitReason, exitCode) { ; [NMS-PA-06] release inputs even if cleanup throws
try this.playback.ReleaseHeldInputs()
try this.CleanupAllResources()
}
}
; ==============================================================================
; [NMS-PD-05] StudioSafety module inlined so the app is one self-contained file
class StudioSafety {
; ---- Injectable side-effect hooks (tests replace these) -----------------
; Always call via .Call(...) — in v2, obj.prop(x) would pass obj as `this`.
static Sender := (keys) => SendEvent(keys)
static Clicker := (options) => Click(options)
static KeySender := (keys) => Send(keys)
static TextSender := (text) => SendText(text)
static KeyState := (key, mode := "") => GetKeyState(key, mode)
static Modifiers := ["LCtrl", "RCtrl", "LAlt", "RAlt", "LShift", "RShift", "LWin", "RWin"]
static Buttons := ["LButton", "RButton", "MButton", "XButton1", "XButton2"]
; ---- Mouse button name -> AHK key name (NMS-008) -----------------------
static ButtonKey(btn) {
static m := StudioSafety._BuildButtonMap()
k := Trim(String(btn))
if m.Has(k)
return m[k]
throw ValueError("Unsupported mouse button: '" btn "'. Use Left, Right, Middle, X1 or X2.")
}
static _BuildButtonMap() {
m := Map()
m.CaseSense := false
for pair in [["Left", "LButton"], ["L", "LButton"], ["LButton", "LButton"]
, ["Right", "RButton"], ["R", "RButton"], ["RButton", "RButton"]
, ["Middle", "MButton"], ["M", "MButton"], ["MButton", "MButton"]
, ["X1", "XButton1"], ["XButton1", "XButton1"]
, ["X2", "XButton2"], ["XButton2", "XButton2"]]
m[pair[1]] := pair[2]
return m
}
; ---- Input release (NMS-001, NMS-003) -----------------------------------
; 1) Releases everything tracked in `held` (Map key -> kind), deleting each
; entry only when its key-up was sent successfully.
; 2) Releases any modifier/button that is logically down but NOT physically
; down (synthetic and stuck). Keys the user is really holding are left.
; 3) Before releasing Alt/Win, sends the menu-mask key vkE8 so a lone
; Alt-up / Win-up cannot open the menu bar or Start menu.
; Idempotent. Physical state ("P") is only accurate with the keyboard and
; mouse hooks installed (PATCHES.md P0/P2).
static ReleaseAll(held := "", includeSynthetic := true) {
result := Map("Released", [], "Failed", [])
if IsObject(held) {
for key, kind in held.Clone() {
try {
StudioSafety.Sender.Call("{Blind}{" key " up}")
held.Delete(key)
result["Released"].Push(key)
} catch {
result["Failed"].Push(key)
}
}
}
if !includeSynthetic
return result
stuck := []
for k in StudioSafety.Modifiers
if StudioSafety._IsSyntheticDown(k)
stuck.Push(k)
for b in StudioSafety.Buttons
if StudioSafety._IsSyntheticDown(b)
stuck.Push(b)
if !stuck.Length
return result
needMask := false
for k in stuck
if RegExMatch(k, "i)alt|win")
needMask := true
if needMask
try StudioSafety.Sender.Call("{Blind}{vkE8}")
for k in stuck {
try {
StudioSafety.Sender.Call("{Blind}{" k " up}")
result["Released"].Push(k)
} catch {
result["Failed"].Push(k)
}
}
return result
}
static _IsSyntheticDown(key) {
try return StudioSafety.KeyState.Call(key, "") && !StudioSafety.KeyState.Call(key, "P")
return false
}
; ---- Track {Key down}/{Key up} tokens inside Send strings (NMS-003) -----
; Returns [[key, "down"|"up"], ...]. "{Down}" (arrow) is NOT a hold token.
static ParseSendDownUp(keys) {
out := []
pos := 1
while pos := RegExMatch(String(keys), "i)\{\s*([^\s{}]+)\s+(downtemp|downr|down|up)\s*\}", &m, pos) {
out.Push([m[1], StrLower(m[2]) = "up" ? "up" : "down"])
pos += m.Len
}
return out
}
static ApplySendTracking(held, keys) {
for tok in StudioSafety.ParseSendDownUp(keys) {
if tok[2] = "down"
held[tok[1]] := "Key"
else if held.Has(tok[1])
held.Delete(tok[1])
}
return held
}
; ---- Hotkey string helpers (NMS-004, -020, -068) -----------------------
static HotkeyBase(hk) {
s := Trim(String(hk))
s := RegExReplace(s, "i)\s+up$")
if InStr(s, " & ") {
parts := StrSplit(s, "&")
s := Trim(parts[parts.Length])
}
return StrLower(RegExReplace(s, "^[~*$<>^!+#]+"))
}
static HotkeyCanon(hk) {
s := Trim(String(hk))
RegExMatch(s, "^[~*$<>^!+#]*", &m)
prefix := m[0]
mods := ""
for c in ["^", "!", "+", "#"]
if InStr(prefix, c)
mods .= c
return mods "|" StudioSafety.HotkeyBase(s)
}
static IsWildcard(hk) {
RegExMatch(Trim(String(hk)), "^[~*$<>^!+#]*", &m)
return InStr(m[0], "*") > 0
}
static IsReservedCombo(keyName, ctrl, alt, shift, win, reserved) {
base := StrLower(Trim(String(keyName)))
mods := (ctrl ? "^" : "") (alt ? "!" : "") (shift ? "+" : "") (win ? "#" : "")
for hk in reserved {
if Trim(String(hk)) = ""
continue
if StudioSafety.HotkeyBase(hk) != base
continue
if StudioSafety.IsWildcard(hk)
return true
if StrSplit(StudioSafety.HotkeyCanon(hk), "|")[1] == mods
return true
}
return false
}
static TriggerConflict(trigger, stopHk, otherHks) {
if Trim(String(trigger)) = ""
return ""
if StudioSafety.HotkeyBase(trigger) = StudioSafety.HotkeyBase(stopHk)
return "uses the Emergency Stop key (" stopHk ")"
c := StudioSafety.HotkeyCanon(trigger)
for hk in otherHks
if Trim(String(hk)) != "" && StudioSafety.HotkeyCanon(hk) = c
return "duplicates studio hotkey " hk
return ""
}
; ---- Recorder text acceptance (NMS-017 AltGr) ---------------------------
static AcceptTypedChars(ctrlP, lctrlP, raltP, lwinP, rwinP) {
altGr := lctrlP && raltP
return (altGr || !ctrlP) && !lwinP && !rwinP
}
; ---- Secret field detection, one shared rule (NMS-027) -----------------
static IsSecretName(text) {
s := RegExReplace(String(text), "([a-z0-9])([A-Z])", "$1 $2")
return RegExMatch(s, "i)(? 0
}
; ---- Safe numeric parsing (NMS-030, -037, -069) ------------------------
static SafeInt(v, def := 0, lo := "", hi := "") {
if IsObject(v)
return def
s := Trim(String(v))
if !IsNumber(s)
return def
n := Integer(Round(Number(s)))
if lo != "" && n < lo
n := lo
if hi != "" && n > hi
n := hi
return n
}
; ---- Wheel burst merging (NMS-022) --------------------------------------
static CanMergeWheel(prevHwnd, prevTick, prevDir, hwnd, tick, dir, gapMs := 300) {
return prevHwnd = hwnd && prevDir = dir && (tick - prevTick) >= 0 && (tick - prevTick) <= gapMs
}
static WheelNotches(sumDelta) {
return sumDelta = 0 ? 0 : Max(1, Round(Abs(sumDelta) / 120))
}
; ---- State model (NMS-026) ----------------------------------------------
static IsLegalTransition(from, to) {
static t := Map("Idle", "|Recording|Advanced Recording|Running|"
, "Recording", "|Idle|"
, "Advanced Recording", "|Idle|"
, "Running", "|Paused|Stopping|Idle|"
, "Paused", "|Running|Stopping|Idle|"
, "Stopping", "|Idle|")
if from == to || to == "Idle"
return true
return t.Has(from) && InStr(t[from], "|" to "|") > 0
}
; ---- Call boundary (NMS-046) --------------------------------------------
static CallBoundarySignal(sig) {
return (sig == "BREAK" || sig == "CONTINUE") ? "" : sig
}
; ---- Fault-isolated step runner (NMS-007) -------------------------------
static RunSteps(steps) {
errors := []
for step in steps {
try step[2].Call()
catch as e
errors.Push(step[1] ": " e.Message)
}
return errors
}
; ---- Durable atomic write (NMS-029) -------------------------------------
; Temp file in the SAME folder -> FlushFileBuffers -> MoveFileExW
; (REPLACE_EXISTING|WRITE_THROUGH), bounded retry for external locks.
; On failure: temp removed, original untouched, throws.
static AtomicWrite(targetPath, content, encoding := "UTF-8", retries := 5, retryMs := 50) {
SplitPath(targetPath, , &dir)
if dir != "" && !DirExist(dir)
DirCreate(dir)
tmp := targetPath ".tmp" DllCall("Kernel32\GetCurrentProcessId", "UInt") "_" A_TickCount
try {
f := FileOpen(tmp, "w", encoding)
try {
f.Write(content)
if !DllCall("Kernel32\FlushFileBuffers", "Ptr", f.Handle, "Int")
throw OSError(A_LastError, , "FlushFileBuffers")
} finally {
f.Close()
}
lastErr := 0
Loop Max(1, retries) {
if DllCall("Kernel32\MoveFileExW", "Str", tmp, "Str", targetPath, "UInt", 0x1 | 0x8, "Int")
return true
lastErr := A_LastError
if A_Index < retries
Sleep(retryMs)
}
throw OSError(lastErr, , "MoveFileExW " targetPath)
} catch as err {
try FileDelete(tmp)
throw err
}
}
}
; APPLICATION ENTRY POINT
; ==============================================================================
for arg in A_Args {
if arg == "--qa"
StudioUtils.UseTestStorage()
}
StudioBranding.Apply()
global g_StudioApp := StudioApp()
g_StudioApp.Start(A_Args)
; ==================== BEGIN VENDORED UIA-v2 ====================
/*
VENDORED UPSTREAM LIBRARY: Descolada/UIA-v2
Repository URL : https://github.com/Descolada/UIA-v2
Source Files : Lib/UIA.ahk, Lib/UIA_Browser.ahk
Upstream Commit : 2846a9b10518a95cf26a6c43671a9512b231ccb7 (2026-04-23T19:45:32Z)
Retrieval Date : 2026-10-17
Integration Note: Disabled top-level standalone UIA.Viewer() auto-execution check
(if !A_IsCompiled && A_LineFile = A_ScriptFullPath) so embedding
inside Nichols Macro Studio.ahk does not trigger standalone viewer mode.
All upstream classes (UIA, UIA_Browser, UIA_Chrome, UIA_Edge,
UIA_Mozilla, UIA_Brave, UIA_Vivaldi) are preserved intact.
LICENSE (MIT):MIT License
Copyright (c) 2023 Descolada
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
/*
Introduction & credits
This library implements Microsoft's UI Automation framework.
Microsoft's official documentation:: https://docs.microsoft.com/en-us/windows/win32/winauto/entry-uiauto-win32
Author: Descolada
Credits: thqby, neptercn (v1), jethrow (AHK v1 UIA library)
A lot of modifications have been added to the original UIA framework, such as custom methods for elements (eg element.Click())
Usage:
All main UIA methods and properties can be accessed through the UIA variable.
Eg UIA.GetRootElement()
Additionally some extra variables are initialized:
UIA.IUIAutomationVersion contains the version number of IUIAutomation interface
UIA.TrueCondition contains a TrueCondition
UIA.TreeWalkerTrue contains a TreeWalker with the TrueCondition
UIA is initialized only once, on the first use of UIA.
The initalized IUIAutomation version depends on the system, but the most recent version is automatically used.
If the version needs to be limited, then set the IUIAutomationMaxVersion global variable before the first use of UIA.
On initialization, SPI_SETSCREENREADER is also called to notify the system of UIA use. This is needed for some programs (such as VSCode).
UIAutomation constants and enumerations are also available in the UIA variable. Eg. UIA.Property.Name contains the UIA_NamePropertyId value.
Microsoft documentation for constants and enumerations:
UI Automation Constants: https://docs.microsoft.com/en-us/windows/win32/winauto/uiauto-entry-constants
UI Automation Enumerations: https://docs.microsoft.com/en-us/windows/win32/winauto/uiauto-entry-enumerations
*/
/*
Questions:
- if method returns a SafeArray, should we return a Wrapped SafeArray, Raw SafeArray, or AHK Array. Currently we return wrapped AHK arrays for SafeArrays. Although SafeArrays are more convenient to loop over, this causes more confusion in users who are not familiar with SafeArrays (questions such as why are they 0-indexed not 1-indexed, why doesnt for k, v in SafeArray work properly etc).
- on UIA Interface conversion methods, how should the data be returned? wrapped/extracted or raw? should raw data be a ByRef param?
- Cached Members?
- UIA Element existance - dependent on window being visible (non minimized), and also sometimes Elements are lazily generated (eg Microsoft Teams, when a meeting is started then the toolbar buttons (eg Mute, react) aren't visible to UIA, but hovering over them with the cursor or calling ElementFromPoint causes Teams to generate and make them visible to UIA.
- better way of supporting differing versions of IUIAutomation (version 2, 3, 4)
- Get methods vs property getter: currently we use properties when the item stores data, fetching the data is "cheap" and when it doesn't have side-effects, and in computationally expensive cases use Get...().
- should ElementFromHandle etc methods have activateChromiumAccessibility set to True or False? Currently is True, because Chromium apps are very common, and checking whether its on should be relatively fast.
Design choices:
- ElementArrays are converted to AHK arrays automatically. This is because speed-testing has shown
that they are either equal, or AHK array comes on top by far. The situation where it loses to the
native one is when we need to get exactly one element from the array and won't use it more. This
is optimized by using the native ElementArray in cases of Element[integer].
To-do:
- Better error handling
*/
; [Nichols Macro Studio Vendoring Adjustment] Disabled standalone auto-launch of UIA.Viewer() when embedded in single-file executable.
class UIA {
; Semantic version of the UIA library
static Version => "1.1.3"
/**
* First use of UIA variable initiates UIA, UIA.IUIAutomationVersion, UIA.TrueCondition and
* UIA.TreeWalkerTrue. Also enables screen reader with SPI_SETSCREENREADER.
* Initialized IUIAutomation version can be altered with changing the global IUIAutomationMaxVersion
* variable, which by default is set to the latest available UIA version.
*/
static __New() {
global IUIAutomationMaxVersion := IUIAutomationMaxVersion ?? 7
, IUIAutomationActivateScreenReader := IUIAutomationActivateScreenReader ?? 1
, IUIAutomationDllPath := IUIAutomationDllPath ?? ""
this.IUIAutomationVersion := IUIAutomationMaxVersion+1, this.ptr := 0
; The following is a partial head-way into making the UIA class name-agnostic (that is, making it possible to rename and reference UIA more easily, eg when wrapped inside inside another class).
; UIA static methods have been converted this way, but IUIAutomationElement runs into a problem: namely the syntax highlighter is unable to detect that IUIAutomationElement has been made to
; extend IUIAutomationBase with this.IUIAutomationElement.base := this.IUIAutomationBase and thus shows "problems" for each UIA.IUIAutomationElement() call
this.prototype.__UIA := this ; Allows referencing UIA static without using the class name
, this.Cleanup.prototype.__UIA := this ; inject reference to UIA in Cleanup. This must be before the next line, since Cleanup gets initiated there
static __IID := {
IUIAutomation:"{30cbe57d-d9d0-452a-ab13-7ac5ac4825ee}",
IUIAutomation2:"{34723aff-0c9d-49d0-9896-7ab52df8cd8a}",
IUIAutomation3:"{73d768da-9b51-4b89-936e-c209290973e7}",
IUIAutomation4:"{1189c02a-05f8-4319-8e21-e817e3db2860}",
IUIAutomation5:"{25f700c8-d816-4057-a9dc-3cbdee77e256}",
IUIAutomation6:"{aae072da-29e3-413d-87a7-192dbf81ed10}",
IUIAutomation7:"{29de312e-83c6-4309-8808-e8dfcb46c3c2}",
IClassFactory:"{00000001-0000-0000-c000-000000000046}"
},
__CLSID := {
CUIAutomation:"{ff48dba4-60ef-4201-aa87-54103eef594e}",
CUIAutomation8:"{e22ad333-b25f-460c-83d0-0581107395c9}"
}, __Cleanup := this.Cleanup()
if (IUIAutomationDllPath != "") {
hModule := DllCall("LoadLibrary", "Str", IUIAutomationDllPath, "Ptr")
if !hModule
throw Error("Failed to load custom UIA DLL",, IUIAutomationDllPath)
pDllGetClassObject := DllCall("GetProcAddress", "Ptr", hModule, "AStr", "DllGetClassObject", "Ptr")
if !pDllGetClassObject
throw Error("Failed to get custom UIA DllGetClassObject")
DllCall("ole32\CLSIDFromString", "Str", __CLSID.CUIAutomation8, "Ptr", CLSID_CUIAutomation8 := Buffer(16))
DllCall("ole32\IIDFromString", "Str", __IID.IClassFactory, "Ptr", IID_IClassFactory := Buffer(16))
if DllCall(pDllGetClassObject, "Ptr", CLSID_CUIAutomation8, "Ptr", IID_IClassFactory, "Ptr*", ppFactory := ComValue(13, 0))
goto RegularCUI
while (--this.IUIAutomationVersion > 1) {
if !__IID.HasOwnProp("IUIAutomation" this.IUIAutomationVersion)
continue
try {
DllCall("ole32\IIDFromString", "Str", __IID.IUIAutomation%(this.IUIAutomationVersion)%, "Ptr", IID := Buffer(16))
ComCall(3, ppFactory, "Ptr", 0, "Ptr", IID, "Ptr*", &ppAutomation:=0)
if !ppAutomation
continue
this.ptr := ppAutomation
break
}
}
RegularCUI:
if !this.HasOwnProp("ptr") || (this.HasOwnProp("ptr") && !this.ptr) {
DllCall("ole32\CLSIDFromString", "Str", __CLSID.CUIAutomation, "Ptr", CLSID_CUIAutomation := Buffer(16))
if DllCall(pDllGetClassObject, "Ptr", CLSID_CUIAutomation, "Ptr", IID_IClassFactory, "Ptr*", ppFactory := ComValue(13, 0))
throw Error("Failed to get CUIAutomation class factory")
DllCall("ole32\IIDFromString", "Str", __IID.IUIAutomation, "Ptr", IID := Buffer(16))
ComCall(3, ppFactory, "Ptr", 0, "Ptr", IID, "Ptr*", &ppAutomation:=0)
if !ppAutomation
throw Error("Failed to initialize UIA from custom DLL")
this.ptr := ppAutomation
}
} else {
while (--this.IUIAutomationVersion > 1) {
if !__IID.HasOwnProp("IUIAutomation" this.IUIAutomationVersion)
continue
try {
this.ptr := ComObjValue(this.__ := ComObject(__CLSID.CUIAutomation8, __IID.IUIAutomation%(this.IUIAutomationVersion)%))
break
}
}
; If all else fails, try the first IUIAutomation version
if !this.HasOwnProp("ptr") || (this.HasOwnProp("ptr") && !this.ptr)
this.ptr := ComObjValue(this.__ := ComObject(__CLSID.CUIAutomation, __IID.IUIAutomation))
}
this.TrueCondition := this.CreateTrueCondition(), this.TreeWalkerTrue := this.CreateTreeWalker(this.TrueCondition)
; Define some properties that shouldn't be included in the value->name Map
this.Property[30000], this.Property.T := 30003, this.Property.ControlType := 30003, this.Property.N := 30005, this.Property.CN := 30012, this.Property.A := 30011
}
class Cleanup {
__New() {
global IUIAutomationActivateScreenReader
this.ScreenReaderStartingState := this.__UIA.GetScreenReader()
if IUIAutomationActivateScreenReader && !this.ScreenReaderStartingState
this.__UIA.SetScreenReader(1)
}
__Delete() {
global IUIAutomationActivateScreenReader
try this.__UIA.RemoveAllEventHandlers()
if IUIAutomationActivateScreenReader && !this.ScreenReaderStartingState
DllCall("user32.dll\SystemParametersInfo", "uint", 0x0047, "uint", this.ScreenReaderStartingState, "int", 0, "uint", 2) ; SPI_SETSCREENREADER
}
}
; ---------- IUIAutomation constants and enumerations. ----------
class Enumeration {
; This is enables getting property names from values using the array style
__Item[param] {
get {
local k, v
if !this.HasOwnProp("__CachedValues") {
this.__CachedValues := Map()
for k, v in this.OwnProps()
this.__CachedValues[v] := k
}
if this.__CachedValues.Has(param)
return this.__CachedValues[param]
throw UnsetItemError("Property item `"" param "`" not found!", -2)
}
}
HasValue(val) {
if !this.HasOwnProp("__CachedValues")
try this[0]
if this.__CachedValues.Has(val)
return this.__CachedValues[val]
return 0
}
}
; Access properties with UIA.property.subproperty (UIA.Type.Button)
; To get the property name from value, use the array style: UIA.property[value] (UIA.Type[50000] == "Button")
; enum MatchMode Contains string comparison options used in various methods involving element comparison with condition.
static MatchMode := {StartsWith:1, Substring:2, Exact:3, RegEx:"RegEx", base:this.Enumeration.Prototype}
; enum CaseSense Contains CaseSense options used in various methods involving element comparison with condition.
static CaseSense := {Off:0, On:1, Default:1, base:this.Enumeration.Prototype}
; enum Type (alias ControlType) Contains UI element types, which are used to identify the capabilities of a control and to determine how to interact with it.
static Type := {Button:50000,Calendar:50001,CheckBox:50002,ComboBox:50003,Edit:50004,Link:50005, Hyperlink:50005,Image:50006,ListItem:50007,List:50008,Menu:50009,MenuBar:50010,MenuItem:50011,ProgressBar:50012,RadioButton:50013,ScrollBar:50014,Slider:50015,Spinner:50016,StatusBar:50017,Tab:50018,TabItem:50019,Text:50020,ToolBar:50021,ToolTip:50022,Tree:50023,TreeItem:50024,Custom:50025,Group:50026,Thumb:50027,DataGrid:50028,DataItem:50029,Document:50030,SplitButton:50031,Window:50032,Pane:50033,Header:50034,HeaderItem:50035,Table:50036,TitleBar:50037,Separator:50038,SemanticZoom:50039,AppBar:50040, base:this.Enumeration.Prototype}
static ControlType := this.Type ; Alias definition
; enum Pattern Contains interface names used to control a particular aspect of a control's functionality. These can be used to retrieve information about a particular capability of the control, or to manipulate a particular aspect of the control's behavior.
static Pattern := {Invoke: 10000, Selection: 10001, Value: 10002, RangeValue: 10003, Scroll: 10004, ExpandCollapse: 10005, Grid: 10006, GridItem: 10007, MultipleView: 10008, Window: 10009, SelectionItem: 10010, Dock: 10011, Table: 10012, TableItem: 10013, Text: 10014, Toggle: 10015, Transform: 10016, ScrollItem: 10017, LegacyIAccessible: 10018, ItemContainer: 10019, VirtualizedItem: 10020, SynchronizedInput: 10021, ObjectModel: 10022, Annotation: 10023, Text2:10024, Styles: 10025, Spreadsheet: 10026, SpreadsheetItem: 10027, Transform2: 10028, TextChild: 10029, Drag: 10030, DropTarget: 10031, TextEdit: 10032, CustomNavigation: 10033, Selection2: 10034, base:this.Enumeration.Prototype}
; enum Event Contains event types evoked by changes in the user interface. Listeners to these can be registered with CreateEventHandler.
static Event := {ToolTipOpened:20000,ToolTipClosed:20001,StructureChanged:20002,MenuOpened:20003,AutomationPropertyChanged:20004,AutomationFocusChanged:20005,AsyncContentLoaded:20006,MenuClosed:20007,LayoutInvalidated:20008,Invoke_Invoked:20009,SelectionItem_ElementAddedToSelection:20010,SelectionItem_ElementRemovedFromSelection:20011,SelectionItem_ElementSelected:20012,Selection_Invalidated:20013,Text_TextSelectionChanged:20014,Text_TextChanged:20015,Window_WindowOpened:20016,Window_WindowClosed:20017,MenuModeStart:20018,MenuModeEnd:20019,InputReachedTarget:20020,InputReachedOtherElement:20021,InputDiscarded:20022,SystemAlert:20023,LiveRegionChanged:20024,HostedFragmentRootsInvalidated:20025,Drag_DragStart:20026,Drag_DragCancel:20027,Drag_DragComplete:20028,DropTarget_DragEnter:20029,DropTarget_DragLeave:20030,DropTarget_Dropped:20031,TextEdit_TextChanged:20032,TextEdit_ConversionTargetChanged:20033,Changes:20034,Notification:20035,ActiveTextPositionChanged:20036, base:this.Enumeration.Prototype}
; enum Property Contains property names and ids that expose properties on UI Automation elements
static Property := {RuntimeId:30000,Id:30000,BoundingRectangle:30001,Location:30001,ProcessId:30002,ControlType:30003,Type:30003,LocalizedControlType:30004, LocalizedType:30004,Name:30005,AcceleratorKey:30006,AccessKey:30007,HasKeyboardFocus:30008,IsKeyboardFocusable:30009,IsEnabled:30010,AutomationId:30011,ClassName:30012,HelpText:30013,ClickablePoint:30014,Culture:30015,IsControlElement:30016,IsContentElement:30017,LabeledBy:30018,IsPassword:30019,NativeWindowHandle:30020,ItemType:30021,IsOffscreen:30022,Orientation:30023,FrameworkId:30024,IsRequiredForForm:30025,ItemStatus:30026,IsDockPatternAvailable:30027,IsExpandCollapsePatternAvailable:30028,IsGridItemPatternAvailable:30029,IsGridPatternAvailable:30030,IsInvokePatternAvailable:30031,IsMultipleViewPatternAvailable:30032,IsRangeValuePatternAvailable:30033,IsScrollPatternAvailable:30034,IsScrollItemPatternAvailable:30035,IsSelectionItemPatternAvailable:30036,IsSelectionPatternAvailable:30037,IsTablePatternAvailable:30038,IsTableItemPatternAvailable:30039,IsTextPatternAvailable:30040,IsTogglePatternAvailable:30041,IsTransformPatternAvailable:30042,IsValuePatternAvailable:30043,IsWindowPatternAvailable:30044,ValueValue:30045,Value:30045,ValueIsReadOnly:30046,RangeValueValue:30047,RangeValueIsReadOnly:30048,RangeValueMinimum:30049,RangeValueMaximum:30050,RangeValueLargeChange:30051,RangeValueSmallChange:30052,ScrollHorizontalScrollPercent:30053,ScrollHorizontalViewSize:30054,ScrollVerticalScrollPercent:30055,ScrollVerticalViewSize:30056,ScrollHorizontallyScrollable:30057,ScrollVerticallyScrollable:30058,SelectionSelection:30059,SelectionCanSelectMultiple:30060,SelectionIsSelectionRequired:30061,GridRowCount:30062,GridColumnCount:30063,GridItemRow:30064,GridItemColumn:30065,GridItemRowSpan:30066,GridItemColumnSpan:30067,GridItemContainingGrid:30068,DockDockPosition:30069,ExpandCollapseExpandCollapseState:30070,MultipleViewCurrentView:30071,MultipleViewSupportedViews:30072,WindowCanMaximize:30073,WindowCanMinimize:30074,WindowWindowVisualState:30075,WindowWindowInteractionState:30076,WindowIsModal:30077,WindowIsTopmost:30078,SelectionItemIsSelected:30079,SelectionItemSelectionContainer:30080,TableRowHeaders:30081,TableColumnHeaders:30082,TableRowOrColumnMajor:30083,TableItemRowHeaderItems:30084,TableItemColumnHeaderItems:30085,ToggleToggleState:30086,TransformCanMove:30087,TransformCanResize:30088,TransformCanRotate:30089,IsLegacyIAccessiblePatternAvailable:30090,LegacyIAccessibleChildId:30091,LegacyIAccessibleName:30092,LegacyIAccessibleValue:30093,LegacyIAccessibleDescription:30094,LegacyIAccessibleRole:30095,LegacyIAccessibleState:30096,LegacyIAccessibleHelp:30097,LegacyIAccessibleKeyboardShortcut:30098,LegacyIAccessibleSelection:30099,LegacyIAccessibleDefaultAction:30100,AriaRole:30101,AriaProperties:30102,IsDataValidForForm:30103,ControllerFor:30104,DescribedBy:30105,FlowsTo:30106,ProviderDescription:30107,IsItemContainerPatternAvailable:30108,IsVirtualizedItemPatternAvailable:30109,IsSynchronizedInputPatternAvailable:30110,OptimizeForVisualContent:30111,IsObjectModelPatternAvailable:30112,AnnotationAnnotationTypeId:30113,AnnotationAnnotationTypeName:30114,AnnotationAuthor:30115,AnnotationDateTime:30116,AnnotationTarget:30117,IsAnnotationPatternAvailable:30118,IsTextPattern2Available:30119,StylesStyleId:30120,StylesStyleName:30121,StylesFillColor:30122,StylesFillPatternStyle:30123,StylesShape:30124,StylesFillPatternColor:30125,StylesExtendedProperties:30126,IsStylesPatternAvailable:30127,IsSpreadsheetPatternAvailable:30128,SpreadsheetItemFormula:30129,SpreadsheetItemAnnotationObjects:30130,SpreadsheetItemAnnotationTypes:30131,IsSpreadsheetItemPatternAvailable:30132,Transform2CanZoom:30133,IsTransformPattern2Available:30134,LiveSetting:30135,IsTextChildPatternAvailable:30136,IsDragPatternAvailable:30137,DragIsGrabbed:30138,DragDropEffect:30139,DragDropEffects:30140,IsDropTargetPatternAvailable:30141,DropTargetDropTargetEffect:30142,DropTargetDropTargetEffects:30143,DragGrabbedItems:30144,Transform2ZoomLevel:30145,Transform2ZoomMinimum:30146,Transform2ZoomMaximum:30147,FlowsFrom:30148,IsTextEditPatternAvailable:30149,IsPeripheral:30150,IsCustomNavigationPatternAvailable:30151,PositionInSet:30152,SizeOfSet:30153,Level:30154,AnnotationTypes:30155,AnnotationObjects:30156,LandmarkType:30157,LocalizedLandmarkType:30158,FullDescription:30159,FillColor:30160,OutlineColor:30161,FillType:30162,VisualEffects:30163,OutlineThickness:30164,CenterPoint:30165,Rotation:30166,Size:30167,IsSelectionPattern2Available:30168,Selection2FirstSelectedItem:30169,Selection2LastSelectedItem:30170,Selection2CurrentSelectedItem:30171,Selection2ItemCount:30173,IsDialog:30174, base:this.Enumeration.Prototype}
; enum PropertyVariantType Internally used enum, mapping property ids to variant types
static PropertyVariantType := Map(30000,0x2003,30001,0x2005,30002,3,30003,3,30004,8,30005,8,30006,8,30007,8,30008,0xB,30009,0xB,30010,0xB,30011,8,30012,8,30013,8,30014,0x2005,30015,3,30016,0xB,30017,0xB,30018,0xD,30019,0xB,30020,3,30021,8,30022,0xB,30023,3,30024,8,30025,0xB,30026,8,30027,0xB,30028,0xB,30029,0xB,30030,0xB,30031,0xB,30032,0xB,30033,0xB,30034,0xB,30035,0xB,30036,0xB,30037,0xB,30038,0xB,30039,0xB,30040,0xB,30041,0xB,30042,0xB,30043,0xB,30044,0xB,30045,8,30046,0xB,30047,5,30048,0xB,30049,5,30050,5,30051,5,30052,5,30053,5,30054,5,30055,5,30056,5,30057,0xB,30058,0xB,30059,0x200D,30060,0xB,30061,0xB,30062,3,30063,3,30064,3,30065,3,30066,3,30067,3,30068,0xD,30069,3,30070,3,30071,3,30072,0x2003,30073,0xB,30074,0xB,30075,3,30076,3,30077,0xB,30078,0xB,30079,0xB,30080,0xD,30081,0x200D,30082,0x200D,30083,0x2003,30084,0x200D,30085,0x200D,30086,3,30087,0xB,30088,0xB,30089,0xB,30090,0xB,30091,3,30092,8,30093,8,30094,8,30095,3,30096,3,30097,8,30098,8,30099,0x200D,30100,8,30101,8,30102,8,30103,0xB,30104,0xD,30105,0xD,30106,0xD,30107,8,30108,0xB,30109,0xB,30110,0xB,30111,0xB,30112,0xB,30113,3,30114,8,30115,8,30116,8,30117,0xD,30118,0xB,30119,0xB,30120,3,30121,8,30122,3,30123,8,30124,8,30125,3,30126,8,30127,0xB,30128,0xB,30129,8,30130,0x200D,30131,0x2003,30132,0xB,30133,0xB,30134,0xB,30135,3,30136,0xB,30137,0xB,30138,0xB,30139,8,30140,0x2008,30141,0xB,30142,8,30143,0x2008,30144,0x200D,30145,5,30146,5,30147,5,30148,0x200D,30149,0xB,30150,0xB,30151,0xB,30152,3,30153,3,30154,3,30155,0x2003,30156,0x2003,30157,3,30158,8,30159,8,30160,3,30161,0x2003,30162,3,30163,3,30164,0x2005,30165,0x2005,30166,5,30167,0x2005,30168,0xB)
static PropertyVariantTypeBSTR := Map(30004,8,30005,8,30006,8,30007,8,30011,8,30012,8,30013,8,30021,8,30024,8,30026,8,30045,8,30092,8,30093,8,30094,8,30097,8,30098,8,30100,8,30101,8,30102,8,30107,8,30114,8,30115,8,30116,8,30121,8,30123,8,30124,8,30126,8,30129,8,30139,8,30142,8,30158,8,30159,8)
; enum TextAttribute Contains format and style properties (text attributes) of textual content
static TextAttribute := {AnimationStyle:40000,BackgroundColor:40001,BulletStyle:40002,CapStyle:40003,Culture:40004,FontName:40005,FontSize:40006,FontWeight:40007,ForegroundColor:40008,HorizontalTextAlignment:40009,IndentationFirstLine:40010,IndentationLeading:40011,IndentationTrailing:40012,IsHidden:40013,IsItalic:40014,IsReadOnly:40015,IsSubscript:40016,IsSuperscript:40017,MarginBottom:40018,MarginLeading:40019,MarginTop:40020,MarginTrailing:40021,OutlineStyles:40022,OverlineColor:40023,OverlineStyle:40024,StrikethroughColor:40025,StrikethroughStyle:40026,Tabs:40027,TextFlowDirections:40028,UnderlineColor:40029,UnderlineStyle:40030,AnnotationTypes:40031,AnnotationObjects:40032,StyleName:40033,StyleId:40034,Link:40035,IsActive:40036,SelectionActiveEnd:40037,CaretPosition:40038,CaretBidiMode:40039,LineSpacing:40040,BeforeParagraphSpacing:40041,AfterParagraphSpacing:40042,SayAsInterpretAs:40043, base:this.Enumeration.Prototype}
; enum AttributeVariantType Internally used enum, mapping TextAttribute ids to variant types
static AttributeVariantType := {40000:3,40001:3,40002:3,40003:3,40004:3,40005:8,40006:5,40007:3,40008:3,40009:3,40010:5,40011:5,40012:5,40013:0xB,40014:0xB,40015:0xB,40016:0xB,40017:0xB,40018:5,40019:5,40020:5,40021:5,40022:3,40023:3,40024:3,40025:3,40026:3,40027:0x2005,40028:3,40029:3,40030:3,40031:0x2003,40032:0x200D,40033:8,40034:3,40035:0xD,40036:0xB,40037:3,40038:3,40039:3,40040:8,40041:5,40042:5,40043:8}
; enum AnnotationType Contains values that are used to identify types of annotations in a document.
static AnnotationType := {Unknown:60000,SpellingError:60001,GrammarError:60002,Comment:60003,FormulaError:60004,TrackChanges:60005,Header:60006,Footer:60007,Highlighted:60008,Endnote:60009,Footnote:60010,InsertionChange:60011,DeletionChange:60012,MoveChange:60013,FormatChange:60014,UnsyncedChange:60015,EditingLockedChange:60016,ExternalChange:60017,ConflictingChange:60018,Author:60019,AdvancedProofingIssue:60020,DataValidationError:60021,CircularReferenceError:60022,Mathematics:60023, base:this.Enumeration.Prototype}
; enum Style Contains values used to identify the visual style of text in a document.
static Style := {Custom:70000,Heading1:70001,Heading2:70002,Heading3:70003,Heading4:70004,Heading5:70005,Heading6:70006,Heading7:70007,Heading8:70008,Heading9:70009,Title:70010,Subtitle:70011,Normal:70012,Emphasis:70013,Quote:70014,BulletedList:70015,NumberedList:70016, base:this.Enumeration.Prototype}
; enum LandmarkType Contains values used to identify landmark types.
static LandmarkType := {Custom:80000,Form:80001,Main:80002,Navigation:80003,Search:80004, base:this.Enumeration.Prototype}
; enum HeadingLevel Contains values to indicate the heading level of a UIA element
static HeadingLevel := {None:80050, 1:80051, 2:80052, 3:80053, 4:80054, 5:80055, 6:80056, 7:80057, 8:80058, 9:80059, base:this.Enumeration.Prototype}
; enum Change Contains values used to identify UIA change information.
static Change := {Summary:90000, base:this.Enumeration.Prototype}
; enum Metadata Contains values used to identify metadata types in a document.
static Metadata := {SayAsInterpretAs:100000, base:this.Enumeration.Prototype}
; enum AsyncContentLoadedState Contains values that describe the progress of asynchronous loading of content.
static AsyncContentLoadedState := {Beginning:0, Progress:1, Completed:2, base:this.Enumeration.Prototype}
; enum AutomationIdentifierType Deprecated: Contains values used in the UiaLookupId function.
static AutomationIdentifierType := {Property:0,Pattern:1,Event:2,Type:3,ControlType:3,TextAttribute:4,LandmarkType:5,Annotation:6,Changes:7,Style:7, base:this.Enumeration.Prototype}
; enum ConditionType Contains values that specify a type of UIA condition.
static ConditionType := {True:0,False:1,Property:2,And:3,Or:4,Not:5, base:this.Enumeration.Prototype}
; enum EventArgsType Contains values that specify the event type described by a UiaEventArgs structure.
static EventArgsType := {Simple:0,PropertyChanged:1,StructureChanged:2,AsyncContentLoaded:3,WindowClosed:4,TextEditTextChanged:5,Changes:6,Notification:7,ActiveTextPositionChanged:8,StructuredMarkup:9, base:this.Enumeration.Prototype}
; enum AutomationElementMode Contains values that specify the type of reference to use when returning UIA elements. This is used in CreateCacheRequest.
static AutomationElementMode := {None:0, Full:1, base:this.Enumeration.Prototype}
; enum CoalesceEventsOptions Contains possible values for the CoalesceEvents property, which indicates whether to receive all events, or a subset where duplicate events are detected and filtered.
static CoalesceEventsOptions := {Disabled:0, Enabled:1, base:this.Enumeration.Prototype}
; enum ConnectionRecoveryBehaviorOptions Contains possible values for the ConnectionRecoveryBehavior property, which indicates whether an accessible technology client adjusts provider request timeouts when the provider is non-responsive.
static ConnectionRecoveryBehaviorOptions := {Disabled:0, Enabled:1, base:this.Enumeration.Prototype}
; enum PropertyConditionFlags Contains values used in creating property conditions with CreatePropertyConditionEx. In condition objects, these can be used with the "flags" key.
static PropertyConditionFlags := {None:0, IgnoreCase:1, MatchSubstring:2, IgnoreCaseMatchSubstring:3, base:this.Enumeration.Prototype}
; enum TreeScope Contains values that specify the scope of various operations in the UIA tree.
static TreeScope := {None: 0, Element: 1, Children: 2, Family:3, Descendants: 4, ElementDescendants: 5, Subtree: 7, Parent: 8, Ancestors: 16, base:this.Enumeration.Prototype}
; enum TreeTraversalOptions Contains values that can be used to customize tree navigation order.
static TreeTraversalOptions := {Default:0, PostOrder:1, LastToFirstOrder:2, LastToFirstPostOrder:3, base:this.Enumeration.Prototype}
; enum TreeTraversalDirection Not currently used.
static TreeTraversalDirection := {Up:0, Down:1, Left:2, Right:3, Next:3, Previous:2, FirstChild:1, LastChild:4, Parent:0, Normalize:5}
; enum ActiveEnd Contains possible values for the SelectionActiveEnd text attribute, which indicates the location of the caret relative to a text range that represents the currently selected text.
static ActiveEnd := {None:0,Start:1,End:2, base:this.Enumeration.Prototype}
; enum AnimationStyle Contains values for the AnimationStyle text attribute.
static AnimationStyle := {None:0,LasVegasLights:1,BlinkingBackground:2,SparkleText:3,MarchingBlackAnts:4,MarchingRedAnts:5,Shimmer:6,Other:-1, base:this.Enumeration.Prototype}
; enum BulletStyle Contains values for the BulletStyle text attribute.
static BulletStyle := {None:0,HollowRoundBullet:1,FilledRoundBullet:2,HollowSquareBullet:3,FilledSquareBullet:4,DashBullet:5,Other:-1, base:this.Enumeration.Prototype}
; enum CapStyle Contains values that specify the value of the CapStyle text attribute.
static CapStyle := {None:0,SmallCap:1,AllCap:2,AllPetiteCaps:3,PetiteCaps:4,Unicase:5,Titling:6,Other:-1, base:this.Enumeration.Prototype}
; enum CaretBidiMode Contains possible values for the CaretBidiMode text attribute, which indicates whether the caret is in text that flows from left to right, or from right to left.
static CaretBidiMode := {LTR:0,RTL:1, base:this.Enumeration.Prototype}
; enum CaretPosition Contains possible values for the CaretPosition text attribute, which indicates the location of the caret relative to a line of text in a text range.
static CaretPosition := {Unknown:0,EndOfLine:1,BeginningOfLine:2, base:this.Enumeration.Prototype}
; enum DockPosition Contains values that specify the location of a docking window represented by the Dock control pattern.
static DockPosition := {Top:0,Left:1,Bottom:2,Right:3,Fill:4,None:5, base:this.Enumeration.Prototype}
; enum ExpandCollapseState Contains values that specify the state of a UI element that can be expanded and collapsed.
static ExpandCollapseState := {Collapsed:0,Expanded:1,PartiallyExpanded:2,LeafNode:3, base:this.Enumeration.Prototype}
; enum FillType Contains values for the FillType attribute.
static FillType := {None:0,Color:1,Gradient:2,Picture:3,Pattern:4, base:this.Enumeration.Prototype}
; enum FlowDirection Contains values for the TextFlowDirections text attribute.
static FlowDirection := {Default:0,RightToLeft:1,BottomToTop:2,Vertical:4, base:this.Enumeration.Prototype}
; enum LiveSetting Contains possible values for the LiveSetting property. This property is implemented by provider elements that are part of a live region.
static LiveSetting := {Off:0,Polite:1,Assertive:2, base:this.Enumeration.Prototype}
; enum NavigateDirection Contains values used to specify the direction of navigation within the Microsoft UI Automation tree.
static NavigateDirection := {Parent:0,NextSibling:1,PreviousSibling:2,FirstChild:3,LastChild:4, base:this.Enumeration.Prototype}
; enum NotificationKind Defines values that indicate the type of a notification event, and a hint to the listener about the processing of the event.
static NotificationKind := {ItemAdded:0,ItemRemoved:1,ActionCompleted:2,ActionAborted:3,Other:4, base:this.Enumeration.Prototype}
; enum NotificationProcessing Defines values that indicate how a notification should be processed.
static NotificationProcessing := {ImportantAll:0,ImportantMostRecent:1,All:2,MostRecent:3,CurrentThenMostRecent:4, base:this.Enumeration.Prototype}
; enum OrientationType Contains values that specify the orientation of a control.
static OrientationType := {None:0,Horizontal:1,Vertical:2, base:this.Enumeration.Prototype}
; enum OutlineStyles Contains values for the OutlineStyle text attribute.
static OutlineStyles := {None:0,Outline:1,Shadow:2,Engraved:4,Embossed:8, base:this.Enumeration.Prototype}
; enum ProviderOptions
static ProviderOptions := {ClientSideProvider:1,ServerSideProvider:2,NonClientAreaProvider:4,OverrideProvider:8,ProviderOwnsSetFocus:10,UseComThreading:20,RefuseNonClientSupport:40,HasNativeIAccessible:80,UseClientCoordinates:100, base:this.Enumeration.Prototype}
; enum RowOrColumnMajor Contains values that specify whether data in a table should be read primarily by row or by column.
static RowOrColumnMajor := {RowMajor:0,ColumnMajor:1,Indeterminate:2, base:this.Enumeration.Prototype}
; enum SayAsInterpretAs Defines the values that indicate how a text-to-speech engine should interpret specific data.
static SayAsInterpretAs := {None:0,Spell:1,Cardinal:2,Ordinal:3,Number:4,Date:5,Time:6,Telephone:7,Currency:8,Net:9,Url:10,Address:11,Name:13,Media:14,Date_MonthDayYear:15,Date_DayMonthYear:16,Date_YearMonthDay:17,Date_YearMonth:18,Date_MonthYear:19,Date_DayMonth:20,Date_MonthDay:21,Date_Year:22,Time_HoursMinutesSeconds12:23,Time_HoursMinutes12:24,Time_HoursMinutesSeconds24:25,Time_HoursMinutes24:26, base:this.Enumeration.Prototype}
; enum ScrollAmount Contains values that specify the direction and distance to scroll.
static ScrollAmount := {NoScroll:-1,LargeDecrement:0,SmallDecrement:1,NoAmount:2,LargeIncrement:3,SmallIncrement:4, base:this.Enumeration.Prototype}
; enum StructureChangeType Contains values that specify the type of change in the Microsoft UI Automation tree structure.
static StructureChangeType := {ChildAdded:0,ChildRemoved:1,ChildrenInvalidated:2,ChildrenBulkAdded:3,ChildrenBulkRemoved:4,ChildrenReordered:5, base:this.Enumeration.Prototype}
; enum SupportedTextSelection Contains values that specify the supported text selection attribute.
static SupportedTextSelection := {None:0,Single:1,Multiple:2, base:this.Enumeration.Prototype}
; enum SynchronizedInputType Contains values that specify the type of synchronized input.
static SynchronizedInputType := {KeyUp:1,KeyDown:2,LeftMouseUp:4,LeftMouseDown:8,RightMouseUp:10,RightMouseDown:20, base:this.Enumeration.Prototype}
; enum TextDecorationLineStyle Contains values that specify the OverlineStyle, StrikethroughStyle, and UnderlineStyle text attributes.
static TextDecorationLineStyle := {None:0, Single:1, WordsOnly:2, Double:3, Dot:4, Dash:5, DashDot:6, DashDotDot:7, Wavy:8, ThickSingle:9, DoubleWavy:11, ThickWavy:12, LongDash:13, ThickDash:14, ThickDashDot:15, ThickDashDotDot:16, ThickDot:17, ThickLongDash:18, Other:-1, base:this.Enumeration.Prototype}
; enum TextEditChangeType Describes the text editing change being performed by controls when text-edit events are raised or handled.
static TextEditChangeType := {None:0,AutoCorrect:1,Composition:2,CompositionFinalized:3,AutoComplete:4, base:this.Enumeration.Prototype}
; enum TextPatternRangeEndpoint Contains values that specify the endpoints of a text range.
static TextPatternRangeEndpoint := {Start:0,End:1, base:this.Enumeration.Prototype}
; enum TextUnit Contains values that specify units of text for the purposes of navigation.
static TextUnit := {Character:0,Format:1,Word:2,Line:3,Paragraph:4,Page:5,Document:6, base:this.Enumeration.Prototype}
; enum ToggleState Contains values that specify the toggle state of a Microsoft UI Automation element that implements the Toggle control pattern.
static ToggleState := {Off:0,On:1,Indeterminate:2, base:this.Enumeration.Prototype}
; enum ZoomUnit Contains possible values for the IUIAutomationTransformPattern2::ZoomByUnit method, which zooms the viewport of a control by the specified unit.
static ZoomUnit := {NoAmount:0,LargeDecrement:1,SmallDecrement:2,LargeIncrement:3,SmallIncrement:4, base:this.Enumeration.Prototype}
; enum WindowVisualState Contains values that specify the visual state of a window.
static WindowVisualState := {Normal:0,Maximized:1,Minimized:2, base:this.Enumeration.Prototype}
; enum WindowInteractionState Contains values that specify the current state of the window for purposes of user interaction.
static WindowInteractionState := {Running:0,Closing:1,ReadyForUserInteraction:2,BlockedByModalWindow:3,NotResponding:4, base:this.Enumeration.Prototype}
; MSAA/Acc enums
class LegacyIAccessible extends UIA.Enumeration {
static SelectionFlag := {None:0x0, TakeFocus:0x1, TakeSelection:0x2, ExtendSelection:0x4, AddSelection:0x8, RemoveSelection:0x10, Valid:0x1f}
static Role := {TitleBar:0x1,MenuBar:0x2, ScrollBar:0x3, Grip:0x4, Sound:0x5, Cursor:0x6, Caret:0x7, Alert:0x8, Window:0x9, Client:0xa, MenuPopup:0xb, MenuItem:0xc, ToolTip:0xd, Application:0xe, Document:0xf, Pane:0x10, Chart:0x11, Dialog:0x12, Border:0x13, Grouping:0x14, Separator:0x15, Toolbar:0x16, StatusBar:0x17, Table:0x18, ColumnHeader:0x19, RowHeader:0x1a, Column:0x1b, Row:0x1c, Cell:0x1d, Link:0x1e, HelpBalloon:0x1f, Character:0x20, List:0x21, ListItem:0x22, Outline:0x23, OutlineItem:0x24, PageTab:0x25, PropertyPage:0x26, Indicator:0x27, Graphic:0x28, StaticText:0x29, Text:0x2a, PushButton:0x2b, CheckButton:0x2c, RadioButton:0x2d, ComboBox:0x2e, Droplist:0x2f, Progressbar:0x30, Dial:0x31, HotkeyField:0x32, Slider:0x33, SpinButton:0x34, Diagram:0x35, Animation:0x36, Equation:0x37, ButtonDropdown:0x38, ButtonMenu:0x39, ButtonDropdownGrid:0x3a, Whitespace:0x3b, PageTabList:0x3c, Clock:0x3d, SplitButton:0x3e, IPAddress:0x3f, OutlineButton:0x40}
static State := {Normal:0, Unavailable:0x1, Selected:0x2, Focused:0x4, Pressed:0x8, Checked:0x10, Mixed:0x20, Indeterminate:0x20, ReadOnly:0x40, HotTracked:0x80, Default:0x100, Expanded:0x200, Collapsed:0x400, Busy:0x800, Floating:0x1000, Marqueed:0x2000, Animated:0x4000, Invisible:0x8000, Offscreen:0x10000, Sizeable:0x20000, Moveable:0x40000, SelfVoicing:0x80000, Focusable:0x100000, Selectable:0x200000, Linked:0x400000, Traversed:0x800000, MultiSelectable:0x1000000, ExtSelectable:0x2000000, Alert_Low:0x4000000, Alert_Medium:0x8000000, Alert_High:0x10000000, Protected:0x20000000, Valid:0x7fffffff}
}
; ---------- UIA Properties ----------
; Check whether a certain version of UIAutomation is available
static IsIUIAutomation2Available := VerCompare(A_OSVersion, ">=6.2.9200")
static IsIUIAutomation3Available := VerCompare(A_OSVersion, ">=6.3.9600")
static IsIUIAutomation4Available := VerCompare(A_OSVersion, ">=10.0.14393")
static IsIUIAutomation5Available := VerCompare(A_OSVersion, ">=10.0.14393")
static IsIUIAutomation6Available := VerCompare(A_OSVersion, ">=10.0.17763")
; Check whether a certain version of UIAutomation Element is available
static IsIUIAutomationElement2Available := VerCompare(A_OSVersion, ">=6.2.9200")
static IsIUIAutomationElement3Available := VerCompare(A_OSVersion, ">=6.3.9600")
static IsIUIAutomationElement4Available := VerCompare(A_OSVersion, ">=10")
static IsIUIAutomationElement5Available := VerCompare(A_OSVersion, ">=10.0.15063")
static IsIUIAutomationElement6Available := VerCompare(A_OSVersion, ">=10.0.15063")
static IsIUIAutomationElement7Available := VerCompare(A_OSVersion, ">=10.0.15063")
static IsIUIAutomationElement8Available := VerCompare(A_OSVersion, ">=10.0.17134")
static IsIUIAutomationElement9Available := VerCompare(A_OSVersion, ">=10.0.17763")
; Retrieves a predefined TreeWalker made with the TrueCondition
static TreeWalkerTrue := ""
; Retrieves a predefined condition that selects all elements.
static TrueCondition := ""
; Retrieves a static token object representing a property or text attribute that is not supported. This property is read-only.
; This object can be used for comparison with the results from UIA.IUIAutomationElement,,GetPropertyValue or IUIAutomationTextRange,,GetAttributeValue.
static ReservedNotSupportedValue {
get {
local notSupportedValue
return (ComCall(54, this, "ptr*", ¬SupportedValue := 0), ComValue(0xd, notSupportedValue))
}
}
; Retrieves a static token object representing a text attribute that is a mixed attribute. This property is read-only.
; The object retrieved by IUIAutomation,,ReservedMixedAttributeValue can be used for comparison with the results from IUIAutomationTextRange,,GetAttributeValue to determine if a text range contains more than one value for a particular text attribute.
static ReservedMixedAttributeValue {
get {
local mixedAttributeValue
return (ComCall(55, this, "ptr*", &mixedAttributeValue := 0), ComValue(0xd, mixedAttributeValue))
}
}
; Retrieves an IUIAutomationTreeWalker interface used to discover control elements.
static ControlViewWalker {
get {
static walker := (ComCall(14, this, "ptr*", &walker := 0), walker?this.IUIAutomationTreeWalker(walker):"")
return walker
}
}
; Retrieves an IUIAutomationTreeWalker interface used to discover content elements.
static ContentViewWalker {
get {
static walker := (ComCall(15, this, "ptr*", &walker := 0), walker?this.IUIAutomationTreeWalker(walker):"")
return walker
}
}
; Retrieves a tree walker object used to traverse an unfiltered view of the UI Automation tree.
static RawViewWalker {
get {
static walker := (ComCall(16, this, "ptr*", &walker := 0), walker?this.IUIAutomationTreeWalker(walker):"")
return walker
}
}
; Retrieves a predefined IUIAutomationCondition interface that selects all UI elements in an unfiltered view.
static RawViewCondition {
get {
static condition := (ComCall(17, this, "ptr*", &condition := 0), condition?this.IUIAutomationCondition(condition):"")
return condition
}
}
; Retrieves a predefined IUIAutomationCondition interface that selects control elements.
static ControlViewCondition {
get {
static condition := (ComCall(18, this, "ptr*", &condition := 0), condition?this.IUIAutomationCondition(condition):"")
return condition
}
}
; Retrieves a predefined IUIAutomationCondition interface that selects content elements.
static ContentViewCondition {
get {
static condition := (ComCall(19, this, "ptr*", &condition := 0), condition?this.IUIAutomationCondition(condition):"")
return condition
}
}
; ---------- IUIAutomation2 properties ----------
; Specifies whether calls to UI Automation control pattern methods automatically set focus to the target element. Default is True.
static AutoSetFocus {
get {
local out
return (ComCall(58, this, "int*", &out:=0), out)
}
set => ComCall(59, this, "int", Value)
}
; Specifies the length of time that UI Automation will wait for a provider to respond to a client request for an automation element. Default is 20000ms (20 seconds), minimum seems to be 50ms.
static ConnectionTimeout {
get {
local out
return (ComCall(60, this, "int*", &out:=0), out)
}
set => ComCall(61, this, "int", Value) ; Minimum seems to be 50 (ms?)
}
; Specifies the length of time that UI Automation will wait for a provider to respond to a client request for information about an automation element. Default is 2000ms (2 seconds), minimum seems to be 50ms.
static TransactionTimeout {
get {
local out
return (ComCall(62, this, "int*", &out:=0), out)
}
set => ComCall(63, this, "int", Value)
}
; ---------- IUIAutomation6 properties ----------
; Indicates whether an accessible technology client adjusts provider request timeouts when the provider is non-responsive.
ConnectionRecoveryBehavior {
get {
local out
return (ComCall(73, this, "int*", &out), out)
}
set => ComCall(74, this, "int", value)
}
; Gets or sets whether an accessible technology client receives all events, or a subset where duplicate events are detected and filtered.
CoalesceEvents {
get {
local out
return (ComCall(75, this, "int*", &out:=0), out)
}
set => ComCall(76, this, "int", value)
}
; ---------- IUIAutomation methods ----------
/**
* Encodes an array of conditions consisting of only Type and index properties to an UIA path,
* which is a string of characters/numbers/symbols in base64 encoding.
* @param path The array of conditions
* @returns {String}
*/
static EncodePath(path) {
/*
FYI, this is probably the most disgusting algorithm I have ever created.
It goes like this:
The input (path variable) is an array of conditions, which can only have the Type property and an index.
This gets encoded into a string of characters. This is a base64 character set of A-Z, a-z,
0-9, and /?<>= with the exception of letters "p" and "P". This is to maintain backwards
compatability with the WalkTree paths, where "p" signifies "parent".
Now, since there are 45 different Types, I've allocated the first 50 encoding characters
(hopefully no more that 5 will be added in the future to UIA) to the Types.
If the condition contains an index as well, then the start of an index is signaled by an
encoding character 50 to 59. 50 means index 2, because index 1 doesn't have to be encoded (it's the default value).
Then the next symbols will be added in base15 to calculate the final number.
Negative indices are 60 to 64, and also the next symbols will be subtracted in base15
to calculate the final index.
Why only 10 symbols for indices 2-11, yet 5 for negative ones? No particular reason other
than it seems pragmatic to include more positive integers than negative to be encoded
with only 1 character. Currently UIAViewer doesn't even use negative indices, users
may create them themselves.
Note that this encoding doesn't allow any other properties (eg AutomationId, Name etc),
although this support might be added in later versions.
Example: "VE0q" => [{Type:"Document"}, {Type:"ScrollBar"}, {Type:"Button", index:2}]
"V" corresponds in Base64IntToChar to 31 which is Type Document, "E" is ScrollBar,
"0" is Button, "q" is 50 which is the first index number, and positive indices start with 2.
*/
local out, i, module
static Base64IntToChar := Map(0,'0',1,'1',2,'2',3,'3',4,'4',5,'5',6,'6',7,'7',8,'8',9,'9',10,'A',11,'B',12,'C',13,'D',14,'E',15,'F',16,'G',17,'H',18,'I',19,'J',20,'K',21,'L',22,'M',23,'N',24,'O',25,'Q',26,'R',27,'S',28,'T',29,'U',30,'V',31,'W',32,'X',33,'Y',34,'Z',35,'a',36,'b',37,'c',38,'d',39,'e',40,'f',41,'g',42,'h',43,'i',44,'j',45,'k',46,'l',47,'m',48,'n',49,'o',50,'q',51,'r',52,'s',53,'t',54,'u',55,'v',56,'w',57,'x',58,'y',59,'z',60,'/',61,'?',62,'<',63,'>',64,'=')
if !(path is Array)
path := [path]
out := ""
for cond in path {
t := cond.HasOwnProp("T") ? cond.t : cond.HasOwnProp("Type") ? cond.Type : cond.HasOwnProp("ControlType") ? cond.ControlType : -1
if t = -1
throw ValueError("Encodable path requires a Type", -1)
if !(IsInteger(t) && t < 50)
t := this.TypeValidation.Type(t) - 50000
out .= Base64IntToChar[t]
i := cond.HasOwnProp("i") ? cond.i : cond.HasOwnProp("index") ? cond.index : 1
if i != 0 && i != 1 {
; 50 = index 2
; 60 = index -1
; 61 = index -2
; 62 = index -3
; 63 = index -4
; 64 = index -5
if i > 1 {
i -= 2, factor := 10
Loop {
if A_index = 1 {
out .= Base64IntToChar[50 + (module := Mod(i, factor))]
} else {
out .= Base64IntToChar[50 + (module := Mod(i, factor*15))//factor]
factor := factor * 15
}
i -= module
} Until i = 0
} else {
i := -i - 1
out .= Base64IntToChar[60 + (module := Mod(i, 5))]
i -= module, factor := 5
Loop {
if A_index > 1 {
out .= Base64IntToChar[50 + (module := Mod(i, factor*15))//factor]
i -= module, factor := factor*15
}
} Until i = 0
}
}
}
return out
}
/**
* Decodes an UIA path to an array of conditions (consisting of only Type and index properties).
* @param path A string UIA path
* @returns {Array}
*/
static DecodePath(path) {
static Base64CharToInt := Map('0',0,'1',1,'2',2,'3',3,'4',4,'5',5,'6',6,'7',7,'8',8,'9',9,'A',10,'B',11,'C',12,'D',13,'E',14,'F',15,'G',16,'H',17,'I',18,'J',19,'K',20,'L',21,'M',22,'N',23,'O',24,'Q',25,'R',26,'S',27,'T',28,'U',29,'V',30,'W',31,'X',32,'Y',33,'Z',34,'a',35,'b',36,'c',37,'d',38,'e',39,'f',40,'g',41,'h',42,'i',43,'j',44,'k',45,'l',46,'m',47,'n',48,'o',49,'q',50,'r',51,'s',52,'t',53,'u',54,'v',55,'w',56,'x',57,'y',58,'z',59,'/',60,'?',61,'<',62,'>',63,'=',64)
local out := [], calculatingIndex := 0, cond := ""
loop parse path {
num := Base64CharToInt[A_LoopField]
if calculatingIndex != 0 && num < 50
calculatingIndex := 0
if num > 49 && calculatingIndex = 0 {
cond.DefineProp("i", {value:num < 60 ? num-48 : 59-num}) ; 50 => index 2 (index 1 would not exist) ; 60 => index -1
calculatingIndex := num < 60 ? 1 : -1
continue
}
if calculatingIndex {
if calculatingIndex > 0 {
cond.i += (num-50)*10*15**(calculatingIndex-1)
calculatingIndex++
} else {
cond.i -= (num-50)*5*15**(-calculatingIndex-1)
calculatingIndex--
}
} else {
if cond
out.Push(cond)
cond := {Type:50000+num}
}
}
if cond
out.Push(cond)
return out
}
static RuntimeIdToString(runtimeId) {
local str := "", v
for v in runtimeId
str .= "." Format("{:X}", v)
return LTrim(str, ".")
}
static RuntimeIdFromString(str) {
local t := StrSplit(str, "."), v, arr := ComObjArray(3, t.Length)
for v in t
arr[A_Index - 1] := Integer("0x" v)
return arr
}
/**
* Filters elements from an element array if "function" evaluates to True.
* The resulting elements will have an Index property added which is the index in the original unfiltered array.
* @param elementArray Array of elements
* @param function A function that accepts one parameter (an element) and validates it against some condition.
* @returns {Array}
*/
static Filter(elementArray, function) {
local i, el, ret := []
if !InStr(Type(elementArray), "Array")
throw TypeError("elementArray must be an Array or IUIAutomationElementArray", -1)
for i, el in elementArray
if function(el)
el.DefineProp("Index", {value: i}), ret.Push(el)
return ret
}
/**
* Can be used to set or get the current scripts DPI awareness to fix problems with invalid coordinates in
* multi-monitor setups.
* Possible values (read more: https://learn.microsoft.com/en-us/windows/win32/hidpi/dpi-awareness-context):
* DPI_AWARENESS_CONTEXT_UNAWARE = -1
* DPI_AWARENESS_CONTEXT_SYSTEM_AWARE = -2 (default)
* DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE = -3
* DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = -4
* DPI_AWARENESS_CONTEXT_UNAWARE_GDISCALED = -5
*
*/
static DPIAwareness {
set => DllCall("SetThreadDpiAwarenessContext", "ptr", value, "ptr")
get {
local context := DllCall("GetThreadDpiAwarenessContext")
Loop 5 {
if DllCall("AreDpiAwarenessContextsEqual", "ptr", context, "ptr", -A_Index)
return -A_index
}
return context
}
}
; Sets the maximum possible DPI awareness level depending on Windows version
static SetMaximumDPIAwareness() => this.DPIAwareness := this.IsIUIAutomationElement6Available ? -4 : -3
static ProcessIsElevated(vPID) {
local hProc, hToken, vIsElevated, vRet
;PROCESS_QUERY_LIMITED_INFORMATION := 0x1000
if !(hProc := DllCall("OpenProcess", "UInt", 0x1000, "Int",0, "UInt",vPID, "Ptr"))
return -1
;TOKEN_QUERY := 0x8
if !(DllCall("advapi32\OpenProcessToken", "Ptr", hProc, "UInt",0x8, "Ptr*", &hToken:=0)) {
DllCall("CloseHandle", "Ptr", hProc)
return -1
}
;TokenElevation := 20
vRet := (DllCall("advapi32\GetTokenInformation", "Ptr", hToken, "Int", 20, "UInt*", &vIsElevated:=0, "UInt", 4, "UInt*", &vSize:=0))
DllCall("CloseHandle", "Ptr",hToken)
DllCall("CloseHandle", "Ptr",hProc)
return vRet ? vIsElevated : -1
}
/**
* Finds the first element matching a condition from an AHK array
* @param elementArray The array to search
* @param condition The condition the element must match, or a callback function (takes 1 argument, the evaluated element, and returns true/false)
* @param index Looks for the n-th element matching the condition. Negative index starts the search from the end.
* @param startingElement Optional: The element to start the search with
* @param cacheRequest Optional: A cache request to cache the found element with
* @param cached Whether the condition match uses cached properties or not
* @returns {UIA.IUIAutomationElement}
*/
static FindElementFromArray(elementArray, condition, index:=1, startingElement:=0, cacheRequest:=0, cached:=False) {
local scope := 0, order := 0, callback := 0
condition := this.IUIAutomationElement.__ExtractConditionNamedParameters(condition, &scope, &order, &startingElement, , &index, &callback)
index := this.TypeValidation.Integer(index, "Index"), startingElement := this.TypeValidation.Element(startingElement)
callback := callback || UIA.IUIAutomationElement.Prototype.ValidateCondition.Bind(, condition, cached)
if index = 0
throw ValueError("Condition index cannot be 0", -1)
if startingElement
startingElement := startingElement.RuntimeId
if index > 0 {
for element in elementArray {
if (startingElement ? (startingElement = element.RuntimeId ? !(startingElement := "") && (scope & 1) : 0) : 1) && callback(element) && --index = 0
return cacheRequest ? element.BuildUpdatedCache(cacheRequest) : element
}
} else {
index := -index, len := elementArray.Length + 1
Loop len-1 {
element := elementArray[len-A_index]
if (startingElement ? (startingElement = element.RuntimeId ? !(startingElement := "") && (scope & 1) : 0) : 1) && callback(element) && --index = 0
return cacheRequest ? element.BuildUpdatedCache(cacheRequest) : element
}
}
throw TargetError("An element matching the condition was not found", -1)
}
static FindCachedElementFromArray(elementArray, condition, index:=1, startingElement:=0) => this.FindElementFromArray(elementArray, condition, index, startingElement,, 1)
/**
* Clears all highlights created by Element.Highlight
*/
static ClearAllHighlights() => this.IUIAutomationElement.Prototype.Highlight("clearall")
/**
* Create a property condition from an AHK object
* @param condition Object or Array that contains property conditions.
* * A single property condition consists of an object where the key is the property name, and value is the property value:
* `{Name:"Test"}` => Creates a condition where the Name property must match "Test" exactly
* * Everything inside {} is an "and" condition
* `{Type:"Button", Name:"Something"}` => Name must match "Something" AND Type must be Button
* * Everything inside [] is an "or" condition
* `[{Name:"Test"}, {Name:"Something"}]` Name must match "Test" OR Name must match "Something"
* * Object key "not" creates a not condition
*
* * matchmode key (short form: mm) can be one of UIA.MatchMode values (except StartsWith and RegEx) and defines the MatchMode:
* 2=can contain anywhere in string; 3=exact match
* * casesense key (short form: cs) defines case sensitivity (default: case-sensitive/True): True=case sensitive; False=case insensitive
*
* @param value If this is set then UIA.CreatePropertyCondition will be called instead, with "condition" being the Property name.
* @param flags If `value` was set then this will be passed to UIA.CreatePropertyConditionEx
*
* #### Examples:
* * `CreateCondition({Name:"Test"})` => Name must match "Test" exactly, case-sensitive
* * `CreateCondition({Type:"Button", or:[Name:"Something", Name:"Else"]})` => Name must match "Something" OR "Else", AND Type must be Button
* * `CreateCondition({Name:"Test", cs:0, mm:2})` => Name must contain "Test" and is case-insensitive
* * `CreateCondition("Type", "Button")` => Type must be Button
*
* @returns {UIA.IUIAutomationCondition}
*/
static CreateCondition(condition, value?, flags?) {
local propertyId, match
if IsSet(value) {
propertyId := this.TypeValidation.Property(condition)
if propertyId = 30003 && !IsNumber(value) {
if this.Type.HasOwnProp(value)
value := this.Type.%value%
else if value is String && RegExMatch(value, "\d{5}", &match:="") && Integer(match[]) >= 50000
value := Integer(match[])
else
throw ValueError("Type '" value '" in a non-existant type!', -1)
}
if IsSet(flags) && (this.TypeValidation.PropertyConditionFlags(flags)) && this.PropertyVariantTypeBSTR.Has(propertyId)
return this.CreatePropertyConditionEx(propertyId, this.TypeValidation.String(value, "Value"), flags)
return this.CreatePropertyCondition(propertyId, value)
}
return this.__ConditionBuilder(condition)
}
static __CreateRawCondition(condition) {
local i, nonUIAEncountered
for i in ["index", "i", "scope", "order", "startingElement"]
if condition.HasOwnProp(i)
throw ValueError("This method doesn't support indexes nor named arguments", -2, '"' i '" can be used with FindElement(s) instead')
condition := this.__ConditionBuilder(condition, &nonUIAEncountered:=0)
if nonUIAEncountered & 2
throw ValueError("This method doesn't support conditions with Cached properties", -2, "Instead use FindElement(s) or FindCachedElement(s)")
else if nonUIAEncountered & 1
throw ValueError("This method doesn't support conditions with MatchMode RegEx nor StartsWith", -2, "Only MatchModes Exact and SubString are allowed. Use FindElement(s) instead, which supports all MatchModes.")
return condition
}
static __ConditionBuilder(obj, &nonUIAEncountered?, isParentNotCondition:=0) {
local sanitizeMM, operator, cs, mm, flags, count, k, v, t, i, j, val, match, arr
sanitizeMM := False
if Type(obj) = "Object" {
obj := obj.Clone() ; Speed-testing showed that not cloning (getting props with HasOwnProp and then ignoring them in the loop) is as fast as cloning.
obj.DeleteProp("index"), obj.DeleteProp("i")
operator := obj.DeleteProp("operator") || obj.DeleteProp("op") || "and"
cs := obj.HasOwnProp("casesense") ? obj.casesense : obj.HasOwnProp("cs") ? obj.cs : 1
obj.DeleteProp("casesense"), obj.DeleteProp("cs")
mm := obj.DeleteProp("matchmode") || obj.DeleteProp("mm") || 3
if !IsInteger(mm)
mm := this.MatchMode.%mm%
if !IsInteger(cs)
cs := this.CaseSense.%cs%
if IsSet(nonUIAEncountered) {
if (mm = "RegEx" || mm = 1)
nonUIAEncountered |= 1, sanitizeMM := True
} else if !((mm = 3) || (mm = 2)) { ; If creating a "pure" UIA condition, allow only Exact and Substring matchmodes
throw TypeError("MatchMode can only be Exact or Substring (3 or 2) when creating UIA conditions.", -1, "MatchMode 1 and RegEx are allowed with FindElement, FindElements, and ElementFromPath methods.")
}
flags := ((mm = 3 ? 0 : 2) | (!cs)) || obj.DeleteProp("flags") || 0
count := ObjOwnPropCount(obj), obj := obj.OwnProps()
} else if obj is Array {
operator := "or", flags := 0, count := obj.Length
} else
throw TypeError("Invalid parameter type", -3, Type(obj))
if count = 0
return this.TrueCondition
arr := ComObjArray(0xd, count), i := 0
for k, v in obj {
if k ~= "i)^Cached" && IsSet(nonUIAEncountered)
nonUIAEncountered |= 2
try k := IsNumber(k) ? Integer(k) : this.Property.%k%
if IsInteger(k) && k >= 30000 {
switch Type(v), 0 {
case "Array":
if (this.PropertyVariantType[k] & 0x2000)
v := this.AHKArrayToSafeArray(v, this.PropertyVariantType[k] & ~0x2000)
else if !(sanitizeMM && this.PropertyVariantTypeBSTR.Has(k)) || mm = 1 {
; Creating an "or" condition with same matchmode and casesense
if !v.Length
throw ValueError("Invalid condition: `"or`" condition cannot be empty", -2)
orArr := ComObjArray(0xd, v.Length)
for j, val in v
orArr[j-1] := (mm = 1 ? this.CreateCondition(k, val, !cs | 2) : this.CreateCondition(k, val, flags))[]
t := this.CreateOrConditionFromArray(orArr)
arr[i++] := t[]
continue
}
case "String":
if k = 30000
v := this.RuntimeIdFromString(v)
else if k = 30003 {
if this.Type.HasOwnProp(v)
v := this.Type.%v%
else if RegExMatch(v, "\d{5}", &match:="") && match[] >= 50000
v := Integer(match[])
else
throw ValueError("Type '" v '" in a non-existant type!', -1)
}
case "Integer":
if k = 30003 && v < 50000
v += 50000
}
if sanitizeMM && this.PropertyVariantTypeBSTR.Has(k) {
t := mm = 1 ? this.CreateCondition(k, v, !cs | 2) : (isParentNotCondition ? this.CreatePropertyCondition(k, "") : this.CreateNotCondition(this.CreatePropertyCondition(k, "")))
arr[i++] := t[]
} else if (k >= 30000) {
t := this.CreateCondition(k, v, flags)
arr[i++] := t[]
}
} else if IsObject(v) && !(SubStr(Type(v), 1, 6) = "ComObj") && !v.HasOwnProp("ptr") {
t := this.__ConditionBuilder(v, &nonUIAEncountered, isParentNotCondition ^ (k = "not" || operator = "not"))
if k = "not" || operator = "not"
t := this.CreateNotCondition(t)
arr[i++] := t[]
continue
} else
throw ValueError("Invalid condition encountered: " k, -2)
}
if count = 1
return operator = "not" ? this.CreateNotCondition(t) : t
switch operator, false {
case "and":
return this.CreateAndConditionFromArray(arr)
case "or":
return this.CreateOrConditionFromArray(arr)
case "not":
return this.CreateNotCondition(this.CreateAndConditionFromArray(arr))
default:
return this.CreateFalseCondition()
}
}
/**
* If the element from ElementFromHandle doesn't contain the content of the window, and the window in
* question is a Chromium app (Window Spy shows "ahk_class Chrome_WidgetWin_1"), then this can be used
* to get the element for the content (using Chrome_RenderWidgetHostHWND1 control).
* @param winTitle A window title or other criteria identifying the target window. See AHK WinTitle.
* @param activateChromiumAccessibility Whether to check if the window is a Chromium application
* and if it is then try to activate accessibility. If not 0 then it also defines the timeout period
* for activation.
* @param timeOut How long to wait for confirmation that accessibility is enabled in the app after
* trying to enable accessibility. Default: 500ms
* @param cacheRequest Optional: a cache request object.
* @returns {UIA.IUIAutomationElement}
*/
static ElementFromChromium(winTitle:="", activateChromiumAccessibility:=500, cacheRequest?) {
if activateChromiumAccessibility
return this.ActivateChromiumAccessibility(winTitle, 1, activateChromiumAccessibility, cacheRequest?)
try cHwnd := ControlGetHwnd("Chrome_RenderWidgetHostHWND1", winTitle)
if !IsSet(cHwnd) || !cHwnd
throw TargetError("Chrome_RenderWidgetHostHWND1 content control was not found", -1)
return this.ElementFromHandle(cHwnd, cacheRequest?, False)
}
/**
* Returns whether a window is a Chromium window or not
* @param winTitle A window title or other criteria identifying the target window. See AHK WinTitle.
*/
static WindowIsChromium(winTitle:="") {
try cHwnd := ControlGetHwnd("Chrome_RenderWidgetHostHWND1", winTitle)
return cHwnd ?? 0
}
/**
* In some setups Chromium-based renderers don't react to UIA calls by enabling accessibility,
* so we need to send the WM_GETOBJECT message to the renderer control to enable accessibility.
* ActivateChromiumAccessibility does that (only once per window) and then returns the content element.
* Explanation why this works: https://www.chromium.org/developers/design-documents/accessibility/#TOC-How-Chrome-detects-the-presence-of-Assistive-Technology
* @param winTitle A window title or other criteria identifying the target window. See AHK WinTitle.
* @param forceActivation By default a window is activated only once per run. If this is set to True
* then the window is activated unconditionally.
* @param timeOutVarRef How long to wait for confirmation that accessibility is enabled in the app after
* trying to enable accessibility. Default: 500ms
* If timeOutVarRef is a VarRef containing a timeout value, then it'll be set to the returned Chromium element.
* @param cacheRequest Optional: a cache request object.
* @returns {UIA.IUIAutomationElement}
* @credit malcev, rommmcek
*/
static ActivateChromiumAccessibility(winTitle:="", forceActivation:=False, timeOutVarRef:=500, cacheRequest?) {
static activatedHwnds := Map(), WM_GETOBJECT := 0x003D
local _, cEl, cHwnd, elVarRef := &cEl, timeOut := timeOutVarRef, hWnd := IsInteger(winTitle) ? winTitle : WinExist(winTitle)
if activatedHwnds.Has(hwnd) && !ForceActivation
return 1
activatedHwnds[hWnd] := 1, cHwnd := 0
try cHwnd := ControlGetHwnd("Chrome_RenderWidgetHostHWND1", winTitle)
if !IsSet(cHwnd) || !cHwnd
throw TargetError("No Chromium control (Chrome_RenderWidgetHostHWND1) found", -1)
SendMessage(WM_GETOBJECT := 0x003D, 0, 1,, cHwnd)
if IsObject(timeOutVarRef) && timeOutVarRef is VarRef
elVarRef := timeOutVarRef, timeOut := %timeOutVarRef%
if (%elVarRef% := this.ElementFromHandle(cHwnd, cacheRequest?, False)) {
cEl := cEl ?? %elVarRef%
waitTime := A_TickCount + timeOut
while (A_TickCount < waitTime) {
try {
if cEl.Children.Length
break
}
Sleep 1
}
}
return %elVarRef%
}
; Compares two UI Automation elements to determine whether they represent the same underlying UI element.
static CompareElements(el1, el2) {
local areSame
return (ComCall(3, this, "ptr", el1, "ptr", el2, "int*", &areSame := 0), areSame)
}
; CompareElements sometimes fails to match elements, so this combines CompareElements with checking
; properties Type, Name, ClassName, AutomationId, and BoundingRectangle
static CompareElementsEx(e1, e2) {
local prop, p1, p2, br1, br2
try {
if UIA.CompareElements(e1, e2)
return 1
}
for prop in ["Type", "Name", "ClassName", "AutomationId"] {
try p1 := e1.Cached%prop%
catch
p1 := e1.%prop%
try p2 := e2.Cached%prop%
catch
p2 := e2.%prop%
if p1 != p2
return 0
}
try br1 := e1.CachedBoundingRectangle
catch
br1 := e1.BoundingRectangle
try br2 := e2.CachedBoundingRectangle
catch
br2 := e2.BoundingRectangle
return br1.l = br2.l && br1.t = br2.t && br1.r = br2.r && br1.b = br2.b
}
; Compares two integer arrays containing run-time identifiers (IDs) to determine whether their content is the same and they belong to the same UI element.
static CompareRuntimeIds(runtimeId1, runtimeId2) {
local areSame
return (ComCall(4, this, "ptr", runtimeId1, "ptr", runtimeId2, "int*", &areSame := 0), areSame)
}
/**
* Retrieves the UI Automation element that represents the desktop.
* @param cacheRequest Optional: a cache request object.
* @returns {UIA.IUIAutomationElement}
*/
static GetRootElement(cacheRequest?) {
if IsSet(cacheRequest)
return this.GetRootElementBuildCache(cacheRequest)
if (ComCall(5, this, "ptr*", &root := 0), root)
return this.IUIAutomationElement(root)
throw UnsetError("No element returned by " A_ThisFunc, -1)
}
/**
* Retrieves a UI Automation element for the specified window.
* @param hwnd WinTitle, window handle, or control handle
* @param cacheRequest Optional: a cache request object.
* @param activateChromiumAccessibility Whether to check if the window is a Chromium application
* and if it is then try to activate accessibility. The value will determine how long to wait for
* activation confirmation.
* If a VarRef is passed, then that variable will be set to the Chromium Document element (only
* if the activation was done).
* @returns {UIA.IUIAutomationElement}
*/
static ElementFromHandle(hwnd:="", cacheRequest?, activateChromiumAccessibility:=500) {
if !IsInteger(hwnd)
hwnd := WinExist(hwnd)
if !hwnd
throw TargetError("No matching window found", -1)
try {
if (activateChromiumAccessibility)
this.ActivateChromiumAccessibility(hwnd,, activateChromiumAccessibility, cacheRequest?)
}
if IsSet(cacheRequest)
return this.ElementFromHandleBuildCache(cacheRequest, hwnd)
if (ComCall(6, this, "ptr", hwnd, "ptr*", &element := 0), element)
return this.IUIAutomationElement(element)
throw UnsetError("No element returned by " A_ThisFunc, -1)
}
static ElementFromWindow(WinTitle:="", cacheRequest?, activateChromiumAccessibility:=500) => this.ElementFromHandle(WinTitle, cacheRequest?, activateChromiumAccessibility)
/**
* Retrieves the UI Automation element at the specified point on the desktop.
* @param x x coordinate for the screen point.
* Omit both x and y to get the element from the current mouse position.
* @param y y coordinate for the screen point.
* @param cacheRequest Optional: a cache request object.
* @param activateChromiumAccessibility Whether to check if the window is a Chromium application
* and if it is then try to activate accessibility. The value will determine how long to wait for
* activation confirmation.
* If a VarRef is passed, then that variable will be set to the Chromium Document element (only
* if the activation was done).
* @returns {UIA.IUIAutomationElement}
*/
static ElementFromPoint(x?, y?, cacheRequest?, activateChromiumAccessibility:=500) {
local pt64, hwnd
if !(IsSet(x) && IsSet(y))
DllCall("user32.dll\GetCursorPos", "int64P", &pt64:=0)
else
pt64 := y << 32 | (x & 0xFFFFFFFF)
try {
if (activateChromiumAccessibility && (hwnd := DllCall("GetAncestor", "Ptr", DllCall("user32.dll\WindowFromPoint", "int64", pt64, "ptr"), "UInt", 2, "ptr"))) ; hwnd from point by SKAN
this.ActivateChromiumAccessibility(hwnd,, activateChromiumAccessibility, cacheRequest?)
}
if IsSet(cacheRequest)
return this.ElementFromPointBuildCache(cacheRequest, pt64)
if (ComCall(7, this, "int64", pt64, "ptr*", &element := 0), element)
return this.IUIAutomationElement(element)
throw UnsetError("No element returned by " A_ThisFunc, -1)
}
/**
* Retrieves the smallest UI Automation element at the specified point on the desktop.
* Regular ElementFromPoint doesn't always return the deepest/smallest element.
* @param x x coordinate for the screen point.
* Omit both x and y to get the element from the current mouse position.
* @param y y coordinate for the screen point.
* @param element Optional: optionally provide an element for which the search is performed for.
* This element must be cached with CachedBoundingRectangle and TreeScope.Element+Descendants.
* @param cacheRequest Optional: a cache request object.
* @param deepSearch Whether SmallestElementFromPoint checks all the elements in the element Subtree
* or filters the elements level by level by whether they contain the point or not. Default is false.
* This means that is deepSearch is True then every element in the subtree is checked, but if
* false then only a small part of the tree is checked, which also means a difference in performance.
* DeepSearch might be useful if some of the intermediary elements have an incorrect size (eg in
* Firefox some group elements are 0-sized).
*
* @returns {UIA.IUIAutomationElement}
*/
static SmallestElementFromPoint(x?, y?, element?, cacheRequest?, deepSearch := false) {
static sCacheRequest := this.CreateCacheRequest(["BoundingRectangle"],,5)
local pt64
if !(IsSet(x) && IsSet(y))
DllCall("user32.dll\GetCursorPos", "int64P", &pt64:=0), x := 0xFFFFFFFF & pt64, y := pt64 >> 32
if deepSearch {
if !IsSet(cacheRequest)
cacheRequest := sCacheRequest
else
cacheRequest.AddProperty(UIA.Property.BoundingRectangle)
if !IsSet(element)
element := UIA.ElementFromPoint(x, y, sCacheRequest)
return this.CachedSmallestElementInElementContainingPoint(x, y, element)
}
if !IsSet(element)
element := UIA.ElementFromPoint(x, y)
element := this.SmallestElementInElementContainingPoint(x, y, element)
return IsSet(cacheRequest) ? element.BuildUpdatedCache(cacheRequest) : element
}
; Returns the smallest element inside another element (it included) that contains the point (x,y)
static SmallestElementInElementContainingPoint(x, y, element) {
static cr := UIA.CreateCacheRequest(["BoundingRectangle"])
local el, smallest := element, smallestSize := 100000000, rect, evaluated := [element.BuildUpdatedCache(cr)]
while evaluated.Length {
el := evaluated.Pop(), rect := el.CachedBoundingRectangle
if rect.l<=x && rect.r >=x && rect.t <= y && rect.b >= y {
evaluated.Push(el.FindAllBuildCache(cr,, 2)*), size := (rect.r-rect.l)*(rect.b-rect.t)
if size < smallestSize
smallest := el, smallestSize := size
}
}
return smallest
}
; Requires the elements subtree to be cached with the BoundingRectangle property
static CachedSmallestElementInElementContainingPoint(x, y, element) {
local el, smallest := element, smallestSize := 100000000, rect
for el in element.GetCachedChildren(5) {
rect := el.CachedBoundingRectangle
if rect.l<=x && rect.r >=x && rect.t <= y && rect.b >= y {
size := (rect.r-rect.l)*(rect.b-rect.t)
if size < smallestSize
smallest := el, smallestSize := size
}
}
return smallest
}
/**
* Retrieves the UI Automation element that has the input focus.
* @param cacheRequest Optional: a cache request object.
* @returns {UIA.IUIAutomationElement}
*/
static GetFocusedElement(cacheRequest?) {
if IsSet(cacheRequest)
return this.GetFocusedElementBuildCache(cacheRequest)
if (ComCall(8, this, "ptr*", &element := 0), element)
return this.IUIAutomationElement(element)
throw UnsetError("No element returned by " A_ThisFunc, -1)
}
; Retrieves the UI Automation element that has the input focus, prefetches the requested properties and control patterns, and stores the prefetched items in the cache.
; This is a raw wrapper, instead use GetRootElement and specify cacheRequest.
static GetRootElementBuildCache(cacheRequest) {
local root
if (ComCall(9, this, "ptr", this.TypeValidation.CacheRequest(cacheRequest), "ptr*", &root := 0), root)
return this.IUIAutomationElement(root)
throw UnsetError("No element returned by " A_ThisFunc, -1)
}
; Retrieves a UI Automation element for the specified window, prefetches the requested properties and control patterns, and stores the prefetched items in the cache.
; This is a raw wrapper, instead use ElementFromHandle and specify cacheRequest.
static ElementFromHandleBuildCache(cacheRequest, hwnd) {
local element
if (ComCall(10, this, "ptr", hwnd, "ptr", this.TypeValidation.CacheRequest(cacheRequest), "ptr*", &element := 0), element)
return this.IUIAutomationElement(element)
throw UnsetError("No element returned by " A_ThisFunc, -1)
}
; Retrieves the UI Automation element at the specified point on the desktop, prefetches the requested properties and control patterns, and stores the prefetched items in the cache.
; This is a raw wrapper, instead use ElementFromPoint and specify cacheRequest.
static ElementFromPointBuildCache(cacheRequest, pt) {
local element
if (ComCall(11, this, "int64", pt, "ptr", this.TypeValidation.CacheRequest(cacheRequest), "ptr*", &element := 0), element)
return this.IUIAutomationElement(element)
throw UnsetError("No element returned by " A_ThisFunc, -1)
}
; Retrieves the UI Automation element that has the input focus, prefetches the requested properties and control patterns, and stores the prefetched items in the cache.
; This is a raw wrapper, instead use GetFocusedElement and specify cacheRequest.
static GetFocusedElementBuildCache(cacheRequest) {
local element
if (ComCall(12, this, "ptr", this.TypeValidation.CacheRequest(cacheRequest), "ptr*", &element := 0), element)
return this.IUIAutomationElement(element)
throw UnsetError("No element returned by " A_ThisFunc, -1)
}
; Retrieves a tree walker object that can be used to traverse the Microsoft UI Automation tree.
static CreateTreeWalker(pCondition) {
local walker
if (ComCall(13, this, "ptr", (Type(pCondition) ~= "i)Condition|ComValue") ? pCondition : this.__CreateRawCondition(pCondition), "ptr*", &walker := 0), walker)
return this.IUIAutomationTreeWalker(walker)
throw UnsetError("No TreeWalker returned by " A_ThisFunc, -1)
}
/**
* Creates a cache request. After obtaining the IUIAutomationCacheRequest interface, use its methods to specify properties and control patterns to be cached when a UI Automation element is obtained.
* @param properties Optional: an array containing properties that will be added to the CacheRequest
* @param patterns Optional: an array containing patterns that will be added to the CacheRequest
* @param scope Optional: set the TreeScope for the CacheRequest (one of UIA.TreeScope values). Default is UIA.TreeScope.Element
* @param mode Optional: set the AutomationElementMode for the CacheRequest (one of UIA.AutomationElementMode values). Default is Full.
* @param filter Optional: a condition for caching elements. Default is ControlView.
*/
static CreateCacheRequest(properties?, patterns?, scope?, mode?, filter?) {
local cacheRequest, v
if cacheRequest := (ComCall(20, this, "ptr*", &cacheRequest := 0), cacheRequest?this.IUIAutomationCacheRequest(cacheRequest):"") {
if IsSet(properties) {
if Type(properties) = "Object" {
if properties.HasOwnProp("filter")
filter := properties.DeleteProp("filter")
if properties.HasOwnProp("mode")
mode := properties.DeleteProp("mode")
if properties.HasOwnProp("scope")
scope := properties.DeleteProp("scope")
if properties.HasOwnProp("patterns")
patterns := properties.DeleteProp("patterns")
if properties.HasOwnProp("properties")
properties := properties.DeleteProp("properties")
}
if properties is Array && properties[1] is String {
for v in properties
cacheRequest.AddProperty(v)
} else if IsObject(properties) {
cacheRequest.AddPropertiesFromCondition(properties)
} else
throw TypeError("Expected properties argument of type Array or Object, but got " Type(properties), -1)
}
if IsSet(patterns) {
if not patterns is Array
throw TypeError("Expected patterns argument of type Array, but got " Type(properties), -1)
for v in patterns
cacheRequest.AddPattern(v)
}
if IsSet(scope)
cacheRequest.TreeScope := scope
if IsSet(mode)
cacheRequest.AutomationElementMode := mode
if IsSet(filter)
cacheRequest.TreeFilter := filter
}
return cacheRequest
}
static CreateTrueCondition() {
local newCondition
if (ComCall(21, this, "ptr*", &newCondition := 0), newCondition)
return this.IUIAutomationBoolCondition(newCondition)
throw UnsetError("No condition returned by " A_ThisFunc, -1)
}
; Creates a condition that is always false.
; This method exists only for symmetry with IUIAutomation.CreateTrueCondition(). A false condition will never enable a match with UI Automation elements, and it cannot usefully be combined with any other condition.
static CreateFalseCondition() {
local newCondition
if (ComCall(22, this, "ptr*", &newCondition := 0), newCondition)
return this.IUIAutomationBoolCondition(newCondition)
throw UnsetError("No condition returned by " A_ThisFunc, -1)
}
; Creates a condition that selects elements that have a property with the specified value.
static CreatePropertyCondition(propertyId, value, variant?) {
local v, newCondition
if A_PtrSize = 4
v := this.ComVar(value, variant ?? this.PropertyVariantType[propertyId], true), ComCall(23, this, "int", propertyId, "int64", NumGet(v, 'int64'), "int64", NumGet(v, 8, "int64"), "ptr*", &newCondition := 0)
else
ComCall(23, this, "int", propertyId, "ptr", this.ComVar(value, variant ?? this.PropertyVariantType[propertyId], true), "ptr*", &newCondition := 0)
if newCondition
return this.IUIAutomationPropertyCondition(newCondition)
throw Error("Creating property condition failed", -1)
}
; Creates a condition that selects elements that have a property with the specified value, using optional flags.
; This is a raw wrapper, instead use CreateCondition and specify flags.
static CreatePropertyConditionEx(propertyId, value, flags := 0, variant?) {
local v, newCondition
if A_PtrSize = 4
v := this.ComVar(value, variant ?? this.PropertyVariantType[propertyId], true), ComCall(24, this, "int", propertyId, "int64", NumGet(v, 'int64'), "int64", NumGet(v, 8, "int64"), "int", flags, "ptr*", &newCondition := 0)
else
ComCall(24, this, "int", propertyId, "ptr", this.ComVar(value, variant ?? this.PropertyVariantType[propertyId], true), "int", flags, "ptr*", &newCondition := 0)
if newCondition
return this.IUIAutomationPropertyCondition(newCondition)
throw Error("Creating property condition failed", -1)
}
; The Create**Condition** method calls AddRef on each pointers. This means you can call Release on those pointers after the call to Create**Condition** returns without invalidating the pointer returned from Create**Condition**.
; When you call Release on the pointer returned from Create**Condition**, UI Automation calls Release on those pointers.
; Creates a condition that selects elements that match both of two conditions.
static CreateAndCondition(condition1, condition2) {
local newCondition
if (ComCall(25, this, "ptr", condition1, "ptr", condition2, "ptr*", &newCondition := 0), newCondition)
return this.IUIAutomationAndCondition(newCondition)
throw UnsetError("No condition returned by " A_ThisFunc, -1)
}
; Creates a condition that selects elements based on multiple conditions, all of which must be true.
static CreateAndConditionFromArray(conditions) {
local newCondition
if (ComCall(26, this, "ptr", conditions is Array ? this.Variant(conditions, 0xd) : conditions, "ptr*", &newCondition := 0), newCondition)
return this.IUIAutomationAndCondition(newCondition)
throw UnsetError("No condition returned by " A_ThisFunc, -1)
}
; Creates a condition that selects elements based on multiple conditions, all of which must be true.
static CreateAndConditionFromNativeArray(conditions, conditionCount) {
local newCondition
if (ComCall(27, this, "ptr", conditions, "int", conditionCount, "ptr*", &newCondition := 0), newCondition)
return this.IUIAutomationAndCondition(newCondition)
throw UnsetError("No condition returned by " A_ThisFunc, -1)
}
; Creates a combination of two conditions where a match exists if either of the conditions is true.
static CreateOrCondition(condition1, condition2) {
local newCondition
if (ComCall(28, this, "ptr", condition1, "ptr", condition2, "ptr*", &newCondition := 0), newCondition)
return this.IUIAutomationOrCondition(newCondition)
throw UnsetError("No condition returned by " A_ThisFunc, -1)
}
; Creates a combination of two or more conditions where a match exists if any of the conditions is true.
static CreateOrConditionFromArray(conditions) {
local newCondition
if (ComCall(29, this, "ptr", conditions is Array ? this.Variant(conditions, 0xd) : conditions, "ptr*", &newCondition := 0), newCondition)
return this.IUIAutomationOrCondition(newCondition)
throw UnsetError("No condition returned by " A_ThisFunc, -1)
}
; Creates a combination of two or more conditions where a match exists if any one of the conditions is true.
static CreateOrConditionFromNativeArray(conditions, conditionCount) {
local newCondition
if (ComCall(30, this, "ptr", conditions, "ptr", conditionCount, "ptr*", &newCondition := 0), newCondition)
return this.IUIAutomationOrCondition(newCondition)
throw UnsetError("No condition returned by " A_ThisFunc, -1)
}
; Creates a condition that is the negative of a specified condition.
static CreateNotCondition(condition) {
local newCondition
if (ComCall(31, this, "ptr", condition, "ptr*", &newCondition := 0), newCondition)
return this.IUIAutomationNotCondition(newCondition)
throw UnsetError("No condition returned by " A_ThisFunc, -1)
}
; Note, Before implementing an event handler, you should be familiar with the threading issues described in Understanding Threading Issues. http,//msdn.microsoft.com/en-us/library/ee671692(v=vs.85).aspx
; A UI Automation client should not use multiple threads to add or remove event handlers. Unexpected behavior can result if one event handler is being added or removed while another is being added or removed in the same client process.
; It is possible for an event to be delivered to an event handler after the handler has been unsubscribed, if the event is received simultaneously with the request to unsubscribe the event. The best practice is to follow the Component Object Model (COM) standard and avoid destroying the event handler object until its reference count has reached zero. Destroying an event handler immediately after unsubscribing for events may result in an access violation if an event is delivered late.
/**
* Registers a method that handles Microsoft UI Automation events.
* @param handler Handler object from UIA.CreateEventHandler()
* @param element UIA element
* @param eventId One of UIA.Event values
* @param scope Optional TreeScope value: Element, Children, Family (Element+Children), Descendants, Subtree (=Element+Descendants). Default is Descendants.
* @param cacheRequest Optional: cache request object
*/
static AddAutomationEventHandler(handler, element, eventId, scope:=0x4, cacheRequest:=0) => ComCall(32, this, "int", this.TypeValidation.Event(eventId), "ptr", this.TypeValidation.Element(element), "int", this.TypeValidation.TreeScope(scope), "ptr", this.TypeValidation.CacheRequest(cacheRequest), "ptr", handler)
/**
* Removes the specified UI Automation event handler.
* @param handler Handler object from UIA.CreateEventHandler()
* @param element UIA element
* @param eventId One of UIA.Event values
*/
static RemoveAutomationEventHandler(handler, element, eventId) => ComCall(33, this, "int", this.TypeValidation.Event(eventId), "ptr", this.TypeValidation.Element(element), "ptr", handler)
; Registers a method that handles property-changed events.
; The UI item specified by element might not support the properties specified by the propertyArray parameter.
; This method serves the same purpose as UIA.AddPropertyChangedEventHandler, but takes a native array of property identifiers instead of a SAFEARRAY.
; Not needed in this library, use UIA.AddPropertyChangedEventHandler instead.
static AddPropertyChangedEventHandlerNativeArray(handler, element, propertyArray, propertyCount, scope:=0x4, cacheRequest:=0) => ComCall(34, this, "ptr", this.TypeValidation.Element(element), "int", this.TypeValidation.TreeScope(scope), "ptr", this.TypeValidation.CacheRequest(cacheRequest), "ptr", handler, "ptr", propertyArray, "int", propertyCount)
/**
* Registers a method that handles property-changed events.
* The UI item specified by element might not support the properties specified by the propertyArray parameter.
* @param handler Handler object from UIA.CreateEventHandler()
* @param element UIA element
* @param propertyArray An array of UIA.Property values
* @param scope Optional TreeScope value: Element, Children, Family (Element+Children), Descendants, Subtree (=Element+Descendants). Default is Descendants.
* @param cacheRequest Optional: cache request object
*/
static AddPropertyChangedEventHandler(handler, element, propertyArray, scope:=0x4, cacheRequest:=0) {
local i, SafeArray
if !IsObject(propertyArray)
propertyArray := [propertyArray]
SafeArray:=ComObjArray(0x3,propertyArray.Length)
for i, propertyId in propertyArray
SafeArray[i-1]:=propertyId
ComCall(35, this, "ptr", this.TypeValidation.Element(element), "int", this.TypeValidation.TreeScope(scope), "ptr", this.TypeValidation.CacheRequest(cacheRequest), "ptr", handler, "ptr", SafeArray)
}
; Removes a property-changed event handler.
static RemovePropertyChangedEventHandler(handler, element) => ComCall(36, this, "ptr", this.TypeValidation.Element(element), "ptr", handler)
/**
* Registers a method that handles structure-changed events.
* @param handler Handler object from UIA.CreateEventHandler()
* @param element UIA element
* @param scope Optional TreeScope value: Element, Children, Family (Element+Children), Descendants, Subtree (=Element+Descendants). Default is Descendants.
* @param cacheRequest Optional: cache request object
*/
static AddStructureChangedEventHandler(handler, element, scope:=0x4, cacheRequest:=0) => ComCall(37, this, "ptr", this.TypeValidation.Element(element), "int", this.TypeValidation.TreeScope(scope), "ptr", this.TypeValidation.CacheRequest(cacheRequest), "ptr", handler)
; Removes a structure-changed event handler.
static RemoveStructureChangedEventHandler(handler, element) => ComCall(38, this, "ptr", this.TypeValidation.Element(element), "ptr", handler)
/**
* Registers a method that handles focus-changed events.
* Focus-changed events are system-wide; you cannot set a narrower scope.
* @param handler Handler object from UIA.CreateEventHandler()
* @param cacheRequest Optional: cache request object
*/
static AddFocusChangedEventHandler(handler, cacheRequest:=0) => ComCall(39, this, "ptr", this.TypeValidation.CacheRequest(cacheRequest), "ptr", handler)
; Removes a focus-changed event handler.
static RemoveFocusChangedEventHandler(handler) => ComCall(40, this, "ptr", handler)
; Removes all registered Microsoft UI Automation event handlers.
static RemoveAllEventHandlers() => ComCall(41, this)
; Converts an array of integers to a SAFEARRAY.
static IntNativeArrayToSafeArray(array, arrayCount) {
local safeArray
return (ComCall(42, this, "ptr", array, "int", arrayCount, "ptr*", &safeArray := 0), ComValue(0x2003, safeArray))
}
; Converts a SAFEARRAY of integers to an array.
static IntSafeArrayToNativeArray(intArray) {
local array, arrayCount
return (ComCall(43, this, "ptr", intArray, "ptr*", &array := 0, "int*", &arrayCount := 0), this.NativeArray(array, arrayCount, "int"))
}
; Creates a VARIANT that contains the coordinates of a rectangle.
; The returned VARIANT has a data type of VT_ARRAY | VT_R8.
static RectToVariant(rc) {
local var
return (ComCall(44, this, "ptr", rc, "ptr", var := this.ComVar()), var)
}
; Converts a VARIANT containing rectangle coordinates to a RECT.
static VariantToRect(var) {
if A_PtrSize = 4
ComCall(45, this, "int64", NumGet(var, "int64"), "int64", NumGet(var, 8, "int64"), "ptr", rc := this.NativeArray(0, 4, "Int"))
else
ComCall(45, this, "ptr", var, "ptr", rc := this.NativeArray(0, 4, "Int"))
return rc
}
; Converts a SAFEARRAY containing rectangle coordinates to an array of type RECT.
static SafeArrayToRectNativeArray(rects) {
local rectArrayCount
return (ComCall(46, this, "ptr", rects, "ptr*", &rectArray := 0, "int*", &rectArrayCount := 0), this.NativeArray(rectArray, rectArrayCount, "int"))
}
; Creates a instance of a proxy factory object.
; Use the IUIAutomationProxyFactoryMapping interface to enter the proxy factory into the table of available proxies.
static CreateProxyFactoryEntry(factory) {
local factoryEntry
if (ComCall(47, this, "ptr", factory, "ptr*", &factoryEntry := 0), factoryEntry)
return this.IUIAutomationProxyFactoryEntry(factoryEntry)
throw UnsetError("No ProxyFactoryEntry returned by " A_ThisFunc, -1)
}
; Retrieves an object that represents the mapping of Window classnames and associated data to individual proxy factories. This property is read-only.
static ProxyFactoryMapping() {
local factoryMapping
if (ComCall(48, this, "ptr*", &factoryMapping := 0), factoryMapping)
return this.IUIAutomationProxyFactoryMapping(factoryMapping)
throw UnsetError("No ProxyFactoryMapping returned by " A_ThisFunc, -1)
}
; The programmatic name is intended for debugging and diagnostic purposes only. The string is not localized.
; This property should not be used in string comparisons. To determine whether two properties are the same, compare the property identifiers directly.
; Retrieves the registered programmatic name of a property.
static GetPropertyProgrammaticName(property) {
local name
return (ComCall(49, this, "int", property, "ptr*", &name := 0), this.BSTR(name))
}
; Retrieves the registered programmatic name of a control pattern.
static GetPatternProgrammaticName(pattern) {
local name
return (ComCall(50, this, "int", this.TypeValidation.Pattern(pattern), "ptr*", &name := 0), this.BSTR(name))
}
; This method is intended only for use by Microsoft UI Automation tools that need to scan for properties. It is not intended to be used by UI Automation clients.
; There is no guarantee that the element will support any particular control pattern when asked for it later.
; Retrieves the control patterns that might be supported on a UI Automation element.
static PollForPotentialSupportedPatterns(pElement, &patternIds, &patternNames) {
ComCall(51, this, "ptr", this.TypeValidation.Element(pElement), "ptr*", &patternIds := 0, "ptr*", &patternNames := 0)
patternIds := this.SafeArrayToAHKArray(patternIds, 3), patternNames := this.SafeArrayToAHKArray(patternNames, 8)
}
; Retrieves the properties that might be supported on a UI Automation element.
static PollForPotentialSupportedProperties(pElement, &propertyIds, &propertyNames) {
ComCall(52, this, "ptr", this.TypeValidation.Element(pElement), "ptr*", &propertyIds := 0, "ptr*", &propertyNames := 0)
propertyIds := this.SafeArrayToAHKArray(propertyIds, 3), propertyNames := this.SafeArrayToAHKArray(propertyNames, 8)
}
; Checks a provided VARIANT to see if it contains the Not Supported identifier.
; After retrieving a property for a UI Automation element, call this method to determine whether the element supports the retrieved property. CheckNotSupported is typically called after calling a property retrieving method such as GetPropertyValue.
static CheckNotSupported(value) {
if A_PtrSize = 4
value := this.ComVar(value, , true), ComCall(53, this, "int64", NumGet(value, "int64"), "int64", NumGet(value, 8, "int64"), "int*", &isNotSupported := 0)
else
ComCall(53, this, "ptr", this.ComVar(value, , true), "int*", &isNotSupported := 0)
return isNotSupported
}
; This method enables UI Automation clients to get UIA.IUIAutomationElement interfaces for accessible objects implemented by a Microsoft Active Accessiblity server.
; This method may fail if the server implements UI Automation provider interfaces alongside Microsoft Active Accessibility support.
; The method returns E_INVALIDARG if the underlying implementation of the Microsoft UI Automation element is not a native Microsoft Active Accessibility server; that is, if a client attempts to retrieve the IAccessible interface for an element originally supported by a proxy object from Oleacc.dll, or by the UIA-to-MSAA Bridge.
; Retrieves a UI Automation element for the specified accessible object from a Microsoft Active Accessibility server.
; Currently not working
static ElementFromIAccessible(accessible, childId:=0) => (InStr(Type(accessible), "IAccessible") ? (ComCall(56, this, "ptr", accessible, "int", accessible.childId, "ptr*", &element := 0), this.IUIAutomationElement(element)) : (ComCall(56, this, "ptr", ComObjValue(accessible), "int", childId, "ptr*", &element := 0), this.IUIAutomationElement(element)))
; Retrieves a UI Automation element for the specified accessible object from a Microsoft Active Accessibility server, prefetches the requested properties and control patterns, and stores the prefetched items in the cache.
static ElementFromIAccessibleBuildCache(cacheRequest, accessible, childId:=0) => (InStr(Type(accessible), "IAccessible") ? (ComCall(57, this, "ptr", accessible.accessible, "int", accessible.childId, "ptr", this.TypeValidation.CacheRequest(cacheRequest), "ptr*", &element := 0), this.IUIAutomationElement(element)) : (ComCall(57, this, "ptr", accessible, "int", childId, "ptr", this.TypeValidation.CacheRequest(cacheRequest), "ptr*", &element := 0), this.IUIAutomationElement(element)))
; ---------- IUIAutomation3 ----------
/**
* Registers a method that handles programmatic text-edit events.
* @param handler Handler object from UIA.CreateEventHandler()
* @param element UIA element
* @param textEditChangeType The specific change type to listen for, one of UIA.TextEditChangeType values (None, AutoCorrect, Composition, CompositionFinalized, AutoComplete)
* @param scope Optional TreeScope value: Element, Children, Family (Element+Children), Descendants, Subtree (=Element+Descendants). Default is Descendants.
* @param cacheRequest Optional: cache request object
*/
static AddTextEditTextChangedEventHandler(handler, element, textEditChangeType, scope:=0x4, cacheRequest:=0) => (ComCall(64, this, "ptr", UIA.TypeValidation.Element(element), "int", UIA.TypeValidation.TreeScope(scope), "int", UIA.TypeValidation.TextEditChangeType(textEditChangeType), "ptr", UIA.TypeValidation.CacheRequest(cacheRequest), "ptr", handler))
static RemoveTextEditTextChangedEventHandler(handler, element) => ComCall(65, this, "ptr", UIA.TypeValidation.Element(element), "ptr", handler)
; ---------- IUIAutomation4 ----------
/**
* Registers a method that handles change events.
* @param handler Handler object from UIA.CreateEventHandler()
* @param element UIA element
* @param changeTypes An array of UIA.Changes values that indicate the change types the event represents.
* @param scope Optional TreeScope value: Element, Children, Family (Element+Children), Descendants, Subtree (=Element+Descendants). Default is Descendants.
* @param cacheRequest Optional: cache request object
*/
static AddChangesEventHandler(handler, element, changeTypes, scope:=0x4, cacheRequest:=0) {
local k, v
if !IsObject(changeTypes)
changeTypes := [changeTypes]
nativeArray := this.NativeArray(0, changeTypes.Length, "int")
for k, v in changeTypes
NumPut("int", v, nativeArray, (k-1)*4)
ComCall(66, this, "ptr", this.TypeValidation.Element(element), "int", this.TypeValidation.TreeScope(scope), "ptr", nativeArray, "int", changeTypes.Length, "ptr", this.TypeValidation.CacheRequest(cacheRequest), "ptr", handler)
}
static RemoveChangesEventHandler(handler, element) => (ComCall(67, this, "ptr", this.TypeValidation.Element(element), "ptr", handler))
; ---------- IUIAutomation5 ----------
/**
* Registers a method that handles notification events.
* @param handler Handler object from UIA.CreateEventHandler()
* @param element UIA element
* @param scope Optional TreeScope value: Element, Children, Family (Element+Children), Descendants, Subtree (=Element+Descendants). Default is Descendants.
* @param cacheRequest Optional: cache request object
*/
static AddNotificationEventHandler(handler, element, scope:=0x4, cacheRequest:=0) => (ComCall(68, this, "ptr", this.TypeValidation.Element(element), "uint", this.TypeValidation.TreeScope(scope), "ptr", this.TypeValidation.CacheRequest(cacheRequest), "ptr", handler))
static RemoveNotificationEventHandler(handler, element) => (ComCall(69, this, "ptr", this.TypeValidation.Element(element), "ptr", handler))
; ---------- IUIAutomation6 ----------
; Registers one or more event listeners in a single method call.
static CreateEventHandlerGroup() {
local out
return (ComCall(70, this, "ptr*", &out:=0), this.IUIAutomationEventHandlerGroup(out))
}
; Registers a collection of event handler methods specified with the IUIAutomation6 CreateEventHandlerGroup.
static AddEventHandlerGroup(handlerGroup, element) => (ComCall(71, this, "ptr", this.TypeValidation.Element(element), "ptr", handlerGroup))
static RemoveEventHandlerGroup(handlerGroup, element) => (ComCall(72, this, "ptr", this.TypeValidation.Element(element), "ptr", handlerGroup))
; Registers a method that handles when the active text position changes.
static AddActiveTextPositionChangedEventHandler(handler, element, scope:=0x4, cacheRequest:=0) => (ComCall(77, this, "ptr", this.TypeValidation.Element(element), "int", this.TypeValidation.TreeScope(scope), "ptr", this.TypeValidation.CacheRequest(cacheRequest), "ptr", handler))
static RemoveActiveTextPositionChangedEventHandler(handler, element) => (ComCall(78, this, "ptr", this.TypeValidation.Element(element), "ptr", handler))
; ---------- IUIAutomation7 ----------
; Has no properties/methods
; ---------- Internal methods and properties ----------
static SetScreenReader(state, fWinIni:=2) {
DllCall("user32.dll\SystemParametersInfo", "uint", 0x0047, "uint", state, "uint", 0, "int", fWinIni) ; SPI_SETSCREENREADER
}
static GetScreenReader() {
(A_PtrSize = 4) ? DllCall("user32.dll\SystemParametersInfo", "uint", 0x0046, "uint", 0, "ptr*", &screenreader:=0, "uint", 0) : DllCall("user32.dll\SystemParametersInfo", "uint", 0x0046, "uint", 0, "ptr*", &screenreader:=0) ; SPI_GETSCREENREADER
return screenreader
}
; BSTR wrapper, convert BSTR to AHK string and free it
static BSTR(ptr) {
static _ := DllCall("LoadLibrary", "str", "oleaut32.dll")
if ptr {
s := StrGet(ptr), DllCall("oleaut32\SysFreeString", "ptr", ptr)
return s
}
}
static SafeArrayToAHKArray(sArr, varType:=3) {
local _, v, ret := []
if IsInteger(sArr)
sArr := ComValue(0x2000 | varType, sArr)
for _, v in sArr
ret.Push(v)
ret.DefineProp("__Value", {value:sArr})
ret.DefineProp("ptr", {value:sArr.ptr})
return ret
}
static AHKArrayToSafeArray(arr, varType:=3) {
local index, value, cArr
cArr := ComObjArray(varType, arr.Length)
for index, value in arr
cArr[index-1] := value
return cArr
}
; X can be pt64 as well, in which case Y should be omitted
static WindowFromPoint(X, Y?) { ; by SKAN and Linear Spoon
return DllCall("GetAncestor", "Ptr", DllCall("user32.dll\WindowFromPoint", "Int64", IsSet(Y) ? (Y << 32 | (X & 0xFFFFFFFF)) : X), "UInt", 2, "Ptr")
}
/**
* Checks whether two rectangles intersect and if they do, then returns an object containing the
* rectangle of the intersection: {l:left, t:top, r:right, b:bottom}
* Note 1: Overlapping area must be at least 1 unit.
* Note 2: Second rectangle starting at the edge of the first doesn't count as intersecting:
* {l:100, t:100, r:200, b:200} does not intersect {l:200, t:100, 400, 400}
* @param l1 x-coordinate of the upper-left corner of the first rectangle
* @param t1 y-coordinate of the upper-left corner of the first rectangle
* @param r1 x-coordinate of the lower-right corner of the first rectangle
* @param b1 y-coordinate of the lower-right corner of the first rectangle
* @param l2 x-coordinate of the upper-left corner of the second rectangle
* @param t2 y-coordinate of the upper-left corner of the second rectangle
* @param r2 x-coordinate of the lower-right corner of the second rectangle
* @param b2 y-coordinate of the lower-right corner of the second rectangle
* @returns {Object}
*/
static IntersectRect(l1, t1, r1, b1, l2, t2, r2, b2) {
rect1 := Buffer(16), rect2 := Buffer(16), rectOut := Buffer(16)
NumPut("int", l1, "int", t1, "int", r1, "int", b1, rect1)
NumPut("int", l2, "int", t2, "int", r2, "int", b2, rect2)
if DllCall("user32\IntersectRect", "Ptr", rectOut, "Ptr", rect1, "Ptr", rect2)
return {l:NumGet(rectOut, 0, "Int"), t:NumGet(rectOut, 4, "Int"), r:NumGet(rectOut, 8, "Int"), b:NumGet(rectOut, 12, "Int")}
}
; Creates a variant to pass into ComCalls
class Variant {
__New(Value := unset, VarType := 0xC) {
local v, i, obj
static SIZEOF_VARIANT := 8 + (2 * A_PtrSize)
this.var := Buffer(SIZEOF_VARIANT, 0)
if VarType != 0xC
NumPut "ushort", VarType, this.var
this.owner := True
if IsSet(Value) {
if (Type(Value) == "ComVar") {
this.var := Value.var, this.ref := Value.ref, this.obj := Value, this.owner := False
return
}
if (IsObject(Value)) {
this.ref := ComValue(0x400C, this.var.ptr)
if Value is Array {
if Value.Length {
switch Type(Value[1]) {
case "Integer": VarType := 3
case "String": VarType := 8
case "Float": VarType := 5
case "ComValue", "ComObject": VarType := ComObjType(Value[1])
default: VarType := 0xC
}
} else
VarType := 0xC
ComObjFlags(obj := ComObjArray(VarType, Value.Length), -1), i := 0, this.ref[] := obj
for v in Value
obj[i++] := v
return
}
}
}
this.ref := ComValue(0x4000 | VarType, this.var.Ptr + (VarType = 0xC ? 0 : 8))
this.ref[] := Value
}
__Delete() => (this.owner ? DllCall("oleaut32\VariantClear", "ptr", this.var) : 0)
__Item {
get => this.Type=0xB?-this.ref[]:this.ref[]
set => this.ref[] := this.Type=0xB?(!value?0:-1):value
}
Ptr => this.var.Ptr
Size => this.var.Size
Type {
get => NumGet(this.var, "ushort")
set {
if (!this.IsVariant)
throw PropertyError("VarType is not VT_VARIANT, Type is read-only.", -2)
NumPut("ushort", Value, this.var)
}
}
IsVariant => ComObjType(this.ref) & 0xC
}
; Construction and deconstruction VARIANT struct
class ComVar {
/**
* Construction VARIANT struct, `ptr` property points to the address, `__Item` property returns var's Value
* @param vVal Values that need to be wrapped, supports String, Integer, Double, Array, ComValue, ComObjArray
* ### Examples
* `var1 := ComVar('string'), MsgBox(var1[])`
*
* `var2 := ComVar([1,2,3,4], , true)`
*
* `var3 := ComVar(ComValue(0xb, -1))`
* @param vType Variant's type, VT_VARIANT (default)
* @param convert Convert AHK's array to ComObjArray
*/
__New(vVal := unset, vType := 0xC, convert := false) {
local v, i, obj
static size := 8 + 2 * A_PtrSize
this.var := Buffer(size, 0), this.owner := true
this.ref := ComValue(0x4000 | vType, this.var.Ptr + (vType = 0xC ? 0 : 8))
if vType != 0xC
NumPut "ushort", vType, this.var
if IsSet(vVal) {
if (Type(vVal) == "ComVar") {
this.var := vVal.var, this.ref := vVal.ref, this.obj := vVal, this.owner := false
} else {
if (IsObject(vVal)) {
if (vType != 0xC)
this.ref := ComValue(0x400C, this.var.ptr)
if convert && (vVal is Array) {
switch Type(vVal[1]) {
case "Integer": vType := 3
case "String": vType := 8
case "Float": vType := 5
case "ComValue", "ComObject": vType := ComObjType(vVal[1])
default: vType := 0xC
}
ComObjFlags(obj := ComObjArray(vType, vVal.Length), -1), i := 0, this.ref[] := obj
for v in vVal
obj[i++] := v
} else
this.ref[] := vVal
} else
this.ref[] := vVal
}
}
}
__Delete() => (this.owner && this.var ? DllCall("oleaut32\VariantClear", "ptr", this.var) : 0)
__Item {
get => this.ref[]
set => this.ref[] := value
}
Ptr => this.var.Ptr
Size => this.var.Size
Type {
get => NumGet(this.var, "ushort")
set {
if (!this.IsVariant)
throw PropertyError("VarType is not VT_VARIANT, Type is read-only.", -2)
NumPut("ushort", Value, this.var)
}
}
IsVariant => ComObjType(this.ref) & 0xC
}
; NativeArray is C style array, zero-based index, it has `__Item` and `__Enum` property
class NativeArray {
__New(ptr, count, type := "ptr") {
static _ := DllCall("LoadLibrary", "str", "ole32.dll")
static bits := { UInt: 4, UInt64: 8, Int: 4, Int64: 8, Short: 2, UShort: 2, Char: 1, UChar: 1, Double: 8, Float: 4, Ptr: A_PtrSize, UPtr: A_PtrSize }
this.size := (this.count := count) * (bit := bits.%type%), this.ptr := ptr || DllCall("ole32\CoTaskMemAlloc", "uint", this.size, "ptr")
this.DefineProp("__Item", { get: (s, i) => NumGet(s, i * bit, type) })
this.DefineProp("__Enum", { call: (s, i) => (i = 1 ?
(i := 0, (&v) => i < count ? (v := NumGet(s, i * bit, type), ++i) : false) :
(i := 0, (&k, &v) => (i < count ? (k := i, v := NumGet(s, i * bit, type), ++i) : false))
) })
}
__Delete() => DllCall("ole32\CoTaskMemFree", "ptr", this)
}
class TypeValidation {
static __Call(method, args) {
local val
if UIA.HasProp(method) { ; Handles enumeration type validation: UIA.TypeValidation.TreeScope(scope)
val := args[1]
if IsInteger(val) {
try UIA.%method%[val]
catch
throw ValueError("UIA." method " does not contain constant `"" val "`"", -2)
return val is Integer ? val : Integer(val)
}
if val is String {
try return UIA.%method%.%val%
throw ValueError("UIA." method " does not contain value for `"" val "`"", -2)
}
throw TypeError(method " requires parameter with type Integer or String, but received " Type(val), -2)
} else {
if !(val := args[1])
return val
if (IsObject(val) && (val is UIA.IUIAutomation%method%)) || (val is ComValue) || (val is Integer)
return val
throw TypeError(method " requires parameter with type UIA.IUIAutomation" method ", but was provided type " Type(val), -2)
}
}
static Integer(arg, paramName) {
if IsInteger(arg)
return arg is Integer ? arg : Integer(arg)
throw TypeError(paramName " requires type Integer, but received type " Type(arg), -2)
}
static String(arg, paramName) {
if arg is String
return arg
if !(arg is Object)
return String(arg)
throw TypeError(paramName " requires type String, but received type " Type(arg), -2)
}
static Object(arg, paramName) {
if arg is Object
return arg
throw TypeError(paramName " requires type Object, but received type " Type(arg), -2)
}
; Provide pre-optimized methods for commonly used validations
static RawCondition(arg) {
if (Type(arg) ~= "i)Condition|ComValue")
return arg
throw TypeError("Condition argument requires parameter with type UIA.IUIAutomationCondition or a ComValue, but receiver " Type(arg), -2)
}
static CacheRequest(arg) {
if !arg || (arg is UIA.IUIAutomationCacheRequest) || (arg is ComValue) || (arg is Integer)
return arg
throw TypeError("CacheRequest argument requires parameter with type UIA.IUIAutomationCacheRequest, but received " Type(arg), -2)
}
static Element(arg) {
if !arg || (arg is UIA.IUIAutomationElement) || (arg is ComValue) || (arg is Integer)
return arg
throw TypeError("Element argument requires parameter with type UIA.IUIAutomationElement, but received " Type(arg), -2)
}
static TreeScope(arg) {
if IsInteger(arg) {
if arg < 1 || arg > 31
throw ValueError("UIA.TreeScope does not contain constant `"" arg "`"", -2)
return arg is Integer ? arg : Integer(arg)
} else if arg is String {
try return UIA.TreeScope.%arg%
throw ValueError("UIA.TreeScope does not contain value for `"" arg "`"", -2)
}
throw TypeError("TreeScope requires parameter with type Integer or String, but received " Type(arg), -2)
}
static Type(arg) {
if IsInteger(arg) {
if arg < 50 && arg >= 0
return arg + 50000
if arg < 50000 || arg > 50050
throw ValueError("UIA.Type does not contain constant `"" arg "`"", -2)
return Integer(arg)
} else if arg is String {
try return UIA.Type.%arg%
try {
local match
if RegExMatch(arg, "\d{5}", &match:="") && Integer(match[]) >= 50000
return Integer(match[])
}
throw ValueError("UIA.Type does not contain value for `"" arg "`"", -2)
}
throw TypeError("UIA.Type requires parameter with type Integer or String, but received " Type(arg), -2)
}
static Property(arg) {
if IsInteger(arg) {
try UIA.Property[arg]
catch
throw ValueError("UIA.Property does not contain constant `"" arg "`"", -2)
return Integer(arg)
} else if arg is String {
try return UIA.Property.%RegexReplace(arg, "^(Cached|Current)",,,1)%
throw ValueError("UIA.Property does not contain value for `"" arg "`"", -2)
}
throw TypeError("Property requires parameter with type Integer or String, but received " Type(arg), -2)
}
static Pattern(arg) {
if IsInteger(arg) {
try UIA.Pattern[arg]
catch
throw ValueError("UIA.Pattern does not contain constant `"" arg "`"", -2)
return Integer(arg)
} else if arg is String {
try return UIA.Pattern.%StrReplace(arg, "Pattern")%
throw ValueError("UIA.Pattern does not contain value for `"" arg "`"", -2)
}
throw TypeError("Pattern requires parameter with type Integer or String, but received " Type(arg), -2)
}
static TreeTraversalOptions(arg) {
if IsInteger(arg) {
try UIA.TreeTraversalOptions[arg]
catch
throw ValueError("UIA.TreeTraversalOptions does not contain constant `"" arg "`"", -2)
return Integer(arg)
} else if arg is String {
try return UIA.TreeTraversalOptions.%arg%
try return UIA.TreeTraversalOptions.%arg "Order"%
throw ValueError("UIA.TreeTraversalOptions does not contain value for `"" arg "`"", -2)
}
throw TypeError("Invalid type provided for UIA.TreeTraversalOptions", -2, "Allowed types are Integer and String, but was provided type " Type(arg))
}
}
; The base class for IUIAutomation objects that return releasable pointers
class IUIAutomationBase {
__New(ptr) {
this.DefineProp("ptr", {Value:ptr})
if !ptr
throw ValueError('Invalid IUnknown interface pointer', -2, this.__Class)
}
__Delete() => this.Release()
__Item => (ObjAddRef(this.ptr), ComValue(0xd, this.ptr))
AddRef() => ObjAddRef(this.ptr)
Release() => this.ptr ? ObjRelease(this.ptr) : 0
__Get(Name, Params) {
if this.base.HasOwnProp(NewName := StrReplace(Name, "Current"))
return this.%NewName%
throw PropertyError("Property " Name " not found in " this.__Class " Class.",-2,Name)
}
__Call(Name, Params) {
if this.base.HasOwnProp(NewName := StrReplace(Name, "Current"))
return this.%NewName%(Params*)
throw MethodError("Method " Name " not found in " this.__Class " Class.",-2,Name)
}
}
/*
Exposes methods and properties for a UI Automation element, which represents a UI item.
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationelement
*/
class IUIAutomationElement extends UIA.IUIAutomationBase {
/**
* Enables array-like use of UIA elements to access child elements.
* If value is an integer then the nth corresponding child will be returned.
* A negative integer return the nth last child
* Eg. Element[2] ==> returns second child of Element
* Element[-1] ==> returns the last child of Element
* If value is a string, then it will be parsed either as an UIA path that was generated by
* UIAViewer, or an comma-separated path of integers/Types
* If value is an object, then it will be used in a FindElement call with scope set to Children.
* Eg. Element[{Type:"Button"}] will return the first child with Type Button.
* @returns {UIA.IUIAutomationElement}
*/
__Item[params*] {
get {
local el, _, param, i, arr, found, path, m
el := this
for _, param in params {
if IsObject(param) {
try el := el.FindElement(param, 2)
catch TargetError {
el := ""
} catch {
try el := el.FindCachedElement(param, 2)
catch
el := ""
}
} else if param is Integer {
try {
ComCall(6, el, "int", 2, "ptr", UIA.TrueCondition, "ptr*", &found := 0)
if found {
arr := UIA.IUIAutomationElementArray(found)
if (i := param < 0 ? arr.Length+param : param-1) <= arr.Length
el := arr.GetElement(i)
else
el := ""
}
} catch {
try {
arr := el.CachedChildren
el := arr[param < 0 ? arr.Length+param+1 : param]
} catch
el := ""
}
} else if param is String {
maybeEl := ""
for path in StrSplit(param, "|") {
try {
if InStr(path, ".") || InStr(path, ",") {
arr := StrSplit(StrReplace(path, ".", ","), ",")
for i, int in arr
arr[i] := IsInteger(int) ? Integer(int) : int
maybeEl := el[arr*]
} else if RegexMatch(path, "i)([a-zA-Z]+) *(\d+)?", &m:="") && UIA.Type.HasOwnProp(m[1]) {
try maybeEl := el.FindElement({Type:m[1], i:(m.Count > 1 ? m[2] : 1)}, 2)
catch TargetError
maybeEl := ""
catch
try maybeEl := el.FindCachedElement({Type:m[1], i:m[2]}, 2)
} else if !(path ~= ",\.+-")
maybeEl := el[UIA.DecodePath(path)*]
else
continue
break ; no errors encountered means that match was found
}
}
el := maybeEl
} else
throw TypeError("Invalid item type at index " _, -1)
if !el
throw IndexError("Invalid index/condition at index " _, -1)
}
return el
}
}
/**
* Enables enumeration of UIA elements, usually in a for loop.
* Usage:
* for [index, ] child in Element
*/
__Enum(varCount) {
local maxLen := this.Length, i := 0, children := this.GetChildren()
EnumElements(&element) {
if ++i > maxLen
return false
element := children[i]
return true
}
EnumIndexAndElements(&index, &element) {
if ++i > maxLen
return false
index := i
element := children[i]
return true
}
return (varCount = 1) ? EnumElements : EnumIndexAndElements
}
/**
* Getter for element properties and element supported pattern properties.
* This allows for syntax such as:
* Element.Name == Element.CurrentName
* Element.ValuePattern == Element.GetPattern("Value")
*/
__Get(Name, Params) {
local pName, pVal, NewName := StrReplace(Name, "Current",,,,1), err, tryName
if (SubStr(Name, 1, 6) = "Cached") {
if UIA.Property.HasOwnProp(PropName := SubStr(Name, 7))
return this.GetCachedPropertyValue(UIA.Property.%PropName%)
} else if this.base.HasOwnProp(NewName)
return this.%NewName%
else if UIA.Property.HasOwnProp(NewName)
return this.GetPropertyValue(UIA.Property.%NewName%)
else {
for pName, pVal in UIA.Pattern.OwnProps()
if IsInteger(pVal) && IsAlnum(pName) && UIA.HasProp("IUIAutomation" pName "Pattern") && (pName != "LegacyIAccessible") { ; Skip LegacyIAccessible to avoid name collisions (eg Select)
if tryName := UIA.IUIAutomation%pName%Pattern.Prototype.HasProp(NewName) ? NewName : UIA.IUIAutomation%pName%Pattern.Prototype.HasProp(Name) ? Name : "" {
try return this.%pName%Pattern.%tryName%
catch Any as err {
if this.Is%pName%PatternAvailable
throw %Type(err)%(err.Message, -1, err.Extra)
}
}
}
; Since LegacyIAccessible was skipped, then try LegacyIAccessible also
if (tryName := UIA.IUIAutomationLegacyIAccessiblePattern.Prototype.HasProp(NewName) ? NewName : UIA.IUIAutomationLegacyIAccessiblePattern.Prototype.HasProp(Name) ? Name : "") && this.IsLegacyIAccessiblePatternAvailable
return this.LegacyIAccessiblePattern.%tryName%
throw PropertyError("Property " Name " not found in " this.__Class " Class.",-1,Name)
}
}
; Setter for UIA element and pattern properties.
__Set(Name, Params, Value) {
local pVal, pName, NewName := StrReplace(Name, "Current",,,,1), tryName, err
if this.base.HasOwnProp(NewName)
return this.%NewName% := Value
for pName, pVal in UIA.Pattern.OwnProps()
if IsInteger(pVal) && IsAlnum(pName) && UIA.HasProp("IUIAutomation" pName "Pattern") && pName != "LegacyIAccessible" {
if tryName := UIA.IUIAutomation%pName%Pattern.Prototype.HasProp(NewName) ? NewName : UIA.IUIAutomation%pName%Pattern.Prototype.HasProp(Name) ? Name : "" {
try return this.%pName%Pattern.%tryName% := Value
catch Any as err {
if this.Is%pName%PatternAvailable
throw %Type(err)%(err.Message, -1, err.Extra)
}
}
}
; Since LegacyIAccessible was skipped, then try LegacyIAccessible also
if (tryName := UIA.IUIAutomationLegacyIAccessiblePattern.Prototype.HasProp(NewName) ? NewName : UIA.IUIAutomationLegacyIAccessiblePattern.Prototype.HasProp(Name) ? Name : "") && this.IsLegacyIAccessiblePatternAvailable
return this.LegacyIAccessiblePattern.%tryName% := Value
throw PropertyError("This class does not support adding properties")
}
/**
* Meta-function for calling methods from supperted patterns.
* This allows for syntax such as:
* Element.Invoke() == Element.GetPattern("Value").Invoke()
*/
__Call(Name, Params) {
local NewName, pName, pVal, tryName, err
if this.base.HasOwnProp(NewName := StrReplace(Name, "Current",,,,1))
return this.%NewName%(Params*)
for pName, pVal in UIA.Pattern.OwnProps()
if IsInteger(pVal) && IsAlpha(pName) && UIA.HasProp("IUIAutomation" pName "Pattern") && (pName != "LegacyIAccessible") {
if (tryName := UIA.IUIAutomation%pName%Pattern.Prototype.HasMethod(Name) ? Name : UIA.IUIAutomation%pName%Pattern.Prototype.HasMethod(NewName) ? NewName : "") {
try return this.%pName%Pattern.%tryName%(Params*)
catch Any as err {
if this.Is%pName%PatternAvailable
throw %Type(err)%(err.Message, -1, err.Extra)
}
}
}
if (tryName := UIA.IUIAutomationLegacyIAccessiblePattern.Prototype.HasMethod(Name) ? Name : UIA.IUIAutomationLegacyIAccessiblePattern.Prototype.HasMethod(NewName) ? NewName : "") && this.IsLegacyIAccessiblePatternAvailable
return this.LegacyIAccessiblePattern.%tryName%(Params*)
throw MethodError("Method " Name " not found in " this.__Class " Class.",-1,Name)
}
; Returns all direct children of the element
Children {
get {
local found
return (ComCall(6, this, "int", 2, "ptr", UIA.TrueCondition, "ptr*", &found := 0), found) ? UIA.IUIAutomationElementArray(found).ToArray() : []
}
}
; Returns direct children in reverse order (also the index in the enumerator counts downwards)
ReversedChildren {
get {
local found
return (ComCall(6, this, "int", 2, "ptr", UIA.TrueCondition, "ptr*", &found := 0), found) ? UIA.IUIAutomationElementArray(found).ToArray().DefineProp("__Enum", {call: (s, i) => (i = 1 ? (i := s.Length, (&v) => i > 0 ? (v := s[i], i--) : false) : (i := s.Length, (&k, &v) => (i > 0 ? (k := i, v := s[i], i--) : false)))}) : []
}
}
; Retrieves the cached child elements of this UI Automation element.
; The view of the returned collection is determined by the TreeFilter property of the IUIAutomationCacheRequest that was active when this element was obtained.
; Children are cached only if the scope of the cache request included TreeScope_Subtree, TreeScope_Children, or TreeScope_Descendants.
; If the cache request specified that children were to be cached at this level, but there are no children, the value of this property is 0. However, if no request was made to cache children at this level, an attempt to retrieve the property returns an error.
CachedChildren {
get {
local children
return (ComCall(19, this, "ptr*", &children := 0), children) ? UIA.IUIAutomationElementArray(children).ToArray() : []
}
}
ReversedCachedChildren {
get {
local children
return (ComCall(19, this, "ptr*", &children := 0), children) ? UIA.IUIAutomationElementArray(children).ToArray().DefineProp("__Enum", {call: (s, i) => (i = 1 ? (i := s.Length, (&v) => i > 0 ? (v := s[i], i--) : false) : (i := s.Length, (&k, &v) => (i > 0 ? (k := i, v := s[i], i--) : false)))}) : []
}
}
GetCachedChildren(scope:=2) {
local children
scope := UIA.TypeValidation.TreeScope(scope)
if this.HasOwnProp("CachedChildrenTreeScope" (UIA.TreeScope[scope & ~1])) {
if scope&1 {
local children := this.CachedChildrenTreeScope%UIA.TreeScope[scope]%.Clone()
children.Push(this)
return children
}
return this.CachedChildrenTreeScope%UIA.TreeScope[scope & ~1]%
}
if scope&4 {
children := []
AppendChildren(this)
} else if scope&2 {
children := this.CachedChildren
}
if scope&1
this.DefineProp("CachedChildrenTreeScope" UIA.TreeScope[scope], {value:children.Clone()}), children.Push(this)
else ; do not create circular reference
this.DefineProp("CachedChildrenTreeScope" UIA.TreeScope[scope], {value:children})
return children
AppendChildren(el) {
local subchildren := el.CachedChildren, child
for child in subchildren {
children.Push(child)
AppendChildren(child)
}
}
}
; Returns the parent of the element
Parent => UIA.TreeWalkerTrue.GetParentElement(this)
; Retrieves from the cache the parent of this UI Automation element.
CachedParent {
get {
local parent
if (ComCall(18, this, "ptr*", &parent := 0), parent)
return UIA.IUIAutomationElement(parent)
throw UnsetError("No element returned by " A_ThisFunc, -1)
}
}
; Returns the number of children of the element
Length => this.GetChildren().Length
/**
* Returns an object containing the location of the element
* @returns {Object} {x: screen x-coordinate, y: screen y-coordinate, w: width, h: height}
*/
Location => (br := this.BoundingRectangle, {x: br.l, y: br.t, w: br.r-br.l, h: br.b-br.t})
/**
* Returns an object containing the last cached location of the element
* @returns {Object} {x: screen x-coordinate, y: screen y-coordinate, w: width, h: height}
*/
CachedLocation => (br := this.CachedBoundingRectangle, {x: br.l, y: br.t, w: br.r-br.l, h: br.b-br.t})
; Gets or sets the current value of the element, if the ValuePattern is supported.
Value {
get {
try return this.ValuePattern.Value
try return this.RangeValuePattern.Value
try return this.LegacyIAccessiblePattern.Value
Throw Error("ValuePattern, RangeValuePattern or LegacyIAccessiblePattern not found!",,-1)
}
set {
try return this.ValuePattern.SetValue(value)
try return this.RangeValuePattern.SetValue(value)
try return this.LegacyIAccessiblePattern.SetValue(value)
Throw Error("Setting the value failed! Is ValuePattern, RangeValuePattern or LegacyIAccessiblePattern supported?",,-1)
}
}
CachedValue => this.GetCachedPropertyValue(UIA.Property.ValueValue)
; Checks whether this object still exists
Exists {
get {
try {
local br
if (br := this.BoundingRectangle) && (!(br.b - br.t) || !(br.r - br.l))
return 0
if this.IsOffscreen
return 0
} catch
return 0
return 1
}
}
; Aliases for UIA.GetPattern(UIA.Pattern.PatternName)
InvokePattern => (this.DefineProp("InvokePattern", {value:this.GetPattern(UIA.Pattern.Invoke)}), this.InvokePattern)
SelectionPattern {
get {
try return (this.DefineProp("SelectionPattern", {value:this.GetPattern(UIA.Pattern.Selection2)}), this.SelectionPattern)
return (this.DefineProp("SelectionPattern", {value:this.GetPattern(UIA.Pattern.Selection )}), this.SelectionPattern)
}
}
ValuePattern => (this.DefineProp("ValuePattern" , {value:this.GetPattern(UIA.Pattern.Value )}), this.ValuePattern)
RangeValuePattern => (this.DefineProp("RangeValuePattern" , {value:this.GetPattern(UIA.Pattern.RangeValue )}), this.RangeValuePattern)
ScrollPattern => (this.DefineProp("ScrollPattern" , {value:this.GetPattern(UIA.Pattern.Scroll )}), this.ScrollPattern)
ExpandCollapsePattern => (this.DefineProp("ExpandCollapsePattern", {value:this.GetPattern(UIA.Pattern.ExpandCollapse)}), this.ExpandCollapsePattern)
GridPattern => (this.DefineProp("GridPattern" , {value:this.GetPattern(UIA.Pattern.Grid )}), this.GridPattern)
GridItemPattern => (this.DefineProp("GridItemPattern" , {value:this.GetPattern(UIA.Pattern.GridItem )}), this.GridItemPattern)
MultipleViewPattern => (this.DefineProp("MultipleViewPattern" , {value:this.GetPattern(UIA.Pattern.MultipleView )}), this.MultipleViewPattern)
WindowPattern => (this.DefineProp("WindowPattern" , {value:this.GetPattern(UIA.Pattern.Window )}), this.WindowPattern)
SelectionItemPattern => (this.DefineProp("SelectionItemPattern" , {value:this.GetPattern(UIA.Pattern.SelectionItem )}), this.SelectionItemPattern)
DockPattern => (this.DefineProp("DockPattern" , {value:this.GetPattern(UIA.Pattern.Dock )}), this.DockPattern)
TablePattern => (this.DefineProp("TablePattern" , {value:this.GetPattern(UIA.Pattern.Table )}), this.TablePattern)
TableItemPattern => (this.DefineProp("TableItemPattern" , {value:this.GetPattern(UIA.Pattern.TableItem )}), this.TableItemPattern)
TextPattern {
get {
try return (this.DefineProp("TextPattern", {value:this.GetPattern(UIA.Pattern.Text2)}), this.TextPattern)
return (this.DefineProp("TextPattern", {value:this.GetPattern(UIA.Pattern.Text )}), this.TextPattern)
}
}
TogglePattern => (this.DefineProp("TogglePattern", {value:this.GetPattern(UIA.Pattern.Toggle)}), this.TogglePattern)
TransformPattern {
get {
try return (this.DefineProp("TransformPattern", {value:this.GetPattern(UIA.Pattern.Transform2)}), this.TransformPattern)
return (this.DefineProp("TransformPattern", {value:this.GetPattern(UIA.Pattern.Transform )}), this.TransformPattern)
}
}
ScrollItemPattern => (this.DefineProp("ScrollItemPattern" , {value:this.GetPattern(UIA.Pattern.ScrollItem )}), this.ScrollItemPattern)
LegacyIAccessiblePattern => (this.DefineProp("LegacyIAccessiblePattern" , {value:this.GetPattern(UIA.Pattern.LegacyIAccessible)}), this.LegacyIAccessiblePattern)
ItemContainerPattern => (this.DefineProp("ItemContainerPattern" , {value:this.GetPattern(UIA.Pattern.ItemContainer )}), this.ItemContainerPattern)
VirtualizedItemPattern => (this.DefineProp("VirtualizedItemPattern" , {value:this.GetPattern(UIA.Pattern.VirtualizedItem )}), this.VirtualizedItemPattern)
SynchronizedInputPattern => (this.DefineProp("SynchronizedInputPattern" , {value:this.GetPattern(UIA.Pattern.SynchronizedInput)}), this.SynchronizedInputPattern)
ObjectModelPattern => (this.DefineProp("ObjectModelPattern" , {value:this.GetPattern(UIA.Pattern.ObjectModel )}), this.ObjectModelPattern)
AnnotationPattern => (this.DefineProp("AnnotationPattern" , {value:this.GetPattern(UIA.Pattern.Annotation )}), this.AnnotationPattern)
StylesPattern => (this.DefineProp("StylesPattern" , {value:this.GetPattern(UIA.Pattern.Styles )}), this.StylesPattern)
SpreadsheetPattern => (this.DefineProp("SpreadsheetPattern" , {value:this.GetPattern(UIA.Pattern.Spreadsheet )}), this.SpreadsheetPattern)
SpreadsheetItemPattern => (this.DefineProp("SpreadsheetItemPattern" , {value:this.GetPattern(UIA.Pattern.SpreadsheetItem )}), this.SpreadsheetItemPattern)
TextChildPattern => (this.DefineProp("TextChildPattern" , {value:this.GetPattern(UIA.Pattern.TextChild )}), this.TextChildPattern)
DragPattern => (this.DefineProp("DragPattern" , {value:this.GetPattern(UIA.Pattern.Drag )}), this.DragPattern)
DropTargetPattern => (this.DefineProp("DropTargetPattern" , {value:this.GetPattern(UIA.Pattern.DropTarget )}), this.DropTargetPattern)
TextEditPattern => (this.DefineProp("TextEditPattern" , {value:this.GetPattern(UIA.Pattern.TextEdit )}), this.TextEditPattern)
CustomNavigationPattern => (this.DefineProp("CustomNavigationPattern" , {value:this.GetPattern(UIA.Pattern.CustomNavigation )}), this.CustomNavigationPattern)
; Aliases for UIA.GetCachedPattern(UIA.Pattern.PatternName)
CachedInvokePattern => (this.DefineProp("CachedInvokePattern" , {value:this.GetCachedPattern(UIA.Pattern.Invoke)}), this.CachedInvokePattern)
CachedSelectionPattern {
get {
try return (this.DefineProp("CachedSelectionPattern", {value:this.GetCachedPattern(UIA.Pattern.Selection2)}), this.CachedSelectionPattern)
return (this.DefineProp("CachedSelectionPattern", {value:this.GetCachedPattern(UIA.Pattern.Selection )}), this.CachedSelectionPattern)
}
}
CachedValuePattern => (this.DefineProp("CachedValuePattern" , {value:this.GetCachedPattern(UIA.Pattern.Value )}), this.CachedValuePattern)
CachedRangeValuePattern => (this.DefineProp("CachedRangeValuePattern" , {value:this.GetCachedPattern(UIA.Pattern.RangeValue )}), this.CachedRangeValuePattern)
CachedScrollPattern => (this.DefineProp("CachedScrollPattern" , {value:this.GetCachedPattern(UIA.Pattern.Scroll )}), this.CachedScrollPattern)
CachedExpandCollapsePattern => (this.DefineProp("CachedExpandCollapsePattern" , {value:this.GetCachedPattern(UIA.Pattern.ExpandCollapse)}), this.CachedExpandCollapsePattern)
CachedGridPattern => (this.DefineProp("CachedGridPattern" , {value:this.GetCachedPattern(UIA.Pattern.Grid )}), this.CachedGridPattern)
CachedGridItemPattern => (this.DefineProp("CachedGridItemPattern" , {value:this.GetCachedPattern(UIA.Pattern.GridItem )}), this.CachedGridItemPattern)
CachedMultipleViewPattern => (this.DefineProp("CachedMultipleViewPattern" , {value:this.GetCachedPattern(UIA.Pattern.MultipleView )}), this.CachedMultipleViewPattern)
CachedWindowPattern => (this.DefineProp("CachedWindowPattern" , {value:this.GetCachedPattern(UIA.Pattern.Window )}), this.CachedWindowPattern)
CachedSelectionItemPattern => (this.DefineProp("CachedSelectionItemPattern" , {value:this.GetCachedPattern(UIA.Pattern.SelectionItem )}), this.CachedSelectionItemPattern)
CachedDockPattern => (this.DefineProp("CachedDockPattern" , {value:this.GetCachedPattern(UIA.Pattern.Dock )}), this.CachedDockPattern)
CachedTablePattern => (this.DefineProp("CachedTablePattern" , {value:this.GetCachedPattern(UIA.Pattern.Table )}), this.CachedTablePattern)
CachedTableItemPattern => (this.DefineProp("CachedTableItemPattern" , {value:this.GetCachedPattern(UIA.Pattern.TableItem )}), this.CachedTableItemPattern)
CachedTextPattern {
get {
try return (this.DefineProp("CachedTextPattern", {value:this.GetCachedPattern(UIA.Pattern.Text2)}), this.CachedTextPattern)
return (this.DefineProp("CachedTextPattern", {value:this.GetCachedPattern(UIA.Pattern.Text )}), this.CachedTextPattern)
}
}
CachedTogglePattern => (this.DefineProp("CachedTogglePattern" , {value:this.GetCachedPattern(UIA.Pattern.Toggle)}), this.CachedTogglePattern)
CachedTransformPattern {
get {
try return (this.DefineProp("CachedTransformPattern", {value:this.GetCachedPattern(UIA.Pattern.Transform2)}), this.CachedTransformPattern)
return (this.DefineProp("CachedTransformPattern", {value:this.GetCachedPattern(UIA.Pattern.Transform )}), this.CachedTransformPattern)
}
}
CachedScrollItemPattern => (this.DefineProp("CachedScrollItemPattern" , {value:this.GetCachedPattern(UIA.Pattern.ScrollItem )}), this.CachedScrollItemPattern)
CachedLegacyIAccessiblePattern => (this.DefineProp("CachedLegacyIAccessiblePattern" , {value:this.GetCachedPattern(UIA.Pattern.LegacyIAccessible)}), this.CachedLegacyIAccessiblePattern)
CachedItemContainerPattern => (this.DefineProp("CachedItemContainerPattern" , {value:this.GetCachedPattern(UIA.Pattern.ItemContainer )}), this.CachedItemContainerPattern)
CachedVirtualizedItemPattern => (this.DefineProp("CachedVirtualizedItemPattern" , {value:this.GetCachedPattern(UIA.Pattern.VirtualizedItem )}), this.CachedVirtualizedItemPattern)
CachedSynchronizedInputPattern => (this.DefineProp("CachedSynchronizedInputPattern" , {value:this.GetCachedPattern(UIA.Pattern.SynchronizedInput)}), this.CachedSynchronizedInputPattern)
CachedObjectModelPattern => (this.DefineProp("CachedObjectModelPattern" , {value:this.GetCachedPattern(UIA.Pattern.ObjectModel )}), this.CachedObjectModelPattern)
CachedAnnotationPattern => (this.DefineProp("CachedAnnotationPattern" , {value:this.GetCachedPattern(UIA.Pattern.Annotation )}), this.CachedAnnotationPattern)
CachedStylesPattern => (this.DefineProp("CachedStylesPattern" , {value:this.GetCachedPattern(UIA.Pattern.Styles )}), this.CachedStylesPattern)
CachedSpreadsheetPattern => (this.DefineProp("CachedSpreadsheetPattern" , {value:this.GetCachedPattern(UIA.Pattern.Spreadsheet )}), this.CachedSpreadsheetPattern)
CachedSpreadsheetItemPattern => (this.DefineProp("CachedSpreadsheetItemPattern" , {value:this.GetCachedPattern(UIA.Pattern.SpreadsheetItem )}), this.CachedSpreadsheetItemPattern)
CachedTextChildPattern => (this.DefineProp("CachedTextChildPattern" , {value:this.GetCachedPattern(UIA.Pattern.TextChild )}), this.CachedTextChildPattern)
CachedDragPattern => (this.DefineProp("CachedDragPattern" , {value:this.GetCachedPattern(UIA.Pattern.Drag )}), this.CachedDragPattern)
CachedDropTargetPattern => (this.DefineProp("CachedDropTargetPattern" , {value:this.GetCachedPattern(UIA.Pattern.DropTarget )}), this.CachedDropTargetPattern)
CachedTextEditPattern => (this.DefineProp("CachedTextEditPattern" , {value:this.GetCachedPattern(UIA.Pattern.TextEdit )}), this.CachedTextEditPattern)
CachedCustomNavigationPattern => (this.DefineProp("CachedCustomNavigationPattern" , {value:this.GetCachedPattern(UIA.Pattern.CustomNavigation )}), this.CachedCustomNavigationPattern)
/**
* Returns the children of this element, optionally filtering by a condition
* @param c Optional UIA condition object. Default is TrueCondition.
* @param scope Optional TreeScope value: Element, Children, Family (Element+Children), Descendants, Subtree (=Element+Descendants). Default is Children.
* @returns {Array}
*/
GetChildren(c?, scope:=0x2) => this.FindAll(c ?? UIA.TrueCondition, scope)
; Get all child elements using TreeWalker. This is only for debugging purposes.
TWGetChildren() {
local arr := [], nextChild
if !IsObject(nextChild := UIA.TreeWalkerTrue.GetFirstChildElement(this))
return ""
arr.Push(nextChild)
while IsObject(nextChild := UIA.TreeWalkerTrue.GetNextSiblingElement(nextChild))
arr.Push(nextChild)
return arr
}
/**
* Returns info about the element: Type, Name, Value, LocalizedType, AutomationId, AcceleratorKey.
* @param scope Optional TreeScope value: Element, Children, Family (Element+Children), Descendants, Subtree (=Element+Descendants). Default is Descendants.
* @param delimiter Optional delimiter to separate the returned properties. Default is space.
* @param maxDepth Optional maximal depth of tree levels traversal. Default is unlimited.
* @returns {String}
*/
Dump(scope:=1, delimiter:=" ", maxDepth:=-1) {
local out := "", n, oChild, el
if !IsInteger(scope)
try scope := UIA.TreeScope.%scope%
; Create cache request, add all the necessary properties that Dump uses: Type, LocalizedType, AutomationId, Name, Value, ClassName, AcceleratorKey
; Don't even get the live element, because we don't need it. Gives a significant speed improvement.
static cacheRequest := UIA.CreateCacheRequest(["Type", "LocalizedType", "AutomationId", "Name", "Value", "ClassName", "AcceleratorKey"],,5,0)
; Speed-testing has shown that DumpAll with Current properties is about 1,5 to 4x slower than with Cached properties.
; Cached Dump with TreeScope.Element or TreeScope.Children is a bit slower than Current Dump.
; This means that we use Current properties if TreeScope is less than Descendants,
; and Cached properties if dumping Descendants. This gives the maximum performance.
if scope < 4 {
if scope&1 {
out := this.CurrentDump(delimiter) "`n"
}
if scope&2 {
for n, oChild in this.GetChildren()
out .= n ": " oChild.CurrentDump(delimiter) "`n"
}
} else {
; Build the cache for the set scope
try el := this.CachedChildren.Length
el := IsSet(el) && el ? this : this.FindFirstBuildCache(cacheRequest, UIA.RawViewCondition, scope)
if scope&1
out := el.CachedDump(delimiter) "`n"
if scope&2 {
for n, oChild in el.CachedChildren
out .= n ": " oChild.CachedDump(delimiter) "`n"
}
if scope&4
return RTrim(RecurseTree(el, out), "`n")
}
return RTrim(out, "`n")
RecurseTree(element, tree, path:="") {
local i, child, count
if maxDepth > 0 {
StrReplace(path, "," , , , &count)
if count >= (maxDepth-1)
return tree
}
For i, child in element.CachedChildren {
tree .= path (path?",":"") i ":" delimiter child.CachedDump(delimiter) "`n"
tree := RecurseTree(child, tree, path (path?",":"") i)
}
return tree
}
}
; Dumps with only "Current" properties
CurrentDump(delimiter:=" ") {
local ctrlType, name, val, lct, aid, cm, ak
return "Type: " (ctrlType := this.Type) " (" UIA.Type[ctrlType] ")" ((name := this.Name) == "" ? "" : delimiter "Name: `"" name "`"") ((val := this.Value) == "" ? "" : delimiter "Value: `"" val "`"") ((lct := this.LocalizedType) == "" ? "" : delimiter "LocalizedType: `"" lct "`"") ((aid := this.AutomationId) == "" ? "" : delimiter "AutomationId: `"" aid "`"") ((cm := this.ClassName) == "" ? "" : delimiter "ClassName: `"" cm "`"") ((ak := this.AcceleratorKey) == "" ? "" : delimiter "AcceleratorKey: `"" ak "`"")
}
; Dumps with only "Cached" properties
CachedDump(delimiter:=" ") {
local ctrlType, name, val, lct, aid, cm, ak
return "Type: " (ctrlType := this.CachedType) " (" UIA.Type[ctrlType] ")" ((name := this.CachedName) == "" ? "" : delimiter "Name: `"" name "`"") ((val := this.CachedValue) == "" ? "" : delimiter "Value: `"" val "`"") ((lct := this.CachedLocalizedType) == "" ? "" : delimiter "LocalizedType: `"" lct "`"") ((aid := this.CachedAutomationId) == "" ? "" : delimiter "AutomationId: `"" aid "`"") ((cm := this.CachedClassName) == "" ? "" : delimiter "ClassName: `"" cm "`"") ((ak := this.CachedAcceleratorKey) == "" ? "" : delimiter "AcceleratorKey: `"" ak "`"")
}
ToString() {
try return this.Dump()
return this.CachedDump()
}
/**
* Returns info about the element and its descendants: Type, Name, Value, LocalizedType, AutomationId, AcceleratorKey.
* @param maxDepth Optional maximal depth of tree levels traversal. Default is unlimited.
* @returns {String}
*/
DumpAll(delimiter:=" ", maxDepth:=-1) => this.Dump(5, delimiter, maxDepth)
/**
* Returns an UIA path leading to the target element.
* This path consists of Type and index information.
* @param targetEl The element the path will lead to from this element
* @param cached Whether this element contains a cached tree that should be used for the search.
* Since UIA path requires Type information, the Type should be cached in the tree.
* @returns {String}
*/
GetUIAPath(targetEl, cached := False) => UIA.EncodePath(this.GetTypeConditionPath(targetEl, cached))
/**
* Returns an array of conditions consisting of Type and index information, defining the path leading to the target element.
* @param targetEl The element the path will lead to from this element
* @param cached Whether this element contains a cached tree that should be used for the search.
* The cached tree must contain Type, Name, ClassName, AutomationId, and BoundingRectangle.
* @returns {Array}
*/
GetTypeConditionPath(targetEl, cached := False) {
local i, child, cachedThis, numPath, conditionPath, children, targetType, targetIndex, sameTypeCount, targetTypeIndex
cachedThis := cached ? this : this.BuildUpdatedCache(UIA.CreateCacheRequest(["Type", "Name", "ClassName", "AutomationId", "BoundingRectangle"],,5))
numPath := cachedThis.GetNumericPath(targetEl, true)
conditionPath := []
Loop numPath.Length {
children := cachedThis.CachedChildren, targetIndex := numPath[A_index], sameTypeCount := 0, targetTypeIndex := 0
targetType := children[targetIndex].CachedType
for i, child in children {
if child.CachedType == targetType
sameTypeCount++
if i == targetIndex
targetTypeIndex := sameTypeCount
}
if targetTypeIndex = 1
conditionPath.Push({Type:targetType})
else if targetTypeIndex = sameTypeCount
conditionPath.Push({Type:targetType, i:-1})
else
conditionPath.Push({Type:targetType, i:targetTypeIndex})
cachedThis := children[targetIndex]
}
return conditionPath
}
/**
* Returns an array of conditions consisting of a (hopefully) unique combination of Type, ClassName,
* AutomationId, Name, and index information, defining the path leading to the target element.
* @param targetEl The element the path will lead to from this element
* @param cached Whether this element contains a cached tree that should be used for the search.
* The cached tree must contain Type, Name, ClassName, AutomationId, and BoundingRectangle.
* @param ignoreNames If set to True then the Name property will not be used. This might make
* the path more reliable in certain circumstances where the Name property can change.
* @param asString Returns the path as a string rather than an array of objects.
* @returns {Array}
*/
GetConditionPath(targetEl, cached := False, ignoreNames := False, asString := False) {
local i, child, cachedThis, numPath, conditionPath, children, targetIndex, sameTypeCount, targetTypeIndex
cachedThis := cached ? this : this.BuildUpdatedCache(UIA.CreateCacheRequest(["Type", "Name", "ClassName", "AutomationId", "BoundingRectangle"],,5))
numPath := cachedThis.GetNumericPath(targetEl, true)
conditionPath := asString ? "" : []
Loop numPath.Length {
children := cachedThis.CachedChildren, targetIndex := numPath[A_index], sameTypeCount := 0, targetTypeIndex := 0
; Create compact condition map for the level
local levelMap := Map(), levelConditions := [], t := "", a := "", n := "", c := "", type, automationId, className, name
; First map all the children with the appropriate conditions to figure out whether to use index 1 or -1
for i, child in children {
type := child.CachedType, t := "{T:" (type-50000)
; levelMap will contain the max index of an element with certain Type, Type+AutomationId, Type+Name, and Type+ClassName
levelMap[t] := levelMap.Has(t) ? levelMap[t] + 1 : 1
try a := StrReplace(automationId := child.CachedAutomationId, "`"", "```"")
; Currently AutomationId will be paired with the Type, but perhaps this isn't necessary because AutomationId should be unique?
if a != "" && !IsInteger(a) ; Ignore Integer AutomationIds, since they seem to be auto-generated in Chromium apps
a := t ",A:`"" a "`"", levelMap[a] := levelMap.Has(a) ? levelMap[a] + 1 : 1 ; This actually shouldn't be needed, if AutomationId's are unique
try c := StrReplace(className := child.CachedClassName, "`"", "```"")
if c != ""
c := t ",CN:`"" c "`"", levelMap[c] := levelMap.Has(c) ? levelMap[c] + 1 : 1
; Consider Name last, because it can change (eg. window title)
try n := StrReplace(name := child.CachedName, "`"", "```"")
if !IgnoreNames && n != ""
n := t ",N:`"" n "`"", levelMap[n] := levelMap.Has(n) ? levelMap[n] + 1 : 1
if levelMap[t] = 1 ; If this is the first element with such a type then only use the type (not including AutomationId etc, to keep the resulting object shorter)
levelConditions.Push([{T:type-50000, i:levelMap[t]}, t])
else if a != "" && !IsInteger(a) {
levelConditions.Push(c != "" ? (levelMap[a] <= levelMap[c] ? [{A:automationId, i:levelMap[a]}, a] : [{CN: className, i:levelMap[c]}, c]) : [{A:automationId, i:levelMap[a]}, a])
} else if c != ""
levelConditions.Push([{CN: className, i:levelMap[c]}, c])
else if !IgnoreNames && n != "" && (levelMap[n] < levelMap[t])
levelConditions.Push([{N: name, i:levelMap[n]}, n])
else
levelConditions.Push([{T:type-50000, i:levelMap[t]}, t])
}
levelCondition := levelConditions[targetIndex]
if asString
conditionPath .= ((levelCondition[1].i = 1) ? levelCondition[2] : (levelCondition[1].i = levelMap[levelCondition[2]] ? (levelCondition[1].i := -1, levelCondition[2] ", i:-1") : (levelCondition[2] ", i:" levelCondition[1].i))) "}" (A_Index = numPath.Length ? "" : ", ")
else
conditionPath.Push((levelCondition[1].i = 1) ? (levelCondition[1].DeleteProp("i"), levelCondition[1]) : (levelCondition[1].i = levelMap[levelCondition[2]] ? (levelCondition[1].i := -1, levelCondition[1]) : levelCondition[1]))
cachedThis := children[targetIndex]
}
return conditionPath
}
/**
* Returns an array of integers defining the numeric path leading to the target element.
* @param targetEl The element the path will lead to from this element
* @param cached Whether this element contains a cached tree that should be used for the search.
* The cached tree must contain Type, Name, ClassName, AutomationId, and BoundingRectangle.
* @returns {Array}
*/
GetNumericPath(targetEl, cached := False) {
local cachedThis, found, cacheRequest
cachedThis := cached ? this : this.BuildUpdatedCache(cacheRequest := UIA.CreateCacheRequest(["Type", "Name", "ClassName", "AutomationId", "BoundingRectangle"],,5))
if found := FindTarget(cachedThis)
return found
throw TargetError("No matching target element found", -1)
FindTarget(el, path:=[]) {
local i, child
for i, child in el.CachedChildren {
path.Push(i)
if UIA.CompareElementsEx(child, targetEl)
return path
if found := FindTarget(child, path)
return found
path.Pop()
}
}
}
/**
* @param relativeTo CoordMode to be used: client, window or screen. Default is A_CoordModeMouse
* @param WinTitle Optional: may be used to specifically define the window that the element belongs to
* @returns {x:x coordinate, y:y coordinate, w:width, h:height}
*/
GetPos(relativeTo:="", WinTitle?) {
if IsSet(WinTitle) && !IsInteger(WinTitle)
WinTitle := WinExist(WinTitle)
local br := this.BoundingRectangle, pt
relativeTo := (relativeTo == "") ? A_CoordModeMouse : relativeTo
if (relativeTo = "screen")
return {x:br.l, y:br.t, w:(br.r-br.l), h:(br.b-br.t)}
else if (relativeTo = "window") {
DllCall("user32\GetWindowRect", "Int", WinTitle ?? this.WinId, "Ptr", RECT := Buffer(16))
return {x:(br.l-NumGet(RECT, 0, "Int")), y:(br.t-NumGet(RECT, 4, "Int")), w:br.r-br.l, h:br.b-br.t}
} else if (relativeTo = "client") {
pt := Buffer(8), NumPut("int",br.l,pt), NumPut("int", br.t,pt,4)
DllCall("ScreenToClient", "Int", WinTitle ?? this.WinId, "Ptr", pt)
return {x:NumGet(pt,0,"int"), y:NumGet(pt,4,"int"), w:br.r-br.l, h:br.b-br.t}
} else
throw Error(relativeTo "is not a valid CoordMode",-1)
}
; Gets the Id in string format (currently the RuntimeId). The exact implementation is subject to
; change in the future, so use of RuntimeId might be preferred. It can't be used for element searches!
Id => (this.DefineProp("Id", {value:this.RuntimeId}), this.Id)
; Gets the RuntimeId in string format
RuntimeId => (this.DefineProp("RuntimeId", {value:UIA.RuntimeIdToString(this.GetRuntimeId())}), this.RuntimeId)
; Get the parent window hwnd from the element
GetWinId() {
static cacheRequest := UIA.CreateCacheRequest(["NativeWindowHandle"],,1, UIA.AutomationElementMode.None), TW := UIA.CreateTreeWalker(UIA.CreateNotCondition(UIA.CreatePropertyCondition(UIA.Property.NativeWindowHandle, 0)))
try return DllCall("GetAncestor", "Ptr", TW.NormalizeElementBuildCache(cacheRequest, this).CachedNativeWindowHandle, "UInt", 2, "Ptr") ; hwnd from point by SKAN
}
WinId => (this.DefineProp("WinId", {value:this.GetWinId()}), this.WinId)
; Get the control hwnd (that the element belongs to) from the element
GetControlId() {
static cacheRequest := UIA.CreateCacheRequest(["NativeWindowHandle"],,1, UIA.AutomationElementMode.None), TW := UIA.CreateTreeWalker(UIA.CreateNotCondition(UIA.CreatePropertyCondition(UIA.Property.NativeWindowHandle, 0)))
try return TW.NormalizeElementBuildCache(cacheRequest, this).CachedNativeWindowHandle
}
ControlId => (this.DefineProp("ControlId", {value:this.GetControlId()}), this.ControlId)
/**
* Tries to click the element. The method depends on WhichButton variable: by default it is attempted
* to use any "click"-like methods, such as InvokePattern Invoke(), TogglePattern Toggle(), SelectionItemPattern Select().
* @param WhichButton
* * If WhichButton is left empty (default), then any "click"-like pattern methods
* will be used (Invoke(), Toggle(), Select() etc.
* * If WhichButton is a number, then Sleep will be called afterwards with that number of milliseconds.
* Eg. Element.Click(200) will sleep 200ms after "clicking".
* * If WhichButton is "left" or "right", then the AHK Click() will be used to move the cursor to
* the center of the element and perform a click.
* @param ClickCount Is used if WhichButton isn't a number or left empty, that is if AHK Click()
* will be used. In this case if ClickCount is a number <10, then that number of clicks will be performed.
* If ClickCount is >=10, then Sleep will be called with that number of ms. Both ClickCount and sleep time
* can be combined by separating with a space.
* Eg. Element.Click("left", 1000) will sleep 1000ms after clicking.
* Element.Click("left", 2) will double-click the element
* Element.Click("left", "2 1000") will double-click the element and then sleep for 1000ms
* @param DownOrUp If AHK Click is used, then this is the same as AHK Click DownOrUp parameter.
* @param Relative If Relative is "Rel" or "Relative" then X and Y coordinates are treated as offsets from the current mouse position.
* Otherwise it expects offset values for both X and Y (eg "-5 10" would offset X by -5 and Y by +10 from the center of the element).
* @param NoActivate If AHK Click is used, then this will determine whether the window is activated
* before clicking if the clickable point isn't visible on the screen. Default is activating.
* @param MoveBack If set then the cursor will be moved back to its original location after sleeping for
* the specified amount of ms. Specify 0 for no sleep.
*/
Click(WhichButton:="", ClickCount:=1, DownOrUp:="", Relative:="", NoActivate:=False, MoveBack?) {
local SleepTime, togglePattern, expandState, selectionPattern, rel, pos
if WhichButton = "" or IsInteger(WhichButton) {
; Caching the properties doesn't seem to make a speed difference, rather it might be slower with caching
; Using DoDefaultAction as default might end up slower (tested in Chrome - clicked much slower)
if (this.GetPropertyValue(UIA.Property.IsInvokePatternAvailable)) {
this.InvokePattern.Invoke()
if WhichButton != ""
Sleep WhichButton
return "Invoke"
}
if (this.GetPropertyValue(UIA.Property.IsTogglePatternAvailable)) {
togglePattern := this.TogglePattern, toggleState := togglePattern.CurrentToggleState
togglePattern.Toggle()
if (togglePattern.CurrentToggleState != toggleState) {
if WhichButton != ""
Sleep WhichButton
return "Toggle"
}
}
if (this.GetPropertyValue(UIA.Property.IsExpandCollapsePatternAvailable)) {
if ((expandState := (pattern := this.ExpandCollapsePattern).ExpandCollapseState) == 0) {
try pattern.Expand() ; Sometimes throws UIA_E_INVALIDOPERATION 0x80131509
action := "Expand"
} else {
try pattern.Collapse()
action := "Collapse"
}
if (pattern.ExpandCollapseState != expandState) {
if WhichButton != ""
Sleep WhichButton
return action
}
}
if (this.GetPropertyValue(UIA.Property.IsSelectionItemPatternAvailable)) {
selectionPattern := this.SelectionItemPattern, selectionState := selectionPattern.IsSelected
selectionPattern.Select()
if (selectionPattern.IsSelected != selectionState) {
if WhichButton != ""
Sleep WhichButton
return "Select"
}
}
if (this.GetPropertyValue(UIA.Property.IsLegacyIAccessiblePatternAvailable)) {
this.LegacyIAccessiblePattern.DoDefaultAction()
if WhichButton != ""
Sleep WhichButton
return "DoDefaultAction"
}
return 0
}
rel := [0,0], pos := this.Location
if (Relative && !InStr(Relative, "rel"))
rel := StrSplit(Relative, " "), Relative := ""
if IsInteger(WhichButton)
SleepTime := WhichButton, WhichButton := "left"
if !IsInteger(ClickCount) && InStr(ClickCount, " ") {
sCount := StrSplit(ClickCount, " ")
ClickCount := sCount[1], SleepTime := sCount[2]
} else if ClickCount > 9 {
SleepTime := ClickCount, ClickCount := 1
}
if (!NoActivate && (UIA.WindowFromPoint(pos.x+pos.w//2+rel[1], pos.y+pos.h//2+rel[2]) != (wId := this.WinId))) {
WinActivate(wId)
WinWaitActive(wId)
}
saveCoordMode := A_CoordModeMouse
CoordMode("Mouse", "Screen")
if IsSet(MoveBack)
MouseGetPos(&prevX, &prevY)
Click(pos.x+pos.w//2+rel[1] " " pos.y+pos.h//2+rel[2] " " WhichButton (ClickCount ? " " ClickCount : "") (DownOrUp ? " " DownOrUp : "") (Relative ? " " Relative : ""))
if IsSet(MoveBack) {
if MoveBack != 0
Sleep MoveBack
MouseMove(prevX, prevY)
}
CoordMode("Mouse", saveCoordMode)
if IsSet(SleepTime)
Sleep(SleepTime)
}
/**
* Uses ControlClick to click the element.
* @param WhichButton determines which button to use to click (left, right, middle).
* If WhichButton is a number, then a Sleep will be called afterwards.
* Eg. ControlClick(200) will sleep 200ms after clicking.
* @param ClickCount How many times to click. Default is 1.
* @param Options Additional ControlClick Options (see AHK documentations).
* @param WinTitle Optional: providing the WinTitle of the window the element belongs to might
* give speed improvements and sometimes be more reliable.
*/
ControlClick(WhichButton:="left", ClickCount:=1, Options:="", WinTitle?) {
local pos := this.GetPos("client", WinTitle?)
ControlClick("X" pos.x+pos.w//2 " Y" pos.y+pos.h//2, WinTitle ?? this.WinId,, IsInteger(WhichButton) ? "left" : WhichButton, ClickCount, Options)
if IsInteger(WhichButton)
Sleep(WhichButton)
}
/**
* Highlights the element for a chosen period of time.
* @param showTime Can be one of the following:
* * Unset - if highlighting exists then removes the highlighting, otherwise highlights for 2 seconds. This is the default value.
* * 0 - Indefinite highlighting
* * Positive integer (eg 2000) - will highlight and pause for the specified amount of time in ms
* * Negative integer - will highlight for the specified amount of time in ms, but script execution will continue
* * "clear" - removes the highlighting unconditionally
* @param color The color of the highlighting. Default is red.
* @param d The border thickness of the highlighting in pixels. Default is 2.
* @returns {UIA.IUIAutomationElement}
*/
Highlight(showTime:=unset, color:="Red", d:=2) {
local loc, x, y, w, h, key, prop
static Guis := Map()
if IsSet(showTime) && showTime = "clearall" {
for key, prop in Guis {
SetTimer(prop.TimerObj, 0)
try prop.GuiObj.Destroy()
}
Guis := Map()
return this
}
if (!IsSet(showTime) && Guis.Has(this.ptr)) || (IsSet(showTime) && showTime = "clear") {
if Guis.Has(this.ptr) {
SetTimer(Guis[this.ptr].TimerObj, 0)
try Guis[this.ptr].GuiObj.Destroy()
Guis.Delete(this.ptr)
}
return this
} else if !IsSet(showTime)
showTime := 2000
try loc := this.BoundingRectangle
if !IsSet(loc) || !IsObject(loc)
try loc := this.CachedBoundingRectangle
if !IsSet(loc) || !IsObject(loc)
return this
if !Guis.Has(this.ptr) {
Guis[this.ptr] := {}
Guis[this.ptr].GuiObj := Gui("+AlwaysOnTop -Caption +ToolWindow -DPIScale +E0x08000000")
Guis[this.ptr].TimerObj := ObjBindMethod(this, "Highlight", "clear")
}
GuiObj := Guis[this.ptr].GuiObj
GuiObj.BackColor := color
x:=loc.l, y:=loc.t, w:=(loc.r-loc.l), h:=(loc.b-loc.t), iw:= w+d, ih:= h+d, w:=w+d*2, h:=h+d*2, x:=x-d, y:=y-d
WinSetRegion("0-0 " w "-0 " w "-" h " 0-" h " 0-0 " d "-" d " " iw "-" d " " iw "-" ih " " d "-" ih " " d "-" d, GuiObj.Hwnd)
GuiObj.Show("NA x" . x . " y" . y . " w" . w . " h" . h)
if showTime > 0 {
Sleep(showTime)
this.Highlight()
} else if showTime < 0
SetTimer(Guis[this.ptr].TimerObj, -Abs(showTime))
return this
}
ClearHighlight() => this.Highlight("clear")
/**
* Waits for this element to not exist
* @param timeout Optional: Waiting time for element to disappear. Default: indefinite wait
* @param tick Optional: Wait time between each check. Default: 20ms
* @returns {Integer}
*/
WaitNotExist(timeOut := -1, tick := 20) {
local endtime := A_TickCount + timeout, exists
while ((exists := this.Exists) && ((timeout == -1) || (A_Tickcount < endtime)))
Sleep tick
return !exists
}
static __ExtractConditionNamedParameters(condition, &scope, &order, &startingElement, &cacheRequest?, &index?, &callback:=0) {
if Type(condition) != "Object" {
if IsObject(condition) && HasMethod(condition) {
callback := condition
return {}
}
return condition
}
pureCondition := condition.Clone()
if IsSet(index) {
index := pureCondition.DeleteProp("index") || pureCondition.DeleteProp("i") || index
if IsInteger(index) && !(index is Integer)
index := Integer(index)
}
scope := pureCondition.DeleteProp("scope") || scope
order := pureCondition.DeleteProp("order") || order
startingElement := pureCondition.DeleteProp("startingElement") || startingElement
if IsSet(cacheRequest)
cacheRequest := pureCondition.DeleteProp("cacheRequest") || cacheRequest
callback := pureCondition.DeleteProp("callback") || callback
return pureCondition
}
/**
* Checks whether an element that matches the specified condition exists within the provided TreeScope.
* If no element is found, then 0 is returned.
* @param condition The condition to filter with, or a callback function.
* The condition object additionally supports named parameters.
* See a more detailed explanation under FindElement condition argument.
* Default MatchMode is "Exact", and CaseSense "On".
* Note: MatchMode "StartsWith" and "RegEx" will have the performance of FindElements (slower).
* @param scope Optional TreeScope value: Element, Children, Family (Element+Children), Descendants, Subtree (=Element+Descendants). Default is Descendants.
* @param index Looks for the n-th element matching the condition
* @param order Optional: custom tree navigation order, one of UIA.TreeTraversalOptions values (LastToFirstOrder, PostOrder, LastToFirstPostOrder). Default is FirstToLast and PreOrder. [requires Windows 10 version 1703+]
* @param startingElement Optional: search will start from this element instead, which must be a child/descendant of the starting element [requires Windows 10 version 1703+]
* If startingElement is supplied then part of the tree will not be searched (depending on TreeTraversalOrder, either everything before this element, or everything after it will be ignored)
* @param cacheRequest Optional: cache request object
* @returns {UIA.IUIAutomationElement}
*/
ElementExist(condition, scope:=4, index:=1, order:=0, startingElement:=0, cacheRequest:=0) {
try return this.FindElement(condition, scope, index, order, startingElement, cacheRequest)
catch TargetError
return 0
return 0
}
/**
* Retrieves the first child or descendant element that matches the specified condition.
* If no element is found, then TargetError is thrown.
* @param condition The condition to filter with, or a callback function
*
* * A single property condition consists of an object where the key is the property name, and value is the property value: `{Name:"Test"}` => Name property must match "Test" exactly
* * Everything inside {} is an "and" condition: `{Type:"Button", Name:"Something"}` => Name must match "Something" AND Type must be Button
* * Everything inside [] is an "or" condition: `[{Name:"Test"}, {Name:"Something"}]` => Name must match "Test" OR Name must match "Something"
* * Object key "not" creates a not condition: `{not:{Type:"Button"}}` => everything except Type Button
*
* * MatchMode key (short form: mm) can be one of UIA.MatchMode values: "StartsWith", "SubString", "Exact", "RegEx". Default MatchMode is "Exact".
* MatchMode applies to all string-type conditions (except Type), multiple different MatchModes are allowed if used in separate sub-conditions.
* Note: MatchMode "StartsWith" and "RegEx" will have the performance of FindElements (slower).
* * CaseSense key (short form: cs) defines case-sense: "On"/True or "Off"/False. Default is "On".
*
* * The condition object additionally supports named parameters: {Type:"Button", index:-1} => last element with Type Button
*
* * If a callback function is provided instead, then it must accept three parameters: `callback(element, index, depth)`
* where `element` is the currently evaluated element, `index` is the step index in the current layer (with
* LastToFirst this still starts from 1), and `depth` is the current depth (0 = starting element).
* If the callback returns 1 then the element is matched, if 0 then is not matched and search continues,
* and if -1 then for PreOrder search the branch under the element is skipped and for PostOrder search
* the search jumps to the parent of the element skipping the siblings.
* In the case of a callback function the tree is walked using a TreeWalker, which is created with a
* UIA.TrueCondition if no other conditions are set. The treewalker can be created with a custom condition if
* the callback is instead provided as a named argument "callback".
* Eg. `Element.FindElement({callback:MyCallback, Type:"Button"})` walks a tree consisting of button-type elements.
* Example: `Element.FindElement((el, i, depth) => depth = 1 && el.Type != UIA.Type.Document ? -1 : el.Name = "Test")`
* This callback function searches only the branch with where at depth 1 the type is Document, and
* then searches for an element named "Test".
*
* @param scope Optional TreeScope value: Element, Children, Family (Element+Children), Descendants, Subtree (=Element+Descendants). Default is Descendants.
* @param index Looks for the n-th element matching the condition
* @param order Optional: custom tree navigation order, one of UIA.TreeTraversalOptions values (LastToFirstOrder, PostOrder, LastToFirstPostOrder). Default is FirstToLast and PreOrder. [requires Windows 10 version 1703+]
* @param startingElement Optional: search will start from this element instead, which must be a child/descendant of the starting element [requires Windows 10 version 1703+]
* If startingElement is supplied then part of the tree will not be searched (depending on TreeTraversalOrder, either everything before this element, or everything after it will be ignored)
* @param cacheRequest Optional: cache request object
* @returns {UIA.IUIAutomationElement}
*/
FindElement(condition, scope:=4, index:=1, order:=0, startingElement:=0, cacheRequest:=0) {
local withOptions := 0, found, cache, callback := 0
condition := UIA.IUIAutomationElement.__ExtractConditionNamedParameters(condition, &scope, &order, &startingElement, &cacheRequest, &index, &callback)
scope := UIA.TypeValidation.TreeScope(scope), index := UIA.TypeValidation.Integer(index, "Index"), order := UIA.TypeValidation.TreeTraversalOptions(order), startingElement := UIA.TypeValidation.Element(startingElement), cacheRequest := UIA.TypeValidation.CacheRequest(cacheRequest)
if index < 0 ; Convert negative index to LastToFirst order
index := -index, order := order | 2
withOptions := order || startingElement
if withOptions && !UIA.IsIUIAutomationElement7Available && (Type(condition) ~= "i)Condition|ComValue")
throw ValueError("If using order or startingElement arguments in Windows <10.0.15063, then condition cannot be IUIAutomationCondition", -1)
if !(Type(condition) ~= "i)Condition|ComValue") {
/*
If MatchMode is 1:
Use MatchMode 2, but then return all the results and filter using the condition
If MatchMode is RegEx:
Find all !"" elements, then filter using the condition
If either of these is encountered, nonUIAEncountered is set to 1.
If a CachedProperty is encountered, nonUIAEncountered is set to 2 and a cached search is used instead.
*/
IUIAcondition := UIA.__ConditionBuilder(condition, &nonUIAEncountered:=0), counter := 0
; In the case of a defined callback, walk the tree with a TreeWalker made on the base of
; IUIAcondition and validate with callback(element).
if callback {
local found, TW := UIA.CreateTreeWalker(IUIAcondition), c := 0
if startingElement
startingElement := startingElement.RuntimeId
; FirstToLast or LastToFirst
if order&2
nextElementFunc := UIA.IUIAutomationTreeWalker.Prototype.TryGetPreviousSiblingElement.Bind(TW),
nextChildFunc := UIA.IUIAutomationTreeWalker.Prototype.TryGetLastChildElement.Bind(TW)
else
nextElementFunc := UIA.IUIAutomationTreeWalker.Prototype.TryGetNextSiblingElement.Bind(TW),
nextChildFunc := UIA.IUIAutomationTreeWalker.Prototype.TryGetFirstChildElement.Bind(TW)
; First handle PostOrder
if order&1 {
if IsObject(found := PostOrderRecursiveFind(this, scope))
return cacheRequest ? found.BuildUpdatedCache(cacheRequest) : found
throw TargetError("An element matching the condition was not found", -1)
}
; PreOrder
if scope&1 && (c := callback(this, 1, 0)) > 0 && --index = 0
return cacheRequest ? this.BuildUpdatedCache(cacheRequest) : this
if c >= 0 && scope > 1 && found := PreOrderRecursiveFind(nextChildFunc(this))
return cacheRequest ? found.BuildUpdatedCache(cacheRequest) : found
throw TargetError("An element matching the condition was not found", -1)
}
if nonUIAEncountered = 1 { ; Some conditions need validating: MatchMode 1 or RegEx was used
; If no cacheRequest was specified, then speed-optimize the search by caching
; the required properties, and searching through cached elements.
; And although it looks like if adding an exception for a set startingElement
; and using FindAllWithOptions from startingElement should give a speed improvement,
; it actually doesn't affect the search speed significantly, probably because
; the cache search is just so much faster.
; It would be useful to use TreeFilter=IUIAcondition, but unfortunately it seems
; that TreeFilter is applied before TreeScope. This leads to the unwanted behavior
; of the tree being flattened, so this can't be used with scope=Children
cache := this.BuildUpdatedCache(UIA.CreateCacheRequest(condition,,scope,, scope>3 ? IUIAcondition : unset))
found := cache.FindCachedElement(condition, scope, index, order, startingElement)
return cacheRequest ? found.BuildUpdatedCache(cacheRequest) : found
} else if nonUIAEncountered = 2 ; A cached name was encountered, use FindCachedElement instead
return this.FindCachedElement(condition, scope, index, order, startingElement)
; If the user is running an older Windows, but is trying to use FindFirstWithOptions arguments
; then either use cached elements, or in the case of index 1 and PreOrder, use TreeWalker
if withOptions && (!UIA.IsIUIAutomationElement7Available || (scope < 4 && startingElement)) {
if index = 1 && order = 2 && !startingElement { ; Special case for index -1, PreOrder, and older Windows version
if scope & 1
try return cacheRequest ? this.FindFirstBuildCache(cacheRequest, IUIAcondition, 1) : this.FindFirst(IUIAcondition, 1)
if scope > 1
return cacheRequest ? UIA.CreateTreeWalker(IUIAcondition).GetLastChildElementBuildCache(cacheRequest, this) : UIA.CreateTreeWalker(IUIAcondition).GetLastChildElement(this)
else
throw TargetError("An element matching the condition was not found", -1)
}
found := this.BuildUpdatedCache(UIA.CreateCacheRequest(condition,,scope,,scope>3 ? IUIAcondition : unset)).FindCachedElement(condition, scope, index, order, startingElement)
return cacheRequest ? found.BuildUpdatedCache(cacheRequest) : found
}
condition := IUIAcondition
}
if !startingElement ; If FindFirstWithOptions is used but startingElement isn't set, start from this element.
startingElement := this
; Use FindAll instead if index > 1
if index != 1 {
try {
unfilteredEls := (cacheRequest ? (withOptions ? startingElement.FindAllWithOptionsBuildCache(cacheRequest, condition, order, this, scope)
: this.FindAllBuildCache(cacheRequest, condition, scope))
: (withOptions ? startingElement.FindAllWithOptions(condition, order, this, scope)
: this.FindAll(condition, scope)))
return unfilteredEls[order&2 && !withOptions ? unfilteredEls.Length + 1 - index : index]
} catch IndexError
throw TargetError("An element matching the condition was not found", -1, "FindAll index " index " was invalid")
}
if cacheRequest {
if withOptions
ComCall(112, startingElement, "int", scope, "ptr", condition, "ptr", cacheRequest, "int", order, "ptr", this, "ptr*", &found := 0) ; FindFirstWithOptionsBuildCache
else
ComCall(7, this, "int", scope, "ptr", condition, "ptr", cacheRequest, "ptr*", &found := 0) ; FindFirstBuildCache
} else {
if withOptions {
ComCall(110, startingElement, "int", scope, "ptr", condition, "int", order, "ptr", this, "ptr*", &found := 0) ; FindFirstWithOptions
} else {
ComCall(5, this, "int", scope, "ptr", condition, "ptr*", &found := 0) ; FindFirst
}
}
if found
return UIA.IUIAutomationElement(found)
throw TargetError("An element matching the condition was not found", -1)
PreOrderRecursiveFind(el, depth:=0) {
local found
depth++
while (c := 0, IsObject(el)) {
if (startingElement ? (startingElement = el.RuntimeId ? !(startingElement := "") && (scope & 1) : 0) : 1) && (c := callback(el, A_Index, depth)) > 0 && --index = 0
return el
else if c >= 0 && scope&4 && IsObject(found := PreOrderRecursiveFind(nextChildFunc(el), depth))
return found
el := nextElementFunc(el)
}
}
PostOrderRecursiveFind(el, scope, i:=1, depth:=0) { ; this is only called if scope >= 4, and handles scope&2 as well
local found, child, c := 0
child := nextChildFunc(el), depth++
if scope > 1 {
while (IsObject(child)) {
if IsObject(found := PostOrderRecursiveFind(child, (scope & ~2)|1, A_Index, depth))
return found
else if found = -1
break
child := nextElementFunc(child)
}
}
if scope&1 && (startingElement ? (startingElement = el.RuntimeId ? !(startingElement := "") && (scope & 1) : 0) : 1) && (c := callback(el, i, depth)) > 0 && --index = 0
return el
return c
}
}
/**
* CachedElementExist can be used to find an element inside a cached tree, using only cached properties.
* This is not a UIA native method: make sure the cached tree is reasonably small, otherwise the performance will suffer.
* If no element is found, then 0 is returned.
* @param condition The condition to filter with.
* The condition object additionally supports named parameters.
* Default MatchMode is "Exact", and CaseSense "On".
* See a more detailed explanation under FindElement condition argument.
* @param scope Optional TreeScope value: Element, Children, Family (Element+Children), Descendants, Subtree (=Element+Descendants). Default is Descendants.
* @param index Looks for the n-th element matching the condition
* @param order Optional: custom tree navigation order, one of UIA.TreeTraversalOptions values (LastToFirstOrder, PostOrder, LastToFirstPostOrder). Default is FirstToLast and PreOrder.
* @param startingElement Optional: search will start from this element instead, which must be a child/descendant of the starting element
* If startingElement is supplied then part of the tree will not be searched (depending on TreeTraversalOrder, either everything before this element, or everything after it will be ignored)
* Unlike FindElement, using this will most likely not have a beneficial effect on performance.
* @returns {UIA.IUIAutomationElement}
*/
CachedElementExist(condition, scope:=4, index:=1, order:=0, startingElement:=0) {
try return this.FindCachedElement(condition, scope, index, order, startingElement)
catch TargetError
return 0
return 0
}
/**
* FindCachedElement can be used to find an element inside a cached tree, using only cached properties.
* This is not a UIA native method: make sure the cached tree is reasonably small, otherwise the performance will suffer.
* If no element is found, then a TargetError is thrown.
* @param condition The condition to filter with, or a callback function.
* The condition object additionally supports named parameters.
* Default MatchMode is "Exact", and CaseSense "On".
* See a more detailed explanation under FindElement condition argument.
*
* There is a difference only if a callback function is used. With a cached search a treewalker is
* not used (instead CachedChildren is accessed), and the `index` argument in the callback function
* will receive the actual index of the element relative to the parent, even if order = LastToFirst.
* @param scope Optional TreeScope value: Element, Children, Family (Element+Children), Descendants, Subtree (=Element+Descendants). Default is Descendants.
* @param index Looks for the n-th element matching the condition
* @param order Optional: custom tree navigation order, one of UIA.TreeTraversalOptions values (LastToFirstOrder, PostOrder, LastToFirstPostOrder). Default is FirstToLast and PreOrder.
* @param startingElement Optional: search will start from this element instead, which must be a child/descendant of the starting element
* If startingElement is supplied then part of the tree will not be searched (depending on TreeTraversalOrder, either everything before this element, or everything after it will be ignored)
* Unlike FindElement, using this will most likely not have a beneficial effect on performance.
* @returns {UIA.IUIAutomationElement}
*/
FindCachedElement(condition, scope:=4, index:=1, order:=0, startingElement:=0) {
local callback := 0, found, c := 0
condition := UIA.IUIAutomationElement.__ExtractConditionNamedParameters(condition, &scope, &order, &startingElement, , &index, &callback)
callback := callback || UIA.IUIAutomationElement.Prototype.ValidateCondition.Bind(unset, condition, true), scope := UIA.TypeValidation.TreeScope(scope), index := UIA.TypeValidation.Integer(index, "Index"), order := UIA.TypeValidation.TreeTraversalOptions(order), startingElement := UIA.TypeValidation.Element(startingElement)
if index < 0
order |= 2, index := -index
else if index = 0
throw ValueError("Condition index cannot be 0", -1)
if startingElement
startingElement := startingElement.RuntimeId
ChildOrder := order&2 ? "ReversedCachedChildren" : "CachedChildren"
; First handle PostOrder
if order&1 {
if found := PostOrderRecursiveFind(this, scope)
return found
throw TargetError("An element matching the condition was not found", -1)
}
; PreOrder
if scope&1 && (c := callback(this, 1, 0)) > 0 && --index = 0
return this
if scope > 1 && c >= 0 {
if found := PreOrderRecursiveFind(this)
return found
}
throw TargetError("An element matching the condition was not found", -1)
PreOrderRecursiveFind(el, depth:=0) {
local child, found, c, i
depth++
for i, child in el.%ChildOrder% {
c := 0
if (startingElement ? (startingElement = child.RuntimeId ? !(startingElement := "") && (scope & 1) : 0) : 1) && (c := callback(child, i, depth)) > 0 && --index = 0
return child
else if (c >= 0) && scope&4 && (found := PreOrderRecursiveFind(child, depth))
return found
}
}
PostOrderRecursiveFind(el, scope, i:=1, depth:=-1) {
local child, found, c := 0, j
depth++
for j, child in el.%ChildOrder% {
if IsObject(found := PostOrderRecursiveFind(child, (scope & ~2)|1, j, depth))
return found
else if found = -1
break
}
if scope&1 && (startingElement ? (startingElement = el.RuntimeId ? !(startingElement := "") && (scope & 1) : 0) : 1) && (c := callback(el, i, depth)) > 0 && --index = 0
return el
return c
}
}
/**
* Returns all UI Automation elements that satisfy the specified condition.
* @param condition The condition to filter with, or a callback function.
* The condition object additionally supports named parameters.
* Default MatchMode is "Exact", and CaseSense "On".
* See a more detailed explanation under FindElement condition argument.
* @param scope Optional TreeScope value: Element, Children, Family (Element+Children), Descendants, Subtree (=Element+Descendants). Default is Descendants.
* @param order Optional: custom tree navigation order, one of UIA.TreeTraversalOptions values (LastToFirstOrder, PostOrder, LastToFirstPostOrder). Default is FirstToLast and PreOrder. [requires Windows 10 version 1703+]
* @param startingElement Optional: element with which to begin the search [requires Windows 10 version 1703+]
* @param cacheRequest Optional: cache request object
* @returns {[UIA.IUIAutomationElement]}
*/
FindElements(condition, scope := 4, order:=0, startingElement:=0, cacheRequest:=0) {
local withOptions, found, cache, callback := 0
condition := UIA.IUIAutomationElement.__ExtractConditionNamedParameters(condition, &scope, &order, &startingElement, &cacheRequest,, &callback)
scope := UIA.TypeValidation.TreeScope(scope), order := UIA.TypeValidation.TreeTraversalOptions(order), startingElement := UIA.TypeValidation.Element(startingElement), cacheRequest := UIA.TypeValidation.CacheRequest(cacheRequest)
withOptions := order || startingElement
if withOptions && !UIA.IsIUIAutomationElement7Available && (Type(condition) ~= "i)Condition|ComValue")
throw ValueError("If using order or startingElement arguments in Windows <10.0.15063, then condition cannot be IUIAutomationCondition", -1)
if !(Type(condition) ~= "i)Condition|ComValue") {
IUIAcondition := UIA.__ConditionBuilder(condition, &nonUIAEncountered:=0), unfilteredEls := [], filteredEls := []
if callback {
local foundElements := [], TW := UIA.CreateTreeWalker(IUIAcondition), c := 0
if startingElement
startingElement := startingElement.RuntimeId
; FirstToLast or LastToFirst
if order&2
nextElementFunc := UIA.IUIAutomationTreeWalker.Prototype.TryGetPreviousSiblingElement.Bind(TW),
nextChildFunc := UIA.IUIAutomationTreeWalker.Prototype.TryGetLastChildElement.Bind(TW)
else
nextElementFunc := UIA.IUIAutomationTreeWalker.Prototype.TryGetNextSiblingElement.Bind(TW),
nextChildFunc := UIA.IUIAutomationTreeWalker.Prototype.TryGetFirstChildElement.Bind(TW)
; First handle PostOrder
if order&1
return (PostOrderRecursiveFind(this, scope), foundElements)
; PreOrder
if scope&1 && (c := callback(this)) > 0
foundElements.Push(cacheRequest ? this.BuildUpdatedCache(cacheRequest) : this)
if scope > 1 && c >= 0
PreOrderRecursiveFind(nextChildFunc(this))
return foundElements
}
if nonUIAEncountered = 2 ; A cached name was encountered, use FindCachedElements instead
return this.FindCachedElements(condition, scope, order, startingElement)
else if nonUIAEncountered = 1 || (withOptions && (!UIA.IsIUIAutomationElement7Available || (scope < 4 && startingElement))) {
cache := this.BuildUpdatedCache(UIA.CreateCacheRequest(condition,,scope,,scope>3 ? IUIAcondition : unset))
found := cache.FindCachedElements(condition, scope, order, startingElement)
if cacheRequest {
Loop found.Length
found[A_Index] := found[A_Index].BuildUpdatedCache(cacheRequest)
}
return found
}
unfilteredCondition := condition, condition := IUIAcondition
}
if !startingElement ; If FindFirstWithOptions is used but startingElement isn't set, start from this element.
startingElement := this
if cacheRequest {
if withOptions
ComCall(113, startingElement, "int", scope, "ptr", condition, "ptr", cacheRequest, "int", order, "ptr", this, "ptr*", &found := 0) ; FindAllWithOptionsBuildCache
else
ComCall(8, this, "int", scope, "ptr", condition, "ptr", cacheRequest, "ptr*", &found := 0) ; FindAllBuildCache
} else {
if withOptions
ComCall(111, startingElement, "int", scope, "ptr", condition, "int", order, "ptr", this, "ptr*", &found := 0) ; FindAllWithOptions
else
ComCall(6, this, "int", scope, "ptr", condition, "ptr*", &found := 0) ; FindAll
}
return found ? UIA.IUIAutomationElementArray(found).ToArray() : []
PreOrderRecursiveFind(el, depth:=0) {
++depth
while (c := 0, IsObject(el)) {
if (startingElement ? (startingElement = el.RuntimeId ? !(startingElement := "") && (scope & 1) : 0) : 1) && (c := callback(el, A_Index, depth)) > 0
foundElements.Push(cacheRequest ? el.BuildUpdatedCache(cacheRequest) : el)
if scope&4 && c >= 0
PreOrderRecursiveFind(nextChildFunc(el), depth)
el := nextElementFunc(el)
}
}
PostOrderRecursiveFind(el, scope, i:=1, depth:=-1) { ; this is only called if scope >= 4, and handles scope&2 as well
local child := nextChildFunc(el), c := 0
++depth
if scope > 1 {
while (IsObject(child)) {
if PostOrderRecursiveFind(child, (scope & ~2)|1, A_Index, depth) = -1
break
child := nextElementFunc(child)
}
}
if (startingElement ? (startingElement = el.RuntimeId ? !(startingElement := "") && (scope & 1) : 0) : 1) && (c := callback(el)) > 0
foundElements.Push(cacheRequest ? el.BuildUpdatedCache(cacheRequest) : el)
return c
}
}
/**
* Returns all UI Automation elements that satisfy the specified condition inside a cached tree, checking only cached properties.
* This is not a UIA native method: make sure the cached tree is reasonably small, otherwise the performance will suffer.
* @param condition The condition to filter with, or a callback function.
* The condition object additionally supports named parameters.
* Default MatchMode is "Exact", and CaseSense "On".
* See a more detailed explanation under FindElement condition argument.
* @param scope Optional TreeScope value: Element, Children, Family (Element+Children), Descendants, Subtree (=Element+Descendants). Default is Descendants.
* @param order Optional: custom tree navigation order, one of UIA.TreeTraversalOptions values (LastToFirstOrder, PostOrder, LastToFirstPostOrder). Default is FirstToLast and PreOrder.
* @param startingElement Optional: element with which to begin the search
* Unlike FindElements, using this will not give a performance benefit.
* @returns {[UIA.IUIAutomationElement]}
*/
FindCachedElements(condition, scope:=4, order:=0, startingElement:=0) {
local callback := 0, foundElements := [], c := 0
condition := UIA.IUIAutomationElement.__ExtractConditionNamedParameters(condition, &scope, &order, &startingElement,,, &callback)
callback := callback || UIA.IUIAutomationElement.Prototype.ValidateCondition.Bind(unset, condition, true), scope := UIA.TypeValidation.TreeScope(scope), order := UIA.TypeValidation.TreeTraversalOptions(order), startingElement := UIA.TypeValidation.Element(startingElement)
if startingElement
startingElement := startingElement.RuntimeId
ChildOrder := order&2 ? "ReversedCachedChildren" : "CachedChildren"
; First handle PostOrder
if order&1
return (PostOrderRecursiveFind(this, scope), foundElements)
; PreOrder
if scope&1 && (c := callback(this, 1, 0)) > 0
foundElements.Push(this)
if scope > 1 && c >= 0
return (PreOrderRecursiveFind(this), foundElements)
return foundElements
PreOrderRecursiveFind(el, depth:=0) {
local child, c, i
depth++
for i, child in el.%ChildOrder% {
c := 0
if (startingElement ? (startingElement = child.RuntimeId ? !(startingElement := "") && (scope & 1) : 0) : 1) && (c := callback(child, i, depth)) > 0
foundElements.Push(child)
if c >= 0 && scope&4
PreOrderRecursiveFind(child, depth)
}
}
PostOrderRecursiveFind(el, scope, i:=1, depth:=-1) {
local child, c := 0, j
depth++
if scope > 1 {
for j, child in el.%ChildOrder% {
if PostOrderRecursiveFind(child, (scope & ~2)|1, j, depth) = -1
break
}
}
if scope&1 && (startingElement ? (startingElement = el.RuntimeId ? !(startingElement := "") && (scope & 1) : 0) : 1) && (c := callback(el, i, depth)) > 0
foundElements.Push(el)
return c
}
}
/**
* Wait element to exist.
* @param condition The condition to filter with.
* The condition object additionally supports named parameters.
* See a more detailed explanation under FindElement condition argument.
* @param timeOut Waiting time for element to appear in ms. Default: indefinite wait
* @param scope Optional TreeScope value: Element, Children, Family (Element+Children), Descendants, Subtree (=Element+Descendants). Default is Descendants.
* @param index Looks for the n-th element matching the condition
* @param order Optional: custom tree navigation order, one of UIA.TreeTraversalOptions values (LastToFirstOrder, PostOrder, LastToFirstPostOrder) [requires Windows 10 version 1703+]
* @param startingElement Optional: element with which to begin the search [requires Windows 10 version 1703+]
* @param cacheRequest Optional: cache request object
* @param tick Optional: sleep time between checks for the element. Default is 20ms
* @returns {UIA.IUIAutomationElement} Found element if successful, 0 if timeout happens
*/
WaitElement(condition, timeOut := -1, scope := 4, index := 1, order := 0, startingElement := 0, cacheRequest := 0, tick := 20) {
local endtime
if Type(condition) = "Object" {
condition := condition.Clone()
timeOut := (condition.DeleteProp("timeOut") || timeOut), tick := (condition.DeleteProp("tick") || tick)
}
timeOut := UIA.TypeValidation.Integer(timeOut, "TimeOut"), tick := UIA.TypeValidation.Integer(tick, "Tick")
endtime := A_TickCount + timeOut
While ((timeOut == -1) || (A_Tickcount < endtime)) {
try return this.FindElement(condition, scope, index, order, startingElement, cacheRequest)
Sleep tick
}
return 0
}
/**
* Wait element to not exist (disappear).
* @param condition The condition to filter with.
* The condition object additionally supports named parameters.
* See a more detailed explanation under FindElement condition argument.
* @param timeout Waiting time for element to disappear. Default: indefinite wait
* @param scope Optional TreeScope value: Element, Children, Family (Element+Children), Descendants, Subtree (=Element+Descendants). Default is Descendants.
* @param order Optional: custom tree navigation order, one of UIA.TreeTraversalOptions values (LastToFirstOrder, PostOrder, LastToFirstPostOrder) [requires Windows 10 version 1703+]
* @param startingElement Optional: element with which to begin the search [requires Windows 10 version 1703+]
* @param cacheRequest Optional: cache request object
* @param tick Optional: sleep time between checks for the element. Default is 20ms
* @returns 1 if element disappeared, 0 otherwise
*/
WaitElementNotExist(condition, timeout := -1, scope := 4, index := 1, order := 0, startingElement := 0, cacheRequest := 0, tick := 20) {
local endtime
if Type(condition) = "Object" {
condition := condition.Clone()
timeOut := (condition.DeleteProp("timeOut") || timeOut), tick := (condition.DeleteProp("tick") || tick)
}
timeOut := UIA.TypeValidation.Integer(timeOut, "TimeOut"), tick := UIA.TypeValidation.Integer(tick, "Tick")
endtime := A_TickCount + timeout
While (timeout == -1) || (A_Tickcount < endtime) {
try this.FindElement(condition, scope, index, order, startingElement, cacheRequest)
catch
return 1
Sleep tick
}
return 0
}
/**
* Tries to get an element from a path. If no element is found, an IndexError is thrown.
* `ElementFromPath(path1[, path2, ...])`
*
* Paths can be:
* 1. Comma-separated numeric path that defines which path to travel down the tree. In addition
* to integer values, or TypeN which selects the nth occurrence of Type.
* Eg. `Element.ElementFromPath("3,2")` => selects Elements third childs second child
* `Element.ElementFromPath("Button3,2")` => selects Elements third child of type Button, then its second child
*
* 2. UIA path copied from UIAViewer.
* Eg. `Element.ElementFromPath("bAx3")`
*
* 3. A condition or conditions. In this case the provided conditions define the route of tree-traversal, by default with Scope Children.
* Eg. `Element.ElementFromPath({Type:"Button"}, {Type:"List"})` => finds the first Button type child of Element, then the first List type child of that element
*
* @returns {UIA.IUIAutomationElement}
*/
ElementFromPath(paths*) {
local err
try return this[paths*]
catch IndexError as err
throw IndexError(StrReplace(err.Message, "at index", "at path index"), -1, err.Extra)
}
/**
* Tries to get a cached element from a path. If no element is found, an IndexError is thrown.
* This method uses only cached elements and cached properties to perform the search.
* `CachedElementFromPath(path1[, path2, ...])`
*
* Paths can be:
* 1. Comma-separated numeric path that defines which path to travel down the tree. In addition
* to integer values, or TypeN which selects the nth occurrence of Type.
* Eg. `Element.CachedElementFromPath("3,2")` => selects Elements third childs second child
* `Element.CachedElementFromPath("Button3,2")` => selects Elements third child of type Button, then its second child
*
* 2. UIA path copied from UIAViewer.
* Eg. `Element.CachedElementFromPath("bAx3")`
*
* 3. A condition or conditions. In this case the provided conditions define the route of tree-traversal, by default with Scope Children.
* Eg. `Element.CachedElementFromPath({Type:"Button"}, {Type:"List"})` => finds the first Button type child of Element, then the first List type child of that element
*
* @returns {UIA.IUIAutomationElement}
*/
CachedElementFromPath(paths*) {
local el := this, _, path, subpath, arr, m
for _, path in paths {
if IsObject(path) {
try el := el.FindCachedElement(path, 2)
catch
el := ""
} else if IsInteger(path) {
try {
arr := el.CachedChildren
el := arr[path < 0 ? arr.Length+path+1 : path]
} catch
el := ""
} else if path is String {
maybeEl := ""
for subpath in StrSplit(path, "|") {
try {
if InStr(subpath, ".") || InStr(subpath, ",")
maybeEl := el.CachedElementFromPath(StrSplit(StrReplace(subpath, ".", ","), ",")*)
else if RegexMatch(subpath, "i)([a-zA-Z]+) *(\d+)?", &m:="") && UIA.Type.HasOwnProp(m[1]) {
try maybeEl := el.FindCachedElement({Type:m[1], i:m[2]}, 2)
} else if !(subpath ~= ",\.+-")
maybeEl := el.CachedElementFromPath(UIA.DecodePath(subpath)*)
else
continue
break ; no errors encountered means that match was found
}
}
el := maybeEl
} else
throw TypeError("Invalid item type at index " _, -1)
if !el
throw IndexError("Invalid index/condition at index " _, -1)
}
return el
}
/**
* Checks whether an element exists at a path and returns the element if one is found.
* If no element is found, 0 is returned.
* `ElementFromPathExist(path1[, path2, ...])`
*
* Paths can be:
* 1. Comma-separated numeric path that defines which path to travel down the tree. In addition
* to integer values, or TypeN which selects the nth occurrence of Type.
* Eg. `Element.ElementFromPathExist("3,2")` => checks for Elements third childs second child
* `Element.ElementFromPathExist("Button3,2")` => checks for Elements third child of type Button, then its second child
*
* 2. UIA path copied from UIAViewer.
* Eg. `Element.ElementFromPathExist("bAx3")`
*
* 3. A condition or conditions. In this case the provided conditions define the route of tree-traversal, by default with Scope Children.
* Eg. `Element.ElementFromPathExist({Type:"Button"}, {Type:"List"})` => checks for the first Button type child of Element, then the first List type child of that element
*
* @returns {UIA.IUIAutomationElement}
*/
ElementFromPathExist(paths*) {
try return this[paths*]
catch IndexError
return 0
return 0
}
/**
* Checks whether a cached element exists at a path and returns the cached element if one is found.
* This method uses only cached elements and cached properties to perform the search.
* If no element is found, 0 is returned.
*
* @param paths Either an UIA path, numeric path, or condition path.
* See longer explanation under CachedElementFromPath
*
* @returns {UIA.IUIAutomationElement}
*/
CachedElementFromPathExist(paths*) {
try return this.CachedElementFromPath(paths*)
catch IndexError
return 0
return 0
}
/**
* Wait element to appear at a path. The last argument may optionally be a timeout in milliseconds (default is indefinite wait).
* `WaitElementFromPath(path1[, path2, ..., timeout])`
*
* Paths can be:
* 1. Comma-separated numeric path that defines which path to travel down the tree. In addition
* to integer values, or TypeN which selects the nth occurrence of Type.
* Eg. `Element.WaitElementFromPath("3,2", 2000)` => waits for Elements third childs second child, timeout 2 seconds
* `Element.WaitElementFromPath("Button3,2")` => waits for Elements third child of type Button, then its second child
*
* 2. UIA path copied from UIAViewer.
* Eg. `Element.WaitElementFromPath("bAx3")`
*
* 3. A condition or conditions. In this case the provided conditions define the route of tree-traversal, by default with Scope Children.
* Eg. `Element.WaitElementFromPath({Type:"Button"}, {Type:"List"})` => waits for the first Button type child of Element, then the first List type child of that element
*
* @returns {UIA.IUIAutomationElement}
*/
WaitElementFromPath(paths*) {
local timeOut := -1, endtime, tick := 20
if paths.Length > 1 && paths[paths.Length] is Integer {
paths := paths.Clone()
if paths[-2] is Integer
tick := paths.Pop()
timeOut := paths.Pop()
}
endtime := A_TickCount + timeOut
While ((timeOut == -1) || (A_Tickcount < endtime)) {
try return this[paths*]
Sleep tick
}
}
/**
* Traverses the tree purely using a TreeWalker that is created with an optional filter-condition (default is TrueCondition)
* @param searchPath This is a comma-separated path that defines the route of tree traversal:
* * n: gets the nth child (using GetFirstChildElement and GetNextSiblingElement)
* * +n: gets the nth next sibling
* * -n: gets the nth previous sibling
* * pn: gets the nth parent
* * "n": normalizes the element (returns the first parent or the element itself matching the filterCondition)
* @param filterCondition Optional: a condition for tree traversal that selects only elements that match the condition.
* @example Element.WalkTree("p,+2,1") ; gets the parent of Element, then the second sibling of the parent, then that siblings first child.
* @returns {UIA.IUIAutomationElement}
*/
WalkTree(searchPath, filterCondition?) {
local PathTW, el, loopFunc, m, err
PathTW := IsSet(filterCondition) ? UIA.CreateTreeWalker(filterCondition) : UIA.TreeWalkerTrue
el := this, searchPath := StrReplace(StrReplace(String(searchPath), " "), ".", ",")
Loop Parse searchPath, "," {
try {
if IsDigit(A_LoopField) {
loopFunc := "GetFirstChildElement", el := PathTW.GetFirstChildElement(el)
if A_LoopField > 1
el := el.WalkTree("+" A_LoopField-1)
} else if A_LoopField = "n" {
loopFunc := "NormalizeElement", el := PathTW.NormalizeElement(el)
} else if RegexMatch(A_LoopField, "i)([p+-]+) *(\d+)?", &m:="") {
if (loopFunc := (m[1] = "p") ? "GetParentElement" : (m[1] = "+") ? "GetNextSiblingElement" : (m[1] = "-") ? "GetPreviousSiblingElement" : "") {
Loop m[2] || 1 {
el := PathTW.%loopFunc%(el)
}
} else
throw ValueError()
} else
throw ValueError()
} catch TargetError, IndexError {
throw IndexError("Step " A_index " with value " A_LoopField " was out of bounds (" loopFunc " failed)", -1)
} catch ValueError {
throw ValueError("Invalid path value " A_LoopField " at step " A_index, -1)
} catch OSError as err {
throw ValueError("Step " A_index " with value " A_LoopField " caused COM error: " err.Message, -1, "Make sure the element is valid and not cached (use WalkCachedTree for cached elements).")
} catch Any as err
throw
}
return el
}
/**
* Traverses the cached tree, optionally filtering by filterCondition
* @param searchPath This is a comma-separated path that defines the route of tree traversal:
* * n: gets the nth child (using GetFirstChildElement and GetNextSiblingElement)
* * +n: gets the nth next sibling
* * -n: gets the nth previous sibling
* * pn: gets the nth parent
* * "n": normalizes the element (returns the first parent or the element itself matching the filterCondition)
* @param filterCondition Optional: a condition for tree traversal that selects only elements that match the condition.
* @example Element.WalkCachedTree("p,+2,1") ; gets the parent of Element, then the second sibling of the parent, then that siblings first child.
* @returns {UIA.IUIAutomationElement}
*/
WalkCachedTree(searchPath, filterCondition?) {
local el, m, parent, children, child, err, steps
el := this, searchPath := StrReplace(StrReplace(String(searchPath), " "), ".", ",")
Loop Parse searchPath, "," {
try {
if IsDigit(A_LoopField) {
el := el.CachedChildren[A_LoopField]
} else if A_LoopField = "n" {
if !IsSet(filterCondition)
throw Error("Normalizing an element requires a filterCondition", -1)
if !this.ValidateCondition(filterCondition, true) {
if !(parent := el.CachedParent)
throw TargetError()
el := parent.WalkCachedTree("n", filterCondition)
}
} else if RegexMatch(A_LoopField, "i)([p+-]+) *(\d+)?", &m:="") {
if (m[1] = "p") {
counter := 0, steps := m[2] || 1
Loop {
if !(el := el.CachedParent)
throw TargetError()
if IsSet(filterCondition) && !el.ValidateCondition(filterCondition, true)
continue
if ++counter = steps
break
}
} else if (m[1] = "+") || (m[1] = "-") {
parent := el.CachedParent, children := parent.CachedChildren
if !parent
throw TargetError()
if IsSet(filterCondition) {
startingIndex := GetIndex(parent), counter := 0, steps := Integer(m[2] || 1)
Loop (m[1] = "+") ? children.Length - startingIndex : startingIndex - 1 {
child := children[startingIndex + ((m[1] = "+") ? A_index : -A_index)]
if child.ValidateCondition(filterCondition, true) && ++counter = steps {
el := child
break
}
RecurseTree(child)
if counter = steps
break
}
if counter != steps
el := ""
} else
el := parent[GetIndex(parent) + ((m[1] = "+") ? (m[2] || 1) : -(m[2] || 1))]
} else
throw ValueError()
}
} catch TargetError, IndexError {
throw IndexError("Step " A_index " with value " A_LoopField " was out of bounds", -1)
} catch ValueError {
throw ValueError("Invalid path value " A_LoopField " at step " A_index, -1)
} catch OSError as err {
throw ValueError("Step " A_index " with value " A_LoopField " caused COM error: " err.Message, -1, "Either CachedParent or CachedChildren failed: make sure the target and the targets parent are cached.")
} catch Any as err
throw
if !el
throw IndexError("No element found after step " A_index " with value " A_LoopField, -1)
}
return el
GetIndex(parent) {
local elId, i, child
elId := el.RuntimeId
for i, child in parent.CachedChildren {
if child.RuntimeId = elId
return i
}
}
RecurseTree(parent) {
local children := parent.CachedChildren, child
if (m[1] = "+") {
for child in children {
if child.ValidateCondition(filterCondition, true) && ++counter = steps
return el := child
if RecurseTree(child)
return
}
} else {
Loop children.Length {
child := children[children.Length-A_Index+1]
if child.ValidateCondition(filterCondition, true) && ++counter = steps
return el := child
if RecurseTree(child)
return
}
}
}
}
; Gets all property values of this element and returns an object where Object.PropertyName = PropertyValue
; Use only for debugging purposes, since this will be quite slow.
GetAllPropertyValues() {
local infos := {}, k, v, arr, t
for k, v in UIA.Property.OwnProps() {
if k = "__CachedValues"
continue
v := this.GetPropertyValue(v)
if (v is ComObjArray) {
arr := []
for t in v
arr.Push(t)
v := arr
}
infos.%k% := v
}
return infos
}
; Internal method: checks whether this element matches the condition
ValidateCondition(cond, cached:=False, i?, depth?) {
local mm, cs, notCond := 0, k, v, result, val
if !IsObject(cond)
throw ValueError("Condition of type " Type(cond) " is an invalid ValidateCondition condition", -1, "The condition can be a plain object, array or a method")
if HasMethod(cond)
return cond(this, i?, depth?)
if Type(cond) = "Object" {
mm := cond.HasOwnProp("matchmode") ? cond.matchmode : cond.HasOwnProp("mm") ? cond.mm : unset
cs := cond.HasOwnProp("casesense") ? cond.casesense : cond.HasOwnProp("cs") ? cond.cs : unset
if !IsInteger(mm ?? 0)
mm := UIA.MatchMode.%mm%
if !IsInteger(cs ?? 0)
cs := UIA.CaseSense.%cs%
notCond := cond.HasOwnProp("operator") ? cond.operator = "not" : cond.HasOwnProp("op") ? cond.op = "not" : 0
cond := cond.OwnProps()
} else if cond is Array {
for k, v in cond {
if IsObject(v) && this.ValidateCondition(v, cached, i?, depth?)
return true
}
return false
} else
throw ValueError("Condition of type " Type(cond) " is an invalid ValidateCondition condition", -1, "The condition can be a plain object, array or a method")
for k, v in cond {
try k := UIA.TypeValidation.Property(k)
if !(IsInteger(k) && k >= 10000) {
if IsObject(v) {
if (k = "not" ? this.ValidateCondition(v, cached, i?, depth?) : !this.ValidateCondition(v, cached, i?, depth?))
return False
}
continue
}
if k = 30003
v := UIA.TypeValidation.Type(v)
try currentValue := this.Get%cached ? "Cached" : ""%PropertyValue(k)
catch { ; If caching is used, should this throw an error to notify the user of a missing cache property?
result := 0
} else {
switch UIA.PropertyVariantType[k] {
case 8:
if v is Array {
for val in v {
if (result := CompareStrings(currentValue, val, mm?, cs?))
break
}
} else
result := CompareStrings(currentValue, v, mm?, cs?)
case 3,5,11:
if v is Array {
for val in v {
if k = 30003
val := UIA.TypeValidation.Type(val)
if (result := currentValue == val)
break
}
} else
result := currentValue == v
default:
if Type(v) = "Object"
v := v.OwnProps(), currentValue := currentValue is Array ? currentValue : currentValue.OwnProps()
if not v is Array {
if k = 30000 {
local v := StrSplit(v, ".")
for t in v
v[A_Index] := Integer("0x" t)
} else
throw ValueError("Invalid PropertyId " k, -1)
}
if result := currentValue.Length == v.Length {
for i, val in v {
try {
if currentValue[i] == val
continue
}
result := 0
break
}
}
}
}
if notCond ? result : !result
return False
}
return True
CompareStrings(str1, str2, matchmode:=3, casesense:=-1) {
if not str1 is String
str1 := String(str1)
if not str2 is String
str2 := String(str2)
if matchmode = 3
return (casesense ? str1 == str2 : str1 = str2)
else if matchmode = 2
return InStr(str1, str2, !!casesense)
if matchmode = 1
return ((casesense && SubStr(str1, 1, StrLen(str2)) == str2) || (!casesense && SubStr(str1, 1, StrLen(str2)) = str2))
else if matchmode = "RegEx" {
if casesense = -1
return RegExMatch(str1, str2)
return RegExMatch(str1, (!casesense && !RegExMatch(str2, "^([^(\\]+)\)")) ? "i)" str2 : str2)
} else
throw Error("Invalid MatchMode", -1, matchmode)
}
}
; Sets the keyboard focus to this UI Automation element.
SetFocus() => ComCall(3, this)
; Retrieves the unique identifier assigned to the UI element.
; The identifier is only guaranteed to be unique to the UI of the desktop on which it was generated. Identifiers can be reused over time.
; The format of run-time identifiers might change in the future. The returned identifier should be treated as an opaque value and used only for comparison; for example, to determine whether a Microsoft UI Automation element is in the cache.
GetRuntimeId() {
local runtimeId
return (ComCall(4, this, "ptr*", &runtimeId := 0), UIA.SafeArrayToAHKArray(runtimeId))
}
/**
* Retrieves the first child or descendant element that matches the specified condition.
* The scope of the search is relative to the element on which the method is called. Elements are returned in the order in which they are encountered in the tree.
* This function cannot search for ancestor elements in the UIA tree; that is, UIA.TreeScope.Ancestors is not a valid value for the scope parameter.
* When searching for top-level windows on the desktop, be sure to specify UIA.TreeScope.Children in the scope parameter, not UIA.TreeScope.Descendants. A search through the entire subtree of the desktop could iterate through thousands of items and lead to a stack overflow.
* @param condition The condition to filter with. MatchModes StartsWith, RegEx, and using indexes are not supported with FindFirst, use FindElement for that.
* @param scope Optional TreeScope value: Element, Children, Family (Element+Children), Descendants, Subtree (=Element+Descendants). Default is Descendants.
* @returns {UIA.IUIAutomationElement}
*/
FindFirst(condition := UIA.TrueCondition, scope:=4) {
local found
scope := UIA.TypeValidation.TreeScope(scope)
if !(Type(condition) ~= "i)Condition|ComValue")
condition := UIA.__CreateRawCondition(condition)
if (ComCall(5, this, "int", scope, "ptr", condition ?? UIA.TrueCondition, "ptr*", &found := 0), found)
return UIA.IUIAutomationElement(found)
throw TargetError("An element matching the condition was not found", -1)
}
/**
* Returns all UI Automation elements that satisfy the specified condition.
* The scope of the search is relative to the element on which the method is called. Elements are returned in the order in which they are encountered in the tree.
* This function cannot search for ancestor elements in the UIA tree; that is, UIA.TreeScope.Ancestors is not a valid value for the scope parameter.
* When searching for top-level windows on the desktop, be sure to specify UIA.TreeScope.Children in the scope parameter, not UIA.TreeScope.Descendants. A search through the entire subtree of the desktop could iterate through thousands of items and lead to a stack overflow.
* @param condition The condition to filter with.
* @param scope Optional TreeScope value: Element, Children, Family (Element+Children), Descendants, Subtree (=Element+Descendants). Default is Descendants.
* @returns {[UIA.IUIAutomationElement]}
*/
FindAll(condition := UIA.TrueCondition, scope := 4) {
local found
if !IsObject(condition)
throw TypeError("Condition must be an condition object or array", -1)
if !(Type(condition) ~= "i)Condition|ComValue")
condition := UIA.__CreateRawCondition(condition)
return (ComCall(6, this, "int", UIA.TypeValidation.TreeScope(scope), "ptr", condition, "ptr*", &found := 0), found) ? UIA.IUIAutomationElementArray(found).ToArray() : []
}
; Retrieves the first child or descendant element that matches the specified condition, prefetches the requested properties and control patterns, and stores the prefetched items in the cache.
FindFirstBuildCache(cacheRequest, condition := UIA.TrueCondition, scope := 4) {
local found
if !(Type(condition) ~= "i)Condition|ComValue")
condition := UIA.__CreateRawCondition(condition)
if (ComCall(7, this, "int", UIA.TypeValidation.TreeScope(scope), "ptr", condition, "ptr", UIA.TypeValidation.CacheRequest(cacheRequest), "ptr*", &found := 0), found)
return UIA.IUIAutomationElement(found)
throw TargetError("An element matching the condition was not found", -1)
}
; Returns all UI Automation elements that satisfy the specified condition, prefetches the requested properties and control patterns, and stores the prefetched items in the cache.
FindAllBuildCache(cacheRequest, condition := UIA.TrueCondition, scope := 4) {
local found
if !(Type(condition) ~= "i)Condition|ComValue")
condition := UIA.__CreateRawCondition(condition)
return (ComCall(8, this, "int", UIA.TypeValidation.TreeScope(scope), "ptr", condition, "ptr", UIA.TypeValidation.CacheRequest(cacheRequest), "ptr*", &found := 0), found) ? UIA.IUIAutomationElementArray(found).ToArray() : []
}
; Retrieves a UI Automation element with an updated cache.
; The original UI Automation element is unchanged. The UIA.IUIAutomationElement interface refers to the same element and has the same runtime identifier.
BuildUpdatedCache(cacheRequest) {
local updatedElement
return (ComCall(9, this, "ptr", UIA.TypeValidation.CacheRequest(cacheRequest), "ptr*", &updatedElement := 0), UIA.IUIAutomationElement(updatedElement))
}
; Microsoft UI Automation properties of the double type support Not a Number (NaN) values. When retrieving a property of the double type, a client can use the _isnan function to determine whether the property is a NaN value.
; Retrieves the current value of a property for this UI Automation element.
; This gets called when Element.Property is used
GetPropertyValue(propertyId) {
local val
if !IsNumber(propertyId) {
if UIA.Property.HasOwnProp(propertyId)
propertyId := UIA.Property.%propertyId%
else
throw ValueError("Invalid propertyId.", -1, IsObject(propertyId) ? "PropertyId must be a string or an integer, but " Type(propertyId) " was provided" : propertyId)
}
ComCall(10, this, "int", propertyId, "ptr", val := UIA.ComVar())
return val[] is ComObjArray ? UIA.SafeArrayToAHKArray(val[]) : val[]
}
; Retrieves a property value for this UI Automation element, optionally ignoring any default value.
; Passing FALSE in the ignoreDefaultValue parameter is equivalent to calling UIA.IUIAutomationElement.GetPropertyValue.
; If the Microsoft UI Automation provider for the element itself supports the property, the value of the property is returned. Otherwise, if ignoreDefaultValue is FALSE, a default value specified by UI Automation is returned.
; This method returns a failure code if the requested property was not previously cached.
GetPropertyValueEx(propertyId, ignoreDefaultValue) {
local val
ComCall(11, this, "int", UIA.TypeValidation.Property(propertyId), "int", ignoreDefaultValue, "ptr", val := UIA.ComVar())
return val[] is ComObjArray ? UIA.SafeArrayToAHKArray(val[]) : val[]
}
; Retrieves a property value from the cache for this UI Automation element.
; This is called when Element.CachedProperty is used (eg Element.CachedName)
GetCachedPropertyValue(propertyId) {
local val
ComCall(12, this, "int", UIA.TypeValidation.Property(propertyId), "ptr", val := UIA.ComVar())
return val[] is ComObjArray ? UIA.SafeArrayToAHKArray(val[]) : val[]
}
; Retrieves a property value from the cache for this UI Automation element, optionally ignoring any default value.
GetCachedPropertyValueEx(propertyId, ignoreDefaultValue, retVal) {
local val
ComCall(13, this, "int", UIA.TypeValidation.Property(propertyId), "int", ignoreDefaultValue, "ptr", val := UIA.ComVar())
return val[] is ComObjArray ? UIA.SafeArrayToAHKArray(val[]) : val[]
}
; Retrieves the control pattern interface of the specified pattern on this UI Automation element.
; For riid specify a GUID string, that is the IID for the desired pattern
; GetPatternAs doesn't have a use in this library, use GetPattern instead
GetPatternAs(patternId, riid) {
local name, GUID
try {
if IsInteger(patternId)
name := UIA.Pattern[patternId]
else
patternId := UIA.Pattern.%(name := patternId)%
} catch
Throw ValueError("Failed to find pattern `"" name "`" among UIA.Pattern properties/values", -1)
DllCall("ole32\CLSIDFromString", "wstr", riid, "ptr", GUID:=Buffer(16))
ComCall(14, this, "int", patternId, "ptr", GUID, "ptr*", &patternObject := 0)
return UIA.IUIAutomation%name%Pattern(patternObject)
}
; Retrieves the control pattern interface of the specified pattern from the cache of this UI Automation element.
; GetCachedPatternAs doesn't have a use in this library, use GetCachedPattern instead
GetCachedPatternAs(patternId, riid) { ; not completed
local name, GUID, patternObject
try {
if IsInteger(patternId)
name := UIA.Pattern[patternId]
else
patternId := UIA.Pattern.%(name := patternId)%
} catch
Throw ValueError("Failed to find pattern `"" name "`" among UIA.Pattern properties/values", -1)
DllCall("ole32\CLSIDFromString", "wstr", riid, "ptr", GUID:=Buffer(16))
ComCall(15, this, "int", patternId, "ptr", GUID, "ptr*", &patternObject := 0)
return UIA.IUIAutomation%name%Pattern(patternObject)
}
; Retrieves the IUnknown interface of the specified control pattern on this UI Automation element.
; This method gets the specified control pattern based on its availability at the time of the call.
; For some forms of UI, this method will incur cross-process performance overhead. Applications can reduce overhead by caching control patterns and then retrieving them by using UIA.IUIAutomationElement,,GetCachedPattern.
GetPattern(patternId) {
local name, patternObject
try {
if IsInteger(patternId)
name := UIA.Pattern[patternId]
else
patternId := UIA.Pattern.%(name := StrReplace(patternId, "Pattern"))%
} catch
Throw ValueError("Failed to find pattern `"" name "`" among UIA.Pattern properties/values", -1)
ComCall(16, this, "int", patternId, "ptr*", &patternObject := 0)
return UIA.IUIAutomation%RegExReplace(name, "\d+$")%Pattern(patternObject)
}
; Retrieves from the cache the IUnknown interface of the specified control pattern of this UI Automation element.
GetCachedPattern(patternId) {
local name, patternObject
try {
if IsInteger(patternId)
name := UIA.Pattern[patternId]
else
patternId := UIA.Pattern.%(name := StrReplace(patternId, "Pattern"))%
} catch
Throw ValueError("Failed to find pattern `"" name "`" among UIA.Pattern properties/values", -1)
ComCall(17, this, "int", patternId, "ptr*", &patternObject := 0)
return UIA.IUIAutomation%RegExReplace(name, "\d+$")%Pattern(patternObject)
}
; Retrieves the identifier of the process that hosts the element.
ProcessId {
get {
local retVal
return (ComCall(20, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the control type of the element.
; Control types describe a known interaction model for UI Automation elements without relying on a localized control type or combination of complex logic rules. This property cannot change at run time unless the control supports the IUIAutomationMultipleViewPattern interface. An example is the Win32 ListView control, which can change from a data grid to a list, depending on the current view.
Type {
get {
local retVal
return (ComCall(21, this, "int*", &retVal := 0), retVal)
}
}
ControlType => this.Type
; Retrieves a localized description of the control type of the element.
LocalizedType {
get {
local retVal
return (ComCall(22, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
LocalizedControlType => this.LocalizedType
; Retrieves the name of the element.
Name {
get {
local retVal
return (ComCall(23, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
; Retrieves the accelerator key for the element.
AcceleratorKey {
get {
local retVal
return (ComCall(24, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
; Retrieves the access key character for the element.
; An access key is a character in the text of a menu, menu item, or label of a control such as a button that activates the attached menu function. For example, the letter "O" is often used to invoke the Open file common dialog box from a File menu. Microsoft UI Automation elements that have the access key property set always implement the Invoke control pattern.
AccessKey {
get {
local retVal
return (ComCall(25, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
; Indicates whether the element has keyboard focus.
HasKeyboardFocus {
get {
local retVal
return (ComCall(26, this, "int*", &retVal := 0), retVal)
}
}
; Indicates whether the element can accept keyboard focus.
IsKeyboardFocusable {
get {
local retVal
return (ComCall(27, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves a cached value that indicates whether the element is enabled.
IsEnabled {
get {
local retVal
return (ComCall(28, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the Microsoft UI Automation identifier of the element.
; The identifier is unique among sibling elements in a container, and is the same in all instances of the application.
AutomationId {
get {
local retVal
return (ComCall(29, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
; Retrieves the class name of the element.
; The value of this property is implementation-defined. The property is useful in testing environments.
ClassName {
get {
local retVal
return (ComCall(30, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
; Retrieves the help text for the element. This information is typically obtained from tooltips.
; Caution Do not retrieve the CachedHelpText property from a control that is based on the SysListview32 class. Doing so could cause the system to become unstable and data to be lost. A client application can discover whether a control is based on SysListview32 by retrieving the CachedClassName or ClassName property from the control.
HelpText {
get {
local retVal
return (ComCall(31, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
; Retrieves the culture identifier for the element.
Culture {
get {
local retVal
return (ComCall(32, this, "int*", &retVal := 0), retVal)
}
}
; Indicates whether the element is a control element.
IsControlElement {
get {
local retVal
return (ComCall(33, this, "int*", &retVal := 0), retVal)
}
}
; Indicates whether the element is a content element.
; A content element contains data that is presented to the user. Examples of content elements are the items in a list box or a button in a dialog box. Non-content elements, also called peripheral elements, are typically used to manipulate the content in a composite control; for example, the button on a drop-down control.
IsContentElement {
get {
local retVal
return (ComCall(34, this, "int*", &retVal := 0), retVal)
}
}
; Indicates whether the element contains a disguised password.
; This property enables applications such as screen-readers to determine whether the text content of a control should be read aloud.
IsPassword {
get {
local retVal
return (ComCall(35, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the window handle of the element.
NativeWindowHandle {
get {
local retVal
return (ComCall(36, this, "ptr*", &retVal := 0), retVal)
}
}
; Retrieves a description of the type of UI item represented by the element.
; This property is used to obtain information about items in a list, tree view, or data grid. For example, an item in a file directory view might be a "Document File" or a "Folder".
ItemType {
get {
local retVal
return (ComCall(37, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
; Indicates whether the element is off-screen.
IsOffscreen {
get {
local retVal
return (ComCall(38, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves a value that indicates the orientation of the element.
; This property is supported by controls such as scroll bars and sliders that can have either a vertical or a horizontal orientation.
Orientation {
get {
local retVal
return (ComCall(39, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the name of the underlying UI framework. The name of the UI framework, such as "Win32", "WinForm", or "DirectUI".
FrameworkId {
get {
local retVal
return (ComCall(40, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
; Indicates whether the element is required to be filled out on a form.
IsRequiredForForm {
get {
local retVal
return (ComCall(41, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the description of the status of an item in an element.
; This property enables a client to ascertain whether an element is conveying status about an item. For example, an item associated with a contact in a messaging application might be "Busy" or "Connected".
ItemStatus {
get {
local retVal
return (ComCall(42, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
; Retrieves the coordinates of the rectangle that completely encloses the element, in screen coordinates.
BoundingRectangle => (ComCall(43, this, "ptr", retVal := UIA.NativeArray(0, 4, "int")), { l: retVal[0], t: retVal[1], r: retVal[2], b: retVal[3] })
; This property maps to the Accessible Rich Internet Applications (ARIA) property.
; Retrieves the element that contains the text label for this element.
; This property could be used to retrieve, for example, the static text label for a combo box.
LabeledBy {
get {
local retVal
return (ComCall(44, this, "ptr*", &retVal := 0), UIA.IUIAutomationElement(retVal))
}
}
; Retrieves the Accessible Rich Internet Applications (ARIA) role of the element.
AriaRole {
get {
local retVal
return (ComCall(45, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
; Retrieves the ARIA properties of the element.
AriaProperties {
get {
local retVal
return (ComCall(46, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
; Indicates whether the element contains valid data for a form.
IsDataValidForForm {
get {
local retVal
return (ComCall(47, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves an array of elements for which this element serves as the controller.
ControllerFor {
get {
local retVal
return (ComCall(48, this, "ptr*", &retVal := 0), retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[])
}
}
; Retrieves an array of elements that describe this element.
DescribedBy {
get {
local retVal
return (ComCall(49, this, "ptr*", &retVal := 0), retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[])
}
}
; Retrieves an array of elements that indicates the reading order after the current element.
FlowsTo {
get {
local retVal
return (ComCall(50, this, "ptr*", &retVal := 0), retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[])
}
}
; Retrieves a description of the provider for this element.
ProviderDescription {
get {
local retVal
return (ComCall(51, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
CachedRuntimeId => (this.DefineProp("CachedRuntimeId", {value:this.RuntimeId}), this.CachedRuntimeId)
; Retrieves the cached ID of the process that hosts the element.
CachedProcessId {
get {
local retVal
return (ComCall(52, this, "int*", &retVal := 0), this.DefineProp("CachedProcessId", {value: retVal}), this.CachedProcessId)
}
}
; Retrieves a cached value that indicates the control type of the element.
CachedType {
get {
local retVal
return (ComCall(53, this, "int*", &retVal := 0), this.DefineProp("CachedType", {value: retVal}), this.CachedType)
}
}
CachedControlType => this.CachedType
; Retrieves the cached localized description of the control type of the element.
CachedLocalizedType {
get {
local retVal
return (ComCall(54, this, "ptr*", &retVal := 0), this.DefineProp("CachedLocalizedType", {value: UIA.BSTR(retVal)}), this.CachedLocalizedType)
}
}
CachedLocalizedControlType => this.CachedLocalizedType
; Retrieves the cached name of the element.
CachedName {
get {
local retVal
return (ComCall(55, this, "ptr*", &retVal := 0), this.DefineProp("CachedName", {value: UIA.BSTR(retVal)}), this.CachedName)
}
}
; Retrieves the cached accelerator key for the element.
CachedAcceleratorKey {
get {
local retVal
return (ComCall(56, this, "ptr*", &retVal := 0), this.DefineProp("CachedAcceleratorKey", {value: UIA.BSTR(retVal)}), this.CachedAcceleratorKey)
}
}
; Retrieves the cached access key character for the element.
CachedAccessKey {
get {
local retVal
return (ComCall(57, this, "ptr*", &retVal := 0), this.DefineProp("CachedAccessKey", {value: UIA.BSTR(retVal)}), this.CachedAccessKey)
}
}
; A cached value that indicates whether the element has keyboard focus.
CachedHasKeyboardFocus {
get {
local retVal
return (ComCall(58, this, "int*", &retVal := 0), this.DefineProp("CachedHasKeyboardFocus", {value: retVal}), this.CachedHasKeyboardFocus)
}
}
; Retrieves a cached value that indicates whether the element can accept keyboard focus.
CachedIsKeyboardFocusable {
get {
local retVal
return (ComCall(59, this, "int*", &retVal := 0), this.DefineProp("CachedIsKeyboardFocusable", {value: retVal}), this.CachedIsKeyboardFocusable)
}
}
; Retrieves a cached value that indicates whether the element is enabled.
CachedIsEnabled {
get {
local retVal
return (ComCall(60, this, "int*", &retVal := 0), this.DefineProp("CachedIsEnabled", {value: retVal}), this.CachedIsEnabled)
}
}
; Retrieves the cached UI Automation identifier of the element.
CachedAutomationId {
get {
local retVal
return (ComCall(61, this, "ptr*", &retVal := 0), this.DefineProp("CachedAutomationId", {value: UIA.BSTR(retVal)}), this.CachedAutomationId)
}
}
; Retrieves the cached class name of the element.
CachedClassName {
get {
local retVal
return (ComCall(62, this, "ptr*", &retVal := 0), this.DefineProp("CachedClassName", {value: UIA.BSTR(retVal)}), this.CachedClassName)
}
}
;
CachedHelpText {
get {
local retVal
return (ComCall(63, this, "ptr*", &retVal := 0), this.DefineProp("CachedHelpText", {value: UIA.BSTR(retVal)}), this.CachedHelpText)
}
}
; Retrieves the cached help text for the element.
CachedCulture {
get {
local retVal
return (ComCall(64, this, "int*", &retVal := 0), this.DefineProp("CachedCulture", {value: retVal}), this.CachedCulture)
}
}
; Retrieves a cached value that indicates whether the element is a control element.
CachedIsControlElement {
get {
local retVal
return (ComCall(65, this, "int*", &retVal := 0), this.DefineProp("CachedIsControlElement", {value: retVal}), this.CachedIsControlElement)
}
}
; A cached value that indicates whether the element is a content element.
CachedIsContentElement {
get {
local retVal
return (ComCall(66, this, "int*", &retVal := 0), this.DefineProp("CachedIsContentElement", {value: retVal}), this.CachedIsContentElement)
}
}
; Retrieves a cached value that indicates whether the element contains a disguised password.
CachedIsPassword {
get {
local retVal
return (ComCall(67, this, "int*", &retVal := 0), this.DefineProp("CachedIsPassword", {value: retVal}), this.CachedIsPassword)
}
}
; Retrieves the cached window handle of the element.
CachedNativeWindowHandle {
get {
local retVal
return (ComCall(68, this, "ptr*", &retVal := 0), this.DefineProp("CachedNativeWindowHandle", {value: retVal}), this.CachedNativeWindowHandle)
}
}
; Retrieves a cached string that describes the type of item represented by the element.
CachedItemType {
get {
local retVal
return (ComCall(69, this, "ptr*", &retVal := 0), this.DefineProp("CachedItemType", {value: UIA.BSTR(retVal)}), this.CachedItemType)
}
}
; Retrieves a cached value that indicates whether the element is off-screen.
CachedIsOffscreen {
get {
local retVal
return (ComCall(70, this, "int*", &retVal := 0), this.DefineProp("CachedIsOffscreen", {value: retVal}), this.CachedIsOffscreen)
}
}
; Retrieves a cached value that indicates the orientation of the element.
CachedOrientation {
get {
local retVal
return (ComCall(71, this, "int*", &retVal := 0), this.DefineProp("CachedOrientation", {value: retVal}), this.CachedOrientation)
}
}
; Retrieves the cached name of the underlying UI framework associated with the element.
CachedFrameworkId {
get {
local retVal
return (ComCall(72, this, "ptr*", &retVal := 0), this.DefineProp("CachedFrameworkId", {value: UIA.BSTR(retVal)}), this.CachedFrameworkId)
}
}
; Retrieves a cached value that indicates whether the element is required to be filled out on a form.
CachedIsRequiredForForm {
get {
local retVal
return (ComCall(73, this, "int*", &retVal := 0), this.DefineProp("CachedIsRequiredForForm", {value: retVal}), this.CachedIsRequiredForForm)
}
}
; Retrieves a cached description of the status of an item within an element.
CachedItemStatus {
get {
local retVal
return (ComCall(74, this, "ptr*", &retVal := 0), this.DefineProp("CachedItemStatus", {value: UIA.BSTR(retVal)}), this.CachedItemStatus)
}
}
; Retrieves the cached coordinates of the rectangle that completely encloses the element.
CachedBoundingRectangle => (ComCall(75, this, "ptr", retVal := UIA.NativeArray(0, 4, "int")), this.DefineProp("CachedBoundingRectangle", {value: { l: retVal[0], t: retVal[1], r: retVal[2], b: retVal[3] }}), this.CachedBoundingRectangle)
; Retrieves the cached element that contains the text label for this element.
CachedLabeledBy {
get {
local retVal
return (ComCall(76, this, "ptr*", &retVal := 0), this.DefineProp("CachedLabeledBy", {value: UIA.IUIAutomationElement(retVal)}), this.CachedLabeledBy)
}
}
; Retrieves the cached ARIA role of the element.
CachedAriaRole {
get {
local retVal
return (ComCall(77, this, "ptr*", &retVal := 0), this.DefineProp("CachedAriaRole", {value: UIA.BSTR(retVal)}), this.CachedAriaRole)
}
}
; Retrieves the cached ARIA properties of the element.
CachedAriaProperties {
get {
local retVal
return (ComCall(78, this, "ptr*", &retVal := 0), this.DefineProp("CachedAriaProperties", {value: UIA.BSTR(retVal)}), this.CachedAriaProperties)
}
}
; Retrieves a cached value that indicates whether the element contains valid data for the form.
CachedIsDataValidForForm {
get {
local retVal
return (ComCall(79, this, "int*", &retVal := 0), this.DefineProp("CachedIsDataValidForForm", {value: retVal}), this.CachedIsDataValidForForm)
}
}
; Retrieves a cached array of UI Automation elements for which this element serves as the controller.
CachedControllerFor {
get {
local retVal
return (ComCall(80, this, "ptr*", &retVal := 0), this.DefineProp("CachedControllerFor", {value: retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[]}), this.CachedControllerFor)
}
}
; Retrieves a cached array of elements that describe this element.
CachedDescribedBy {
get {
local retVal
return (ComCall(81, this, "ptr*", &retVal := 0), this.DefineProp("CachedDescribedBy", {value: retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[]}), this.CachedDescribedBy)
}
}
; Retrieves a cached array of elements that indicate the reading order after the current element.
CachedFlowsTo {
get {
local retVal
return (ComCall(82, this, "ptr*", &retVal := 0), this.DefineProp("CachedFlowsTo", {value: retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[]}), this.CachedFlowsTo)
}
}
; Retrieves a cached description of the provider for this element.
CachedProviderDescription {
get {
local retVal
return (ComCall(83, this, "ptr*", &retVal := 0), this.DefineProp("CachedProviderDescription", {value: UIA.BSTR(retVal)}), this.CachedProviderDescription)
}
}
; Retrieves a point on the element that can be clicked.
; A client application can use this method to simulate clicking the left or right mouse button. For example, to simulate clicking the right mouse button to display the context menu for a control,
; • Call the GetClickablePoint method to find a clickable point on the control.
; • Call the SendInput function to send a right-mouse-down, right-mouse-up sequence.
GetClickablePoint() {
if (ComCall(84, this, "ptr", clickable := Buffer(8), "int*", &gotClickable := 0), gotClickable)
return { x: NumGet(clickable, 0, 'int'), y: NumGet(clickable, 4, 'int') }
throw TargetError('The element has no clickable point')
}
;; UIA.IUIAutomationElement2
OptimizeForVisualContent {
get {
local retVal
return (ComCall(85, this, "int*", &retVal := 0), retVal)
}
}
CachedOptimizeForVisualContent {
get {
local retVal
return (ComCall(86, this, "int*", &retVal := 0), retVal)
}
}
LiveSetting {
get {
local retVal
return (ComCall(87, this, "int*", &retVal := 0), retVal)
}
}
CachedLiveSetting {
get {
local retVal
return (ComCall(88, this, "int*", &retVal := 0), retVal)
}
}
FlowsFrom {
get {
local retVal
return (ComCall(89, this, "ptr*", &retVal := 0), retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[])
}
}
CachedFlowsFrom {
get {
local retVal
return (ComCall(90, this, "ptr*", &retVal := 0), retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[])
}
}
;; UIA.IUIAutomationElement3
ShowContextMenu() => ComCall(91, this)
IsPeripheral {
get {
local retVal
return (ComCall(92, this, "int*", &retVal := 0), retVal)
}
}
CachedIsPeripheral {
get {
local retVal
return (ComCall(93, this, "int*", &retVal := 0), retVal)
}
}
;; UIA.IUIAutomationElement4
PositionInSet {
get {
local retVal
return (ComCall(94, this, "int*", &retVal := 0), retVal)
}
}
SizeOfSet {
get {
local retVal
return (ComCall(95, this, "int*", &retVal := 0), retVal)
}
}
Level {
get {
local retVal
return (ComCall(96, this, "int*", &retVal := 0), retVal)
}
}
AnnotationTypes {
get {
local retVal
return (ComCall(97, this, "ptr*", &retVal := 0), ComValue(0x2003, retVal))
}
}
AnnotationObjects {
get {
local retVal
return (ComCall(98, this, "ptr*", &retVal := 0), retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[])
}
}
CachedPositionInSet {
get {
local retVal
return (ComCall(99, this, "int*", &retVal := 0), retVal)
}
}
CachedSizeOfSet {
get {
local retVal
return (ComCall(100, this, "int*", &retVal := 0), retVal)
}
}
CachedLevel {
get {
local retVal
return (ComCall(101, this, "int*", &retVal := 0), retVal)
}
}
CachedAnnotationTypes {
get {
local retVal
return (ComCall(102, this, "ptr*", &retVal := 0), ComValue(0x2003, retVal))
}
}
CachedAnnotationObjects {
get {
local retVal
return (ComCall(103, this, "ptr*", &retVal := 0), retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[])
}
}
;; UIA.IUIAutomationElement5
LandmarkType {
get {
local retVal
return (ComCall(104, this, "int*", &retVal := 0), retVal)
}
}
LocalizedLandmarkType {
get {
local retVal
return (ComCall(105, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
CachedLandmarkType {
get {
local retVal
return (ComCall(106, this, "int*", &retVal := 0), retVal)
}
}
CachedLocalizedLandmarkType {
get {
local retVal
return (ComCall(107, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
;; UIA.IUIAutomationElement6
FullDescription {
get {
local retVal
return (ComCall(108, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
CachedFullDescription {
get {
local retVal
return (ComCall(109, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
;; UIA.IUIAutomationElement7
; FindFirst with additional parameters
; This gets called when FindFirst or FindElement is used with traversalOptions or startingElement arguments
FindFirstWithOptions(condition, traversalOptions:=0, root:=0, scope:=4) {
local found
if (ComCall(110, this, "int", UIA.TypeValidation.TreeScope(scope), "ptr", (Type(condition) ~= "i)Condition|ComValue") ? condition : UIA.__CreateRawCondition(condition), "int", UIA.TypeValidation.TreeTraversalOptions(traversalOptions), "ptr", root, "ptr*", &found := 0), found)
return UIA.IUIAutomationElement(found)
throw TargetError("An element matching the condition was not found", -1)
}
; FindAll with additional parameters
; This gets called when FindAll or FindElements is used with traversalOptions or startingElement arguments
FindAllWithOptions(condition, traversalOptions:=0, root:=0, scope:=4) {
local found
if (ComCall(111, this, "int", UIA.TypeValidation.TreeScope(scope), "ptr", (Type(condition) ~= "i)Condition|ComValue") ? condition : UIA.__CreateRawCondition(condition), "int", UIA.TypeValidation.TreeTraversalOptions(traversalOptions), "ptr", root, "ptr*", &found := 0), found)
return UIA.IUIAutomationElementArray(found).ToArray()
return []
}
; TreeScope, IUIAutomationCondition, IUIAutomationCacheRequest, TreeTraversalOptions, UIA.IUIAutomationElement
FindFirstWithOptionsBuildCache(cacheRequest, condition, traversalOptions:=0, root:=0, scope := 4) {
local found
if (ComCall(112, this, "int", UIA.TypeValidation.TreeScope(scope), "ptr", InStr(Type(condition), "Condition") ? condition : UIA.__CreateRawCondition(condition), "ptr", UIA.TypeValidation.CacheRequest(cacheRequest), "int", traversalOptions, "ptr", root, "ptr*", &found := 0), found)
return UIA.IUIAutomationElement(found)
throw TargetError("An element matching the condition was not found", -1)
}
FindAllWithOptionsBuildCache(cacheRequest, condition, traversalOptions:=0, root:=0, scope := 4) {
local found
if (ComCall(113, this, "int", UIA.TypeValidation.TreeScope(scope), "ptr", InStr(Type(condition), "Condition") ? condition : UIA.__CreateRawCondition(condition), "ptr", UIA.TypeValidation.CacheRequest(cacheRequest), "int", traversalOptions, "ptr", root, "ptr*", &found := 0), found)
return UIA.IUIAutomationElementArray(found).ToArray()
return []
}
GetMetadataValue(targetId, metadataId) {
local returnVal
return (ComCall(114, this, "int", targetId, "int", metadataId, "ptr", returnVal := UIA.ComVar()), returnVal[])
}
;; UIA.IUIAutomationElement8
HeadingLevel {
get {
local retVal
return (ComCall(115, this, "int*", &retVal := 0), retVal)
}
}
CachedHeadingLevel {
get {
local retVal
return (ComCall(116, this, "int*", &retVal := 0), retVal)
}
}
;; UIA.IUIAutomationElement9
IsDialog {
get {
local retVal
return (ComCall(117, this, "int*", &retVal := 0), retVal)
}
}
CachedIsDialog {
get {
local retVal
return (ComCall(118, this, "int*", &retVal := 0), retVal)
}
}
;; Some aliases for properties from GetPropertyValue
/*
ClickablePoint => this.GetPropertyValue(UIA.Property.ClickablePoint)
IsDockPatternAvailable => this.GetPropertyValue(UIA.Property.IsDockPatternAvailable)
IsExpandCollapsePatternAvailable => this.GetPropertyValue(UIA.Property.IsExpandCollapsePatternAvailable)
IsGridItemPatternAvailable => this.GetPropertyValue(UIA.Property.IsGridItemPatternAvailable)
IsGridPatternAvailable => this.GetPropertyValue(UIA.Property.IsGridPatternAvailable)
IsInvokePatternAvailable => this.GetPropertyValue(UIA.Property.IsInvokePatternAvailable)
IsMultipleViewPatternAvailable => this.GetPropertyValue(UIA.Property.IsMultipleViewPatternAvailable)
IsRangeValuePatternAvailable => this.GetPropertyValue(UIA.Property.IsRangeValuePatternAvailable)
IsScrollPatternAvailable => this.GetPropertyValue(UIA.Property.IsScrollPatternAvailable)
IsScrollItemPatternAvailable => this.GetPropertyValue(UIA.Property.IsScrollItemPatternAvailable)
IsSelectionItemPatternAvailable => this.GetPropertyValue(UIA.Property.IsSelectionItemPatternAvailable)
IsSelectionPatternAvailable => this.GetPropertyValue(UIA.Property.IsSelectionPatternAvailable)
IsTablePatternAvailable => this.GetPropertyValue(UIA.Property.IsTablePatternAvailable)
IsTableItemPatternAvailable => this.GetPropertyValue(UIA.Property.IsTableItemPatternAvailable)
IsTextPatternAvailable => this.GetPropertyValue(UIA.Property.IsTextPatternAvailable)
IsTogglePatternAvailable => this.GetPropertyValue(UIA.Property.IsTogglePatternAvailable)
IsTransformPatternAvailable => this.GetPropertyValue(UIA.Property.IsTransformPatternAvailable)
IsValuePatternAvailable => this.GetPropertyValue(UIA.Property.IsValuePatternAvailable)
IsWindowPatternAvailable => this.GetPropertyValue(UIA.Property.IsWindowPatternAvailable)
ValueIsReadOnly => this.GetPropertyValue(UIA.Property.ValueIsReadOnly)
RangeValueValue => this.GetPropertyValue(UIA.Property.RangeValueValue)
RangeValueIsReadOnly => this.GetPropertyValue(UIA.Property.RangeValueIsReadOnly)
RangeValueMinimum => this.GetPropertyValue(UIA.Property.RangeValueMinimum)
RangeValueMaximum => this.GetPropertyValue(UIA.Property.RangeValueMaximum)
RangeValueLargeChange => this.GetPropertyValue(UIA.Property.RangeValueLargeChange)
RangeValueSmallChange => this.GetPropertyValue(UIA.Property.RangeValueSmallChange)
ScrollHorizontalScrollPercent => this.GetPropertyValue(UIA.Property.ScrollHorizontalScrollPercent)
ScrollHorizontalViewSize => this.GetPropertyValue(UIA.Property.ScrollHorizontalViewSize)
ScrollVerticalScrollPercent => this.GetPropertyValue(UIA.Property.ScrollVerticalScrollPercent)
ScrollVerticalViewSize => this.GetPropertyValue(UIA.Property.ScrollVerticalViewSize)
ScrollHorizontallyScrollable => this.GetPropertyValue(UIA.Property.ScrollHorizontallyScrollable)
ScrollVerticallyScrollable => this.GetPropertyValue(UIA.Property.ScrollVerticallyScrollable)
SelectionSelection => this.GetPropertyValue(UIA.Property.SelectionSelection)
SelectionCanSelectMultiple => this.GetPropertyValue(UIA.Property.SelectionCanSelectMultiple)
SelectionIsSelectionRequired => this.GetPropertyValue(UIA.Property.SelectionIsSelectionRequired)
GridRowCount => this.GetPropertyValue(UIA.Property.GridRowCount)
GridColumnCount => this.GetPropertyValue(UIA.Property.GridColumnCount)
GridItemRow => this.GetPropertyValue(UIA.Property.GridItemRow)
GridItemColumn => this.GetPropertyValue(UIA.Property.GridItemColumn)
GridItemRowSpan => this.GetPropertyValue(UIA.Property.GridItemRowSpan)
GridItemColumnSpan => this.GetPropertyValue(UIA.Property.GridItemColumnSpan)
GridItemContainingGrid => this.GetPropertyValue(UIA.Property.GridItemContainingGrid)
DockDockPosition => this.GetPropertyValue(UIA.Property.DockDockPosition)
ExpandCollapseExpandCollapseState => this.GetPropertyValue(UIA.Property.ExpandCollapseExpandCollapseState)
MultipleViewCurrentView => this.GetPropertyValue(UIA.Property.MultipleViewCurrentView)
MultipleViewSupportedViews => this.GetPropertyValue(UIA.Property.MultipleViewSupportedViews)
WindowCanMaximize => this.GetPropertyValue(UIA.Property.WindowCanMaximize)
WindowCanMinimize => this.GetPropertyValue(UIA.Property.WindowCanMinimize)
WindowWindowVisualState => this.GetPropertyValue(UIA.Property.WindowWindowVisualState)
WindowWindowInteractionState => this.GetPropertyValue(UIA.Property.WindowWindowInteractionState)
WindowIsModal => this.GetPropertyValue(UIA.Property.WindowIsModal)
WindowIsTopmost => this.GetPropertyValue(UIA.Property.WindowIsTopmost)
SelectionItemIsSelected => this.GetPropertyValue(UIA.Property.SelectionItemIsSelected)
SelectionItemSelectionContainer => this.GetPropertyValue(UIA.Property.SelectionItemSelectionContainer)
TableRowHeaders => this.GetPropertyValue(UIA.Property.TableRowHeaders)
TableColumnHeaders => this.GetPropertyValue(UIA.Property.TableColumnHeaders)
TableRowOrColumnMajor => this.GetPropertyValue(UIA.Property.TableRowOrColumnMajor)
TableItemRowHeaderItems => this.GetPropertyValue(UIA.Property.TableItemRowHeaderItems)
TableItemColumnHeaderItems => this.GetPropertyValue(UIA.Property.TableItemColumnHeaderItems)
ToggleToggleState => this.GetPropertyValue(UIA.Property.ToggleToggleState)
TransformCanMove => this.GetPropertyValue(UIA.Property.TransformCanMove)
TransformCanResize => this.GetPropertyValue(UIA.Property.TransformCanResize)
TransformCanRotate => this.GetPropertyValue(UIA.Property.TransformCanRotate)
IsLegacyIAccessiblePatternAvailable => this.GetPropertyValue(UIA.Property.IsLegacyIAccessiblePatternAvailable)
LegacyIAccessibleChildId => this.GetPropertyValue(UIA.Property.LegacyIAccessibleChildId)
LegacyIAccessibleName => this.GetPropertyValue(UIA.Property.LegacyIAccessibleName)
LegacyIAccessibleValue => this.GetPropertyValue(UIA.Property.LegacyIAccessibleValue)
LegacyIAccessibleDescription => this.GetPropertyValue(UIA.Property.LegacyIAccessibleDescription)
LegacyIAccessibleRole => this.GetPropertyValue(UIA.Property.LegacyIAccessibleRole)
LegacyIAccessibleState => this.GetPropertyValue(UIA.Property.LegacyIAccessibleState)
LegacyIAccessibleHelp => this.GetPropertyValue(UIA.Property.LegacyIAccessibleHelp)
LegacyIAccessibleKeyboardShortcut => this.GetPropertyValue(UIA.Property.LegacyIAccessibleKeyboardShortcut)
LegacyIAccessibleSelection => this.GetPropertyValue(UIA.Property.LegacyIAccessibleSelection)
LegacyIAccessibleDefaultAction => this.GetPropertyValue(UIA.Property.LegacyIAccessibleDefaultAction)
IsItemContainerPatternAvailable => this.GetPropertyValue(UIA.Property.IsItemContainerPatternAvailable)
IsVirtualizedItemPatternAvailable => this.GetPropertyValue(UIA.Property.IsVirtualizedItemPatternAvailable)
IsSynchronizedInputPatternAvailable => this.GetPropertyValue(UIA.Property.IsSynchronizedInputPatternAvailable)
IsObjectModelPatternAvailable => this.GetPropertyValue(UIA.Property.IsObjectModelPatternAvailable)
AnnotationAnnotationTypeId => this.GetPropertyValue(UIA.Property.AnnotationAnnotationTypeId)
AnnotationAnnotationTypeName => this.GetPropertyValue(UIA.Property.AnnotationAnnotationTypeName)
AnnotationAuthor => this.GetPropertyValue(UIA.Property.AnnotationAuthor)
AnnotationDateTime => this.GetPropertyValue(UIA.Property.AnnotationDateTime)
AnnotationTarget => this.GetPropertyValue(UIA.Property.AnnotationTarget)
IsAnnotationPatternAvailable => this.GetPropertyValue(UIA.Property.IsAnnotationPatternAvailable)
IsTextPattern2Available => this.GetPropertyValue(UIA.Property.IsTextPattern2Available)
StylesStyleId => this.GetPropertyValue(UIA.Property.StylesStyleId)
StylesStyleName => this.GetPropertyValue(UIA.Property.StylesStyleName)
StylesFillColor => this.GetPropertyValue(UIA.Property.StylesFillColor)
StylesFillPatternStyle => this.GetPropertyValue(UIA.Property.StylesFillPatternStyle)
StylesShape => this.GetPropertyValue(UIA.Property.StylesShape)
StylesFillPatternColor => this.GetPropertyValue(UIA.Property.StylesFillPatternColor)
StylesExtendedProperties => this.GetPropertyValue(UIA.Property.StylesExtendedProperties)
IsStylesPatternAvailable => this.GetPropertyValue(UIA.Property.IsStylesPatternAvailable)
IsSpreadsheetPatternAvailable => this.GetPropertyValue(UIA.Property.IsSpreadsheetPatternAvailable)
SpreadsheetItemFormula => this.GetPropertyValue(UIA.Property.SpreadsheetItemFormula)
SpreadsheetItemAnnotationObjects => this.GetPropertyValue(UIA.Property.SpreadsheetItemAnnotationObjects)
SpreadsheetItemAnnotationTypes => this.GetPropertyValue(UIA.Property.SpreadsheetItemAnnotationTypes)
IsSpreadsheetItemPatternAvailable => this.GetPropertyValue(UIA.Property.IsSpreadsheetItemPatternAvailable)
Transform2CanZoom => this.GetPropertyValue(UIA.Property.Transform2CanZoom)
IsTransformPattern2Available => this.GetPropertyValue(UIA.Property.IsTransformPattern2Available)
IsTextChildPatternAvailable => this.GetPropertyValue(UIA.Property.IsTextChildPatternAvailable)
IsDragPatternAvailable => this.GetPropertyValue(UIA.Property.IsDragPatternAvailable)
DragIsGrabbed => this.GetPropertyValue(UIA.Property.DragIsGrabbed)
DragDropEffect => this.GetPropertyValue(UIA.Property.DragDropEffect)
DragDropEffects => this.GetPropertyValue(UIA.Property.DragDropEffects)
IsDropTargetPatternAvailable => this.GetPropertyValue(UIA.Property.IsDropTargetPatternAvailable)
DropTargetDropTargetEffect => this.GetPropertyValue(UIA.Property.DropTargetDropTargetEffect)
DropTargetDropTargetEffects => this.GetPropertyValue(UIA.Property.DropTargetDropTargetEffects)
DragGrabbedItems => this.GetPropertyValue(UIA.Property.DragGrabbedItems)
Transform2ZoomLevel => this.GetPropertyValue(UIA.Property.Transform2ZoomLevel)
Transform2ZoomMinimum => this.GetPropertyValue(UIA.Property.Transform2ZoomMinimum)
Transform2ZoomMaximum => this.GetPropertyValue(UIA.Property.Transform2ZoomMaximum)
IsTextEditPatternAvailable => this.GetPropertyValue(UIA.Property.IsTextEditPatternAvailable)
IsCustomNavigationPatternAvailable => this.GetPropertyValue(UIA.Property.IsCustomNavigationPatternAvailable)
FillColor => this.GetPropertyValue(UIA.Property.FillColor)
OutlineColor => this.GetPropertyValue(UIA.Property.OutlineColor)
FillType => this.GetPropertyValue(UIA.Property.FillType)
VisualEffects => this.GetPropertyValue(UIA.Property.VisualEffects)
OutlineThickness => this.GetPropertyValue(UIA.Property.OutlineThickness)
CenterPoint => this.GetPropertyValue(UIA.Property.CenterPoint)
Rotation => this.GetPropertyValue(UIA.Property.Rotation)
Size => this.GetPropertyValue(UIA.Property.Size)
IsSelectionPattern2Available => this.GetPropertyValue(UIA.Property.IsSelectionPattern2Available)
Selection2FirstSelectedItem => this.GetPropertyValue(UIA.Property.Selection2FirstSelectedItem)
Selection2LastSelectedItem => this.GetPropertyValue(UIA.Property.Selection2LastSelectedItem)
Selection2CurrentSelectedItem => this.GetPropertyValue(UIA.Property.Selection2CurrentSelectedItem)
Selection2ItemCount => this.GetPropertyValue(UIA.Property.Selection2ItemCount)
*/
}
class IUIAutomationArray extends UIA.IUIAutomationBase {
/**
* Element[i] returns the i-th element.
* Element[-i] returns the i-th last element: Element[-1] will return the last element.
*/
__Item[index] {
get {
try {
if index>0
return this.GetElement(index-1)
else
return this.GetElement(this.Length+index)
} catch
throw IndexError("Index " index " out of bounds", -2)
}
}
__Enum(varCount) {
local maxLen := this.Length-1, i := 0
EnumElements(&element) {
if i > maxLen
return false
element := this.GetElement(i++)
return true
}
EnumIndexAndElements(&index, &element) {
if i > maxLen
return false
element := this.GetElement(i++)
index := i
return true
}
return (varCount = 1) ? EnumElements : EnumIndexAndElements
}
; Converts an IUIAutomationArray into AHK array
ToArray() {
local ret := []
Loop this.Length
ret.Push(this.GetElement(A_index-1))
return ret
}
ToReversedArray() {
local ret := [], len := this.Length
Loop len
ret.Push(this.GetElement(len-A_Index))
return ret
}
}
class IUIAutomationElementArray extends UIA.IUIAutomationArray {
; Retrieves the number of elements in the collection.
Length {
get {
local length
return (ComCall(3, this, "int*", &length := 0), length)
}
}
; Retrieves a Microsoft UI Automation element from the collection.
; Index is 0-based
GetElement(index) {
local element
return (ComCall(4, this, "int", index, "ptr*", &element := 0), UIA.IUIAutomationElement(element))
}
}
/*
Exposes properties and methods that UI Automation client applications use to view and navigate the UI Automation elements on the desktop.
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationtreewalker
*/
class IUIAutomationTreeWalker extends UIA.IUIAutomationBase {
; The structure of the Microsoft UI Automation tree changes as the visible UI elements on the desktop change.
; An element can have additional child elements that do not match the current view condition and thus are not returned when navigating the element tree.
; Retrieves the parent element of the specified UI Automation element.
GetParentElement(element) {
local out
if (ComCall(3, this, "ptr", UIA.TypeValidation.Element(element), "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
throw UnsetError("No element found with GetParentElement", -1)
}
TryGetParentElement(element) {
local out
try if (ComCall(3, this, "ptr", element, "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
return 0
}
; Retrieves the first child element of the specified UI Automation element.
GetFirstChildElement(element) {
local out
if (ComCall(4, this, "ptr", UIA.TypeValidation.Element(element), "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
throw UnsetError("No element found with GetFirstChildElement", -1)
}
TryGetFirstChildElement(element) {
local out
try if (ComCall(4, this, "ptr", element, "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
return 0
}
; Retrieves the last child element of the specified UI Automation element.
GetLastChildElement(element) {
local out
if (ComCall(5, this, "ptr", UIA.TypeValidation.Element(element), "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
throw UnsetError("No element found with GetLastChildElement", -1)
}
TryGetLastChildElement(element) {
local out
try if (ComCall(5, this, "ptr", element, "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
return 0
}
; Retrieves the next sibling element of the specified UI Automation element, and caches properties and control patterns.
GetNextSiblingElement(element) {
local out
if (ComCall(6, this, "ptr", UIA.TypeValidation.Element(element), "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
throw UnsetError("No element found with GetNextSiblingElement", -1)
}
TryGetNextSiblingElement(element) {
local out
try if (ComCall(6, this, "ptr", element, "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
return 0
}
; Retrieves the previous sibling element of the specified UI Automation element, and caches properties and control patterns.
GetPreviousSiblingElement(element) {
local out
if (ComCall(7, this, "ptr", UIA.TypeValidation.Element(element), "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
throw UnsetError("No element found with GetPreviousSiblingElement", -1)
}
TryGetPreviousSiblingElement(element) {
local out
try if (ComCall(7, this, "ptr", element, "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
return 0
}
; Retrieves the ancestor element nearest to the specified Microsoft UI Automation element in the tree view.
; The element is normalized by navigating up the ancestor chain in the tree until an element that satisfies the view condition (specified by a previous call to IUIAutomationTreeWalker,,Condition) is reached. If the root element is reached, the root element is returned, even if it does not satisfy the view condition.
; This method is useful for applications that obtain references to UI Automation elements by hit-testing. The application might want to work only with specific types of elements, and can use IUIAutomationTreeWalker,,Normalize to make sure that no matter what element is initially retrieved (for example, when a scroll bar gets the input focus), only the element of interest (such as a content element) is ultimately retrieved.
NormalizeElement(element) {
local out
if (ComCall(8, this, "ptr", UIA.TypeValidation.Element(element), "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
throw UnsetError("No element found with NormalizeElement", -1)
}
TryNormalizeElement(element) {
local out
try if (ComCall(8, this, "ptr", element, "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
return 0
}
; Retrieves the parent element of the specified UI Automation element, and caches properties and control patterns.
GetParentElementBuildCache(cacheRequest, element) {
local out
if (ComCall(9, this, "ptr", UIA.TypeValidation.Element(element), "ptr", UIA.TypeValidation.CacheRequest(cacheRequest), "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
throw UnsetError("No element found with GetParentElementBuildCache", -1)
}
TryGetParentElementBuildCache(cacheRequest, element) {
local out
try if (ComCall(9, this, "ptr", element, "ptr", cacheRequest, "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
return 0
}
; Retrieves the first child element of the specified UI Automation element, and caches properties and control patterns.
GetFirstChildElementBuildCache(cacheRequest, element) {
local out
if (ComCall(10, this, "ptr", UIA.TypeValidation.Element(element), "ptr", UIA.TypeValidation.CacheRequest(cacheRequest), "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
throw UnsetError("No element found with GetFirstChildElementBuildCache", -1)
}
TryGetFirstChildElementBuildCache(cacheRequest, element) {
local out
try if (ComCall(10, this, "ptr", element, "ptr", cacheRequest, "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
return 0
}
; Retrieves the last child element of the specified UI Automation element, and caches properties and control patterns.
GetLastChildElementBuildCache(cacheRequest, element) {
local out
if (ComCall(11, this, "ptr", UIA.TypeValidation.Element(element), "ptr", UIA.TypeValidation.CacheRequest(cacheRequest), "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
throw UnsetError("No element found with GetLastChildElementBuildCache", -1)
}
TryGetLastChildElementBuildCache(cacheRequest, element) {
local out
try if (ComCall(11, this, "ptr", element, "ptr", cacheRequest, "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
return 0
}
; Retrieves the next sibling element of the specified UI Automation element, and caches properties and control patterns.
GetNextSiblingElementBuildCache(cacheRequest, element) {
local out
if (ComCall(12, this, "ptr", UIA.TypeValidation.Element(element), "ptr", UIA.TypeValidation.CacheRequest(cacheRequest), "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
throw UnsetError("No element found with GetNextSiblingElementBuildCache", -1)
}
TryGetNextSiblingElementBuildCache(cacheRequest, element) {
local out
try if (ComCall(12, this, "ptr", element, "ptr", cacheRequest, "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
return 0
}
; Retrieves the previous sibling element of the specified UI Automation element, and caches properties and control patterns.
GetPreviousSiblingElementBuildCache(cacheRequest, element) {
local out
if (ComCall(13, this, "ptr", UIA.TypeValidation.Element(element), "ptr", UIA.TypeValidation.CacheRequest(cacheRequest), "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
throw UnsetError("No element found with GetPreviousSiblingElementBuildCache", -1)
}
TryGetPreviousSiblingElementBuildCache(cacheRequest, element) {
local out
try if (ComCall(13, this, "ptr", element, "ptr", cacheRequest, "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
return 0
}
; Retrieves the ancestor element nearest to the specified Microsoft UI Automation element in the tree view, prefetches the requested properties and control patterns, and stores the prefetched items in the cache.
NormalizeElementBuildCache(cacheRequest, element) {
local out
if (ComCall(14, this, "ptr", UIA.TypeValidation.Element(element), "ptr", UIA.TypeValidation.CacheRequest(cacheRequest), "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
throw UnsetError("No element found with NormalizeElementBuildCache", -1)
}
TryNormalizeElementBuildCache(cacheRequest, element) {
local out
try if (ComCall(14, this, "ptr", element, "ptr", cacheRequest, "ptr*", &out := 0), out)
return UIA.IUIAutomationElement(out)
return 0
}
; Retrieves the condition that defines the view of the UI Automation tree. This property is read-only.
; The condition that defines the view. This is the interface that was passed to CreateTreeWalker.
Condition {
get {
local condition
return (ComCall(15, this, "ptr*", &condition := 0), UIA.IUIAutomationCondition(condition))
}
}
}
/*
Represents a condition based on a property value that is used to find UI Automation elements.
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationpropertycondition
*/
class IUIAutomationPropertyCondition extends UIA.IUIAutomationCondition {
static __IID := "{99ebf2cb-5578-4267-9ad4-afd6ea77e94b}"
PropertyId {
get {
local propertyId
return (ComCall(3, this, "int*", &propertyId := 0), propertyId)
}
}
PropertyValue {
get {
local propertyValue
return (ComCall(4, this, "ptr", propertyValue := UIA.ComVar()), propertyValue[])
}
}
PropertyConditionFlags {
get {
local flags
return (ComCall(5, this, "int*", &flags := 0), flags)
}
}
}
/*
Exposes properties and methods that Microsoft UI Automation client applications can use to retrieve information about an AND-based property condition.
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationandcondition
*/
class IUIAutomationAndCondition extends UIA.IUIAutomationCondition {
static __IID := "{a7d0af36-b912-45fe-9855-091ddc174aec}"
ChildCount {
get {
local childCount
return (ComCall(3, this, "int*", &childCount := 0), childCount)
}
}
GetChildrenAsNativeArray() {
local childArrayCount
return (ComCall(4, this, "ptr*", &childArray := 0, "int*", &childArrayCount := 0), UIA.NativeArray(childArray, childArrayCount))
}
GetChildren() {
local childArray
return (ComCall(5, this, "ptr*", &childArray := 0), UIA.IUIAutomationCondition.__SafeArrayToConditionArray(childArray))
}
}
/*
Represents a condition made up of multiple conditions, at least one of which must be true.
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationorcondition
*/
class IUIAutomationOrCondition extends UIA.IUIAutomationAndCondition {
static __IID := "{8753f032-3db1-47b5-a1fc-6e34a266c712}"
ChildCount {
get {
local childCount
return (ComCall(3, this, "int*", &childCount := 0), childCount)
}
}
GetChildrenAsNativeArray() {
local childArrayCount
return (ComCall(4, this, "ptr*", &childArray := 0, "int*", &childArrayCount := 0), UIA.NativeArray(childArray, childArrayCount))
}
GetChildren() {
local childArray
return (ComCall(5, this, "ptr*", &childArray := 0), UIA.IUIAutomationCondition.__SafeArrayToConditionArray(childArray))
}
}
/*
Represents a condition that can be either TRUE=1 (selects all elements) or FALSE=0(selects no elements).
Microsoft documentation:
*/
class IUIAutomationBoolCondition extends UIA.IUIAutomationCondition {
static __IID := "{1B4E1F2E-75EB-4D0B-8952-5A69988E2307}"
Value {
get {
local boolVal
return (ComCall(3, this, "int*", &boolVal := 0), boolVal)
}
}
}
/*
Represents a condition that is the negative of another condition.
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationnotcondition
*/
class IUIAutomationNotCondition extends UIA.IUIAutomationCondition {
static __IID := "{f528b657-847b-498c-8896-d52b565407a1}"
GetChild() {
local condition
return (ComCall(3, this, "ptr*", &condition := 0), UIA.IUIAutomationCondition.__QueryCondition(condition))
}
}
class IUIAutomationCondition extends UIA.IUIAutomationBase {
static __QueryCondition(pCond) {
for n in ["Property", "Bool", "And", "Or", "Not"] {
try {
if ComObjQuery(pCond, UIA.IUIAutomation%n%Condition.__IID)
return UIA.IUIAutomation%n%Condition(pCond)
}
}
}
static __SafeArrayToConditionArray(pSafeArr) {
local safeArray := ComValue(0x2003,pSafeArr), out := [], k, cond
for k in safeArray {
if cond := UIA.IUIAutomationCondition.__QueryCondition(k)
out.Push(cond)
}
return out
}
}
/*
Exposes properties and methods of a cache request. Client applications use this interface to specify the properties and control patterns to be cached when a Microsoft UI Automation element is obtained.
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationcacherequest
*/
class IUIAutomationCacheRequest extends UIA.IUIAutomationBase {
; Adds a property to the cache request.
AddProperty(propertyId) => ComCall(3, this, "int", UIA.TypeValidation.Property(propertyId))
; Adds a control pattern to the cache request. Adding a control pattern that is already in the cache request has no effect.
AddPattern(patternId) => ComCall(4, this, "int", UIA.TypeValidation.Pattern(patternId))
; Creates a copy of the cache request.
Clone() {
local clonedRequest
if (ComCall(5, this, "ptr*", &clonedRequest := 0), clonedRequest)
return UIA.IUIAutomationCacheRequest(clonedRequest)
throw Error("Cloning the CacheRequest failed", -1)
}
TreeScope {
get {
local scope
return (ComCall(6, this, "int*", &scope := 0), scope)
}
set => ComCall(7, this, "int", UIA.TypeValidation.TreeScope(value))
}
TreeFilter {
get {
local filter
if (ComCall(8, this, "ptr*", &filter := 0), filter)
return UIA.IUIAutomationCondition(filter)
throw UnsetError("No condition returned by " A_ThisFunc, -1)
}
set => ComCall(9, this, "ptr", (Type(Value) ~= "i)Condition|ComValue") ? value : UIA.__CreateRawCondition(value))
}
AutomationElementMode {
get {
local mode
return (ComCall(10, this, "int*", &mode := 0), mode)
}
set => ComCall(11, this, "int", UIA.TypeValidation.AutomationElementMode(Value))
}
; Extracts all properties from an object condition and adds them to the CacheRequest
AddPropertiesFromCondition(condition) {
local value, prop
if Type(condition) = "Object"
condition := condition.OwnProps()
for prop, value in condition {
try prop := UIA.TypeValidation.Property(prop)
if !(IsInteger(prop) && prop > 10000) {
if IsObject(value)
this.AddPropertiesFromCondition(value)
} else
this.AddProperty(prop)
}
}
}
/**
* Creates a new event handler, that when registered will call the supplied function on the registered event.
* @param funcObj The callback function that will get called on events.
* The function needs to accept a certain number of parameters that depends on which event will be registered.
* HandleAutomationEvent(sender, eventId)
* HandleFocusChangedEvent(sender)
* HandlePropertyChangedEvent(sender, propertyId, newValue)
* HandleStructureChangedEvent(sender, changeType, runtimeId)
* HandleTextEditTextChangedEvent(sender, changeType, eventStrings)
* HandleChangesEvent(sender, uiaChanges, changesCount)
* HandleNotificationEvent(sender, notificationKind, notificationProcessing, displayString, activityId)
* @param handlerType This needs to be provided if the handler is going to be used with something other than UIA.AddAutomationEventHandler()
* For UIA.AddAutomationEventHandler leave this empty (default value).
* For UIA.Add...EventHandler, specify the ... part: FocusChanged, StructureChanged, TextEditTextChanged, Changes, Notification.
* Eg. For UIA.AddFocusChangedEventHandler, set this value to "FocusChanged": CreateEventHandler(Func, "FocusChanged")
*/
static CreateEventHandler(funcObj, handlerType:="") {
local buf, handler, cR, cAF, cQI, cF
if funcObj is String
try funcObj := %funcObj%
if !HasMethod(funcObj, "Call")
throw TypeError("Invalid function provided", -2)
buf := Buffer(A_PtrSize * 6)
handler := UIA.IUIAutomation%handlerType%EventHandler()
handler.Buffer := buf, handler.Ptr := buf.ptr
handlerFunc := handler.Handle%(handlerType ? handlerType : "Automation")%Event
NumPut("ptr", buf.Ptr + 2*A_PtrSize, "ptr", ObjPtr(handler), "ptr", cQI:=CallbackCreate(QueryInterface,, 3), "ptr", cAF:=CallbackCreate(AddRef,, 1), "ptr", cR:=CallbackCreate(Release,, 1), "ptr", cF:=CallbackCreate(handlerFunc.Bind(handler),, handlerFunc.MaxParams-1), buf)
ObjRelease(ObjPtr(handler)) ; CallbackCreate binds "handler" to itself, so decrease ref count by 1 to allow it to be released, then inside __Delete add it back before CallbackFree
handler.DefineProp("__Delete", { call: (this, *) => (ObjAddRef(ObjPtr(this)), CallbackFree(cQI), CallbackFree(cAF), CallbackFree(cR), CallbackFree(cF)) })
handler.EventHandler := funcObj
return handler
QueryInterface(pSelf, pRIID, pObj){ ; Credit: https://github.com/neptercn/UIAutomation/blob/master/UIA.ahk
DllCall("ole32\StringFromIID","ptr",pRIID,"wstr*",&str)
return (str="{00000000-0000-0000-C000-000000000046}")||(str="{146c3c17-f12e-4e22-8c27-f894b9b79c69}")||(str="{40cd37d4-c756-4b0c-8c6f-bddfeeb13b50}")||(str="{e81d1b4e-11c5-42f8-9754-e7036c79f054}")||(str="{c270f6b5-5c69-4290-9745-7a7f97169468}")||(str="{92FAA680-E704-4156-931A-E32D5BB38F3F}")||(str="{58EDCA55-2C3E-4980-B1B9-56C17F27A2A0}")||(str="{C7CB2637-E6C2-4D0C-85DE-4948C02175C7}")?(NumPut("ptr",pSelf,pObj), ObjAddRef(pSelf))*0:0x80004002 ; E_NOINTERFACE
}
AddRef(pSelf) => ObjAddRef(NumGet(pSelf, A_PtrSize, "ptr"))
Release(pSelf) => ObjRelease(NumGet(pSelf, A_PtrSize, "ptr"))
}
static CreateAutomationEventHandler(funcObj) => UIA.CreateEventHandler(funcObj)
static CreateFocusChangedEventHandler(funcObj) => UIA.CreateEventHandler(funcObj, "FocusChanged")
static CreatePropertyChangedEventHandler(funcObj) => UIA.CreateEventHandler(funcObj, "PropertyChanged")
static CreateStructureChangedEventHandler(funcObj) => UIA.CreateEventHandler(funcObj, "StructureChanged")
static CreateTextEditTextChangedEventHandler(funcObj) => UIA.CreateEventHandler(funcObj, "TextEditTextChanged")
static CreateChangesEventHandler(funcObj) => UIA.CreateEventHandler(funcObj, "Changes")
static CreateNotificationEventHandler(funcObj) => UIA.CreateEventHandler(funcObj, "Notification")
class IUIAutomationEventHandler {
static __IID := "{146c3c17-f12e-4e22-8c27-f894b9b79c69}"
HandleAutomationEvent(pSelf, sender, eventId) {
ObjAddRef(sender), this.EventHandler.Call(UIA.IUIAutomationElement(sender), eventId&0xFFFFFFFF)
}
}
class IUIAutomationFocusChangedEventHandler {
static __IID := "{c270f6b5-5c69-4290-9745-7a7f97169468}"
HandleFocusChangedEvent(pSelf, sender) {
ObjAddRef(sender), this.EventHandler.Call(UIA.IUIAutomationElement(sender))
}
}
/*
Exposes a method to handle Microsoft UI Automation events that occur when a property is changed.
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationpropertychangedeventhandler
*/
class IUIAutomationPropertyChangedEventHandler { ; UNTESTED
;~ http://msdn.microsoft.com/en-us/library/windows/desktop/ee696119(v=vs.85).aspx
static __IID := "{40cd37d4-c756-4b0c-8c6f-bddfeeb13b50}"
HandlePropertyChangedEvent(pSelf, sender, propertyId, newValue) {
local val := ComValue(0x400C, newValue)[]
DllCall("oleaut32\VariantClear", "ptr", newValue)
ObjAddRef(sender), this.EventHandler.Call(UIA.IUIAutomationElement(sender), propertyId&0xFFFFFFFF, val)
}
}
/*
Exposes a method to handle events that occur when the Microsoft UI Automation tree structure is changed.
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationstructurechangedeventhandler
*/
class IUIAutomationStructureChangedEventHandler {
;~ http://msdn.microsoft.com/en-us/library/windows/desktop/ee696197(v=vs.85).aspx
static __IID := "{e81d1b4e-11c5-42f8-9754-e7036c79f054}"
HandleStructureChangedEvent(pSelf, sender, changeType, runtimeId) {
ObjAddRef(sender), this.EventHandler.Call(UIA.IUIAutomationElement(sender), changeType&0xFFFFFFFF, UIA.SafeArrayToAHKArray(runtimeId))
DllCall("oleaut32\VariantClear", "ptr", runtimeId)
}
}
/*
Exposes a method to handle events that occur when Microsoft UI Automation reports a text-changed event from text edit controls
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationtextedittextchangedeventhandler
*/
class IUIAutomationTextEditTextChangedEventHandler { ; UNTESTED
;~ http://msdn.microsoft.com/en-us/library/windows/desktop/dn302202(v=vs.85).aspx
static __IID := "{92FAA680-E704-4156-931A-E32D5BB38F3F}"
HandleTextEditTextChangedEvent(pSelf, sender, changeType, eventStrings) {
local val := ComValue(0x400C, eventStrings)[]
DllCall("oleaut32\VariantClear", "ptr", eventStrings)
ObjAddRef(sender), this.EventHandler.Call(UIA.IUIAutomationElement(sender), changeType&0xFFFFFFFF, val)
}
}
/*
Exposes a method to handle one or more Microsoft UI Automation change events
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationchangeseventhandler
*/
class IUIAutomationChangesEventHandler { ; UNTESTED
static __IID := "{58EDCA55-2C3E-4980-B1B9-56C17F27A2A0}"
HandleChangesEvent(pSelf, sender, uiaChanges, changesCount) {
local changes, pExtraInfo
changes := {id:NumGet(uiaChanges,"Int"), payload:ComValue(0x400C, pPayload := NumGet(uiaChanges,8,"uint64"))[], extraInfo:ComValue(0x400C, pExtraInfo := NumGet(uiaChanges,16+2*A_PtrSize,"uint64")[])}
DllCall("oleaut32\VariantClear", "ptr", pPayload), DllCall("oleaut32\VariantClear", "ptr", pExtraInfo)
ObjAddRef(sender), this.EventHandler.Call(UIA.IUIAutomationElement(sender), changes, changesCount)
}
}
/*
Exposes a method to handle Microsoft UI Automation notification events
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationnotificationeventhandler
*/
class IUIAutomationNotificationEventHandler {
static __IID := "{C7CB2637-E6C2-4D0C-85DE-4948C02175C7}"
HandleNotificationEvent(pSelf, sender, notificationKind, notificationProcessing, displayString, activityId) {
ObjAddRef(sender), this.EventHandler.Call(UIA.IUIAutomationElement(sender), notificationKind, notificationProcessing, UIA.BSTR(displayString), UIA.BSTR(activityId))
}
}
class IUIAutomationEventHandlerGroup extends UIA.IUIAutomationBase {
static __IID := "{C9EE12F2-C13B-4408-997C-639914377F4E}"
AddActiveTextPositionChangedEventHandler(handler, scope:=0x4, cacheRequest:=0) => ComCall(3, this, "int", UIA.TypeValidation.TreeScope(scope), "ptr", UIA.TypeValidation.CacheRequest(cacheRequest), "ptr", handler)
AddAutomationEventHandler(handler, eventId, scope:=0x4, cacheRequest:=0) => ComCall(4, this, "uint", eventId, "int", UIA.TypeValidation.TreeScope(scope), "ptr", UIA.TypeValidation.CacheRequest(cacheRequest), "ptr", handler)
AddChangesEventHandler(handler, changeTypes, scope:=0x4, cacheRequest:=0) {
local k, v
if !IsObject(changeTypes)
changeTypes := [changeTypes]
nativeArray := UIA.NativeArray(0, changeTypes.Length, "int")
for k, v in changeTypes
NumPut("int", v, nativeArray, (k-1)*4)
return ComCall(5, this, "int", UIA.TypeValidation.TreeScope(scope), "ptr", nativeArray, "int", changeTypes.Length, "int", cacheRequest, "ptr", handler)
}
AddNotificationEventHandler(handler, scope:=0x4, cacheRequest:=0) => ComCall(6, this, "int", UIA.TypeValidation.TreeScope(scope), "ptr", UIA.TypeValidation.CacheRequest(cacheRequest), "ptr", handler)
AddPropertyChangedEventHandler(handler, propertyArray, scope:=0x1,cacheRequest:=0) {
local i, propertyId, SafeArray
if !IsObject(propertyArray)
propertyArray := [propertyArray]
SafeArray:=ComObjArray(0x3,propertyArray.Length)
for i,propertyId in propertyArray
SafeArray[i-1]:=propertyId
return ComCall(7, this, "int", UIA.TypeValidation.TreeScope(scope), "ptr", UIA.TypeValidation.CacheRequest(cacheRequest),"ptr", handler,"ptr", SafeArray)
}
AddStructureChangedEventHandler(handler, scope:=0x4, cacheRequest:=0) => ComCall(8, this "int", UIA.TypeValidation.TreeScope(scope), "ptr",cacheRequest, "ptr", handler)
AddTextEditTextChangedEventHandler(handler, textEditChangeType, scope:=0x4, cacheRequest:=0) => ComCall(9, this, "int", UIA.TypeValidation.TreeScope(scope), "int", UIA.TypeValidation.TextEditChangeType(textEditChangeType), "ptr", UIA.TypeValidation.CacheRequest(cacheRequest), "ptr", handler)
}
/*
Provides access to the properties of an annotation in a document.
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationannotationpattern
*/
class IUIAutomationAnnotationPattern extends UIA.IUIAutomationBase {
AnnotationTypeId {
get {
local retVal
return (ComCall(3, this, "int*", &retVal := 0), retVal)
}
}
AnnotationTypeName {
get {
local retVal
return (ComCall(4, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
Author {
get {
local retVal
return (ComCall(5, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
DateTime {
get {
local retVal
return (ComCall(6, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
Target {
get {
local retVal
if (ComCall(7, this, "ptr*", &retVal := 0), retVal)
return UIA.IUIAutomationElement(retVal)
throw UnsetError("No element returned by " A_ThisFunc, -1)
}
}
CachedAnnotationTypeId {
get {
local retVal
return (ComCall(8, this, "int*", &retVal := 0), retVal)
}
}
CachedAnnotationTypeName {
get {
local retVal
return (ComCall(9, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
CachedAuthor {
get {
local retVal
return (ComCall(10, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
CachedDateTime {
get {
local retVal
return (ComCall(11, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
CachedTarget {
get {
local retVal
if (ComCall(11, this, "ptr*", &retVal := 0), retVal)
return UIA.IUIAutomationElement(retVal)
throw UnsetError("No element returned by " A_ThisFunc, -1)
}
}
}
/*
Exposes a method to support access by a Microsoft UI Automation client to controls that support a custom navigation order.
Microsoft documentation: https://learn.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationcustomnavigationpattern
*/
class IUIAutomationCustomNavigationPattern extends UIA.IUIAutomationBase {
; Gets the next element in the specified direction within the logical UI tree.
; direction can be one of UIA.NavigateDirection values: Parent, NextSibling, PreviousSibling, FirstChild, LastChild
Navigate(direction) {
local pRetVal
if (ComCall(3, this, "int", UIA.TypeValidation.NavigateDirection(direction), "ptr*", &pRetVal := 0), pRetVal)
return UIA.IUIAutomationElement(pRetVal)
throw UnsetError("No element returned by " A_ThisFunc, -1)
}
}
/*
Provides access to a control that enables child elements to be arranged horizontally and vertically, relative to each other.
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationdockpattern
*/
class IUIAutomationDockPattern extends UIA.IUIAutomationBase {
static __IID := "{fde5ef97-1464-48f6-90bf-43d0948e86ec}"
; ---------- DockPattern properties ----------
; Retrieves the `dock position` of this element within its docking container.
DockPosition {
get {
local retVal
return (ComCall(4, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the `cached dock` position of this element within its docking container.
CachedDockPosition {
get {
local retVal
return (ComCall(5, this, "int*", &retVal := 0), retVal)
}
}
; ---------- DockPattern methods ----------
/**
* Sets the dock position of this element.
* @param dockPos One of UIA.DockPosition values: Top, Left, Bottom, Right, Fill, None
*/
SetDockPosition(dockPos) => ComCall(3, this, "int", UIA.TypeValidation.DockPosition(dockPos))
}
/*
Provides access to information exposed by a UI Automation provider for an element that can be dragged as part of a drag-and-drop operation.
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationdragpattern
*/
class IUIAutomationDragPattern extends UIA.IUIAutomationBase {
static __IID := "{1DC7B570-1F54-4BAD-BCDA-D36A722FB7BD}"
; ---------- DragPattern properties ----------
IsGrabbed {
get {
local retVal
return (ComCall(3, this, "int*", &retVal := 0), retVal)
}
}
CachedIsGrabbed {
get {
local retVal
return (ComCall(4, this, "int*", &retVal := 0), retVal)
}
}
DropEffect {
get {
local retVal
return (ComCall(5, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
CachedDropEffect {
get {
local retVal
return (ComCall(6, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
DropEffects {
get {
local retVal
return (ComCall(7, this, "ptr*", &retVal := 0), ComValue(0x2008, retVal))
}
}
CachedDropEffects {
get {
local retVal
return (ComCall(8, this, "ptr*", &retVal := 0), ComValue(0x2008, retVal))
}
}
; ---------- DragPattern methods ----------
/**
* Retrieves a collection of elements that represent the full set of items that the user is dragging as part of a drag operation.
* @returns {IUIAutomationElementArray}
*/
GetGrabbedItems() {
local retVal
return (ComCall(9, this, "ptr*", &retVal := 0), retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[])
}
GetCachedGrabbedItems() {
local retVal
return (ComCall(10, this, "ptr*", &retVal := 0), retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[])
}
}
/*
Provides access to drag-and-drop information exposed by a Microsoft UI Automation provider for an element that can be the drop target of a drag-and-drop operation.
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationdroptargetpattern
*/
class IUIAutomationDropTargetPattern extends UIA.IUIAutomationBase {
static __IID := "{69A095F7-EEE4-430E-A46B-FB73B1AE39A5}"
; ---------- DropTargetPattern properties ----------
DropTargetEffect {
get {
local retVal
return (ComCall(3, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
CachedDropTargetEffect {
get {
local retVal
return (ComCall(4, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
DropTargetEffects {
get {
local retVal
return (ComCall(5, this, "ptr*", &retVal := 0), ComValue(0x2008, retVal))
}
}
CachedDropTargetEffects {
get {
local retVal
return (ComCall(6, this, "ptr*", &retVal := 0), ComValue(0x2008, retVal))
}
}
}
class IUIAutomationExpandCollapsePattern extends UIA.IUIAutomationBase {
; This is a blocking method that returns after the element has been collapsed.
; There are cases when a element that is marked as a leaf node might not know whether it has children until either the IUIAutomationExpandCollapsePattern,,Collapse or the IUIAutomationExpandCollapsePattern,,Expand method is called. This behavior is possible with a tree view control that does delayed loading of its child items. For example, Microsoft Windows Explorer might display the expand icon for a node even though there are currently no child items; when the icon is clicked, the control polls for child items, finds none, and removes the expand icon. In these cases clients should listen for a property-changed event on the IUIAutomationExpandCollapsePattern,,ExpandCollapseState property.
; Displays all child nodes, controls, or content of the element.
Expand() => ComCall(3, this)
; Hides all child nodes, controls, or content of the element.
Collapse() => ComCall(4, this)
; Retrieves a value that indicates the state, expanded or collapsed, of the element.
; Retrieve the name of the state via UIA.ExpandCollapseState[value]
ExpandCollapseState {
get {
local retVal
return (ComCall(5, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves a cached value that indicates the state, expanded or collapsed, of the element.
CachedExpandCollapseState {
get {
local retVal
return (ComCall(6, this, "int*", &retVal := 0), retVal)
}
}
}
class IUIAutomationGridItemPattern extends UIA.IUIAutomationBase {
; Retrieves the element that contains the grid item.
ContainingGrid {
get {
local retVal
if (ComCall(3, this, "ptr*", &retVal := 0), retVal)
return UIA.IUIAutomationElement(retVal)
throw UnsetError("No element returned by " A_ThisFunc, -1)
}
}
; Retrieves the zero-based index of the row that contains the grid item.
Row {
get {
local retVal
return (ComCall(4, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the zero-based index of the column that contains the item.
Column {
get {
local retVal
return (ComCall(5, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the number of rows spanned by the grid item.
RowSpan {
get {
local retVal
return (ComCall(6, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the number of columns spanned by the grid item.
ColumnSpan {
get {
local retVal
return (ComCall(7, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the cached element that contains the grid item.
CachedContainingGrid {
get {
local retVal
if (ComCall(8, this, "ptr*", &retVal := 0), retVal)
return UIA.IUIAutomationElement(retVal)
throw UnsetError("No element returned by " A_ThisFunc, -1)
}
}
; Retrieves the cached zero-based index of the row that contains the item.
CachedRow {
get {
local retVal
return (ComCall(9, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the cached zero-based index of the column that contains the grid item.
CachedColumn {
get {
local retVal
return (ComCall(10, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the cached number of rows spanned by a grid item.
CachedRowSpan {
get {
local retVal
return (ComCall(11, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the cached number of columns spanned by the grid item.
CachedColumnSpan {
get {
local retVal
return (ComCall(12, this, "int*", &retVal := 0), retVal)
}
}
}
class IUIAutomationGridPattern extends UIA.IUIAutomationBase {
; Retrieves a UI Automation element representing an item in the grid.
GetItem(row, column) {
local element
if (ComCall(3, this, "int", row, "int", column, "ptr*", &element := 0), element)
return UIA.IUIAutomationElement(element)
throw UnsetError("No element returned by " A_ThisFunc, -1)
}
; Hidden rows and columns, depending on the provider implementation, may be loaded in the Microsoft UI Automation tree and will therefore be reflected in the row count and column count properties. If the hidden rows and columns have not yet been loaded they are not counted.
; Retrieves the number of rows in the grid.
RowCount {
get {
local retVal
return (ComCall(4, this, "int*", &retVal := 0), retVal)
}
}
; The number of columns in the grid.
ColumnCount {
get {
local retVal
return (ComCall(5, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the cached number of rows in the grid.
CachedRowCount {
get {
local retVal
return (ComCall(6, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the cached number of columns in the grid.
CachedColumnCount {
get {
local retVal
return (ComCall(7, this, "int*", &retVal := 0), retVal)
}
}
}
class IUIAutomationInvokePattern extends UIA.IUIAutomationBase {
; Invokes the action of a control, such as a button click.
; Calls to this method should return immediately without blocking. However, this behavior depends on the implementation.
Invoke() => ComCall(3, this)
}
class IUIAutomationItemContainerPattern extends UIA.IUIAutomationBase {
; IUIAutomationItemContainerPattern
; Retrieves an element within a containing element, based on a specified property value.
; The provider may return an actual UIA.IUIAutomationElement interface or a placeholder if the matching element is virtualized.
; This method returns E_INVALIDARG if the property requested is not one that the container supports searching over. It is expected that most containers will support Name property, and if appropriate for the container, AutomationId and IsSelected.
; This method can be slow, because it may need to traverse multiple objects to find a matching one. When used in a loop to return multiple items, no specific order is defined so long as each item is returned only once (that is, the loop should terminate). This method is also item-centric, not UI-centric, so items with multiple UI representations need to be hit only once.
; When the propertyId parameter is specified as 0 (zero), the provider is expected to return the next item after pStartAfter. If pStartAfter is specified as NULL with a propertyId of 0, the provider should return the first item in the container. When propertyId is specified as 0, the value parameter should be VT_EMPTY.
FindItemByProperty(pStartAfter, propertyId, value) {
if A_PtrSize = 4
value := UIA.ComVar(value, , true), ComCall(3, this, "ptr", pStartAfter, "int", propertyId, "int64", NumGet(value, "int64"), "int64", NumGet(value, 8, "int64"), "ptr*", &pFound := 0)
else
ComCall(3, this, "ptr", pStartAfter, "int", propertyId, "ptr", UIA.ComVar(value, , true), "ptr*", &pFound := 0)
if (pFound)
return UIA.IUIAutomationElement(pFound)
}
}
class IUIAutomationLegacyIAccessiblePattern extends UIA.IUIAutomationBase {
; IUIAutomationLegacyIAccessiblePattern
; Performs a Microsoft Active Accessibility selection.
Select(flagsSelect:=3) => ComCall(3, this, "int", flagsSelect)
; Performs the Microsoft Active Accessibility default action for the element.
DoDefaultAction() => ComCall(4, this)
; Sets the Microsoft Active Accessibility value property for the element. This method is supported only for some elements (usually edit controls).
SetValue(szValue) => ComCall(5, this, "wstr", szValue)
; Retrieves the Microsoft Active Accessibility child identifier for the element. If the element is not a child element, CHILDID_SELF (0) is returned.
ChildId {
get {
local pRetVal
return (ComCall(6, this, "int*", &pRetVal := 0), pRetVal)
}
}
; Retrieves the Microsoft Active Accessibility name property of the element. The name of an element can be used to find the element in the element tree when the automation ID property is not supported on the element.
Name {
get {
local pszName
return (ComCall(7, this, "ptr*", &pszName := 0), UIA.BSTR(pszName))
}
}
; Retrieves the Microsoft Active Accessibility value property.
Value {
get {
local pszValue
return (ComCall(8, this, "ptr*", &pszValue := 0), UIA.BSTR(pszValue))
}
set => this.SetValue(value)
}
; Retrieves the Microsoft Active Accessibility description of the element.
Description {
get {
local pszDescription
return (ComCall(9, this, "ptr*", &pszDescription := 0), UIA.BSTR(pszDescription))
}
}
; Retrieves the Microsoft Active Accessibility role identifier of the element.
Role {
get {
local pdwRole
return (ComCall(10, this, "uint*", &pdwRole := 0), pdwRole)
}
}
; Retrieves the Microsoft Active Accessibility state identifier for the element.
State {
get {
local pdwState
return (ComCall(11, this, "uint*", &pdwState := 0), pdwState)
}
}
; Retrieves the Microsoft Active Accessibility help string for the element.
Help {
get {
local pszHelp
return (ComCall(12, this, "ptr*", &pszHelp := 0), UIA.BSTR(pszHelp))
}
}
; Retrieves the Microsoft Active Accessibility keyboard shortcut property for the element.
KeyboardShortcut {
get {
local pszKeyboardShortcut
return (ComCall(13, this, "ptr*", &pszKeyboardShortcut := 0), UIA.BSTR(pszKeyboardShortcut))
}
}
; Retrieves the Microsoft Active Accessibility property that identifies the selected children of this element.
GetSelection() {
local pvarSelectedChildren
return (ComCall(14, this, "ptr*", &pvarSelectedChildren := 0), pvarSelectedChildren?UIA.IUIAutomationElementArray(pvarSelectedChildren).ToArray():[])
}
; Retrieves the Microsoft Active Accessibility default action for the element.
DefaultAction {
get {
local pszDefaultAction
return (ComCall(15, this, "ptr*", &pszDefaultAction := 0), UIA.BSTR(pszDefaultAction))
}
}
; Retrieves the cached Microsoft Active Accessibility child identifier for the element.
CachedChildId {
get {
local pRetVal
return (ComCall(16, this, "int*", &pRetVal := 0), pRetVal)
}
}
; Retrieves the cached Microsoft Active Accessibility name property of the element.
CachedName {
get {
local pszName
return (ComCall(17, this, "ptr*", &pszName := 0), UIA.BSTR(pszName))
}
}
; Retrieves the cached Microsoft Active Accessibility value property.
CachedValue {
get {
local pszValue
return (ComCall(18, this, "ptr*", &pszValue := 0), UIA.BSTR(pszValue))
}
}
; Retrieves the cached Microsoft Active Accessibility description of the element.
CachedDescription {
get {
local pszDescription
return (ComCall(19, this, "ptr*", &pszDescription := 0), UIA.BSTR(pszDescription))
}
}
; Retrieves the cached Microsoft Active Accessibility role of the element.
CachedRole {
get {
local pdwRole
return (ComCall(20, this, "uint*", &pdwRole := 0), pdwRole)
}
}
; Retrieves the cached Microsoft Active Accessibility state identifier for the element.
CachedState {
get {
local pdwState
return (ComCall(21, this, "uint*", &pdwState := 0), pdwState)
}
}
; Retrieves the cached Microsoft Active Accessibility help string for the element.
CachedHelp {
get {
local pszHelp
return (ComCall(22, this, "ptr*", &pszHelp := 0), UIA.BSTR(pszHelp))
}
}
; Retrieves the cached Microsoft Active Accessibility keyboard shortcut property for the element.
CachedKeyboardShortcut {
get {
local pszKeyboardShortcut
return (ComCall(23, this, "ptr*", &pszKeyboardShortcut := 0), UIA.BSTR(pszKeyboardShortcut))
}
}
; Retrieves the cached Microsoft Active Accessibility property that identifies the selected children of this element.
GetCachedSelection() {
local pvarSelectedChildren
return (ComCall(24, this, "ptr*", &pvarSelectedChildren := 0), pvarSelectedChildren?UIA.IUIAutomationElementArray(pvarSelectedChildren).ToArray():[])
}
; Retrieves the Microsoft Active Accessibility default action for the element.
CachedDefaultAction {
get {
local pszDefaultAction
return (ComCall(25, this, "ptr*", &pszDefaultAction := 0), UIA.BSTR(pszDefaultAction))
}
}
; Retrieves an IAccessible object that corresponds to the Microsoft UI Automation element.
; This method returns NULL if the underlying implementation of the UI Automation element is not a native Microsoft Active Accessibility server; that is, if a client attempts to retrieve the IAccessible interface for an element originally supported by a proxy object from OLEACC.dll, or by the UIA-to-MSAA Bridge.
GetIAccessible() {
local ppAccessible
return (ComCall(26, this, "ptr*", &ppAccessible := 0), ComValue(9, ppAccessible))
}
}
class IUIAutomationMultipleViewPattern extends UIA.IUIAutomationBase {
static __IID := "{8d253c91-1dc5-4bb5-b18f-ade16fa495e8}"
; ---------- MultipleViewPattern properties ----------
; Retrieves the name of a control-specific view.
GetViewName(view) {
local name
return (ComCall(3, this, "int", view, "ptr*", &name := 0), UIA.BSTR(name))
}
; Sets the view of the control.
SetView(view) => ComCall(4, this, "int", view)
; Retrieves the control-specific identifier of the current view of the control.
View => this.CurrentView
CurrentView {
get {
local retVal
return (ComCall(5, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves a collection of control-specific view identifiers.
GetSupportedViews() {
local retVal
return (ComCall(6, this, "ptr*", &retVal := 0), UIA.SafeArrayToAHKArray(retVal))
}
; Retrieves the cached control-specific identifier of the current view of the control.
CachedView => this.CachedCurrentView
CachedCurrentView {
get {
local retVal
return (ComCall(7, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves a collection of control-specific view identifiers from the cache.
GetCachedSupportedViews() {
local retVal
return (ComCall(8, this, "ptr*", &retVal := 0), UIA.SafeArrayToAHKArray(retVal))
}
}
/*
Provides access to the underlying object model implemented by a control or application.
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationobjectmodelpattern
*/
class IUIAutomationObjectModelPattern extends UIA.IUIAutomationBase {
static __IID := "{71c284b3-c14d-4d14-981e-19751b0d756d}"
; Retrieves an interface used to access the underlying object model of the provider.
GetUnderlyingObjectModel() {
local retVal
return (ComCall(3, this, "ptr*", &retVal := 0), ComValue(0xd, retVal))
}
}
class IUIAutomationProxyFactory extends UIA.IUIAutomationBase {
CreateProvider(hwnd, idObject, idChild) {
local provider
return (ComCall(3, this, "ptr", hwnd, "int", idObject, "int", idChild, "ptr*", &provider := 0), ComValue(0xd, provider))
}
ProxyFactoryId {
get {
local factoryId
return (ComCall(4, this, "ptr*", &factoryId := 0), UIA.BSTR(factoryId))
}
}
}
class IUIAutomationProxyFactoryEntry extends UIA.IUIAutomationBase {
ProxyFactory() {
local factory
if (ComCall(3, this, "ptr*", &factory := 0), factory)
return UIA.IUIAutomationProxyFactory(factory)
throw UnsetError("No ProxyFactory returned by " A_ThisFunc, -1)
}
ClassName {
get {
local classname
return (ComCall(4, this, "ptr*", &classname := 0), UIA.BSTR(classname))
}
set => (ComCall(9, this, "wstr", Value))
}
ImageName {
get {
local imageName
return (ComCall(5, this, "ptr*", &imageName := 0), UIA.BSTR(imageName))
}
set => (ComCall(10, this, "wstr", Value))
}
AllowSubstringMatch {
get {
local allowSubstringMatch
return (ComCall(6, this, "int*", &allowSubstringMatch := 0), allowSubstringMatch)
}
set => (ComCall(11, this, "int", Value))
}
CanCheckBaseClass {
get {
local canCheckBaseClass
return (ComCall(7, this, "int*", &canCheckBaseClass := 0), canCheckBaseClass)
}
set => (ComCall(12, this, "int", Value))
}
NeedsAdviseEvents {
get {
local adviseEvents
return (ComCall(8, this, "int*", &adviseEvents := 0), adviseEvents)
}
set => (ComCall(13, this, "int", Value))
}
SetWinEventsForAutomationEvent(eventId, propertyId, winEvents) => ComCall(14, this, "int", eventId, "Int", propertyId, "ptr", winEvents)
GetWinEventsForAutomationEvent(eventId, propertyId) {
local winEvents
return (ComCall(15, this, "int", eventId, "Int", propertyId, "ptr*", &winEvents := 0), ComValue(0x200d, winEvents))
}
}
class IUIAutomationProxyFactoryMapping extends UIA.IUIAutomationBase {
Count {
get {
local count
return (ComCall(3, this, "uint*", &count := 0), count)
}
}
GetTable() {
local table
return (ComCall(4, this, "ptr*", &table := 0), ComValue(0x200d, table))
}
GetEntry(index) {
local entry
if (ComCall(5, this, "int", index, "ptr*", &entry := 0), entry)
return UIA.IUIAutomationProxyFactoryEntry(entry)
throw UnsetError("No ProxyFactoryEntry returned by " A_ThisFunc, -1)
}
SetTable(factoryList) => ComCall(6, this, "ptr", factoryList)
InsertEntries(before, factoryList) => ComCall(7, this, "uint", before, "ptr", factoryList)
InsertEntry(before, factory) => ComCall(8, this, "uint", before, "ptr", factory)
RemoveEntry(index) => ComCall(9, this, "uint", index)
ClearTable() => ComCall(10, this)
RestoreDefaultTable() => ComCall(11, this)
}
class IUIAutomationRangeValuePattern extends UIA.IUIAutomationBase {
; Sets the value of the control.
SetValue(val) => ComCall(3, this, "double", val)
; Retrieves the value of the control.
Value {
get {
local retVal
return (ComCall(4, this, "double*", &retVal := 0), retVal)
}
set => ComCall(3, this, "double", value)
}
; Indicates whether the value of the element can be changed.
IsReadOnly {
get {
local retVal
return (ComCall(5, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the maximum value of the control.
Maximum {
get {
local retVal
return (ComCall(6, this, "double*", &retVal := 0), retVal)
}
}
; Retrieves the minimum value of the control.
Minimum {
get {
local retVal
return (ComCall(7, this, "double*", &retVal := 0), retVal)
}
}
; The LargeChange and SmallChange property can support a Not a Number (NaN) value. When retrieving this property, a client can use the _isnan function to determine whether the property is a NaN value.
; Retrieves the value that is added to or subtracted from the value of the control when a large change is made, such as when the PAGE DOWN key is pressed.
LargeChange {
get {
local retVal
return (ComCall(8, this, "double*", &retVal := 0), retVal)
}
}
; Retrieves the value that is added to or subtracted from the value of the control when a small change is made, such as when an arrow key is pressed.
SmallChange {
get {
local retVal
return (ComCall(9, this, "double*", &retVal := 0), retVal)
}
}
; Retrieves the cached value of the control.
CachedValue {
get {
local retVal
return (ComCall(10, this, "double*", &retVal := 0), retVal)
}
}
; Retrieves a cached value that indicates whether the value of the element can be changed.
CachedIsReadOnly {
get {
local retVal
return (ComCall(11, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the cached maximum value of the control.
CachedMaximum {
get {
local retVal
return (ComCall(12, this, "double*", &retVal := 0), retVal)
}
}
; Retrieves the cached minimum value of the control.
CachedMinimum {
get {
local retVal
return (ComCall(13, this, "double*", &retVal := 0), retVal)
}
}
; Retrieves, from the cache, the value that is added to or subtracted from the value of the control when a large change is made, such as when the PAGE DOWN key is pressed.
CachedLargeChange {
get {
local retVal
return (ComCall(14, this, "double*", &retVal := 0), retVal)
}
}
; Retrieves, from the cache, the value that is added to or subtracted from the value of the control when a small change is made, such as when an arrow key is pressed.
CachedSmallChange {
get {
local retVal
return (ComCall(15, this, "double*", &retVal := 0), retVal)
}
}
}
class IUIAutomationScrollItemPattern extends UIA.IUIAutomationBase {
; Scrolls the content area of a container object to display the UI Automation element within the visible region (viewport) of the container.
; This method does not provide the ability to specify the position of the element within the viewport.
ScrollIntoView() => ComCall(3, this)
}
class IUIAutomationScrollPattern extends UIA.IUIAutomationBase {
; Scrolls the visible region of the content area horizontally and vertically.
; Default values for horizontalAmount and horizontalAmount is UIA.ScrollAmount.NoAmount
Scroll(verticalAmount:=-1, horizontalAmount:=-1) => ComCall(3, this, "int", UIA.TypeValidation.ScrollAmount(horizontalAmount), "int", UIA.TypeValidation.ScrollAmount(verticalAmount))
; Sets the horizontal and vertical scroll positions as a percentage of the total content area within the UI Automation element.
; This method is useful only when the content area of the control is larger than the visible region.
; Default values for horizontalPercent and verticalPercent is UIA.ScrollAmount.NoAmount
SetScrollPercent(verticalPercent:=-1, horizontalPercent:=-1) => ComCall(4, this, "double", horizontalPercent, "double", verticalPercent)
; Retrieves the horizontal scroll position.
HorizontalScrollPercent {
get {
local retVal
return (ComCall(5, this, "double*", &retVal := 0), retVal)
}
set => this.SetScrollPercent(,value)
}
; Retrieves the vertical scroll position.
VerticalScrollPercent {
get {
local retVal
return (ComCall(6, this, "double*", &retVal := 0), retVal)
}
set => this.SetScrollPercent(value)
}
; Retrieves the horizontal size of the viewable region of a scrollable element.
HorizontalViewSize {
get {
local retVal
return (ComCall(7, this, "double*", &retVal := 0), retVal)
}
}
; Retrieves the vertical size of the viewable region of a scrollable element.
VerticalViewSize {
get {
local retVal
return (ComCall(8, this, "double*", &retVal := 0), retVal)
}
}
; Indicates whether the element can scroll horizontally.
; This property can be dynamic. For example, the content area of the element might not be larger than the current viewable area, meaning that the property is FALSE. However, resizing the element or adding child items can increase the bounds of the content area beyond the viewable area, making the property TRUE.
HorizontallyScrollable {
get {
local retVal
return (ComCall(9, this, "int*", &retVal := 0), retVal)
}
}
; Indicates whether the element can scroll vertically.
VerticallyScrollable {
get {
local retVal
return (ComCall(10, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the cached horizontal scroll position.
CachedHorizontalScrollPercent {
get {
local retVal
return (ComCall(11, this, "double*", &retVal := 0), retVal)
}
}
; Retrieves the cached vertical scroll position.
CachedVerticalScrollPercent {
get {
local retVal
return (ComCall(12, this, "double*", &retVal := 0), retVal)
}
}
; Retrieves the cached horizontal size of the viewable region of a scrollable element.
CachedHorizontalViewSize {
get {
local retVal
return (ComCall(13, this, "double*", &retVal := 0), retVal)
}
}
; Retrieves the cached vertical size of the viewable region of a scrollable element.
CachedVerticalViewSize {
get {
local retVal
return (ComCall(14, this, "double*", &retVal := 0), retVal)
}
}
; Retrieves a cached value that indicates whether the element can scroll horizontally.
CachedHorizontallyScrollable {
get {
local retVal
return (ComCall(15, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves a cached value that indicates whether the element can scroll vertically.
CachedVerticallyScrollable {
get {
local retVal
return (ComCall(16, this, "int*", &retVal := 0), retVal)
}
}
}
class IUIAutomationSelectionItemPattern extends UIA.IUIAutomationBase {
; Clears any selected items and then selects the current element.
Select() => ComCall(3, this)
; Adds the current element to the collection of selected items.
AddToSelection() => ComCall(4, this)
; Removes this element from the selection.
; An error code is returned if this element is the only one in the selection and the selection container requires at least one element to be selected.
RemoveFromSelection() => ComCall(5, this)
; Indicates whether this item is selected.
IsSelected {
get {
local retVal
return (ComCall(6, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the element that supports IUIAutomationSelectionPattern and acts as the container for this item.
SelectionContainer {
get {
local retVal
if (ComCall(7, this, "ptr*", &retVal := 0), retVal)
return UIA.IUIAutomationElement(retVal)
throw UnsetError("No element returned by " A_ThisFunc, -1)
}
}
; A cached value that indicates whether this item is selected.
CachedIsSelected {
get {
local retVal
return (ComCall(8, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the cached element that supports IUIAutomationSelectionPattern and acts as the container for this item.
CachedSelectionContainer {
get {
local retVal
if (ComCall(9, this, "ptr*", &retVal := 0), retVal)
return UIA.IUIAutomationElement(retVal)
throw UnsetError("No element returned by " A_ThisFunc, -1)
}
}
}
class IUIAutomationSelectionPattern extends UIA.IUIAutomationBase {
; Retrieves the selected elements in the container.
GetSelection() {
local retVal
return (ComCall(3, this, "ptr*", &retVal := 0), retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[])
}
; Indicates whether more than one item in the container can be selected at one time.
CanSelectMultiple {
get {
local retVal
return (ComCall(4, this, "int*", &retVal := 0), retVal)
}
}
; Indicates whether at least one item must be selected at all times.
IsSelectionRequired {
get {
local retVal
return (ComCall(5, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the cached selected elements in the container.
GetCachedSelection() {
local retVal
return (ComCall(6, this, "ptr*", &retVal := 0), retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[])
}
; Retrieves a cached value that indicates whether more than one item in the container can be selected at one time.
CachedCanSelectMultiple {
get {
local retVal
return (ComCall(7, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves a cached value that indicates whether at least one item must be selected at all times.
CachedIsSelectionRequired {
get {
local retVal
return (ComCall(8, this, "int*", &retVal := 0), retVal)
}
}
; --------------- SelectionPattern2 ---------------
; Gets an IUIAutomationElement object representing the first item in a group of selected items.
FirstSelectedItem {
get {
local retVal
return (ComCall(9, this, "int*", &retVal := 0), retVal)
}
}
; Gets an IUIAutomationElement object representing the last item in a group of selected items.
LastSelectedItem {
get {
local retVal
return (ComCall(10, this, "int*", &retVal := 0), retVal)
}
}
; Gets an IUIAutomationElement object representing the currently selected item.
SelectedItem {
get {
local retVal
return (ComCall(11, this, "int*", &retVal := 0), retVal)
}
}
; Gets an integer value indicating the number of selected items.
ItemCount {
get {
local retVal
return (ComCall(12, this, "int*", &retVal := 0), retVal)
}
}
; Gets a cached IUIAutomationElement object representing the first item in a group of selected items.
CachedFirstSelectedItem {
get {
local retVal
return (ComCall(13, this, "int*", &retVal := 0), retVal)
}
}
; Gets a cached IUIAutomationElement object representing the last item in a group of selected items.
CachedLastSelectedItem {
get {
local retVal
return (ComCall(14, this, "int*", &retVal := 0), retVal)
}
}
; Gets a cached IUIAutomationElement object representing the currently selected item.
CachedSelectedItem {
get {
local retVal
return (ComCall(15, this, "int*", &retVal := 0), retVal)
}
}
; Gets a cached integer value indicating the number of selected items.
CachedItemCount {
get {
local retVal
return (ComCall(16, this, "int*", &retVal := 0), retVal)
}
}
}
class IUIAutomationSpreadsheetPattern extends UIA.IUIAutomationBase {
GetItemByName(name) {
local element
if (ComCall(3, this, "wstr", name, "ptr*", &element := 0), element)
return UIA.IUIAutomationElement(element)
throw UnsetError("No element returned by " A_ThisFunc, -1)
}
}
class IUIAutomationSpreadsheetItemPattern extends UIA.IUIAutomationBase {
Formula {
get {
local retVal
return (ComCall(3, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
GetAnnotationObjects() {
local retVal
return (ComCall(4, this, "ptr*", &retVal := 0), retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[])
}
GetAnnotationTypes() {
local retVal
return (ComCall(5, this, "ptr*", &retVal := 0), ComValue(0x2003, retVal))
}
CachedFormul {
get {
local retVal
return (ComCall(6, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
GetCachedAnnotationObjects() {
local retVal
return (ComCall(7, this, "ptr*", &retVal := 0), retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[])
}
GetCachedAnnotationTypes() {
local retVal
return (ComCall(8, this, "ptr*", &retVal := 0), ComValue(0x2003, retVal))
}
}
class IUIAutomationStylesPattern extends UIA.IUIAutomationBase {
StyleId {
get {
local retVal
return (ComCall(3, this, "int*", &retVal := 0), retVal)
}
}
StyleName {
get {
local retVal
return (ComCall(4, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
FillColor {
get {
local retVal
return (ComCall(5, this, "int*", &retVal := 0), retVal)
}
}
FillPatternStyle {
get {
local retVal
return (ComCall(6, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
Shape {
get {
local retVal
return (ComCall(7, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
FillPatternColor {
get {
local retVal
return (ComCall(8, this, "int*", &retVal := 0), retVal)
}
}
ExtendedProperties {
get {
local retVal
return (ComCall(9, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
GetExtendedPropertiesAsArray() {
local arr := [], p, propertyArray, propertyCount
ComCall(10, this, "ptr*", &propertyArray := 0, "int*", &propertyCount := 0)
for p in UIA.NativeArray(propertyArray, propertyCount)
arr.Push({ PropertyName: UIA.BSTR(NumGet(p, "ptr")), PropertyValue: UIA.BSTR(NumGet(p, A_PtrSize, "ptr")) })
return arr
}
CachedStyleId {
get {
local retVal
return (ComCall(11, this, "int*", &retVal := 0), retVal)
}
}
CachedStyleName {
get {
local retVal
return (ComCall(12, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
CachedFillColor {
get {
local retVal
return (ComCall(13, this, "int*", &retVal := 0), retVal)
}
}
CachedFillPatternStyle {
get {
local retVal
return (ComCall(14, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
CachedShape {
get {
local retVal
return (ComCall(15, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
CachedFillPatternColor {
get {
local retVal
return (ComCall(16, this, "int*", &retVal := 0), retVal)
}
}
CachedExtendedProperties {
get {
local retVal
return (ComCall(17, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
GetCachedExtendedPropertiesAsArray() {
local arr := [], p, propertyArray, propertyCount
ComCall(18, this, "ptr*", &propertyArray := 0, "int*", &propertyCount := 0)
for p in UIA.NativeArray(propertyArray, propertyCount)
arr.Push({ PropertyName: UIA.BSTR(NumGet(p, "ptr")), PropertyValue: UIA.BSTR(NumGet(p, A_PtrSize, "ptr")) })
return arr
}
}
class IUIAutomationSynchronizedInputPattern extends UIA.IUIAutomationBase {
; Causes the Microsoft UI Automation provider to start listening for mouse or keyboard input.
; When matching input is found, the provider checks whether the target element matches the current element. If they match, the provider raises the UIA_InputReachedTargetEventId event; otherwise it raises the UIA_InputReachedOtherElementEventId or UIA_InputDiscardedEventId event.
; After receiving input of the specified type, the provider stops checking for input and continues as normal.
; If the provider is already listening for input, this method returns E_INVALIDOPERATION.
StartListening(inputType) => ComCall(3, this, "int", inputType)
; Causes the Microsoft UI Automation provider to stop listening for mouse or keyboard input.
Cancel() => ComCall(4, this)
}
class IUIAutomationTableItemPattern extends UIA.IUIAutomationBase {
; Retrieves the row headers associated with a table item or cell.
GetRowHeaderItems() {
local retVal
return (ComCall(3, this, "ptr*", &retVal := 0), retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[])
}
; Retrieves the column headers associated with a table item or cell.
GetColumnHeaderItems() {
local retVal
return (ComCall(4, this, "ptr*", &retVal := 0), retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[])
}
; Retrieves the cached row headers associated with a table item or cell.
GetCachedRowHeaderItems() {
local retVal
return (ComCall(5, this, "ptr*", &retVal := 0), retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[])
}
; Retrieves the cached column headers associated with a table item or cell.
GetCachedColumnHeaderItems() {
local retVal
return (ComCall(6, this, "ptr*", &retVal := 0), retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[])
}
}
class IUIAutomationTablePattern extends UIA.IUIAutomationBase {
; Retrieves a collection of UI Automation elements representing all the row headers in a table.
GetRowHeaders() {
local retVal
return (ComCall(3, this, "ptr*", &retVal := 0), retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[])
}
; Retrieves a collection of UI Automation elements representing all the column headers in a table.
GetColumnHeaders() {
local retVal
return (ComCall(4, this, "ptr*", &retVal := 0), retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[])
}
; Retrieves the primary direction of traversal for the table.
RowOrColumnMajor {
get {
local retVal
return (ComCall(5, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves a cached collection of UI Automation elements representing all the row headers in a table.
GetCachedRowHeaders() {
local retVal
return (ComCall(6, this, "ptr*", &retVal := 0), retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[])
}
; Retrieves a cached collection of UI Automation elements representing all the column headers in a table.
GetCachedColumnHeaders() {
local retVal
return (ComCall(7, this, "ptr*", &retVal := 0), retVal?UIA.IUIAutomationElementArray(retVal).ToArray():[])
}
; Retrieves the cached primary direction of traversal for the table.
CachedRowOrColumnMajor {
get {
local retVal
return (ComCall(8, this, "int*", &retVal := 0), retVal)
}
}
}
class IUIAutomationTextChildPattern extends UIA.IUIAutomationBase {
TextContainer {
get {
local container
if (ComCall(3, this, "ptr*", &container := 0), container)
return UIA.IUIAutomationElement(container)
throw UnsetError("No element returned by " A_ThisFunc, -1)
}
}
TextRange {
get {
local range
if (ComCall(4, this, "ptr*", &range := 0), range)
return UIA.IUIAutomationTextRange(range)
throw UnsetError("No TextRange returned by " A_ThisFunc, -1)
}
}
}
class IUIAutomationTextEditPattern extends UIA.IUIAutomationBase {
GetActiveComposition() {
local range
if (ComCall(3, this, "ptr*", &range := 0), range)
return UIA.IUIAutomationTextRange(range)
throw UnsetError("No TextRange returned by " A_ThisFunc, -1)
}
GetConversionTarget() {
local range
if (ComCall(4, this, "ptr*", &range := 0), range)
return UIA.IUIAutomationTextRange(range)
throw UnsetError("No TextRange returned by " A_ThisFunc, -1)
}
}
class IUIAutomationTextPattern extends UIA.IUIAutomationBase {
/*
* Retrieves the degenerate (empty) text range nearest to the specified screen coordinates.
* A text range that wraps a child object is returned if the screen coordinates are within the coordinates of an image, hyperlink, Microsoft Excel spreadsheet, or other embedded object.
* Because hidden text is not ignored, this method retrieves a degenerate range from the visible text closest to the specified coordinates.
*/
RangeFromPoint(x, y?) {
local range
if (ComCall(3, this, "int64", IsSet(y) ? y << 32 | (x & 0xFFFFFFFF) : x, "ptr*", &range := 0), range)
return UIA.IUIAutomationTextRange(range)
throw UnsetError("No TextRange returned by " A_ThisFunc, -1)
}
; Retrieves a text range enclosing a child element such as an image, hyperlink, Microsoft Excel spreadsheet, or other embedded object.
; If there is no text in the range that encloses the child element, a degenerate (empty) range is returned.
; The child parameter is either a child of the element associated with a IUIAutomationTextPattern or from the array of children of a IUIAutomationTextRange.
RangeFromChild(child) {
local range
if (ComCall(4, this, "ptr", child, "ptr*", &range := 0), range)
return UIA.IUIAutomationTextRange(range)
throw UnsetError("No TextRange returned by " A_ThisFunc, -1)
}
; Retrieves a collection of text ranges that represents the currently selected text in a text-based control.
; If the control supports the selection of multiple, non-contiguous spans of text, the ranges collection receives one text range for each selected span.
; If the control contains only a single span of selected text, the ranges collection receives a single text range.
; If the control contains a text insertion point but no text is selected, the ranges collection receives a degenerate (empty) text range at the position of the text insertion point.
; If the control does not contain a text insertion point or does not support text selection, ranges is set to NULL.
; Use the IUIAutomationTextPattern.SupportedTextSelection property to test whether a control supports text selection.
GetSelection() {
local ranges
return (ComCall(5, this, "ptr*", &ranges := 0), ranges?UIA.IUIAutomationTextRangeArray(ranges).ToArray():[])
}
; Retrieves the first selection text range that represents the currently selected text in a text-based control.
SelectionRange {
get => this.GetSelection()[1]
}
; Retrieves an array of disjoint text ranges from a text-based control where each text range represents a contiguous span of visible text.
; If the visible text consists of one contiguous span of text, the ranges array will contain a single text range that represents all of the visible text.
; If the visible text consists of multiple, disjoint spans of text, the ranges array will contain one text range for each visible span, beginning with the first visible span, and ending with the last visible span. Disjoint spans of visible text can occur when the content of a text-based control is partially obscured by an overlapping window or other object, or when a text-based control with multiple pages or columns has content that is partially scrolled out of view.
; IUIAutomationTextPattern,,GetVisibleRanges retrieves a degenerate (empty) text range if no text is visible, if all text is scrolled out of view, or if the text-based control contains no text.
GetVisibleRanges() {
local ranges
return (ComCall(6, this, "ptr*", &ranges := 0), ranges?UIA.IUIAutomationTextRangeArray(ranges).ToArray():[])
}
; Retrieves a text range that encloses the main text of a document.
; Some auxiliary text such as headers, footnotes, or annotations might not be included.
DocumentRange {
get {
local range
if (ComCall(7, this, "ptr*", &range := 0), range)
return UIA.IUIAutomationTextRange(range)
throw UnsetError("No TextRange returned by " A_ThisFunc, -1)
}
}
; Retrieves a value that specifies the type of text selection that is supported by the control.
SupportedTextSelection {
get {
local supportedTextSelection
return (ComCall(8, this, "int*", &supportedTextSelection := 0), supportedTextSelection)
}
}
; ------------- TextPattern2 ------------
RangeFromAnnotation(annotation) {
local out
if (ComCall(9, this, "ptr", annotation, "ptr*", &out:=0), out)
return UIA.IUIAutomationTextRange(out)
throw UnsetError("No TextRange returned by " A_ThisFunc, -1)
}
GetCaretRange(&isActive:=0) {
local out
if (ComCall(10, this, "ptr*", &isActive:=0, "ptr*", &out:=0), out)
return UIA.IUIAutomationTextRange(out)
throw UnsetError("No TextRange returned by " A_ThisFunc, -1)
}
}
/*
Provides access to a span of continuous text in a container that supports the TextPattern interface. TextRange can be used to select, compare, and retrieve embedded objects from the text span. The interface uses two endpoints to delimit where the text span starts and ends. Disjoint spans of text are represented by a TextRangeArray, which is an array of TextRange interfaces.
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationtextrange
*/
class IUIAutomationTextRange extends UIA.IUIAutomationBase {
static __IID := "{A543CC6A-F4AE-494B-8239-C814481187A8}"
; Retrieves a IUIAutomationTextRange identical to the original and inheriting all properties of the original.
; The range can be manipulated independently of the original.
Clone() {
local clonedRange
if (ComCall(3, this, "ptr*", &clonedRange := 0), clonedRange)
return UIA.IUIAutomationTextRange(clonedRange)
throw UnsetError("No TextRange returned by " A_ThisFunc, -1)
}
; Retrieves a value that specifies whether this text range has the same endpoints as another text range.
; This method compares the endpoints of the two text ranges, not the text in the ranges. The ranges are identical if they share the same endpoints. If two text ranges have different endpoints, they are not identical even if the text in both ranges is exactly the same.
Compare(range) {
local areSame
return (ComCall(4, this, "ptr", range, "int*", &areSame := 0), areSame)
}
; Retrieves a value that specifies whether the start or end endpoint of this text range is the same as the start or end endpoint of another text range.
; EndPoint must be one of UIA.TextPatternRangeEndpoint values: Start, End
CompareEndpoints(srcEndPoint, range, targetEndPoint) {
local compValue
return (ComCall(5, this, "int", UIA.TypeValidation.TextPatternRangeEndpoint(srcEndPoint), "ptr", range, "int", UIA.TypeValidation.TextPatternRangeEndpoint(targetEndPoint), "int*", &compValue := 0), compValue)
}
; Normalizes the text range by the specified text unit. The range is expanded if it is smaller than the specified unit, or shortened if it is longer than the specified unit.
; Client applications such as screen readers use this method to retrieve the full word, sentence, or paragraph that exists at the insertion point or caret position.
; Despite its name, the ExpandToEnclosingUnit method does not necessarily expand a text range. Instead, it "normalizes" a text range by moving the endpoints so that the range encompasses the specified text unit. The range is expanded if it is smaller than the specified unit, or shortened if it is longer than the specified unit. If the range is already an exact quantity of the specified units, it remains unchanged. The following diagram shows how ExpandToEnclosingUnit normalizes a text range by moving the endpoints of the range.
; ExpandToEnclosingUnit defaults to the next largest text unit supported if the specified text unit is not supported by the control. The order, from smallest unit to largest, is as follows, Character Format Word Line Paragraph Page Document
; ExpandToEnclosingUnit respects both visible and hidden text.
; TextUnit must be one of UIA.TextUnit values: Character, Format, Word, Line, Paragraph, Page, Document. Default is Document.
ExpandToEnclosingUnit(textUnit:=6) => ComCall(6, this, "int", textUnit)
; Retrieves a text range subset that has the specified text attribute value.
; The FindAttribute method retrieves matching text regardless of whether the text is hidden or visible. Use UIA_IsHiddenAttributeId to check text visibility.
FindAttribute(attr, val, backward:=False) {
local found
if A_PtrSize = 4
val := UIA.ComVar(val, , true), ComCall(7, this, "int", attr, "int64", NumGet(val, "int64"), "int64", NumGet(val, 8, "int64"), "int", backward, "ptr*", &found := 0)
else
ComCall(7, this, "int", attr, "ptr", UIA.ComVar(val, , true), "int", backward, "ptr*", &found := 0)
return found?UIA.IUIAutomationTextRange(found):""
}
; Retrieves a text range subset that contains the specified text. There is no differentiation between hidden and visible text.
FindText(text, backward:=False, ignoreCase:=False) {
local found
if (ComCall(8, this, "wstr", text, "int", backward, "int", ignoreCase, "ptr*", &found := 0), found)
return UIA.IUIAutomationTextRange(found)
throw UnsetError("No TextRange returned by " A_ThisFunc, -1)
}
; Retrieves the value of the specified text attribute across the entire text range.
; The type of value retrieved by this method depends on the attr parameter. For example, calling GetAttributeValue with the attr parameter set to UIA_FontNameAttributeId returns a string that represents the font name of the text range, while calling GetAttributeValue with attr set to UIA_IsItalicAttributeId would return a boolean.
; If the attribute specified by attr is not supported, the value parameter receives a value that is equivalent to the IUIAutomation,,ReservedNotSupportedValue property.
; A text range can include more than one value for a particular attribute. For example, if a text range includes more than one font, the FontName attribute will have multiple values. An attribute with more than one value is called a mixed attribute. You can determine if a particular attribute is a mixed attribute by comparing the value retrieved from GetAttributeValue with the UIAutomation,,ReservedMixedAttributeValue property.
; The GetAttributeValue method retrieves the attribute value regardless of whether the text is hidden or visible. Use UIA_ IsHiddenAttributeId to check text visibility.
GetAttributeValue(attr) {
local val
return (ComCall(9, this, "int", attr, "ptr", val := UIA.ComVar()), val[])
}
; Retrieves a collection of bounding rectangles for each fully or partially visible line of text in a text range.
GetBoundingRectangles() {
ComCall(10, this, "ptr*", &boundingRects := 0)
DllCall("oleaut32\SafeArrayGetVartype", "ptr", boundingRects, "ushort*", &baseType:=0)
retArr := [], sa := ComValue(0x2000 | baseType, boundingRects)
Loop sa.MaxIndex() / 4 + 1
retArr.Push({x:Floor(sa[4*(A_Index-1)]),y:Floor(sa[4*(A_Index-1)+1]),w:Floor(sa[4*(A_Index-1)+2]),h:Floor(sa[4*(A_Index-1)+3])})
return retArr
}
; Returns the innermost UI Automation element that encloses the text range.
GetEnclosingElement() {
local enclosingElement
if (ComCall(11, this, "ptr*", &enclosingElement := 0), enclosingElement)
return UIA.IUIAutomationElement(enclosingElement)
throw UnsetError("No element returned by " A_ThisFunc, -1)
}
; Returns the plain text of the text range.
GetText(maxLength := -1) {
local text
return (ComCall(12, this, "int", maxLength, "ptr*", &text := 0), UIA.BSTR(text))
}
; Moves the text range forward or backward by the specified number of text units.
; unit must be one of UIA.TextUnit values: Character, Format, Word, Line, Paragraph, Page, Document.
Move(unit, count) {
local moved
return (ComCall(13, this, "int", UIA.TypeValidation.TextUnit(unit), "int", count, "int*", &moved := 0), moved)
}
; Moves one endpoint of the text range the specified number of text units within the document range.
; unit must be one of UIA.TextUnit values: Character, Format, Word, Line, Paragraph, Page, Document. Default is Document.
; EndPoint must be one of UIA.TextPatternRangeEndpoint values: Start, End
MoveEndpointByUnit(endpoint, unit, count) {
local moved
return (ComCall(14, this, "int", UIA.TypeValidation.TextPatternRangeEndpoint(endpoint), "int", UIA.TypeValidation.TextUnit(unit), "int", count, "int*", &moved := 0), moved)
}
; Moves one endpoint of the current text range to the specified endpoint of a second text range.
; If the endpoint being moved crosses the other endpoint of the same text range, that other endpoint is moved also, resulting in a degenerate (empty) range and ensuring the correct ordering of the endpoints (that is, the start is always less than or equal to the end).
; EndPoint must be one of UIA.TextPatternRangeEndpoint values: Start, End
MoveEndpointByRange(srcEndPoint, range, targetEndPoint) { ; TextPatternRangeEndpoint , IUIAutomationTextRange , TextPatternRangeEndpoint
ComCall(15, this, "int", UIA.TypeValidation.TextPatternRangeEndpoint(srcEndPoint), "ptr", range, "int", UIA.TypeValidation.TextPatternRangeEndpoint(targetEndPoint))
}
; Selects the span of text that corresponds to this text range, and removes any previous selection.
; If the Select method is called on a text range object that represents a degenerate (empty) text range, the text insertion point moves to the starting endpoint of the text range.
Select() => ComCall(16, this)
; Adds the text range to the collection of selected text ranges in a control that supports multiple, disjoint spans of selected text.
; The text insertion point moves to the newly selected text. If AddToSelection is called on a text range object that represents a degenerate (empty) text range, the text insertion point moves to the starting endpoint of the text range.
AddToSelection() => ComCall(17, this)
; Removes the text range from an existing collection of selected text in a text container that supports multiple, disjoint selections.
; The text insertion point moves to the area of the removed highlight. Providing a degenerate text range also moves the insertion point.
RemoveFromSelection() => ComCall(18, this)
; Causes the text control to scroll until the text range is visible in the viewport.
; The method respects both hidden and visible text. If the text range is hidden, the text control will scroll only if the hidden text has an anchor in the viewport.
; A Microsoft UI Automation client can check text visibility by calling IUIAutomationTextRange,,GetAttributeValue with the attr parameter set to UIA_IsHiddenAttributeId.
ScrollIntoView(alignToTop:=0) => ComCall(19, this, "int", alignToTop)
; Retrieves a collection of all embedded objects that fall within the text range.
GetChildren() {
local children
return (ComCall(20, this, "ptr*", &children := 0), children?UIA.IUIAutomationElementArray(children).ToArray():"")
}
; ---------- TextRange2 ----------
ShowContextMenu() => ComCall(21, this)
; ---------- TextRange3 ----------
GetEnclosingElementBuildCache(cacheRequest) {
local out
if (ComCall(22, this, "ptr", UIA.TypeValidation.CacheRequest(cacheRequest), "ptr*", &out:=0), out)
return UIA.IUIAutomationElement(out)
throw UnsetError("No element returned by " A_ThisFunc, -1)
}
GetChildrenBuildCache(cacheRequest) {
local out
return (ComCall(23, this, "ptr", UIA.TypeValidation.CacheRequest(cacheRequest), "ptr*", &out:=0), out?UIA.IUIAutomationElementArray(out).ToArray():[])
}
GetAttributeValues(attributeIds, attributeIdCount) {
local out
ComCall(24, this, "ptr", ComObjValue(ComObjArray(8, attributeIds*)), "int", attributeIdCount, "ptr*", &out:=UIA.ComVar())
return out[]
}
}
class IUIAutomationTextRangeArray extends UIA.IUIAutomationArray {
; Retrieves the number of text ranges in the collection.
Length {
get {
local length
return (ComCall(3, this, "int*", &length := 0), length)
}
}
; Retrieves a text range from the collection.
GetElement(index) {
local element
if (ComCall(4, this, "int", index, "ptr*", &element := 0), element)
return UIA.IUIAutomationTextRange(element)
throw UnsetError("No TextRange returned by " A_ThisFunc, -1)
}
}
class IUIAutomationTogglePattern extends UIA.IUIAutomationBase {
; Cycles through the toggle states of the control.
; A control cycles through its states in this order, ToggleState_On, ToggleState_Off and, if supported, ToggleState_Indeterminate.
Toggle() => ComCall(3, this)
; Retrieves the state of the control.
ToggleState {
get {
local retVal
return (ComCall(4, this, "int*", &retVal := 0), retVal)
}
set {
if (this.ToggleState != value)
this.Toggle()
}
}
; Retrieves the cached state of the control.
CachedToggleState {
get {
local retVal
return (ComCall(5, this, "int*", &retVal := 0), retVal)
}
}
}
/*
Provides access to a control that can be moved, resized, or rotated.
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationtransformpattern
*/
class IUIAutomationTransformPattern extends UIA.IUIAutomationBase {
; An element cannot be moved, resized or rotated such that its resulting screen location would be completely outside the coordinates of its container and inaccessible to the keyboard or mouse. For example, when a top-level window is moved completely off-screen or a child object is moved outside the boundaries of the container's viewport, the object is placed as close to the requested screen coordinates as possible with the top or left coordinates overridden to be within the container boundaries.
; Moves the UI Automation element.
Move(x, y) => ComCall(3, this, "double", x, "double", y)
; Resizes the UI Automation element.
; When called on a control that supports split panes, this method can have the side effect of resizing other contiguous panes.
Resize(width, height) => ComCall(4, this, "double", width, "double", height)
; Rotates the UI Automation element.
Rotate(degrees) => ComCall(5, this, "double", degrees)
; Indicates whether the element can be moved.
CanMove {
get {
local retVal
return (ComCall(6, this, "int*", &retVal := 0), retVal)
}
}
; Indicates whether the element can be resized.
CanResize {
get {
local retVal
return (ComCall(7, this, "int*", &retVal := 0), retVal)
}
}
; Indicates whether the element can be rotated.
CanRotate {
get {
local retVal
return (ComCall(8, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves a cached value that indicates whether the element can be moved.
CachedCanMove {
get {
local retVal
return (ComCall(9, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves a cached value that indicates whether the element can be resized.
CachedCanResize {
get {
local retVal
return (ComCall(10, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves a cached value that indicates whether the element can be rotated.
CachedCanRotate {
get {
local retVal
return (ComCall(11, this, "int*", &retVal := 0), retVal)
}
}
; --------------- TransformPattern2 ---------------
CanZoom {
get {
local retVal
return (ComCall(14, this, "int*", &retVal := 0), retVal)
}
}
CachedCanZoom {
get {
local retVal
return (ComCall(15, this, "int*", &retVal := 0), retVal)
}
}
ZoomLevel {
get {
local retVal
return (ComCall(16, this, "double*", &retVal := 0), retVal)
}
}
CachedZoomLevel {
get {
local retVal
return (ComCall(17, this, "double*", &retVal := 0), retVal)
}
}
ZoomMinimum {
get {
local retVal
return (ComCall(18, this, "double*", &retVal := 0), retVal)
}
}
CachedZoomMinimum {
get {
local retVal
return (ComCall(19, this, "double*", &retVal := 0), retVal)
}
}
ZoomMaximum {
get {
local retVal
return (ComCall(20, this, "double*", &retVal := 0), retVal)
}
}
CachedZoomMaximum {
get {
local retVal
return (ComCall(21, this, "double*", &retVal := 0), retVal)
}
}
Zoom(zoomValue) => ComCall(12, this, "double", zoomValue)
ZoomByUnit(ZoomUnit) => ComCall(13, this, "uint", ZoomUnit)
}
class IUIAutomationValuePattern extends UIA.IUIAutomationBase {
; Sets the value of the element.
; The IsEnabled property must be TRUE, and the IUIAutomationValuePattern,,IsReadOnly property must be FALSE.
SetValue(val) => ComCall(3, this, "wstr", val)
; Retrieves the value of the element.
; Single-line edit controls support programmatic access to their contents through IUIAutomationValuePattern. However, multiline edit controls do not support this control pattern, and their contents must be retrieved by using IUIAutomationTextPattern.
; This property does not support the retrieval of formatting information or substring values. IUIAutomationTextPattern must be used in these scenarios as well.
Value {
get {
local retVal
return (ComCall(4, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
set => ComCall(3, this, "wstr", value)
}
; Indicates whether the value of the element is read-only.
IsReadOnly {
get {
local retVal
return (ComCall(5, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the cached value of the element.
CachedValue {
get {
local retVal
return (ComCall(6, this, "ptr*", &retVal := 0), UIA.BSTR(retVal))
}
}
; Retrieves a cached value that indicates whether the value of the element is read-only.
; This property must be TRUE for IUIAutomationValuePattern,,SetValue to succeed.
CachedIsReadOnly {
get {
local retVal
return (ComCall(7, this, "int*", &retVal := 0), retVal)
}
}
}
/*
Represents a virtualized item, which is an item that is represented by a placeholder automation element in the Microsoft UI Automation tree.
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationvirtualizeditempattern
*/
class IUIAutomationVirtualizedItemPattern extends UIA.IUIAutomationBase {
; Creates a full UI Automation element for a virtualized item.
; A virtualized item is represented by a placeholder automation element in the UI Automation tree. The Realize method causes the provider to make full information available for the item so that a full UI Automation element can be created for the item.
Realize() => ComCall(3, this)
}
/*
Provides access to the fundamental functionality of a window.
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationwindowpattern
*/
class IUIAutomationWindowPattern extends UIA.IUIAutomationBase {
; Closes the window.
; When called on a split pane control, this method closes the pane and removes the associated split. This method may also close all other panes, depending on implementation.
Close() => ComCall(3, this)
; Causes the calling code to block for the specified time or until the associated process enters an idle state, whichever completes first.
WaitForInputIdle(milliseconds) {
local success
return (ComCall(4, this, "int", milliseconds, "int*", &success := 0), success)
}
; Minimizes, maximizes, or restores the window.
SetWindowVisualState(state) => ComCall(5, this, "int", state)
; Indicates whether the window can be maximized.
CanMaximize {
get {
local retVal
return (ComCall(6, this, "int*", &retVal := 0), retVal)
}
}
; Indicates whether the window can be minimized.
CanMinimize {
get {
local retVal
return (ComCall(7, this, "int*", &retVal := 0), retVal)
}
}
; Indicates whether the window is modal.
IsModal {
get {
local retVal
return (ComCall(8, this, "int*", &retVal := 0), retVal)
}
}
; Indicates whether the window is the topmost element in the z-order.
IsTopmost {
get {
local retVal
return (ComCall(9, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the visual state of the window; that is, whether it is in the normal, maximized, or minimized state.
WindowVisualState {
get {
local retVal
return (ComCall(10, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves the current state of the window for the purposes of user interaction.
WindowInteractionState {
get {
local retVal
return (ComCall(11, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves a cached value that indicates whether the window can be maximized.
CachedCanMaximize {
get {
local retVal
return (ComCall(12, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves a cached value that indicates whether the window can be minimized.
CachedCanMinimize {
get {
local retVal
return (ComCall(13, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves a cached value that indicates whether the window is modal.
CachedIsModal {
get {
local retVal
return (ComCall(14, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves a cached value that indicates whether the window is the topmost element in the z-order.
CachedIsTopmost {
get {
local retVal
return (ComCall(15, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves a cached value that indicates the visual state of the window; that is, whether it is in the normal, maximized, or minimized state.
CachedWindowVisualState {
get {
local retVal
return (ComCall(16, this, "int*", &retVal := 0), retVal)
}
}
; Retrieves a cached value that indicates the current state of the window for the purposes of user interaction.
CachedWindowInteractionState {
get {
local retVal
return (ComCall(17, this, "int*", &retVal := 0), retVal)
}
}
}
; Internal class: UIAViewer code
class Viewer {
static SettingsFolderPath := A_AppData "\UIAViewer"
static SettingsFilePath := A_AppData "\UIAViewer\settings.ini"
__New() {
local v, pattern, i
OnError this.ErrorHandler.Bind(this)
CoordMode "Mouse", "Screen"
DetectHiddenWindows "On"
this.Stored := {mwId:0, FilteredTreeView:Map(), TreeView:Map(), HighlightedElement:0}
this.Capturing := False, this.MacroSidebarVisible := False, this.MacroSidebarWidth := 350, this.MacroSidebarMinWidth := 290, this.GuiMinWidth := 540, this.GuiMinHeight := 400, this.Focused := 1
this.LoadSettings()
this.cacheRequest := UIA.CreateCacheRequest()
; Don't even get the live element, because we don't need it. Gives a significant speed improvement.
this.cacheRequest.AutomationElementMode := UIA.AutomationElementMode.None
; Set TreeScope to include the starting element and all descendants as well
this.cacheRequest.TreeScope := 5
this.gViewer := Gui((this.AlwaysOnTop ? "AlwaysOnTop " : "") "Resize +MinSize" this.GuiMinWidth "x" this.GuiMinHeight, "UIAViewer")
this.gViewer.OnEvent("Close", this.gViewer_Close.Bind(this))
this.gViewer.OnEvent("Size", this.gViewer_Size.Bind(this))
(this.TextLVWin := this.gViewer.Add("Text", "w250", "Window Info")).SetFont("bold")
this.LVWin := this.gViewer.Add("ListView", "h135 w250", ["Property", "Value"])
this.LVWin.OnEvent("ContextMenu", LV_CopyTextMethod := this.LV_CopyText.Bind(this))
this.LVWin.ModifyCol(1,60)
this.LVWin.ModifyCol(2,180)
for v in ["Title", "Text", "Id", "Location", "Class(NN)", "Process", "PID"]
this.LVWin.Add(,v,"")
this.gViewer.Add("Text", "w100", "Properties").SetFont("bold")
this.LVProps := this.gViewer.Add("ListView", "h200 w250", ["Property", "Value"])
this.LVProps.OnEvent("ContextMenu", LV_CopyTextMethod)
this.LVProps.ModifyCol(1,100)
this.LVProps.ModifyCol(2,140)
this.DisplayedProps := ["Type", "LocalizedType", "Name", "Value", "AutomationId", "BoundingRectangle", "ClassName", "FullDescription", "HelpText", "AccessKey", "AcceleratorKey", "HasKeyboardFocus", "IsKeyboardFocusable", "ItemType", "ProcessId", "IsEnabled", "IsPassword", "IsOffscreen", "FrameworkId", "IsRequiredForForm", "ItemStatus", "RuntimeId"]
Loop DisplayedPropsLength := this.DisplayedProps.Length {
v := this.DisplayedProps[i := DisplayedPropsLength-A_Index+1]
try this.cacheRequest.AddProperty(v) ; Throws if not available,
catch
this.DisplayedProps.RemoveAt(i) ; Remove property if it is not available
}
for v in this.DisplayedProps
this.LVProps.Add(,v = "BoundingRectangle" ? "Location" : v,"")
for pattern in [UIA.Property.OwnProps()*] {
if pattern ~= "Is([\w]+Pattern.?)Available"
try this.cacheRequest.AddProperty(UIA.Property.%pattern%)
catch
UIA.Property.DeleteProp(pattern) ; Remove pattern if it is not available
}
(this.TextTVPatterns := this.gViewer.Add("Text", "w100 r1", "Patterns")).SetFont("bold")
this.TVPatterns := this.gViewer.Add("TreeView", "h85 w250")
this.TVPatterns.OnEvent("DoubleClick", this.TVPatterns_DoubleClick.Bind(this))
this.ButCapture := this.gViewer.Add("Button", "xp+60 y+10 w130", "Start capturing (Alt+S)")
this.ButCapture.OnEvent("Click", this.CaptureHotkeyFunc := this.ButCapture_Click.Bind(this))
HotKey("!s", this.CaptureHotkeyFunc)
this.SBMain := this.gViewer.Add("StatusBar",, " Start capturing, then hold cursor still to construct tree")
this.SBMain.OnEvent("Click", this.SBMain_Click.Bind(this))
this.SBMain.OnEvent("ContextMenu", this.SBMain_ContextMenu.Bind(this))
(this.TextTVUIA := this.gViewer.Add("Text", "x278 y10 w600 r1", "UIA Tree")).SetFont("bold")
this.TVUIA := this.gViewer.Add("TreeView", "x275 y25 w300 h465")
this.TVUIA.OnEvent("Click", this.TVUIA_Click.Bind(this))
this.TVUIA.OnEvent("ContextMenu", this.TVUIA_ContextMenu.Bind(this))
this.TVUIA.Add("Start capturing to show tree")
this.TextFilterTVUIA := this.gViewer.Add("Text", "x275 y503", "&Filter:")
this.EditFilterTVUIA := this.gViewer.Add("Edit", "x305 y500 w100")
this.EditFilterTVUIA.OnEvent("Change", this.EditFilterTVUIA_Change.Bind(this))
this.GroupBoxMacro := this.gViewer.Add("GroupBox", "x900 y20 w" (this.MacroSidebarWidth-20), "Macro creator")
(this.TextMacroAction := this.gViewer.Add("Text", "x900 y40 w40", "Action:")).SetFont("bold")
this.DDLMacroAction := this.gViewer.Add("DDL", "Choose1 x900 y38 w120", ["No element selected"])
(this.ButMacroAddElement := this.gViewer.Add("Button","x900 y37 w90 h20", "&Add element")).SetFont("bold")
this.ButMacroAddElement.OnEvent("Click", this.ButMacroAddElement_Click.Bind(this))
(this.EditMacroScript := this.gViewer.Add("Edit", "-Wrap HScroll x900 y65 h410 w" (this.MacroSidebarWidth-40), "#include UIA.ahk`n`n")).SetFont("s10") ; Setting a font here disables UTF-8-BOM
(this.ButMacroScriptRun := this.gViewer.Add("Button", "x880 y120 w70", "&Test script")).SetFont("bold")
this.ButMacroScriptRun.OnEvent("Click", this.ButMacroScriptRun_Click.Bind(this))
this.ButMacroScriptCopy := this.gViewer.Add("Button", "x920 y120 w70", "&Copy")
this.ButMacroScriptCopy.OnEvent("Click", (*) => (A_Clipboard := this.EditMacroScript.Text, ToolTip("Macro code copied to Clipboard!"), SetTimer(ToolTip, -3000)))
this.ButToggleMacroSidebar := this.gViewer.Add("Button", "x490 y500 w120", "Show macro &sidebar =>")
this.ButToggleMacroSidebar.OnEvent("Click", this.ButToggleMacroSidebar_Click.Bind(this))
xy := ""
if this.RememberGuiPosition {
xy := StrSplit(this.RememberGuiPosition, ","), monitor := 0
Loop MonitorGetCount() {
MonitorGetWorkArea(A_Index, &Left, &Top, &Right, &Bottom)
if xy[1] > (Left-50) && xy[2] > (Top-50) && xy[1] < (Right-50) && xy[2] < (Bottom-30) {
monitor := A_Index
break
}
}
xy := monitor ? "x" xy[1] " y" xy[2] " " : ""
}
this.gViewer.Show(xy "w600 h550")
this.gViewer_Size(this.gViewer,0,600,550)
this.FocusHook := DllCall("SetWinEventHook", "UInt", 0x8005, "UInt", 0x8005, "Ptr",0,"Ptr", CallbackCreate(this.HandleFocusChangedEvent.Bind(this), "C", 7),"UInt", 0, "UInt",0, "UInt",0)
}
__Delete() {
DllCall("UnhookWinEvent", "Ptr", this.FocusHook)
}
HandleFocusChangedEvent(hWinEventHook, Event, hWnd, idObject, idChild, dwEventThread, dwmsEventTime) => SetTimer(this._HandleFocusChangedEvent.Bind(this, hWnd), -1)
_HandleFocusChangedEvent(hWnd) {
winHwnd := DllCall("GetAncestor", "Ptr", hWnd, "UInt", 2, "Ptr")
if winHwnd = this.gViewer.Hwnd {
if !this.Focused {
this.Focused := 1
if IsObject(this.Stored.HighlightedElement)
this.Stored.HighlightedElement.Highlight(0, "Blue", 4)
}
} else {
if this.Focused {
this.Focused := 0
if IsObject(this.Stored.HighlightedElement)
this.Stored.HighlightedElement.Highlight("clear")
}
}
if this.Capturing && this.Stored.HasOwnProp("CapturedWindowBuildUpdatedCache")
SetTimer(this.Stored.CapturedWindowBuildUpdatedCache, -2000)
return 0
}
SaveSettings() {
if !FileExist(A_AppData "\UIAViewer")
DirCreate(A_AppData "\UIAViewer")
IniWrite(this.PathIgnoreNames, UIA.Viewer.SettingsFilePath, "Path", "IgnoreNames")
IniWrite(this.PathType, UIA.Viewer.SettingsFilePath, "Path", "Type")
IniWrite(this.AlwaysOnTop, UIA.Viewer.SettingsFilePath, "General", "AlwaysOnTop")
IniWrite(this.DPIAwareness, UIA.Viewer.SettingsFilePath, "General", "DPIAwareness")
IniWrite(this.RememberGuiPosition, UIA.Viewer.SettingsFilePath, "General", "RememberGuiPosition")
}
LoadSettings() {
this.PathIgnoreNames := IniRead(UIA.Viewer.SettingsFilePath, "Path", "IgnoreNames", 1)
this.PathType := IniRead(UIA.Viewer.SettingsFilePath, "Path", "Type", "")
this.AlwaysOnTop := IniRead(UIA.Viewer.SettingsFilePath, "General", "AlwaysOnTop", 1)
this.DPIAwareness := IniRead(UIA.Viewer.SettingsFilePath, "General", "DPIAwareness", 0)
this.RememberGuiPosition := IniRead(UIA.Viewer.SettingsFilePath, "General", "RememberGuiPosition", "")
}
ErrorHandler(Exception, Mode) => (OutputDebug(Format("{1} ({2}) : ({3}) {4}`n", Exception.File, Exception.Line, Exception.What, Exception.Message) (HasProp(Exception, "Extra") ? " Specifically: " Exception.Extra "`n" : "") "Stack:`n" Exception.Stack "`n`n"), 1)
gViewer_Close(GuiObj, *) {
local X, Y
if this.RememberGuiPosition {
WinGetPos(&X, &Y,,,GuiObj.Hwnd), this.RememberGuiPosition := X "," Y, this.SaveSettings()
}
ExitApp()
}
; Resizes window controls when window is resized
gViewer_Size(GuiObj, MinMax, Width, Height) {
static RedrawFunc := WinRedraw.Bind(GuiObj.Hwnd)
this.TVUIA.GetPos(&TV_Pos_X, &TV_Pos_Y, &TV_Pos_W, &TV_Pos_H)
this.MoveControls(this.MacroSidebarVisible ? {Control:this.TVUIA,h:(TV_Pos_H:=Height-TV_Pos_Y-60)} : {Control:this.TVUIA,w:(TV_Pos_W:=Width-TV_Pos_X-10),h:(TV_Pos_H:=Height-TV_Pos_Y-60)})
TV_Pos_R := TV_Pos_X+TV_Pos_W
this.LVProps.GetPos(&LVPropsX, &LVPropsY, &LVPropsWidth, &LVPropsHeight)
this.ButToggleMacroSidebar.GetPos(,,&ButToggleMacroSidebarW)
this.MoveControls(
{Control:this.TextFilterTVUIA, x:TV_Pos_X, y:Height-47},
{Control:this.ButToggleMacroSidebar, x:TV_Pos_X+TV_Pos_W-ButToggleMacroSidebarW, y:Height-50},
{Control:this.EditFilterTVUIA, x:TV_Pos_X+30, y:Height-50},
{Control:this.LVProps,h:Height-LVPropsY-170},
{Control:this.TextTVPatterns,y:Height-165},
{Control:this.TVPatterns,y:Height-145},
{Control:this.ButCapture,y:Height-50})
if this.MacroSidebarVisible
this.MacroSidebarWidth := Width-(TV_Pos_X+TV_Pos_W)-10
this.MoveControls(
{Control:this.GroupBoxMacro,x:TV_Pos_R+15, w:Width-TV_Pos_R-30, h:TV_Pos_H+35},
{Control:this.TextMacroAction,x:TV_Pos_R+25},
{Control:this.DDLMacroAction,x:TV_Pos_R+70},
{Control:this.ButMacroAddElement,x:TV_Pos_R+this.MacroSidebarWidth-105},
{Control:this.EditMacroScript,x:TV_Pos_R+25,w:Width-TV_Pos_R-50,h:TV_Pos_H-50},
{Control:this.ButMacroScriptRun,x:TV_Pos_R+85,y:TV_Pos_Y+TV_Pos_H-2},
{Control:this.ButMacroScriptCopy,x:TV_Pos_R+this.MacroSidebarWidth-145,y:TV_Pos_Y+TV_Pos_H-2})
DllCall("RedrawWindow", "ptr", GuiObj.Hwnd, "ptr", 0, "ptr", 0, "uint", 0x0081) ; Reduces flicker compared to RedrawFunc
}
MoveControls(ctrls*) {
local ctrl
for ctrl in ctrls
ctrl.Control.Move(ctrl.HasOwnProp("x") ? ctrl.x : unset, ctrl.HasOwnProp("y") ? ctrl.y : unset, ctrl.HasOwnProp("w") ? ctrl.w : unset, ctrl.HasOwnProp("h") ? ctrl.h : unset)
}
; Show/hide macros sidebar
ButToggleMacroSidebar_Click(GuiCtrlObj?, Info?) {
local w
this.MacroSidebarVisible := !this.MacroSidebarVisible
GuiCtrlObj.Text := this.MacroSidebarVisible ? "Hide macro &sidebar <=" : "Show macro &sidebar =>"
this.gViewer.GetPos(,, &w)
this.gViewer.Opt("+MinSize" (this.MacroSidebarVisible ? w + this.MacroSidebarMinWidth : this.GuiMinWidth) "x" this.GuiMinHeight)
this.gViewer.Move(,,w+(this.MacroSidebarVisible ? this.MacroSidebarWidth : -this.MacroSidebarWidth))
}
; Handles adding elements with actions to the macro Edit
ButMacroAddElement_Click(GuiCtrlObj?, Info?) {
local match, selectedElPath, winElVariable, winElText, processName
if !this.Stored.HasOwnProp("CapturedElement")
return
processName := WinGetProcessName(this.Stored.mwId)
winElVariable := RegExMatch(processName, "^[^ .\d]+", &match:="") ? RegExReplace(match[], "[^\p{L}0-9_#@$]") "El" : "winEl" ; Leaves only letters, numbers, and symbols _#@$ (allowed AHK characters)
winElText := winElVariable " := UIA.ElementFrom" (InStr(this.TextTVUIA.Text, "Chromium") ? "Chromium" : "Handle") "(`"" WinGetTitle(this.Stored.mwId) " ahk_exe " processName "`")"
if !InStr(this.EditMacroScript.Text, winElText) || RegExMatch(this.EditMacroScript.Text, "\Q" winElText "\E(?=[\w\W]*\QwinEl := UIA.ElementFromHandle(`"ahk_exe\E)")
this.EditMacroScript.Text := RTrim(this.EditMacroScript.Text, "`r`n`t ") "`r`n`r`n" winElText
else
this.EditMacroScript.Text := RTrim(this.EditMacroScript.Text, "`r`n`t ")
selectedElPath := SubStr(this.SBMain.Text, 9)
winElVariable := winElVariable (selectedElPath && StrLen(selectedElPath) > 2 ? ".ElementFromPath(" selectedElPath ")" : "") (this.DDLMacroAction.Text ? "." this.DDLMacroAction.Text : "")
if InStr(this.DDLMacroAction.Text, "Dump")
winElVariable := "MsgBox(" winElVariable ")"
this.EditMacroScript.Text := this.EditMacroScript.Text "`r`n" RegExReplace(winElVariable, "(? GuiCtrlObj.GetCount()
? ListViewGetContent("", GuiCtrlObj)
: ListViewGetContent("Selected", GuiCtrlObj)
for LVData in StrSplit(LVData, "`n") {
LVData := StrSplit(LVData, "`t",,2)
if LVData.Length < 2
continue
switch LVData[1], 0 {
case "Type":
LVData[2] := "`"" RTrim(SubStr(LVData[2],8), ")") "`""
case "Location":
LVData[2] := "{" RegExReplace(LVData[2], "(\w:) (\d+)(?= )", "$1$2,") "}"
case "RuntimeId":
LVData[2] := "`"" LVData[2] "`""
}
Property := -1
try Property := UIA.Property.%LVData[1]%
out .= ", " (GuiCtrlObj.Hwnd = this.LVWin.Hwnd ? "" : LVData[1] ":") (UIA.PropertyVariantTypeBSTR.Has(Property) ? "`"" StrReplace(StrReplace(LVData[2], "``", "````"), "`"", "```"") "`"" : LVData[2])
}
ToolTip("Copied: " (A_Clipboard := SubStr(out, 3)))
SetTimer(ToolTip, -3000)
}
; Handles running pattern methods, first trying to find the live element by RuntimeId
TVPatterns_DoubleClick(GuiCtrlObj, Info) {
if !Info
return
Item := GuiCtrlObj.GetText(Info)
if !InStr(Item, "()")
return
Item := SubStr(Item, 1, -2)
if !WinExist(this.Stored.mwId) || !(WinEl := UIA.ElementFromHandle(this.Stored.mwId))
return MsgBox("Target window not found!",,"4096")
if !(CurrentEl := WinEl.ElementExist({RuntimeId:this.Stored.CapturedElement.CachedRuntimeId}, 5))
&& !(CurrentEl := WinEl.ElementFromPathExist(Trim(this.Stored.CapturedElement.Path, "```"")))
return MsgBox("Live element not found!",,"4096")
if Item ~= "Value|Scroll(?!Into)" {
this.gViewer.Opt("-AlwaysOnTop")
Ret := InputBox("Insert value", Item, "W200 H120")
this.gViewer.Opt("+AlwaysOnTop")
if Ret.Result != "OK"
return
}
WinActivate(this.Stored.mwId)
WinWaitActive(this.Stored.mwId)
try CurrentEl.%GuiCtrlObj.GetText(GuiCtrlObj.GetParent(Info)) "Pattern"%.%Item%(IsSet(Ret) ? Ret.Value : unset)
}
; Copies the UIA path to clipboard when statusbar is clicked
SBMain_Click(GuiCtrlObj, Info, *) {
if InStr(this.SBMain.Text, "Path:") {
ToolTip("Copied: " (A_Clipboard := SubStr(this.SBMain.Text, 9)))
SetTimer(ToolTip, -3000)
}
}
; StatusBar context menu creation
SBMain_ContextMenu(GuiCtrlObj, Item, IsRightClick, X, Y) {
SBMain_Menu := Menu()
if InStr(this.SBMain.Text, "Path:") {
SBMain_Menu.Add("Copy UIA path", (*) => (ToolTip("Copied: " (A_Clipboard := this.Stored.CapturedElement.Path)), SetTimer(ToolTip, -3000)))
SBMain_Menu.Add("Copy condition path", (*) => (ToolTip("Copied: " (A_Clipboard := this.Stored.CapturedElement.ConditionPath)), SetTimer(ToolTip, -3000)))
SBMain_Menu.Add("Copy numeric path", (*) => (ToolTip("Copied: " (A_Clipboard := this.Stored.CapturedElement.NumericPath)), SetTimer(ToolTip, -3000)))
SBMain_Menu.Add()
}
SBMain_Menu.Add("Display UIA path (relatively reliable, shortest)", (*) => (this.PathType := this.PathType = "" ? "" : "", this.Stored.HasOwnProp("CapturedElement") && this.Stored.CapturedElement.HasOwnProp("Path") ? this.SBMain.SetText(" Path: " (this.PathType = "Numeric" ? this.Stored.CapturedElement.NumericPath : this.Stored.CapturedElement.Path)) : 1))
SBMain_Menu.Add("Display numeric path (least reliable, short)", (*) => (this.PathType := this.PathType = "Numeric" ? "" : "Numeric", this.Stored.HasOwnProp("CapturedElement") && this.Stored.CapturedElement.HasOwnProp("Path") ? this.SBMain.SetText(" Path: " (this.PathType = "Numeric" ? this.Stored.CapturedElement.NumericPath : this.Stored.CapturedElement.Path)) : 1))
SBMain_Menu.Add("Display condition path (most reliable, longest)", (*) => (this.PathType := this.PathType = "Condition" ? "" : "Condition", this.Stored.HasOwnProp("CapturedElement") && this.Stored.CapturedElement.HasOwnProp("Path") ? this.SBMain.SetText(" Path: " (this.PathType = "Condition" ? this.Stored.CapturedElement.ConditionPath : this.Stored.CapturedElement.Path)) : 1))
SBMain_Menu.Add("Ignore Name properties in condition path", (*) => (this.PathIgnoreNames := !this.PathIgnoreNames))
if this.PathIgnoreNames
SBMain_Menu.Check("Ignore Name properties in condition path")
if this.PathType = ""
SBMain_Menu.Check("Display UIA path (relatively reliable, shortest)")
if this.PathType = "Numeric"
SBMain_Menu.Check("Display numeric path (least reliable, short)")
if this.PathType = "Condition"
SBMain_Menu.Check("Display condition path (most reliable, longest)")
SBMain_Menu.Add()
SBMain_Menu.Add("UIAViewer always on top", (*) => (this.AlwaysOnTop := !this.AlwaysOnTop, this.gViewer.Opt((this.AlwaysOnTop ? "+" : "-") "AlwaysOnTop")))
if this.AlwaysOnTop
SBMain_Menu.Check("UIAViewer always on top")
SBMain_Menu.Add("Remember UIAViewer position", (*) => (this.RememberGuiPosition := !this.RememberGuiPosition, this.SaveSettings()))
if this.RememberGuiPosition
SBMain_Menu.Check("Remember UIAViewer position")
SBMain_Menu.Add("Enable DPI awareness", (*) => (this.DPIAwareness := !this.DPIAwareness, this.DPIAwareness ? UIA.SetMaximumDPIAwareness() : UIA.DPIAwareness := -2))
if this.DPIAwareness
SBMain_Menu.Check("Enable DPI awareness")
SBMain_Menu.Add()
SBMain_Menu.Add("Save settings", (*) => (this.SaveSettings(), ToolTip("Settings saved!"), SetTimer(ToolTip, -2000)))
SBMain_Menu.Show()
}
; Stops capturing elements under mouse, unhooks CaptureCallback
StopCapture(GuiCtrlObj:=0, Info:=0) {
if this.Capturing {
this.Capturing := False
SetTimer(this.CaptureCallback, 0)
SetTimer(this.Stored.CapturedWindowBuildUpdatedCache, 0)
this.ButCapture.Text := "Start capturing (Alt+S)"
if IsObject(this.Stored.HighlightedElement)
this.Stored.HighlightedElement.Highlight("clear")
}
}
; Gets UIA element under mouse, updates the GUI.
; If the mouse is not moved for 1 second then constructs the UIA tree.
CaptureCycle() {
local clientX:=0, clientY:=0, clientW:=0, clientH:=0, mX, mY, mwId, mwCtrl, elBr, same, propsOrder
, mwX, mwY, mwW, mwH
SetTimer(this.CaptureCallback, -3000) ; In case of an error try again in 3 seconds
CoordMode "Mouse", "Screen"
MouseGetPos(&mX, &mY, &mwId := 0, &mwCtrl := 0, 2)
; If is a Chromium window then also get the control, because some Chromium windows don't show content from main window
; Also activate accessibility, afterwards don't activate anymore
try {
mwCtrl := ControlGetHwnd("Chrome_RenderWidgetHostHWND1", mwId)
UIA.ActivateChromiumAccessibility(mwId)
}
; If the control was considered the window, assume that this is still needed
if mwCtrl && mwCtrl = this.Stored.mwId
mwId := mwCtrl
CapturedElement := this.TryUpdateElementVariables(mwId, mX, mY)
; If ctrl and main window aren't the same, then compare their sizes. If sizes are the same
; then instead try to get the element from the control under the mouse (eg Chromium content)
if mwCtrl && mwId != mwCtrl && this.Stored.mwId != mwCtrl && CapturedElement {
try WinGetClientPos(&clientX, &clientY, &clientW, &clientH, mwId)
elBr := CapturedElement.CachedBoundingRectangle, winBr := this.Stored.CapturedWindow.CachedBoundingRectangle
; If element size is equal to window/client size, then probably it's not accessible through the window
; Instead try to get the content through the control under the cursor
if Abs(elBr.l - winBr.l + elbr.t - winBr.t + elBr.r - winBr.r + elBr.b - winBr.b) < 4
|| Abs(elBr.l - clientX + elBr.t - clientY + elBr.r - (clientX+clientW) + elBr.b - (clientY+clientH)) < 4 {
CapturedElementCtrl := this.TryUpdateElementVariables(mwCtrl, mX, mY)
if CapturedElementCtrl {
clsNN := ControlGetClassNN(mwCtrl, mwId), CapturedElement := CapturedElementCtrl, mwId := mwCtrl
this.TextLVWin.Text := "Control Info for " (clsNN = "Chrome_RenderWidgetHostHWND1" ? "Chromium" : clsNN " Control")
this.TextTVUIA.Text := "UIA Tree for " (clsNN = "Chrome_RenderWidgetHostHWND1" ? "Chromium (" clsNN ")" : clsNN)
}
}
}
if this.Capturing
SetTimer(this.CaptureCallback, 200)
if !CapturedElement
return
if this.Stored.HasOwnProp("CapturedElement") && IsObject(CapturedElement) {
try same := UIA.CompareElementsEx(CapturedElement, this.Stored.CapturedElement) ; UIA.CompareElements(CapturedElement, this.Stored.CapturedElement) ; Cached element RuntimeIds sometimes cause an error here
if same ?? 0 {
if this.FoundTime != 0 && ((A_TickCount - this.FoundTime) > 500) {
if (mX == this.Stored.mX) && (mY == this.Stored.mY) {
if !(this.Stored.HasOwnProp("TreeViewWindow") && UIA.CompareElementsEx(this.Stored.CapturedWindow, this.Stored.TreeViewWindow))
|| !this.TreeViewSelectCapturedElement()
this.ConstructTreeView()
this.FoundTime := 0
} else
this.FoundTime := A_TickCount
}
this.Stored.mX := mX, this.Stored.mY := mY
return
}
}
this.LVWin.Delete()
try WinGetPos(&mwX, &mwY, &mwW, &mwH, mwId)
catch
return
this.Stored.mwId := mwId, this.Stored.CapturedElement := CapturedElement, this.Stored.mX := mX, this.Stored.mY := mY, this.FoundTime := A_TickCount
propsOrder := ["Title", "Text", "Id", "Location", "Class(NN)", "Process", "PID"]
prop := Map("Title", WinGetTitle(mwId), "Text", WinGetText(mwId), "Id", mwId, "Location", "x: " mwX " y: " mwY " w: " mwW " h: " mwH, "Class(NN)", WinGetClass(mwId), "Process", WinGetProcessName(mwId), "PID", WinGetPID(mwId))
for propName in propsOrder
this.LVWin.Add(,propName,prop[propName])
this.PopulatePropsPatterns(CapturedElement)
}
; Updates this.Stored.CapturedWindowLive, this.Stored.CapturedWindow, this.Stored.CapturedWindowBuildUpdatedCache, returns CapturedElement
; Also removes and adds back the StructureChangedEventHandler
TryUpdateElementVariables(mwId, mX, mY) {
if mwId != this.Stored.mwId {
if UIA.ProcessIsElevated(WinGetPID(mwId)) > 0 && !A_IsAdmin {
if MsgBox("The inspected window is running with elevated privileges.`nUIAViewer must be running in UIAccess mode or as administrator to inspect it.`n`nRun UIAViewer as administrator to inspect it?",, 0x1000 | 0x30 | 0x4) = "Yes" {
try {
Run('*RunAs "' (A_IsCompiled ? A_ScriptFullPath '" /restart' : A_AhkPath '" /restart "' A_ScriptFullPath '"'))
ExitApp
}
}
}
this.TextLVWin.Text := "Window Info", this.TextTVUIA.Text := "UIA Tree"
this.UpdateCapturedWindowCache(mwId)
}
try return CapturedElement := UIA.CachedSmallestElementInElementContainingPoint(mX, mY, this.Stored.CapturedWindow)
}
UpdateCapturedWindowCache(mwId?) {
SetTimer(this.Stored.CapturedWindowBuildUpdatedCache, 0)
if !WinExist(mwId ?? this.Stored.mwId)
return
this.Stored.CapturedWindowLive := UIA.ElementFromHandle(mwId ?? this.Stored.mwId,,false)
this.Stored.CapturedWindow := this.Stored.CapturedWindowLive.BuildUpdatedCache(this.CacheRequest)
}
; Populates the listview with UIA element properties
PopulatePropsPatterns(Element) {
local v, value, pattern, parent, proto, match, X, Y, W, H, name, prop
if IsObject(this.Stored.HighlightedElement)
this.Stored.HighlightedElement.Highlight("clear")
this.Stored.HighlightedElement := Element
try { ; Show the Highlight only if the window is visible and
WinGetPos(&X, &Y, &W, &H, this.Stored.mwId)
if IsObject(this.Stored.HighlightedElement) && (elBR := this.Stored.HighlightedElement.CachedBoundingRectangle) && UIA.IntersectRect(X, Y, X+W, Y+H, elBR.l, elBR.t, elBR.r, elBR.b)
Element.Highlight(0, "Blue", 4) ; Indefinite show
}
this.LVProps.Delete()
this.TVPatterns.Delete()
for v in this.DisplayedProps {
try prop := Element.Cached%v%
switch v, 0 {
case "Type":
try name := UIA.Type[prop]
catch
name := "Unknown"
try this.LVProps.Add(, v, prop " (" name ")")
case "BoundingRectangle":
prop := prop ? prop : {l:0,t:0,r:0,b:0}
try this.LVProps.Add(, "Location", "x: " prop.l " y: " prop.t " w: " (prop.r - prop.l) " h: " (prop.b - prop.t))
case "RuntimeId":
try this.LVProps.Add(, v, prop)
default:
try this.LVProps.Add(, v, prop)
}
prop := ""
}
lastAction := this.DDLMacroAction.Text
this.DDLMacroAction.Delete()
this.DDLMacroAction.Add(['', 'Click()', 'Click("left")', 'ControlClick()', 'SetFocus()', 'ShowContextMenu()', 'Highlight()', 'Dump()','DumpAll()'])
for pattern, value in UIA.Property.OwnProps() {
if RegExMatch(pattern, "Is([\w]+)Pattern(\d?)Available", &match:=0) && Element.GetCachedPropertyValue(value) {
parent := this.TVPatterns.Add(match[1] (match.Count > 1 ? match[2] : ""))
if !IsObject(UIA.IUIAutomation%match[1]%Pattern)
continue
proto := UIA.IUIAutomation%match[1]%Pattern.Prototype
switch match[1], 0 {
case "Invoke":
this.DDLMacroAction.Add(['Invoke()'])
case "ExpandCollapse":
this.DDLMacroAction.Add(['Expand()', 'Collapse()'])
case "Value":
this.DDLMacroAction.Add(['Value := "value"'])
case "Toggle":
this.DDLMacroAction.Add(['Toggle()'])
case "SelectionItem":
this.DDLMacroAction.Add(['Select()', 'AddToSelection()', 'RemoveFromSelection()'])
case "ScrollItem":
this.DDLMacroAction.Add(['ScrollIntoView()'])
}
for name in proto.OwnProps() {
if name ~= "i)^(_|Cached)"
continue
this.TVPatterns.Add(name (proto.GetOwnPropDesc(name).HasOwnProp("call") ? "()" : ""), parent)
}
}
}
try this.DDLMacroAction.Choose(lastAction)
catch
this.DDLMacroAction.Choose(7)
}
; Handles selecting elements in the UIA tree, highlights the selected element
TVUIA_Click(GuiCtrlObj, Info) {
if this.Capturing
return
try Element := this.EditFilterTVUIA.Value ? this.Stored.FilteredTreeView[Info] : this.Stored.TreeView[Info]
if IsSet(Element) && Element {
if IsObject(this.Stored.HighlightedElement) {
if UIA.CompareElementsEx(Element, this.Stored.HighlightedElement)
return (this.Stored.HighlightedElement.Highlight("clear"), this.Stored.HighlightedElement := 0)
}
this.Stored.CapturedElement := Element
try this.SBMain.SetText(" Path: " (this.PathType = "Numeric" ? Element.NumericPath : this.PathType = "Condition" ? Element.ConditionPath : Element.Path))
this.PopulatePropsPatterns(Element)
}
}
; Permits copying the Dump of UIA element(s) to clipboard
TVUIA_ContextMenu(GuiCtrlObj, Item, IsRightClick, X, Y) {
this.TVUIA.Modify(Item, "Select")
this.TVUIA_Click(GuiCtrlObj, Item)
TVUIA_Menu := Menu()
try Element := this.EditFilterTVUIA.Value ? this.Stored.FilteredTreeView[Item] : this.Stored.TreeView[Item]
if IsSet(Element)
TVUIA_Menu.Add("Copy to Clipboard", (*) => (ToolTip("Copied Dump() output to Clipboard!"), A_Clipboard := Element.CachedDump(), SetTimer((*) => ToolTip(), -3000)))
TVUIA_Menu.Add("Copy Tree to Clipboard", (*) => (ToolTip("Copied DumpAll() output to Clipboard!"), A_Clipboard := UIA.ElementFromHandle(this.Stored.mwId, this.cacheRequest).DumpAll(), SetTimer((*) => ToolTip(), -3000)))
if IsSet(Element) {
TVUIA_Menu.Add("")
TVUIA_Menu.Add("Expand/Collapse All", this.TVUIA_ExpandCollapseAll.bind(this))
TVUIA_Menu.Add("Focus Element", this.TVUIA_FocusElement.bind(this))
}
TVUIA_Menu.Show()
}
TVUIA_ExpandCollapseAll(GuiCtrlObj, Item, *) {
FocusId := this.TVUIA.GetSelection()
expandCollapse := this.TVUIA.IsCollapsed ? "Expand" : "-Expand"
this.TVUIA.Opt("-Redraw")
ItemID := 0
while ItemID := this.TVUIA.GetNext(ItemID, "Full")
this.TVUIA.Modify(ItemID, expandCollapse)
FocusId := this.TVUIA.isCollapsed ? FocusId : this.TVUIA.GetNext()
this.TVUIA.Modify(FocusId, "Select Vis")
this.TVUIA.Opt("+Redraw")
this.TVUIA.IsCollapsed := !this.TVUIA.IsCollapsed
}
TVUIA_FocusElement(GuiCtrlObj, *) {
FocusId := this.TVUIA.GetSelection()
ItemId := 0
this.TVUIA.Opt("-Redraw")
while ItemID := this.TVUIA.GetNext(ItemID, "Full") ; Collapse all elements.
this.TVUIA.Modify(ItemID, "-Expand")
this.TVUIA.Modify(FocusId, "Select Vis") ; Reselect the item, which also expands the parents
this.TVUIA.Opt("+Redraw")
this.TVUIA.IsCollapsed := true
}
; Handles filtering the UIA elements inside the TreeView when the text hasn't been changed in 500ms.
; Sorts the results by UIA properties.
EditFilterTVUIA_Change(GuiCtrlObj, Info, *) {
static TimeoutFunc := "", ChangeActive := False
local index, prop
if !this.Stored.TreeView.Count
return
if (Info != "DoAction") || ChangeActive {
if !TimeoutFunc
TimeoutFunc := this.EditFilterTVUIA_Change.Bind(this, GuiCtrlObj, "DoAction")
SetTimer(TimeoutFunc, -500)
return
}
ChangeActive := True
this.Stored.FilteredTreeView := Map(), parents := Map()
if !(searchPhrase := this.EditFilterTVUIA.Value) {
this.ConstructTreeView()
ChangeActive := False
return
}
this.TVUIA.Delete()
temp := this.TVUIA.Add("Searching...")
Sleep -1
this.TVUIA.Opt("-Redraw")
this.TVUIA.Delete()
for index, Element in this.Stored.TreeView {
for prop in this.DisplayedProps {
try {
if InStr(Element.Cached%Prop%, searchPhrase) {
if !parents.Has(prop)
parents[prop] := this.TVUIA.Add(prop,, "Expand")
this.Stored.FilteredTreeView[this.TVUIA.Add(this.GetShortDescription(Element), parents[prop], "Expand")] := Element
}
}
}
}
if !this.Stored.FilteredTreeView.Count
this.TVUIA.Add("No results found matching `"" searchPhrase "`"")
this.TVUIA.Opt("+Redraw")
TimeoutFunc := "", ChangeActive := False
}
; Populates the TreeView with the UIA tree when capturing and the mouse is held still
ConstructTreeView() {
this.TVUIA.Delete()
this.TVUIA.Add("Constructing Tree, please wait...")
this.TVUIA.IsCollapsed := false
Sleep -1
this.TVUIA.Opt("-Redraw")
this.TVUIA.Delete()
this.Stored.TreeView := Map()
this.Stored.TreeViewWindow := this.Stored.CapturedWindow
try this.RecurseTreeView(this.Stored.CapturedWindow)
catch {
this.Stored.TreeView := []
this.TVUIA.Add("Error: unspecified error (window not found?)")
}
this.TVUIA.Opt("+Redraw")
this.SBMain.SetText(" Path: ")
this.TreeViewSelectCapturedElement()
}
TreeViewSelectCapturedElement() {
local k, v
if !this.Stored.CapturedElement.HasOwnProp("Path") {
this.Stored.CapturedElement.DefineProp("Path", {Value:""})
this.Stored.CapturedElement.DefineProp("NumericPath", {Value:""})
this.Stored.CapturedElement.DefineProp("ConditionPath", {Value:""})
}
for k, v in this.Stored.TreeView {
if UIA.CompareElementsEx(this.Stored.CapturedElement, v) {
this.TVUIA.Modify(k, "Vis Select"), this.SBMain.SetText(" Path: " (this.PathType = "Numeric" ? v.NumericPath : this.PathType = "Condition" ? v.ConditionPath : v.Path))
, this.Stored.CapturedElement.Path := v.Path
, this.Stored.CapturedElement.NumericPath := v.NumericPath
, this.Stored.CapturedElement.ConditionPath := v.ConditionPath
return 1
}
}
return 0
}
; Stores the UIA tree with corresponding path values for each element
RecurseTreeView(Element, parent:=0, path:="", conditionpath := "", numpath:="") {
local info, child, type, k, paths := Map(), childInfo := [], children := Element.CachedChildren
Element.DefineProp("Path", {value:"`"" path "`""})
Element.DefineProp("ConditionPath", {value:conditionpath})
Element.DefineProp("NumericPath", {value:numpath})
this.Stored.TreeView[TWEl := this.TVUIA.Add(this.GetShortDescription(Element), parent, "Expand")] := Element
; First count up all multiple-condition-index conditions and type-index conditions
; This is to know whether the condition is the last of the matching ones, so we can use index -1
; This gives an important speed difference over regular indexing
for child in children {
compactCondition := this.GetCompactCondition(child, &paths, &typeCondition := "", &type:="")
childInfo.Push([compactCondition, paths[compactCondition], typeCondition, paths[typeCondition], type])
}
; Now create the final conditions and recurse the tree
for k, child in children {
info := childInfo[k], compactCondition := info[1], conditionIndex := info[2]
if conditionIndex > 1 && conditionIndex = paths[compactCondition]
conditionIndex := -1
compactCondition .= conditionIndex = 1 ? "}" : ", i:" conditionIndex "}"
typeIndex := info[4]
if typeIndex > 1 && typeIndex = paths[info[3]]
typeIndex := -1
this.RecurseTreeView(child, TWEl, path UIA.EncodePath([typeIndex = 1 ? {Type:info[5]} : {Type:info[5], i:typeIndex}]), conditionpath (conditionpath?", ":"") compactCondition, numpath (numpath?",":"") k)
}
}
; Creates a short description string for the UIA tree elements
GetShortDescription(Element) {
local elDesc := " `"`""
try elDesc := " `"" Element.CachedName "`""
try elDesc := Element.CachedLocalizedType elDesc
catch
elDesc := "`"`"" elDesc
return elDesc
}
GetCompactCondition(Element, &pathsMap, &t := "", &type := "", &automationId := "", &className := "", &name := "") {
local n := "", c := "", a := ""
type := Element.CachedType
t := "{T:" (type-50000)
pathsMap[t] := pathsMap.Has(t) ? pathsMap[t] + 1 : 1
try a := StrReplace(automationId := Element.CachedAutomationId, "`"", "```"")
if a != "" && !IsInteger(a) { ; Ignore Integer AutomationIds, since they seem to be auto-generated in Chromium apps
a := t ",A:`"" a "`""
pathsMap[a] := pathsMap.Has(a) ? pathsMap[a] + 1 : 1 ; This actually shouldn't be needed, if AutomationId's are unique
}
try c := StrReplace(className := Element.CachedClassName, "`"", "```"")
if c != "" {
c := t ",CN:`"" c "`""
pathsMap[c] := pathsMap.Has(c) ? pathsMap[c] + 1 : 1
}
try n := StrReplace(name := Element.CachedName, "`"", "```"")
if !this.PathIgnoreNames && n != "" { ; Consider Name last, because it can change (eg. window title)
n := t ",N:`"" n "`""
pathsMap[n] := pathsMap.Has(n) ? pathsMap[n] + 1 : 1
}
if pathsMap[t] = 1
return t
if a != "" && !IsInteger(a) {
return c != "" ? (pathsMap[a] <= pathsMap[c] ? a : c) : a
} else if c != ""
return c
else if !this.PathIgnoreNames && n != "" && (pathsMap[n] < pathsMap[t])
return n
return t
}
}
}
/*
Introduction:
UIA_Browser implements some methods to help automate browsers with UIAutomation framework.
Initiate new instance of UIA_Browser with
cUIA := UIA_Browser(wTitle="")
wTitle: the title of the browser
Example: cUIA := UIA_Browser("ahk_exe chrome.exe")
Instances for specific browsers may be initiated with UIA_Chrome, UIA_Edge, UIA_Mozilla (arguments are the same as for UIA_Browser).
These are usually auto-detected by UIA_Browser, so do not have to be used.
Available properties for UIA_Browser:
BrowserId
ahk_id of the browser window
BrowserType
"Chrome", "Edge", "Mozilla", "Vivaldi", "Brave" or "Unknown"
BrowserElement
The browser window element, which can also be accessed by just calling an element method from UIA_Browser (cUIA.FindFirst would call FindFirst method on the BrowserElement, is equal to cUIA.BrowserElement.FindFirst)
MainPaneElement
Element for the upper part of the browser containing the URL bar, tabs, extensions etc
URLEditElement
Element for the address bar
UIA_Browser methods:
GetCurrentMainPaneElement()
Refreshes UIA_Browser.MainPaneElement and also returns it
GetCurrentDocumentElement()
Returns the current document/content element of the browser. For Mozilla, the tab name which content to get can be specified.
GetAllText()
Gets all text from the browser element (Name properties for all child elements)
GetAllLinks()
Gets all link elements from the browser (returns an array of elements)
WaitTitleChange(targetTitle:="", timeOut:=-1)
Waits the browser title to change to targetTitle (by default just waits for the title to change), timeOut is in milliseconds (default is indefinite waiting)
WaitPageLoad(targetTitle:="", timeOut:=-1, sleepAfter:=500, titleMatchMode:=3, titleCaseSensitive:=True)
Waits the browser page to load to targetTitle, default timeOut is indefinite waiting, sleepAfter additionally sleeps for 200ms after the page has loaded.
Back()
Presses the Back button
Forward()
Presses the Forward button
Reload()
Presses the Reload button
Home()
Presses the Home button if it exists.
GetCurrentURL(fromAddressBar:=False)
Gets the current URL. fromAddressBar=True gets it straight from the URL bar element, which is not a very good method, because the text might be changed by the user and doesn't start with "http(s)://". Default of fromAddressBar=False will cause the real URL to be fetched, but the browser must be visible for it to work (if is not visible, it will be automatically activated).
SetURL(newUrl, navigateToNewUrl:=False)
Sets the URL bar to newUrl, optionally also navigates to it if navigateToNewUrl=True
Navigate(url, targetTitle:="", waitLoadTimeOut:=-1, sleepAfter:=500)
Navigates to URL and waits page to load
NewTab()
Opens a new tab.
GetTab(searchPhrase:="", matchMode:=3, caseSense:=True)
Returns a tab element with text of searchPhrase, or if empty then the currently selected tab. matchMode follows SetTitleMatchMode scheme: 1=tab name must must start with tabName; 2=can contain anywhere; 3=exact match; RegEx
TabExist(searchPhrase:="", matchMode:=3, caseSense:=True)
Checks whether a tab element with text of searchPhrase exists: if a matching tab is found then the element is returned, otherwise 0 is returned. matchMode follows SetTitleMatchMode scheme: 1=tab name must must start with tabName; 2=can contain anywhere; 3=exact match; RegEx
GetTabs(searchPhrase:="", matchMode:=3, caseSense:=True)
Returns all tab elements with text of searchPhrase, or if empty then all tabs. matchMode follows SetTitleMatchMode scheme: 1=tab name must must start with tabName; 2=can contain anywhere; 3=exact match; RegEx
GetAllTabNames()
Gets all the titles of tabs
SelectTab(tabName, matchMode:=3, caseSense:=True)
Selects a tab with the text of tabName. matchMode follows SetTitleMatchMode scheme: 1=tab name must must start with tabName; 2=can contain anywhere; 3=exact match; RegEx
CloseTab(tabElementOrName:="", matchMode:=3, caseSense:=True)
Close tab by either providing the tab element or the name of the tab. If tabElementOrName is left empty, the current tab will be closed.
IsBrowserVisible()
Returns True if any of the 4 corners of the browser are visible.
Send(text)
Uses ControlSend to send text to the browser.
GetAlertText()
Gets the text from an alert box
CloseAlert()
Closes an alert box
JSExecute(js)
Executes Javascript code using the address bar
NOTE: In Firefox this is done by default through the console, which is a slow and inefficient method.
A better way is to create a new bookmark with URL "javascript:%s" and keyword "javascript". This
allows executing javascript through the address bar with "javascript alert("hello")".
To make JSExecute use this method, either create UIA_Mozilla with JavascriptExecutionMethod set to "Bookmark",
or set cUIA.JavascriptExecutionMethod := "Bookmark". Default value is "Console".
JSReturnThroughClipboard(js)
Executes Javascript code using the address bar and returns the return value of the code using the clipboard (resetting it back afterwards)
JSReturnThroughTitle(js, timeOut:=500)
Executes Javascript code using the address bar and returns the return value of the code using the browsers title (resetting it back afterwards). This might be unreliable, so the clipboard method is recommended instead.
JSSetTitle(newTitle)
Uses Javascript through the address bar to change the title of the browser
JSGetElementPos(selector, useRenderWidgetPos:=False)
Uses Javascript's querySelector to get a Javascript element and then its position. useRenderWidgetPos=True uses position of the Chrome_RenderWidgetHostHWND1 control to locate the position element relative to the window, otherwise it uses UIA_Browsers CurrentDocumentElement position.
JSClickElement(selector)
Uses Javascript's querySelector to get and click a Javascript element
ControlClickJSElement(selector, WhichButton:="", ClickCount:="", Options:="", useRenderWidgetPos:=False)
Uses Javascript's querySelector to get a Javascript element and then ControlClicks that position. useRenderWidgetPos=True uses position of the Chrome_RenderWidgetHostHWND1 control to locate the position element relative to the window, otherwise it uses UIA_Browsers CurrentDocumentElement position.
ClickJSElement(selector, WhichButton:="", ClickCount:=1, DownOrUp:="", Relative:="", useRenderWidgetPos:=False)
Uses Javascript's querySelector to get a Javascript element and then Clicks that position. useRenderWidgetPos=True uses position of the Chrome_RenderWidgetHostHWND1 control to locate the position element relative to the window, otherwise it uses UIA_Browsers CurrentDocumentElement position.
*/
/*
If implementing new browser classes, then necessary methods/properties for main browser functions are:
this.GetCurrentMainPaneElement() -- fetches MainPaneElement, NavigationBarElement, TabBarElement, URLEditElement
// this might be necessary to implement for speed reasons, and is automatically called by InitiateUIA method
this.GetCurrentDocumentElement() -- fetches Document element for the current page // might be necessary to implement
this.GetCurrentBackButton()
this.GetCurrentReloadButton()
this.MainPaneElement -- element that doesn't contain page content: this element includes URL bar, navigation buttons, setting buttons etc
this.NavigationBarElement -- smallest element (usually a Toolbar element) that contains the URL bar and navigation buttons
this.TabBarElement -- contains only tabs
this.URLEditElement -- the URL bar element
this.ReloadButton
this.BackButton
*/
class UIA_Vivaldi extends UIA_Browser {
__New(wTitle:="") {
this.BrowserType := "Vivaldi"
this.InitiateUIA(wTitle)
}
GetCurrentMainPaneElement() {
this.GetCurrentDocumentElement()
this.DialogTreeWalker := UIA.CreateTreeWalker(UIA.CreateAndCondition(UIA.CreatePropertyCondition(UIA.Property.Type, UIA.Type.Group), UIA.CreatePropertyCondition(UIA.Property.AutomationId, "modal-bg")))
if !this.HasOwnProp("DocumentElement") && !(this.DocumentElement := this.MainPaneElement)
throw TargetError("UIA_Browser was unable to find the Document element for browser. Make sure the browser is at least partially visible or active before calling UIA_Browser()", -2)
Loop 2 {
this.URLEditElement := this.BrowserElement.WaitElement({AutomationId:"urlFieldInput"}, 3000)
TabElement := this.BrowserElement.FindElement({AutomationId:"tab-", matchmode:"Substring"})
NewTabButton := this.BrowserElement.FindElement({Type:"Button", startingElement:TabElement})
try {
this.TabBarElement := TabElement.Parent
this.NavigationBarElement := this.TabBarElement.Parent
this.ReloadButton := "", this.BackButton := "", this.ReloadButtonDescription := "", this.ReloadButtonFullDescription := "", this.ReloadButtonName := ""
this.ReloadButton := this.URLEditElement.WalkTree("-3", {Type:"Button"})
this.ReloadButtonDescription := this.ReloadButton.LegacyIAccessiblePattern.Description
this.ReloadButtonName := this.ReloadButton.Name
if !this.ReloadButtonDescription && !this.ReloadButtonName
this.ReloadButtonName := "Reload"
return this.MainPaneElement
} catch {
WinActivate "ahk_id " this.BrowserId
WinWaitActive "ahk_id " this.BrowserId,,1
}
}
; If all goes well, this part is not reached
}
GetCurrentDocumentElement() {
Loop 2 {
try {
this.MainPaneElement := this.BrowserElement.FindElement({Type:"Document"})
return this.DocumentElement := this.BrowserElement.FindElement({Type:"Document", not:{Value:""}, startingElement:this.MainPaneElement})
} catch TargetError {
WinActivate this.BrowserId
WinWaitActive this.BrowserId,,1
}
}
}
GetAllTabs() {
return this.TabBarElement.FindElements({AutomationId:"tab-", matchmode:"Substring"}, 2)
}
GetTabs(searchPhrase:="", matchMode:=3, caseSense:=True) {
local allTabs := this.GetAllTabs()
matchMode := UIA.TypeValidation.MatchMode(matchMode)
if !searchPhrase
return allTabs
return UIA.Filter(allTabs, (element) => element.ElementExist({Name:searchPhrase, matchMode:matchMode, caseSense:caseSense}))
}
GetTab(searchPhrase:="", matchMode:=3, caseSense:=True) {
local match, els
if searchPhrase is Integer
return this.TabBarElement.FindElement({AutomationId:"tab-", matchmode:"Substring", i:searchPhrase}, 2)
if !searchPhrase {
RegExMatch(WinGetTitle(this.BrowserId), "(.*) - Vivaldi$", &match:="")
searchPhrase := match[1], matchMode := 3, caseSense := True
}
if !(tabs := this.GetAllTabs()).Length
throw Error("Unable to get tab elements", -1, "Please file a bug report")
if !(els := UIA.Filter(tabs, (element) => element.ElementExist({Type:["Text", "TabItem"], Name:searchPhrase, matchMode:matchMode, caseSense:caseSense, scope:3}))).Length
throw Error("No search phrase matches found", -1)
return els[els.Length]
}
GetAllTabNames() {
local names := [], k, v
for k, v in this.GetTabs() {
names.Push(v.FindElement({Type:["Text", "TabItem"], scope:3}).Name)
}
return names
}
SetURL(newUrl, navigateToNewUrl := False) => UIA_Mozilla.Prototype.GetMethod("SetURL")(this, newUrl, navigateToNewUrl, "{Enter}")
CloseTab(tabElementOrName:="", matchMode:=3, caseSense:=True) {
this.SelectTab(tabElementOrName)
Sleep 40
this.ControlSend("{ctrl down}w{ctrl up}")
}
Reload() {
this.GetCurrentReloadButton().ControlClick()
}
Back() {
this.ReloadButton.WalkTree("-2", this.ButtonControlCondition).Click()
}
Forward() {
this.ReloadButton.WalkTree("-1", this.ButtonControlCondition).Click()
}
Home() {
throw Error("Method not implemented", -1)
}
}
class UIA_Chrome extends UIA_Browser {
__New(wTitle:="") {
this.BrowserType := "Chrome"
this.InitiateUIA(wTitle)
}
; Refreshes UIA_Browser.MainPaneElement and returns it
GetCurrentMainPaneElement() {
this.GetCurrentDocumentElement()
if !this.HasOwnProp("DocumentElement")
throw TargetError("UIA_Browser was unable to find the Document element for browser. Make sure the browser is at least partially visible or active before calling UIA_Browser()", -2)
Loop 2 {
try this.URLEditElement := this.BrowserElement.FindFirst({ClassName:"TopContainerView"}).FindFirstWithOptions(this.EditControlCondition, 2, this.BrowserElement)
catch
this.URLEditElement := this.BrowserElement.FindFirstWithOptions(this.EditControlCondition, 2, this.BrowserElement)
try {
if !this.URLEditElement
this.URLEditElement := UIA.CreateTreeWalker(this.EditControlCondition).GetLastChildElement(this.BrowserElement)
this.NavigationBarElement := UIA.CreateTreeWalker(this.ToolbarControlCondition).GetParentElement(this.URLEditElement)
this.MainPaneElement := UIA.TreeWalkerTrue.GetParentElement(this.NavigationBarElement)
if !this.NavigationBarElement
this.NavigationBarElement := this.BrowserElement
if !this.MainPaneElement
this.MainPaneElement := this.BrowserElement
if !(this.TabBarElement := UIA.CreateTreeWalker(this.TabControlCondition).GetNextSiblingElement(this.NavigationBarElement))
this.TabBarElement := this.MainPaneElement
this.BackButton := "", this.ReloadButton := "", this.ReloadButtonDescription := "", this.ReloadButtonFullDescription := "", this.ReloadButtonName := ""
Loop 2 {
try {
this.ReloadButton := UIA.TreeWalkerTrue.GetNextSiblingElement(UIA.TreeWalkerTrue.GetNextSiblingElement(this.ButtonTreeWalker.GetFirstChildElement(this.NavigationBarElement)))
this.ReloadButtonDescription := this.ReloadButton.LegacyIAccessiblePattern.Description
this.ReloadButtonName := this.ReloadButton.Name
}
if (this.ReloadButtonDescription || this.ReloadButtonName)
break
Sleep 200
}
return this.MainPaneElement
} catch {
WinActivate "ahk_id " this.BrowserId
WinWaitActive "ahk_id " this.BrowserId,,1
}
}
; If all goes well, this part is not reached
}
}
class UIA_Brave extends UIA_Chrome {
}
class UIA_Edge extends UIA_Browser {
__New(wTitle:="") {
this.BrowserType := "Edge"
this.InitiateUIA(wTitle)
}
; Refreshes UIA_Browser.MainPaneElement and returns it
GetCurrentMainPaneElement() {
local k, v, el, topCoord, bt
this.GetCurrentDocumentElement()
if !this.HasOwnProp("DocumentElement")
throw TargetError("UIA_Browser was unable to find the Document element for browser. Make sure the browser is at least partially visible or active before calling UIA_Browser()", -2)
Loop 2 {
try {
if !(this.URLEditElement := this.BrowserElement.ElementExist({Type:"Edit"})) {
this.ToolbarElements := this.BrowserElement.FindAll(this.ToolbarControlCondition), topCoord := 10000000
for k, v in this.ToolbarElements {
if ((bT := v.BoundingRectangle.t) && (bt < topCoord))
topCoord := bT, this.NavigationBarElement := v
}
this.URLEditElement := this.NavigationBarElement.FindFirst(this.EditControlCondition)
if this.URLEditElement.GetChildren().Length
this.URLEditElement := (el := this.URLEditElement.FindFirst(this.EditControlCondition)) ? el : this.URLEditElement
} Else {
this.NavigationBarElement := UIA.CreateTreeWalker(this.ToolbarControlCondition).GetParentElement(this.URLEditElement)
}
this.MainPaneElement := UIA.TreeWalkerTrue.GetParentElement(this.NavigationBarElement)
if !this.NavigationBarElement
this.NavigationBarElement := this.BrowserElement
if !this.MainPaneElement
this.MainPaneElement := this.BrowserElement
if !(this.TabBarElement := UIA.CreateTreeWalker(this.TabControlCondition).GetNextSiblingElement(this.NavigationBarElement))
this.TabBarElement := this.MainPaneElement
this.BackButton := "", this.ReloadButton := "", this.ReloadButtonDescription := "", this.ReloadButtonFullDescription := "", this.ReloadButtonName := ""
Loop 2 {
try {
this.ReloadButton := this.ButtonTreeWalker.GetNextSiblingElement(this.ButtonTreeWalker.GetNextSiblingElement(this.ButtonTreeWalker.GetFirstChildElement(this.NavigationBarElement)))
this.ReloadButtonFullDescription := this.ReloadButton.FullDescription
this.ReloadButtonName := this.ReloadButton.Name
}
if (this.ReloadButtonDescription || this.ReloadButtonName)
break
Sleep 200
}
return this.MainPaneElement
} catch {
WinActivate "ahk_id " this.BrowserId
WinWaitActive "ahk_id " this.BrowserId,,1
}
}
; If all goes well, this part is not reached
}
GetCurrentDocumentElement() {
local endtime := A_TickCount+3000
While A_TickCount < endtime
try return this.DocumentElement := this.CurrentDocumentElement := UIA.ElementFromHandle(this.BrowserId).FindFirst(this.DocumentControlCondition,4) ; ElementFromChromium works unreliably
throw Error("Unable to get the current Document element", -1)
}
}
class UIA_Mozilla extends UIA_Browser {
__New(wTitle:="", javascriptExecutionMethod:="Console") {
this.JavascriptExecutionMethod := javascriptExecutionMethod
this.BrowserType := "Mozilla"
this.InitiateUIA(wTitle)
}
; Refreshes UIA_Browser.MainPaneElement and returns it
GetCurrentMainPaneElement() {
try this.BrowserElement.FindElement({AutomationId:"panel", mm:2},2)
catch {
WinActivate this.BrowserId
WinWaitActive this.BrowserId,,1
}
Loop 2 {
try {
this.TabBarElement := this.ToolbarTreeWalker.GetNextSiblingElement(this.ToolbarTreeWalker.GetFirstChildElement(this.BrowserElement))
this.NavigationBarElement := this.ToolbarTreeWalker.GetNextSiblingElement(this.TabBarElement)
this.MainPaneElement := UIA.TreeWalkerTrue.GetParentElement(this.NavigationBarElement)
this.URLEditElement := this.NavigationBarElement.FindFirst(UIA.CreateOrCondition(this.EditControlCondition, UIA.CreatePropertyCondition(UIA.Property.Type, UIA.Type.ComboBox)))
if !this.NavigationBarElement
this.NavigationBarElement := this.BrowserElement
if !this.MainPaneElement
this.MainPaneElement := this.BrowserElement
this.BackButton := "", this.ReloadButton := "", this.ReloadButtonDescription := "", this.ReloadButtonFullDescription := "", this.ReloadButtonName := ""
Loop 2 {
try {
this.ReloadButton := UIA.TreeWalkerTrue.GetNextSiblingElement(UIA.TreeWalkerTrue.GetNextSiblingElement(UIA.TreeWalkerTrue.GetFirstChildElement(this.NavigationBarElement)))
this.ReloadButtonFullDescription := this.ReloadButton.FullDescription
this.ReloadButtonName := this.ReloadButton.Name
}
if (this.ReloadButtonDescription || this.ReloadButtonName)
break
Sleep 200
}
return this.MainPaneElement
} catch {
WinActivate this.BrowserId
WinWaitActive this.BrowserId,,1
}
}
; If all goes well, this part is not reached
}
; Returns the current document/content element of the browser
GetCurrentDocumentElement() {
Loop 2 {
try {
try this.DocumentPanelElement := this.BrowserElement.FindElement({Type:"Custom", IsOffscreen:0},2)
catch
this.DocumentPanelElement := this.BrowserElement.FindElement({AutomationId:"tabbrowser-tabpanels"},2).FindElement({Type:"Pane", IsOffscreen:0},2)
return UIA.TreeWalkerTrue.GetFirstChildElement(UIA.TreeWalkerTrue.GetFirstChildElement(this.DocumentPanelElement))
} catch TargetError {
WinActivate this.BrowserId
WinWaitActive this.BrowserId,,1
}
}
}
; Sets the URL bar to newUrl, optionally also navigates to it if navigateToNewUrl=True
SetURL(newUrl, navigateToNewUrl := False, triggerNavigateKeys := "{LCtrl down}{Enter}{LCtrl up}") {
local endTime
this.URLEditElement.SetFocus()
this.URLEditElement.Value := newUrl " "
endTime := A_TickCount+200
if navigateToNewUrl {
while !InStr(this.URLEditElement.Value, newUrl) && (A_TickCount < endTime)
Sleep 40
if A_TickCount < endTime {
this.ControlSend(triggerNavigateKeys)
}
}
}
JSExecute(js) {
if this.JavascriptExecutionMethod = "Bookmark" {
this.SetURL("javascript " js, True)
return
}
this.ControlSend("{ctrl down}{shift down}k{ctrl up}{shift up}")
if !this.BrowserElement.WaitElement({Name:"Switch to multi-line editor mode (Ctrl + B)", Type:"Button"},5000)
return
ClipSave := ClipboardAll()
A_Clipboard := js
this.ControlSend("allow pasting{ctrl down}{z 2}{ctrl up}{ctrl down}v{ctrl up}")
Sleep 20
this.ControlSend("{ctrl down}{enter}{ctrl up}")
sleep 40
this.ControlSend("{ctrl down}{shift down}i{ctrl up}{shift up}")
A_Clipboard := ClipSave
}
; Gets text from an alert-box
GetAlertText(closeAlert:=True, timeOut:=3000) {
this.GetCurrentDocumentElement()
local startTime := A_TickCount, text := ""
if !(alertEl := UIA.TreeWalkerTrue.GetNextSiblingElement(UIA.TreeWalkerTrue.GetFirstChildElement(this.DocumentPanelElement)))
return
while ((A_tickCount - startTime) < timeOut) {
try {
dialogEl := alertEl.FindElement({AutomationId:"commonDialogWindow"})
OKBut := dialogEl.FindFirst(this.ButtonControlCondition)
break
} catch
Sleep 100
}
try text := dialogEl.FindElement({AutomationId:"infoBody"}).Name
if closeAlert
try OKBut.Click()
return text
}
CloseAlert() {
this.GetCurrentDocumentElement()
try UIA.TreeWalkerTrue.GetNextSiblingElement(UIA.TreeWalkerTrue.GetFirstChildElement(this.DocumentPanelElement)).FindElement({AutomationId:"commonDialogWindow"}).FindFirst(this.ButtonControlCondition).Click()
}
; Close tab by either providing the tab element or the name of the tab. If tabElementOrName is left empty, the current tab will be closed.
CloseTab(tabElementOrName:="", matchMode:=3, caseSense:=True) {
if (tabElementOrName != "") {
if IsObject(tabElementOrName) {
if (tabElementOrName.Type == UIA.Type.TabItem)
tabElementOrName.Click()
} else {
try this.TabBarElement.FindElement({Name:tabElementOrName, Type:"TabItem", mm:matchMode, cs:caseSense}).Click()
}
}
this.ControlSend("{Ctrl down}w{Ctrl up}")
}
GetCurrentBackButton() {
try {
if this.BackButton && this.BackButton.Name
return this.BackButton
}
this.BackButton := this.NavigationBarElement.FindElement({Type:"Button", AutomationId:"back-button"})
return this.BackButton
}
}
class UIA_Browser {
InitiateUIA(wTitle:="") {
this.BrowserId := WinExist(wTitle)
if !this.BrowserId
throw TargetError("UIA_Browser: failed to find the browser!", -1)
this.TextControlCondition := UIA.CreatePropertyCondition(UIA.Property.Type, UIA.Type.Text)
this.DocumentControlCondition := UIA.CreatePropertyCondition(UIA.Property.Type, UIA.Type.Document)
this.ButtonControlCondition := UIA.CreatePropertyCondition(UIA.Property.Type, UIA.Type.Button)
this.EditControlCondition := UIA.CreatePropertyCondition(UIA.Property.Type, UIA.Type.Edit)
this.ToolbarControlCondition := UIA.CreatePropertyCondition(UIA.Property.Type, UIA.Type.ToolBar)
this.TabControlCondition := UIA.CreatePropertyCondition(UIA.Property.Type, UIA.Type.Tab)
this.ToolbarTreeWalker := UIA.CreateTreeWalker(this.ToolbarControlCondition)
this.ButtonTreeWalker := UIA.CreateTreeWalker(this.ButtonControlCondition)
this.BrowserElement := UIA.ElementFromHandle(this.BrowserId)
this.DialogTreeWalker := UIA.CreateTreeWalker(UIA.CreateOrCondition(UIA.CreatePropertyCondition(UIA.Property.Type, UIA.Type.Custom), UIA.CreatePropertyCondition(UIA.Property.Type, UIA.Type.Window)))
this.GetCurrentMainPaneElement()
}
; Initiates UIA and hooks to the browser window specified with wTitle.
__New(wTitle:="") {
this.BrowserId := WinExist(wTitle)
if !this.BrowserId
throw TargetError("UIA_Browser: failed to find the browser!", -1)
wExe := WinGetProcessName("ahk_id" this.BrowserId)
wClass := WinGetClass("ahk_id" this.BrowserId)
this.BrowserType := (wExe = "chrome.exe") ? "Chrome" : (wExe = "msedge.exe") ? "Edge" : (wExe = "vivaldi.exe") ? "Vivaldi" : InStr(wClass, "Mozilla") ? "Mozilla" : (wExe = "brave.exe") ? "Brave" : "Unknown"
if (this.BrowserType != "Unknown") {
this.base := UIA_%(this.BrowserType)%.Prototype
this.__New(wTitle)
} else
this.InitiateUIA(wTitle)
}
__Get(member, params) {
local err
if this.HasOwnProp("BrowserElement") {
try return this.BrowserElement.%member%
catch PropertyError {
} catch Any as err
throw %Type(err)%(err.Message, -1, err.Extra)
}
try return UIA.%member%
catch PropertyError
throw PropertyError("This class does not contain property `"" member "`"", -1)
catch Any as err
throw %Type(err)%(err.Message, -1, err.Extra)
}
__Call(member, params) {
local err
if this.HasOwnProp("BrowserElement") {
try return this.BrowserElement.%member%(params*)
catch MethodError {
} catch Any as err
throw %Type(err)%(err.Message, -1, err.Extra)
}
try return UIA.%member%(params*)
catch MethodError
throw MethodError("This class does not contain method `"" member "`"", -1)
catch Any as err
throw %Type(err)%(err.Message, -1, err.Extra)
}
__Set(member, params, value) {
if this.HasOwnProp("BrowserElement")
if this.BrowserElement.HasOwnProp(member)
this.BrowserElement.%member% := Value
if UIA.HasOwnProp(member)
UIA.%member% := Value
this.DefineProp(member, {Value:value})
}
__Item[params*] {
get => this.BrowserElement[params*]
}
; Refreshes UIA_Browser.MainPaneElement and returns it
GetCurrentMainPaneElement() {
this.GetCurrentDocumentElement()
if !this.HasOwnProp("DocumentElement")
throw TargetError("UIA_Browser was unable to find the Document element for browser. Make sure the browser is at least partially visible or active before calling UIA_Browser()", -2)
; Finding the correct Toolbar ends up to be quite tricky.
; In Chrome the toolbar element is located in the tree after the content element,
; so if the content contains a toolbar then that will be returned.
; Two workarounds I can think of: either look for the Toolbar by name ("Address and search bar"
; both in Chrome and edge), or by location (it must be the topmost toolbar). I opted for a
; combination of two, so if finding by name fails, all toolbar elements are evaluated.
Loop 2 {
try this.URLEditElement := (this.BrowserType = "Chrome" && this.BrowserElement[1].Type = UIA.Property.Document) ? this.BrowserElement.FindFirstWithOptions(this.EditControlCondition, 2, this.BrowserElement) : this.BrowserElement.FindFirst(this.EditControlCondition)
try {
if (this.BrowserType = "Chrome") && !this.URLEditElement
this.URLEditElement := UIA.CreateTreeWalker(this.EditControlCondition).GetLastChildElement(this.BrowserElement)
this.NavigationBarElement := UIA.CreateTreeWalker(this.ToolbarControlCondition).GetParentElement(this.URLEditElement)
this.MainPaneElement := UIA.TreeWalkerTrue.GetParentElement(this.NavigationBarElement)
if !this.NavigationBarElement
this.NavigationBarElement := this.BrowserElement
if !this.MainPaneElement
this.MainPaneElement := this.BrowserElement
if !(this.TabBarElement := UIA.CreateTreeWalker(this.TabControlCondition).GetPreviousSiblingElement(this.NavigationBarElement))
this.TabBarElement := this.MainPaneElement
this.GetCurrentBackButton()
this.GetCurrentReloadButton()
this.BackButton := "", this.ReloadButton := "", this.ReloadButtonDescription := "", this.ReloadButtonFullDescription := "", this.ReloadButtonName := ""
Loop 2 {
try {
this.ReloadButtonDescription := this.ReloadButton.LegacyIAccessiblePattern.Description
this.ReloadButtonFullDescription := this.ReloadButton.FullDescription
this.ReloadButtonName := this.ReloadButton.Name
}
if (this.ReloadButtonDescription || this.ReloadButtonName)
break
Sleep 200
}
return this.MainPaneElement
} catch {
WinActivate "ahk_id " this.BrowserId
WinWaitActive "ahk_id " this.BrowserId,,1
}
}
; If all goes well, this part is not reached
}
; Returns the current document/content element of the browser
GetCurrentDocumentElement() {
return (this.DocumentElement := this.CurrentDocumentElement := this.BrowserElement.WaitElement(this.DocumentControlCondition, 3000))
}
GetCurrentBackButton() {
try {
if this.BackButton && this.BackButton.Name
return this.BackButton
}
this.BackButton := this.ButtonTreeWalker.GetFirstChildElement(this.NavigationBarElement)
return this.BackButton
}
GetCurrentReloadButton() {
try {
if this.ReloadButton && this.ReloadButton.Name
return this.ReloadButton
}
this.ReloadButton := this.ButtonTreeWalker.GetNextSiblingElement(this.ButtonTreeWalker.GetNextSiblingElement(this.ButtonTreeWalker.GetFirstChildElement(this.NavigationBarElement)))
return this.ReloadButton
}
; Uses Javascript to set the title of the browser.
JSSetTitle(newTitle) {
this.JSExecute("document.title=`"" newTitle "`"; void(0);")
}
JSExecute(js) {
this.SetURL("javascript:" js, True)
}
JSAlert(js, closeAlert:=True, timeOut:=3000) {
this.JSExecute("alert(" js ");")
return this.GetAlertText(closeAlert, timeOut)
}
; Executes Javascript code through the address bar and returns the return value through the clipboard.
JSReturnThroughClipboard(js) {
saveClip := ClipboardAll()
A_Clipboard := ""
this.JSExecute("copyToClipboard(" js ");function copyToClipboard(text) {const elem = document.createElement('textarea');elem.value = text;document.body.appendChild(elem);elem.select();document.execCommand('copy');document.body.removeChild(elem);}")
ClipWait 2
returnText := A_Clipboard
A_Clipboard := saveClip
return returnText
}
; Executes Javascript code through the address bar and returns the return value through the browser windows title.
JSReturnThroughTitle(js, timeOut:=500) {
this.JSExecute("origTitle=document.title;document.title=(" js ");void(0);setTimeout(function() {document.title=origTitle;void(0);}, " timeOut ")")
local startTime := A_TickCount, origTitle := WinGetTitle("ahk_id " this.BrowserId), newTitle
Loop {
newTitle := WinGetTitle("ahk_id " this.BrowserId)
Sleep 40
} Until ((origTitle != newTitle) || (A_TickCount - startTime > timeOut))
return (origTitle == newTitle) ? "" : RegexReplace(newTitle, "(?: - Personal)? - [^-]+$")
}
; Uses Javascript's querySelector to get a Javascript element and then its position. useRenderWidgetPos=True uses position of the Chrome_RenderWidgetHostHWND1 control to locate the position element relative to the window, otherwise it uses UIA_Browsers CurrentDocumentElement position.
JSGetElementPos(selector, useRenderWidgetPos:=False) { ; based on code by AHK Forums user william_ahk
local js := Format("
(LTrim Join
(() => {
let bounds = document.querySelector("{1}").getBoundingClientRect().toJSON();
let zoom = window.devicePixelRatio.toFixed(2);
for (const key in bounds) {
bounds[key] = bounds[key] * zoom;
}
return JSON.stringify(bounds);
})()
)", selector)
local bounds_str := this.JSReturnThroughClipboard(js)
RegexMatch(bounds_str, "`"x`":(\d+).?\d*?,`"y`":(\d+).?\d*?,`"width`":(\d+).?\d*?,`"height`":(\d+).?\d*?", &size)
if useRenderWidgetPos {
ControlGetPos &win_x, &win_y, &win_w, &win_h, "Chrome_RenderWidgetHostHWND1", this.BrowserId
return {x:size[1]+win_x,y:size[2]+win_y,w:size[3],h:size[4]}
} else {
br := this.GetCurrentDocumentElement().GetPos("window")
return {x:size[1]+br.x,y:size[2]+br.y,w:size[3],h:size[4]}
}
}
; Uses Javascript's querySelector to get and click a Javascript element. Compared with ClickJSElement method, this method has the advantage of skipping the need to wait for a return value from the clipboard, but it might be more unreliable (some elements might not support Javascript's "click()" properly).
JSClickElement(selector) {
this.JSExecute("document.querySelector(`"" selector "`").click();")
}
; Uses Javascript's querySelector to get a Javascript element and then ControlClicks that position. useRenderWidgetPos=True uses position of the Chrome_RenderWidgetHostHWND1 control to locate the position element relative to the window, otherwise it uses UIA_Browsers CurrentDocumentElement position.
ControlClickJSElement(selector, WhichButton?, ClickCount?, Options?, useRenderWidgetPos:=False) {
bounds := this.JSGetElementPos(selector, useRenderWidgetPos)
ControlClick("X" (bounds.x + bounds.w // 2) " Y" (bounds.y + bounds.h // 2), this.browserId,, WhichButton?, ClickCount?, Options?)
}
; Uses Javascript's querySelector to get a Javascript element and then Clicks that position. useRenderWidgetPos=True uses position of the Chrome_RenderWidgetHostHWND1 control to locate the position element relative to the window, otherwise it uses UIA_Browsers CurrentDocumentElement position.
ClickJSElement(selector, WhichButton:="", ClickCount:=1, DownOrUp:="", Relative:="", useRenderWidgetPos:=False) {
bounds := this.JSGetElementPos(selector, useRenderWidgetPos)
Click((bounds.x + bounds.w / 2) " " (bounds.y + bounds.h / 2) " " WhichButton (ClickCount ? " " ClickCount : "") (DownOrUp ? " " DownOrUp : "") (Relative ? " " Relative : ""))
}
; Gets text from an alert-box created with for example javascript:alert('message')
GetAlertText(closeAlert:=True, timeOut:=3000) {
local startTime := A_TickCount, text := ""
startTime := A_TickCount
while ((A_tickCount - startTime) < timeOut) {
try {
if IsObject(dialogEl := this.DialogTreeWalker.GetLastChildElement(this.BrowserElement)) && IsObject(OKBut := dialogEl.FindFirst(this.ButtonControlCondition))
break
}
Sleep 100
}
try
text := this.BrowserType = "Edge" ? dialogEl.FindFirstWithOptions(this.TextControlCondition, 2, dialogEl).Name : dialogEl.FindFirst(this.TextControlCondition).Name
if closeAlert {
Sleep 500
try OKBut.Click()
}
return text
}
CloseAlert() {
try {
dialogEl := this.DialogTreeWalker.GetLastChildElement(this.BrowserElement)
OKBut := dialogEl.FindFirst(this.ButtonControlCondition)
OKBut.Click()
}
}
; Gets all text from the browser element (Name properties for all Text elements)
GetAllText() {
local TextArray, Text, k, v
if !this.IsBrowserVisible()
WinActivate this.BrowserId
TextArray := this.BrowserElement.FindAll(this.TextControlCondition)
Text := ""
for k, v in TextArray
try Text .= v.Name "`n"
return Text
}
; Gets all link elements from the browser
GetAllLinks() {
static LinkCondition := UIA.CreatePropertyCondition(UIA.Property.Type, UIA.Type.Hyperlink)
if !this.IsBrowserVisible()
WinActivate this.BrowserId
return this.BrowserElement.FindAll(LinkCondition)
}
; Waits the browser title to change to targetTitle (by default just waits for the title to change), timeOut is in milliseconds (default is indefinite waiting)
WaitTitleChange(targetTitle:="", timeOut:=-1) {
local origTitle := WinGetTitle("ahk_id" this.BrowserId), startTime := A_TickCount, newTitle := origTitle
while ((((A_TickCount - startTime) < timeOut) || (timeOut = -1)) && (targetTitle ? !UIA_Browser.CompareTitles(targetTitle, newTitle) : (origTitle == newTitle))) {
Sleep 200
newTitle := WinGetTitle("A")
}
if (((A_TickCount - startTime) < timeOut) || (timeOut = -1))
return newTitle
return false
}
; Waits the browser page to load to targetTitle, default timeOut is indefinite waiting, sleepAfter additionally sleeps for 200ms after the page has loaded.
WaitPageLoad(targetTitle:="", timeOut:=-1, sleepAfter:=500, titleMatchMode:="", titleCaseSensitive:=False) {
local legacyPattern := "", startTime := A_TickCount, wTitle := "", ReloadButtonName := "", ReloadButtonDescription := "", ReloadButtonFullDescription := ""
Sleep 200 ; Give some time for the Reload button to change after navigating
if this.ReloadButtonDescription
try legacyPattern := this.ReloadButton.LegacyIAccessiblePattern
while ((A_TickCount - startTime) < timeOut) || (timeOut = -1) {
if this.BrowserType = "Mozilla"
this.GetCurrentReloadButton()
try ReloadButtonName := this.ReloadButton.Name
try ReloadButtonDescription := legacyPattern.Description
try ReloadButtonFullDescription := this.ReloadButton.FullDescription
if (((this.ReloadButtonName ? InStr(ReloadButtonName, this.ReloadButtonName) : 1)
&& (this.ReloadButtonDescription && legacyPattern ? InStr(ReloadButtonDescription, this.ReloadButtonDescription) : 1)
&& (this.ReloadButtonFullDescription ? InStr(ReloadButtonFullDescription, this.ReloadButtonFullDescription) : 1)))
|| !this.ReloadButton.IsEnabled {
if targetTitle != "" {
wTitle := WinGetTitle(this.BrowserId)
if UIA_Browser.CompareTitles(targetTitle, wTitle, titleMatchMode, titleCaseSensitive)
break
} else
break
}
Sleep 40
}
if ((A_TickCount - startTime) < timeOut) || (timeOut = -1)
Sleep sleepAfter
else
return false
return targetTitle = "" ? true : wTitle
}
; Presses the Back button
Back() {
this.GetCurrentBackButton().Click()
}
; Presses the Forward button
Forward() {
this.ButtonTreeWalker.GetNextSiblingElement(this.GetCurrentBackButton()).Click()
}
; Presses the Reload button
Reload() {
this.GetCurrentReloadButton().Click()
}
; Presses the Home button if it exists.
Home() {
if homeBut := this.ButtonTreeWalker.GetNextSiblingElement(this.ReloadButton)
return homeBut.Click()
;NameCondition := UIA.CreatePropertyCondition(UIA.NamePropertyId, this.CustomNames.HomeButtonName ? this.CustomNames.HomeButtonName : butName)
;this.NavigationBarElement.FindFirst(UIA.CreateAndCondition(NameCondition, this.ButtonControlCondition)).Click()
}
; Gets the current URL. fromAddressBar=True gets it straight from the URL bar element, which is not a very good method, because the text might be changed by the user and doesn't start with "http(s)://". Default of fromAddressBar=False will cause the real URL to be fetched, but the browser must be visible for it to work (if is not visible, it will be automatically activated).
GetCurrentURL(fromAddressBar:=False) {
if fromAddressBar {
URL := this.URLEditElement.Value
return URL ? (RegexMatch(URL, "^https?:\/\/") ? URL : "https://" URL) : ""
} else {
; This can be used in Chrome and Edge, but works only if the window is active
if (!this.IsBrowserVisible() && (this.BrowserType != "Mozilla"))
WinActivate this.BrowserId
return this.GetCurrentDocumentElement().Value
}
}
; Sets the URL bar to newUrl, optionally also navigates to it if navigateToNewUrl=True
SetURL(newUrl, navigateToNewUrl := False) {
this.URLEditElement.ValuePattern.SetValue(newUrl " ")
if !InStr(this.URLEditElement.Value, newUrl) {
legacyPattern := this.URLEditElement.LegacyIAccessiblePattern
legacyPattern.SetValue(newUrl " ")
}
if (navigateToNewUrl&&InStr(this.URLEditElement.Value, newUrl)) {
this.ControlSend("{Ctrl down}l{Ctrl up}{Enter}")
}
}
; Navigates to URL and waits page to load
Navigate(url, targetTitle:="", waitLoadTimeOut:=-1, sleepAfter:=500) {
this.SetURL(url, True)
this.WaitPageLoad(targetTitle,waitLoadTimeOut,sleepAfter)
}
; Opens a new tab by sending Ctrl+T
NewTab() {
this.ControlSend("{LCtrl down}t{LCtrl up}")
}
GetAllTabs() {
return this.TabBarElement.FindAll(UIA.CreatePropertyCondition(UIA.Property.Type, UIA.Type.TabItem))
}
; Gets all tab elements matching searchPhrase, matchMode and caseSense
; If searchPhrase is omitted then all tabs will be returned
GetTabs(searchPhrase:="", matchMode:=3, caseSense:=True) {
return (searchPhrase == "") ? this.TabBarElement.FindAll(UIA.CreatePropertyCondition(UIA.Property.Type, UIA.Type.TabItem)) : this.TabBarElement.FindElements({Name:searchPhrase, Type:"TabItem", mm:matchMode, cs:caseSense})
}
; Gets all the titles of tabs
GetAllTabNames() {
local names := [], k, v
for k, v in this.GetTabs() {
names.Push(v.Name)
}
return names
}
; Returns a tab element with text of searchPhrase, or if empty then the currently selected tab. matchMode follows SetTitleMatchMode scheme: 1=tab name must must start with tabName; 2=can contain anywhere; 3=exact match; RegEx
GetTab(searchPhrase:="", matchMode:=3, caseSense:=True) {
return (searchPhrase == "") ? this.TabBarElement.FindElement({Type:"TabItem", SelectionItemIsSelected:1}) : this.TabBarElement.FindElement(searchPhrase is Integer ? {Type:"TabItem", i:searchPhrase} : {Name:searchPhrase, Type:"TabItem", mm:matchMode, cs:caseSense})
}
; Checks whether a tab element with text of searchPhrase exists: if a matching tab is found then the element is returned, otherwise 0 is returned. matchMode follows SetTitleMatchMode scheme: 1=tab name must must start with tabName; 2=can contain anywhere; 3=exact match; RegEx
TabExist(searchPhrase:="", matchMode:=3, caseSense:=True) {
try return this.GetTab(searchPhrase, matchMode, caseSense)
return 0
}
; Selects a tab with the text of tabName. matchMode follows SetTitleMatchMode scheme: 1=tab name must must start with tabName; 2=can contain anywhere; 3=exact match; RegEx
SelectTab(tabName, matchMode:=3, caseSense:=True) {
local selectedTab
try {
selectedTab := IsObject(tabName) ? tabName : this.GetTab(tabName, matchMode, caseSense)
if this.BrowserType = "Vivaldi"
selectedTab.ControlClick(,, "NA", this.BrowserId)
else
selectedTab.Click()
} catch TargetError
throw TargetError("Tab with name " tabName " was not found (MatchMode: " matchMode ", CaseSense: " caseSense ")")
return selectedTab
}
; Close tab by either providing the tab element or the name of the tab. If tabElementOrName is left empty, the current tab will be closed.
CloseTab(tabElementOrName:="", matchMode:=3, caseSense:=True) {
if IsObject(tabElementOrName) {
if (tabElementOrName.Type == UIA.Type.TabItem) {
try tabElementOrName.FindElement({i:-1}, 2).Click()
}
} else {
if (tabElementOrName == "") {
try this.GetTab().FindElement({i:-1}, 2).Click()
} else {
try {
targetTab := this.GetTab(tabElementOrName, matchMode, caseSense)
targetTab.FindElement({i:-1}, 2).Click()
} catch
throw TargetError("Tab with name " tabElementOrName " was not found (MatchMode: " matchMode ", CaseSense: " caseSense ")")
}
}
}
; Returns True if any of window 4 corners are visible
IsBrowserVisible() {
local X, Y, W, H
WinGetPos &X, &Y, &W, &H, "ahk_id" this.BrowserId
if ((this.BrowserId == this.WindowFromPoint(X, Y)) || (this.BrowserId == this.WindowFromPoint(X, Y+H-1)) || (this.BrowserId == this.WindowFromPoint(X+W-1, Y)) || (this.BrowserId == this.WindowFromPoint(X+W-1, Y+H-1)))
return True
return False
}
Send(text) {
SendMessage(0x0006, 1, this.BrowserId,, this.BrowserId)
ControlSend text, , this.BrowserId
}
ControlSend(text, releaseModifiers:=true) {
SendMessage(0x0006, 1, this.BrowserId,, this.BrowserId)
PrevKeyDelay := A_KeyDelay, PrevKeyDuration := A_KeyDuration
SetKeyDelay 0, 1
if releaseModifiers {
released := []
for key in ["LCtrl", "RCtrl", "LAlt", "RAlt", "LShift", "RShift"]
if GetKeyState(key)
released.Push(key), ControlSend("{" key " up}", , this.BrowserId)
}
ControlSend text, , this.BrowserId
if releaseModifiers {
for key in released
ControlSend "{" key " down}", , this.BrowserId
}
SetKeyDelay PrevKeyDelay, PrevKeyDuration
}
WindowFromPoint(X, Y) { ; by SKAN and Linear Spoon
return DllCall( "GetAncestor", "UInt"
, DllCall( "WindowFromPoint", "UInt64", (X & 0xFFFFFFFF) | (Y << 32))
, "UInt", 2 ) ; GA_ROOT
}
PrintArray(arr) {
local ret := "", k, v
for k, v in arr
ret .= "Key: " k " Value: " (HasMethod(v)? v.name:IsObject(v)?this.PrintArray(v):v) "`n"
return ret
}
static CompareTitles(compareTitle, winTitle, matchMode:="", caseSense:=True) => UIA_Browser.StrCompare(winTitle, compareTitle, matchMode ? matchMode : A_TitleMatchMode, caseSense)
static StrCompare(str1, str2, matchMode:=3, caseSense:=True) {
local str3, len3
matchMode := UIA.TypeValidation.MatchMode(matchMode)
if matchMode != "RegEx" && (len1 := StrLen(str1)) < (len2 := StrLen(str2))
str3 := str1, str1 := str2, str2 := str3, len3 := len1, len1 := len2, len2 := len3
if matchMode = 1
return caseSense ? SubStr(str1, 1, len2) == str2 : SubStr(str1, 1, len2) = str2
else if matchMode = 2
return InStr(str1, str2, caseSense)
else if matchMode = 3
return caseSense ? str1 == str2 : str1 = str2
else if matchMode = "Regex"
return RegExMatch(str1, str2)
return 0
}
}
; Explicit diagnostic only: class declarations must not run a library self-test.
; Normal startup initializes UIA through StudioApp.Start and logs its result.
; ==================== END VENDORED UIA-v2 ====================
; ==================== BEGIN VENDORED OCR ====================
/*
Descolada/OCR — https://github.com/Descolada/OCR
Pinned commit: 15154d1477eb21ade15dc82a62594053face757f
Retrieved October 26, 2026. Upstream source unmodified.
MIT License
Copyright (c) 2023 Descolada
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#Requires AutoHotkey v2
/**
* OCR library: a wrapper for the the UWP Windows.Media.Ocr library.
* Based on the UWP OCR function for AHK v1 by malcev.
*
* Ways of initiating OCR:
* OCR(RandomAccessStreamOrSoftwareBitmap, Options?)
* OCR.FromDesktop(Options?)
* OCR.FromMonitor(Monitor?, Options?)
* OCR.FromRect(X, Y, W, H, Options?)
* OCR.FromWindow(WinTitle:="", Options?, WinText:="", ExcludeTitle:="", ExcludeText:="")
* Note: the result object coordinates will be in CoordMode "Pixel"
* OCR.FromFile(FileName, Options?)
* OCR.FromBitmap(bitmap, Options?, hDC?)
* OCR.FromPDF(FileName, Options?, Start:=1, End?, Password:="") => returns an array of results for each PDF page
* OCR.FromPDFPage(FileName, page, Options?)
* Helper functions for PDF OCR:
* OCR.GetPdfPageCount(FileName, Password:="")
* OCR.GetPdfPageProperties(FileName, Page, Password:="")
*
* Options can be an object containing none or all of these elements:
* {
* lang: OCR language. Default is first from available languages. This can also be a function which evaluates to a language string.
* scale: a Float scale factor to zoom the image in or out, which might improve detection.
* The resulting coordinates will be adjusted to scale. Default is 1.
* grayscale: Boolean 0 | 1 whether to convert the image to black-and-white. Default is 0.
* monochrome: 0-255, converts all pixels with luminosity less than the threshold to black, otherwise to white. Default is 0 (no conversion).
* invertcolors: Boolean 0 | 1, whether to invert the colors of the image. Default is 0.
* rotate: 0 | 90 | 180 | 270, can be used to rotate the image clock-wise by degrees. Default is 0.
* flip: 0 | "x" | "y", can be used to flip the image on the x- or y-axis. Default is 0.
* x, y, w, h: can be used to crop the image. This is applied before scaling. Default is no cropping.
* decoder: gif | ico | jpeg | jpegxr | png | tiff | bmp. Optional bitmap codec name to decode RandomAccessStream. Default is automatic detection.
* }
*
* Note: Options also accepts any optional parameters after it like named parameters.
* Eg. OCR.FromMonitor({lang:"en-us", monitor:2})
*
* Additional methods:
* OCR.GetAvailableLanguages()
* OCR.LoadLanguage(lang:="FirstFromAvailableLanguages")
* OCR.WaitText(needle, timeout:=-1, func?, casesense:=False, comparefunc?)
* Calls a func (the provided OCR method) until a string is found
* OCR.WordsBoundingRect(words*)
* Returns the bounding rectangle for multiple words
* OCR.ClearAllHighlights()
* Removes all highlights created by Result.Highlight
* OCR.Cluster(objs, eps_x:=-1, eps_y:=-1, minPts:=1, compareFunc?, &noise?)
* Clusters objects (by default based on distance from eachother). Can be used to create more
* accurate "Line" results.
* OCR.SortArray(arr, optionsOrCallback:="N", key?)
* Sorts an array in-place, optionally by object keys or using a callback function.
* OCR.ReverseArray(arr)
* Reverses an array in-place.
* OCR.UniqueArray(arr)
* Returns an array with unique values.
* OCR.FlattenArray(arr)
* Returns a one-dimensional array from a multi-dimensional array
*
* Properties:
* OCR.MaxImageDimension
* MinImageDimension is not documented, but appears to be 40 pixels (source: user FanaticGuru in AutoHotkey forums)
* OCR.PerformanceMode
* Increases speed of OCR acquisition by about 20-50ms if set to 1, but also increases CPU usage. Default is 0.
* OCR.DisplayImage
* If set to True then the captured image is displayed on the screen before proceeding to OCR-ing the image.
*
* OCR returns an OCR.Result object:
* Result.Text => All recognized text
* Result.TextAngle => Clockwise rotation of the recognized text
* Result.Lines => Array of all OCR.Line objects
* Result.Words => Array of all OCR.Word objects
* Result.ImageWidth => Used image width
* Result.ImageHeight => Used image height
*
* Result.FindString(Needle, Options?)
* Finds a string in the result. Possible options (see descriptions at the function definition):
* {CaseSense: False, IgnoreLinebreaks: False, AllowOverlap: false, i: 1, x, y, w, h, SearchFunc}
* Result.FindStrings(Needle, Options?)
* Finds all strings in the result.
* Result.Filter(callback)
* Returns a filtered result object that contains only words that satisfy the callback function
* Result.Crop(x1, y1, x2, y2)
* Crops the result object to contain only results from an area defined by points (x1,y1) and (x2,y2).
*
* OCR.Line object:
* Line.Text => Recognized text of the line
* Line.Words => Array of Word objects for the Line
* Line.x,y,w,h => Size and location of the Line.
*
* OCR.Word object:
* Word.Text => Recognized text of the word
* Word.x,y,w,h => Size and location of the Word.
* Word.BoundingRect => Bounding rectangle of the Word in format {x,y,w,h}.
*
* OCR.Result, OCR.Line, and OCR.Word also all have some common methods:
*
* Result.Click(WhichButton?, ClickCount?, DownOrUp?)
* Clicks an object (Word, FindString result etc)
* Result.ControlClick(WinTitle?, WinText?, WhichButton?, ClickCount?, Options?, ExcludeTitle?, ExcludeText?)
* ControlClicks an object (Word, FindString result etc)
* Result.Highlight(showTime?, color:="Red", d:=2)
* Highlights a Word, Line, or object with {x,y,w,h} properties on the screen (default: 2 seconds), or removes the highlighting
*
* Additional notes:
* Languages are recognized in BCP-47 language tags. Eg. OCR.FromFile("myfile.bmp", {lang: "en-AU"})
* Languages can be installed for example with PowerShell (run as admin): Install-Language
* or from Language settings in Settings.
* Not all language packs support OCR though. A list of supported language can be gotten from
* Powershell (run as admin) with the following command: Get-WindowsCapability -Online | Where-Object { $_.Name -Like 'Language.OCR*' }
*/
class OCR {
static Version => "2.0.0"
static IID_IRandomAccessStream := "{905A0FE1-BC53-11DF-8C49-001E4FC686DA}"
, IID_IPicture := "{7BF80980-BF32-101A-8BBB-00AA00300CAB}"
, IID_IAsyncInfo := "{00000036-0000-0000-C000-000000000046}"
, IID_IAsyncOperation_OcrResult := "{c7d7118e-ae36-59c0-ac76-7badee711c8b}"
, IID_IAsyncOperation_SoftwareBitmap := "{c4a10980-714b-5501-8da2-dbdacce70f73}"
, IID_IAsyncOperation_BitmapDecoder := "{aa94d8e9-caef-53f6-823d-91b6e8340510}"
, IID_IAsyncOperationCompletedHandler_OcrResult := "{989c1371-444a-5e7e-b197-9eaaf9d2829a}"
, IID_IAsyncOperationCompletedHandler_SoftwareBitmap := "{b699b653-33ed-5e2d-a75f-02bf90e32619}"
, IID_IAsyncOperationCompletedHandler_BitmapDecoder := "{bb6514f2-3cfb-566f-82bc-60aabd302d53}"
, IID_IPdfDocumentStatics := "{433A0B5F-C007-4788-90F2-08143D922599}"
, Vtbl_GetDecoder := {bmp:6, jpg:7, jpeg:7, png:8, tiff:9, gif:10, jpegxr:11, ico:12}
, PerformanceMode := 0
, DisplayImage := 0
class IBase {
__OCR := OCR
__New(ptr?) {
if IsSet(ptr) {
if !ptr
throw ValueError('Invalid IUnknown interface pointer', -2, this.__Class)
else if IsObject(ptr) {
if ptr.HasProp("Relative")
this.DefineProp("Relative", {value: ptr.Relative})
ptr := 0
}
}
this.DefineProp("ptr", {Value:ptr ?? 0})
}
__Delete() => this.ptr ? ObjRelease(this.ptr) : 0
}
static __New() {
this.LanguageFactory := this.CreateClass("Windows.Globalization.Language", ILanguageFactory := "{9B0252AC-0C27-44F8-B792-9793FB66C63E}")
this.SoftwareBitmapFactory := this.CreateClass("Windows.Graphics.Imaging.SoftwareBitmap", "{c99feb69-2d62-4d47-a6b3-4fdb6a07fdf8}")
this.BitmapTransform := this.CreateClass("Windows.Graphics.Imaging.BitmapTransform")
this.BitmapDecoderStatics := this.CreateClass("Windows.Graphics.Imaging.BitmapDecoder", IBitmapDecoderStatics := "{438CCB26-BCEF-4E95-BAD6-23A822E58D01}")
this.BitmapEncoderStatics := this.CreateClass("Windows.Graphics.Imaging.BitmapEncoder", IBitmapDecoderStatics := "{a74356a7-a4e4-4eb9-8e40-564de7e1ccb2}")
this.SoftwareBitmapStatics := this.CreateClass("Windows.Graphics.Imaging.SoftwareBitmap", ISoftwareBitmapStatics := "{df0385db-672f-4a9d-806e-c2442f343e86}")
this.OcrEngineStatics := this.CreateClass("Windows.Media.Ocr.OcrEngine", IOcrEngineStatics := "{5BFFA85A-3384-3540-9940-699120D428A8}")
ComCall(6, this.OcrEngineStatics, "uint*", &MaxImageDimension:=0) ; MaxImageDimension
this.MaxImageDimension := MaxImageDimension
DllCall("Dwmapi\DwmIsCompositionEnabled", "Int*", &compositionEnabled:=0)
this.CAPTUREBLT := compositionEnabled ? 0 : 0x40000000
/* // Based on code by AHK forums user Xtra
unsigned int Convert_GrayScale(unsigned int bitmap[], unsigned int w, unsigned int h, unsigned int Stride)
{
unsigned int a, r, g, b, gray, ARGB;
unsigned int x, y, offset = Stride/4;
for (y = 0; y < h * offset; y += offset) {
for (x = 0; x < w; ++x) {
ARGB = bitmap[x+y];
a = ARGB & 0xFF000000;
r = (ARGB & 0x00FF0000) >> 16;
g = (ARGB & 0x0000FF00) >> 8;
b = (ARGB & 0x000000FF);
gray = ((300 * r) + (590 * g) + (110 * b)) >> 10;
bitmap[x+y] = (gray << 16) | (gray << 8) | gray | a;
}
}
return 0;
}
*/
this.GrayScaleMCode := this.MCode((A_PtrSize = 4)
? "2,x86:VVdWU4PsCIt8JCiLdCQki0QkIMHvAg+v94k0JIX2dH+FwHR7jTS9AAAAAIl0JASLdCQcjRyGMfaNtCYAAAAAkItEJByNDLCNtCYAAAAAZpCLEYPBBInQD7buwegQae1OAgAAD7bAacAsAQAAAegPtuqB4gAAAP9r7W4B6MHoConFCcLB4AjB5RAJ6gnQiUH8Odl1vAH+A1wkBDs0JHKhg8QIMcBbXl9dww=="
: "2,x64:V1ZTQcHpAkSJxkiJy0GJ00EPr/GF9nRnRTHAhdJ0YJBEicEPH0QAAInIg8EBTI0Ug0GLEonQD7b+wegQaf9OAgAAD7bAacAsAQAAAfgPtvqB4gAAAP9r/24B+MHoConHCcLB4AjB5xAJ+gnCQYkSRDnZdbRFAchFActBOfByoTHAW15fww==")
/*
unsigned int Invert_Colors(unsigned int bitmap[], unsigned int w, unsigned int h, unsigned int Stride)
{
unsigned int a, r, g, b, gray, ARGB;
unsigned int x, y, offset = Stride/4;
for (y = 0; y < h * offset; y += offset) {
for (x = 0; x < w; ++x) {
ARGB = bitmap[x+y];
a = ARGB & 0xFF000000;
r = (ARGB & 0x00FF0000) >> 16;
g = (ARGB & 0x0000FF00) >> 8;
b = (ARGB & 0x000000FF);
bitmap[x+y] = ((255-r) << 16) | ((255-g) << 8) | (255-b) | a;
}
}
return 0;
}
*/
this.InvertColorsMCode := this.MCode((A_PtrSize = 4)
? "2,x86:VVdWU4PsCItsJCiLfCQki0QkIMHtAg+v/Yk8JIX/dGeFwHRjjTytAAAAAIl8JASLfCQcjTSHMf+NtCYAAAAAkItEJByNDLiNtCYAAAAAZpCLEYPBBInQidOB4v8AAP/30PfTgPL/JQAA/wCB4wD/AAAJ2AnQiUH8OfF11AHvA3QkBDs8JHK5g8QIMcBbXl9dww=="
: "2,x64:V1ZTQcHpAkSJx0iJzonTQQ+v+YX/dFNFMcCF0nRMZpBEicEPH0QAAInIg8EBTI0chkGLE4nQQYnSgeL/AAD/99BB99KA8v8lAAD/AEGB4gD/AABECdAJ0EGJAznLdclFAchEActBOfhytjHAW15fww==")
/*
unsigned int Convert_Monochrome(unsigned int bitmap[], unsigned int w, unsigned int h, unsigned int Stride, unsigned int threshold)
{
unsigned int a, r, g, b, ARGB;
unsigned int x, y, offset = Stride / 4;
for (y = 0; y < h * offset; y += offset) {
for (x = 0; x < w; ++x) {
ARGB = bitmap[x + y];
a = ARGB & 0xFF000000;
r = (ARGB & 0x00FF0000) >> 16;
g = (ARGB & 0x0000FF00) >> 8;
b = (ARGB & 0x000000FF);
unsigned int luminance = (77 * r + 150 * g + 29 * b) >> 8;
bitmap[x + y] = (luminance > threshold) ? 0xFFFFFFFF : 0xFF000000;
}
}
return 0;
}
*/
this.MonochromeMCode := this.MCode((A_PtrSize = 4)
? "2,x86:VVdWU4PsDIt0JCyLTCQoi0QkJIt8JDDB7gIPr86JNCSJTCQEhcl0aYXAdGXB5gIx7Yl0JAiLdCQgjTSGjXQmAItEJCCNDKiNtCYAAAAAZpCLEYnTD7bGD7bSwesQacCWAAAAD7bba9Ida9tNAdgB0MHoCDn4dinHAf////+DwQQ58XXMAywkA3QkCDlsJAR3r4PEDDHAW15fXcONdCYAkMcBAAAA/4PBBDnxdaMDLCQDdCQIOWwkBHeG69U="
: "2,x64:VVdWU4t0JEhBwekCRInHSInLQYnTQQ+v+YX/dFyF0nRYRTHADx9AAESJwQ8fRAAAichMjRSDQYsSidUPtsYPttLB7RBpwJYAAABAD7bta9Ida+1NAegB0MHoCDnwdiGDwQFBxwL/////QTnLdcJFAchFActEOcd3rzHAW15fXcODwQFBxwIAAAD/RDnZdaFFAchFActEOcd3juvd")
}
/**
* Returns an OCR results object for an IRandomAccessStream.
* Images of other types should be first converted to this format (eg from file, from bitmap).
* @param RandomAccessStreamOrSoftwareBitmap Pointer or an object containing a ptr to a RandomAccessStream or SoftwareBitmap
* @param {String} lang OCR language. Default is first from available languages.
* @param {Integer|Object} transform Either a scale factor number, or an object {scale:Float, grayscale:Boolean, invertcolors:Boolean, monochrome:0-255, rotate: 0 | 90 | 180 | 270, flip: 0 | "x" | "y"}
* @param {String} decoder Optional bitmap codec name to decode RandomAccessStream. Default is automatic detection.
* Possible values are gif, ico, jpeg, jpegxr, png, tiff, bmp.
* @returns {OCR.Result}
*/
static Call(RandomAccessStreamOrSoftwareBitmap, Options:=0) {
local SoftwareBitmap := 0, RandomAccessStream := 0, lang:="FirstFromAvailableLanguages", width, height, x := 0, y := 0, w := 0, h := 0, scale, grayscale, invertcolors, monochrome, OcrResult := this.Result(), Result, transform := 0, decoder := 0
this.__ExtractTransformParameters(Options, &transform)
scale := transform.scale, grayscale := transform.grayscale, invertcolors := transform.invertcolors, monochrome := transform.monochrome, rotate := transform.rotate, flip := transform.flip
this.__ExtractNamedParameters(Options, "x", &x, "y", &y, "w", &w, "h", &h, "language", &lang, "lang", &lang, "decoder", &decoder)
this.LoadLanguage(lang)
local customRegion := x || y || w || h
try SoftwareBitmap := ComObjQuery(RandomAccessStreamOrSoftwareBitmap, "{689e0708-7eef-483f-963f-da938818e073}") ; ISoftwareBitmap
if SoftwareBitmap {
ComCall(8, SoftwareBitmap, "uint*", &width:=0) ; get_PixelWidth
ComCall(9, SoftwareBitmap, "uint*", &height:=0) ; get_PixelHeight
this.ImageWidth := width, this.ImageHeight := height
if (Floor(width*scale) > this.MaxImageDimension) or (Floor(height*scale) > this.MaxImageDimension)
throw ValueError("Image is too big - " width "x" height ".`nIt should be maximum - " this.MaxImageDimension " pixels (with scale applied)")
if scale != 1 || customRegion || rotate || flip
SoftwareBitmap := this.TransformSoftwareBitmap(SoftwareBitmap, &width, &height, scale, rotate, flip, x?, y?, w?, h?)
goto SoftwareBitmapCommon
}
RandomAccessStream := RandomAccessStreamOrSoftwareBitmap
if decoder {
ComCall(this.Vtbl_GetDecoder.%decoder%, this.BitmapDecoderStatics, "ptr", DecoderGUID:=Buffer(16))
ComCall(15, this.BitmapDecoderStatics, "ptr", DecoderGUID, "ptr", RandomAccessStream, "ptr*", BitmapDecoder:=ComValue(13,0)) ; CreateAsync
} else
ComCall(14, this.BitmapDecoderStatics, "ptr", RandomAccessStream, "ptr*", BitmapDecoder:=ComValue(13,0)) ; CreateAsync
this.WaitForAsync(&BitmapDecoder)
BitmapFrame := ComObjQuery(BitmapDecoder, IBitmapFrame := "{72A49A1C-8081-438D-91BC-94ECFC8185C6}")
ComCall(12, BitmapFrame, "uint*", &width:=0) ; get_PixelWidth
ComCall(13, BitmapFrame, "uint*", &height:=0) ; get_PixelHeight
if (width > this.MaxImageDimension) or (height > this.MaxImageDimension)
throw ValueError("Image is too big - " width "x" height ".`nIt should be maximum - " this.MaxImageDimension " pixels")
BitmapFrameWithSoftwareBitmap := ComObjQuery(BitmapDecoder, IBitmapFrameWithSoftwareBitmap := "{FE287C9A-420C-4963-87AD-691436E08383}")
OcrResult.ImageWidth := width, OcrResult.ImageHeight := height
if !(customRegion || rotate || flip) && (width < 40 || height < 40 || scale != 1) {
scale := scale = 1 ? 40.0 / Min(width, height) : scale
ComCall(7, this.BitmapTransform, "int", width := Floor(width*scale)) ; put_ScaledWidth
ComCall(9, this.BitmapTransform, "int", height := Floor(height*scale)) ; put_ScaledHeight
ComCall(8, BitmapFrame, "uint*", &BitmapPixelFormat:=0) ; get_BitmapPixelFormat
ComCall(9, BitmapFrame, "uint*", &BitmapAlphaMode:=0) ; get_BitmapAlphaMode
ComCall(8, BitmapFrameWithSoftwareBitmap, "uint", BitmapPixelFormat, "uint", BitmapAlphaMode, "ptr", this.BitmapTransform, "uint", IgnoreExifOrientation := 0, "uint", DoNotColorManage := 0, "ptr*", SoftwareBitmap:=this.IBase()) ; GetSoftwareBitmapAsync
} else {
ComCall(6, BitmapFrameWithSoftwareBitmap, "ptr*", SoftwareBitmap:=this.IBase()) ; GetSoftwareBitmapAsync
}
this.WaitForAsync(&SoftwareBitmap)
if customRegion || rotate || flip || scale != 1
SoftwareBitmap := this.TransformSoftwareBitmap(SoftwareBitmap, &width, &height, scale, rotate, flip, x?, y?, w?, h?)
SoftwareBitmapCommon:
if (grayscale || invertcolors || monochrome || this.DisplayImage) {
ComCall(15, SoftwareBitmap, "int", 2, "ptr*", &BitmapBuffer := 0) ; LockBuffer
MemoryBuffer := ComObjQuery(BitmapBuffer, "{fbc4dd2a-245b-11e4-af98-689423260cf8}")
ComCall(6, MemoryBuffer, "ptr*", &MemoryBufferReference := 0) ; CreateReference
BufferByteAccess := ComObjQuery(MemoryBufferReference, "{5b0d3235-4dba-4d44-865e-8f1d0e4fd04d}")
ComCall(3, BufferByteAccess, "ptr*", &SoftwareBitmapByteBuffer:=0, "uint*", &BufferSize:=0) ; GetBuffer
if grayscale
DllCall(this.GrayScaleMCode, "ptr", SoftwareBitmapByteBuffer, "uint", width, "uint", height, "uint", (width*4+3) // 4 * 4, "cdecl uint")
if monochrome
DllCall(this.MonochromeMCode, "ptr", SoftwareBitmapByteBuffer, "uint", width, "uint", height, "uint", (width*4+3) // 4 * 4, "uint", monochrome, "cdecl uint")
if invertcolors
DllCall(this.InvertColorsMCode, "ptr", SoftwareBitmapByteBuffer, "uint", width, "uint", height, "uint", (width*4+3) // 4 * 4, "cdecl uint")
if this.DisplayImage {
local hdc := DllCall("GetDC", "ptr", 0, "ptr"), bi := Buffer(40, 0), hbm
NumPut("uint", 40, "int", width, "int", -height, "ushort", 1, "ushort", 32, bi)
hbm := DllCall("CreateDIBSection", "ptr", hdc, "ptr", bi, "uint", 0, "ptr*", &ppvBits:=0, "ptr", 0, "uint", 0, "ptr")
DllCall("ntdll\memcpy", "ptr", ppvBits, "ptr", SoftwareBitmapByteBuffer, "uint", BufferSize, "cdecl")
DllCall("ReleaseDC", "Ptr", 0, "Ptr", hdc, "Int")
this.DisplayHBitmap(hbm)
}
BufferByteAccess := "", ObjRelease(MemoryBufferReference), MemoryBuffer := "", ObjRelease(BitmapBuffer) ; Release in correct order
}
ComCall(6, this.OcrEngine, "ptr", SoftwareBitmap, "ptr*", Result:=ComValue(13,0)) ; RecognizeAsync
this.WaitForAsync(&Result)
OcrResult.Ptr := Result.Ptr, ObjAddRef(OcrResult.ptr)
; Cleanup
if RandomAccessStream is this.IBase
this.CloseIClosable(RandomAccessStream)
if SoftwareBitmap is this.IBase
this.CloseIClosable(SoftwareBitmap)
if scale != 1 || x != 0 || y != 0
this.NormalizeCoordinates(OcrResult, scale, x, y)
return OcrResult
}
static ClearAllHighlights() => this.Result.Prototype.Highlight("clearall")
class Result extends OCR.Common {
; Gets the recognized text.
Text {
get {
ComCall(8, this, "ptr*", &hAllText:=0) ; get_Text
buf := DllCall("Combase.dll\WindowsGetStringRawBuffer", "ptr", hAllText, "uint*", &length:=0, "ptr")
this.DefineProp("Text", {Value:StrGet(buf, "UTF-16")})
this.__OCR.DeleteHString(hAllText)
return this.Text
}
}
; Gets the clockwise rotation of the recognized text, in degrees, around the center of the image.
TextAngle {
get => (ComCall(7, this, "double*", &value:=0), value)
}
; Returns all Line objects for the result.
Lines {
get {
ComCall(6, this, "ptr*", LinesList:=ComValue(13, 0)) ; get_Lines
ComCall(7, LinesList, "int*", &count:=0) ; count
lines := []
loop count {
ComCall(6, LinesList, "int", A_Index-1, "ptr*", Line:=this.__OCR.Line(this))
lines.Push(Line)
}
this.DefineProp("Lines", {Value:lines})
return lines
}
}
; Returns all Word objects for the result. Equivalent to looping over all the Lines and getting the Words.
Words {
get {
local words := [], line, word
for line in this.Lines
for word in line.Words
words.Push(word)
this.DefineProp("Words", {Value:words})
return words
}
}
BoundingRect {
get => this.DefineProp("BoundingRect", {Value:this.__OCR.WordsBoundingRect(this.Words*)}).BoundingRect
}
/**
* Finds a string in the search results, and returns a new Result object.
* If the match is partial then the result will contain the whole word: in "hello world" searching "wo" will return "world".
* To force a full word search instead of a partial search, use IgnoreLinebreaks:True
* and add a space to the beginning and end: " hello "
* To search multi-line matches, set IgnoreLinebreaks:True and use a linebreak in the needle: "hello`nworld"
* @param Needle The string to find.
* @param Options Extra search options object, which can contain the following properties:
* CaseSense: False (this is ignored if a custom SearchFunc is used)
* IgnoreLinebreaks: False (if this is True, then linebreaks are converted to whitespaces, otherwise remain `n)
* AllowOverlap: False (if True then the needle can overlap itself)
* i: 1 (which occurrence of the needle to find)
* x, y, w, h: defines the search area inside the result object
* SearchFunc: default is InStr, but if a custom function is provided then it needs to return
* the needle location in the haystack, and accept arguments (Haystack, Needle, &FoundMatch)
* This can used for example to perform a RegEx search by providing RegExMatch
* @returns {Object}
*/
FindString(Needle, Options := "") => this.__FindString(Needle, Options, 0)
/**
* Finds all strings matching the needle in the search results. Returns an array of Result objects.
* @param Needle The string to find.
* @param Options See Result.FindString. {CaseSense: False, IgnoreLinebreaks: False, AllowOverlap: false, i: 1, x, y, w, h, SearchFunc}
* If i is specified then the result object will contains matches starting from i.
* @returns {Array}
*/
FindStrings(Needle, Options := "") => this.__FindString(Needle, Options, true)
__FindString(Needle, Options, All) {
local CaseSense := false, IgnoreLinebreaks := false, AllowOverlap := false, i := 1, SearchFunc, x, y, w, h
local currentHaystack, fullHaystackLinebreaks := "`n", offset := 0, line, counter := 0, x1, y1, x2, y2, result, results := [], word
if !(Needle is String)
throw TypeError("Needle is required to be a string, not type " Type(Needle), -1)
if Trim(Needle, " `t`n`r") == ""
throw ValueError("Needle cannot be an empty string", -1)
this.__OCR.__ExtractNamedParameters(Options, "CaseSense", &CaseSense, "IgnoreLinebreaks", &IgnoreLinebreaks, "AllowOverlap", &AllowOverlap, "i", &i, "SearchFunc", &SearchFunc, "x", &x, "y", &y, "w", &w, "h", &h)
if !IsSet(SearchFunc)
SearchFunc := (haystack, needle, &foundstr) => (pos := InStr(haystack, needle, casesense), foundstr := SubStr(haystack, pos, StrLen(needle)), pos)
if (IsSet(x) || IsSet(y) || IsSet(w) || IsSet(h)) {
x1 := x ?? -100000, y1 := y ?? -100000, x2 := IsSet(w) ? x + w : 100000, y2 := IsSet(h) ? y + h : 100000
}
tokenizedHaystack := [IgnoreLinebreaks ? " " : "`n"]
for Line in this.Lines {
fullHaystackLinebreaks .= line.Text "`n"
for Word in Line.Words
tokenizedHaystack.Push(Word, " ")
tokenizedHaystack.Pop()
tokenizedHaystack.Push(IgnoreLinebreaks ? " " : "`n")
}
fullHaystackNoLinebreaks := StrReplace(fullHaystackLinebreaks, "`n", " ") ; Make sure the words are in the same order as the tokenized version
fullHaystack := IgnoreLinebreaks ? fullHaystackNoLinebreaks : fullHaystackLinebreaks
Needle := RegExReplace(StrReplace(Needle, "`t", " "), " +", " ")
fullFirst := SubStr(Needle, 1, 1) ~= "[ \n]", fullLast := SubStr(Needle, -1, 1) ~= "[ \n]"
currentHaystack := fullHaystack
Loop {
if !(loc := SearchFunc(currentHaystack, Needle, &foundNeedle))
break
if IsObject(foundNeedle)
foundNeedle := foundNeedle[]
foundLen := AllowOverlap ? 1 : StrLen(foundNeedle)
currentHaystack := SubStr(currentHaystack, loc + foundLen) ; Remove the match from the haystack, allowing overlap
offset += loc + foundLen - 1
if ++counter < i
continue
tokenizedNeedle := []
; Tokenize the needle
for wsNeedle in wsSplit := StrSplit(foundNeedle, " ") {
for lbNeedle in lbSplit := StrSplit(wsNeedle, "`n") {
tokenizedNeedle.Push(lbNeedle, "`n")
}
if lbSplit.Length
tokenizedNeedle.Pop()
tokenizedNeedle.Push(" ")
}
tokenizedNeedle.Pop()
preceding := SubStr(fullHaystackNoLinebreaks, 1, offset - foundLen)
; Find first Word location
StrReplace(preceding, " ",,, &startingWord:=0)
startingWord := startingWord*2 + fullFirst - 1 ; Substracted 1 to allow subsequent loop to just add A_Index
foundNeedle := "", foundWords := [], foundLines := [], line := this.__OCR.Line(this), line.DefineProp("Words", {value:[]}), line.DefineProp("Text", {value:""})
Loop tokenizedNeedle.Length {
word := tokenizedHaystack[startingWord + A_Index]
if (word == "`n") {
foundNeedle .= line.Text
line.Text := RTrim(line.Text), foundLines.Push(line)
line := this.__OCR.Line(this), line.DefineProp("Words", {value:[]}), line.DefineProp("Text", {value:""})
}
if !IsObject(word)
continue
If IsSet(x1) && (word.x < x1 || word.y < y1 || word.x+word.w > x2 || word.y+word.h > y2) {
counter--
continue 2
}
line.Words.Push(word), line.Text .= word.Text " "
foundWords.Push(word)
}
if line.Text {
foundNeedle .= line.Text
line.Text := RTrim(line.Text), foundLines.Push(line)
}
result := this.Clone(), ObjAddRef(this.ptr)
result.DefineProp("BoundingRect", {value: this.__OCR.WordsBoundingRect(foundWords*)})
result.DefineProp("Lines", {value: foundLines})
result.DefineProp("Words", {value: foundWords})
result.DefineProp("Text", {value: foundNeedle})
if All {
results.Push(result)
} else
return result
}
if All
return results
throw TargetError('The target string "' Needle '" was not found', -1)
}
/**
* Filters out all the words that do not satisfy the callback function and returns a new OCR.Result object
* @param {Object} callback The callback function that accepts a OCR.Word object.
* If the callback returns 0 then the word is filtered out (rejected), otherwise is kept.
* @returns {OCR.Result}
*/
Filter(callback) {
if !HasMethod(callback)
throw ValueError("Filter callback must be a function", -1)
local result := this.Clone(), line, croppedLines := [], croppedText := "", croppedWords := [], lineText := "", word
ObjAddRef(result.ptr)
for line in result.Lines {
croppedWords := [], lineText := ""
for word in line.Words {
if callback(word)
croppedWords.Push(word), lineText .= word.Text " "
}
if croppedWords.Length {
line := this.__OCR.Line()
line.DefineProp("Text", {value:Trim(lineText)})
line.DefineProp("Words", {value:croppedWords})
croppedLines.Push(line)
croppedText .= lineText
}
}
result.DefineProp("Lines", {Value:croppedLines})
result.DefineProp("Text", {Value:Trim(croppedText)})
result.DefineProp("Words", this.__OCR.Result.Prototype.GetOwnPropDesc("Words"))
return result
}
/**
* Crops the result object to contain only results from an area defined by points (x1,y1) and (x2,y2).
* Note that these coordinates are relative to the result object, not to the screen.
* @param {Integer} x1 x coordinate of the top left corner of the search area
* @param {Integer} y1 y coordinate of the top left corner of the search area
* @param {Integer} x2 x coordinate of the bottom right corner of the search area
* @param {Integer} y2 y coordinate of the bottom right corner of the search area
* @returns {OCR.Result}
*/
Crop(x1:=-100000, y1:=-100000, x2:=100000, y2:=100000) => this.Filter((word) => word.x >= x1 && word.y >= y1 && (word.x+word.w) <= x2 && (word.y+word.h) <= y2)
}
class Line extends OCR.Common {
; Gets the recognized text for the line.
Text {
get {
ComCall(7, this, "ptr*", &hText:=0) ; get_Text
buf := DllCall("Combase.dll\WindowsGetStringRawBuffer", "ptr", hText, "uint*", &length:=0, "ptr")
text := StrGet(buf, "UTF-16")
this.__OCR.DeleteHString(hText)
this.DefineProp("Text", {Value:text})
return text
}
}
; Gets the Word objects for the line
Words {
get {
ComCall(6, this, "ptr*", WordsList:=ComValue(13, 0)) ; get_Words
ComCall(7, WordsList, "int*", &WordsCount:=0) ; Words count
words := []
loop WordsCount {
ComCall(6, WordsList, "int", A_Index-1, "ptr*", Word:=this.__OCR.Word(this))
words.Push(Word)
}
this.DefineProp("Words", {Value:words})
return words
}
}
BoundingRect {
get => this.DefineProp("BoundingRect", {Value:this.__OCR.WordsBoundingRect(this.Words*)}).BoundingRect
}
}
class Word extends OCR.Common {
; Gets the recognized text for the word
Text {
get {
ComCall(7, this, "ptr*", &hText:=0) ; get_Text
buf := DllCall("Combase.dll\WindowsGetStringRawBuffer", "ptr", hText, "uint*", &length:=0, "ptr")
text := StrGet(buf, "UTF-16")
this.__OCR.DeleteHString(hText)
this.DefineProp("Text", {Value:text})
return text
}
}
/**
* Gets the bounding rectangle of the text in {x,y,w,h} format.
* The bounding rectangles coordinate system will be dependant on the image capture method.
* For example, if the image was captured as a rectangle from the screen, then the coordinates
* will be relative to the left top corner of the screen.
*/
BoundingRect {
get {
ComCall(6, this, "ptr", RECT := Buffer(16, 0)) ; get_BoundingRect
this.DefineProp("x", {Value:Integer(NumGet(RECT, 0, "float"))})
, this.DefineProp("y", {Value:Integer(NumGet(RECT, 4, "float"))})
, this.DefineProp("w", {Value:Integer(NumGet(RECT, 8, "float"))})
, this.DefineProp("h", {Value:Integer(NumGet(RECT, 12, "float"))})
return this.DefineProp("BoundingRect", {Value:{x:this.x, y:this.y, w:this.w, h:this.h}}).BoundingRect
}
}
}
class Common extends OCR.IBase {
x {
get => this.BoundingRect.x
}
y {
get => this.BoundingRect.y
}
w {
get => this.BoundingRect.w
}
h {
get => this.BoundingRect.h
}
/**
* Highlights the object on the screen with a red box
* @param {number} showTime Default is 2 seconds.
* * Unset - if highlighting exists then removes the highlighting, otherwise pauses for 2 seconds
* * 0 - Indefinite highlighting
* * Positive integer (eg 2000) - will highlight and pause for the specified amount of time in ms
* * Negative integer - will highlight for the specified amount of time in ms, but script execution will continue
* * "clear" - removes the highlighting unconditionally
* * "clearall" - remove highlightings from all OCR objects
* @param {string} color The color of the highlighting. Default is red.
* @param {number} d The border thickness of the highlighting in pixels. Default is 2.
* @returns {OCR.Result}
*/
Highlight(showTime?, color:="Red", d:=2) {
static Guis := Map()
local x, y, w, h, key, oObj, GuiObj, iw, ih
; showTime unset => either highlights for 2s, or removes highlight
; showTime clear => removes highlight
if IsSet(showTime) {
if showTime = "clearall" {
for key, oObj in Guis { ; enum all OCR result objects
try oObj.GuiObj.Destroy()
SetTimer(oObj.TimerObj, 0)
}
Guis := Map()
return this
} else if showTime = "clear" {
if Guis.Has(this) {
try Guis[this].GuiObj.Destroy()
SetTimer(Guis[this].TimerObj, 0)
Guis.Delete(this)
}
return this
}
}
if !IsSet(showTime) {
if Guis.Has(this) {
try Guis[this].GuiObj.Destroy()
SetTimer(Guis[this].TimerObj, 0)
Guis.Delete(this)
return this
} else
showTime := 2000
}
x := this.x, y := this.y, w := this.w, h := this.h
if this.HasProp("Relative") {
if this.Relative.HasProp("CoordMode") {
if this.Relative.CoordMode = "Client"
WinGetClientPos(&rX, &rY,,, this.Relative.hWnd), x += rX, y += rY
else if this.Relative.CoordMode = "Window"
WinGetPos(&rX, &rY,,, this.Relative.hWnd), x += rX, y += rY
}
x += this.Relative.HasProp("x") ? this.Relative.x : 0
y += this.Relative.HasProp("y") ? this.Relative.y : 0
}
if !Guis.Has(this) {
Guis[this] := {}
Guis[this].GuiObj := Gui("+AlwaysOnTop -Caption +ToolWindow -DPIScale +E0x08000000")
Guis[this].TimerObj := ObjBindMethod(this, "Highlight", "clear")
}
GuiObj := Guis[this].GuiObj
GuiObj.BackColor := color
iw:= w+d, ih:= h+d, w:=w+d*2, h:=h+d*2, x:=x-d, y:=y-d
WinSetRegion("0-0 " w "-0 " w "-" h " 0-" h " 0-0 " d "-" d " " iw "-" d " " iw "-" ih " " d "-" ih " " d "-" d, GuiObj.Hwnd)
GuiObj.Show("NA x" . x . " y" . y . " w" . w . " h" . h)
if showTime > 0 {
Sleep(showTime)
this.Highlight()
} else if showTime < 0
SetTimer(Guis[this].TimerObj, -Abs(showTime))
return this
}
ClearHighlight() => this.Highlight("clear")
/**
* Clicks an object
* If this object (the one Click is called from) contains a "Relative" property (this is
* added by default with OCR.FromWindow) containing a hWnd property, then that window will be activated,
* otherwise the Relative objects x/y properties values will be added to the x and y coordinates as offsets.
*/
Click(WhichButton?, ClickCount?, DownOrUp?) {
local x := this.x, y := this.y, w := this.w, h := this.h, mode := "Screen", hwnd
if this.HasProp("Relative") {
if this.Relative.HasProp("CoordMode") {
if this.Relative.CoordMode = "Window"
mode := "Window", hwnd := this.Relative.Hwnd
else if this.Relative.CoordMode = "Client"
mode := "Client", hwnd := this.Relative.Hwnd
if IsSet(hwnd) && !WinActive(hwnd) {
WinActivate(hwnd)
WinWaitActive(hwnd,,1)
}
}
x += this.Relative.HasProp("x") ? this.Relative.x : 0
y += this.Relative.HasProp("y") ? this.Relative.y : 0
}
oldCoordMode := A_CoordModeMouse
CoordMode "Mouse", mode
Click(x+w//2, y+h//2, WhichButton?, ClickCount?, DownOrUp?)
CoordMode "Mouse", oldCoordMode
}
/**
* ControlClicks an object.
* If the result object originates from OCR.FromWindow which captured only the client area,
* then the result object will contain correct coordinates for the ControlClick.
* Coordinates will be adjusted to Client area from the CoordMode that the OCR happened in.
* Otherwise, if additionally a WinTitle is provided then the coordinates are treated as Screen
* coordinates and converted to Client coordinates.
* @param WinTitle If WinTitle is set, then the coordinates stored in Obj will be converted to
* client coordinates and ControlClicked.
*/
ControlClick(WinTitle?, WinText?, WhichButton?, ClickCount?, Options?, ExcludeTitle?, ExcludeText?) {
local x := this.x, y := this.y, w := this.w, h := this.h, hWnd
if this.HasProp("Relative") {
x += this.Relative.HasProp("x") ? this.Relative.x : 0
y += this.Relative.HasProp("y") ? this.Relative.y : 0
}
if this.HasProp("Relative") && this.Relative.HasProp("CoordMode") && (this.Relative.CoordMode = "Client" || this.Relative.CoordMode = "Window") {
mode := this.Relative.CoordMode, hWnd := this.Relative.hWnd
if mode = "Window" {
; Window -> Client
RECT := Buffer(16, 0), pt := Buffer(8, 0)
DllCall("user32\GetWindowRect", "Ptr", hWnd, "Ptr", RECT)
winX := NumGet(RECT, 0, "Int"), winY := NumGet(RECT, 4, "Int")
NumPut("int", winX+x, "int", winY+y, pt)
DllCall("user32\ScreenToClient", "Ptr", hWnd, "Ptr", pt)
x := NumGet(pt,0,"int"), y := NumGet(pt,4,"int")
}
} else if IsSet(WinTitle) {
hWnd := WinExist(WinTitle, WinText?, ExcludeTitle?, ExcludeText?)
pt := Buffer(8), NumPut("int",x,pt), NumPut("int", y,pt,4)
DllCall("ScreenToClient", "Int", Hwnd, "Ptr", pt)
x := NumGet(pt,0,"int"), y := NumGet(pt,4,"int")
} else
throw TargetError("ControlClick needs to be called either after a OCR.FromWindow result or with a WinTitle argument")
ControlClick("X" (x+w//2) " Y" (y+h//2), hWnd,, WhichButton?, ClickCount?, Options?)
}
OffsetCoordinates(offsetX?, offsetY?) {
if !IsSet(offsetX) || !IsSet(offsetY) {
if this.HasOwnProp("Relative") {
offsetX := this.Relative.HasProp("x") ? this.Relative.X : 0
offsetY := this.Relative.HasProp("y") ? this.Relative.Y : 0
} else
throw Error("No Relative property found",, -1)
}
if offsetX = 0 && offsetY = 0
return this
local word
for word in this.Words
word.x += offsetX, word.y += offsetY, word.BoundingRect := {X:word.x, Y:word.y, W:word.w, H:word.h}
return this
}
}
/**
* Returns an OCR results object for an image file. Locations of the words will be relative to
* the top left corner of the image.
* @param FileName Either full or relative (to A_WorkingDir) path to the file.
* @param lang OCR language. Default is first from available languages.
* @param transform Either a scale factor number, or an object {scale:Float, grayscale:Boolean, invertcolors:Boolean, monochrome:0-255, rotate: 0 | 90 | 180 | 270, flip: 0 | "x" | "y"}
* @returns {OCR.Result}
*/
static FromFile(FileName, Options:=0) {
if !(fe := FileExist(FileName)) or InStr(fe, "D")
throw TargetError("File `"" FileName "`" doesn't exist", -1)
GUID := this.CLSIDFromString(this.IID_IRandomAccessStream)
DllCall("ShCore\CreateRandomAccessStreamOnFile", "wstr", FileName, "uint", Read := 0, "ptr", GUID, "ptr*", IRandomAccessStream:=this.IBase())
if IsObject(Options) && !Options.HasProp("Decoder")
Options.Decoder := this.Vtbl_GetDecoder.HasOwnProp(ext := StrSplit(FileName, ".")[-1]) ? ext : ""
return this(IRandomAccessStream, Options)
}
/**
* Returns an array of OCR results objects for a PDF file. Locations of the words will be relative to
* the top left corner of the PDF page.
* @param FileName Either full or relative (to A_WorkingDir) path to the file.
* @param Options Optional: OCR options {lang, scale, grayscale, invertcolors, rotate, flip, x, y, w, h, decoder}.
* @param Start Optional: Page number to start from. Default is first page.
* @param End Optional: Page number to end with (included). Default is last page.
* @param Password Optional: PDF password.
* @returns {OCR.Result}
*/
static FromPDF(FileName, Options:=0, Start:=1, End?, Password:="") {
this.__ExtractNamedParameters(Options, "lang", &lang, "start", &Start, "end", &End, "password", &Password)
if !(fe := FileExist(FileName)) or InStr(fe, "D")
throw TargetError("File `"" FileName "`" doesn't exist", -1)
DllCall("ShCore\CreateRandomAccessStreamOnFile", "wstr", FileName, "uint", Read := 0, "ptr", GUID := this.CLSIDFromString(this.IID_IRandomAccessStream), "ptr*", IRandomAccessStream:=ComValue(13,0))
PdfDocument := this.__OpenPdfDocument(IRandomAccessStream, Password)
this.CloseIClosable(IRandomAccessStream)
if !IsSet(End) {
ComCall(7, PdfDocument, "uint*", &End:=0) ; GetPageCount
if !End
throw Error("Unable to get PDF page count", -1)
}
local results := []
Loop (End+1-Start)
results.Push(this.FromPDFPage(PdfDocument, Start+(A_Index-1), Options))
return results
}
static GetPdfPageCount(FileName, Password:="") {
DllCall("ShCore\CreateRandomAccessStreamOnFile", "wstr", FileName, "uint", Read := 0, "ptr", GUID := this.CLSIDFromString(this.IID_IRandomAccessStream), "ptr*", IRandomAccessStream:=ComValue(13,0))
PdfDocument := this.__OpenPdfDocument(IRandomAccessStream, Password)
this.CloseIClosable(IRandomAccessStream)
ComCall(7, PdfDocument, "uint*", &PageCount:=0) ; GetPageCount
if !PageCount
throw Error("Unable to get PDF page count", -1)
return PageCount
}
; Returns {Width, Height, Rotation, PreferredZoom}
static GetPdfPageProperties(FileName, Page, Password:="") {
DllCall("ShCore\CreateRandomAccessStreamOnFile", "wstr", FileName, "uint", Read := 0, "ptr", GUID := this.CLSIDFromString(this.IID_IRandomAccessStream), "ptr*", IRandomAccessStream:=ComValue(13,0))
PdfDocument := this.__OpenPdfDocument(IRandomAccessStream, Password)
this.CloseIClosable(IRandomAccessStream)
ComCall(6, PdfDocument, "uint", Page-1, "ptr*", PdfPage:=ComValue(13, 0)) ; GetPage
ComCall(10, PdfPage, "ptr*", Size:=Buffer(8, 0)) ; Size
ComCall(12, PdfPage, "uint*", &Rotation:=0)
ComCall(12, PdfPage, "float*", &PreferredZoom:=0)
return {Width: NumGet(Size, 0, "float"), Height: NumGet(size, 4, "float"), Rotation: Rotation*90, PreferredZoom:PreferredZoom}
}
/**
* Returns an OCR result object for a PDF page. Locations of the words will be relative to
* the top left corner of the PDF page.
* @param FileName Either full or relative (to A_WorkingDir) path to the file.
* @param Page The page number to OCR.
* @param Options Optional: OCR options {lang, scale, grayscale, invertcolors, rotate, flip, x, y, w, h, decoder}.
* @param Password Optional: PDF password.
* @returns {OCR.Result}
*/
static FromPDFPage(FileName, Page, Options:=0, Password:="") {
local scale := 1, x := 0, y := 0, w := 0, h := 0
if IsObject(Options)
Options := Options.Clone()
this.__ExtractNamedParameters(Options, "Password", &Password, "scale", &scale, "x", &x, "y", &y, "w", &w, "h", &h)
if FileName is String {
if !(fe := FileExist(FileName)) or InStr(fe, "D")
throw TargetError("File `"" FileName "`" doesn't exist", -1)
GUID := this.CLSIDFromString(this.IID_IRandomAccessStream)
DllCall("ShCore\CreateRandomAccessStreamOnFile", "wstr", FileName, "uint", Read := 0, "ptr", GUID, "ptr*", IRandomAccessStream:=ComValue(13, 0))
PdfDocument := this.__OpenPdfDocument(IRandomAccessStream, Password)
} else
PdfDocument := FileName
ComCall(6, PdfDocument, "uint", Page-1, "ptr*", PdfPage:=ComValue(13, 0)) ; GetPage
InMemoryRandomAccessStream := this.CreateClass("Windows.Storage.Streams.InMemoryRandomAccessStream")
PdfPageRenderOptions := this.CreateClass("Windows.Data.Pdf.PdfPageRenderOptions")
ComCall(15, PdfPageRenderOptions, "uint", true) ; IsIgnoringHighContrast
if x || y || w || h {
rect := Buffer(16, 0), NumPut("float", x, "float", y, "float", w, "float", h, rect)
ComCall(7, PdfPageRenderOptions, "ptr", rect) ; put_SourceRect
Options.w := Options.w*scale, Options.h := Options.h*scale
Options.DeleteProp("x"), Options.DeleteProp("y"), Options.DeleteProp("w"), Options.DeleteProp("h")
}
if (scale != 1) {
ComCall(10, PdfPage, "ptr", Size:=Buffer(8, 0)) ; get_Size
ComCall(9, PdfPageRenderOptions, "uint", Floor((w || NumGet(size, 0, "float"))*scale)) ; put_DestinationWidth
ComCall(11, PdfPageRenderOptions, "uint", Floor((h || NumGet(size, 4, "float"))*scale)) ; put_DestinationHeight
Options.DeleteProp("scale")
}
ComCall(7, PdfPage, "ptr", InMemoryRandomAccessStream, "ptr", PdfPageRenderOptions, "ptr*", asyncInfo:=ComValue(13, 0)) ; RenderWithOptionsToStreamAsync
this.WaitForAsync(&asyncInfo)
if FileName is String
this.CloseIClosable(IRandomAccessStream)
PdfPage := "", PdfDocument := "", IRandomAccessStream := ""
OcrResult := this(InMemoryRandomAccessStream, Options)
if scale != 1
this.NormalizeCoordinates(OcrResult, scale)
return OcrResult
}
/**
* Returns an OCR results object for a given window. Locations of the words will be relative
* using the CoordMode from A_CoordModePixel (default is Client).
* The window from where the image was captured is stored in Result.Relative.hWnd
* Additionally, Result.Relative.CoordMode is stored (the A_CoordModePixel at the time of OCR).
* @param WinTitle A window title or other criteria identifying the target window.
* @param Options Optional: OCR options {lang, scale, grayscale, invertcolors, rotate, flip, x, y, w, h, decoder}.
* Additionally for FromWindow the options may include:
* mode: Different methods of capturing the window.
* 0 = uses GetDC with BitBlt
* 1 = same as 0 but window transparency is turned off beforehand with WinSetTransparent
* 2 = uses PrintWindow.
* 3 = same as 1 but window transparency is turned off beforehand with WinSetTransparent
* 4 = uses PrintWindow with undocumented PW_RENDERFULLCONTENT flag, allowing capture of hardware-accelerated windows
* 5 = uses Direct3D11 from UWP Windows.Graphics.Capture (slowest option, but may work with games)
* This may draw a yellow border around the target window in older Windows versions.
* @param WinText Additional window criteria.
* @param ExcludeTitle Additional window criteria.
* @param ExcludeText Additional window criteria.
* @returns {OCR.Result}
*/
static FromWindow(WinTitle:="", Options:=0, WinText:="", ExcludeTitle:="", ExcludeText:="") {
local result, coordsmode := A_CoordModePixel, onlyClientArea := coordsMode = "Client", mode := 4, X := 0, Y := 0, W := 0, H := 0, sX, sY, hBitMap, hwnd, customRect := 0, transform := 0
if !Options && Type(WinTitle) = "Object"
Options := WinTitle, WinTitle := ""
if IsObject(Options)
Options := Options.Clone()
this.__ExtractTransformParameters(Options, &transform)
this.__ExtractNamedParameters(Options, "x", &x, "y", &y, "w", &w, "width", &w, "h", &h, "height", &h, "mode", &mode, "WinTitle", &WinTitle, "WinText", &WinText, "ExcludeTitle", &ExcludeTitle, "ExcludeText", &ExcludeText)
this.__DeleteProps(Options, "x", "y", "w", "width", "h", "height", "scale", "mode")
if (x !=0 || y != 0 || w != 0 || h != 0)
customRect := 1
if !(hWnd := WinExist(WinTitle, WinText, ExcludeTitle, ExcludeText))
throw TargetError("Target window not found", -1)
if DllCall("IsIconic", "uptr", hwnd)
DllCall("ShowWindow", "uptr", hwnd, "int", 4)
if mode < 4 && mode&1 {
oldStyle := WinGetExStyle(hwnd), i := 0
WinSetTransparent(255, hwnd)
While (WinGetTransparent(hwnd) != 255 && ++i < 30)
Sleep 100
}
WinGetPos(&wX, &wY, &wW, &wH, hWnd)
If onlyClientArea {
WinGetClientPos(&cX, &cY, &cW, &cH, hWnd)
W := W || cW, H := H || cH, sX := X + cX, sY := Y + cY ; Calculate final X and Y screen coordinates
} else {
W := W || wW, H := H || wH, sX := X + wX, sY := Y + wY
}
if mode = 5 {
/*
If we are capturing the whole window, then WinGetPos/MouseGetPos might include hidden borders.
Eg (0,0) might be (-11, -11) for Direct3D, meaning (11,11) by WinGetPos is (0,0) for Direct3D.
These offsets are calculated and stored in offsetX, offsetY, and if only the window
area is captured then the result object coordinates are adjusted accordingly.
If the SoftwareBitmap needs to be transformed in any way (eg scale or custom rect is
provided) then we need to offset coordinates and possibly width/height as well.
*/
SoftwareBitmap := this.CreateDirect3DSoftwareBitmapFromWindow(hWnd)
local sbW := SoftwareBitmap.W, sbH := SoftwareBitmap.H, sbX := SoftwareBitmap.X, sbY := SoftwareBitmap.Y
local offsetX := 0, offsetY := 0
if transform.scale != 1 || transform.rotate || transform.flip || customRect || onlyClientArea {
; The bounds need to fit inside the SoftwareBitmap bounds, so possibly X,Y need to be adjusted along with W,H
local tX := X, tY := Y, tW := W, tH := H
if onlyClientArea
tX -= SoftwareBitmap.X-cX, tY -= SoftwareBitmap.Y-cY
else
tX -= SoftwareBitmap.X-wX, tY -= SoftwareBitmap.Y-wY
if tX < 0 ; If resulting coordinates are negative then adjust width and height accordingly
tW += tX, offsetX := -tX, tX := 0
if tY < 0
tH += tY, offsetY := -tY, tY := 0
tW := Min(sbW-tX, tW), tH := Min(sbH-tY, tH)
SoftwareBitmap := this.TransformSoftwareBitmap(SoftwareBitmap, &sbW, &sbH, transform.scale, transform.rotate, transform.flip, tX, tY, tW, tH)
this.__DeleteProps(Options, "scale", "rotate", "flip")
} else
offsetX := sbX-wX, offsetY := sbY-wY
result := this(SoftwareBitmap, Options)
} else {
hBitMap := this.CreateHBitmap(X, Y, W, H, {hWnd:hWnd, onlyClientArea:onlyClientArea, mode:(mode//2)}, transform.scale)
if mode&1
WinSetExStyle(oldStyle, hwnd)
SoftwareBitmap := this.HBitmapToSoftwareBitmap(hBitMap,, transform)
this.__DeleteProps(Options, "invertcolors", "grayscale", "monochrome")
result := this(SoftwareBitmap, Options)
}
result.Relative := {CoordMode:coordsmode, hWnd:hWnd}
if coordsmode = "Screen"
x += sX, y += sY
this.NormalizeCoordinates(result, transform.scale, x, y)
if mode = 5 && !onlyClientArea
result.OffsetCoordinates(offsetX, offsetY)
return result
}
/**
* Returns an OCR results object for the specified monitor. Locations of the words will be relative to
* the primary screen (CoordMode "Screen"), even if a secondary monitor is being captured.
* @param Monitor Optional: The monitor from which to get the desktop area. Default is primary monitor.
* If screen scaling between monitors differs, then use DllCall("SetThreadDpiAwarenessContext", "ptr", -3)
* @param Options Optional: OCR options {lang, scale, grayscale, invertcolors, rotate, flip, x, y, w, h, decoder}.
* @returns {OCR.Result}
*/
static FromMonitor(Monitor?, Options:=0) {
if !Options && IsSet(Monitor) && IsObject(Monitor)
Options := Monitor, Monitor := unset
this.__ExtractNamedParameters(Options, "Monitor", &Monitor)
MonitorGet(monitor?, &Left, &Top, &Right, &Bottom)
return this.FromRect(Left, Top, Right-Left, Bottom-Top, Options)
}
/**
* Returns an OCR results object for the whole virtual screen. Locations of the words will be relative to
* the primary screen (CoordMode "Screen").
* @param Options Optional: OCR options {lang, scale, grayscale, invertcolors, rotate, flip, x, y, w, h, decoder}.
* If screen scaling between monitors differs, then use DllCall("SetThreadDpiAwarenessContext", "ptr", -3)
* @returns {OCR.Result}
*/
static FromDesktop(Options:=0) => this.FromRect(SysGet(76), SysGet(77), SysGet(78), SysGet(79), Options)
/**
* Returns an OCR results object for a region of the screen. Locations of the words will be relative
* to the screen.
* @param x Screen x coordinate
* @param y Screen y coordinate
* @param w Region width. Maximum is OCR.MaxImageDimension; minimum is 40 pixels (source: user FanaticGuru in AutoHotkey forums), smaller images will be scaled to at least 40 pixels.
* @param h Region height. Maximum is OCR.MaxImageDimension; minimum is 40 pixels, smaller images will be scaled accordingly.
* @param Options OCR options {lang, scale, grayscale, invertcolors, rotate, flip, x, y, w, h, decoder}.
* @returns {OCR.Result}
*/
static FromRect(x, y, w, h, Options:=0) {
local transform := 0, result
if IsObject(Options)
Options := Options.Clone()
this.__ExtractTransformParameters(Options, &transform)
this.__DeleteProps(Options, "scale", "invertcolors", "grayscale")
local scale := transform.scale
, hBitmap := this.CreateHBitmap(X, Y, W, H,, scale)
, SoftwareBitmap := this.HBitmapToSoftwareBitmap(hBitmap,, transform)
, result := this(SoftwareBitmap, Options)
return this.NormalizeCoordinates(result, scale, x, y)
}
/**
* Returns an OCR results object from a bitmap. Locations of the words will be relative
* to the top left corner of the bitmap.
* @param Bitmap A pointer to a GDIP Bitmap object, or HBITMAP, or an object with a ptr property
* set to one of the two.
* @param Options OCR options {lang, scale, grayscale, invertcolors, rotate, flip, x, y, w, h, decoder}.
* @param hDC Optional: a device context for the bitmap. If omitted then the screen DC is used.
* @returns {OCR.Result}
*/
static FromBitmap(Bitmap, Options:=0, hDC?) {
local result, pDC, hBitmap, hBM2, oBM, oBM2, pBitmapInfo := Buffer(32, 0), W, H, scale, transform := 0
if IsObject(Options)
Options := Options.Clone()
this.__ExtractTransformParameters(Options, &transform)
scale := transform.scale
this.__ExtractNamedParameters(Options, "hDC", &hDC)
this.__DeleteProps(Options, "scale", "invertcolors", "grayscale")
if !DllCall("GetObject", "ptr", Bitmap, "int", pBitmapInfo.Size, "ptr", pBitmapInfo) {
DllCall("gdiplus\GdipCreateHBITMAPFromBitmap", "UPtr", Bitmap, "UPtr*", &hBitmap:=0, "Int", 0xffffffff)
DllCall("GetObject", "ptr", hBitmap, "int", pBitmapInfo.Size, "ptr", pBitmapInfo)
Bitmap := 0 ; Marks hBitmap to be deleted afterwards
} else
hBitmap := Bitmap
W := NumGet(pBitmapInfo, 4, "int"), H := NumGet(pBitmapInfo, 8, "int")
if scale != 1 || (W && H && (W < 40 || H < 40)) {
sW := Ceil(W * scale), sH := Ceil(H * scale)
hDC := DllCall("CreateCompatibleDC", "Ptr", 0, "Ptr")
, oBM := DllCall("SelectObject", "Ptr", hDC, "Ptr", hBitmap, "Ptr")
, pDC := DllCall("CreateCompatibleDC", "Ptr", hDC, "Ptr")
, hBM2 := DllCall("CreateCompatibleBitmap", "Ptr", hDC, "Int", Max(40, sW), "Int", Max(40, sH), "Ptr")
, oBM2 := DllCall("SelectObject", "Ptr", pDC, "Ptr", hBM2, "Ptr")
if sW < 40 || sH < 40 ; Fills the bitmap so it's at least 40x40, which seems to improve recognition
DllCall("StretchBlt", "Ptr", pDC, "Int", 0, "Int", 0, "Int", Max(40,sW), "Int", Max(40,sH), "Ptr", hDC, "Int", 0, "Int", 0, "Int", 1, "Int", 1, "UInt", 0x00CC0020 | this.CAPTUREBLT) ; SRCCOPY.
PrevStretchBltMode := DllCall("SetStretchBltMode", "Ptr", PDC, "Int", 3, "Int") ; COLORONCOLOR
, DllCall("StretchBlt", "Ptr", pDC, "Int", 0, "Int", 0, "Int", sW, "Int", sH, "Ptr", hDC, "Int", 0, "Int", 0, "Int", W, "Int", H, "UInt", 0x00CC0020 | this.CAPTUREBLT) ; SRCCOPY
, DllCall("SetStretchBltMode", "Ptr", PDC, "Int", PrevStretchBltMode)
, DllCall("SelectObject", "Ptr", pDC, "Ptr", oBM2)
, DllCall("SelectObject", "Ptr", hDC, "Ptr", oBM)
, DllCall("DeleteDC", "Ptr", hDC)
SoftwareBitmap := this.HBitmapToSoftwareBitmap(hBM2, pDC, transform)
result := this(SoftwareBitmap, Options)
this.NormalizeCoordinates(result, scale)
DllCall("DeleteDC", "Ptr", pDC)
, DllCall("DeleteObject", "UPtr", hBM2)
goto End
}
result := this(this.HBitmapToSoftwareBitmap(hBitmap, hDC?, transform), Options)
End:
if !Bitmap
DllCall("DeleteObject", "UPtr", hBitmap)
return result
}
/**
* Returns all available languages as a string, where the languages are separated by newlines.
* @returns {String}
*/
static GetAvailableLanguages() {
ComCall(7, this.OcrEngineStatics, "ptr*", &LanguageList := 0) ; AvailableRecognizerLanguages
ComCall(7, LanguageList, "int*", &count := 0) ; count
Loop count {
ComCall(6, LanguageList, "int", A_Index - 1, "ptr*", &Language := 0) ; get_Item
ComCall(6, Language, "ptr*", &hText := 0)
buf := DllCall("Combase.dll\WindowsGetStringRawBuffer", "ptr", hText, "uint*", &length := 0, "ptr")
text .= StrGet(buf, "UTF-16") "`n"
this.DeleteHString(hText)
ObjRelease(Language)
}
ObjRelease(LanguageList)
return text
}
/**
* Loads a new language which will be used with subsequent OCR calls.
* @param {string} lang OCR language. Default is first from available languages.
* @returns {void}
*/
static LoadLanguage(lang:="FirstFromAvailableLanguages") {
local hString, Language:=ComValue(13, 0), OcrEngine:=ComValue(13, 0)
if this.HasOwnProp("CurrentLanguage") && this.HasOwnProp("OcrEngine") && this.CurrentLanguage = lang
return
if HasMethod(lang)
lang := lang()
if (lang = "FirstFromAvailableLanguages")
ComCall(10, this.OcrEngineStatics, "ptr*", OcrEngine) ; TryCreateFromUserProfileLanguages
else {
hString := this.CreateHString(lang)
, ComCall(6, this.LanguageFactory, "ptr", hString, "ptr*", Language) ; CreateLanguage
, this.DeleteHString(hString)
, ComCall(9, this.OcrEngineStatics, "ptr", Language, "ptr*", OcrEngine) ; TryCreateFromLanguage
}
if (OcrEngine.ptr = 0)
Throw Error(lang = "FirstFromAvailableLanguages" ? "Failed to use FirstFromAvailableLanguages for OCR:`nmake sure the primary language pack has OCR capabilities installed.`n`nAlternatively try `"en-us`" as the language." : "Can not use language `"" lang "`" for OCR, please install language pack.")
this.OcrEngine := OcrEngine, this.CurrentLanguage := lang
}
/**
* Returns a bounding rectangle {x,y,w,h} for the provided Word objects
* @param words Word object arguments (at least 1)
* @returns {Object}
*/
static WordsBoundingRect(words*) {
if !words.Length
throw ValueError("This function requires at least one argument", -1)
local X1 := 100000000, Y1 := 100000000, X2 := -100000000, Y2 := -100000000, word
for word in words {
X1 := Min(word.x, X1), Y1 := Min(word.y, Y1), X2 := Max(word.x+word.w, X2), Y2 := Max(word.y+word.h, Y2)
}
return {X:X1, Y:Y1, W:X2-X1, H:Y2-Y1, X2:X2, Y2:Y2}
}
/**
* Waits text to appear on screen. If the method is successful, then Func's return value is returned.
* Otherwise nothing is returned.
* @param needle The searched text
* @param {number} timeout Timeout in milliseconds. Less than 0 is indefinite wait (default)
* @param func The function to be called for the OCR. Default is OCR.FromDesktop
* @param casesense Text comparison case-sensitivity
* @param comparefunc A custom string compare/search function, that accepts two arguments: haystack and needle.
* Default is InStr. If a custom function is used, then casesense is ignored.
* @returns {OCR.Result}
*/
static WaitText(needle, timeout:=-1, func?, casesense:=False, comparefunc?) {
local endTime := A_TickCount+timeout, result, line, total
if !IsSet(func)
func := this.FromDesktop
if !IsSet(comparefunc)
comparefunc := InStr.Bind(,,casesense)
While timeout > 0 ? (A_TickCount < endTime) : 1 {
result := func(), total := ""
for line in result.Lines
total .= line.Text "`n"
if comparefunc(Trim(total, "`n"), needle)
return result
}
return
}
/**
* Returns word clusters using a two-dimensional DBSCAN algorithm
* @param objs An array of objects (Words, Lines etc) to cluster. Must have x, y, w, h and Text properties.
* @param eps_x Optional epsilon value for x-axis. Default is infinite.
* This is unused if compareFunc is provided.
* @param eps_y Optional epsilon value for y-axis. Default is median height of objects divided by two.
* This is unused if compareFunc is provided.
* @param minPts Optional minimum cluster size.
* @param compareFunc Optional comparison function to judge the minimum distance between objects
* to consider it a cluster. Must accept two objects to compare.
* Default comparison function determines whether the difference of middle y-coordinates of
* the objects are less than epsilon-y, and whether objects are less than eps_x apart on the x-axis.
*
* Eg `(p1, p2) => ((Abs(p1.y+p1.h-p2.y) < 5 || Abs(p2.y+p2.h-p1.y) < 5) && ((p1.x >= p2.x && p1.x <= (p2.x+p2.w)) || ((p1.x+p1.w) >= p2.x && (p1.x+p1.w) <= (p2.x+p2.w))))`
* will cluster objects if they are located on top of eachother on the x-axis, and less than 5 pixels
* apart in the y-axis.
* @param noise If provided, then will be set to an array of clusters that didn't satisfy minPts
* @returns {Array} Array of objects with {x,y,w,h,Text,Words} properties
*/
static Cluster(objs, eps_x:=-1, eps_y:=-1, minPts:=1, compareFunc?, &noise?) {
local clusters := [], start := 0, cluster, word
visited := Map(), clustered := Map(), C := [], c_n := 0, sum := 0, noise := IsSet(noise) && (noise is Array) ? noise : []
if !IsObject(objs) || !(objs is Array)
throw ValueError("objs argument must be an Array", -1)
if !objs.Length
return []
if IsSet(compareFunc) && !HasMethod(compareFunc)
throw ValueError("compareFunc must be a valid function", -1)
if !IsSet(compareFunc) {
if (eps_y < 0) {
for point in objs
sum += point.h
eps_y := (sum // objs.Length) // 2
}
compareFunc := (p1, p2) => Abs(p1.y+p1.h//2-p2.y-p2.h//2) array is considered to consist of only numeric values. This is the default option.
* C, C1 or COn => case-sensitive sort of strings
* C0 or COff => case-insensitive sort of strings
*
* The callback function should accept two parameters elem1 and elem2 and return an integer:
* Return integer < 0 if elem1 less than elem2
* Return 0 is elem1 is equal to elem2
* Return > 0 if elem1 greater than elem2
* @param Key Optional: Omit it if you want to sort a array of primitive values (strings, numbers etc).
* If you have an array of objects, specify here the key by which contents the object will be sorted.
* @returns {Array}
*/
static SortArray(arr, optionsOrCallback:="N", key?) {
if (arr.Length < 2)
return this
if HasMethod(optionsOrCallback)
compareFunc := optionsOrCallback, optionsOrCallback := ""
else {
if InStr(optionsOrCallback, "N")
compareFunc := IsSet(key) ? NumericCompareKey.Bind(key) : NumericCompare
if RegExMatch(optionsOrCallback, "i)C(?!0)|C1|COn")
compareFunc := IsSet(key) ? StringCompareKey.Bind(key,,True) : StringCompare.Bind(,,True)
if RegExMatch(optionsOrCallback, "i)C0|COff")
compareFunc := IsSet(key) ? StringCompareKey.Bind(key) : StringCompare
if InStr(optionsOrCallback, "Random") {
len := arr.Length
Loop len-1 {
i := len + 1 - A_Index
j := Random(1, i)
if (j != i)
tmp := arr[i], arr[i] := arr[j], arr[j] := tmp
}
return arr
}
if !IsSet(compareFunc)
throw ValueError("No valid options provided!", -1)
}
QuickSort(1, arr.Length)
if RegExMatch(optionsOrCallback, "i)R(?!a)")
this.ReverseArray(arr)
if InStr(optionsOrCallback, "U")
arr := this.UniqueArray(arr)
return arr
NumericCompare(left, right) => (left > right) - (left < right)
NumericCompareKey(key, left, right) => ((f1 := left.HasProp("__Item") ? left[key] : left.%key%), (f2 := right.HasProp("__Item") ? right[key] : right.%key%), (f1 > f2) - (f1 < f2))
StringCompare(left, right, casesense := False) => StrCompare(left "", right "", casesense)
StringCompareKey(key, left, right, casesense := False) => StrCompare((left.HasProp("__Item") ? left[key] : left.%key%) "", (right.HasProp("__Item") ? right[key] : right.%key%) "", casesense)
; In-place quicksort (Hoare-style partition with middle pivot)
QuickSort(left, right) {
i := left
j := right
pivot := arr[(left + right) // 2]
while (i <= j) {
while (compareFunc(arr[i], pivot) < 0)
i++
while (compareFunc(arr[j], pivot) > 0)
j--
if (i <= j) {
temp := arr[i], arr[i] := arr[j], arr[j] := temp
i++, j--
}
}
if (left < j)
QuickSort(left, j)
if (i < right)
QuickSort(i, right)
}
}
; Reverses the array in-place
static ReverseArray(arr) {
local len := arr.Length + 1, max := (len // 2), i := 0
while ++i <= max
temp := arr[len - i], arr[len - i] := arr[i], arr[i] := temp
return arr
}
; Returns a new array with only unique values
static UniqueArray(arr) {
local unique := Map()
for v in arr
unique[v] := 1
return [unique*]
}
; Returns a one-dimensional array from a multi-dimensional array
static FlattenArray(arr) {
local r := []
for v in arr {
if v is Array
r.Push(this.FlattenArray(v)*)
else
r.Push(v)
}
return r
}
;; Only internal methods ahead
; Scales and optionally crops a SoftwareBitmap. Crop parameters need to not be scale-adjusted.
; Rotation can be clockwise 0, 90, 180, or 270 degrees
; Flip: 0 = no flip, 1 = around y-axis, 2 = around x-axis
static TransformSoftwareBitmap(SoftwareBitmap, &sbW, &sbH, scale:=1, rotate:=0, flip:=0, X?, Y?, W?, H?) {
InMemoryRandomAccessStream := this.SoftwareBitmapToRandomAccessStream(SoftwareBitmap)
ComCall(this.Vtbl_GetDecoder.png, this.BitmapDecoderStatics, "ptr", DecoderGUID:=Buffer(16))
ComCall(15, this.BitmapDecoderStatics, "ptr", DecoderGUID, "ptr", InMemoryRandomAccessStream, "ptr*", BitmapDecoder:=ComValue(13,0)) ; CreateAsync
this.WaitForAsync(&BitmapDecoder)
BitmapFrameWithSoftwareBitmap := ComObjQuery(BitmapDecoder, IBitmapFrameWithSoftwareBitmap := "{FE287C9A-420C-4963-87AD-691436E08383}")
BitmapFrame := ComObjQuery(BitmapDecoder, IBitmapFrame := "{72A49A1C-8081-438D-91BC-94ECFC8185C6}")
BitmapTransform := this.CreateClass("Windows.Graphics.Imaging.BitmapTransform")
if IsSet(W) && W
sbW := Min(sbW, W)
if IsSet(H) && H
sbH := Min(sbH, H)
local sW := Floor(sbW*scale), sH := Floor(sbH*scale), intermediate
if scale != 1 {
; First the bitmap is scaled, then cropped
ComCall(7, BitmapTransform, "uint", sW) ; put_ScaledWidth
ComCall(9, BitmapTransform, "uint", sH) ; put_ScaledHeight
}
if rotate {
ComCall(15, BitmapTransform, "uint", rotate//90) ; put_Rotation
if rotate = 90 || rotate = 270
intermediate := sW, sW := sH, sH := intermediate
}
if flip
ComCall(13, BitmapTransform, "uint", flip) ; put_Flip
if (IsSet(X) && X != 0) || (IsSet(Y) && Y != 0) || IsSet(W) || IsSet(H) {
bounds := Buffer(16,0), NumPut("int", Floor(X*scale), "int", Floor(Y*scale), "int", Floor(sbW*scale), "int", Floor(sbH*scale), bounds)
ComCall(17, BitmapTransform, "ptr", bounds) ; put_Bounds
}
ComCall(8, BitmapFrame, "uint*", &BitmapPixelFormat:=0) ; get_BitmapPixelFormat
ComCall(9, BitmapFrame, "uint*", &BitmapAlphaMode:=0) ; get_BitmapAlphaMode
ComCall(8, BitmapFrameWithSoftwareBitmap, "uint", BitmapPixelFormat, "uint", BitmapAlphaMode, "ptr", BitmapTransform, "uint", IgnoreExifOrientation := 0, "uint", DoNotColorManage := 0, "ptr*", SoftwareBitmap:=ComValue(13,0)) ; GetSoftwareBitmapTransformedAsync
this.WaitForAsync(&SoftwareBitmap)
; this.CloseIClosable(BitmapFrameWithSoftwareBitmap) ; Implemented, but is it necessary?
this.CloseIClosable(InMemoryRandomAccessStream)
sbW := sW, sbH := sH
return SoftwareBitmap
}
static CreateDIBSection(w, h, hdc?, bpp:=32, &ppvBits:=0) {
local hdc2 := IsSet(hdc) ? hdc : DllCall("GetDC", "Ptr", 0, "UPtr")
, bi := Buffer(40, 0), hbm
NumPut("int", 40, "int", w, "int", h, "ushort", 1, "ushort", bpp, "int", 0, bi)
hbm := DllCall("CreateDIBSection", "uint", hdc2, "ptr" , bi, "uint" , 0, "uint*", &ppvBits:=0, "uint" , 0, "uint" , 0)
if !IsSet(hdc)
DllCall("ReleaseDC", "Ptr", 0, "Ptr", hdc2)
return hbm
}
/**
* Creates an hBitmap of a region of the screen or a specific window
* @param X Captured rectangle X coordinate. This is relative to the screen unless hWnd is specified,
* in which case it may be relative to the window/client
* @param Y Captured rectangle Y coordinate.
* @param W Captured rectangle width.
* @param H Captured rectangle height.
* @param {Integer|Object} hWnd Window handle which to capture. Coordinates will be relative to the window.
* hWnd may also be an object {hWnd, onlyClientArea, mode} where onlyClientArea:1 means the client area will be captured instead of the whole window (and X, Y will also be relative to client)
* mode 0 uses GetDC + StretchBlt, mode 1 uses PrintWindow, mode 2 uses PrintWindow with undocumented PW_RENDERFULLCONTENT flag.
* Default is mode 2.
* @param {Integer} scale
* @returns {OCR.IBase}
*/
static CreateHBitmap(X, Y, W, H, hWnd:=0, scale:=1) {
local sW := Ceil(W*scale), sH := Ceil(H*scale), onlyClientArea := 0, mode := 2, HDC, obm, hbm, pdc, hbm2
if hWnd {
if IsObject(hWnd)
onlyClientArea := hWnd.HasOwnProp("onlyClientArea") ? hWnd.onlyClientArea : onlyClientArea, mode := hWnd.HasOwnProp("mode") ? hWnd.mode : mode, hWnd := hWnd.hWnd
HDC := DllCall("GetDCEx", "Ptr", hWnd, "Ptr", 0, "Int", 2|!onlyClientArea, "Ptr")
if mode > 0 {
PDC := DllCall("CreateCompatibleDC", "Ptr", 0, "Ptr")
HBM := DllCall("CreateCompatibleBitmap", "Ptr", HDC, "Int", Max(40,X+W), "Int", Max(40,Y+H), "Ptr")
, OBM := DllCall("SelectObject", "Ptr", PDC, "Ptr", HBM, "Ptr")
, DllCall("PrintWindow", "Ptr", hWnd, "Ptr", PDC, "UInt", (mode=2?2:0)|!!onlyClientArea)
if scale != 1 || X != 0 || Y != 0 {
PDC2 := DllCall("CreateCompatibleDC", "Ptr", PDC, "Ptr")
, HBM2 := DllCall("CreateCompatibleBitmap", "Ptr", PDC, "Int", Max(40,sW), "Int", Max(40,sH), "Ptr")
, OBM2 := DllCall("SelectObject", "Ptr", PDC2, "Ptr", HBM2, "Ptr")
, PrevStretchBltMode := DllCall("SetStretchBltMode", "Ptr", PDC, "Int", 3, "Int") ; COLORONCOLOR
, DllCall("StretchBlt", "Ptr", PDC2, "Int", 0, "Int", 0, "Int", sW, "Int", sH, "Ptr", PDC, "Int", X, "Int", Y, "Int", W, "Int", H, "UInt", 0x00CC0020 | this.CAPTUREBLT) ; SRCCOPY
, DllCall("SetStretchBltMode", "Ptr", PDC, "Int", PrevStretchBltMode)
, DllCall("SelectObject", "Ptr", PDC2, "Ptr", obm2)
, DllCall("DeleteDC", "Ptr", PDC)
, DllCall("DeleteObject", "UPtr", HBM)
, hbm := hbm2, pdc := pdc2
}
DllCall("SelectObject", "Ptr", PDC, "Ptr", OBM)
, DllCall("DeleteDC", "Ptr", HDC)
, oHBM := this.IBase(HBM), oHBM.DC := PDC
return oHBM.DefineProp("__Delete", {call:(this, *)=>(DllCall("DeleteObject", "Ptr", this), DllCall("DeleteDC", "Ptr", this.DC))})
}
} else {
HDC := DllCall("GetDC", "Ptr", 0, "Ptr")
}
PDC := DllCall("CreateCompatibleDC", "Ptr", HDC, "Ptr")
, HBM := DllCall("CreateCompatibleBitmap", "Ptr", HDC, "Int", Max(40,sW), "Int", Max(40,sH), "Ptr")
, OBM := DllCall("SelectObject", "Ptr", PDC, "Ptr", HBM, "Ptr")
if sW < 40 || sH < 40 ; Fills the bitmap so it's at least 40x40, which seems to improve recognition
DllCall("StretchBlt", "Ptr", PDC, "Int", 0, "Int", 0, "Int", Max(40,sW), "Int", Max(40,sH), "Ptr", HDC, "Int", X, "Int", Y, "Int", 1, "Int", 1, "UInt", 0x00CC0020 | this.CAPTUREBLT) ; SRCCOPY.
PrevStretchBltMode := DllCall("SetStretchBltMode", "Ptr", PDC, "Int", 3, "Int") ; COLORONCOLOR
, DllCall("StretchBlt", "Ptr", PDC, "Int", 0, "Int", 0, "Int", sW, "Int", sH, "Ptr", HDC, "Int", X, "Int", Y, "Int", W, "Int", H, "UInt", 0x00CC0020 | this.CAPTUREBLT) ; SRCCOPY
, DllCall("SetStretchBltMode", "Ptr", PDC, "Int", PrevStretchBltMode)
, DllCall("SelectObject", "Ptr", PDC, "Ptr", OBM)
, DllCall("DeleteDC", "Ptr", HDC)
, oHBM := this.IBase(HBM), oHBM.DC := PDC
return oHBM.DefineProp("__Delete", {call:(this, *)=>(DllCall("DeleteObject", "Ptr", this), DllCall("DeleteDC", "Ptr", this.DC))})
}
static CreateDirect3DSoftwareBitmapFromWindow(hWnd) {
static init := 0, DXGIDevice, Direct3DDevice, Direct3D11CaptureFramePoolStatics, GraphicsCaptureItemInterop, GraphicsCaptureItemGUID, D3D_Device, D3D_Context
local x, y, w, h, rect
if !init {
DllCall("LoadLibrary","str","DXGI")
DllCall("LoadLibrary","str","D3D11")
DllCall("LoadLibrary","str","Dwmapi")
DllCall("D3D11\D3D11CreateDevice", "ptr", 0, "int", D3D_DRIVER_TYPE_HARDWARE := 1, "ptr", 0, "uint", D3D11_CREATE_DEVICE_BGRA_SUPPORT := 0x20, "ptr", 0, "uint", 0, "uint", D3D11_SDK_VERSION := 7, "ptr*", D3D_Device:=ComValue(13, 0), "ptr*", 0, "ptr*", D3D_Context:=ComValue(13, 0))
DXGIDevice := ComObjQuery(D3D_Device, IID_IDXGIDevice := "{54ec77fa-1377-44e6-8c32-88fd5f44c84c}")
DllCall("D3D11\CreateDirect3D11DeviceFromDXGIDevice", "ptr", DXGIDevice, "ptr*", GraphicsDevice:=ComValue(13, 0))
Direct3DDevice := ComObjQuery(GraphicsDevice, IDirect3DDevice := "{A37624AB-8D5F-4650-9D3E-9EAE3D9BC670}")
Direct3D11CaptureFramePoolStatics := this.CreateClass("Windows.Graphics.Capture.Direct3D11CaptureFramePool", IDirect3D11CaptureFramePoolStatics := "{7784056a-67aa-4d53-ae54-1088d5a8ca21}")
GraphicsCaptureItemStatics := this.CreateClass("Windows.Graphics.Capture.GraphicsCaptureItem", IGraphicsCaptureItemStatics := "{A87EBEA5-457C-5788-AB47-0CF1D3637E74}")
GraphicsCaptureItemInterop := ComObjQuery(GraphicsCaptureItemStatics, IGraphicsCaptureItemInterop := "{3628E81B-3CAC-4C60-B7F4-23CE0E0C3356}")
GraphicsCaptureItemGUID := Buffer(16,0)
DllCall("ole32\CLSIDFromString", "wstr", IGraphicsCaptureItem := "{79c3f95b-31f7-4ec2-a464-632ef5d30760}", "ptr", GraphicsCaptureItemGUID)
init := 1
}
; INIT done
DllCall("Dwmapi.dll\DwmGetWindowAttribute", "ptr", hWnd, "uint", DWMWA_EXTENDED_FRAME_BOUNDS := 9, "ptr", rect := Buffer(16,0), "uint", 16)
x := NumGet(rect, 0, "int"), y := NumGet(rect, 4, "int"), w := NumGet(rect, 8, "int") - x, h := NumGet(rect, 12, "int") - y
ComCall(6, Direct3D11CaptureFramePoolStatics, "ptr", Direct3DDevice, "int", B8G8R8A8UIntNormalized := 87, "int", numberOfBuffers := 2, "int64", (h << 32) | w, "ptr*", Direct3D11CaptureFramePool:=ComValue(13, 0)) ; Direct3D11CaptureFramePool.Create
if ComCall(3, GraphicsCaptureItemInterop, "ptr", hWnd, "ptr", GraphicsCaptureItemGUID, "ptr*", GraphicsCaptureItem:=ComValue(13, 0), "uint") { ; IGraphicsCaptureItemInterop::CreateForWindow
this.CloseIClosable(Direct3D11CaptureFramePool)
throw Error("Failed to capture GraphicsItem of window",, -1)
}
ComCall(10, Direct3D11CaptureFramePool, "ptr", GraphicsCaptureItem, "ptr*", GraphicsCaptureSession:=ComValue(13, 0)) ; Direct3D11CaptureFramePool.CreateCaptureSession
GraphicsCaptureSession2 := ComObjQuery(GraphicsCaptureSession, IGraphicsCaptureSession2 := "{2c39ae40-7d2e-5044-804e-8b6799d4cf9e}")
ComCall(7, GraphicsCaptureSession2, "int", 0) ; GraphicsCaptureSession.IsCursorCaptureEnabled put
if (Integer(StrSplit(A_OSVersion, ".")[3]) >= 20348) { ; hide border
GraphicsCaptureSession3 := ComObjQuery(GraphicsCaptureSession, IGraphicsCaptureSession3 := "{f2cdd966-22ae-5ea1-9596-3a289344c3be}")
ComCall(7, GraphicsCaptureSession3, "int", 0) ; GraphicsCaptureSession.IsBorderRequired put
}
ComCall(6, GraphicsCaptureSession) ; GraphicsCaptureSession.StartCapture
Loop {
ComCall(7, Direct3D11CaptureFramePool, "ptr*", Direct3D11CaptureFrame:=ComValue(13, 0)) ; Direct3D11CaptureFramePool.TryGetNextFrame
if (Direct3D11CaptureFrame.ptr != 0)
break
}
ComCall(6, Direct3D11CaptureFrame, "ptr*", Direct3DSurface:=ComValue(13, 0)) ; Direct3D11CaptureFrame.Surface
ComCall(11, this.SoftwareBitmapStatics, "ptr", Direct3DSurface, "ptr*", SoftwareBitmap:=ComValue(13, 0)) ; SoftwareBitmap::CreateCopyFromSurfaceAsync
this.WaitForAsync(&SoftwareBitmap)
this.CloseIClosable(Direct3D11CaptureFramePool)
this.CloseIClosable(GraphicsCaptureSession)
if GraphicsCaptureSession2 {
this.CloseIClosable(GraphicsCaptureSession2)
}
if IsSet(GraphicsCaptureSession3) {
this.CloseIClosable(GraphicsCaptureSession3)
}
this.CloseIClosable(Direct3D11CaptureFrame)
this.CloseIClosable(Direct3DSurface)
SoftwareBitmap.x := x, SoftwareBitmap.y := y, SoftwareBitmap.w := w, SoftwareBitmap.h := h
return SoftwareBitmap
}
static HBitmapToRandomAccessStream(hBitmap) {
static PICTYPE_BITMAP := 1
, BSOS_DEFAULT := 0
, sz := 8 + A_PtrSize*2
local PICTDESC, riid, size, pIRandomAccessStream
DllCall("Ole32\CreateStreamOnHGlobal", "Ptr", 0, "UInt", true, "Ptr*", pIStream:=ComValue(13,0), "UInt")
, PICTDESC := Buffer(sz, 0)
, NumPut("uint", sz, "uint", PICTYPE_BITMAP, "ptr", IsInteger(hBitmap) ? hBitmap : hBitmap.ptr, PICTDESC)
, riid := this.CLSIDFromString(this.IID_IPicture)
, DllCall("OleAut32\OleCreatePictureIndirect", "Ptr", PICTDESC, "Ptr", riid, "UInt", 0, "Ptr*", pIPicture:=ComValue(13,0), "UInt")
, ComCall(15, pIPicture, "Ptr", pIStream, "UInt", true, "uint*", &size:=0, "UInt") ; IPicture::SaveAsFile
, riid := this.CLSIDFromString(this.IID_IRandomAccessStream)
, DllCall("ShCore\CreateRandomAccessStreamOverStream", "Ptr", pIStream, "UInt", BSOS_DEFAULT, "Ptr", riid, "Ptr*", pIRandomAccessStream:=ComValue(13, 0), "UInt")
Return pIRandomAccessStream
}
; Converts HBITMAP to SoftwareBitmap. NOTE: SetStretchBltMode HALFTONE breaks this
; The optional transform parameter may contain {grayscale, invertcolors}
static HBitmapToSoftwareBitmap(hBitmap, hDC?, transform?) {
local bi := Buffer(40, 0), W, H, BitmapBuffer, MemoryBuffer, MemoryBufferReference, BufferByteAccess, BufferSize
hDC := (hBitmap is OCR.IBase ? hBitmap.DC : (hDC ?? dhDC := DllCall("GetDC", "Ptr", 0, "UPtr")))
NumPut("uint", 40, bi, 0)
DllCall("GetDIBits", "ptr", hDC, "ptr", hBitmap, "uint", 0, "uint", 0, "ptr", 0, "ptr", bi, "uint", 0)
W := NumGet(bi, 4, "int"), H := NumGet(bi, 8, "int")
ComCall(7, this.SoftwareBitmapFactory, "int", 87, "int", W, "int", H, "int", 0, "ptr*", SoftwareBitmap := ComValue(13,0)) ; CreateWithAlpha: Bgra8 & Premultiplied
ComCall(15, SoftwareBitmap, "int", 2, "ptr*", &BitmapBuffer := 0) ; LockBuffer
MemoryBuffer := ComObjQuery(BitmapBuffer, "{fbc4dd2a-245b-11e4-af98-689423260cf8}")
ComCall(6, MemoryBuffer, "ptr*", &MemoryBufferReference := 0) ; CreateReference
BufferByteAccess := ComObjQuery(MemoryBufferReference, "{5b0d3235-4dba-4d44-865e-8f1d0e4fd04d}")
ComCall(3, BufferByteAccess, "ptr*", &SoftwareBitmapByteBuffer:=0, "uint*", &BufferSize:=0) ; GetBuffer
NumPut("short", 32, "short", 0, bi, 14), NumPut("int", -H, bi, 8) ; Negative height to get correctly oriented image
DllCall("GetDIBits", "ptr", hDC, "ptr", hBitmap, "uint", 0, "uint", H, "ptr", SoftwareBitmapByteBuffer, "ptr", bi, "uint", 0)
if IsSet(transform) {
if (transform.HasProp("grayscale") && transform.grayscale)
DllCall(this.GrayScaleMCode, "ptr", SoftwareBitmapByteBuffer, "uint", w, "uint", h, "uint", (w*4+3) // 4 * 4, "cdecl uint")
if (transform.HasProp("monochrome") && transform.monochrome)
DllCall(this.MonochromeMCode, "ptr", SoftwareBitmapByteBuffer, "uint", w, "uint", h, "uint", (w*4+3) // 4 * 4, "uint", transform.monochrome, "cdecl uint")
if (transform.HasProp("invertcolors") && transform.invertcolors)
DllCall(this.InvertColorsMCode, "ptr", SoftwareBitmapByteBuffer, "uint", w, "uint", h, "uint", (w*4+3) // 4 * 4, "cdecl uint")
}
if IsSet(dhDC)
DllCall("DeleteDC", "ptr", dhDC)
if BufferByteAccess.HasMethod("Dispose")
BufferByteAccess.Dispose()
if MemoryBuffer.HasMethod("Dispose")
MemoryBuffer.Dispose()
BufferByteAccess := "", ObjRelease(MemoryBufferReference), MemoryBuffer := "", ObjRelease(BitmapBuffer) ; Release in correct order
return SoftwareBitmap
}
static MCode(mcode) {
static e := Map('1', 4, '2', 1), c := (A_PtrSize=8) ? "x64" : "x86"
if (!regexmatch(mcode, "^([0-9]+),(" c ":|.*?," c ":)([^,]+)", &m))
return
if (!DllCall("crypt32\CryptStringToBinary", "str", m.3, "uint", 0, "uint", e[m.1], "ptr", 0, "uint*", &s := 0, "ptr", 0, "ptr", 0))
return
p := DllCall("GlobalAlloc", "uint", 0, "ptr", s, "ptr")
if (c="x64")
DllCall("VirtualProtect", "ptr", p, "ptr", s, "uint", 0x40, "uint*", &op := 0)
if (DllCall("crypt32\CryptStringToBinary", "str", m.3, "uint", 0, "uint", e[m.1], "ptr", p, "uint*", &s, "ptr", 0, "ptr", 0))
return p
DllCall("GlobalFree", "ptr", p)
}
static DisplayHBitmap(hBitmap) {
local gImage := Gui("-DPIScale"), W, H
, hPic := gImage.Add("Text", "0xE w640 h640")
SendMessage(0x172, 0, hBitmap,, hPic.hWnd)
hPic.GetPos(,,&W, &H)
gImage.Show("w" (W+20) " H" (H+20))
WinWaitClose gImage
}
static SoftwareBitmapToRandomAccessStream(SoftwareBitmap) {
InMemoryRandomAccessStream := this.CreateClass("Windows.Storage.Streams.InMemoryRandomAccessStream")
ComCall(8, this.BitmapEncoderStatics, "ptr", encoderId := Buffer(16, 0)) ; IBitmapEncoderStatics::PngEncoderId
ComCall(13, this.BitmapEncoderStatics, "ptr", encoderId, "ptr", InMemoryRandomAccessStream, "ptr*", BitmapEncoder:=ComValue(13,0)) ; IBitmapEncoderStatics::CreateAsync
this.WaitForAsync(&BitmapEncoder)
BitmapEncoderWithSoftwareBitmap := ComObjQuery(BitmapEncoder, "{686cd241-4330-4c77-ace4-0334968b1768}")
ComCall(6, BitmapEncoderWithSoftwareBitmap, "ptr", SoftwareBitmap) ; SetSoftwareBitmap
ComCall(19, BitmapEncoder, "ptr*", asyncAction:=ComValue(13,0)) ; FlushAsync
this.WaitForAsync(&asyncAction)
ComCall(11, InMemoryRandomAccessStream, "int64", 0) ; Seek to beginning
return InMemoryRandomAccessStream
}
static CreateClass(str, interface?) {
local hString := this.CreateHString(str), result
if !IsSet(interface) {
result := DllCall("Combase.dll\RoActivateInstance", "ptr", hString, "ptr*", cls:=ComValue(13, 0), "uint")
} else {
GUID := this.CLSIDFromString(interface)
result := DllCall("Combase.dll\RoGetActivationFactory", "ptr", hString, "ptr", GUID, "ptr*", cls:=ComValue(13, 0), "uint")
}
if (result != 0) {
if (result = 0x80004002)
throw Error("No such interface supported", -1, interface)
else if (result = 0x80040154)
throw Error("Class not registered", -1)
else
throw Error(result)
}
this.DeleteHString(hString)
return cls
}
static CreateHString(str) => (DllCall("Combase.dll\WindowsCreateString", "wstr", str, "uint", StrLen(str), "ptr*", &hString:=0), hString)
static DeleteHString(hString) => DllCall("Combase.dll\WindowsDeleteString", "ptr", hString)
static WaitForAsync(&obj) {
local AsyncInfo := ComObjQuery(obj, this.IID_IAsyncInfo), status, ErrorCode
Loop {
ComCall(7, AsyncInfo, "uint*", &status:=0) ; IAsyncInfo.Status
if (status != 0) {
if (status != 1) {
ComCall(8, ASyncInfo, "uint*", &ErrorCode:=0) ; IAsyncInfo.ErrorCode
throw Error("AsyncInfo failed with status error " ErrorCode, -1)
}
break
}
Sleep this.PerformanceMode ? -1 : 0
}
ComCall(8, obj, "ptr*", ObjectResult:=this.IBase()) ; GetResults
obj := ObjectResult
}
static CloseIClosable(pClosable) {
static IClosable := "{30D5A829-7FA4-4026-83BB-D75BAE4EA99E}"
local Close := ComObjQuery(pClosable, IClosable)
ComCall(6, Close) ; Close
}
static CLSIDFromString(IID) {
local CLSID := Buffer(16), res
if res := DllCall("ole32\CLSIDFromString", "WStr", IID, "Ptr", CLSID, "UInt")
throw Error("CLSIDFromString failed. Error: " . Format("{:#x}", res))
Return CLSID
}
static NormalizeCoordinates(result, scale, x:=0, y:=0) {
local word
if (scale == 1 && x == 0 && y == 0)
return result
for word in result.Words
word.x := Integer(word.x / scale)+x, word.y := Integer(word.y / scale)+y, word.w := Integer(word.w / scale), word.h := Integer(word.h / scale), word.BoundingRect := {X:word.x, Y:word.y, W:word.w, H:word.h}
return result
}
static __OpenPdfDocument(IRandomAccessStream, Password:="") {
PdfDocumentStatics := this.CreateClass("Windows.Data.Pdf.PdfDocument", this.IID_IPdfDocumentStatics)
ComCall(8, PdfDocumentStatics, "ptr", IRandomAccessStream, "ptr*", PdfDocument:=ComValue(13, 0)) ; LoadFromStreamAsync
this.WaitForAsync(&PdfDocument)
return PdfDocument
}
static __ExtractNamedParameters(obj, params*) {
local i := 0
if !IsObject(obj) || Type(obj) != "Object"
return 0
Loop params.Length // 2 {
name := params[++i], value := params[++i]
if obj.HasProp(name)
%value% := obj.%name%
}
return 1
}
static __ExtractTransformParameters(obj, &transform) {
local scale := 1, grayscale := 0, invertcolors := 0, monochrome := 0, rotate := 0, flip := 0
if IsObject(obj)
this.__ExtractNamedParameters(obj, "scale", &scale, "grayscale", &grayscale, "invertcolors", &invertcolors, "monochrome", &monochrome, "rotate", &rotate, "flip", &flip, "transform", &transform)
if IsSet(transform) && IsObject(transform) {
for prop in ["scale", "grayscale", "invertcolors", "monochrome", "rotate", "flip"]
if !transform.HasProp(prop)
transform.%prop% := %prop%
} else
transform := {scale:scale, grayscale:grayscale, invertcolors:invertcolors, monochrome:monochrome, rotate:rotate, flip:flip}
transform.flip := transform.flip = "y" ? 1 : transform.flip = "x" ? 2 : transform.flip
}
static __DeleteProps(obj, props*) {
if IsObject(obj)
for prop in props
obj.DeleteProp(prop)
}
/**
* Converts coordinates between screen, window and client.
* @param X X-coordinate to convert
* @param Y Y-coordinate to convert
* @param outX Variable where to store the converted X-coordinate
* @param outY Variable where to store the converted Y-coordinate
* @param relativeFrom CoordMode where to convert from. Default is A_CoordModeMouse.
* @param relativeTo CoordMode where to convert to. Default is Screen.
* @param winTitle A window title or other criteria identifying the target window.
* @param winText If present, this parameter must be a substring from a single text element of the target window.
* @param excludeTitle Windows whose titles include this value will not be considered.
* @param excludeText Windows whose text include this value will not be considered.
*/
static ConvertWinPos(X, Y, &outX, &outY, relativeFrom:="", relativeTo:="screen", winTitle?, winText?, excludeTitle?, excludeText?) {
relativeFrom := relativeFrom || A_CoordModeMouse
if relativeFrom = relativeTo {
outX := X, outY := Y
return
}
local hWnd := WinExist(winTitle?, winText?, excludeTitle?, excludeText?)
switch relativeFrom, 0 {
case "screen", "s":
if relativeTo = "window" || relativeTo = "w" {
DllCall("user32\GetWindowRect", "Int", hWnd, "Ptr", RECT := Buffer(16))
outX := X-NumGet(RECT, 0, "Int"), outY := Y-NumGet(RECT, 4, "Int")
} else {
; screen to client
pt := Buffer(8), NumPut("int",X,pt), NumPut("int",Y,pt,4)
DllCall("ScreenToClient", "Int", hWnd, "Ptr", pt)
outX := NumGet(pt,0,"int"), outY := NumGet(pt,4,"int")
}
case "window", "w":
; window to screen
WinGetPos(&outX, &outY,,,hWnd)
outX += X, outY += Y
if relativeTo = "client" || relativeTo = "c" {
; screen to client
pt := Buffer(8), NumPut("int",outX,pt), NumPut("int",outY,pt,4)
DllCall("ScreenToClient", "Int", hWnd, "Ptr", pt)
outX := NumGet(pt,0,"int"), outY := NumGet(pt,4,"int")
}
case "client", "c":
; client to screen
pt := Buffer(8), NumPut("int",X,pt), NumPut("int",Y,pt,4)
DllCall("ClientToScreen", "Int", hWnd, "Ptr", pt)
outX := NumGet(pt,0,"int"), outY := NumGet(pt,4,"int")
if relativeTo = "window" || relativeTo = "w" { ; screen to window
DllCall("user32\GetWindowRect", "Int", hWnd, "Ptr", RECT := Buffer(16))
outX -= NumGet(RECT, 0, "Int"), outY -= NumGet(RECT, 4, "Int")
}
}
}
}
; ==================== END VENDORED OCR ====================
; [NMS-PC-08] self-test appended to the candidate build. Runs only with: --qa --nms-selftest
; Uses mock objects and no real input: it never clicks, types or opens a window.
class NMS_TestPlayback extends PlaybackEngine {
dispatchCount := 0
verifyResult := false
__New(app := "") {
super.__New(app, "", "", "", "", "", LoggingEngine())
}
_DispatchAction(macro, act) {
this.dispatchCount += 1
return ActionResultModel(true, "Passed", "selftest dispatch")
}
_VerifyPostActionExpectation(macro, act) {
return this.verifyResult
}
_InterruptibleSleep(ms) {
return
}
}
NMS_ST_Add(results, name, ok, detail := "") {
results.Push(Map("Name", name, "Ok", ok ? true : false, "Detail", detail))
}
NMS_ST_Retry(results) {
try {
macro := MacroModel("SelfTest")
pb := NMS_TestPlayback()
act := ActionModel("Key_TypeText")
act.RetryCount := 3
act.ExpectOutcome := "TitleContains"
act.ExpectValue := "never-matches"
res := pb._ExecuteSingleActionWithPolicy(macro, act)
NMS_ST_Add(results, "PB-01 non-repeatable step is not re-run after a failed post-check", pb.dispatchCount = 1 && !res.Success, "dispatches=" pb.dispatchCount " (expected 1)")
pb2 := NMS_TestPlayback()
act2 := ActionModel("Wait_Duration")
act2.RetryCount := 2
act2.ExpectOutcome := "TitleContains"
act2.ExpectValue := "never-matches"
res2 := pb2._ExecuteSingleActionWithPolicy(macro, act2)
NMS_ST_Add(results, "PB-01 repeatable step is still retried", pb2.dispatchCount = 3 && !res2.Success, "dispatches=" pb2.dispatchCount " (expected 3)")
} catch as e {
NMS_ST_Add(results, "PB-01 retry guard", false, "exception: " e.Message " (line " e.Line ")")
}
}
NMS_ST_Ambiguity(results) {
try {
t := TargetModel("SelfTest button", "Button", "UIA")
act := ActionModel("UIA_Click")
t.LastMatchCount := 3
pbStop := NMS_TestPlayback({persistence: {settings: Map("AmbiguousTargetPolicy", "Stop")}})
out := pbStop._ApplyAmbiguityPolicy(act, t, Map("Found", true, "Message", ""))
NMS_ST_Add(results, "PC-03 policy Stop refuses an ambiguous target", !out["Found"] && InStr(out["Message"], "Ambiguous") > 0, "Found=" out["Found"])
pbWarn := NMS_TestPlayback({persistence: {settings: Map("AmbiguousTargetPolicy", "Warn")}})
out := pbWarn._ApplyAmbiguityPolicy(act, t, Map("Found", true, "Message", ""))
NMS_ST_Add(results, "PC-03 policy Warn proceeds and logs one warning", out["Found"] && pbWarn.logger.entries.Length = 1, "Found=" out["Found"] " logEntries=" pbWarn.logger.entries.Length)
pbFirst := NMS_TestPlayback({persistence: {settings: Map("AmbiguousTargetPolicy", "UseFirst")}})
out := pbFirst._ApplyAmbiguityPolicy(act, t, Map("Found", true, "Message", ""))
NMS_ST_Add(results, "PC-03 policy UseFirst proceeds silently", out["Found"] && pbFirst.logger.entries.Length = 0, "Found=" out["Found"] " logEntries=" pbFirst.logger.entries.Length)
pbNone := NMS_TestPlayback()
out := pbNone._ApplyAmbiguityPolicy(act, t, Map("Found", true, "Message", ""))
NMS_ST_Add(results, "PC-03 no settings object (exported script) defaults to Warn", out["Found"] && pbNone.logger.entries.Length = 1, "Found=" out["Found"] " logEntries=" pbNone.logger.entries.Length)
act.Parameters["AllowAmbiguousTarget"] := true
out := pbStop._ApplyAmbiguityPolicy(act, t, Map("Found", true, "Message", ""))
NMS_ST_Add(results, "PC-03 a step marked allow-ambiguity is not refused", out["Found"], "Found=" out["Found"])
act.Parameters["AllowAmbiguousTarget"] := false
t.LastMatchCount := 1
out := pbStop._ApplyAmbiguityPolicy(act, t, Map("Found", true, "Message", ""))
NMS_ST_Add(results, "PC-03 a unique match is never refused", out["Found"], "Found=" out["Found"])
t.LastMatchCount := 3
out := pbStop._ApplyAmbiguityPolicy(act, t, Map("Found", false, "Message", "not found"))
NMS_ST_Add(results, "PC-03 a not-found result passes through unchanged", !out["Found"] && out["Message"] == "not found", "Message=" out["Message"])
} catch as e {
NMS_ST_Add(results, "PC-03 ambiguity policy", false, "exception: " e.Message " (line " e.Line ")")
}
}
NMS_ST_Metrics(results) {
try {
t := TargetModel("SelfTest", "Button", "UIA")
t.RecordOutcome(true, "UIA_Primary", 1)
TargetModel.MetricsStart()
t.RecordOutcome(true, "UIA_Primary", 1)
t.RecordOutcome(true, "UIA_Primary", 2)
t.RecordOutcome(true, "UIA_Alternate", 1)
t.RecordOutcome(true, "ScreenCoord", 1)
t.RecordOutcome(false, "None", 0)
d := TargetModel.MetricsStop()
t.RecordOutcome(true, "UIA_Primary", 1)
good := d["Unique"] = 1 && d["Ambiguous"] = 1 && d["Fallback"] = 1 && d["Coordinate"] = 1 && d["NotFound"] = 1
NMS_ST_Add(results, "PC-02 counters count only while a macro is playing", good, "unique=" d["Unique"] " ambiguous=" d["Ambiguous"] " fallback=" d["Fallback"] " coordinate=" d["Coordinate"] " notfound=" d["NotFound"] " (expected 1 each)")
txt := TargetModel.MetricsText(d)
NMS_ST_Add(results, "PC-02 summary text", InStr(txt, "AMBIGUOUS 1") > 0, txt)
} catch as e {
NMS_ST_Add(results, "PC-02 metrics", false, "exception: " e.Message " (line " e.Line ")")
}
}
NMS_ST_Schema(results) {
try {
p := ProjectModel("SelfTest project")
m := p.ToMap()
m["SchemaVersion"] := 3
threw := false
msg := ""
try ProjectModel.FromMap(m)
catch as e {
threw := true
msg := e.Message
}
NMS_ST_Add(results, "PB-02 newer-schema project is refused", threw && InStr(msg, "newer version") > 0, msg)
m2 := p.ToMap()
loadedOk := true
try ProjectModel.FromMap(m2)
catch as e2 {
loadedOk := false
msg := e2.Message
}
NMS_ST_Add(results, "PB-02 current-schema project still loads", loadedOk, loadedOk ? "ok" : msg)
} catch as e3 {
NMS_ST_Add(results, "PB-02 schema check", false, "exception: " e3.Message " (line " e3.Line ")")
}
}
NMS_ST_Risky(results) {
try {
pbOn := NMS_TestPlayback({persistence: {settings: Map("ConfirmRiskyActions", true)}})
pbOff := NMS_TestPlayback({persistence: {settings: Map("ConfirmRiskyActions", false)}})
risky := ActionModel("File_Write")
calm := ActionModel("Wait_Duration")
NMS_ST_Add(results, "PC-04 risky type needs confirmation when the setting is on", pbOn._RiskyActionReason(risky) != "", pbOn._RiskyActionReason(risky))
NMS_ST_Add(results, "PC-04 calm type never needs confirmation", pbOn._RiskyActionReason(calm) == "", "reason='" pbOn._RiskyActionReason(calm) "'")
NMS_ST_Add(results, "PC-04 nothing is asked when the setting is off", pbOff._RiskyActionReason(risky) == "", "reason='" pbOff._RiskyActionReason(risky) "'")
calm.Parameters["ConfirmBeforeRun"] := true
NMS_ST_Add(results, "PC-04 a step marked confirm-before-run is always confirmed", pbOff._RiskyActionReason(calm) != "", pbOff._RiskyActionReason(calm))
} catch as e {
NMS_ST_Add(results, "PC-04 risky-step check", false, "exception: " e.Message " (line " e.Line ")")
}
}
NMS_SelfTest_Run() {
results := []
NMS_ST_Retry(results)
NMS_ST_Ambiguity(results)
NMS_ST_Metrics(results)
NMS_ST_Schema(results)
NMS_ST_Risky(results)
failCnt := 0
for r in results {
StudioUtils.DiagnosticWrite((r["Ok"] ? "PASS" : "FAIL") " | " r["Name"] " | " r["Detail"] "`r`n")
if !r["Ok"]
failCnt += 1
}
StudioUtils.DiagnosticWrite("SELFTEST SUMMARY pass=" (results.Length - failCnt) " fail=" failCnt "`r`n")
ExitApp(failCnt ? 1 : 0)
}
; [NMS-PD-08] automated end-to-end checks that REPLACE the manual tests. Run with: --qa --nms-e2e
; It presses the real Stop key (F8) using SendLevel 1, so the app's own hotkey receives it (the hotkey swallows F8).
; It briefly holds Left Shift and always releases it. Hands off keyboard and mouse while it runs (about 30 seconds).
; THREAD MODEL (v9): AutoHotkey cannot resume an interrupted thread until the thread that interrupted it ends.
; So every scenario runs the macro in the MAIN thread (like a real playback) and a one-shot TIMER thread plays the
; "user" (presses F8, clicks a button). Timer threads re-arm themselves instead of waiting in a loop.
class NMS_E2EPlayback extends PlaybackEngine {
mode := "block"
dispatchCount := 0
verifyResult := false
lastChoice := "(dialog not asked)"
stopAtEntry := "?"
stopAfter := "?"
__New(app) {
a := g_StudioApp
super.__New(app, a.varStore, a.condEngine, a.uiaEngine, a.browserMgr, a.imageEngine, a.logger)
}
; "block" holds Left Shift and then ignores the stop flag for 4 seconds, like a long uninterruptible call.
_DispatchAction(macro, act) {
this.dispatchCount += 1
if this.mode = "block" {
this.SetHeldInput("LShift", true, "Key")
t0 := A_TickCount
while (A_TickCount - t0) < 4000
Sleep(20)
return ActionResultModel(false, "Stopped", "e2e blocked step ended")
}
return ActionResultModel(true, "Passed", "e2e ok")
}
_VerifyPostActionExpectation(macro, act) {
return this.verifyResult
}
; records what the confirmation dialog returned and whether the stop flag was already set when it opened
_ConfirmRiskyAction(macro, act, why) {
this.stopAtEntry := this.stopRequested ? 1 : 0
c := super._ConfirmRiskyAction(macro, act, why)
this.lastChoice := c
this.stopAfter := this.stopRequested ? 1 : 0
return c
}
}
NMS_E2E_Add(results, name, ok, detail := "") {
results.Push(Map("Name", name, "Ok", ok ? true : false, "Detail", detail))
}
NMS_E2E_Stub(proj, withGui := false) {
return {currentState: "Idle", project: proj, persistence: g_StudioApp.persistence, gui: withGui ? Object() : "", SetState: (*) => 0, ShowToast: (*) => 0}
}
NMS_E2E_PressStop() {
SendLevel(1)
SendEvent("{Blind}{F8}")
SendLevel(0)
}
; Runs the macro in the CURRENT thread (blocks until it ends) and records the outcome.
NMS_E2E_Play(pb, mac, res) {
try res["ok"] := pb.PlayMacro(mac)
catch as e
res["err"] := e.Message
res["done"] := true
}
NMS_E2E_Has(arr, v) {
for x in arr {
if x = v
return true
}
return false
}
; ---- M-03 / M-08 control thread: acts as the user while the main thread is stuck in a blocking step ----
NMS_E2E_StopCtl(pb, st) {
try {
if !GetKeyState("LShift") {
if (A_TickCount - st["t0"]) < 3000
SetTimer(NMS_E2E_StopCtl.Bind(pb, st), -20)
else
st["err"] := "Left Shift was never held by the blocked step"
return
}
st["shiftBefore"] := true
pb.Pause()
Sleep(40)
st["pausedUp"] := GetKeyState("LShift") ? false : true
pb.Resume()
Sleep(40)
st["resumedDown"] := GetKeyState("LShift") ? true : false
NMS_E2E_PressStop()
Sleep(600)
st["shiftAfter"] := GetKeyState("LShift") ? true : false
st["stopFlag"] := pb.stopRequested ? true : false
st["stillBlocked"] := pb.isRunning ? true : false
st["ctlDone"] := true
} catch as e {
st["err"] := "control thread: " e.Message " (line " e.Line ")"
}
}
; M-03, M-04, M-08: real F8 stops a macro stuck in a blocking step and releases a held key at once.
NMS_E2E_StopKey(results) {
a := g_StudioApp
orig := a.playback
st := Map("t0", A_TickCount, "shiftBefore", false, "pausedUp", false, "resumedDown", false, "shiftAfter", true, "stopFlag", false, "stillBlocked", false, "ctlDone", false, "err", "")
try {
mac := MacroModel("E2E stop")
mac.Actions.Push(ActionModel("Wait_Duration"))
pb := NMS_E2EPlayback(NMS_E2E_Stub(a.project))
a.playback := pb
res := Map("done", false, "ok", "", "err", "")
SetTimer(NMS_E2E_StopCtl.Bind(pb, st), -20)
NMS_E2E_Play(pb, mac, res)
ended := pb.isRunning ? false : true
NMS_E2E_Add(results, "M-08 pause releases a held key and resume presses it again", st["shiftBefore"] && st["pausedUp"] && st["resumedDown"], "heldBefore=" st["shiftBefore"] " upAfterPause=" st["pausedUp"] " downAfterResume=" st["resumedDown"] " err=" st["err"])
NMS_E2E_Add(results, "M-03 real F8 stops playback and releases the held key even while the step is blocked", st["shiftBefore"] && st["stopFlag"] && !st["shiftAfter"] && st["stillBlocked"] && ended, "stopFlag=" st["stopFlag"] " shiftReleasedWhileStillBlocked=" (!st["shiftAfter"] && st["stillBlocked"]) " shiftDownAfter600ms=" st["shiftAfter"] " playbackEnded=" ended " err=" st["err"])
pb.mode := "count"
res2 := Map("done", false, "ok", "", "err", "")
NMS_E2E_Play(pb, mac, res2)
NMS_E2E_Add(results, "M-04 a new playback starts normally after a Stop", res2["ok"] = true, "ok=" res2["ok"] " err=" res2["err"])
} catch as err {
NMS_E2E_Add(results, "M-03/M-04/M-08 stop key scenario", false, "exception: " err.Message " (line " err.Line ")")
} finally {
try SendEvent("{Blind}{LShift up}")
a.playback := orig
}
}
; ---- M-17 control thread: waits (by re-arming) for the confirmation dialog, then presses F8 or clicks a button ----
NMS_E2E_RiskyCtl(pb, st, how) {
try {
hwnd := WinExist("Confirm risky step ahk_pid " ProcessExist())
if !hwnd {
if (A_TickCount - st["t0"]) < 5000
SetTimer(NMS_E2E_RiskyCtl.Bind(pb, st, how), -30)
else
pb.EmergencyStop()
return
}
st["hwnd"] := hwnd
Sleep(150)
if how = "F8"
NMS_E2E_PressStop()
else
ControlClick(how = "Run" ? "Button1" : (how = "Skip" ? "Button2" : "Button3"), "ahk_id " hwnd)
st["acted"] := true
} catch as e {
st["err"] := "control thread: " e.Message " (line " e.Line ")"
try pb.EmergencyStop()
}
}
; M-17: the risky-step confirmation dialog. how = F8 | Run | Skip | Stop
NMS_E2E_RiskyOne(results, how) {
a := g_StudioApp
orig := a.playback
s := a.persistence.settings
hadKey := s.Has("ConfirmRiskyActions")
savedVal := hadKey ? s["ConfirmRiskyActions"] : false
label := "M-17 risky-step confirmation, " (how = "F8" ? "Stop key closes it and stops" : (how = "Run" ? "Run button runs the step" : (how = "Skip" ? "Skip button skips the step" : "Stop button stops")))
try {
s["ConfirmRiskyActions"] := true
mac := MacroModel("E2E risky")
act := ActionModel("File_Write")
mac.Actions.Push(act)
pb := NMS_E2EPlayback(NMS_E2E_Stub(a.project))
pb.mode := "count"
a.playback := pb
reason := pb._RiskyActionReason(act)
res := Map("done", false, "ok", "", "err", "")
st := Map("t0", A_TickCount, "hwnd", 0, "acted", false, "err", "")
SetTimer(NMS_E2E_RiskyCtl.Bind(pb, st, how), -20)
NMS_E2E_Play(pb, mac, res)
if !st["hwnd"] {
NMS_E2E_Add(results, label, false, "the confirmation dialog did not appear; reason='" reason "' macroOk=" res["ok"] " err=" res["err"] " ctlErr=" st["err"] " stepRan=" pb.dispatchCount)
return
}
gone := WinExist("ahk_id " st["hwnd"]) ? false : true
wantRan := (how = "Run") ? 1 : 0
wantOk := (how = "Run" || how = "Skip") ? true : false
good := gone && res["done"] && (pb.dispatchCount = wantRan) && ((res["ok"] = true) = wantOk)
NMS_E2E_Add(results, label, good, "dialogClosed=" gone " finished=" res["done"] " stepRan=" pb.dispatchCount " (want " wantRan ") macroOk=" res["ok"] " (want " wantOk ") err=" res["err"] " ctlErr=" st["err"] " dialogReturned=" pb.lastChoice " stopFlagAtOpen=" pb.stopAtEntry " stopFlagAfter=" pb.stopAfter " clicked=" st["acted"])
} catch as err {
NMS_E2E_Add(results, label, false, "exception: " err.Message " (line " err.Line ")")
} finally {
Sleep(400)
if hadKey
s["ConfirmRiskyActions"] := savedVal
else if s.Has("ConfirmRiskyActions")
s.Delete("ConfirmRiskyActions")
a.playback := orig
}
}
; M-18: the Target Not Found repair dialog closes when Stop is requested.
NMS_E2E_Repair(results) {
a := g_StudioApp
try {
mac := MacroModel("E2E repair")
act := ActionModel("UIA_Click")
mac.Actions.Push(act)
pb := NMS_E2EPlayback(NMS_E2E_Stub(a.project, true))
SetTimer(() => pb.EmergencyStop(), -700)
t0 := A_TickCount
choice := pb._PromptInteractiveTargetRepair(mac, act, ActionResultModel(false, "Failed", "e2e"))
took := A_TickCount - t0
stillOpen := WinExist("Target Not Found ahk_pid " ProcessExist()) ? true : false
NMS_E2E_Add(results, "M-18 the repair dialog closes and returns Stop when Stop is requested", choice = "Stop" && took < 3500 && !stillOpen, "choice=" choice " ms=" took " stillOpen=" stillOpen)
} catch as err {
NMS_E2E_Add(results, "M-18 repair dialog and Stop", false, "exception: " err.Message " (line " err.Line ")")
}
}
; Watches (by re-arming) for the repair dialog; if it ever appears the check fails and the dialog is closed.
NMS_E2E_WatchRepair(pb, st) {
if st.Has("stop")
return
if WinExist("Target Not Found ahk_pid " ProcessExist()) {
st["dlg"] := true
pb.EmergencyStop()
return
}
if (A_TickCount - st["t0"]) < 6000
SetTimer(NMS_E2E_WatchRepair.Bind(pb, st), -30)
}
; M-19: a step that already ran (post-check failed) is not retried and does not open the repair dialog.
NMS_E2E_NoRetryDialog(results) {
a := g_StudioApp
try {
mac := MacroModel("E2E noretry")
act := ActionModel("UIA_Click")
act.RetryCount := 3
act.ExpectOutcome := "TitleContains"
act.ExpectValue := "never-matches"
mac.Actions.Push(act)
pb := NMS_E2EPlayback(NMS_E2E_Stub(a.project, true))
pb.mode := "count"
res := Map("done", false, "ok", "", "err", "")
st := Map("t0", A_TickCount, "dlg", false)
SetTimer(NMS_E2E_WatchRepair.Bind(pb, st), -20)
NMS_E2E_Play(pb, mac, res)
st["stop"] := true
NMS_E2E_Add(results, "M-19 no repair dialog and no re-run for a step that already ran", !st["dlg"] && res["done"] && pb.dispatchCount = 1, "repairDialogShown=" st["dlg"] " finished=" res["done"] " dispatches=" pb.dispatchCount " (want 1) err=" res["err"])
} catch as err {
NMS_E2E_Add(results, "M-19 no retry dialog", false, "exception: " err.Message " (line " err.Line ")")
}
}
; M-11, M-15: Stop key fallback and trigger-versus-Stop protection, checked on the real hotkey table.
NMS_E2E_Hotkeys(results) {
a := g_StudioApp
s := a.persistence.settings
savedStop := s["Hotkey_Stop"]
macroCount := a.project.Macros.Length
try {
s["Hotkey_Stop"] := "ZZZ_not_a_key"
a.RegisterGlobalStudioHotkeys()
NMS_E2E_Add(results, "M-11 an unusable Stop key falls back to F8", NMS_E2E_Has(a.registeredHotkeys, "*F8"), "registered=" NMS_E2E_Join(a.registeredHotkeys))
s["Hotkey_Stop"] := "F8"
m1 := MacroModel("E2E trigger F8")
m1.TriggerHotkey := "F8"
m2 := MacroModel("E2E trigger Ctrl+F8")
m2.TriggerHotkey := "^F8"
a.project.Macros.Push(m1)
a.project.Macros.Push(m2)
a.RegisterGlobalStudioHotkeys()
shadow := NMS_E2E_Has(a.registeredHotkeys, "F8") || NMS_E2E_Has(a.registeredHotkeys, "^F8")
stopOk := NMS_E2E_Has(a.registeredHotkeys, "*F8")
NMS_E2E_Add(results, "M-15 a macro trigger on F8 or Ctrl+F8 is refused and Stop stays registered", !shadow && stopOk, "registered=" NMS_E2E_Join(a.registeredHotkeys))
} catch as err {
NMS_E2E_Add(results, "M-11/M-15 hotkey checks", false, "exception: " err.Message " (line " err.Line ")")
} finally {
while a.project.Macros.Length > macroCount
a.project.Macros.Pop()
s["Hotkey_Stop"] := savedStop
try a.RegisterGlobalStudioHotkeys()
}
}
NMS_E2E_Join(arr) {
out := ""
for x in arr
out .= (out = "" ? "" : ",") x
return out
}
; M-14: a project file written by a newer schema is refused and left untouched.
NMS_E2E_Schema(results) {
a := g_StudioApp
path := StudioConstants.AppDataDir "\e2e_newer_schema.json"
try {
if !DirExist(StudioConstants.AppDataDir)
DirCreate(StudioConstants.AppDataDir)
m := ProjectModel("E2E newer").ToMap()
m["SchemaVersion"] := 3
txt := JsonCodec.Dump(m, " ")
try FileDelete(path)
FileAppend(txt, path, "UTF-8-RAW")
before := FileRead(path, "UTF-8-RAW")
threw := false
msg := ""
try a.persistence.LoadProject(path)
catch as e {
threw := true
msg := e.Message
}
after := FileRead(path, "UTF-8-RAW")
NMS_E2E_Add(results, "M-14 a project file with a newer schema is refused and left unchanged", threw && InStr(msg, "newer version") > 0 && before == after, "refused=" threw " unchanged=" (before == after) " message=" msg)
} catch as err {
NMS_E2E_Add(results, "M-14 newer schema file", false, "exception: " err.Message " (line " err.Line ")")
} finally {
try FileDelete(path)
}
}
; M-01: Stop pressed while nothing is running raises no error dialog.
NMS_E2E_IdleStop(results) {
try {
NMS_E2E_PressStop()
Sleep(500)
dlg := WinExist("ahk_class #32770 ahk_pid " ProcessExist()) ? true : false
NMS_E2E_Add(results, "M-01 Stop pressed while idle raises no error dialog", !dlg, "dialogOpen=" dlg)
} catch as err {
NMS_E2E_Add(results, "M-01 idle stop", false, "exception: " err.Message " (line " err.Line ")")
}
}
; New settings screen: controls build, Save stores the values, reopening shows them.
NMS_E2E_Options(results) {
a := g_StudioApp
s := a.persistence.settings
savedPol := s.Get("AmbiguousTargetPolicy", "Warn")
savedRisk := s.Get("ConfirmRiskyActions", false)
try {
a.gui.Build()
ui := StudioOptionsUI(a.gui)
ui.fields["AmbiguousTargetPolicy"].Choose(2)
ui.fields["ConfirmRiskyActions"].Value := 1
saved := ui.Save()
stored := saved && s["AmbiguousTargetPolicy"] = "Stop" && StudioUtils.ToBool(s["ConfirmRiskyActions"])
NMS_E2E_Add(results, "PD-01..03 Settings: Save stores the ambiguity policy and risky-step choice", stored, "saved=" saved " policy=" s.Get("AmbiguousTargetPolicy", "?") " confirm=" s.Get("ConfirmRiskyActions", "?"))
ui2 := StudioOptionsUI(a.gui)
polIdx2 := ui2.fields["AmbiguousTargetPolicy"].Value
chkVal2 := ui2.fields["ConfirmRiskyActions"].Value
ui2.Close()
NMS_E2E_Add(results, "PD-01..03 Settings: reopening shows the saved choices", polIdx2 = 2 && chkVal2 = 1, "policyIndex=" polIdx2 " (want 2) confirmChecked=" chkVal2 " (want 1)")
} catch as err {
NMS_E2E_Add(results, "PD-01..03 Settings screen", false, "exception: " err.Message " (line " err.Line ")")
} finally {
s["AmbiguousTargetPolicy"] := savedPol
s["ConfirmRiskyActions"] := savedRisk
}
}
; M-05, M-10: after every scenario nothing is left logically held down.
NMS_E2E_NoStuckKeys(results) {
stuck := ""
for k in ["LCtrl", "RCtrl", "LAlt", "RAlt", "LShift", "RShift", "LWin", "RWin", "LButton", "RButton", "MButton", "XButton1", "XButton2"] {
if GetKeyState(k) && !GetKeyState(k, "P")
stuck .= k " "
}
NMS_E2E_Add(results, "M-05/M-10 no modifier or mouse button is left held after all scenarios", stuck = "", "stuck=[" stuck "]")
}
NMS_E2E_Run() {
results := []
a := g_StudioApp
NMS_E2E_Add(results, "StudioSafety module is part of this build", IsSet(StudioSafety), "")
try a.RegisterGlobalStudioHotkeys()
NMS_E2E_StopKey(results)
NMS_E2E_RiskyOne(results, "F8")
NMS_E2E_RiskyOne(results, "Run")
NMS_E2E_RiskyOne(results, "Skip")
NMS_E2E_RiskyOne(results, "Stop")
NMS_E2E_Repair(results)
NMS_E2E_NoRetryDialog(results)
NMS_E2E_Hotkeys(results)
NMS_E2E_Schema(results)
NMS_E2E_IdleStop(results)
NMS_E2E_NoStuckKeys(results)
NMS_E2E_Options(results)
failCnt := 0
for r in results {
StudioUtils.DiagnosticWrite((r["Ok"] ? "PASS" : "FAIL") " | " r["Name"] " | " r["Detail"] "`r`n")
if !r["Ok"]
failCnt += 1
}
StudioUtils.DiagnosticWrite("E2E SUMMARY pass=" (results.Length - failCnt) " fail=" failCnt "`r`n")
ExitApp(failCnt ? 1 : 0)
}
; M-20: writes an exported standalone script so the harness can run it from another folder.
NMS_ExportTest_Run() {
outPath := ""
for i, v in A_Args {
if v = "--nms-export-test" && i < A_Args.Length
outPath := A_Args[i + 1]
}
if outPath = "" {
StudioUtils.DiagnosticWrite("FAIL | export test | no output path given`r`n")
ExitApp(1)
}
try {
p := ProjectModel("E2E export")
act := ActionModel("Wait_Duration")
pp := ""
for k, v in act.Parameters
pp .= k "=" (IsObject(v) ? "(object)" : v) "; "
StudioUtils.DiagnosticWrite("INFO | Wait_Duration default parameters | " pp "`r`n")
p.GetActiveMacro().Actions.Push(act)
txt := AHKExporter.ExportProjectToAhk(p, "Auto", "Once", 0)
f := FileOpen(outPath, "w", "UTF-8")
f.Write(txt)
f.Close()
StudioUtils.DiagnosticWrite("PASS | export written | chars=" StrLen(txt) "`r`n")
ExitApp(0)
} catch as err {
StudioUtils.DiagnosticWrite("FAIL | export threw | " err.Message " (line " err.Line ")`r`n")
ExitApp(1)
}
}
; M-09: closing the app while a macro holds Shift. The harness checks the key state AFTER the process exits.
; The macro runs in the main thread; a timer thread (the "user closing the app") fires while the step is blocked.
NMS_ExitTest_Ctl(st) {
held := GetKeyState("LShift") ? true : false
if !held && (A_TickCount - st["t0"]) < 3000 {
SetTimer(NMS_ExitTest_Ctl.Bind(st), -20)
return
}
Sleep(150)
held := GetKeyState("LShift") ? true : false
StudioUtils.DiagnosticWrite("EXITTEST shift_down_before_exit=" (held ? 1 : 0) "`r`n")
g_StudioApp.ShutdownAndExit()
}
NMS_ExitTest_Run() {
a := g_StudioApp
mac := MacroModel("E2E exit")
mac.Actions.Push(ActionModel("Wait_Duration"))
pb := NMS_E2EPlayback(NMS_E2E_Stub(a.project))
a.playback := pb
res := Map("done", false, "ok", "", "err", "")
st := Map("t0", A_TickCount)
SetTimer(NMS_ExitTest_Ctl.Bind(st), -20)
NMS_E2E_Play(pb, mac, res)
StudioUtils.DiagnosticWrite("EXITTEST the app did not exit by itself; playback ended first`r`n")
ExitApp(1)
}