# Raids Timer PC popup (Chat helper). Tray next to the clock. # Prefer double-click pc-banner.cmd so Windows cannot flash-close this script. # Right-click this file → Run with PowerShell also works after Unblock. # Auto Farm: right-click tray → How to use Auto Farm. param([switch]$DetectOnly, [switch]$ListProfiles, [switch]$OpenChat, [switch]$OpenFarm, [switch]$SkipWebUpdate) $script:HelperVersion = "1.0.201" $script:FarmMaxInstances = 12 $script:FarmSplitMax = 4 $script:helperT = @{} function Show-HelperCrash { param($err) $txt = @" The helper stopped before the tray icon stayed open. $err If Windows closed a black window: 1. Double-click pc-banner.cmd (not only the .ps1). 2. Right-click pc-banner.ps1 → Properties → tick Unblock → Apply. 3. If you see Windows protected your PC → More info → Run anyway. 4. The icon sits next to the clock. Click the up-arrow ^ if it is hidden. "@ try { Add-Type -AssemblyName System.Windows.Forms -ErrorAction SilentlyContinue [void][System.Windows.Forms.MessageBox]::Show( $txt, "Raids Timer helper", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Warning ) } catch { Write-Host $txt Start-Sleep -Seconds 25 } } function Get-HelperCrashLogPath { return (Join-Path $env:APPDATA "RaidsTimer\helper-crash-log.txt") } function Write-HelperCrashLog([string]$err) { $line = [string]$err if (-not $line) { return } try { $p = Get-HelperCrashLogPath $dir = Split-Path -Parent $p if ($dir -and -not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Force -Path $dir | Out-Null } $row = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss") + " " + $line.Replace("`r", " ").Replace("`n", " ") $old = @() if (Test-Path -LiteralPath $p) { $old = @(Get-Content -LiteralPath $p -ErrorAction SilentlyContinue) } $all = @($old + $row) if ($all.Count -gt 120) { $all = $all[($all.Count - 120)..($all.Count - 1)] } Set-Content -LiteralPath $p -Value $all -Encoding UTF8 } catch {} } function Write-HelperCrash([string]$err) { try { $p = Join-Path $env:APPDATA "RaidsTimer\helper-crash.txt" $dir = Split-Path -Parent $p if ($dir -and -not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Force -Path $dir | Out-Null } Set-Content -LiteralPath $p -Value (((Get-Date).ToString("o")) + "`r`n" + [string]$err) -Encoding UTF8 } catch {} Write-HelperCrashLog ([string]$err) } function Get-HelperCrashLogText { $who = "" $srv = "" try { if ($script:cfg -and $script:cfg.displayName) { $who = [string]$script:cfg.displayName } } catch {} try { if ($script:cfg -and $script:cfg.serverNumber) { $srv = [string]$script:cfg.serverNumber } } catch {} $paid = "" try { $paid = [string]$script:farmBox.chatPaid } catch {} $lines = New-Object System.Collections.Generic.List[string] [void]$lines.Add("Raids Timer helper crash log") [void]$lines.Add("version=" + [string]$script:HelperVersion) [void]$lines.Add("commander=" + $who + " server=" + $srv) [void]$lines.Add("chatPaid=" + $paid) [void]$lines.Add("copied=" + (Get-Date).ToString("yyyy-MM-dd HH:mm:ss")) [void]$lines.Add("") $p = Get-HelperCrashLogPath if (Test-Path -LiteralPath $p) { [void]$lines.Add("--- recent ---") foreach ($row in @(Get-Content -LiteralPath $p -ErrorAction SilentlyContinue)) { if ($row) { [void]$lines.Add([string]$row) } } } else { [void]$lines.Add("--- recent ---") [void]$lines.Add("(no crash lines yet)") } $last = Join-Path $env:APPDATA "RaidsTimer\helper-crash.txt" if (Test-Path -LiteralPath $last) { [void]$lines.Add("") [void]$lines.Add("--- last crash ---") foreach ($row in @(Get-Content -LiteralPath $last -ErrorAction SilentlyContinue)) { [void]$lines.Add([string]$row) } } return ($lines -join "`r`n") } function Copy-HelperCrashLog { $txt = Get-HelperCrashLogText try { [System.Windows.Forms.Clipboard]::SetText($txt) return $true } catch { return $false } } function Show-HelperCrashLog { $txt = Get-HelperCrashLogText $dlg = New-Object System.Windows.Forms.Form $dlg.Text = "Crash log · copy and paste" $dlg.Size = New-Object System.Drawing.Size(560, 420) $dlg.StartPosition = "CenterScreen" $dlg.TopMost = $true $dlg.MinimizeBox = $false $dlg.MaximizeBox = $false $dlg.FormBorderStyle = "FixedDialog" try { $dlg.Icon = $script:appIcon } catch {} $box = New-Object System.Windows.Forms.TextBox $box.Multiline = $true $box.ReadOnly = $true $box.ScrollBars = "Vertical" $box.Location = New-Object System.Drawing.Point(12, 12) $box.Size = New-Object System.Drawing.Size(520, 320) $box.BackColor = [System.Drawing.Color]::FromArgb(24, 28, 22) $box.ForeColor = [System.Drawing.Color]::FromArgb(236, 255, 210) $box.Font = New-Object System.Drawing.Font("Consolas", 10) $box.HideSelection = $true $box.Text = $txt $box.SelectionStart = 0 $box.SelectionLength = 0 $copy = New-Object System.Windows.Forms.Button $copy.Text = "Copy" $copy.Location = New-Object System.Drawing.Point(12, 344) $copy.Size = New-Object System.Drawing.Size(160, 32) $close = New-Object System.Windows.Forms.Button $close.Text = "Close" $close.Location = New-Object System.Drawing.Point(372, 344) $close.Size = New-Object System.Drawing.Size(160, 32) $copy.Add_Click({ if (Copy-HelperCrashLog) { Set-FarmStatus "Crash log copied. Paste it in chat." } else { Set-FarmStatus "Could not copy. Select the text and Ctrl+C." } }) $close.Add_Click({ Close-ClickedHelperForm }) $dlg.Controls.AddRange(@($box, $copy, $close)) [void]$dlg.ShowDialog() $dlg.Dispose() } function Write-HelperBoot([string]$step) { try { Set-Content -LiteralPath (Join-Path $env:APPDATA "RaidsTimer\helper-boot.txt") -Value (((Get-Date).ToString("o")) + " " + [string]$step) -Encoding UTF8 } catch {} } trap { Write-HelperCrash $_ if ($script:helperUiUp) { continue } continue } try { Unblock-File -LiteralPath $PSCommandPath -ErrorAction SilentlyContinue } catch {} try { Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force -ErrorAction SilentlyContinue } catch {} function Clear-HelperMarkOfWeb([string]$path) { if (-not $path) { return } try { Unblock-File -LiteralPath $path -ErrorAction SilentlyContinue } catch {} try { Remove-Item -LiteralPath $path -Stream Zone.Identifier -Force -ErrorAction SilentlyContinue } catch {} } function Copy-HelperFileClean([string]$from, [string]$to) { if (-not $from -or -not $to -or -not (Test-Path -LiteralPath $from)) { return $false } try { $dir = Split-Path -Parent $to if ($dir -and -not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Force -Path $dir | Out-Null } [IO.File]::WriteAllBytes($to, [IO.File]::ReadAllBytes($from)) Clear-HelperMarkOfWeb $to return $true } catch { return $false } } try { Clear-HelperMarkOfWeb $PSCommandPath } catch {} try { $h = Invoke-RestMethod -Uri "http://127.0.0.1:18765/health" -TimeoutSec 2 if ($h -and $h.ok -eq $true) { $running = [version]"0.0.0" try { if ($h.version) { $running = [version]([string]$h.version) } } catch {} $meVer = [version]"0.0.0" try { $meVer = [version]$script:HelperVersion } catch {} if ($running -ge $meVer) { if ($OpenFarm -or $OpenChat) { try { Invoke-RestMethod -Method POST -Uri "http://127.0.0.1:18765/ui/open" -ContentType "application/json" -Body "{}" -TimeoutSec 3 | Out-Null } catch {} } exit 0 } } } catch {} try { $mePid = [int]$PID Get-CimInstance Win32_Process -Filter "Name='powershell.exe' OR Name='pwsh.exe'" -ErrorAction SilentlyContinue | ForEach-Object { $cl = [string]$_.CommandLine if ($cl -notmatch 'pc-banner\.ps1') { return } if ([int]$_.ProcessId -eq $mePid) { return } try { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } catch {} } } catch {} $ErrorActionPreference = "Continue" try { Add-Type -AssemblyName System.Windows.Forms } catch {} try { Add-Type -AssemblyName System.Drawing } catch {} try { Add-Type -AssemblyName Microsoft.VisualBasic } catch {} Add-Type @" using System; using System.Runtime.InteropServices; using System.Text; public static class RtFarmMouse { [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X; public int Y; } [DllImport("user32.dll")] public static extern bool SetCursorPos(int X, int Y); [DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT lpPoint); [DllImport("user32.dll")] public static extern short GetAsyncKeyState(int vKey); [DllImport("user32.dll")] public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, UIntPtr dwExtraInfo); [DllImport("user32.dll")] public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo); public const uint LEFTDOWN = 0x0002; public const uint LEFTUP = 0x0004; public const uint KEYUP = 0x0002; public static void Down() { mouse_event(LEFTDOWN, 0, 0, 0, UIntPtr.Zero); } public static void Up() { mouse_event(LEFTUP, 0, 0, 0, UIntPtr.Zero); } public static void KeyDown(byte vk) { if (vk != 0) keybd_event(vk, 0, 0, UIntPtr.Zero); } public static void KeyUp(byte vk) { if (vk != 0) keybd_event(vk, 0, KEYUP, UIntPtr.Zero); } } public static class RtFarmKeys179 { [DllImport("user32.dll")] public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo); public const uint KEYUP = 0x0002; public static void Down(byte vk) { if (vk != 0) keybd_event(vk, 0, 0, UIntPtr.Zero); } public static void Up(byte vk) { if (vk != 0) keybd_event(vk, 0, KEYUP, UIntPtr.Zero); } } public static class RtFarmGeom { public struct RECT { public int Left, Top, Right, Bottom; } public delegate bool EnumProc(IntPtr h, IntPtr l); [DllImport("user32.dll")] public static extern bool EnumWindows(EnumProc cb, IntPtr l); [DllImport("user32.dll")] public static extern int GetWindowText(IntPtr h, StringBuilder s, int n); [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h); [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r); [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr insertAfter, int X, int Y, int cx, int cy, uint flags); [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hWnd); [DllImport("user32.dll")] public static extern bool IsZoomed(IntPtr hWnd); public static IntPtr FindTitleContains(string part) { IntPtr found = IntPtr.Zero; if (string.IsNullOrEmpty(part)) return found; EnumWindows((h, l) => { if (!IsWindowVisible(h)) return true; var sb = new StringBuilder(512); GetWindowText(h, sb, 512); var t = sb.ToString(); if (t.IndexOf(part, StringComparison.OrdinalIgnoreCase) >= 0) { found = h; return false; } return true; }, IntPtr.Zero); return found; } public static string[] ListTitles() { var list = new System.Collections.Generic.List(); EnumWindows((h, l) => { if (!IsWindowVisible(h)) return true; var sb = new StringBuilder(512); GetWindowText(h, sb, 512); var t = sb.ToString(); if (t.Length >= 2 && t.IndexOf("Auto Farm", StringComparison.OrdinalIgnoreCase) < 0) list.Add(t); return true; }, IntPtr.Zero); return list.ToArray(); } } "@ Add-Type -ReferencedAssemblies System.Drawing.dll -TypeDefinition @" using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; public static class RtFarmGrab { [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; } [DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr hwnd, IntPtr hdc, uint flags); [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hwnd); [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hwnd, int nCmdShow); [DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr hwnd); [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hwnd); [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr pid); [DllImport("kernel32.dll")] public static extern uint GetCurrentThreadId(); [DllImport("user32.dll")] public static extern bool AttachThreadInput(uint a, uint b, bool attach); [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hwnd, out RECT r); [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hwnd); [DllImport("user32.dll")] public static extern bool EnumChildWindows(IntPtr parent, ChildProc cb, IntPtr lParam); public delegate bool ChildProc(IntPtr hwnd, IntPtr lParam); static ChildProc keepChildProc; static IntPtr bestChild; static int bestArea; public static bool PickChild(IntPtr hwnd, IntPtr lParam) { if (!IsWindowVisible(hwnd)) return true; RECT r; if (!GetWindowRect(hwnd, out r)) return true; int w = r.Right - r.Left; int hh = r.Bottom - r.Top; if (w < 180 || hh < 180) return true; int area = w * hh; if (area > bestArea) { bestArea = area; bestChild = hwnd; } return true; } [DllImport("user32.dll")] public static extern uint GetDpiForWindow(IntPtr hwnd); [DllImport("user32.dll")] public static extern IntPtr GetDC(IntPtr hwnd); [DllImport("user32.dll")] public static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc); [DllImport("gdi32.dll")] public static extern int GetDeviceCaps(IntPtr hdc, int index); public static double ScaleOf(IntPtr hwnd) { try { if (hwnd != IntPtr.Zero) { uint dpi = GetDpiForWindow(hwnd); if (dpi >= 96) return dpi / 96.0; } } catch {} IntPtr dc = GetDC(IntPtr.Zero); try { int logical = GetDeviceCaps(dc, 8); int physical = GetDeviceCaps(dc, 118); if (logical > 0 && physical > logical) return physical / (double)logical; } finally { if (dc != IntPtr.Zero) ReleaseDC(IntPtr.Zero, dc); } return 1.0; } public static IntPtr GameSurface(IntPtr parent) { if (parent == IntPtr.Zero || IsIconic(parent)) return parent; bestChild = IntPtr.Zero; bestArea = 0; if (keepChildProc == null) keepChildProc = new ChildProc(PickChild); EnumChildWindows(parent, keepChildProc, IntPtr.Zero); if (bestChild != IntPtr.Zero) return bestChild; return parent; } [DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(IntPtr hwnd, int attr, out RECT r, int size); public static RECT ScreenFrame(IntPtr hwnd) { RECT frame; int rc = DwmGetWindowAttribute(hwnd, 9, out frame, Marshal.SizeOf(typeof(RECT))); if (rc != 0 || frame.Right - frame.Left < 20 || frame.Bottom - frame.Top < 20) { GetWindowRect(hwnd, out frame); } return frame; } public static bool IsMinimized(IntPtr hwnd) { if (hwnd == IntPtr.Zero) return false; return IsIconic(hwnd); } public static void Focus(IntPtr hwnd) { if (hwnd == IntPtr.Zero || IsIconic(hwnd)) return; if (GetForegroundWindow() == hwnd) return; ShowWindow(hwnd, 5); IntPtr fg = GetForegroundWindow(); uint fgThread = GetWindowThreadProcessId(fg, IntPtr.Zero); uint me = GetCurrentThreadId(); if (fgThread != 0 && fgThread != me) AttachThreadInput(me, fgThread, true); BringWindowToTop(hwnd); SetForegroundWindow(hwnd); if (fgThread != 0 && fgThread != me) AttachThreadInput(me, fgThread, false); } public static Bitmap FromWindow(IntPtr hwnd, int w, int h) { if (hwnd == IntPtr.Zero || w < 8 || h < 8) return null; var bmp = new Bitmap(w, h, PixelFormat.Format32bppArgb); using (var g = Graphics.FromImage(bmp)) { IntPtr hdc = g.GetHdc(); bool ok = false; try { ok = PrintWindow(hwnd, hdc, 2); } finally { g.ReleaseHdc(hdc); } if (!ok) { bmp.Dispose(); return null; } } return bmp; } } "@ Add-Type -ReferencedAssemblies System.Drawing.dll -TypeDefinition @" using System; using System.Drawing; using System.Runtime.InteropServices; public static class RtFarmGlass { [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X; public int Y; } [DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT lpPoint); [DllImport("user32.dll")] public static extern bool GetPhysicalCursorPos(out POINT lpPoint); [DllImport("user32.dll")] public static extern IntPtr GetDC(IntPtr hWnd); [DllImport("user32.dll")] public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); [DllImport("user32.dll")] public static extern int GetSystemMetrics(int nIndex); [DllImport("user32.dll")] public static extern int GetWindowLong(IntPtr hWnd, int nIndex); [DllImport("user32.dll")] public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); [DllImport("user32.dll")] public static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags); [DllImport("gdi32.dll")] public static extern bool BitBlt(IntPtr hdcDest, int xDest, int yDest, int w, int h, IntPtr hdcSrc, int xSrc, int ySrc, int rop); [DllImport("gdi32.dll")] public static extern int GetDeviceCaps(IntPtr hdc, int index); public const int SRCCOPY = 0x00CC0020; public const int GWL_EXSTYLE = -20; public const int WS_EX_LAYERED = 0x80000; public const int WS_EX_TRANSPARENT = 0x20; public const int WS_EX_TOOLWINDOW = 0x80; public const int LWA_ALPHA = 0x2; public static int LastX; public static int LastY; public static void MakeClickThroughLoupe(IntPtr hwnd) { int ex = GetWindowLong(hwnd, GWL_EXSTYLE); SetWindowLong(hwnd, GWL_EXSTYLE, ex | WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW); SetLayeredWindowAttributes(hwnd, 0, 255, LWA_ALPHA); } public static void ReadCursor(out int x, out int y) { POINT p; GetCursorPos(out p); x = p.X; y = p.Y; LastX = x; LastY = y; } public static Bitmap GrabAroundCursor(int size) { POINT p; GetCursorPos(out p); LastX = p.X; LastY = p.Y; int half = size / 2; Bitmap bmp = new Bitmap(size, size); using (Graphics g = Graphics.FromImage(bmp)) { g.CopyFromScreen(p.X - half, p.Y - half, 0, 0, new Size(size, size)); } return bmp; } } "@ $root = Join-Path $env:APPDATA "RaidsTimer" New-Item -ItemType Directory -Force -Path $root | Out-Null try { Set-Content -Path (Join-Path $root "helper-alive.txt") -Value ((Get-Date).ToString("o") + " v" + $script:HelperVersion) -Encoding UTF8 } catch {} $cfgPath = Join-Path $root "pc-banner.json" $serverDefault = "https://savemypet-backend.onrender.com" $siteDefault = "https://raidstimer.me/raids-timer" function Get-LastCommanderPath { return (Join-Path $root "last-commander.json") } function Read-Cfg { $cfg = $null if (Test-Path $cfgPath) { try { $cfg = Get-Content $cfgPath -Raw | ConvertFrom-Json } catch { $cfg = $null } } $hasWho = $false try { if ($cfg -and ($cfg.code -or ($cfg.displayName -and [string]$cfg.displayName -ne "Commander"))) { $hasWho = $true } } catch {} if (-not $hasWho) { $lastPath = Get-LastCommanderPath if (Test-Path -LiteralPath $lastPath) { try { $last = Get-Content -LiteralPath $lastPath -Raw | ConvertFrom-Json if ($last -and ($last.code -or $last.displayName)) { $ht = @{} if ($cfg) { foreach ($p in $cfg.PSObject.Properties) { $ht[$p.Name] = $p.Value } } foreach ($p in $last.PSObject.Properties) { if (-not $ht.ContainsKey($p.Name) -or -not $ht[$p.Name]) { $ht[$p.Name] = $p.Value } } $ht | ConvertTo-Json | Set-Content -Path $cfgPath -Encoding UTF8 $cfg = Get-Content $cfgPath -Raw | ConvertFrom-Json } } catch {} } } return $cfg } function Save-Cfg($code, $server, $profile, $picked) { $row = @{} try { $old = Read-Cfg if ($old) { foreach ($p in $old.PSObject.Properties) { $row[$p.Name] = $p.Value } } } catch {} $row.code = $code $row.server = $server $row.picked = [bool]$picked if ($profile) { $row.displayName = [string]$profile.displayName $row.allianceName = [string]$profile.allianceName $row.serverNumber = [string]$profile.serverNumber $row.playerId = [string]$profile.playerId if ($profile.browser) { $row.browser = [string]$profile.browser } } try { $row.lang = Get-UiLang } catch {} $row | ConvertTo-Json | Set-Content -Path $cfgPath -Encoding UTF8 try { if ($row.code -or ($row.displayName -and [string]$row.displayName -ne "Commander")) { $row | ConvertTo-Json | Set-Content -LiteralPath (Get-LastCommanderPath) -Encoding UTF8 } } catch {} } function Normalize-HelperLang([string]$raw) { $s = ([string]$raw).Trim().ToLower().Replace("_", "-") if ($s.Length -lt 2) { return "en" } if ($s -match '^([a-z]{2})') { $s = $Matches[1] } if ($s.Length -gt 8) { $s = $s.Substring(0, 8) } return $s } function Get-UiLang { try { if ($script:farmBox -and $script:farmBox.uiLang) { return (Normalize-HelperLang ([string]$script:farmBox.uiLang)) } } catch {} try { $p = Join-Path $root "helper-lang.txt" if (Test-Path -LiteralPath $p) { return (Normalize-HelperLang (Get-Content -LiteralPath $p -Raw -ErrorAction SilentlyContinue)) } } catch {} try { if ($script:cfg -and $script:cfg.lang) { return (Normalize-HelperLang ([string]$script:cfg.lang)) } } catch {} try { return (Normalize-HelperLang ([cultureinfo]::CurrentUICulture.TwoLetterISOLanguageName)) } catch {} return "en" } function Set-HelperLang([string]$lang) { $n = Normalize-HelperLang $lang $script:uiLang = $n try { if ($script:farmBox) { $script:farmBox.uiLang = $n } } catch {} try { Set-Content -LiteralPath (Join-Path $root "helper-lang.txt") -Value $n -Encoding UTF8 } catch {} try { $c = Read-Cfg if ($c) { $ht = @{} foreach ($p in $c.PSObject.Properties) { $ht[$p.Name] = $p.Value } $ht.lang = $n ($ht | ConvertTo-Json) | Set-Content -Path $cfgPath -Encoding UTF8 $script:cfg = Read-Cfg } } catch {} return $n } function Translate-HelperText([string]$text, [string]$lang) { $tgt = Normalize-HelperLang $lang if (-not $text) { return $text } if ($tgt -eq "en") { return $text } try { $payload = @{ text = $text; lang = $tgt } | ConvertTo-Json -Compress $r = Invoke-RestMethod -Method POST -Uri "$(Get-ServerBase)/api/raids-helper/translate" -ContentType "application/json; charset=utf-8" -Body $payload -TimeoutSec 20 if ($r -and $r.text) { return [string]$r.text } if ($r -and $r.ok -eq $true -and $r.text -eq "") { return $text } } catch {} return $text } function Helper-T([string]$en) { $lang = Get-UiLang $src = [string]$en if (-not $src) { return $src } if ($lang -eq "en") { return $src } if (-not $script:helperT) { $script:helperT = @{} } $key = $lang + "`t" + $src if ($script:helperT.ContainsKey($key)) { return [string]$script:helperT[$key] } $out = Translate-HelperText $src $lang $script:helperT[$key] = $out return $out } function Apply-HelperToolLang { $lang = Get-UiLang try { if ($script:chatLangBox -and -not $script:chatLangBox.IsDisposed) { $script:chatFillingLang = $true if ($script:chatLangBox.Items.IndexOf($lang) -lt 0) { [void]$script:chatLangBox.Items.Insert(0, $lang) } try { $script:chatLangBox.SelectedItem = $lang } catch {} $script:chatFillingLang = $false } } catch {} try { if ($script:chatForm -and -not $script:chatForm.IsDisposed) { $script:chatForm.Text = Helper-T "Raids Timer Chat" } } catch {} try { if ($script:chatSend -and -not $script:chatSend.IsDisposed) { $script:chatSend.Text = Helper-T "Send" } } catch {} try { if ($script:chatStatus -and -not $script:chatStatus.IsDisposed) { $who = "Commander" $ally = "" if ($script:cfg -and $script:cfg.displayName) { $who = [string]$script:cfg.displayName } if ($script:cfg -and $script:cfg.allianceName) { $ally = [string]$script:cfg.allianceName } $line = (Helper-T "Chat unlocked") + " · " + $who if ($ally) { $line = "$line · $ally" } $line = "$line · lang $lang" $script:chatStatus.Text = $line } } catch {} try { if ($script:chatFarmBtn -and -not $script:chatFarmBtn.IsDisposed) { $script:chatFarmBtn.Text = Helper-T "Auto Farm" } if ($script:chatShareBtn -and -not $script:chatShareBtn.IsDisposed) { $script:chatShareBtn.Text = Helper-T "Share site" } } catch {} $u = $script:farmUi if ($u) { try { if ($u.form -and -not $u.form.IsDisposed) { $u.form.Text = (Helper-T "Auto Farm") + " " + [string]$script:HelperVersion } if ($u.rec) { $u.rec.Text = Helper-T "Record" } if ($u.stopRec) { $u.stopRec.Text = Helper-T "Stop record" } if ($u.play) { $u.play.Text = Helper-T "Play" } if ($u.stopPlay) { $u.stopPlay.Text = Helper-T "Stop play" } if ($u.how) { $u.how.Text = Helper-T "How to use" } if ($u.loop) { $u.loop.Text = Helper-T "Loop" } if ($u.delayLbl) { $u.delayLbl.Text = Helper-T "Click delay (ms)" } if ($u.keyDelayLbl) { $u.keyDelayLbl.Text = Helper-T "Key delay (ms)" } if ($u.qLbl) { $u.qLbl.Text = Helper-T "Play list rule: Play always starts at #1 and does each row once in this order. Only Loop repeats the list. Pictures stay saved and wait until found." } if ($u.playlistScreensLbl) { $u.playlistScreensLbl.Text = Helper-T "This list + pictures is for these screens. Tick, then Save for screens. Each screen can have different images." } if ($u.playlistSaveScreens) { $u.playlistSaveScreens.Text = Helper-T "Save for screens" } if ($u.playlistLoadScreen) { $u.playlistLoadScreen.Text = Helper-T "Load screen" } if ($u.instanceHelp) { $u.instanceHelp.Text = Helper-T "How to: tick screens next to the numbered play list, add that screen's pictures, Save for screens. Play screen farms that window's own list from #1. Run checked in order does one screen at a time. Split view tiles 2-4. Five or more (or more than this PC can run) opens one at a time. WARNING above names RAM/CPU/disk. Hide helper tucks this window; reopen Auto Farm from the tray." } if ($u.savesHow) { $u.savesHow.Text = Helper-T "Left: pick a day. Right: tick which saved farms run on that day." } if ($u.listHead) { $u.listHead.Text = Helper-T "Saved farms" } if ($u.listHow) { $u.listHow.Text = Helper-T "Tick = that day. Queue today fills the play list from this day. Add = one farm now." } if ($u.picHow) { $u.picHow.Text = Helper-T "Pictures: 1 Mag glass 2 drag around the exact visible image 3 Add to farm. Play waits until found, then clicks the middle. Save each screen's list separately." } if ($u.winHow) { $u.winHow.Text = Helper-T "BlueStacks: Launch it here, pick it and Use window, then Save size + location. Restore size + location puts it back in the same screen spot." } if ($u.launchBlue) { $u.launchBlue.Text = Helper-T "Launch BlueStacks" } if ($u.autoBlue) { $u.autoBlue.Text = Helper-T "When helper opens: launch BlueStacks + restore saved size/location" } if ($u.sizeNameLbl) { $u.sizeNameLbl.Text = Helper-T "Size label" } if ($u.saveSize) { $u.saveSize.Text = Helper-T "Save size + location" } if ($u.restoreSize) { $u.restoreSize.Text = Helper-T "Restore size + location" } if ($u.addQ) { $u.addQ.Text = Helper-T "Add" } if ($u.upQ) { $u.upQ.Text = Helper-T "Move up" } if ($u.downQ) { $u.downQ.Text = Helper-T "Move down" } if ($u.nameLbl) { $u.nameLbl.Text = Helper-T "Name" } if ($u.save) { $u.save.Text = Helper-T "Save" } if ($u.remQ) { $u.remQ.Text = Helper-T "Remove" } if ($u.addPicQ) { $u.addPicQ.Text = Helper-T "Add picture" } if ($u.load) { $u.load.Text = Helper-T "Load selected" } if ($u.close) { $u.close.Text = Helper-T "Close" } if ($u.chat) { $u.chat.Text = Helper-T "Chat" } if ($u.share) { $u.share.Text = Helper-T "Share site" } if ($u.pay) { $u.pay.Text = Helper-T "PayPal unlock" } if ($u.today) { $u.today.Text = Helper-T "Queue today" } if ($u.autoLoad) { $u.autoLoad.Text = Helper-T "Auto load" } if ($u.gameLbl) { $u.gameLbl.Text = Helper-T "Game" } if ($u.pick) { $u.pick.Text = Helper-T "Pick spot" } if ($u.mag) { $u.mag.Text = Helper-T "Mag glass" } if ($u.savePic) { $u.savePic.Text = Helper-T "Save picture" } if ($u.waitImg) { $u.waitImg.Text = Helper-T "Hit any picture" } if ($u.glassLbl) { $u.glassLbl.Text = Helper-T "Pictures" } if ($u.remGlass) { $u.remGlass.Text = Helper-T "Remove picture" } if ($u.addPicFarm) { $u.addPicFarm.Text = Helper-T "Add to farm" } if ($u.tabPics) { $u.tabPics.Text = Helper-T "Pictures" } if ($u.tabWin) { $u.tabWin.Text = Helper-T "Window" } if ($u.timesLbl) { $u.timesLbl.Text = Helper-T "Times" } if ($u.winRef) { $u.winRef.Text = Helper-T "Windows" } if ($u.winUse) { $u.winUse.Text = Helper-T "Use window" } try { Paint-FarmGameSetup } catch {} try { Paint-FarmSightLabel } catch {} if ($u.lead -and $script:cfg) { $who = [string]$script:cfg.displayName if (-not $who) { $who = "Commander" } $ally = [string]$script:cfg.allianceName $logged = (Helper-T "Logged in as") + " " + $who if ($ally) { $logged = $logged + " | " + (Helper-T "alliance") + " " + $ally } $u.lead.Text = "$logged`r`n" + (Helper-T "Record clicks and keys. Play repeats the play list. Click delay and Key delay default to 500 ms. Helper") + " " + [string]$script:HelperVersion + "`r`n" + (Format-ChatPaidLine) } } catch {} } $t = $script:toolsUi if ($t) { try { if ($t.form -and -not $t.form.IsDisposed) { $t.form.Text = Helper-T "Raids Timer helper" } if ($t.go) { $t.go.Text = Helper-T "Open" } if ($t.farmNow) { $t.farmNow.Text = Helper-T "Auto Farm" } if ($t.close) { $t.close.Text = Helper-T "Close" } if ($t.lead -and $script:cfg) { $who = [string]$script:cfg.displayName if (-not $who) { $who = "Commander" } $t.lead.Text = (Helper-T "Using") + " " + $who + ". " + (Helper-T "Auto Farm is the first tool:") } if ($t.list -and $t.list.Items.Count -ge 4) { $sel = $t.list.SelectedIndex $t.list.Items.Clear() [void]$t.list.Items.Add((Helper-T "Auto Farm")) [void]$t.list.Items.Add((Helper-T "Chat")) [void]$t.list.Items.Add((Helper-T "How to use Auto Farm")) [void]$t.list.Items.Add((Helper-T "Share website")) [void]$t.list.Items.Add((Helper-T "Change commander")) if ($sel -ge 0 -and $sel -lt $t.list.Items.Count) { $t.list.SelectedIndex = $sel } } } catch {} } } function Close-ClickedHelperForm { try { $f = $null try { $f = $this.FindForm() } catch {} if (-not $f) { try { $f = [System.Windows.Forms.Form]::ActiveForm } catch {} } if ($f -and -not $f.IsDisposed) { $f.Close() } } catch {} } function Find-RaidsProfiles { $roots = @( "$env:LOCALAPPDATA\Microsoft\Edge\User Data", "$env:LOCALAPPDATA\Google\Chrome\User Data" ) $found = @{} function Add-FoundProfile($code, $displayName, $allianceName, $serverNumber, $playerId, $stamp, $browser) { if (-not $code -or -not $displayName) { return } $prev = $found[$code] if ($prev -and $prev.stamp -gt $stamp) { return } $found[$code] = @{ code = $code displayName = $displayName allianceName = [string]$allianceName serverNumber = [string]$serverNumber playerId = [string]$playerId browser = [string]$browser stamp = $stamp } } $deadline = (Get-Date).AddSeconds(6) foreach ($root in $roots) { if ((Get-Date) -gt $deadline) { break } if (-not (Test-Path $root)) { continue } $profiles = @(Get-ChildItem $root -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq "Default" -or $_.Name -like "Profile*" }) foreach ($p in $profiles) { if ((Get-Date) -gt $deadline) { break } $ldb = Join-Path $p.FullName "Local Storage\leveldb" if (-not (Test-Path $ldb)) { continue } $files = @(Get-ChildItem $ldb -File -ErrorAction SilentlyContinue | Where-Object { $_.Extension -eq ".log" -or $_.Extension -eq ".ldb" } | Sort-Object LastWriteTime -Descending) $n = 0 foreach ($f in $files) { if ((Get-Date) -gt $deadline) { break } $n++ if ($n -gt 12) { break } if ($f.Length -gt 6MB) { continue } $text = "" try { $fs = New-Object System.IO.FileStream( $f.FullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite ) $reader = New-Object System.IO.StreamReader($fs, [System.Text.Encoding]::UTF8, $true) $text = $reader.ReadToEnd() $reader.Close() $fs.Close() } catch { continue } $idx = 0 while (($i = $text.IndexOf("raids-timer-local-v2", $idx)) -ge 0) { $take = [Math]::Min(12000, $text.Length - $i) $window = $text.Substring($i, $take) $uid = [regex]::Match($window, '"userId"\s*:\s*"([A-Za-z0-9_\-.:@]{3,120})"') $name = [regex]::Match($window, '"displayName"\s*:\s*"([^"\\]{1,80})"') $srv = [regex]::Match($window, '"serverNumber"\s*:\s*"([0-9]{1,12})"') $loose = [regex]::Match($window, 'ks_s([0-9]{1,12})_p([A-Za-z0-9_]{1,80})') $browser = "Chrome" if ($root -like "*\Edge\*") { $browser = "Edge" } if ($uid.Success -and $name.Success) { $ally = [regex]::Match($window, '"allianceName"\s*:\s*"([^"\\]{0,80})"') $player = [regex]::Match($window, '"playerId"\s*:\s*"([^"\\]{0,80})"') Add-FoundProfile $uid.Groups[1].Value $name.Groups[1].Value $(if ($ally.Success) { $ally.Groups[1].Value } else { "" }) $(if ($srv.Success) { $srv.Groups[1].Value } else { "" }) $(if ($player.Success) { $player.Groups[1].Value } else { "" }) $f.LastWriteTime $browser } foreach ($pair in [regex]::Matches($window, '"displayName"\s*:\s*"([^"\\]{1,80})"[\s\S]{0,400}"allianceName"\s*:\s*"([^"\\]{0,80})"')) { $dn = $pair.Groups[1].Value $al = $pair.Groups[2].Value $code2 = "name_" + ($dn -replace '[^A-Za-z0-9]', '_').ToLower() if ($srv.Success) { $code2 = "ks_s$($srv.Groups[1].Value)_p" + ($dn -replace '[^A-Za-z0-9]', '_').ToLower() } Add-FoundProfile $code2 $dn $al $(if ($srv.Success) { $srv.Groups[1].Value } else { "" }) $dn $f.LastWriteTime $browser } if ($loose.Success) { $code = "ks_s$($loose.Groups[1].Value)_p$($loose.Groups[2].Value)" Add-FoundProfile $code $loose.Groups[2].Value "" $loose.Groups[1].Value $loose.Groups[2].Value $f.LastWriteTime $browser } $idx = $i + 20 } } } } if ($script:cfg -and $script:cfg.code -and -not $found.ContainsKey([string]$script:cfg.code)) { $found[[string]$script:cfg.code] = @{ code = [string]$script:cfg.code displayName = [string]$script:cfg.displayName allianceName = [string]$script:cfg.allianceName serverNumber = [string]$script:cfg.serverNumber playerId = [string]$script:cfg.playerId browser = [string]$script:cfg.browser stamp = Get-Date } } return @($found.Values | Sort-Object displayName, serverNumber) } function Find-RaidsProfile { $all = @(Find-RaidsProfiles) if ($all.Count -lt 1) { return $null } return $all[0] } function Get-LoggedCommanderLine { $who = "Commander" $ally = "" if ($script:cfg -and $script:cfg.displayName) { $who = [string]$script:cfg.displayName } if ($script:cfg -and $script:cfg.allianceName) { $ally = [string]$script:cfg.allianceName } $logged = "Logged in as $who" if ($ally) { $logged = "Logged in as $who | alliance $ally" } return $logged } function Sync-SavedCommanderFromBrowser { if (-not $script:cfg -or -not $script:cfg.code) { return $false } $code = [string]$script:cfg.code $name = [string]$script:cfg.displayName $serverNum = [string]$script:cfg.serverNumber $hit = $null $byName = $null foreach ($p in @(Find-RaidsProfiles)) { if ([string]$p.code -eq $code) { $hit = $p; break } if (-not $byName -and $name -and [string]$p.displayName -eq $name -and (-not $serverNum -or [string]$p.serverNumber -eq $serverNum) -and [string]$p.allianceName) { $byName = $p } } if (-not $hit) { $hit = $byName } if (-not $hit) { return $false } $newAlly = [string]$hit.allianceName $oldAlly = [string]$script:cfg.allianceName if (-not $newAlly -or $newAlly -eq $oldAlly) { return $false } $server = $serverDefault try { if ($script:cfg.server) { $server = [string]$script:cfg.server } } catch {} Save-Cfg ([string]$hit.code) $server $hit $true $script:cfg = Read-Cfg try { if ($script:farmUi -and $script:farmUi.lead -and -not $script:farmUi.lead.IsDisposed) { $script:farmUi.lead.Text = (Get-LoggedCommanderLine) + "`r`nRecord clicks and keys. Play repeats the play list. Click delay and Key delay default to 500 ms. Helper " + [string]$script:HelperVersion + "`r`n" + (Format-ChatPaidLine) } } catch {} return $true } function Format-ProfileLine($profile) { $who = [string]$profile.displayName if ($profile.allianceName) { $who = "$who · $($profile.allianceName)" } if ($profile.serverNumber) { $who = "$who · server $($profile.serverNumber)" } if ($profile.browser) { $who = "$who · $($profile.browser)" } return $who } if ($ListProfiles) { $listed = @(Find-RaidsProfiles) foreach ($p in $listed) { Write-Output (Format-ProfileLine $p) } if ($listed.Count -lt 1) { exit 2 } exit 0 } $script:cfg = Read-Cfg try { Sync-SavedCommanderFromBrowser | Out-Null } catch {} if ($DetectOnly) { if ($script:cfg) { Write-Output ("code=" + $script:cfg.code) Write-Output ("displayName=" + $script:cfg.displayName) Write-Output ("allianceName=" + $script:cfg.allianceName) Write-Output ("serverNumber=" + $script:cfg.serverNumber) Write-Output ("playerId=" + $script:cfg.playerId) exit 0 } exit 2 } function Get-HelperSiteBases { @( "https://raidstimer.me/raids-timer", "https://www.raidstimer.me/raids-timer", "$serverDefault/raids-timer", $siteDefault ) | Select-Object -Unique } function Save-HelperUrl([string]$rel, [string]$dest, [int]$minLen) { if (-not $rel -or -not $dest) { return $false } try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 } catch {} foreach ($base in (Get-HelperSiteBases)) { try { $u = ($base.TrimEnd("/") + "/" + $rel.TrimStart("/")) Invoke-WebRequest -Uri $u -OutFile $dest -UseBasicParsing -TimeoutSec 12 if ((Test-Path -LiteralPath $dest) -and ((Get-Item -LiteralPath $dest).Length -ge $minLen)) { Clear-HelperMarkOfWeb $dest return $true } } catch {} } return $false } function Ensure-HelperInstallFiles { $png = Join-Path $root "icon-192.png" $needPng = $true if (Test-Path -LiteralPath $png) { try { if ((Get-Item -LiteralPath $png).Length -ge 500) { $needPng = $false } } catch {} } if ($needPng) { foreach ($name in @("icon-192.png", "RaidsTimer-icon-192.png")) { $beside = $null if ($PSScriptRoot) { $beside = Join-Path $PSScriptRoot $name } if ($beside -and (Test-Path -LiteralPath $beside)) { try { Copy-HelperFileClean $beside $png if ((Get-Item -LiteralPath $png).Length -ge 500) { $needPng = $false; break } } catch {} } } } if ($needPng) { [void](Save-HelperUrl "icon-192.png" $png 500) } $cmdDest = Join-Path $root "Start-Raids-Timer-Helper.cmd" $cmdBeside = $null if ($PSScriptRoot) { $cmdBeside = Join-Path $PSScriptRoot "pc-banner.cmd" } if ($cmdBeside -and (Test-Path -LiteralPath $cmdBeside)) { try { [void](Copy-HelperFileClean $cmdBeside $cmdDest) } catch {} } $needCmd = -not (Test-Path -LiteralPath $cmdDest) if (-not $needCmd) { try { if ((Get-Item -LiteralPath $cmdDest).Length -lt 200) { $needCmd = $true } } catch { $needCmd = $true } } if ($needCmd) { [void](Save-HelperUrl "pc-banner.cmd" $cmdDest 200) } $startBeside = $null if ($PSScriptRoot) { $startBeside = Join-Path $PSScriptRoot "pc-banner-start.ps1" } $startDest = Join-Path $root "pc-banner-start.ps1" if ($startBeside -and (Test-Path -LiteralPath $startBeside)) { try { [void](Copy-HelperFileClean $startBeside $startDest) } catch {} } } function Get-AppIcon { Ensure-HelperInstallFiles $png = Join-Path $root "icon-192.png" if (-not (Test-Path -LiteralPath $png) -or ((Get-Item -LiteralPath $png).Length -lt 500)) { return [System.Drawing.SystemIcons]::Application } try { $bmp = New-Object System.Drawing.Bitmap $png } catch { try { Remove-Item -LiteralPath $png -Force -ErrorAction SilentlyContinue } catch {} [void](Save-HelperUrl "icon-192.png" $png 500) try { $bmp = New-Object System.Drawing.Bitmap $png } catch { return [System.Drawing.SystemIcons]::Application } } $thumb = New-Object System.Drawing.Bitmap 32, 32 $g = [System.Drawing.Graphics]::FromImage($thumb) $g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic $g.DrawImage($bmp, 0, 0, 32, 32) $g.Dispose() $card = New-Object System.Drawing.Bitmap 48, 48 $cg = [System.Drawing.Graphics]::FromImage($card) $cg.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic $cg.DrawImage($bmp, 0, 0, 48, 48) $cg.Dispose() $bmp.Dispose() $script:appThumb = $thumb $script:cardBitmap = $card $icon = [System.Drawing.Icon]::FromHandle($thumb.GetHicon()) try { $icoPath = Join-Path $root "raids-timer.ico" $fs = [System.IO.File]::Create($icoPath) $icon.Save($fs) $fs.Close() $script:icoPath = $icoPath } catch { } return $icon } function Stop-OldPcHelpers { $me = [int]$PID try { Get-CimInstance Win32_Process -Filter "Name='powershell.exe' OR Name='pwsh.exe'" -ErrorAction SilentlyContinue | ForEach-Object { $cl = [string]$_.CommandLine if ($cl -notmatch 'pc-banner\.ps1') { return } if ([int]$_.ProcessId -eq $me) { return } try { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } catch {} } } catch {} } function Remove-OldHelperDownloads { $keep = New-Object System.Collections.Generic.List[string] try { if ($PSCommandPath) { [void]$keep.Add([IO.Path]::GetFullPath($PSCommandPath)) } } catch {} try { $installed = Join-Path $root "pc-banner.ps1" if (Test-Path $installed) { [void]$keep.Add([IO.Path]::GetFullPath($installed)) } } catch {} $dirs = @( (Join-Path $env:USERPROFILE "Downloads"), [Environment]::GetFolderPath("Desktop"), (Join-Path $env:USERPROFILE "Downloads") ) | Select-Object -Unique foreach ($dir in $dirs) { if (-not $dir -or -not (Test-Path -LiteralPath $dir)) { continue } Get-ChildItem -LiteralPath $dir -File -ErrorAction SilentlyContinue | Where-Object { $_.Name -match '(?i)^(pc-banner.*|RaidsTimer-helper.*)\.(ps1|cmd)$' } | ForEach-Object { $full = $_.FullName $skip = $false foreach ($k in $keep) { if ($k -and [string]::Equals($k, $full, [StringComparison]::OrdinalIgnoreCase)) { $skip = $true } } if (-not $skip) { try { Remove-Item -LiteralPath $full -Force -ErrorAction SilentlyContinue } catch {} } } } } function Read-HelperFileVersion([string]$path) { if (-not $path -or -not (Test-Path -LiteralPath $path)) { return "0.0.0" } try { $hit = Select-String -LiteralPath $path -Pattern 'HelperVersion\s*=\s*"([^"]+)"' | Select-Object -First 1 if ($hit) { return [string]$hit.Matches[0].Groups[1].Value } } catch {} return "0.0.0" } function Test-HelperFileParses([string]$path) { if (-not $path -or -not (Test-Path -LiteralPath $path)) { return $false } $tok = $null $err = $null try { [void][System.Management.Automation.Language.Parser]::ParseFile($path, [ref]$tok, [ref]$err) return (-not $err) -or (@($err).Count -eq 0) } catch { return $false } } function Test-HelperVersionAtLeast([string]$incoming, [string]$have) { try { return ([version]$incoming -ge [version]$have) } catch { return $true } } function Restart-HelperKeepingPresets { param([string]$FilePath) $dest = $FilePath if (-not $dest) { $dest = Join-Path $root "pc-banner.ps1" } if (-not (Test-Path -LiteralPath $dest)) { return } $exe = "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" try { Start-Process -FilePath $exe -ArgumentList @( "-NoProfile", "-STA", "-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden", "-File", $dest, "-OpenFarm", "-SkipWebUpdate" ) } catch {} try { if ($script:tray) { $script:tray.Visible = $false } } catch {} try { [System.Windows.Forms.Application]::Exit() } catch {} [Environment]::Exit(0) } function Show-HelperNotice([string]$text, [string]$title) { $icon = [System.Windows.Forms.MessageBoxIcon]::Information $buttons = [System.Windows.Forms.MessageBoxButtons]::OK $owner = $null try { if ($script:settingsForm -and -not $script:settingsForm.IsDisposed) { $owner = $script:settingsForm } } catch {} if ($owner) { try { $owner.Activate() } catch {} [void][System.Windows.Forms.MessageBox]::Show($owner, $text, $title, $buttons, $icon) } else { [void][System.Windows.Forms.MessageBox]::Show($text, $title, $buttons, $icon) } } function Install-HelperScript([string]$from) { if (-not $from -or -not (Test-Path -LiteralPath $from)) { return "" } $dest = Join-Path $root "pc-banner.ps1" if (Copy-HelperFileClean $from $dest) { try { Ensure-HelperInstallFiles } catch {} return $dest } $side = Join-Path $root "pc-banner-updated.ps1" if (Copy-HelperFileClean $from $side) { try { Ensure-HelperInstallFiles } catch {} return $side } return "" } function Update-HelperFromWebsite { if ($DetectOnly -or $ListProfiles -or $SkipWebUpdate) { return } $dest = Join-Path $root "pc-banner.ps1" $have = [version]"0.0.0" try { $have = [version](Read-HelperFileVersion $dest) } catch {} try { $me = [version]$script:HelperVersion if ($me -gt $have) { $have = $me } } catch {} try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 } catch {} $urls = @( "https://raidstimer.me/raids-timer/pc-banner.ps1", "https://www.raidstimer.me/raids-timer/pc-banner.ps1", "https://savemypet-backend.onrender.com/raids-timer/pc-banner.ps1" ) $tmp = Join-Path $root "pc-banner.fetch.ps1" foreach ($u in $urls) { try { Invoke-WebRequest -Uri $u -OutFile $tmp -UseBasicParsing -TimeoutSec 12 if (-not (Test-Path -LiteralPath $tmp)) { continue } if ((Get-Item -LiteralPath $tmp).Length -lt 4000) { continue } if (-not (Test-HelperFileParses $tmp)) { continue } $ver = [version](Read-HelperFileVersion $tmp) if ($ver -lt $have) { continue } Copy-HelperFileClean $tmp $dest try { Ensure-HelperInstallFiles } catch {} return } catch {} } } function Install-PcHelperOnThisPc { Stop-OldPcHelpers try { Ensure-HelperInstallFiles } catch {} $dest = Join-Path $root "pc-banner.ps1" try { $have = Read-HelperFileVersion $dest $incoming = [string]$script:HelperVersion $allowCopy = Test-HelperVersionAtLeast $incoming $have if ($allowCopy -and $PSCommandPath -and (Test-Path -LiteralPath $PSCommandPath)) { Copy-HelperFileClean $PSCommandPath $dest } } catch {} $ico = "" if ($script:icoPath -and (Test-Path -LiteralPath $script:icoPath)) { $ico = $script:icoPath } else { $tryIco = Join-Path $root "raids-timer.ico" if (Test-Path -LiteralPath $tryIco) { $ico = $tryIco } } $ps1 = $dest if (-not (Test-Path $ps1)) { $ps1 = $PSCommandPath } $argLine = "-NoProfile -STA -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$ps1`" -OpenFarm" $w = New-Object -ComObject WScript.Shell foreach ($dir in @( [Environment]::GetFolderPath("Desktop"), (Join-Path $env:APPDATA "Microsoft\Windows\Start Menu\Programs") )) { if (-not $dir) { continue } try { New-Item -ItemType Directory -Force -Path $dir | Out-Null $lnk = Join-Path $dir "Raids Timer Chat.lnk" $sc = $w.CreateShortcut($lnk) $sc.TargetPath = "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" $sc.Arguments = $argLine $sc.WorkingDirectory = $root $sc.WindowStyle = 7 $sc.Description = "Raids Timer Chat helper - icon next to the clock" if ($ico) { $sc.IconLocation = "$ico,0" } $sc.Save() } catch {} } Remove-OldHelperDownloads try { $ps1File = $ps1 $hk = "HKCU:\Software\Classes\raidstimerhelper" New-Item -Path $hk -Force | Out-Null Set-ItemProperty -Path $hk -Name "(default)" -Value "URL:Raids Timer Helper" New-ItemProperty -Path $hk -Name "URL Protocol" -Value "" -PropertyType String -Force | Out-Null $cmdKey = Join-Path $hk "shell\open\command" New-Item -Path $cmdKey -Force | Out-Null $exe = "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" Set-ItemProperty -Path $cmdKey -Name "(default)" -Value "`"$exe`" -NoProfile -STA -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$ps1File`" -OpenFarm" } catch {} } function Start-NewestHelperAlways { if ($DetectOnly -or $ListProfiles) { return } $dest = Join-Path $root "pc-banner.ps1" try { New-Item -ItemType Directory -Force -Path $root | Out-Null } catch {} $files = New-Object System.Collections.Generic.List[string] $add = { param($p) if (-not $p) { return } try { if (-not (Test-Path -LiteralPath $p)) { return } $full = [IO.Path]::GetFullPath($p) foreach ($x in $files) { if ([string]::Equals($x, $full, [StringComparison]::OrdinalIgnoreCase)) { return } } [void]$files.Add($full) } catch {} } & $add $PSCommandPath & $add $dest if ($PSScriptRoot) { & $add (Join-Path $PSScriptRoot "pc-banner.ps1") } foreach ($dir in @( (Join-Path $env:USERPROFILE "Downloads"), [Environment]::GetFolderPath("Desktop"), (Join-Path $env:USERPROFILE "Downloads") )) { if (-not $dir -or -not (Test-Path -LiteralPath $dir)) { continue } Get-ChildItem -LiteralPath $dir -File -ErrorAction SilentlyContinue | Where-Object { $_.Name -match '(?i)^(pc-banner.*|RaidsTimer-helper.*)\.ps1$' } | ForEach-Object { & $add $_.FullName } } $bestPath = $PSCommandPath $bestVer = $null try { $bestVer = [version]$script:HelperVersion } catch { $bestVer = [version]"0.0.0" } foreach ($f in $files) { $v = $null try { $v = [version](Read-HelperFileVersion $f) } catch { continue } if (-not (Test-HelperFileParses $f)) { continue } if ($v -gt $bestVer) { $bestVer = $v $bestPath = $f } } if (-not $bestPath -or -not (Test-Path -LiteralPath $bestPath)) { return } try { Copy-HelperFileClean $bestPath $dest } catch {} $me = $null try { $me = [version]$script:HelperVersion } catch { $me = [version]"0.0.0" } $cur = "" $destFull = "" try { if ($PSCommandPath) { $cur = [IO.Path]::GetFullPath($PSCommandPath) } } catch {} try { if (Test-Path -LiteralPath $dest) { $destFull = [IO.Path]::GetFullPath($dest) } } catch {} if (-not $destFull) { return } $needHop = $false if ($me -lt $bestVer) { $needHop = $true } elseif ($cur -and -not [string]::Equals($cur, $destFull, [StringComparison]::OrdinalIgnoreCase)) { $needHop = $true } if (-not $needHop) { return } $exe = "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" try { Start-Process -FilePath $exe -ArgumentList @("-NoProfile", "-STA", "-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden", "-File", $destFull, "-OpenFarm", "-SkipWebUpdate") } catch {} exit 0 } function Show-WindowsBlockHelp { $txt = @" Keep this helper open - Windows must not close it. The Raids Timer icon is next to the clock (bottom-right). Click the little up-arrow ^ if Windows hid it. Drag the icon onto the taskbar so it stays visible. If a black window flashed and closed, or nothing appeared: 1. Double-click pc-banner.cmd (Start helper). Do not only double-click the .ps1 (that can open Notepad or close instantly). 2. Right-click pc-banner.ps1 → Properties. If you see Unblock, tick it → Apply → OK. 3. If Windows says "Windows protected your PC": More info → Run anyway. 4. Then use the Desktop shortcut "Raids Timer Chat" (this helper installs it). Leave the tray icon running. Do not Exit unless you are updating. "@ [System.Windows.Forms.MessageBox]::Show( $txt, "If Windows blocked or closed the helper", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information ) | Out-Null } function Update-IdleTip { $name = "" if ($script:cfg -and $script:cfg.displayName) { $name = " · " + [string]$script:cfg.displayName } $farm = "" if ($script:farmHttpOn) { $farm = " · Farm" } $tip = "Raids Timer" + $name + $farm if ($tip.Length -gt 63) { $tip = $tip.Substring(0, 63) } $script:idleTip = $tip if ($script:tray -and $script:fireAt -le 0) { $script:tray.Text = $tip } } function Get-ServerBase { $base = "" if ($script:cfg -and $script:cfg.server) { $base = [string]$script:cfg.server } if (-not $base) { $base = $serverDefault } if ($base.EndsWith("/")) { $base = $base.Substring(0, $base.Length - 1) } return $base } function Use-HelperTls { try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 } catch {} try { [Net.ServicePointManager]::Expect100Continue = $false } catch {} } function Test-HelperNetGlitch([string]$msg) { return ([string]$msg -match '(?i)connection was closed|underlying connection|timed out|forcibly closed|connection reset|unable to connect|502|503|504|NameResolution|receive failure|send failure|existing connection') } function Invoke-HelperRest { param( [string]$Method = "GET", [string]$Uri, $Body = $null, [int]$TimeoutSec = 20, [int]$Tries = 3 ) Use-HelperTls $last = $null for ($i = 1; $i -le $Tries; $i++) { try { if ($Method -eq "POST") { return Invoke-RestMethod -Method POST -Uri $Uri -ContentType "application/json; charset=utf-8" -Body $Body -TimeoutSec $TimeoutSec -Headers @{ Connection = "close" } } return Invoke-RestMethod -Uri $Uri -TimeoutSec $TimeoutSec -Headers @{ Connection = "close" } } catch { $last = $_ $m = [string]$_.Exception.Message if ($i -ge $Tries -or -not (Test-HelperNetGlitch $m)) { throw } Start-Sleep -Milliseconds (400 * $i) } } throw $last } function Get-ChatIdentity { $uid = "" $player = "" $server = "" $name = "Commander" $ally = "" if ($script:cfg) { $uid = [string]$script:cfg.code $player = [string]$script:cfg.playerId $server = [string]$script:cfg.serverNumber if ($script:cfg.displayName) { $name = [string]$script:cfg.displayName } $ally = [string]$script:cfg.allianceName } if ($uid -match '^ks_s([^_]+)_p(.+)$') { if (-not $server) { $server = $Matches[1] } if (-not $player) { $player = $Matches[2] } } return @{ userId = $uid playerId = $player serverNumber = $server displayName = $name allianceName = $ally } } function Unwrap-Trpc($res) { if (-not $res) { return $null } if ($res.result -and $res.result.data -and $res.result.data.json) { return $res.result.data.json } if ($res.result -and $res.result.data) { return $res.result.data } return $null } function Invoke-TrpcGet($path, $inputObj) { $payload = @{ json = $inputObj } | ConvertTo-Json -Compress -Depth 6 $url = "$(Get-ServerBase)/api/trpc/${path}?input=" + [uri]::EscapeDataString($payload) return Invoke-RestMethod -Uri $url -TimeoutSec 20 } function Invoke-TrpcPost($path, $inputObj) { $body = @{ json = $inputObj } | ConvertTo-Json -Compress -Depth 6 return Invoke-RestMethod -Uri "$(Get-ServerBase)/api/trpc/$path" -Method POST -ContentType "application/json; charset=utf-8" -Body $body -TimeoutSec 20 } function Get-HelperPlayerKey { $id = Get-ChatIdentity $p = [string]$id.playerId if (-not $p) { $p = [string]$id.displayName } return $p.Trim() } function Test-HelperOrderProfile { $id = Get-ChatIdentity return ([string]$id.displayName).Trim() -and ([string]$id.allianceName).Trim() -and ([string]$id.serverNumber).Trim() } function Parse-MarchSec([string]$raw) { $s = [string]$raw if ($s -match '^\s*(\d+)\s*:\s*(\d+)\s*:\s*(\d+)\s*$') { return (([int]$Matches[1] * 3600) + ([int]$Matches[2] * 60) + [int]$Matches[3]) } if ($s -match '^\s*(\d+)\s*:\s*(\d+)\s*$') { return (([int]$Matches[1] * 60) + [int]$Matches[2]) } $n = 0 if ([int]::TryParse($s.Trim(), [ref]$n)) { return [Math]::Max(0, $n) } return 0 } function Patch-HelperCfg($fields) { try { $row = @{} $old = Read-Cfg if ($old) { foreach ($p in $old.PSObject.Properties) { $row[$p.Name] = $p.Value } } foreach ($k in @($fields.Keys)) { $row[$k] = $fields[$k] } $row | ConvertTo-Json | Set-Content -Path $cfgPath -Encoding UTF8 $script:cfg = Read-Cfg } catch {} } function Get-HelperMarchSec { $n = 0 try { $n = [int]$script:cfg.marchSec } catch { $n = 0 } return [Math]::Max(0, $n) } function Next-OrderFireFromSchedules($schedules, $myId, $marchSec) { $now = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() $best = 0 $bestKind = "land" $bestTitle = "" $bestWho = "" foreach ($s in @($schedules)) { if (-not $s) { continue } $st = [string]$s.status if ($st -and $st -match '(?i)cancel|complete') { continue } $land = 0 try { $land = [int64]$s.landAtUtcMs } catch { $land = 0 } $send = 0 try { $send = [int64]$s.sendAtUtcMs } catch { $send = 0 } if ($land -le 0) { $land = $send } $myMarch = [int]$marchSec foreach ($t in @($s.teams)) { foreach ($row in @($t.picks) + @($t.assignments)) { if (-not $row) { continue } $uid = [string]$row.userId if ($myId -and $uid -and [string]::Equals($uid, $myId, [StringComparison]::OrdinalIgnoreCase)) { try { $m = [int]$row.marchDurationSec if ($m -gt 0) { $myMarch = $m } } catch {} } } } $fire = $land $kind = "land" if ($myMarch -gt 0 -and $land -gt 0) { $fire = $land - ([int64]$myMarch * 1000) $kind = "send" } elseif ($send -gt 0 -and $land -gt 0 -and $send -lt $land) { $fire = $send $kind = "send" } if ($fire -le 0) { continue } if (($now - $fire) -gt 20000) { continue } if ($best -eq 0 -or $fire -lt $best) { $best = $fire $bestKind = $kind $bestTitle = [string]$s.title $bestWho = [string]$s.publishedByName } } return @{ fireAt = $best; kind = $bestKind; title = $bestTitle; who = $bestWho } } function Refresh-AllianceOrderClock { if (-not (Test-HelperOrderProfile)) { $script:orderFireAt = 0 $script:orderKind = "land" $script:orderBody = "" return } $id = Get-ChatIdentity $player = Get-HelperPlayerKey $input = @{ playerId = $player serverNumber = [string]$id.serverNumber allianceName = [string]$id.allianceName } $data = $null try { $data = Unwrap-Trpc (Invoke-TrpcGet "raids.listAllianceSends" $input) } catch { $data = $null } if (-not $data -or $data.success -ne $true) { try { $syncIn = @{ playerId = $player serverNumber = [string]$id.serverNumber allianceName = [string]$id.allianceName displayName = [string]$id.displayName } $data = Unwrap-Trpc (Invoke-TrpcPost "raids.syncAllianceSpace" $syncIn) } catch { $data = $null } } $schedules = @() if ($data -and $data.schedules) { $schedules = @($data.schedules) } try { $recvIn = @{ playerId = $player serverNumber = [string]$id.serverNumber allianceName = [string]$id.allianceName displayName = [string]$id.displayName } $recv = Unwrap-Trpc (Invoke-TrpcGet "raids.listReceivedOrders" $recvIn) if ($recv -and $recv.orders) { foreach ($o in @($recv.orders)) { if (-not $o) { continue } $schedules += [pscustomobject]@{ title = [string]$o.title landAtUtcMs = $o.landAtUtcMs sendAtUtcMs = $o.sendAtUtcMs publishedByName = [string]$o.senderName status = [string]$o.scheduleStatus teams = @() } } } } catch {} $hit = Next-OrderFireFromSchedules $schedules ([string]$id.userId) (Get-HelperMarchSec) $script:orderFireAt = [int64]$hit.fireAt $script:orderKind = [string]$hit.kind if (-not $script:orderKind) { $script:orderKind = "land" } $who = [string]$hit.who $ttl = [string]$hit.title if (-not $ttl) { $ttl = "Rally" } if ($who) { $script:orderBody = $who + " · " + $ttl } else { $script:orderBody = $ttl } } function Publish-HelperAllianceOrder([string]$title, [int]$landMin, [int]$marchSec) { if (-not (Test-HelperOrderProfile)) { throw "Set in-game name, alliance, and server first (same as the website)." } if ($landMin -lt 1) { $landMin = 1 } if ($landMin -gt 180) { $landMin = 180 } $id = Get-ChatIdentity $player = Get-HelperPlayerKey $now = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() $landMs = $now + ([int64]$landMin * 60000) $sendMs = $landMs if ($marchSec -gt 0) { $sendMs = $landMs - ([int64]$marchSec * 1000) } $ttl = [string]$title if (-not $ttl) { $ttl = "Rally" } $uid = [string]$id.userId if (-not $uid) { $uid = "ks_s" + [string]$id.serverNumber + "_p" + $player } $teams = @() if ($marchSec -gt 0) { $teams = @( @{ teamName = "Team 1" sendAtUtcMs = $sendMs kind = "rally" landAtUtcMs = $landMs assignments = @( @{ userId = $uid displayName = [string]$id.displayName playerId = $player marchDurationSec = $marchSec } ) } ) } $payload = @{ playerId = $player serverNumber = [string]$id.serverNumber allianceName = [string]$id.allianceName displayName = [string]$id.displayName title = $ttl.Trim().Substring(0, [Math]::Min(120, $ttl.Trim().Length)) notes = "From PC helper banner" sendAtUtcMs = $sendMs landAtUtcMs = $landMs teams = $teams inviteUserIds = @() confirmSender = $true } $res = Unwrap-Trpc (Invoke-TrpcPost "raids.publishAllianceSend" $payload) if (-not $res -or $res.success -ne $true) { $err = "Could not share the order." try { if ($res.error) { $err = [string]$res.error } } catch {} throw $err } Patch-HelperCfg @{ marchSec = $marchSec } $script:orderFireAt = $sendMs if ($marchSec -gt 0) { $script:orderKind = "send" } else { $script:orderKind = "land" } $script:orderBody = [string]$id.displayName + " · " + $ttl return $true } function Show-SendOrderDialog { $id = Get-ChatIdentity $dlg = New-Object System.Windows.Forms.Form $dlg.Text = Helper-T "Send order" $dlg.FormBorderStyle = "FixedDialog" $dlg.StartPosition = "CenterScreen" $dlg.Size = New-Object System.Drawing.Size(420, 360) $dlg.MaximizeBox = $false $dlg.MinimizeBox = $false $dlg.TopMost = $true $y = 12 $addLbl = { param($text) $l = New-Object System.Windows.Forms.Label $l.Text = Helper-T $text $l.Location = New-Object System.Drawing.Point(16, $script:soY) $l.Size = New-Object System.Drawing.Size(370, 18) $dlg.Controls.Add($l) $script:soY += 20 } $script:soY = $y & $addLbl "Same alliance board as the website. Chat plan not required." $script:soY += 4 & $addLbl "In-game name" $script:soNameBox = New-Object System.Windows.Forms.TextBox $script:soNameBox.Location = New-Object System.Drawing.Point(16, $script:soY) $script:soNameBox.Size = New-Object System.Drawing.Size(370, 24) $script:soNameBox.Text = [string]$id.displayName $dlg.Controls.Add($script:soNameBox) $script:soY += 28 & $addLbl "Alliance" $script:soAllyBox = New-Object System.Windows.Forms.TextBox $script:soAllyBox.Location = New-Object System.Drawing.Point(16, $script:soY) $script:soAllyBox.Size = New-Object System.Drawing.Size(370, 24) $script:soAllyBox.Text = [string]$id.allianceName $dlg.Controls.Add($script:soAllyBox) $script:soY += 28 & $addLbl "Server number" $script:soSrvBox = New-Object System.Windows.Forms.TextBox $script:soSrvBox.Location = New-Object System.Drawing.Point(16, $script:soY) $script:soSrvBox.Size = New-Object System.Drawing.Size(370, 24) $script:soSrvBox.Text = [string]$id.serverNumber $dlg.Controls.Add($script:soSrvBox) $script:soY += 28 & $addLbl "Title" $script:soTitleBox = New-Object System.Windows.Forms.TextBox $script:soTitleBox.Location = New-Object System.Drawing.Point(16, $script:soY) $script:soTitleBox.Size = New-Object System.Drawing.Size(370, 24) $script:soTitleBox.Text = "Rally" $dlg.Controls.Add($script:soTitleBox) $script:soY += 28 & $addLbl "Land in minutes (UTC landing clock)" $script:soMinBox = New-Object System.Windows.Forms.TextBox $script:soMinBox.Location = New-Object System.Drawing.Point(16, $script:soY) $script:soMinBox.Size = New-Object System.Drawing.Size(120, 24) $script:soMinBox.Text = "5" $dlg.Controls.Add($script:soMinBox) $script:soY += 28 & $addLbl "Your march (sec or m:ss) - optional, for SEND countdown" $script:soMarchBox = New-Object System.Windows.Forms.TextBox $script:soMarchBox.Location = New-Object System.Drawing.Point(16, $script:soY) $script:soMarchBox.Size = New-Object System.Drawing.Size(120, 24) $ms = Get-HelperMarchSec if ($ms -gt 0) { $script:soMarchBox.Text = [string]$ms } else { $script:soMarchBox.Text = "" } $dlg.Controls.Add($script:soMarchBox) $script:soY += 36 $script:soDlg = $dlg $ok = New-Object System.Windows.Forms.Button $ok.Text = Helper-T "Lock and share" $ok.Location = New-Object System.Drawing.Point(16, $script:soY) $ok.Size = New-Object System.Drawing.Size(180, 32) $cancel = New-Object System.Windows.Forms.Button $cancel.Text = Helper-T "Cancel" $cancel.Location = New-Object System.Drawing.Point(206, $script:soY) $cancel.Size = New-Object System.Drawing.Size(180, 32) $ok.Add_Click({ try { Patch-HelperCfg @{ displayName = $script:soNameBox.Text.Trim() allianceName = $script:soAllyBox.Text.Trim() serverNumber = $script:soSrvBox.Text.Trim() } $mins = 5 [void][int]::TryParse($script:soMinBox.Text.Trim(), [ref]$mins) $march = Parse-MarchSec $script:soMarchBox.Text [void](Publish-HelperAllianceOrder $script:soTitleBox.Text $mins $march) try { Paint-Clock } catch {} $script:soDlg.Close() Show-Card "Order" (Helper-T "Shared") (Helper-T "Alliance can see this land time.") ([System.Drawing.Color]::FromArgb(22, 48, 28)) } catch { [void][System.Windows.Forms.MessageBox]::Show( [string]$_, (Helper-T "Send order"), [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Warning ) } }) $cancel.Add_Click({ $script:soDlg.Close() }) $dlg.Controls.Add($ok) $dlg.Controls.Add($cancel) [void]$dlg.ShowDialog() $dlg.Dispose() } function ChatSub-IsPaid($sub) { if (-not $sub) { return $false } $now = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() $exp = 0 try { $exp = [int64]$sub.expiresAt } catch { $exp = 0 } $flag = $false try { $raw = $sub.active if ($raw -eq $true -or $raw -eq 1) { $flag = $true } elseif ([string]$raw -match '^(?i)true|1|yes$') { $flag = $true } } catch {} if ($exp -gt 0 -and $exp -le ($now - 120000)) { return $false } if ($flag) { return $true } if ($exp -gt $now) { return $true } return $false } function Test-HasCommander { if (-not $script:cfg) { return $false } if ($script:cfg.code) { return $true } $name = [string]$script:cfg.displayName return ($name -and $name -ne "Commander") } function Get-ChatSubscription { $id = Get-ChatIdentity if (-not (Test-HasCommander)) { $script:chatPayState = "unknown" return $null } if (-not $id.userId -and -not $id.displayName) { return $null } $ids = New-Object System.Collections.Generic.List[string] try { foreach ($x in @(Get-BannerPollIds)) { if ($x) { [void]$ids.Add([string]$x) } } } catch {} if ($id.userId -and -not $ids.Contains([string]$id.userId)) { [void]$ids.Insert(0, [string]$id.userId) } if ($ids.Count -lt 1 -and $id.displayName) { [void]$ids.Add("") } $best = $null $script:farmLeaseUserId = "" $script:chatPayState = "unknown" $answered = $false foreach ($uid in $ids) { $q = "userId=" + [uri]::EscapeDataString([string]$uid) $q += "&displayName=" + [uri]::EscapeDataString([string]$id.displayName) $q += "&allianceName=" + [uri]::EscapeDataString([string]$id.allianceName) $url = "$(Get-ServerBase)/api/raids-chat/paypal/status?$q" try { $sub = Invoke-HelperRest -Uri $url -TimeoutSec 12 -Tries 2 } catch { continue } if (-not $sub) { continue } $answered = $true if (-not $best) { $best = $sub } if (ChatSub-IsPaid $sub) { $best = $sub $script:chatPayState = "paid" $script:farmLeaseUserId = [string]$uid Remember-ChatPaid $sub try { if ($script:farmBox) { $script:farmBox.chatPaid = $true } } catch {} break } } if ($script:chatPayState -ne "paid") { if (Test-RememberedChatPaid) { $script:chatPayState = "paid" } elseif ($answered) { $script:chatPayState = "unpaid" } else { $script:chatPayState = "unknown" } } if ($best -and $best.farmTicket) { $script:farmTicket = [string]$best.farmTicket try { $script:chatPaidUntil = [int64]$best.expiresAt } catch { $script:chatPaidUntil = 0 } try { $script:chatLastPaid = [int64]$best.lastPaidAt } catch { $script:chatLastPaid = 0 } $script:chatPaidSource = [string]$best.source } return $best } function Get-HelperSha256 { if ($script:helperShaCached) { return [string]$script:helperShaCached } try { if (-not $PSCommandPath -or -not (Test-Path -LiteralPath $PSCommandPath)) { return "" } $script:helperShaCached = (Get-FileHash -LiteralPath $PSCommandPath -Algorithm SHA256).Hash.ToLower() return [string]$script:helperShaCached } catch { return "" } } function Format-MsLocal([int64]$ms) { if ($ms -le 0) { return "" } try { return [DateTimeOffset]::FromUnixTimeMilliseconds($ms).ToLocalTime().ToString("yyyy-MM-dd HH:mm") } catch { return "" } } function Format-ChatPaidLine { if (-not $script:chatPaidUntil) { try { Get-ChatSubscription | Out-Null } catch {} } $until = Format-MsLocal ([int64]$script:chatPaidUntil) $last = Format-MsLocal ([int64]$script:chatLastPaid) $src = [string]$script:chatPaidSource $name = "PayPal Chat" if ($src -match 'apple|storekit') { $name = "Apple Chat" } if (-not $until) { return "Chat not unlocked. PayPal Chat or Apple Chat (same name and alliance) is required." } $line = "$name active until $until" if ($last) { $line = "$line. Last known payment $last" } return $line } function Format-ChatLog($messages) { $lines = New-Object System.Collections.Generic.List[string] foreach ($m in @($messages)) { if (-not $m) { continue } $when = "" try { $ms = [int64]$m.createdAt if ($ms -gt 0) { $when = [DateTimeOffset]::FromUnixTimeMilliseconds($ms).ToLocalTime().ToString("HH:mm") + " " } } catch { } $who = [string]$m.senderName if (-not $who) { $who = "Commander" } $text = ([string]$m.messageText) -replace "`r", "" -replace "`n", " " if ($text.Length -gt 500) { $text = $text.Substring(0, 500) } $lines.Add("$when$who`: $text") } return ($lines -join "`r`n") } function Join-ChatRooms { $id = Get-ChatIdentity if (-not $id.playerId -or -not $id.serverNumber) { return $null } $raw = Invoke-TrpcPost "raids.joinServerChat" @{ playerId = $id.playerId serverNumber = $id.serverNumber displayName = $id.displayName allianceName = $id.allianceName gameId = "kingshot" } return Unwrap-Trpc $raw } function Update-ChatLog { if ($script:chatBusy) { return } if (-not $script:chatForm -or $script:chatForm.IsDisposed) { return } if (-not $script:chatRoomId) { return } $script:chatBusy = $true try { $id = Get-ChatIdentity $raw = Invoke-TrpcGet "raids.getChat" @{ userId = $id.userId conversationId = $script:chatRoomId preferredLang = (Get-UiLang) autoTranslate = $true } $data = Unwrap-Trpc $raw if ($data -and $data.success -eq $false) { Join-ChatRooms | Out-Null $raw = Invoke-TrpcGet "raids.getChat" @{ userId = $id.userId conversationId = $script:chatRoomId preferredLang = (Get-UiLang) autoTranslate = $true } $data = Unwrap-Trpc $raw } $msgs = @() if ($data -and $data.messages) { $msgs = @($data.messages) } $text = Format-ChatLog $msgs if ($script:chatLog -and $script:chatLog.Text -ne $text) { $box = $script:chatLog $stick = $script:chatStick -or ($box.SelectionStart -ge [Math]::Max(0, $box.TextLength - 2)) $box.Text = $text if ($stick) { $box.SelectionStart = $box.TextLength $box.ScrollToCaret() } $script:chatStick = $false } } catch { if ($script:chatStatus) { $script:chatStatus.Text = "Could not load messages. Still checking." } } finally { $script:chatBusy = $false } } function Send-ChatText { $text = "" if ($script:chatInput) { $text = $script:chatInput.Text.Trim() } if (-not $text -or -not $script:chatRoomId) { return } try { $sub = Get-ChatSubscription if (-not (ChatSub-IsPaid $sub)) { if ($script:chatStatus) { $script:chatStatus.Text = "Chat is locked. This commander needs an active subscription." } if ($script:chatInput) { $script:chatInput.Enabled = $false } if ($script:chatSend) { $script:chatSend.Enabled = $false } return } } catch { if ($script:chatStatus) { $script:chatStatus.Text = "Could not check the subscription." } return } $id = Get-ChatIdentity if ($script:chatInput) { $script:chatInput.Text = "" } $script:chatStick = $true try { $raw = Invoke-TrpcPost "raids.sendChat" @{ userId = $id.userId displayName = $id.displayName phone = "" conversationId = $script:chatRoomId messageText = $text sourceLang = (Get-UiLang) serverNumber = $id.serverNumber allianceName = $id.allianceName avatarUrl = "" } $sent = Unwrap-Trpc $raw if ($sent -and $sent.success -eq $false -and $script:chatStatus) { $err = [string]$sent.error if (-not $err) { $err = "Message was not sent." } $script:chatStatus.Text = $err } } catch { if ($script:chatStatus) { $script:chatStatus.Text = "Message was not sent." } } Update-ChatLog } function Test-RememberedChatPaid { $until = 0 try { if ($script:cfg) { $until = [int64]$script:cfg.chatPaidUntil } } catch { $until = 0 } if ($until -le 0) { try { $until = [int64]$script:chatPaidUntil } catch { $until = 0 } } if ($until -le 0) { return $false } $now = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() return ($until -gt ($now + 60000)) } function Remember-ChatPaid($sub) { if (-not $sub) { return } $until = 0 try { $until = [int64]$sub.expiresAt } catch { return } if ($until -le 0) { return } $script:chatPaidUntil = $until try { $script:chatPaidSource = [string]$sub.source } catch {} try { $c = Read-Cfg if (-not $c) { return } $ht = @{} foreach ($p in $c.PSObject.Properties) { $ht[$p.Name] = $p.Value } $ht.chatPaidUntil = $until $ht.chatPaidSource = [string]$sub.source ($ht | ConvertTo-Json) | Set-Content -Path $cfgPath -Encoding UTF8 $script:cfg = Read-Cfg } catch {} } function Apply-BackendChatPaid($sub) { if (-not $sub) { return $false } $on = $false try { if ($sub.active -eq $true -or (ChatSub-IsPaid $sub)) { $on = $true } } catch { $on = $false } if (-not $on) { return $false } $script:chatPayState = "paid" try { if ($sub.farmTicket) { $script:farmTicket = [string]$sub.farmTicket } } catch {} try { $script:chatPaidUntil = [int64]$sub.expiresAt } catch {} try { $script:chatLastPaid = [int64]$sub.lastPaidAt } catch {} try { if ($sub.source) { $script:chatPaidSource = [string]$sub.source } } catch {} Remember-ChatPaid $sub try { if ($script:farmBox) { $script:farmBox.chatPaid = $true } } catch {} return $true } function Accept-SiteChatPaid { $b = $script:farmBox if (-not $b) { return $false } $dirty = $false try { $dirty = [bool]$b.chatPaidDirty } catch { $dirty = $false } if (-not $dirty) { return $false } $b.chatPaidDirty = $false $on = $false try { $on = [bool]$b.chatPaidPush } catch { $on = $false } if (-not $on) { return $false } $script:chatPayState = "paid" try { if ($b.farmTicketPush) { $script:farmTicket = [string]$b.farmTicketPush } } catch {} try { if ($b.chatPaidUntilPush) { $script:chatPaidUntil = [int64]$b.chatPaidUntilPush } } catch {} try { if ($b.chatPaidSourcePush) { $script:chatPaidSource = [string]$b.chatPaidSourcePush } } catch {} $b.chatPaid = $true try { Remember-ChatPaid ([pscustomobject]@{ expiresAt = $script:chatPaidUntil; source = $script:chatPaidSource }) } catch {} return $true } function Sync-ChatPaidFromBackend { try { if (Accept-SiteChatPaid) { return $true } } catch {} $sub = $null try { $sub = Get-ChatSubscription } catch { $sub = $null } if (Apply-BackendChatPaid $sub) { return $true } if (Test-RememberedChatPaid) { $script:chatPayState = "paid" try { if ($script:farmBox) { $script:farmBox.chatPaid = $true } } catch {} return $true } return $false } function Test-ChatPaid { try { if (Accept-SiteChatPaid) { return $true } } catch {} if ($script:chatPayState -eq "paid" -and (Test-RememberedChatPaid -or $script:farmTicket)) { try { if ($script:farmBox) { $script:farmBox.chatPaid = $true } } catch {} return $true } if (Test-RememberedChatPaid) { $script:chatPayState = "paid" try { if ($script:farmBox) { $script:farmBox.chatPaid = $true } } catch {} return $true } return (Sync-ChatPaidFromBackend) } function Test-ChatNeedsPayPalPrompt { return ($script:chatPayState -eq "unpaid") } function Open-PayPalUnlock { try { $id = Get-ChatIdentity $payload = @{ userId = [string]$id.userId displayName = [string]$id.displayName allianceName = [string]$id.allianceName returnUrl = "https://raidstimer.me/raids-timer/?paypal=return" cancelUrl = "https://raidstimer.me/raids-timer/?paypal=cancel" } | ConvertTo-Json -Compress $r = Invoke-RestMethod -Method POST -Uri "$(Get-ServerBase)/api/raids-chat/paypal/start" -ContentType "application/json; charset=utf-8" -Body $payload -TimeoutSec 12 if ($r -and $r.approveUrl) { Open-HelperUrl ([string]$r.approveUrl) return } } catch {} } function Show-PayPalUnlockPrompt { $who = "this commander" try { if ($script:cfg -and $script:cfg.displayName) { $who = [string]$script:cfg.displayName } } catch {} $txt = "Chat and Auto Farm stay locked until $who has an active Chat plan.`r`n`r`nIf you already paid with Apple Chat on iPhone, open Raids Timer on that phone, use the same in-game name (and alliance if you set one), then tap Restore Chat. This helper reads Apple Chat from the server. You do not need to pay PayPal again.`r`n`r`nPayPal Chat (`$1.00 for 31 days) is only if you did not pay on Apple.`r`n`r`nOpen PayPal now?" $ans = [System.Windows.Forms.MessageBox]::Show( $txt, "PayPal · unlock Auto Farm", [System.Windows.Forms.MessageBoxButtons]::YesNo, [System.Windows.Forms.MessageBoxIcon]::Information ) if ($ans -eq [System.Windows.Forms.DialogResult]::Yes) { Open-PayPalUnlock } } function Show-NoChatSub { Show-PayPalUnlockPrompt } function Check-PcHelperUpdate { param([switch]$Manual) if (-not $Manual -and ($DetectOnly -or $ListProfiles -or $SkipWebUpdate)) { return } try { if (-not $Manual -and $script:farmBox -and $script:farmBox.playing) { return } } catch {} try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 } catch {} $me = $null try { $me = [version]$script:HelperVersion } catch { $me = [version]"0.0.0" } $listed = "" $urls = @( "https://raidstimer.me/raids-timer/downloads/versions.json", "https://www.raidstimer.me/raids-timer/downloads/versions.json", "https://raids-timer.onrender.com/downloads/versions.json", "https://savemypet-backend.onrender.com/raids-timer/downloads/versions.json" ) foreach ($u in $urls) { try { $man = Invoke-RestMethod -Uri $u -TimeoutSec 12 if (-not $man -or -not $man.tools) { continue } $tool = @($man.tools | Where-Object { [string]$_.id -eq "pc-helper" }) | Select-Object -First 1 if ($tool -and $tool.latest) { $listed = [string]$tool.latest; break } } catch {} } $psUrls = @( "https://raidstimer.me/raids-timer/pc-banner.ps1", "https://www.raidstimer.me/raids-timer/pc-banner.ps1", "https://savemypet-backend.onrender.com/raids-timer/pc-banner.ps1" ) $tmp = Join-Path $root "pc-banner.fetch.ps1" $best = Join-Path $root "pc-banner.fetch-best.ps1" $bestVer = $me $sawFile = $false foreach ($u in $psUrls) { try { Invoke-WebRequest -Uri $u -OutFile $tmp -UseBasicParsing -TimeoutSec 20 if (-not (Test-Path -LiteralPath $tmp)) { continue } if ((Get-Item -LiteralPath $tmp).Length -lt 4000) { continue } if (-not (Test-HelperFileParses $tmp)) { continue } $sawFile = $true $ver = [version](Read-HelperFileVersion $tmp) if ($ver -gt $bestVer) { $bestVer = $ver Copy-HelperFileClean $tmp $best | Out-Null } } catch {} } if (-not $sawFile) { if ($Manual) { Show-HelperNotice "Could not reach the site to check. Try again in a minute." "Helper update" } return } if ($bestVer -le $me -or -not (Test-Path -LiteralPath $best)) { if ($Manual) { $msg = "This helper is current: " + [string]$script:HelperVersion + ". Farm saves stay." if ($listed) { try { if (([version]$listed) -gt $me) { $msg = "The site list says " + $listed + ", but the helper file there is still " + [string]$bestVer + ". Try again after the site finishes updating. Farm saves stay." } } catch {} } Show-HelperNotice $msg "Helper update" } return } $installed = Install-HelperScript $best if (-not $installed) { if ($Manual) { Show-HelperNotice ("A newer helper is on the site (" + [string]$bestVer + "). This copy could not save it. Close the helper, then open raidstimer.me and download the Windows helper.") "Helper update" } return } $latest = [string]$bestVer try { Set-FarmStatus ("Updated helper to " + $latest + ". Your farm saves stay. Restarting.") } catch {} try { if ($script:tray) { $script:tray.BalloonTipTitle = "Raids Timer helper updated" $script:tray.BalloonTipText = "Now $latest. Farm saves, commander, and pictures were not erased." $script:tray.ShowBalloonTip(8000) } } catch {} if ($Manual) { Show-HelperNotice ("Updated to " + $latest + ". Farm saves, commander, and pictures stay. The helper will restart.") "Helper update" } Start-Sleep -Milliseconds 400 Restart-HelperKeepingPresets $installed } function Test-FarmUnlocked { if (-not $script:cfg) { return $false } $hasWho = [string]$script:cfg.displayName if (-not $script:cfg.code -and -not $hasWho) { return $false } try { $sub = Get-ChatSubscription return (ChatSub-IsPaid $sub) } catch { return $false } } function Get-FarmMacroPath { return (Join-Path $root "farm-macros.json") } function Read-FarmMacros { $p = Get-FarmMacroPath if (-not (Test-Path -LiteralPath $p)) { return @() } try { $j = Get-Content -LiteralPath $p -Raw -Encoding UTF8 | ConvertFrom-Json return @($j) } catch { return @() } } function Write-FarmMacros($list) { $json = ConvertTo-Json -InputObject @($list) -Depth 12 Set-Content -LiteralPath (Get-FarmMacroPath) -Value $json -Encoding UTF8 } function Get-FarmQueueMax { return 10000 } function Get-FarmDefaultStepMs { $d = 500 try { if ($script:farmDelay) { $d = [int]$script:farmDelay.Value } } catch {} if ($d -lt 0) { $d = 0 } if ($d -gt 8000) { $d = 8000 } return $d } function Clamp-FarmStepMs($ms) { $v = 500 try { $v = [int]$ms } catch { $v = Get-FarmDefaultStepMs } if ($v -lt 0) { $v = 0 } if ($v -gt 8000) { $v = 8000 } return $v } function Ensure-FarmQueueMs { if (-not $script:farmQueueMs) { $script:farmQueueMs = New-Object System.Collections.ArrayList } $q = $script:farmQueue if (-not $q) { return } $def = Get-FarmDefaultStepMs while ($script:farmQueueMs.Count -lt $q.Items.Count) { [void]$script:farmQueueMs.Add($def) } while ($script:farmQueueMs.Count -gt $q.Items.Count) { $script:farmQueueMs.RemoveAt(($script:farmQueueMs.Count - 1)) } } function Get-FarmQueueStepMs([int]$index) { Ensure-FarmQueueMs if ($index -lt 0 -or $index -ge $script:farmQueueMs.Count) { return (Get-FarmDefaultStepMs) } return (Clamp-FarmStepMs $script:farmQueueMs[$index]) } function Set-FarmQueueStepMs([int]$index, $ms) { Ensure-FarmQueueMs if ($index -lt 0 -or $index -ge $script:farmQueueMs.Count) { return } $script:farmQueueMs[$index] = (Clamp-FarmStepMs $ms) } function Split-FarmQueueStored($raw) { $def = Get-FarmDefaultStepMs $item = "" $ms = $def if ($null -eq $raw) { return @{ item = ""; ms = $def } } if ($raw -is [string]) { return @{ item = [string]$raw; ms = $def } } try { $item = [string]$raw.item } catch { $item = "" } if (-not $item) { try { $item = [string]$raw.n } catch { $item = "" } } if (-not $item) { try { $item = [string]$raw } catch { $item = "" } } try { if ($null -ne $raw.ms -and "$($raw.ms)" -ne "") { $ms = [int]$raw.ms } } catch {} try { if ($null -ne $raw.d -and "$($raw.d)" -ne "") { $ms = [int]$raw.d } } catch {} return @{ item = $item; ms = (Clamp-FarmStepMs $ms) } } function Add-FarmQueueRow([string]$label, $index, $ms) { $q = $script:farmQueue if (-not $q -or -not $label) { return $false } Ensure-FarmQueueMs if ($q.Items.Count -ge (Get-FarmQueueMax)) { return $false } $i = $q.Items.Count if ($null -ne $index -and "$index" -ne "") { try { $i = [int]$index } catch { $i = $q.Items.Count } } if ($i -lt 0 -or $i -gt $q.Items.Count) { $i = $q.Items.Count } if ($null -eq $ms -or "$ms" -eq "") { $ms = Get-FarmDefaultStepMs } $q.Items.Insert($i, $label) $script:farmQueueMs.Insert($i, (Clamp-FarmStepMs $ms)) return $true } function Remove-FarmQueueRowAt([int]$index) { $q = $script:farmQueue if (-not $q -or $index -lt 0 -or $index -ge $q.Items.Count) { return } Ensure-FarmQueueMs $q.Items.RemoveAt($index) if ($index -lt $script:farmQueueMs.Count) { $script:farmQueueMs.RemoveAt($index) } } function Place-FarmQueueMsEditor { $q = $script:farmQueue $box = $null try { if ($script:farmUi) { $box = $script:farmUi.qMs } } catch { $box = $null } if (-not $q -or -not $box -or $box.IsDisposed) { return } $i = -1 try { $i = [int]$q.SelectedIndex } catch { $i = -1 } if ($i -lt 0 -or $i -ge $q.Items.Count) { $box.Visible = $false return } $r = $q.GetItemRectangle($i) if ($r.Bottom -lt 4 -or $r.Top -gt ($q.ClientSize.Height - 4)) { $box.Visible = $false return } $script:farmQueueMsBusy = $true try { $box.Value = [decimal](Get-FarmQueueStepMs $i) } catch {} $script:farmQueueMsBusy = $false $x = [int]$q.Left + [int]$q.ClientSize.Width - 86 if ($x -lt ([int]$q.Left + 80)) { $x = [int]$q.Left + 80 } $y = [int]$q.Top + [int]$r.Y + 8 $box.Location = New-Object System.Drawing.Point($x, $y) $box.Visible = $true $box.BringToFront() } function Get-FarmPlayOrderPath { return (Join-Path $root "farm-queue.json") } function Get-FarmPlaylistPath { return (Join-Path $root "farm-playlists.json") } function Get-FarmPlaylistTypes { return @( [pscustomobject]@{ id = "healing-troops"; label = "Healing troops" }, [pscustomobject]@{ id = "farming"; label = "Farming" }, [pscustomobject]@{ id = "troop-building"; label = "Troop building" }, [pscustomobject]@{ id = "best-farming"; label = "Best farming" } ) } function Read-FarmPlaylists { $p = Get-FarmPlaylistPath foreach ($tryPath in @($p, ($p + ".bak"))) { if (-not (Test-Path -LiteralPath $tryPath)) { continue } try { $j = Get-Content -LiteralPath $tryPath -Raw -Encoding UTF8 | ConvertFrom-Json return @($j) } catch {} } return @() } function Write-FarmPlaylists($rows) { $p = Get-FarmPlaylistPath $tmp = $p + ".tmp" $bak = $p + ".bak" ConvertTo-Json -InputObject @($rows) -Depth 10 | Set-Content -LiteralPath $tmp -Encoding UTF8 if (Test-Path -LiteralPath $p) { Copy-Item -LiteralPath $p -Destination $bak -Force } Move-Item -LiteralPath $tmp -Destination $p -Force Copy-Item -LiteralPath $p -Destination $bak -Force } function Get-FarmPlaylistTypeId { $box = $null try { if ($script:farmUi) { $box = $script:farmUi.playlistType } } catch {} $i = 0 try { $i = [int]$box.SelectedIndex } catch { $i = 0 } $types = @(Get-FarmPlaylistTypes) if ($i -lt 0 -or $i -ge $types.Count) { $i = 0 } return [string]$types[$i].id } function Get-FarmQueueRowsForSave { $q = $script:farmQueue $savedRows = New-Object System.Collections.ArrayList if (-not $q -or $q.Items.Count -lt 1) { return @() } Ensure-FarmQueueMs for ($i = 0; $i -lt $q.Items.Count; $i++) { $item = [string]$q.Items[$i] if (-not $item.StartsWith("pic:")) { $nm = Get-FarmMacroNameFromLabel $item if ($nm) { $item = $nm } } [void]$savedRows.Add([pscustomobject]@{ item = $item; ms = (Get-FarmQueueStepMs $i) }) } return @($savedRows) } function Get-FarmPlaylistInstanceId($one) { if (-not $one) { return "" } try { return [string]$one.instanceId } catch { return "" } } function Get-FarmScreenPlaylist([string]$instanceId) { if (-not $instanceId) { return $null } $gid = [string](Get-FarmGameId) $pick = $null foreach ($one in @(Read-FarmPlaylists)) { $iid = Get-FarmPlaylistInstanceId $one if (-not $iid) { continue } if ($iid -eq $instanceId -and [string]$one.gameId -eq $gid) { $pick = $one } } return $pick } function Test-FarmInstanceHasScreenList([string]$instanceId) { $pick = Get-FarmScreenPlaylist $instanceId if (-not $pick) { return $false } try { return (@($pick.rows).Count -gt 0) } catch { return $false } } function Get-FarmScreenNumberById([string]$instanceId) { if (-not $instanceId) { return 0 } $all = @($script:farmInstanceCatalog) if ($all.Count -lt 1) { $all = @(Get-BlueStacksInstanceCatalog) } for ($i = 0; $i -lt $all.Count; $i++) { if ([string]$all[$i].id -eq $instanceId) { return ($i + 1) } } return 0 } function Apply-FarmPlaylistRows($pick, [string]$statusText) { $q = $script:farmQueue if (-not $q -or -not $pick) { return $false } $q.Items.Clear() $script:farmQueueMs = New-Object System.Collections.ArrayList foreach ($raw in @($pick.rows)) { $row = Split-FarmQueueStored $raw if (-not [string]$row.item) { continue } [void](Add-FarmQueueRow ([string]$row.item) $null $row.ms) } Save-FarmPlayOrderFromUi try { Place-FarmQueueMsEditor } catch {} try { $q.Invalidate() } catch {} if ($statusText) { Set-FarmStatus $statusText } return ($q.Items.Count -gt 0) } function Get-FarmCheckedPlaylistScreenIds { $ids = New-Object System.Collections.ArrayList $box = $null try { if ($script:farmUi) { $box = $script:farmUi.playlistScreens } } catch {} if (-not $box) { return @() } $all = @($script:farmInstanceCatalog) foreach ($i in @($box.CheckedIndices)) { try { $row = $all[[int]$i] if ($row -and $row.id) { [void]$ids.Add([string]$row.id) } } catch {} } return @($ids | Select-Object -Unique) } function Get-FarmSelectedPlaylistScreenId { $box = $null try { if ($script:farmUi) { $box = $script:farmUi.playlistScreens } } catch {} $i = -1 try { $i = [int]$box.SelectedIndex } catch {} $all = @($script:farmInstanceCatalog) if ($i -ge 0 -and $i -lt $all.Count) { return [string]$all[$i].id } $checked = @(Get-FarmCheckedPlaylistScreenIds) if ($checked.Count -eq 1) { return [string]$checked[0] } return "" } function Refresh-FarmPlaylistScreenBoxes { $box = $null try { if ($script:farmUi) { $box = $script:farmUi.playlistScreens } } catch {} if (-not $box) { return } $keep = New-Object System.Collections.ArrayList $allNow = @($script:farmInstanceCatalog) if ($box.Items.Count -gt 0 -and $allNow.Count -gt 0) { foreach ($i in @($box.CheckedIndices)) { try { $row = $allNow[[int]$i] if ($row -and $row.id) { [void]$keep.Add([string]$row.id) } } catch {} } } $hadItems = ($box.Items.Count -gt 0) if ($allNow.Count -lt 1) { $script:farmInstanceCatalog = @(Get-BlueStacksInstanceCatalog) $allNow = @($script:farmInstanceCatalog) } $sel = -1 try { $sel = [int]$box.SelectedIndex } catch { $sel = -1 } $box.Items.Clear() for ($i = 0; $i -lt $allNow.Count; $i++) { $row = $allNow[$i] $n = $i + 1 $pick = Get-FarmScreenPlaylist ([string]$row.id) $mark = "no list yet" if ($pick) { $rc = 0 try { $rc = @($pick.rows).Count } catch {} $mark = $rc.ToString() + " steps saved" } $text = "Screen " + $n + ": " + [string]$row.label + " [" + [string]$row.id + "] " + $mark $on = $false if ($hadItems) { $on = ($keep -contains [string]$row.id) } else { $on = [bool]$pick } [void]$box.Items.Add($text, $on) } if ($sel -ge 0 -and $sel -lt $box.Items.Count) { try { $box.SelectedIndex = $sel } catch {} } elseif ($box.Items.Count -gt 0 -and $box.SelectedIndex -lt 0) { $box.SelectedIndex = 0 } } function Save-FarmPlaylistsForInstanceIds($instanceIds, [string]$alsoTypeId) { $ids = @($instanceIds | Where-Object { $_ }) if ($ids.Count -lt 1) { Set-FarmStatus "Tick at least one screen next to the play list, then Save for screens." return $false } $savedRows = @(Get-FarmQueueRowsForSave) if ($savedRows.Count -lt 1) { Set-FarmStatus "The numbered play list is empty. Add steps or pictures first." return $false } $gid = [string](Get-FarmGameId) $when = (Get-Date).ToString("s") $typeId = [string]$alsoTypeId $typeLabel = "" if ($typeId) { foreach ($type in @(Get-FarmPlaylistTypes)) { if ([string]$type.id -eq $typeId) { $typeLabel = [string]$type.label; break } } } $next = New-Object System.Collections.ArrayList foreach ($old in @(Read-FarmPlaylists)) { $oldInst = Get-FarmPlaylistInstanceId $old $drop = $false if ($oldInst) { foreach ($id in $ids) { if ($oldInst -eq $id -and [string]$old.gameId -eq $gid) { $drop = $true; break } } } elseif ($typeId -and [string]$old.gameId -eq $gid -and [string]$old.type -eq $typeId) { $drop = $true } if (-not $drop) { [void]$next.Add($old) } } if ($typeId) { [void]$next.Add([pscustomobject]@{ gameId = $gid type = $typeId label = $typeLabel rows = @($savedRows) saved = $when }) } $names = New-Object System.Collections.ArrayList foreach ($id in $ids) { $n = Get-FarmScreenNumberById $id $lab = $(if ($n -gt 0) { "Screen " + $n } else { $id }) [void]$next.Add([pscustomobject]@{ gameId = $gid type = "screen" instanceId = $id label = $lab rows = @($savedRows) saved = $when }) [void]$names.Add($lab) if ($typeId) { [void](Set-FarmInstancePlaylistType $id $typeId) } } Write-FarmPlaylists @($next) try { Refresh-FarmPlaylistScreenBoxes } catch {} try { Refresh-FarmInstanceList } catch {} Set-FarmStatus ("Saved " + $savedRows.Count + " numbers and pictures for " + ($names -join ", ") + ". Play on that screen starts at #1 and waits for each picture.") return $true } function Save-CurrentFarmPlaylist { $savedRows = @(Get-FarmQueueRowsForSave) if ($savedRows.Count -lt 1) { Set-FarmStatus "The numbered play list is empty. Add steps or pictures first." return $false } $typeId = Get-FarmPlaylistTypeId $typeLabel = $typeId foreach ($type in @(Get-FarmPlaylistTypes)) { if ([string]$type.id -eq $typeId) { $typeLabel = [string]$type.label; break } } $gid = [string](Get-FarmGameId) $next = New-Object System.Collections.ArrayList foreach ($old in @(Read-FarmPlaylists)) { $oldInst = Get-FarmPlaylistInstanceId $old if ($oldInst) { [void]$next.Add($old); continue } if ([string]$old.gameId -eq $gid -and [string]$old.type -eq $typeId) { continue } [void]$next.Add($old) } [void]$next.Add([pscustomobject]@{ gameId = $gid type = $typeId label = $typeLabel rows = @($savedRows) saved = (Get-Date).ToString("s") }) Write-FarmPlaylists @($next) $ticked = @(Get-FarmCheckedPlaylistScreenIds) if ($ticked.Count -gt 0) { return (Save-FarmPlaylistsForInstanceIds $ticked $typeId) } Set-FarmStatus ("Saved all " + $savedRows.Count + " numbers as " + $typeLabel + " for " + (Get-FarmGameNameById $gid) + ". Tick screens below and Save for screens to give each BlueStacks window its own pictures.") return $true } function Save-FarmPlaylistForCheckedScreens { return (Save-FarmPlaylistsForInstanceIds @(Get-FarmCheckedPlaylistScreenIds) "") } function Load-SelectedFarmPlaylist { return (Load-FarmPlaylistByType (Get-FarmPlaylistTypeId)) } function Load-FarmPlaylistByType([string]$typeId) { if (-not $typeId) { return $false } $gid = [string](Get-FarmGameId) $pick = $null foreach ($one in @(Read-FarmPlaylists)) { $iid = Get-FarmPlaylistInstanceId $one if ($iid) { continue } if ([string]$one.gameId -eq $gid -and [string]$one.type -eq $typeId) { $pick = $one } } if (-not $pick) { Set-FarmStatus "Nothing is saved for that play-list type in this game." return $false } $n = @($pick.rows).Count $ok = Apply-FarmPlaylistRows $pick ("Loaded " + [string]$pick.label + " with " + $n + " numbers. Play starts at #1.") return $ok } function Load-FarmPlaylistForInstance([string]$instanceId) { if (-not $instanceId) { return $false } $n = Get-FarmScreenNumberById $instanceId $screenText = $(if ($n -gt 0) { "Screen " + $n } else { $instanceId }) $pick = Get-FarmScreenPlaylist $instanceId if (-not $pick -or @($pick.rows).Count -lt 1) { Set-FarmStatus ($screenText + " has no play list yet. Tick that screen next to the numbered list, add its pictures, then Save for screens. This screen will not use another screen's images.") return $false } $nRows = @($pick.rows).Count $ok = Apply-FarmPlaylistRows $pick ("Loaded " + $screenText + " list: " + $nRows + " numbers (including pictures). Play starts at #1 and waits until each picture is found.") return $ok } function Load-FarmPlaylistForSelectedScreen { $id = Get-FarmSelectedPlaylistScreenId if (-not $id) { Set-FarmStatus "Select or tick one screen next to the play list, then Load screen." return $false } return (Load-FarmPlaylistForInstance $id) } function Refresh-FarmPlaylistStatus { $info = $null try { if ($script:farmUi) { $info = $script:farmUi.playlistInfo } } catch {} if (-not $info -or $info.IsDisposed) { return } $typeId = Get-FarmPlaylistTypeId $gid = [string](Get-FarmGameId) $pick = $null $screenN = 0 foreach ($one in @(Read-FarmPlaylists)) { $iid = Get-FarmPlaylistInstanceId $one if ($iid) { if ([string]$one.gameId -eq $gid) { $screenN++ } continue } if ([string]$one.gameId -eq $gid -and [string]$one.type -eq $typeId) { $pick = $one } } $typeBit = "Nothing saved for this type in " + (Get-FarmGameNameById $gid) + "." if ($pick) { $typeBit = [string]$pick.label + " type: " + @($pick.rows).Count + " rows. Load list or Play saved." } $info.Text = $typeBit + " Screens with their own list: " + $screenN + ". Tick screens, then Save for screens." } function Read-FarmPlayOrderMap { $p = Get-FarmPlayOrderPath $blank = @{} foreach ($tryPath in @($p, ($p + ".bak"))) { if (-not (Test-Path -LiteralPath $tryPath)) { continue } try { $j = Get-Content -LiteralPath $tryPath -Raw -Encoding UTF8 | ConvertFrom-Json if (-not $j) { continue } foreach ($prop in $j.PSObject.Properties) { $blank[[string]$prop.Name] = @($prop.Value) } return $blank } catch {} } return $blank } function Write-FarmPlayOrderMap($map) { $p = Get-FarmPlayOrderPath $tmp = $p + ".tmp" $bak = $p + ".bak" $json = ConvertTo-Json -InputObject $map -Depth 8 Set-Content -LiteralPath $tmp -Value $json -Encoding UTF8 if (Test-Path -LiteralPath $p) { Copy-Item -LiteralPath $p -Destination $bak -Force } Move-Item -LiteralPath $tmp -Destination $p -Force Copy-Item -LiteralPath $p -Destination $bak -Force } function Save-FarmPlayOrderFromUi { $q = $script:farmQueue if (-not $q) { return } $gid = [string](Get-FarmGameId) if (-not $gid) { $gid = "kingshot" } $names = New-Object System.Collections.ArrayList Ensure-FarmQueueMs $i = 0 foreach ($lab in @($q.Items)) { $s = [string]$lab $ms = Get-FarmQueueStepMs $i $item = $s if (-not $s.StartsWith("pic:")) { $nm = Get-FarmMacroNameFromLabel $s if ($nm) { $item = $nm } } [void]$names.Add([pscustomobject]@{ item = $item; ms = $ms }) $i++ } $map = Read-FarmPlayOrderMap $map[$gid] = @($names) Write-FarmPlayOrderMap $map } function Load-FarmPlayOrderToUi { $q = $script:farmQueue if (-not $q) { return } $q.Items.Clear() $script:farmQueueMs = New-Object System.Collections.ArrayList $gid = [string](Get-FarmGameId) $map = Read-FarmPlayOrderMap $names = @() if ($gid -and $map.ContainsKey($gid)) { $names = @($map[$gid]) } $max = Get-FarmQueueMax foreach ($nm in $names) { if ($q.Items.Count -ge $max) { break } $row = Split-FarmQueueStored $nm $s = [string]$row.item $ms = $row.ms if ($s.StartsWith("pic:")) { $fp = Resolve-FarmPicFile $s if (-not $fp) { $fp = Get-FarmPicQueueFile $s } $nm2 = "picture" $bar = $s.IndexOf("|") if ($bar -ge 0) { $nm2 = $s.Substring($bar + 1) } $picLabel = $s if ($fp) { $picLabel = Format-FarmPicQueueLabel $fp $nm2 } [void](Add-FarmQueueRow $picLabel $null $ms) continue } $m = Find-FarmMacroByName $s if ($m) { [void](Add-FarmQueueRow (Format-FarmMacroLabel $m) $null $ms) } } try { Place-FarmQueueMsEditor } catch {} } function Move-FarmQueueSelected([int]$delta) { $q = $script:farmQueue if (-not $q) { return } $i = -1 try { $i = [int]$q.SelectedIndex } catch { $i = -1 } $n = [int]$q.Items.Count if ($i -lt 0 -or $n -lt 2) { return } $to = $i + [int]$delta if ($to -lt 0) { $to = 0 } if ($to -ge $n) { $to = $n - 1 } if ($to -eq $i) { return } $item = $q.Items[$i] Ensure-FarmQueueMs $ms = Get-FarmQueueStepMs $i $q.Items.RemoveAt($i) if ($i -lt $script:farmQueueMs.Count) { $script:farmQueueMs.RemoveAt($i) } $q.Items.Insert($to, $item) $script:farmQueueMs.Insert($to, $ms) $q.SelectedIndex = $to try { $vis = [Math]::Max(1, [int][Math]::Floor($q.ClientSize.Height / [Math]::Max(1, $q.ItemHeight))) $top = [int]$to - [int][Math]::Floor($vis / 2) if ($top -lt 0) { $top = 0 } $q.TopIndex = $top } catch {} try { Save-FarmPlayOrderFromUi } catch {} try { Place-FarmQueueMsEditor } catch {} } function Scroll-FarmQueueToward([int]$y) { $q = $script:farmQueue if (-not $q -or $q.Items.Count -lt 2) { return } $now = [Environment]::TickCount if ($script:queueDragScrollAt -and (($now - [int]$script:queueDragScrollAt) -lt 90)) { return } $script:queueDragScrollAt = $now $edge = 28 $h = [int]$q.ClientSize.Height $top = [int]$q.TopIndex $vis = [Math]::Max(1, [int][Math]::Floor($h / [Math]::Max(1, $q.ItemHeight))) $maxTop = [Math]::Max(0, $q.Items.Count - $vis) if ($y -lt $edge -and $top -gt 0) { $q.TopIndex = $top - 1 } elseif ($y -gt ($h - $edge) -and $top -lt $maxTop) { $q.TopIndex = $top + 1 } } function Add-FarmPlayStep($m) { if (-not $m) { return } $lab = Format-FarmMacroLabel $m $q = $script:farmQueue if ($q) { if ($q.Items.Count -ge (Get-FarmQueueMax)) { Set-FarmStatus ("Play list is full (" + (Get-FarmQueueMax) + "). Remove one, then Save.") return } [void](Add-FarmQueueRow $lab $null $null) } Save-FarmPlayOrderFromUi try { Place-FarmQueueMsEditor } catch {} } function Convert-FarmEvents($raw) { $out = New-Object System.Collections.ArrayList foreach ($e in @($raw)) { if (-not $e) { continue } $et = "" try { $et = [string]$e.type } catch { $et = "" } if ($et -eq "loop") { continue } $t = 0 $x = 0 $y = 0 $fp = "" try { $t = [int]$e.t } catch {} try { $x = [int]$e.x } catch {} try { $y = [int]$e.y } catch {} try { $fp = [string]$e.file } catch {} $key = 0 try { $key = [int]$e.key } catch { $key = 0 } $nx = -1.0 $ny = -1.0 $ms = 500 try { $nx = [double]$e.nx } catch { $nx = -1.0 } try { $ny = [double]$e.ny } catch { $ny = -1.0 } try { if ($null -ne $e.ms) { $ms = [int]$e.ms } } catch { $ms = 500 } [void]$out.Add(@{ t = $t type = [string]$e.type x = $x y = $y key = $key file = $fp nx = $nx ny = $ny ms = $ms }) } return ,$out.ToArray() } function Add-FarmWaitPicStep([string]$path) { $fp = [string]$path if (-not $fp -or -not (Test-Path -LiteralPath $fp)) { return } $t = 0 $ev = New-Object System.Collections.ArrayList foreach ($e in @($script:lastFarmEvents)) { if (-not $e) { continue } [void]$ev.Add($e) try { if ([int]$e.t -gt $t) { $t = [int]$e.t } } catch {} } $step = @{ t = ($t + 200); type = "waitpic"; x = 0; y = 0; file = $fp } $b = $script:farmBox try { if ($b -and $b.recording) { foreach ($e in @($b.events)) { try { if ([int]$e.t -gt $t) { $t = [int]$e.t } } catch {} } $step.t = $t + 200 [void]$b.events.Add($step) } } catch {} [void]$ev.Add($step) $script:lastFarmEvents = @($ev) } function Add-FarmSelectedPicToFarm { $box = $null try { if ($script:farmUi -and $script:farmUi.glass) { $box = $script:farmUi.glass } } catch {} $all = @(Read-FarmGlassList) $i = -1 try { if ($box) { $i = [int]$box.SelectedIndex } } catch { $i = -1 } if ($i -lt 0 -and $all.Count -gt 0) { $i = $all.Count - 1 } if ($i -lt 0 -or $i -ge $all.Count) { Set-FarmStatus (Helper-T "Take a picture with Mag glass on Pictures, then Add picture.") return } $name = [string]$all[$i].name if (-not $name) { $name = "picture" } $lab = Format-FarmPicQueueLabel ([string]$all[$i].file) $name $q = $script:farmQueue $at = 0 try { if ($q) { $at = $q.Items.Count } } catch { $at = 0 } if (Insert-FarmQueueLabel $lab $at) { try { if ($q -and $q.Items.Count -gt 0) { $q.SelectedIndex = $q.Items.Count - 1 } } catch {} Show-FarmToast ($name + " is on the play list. Scroll, then Move up / Move down or drag a row to change the order.") } } function Invoke-FarmLogout([string]$msg) { try { Farm-StopPlay } catch {} if ($script:cfg) { try { Save-Cfg $script:cfg.code (Get-ServerBase) $script:cfg $false } catch {} try { $script:cfg = Read-Cfg } catch {} } Set-FarmStatus $msg [void][System.Windows.Forms.MessageBox]::Show( $msg, "Auto Farm", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Warning ) } function Keep-FarmPlayJob($play) { $old = $null try { $old = $script:farmPlayJob } catch { $old = $null } $script:farmPlayJob = $play try { if ($script:farmBox) { $script:farmBox.playJob = $play } } catch {} if ($old -and $old -ne $play) { try { $old.Stop() } catch {} try { if ($old.Runspace) { $old.Runspace.Close(); $old.Runspace.Dispose() } } catch {} try { $old.Dispose() } catch {} } } function Request-FarmLease { param([string]$action, [switch]$Quiet) if ($action -ne "stop" -and $action -ne "beat") { $needSub = $true try { if ($script:farmTicket -and $script:chatPayState -eq "paid") { $needSub = $false } } catch { $needSub = $true } if ($needSub) { try { Get-ChatSubscription | Out-Null } catch {} } } $id = Get-ChatIdentity $uid = [string]$id.userId if ($script:farmLeaseUserId) { $uid = [string]$script:farmLeaseUserId } $payload = @{ action = [string]$action userId = $uid displayName = [string]$id.displayName allianceName = [string]$id.allianceName farmTicket = [string]$script:farmTicket helperSha256 = Get-HelperSha256 helperVersion = [string]$script:HelperVersion } | ConvertTo-Json -Compress try { $r = Invoke-HelperRest -Method POST -Uri "$(Get-ServerBase)/api/raids-chat/farm/lease" -Body $payload -TimeoutSec 20 -Tries 3 if ($r.ok -eq $true) { return $true } if ($r.logout -eq $true) { Invoke-FarmLogout ([string]$r.error); return $false } throw [string]$r.error } catch { $msg = [string]$_.Exception.Message $logout = $false try { $raw = $_.ErrorDetails.Message if ($raw) { $j = $raw | ConvertFrom-Json if ($j.error) { $msg = [string]$j.error } if ($j.logout -eq $true) { $logout = $true } } } catch {} if ($logout) { Invoke-FarmLogout $msg; return $false } if (Test-HelperNetGlitch $msg) { $msg = "Could not reach the farm server. Press Play again." } if (-not $Quiet -and $action -ne "beat" -and $action -ne "stop") { try { if ($script:farmForm) { $script:farmForm.TopMost = $false } } catch {} Set-FarmStatus $msg try { Show-FarmToast $msg } catch { [void][System.Windows.Forms.MessageBox]::Show( $msg, "Auto Farm", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information ) } } return $false } } function Get-FarmWatchPath { return (Join-Path $root "farm-watch.png") } function Get-FarmGlassDir { $d = Join-Path $root "farm-glass" New-Item -ItemType Directory -Force -Path $d | Out-Null return $d } function Get-FarmGlassListPath { return (Join-Path (Get-FarmGlassDir) "list.json") } function Read-FarmGlassList { $p = Get-FarmGlassListPath foreach ($tryPath in @($p, ($p + ".bak"))) { if (-not (Test-Path -LiteralPath $tryPath)) { continue } try { $j = Get-Content -LiteralPath $tryPath -Raw -Encoding UTF8 | ConvertFrom-Json return @($j) } catch {} } return @() } function Write-FarmGlassList($list) { $p = Get-FarmGlassListPath $tmp = $p + ".tmp" $bak = $p + ".bak" $json = ConvertTo-Json -InputObject @($list) -Depth 6 Set-Content -LiteralPath $tmp -Value $json -Encoding UTF8 if (Test-Path -LiteralPath $p) { Copy-Item -LiteralPath $p -Destination $bak -Force } Move-Item -LiteralPath $tmp -Destination $p -Force Copy-Item -LiteralPath $p -Destination $bak -Force } function Get-FarmGlassFiles { $out = New-Object System.Collections.ArrayList foreach ($row in @(Read-FarmGlassList)) { $f = [string]$row.file if (-not $f) { continue } if (-not [IO.Path]::IsPathRooted($f)) { $f = Join-Path (Get-FarmGlassDir) $f } if (Test-Path -LiteralPath $f) { [void]$out.Add($f) } } $legacy = Get-FarmWatchPath if ((Test-Path -LiteralPath $legacy) -and ($out -notcontains $legacy)) { [void]$out.Add($legacy) } return @($out) } function Fill-FarmGlassList { $box = $null try { if ($script:farmUi -and $script:farmUi.glass) { $box = $script:farmUi.glass } } catch {} if (-not $box) { return } $box.Items.Clear() $n = 0 foreach ($row in @(Read-FarmGlassList)) { $n++ $nm = [string]$row.name if (-not $nm) { $nm = "picture $n" } [void]$box.Items.Add(("$n. " + $nm)) } if ($box.Items.Count -gt 0 -and $box.SelectedIndex -lt 0) { $box.SelectedIndex = $box.Items.Count - 1 } Show-FarmGlassListPreview } function Show-FarmGlassListPreview { $pic = $null $box = $null try { if ($script:farmUi) { $pic = $script:farmUi.glassPreview; $box = $script:farmUi.glass } } catch {} if (-not $pic) { return } try { if ($script:glassListBmp) { $script:glassListBmp.Dispose() } } catch {} $script:glassListBmp = $null $i = -1 try { if ($box) { $i = [int]$box.SelectedIndex } } catch { $i = -1 } $all = @(Read-FarmGlassList) if ($i -lt 0 -or $i -ge $all.Count) { $pic.Image = $null return } $f = Join-Path (Get-FarmGlassDir) ([string]$all[$i].file) if (-not (Test-Path -LiteralPath $f)) { $pic.Image = $null; return } try { $fs = [IO.File]::Open($f, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::ReadWrite) $tmp = New-Object System.Drawing.Bitmap $fs $fs.Close() $hold = New-Object System.Drawing.Bitmap $tmp $tmp.Dispose() $script:glassListBmp = $hold $pic.Image = $hold } catch { $pic.Image = $null } } function Get-FarmGameRect { $h = [IntPtr]::Zero try { $h = Find-FarmGameHwnd } catch { $h = [IntPtr]::Zero } if ($h -eq [IntPtr]::Zero) { return $null } try { if ([RtFarmGrab]::IsMinimized($h)) { return $null } } catch {} $surf = $h try { $g = [RtFarmGrab]::GameSurface($h) if ($g -ne [IntPtr]::Zero) { $surf = $g } } catch {} $r = New-Object RtFarmGrab+RECT [void][RtFarmGrab]::GetWindowRect($surf, [ref]$r) $w = [int]$r.Right - [int]$r.Left $hh = [int]$r.Bottom - [int]$r.Top if ($w -lt 20 -or $hh -lt 20) { return $null } return @{ X = [int]$r.Left; Y = [int]$r.Top; W = $w; H = $hh; Hwnd = $surf } } function Copy-FarmGameBox($shot) { $game = Get-FarmGameRect if (-not $game) { return $null } $scale = 1.0 try { $scale = [double][RtFarmGrab]::ScaleOf([IntPtr]$game.Hwnd) } catch { $scale = 1 } if ($scale -lt 1) { $scale = 1 } $bw = [int][Math]::Round([int]$game.W * $scale) $bh = [int][Math]::Round([int]$game.H * $scale) if ($bw -lt 8 -or $bh -lt 8) { return $null } $full = $null try { $full = [RtFarmGrab]::FromWindow([IntPtr]$game.Hwnd, $bw, $bh) } catch { $full = $null } if (-not $full) { return $null } $x = [int][Math]::Round(([int]$shot.x - [int]$game.X) * $scale) $y = [int][Math]::Round(([int]$shot.y - [int]$game.Y) * $scale) $w = [int][Math]::Round([int]$shot.w * $scale) $h = [int][Math]::Round([int]$shot.h * $scale) if ($x -lt 0) { $w += $x; $x = 0 } if ($y -lt 0) { $h += $y; $y = 0 } if ($x -ge $full.Width -or $y -ge $full.Height) { try { $full.Dispose() } catch {} return $null } if (($x + $w) -gt $full.Width) { $w = $full.Width - $x } if (($y + $h) -gt $full.Height) { $h = $full.Height - $y } if ($w -lt 8 -or $h -lt 8) { try { $full.Dispose() } catch {} return $null } $crop = New-Object System.Drawing.Bitmap $w, $h $g = [System.Drawing.Graphics]::FromImage($crop) $dest = New-Object System.Drawing.Rectangle 0, 0, $w, $h $src = New-Object System.Drawing.Rectangle $x, $y, $w, $h $g.DrawImage($full, $dest, $src, [System.Drawing.GraphicsUnit]::Pixel) $g.Dispose() $nx = [Math]::Round((($x + ($w / 2.0)) / [double]$full.Width), 5) $ny = [Math]::Round((($y + ($h / 2.0)) / [double]$full.Height), 5) try { if ($null -ne $shot.cx -and $null -ne $shot.cy -and [int]$shot.cx -ne 0) { $rel = Get-FarmRelPoint ([int]$shot.cx) ([int]$shot.cy) if ($rel) { $nx = [double]$rel.nx; $ny = [double]$rel.ny } } } catch {} try { $full.Dispose() } catch {} return @{ bmp = $crop; spot = @{ nx = $nx; ny = $ny } } } function Test-FarmBitmapBlank($bmp) { if (-not $bmp -or $bmp.Width -lt 2 -or $bmp.Height -lt 2) { return $true } try { $minR = 255; $minG = 255; $minB = 255 $maxR = 0; $maxG = 0; $maxB = 0 $sum = 0L; $count = 0 $stepX = [Math]::Max(1, [int][Math]::Floor($bmp.Width / 12)) $stepY = [Math]::Max(1, [int][Math]::Floor($bmp.Height / 12)) for ($y = 0; $y -lt $bmp.Height; $y += $stepY) { for ($x = 0; $x -lt $bmp.Width; $x += $stepX) { $c = $bmp.GetPixel($x, $y) if ($c.A -lt 8) { continue } if ($c.R -lt $minR) { $minR = $c.R } if ($c.G -lt $minG) { $minG = $c.G } if ($c.B -lt $minB) { $minB = $c.B } if ($c.R -gt $maxR) { $maxR = $c.R } if ($c.G -gt $maxG) { $maxG = $c.G } if ($c.B -gt $maxB) { $maxB = $c.B } $sum += [int]$c.R + [int]$c.G + [int]$c.B $count++ } } if ($count -lt 4) { return $true } $avg = $sum / [double]($count * 3) $range = [Math]::Max(($maxR - $minR), [Math]::Max(($maxG - $minG), ($maxB - $minB))) return ($avg -lt 4 -or $range -lt 4) } catch { return $true } } function Copy-FarmScreenBox($shot) { if (-not $shot -or [int]$shot.w -lt 8 -or [int]$shot.h -lt 8) { return $null } $bmp = $null try { $scale = 1.0 $game = Get-FarmGameRect if ($game -and $game.Hwnd) { try { $scale = [double][RtFarmGrab]::ScaleOf([IntPtr]$game.Hwnd) } catch { $scale = 1.0 } } if ($scale -lt 1.0) { $scale = 1.0 } $sx = [int][Math]::Round([int]$shot.x * $scale) $sy = [int][Math]::Round([int]$shot.y * $scale) $sw = [int][Math]::Round([int]$shot.w * $scale) $sh = [int][Math]::Round([int]$shot.h * $scale) if ($sw -lt 8 -or $sh -lt 8) { return $null } $bmp = New-Object System.Drawing.Bitmap $sw, $sh $g = [System.Drawing.Graphics]::FromImage($bmp) $g.CopyFromScreen($sx, $sy, 0, 0, $bmp.Size) $g.Dispose() return $bmp } catch { try { if ($g) { $g.Dispose() } } catch {} try { if ($bmp) { $bmp.Dispose() } } catch {} return $null } } function Get-FarmRelPoint([int]$sx, [int]$sy) { $r = Get-FarmGameRect if (-not $r) { return $null } $nx = ($sx - [int]$r.X) / [double]$r.W $ny = ($sy - [int]$r.Y) / [double]$r.H if ($nx -lt -0.02 -or $ny -lt -0.02 -or $nx -gt 1.02 -or $ny -gt 1.02) { return $null } if ($nx -lt 0) { $nx = 0 } if ($ny -lt 0) { $ny = 0 } if ($nx -gt 1) { $nx = 1 } if ($ny -gt 1) { $ny = 1 } return @{ nx = [Math]::Round($nx, 5); ny = [Math]::Round($ny, 5) } } function Get-FarmRelForFile([string]$path) { $name = "" try { $name = [IO.Path]::GetFileName([string]$path) } catch { $name = "" } if (-not $name) { return $null } foreach ($row in @(Read-FarmGlassList)) { $file = [string]$row.file if ($file -ne $name -and $file -ne [string]$path) { continue } $nx = -1.0 $ny = -1.0 try { if ($null -ne $row.nx -and "$($row.nx)" -ne "") { $nx = [double]$row.nx } } catch {} try { if ($null -ne $row.ny -and "$($row.ny)" -ne "") { $ny = [double]$row.ny } } catch {} if ($nx -ge 0 -and $ny -ge 0 -and $nx -le 1 -and $ny -le 1) { return @{ nx = $nx; ny = $ny } } } return $null } function Add-FarmGlassBitmap($bmp, [string]$name, $spot) { if (-not $bmp) { return $false } $dir = Get-FarmGlassDir $id = [DateTime]::Now.ToString("yyyyMMddHHmmssfff") $file = Join-Path $dir ($id + ".png") $bmp.Save($file, [System.Drawing.Imaging.ImageFormat]::Png) if (-not $name) { $name = "Picture " + ((@(Read-FarmGlassList).Count) + 1) } $row = [ordered]@{ id = $id; name = $name; file = ($id + ".png") } if ($spot -and $null -ne $spot.nx -and $null -ne $spot.ny) { $row.nx = [double]$spot.nx $row.ny = [double]$spot.ny } $all = @(Read-FarmGlassList) + @([pscustomobject]$row) Write-FarmGlassList $all Fill-FarmGlassList try { if ($script:farmUi -and $script:farmUi.glass -and $script:farmUi.glass.Items.Count -gt 0) { $script:farmUi.glass.SelectedIndex = $script:farmUi.glass.Items.Count - 1 } if ($script:farmUi -and $script:farmUi.tabs) { $script:farmUi.tabs.SelectedIndex = 0 } Show-FarmGlassListPreview } catch {} try { Copy-Item -Force $file (Get-FarmWatchPath) } catch {} return $true } function Remove-FarmGlassSelected { $box = $null try { if ($script:farmUi -and $script:farmUi.glass) { $box = $script:farmUi.glass } } catch {} if (-not $box -or $box.SelectedIndex -lt 0) { return } $all = @(Read-FarmGlassList) $i = [int]$box.SelectedIndex if ($i -ge $all.Count) { return } $row = $all[$i] $queued = $false $targetFile = [IO.Path]::GetFileName([string]$row.file) try { $map = Read-FarmPlayOrderMap foreach ($gameKey in @($map.Keys)) { foreach ($savedRow in @($map[$gameKey])) { $stored = Split-FarmQueueStored $savedRow $label = [string]$stored.item if (-not $label.StartsWith("pic:")) { continue } $queuedFile = [IO.Path]::GetFileName((Get-FarmPicQueueFile $label)) if ($queuedFile -and $queuedFile -eq $targetFile) { $queued = $true; break } } if ($queued) { break } } } catch {} if (-not $queued) { try { foreach ($playlist in @(Read-FarmPlaylists)) { foreach ($savedRow in @($playlist.rows)) { $stored = Split-FarmQueueStored $savedRow $label = [string]$stored.item if (-not $label.StartsWith("pic:")) { continue } $queuedFile = [IO.Path]::GetFileName((Get-FarmPicQueueFile $label)) if ($queuedFile -and $queuedFile -eq $targetFile) { $queued = $true; break } } if ($queued) { break } } } catch {} } if ($queued) { Set-FarmStatus "That picture is still on a current or saved play list, so it was not deleted." return } $f = Join-Path (Get-FarmGlassDir) ([string]$row.file) try { if (Test-Path -LiteralPath $f) { Remove-Item -LiteralPath $f -Force } } catch {} $next = New-Object System.Collections.ArrayList $n = 0 foreach ($r in $all) { if ($n -ne $i) { [void]$next.Add($r) } $n++ } Write-FarmGlassList @($next) Fill-FarmGlassList Paint-FarmSightLabel Set-FarmStatus "Picture removed. Play still hits any picture that is left." } function Capture-FarmGlassAtCursor { param([switch]$HideGlass) $size = 64 $half = 32 $pt = [System.Windows.Forms.Cursor]::Position $ox = [int]$pt.X - $half $oy = [int]$pt.Y - $half $f = $script:glassForm try { if ($f -and -not $f.IsDisposed) { $f.Location = New-Object System.Drawing.Point(-5000, -5000) try { [System.Windows.Forms.Application]::DoEvents() } catch {} } } catch {} $bmp = $null try { $bmp = New-Object System.Drawing.Bitmap $size, $size $g = [System.Drawing.Graphics]::FromImage($bmp) $g.CopyFromScreen($ox, $oy, 0, 0, $bmp.Size) $g.Dispose() } catch { $bmp = $null } try { if ($f -and -not $f.IsDisposed) { $f.Location = New-Object System.Drawing.Point($ox, $oy) $f.Visible = $true $f.TopMost = $true } } catch {} return @{ bmp = $bmp } } function Show-FarmGlassPreview($raw) { if (-not $raw -or -not $script:glassPic) { return } $hold = $raw.Clone() $old = $script:glassShowBmp $script:glassShowBmp = $hold $script:glassPic.Image = $hold try { if ($old) { $old.Dispose() } } catch {} } function Save-FarmGlassSnap { $f = $script:glassForm try { if ($f -and -not $f.IsDisposed) { $f.Visible = $false } } catch {} try { [System.Windows.Forms.Application]::DoEvents() } catch {} $cap = Capture-FarmGlassAtCursor -HideGlass try { if ($f -and -not $f.IsDisposed) { $f.Visible = $true; $f.TopMost = $true } } catch {} if (-not $cap -or -not $cap.bmp) { return } $n = (@(Read-FarmGlassList).Count) + 1 if (Add-FarmGlassBitmap $cap.bmp ("Picture " + $n)) { Set-FarmStatus ("Saved picture " + $n + ". Left mouse takes another. Right-click or Esc closes the glass.") try { if ($script:farmWaitImg) { $script:farmWaitImg.Checked = $true } } catch {} Paint-FarmSightLabel } try { $cap.bmp.Dispose() } catch {} } function Close-FarmMagGlass { if ($script:glassClosing) { return } $script:glassClosing = $true try { if ($script:glassTick) { $script:glassTick.Stop(); $script:glassTick.Dispose() } } catch {} $script:glassTick = $null $f = $script:glassForm $script:glassForm = $null $script:glassPic = $null try { if ($script:glassLastBmp) { $script:glassLastBmp.Dispose() } } catch {} $script:glassLastBmp = $null try { if ($script:glassShowBmp) { $script:glassShowBmp.Dispose() } } catch {} $script:glassShowBmp = $null try { if ($f -and -not $f.IsDisposed) { $f.Close() } } catch {} try { if ($script:farmForm -and -not $script:farmForm.IsDisposed) { $script:farmForm.Opacity = 1 } } catch {} $script:glassClosing = $false } function Get-FarmMagGlassSpot($pt) { $half = 32 return New-Object System.Drawing.Point (([int]$pt.X - $half), ([int]$pt.Y - $half)) } function Show-FarmMagGlass { Set-FarmStatus "Press where the picture starts, drag, then let go. Play clicks the middle of that box, even if the picture is a different size." Show-FarmGlassDragBox } function Show-FarmGlassDragBox { $shot = @{ x = 0; y = 0; w = 0; h = 0; ok = $false } try { if ($script:farmForm -and -not $script:farmForm.IsDisposed) { $script:farmForm.Hide() } } catch {} $f = New-Object System.Windows.Forms.Form $f.FormBorderStyle = "None" $f.WindowState = "Maximized" $f.TopMost = $true $f.Opacity = 0.18 $f.BackColor = [System.Drawing.Color]::Black $f.Cursor = [System.Windows.Forms.Cursors]::Cross $f.KeyPreview = $true $f.ShowInTaskbar = $false $box = New-Object System.Windows.Forms.Panel $box.BackColor = [System.Drawing.Color]::FromArgb(80, 255, 220, 40) $box.BorderStyle = "FixedSingle" $box.Visible = $false $box.Enabled = $false $f.Controls.Add($box) $hold = @{ box = $box; shot = $shot } $f.Tag = $hold $script:glassDragAX = $null $script:glassDragAY = $null $f.Add_KeyDown({ if ($_.KeyCode -eq "Escape") { $this.Close() } }) $f.Add_MouseDown({ if ($_.Button -ne [System.Windows.Forms.MouseButtons]::Left) { return } $pt = [System.Windows.Forms.Cursor]::Position $script:glassDragAX = [int]$pt.X $script:glassDragAY = [int]$pt.Y try { $this.Capture = $true } catch {} $cl = $this.PointToClient($pt) $b = $this.Tag.box $b.Location = $cl $b.Size = New-Object System.Drawing.Size(1, 1) $b.Visible = $true }) $f.Add_MouseMove({ if ($null -eq $script:glassDragAX) { return } $p = [System.Windows.Forms.Cursor]::Position $a = New-Object System.Drawing.Point -ArgumentList @(([int]$script:glassDragAX), ([int]$script:glassDragAY)) $c1 = $this.PointToClient($a) $c2 = $this.PointToClient($p) $x = [Math]::Min($c1.X, $c2.X) $y = [Math]::Min($c1.Y, $c2.Y) $w = [Math]::Abs($c1.X - $c2.X) $h = [Math]::Abs($c1.Y - $c2.Y) if ($w -lt 1) { $w = 1 } if ($h -lt 1) { $h = 1 } $b = $this.Tag.box $b.Location = New-Object System.Drawing.Point($x, $y) $b.Size = New-Object System.Drawing.Size($w, $h) }) $f.Add_MouseUp({ if ($_.Button -ne [System.Windows.Forms.MouseButtons]::Left) { return } try { $this.Capture = $false } catch {} if ($null -eq $script:glassDragAX) { $this.Close(); return } $p = [System.Windows.Forms.Cursor]::Position $ax = [int]$script:glassDragAX $ay = [int]$script:glassDragAY $px = [int]$p.X $py = [int]$p.Y $x = [Math]::Min($ax, $px) $y = [Math]::Min($ay, $py) $w = [Math]::Abs($ax - $px) $h = [Math]::Abs($ay - $py) if ($w -ge 8 -and $h -ge 8) { $this.Tag.shot.x = [int]$x $this.Tag.shot.y = [int]$y $this.Tag.shot.w = [int]$w $this.Tag.shot.h = [int]$h $this.Tag.shot.cx = [int][Math]::Round(($ax + $px) / 2.0) $this.Tag.shot.cy = [int][Math]::Round(($ay + $py) / 2.0) $this.Tag.shot.ok = $true } $script:glassDragAX = $null $script:glassDragAY = $null $this.Close() }) [void]$f.ShowDialog() try { $f.Dispose() } catch {} Start-Sleep -Milliseconds 80 try { [System.Windows.Forms.Application]::DoEvents() } catch {} if ($shot.ok) { $bmp = $null try { # Mag glass must save the exact visible screen rectangle the user dragged. # BlueStacks PrintWindow/child-surface coordinates can point at a different # part of its GPU-rendered window, so do not translate this selection. $bmp = Copy-FarmScreenBox $shot $spot = Get-FarmRelPoint ([int]$shot.cx) ([int]$shot.cy) if (-not $bmp -or (Test-FarmBitmapBlank $bmp)) { try { if ($bmp) { $bmp.Dispose() } } catch {} $bmp = $null Set-FarmStatus "That capture was blank. Keep BlueStacks visible, show the image, then use Mag glass again." } else { $num = (@(Read-FarmGlassList).Count) + 1 if (Add-FarmGlassBitmap $bmp ("Picture " + $num) $spot) { try { if ($script:farmWaitImg) { $script:farmWaitImg.Checked = $true } } catch {} Paint-FarmSightLabel if ($spot) { Set-FarmStatus ("Saved the exact box you dragged as picture " + $num + ". Play clicks the middle of that box.") } else { Set-FarmStatus ("Saved picture " + $num + ", but that box was not on BlueStacks. Drag it on the game.") } } } } catch { Set-FarmStatus "Could not copy that box. Try Mag glass again." } try { if ($bmp) { $bmp.Dispose() } } catch {} } try { if ($script:farmForm -and -not $script:farmForm.IsDisposed) { $script:farmForm.Show() $script:farmForm.BringToFront() } } catch {} } function Save-FarmSightCfg { try { $c = Read-Cfg $ht = @{} if ($c) { foreach ($p in $c.PSObject.Properties) { $ht[$p.Name] = $p.Value } } $b = $script:farmBox $ht.farmSightX = [int]$b.sightX $ht.farmSightY = [int]$b.sightY $ht.farmSightW = [int]$b.sightW $ht.farmSightH = [int]$b.sightH $ht.farmWinTitle = [string]$b.winTitle try { $ht.farmSizeName = [string]$b.sizeName } catch { $ht.farmSizeName = "BlueStacks" } try { $ht.farmSizeX = [int]$b.sizeX } catch {} try { $ht.farmSizeY = [int]$b.sizeY } catch {} try { $ht.farmSizeW = [int]$b.sizeW } catch {} try { $ht.farmSizeH = [int]$b.sizeH } catch {} ($ht | ConvertTo-Json) | Set-Content -Path $cfgPath -Encoding UTF8 $script:cfg = Read-Cfg } catch {} } function Load-FarmSightCfg { try { $c = Read-Cfg if (-not $c -or -not $script:farmBox) { return } if ($c.farmSightW) { $script:farmBox.sightX = [int]$c.farmSightX $script:farmBox.sightY = [int]$c.farmSightY $script:farmBox.sightW = [int]$c.farmSightW $script:farmBox.sightH = [int]$c.farmSightH } if ($c.farmWinTitle) { $script:farmBox.winTitle = [string]$c.farmWinTitle } try { if ($c.farmSizeName) { $script:farmBox.sizeName = [string]$c.farmSizeName } if ($c.farmSizeW) { $script:farmBox.sizeX = [int]$c.farmSizeX $script:farmBox.sizeY = [int]$c.farmSizeY $script:farmBox.sizeW = [int]$c.farmSizeW $script:farmBox.sizeH = [int]$c.farmSizeH } } catch {} } catch {} } function Format-FarmWinBox([int]$x, [int]$y, [int]$w, [int]$h) { return ([string]$w + " x " + [string]$h + " at " + [string]$x + ", " + [string]$y) } function Get-FarmSizeLabelName { $nm = "BlueStacks" try { $u = $script:farmUi if ($u -and $u.sizeName -and $u.sizeName.Text) { $nm = [string]$u.sizeName.Text.Trim() } } catch {} if (-not $nm) { try { $nm = [string]$script:farmBox.sizeName } catch { $nm = "" } } if (-not $nm) { $nm = "BlueStacks" } return $nm } function Find-FarmGameHwnd { $title = "" try { $title = [string]$script:farmBox.winTitle } catch {} $h = [IntPtr]::Zero $targetPid = 0 try { $targetPid = [int]$script:farmBox.targetPid } catch { $targetPid = 0 } if ($targetPid -gt 0) { try { $targetProc = Get-Process -Id $targetPid -ErrorAction Stop if ($targetProc.MainWindowHandle -ne 0) { $h = [IntPtr]$targetProc.MainWindowHandle } } catch { $h = [IntPtr]::Zero } } if ($h -eq [IntPtr]::Zero) { $targetId = "" try { $targetId = [string]$script:farmBox.targetInstance } catch {} if ($targetId) { try { foreach ($instanceRow in @(Get-BlueStacksInstanceCatalog)) { if ([string]$instanceRow.id -eq $targetId -and [long]$instanceRow.hwnd -ne 0) { $h = [IntPtr][long]$instanceRow.hwnd $script:farmBox.targetPid = [int]$instanceRow.pid break } } } catch {} } } if ($h -eq [IntPtr]::Zero -and $title) { try { $h = [RtFarmGeom]::FindTitleContains($title) } catch { $h = [IntPtr]::Zero } if ($h -ne [IntPtr]::Zero) { try { $actualTitle = New-Object Text.StringBuilder 512 [void][RtFarmGeom]::GetWindowText($h, $actualTitle, 512) if ($actualTitle.ToString() -match '(?i)keymap overlay|bluestacks-services') { $h = [IntPtr]::Zero } } catch {} } } if ($h -eq [IntPtr]::Zero) { try { foreach ($procName in @("HD-Player", "Bluestacks")) { $proc = Get-Process -Name $procName -ErrorAction SilentlyContinue | Where-Object { $_.MainWindowHandle -ne 0 } | Select-Object -First 1 if ($proc) { $h = [IntPtr]$proc.MainWindowHandle; break } } } catch { $h = [IntPtr]::Zero } } if ($h -eq [IntPtr]::Zero) { try { $h = [RtFarmGeom]::FindTitleContains("BlueStacks") } catch { $h = [IntPtr]::Zero } } if ($h -eq [IntPtr]::Zero) { try { $h = [RtFarmGeom]::FindTitleContains("HD-Player") } catch { $h = [IntPtr]::Zero } } return $h } function Get-BlueStacksPlayerPath { $dirs = New-Object System.Collections.ArrayList foreach ($key in @( "HKLM:\SOFTWARE\BlueStacks_nxt", "HKLM:\SOFTWARE\BlueStacks", "HKLM:\SOFTWARE\WOW6432Node\BlueStacks_nxt", "HKLM:\SOFTWARE\WOW6432Node\BlueStacks", "HKCU:\SOFTWARE\BlueStacks_nxt", "HKCU:\SOFTWARE\BlueStacks" )) { foreach ($name in @("InstallDir", "UserDefinedDir", "DataDir")) { try { $v = [string](Get-ItemProperty -LiteralPath $key -Name $name -ErrorAction Stop).$name if ($v) { [void]$dirs.Add($v) } } catch {} } } foreach ($dir in @($dirs)) { foreach ($name in @("HD-Player.exe", "Bluestacks.exe")) { foreach ($p in @((Join-Path $dir $name), (Join-Path $dir ("Client\" + $name)))) { if ($p -and (Test-Path -LiteralPath $p)) { return $p } } } } foreach ($p in @( "${env:ProgramFiles}\BlueStacks_nxt\HD-Player.exe", "${env:ProgramFiles(x86)}\BlueStacks_nxt\HD-Player.exe", "${env:ProgramFiles}\BlueStacks\HD-Player.exe", "${env:ProgramFiles(x86)}\BlueStacks\HD-Player.exe", "${env:ProgramFiles}\BlueStacks_msi5\HD-Player.exe", "${env:ProgramFiles(x86)}\BlueStacks_msi5\HD-Player.exe", "$env:LOCALAPPDATA\BlueStacks_nxt\HD-Player.exe", "$env:LOCALAPPDATA\BlueStacks\HD-Player.exe", "$env:ProgramData\BlueStacks_nxt\HD-Player.exe" )) { if ($p -and (Test-Path -LiteralPath $p)) { return $p } } return "" } function Get-FarmInstancesPath { return (Join-Path $root "farm-instances.json") } function Read-FarmInstancePlan { $p = Get-FarmInstancesPath foreach ($tryPath in @($p, ($p + ".bak"))) { if (-not (Test-Path -LiteralPath $tryPath)) { continue } try { $j = Get-Content -LiteralPath $tryPath -Raw -Encoding UTF8 | ConvertFrom-Json if ($j) { return $j } } catch {} } return [pscustomobject]@{ schemaVersion = 1 desiredCount = 2 ramGB = 2 diskGB = 12 enabledIds = @() activeId = "" playlistById = [pscustomobject]@{} layoutById = [pscustomobject]@{} } } function Write-FarmInstancePlan($plan) { $p = Get-FarmInstancesPath $tmp = $p + ".tmp" $bak = $p + ".bak" ConvertTo-Json -InputObject $plan -Depth 8 | Set-Content -LiteralPath $tmp -Encoding UTF8 if (Test-Path -LiteralPath $p) { Copy-Item -LiteralPath $p -Destination $bak -Force } Move-Item -LiteralPath $tmp -Destination $p -Force Copy-Item -LiteralPath $p -Destination $bak -Force } function Get-FarmInstancePlaylistType([string]$instanceId) { if (-not $instanceId) { return "" } try { $map = (Read-FarmInstancePlan).playlistById if ($map) { $prop = $map.PSObject.Properties | Where-Object { [string]$_.Name -eq $instanceId } | Select-Object -First 1 if ($prop) { return [string]$prop.Value } } } catch {} return "" } function Set-FarmInstancePlaylistType([string]$instanceId, [string]$typeId) { if (-not $instanceId -or -not $typeId) { return $false } $plan = Read-FarmInstancePlan $map = @{} try { if ($plan.playlistById) { foreach ($prop in $plan.playlistById.PSObject.Properties) { $map[[string]$prop.Name] = [string]$prop.Value } } } catch {} $map[$instanceId] = $typeId if ($plan.PSObject.Properties["playlistById"]) { $plan.playlistById = [pscustomobject]$map } else { $plan | Add-Member -NotePropertyName playlistById -NotePropertyValue ([pscustomobject]$map) } Write-FarmInstancePlan $plan return $true } function Find-FarmHdPlayerForLabel([string]$label, $knownLabels) { if (-not $label) { return $null } $players = @(Get-Process -Name HD-Player -ErrorAction SilentlyContinue | Where-Object { $_.MainWindowHandle -ne 0 }) $exact = $players | Where-Object { [string]$_.MainWindowTitle -eq $label } | Select-Object -First 1 if ($exact) { return $exact } $others = @($knownLabels | Where-Object { $_ -and $_ -ne $label -and $_.Length -gt $label.Length }) foreach ($p in $players) { $title = [string]$p.MainWindowTitle if (-not $title.StartsWith($label)) { continue } $stolen = $false foreach ($other in $others) { if ($title -eq $other -or $title.StartsWith($other)) { $stolen = $true; break } } if (-not $stolen) { return $p } } return $null } function Get-FarmPlaylistTypeLabel([string]$typeId) { foreach ($type in @(Get-FarmPlaylistTypes)) { if ([string]$type.id -eq $typeId) { return [string]$type.label } } return $(if ($typeId) { $typeId } else { "current numbered list" }) } function Get-FarmInstanceLayoutMap { $map = @{} try { $plan = Read-FarmInstancePlan $raw = $null try { $raw = $plan.layoutById } catch {} if ($raw) { $items = @($raw) $looksLikeRows = $false try { if ($null -ne $items[0].id) { $looksLikeRows = $true } } catch {} if ($looksLikeRows) { foreach ($v in $items) { $id = [string]$v.id $w = 0; $h = 0 try { $w = [int]$v.w } catch {} try { $h = [int]$v.h } catch {} if ($id -and $w -ge 40 -and $h -ge 40) { $map[$id] = [pscustomobject]@{ x = [int]$v.x; y = [int]$v.y; w = $w; h = $h } } } } else { foreach ($prop in $raw.PSObject.Properties) { $v = $prop.Value $x = 0; $y = 0; $w = 0; $h = 0 try { $x = [int]$v.x } catch {} try { $y = [int]$v.y } catch {} try { $w = [int]$v.w } catch {} try { $h = [int]$v.h } catch {} if ($w -ge 40 -and $h -ge 40) { $map[[string]$prop.Name] = [pscustomobject]@{ x = $x; y = $y; w = $w; h = $h } } } } } } catch {} return $map } function Get-FarmInstanceLayout([string]$instanceId) { if (-not $instanceId) { return $null } $map = Get-FarmInstanceLayoutMap if ($map.ContainsKey($instanceId)) { return $map[$instanceId] } return $null } function Write-FarmInstanceLayoutMap($layoutMap) { $plan = Read-FarmInstancePlan $rows = New-Object System.Collections.ArrayList foreach ($key in @($layoutMap.Keys)) { $v = $layoutMap[$key] [void]$rows.Add([pscustomobject]@{ id = [string]$key x = [int]$v.x y = [int]$v.y w = [int]$v.w h = [int]$v.h }) } if ($plan.PSObject.Properties["layoutById"]) { $plan.layoutById = @($rows) } else { $plan | Add-Member -NotePropertyName layoutById -NotePropertyValue @($rows) } Write-FarmInstancePlan $plan } function Save-FarmInstanceLayoutsFromWindows($targetIds, [switch]$Quiet) { $ids = @() if ($null -ne $targetIds) { $ids = @($targetIds | Where-Object { $_ }) } if ($ids.Count -lt 1) { $ids = @(Get-FarmEnabledInstanceIds) } $catalog = @(Get-BlueStacksInstanceCatalog) $map = Get-FarmInstanceLayoutMap $saved = 0 foreach ($row in $catalog) { if ($ids.Count -gt 0 -and $ids -notcontains [string]$row.id) { continue } $hwnd = [long]$row.hwnd if ($hwnd -eq 0) { try { $known = @($catalog | ForEach-Object { [string]$_.label }) $gp = Find-FarmHdPlayerForLabel ([string]$row.label) $known if ($gp) { $hwnd = [long]$gp.MainWindowHandle } } catch {} } if ($hwnd -eq 0) { continue } try { $wr = New-Object RtFarmGeom+RECT $hPtr = [IntPtr][int64]$hwnd [void][RtFarmGeom]::GetWindowRect($hPtr, [ref]$wr) $w = [int]$wr.Right - [int]$wr.Left $h = [int]$wr.Bottom - [int]$wr.Top if ($w -lt 40 -or $h -lt 40) { try { Add-Type -AssemblyName UIAutomationClient -ErrorAction SilentlyContinue $el = [System.Windows.Automation.AutomationElement]::FromHandle($hPtr) $br = $el.Current.BoundingRectangle $wr.Left = [int]$br.Left $wr.Top = [int]$br.Top $wr.Right = [int]$br.Right $wr.Bottom = [int]$br.Bottom $w = [int]$br.Width $h = [int]$br.Height } catch {} } if ($w -lt 40 -or $h -lt 40) { continue } $map[[string]$row.id] = [pscustomobject]@{ x = [int]$wr.Left; y = [int]$wr.Top; w = $w; h = $h } $saved++ } catch {} } if ($saved -lt 1) { try { Write-HelperCrashLog ("save screen sizes found 0 windows; catalog=" + ($catalog | ForEach-Object { [string]$_.id + ":" + [string]$_.hwnd } | Out-String).Trim()) } catch {} if (-not $Quiet) { Set-FarmStatus "Open the BlueStacks screens, place them where you want, then Save screen sizes." } return $false } Write-FarmInstanceLayoutMap $map try { [void](Set-BlueStacksSplitLayoutConfig @($map.Keys) $map.Count) } catch {} if (-not $Quiet) { Set-FarmStatus ("Saved size + location for " + $saved + " BlueStacks screen(s). Start split view puts them back there next time.") } return $true } function Get-BlueStacksConfPath { foreach ($key in @("HKLM:\SOFTWARE\BlueStacks_nxt", "HKLM:\SOFTWARE\WOW6432Node\BlueStacks_nxt")) { foreach ($name in @("DataDir", "UserDefinedDir", "InstallDir")) { try { $dir = [string](Get-ItemProperty -LiteralPath $key -Name $name -ErrorAction Stop).$name $p = Join-Path $dir "bluestacks.conf" if (Test-Path -LiteralPath $p) { return $p } } catch {} } } $fallback = Join-Path $env:ProgramData "BlueStacks_nxt\bluestacks.conf" if (Test-Path -LiteralPath $fallback) { return $fallback } return "" } function Get-BlueStacksInstanceCatalog { $rows = @{} $conf = Get-BlueStacksConfPath if ($conf) { try { foreach ($line in @(Get-Content -LiteralPath $conf -Encoding UTF8)) { if ($line -notmatch '^bst\.instance\.([^.]+)\.(display_name|ram|cpus|status\.adb_port)="(.*)"$') { continue } $id = [string]$Matches[1] $key = [string]$Matches[2] $value = [string]$Matches[3] if (-not $rows.ContainsKey($id)) { $rows[$id] = [ordered]@{ id = $id; label = $id; ramMB = 0; cpus = 0; adbPort = 0; pid = 0; hwnd = 0 } } if ($key -eq "display_name" -and $value) { $rows[$id].label = $value } elseif ($key -eq "ram") { try { $rows[$id].ramMB = [int]$value } catch {} } elseif ($key -eq "cpus") { try { $rows[$id].cpus = [int]$value } catch {} } elseif ($key -eq "status.adb_port") { try { $rows[$id].adbPort = [int]$value } catch {} } } } catch {} } try { foreach ($proc in @(Get-CimInstance Win32_Process -Filter "Name='HD-Player.exe'" -ErrorAction SilentlyContinue)) { $id = "" $cmd = [string]$proc.CommandLine if ($cmd -match '(?i)--instance(?:=|\s+)"?([^"\s]+)') { $id = [string]$Matches[1] } if (-not $id) { try { $gpByTitle = Get-Process -Id ([int]$proc.ProcessId) -ErrorAction Stop $windowTitle = [string]$gpByTitle.MainWindowTitle $labels = @($rows.Keys | ForEach-Object { [string]$rows[$_].label }) foreach ($knownId in @($rows.Keys)) { $lab = [string]$rows[$knownId].label if (-not $windowTitle -or -not $lab) { continue } if ($windowTitle -eq $lab -or $windowTitle.StartsWith($lab)) { $stolen = $false foreach ($other in $labels) { if ($other -ne $lab -and $other.Length -gt $lab.Length -and ($windowTitle -eq $other -or $windowTitle.StartsWith($other))) { $stolen = $true; break } } if (-not $stolen) { $id = [string]$knownId; break } } } } catch {} } if (-not $id -and $rows.Count -eq 1) { $id = [string](@($rows.Keys)[0]) } if (-not $id) { continue } if (-not $rows.ContainsKey($id)) { $rows[$id] = [ordered]@{ id = $id; label = $id; ramMB = 0; cpus = 0; adbPort = 0; pid = 0; hwnd = 0 } } $rows[$id].pid = [int]$proc.ProcessId try { $gp = Get-Process -Id ([int]$proc.ProcessId) -ErrorAction Stop $rows[$id].hwnd = [long]$gp.MainWindowHandle } catch {} } } catch {} try { $labels = @($rows.Keys | ForEach-Object { [string]$rows[$_].label }) foreach ($knownId in @($rows.Keys)) { $gp = Find-FarmHdPlayerForLabel ([string]$rows[$knownId].label) $labels if (-not $gp) { continue } if ([int]$rows[$knownId].pid -eq 0) { $rows[$knownId].pid = [int]$gp.Id } if ([long]$rows[$knownId].hwnd -eq 0) { $rows[$knownId].hwnd = [long]$gp.MainWindowHandle } } } catch {} $out = New-Object System.Collections.ArrayList foreach ($id in @($rows.Keys | Sort-Object)) { [void]$out.Add([pscustomobject]$rows[$id]) } return @($out) } function Get-FarmHostCapacity($ramPerInstance, $diskPerInstance) { $ram = 2 $disk = 12 try { $ram = [int]$ramPerInstance } catch {} try { $disk = [int]$diskPerInstance } catch {} if ($ram -lt 1) { $ram = 1 } if ($disk -lt 1) { $disk = 1 } $totalGB = 0.0 $freeRamGB = 0.0 $logical = 1 $freeDiskGB = 0.0 try { $cs = Get-CimInstance Win32_ComputerSystem -ErrorAction Stop $totalGB = [Math]::Round([double]$cs.TotalPhysicalMemory / 1GB, 1) } catch {} try { $os = Get-CimInstance Win32_OperatingSystem -ErrorAction Stop $freeRamGB = [Math]::Round(([double]$os.FreePhysicalMemory * 1KB) / 1GB, 1) } catch {} try { $logical = [int]((Get-CimInstance Win32_Processor -ErrorAction Stop | Measure-Object NumberOfLogicalProcessors -Sum).Sum) } catch {} try { $drive = [IO.Path]::GetPathRoot((Get-BlueStacksConfPath)) if (-not $drive) { $drive = [IO.Path]::GetPathRoot($root) } $device = $drive.TrimEnd('\') $d = Get-CimInstance Win32_LogicalDisk -Filter ("DeviceID='" + $device + "'") -ErrorAction Stop $freeDiskGB = [Math]::Round([double]$d.FreeSpace / 1GB, 1) } catch {} $byCpu = [Math]::Max(1, [Math]::Floor(([Math]::Max(1, $logical - 2)) / 2.0)) $byRam = [Math]::Max(1, [Math]::Floor(([Math]::Max(1, $totalGB - 6)) / [double]$ram)) $byDisk = [Math]::Max(1, [Math]::Floor([Math]::Max(1, $freeDiskGB - 12) / [double]$disk)) $safe = [int][Math]::Min([int]$script:FarmMaxInstances, [Math]::Min($byCpu, [Math]::Min($byRam, $byDisk))) $limit = "CPU" if ($byRam -le $byCpu -and $byRam -le $byDisk) { $limit = "RAM" } elseif ($byDisk -le $byCpu -and $byDisk -le $byRam) { $limit = "disk" } return [pscustomobject]@{ totalRamGB = $totalGB availableRamGB = $freeRamGB logicalCpu = $logical freeDiskGB = $freeDiskGB safeCount = $safe byCpu = [int]$byCpu byRam = [int]$byRam byDisk = [int]$byDisk limitName = $limit ramPerGB = [int]$ram diskPerGB = [int]$disk } } function Get-FarmRecommendForCount([int]$count, [int]$ramPer) { if ($count -lt 1) { $count = 1 } if ($ramPer -lt 1) { $ramPer = 2 } $needRam = ($count * $ramPer) + 6 $needCpu = ($count * 2) + 2 return [pscustomobject]@{ count = $count ramGB = $needRam logicalCpu = $needCpu ramPerGB = $ramPer } } function Format-FarmRecommendText($need) { if (-not $need) { return "" } $n = [int]$need.count $ramEach = [int]$need.ramPerGB return ("Recommended PC for " + $n + " screen(s): " + [int]$need.ramGB + " GB of RAM or more (" + $n + " x " + $ramEach + " GB plus 6 GB for Windows), and a processor with at least " + [int]$need.logicalCpu + " CPU threads (2 threads per screen plus 2 for Windows).") } function Get-FarmUiPlanNumbers { $count = 2 $ram = 2 $disk = 12 try { $count = [int]$script:farmUi.instanceCount.Value } catch { try { $count = [int](Read-FarmInstancePlan).desiredCount } catch {} } try { $ram = [int]$script:farmUi.instanceRam.Value } catch { try { $ram = [int](Read-FarmInstancePlan).ramGB } catch {} } try { $disk = [int]$script:farmUi.instanceDisk.Value } catch { try { $disk = [int](Read-FarmInstancePlan).diskGB } catch {} } if ($count -lt 1) { $count = 1 } if ($count -gt [int]$script:FarmMaxInstances) { $count = [int]$script:FarmMaxInstances } if ($ram -lt 1) { $ram = 2 } if ($disk -lt 1) { $disk = 12 } return [pscustomobject]@{ count = $count; ramGB = $ram; diskGB = $disk } } function Test-FarmShouldRunOneAtATime { $nums = Get-FarmUiPlanNumbers $cap = Get-FarmHostCapacity $nums.ramGB $nums.diskGB $enabled = 0 try { $enabled = @($(Get-FarmEnabledInstanceIds)).Count } catch {} $n = [int]$nums.count if ($enabled -gt $n) { $n = $enabled } if ($n -gt [int]$script:FarmSplitMax) { return $true } if ($n -gt [int]$cap.safeCount) { return $true } return $false } function Get-FarmOverCapacityMessage { $nums = Get-FarmUiPlanNumbers $cap = Get-FarmHostCapacity $nums.ramGB $nums.diskGB $need = Get-FarmRecommendForCount ([int]$nums.count) ([int]$nums.ramGB) $short = New-Object System.Collections.ArrayList if ([int]$nums.count -gt [int]$cap.byCpu) { [void]$short.Add("CPU (" + $cap.logicalCpu + " threads here; about " + $cap.byCpu + " screens is the CPU limit)") } if ([int]$nums.count -gt [int]$cap.byRam) { [void]$short.Add("RAM (" + $cap.totalRamGB + " GB here; about " + $cap.byRam + " screens is the RAM limit)") } if ([int]$nums.count -gt [int]$cap.byDisk) { [void]$short.Add("disk (" + $cap.freeDiskGB + " GB free; about " + $cap.byDisk + " screens is the disk limit)") } if ($short.Count -lt 1) { return "" } return ("WARNING: this PC cannot support " + $nums.count + " BlueStacks screens at the same time. You are short on " + ($short -join "; ") + ". Auto Farm will open and farm one screen at a time so the PC is not overloaded. " + (Format-FarmRecommendText $need)) } function Get-FarmEnabledInstanceIds { $ids = New-Object System.Collections.ArrayList $box = $null try { if ($script:farmUi) { $box = $script:farmUi.instanceList } } catch {} if ($box) { foreach ($i in @($box.CheckedIndices)) { try { $row = @($script:farmInstanceCatalog)[[int]$i] if ($row -and $row.id) { [void]$ids.Add([string]$row.id) } } catch {} } } else { try { foreach ($id in @((Read-FarmInstancePlan).enabledIds)) { if ($id) { [void]$ids.Add([string]$id) } } } catch {} } return @($ids | Select-Object -Unique) } function Get-FarmSelectedInstance { $box = $null try { if ($script:farmUi) { $box = $script:farmUi.instanceList } } catch {} $i = -1 try { $i = [int]$box.SelectedIndex } catch {} $all = @($script:farmInstanceCatalog) if ($i -ge 0 -and $i -lt $all.Count) { return $all[$i] } return $null } function Refresh-FarmInstanceList { $box = $null try { if ($script:farmUi) { $box = $script:farmUi.instanceList } } catch {} if (-not $box) { return } $plan = Read-FarmInstancePlan $enabled = @($plan.enabledIds) $script:farmInstanceCatalog = @(Get-BlueStacksInstanceCatalog) if ($enabled.Count -lt 1) { $take = 2 try { $take = [int]$plan.desiredCount } catch {} if ($take -lt 1) { $take = 1 } if ($take -gt [int]$script:FarmMaxInstances) { $take = [int]$script:FarmMaxInstances } $enabled = @($script:farmInstanceCatalog | Select-Object -First $take | ForEach-Object { [string]$_.id }) } $box.Items.Clear() for ($i = 0; $i -lt $script:farmInstanceCatalog.Count; $i++) { $row = $script:farmInstanceCatalog[$i] $state = $(if ([long]$row.hwnd -ne 0) { "running" } else { "stopped" }) $typeId = Get-FarmInstancePlaylistType ([string]$row.id) $screenPick = Get-FarmScreenPlaylist ([string]$row.id) $farmLabel = "no list yet" if ($screenPick) { $rc = 0 try { $rc = @($screenPick.rows).Count } catch {} $farmLabel = $rc.ToString() + " steps saved" } if ($typeId) { $farmLabel = $farmLabel + " / " + (Get-FarmPlaylistTypeLabel $typeId) } $text = "Screen " + ($i + 1) + ": " + [string]$row.label + " [" + [string]$row.id + "] " + $state + " - " + $farmLabel [void]$box.Items.Add($text, ($enabled -contains [string]$row.id)) } if ($box.Items.Count -gt 0 -and $box.SelectedIndex -lt 0) { $box.SelectedIndex = 0 } try { Update-FarmInstanceCapacity } catch {} try { Refresh-FarmPlaylistScreenBoxes } catch {} } function Save-FarmInstancePlanFromUi { $old = Read-FarmInstancePlan $count = 2 $ram = 2 $disk = 12 try { $count = [int]$script:farmUi.instanceCount.Value } catch {} try { $ram = [int]$script:farmUi.instanceRam.Value } catch {} try { $disk = [int]$script:farmUi.instanceDisk.Value } catch {} if ($count -lt 2) { $count = 2 } if ($count -gt [int]$script:FarmMaxInstances) { $count = [int]$script:FarmMaxInstances } $active = "" try { $active = [string]$script:farmBox.targetInstance } catch {} $playlistById = [pscustomobject]@{} try { if ($old.playlistById) { $playlistById = $old.playlistById } } catch {} $layoutById = [pscustomobject]@{} try { if ($old.layoutById) { $layoutById = $old.layoutById } } catch {} $plan = [pscustomobject]@{ schemaVersion = 1 desiredCount = $count ramGB = $ram diskGB = $disk enabledIds = @(Get-FarmEnabledInstanceIds) activeId = $active playlistById = $playlistById layoutById = $layoutById } Write-FarmInstancePlan $plan try { Set-BlueStacksInstanceResources @($plan.enabledIds) $ram 2 } catch {} Update-FarmInstanceCapacity $warn = Get-FarmOverCapacityMessage if ($warn) { Set-FarmStatus ("Saved the BlueStacks instance plan. " + $warn) } else { Set-FarmStatus "Saved the BlueStacks instance plan. RAM applies when those instances restart; disk is a capacity budget." } } function Set-BlueStacksInstanceResources($instanceIds, [int]$ramGB, [int]$cpus) { $conf = Get-BlueStacksConfPath if (-not $conf -or -not (Test-Path -LiteralPath $conf)) { return $false } if ($ramGB -lt 2) { $ramGB = 2 } if ($cpus -lt 1) { $cpus = 1 } $text = [IO.File]::ReadAllText($conf) $changed = $false foreach ($id in @($instanceIds)) { if (-not $id) { continue } $esc = [regex]::Escape([string]$id) $ramLine = 'bst.instance.' + [string]$id + '.ram="' + ($ramGB * 1024) + '"' $cpuLine = 'bst.instance.' + [string]$id + '.cpus="' + $cpus + '"' $ramPattern = '(?m)^bst\.instance\.' + $esc + '\.ram="[^"]*"$' $cpuPattern = '(?m)^bst\.instance\.' + $esc + '\.cpus="[^"]*"$' if ([regex]::IsMatch($text, $ramPattern)) { $text = [regex]::Replace($text, $ramPattern, $ramLine); $changed = $true } if ([regex]::IsMatch($text, $cpuPattern)) { $text = [regex]::Replace($text, $cpuPattern, $cpuLine); $changed = $true } } if (-not $changed) { return $false } $bak = $conf + ".raidstimer.bak" $tmp = $conf + ".raidstimer.tmp" Copy-Item -LiteralPath $conf -Destination $bak -Force [IO.File]::WriteAllText($tmp, $text, (New-Object Text.UTF8Encoding($false))) Move-Item -LiteralPath $tmp -Destination $conf -Force return $true } function Update-FarmInstanceCapacity { $u = $script:farmUi if (-not $u -or -not $u.instanceCapacity) { return } $nums = Get-FarmUiPlanNumbers $count = [int]$nums.count $ram = [int]$nums.ramGB $disk = [int]$nums.diskGB $cap = Get-FarmHostCapacity $ram $disk $need = Get-FarmRecommendForCount $count $ram $ramNeed = $count * $ram $diskNeed = $count * $disk try { $u.instanceRamGraph.Maximum = [Math]::Max(1, [int][Math]::Ceiling($cap.totalRamGB)) $u.instanceRamGraph.Value = [Math]::Min($u.instanceRamGraph.Maximum, $ramNeed) $u.instanceDiskGraph.Maximum = [Math]::Max(1, [int][Math]::Ceiling($cap.freeDiskGB)) $u.instanceDiskGraph.Value = [Math]::Min($u.instanceDiskGraph.Maximum, $diskNeed) } catch {} $verdict = "Safe simultaneous count on this PC: " + $cap.safeCount + " (" + $cap.limitName + " limited)." if ($count -le $cap.safeCount) { $verdict = "Safe for " + $count + " at once. " + $verdict } else { $verdict = "WARNING: " + $count + " is more than this PC can run at once. You are out of " + $cap.limitName + " for that many. Auto Farm will open and farm one screen at a time. " + $verdict } $u.instanceCapacity.Text = "PC: " + $cap.logicalCpu + " CPU threads, " + $cap.totalRamGB + " GB RAM (" + $cap.availableRamGB + " free), " + $cap.freeDiskGB + " GB disk free. " + $verdict try { if ($u.instanceNeed) { $u.instanceNeed.Text = Format-FarmRecommendText $need } } catch {} } function Start-FarmBlueStacksInstance([string]$instanceId) { if (-not $instanceId) { return $false } foreach ($row in @(Get-BlueStacksInstanceCatalog)) { if ([string]$row.id -eq $instanceId -and [long]$row.hwnd -ne 0) { return $true } } $player = Get-BlueStacksPlayerPath if (-not $player) { return $false } try { Start-Process -FilePath $player -ArgumentList @("--instance", $instanceId) | Out-Null return $true } catch { return $false } } function Stop-FarmBlueStacksInstance([string]$instanceId) { if (-not $instanceId) { return } foreach ($row in @(Get-BlueStacksInstanceCatalog)) { if ([string]$row.id -ne $instanceId) { continue } $pid = 0 try { $pid = [int]$row.pid } catch {} if ($pid -lt 1) { continue } try { [void](Get-Process -Id $pid -ErrorAction Stop).CloseMainWindow() } catch {} } } function Get-FarmCatalogRowById([string]$instanceId) { if (-not $instanceId) { return $null } foreach ($row in @(Get-BlueStacksInstanceCatalog)) { if ([string]$row.id -eq $instanceId) { return $row } } return $null } function Start-FarmLaunchCheckedInstances { $ids = @(Get-FarmEnabledInstanceIds) if ($ids.Count -lt 1) { Set-FarmStatus "Check at least one instance first."; return } if ($ids.Count -gt [int]$script:FarmMaxInstances) { $ids = @($ids | Select-Object -First ([int]$script:FarmMaxInstances)) } $warn = Get-FarmOverCapacityMessage if (Test-FarmShouldRunOneAtATime) { $pick = $null foreach ($id in $ids) { $row = Get-FarmCatalogRowById ([string]$id) if ($row -and [long]$row.hwnd -eq 0) { $pick = $row; break } } if (-not $pick) { $msg = "A checked BlueStacks screen is already open. Close it before opening the next one. With this many screens, the helper opens one at a time." if ($warn) { $msg = $msg + " " + $warn } Set-FarmStatus $msg return } foreach ($id in $ids) { if ([string]$id -ne [string]$pick.id) { Stop-FarmBlueStacksInstance ([string]$id) } } [void](Start-FarmBlueStacksInstance ([string]$pick.id)) $msg = "Opening one at a time. Launched " + [string]$pick.label + ". Farm or close that screen before launching the next. Use Run checked in order to farm each screen in turn." if ($warn) { $msg = $msg + " " + $warn } Set-FarmStatus $msg return } foreach ($id in $ids) { [void](Start-FarmBlueStacksInstance $id) } Set-FarmStatus ("Launching " + $ids.Count + " checked instance(s). Press Refresh when they finish opening.") } function Open-FarmBlueStacksManager { $player = Get-BlueStacksPlayerPath if (-not $player) { Set-FarmStatus "BlueStacks was not found."; return } $mgr = Join-Path (Split-Path -Parent $player) "HD-MultiInstanceManager.exe" if (-not (Test-Path -LiteralPath $mgr)) { Set-FarmStatus "BlueStacks Multi-instance Manager was not found."; return } try { Start-Process -FilePath $mgr | Out-Null Set-FarmStatus "BlueStacks Multi-instance Manager opened. Create enough instances, then press Refresh." } catch { Set-FarmStatus "Could not open BlueStacks Multi-instance Manager." } } function Set-FarmTargetInstance($row) { if (-not $row) { return $false } $fresh = $null foreach ($one in @(Get-BlueStacksInstanceCatalog)) { if ([string]$one.id -eq [string]$row.id) { $fresh = $one; break } } if (-not $fresh -or [long]$fresh.hwnd -eq 0) { Set-FarmStatus "That BlueStacks instance is not running. Launch it first." return $false } $script:farmBox.targetInstance = [string]$fresh.id $script:farmBox.targetPid = [int]$fresh.pid $script:farmBox.winTitle = [string]$fresh.label $h = [IntPtr][long]$fresh.hwnd try { $wr = New-Object RtFarmGeom+RECT [void][RtFarmGeom]::GetWindowRect($h, [ref]$wr) $script:farmBox.sightX = [int]$wr.Left $script:farmBox.sightY = [int]$wr.Top $script:farmBox.sightW = [int]($wr.Right - $wr.Left) $script:farmBox.sightH = [int]($wr.Bottom - $wr.Top) } catch {} try { $plan = Read-FarmInstancePlan $plan.activeId = [string]$fresh.id Write-FarmInstancePlan $plan } catch {} $screenNumber = 0 for ($i = 0; $i -lt @($script:farmInstanceCatalog).Count; $i++) { if ([string]$script:farmInstanceCatalog[$i].id -eq [string]$fresh.id) { $screenNumber = $i + 1; break } } $screenText = $(if ($screenNumber -gt 0) { "screen " + $screenNumber + " - " } else { "" }) Set-FarmStatus ("Multi-screen mode target: " + $screenText + [string]$fresh.label + ". Clicks and keys now stay on that BlueStacks screen.") return $true } function Assign-FarmPlaylistToSelectedInstance { $row = Get-FarmSelectedInstance if (-not $row) { Set-FarmStatus "Select a numbered BlueStacks screen first."; return $false } $typeId = Get-FarmPlaylistTypeId if (-not (Set-FarmInstancePlaylistType ([string]$row.id) $typeId)) { Set-FarmStatus "Could not assign that saved list to the selected screen." return $false } $screenNumber = [int]$script:farmUi.instanceList.SelectedIndex + 1 Refresh-FarmInstanceList try { $script:farmUi.instanceList.SelectedIndex = $screenNumber - 1 } catch {} Set-FarmStatus ("Screen " + $screenNumber + " will use " + (Get-FarmPlaylistTypeLabel $typeId) + ".") return $true } function Start-FarmSelectedInstance { $row = Get-FarmSelectedInstance if (-not $row) { Set-FarmStatus "Select a numbered BlueStacks screen first."; return $false } if (-not (Set-FarmTargetInstance $row)) { return $false } if (-not (Load-FarmPlaylistForInstance ([string]$row.id))) { return $false } Reset-FarmPlayToNumberOne Hide-HelperOverGame if (-not (Farm-PlayNow)) { Restore-FarmWindow return $false } return $true } function Move-FarmInstanceWindow($row, [int]$x, [int]$y, [int]$w, [int]$hgt) { if (-not $row -or [long]$row.hwnd -eq 0) { return $false } $h = [IntPtr][long]$row.hwnd try { if ([RtFarmGeom]::IsIconic($h) -or [RtFarmGeom]::IsZoomed($h)) { [void][RtFarmGeom]::ShowWindow($h, 9); Start-Sleep -Milliseconds 100 } } catch {} $wr = New-Object RtFarmGeom+RECT try { [void][RtFarmGeom]::SetWindowPos($h, [IntPtr]::Zero, $x, $y, $w, $hgt, 0x0014) Start-Sleep -Milliseconds 180 [void][RtFarmGeom]::GetWindowRect($h, [ref]$wr) } catch { return $false } $oldCursor = New-Object RtFarmMouse+POINT $haveCursor = $false try { $haveCursor = [RtFarmMouse]::GetCursorPos([ref]$oldCursor) } catch {} for ($attempt = 0; $attempt -lt 5; $attempt++) { [void][RtFarmGeom]::GetWindowRect($h, [ref]$wr) $dx = $x - [int]$wr.Left $dy = $y - [int]$wr.Top if ([Math]::Abs($dx) -le 3 -and [Math]::Abs($dy) -le 3) { break } $sx = [int]$wr.Left + [int][Math]::Round((([int]$wr.Right - [int]$wr.Left) * 0.65)) $sy = [int]$wr.Top + 30 try { [RtFarmGrab]::Focus($h) } catch {} [void][RtFarmMouse]::SetCursorPos($sx, $sy) Start-Sleep -Milliseconds 70 [RtFarmMouse]::Down() for ($step = 1; $step -le 8; $step++) { [void][RtFarmMouse]::SetCursorPos(($sx + [int][Math]::Round($dx * $step / 8.0)), ($sy + [int][Math]::Round($dy * $step / 8.0))) Start-Sleep -Milliseconds 22 } [RtFarmMouse]::Up() Start-Sleep -Milliseconds 160 } if ($haveCursor) { try { [void][RtFarmMouse]::SetCursorPos([int]$oldCursor.X, [int]$oldCursor.Y) } catch {} } [void][RtFarmGeom]::GetWindowRect($h, [ref]$wr) $finalW = [int]$wr.Right - [int]$wr.Left $finalH = [int]$wr.Bottom - [int]$wr.Top return ( [Math]::Abs([int]$wr.Left - $x) -le 8 -and [Math]::Abs([int]$wr.Top - $y) -le 8 -and $finalW -le ($w + 24) -and $finalH -le ($hgt + 24) ) } function Tile-FarmInstances($targetIds) { $ids = @() if ($null -ne $targetIds) { $ids = @($targetIds | Where-Object { $_ }) } if ($ids.Count -lt 1) { $ids = @(Get-FarmEnabledInstanceIds) } $catalog = @(Get-BlueStacksInstanceCatalog) $rows = @($catalog | Where-Object { $ids -contains [string]$_.id -and [long]$_.hwnd -ne 0 } | Select-Object -First ([int]$script:FarmSplitMax)) if ($rows.Count -lt 2) { Set-FarmStatus "At least 2 BlueStacks screens must finish opening before split view can start."; return $false } $wa = [System.Windows.Forms.Screen]::PrimaryScreen.WorkingArea try { if ($script:farmForm) { $wa = [System.Windows.Forms.Screen]::FromControl($script:farmForm).WorkingArea } } catch {} $cols = 2 $rowsN = $(if ($rows.Count -le 2) { 1 } else { 2 }) $gap = 10 $tw = [int][Math]::Floor(($wa.Width - (($cols - 1) * $gap)) / $cols) $th = [int][Math]::Floor(($wa.Height - (($rowsN - 1) * $gap)) / $rowsN) $placed = 0 $usedSaved = 0 for ($i = 0; $i -lt $rows.Count; $i++) { $layout = Get-FarmInstanceLayout ([string]$rows[$i].id) if ($layout) { if (Move-FarmInstanceWindow $rows[$i] ([int]$layout.x) ([int]$layout.y) ([int]$layout.w) ([int]$layout.h)) { $placed++ } $usedSaved++ continue } $col = $i % $cols $rr = [int][Math]::Floor($i / $cols) $x = $wa.Left + ($col * ($tw + $gap)) $y = $wa.Top + ($rr * ($th + $gap)) # BlueStacks preserves its own wide aspect ratio. Asking for the full # desktop height makes it expand past the column width, so constrain the # requested height from the live window ratio before moving it. $ratio = 1.78 try { $now = New-Object RtFarmGeom+RECT [void][RtFarmGeom]::GetWindowRect([IntPtr][long]$rows[$i].hwnd, [ref]$now) $nowW = [int]$now.Right - [int]$now.Left $nowH = [int]$now.Bottom - [int]$now.Top if ($nowW -gt 0 -and $nowH -gt 0) { $ratio = [Math]::Max(1.35, [Math]::Min(2.2, $nowW / [double]$nowH)) } } catch {} $fitH = [int][Math]::Floor($tw / $ratio) if ($fitH -gt $th) { $fitH = $th } if ($fitH -lt 220) { $fitH = [Math]::Min($th, 220) } $y += [int][Math]::Max(0, [Math]::Floor(($th - $fitH) / 2)) if (Move-FarmInstanceWindow $rows[$i] $x $y $tw $fitH) { $placed++ } } if ($placed -lt $rows.Count) { Set-FarmStatus ("BlueStacks opened " + $rows.Count + " screens, but only " + $placed + " accepted the split position. Press Start split view once more after they finish loading.") return $false } try { [void](Save-FarmInstanceLayoutsFromWindows $ids -Quiet) } catch {} if ($usedSaved -gt 0) { Set-FarmStatus ("Restored the saved size + location for " + $usedSaved + " BlueStacks screen(s).") } else { Set-FarmStatus ("Tiled " + $rows.Count + " BlueStacks instances with visible dividers. Those sizes are saved for next time.") } return $true } function Set-BlueStacksSplitLayoutConfig($instanceIds, [int]$count) { $conf = Get-BlueStacksConfPath if (-not $conf -or -not (Test-Path -LiteralPath $conf)) { return $false } $wa = [System.Windows.Forms.Screen]::PrimaryScreen.WorkingArea $cols = 2 $rowsN = $(if ($count -le 2) { 1 } else { 2 }) $gap = 10 $cellW = [int][Math]::Floor(($wa.Width - $gap) / $cols) $cellH = [int][Math]::Floor(($wa.Height - (($rowsN - 1) * $gap)) / $rowsN) $saved = Get-FarmInstanceLayoutMap $text = [IO.File]::ReadAllText($conf) for ($i = 0; $i -lt @($instanceIds).Count; $i++) { $id = [string]@($instanceIds)[$i] if (-not $id) { continue } $col = $i % 2 $rr = [int][Math]::Floor($i / 2) $x = $wa.Left + ($col * ($cellW + $gap)) $y = $wa.Top + ($rr * ($cellH + $gap)) $gameH = [int][Math]::Floor(($cellW - 90) / 1.78) if ($gameH -gt ($cellH - 42)) { $gameH = $cellH - 42 } if ($gameH -lt 220) { $gameH = 220 } if ($saved.ContainsKey($id)) { $layout = $saved[$id] $x = [int]$layout.x $y = [int]$layout.y $gameH = [int]$layout.h - 42 if ($gameH -lt 220) { $gameH = [int]$layout.h } } $esc = [regex]::Escape($id) foreach ($pair in @( [pscustomobject]@{ key = "gl_win_height"; value = $gameH }, [pscustomobject]@{ key = "gl_win_x"; value = $x }, [pscustomobject]@{ key = "gl_win_y"; value = $y } )) { $pattern = '(?m)^bst\.instance\.' + $esc + '\.' + [regex]::Escape([string]$pair.key) + '="[^"]*"$' $line = 'bst.instance.' + $id + '.' + [string]$pair.key + '="' + [string]$pair.value + '"' if ([regex]::IsMatch($text, $pattern)) { $text = [regex]::Replace($text, $pattern, $line) } } } try { Copy-Item -LiteralPath $conf -Destination ($conf + ".raidstimer.split.bak") -Force [IO.File]::WriteAllText($conf, $text, (New-Object Text.UTF8Encoding($false))) return $true } catch { return $false } } function Start-FarmSplitView { $count = 2 try { $count = [int]$script:farmUi.instanceCount.Value } catch {} if ($count -lt 2) { $count = 2 } if ($count -gt [int]$script:FarmMaxInstances) { $count = [int]$script:FarmMaxInstances } $warn = Get-FarmOverCapacityMessage $catalog = @(Get-BlueStacksInstanceCatalog) if ($count -gt [int]$script:FarmSplitMax -or (Test-FarmShouldRunOneAtATime)) { if ($catalog.Count -lt 1) { Set-FarmStatus ("No BlueStacks instances were found. Use Create instances until there are " + $count + ", then open one at a time.") Open-FarmBlueStacksManager return $false } $ids = @($catalog | Select-Object -First $count | ForEach-Object { [string]$_.id }) try { Refresh-FarmInstanceList for ($i = 0; $i -lt $script:farmUi.instanceList.Items.Count; $i++) { $script:farmUi.instanceList.SetItemChecked($i, ($i -lt $count)) } Save-FarmInstancePlanFromUi } catch {} $firstId = [string]$ids[0] foreach ($id in $ids) { if ([string]$id -ne $firstId) { Stop-FarmBlueStacksInstance ([string]$id) } } [void](Start-FarmBlueStacksInstance $firstId) $first = Get-FarmCatalogRowById $firstId $label = $(if ($first) { [string]$first.label } else { $firstId }) $msg = "Opening screen 1 only (" + $label + "). Use Run checked in order to farm one screen at a time." if ($count -gt [int]$script:FarmSplitMax) { $msg = "Cannot tile " + $count + " BlueStacks screens on one desktop. " + $msg } else { $msg = "This PC cannot run " + $count + " BlueStacks screens at the same time. " + $msg } if ($warn) { $msg = $msg + " " + $warn } Set-FarmStatus $msg return $true } if ($catalog.Count -lt $count) { Set-FarmStatus ("Only " + $catalog.Count + " BlueStacks instance(s) exist. Use Create instances until there are " + $count + ", then start split view again.") Open-FarmBlueStacksManager return $false } $ids = @($catalog | Select-Object -First $count | ForEach-Object { [string]$_.id }) $runningRows = @($catalog | Where-Object { $ids -contains [string]$_.id -and [int]$_.pid -gt 0 }) if ($runningRows.Count -gt 0) { Set-FarmStatus "Restarting the selected BlueStacks screens at a split-view size..." foreach ($row in $runningRows) { try { [void](Get-Process -Id ([int]$row.pid) -ErrorAction Stop).CloseMainWindow() } catch {} } for ($wait = 0; $wait -lt 8; $wait++) { $stillOpen = @($runningRows | Where-Object { Get-Process -Id ([int]$_.pid) -ErrorAction SilentlyContinue }) if ($stillOpen.Count -lt 1) { break } Start-Sleep -Milliseconds 500 } $stillOpen = @($runningRows | Where-Object { Get-Process -Id ([int]$_.pid) -ErrorAction SilentlyContinue }) if ($stillOpen.Count -gt 0) { foreach ($row in $stillOpen) { try { Stop-Process -Id ([int]$row.pid) -Force -ErrorAction Stop } catch {} } # BlueStacks keeps its takeover mutex briefly after HD-Player exits. # Wait before relaunching or the new players immediately exit with 114. Start-Sleep -Seconds 4 } } if (-not (Set-BlueStacksSplitLayoutConfig $ids $count)) { Set-FarmStatus "Could not save the BlueStacks split-window size." return $false } try { Refresh-FarmInstanceList for ($i = 0; $i -lt $script:farmUi.instanceList.Items.Count; $i++) { $script:farmUi.instanceList.SetItemChecked($i, ($i -lt $count)) } Save-FarmInstancePlanFromUi } catch {} foreach ($id in $ids) { [void](Start-FarmBlueStacksInstance $id) } $script:farmSplitIds = @($ids) $script:farmSplitTries = 0 $script:farmSplitMode = $true try { if ($script:farmForm) { $script:farmForm.TopMost = $false } } catch {} try { if ($script:farmSplitTimer) { $script:farmSplitTimer.Stop(); $script:farmSplitTimer.Dispose() } } catch {} $script:farmSplitTimer = New-Object System.Windows.Forms.Timer $script:farmSplitTimer.Interval = 1000 $script:farmSplitTimer.Add_Tick({ $script:farmSplitTries++ $fresh = @(Get-BlueStacksInstanceCatalog) $ready = @($fresh | Where-Object { @($script:farmSplitIds) -contains [string]$_.id -and [long]$_.hwnd -ne 0 }) if ($ready.Count -ge @($script:farmSplitIds).Count) { $script:farmSplitTimer.Stop() Refresh-FarmInstanceList [void](Tile-FarmInstances @($script:farmSplitIds)) Set-FarmStatus ("Split view is ready with " + $ready.Count + " screens and visible dividers. Move the helper anywhere or press Hide helper.") } elseif ($script:farmSplitTries -ge 45) { $script:farmSplitTimer.Stop() Refresh-FarmInstanceList Set-FarmStatus ("Only " + $ready.Count + " of " + @($script:farmSplitIds).Count + " BlueStacks screens opened. Check BlueStacks, then press Start split view again.") } else { Set-FarmStatus ("Opening split view: " + $ready.Count + " of " + @($script:farmSplitIds).Count + " screens ready...") } }) $script:farmSplitTimer.Start() Set-FarmStatus ("Launching " + $count + " BlueStacks screens for split view...") return $true } function Hide-FarmControlWindow { try { if ($script:farmForm -and -not $script:farmForm.IsDisposed) { $script:farmForm.TopMost = $false $script:farmForm.Hide() } Set-FarmStatus "Helper hidden. Use the Raids Timer tray icon, then Auto Farm, to show it again." } catch {} } function Show-FarmSelectedInstanceLarge { $row = Get-FarmSelectedInstance if (-not $row -or [long]$row.hwnd -eq 0) { Set-FarmStatus "Select a running instance first."; return } try { [void][RtFarmGeom]::ShowWindow([IntPtr][long]$row.hwnd, 3) [RtFarmGrab]::Focus([IntPtr][long]$row.hwnd) [void](Set-FarmTargetInstance $row) } catch {} } function Start-FarmInstancesSequential { if ($script:farmInstanceSequence) { Set-FarmStatus "The checked-instance run is already in progress. Press Stop play before starting it again." return } $ids = @(Get-FarmEnabledInstanceIds) if ($ids.Count -gt [int]$script:FarmMaxInstances) { $ids = @($ids | Select-Object -First ([int]$script:FarmMaxInstances)) } $catalog = @(Get-BlueStacksInstanceCatalog) $byId = @{} foreach ($row in $catalog) { $byId[[string]$row.id] = $row } $queue = New-Object System.Collections.ArrayList foreach ($id in $ids) { if (-not $byId.ContainsKey([string]$id)) { continue } $row = $byId[[string]$id] if (-not (Test-FarmInstanceHasScreenList ([string]$row.id))) { $n = Get-FarmScreenNumberById ([string]$row.id) $who = $(if ($n -gt 0) { "Screen " + $n } else { [string]$row.label }) Set-FarmStatus ($who + " has no play list yet. Tick it next to the numbered list, add its pictures, then Save for screens. Run checked will not borrow another screen's images.") return } [void]$queue.Add($row) } if ($queue.Count -lt 1) { Set-FarmStatus "Check at least one BlueStacks instance first."; return } try { if ($script:farmLoop) { $script:farmSequenceOldLoop = [bool]$script:farmLoop.Checked; $script:farmLoop.Checked = $false } } catch {} $script:farmInstanceSequence = @($queue) $script:farmInstanceSequenceIndex = 0 $script:farmInstanceSequenceWaiting = $false $script:farmInstanceSequenceSawPlaying = $false $script:farmInstanceSequenceOneAtATime = [bool](Test-FarmShouldRunOneAtATime) $script:farmInstanceSequenceLaunchId = "" $script:farmInstanceSequenceLaunchTries = 0 $script:farmInstanceSequenceCooldown = 0 $warn = Get-FarmOverCapacityMessage $mode = $(if ($script:farmInstanceSequenceOneAtATime) { "one screen at a time" } else { "in order, leaving open screens as they are" }) $msg = "Sequential Auto Farm ready for " + $queue.Count + " instance(s) (" + $mode + "). Starting the first target." if ($warn) { $msg = $msg + " " + $warn } Set-FarmStatus $msg } function Prepare-FarmSequenceTarget { $seq = @($script:farmInstanceSequence) $i = 0 try { $i = [int]$script:farmInstanceSequenceIndex } catch {} if ($i -ge $seq.Count) { return $null } $target = $seq[$i] $id = [string]$target.id $cool = 0 try { $cool = [int]$script:farmInstanceSequenceCooldown } catch {} if ($cool -gt 0) { $script:farmInstanceSequenceCooldown = $cool - 1 Set-FarmStatus ("Waiting to open the next BlueStacks screen one at a time (" + ($i + 1) + " of " + $seq.Count + ")...") return "wait" } $fresh = Get-FarmCatalogRowById $id if (-not $fresh) { return "skip" } if ([long]$fresh.hwnd -eq 0) { if ([string]$script:farmInstanceSequenceLaunchId -ne $id) { if ($script:farmInstanceSequenceOneAtATime) { foreach ($row in $seq) { if ([string]$row.id -ne $id) { Stop-FarmBlueStacksInstance ([string]$row.id) } } } [void](Start-FarmBlueStacksInstance $id) $script:farmInstanceSequenceLaunchId = $id $script:farmInstanceSequenceLaunchTries = 0 } $script:farmInstanceSequenceLaunchTries++ if ($script:farmInstanceSequenceLaunchTries -gt 50) { Set-FarmStatus ("That BlueStacks screen did not open: " + [string]$target.label + ". Skipping.") return "skip" } Set-FarmStatus ("Opening screen " + ($i + 1) + " of " + $seq.Count + " one at a time: " + [string]$target.label + "...") return "wait" } return $fresh } function Save-FarmStartBlueStacks([bool]$on) { try { $c = Read-Cfg $ht = @{} if ($c) { foreach ($p in $c.PSObject.Properties) { $ht[$p.Name] = $p.Value } } $ht.farmStartBlueStacks = $on ($ht | ConvertTo-Json) | Set-Content -Path $cfgPath -Encoding UTF8 $script:cfg = Read-Cfg } catch {} } function Start-FarmBlueStacks { $h = Find-FarmGameHwnd if ($h -ne [IntPtr]::Zero) { Set-FarmStatus "BlueStacks is already open. Restoring the saved size." Restore-FarmWindowSizeLabel return $true } $player = Get-BlueStacksPlayerPath if (-not $player) { Set-FarmStatus "BlueStacks was not found on this PC. Install BlueStacks, then press Launch BlueStacks." return $false } try { Start-Process -FilePath $player | Out-Null Set-FarmStatus "BlueStacks is starting. Its saved size will be restored when the window opens." } catch { Set-FarmStatus "BlueStacks could not start. Open it from Windows, then press Restore size." return $false } try { if ($script:blueRestoreTimer) { $script:blueRestoreTimer.Stop(); $script:blueRestoreTimer.Dispose() } $script:blueRestoreTries = 0 $script:blueRestoreTimer = New-Object System.Windows.Forms.Timer $script:blueRestoreTimer.Interval = 900 $script:blueRestoreSettle = 0 $script:blueRestoreTimer.Add_Tick({ $script:blueRestoreTries++ $hwnd = Find-FarmGameHwnd if ($hwnd -ne [IntPtr]::Zero) { Restore-FarmWindowSizeLabel $script:blueRestoreSettle++ if ($script:blueRestoreSettle -ge 6) { $script:blueRestoreTimer.Stop() return } } if ($script:blueRestoreTries -ge 45) { $script:blueRestoreTimer.Stop() Set-FarmStatus "BlueStacks is still starting. When it opens, press Restore size." } }) $script:blueRestoreTimer.Start() } catch {} return $true } function Save-FarmWindowSizeLabel { $r = $null $h = Find-FarmGameHwnd if ($h -ne [IntPtr]::Zero) { $wr = New-Object RtFarmGeom+RECT [void][RtFarmGeom]::GetWindowRect($h, [ref]$wr) $ww = [int]($wr.Right - $wr.Left) $hh = [int]($wr.Bottom - $wr.Top) if ($ww -gt 20 -and $hh -gt 20) { $r = @{ X = [int]$wr.Left; Y = [int]$wr.Top; W = $ww; H = $hh } } } if (-not $r) { $r = Resolve-FarmSightRect } if (-not $r) { Set-FarmStatus "Pick BlueStacks, then Use window, then Save size + location." return } $nm = Get-FarmSizeLabelName $b = $script:farmBox $b.sizeName = $nm $b.sizeX = [int]$r.X $b.sizeY = [int]$r.Y $b.sizeW = [int]$r.W $b.sizeH = [int]$r.H $b.sightX = [int]$r.X $b.sightY = [int]$r.Y $b.sightW = [int]$r.W $b.sightH = [int]$r.H Save-FarmSightCfg Paint-FarmSightLabel Set-FarmStatus ("Saved " + $nm + " size + screen location: " + (Format-FarmWinBox ([int]$r.X) ([int]$r.Y) ([int]$r.W) ([int]$r.H)) + ". Restore size + location puts BlueStacks back exactly there.") } function Restore-FarmWindowSizeLabel { $b = $script:farmBox $sw = 0 try { $sw = [int]$b.sizeW } catch { $sw = 0 } $sh = 0 try { $sh = [int]$b.sizeH } catch { $sh = 0 } if ($sw -lt 40 -or $sh -lt 40) { Set-FarmStatus "Save size + location first, while BlueStacks is where you want it." return } $h = Find-FarmGameHwnd if ($h -eq [IntPtr]::Zero) { Set-FarmStatus "BlueStacks is not open. Open it, Use window, then Restore size + location." return } try { if ([RtFarmGeom]::IsIconic($h) -or [RtFarmGeom]::IsZoomed($h)) { [void][RtFarmGeom]::ShowWindow($h, 9) Start-Sleep -Milliseconds 120 } } catch {} $ok = $false $wr = New-Object RtFarmGeom+RECT for ($attempt = 0; $attempt -lt 6; $attempt++) { try { $moved = [RtFarmGeom]::SetWindowPos($h, [IntPtr]::Zero, [int]$b.sizeX, [int]$b.sizeY, [int]$b.sizeW, [int]$b.sizeH, 0x0014) } catch { $moved = $false } Start-Sleep -Milliseconds 180 try { [void][RtFarmGeom]::GetWindowRect($h, [ref]$wr) $samePlace = ([Math]::Abs([int]$wr.Left - [int]$b.sizeX) -le 2 -and [Math]::Abs([int]$wr.Top - [int]$b.sizeY) -le 2) $sameSize = ([Math]::Abs(([int]$wr.Right - [int]$wr.Left) - [int]$b.sizeW) -le 2 -and [Math]::Abs(([int]$wr.Bottom - [int]$wr.Top) - [int]$b.sizeH) -le 2) if ($moved -and $samePlace -and $sameSize) { $ok = $true; break } } catch {} } if (-not $ok) { $oldCursor = New-Object RtFarmMouse+POINT $haveCursor = $false try { $haveCursor = [RtFarmMouse]::GetCursorPos([ref]$oldCursor) } catch {} for ($dragAttempt = 0; $dragAttempt -lt 5; $dragAttempt++) { try { [void][RtFarmGeom]::GetWindowRect($h, [ref]$wr) $dx = [int]$b.sizeX - [int]$wr.Left $dy = [int]$b.sizeY - [int]$wr.Top if ([Math]::Abs($dx) -le 2 -and [Math]::Abs($dy) -le 2) { break } $wwNow = [int]$wr.Right - [int]$wr.Left $sx = [int]$wr.Left + [int][Math]::Round($wwNow * 0.65) $sy = [int]$wr.Top + 30 $vs = [System.Windows.Forms.SystemInformation]::VirtualScreen if ($sx -lt ($vs.Left + 40)) { $sx = $vs.Left + 40 } if ($sx -gt ($vs.Right - 40)) { $sx = $vs.Right - 40 } if ($sy -lt ($vs.Top + 20)) { $sy = $vs.Top + 20 } if ($sy -gt ($vs.Bottom - 40)) { $sy = $vs.Bottom - 40 } try { [RtFarmGrab]::Focus($h) } catch {} [void][RtFarmMouse]::SetCursorPos($sx, $sy) Start-Sleep -Milliseconds 100 [RtFarmMouse]::Down() Start-Sleep -Milliseconds 80 for ($dragStep = 1; $dragStep -le 10; $dragStep++) { $mx = $sx + [int][Math]::Round($dx * $dragStep / 10.0) $my = $sy + [int][Math]::Round($dy * $dragStep / 10.0) [void][RtFarmMouse]::SetCursorPos($mx, $my) Start-Sleep -Milliseconds 24 } [RtFarmMouse]::Up() Start-Sleep -Milliseconds 220 } catch { try { [RtFarmMouse]::Up() } catch {} } } if ($haveCursor) { try { [void][RtFarmMouse]::SetCursorPos([int]$oldCursor.X, [int]$oldCursor.Y) } catch {} } try { [void][RtFarmGeom]::GetWindowRect($h, [ref]$wr) $samePlace = ([Math]::Abs([int]$wr.Left - [int]$b.sizeX) -le 2 -and [Math]::Abs([int]$wr.Top - [int]$b.sizeY) -le 2) $sameSize = ([Math]::Abs(([int]$wr.Right - [int]$wr.Left) - [int]$b.sizeW) -le 2 -and [Math]::Abs(([int]$wr.Bottom - [int]$wr.Top) - [int]$b.sizeH) -le 2) $ok = ($samePlace -and $sameSize) } catch { $ok = $false } } $b.sightX = [int]$wr.Left $b.sightY = [int]$wr.Top $b.sightW = [int]($wr.Right - $wr.Left) $b.sightH = [int]($wr.Bottom - $wr.Top) Save-FarmSightCfg Paint-FarmSightLabel $nm = Get-FarmSizeLabelName if ($ok) { Set-FarmStatus ("Restored " + $nm + " size and Windows desktop location to " + (Format-FarmWinBox ([int]$b.sizeX) ([int]$b.sizeY) ([int]$b.sizeW) ([int]$b.sizeH)) + ".") } else { Set-FarmStatus ("BlueStacks resisted the saved spot. Current: " + (Format-FarmWinBox ([int]$wr.Left) ([int]$wr.Top) ([int]($wr.Right - $wr.Left)) ([int]($wr.Bottom - $wr.Top))) + ". Press Restore size + location again.") } } function Resolve-FarmSightRect { $b = $script:farmBox $targetH = [IntPtr]::Zero try { $targetH = Find-FarmGameHwnd } catch {} if ($targetH -ne [IntPtr]::Zero) { $r = New-Object RtFarmGeom+RECT [void][RtFarmGeom]::GetWindowRect($targetH, [ref]$r) $w = $r.Right - $r.Left $hgt = $r.Bottom - $r.Top if ($w -gt 20 -and $hgt -gt 20) { return @{ X = $r.Left; Y = $r.Top; W = $w; H = $hgt } } } $w = 0 try { $w = [int]$b.sightW } catch { $w = 0 } $hgt = 0 try { $hgt = [int]$b.sightH } catch { $hgt = 0 } if ($w -gt 8 -and $hgt -gt 8) { return @{ X = [int]$b.sightX; Y = [int]$b.sightY; W = $w; H = $hgt } } return $null } function Paint-FarmSightLabel { $u = $script:farmUi if (-not $u -or -not $u.sightLab) { return } $r = Resolve-FarmSightRect $pic = (@(Get-FarmGlassFiles)).Count $now = "" if ($r) { $now = Format-FarmWinBox ([int]$r.X) ([int]$r.Y) ([int]$r.W) ([int]$r.H) } $savedW = 0 try { $savedW = [int]$script:farmBox.sizeW } catch { $savedW = 0 } $savedH = 0 try { $savedH = [int]$script:farmBox.sizeH } catch { $savedH = 0 } $savedNm = "BlueStacks" try { if ($script:farmBox.sizeName) { $savedNm = [string]$script:farmBox.sizeName } } catch {} try { if ($u.sizeName -and $savedNm) { $u.sizeName.Text = $savedNm } } catch {} $saved = "" if ($savedW -gt 20 -and $savedH -gt 20) { $saved = Format-FarmWinBox ([int]$script:farmBox.sizeX) ([int]$script:farmBox.sizeY) $savedW $savedH } $lines = New-Object System.Collections.ArrayList if ($now) { [void]$lines.Add((Helper-T "Now") + ": " + $now) } else { [void]$lines.Add((Helper-T "Pick BlueStacks in the list, then Use window.")) } if ($saved) { [void]$lines.Add((Helper-T "Saved") + " " + $savedNm + ": " + $saved) if ($now -and $now -eq $saved) { [void]$lines.Add((Helper-T "Same size. Clicks stay on the same spots.")) } else { [void]$lines.Add((Helper-T "Restore size + location puts BlueStacks back at the saved X/Y screen spot and saved width/height.")) } } else { [void]$lines.Add((Helper-T "Place and resize BlueStacks where you want it, then Save size + location.")) } if ($pic -gt 0) { [void]$lines.Add(([string]$pic) + " " + (Helper-T "picture(s). Play waits for a picture on the list, then clicks it.")) } $u.sightLab.Text = ($lines -join "`r`n") } function Show-FarmPickBox { $f = New-Object System.Windows.Forms.Form $f.FormBorderStyle = "None" $f.WindowState = "Maximized" $f.TopMost = $true $f.Opacity = 0.28 $f.BackColor = [System.Drawing.Color]::Navy $f.Cursor = [System.Windows.Forms.Cursors]::Cross $f.KeyPreview = $true $holder = @{ a = $null } $f.Tag = $holder $f.Add_KeyDown({ if ($_.KeyCode -eq "Escape") { $this.Close() } }) $f.Add_MouseDown({ $this.Tag.a = [System.Windows.Forms.Cursor]::Position }) $f.Add_MouseUp({ $a = $this.Tag.a $bpt = [System.Windows.Forms.Cursor]::Position $this.Close() if (-not $a) { return } $x = [Math]::Min($a.X, $bpt.X) $y = [Math]::Min($a.Y, $bpt.Y) $w = [Math]::Abs($a.X - $bpt.X) $h = [Math]::Abs($a.Y - $bpt.Y) if ($w -lt 12 -or $h -lt 12) { return } $box = $script:farmBox $box.sightX = [int]$x $box.sightY = [int]$y $box.sightW = [int]$w $box.sightH = [int]$h $box.winTitle = "" Save-FarmSightCfg Paint-FarmSightLabel Set-FarmStatus "Spot saved. Show the picture in that box, then Save picture." }) try { if ($script:farmForm) { $script:farmForm.Hide() } } catch {} [void]$f.ShowDialog() try { if ($script:farmForm -and -not $script:farmForm.IsDisposed) { $script:farmForm.Show() $script:farmForm.BringToFront() } } catch {} } function Save-FarmWatchPicture { try { if ($script:glassLastBmp) { $copy = $script:glassLastBmp.Clone() $n = (@(Read-FarmGlassList).Count) + 1 [void](Add-FarmGlassBitmap $copy ("Picture " + $n)) try { $copy.Dispose() } catch {} try { if ($script:farmWaitImg) { $script:farmWaitImg.Checked = $true } } catch {} Paint-FarmSightLabel Set-FarmStatus ("Saved picture " + $n + " from the mag glass. Any one that shows is clicked.") return } } catch {} Show-FarmMagGlass } function Fill-FarmWindowCombo { $u = $script:farmUi if (-not $u -or -not $u.win) { return } $u.win.Items.Clear() foreach ($t in ([RtFarmGeom]::ListTitles() | Select-Object -First 40)) { [void]$u.win.Items.Add($t) } } function Use-FarmWindowPick { $u = $script:farmUi if (-not $u -or -not $u.win -or $u.win.SelectedIndex -lt 0) { Set-FarmStatus "Pick a window in the list." return } $title = [string]$u.win.SelectedItem $script:farmBox.winTitle = $title $r = Resolve-FarmSightRect if ($r) { $script:farmBox.sightX = [int]$r.X $script:farmBox.sightY = [int]$r.Y $script:farmBox.sightW = [int]$r.W $script:farmBox.sightH = [int]$r.H } Save-FarmSightCfg Paint-FarmSightLabel Set-FarmStatus ("Tied to that window. Now " + (Format-FarmWinBox ([int]$script:farmBox.sightX) ([int]$script:farmBox.sightY) ([int]$script:farmBox.sightW) ([int]$script:farmBox.sightH)) + ". Save this size to remember it.") } function Farm-PlayNow { $script:farmPlayFail = "" try { Save-FarmPlayOrderFromUi } catch {} $batches = New-Object System.Collections.ArrayList $hadPic = $false $missPic = $false $hadStep = $false $playLabels = @(Get-FarmPlayRowsNow) $hadList = ($playLabels.Count -gt 0) $stepDelays = New-Object System.Collections.ArrayList foreach ($row in $playLabels) { $s = [string]$row.label $stepMs = Clamp-FarmStepMs $row.ms if ($s.StartsWith("pic:")) { $hadPic = $true $fp = Resolve-FarmPicFile $s if (-not $fp) { $fp = Get-FarmPicQueueFile $s } $nx = -1.0 $ny = -1.0 if ($fp) { $spot = Get-FarmRelForFile $fp if ($spot) { $nx = [double]$spot.nx; $ny = [double]$spot.ny } } $one = [pscustomobject]@{ t = 0; type = "waitpic"; x = 0; y = 0; file = $fp; nx = $nx; ny = $ny; ms = $stepMs } [void]$batches.Add(@($one)) [void]$stepDelays.Add($stepMs) $hadStep = $true if (-not $fp -or -not (Test-Path -LiteralPath $fp)) { $missPic = $true } continue } $want = Get-FarmMacroNameFromLabel $s $m = Find-FarmMacroByName $want if ($m -and $m.events) { [void]$batches.Add($m.events) [void]$stepDelays.Add($stepMs) $hadStep = $true } } if ((-not $hadList) -and $batches.Count -lt 1) { if ($script:lastFarmEvents -and @($script:lastFarmEvents).Count -gt 0) { [void]$batches.Add($script:lastFarmEvents) [void]$stepDelays.Add((Get-FarmDefaultStepMs)) } } $doLoop = $false try { if ($script:farmLoop) { $doLoop = [bool]$script:farmLoop.Checked } } catch {} try { if ($script:farmBox -and $script:farmBox.playLoopForce) { $doLoop = [bool]$script:farmBox.playLoop $script:farmBox.playLoopForce = $false } } catch {} $delay = 500 $keyDelay = 500 try { if ($script:farmDelay) { $delay = [int]$script:farmDelay.Value } } catch {} try { if ($script:farmKeyDelay) { $keyDelay = [int]$script:farmKeyDelay.Value } } catch {} try { if ($script:farmBox -and $script:farmBox.playDelayForce) { $delay = [int]$script:farmBox.playDelay $script:farmBox.playDelayForce = $false } } catch {} $times = 1 $waitPic = $false try { if ($script:farmWaitImg) { $waitPic = [bool]$script:farmWaitImg.Checked } } catch {} $glass = "" if ($waitPic) { try { $glass = (@(Get-FarmGlassFiles) -join ";") } catch { $glass = "" } } if ($batches.Count -lt 1) { if ($missPic -and -not $hadStep) { $script:farmPlayFail = "The picture on the play list is missing from disk. Take that picture again, or Play a recorded click step. Pictures are optional." } else { $script:farmPlayFail = "Record a click step, then Play. Adding a picture is optional." } return $false } $ok = Farm-StartPlay $batches $doLoop $delay $keyDelay $times $waitPic $glass @($stepDelays) if (-not $ok -and -not $script:farmPlayFail) { $script:farmPlayFail = "Play did not start." } return $ok } function Farm-FillTodayQueue { Show-AutoFarm return (Fill-TodayFarmQueue) } function Farm-StartRecord { if (-not (Test-HasCommander)) { try { if ($script:farmForm) { $script:farmForm.TopMost = $false } } catch {} Show-FarmToast "Pick your commander in Settings first. Chat is already paid for that name." try { Show-ProfileSettings } catch {} return $false } $paid = $false try { $paid = Sync-ChatPaidFromBackend } catch { $paid = $false } if (-not $paid) { try { $paid = Test-ChatPaid } catch { $paid = $false } } if (-not $paid) { try { if ($script:farmForm) { $script:farmForm.TopMost = $false } } catch {} if ($script:chatPayState -eq "unpaid" -and -not (Test-RememberedChatPaid)) { Show-PayPalUnlockPrompt } else { Show-FarmToast "Still checking Chat with the server. Press Record again in a moment." } return $false } try { Request-FarmLease -action start -Quiet | Out-Null } catch {} $b = $script:farmBox $b.stopPlay = $true $b.playing = $false $b.events.Clear() $b.recT0 = [Environment]::TickCount $b.recWasDown = $false $b.recLastMove = 0 $b.recLastX = -1 $b.recLastY = -1 $keys = New-Object 'bool[]' 256 for ($vk = 8; $vk -le 254; $vk++) { $keys[$vk] = (([RtFarmMouse]::GetAsyncKeyState($vk) -band 0x8000) -ne 0) } $b.recKeyDown = $keys $b.recNeedRightUp = $true $b.recRightWasDown = $true $b.recIgnoreRightUntil = [Environment]::TickCount + 500 $b.recording = $true Write-HelperCrashLog "record start" return $true } function Farm-StopRecord { $b = $script:farmBox $b.recording = $false Start-Sleep -Milliseconds 40 $script:lastFarmEvents = Convert-FarmEvents @($b.events) return $script:lastFarmEvents } function Save-FarmRecording($ev) { $events = @($ev) if ($events.Count -lt 1) { return "" } $nm = "" try { if ($script:farmNameBox) { $nm = [string]$script:farmNameBox.Text.Trim() } } catch {} if (-not $nm -or $nm -eq "macro") { $nm = "step" } $gid = "" try { $gid = [string](Get-FarmComboGameId $(if ($script:farmUi) { $script:farmUi.saveGame } else { $null })) } catch { $gid = "" } $all = @(Read-FarmMacros) $base = $nm $n = 2 $taken = $true while ($taken -and $n -lt 300) { $taken = $false foreach ($old in $all) { if ([string]$old.name -eq $nm -and [string]$old.gameId -eq $gid) { $taken = $true; break } } if ($taken) { $nm = "$base $n"; $n++ } } try { if ($script:farmNameBox) { $script:farmNameBox.Text = $nm } } catch {} $row = [pscustomobject]@{ name = $nm; events = $events; days = @(Get-FarmDayChecks); saved = (Get-Date).ToString("s"); gameId = $gid } $next = New-Object System.Collections.ArrayList foreach ($old in $all) { [void]$next.Add($old) } [void]$next.Add($row) Write-FarmMacros @($next) try { Refresh-FarmMacroList $script:farmList } catch {} try { Add-FarmPlayStep $row } catch {} return $nm } function Farm-StopPlay { $b = $script:farmBox $wasInstanceSequence = [bool]$script:farmInstanceSequence $script:farmInstanceSequence = $null $script:farmInstanceSequenceWaiting = $false $script:farmInstanceSequenceSawPlaying = $false $script:farmInstanceSequenceOneAtATime = $false $script:farmInstanceSequenceLaunchId = "" $script:farmInstanceSequenceLaunchTries = 0 $script:farmInstanceSequenceCooldown = 0 if ($wasInstanceSequence) { try { if ($script:farmLoop) { $script:farmLoop.Checked = [bool]$script:farmSequenceOldLoop } } catch {} } $b.recording = $false $b.stopPlay = $true $b.playing = $false try { Request-FarmLease "stop" | Out-Null } catch {} } function Reset-FarmPlayToNumberOne { $b = $script:farmBox if (-not $b) { return } $b.stopPlay = $true $b.playing = $false $old = $null try { $old = $script:farmPlayJob } catch { $old = $null } if ($old) { try { $old.Stop() } catch {} try { if ($old.Runspace) { $old.Runspace.Close(); $old.Runspace.Dispose() } } catch {} try { $old.Dispose() } catch {} } $script:farmPlayJob = $null try { $b.playJob = $null } catch {} Start-Sleep -Milliseconds 80 $b.stopPlay = $false } function Farm-StartPlay($batches, $loop, $clickDelay, $keyDelay, $times, $waitPic, $glassFiles, $stepDelays) { if (-not (Test-HasCommander)) { $script:farmPlayFail = "Pick your commander in Settings first. Chat is already paid for that name." Show-FarmToast $script:farmPlayFail try { Show-ProfileSettings } catch {} return $false } $paid = $false try { $paid = Sync-ChatPaidFromBackend } catch { $paid = $false } if (-not $paid) { try { $paid = Test-ChatPaid } catch { $paid = $false } } if (-not $paid) { if ($script:chatPayState -eq "unpaid" -and -not (Test-RememberedChatPaid)) { Show-PayPalUnlockPrompt } else { $script:farmPlayFail = "Still checking Chat with the server. Press Play again." Show-FarmToast $script:farmPlayFail } return $false } $seqs = New-Object System.Collections.ArrayList foreach ($raw in @($batches)) { $list = Convert-FarmEvents $raw if ($list.Count -gt 0) { [void]$seqs.Add($list) } } $glass = "" if ($waitPic) { $glass = [string]$glassFiles } if ($seqs.Count -lt 1) { $script:farmPlayFail = "Record a click step, then Play. Adding a picture is optional." return $false } try { Request-FarmLease -action start -Quiet | Out-Null } catch {} $delay = 0 try { $delay = [int]$clickDelay } catch { $delay = 0 } if ($delay -lt 0) { $delay = 0 } if ($delay -gt 8000) { $delay = 8000 } $keyMs = 500 try { $keyMs = [int]$keyDelay } catch { $keyMs = 500 } if ($keyMs -lt 0) { $keyMs = 0 } if ($keyMs -gt 8000) { $keyMs = 8000 } $nTimes = 1 $b = $script:farmBox $b.stopPlay = $false $delayCsv = "" try { if ($stepDelays) { $delayCsv = (@($stepDelays) -join ",") } } catch { $delayCsv = "" } $watch = Get-FarmWatchPath $play = [powershell]::Create().AddScript({ param($seqs, $loop, $clickDelay, $box, $nTimes, $waitPic, $watch, $glassFiles, $keyDelay, $delayCsv) Add-Type -AssemblyName System.Drawing Add-Type -AssemblyName System.Windows.Forms if (-not ("RtFarmSight" -as [type])) { Add-Type -ReferencedAssemblies System.Drawing.dll -TypeDefinition @" using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; public static class RtFarmSight { public static bool CloseEnough(Bitmap a, Bitmap b, int maxAvg) { int tw = 48, th = 48; using (var aa = new Bitmap(tw, th)) using (var bb = new Bitmap(tw, th)) { using (var g = Graphics.FromImage(aa)) { g.DrawImage(a, 0, 0, tw, th); } using (var g = Graphics.FromImage(bb)) { g.DrawImage(b, 0, 0, tw, th); } long diff = 0; int n = 0; for (int y = 0; y < th; y += 2) { for (int x = 0; x < tw; x += 2) { Color ca = aa.GetPixel(x, y); Color cb = bb.GetPixel(x, y); diff += Math.Abs(ca.R - cb.R) + Math.Abs(ca.G - cb.G) + Math.Abs(ca.B - cb.B); n++; } } return n > 0 && (diff / n) <= maxAvg; } } public struct Hit { public bool Ok; public int X; public int Y; } static void CopyTopDown(Bitmap bmp, out byte[] bytes, out int stride) { BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); int raw = data.Stride; int abs = Math.Abs(raw); int h = bmp.Height; byte[] buf = new byte[abs * h]; Marshal.Copy(data.Scan0, buf, 0, buf.Length); bmp.UnlockBits(data); if (raw < 0) { byte[] flip = new byte[buf.Length]; for (int y = 0; y < h; y++) Buffer.BlockCopy(buf, (h - 1 - y) * abs, flip, y * abs, abs); buf = flip; } bytes = buf; stride = abs; } static void DrawFit(Bitmap src, Bitmap dst) { using (Graphics g = Graphics.FromImage(dst)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half; g.DrawImage(src, 0, 0, dst.Width, dst.Height); } } static void BestOn(byte[] hb, int hStride, byte[] nb, int nStride, int nw, int nh, int x0, int y0, int x1, int y1, int step, int gap, out double avg, out int ox, out int oy) { avg = 1e9; ox = x0; oy = y0; if (x1 < x0 || y1 < y0 || nw < 2 || nh < 2) return; int ix0 = nw / 10; int iy0 = nh / 10; int ix1 = nw - ix0; int iy1 = nh - iy0; if (ix1 <= ix0 + 1 || iy1 <= iy0 + 1) { ix0 = 0; iy0 = 0; ix1 = nw; iy1 = nh; } int samples = 0; for (int yy = iy0; yy < iy1; yy += gap) for (int xx = ix0; xx < ix1; xx += gap) samples++; if (samples < 1) return; if (step < 1) step = 1; if (gap < 1) gap = 1; double best = 1e9; for (int y = y0; y <= y1; y += step) { for (int x = x0; x <= x1; x += step) { long diff = 0; int n = 0; bool dead = false; for (int yy = iy0; yy < iy1 && !dead; yy += gap) { int ho = (y + yy) * hStride + x * 4; int noff = yy * nStride; for (int xx = ix0; xx < ix1; xx += gap) { int hi = ho + xx * 4; int ni = noff + xx * 4; diff += Math.Abs(hb[hi] - nb[ni]) + Math.Abs(hb[hi + 1] - nb[ni + 1]) + Math.Abs(hb[hi + 2] - nb[ni + 2]); n++; if (diff > best * (n + (samples - n))) { dead = true; break; } } } if (!dead && n > 0) { double a = (double)diff / n; if (a < best) { best = a; ox = x; oy = y; } } } } avg = best; } public static Hit FindNeedle(Bitmap hay, Bitmap needle, int maxAvg) { Hit miss; miss.Ok = false; miss.X = 0; miss.Y = 0; if (hay == null || needle == null || needle.Width < 2 || needle.Height < 2) return miss; int limit = maxAvg; if (limit < 120) limit = 128; double s = hay.Width > 400 ? 400.0 / hay.Width : 1.0; int hw = Math.Max(8, (int)Math.Round(hay.Width * s)); int hh = Math.Max(8, (int)Math.Round(hay.Height * s)); byte[] hb; int hStride; using (Bitmap hs = new Bitmap(hw, hh, PixelFormat.Format32bppArgb)) { DrawFit(hay, hs); CopyTopDown(hs, out hb, out hStride); } double bestAvg = 1e9; int bx = 0, by = 0, bnw = 1, bnh = 1; double bestK = 1.0; for (double k = 0.12; k <= 8.01; k *= 1.18) { int nw = (int)Math.Round(needle.Width * s * k); int nh = (int)Math.Round(needle.Height * s * k); if (nw < 6 || nh < 6 || nw >= hw - 1 || nh >= hh - 1) continue; byte[] nb; int nStride; using (Bitmap ns = new Bitmap(nw, nh, PixelFormat.Format32bppArgb)) { DrawFit(needle, ns); CopyTopDown(ns, out nb, out nStride); } double avg; int ox, oy; int gap = nw < 22 ? 1 : 2; int step = nw < 28 ? 2 : 3; BestOn(hb, hStride, nb, nStride, nw, nh, 0, 0, hw - nw, hh - nh, step, gap, out avg, out ox, out oy); if (avg < bestAvg) { bestAvg = avg; bx = ox; by = oy; bnw = nw; bnh = nh; bestK = k; } } if (bestAvg > 260) return miss; double inv = s <= 0 ? 1.0 : (1.0 / s); int cx = (int)Math.Round((bx + bnw / 2.0) * inv); int cy = (int)Math.Round((by + bnh / 2.0) * inv); byte[] fb; int fStride; using (Bitmap full = new Bitmap(hay.Width, hay.Height, PixelFormat.Format32bppArgb)) { DrawFit(hay, full); CopyTopDown(full, out fb, out fStride); } double[] refineMul = new double[] { 0.80, 0.90, 1.0, 1.10, 1.22 }; double fullAvg = 1e9; int fx = Math.Max(0, cx), fy = Math.Max(0, cy), fnw = Math.Max(2, (int)Math.Round(needle.Width * bestK)), fnh = Math.Max(2, (int)Math.Round(needle.Height * bestK)); for (int ri = 0; ri < refineMul.Length; ri++) { double k = bestK * refineMul[ri]; int nw = Math.Max(4, (int)Math.Round(needle.Width * k)); int nh = Math.Max(4, (int)Math.Round(needle.Height * k)); if (nw >= hay.Width - 1 || nh >= hay.Height - 1) continue; byte[] nb; int nStride; using (Bitmap ns = new Bitmap(nw, nh, PixelFormat.Format32bppArgb)) { DrawFit(needle, ns); CopyTopDown(ns, out nb, out nStride); } int pad = Math.Max(16, (int)Math.Round(12.0 * inv)); int x0 = Math.Max(0, cx - nw / 2 - pad); int y0 = Math.Max(0, cy - nh / 2 - pad); int x1 = Math.Min(hay.Width - nw, cx - nw / 2 + pad); int y1 = Math.Min(hay.Height - nh, cy - nh / 2 + pad); double avg; int ox, oy; BestOn(fb, fStride, nb, nStride, nw, nh, x0, y0, x1, y1, 2, 2, out avg, out ox, out oy); if (avg < fullAvg) { fullAvg = avg; fx = ox; fy = oy; fnw = nw; fnh = nh; } } if (fullAvg > limit) { if (bestAvg > 180) return miss; miss.Ok = true; miss.X = cx; miss.Y = cy; } else { miss.Ok = true; miss.X = fx + (int)Math.Round(fnw / 2.0); miss.Y = fy + (int)Math.Round(fnh / 2.0); } if (miss.X < 0) miss.X = 0; if (miss.Y < 0) miss.Y = 0; if (miss.X >= hay.Width) miss.X = hay.Width - 1; if (miss.Y >= hay.Height) miss.Y = hay.Height - 1; return miss; } } "@ } function Get-PlayStepMs([int]$index) { $fb = 500 try { $fb = [int]$clickDelay } catch { $fb = 500 } if ($fb -lt 0) { $fb = 0 } $csv = [string]$delayCsv if (-not $csv) { return $fb } $parts = @($csv.Split(',')) if ($index -lt 0 -or $index -ge $parts.Count) { return $fb } $v = $fb try { $v = [int]$parts[$index] } catch { $v = $fb } if ($v -lt 0) { $v = 0 } if ($v -gt 8000) { $v = 8000 } return $v } function Get-PlayHwnd { $targetPid = 0 try { $targetPid = [int]$box.targetPid } catch {} if ($targetPid -gt 0) { try { $targetProc = Get-Process -Id $targetPid -ErrorAction Stop if ($targetProc.MainWindowHandle -ne 0) { return [IntPtr]$targetProc.MainWindowHandle } } catch { try { $box.stopPlay = $true; $box.playError = "The selected BlueStacks instance closed. Playback stopped safely." } catch {} return [IntPtr]::Zero } } $title = "" try { $title = [string]$box.winTitle } catch {} if ($title) { $h = [RtFarmGeom]::FindTitleContains($title) if ($h -ne [IntPtr]::Zero) { return $h } } foreach ($part in @("BlueStacks", "HD-Player")) { $h = [RtFarmGeom]::FindTitleContains($part) if ($h -ne [IntPtr]::Zero) { return $h } } return [IntPtr]::Zero } function Get-PlayRect { $top = Get-PlayHwnd if ($top -ne [IntPtr]::Zero) { $mini = $false try { $mini = [RtFarmGrab]::IsMinimized($top) } catch { $mini = $false } if ($mini) { return @{ X = 0; Y = 0; W = 0; H = 0; Hwnd = $top; Top = $top; Minimized = $true } } $h = $top try { $surf = [RtFarmGrab]::GameSurface($top) if ($surf -ne [IntPtr]::Zero) { $h = $surf } } catch {} $r = New-Object RtFarmGeom+RECT [void][RtFarmGeom]::GetWindowRect($h, [ref]$r) $w = $r.Right - $r.Left $hh = $r.Bottom - $r.Top if ($w -gt 20 -and $hh -gt 20) { $scale = 1.0 try { $scale = [double][RtFarmGrab]::ScaleOf($h) } catch { $scale = 1 } if ($scale -lt 1) { $scale = 1 } return @{ X = $r.Left; Y = $r.Top; W = $w; H = $hh; Hwnd = $h; Top = $top; Minimized = $false; Scale = $scale } } } $w = 0 try { $w = [int]$box.sightW } catch { $w = 0 } $hh = 0 try { $hh = [int]$box.sightH } catch { $hh = 0 } if ($w -gt 8 -and $hh -gt 8) { return @{ X = [int]$box.sightX; Y = [int]$box.sightY; W = $w; H = $hh; Hwnd = [IntPtr]::Zero } } $screen = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds return @{ X = [int]$screen.X; Y = [int]$screen.Y; W = [int]$screen.Width; H = [int]$screen.Height; Hwnd = [IntPtr]::Zero } } function Copy-PlayShot($reg) { try { if ($reg.Minimized) { return $null } } catch {} $hwnd = [IntPtr]::Zero try { if ($reg.Hwnd) { $hwnd = [IntPtr]$reg.Hwnd } } catch {} $focus = $hwnd try { if ($reg.Top -and [IntPtr]$reg.Top -ne [IntPtr]::Zero) { $focus = [IntPtr]$reg.Top } } catch {} if ($focus -ne [IntPtr]::Zero) { try { [RtFarmGrab]::Focus($focus) } catch {} } if ($hwnd -ne [IntPtr]::Zero) { try { $scale = 1.0 try { if ($reg.Scale) { $scale = [double]$reg.Scale } } catch { $scale = 1 } if ($scale -lt 1) { $scale = 1 } $bw = [int][Math]::Round([int]$reg.W * $scale) $bh = [int][Math]::Round([int]$reg.H * $scale) $shot = [RtFarmGrab]::FromWindow($hwnd, $bw, $bh) if ($shot) { return $shot } } catch {} } $hay = New-Object System.Drawing.Bitmap ([int]$reg.W, [int]$reg.H) $g = [System.Drawing.Graphics]::FromImage($hay) $g.CopyFromScreen([int]$reg.X, [int]$reg.Y, 0, 0, $hay.Size) $g.Dispose() return $hay } function Convert-PlayHit($reg, $hit, $hay) { $x = [int]$hit.X $y = [int]$hit.Y $bw = 0 $bh = 0 try { if ($hay) { $bw = [int]$hay.Width; $bh = [int]$hay.Height } } catch {} $ww = [int]$reg.W $wh = [int]$reg.H if ($bw -gt 8 -and $bh -gt 8 -and $ww -gt 8 -and $wh -gt 8) { $x = [int][Math]::Round($x * $ww / [double]$bw) $y = [int][Math]::Round($y * $wh / [double]$bh) } return (New-Object PSObject -Property @{ Ok = $true; X = $x; Y = $y }) } function Invoke-PlayClick($reg, $hit) { $hwnd = [IntPtr]::Zero try { if ($reg.Hwnd) { $hwnd = [IntPtr]$reg.Hwnd } } catch {} $mini = $false try { if ($reg.Minimized) { $mini = $true } } catch {} try { if ($hwnd -ne [IntPtr]::Zero -and [RtFarmGrab]::IsMinimized($hwnd)) { $mini = $true } } catch {} $focus = $hwnd try { if ($reg.Top -and [IntPtr]$reg.Top -ne [IntPtr]::Zero) { $focus = [IntPtr]$reg.Top } } catch {} try { if ($focus -ne [IntPtr]::Zero -and [RtFarmGrab]::IsMinimized($focus)) { $mini = $true } } catch {} if ($mini) { $box.sawMinimized = $true if (-not $box.playNotice) { $box.playNotice = "BlueStacks is minimized. Open the game window." } return } if ($focus -ne [IntPtr]::Zero) { try { [RtFarmGrab]::Focus($focus) } catch {} Start-Sleep -Milliseconds 80 } $ox = [int]$reg.X $oy = [int]$reg.Y $ww = [int]$reg.W $wh = [int]$reg.H if ($hwnd -ne [IntPtr]::Zero) { try { $wr = New-Object RtFarmGrab+RECT [void][RtFarmGrab]::GetWindowRect($hwnd, [ref]$wr) $ox = [int]$wr.Left $oy = [int]$wr.Top $ww = [int]$wr.Right - [int]$wr.Left $wh = [int]$wr.Bottom - [int]$wr.Top } catch {} } $hx = [int]$hit.X $hy = [int]$hit.Y if ($ww -gt 20 -and $wh -gt 20 -and [int]$reg.W -gt 20 -and [int]$reg.H -gt 20) { if ([Math]::Abs($ww - [int]$reg.W) -gt 6 -or [Math]::Abs($wh - [int]$reg.H) -gt 6) { $hx = [int][Math]::Round($hx * $ww / [double][int]$reg.W) $hy = [int][Math]::Round($hy * $wh / [double][int]$reg.H) } } $cx = $ox + $hx $cy = $oy + $hy [void][RtFarmMouse]::SetCursorPos($cx, $cy) Start-Sleep -Milliseconds 40 [RtFarmMouse]::Down() Start-Sleep -Milliseconds 40 [RtFarmMouse]::Up() } function Invoke-PlaySeenPic { param($reg, $hit, $stepMs, $need, $hay) $wait = 0 try { $wait = [int]$stepMs } catch { $wait = 0 } if ($wait -gt 0) { Start-Sleep -Milliseconds $wait } if (Test-PlayStopped) { return } $useReg = $reg $useHit = $hit $useHay = $hay $hay2 = $null if ($need) { $reg2 = Wait-PlayShotReady if (-not $reg2) { return $false } try { $hay2 = Copy-PlayShot $reg2 $hit2 = [RtFarmSight]::FindNeedle($hay2, $need, 46) $near = $false if ($hit2.Ok) { $maxMove = [Math]::Max(18, [Math]::Max([int]$need.Width, [int]$need.Height)) $near = ([Math]::Abs([int]$hit2.X - [int]$hit.X) -le $maxMove -and [Math]::Abs([int]$hit2.Y - [int]$hit.Y) -le $maxMove) } if (-not $near) { try { if ($hay2) { $hay2.Dispose() } } catch {} return $false } $useReg = $reg2 $useHit = $hit2 $useHay = $hay2 } catch { try { if ($hay2) { $hay2.Dispose() } } catch {} return $false } } Invoke-PlayClick $useReg (Convert-PlayHit $useReg $useHit $useHay) try { if ($hay2) { $hay2.Dispose() } } catch {} if ($wait -gt 0) { Start-Sleep -Milliseconds $wait } return $true } function Test-PlayStopped { if ($box.stopPlay) { return $true } if ([RtFarmMouse]::GetAsyncKeyState(0x1B) -band 0x8000) { $box.stopPlay = $true; return $true } if ([RtFarmMouse]::GetAsyncKeyState(0x02) -band 0x8000) { $box.stopPlay = $true; return $true } return $false } function Wait-PlayShotReady { while ($true) { if (Test-PlayStopped) { return $null } $reg = Get-PlayRect if (-not $reg) { Start-Sleep -Milliseconds 200; continue } if ($reg.Minimized) { $box.sawMinimized = $true if (-not $box.playNotice) { $box.playNotice = "BlueStacks is minimized. Open the game window. Play waits." } Start-Sleep -Milliseconds 400 continue } return $reg } } function Add-PlayEventRow($out, $events) { if ($null -eq $events) { return } $et = "" try { $et = [string]$events.type } catch { $et = "" } if (-not $et) { try { if ($events -is [System.Collections.IDictionary]) { $et = [string]$events["type"] } } catch { $et = "" } } $fp = "" try { $fp = [string]$events.file } catch { $fp = "" } if (-not $fp) { try { if ($events -is [System.Collections.IDictionary]) { $fp = [string]$events["file"] } } catch { $fp = "" } } $isStep = ($et -eq "waitpic" -or $et -eq "down" -or $et -eq "up" -or $et -eq "move" -or $et -eq "keydown" -or $et -eq "keyup" -or ($fp -and $fp -match '\.png')) if ($isStep -or ($events -is [System.Collections.IDictionary])) { if ($events -is [System.Collections.IDictionary]) { $o = New-Object PSObject -Property @{ t = $events["t"] type = [string]$events["type"] x = $events["x"] y = $events["y"] file = [string]$events["file"] key = $events["key"] nx = $events["nx"] ny = $events["ny"] ms = $events["ms"] } if (-not $o.type -and $o.file) { $o.type = "waitpic" } [void]$out.Add($o) return } [void]$out.Add($events) return } $isList = $false try { $isList = ($events -is [System.Array]) -or ($events -is [System.Collections.IList]) } catch { $isList = $false } if ($isList) { foreach ($one in @($events)) { if ($null -eq $one) { continue } Add-PlayEventRow $out $one } return } [void]$out.Add($events) } function Test-PlayIsPic($e) { $et = "" try { $et = [string]$e.type } catch { $et = "" } $fp = "" try { $fp = [string]$e.file } catch { $fp = "" } if ($et -eq "waitpic") { return $true } if ($fp -and $fp -match '(?i)\.png') { return $true } return $false } function Get-PlayEventList($events) { $out = New-Object System.Collections.ArrayList Add-PlayEventRow $out $events return $out } function Wait-PlayPicture { $files = New-Object System.Collections.ArrayList try { foreach ($p in @(([string]$glassFiles) -split ';')) { $t = ([string]$p).Trim() if ($t -and (Test-Path -LiteralPath $t)) { [void]$files.Add($t) } } } catch {} if ($files.Count -lt 1 -and $watch -and (Test-Path -LiteralPath $watch)) { [void]$files.Add($watch) } if (-not $waitPic -and $files.Count -lt 1) { return $true } if ($files.Count -lt 1) { return $true } $needles = New-Object System.Collections.ArrayList foreach ($fp in $files) { try { [void]$needles.Add((New-Object System.Drawing.Bitmap ([string]$fp))) } catch {} } if ($needles.Count -lt 1) { return $true } if (-not $box.waitTold) { $box.waitTold = $true $box.playNotice = "Waiting until the picture shows. It clicks that, then the next step. Right-click stops." } $ok = $false while (-not $ok) { if (Test-PlayStopped) { break } $reg = Wait-PlayShotReady if (-not $reg) { break } $hay = $null try { $hay = Copy-PlayShot $reg foreach ($need in $needles) { $hit = [RtFarmSight]::FindNeedle($hay, $need, 46) if ($hit.Ok) { $ok = [bool](Invoke-PlaySeenPic $reg $hit $clickDelay $need $hay) break } } } catch {} try { if ($hay) { $hay.Dispose() } } catch {} if (-not $ok) { Start-Sleep -Milliseconds 280 } } foreach ($need in $needles) { try { $need.Dispose() } catch {} } return $ok } function Test-PlayPicOnScreen($need) { if (-not $need) { return $false } $reg = Wait-PlayShotReady if (-not $reg) { return $false } $hay = $null $seen = $false try { $hay = Copy-PlayShot $reg $hit = [RtFarmSight]::FindNeedle($hay, $need, 46) $seen = [bool]$hit.Ok } catch { $seen = $false } try { if ($hay) { $hay.Dispose() } } catch {} return $seen } function Wait-PlayPictureGone($need) { if (-not $need) { return } $box.playNotice = "Waiting until that picture is gone, then the next step." $gone = 0 while ($gone -lt 3) { if (Test-PlayStopped) { return } if (Test-PlayPicOnScreen $need) { $gone = 0 } else { $gone++ } Start-Sleep -Milliseconds 280 } } function Wait-PlayPictureOne { param($oneFile, $stepMs, $again, $expectedNx, $expectedNy) $fp = [string]$oneFile $waitMs = 500 try { $waitMs = [int]$stepMs } catch { $waitMs = 500 } if ($waitMs -lt 0) { $waitMs = 0 } $need = $null $ok = $false $box.waitTold = $true $box.playNotice = "Waiting until this picture shows. It will not go to the next number until it clicks it." while (-not $ok) { if (Test-PlayStopped) { break } if (-not $need) { if ($fp -and (Test-Path -LiteralPath $fp)) { try { $nfs = [IO.File]::Open($fp, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::ReadWrite) $ntmp = New-Object System.Drawing.Bitmap $nfs $nfs.Close() $need = New-Object System.Drawing.Bitmap $ntmp $ntmp.Dispose() } catch { $need = $null } } if (-not $need) { $box.playNotice = "Waiting for that picture file. It will not skip this list number." Start-Sleep -Milliseconds 400 continue } $box.playNotice = "Waiting until this picture shows. Then " + $waitMs + " ms, click the middle, then the next number." } $reg = Wait-PlayShotReady if (-not $reg) { continue } $hay = $null try { $hay = Copy-PlayShot $reg $hit = [RtFarmSight]::FindNeedle($hay, $need, 46) if ($hit.Ok) { $rightPlace = $true try { $enx = [double]$expectedNx $eny = [double]$expectedNy if ($enx -ge 0 -and $eny -ge 0 -and $hay.Width -gt 0 -and $hay.Height -gt 0) { $hnx = ([double]$hit.X + ([double]$need.Width / 2.0)) / [double]$hay.Width $hny = ([double]$hit.Y + ([double]$need.Height / 2.0)) / [double]$hay.Height $rightPlace = ([Math]::Abs($hnx - $enx) -le 0.14 -and [Math]::Abs($hny - $eny) -le 0.14) } } catch { $rightPlace = $true } if ($rightPlace) { $ok = [bool](Invoke-PlaySeenPic $reg $hit $waitMs $need $hay) if ($ok) { try { $box.lastPicFile = $fp } catch {} } } } } catch {} try { if ($hay) { $hay.Dispose() } } catch {} if (-not $ok) { Start-Sleep -Milliseconds 280 } } if ($ok) { $box.playNotice = "Clicked that picture. Next list number." } try { if ($need) { $need.Dispose() } } catch {} return $ok } $hasWaitIn = $false foreach ($events in $seqs) { $look = Get-PlayEventList $events for ($li = 0; $li -lt $look.Count; $li++) { if ([string]$look[$li].type -eq "waitpic" -or (Test-PlayIsPic $look[$li])) { $hasWaitIn = $true } } } $box.playError = "" $box.playNotice = "" $box.waitTold = $false $box.sawMinimized = $false $box.lastPicFile = "" $box.playing = $true $round = 0 $heldKeys = @{} try { do { $round++ $box.lastPicFile = "" $box.waitTold = $false if ($round -gt 1) { $box.playNotice = "Loop. Each picture number clicks again if it is on screen." } if ($waitPic -and -not $hasWaitIn) { if (-not (Wait-PlayPicture)) { if ($box.stopPlay) { break } } } if ($box.stopPlay) { break } $seqI = -1 foreach ($events in $seqs) { if ($box.stopPlay) { break } $seqI++ $box.playNotice = "Playing list #" + ($seqI + 1) + " of " + $seqs.Count + $(if ($round -gt 1) { " (Loop " + $round + ")" } else { "" }) $useDelay = Get-PlayStepMs $seqI $prevT = 0 $reg = Get-PlayRect $batch = Get-PlayEventList $events for ($ei = 0; $ei -lt $batch.Count; $ei++) { $e = $batch[$ei] if ($box.stopPlay) { break } if ([RtFarmMouse]::GetAsyncKeyState(0x1B) -band 0x8000) { $box.stopPlay = $true; break } if ([RtFarmMouse]::GetAsyncKeyState(0x02) -band 0x8000) { $box.stopPlay = $true; break } $wait = 0 try { $wait = [int](([int]$e.t) - $prevT) } catch { $wait = 0 } if ($wait -gt 0 -and $wait -lt 120000) { Start-Sleep -Milliseconds $wait } try { $prevT = [int]$e.t } catch { $prevT = $prevT } if ((Test-PlayIsPic $e) -or [string]$e.type -eq "waitpic") { $box.waitTold = $false $picFile = [string]$e.file $picMs = $useDelay try { if ($null -ne $e.ms -and "$($e.ms)" -ne "") { $picMs = [int]$e.ms } } catch {} $didPic = $false while ((-not $box.stopPlay) -and (-not $didPic)) { $picNx = -1.0 $picNy = -1.0 try { if ($null -ne $e.nx) { $picNx = [double]$e.nx } } catch {} try { if ($null -ne $e.ny) { $picNy = [double]$e.ny } } catch {} $didPic = [bool](Wait-PlayPictureOne $picFile $picMs $false $picNx $picNy) if ((-not $didPic) -and (-not $box.stopPlay)) { Start-Sleep -Milliseconds 200 } } if (-not $didPic) { break } continue } if ([string]$e.type -eq "keydown" -or [string]$e.type -eq "keyup") { try { $vk = 0 try { $vk = [int]$e.key } catch { $vk = 0 } if ($vk -ge 1 -and $vk -le 254) { try { $h = [IntPtr]::Zero if ($reg -and $reg.Top) { $h = [IntPtr]$reg.Top } elseif ($reg -and $reg.Hwnd) { $h = [IntPtr]$reg.Hwnd } if ($h -ne [IntPtr]::Zero) { [RtFarmGrab]::Focus($h) Start-Sleep -Milliseconds 100 } } catch {} if ([string]$e.type -eq "keydown") { [RtFarmKeys179]::Down([byte]$vk) $heldKeys[$vk] = $true } else { [RtFarmKeys179]::Up([byte]$vk) [void]$heldKeys.Remove($vk) } if ($keyDelay -gt 0) { Start-Sleep -Milliseconds $keyDelay } } } catch { try { $box.crashLine = "play key failed: " + $_.Exception.Message } catch {} } continue } $x = 0 $y = 0 try { $x = [int]$e.x } catch { $x = 0 } try { $y = [int]$e.y } catch { $y = 0 } if ($reg) { $usedRelative = $false try { $nx = [double]$e.nx $ny = [double]$e.ny if ($nx -ge 0 -and $nx -le 1 -and $ny -ge 0 -and $ny -le 1) { $x = [int]$reg.X + [int][Math]::Round($nx * ([int]$reg.W - 1)) $y = [int]$reg.Y + [int][Math]::Round($ny * ([int]$reg.H - 1)) $usedRelative = $true } } catch {} if (-not $usedRelative) { try { if ([int]$box.sizeW -gt 20 -and [int]$box.sizeH -gt 20) { $x = [int]$reg.X + [int][Math]::Round((([double]$x - [double][int]$box.sizeX) / [double][int]$box.sizeW) * [int]$reg.W) $y = [int]$reg.Y + [int][Math]::Round((([double]$y - [double][int]$box.sizeY) / [double][int]$box.sizeH) * [int]$reg.H) } } catch {} } if ($x -lt [int]$reg.X) { $x = [int]$reg.X } if ($y -lt [int]$reg.Y) { $y = [int]$reg.Y } if ($x -gt ([int]$reg.X + [int]$reg.W - 1)) { $x = [int]$reg.X + [int]$reg.W - 1 } if ($y -gt ([int]$reg.Y + [int]$reg.H - 1)) { $y = [int]$reg.Y + [int]$reg.H - 1 } } [void][RtFarmMouse]::SetCursorPos($x, $y) if ($e.type -eq "down") { [RtFarmMouse]::Down() } elseif ($e.type -eq "up") { [RtFarmMouse]::Up() if ($useDelay -gt 0) { Start-Sleep -Milliseconds $useDelay } } } } } while ((-not $box.stopPlay) -and [bool]$loop) } catch { $fail = "Playback failed: " + [string]$_.Exception.Message try { $box.playError = $fail } catch { $box.playError = "Playback failed." } try { $box.crashLine = $fail } catch {} } foreach ($heldVk in @($heldKeys.Keys)) { try { [RtFarmKeys179]::Up([byte][int]$heldVk) } catch {} } $box.playing = $false }).AddArgument($seqs).AddArgument([bool]$loop).AddArgument($delay).AddArgument($b).AddArgument($nTimes).AddArgument([bool]$waitPic).AddArgument([string]$watch).AddArgument([string]$glass).AddArgument($keyMs).AddArgument([string]$delayCsv) $play.Runspace = [runspacefactory]::CreateRunspace() $play.Runspace.Open() Keep-FarmPlayJob $play [void]$play.BeginInvoke() return $true } function Test-BlueStacksMinimized { $h = [IntPtr]::Zero try { $h = Find-FarmGameHwnd if ($h -eq [IntPtr]::Zero) { return $false } return [bool][RtFarmGrab]::IsMinimized($h) } catch { return $false } } function Set-FarmStatus([string]$msg) { $lab = $script:farmStatus if (-not $lab) { return } try { if ($lab.IsDisposed) { return } $lab.Text = $msg $lab.BringToFront() } catch {} } function Hide-HelperOverGame { try { if ($script:farmToastTimer) { $script:farmToastTimer.Stop() } } catch {} try { if ($script:farmToast -and -not $script:farmToast.IsDisposed) { $script:farmToast.Close() } } catch {} try { if ($script:glassForm -and -not $script:glassForm.IsDisposed) { $script:glassForm.Close() } } catch {} foreach ($f in @($script:farmForm, $script:chatForm, $form)) { try { if ($f -and -not $f.IsDisposed) { $f.TopMost = $false } } catch {} } } function Show-FarmToast([string]$text, [switch]$NoWindow) { Set-FarmStatus $text try { if ($script:tray) { $script:tray.BalloonTipTitle = "Auto Farm" $script:tray.BalloonTipText = $text $script:tray.ShowBalloonTip(6000) } } catch {} if ($NoWindow) { return } try { if ($script:farmToast -and -not $script:farmToast.IsDisposed) { $script:farmToast.Close() } } catch {} try { $f = New-Object System.Windows.Forms.Form $f.FormBorderStyle = "None" $f.TopMost = $true $f.ShowInTaskbar = $false $f.StartPosition = "Manual" $f.BackColor = [System.Drawing.Color]::FromArgb(20, 24, 28) $f.Size = New-Object System.Drawing.Size(460, 72) $area = [System.Windows.Forms.Screen]::PrimaryScreen.WorkingArea $f.Location = New-Object System.Drawing.Point(($area.Right - 480), ($area.Top + 16)) $lab = New-Object System.Windows.Forms.Label $lab.Text = $text $lab.ForeColor = [System.Drawing.Color]::White $lab.Font = New-Object System.Drawing.Font("Segoe UI", 11, [System.Drawing.FontStyle]::Bold) $lab.Dock = "Fill" $lab.TextAlign = "MiddleCenter" $f.Controls.Add($lab) $f.Show() $script:farmToast = $f $timer = New-Object System.Windows.Forms.Timer $timer.Interval = 4200 $script:farmToastTimer = $timer $timer.Add_Tick({ try { $script:farmToastTimer.Stop() } catch {} try { if ($script:farmToast -and -not $script:farmToast.IsDisposed) { $script:farmToast.Close() } } catch {} }) $timer.Start() } catch {} } function Restore-FarmWindow { try { if ($script:farmForm -and -not $script:farmForm.IsDisposed) { $script:farmForm.WindowState = "Normal" $script:farmForm.TopMost = (-not [bool]$script:farmSplitMode) $script:farmForm.Show() $script:farmForm.BringToFront() } } catch {} try { if ($form -and -not $form.IsDisposed) { $form.WindowState = "Normal" $form.TopMost = $true $form.Show() } } catch {} } function Show-FarmHowTo { $lang = Get-UiLang $txt = Get-FarmHowToText $title = "Auto Farm how to use" if ($lang -ne "en") { try { $txt = Translate-HelperText $txt $lang } catch {} try { $title = Translate-HelperText $title $lang } catch {} } [System.Windows.Forms.MessageBox]::Show( $txt, $title, [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information ) | Out-Null } function Get-FarmSiteUrl { return "https://raidstimer.me/raids-timer/" } function Get-FarmGameCatalog { if ($script:FarmGames -and $script:FarmGames.games) { return $script:FarmGames } $cache = Join-Path $root "farm-game-setup.json" $urls = @( "https://raidstimer.me/raids-timer/farm-game-setup.json", "https://www.raidstimer.me/raids-timer/farm-game-setup.json" ) foreach ($u in $urls) { try { $j = Invoke-RestMethod -Uri $u -TimeoutSec 10 if ($j -and $j.games) { $script:FarmGames = $j try { ($j | ConvertTo-Json -Depth 8) | Set-Content -LiteralPath $cache -Encoding UTF8 } catch {} return $j } } catch {} } if (Test-Path -LiteralPath $cache) { try { $j = Get-Content -LiteralPath $cache -Raw | ConvertFrom-Json if ($j -and $j.games) { $script:FarmGames = $j; return $j } } catch {} } $script:FarmGames = @{ games = @(@{ id = "kingshot"; name = "Kingshot"; troops = @("Infantry","Cavalry","Archers"); map = ""; setup = @("Open Kingshot in BlueStacks. Record the gather taps you use.") }) } return $script:FarmGames } function Get-FarmGameId { try { if ($script:farmBox -and $script:farmBox.farmGame) { return [string]$script:farmBox.farmGame } } catch {} try { $c = Read-Cfg if ($c -and $c.farmGame) { return [string]$c.farmGame } } catch {} return "kingshot" } function Save-FarmGameId([string]$id) { $g = [string]$id if (-not $g) { $g = "kingshot" } try { if ($script:farmBox) { $script:farmBox.farmGame = $g } } catch {} try { $c = Read-Cfg $ht = @{} if ($c) { foreach ($p in $c.PSObject.Properties) { $ht[$p.Name] = $p.Value } } $ht.farmGame = $g ($ht | ConvertTo-Json) | Set-Content -Path $cfgPath -Encoding UTF8 $script:cfg = Read-Cfg } catch {} } function Get-FarmGameRow { $id = Get-FarmGameId $cat = Get-FarmGameCatalog foreach ($g in @($cat.games)) { if ([string]$g.id -eq $id) { return $g } } if ($cat.games -and $cat.games.Count) { return $cat.games[0] } return $null } function Get-FarmHowToText { $row = Get-FarmGameRow $name = "this game" $setup = "" $n = 1 if ($row) { if ($row.name) { $name = [string]$row.name } if ($row.setup) { foreach ($s in @($row.setup)) { $setup += "$n. $s`r`n" $n++ } } } if (-not $setup) { $setup = "1. Open $name in BlueStacks.`r`n" $n = 2 } return @" How to use Auto Farm - $name Orders on this helper Send order (on the clock banner) publishes to the same alliance board as the website. Chat plan is not required for orders. When your alliance shares a wave, this banner counts down (GET READY / SEND NOW). Set in-game name, alliance, and server (same as the website). Optional march time makes SEND = land minus march. What this window does This helper records your clicks and keys, then Play repeats them in play-list order. You farm as the commander at the top (screen name and alliance). How to use (this text) covers every section below. Get set $setup $n. Commander: pick the in-game name this farm belongs to. $($n+1). Game: pick the game. The play list, pictures, and per-screen saves stay with that game. Record and Play $($n+2). Record: the window tucks away. Left-click the game and press the keys you use. $($n+3). Right-click or Stop record saves that step and puts it on the play list only. The list does not fill itself. $($n+4). Every Play press stops any older run and starts fresh at number 1. It runs each numbered row once, in the exact order shown. Stop play or right-click stops. $($n+5). Each play-list row has its own ms. Click the ms on that row to change it. Default 500. Pictures wait that long after they show, then click the middle of the image. $($n+6). Key delay waits after each key. Default 500 ms so typing is not skipped. $($n+7). Loop off means one pass only: every row once, then stop. Loop on is the only way the list repeats; after the last row it starts again at #1. Numbered play list $($n+8). This list is only what you Add, Record, or drag onto it. Each number shows its own ms. $($n+9). Scroll to see every number. Move up / Move down or drag a row to change the order. $($n+10). Remove takes that number off. It does not delete the saved step or picture. Remove picture will not delete an image while any play list still uses it. Saved play list types (Healing troops, Farming, Troop building, Best farming) $($n+11). These types are shared templates for the selected game. They do not by themselves decide which BlueStacks window to farm. $($n+12). Save list stores every numbered row, picture, order, and row delay under that type. If screens are ticked below, it also saves that same list onto those screens. $($n+13). Load list puts the type back on the numbered list. Play saved loads that type and starts at #1. The main Loop check box still controls repeating. Which screen this list is for (checkboxes next to the play list) $($n+14). Tick Screen 1, Screen 2, ... to mark which BlueStacks window the CURRENT numbered list and pictures belong to. Different screens can have different setups and different images. $($n+15). Save for screens writes the actual numbered rows (including pictures) to each ticked screen and keeps them in AppData so a helper restart does not lose them. $($n+16). Load screen puts THAT screen's own saved list back on the numbered list. If a screen has no list yet, the helper says so. It will not use another screen's pictures. $($n+17). Play (top buttons) uses whatever is on the numbered list right now. Play screen on the 2-12 tab loads that screen's saved list first, then farms only that window. Saved steps and calendar $($n+18). Name + Save stores a recorded step. This save is for picks which game that save belongs to. $($n+19). Calendar (left): click the day you mean. Bold days already have a ticked farm. $($n+20). Saved farms (right): tick a name to put that farm on the day you clicked. Untick to take it off that day. $($n+21). Queue today puts the ticks for the day you clicked onto the play list. Pictures already on the play list stay. Click a name, then Add, to put one farm on the play list now. $($n+22). Auto load, when the helper opens, queues farms ticked for today's date. Load selected only fills Name. It does not add to the play list. 2-12 BlueStacks tab - Create instances opens BlueStacks Multi-instance Manager. Create the missing instances there (up to 12), then Refresh. The helper does not clone instances by itself. - Set 2-12 in Screens, RAM for each, and a disk budget. The graph and message say how many this PC can safely run at the same time, and what RAM plus CPU threads you would need for the number you picked. - Each screen is counted as about 2 GB of RAM and 2 CPU threads. Windows keeps about 6 GB of RAM and 2 CPU threads. Example: 12 screens need about 30 GB of RAM (12 x 2 GB plus 6 GB) and 26 CPU threads (2 per screen plus 2 for Windows). - If your count is higher than this PC can run at once, a WARNING says you are out of RAM, CPU, or disk. Auto Farm then opens and farms one screen at a time so 12 games are never running together. - Pick 2-4 in Screens, then Start split view, to tile 2 side by side or 3-4 in a grid with visible dividers. Five or more screens cannot be tiled; Start split view opens screen 1 only. - Each screen's size and Windows desktop spot are saved, the same way the single BlueStacks Save size + location works. Start split view puts 2-4 back next time. - After you move or resize a screen, press Save screen sizes. The helper is no longer forced over the games in split mode. Move it anywhere, or press Hide helper and reopen Auto Farm from the Raids Timer tray icon. - Tick screens next to the numbered play list (not only Assign chosen saved list). Assign chosen saved list still copies a TYPE name onto a row as a reminder. The screen checkbox plus Save for screens is the source of truth for that window's setup and images. - Double-click a screen or Open selected large to focus it. Use for Auto Farm makes only that numbered screen receive recorded clicks, keys, and picture matching. - Play screen loads that screen's own saved list and pictures, starts at #1, and farms that window only. If that screen has no list, it tells you instead of using another screen. - Run checked in order: for each ticked row on this tab, load THAT screen's own list and pictures, play once (unless Loop is on), then the next screen. High counts open the next screen only after the last one finishes, so input and RAM cannot collide. Pictures tab $($n+23). Mag glass: drag around the exact image you see on screen, then let go. The saved preview is that exact visible box. Play clicks its middle and can find it bigger or smaller. $($n+24). Select the picture, then Add picture (next to the play list), or drag it onto the play list. $($n+25). Play stays on that picture number until it finds it on the ACTIVE target screen, waits that row's ms, confirms it is still there, clicks the middle, then the next number. It does not skip the picture. Loop does the same. $($n+26). Only one picture is looked for at a time, in list order, on the window Auto Farm is targeting. It does not search every screen's images at once on the wrong window. $($n+27). Hit any picture clicks whichever saved picture shows (order does not matter). Leave it off for normal farm lists. Remove picture drops one unless a current or saved play list still uses it. Window tab $($n+28). Launch BlueStacks starts it from the helper. Turn on "When helper opens" if you want the helper to launch BlueStacks and restore its saved size automatically. $($n+29). Pick BlueStacks from the window list, then Use window. Move and resize it where you want it. Give that layout a Size label, then Save size + location. $($n+30). Restore size + location moves BlueStacks back to the saved X/Y screen position and saved width/height so recorded clicks hit the same places. Messages tab $($n+31). Paid Chat. Friends are people you mark Friend here. Alliance is your same alliance and server. $($n+32). Tap a name, type, Send. Popup notifications is a tray pop-up for a new message in this chat. Record and share tab $($n+33). Paid Chat. Tick Enable record and share. Window tab: Use window first. $($n+34). Start screen record. Play can keep farming. Stop, then Save clip. $($n+35). Paste your YouTube channel. Send clip to YouTube opens the clip folder and YouTube upload. Chat, PayPal, Share site, Settings $($n+36). PayPal unlock pays Chat. Chat opens messages. Share site is Facebook, Discord, X, TikTok, Instagram. $($n+37). Copy crash log is in Settings (tray -> Settings), next to Check for update. It is not on the Auto Farm page. $($n+38). One Chat subscription is one device. A second device is logged out unless this account bought Chat again. The helper repeats only the clicks and keys you record for $name, plus pictures you saved for the screen being farmed. "@ } function Get-FarmSocialPath { return (Join-Path $root "farm-social.json") } function Read-FarmSocial { $path = Get-FarmSocialPath $base = @{ friends = @(); popup = $false; captureOn = $false; youtube = "" } if (-not (Test-Path -LiteralPath $path)) { return $base } try { $j = Get-Content -LiteralPath $path -Raw -Encoding UTF8 | ConvertFrom-Json if ($j.friends) { $base.friends = @($j.friends) } if ($j.popup -eq $true) { $base.popup = $true } if ($j.captureOn -eq $true) { $base.captureOn = $true } if ($j.youtube) { $base.youtube = [string]$j.youtube } } catch {} return $base } function Write-FarmSocial($social) { try { $social | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Get-FarmSocialPath) -Encoding UTF8 } catch {} } function Farm-RequirePaid([string]$why) { if (Test-ChatPaid) { return $true } Set-FarmStatus $(if ($why) { $why } else { "Unlock Chat first. PayPal or Apple, same commander." }) return $false } function Refresh-FarmPeopleLists { $u = $script:farmUi if (-not $u -or -not $u.msgFriends -or -not $u.msgAlliance) { return } $social = Read-FarmSocial $u.msgFriends.Items.Clear() $script:farmFriendRows = @() foreach ($f in @($social.friends)) { $name = [string]$f.displayName if (-not $name) { continue } [void]$u.msgFriends.Items.Add($name) $script:farmFriendRows += ,$f } $u.msgAlliance.Items.Clear() $script:farmAllyRows = @() try { $id = Get-ChatIdentity if ($id.playerId -and $id.serverNumber -and $id.allianceName) { $raw = Invoke-TrpcGet "raids.listAllianceMembers" @{ playerId = $id.playerId serverNumber = $id.serverNumber allianceName = $id.allianceName displayName = $id.displayName } $data = Unwrap-Trpc $raw foreach ($m in @($data.members)) { $uid = [string]$m.userId $name = [string]$m.displayName if (-not $uid -or -not $name) { continue } if ($uid -eq [string]$id.userId) { continue } [void]$u.msgAlliance.Items.Add($name) $script:farmAllyRows += ,$m } } } catch {} } function Farm-PickPerson($kind) { $u = $script:farmUi if (-not $u) { return } $row = $null if ($kind -eq "friend") { $i = $u.msgFriends.SelectedIndex if ($i -ge 0 -and $script:farmFriendRows -and $i -lt @($script:farmFriendRows).Count) { $row = @($script:farmFriendRows)[$i] } } else { $i = $u.msgAlliance.SelectedIndex if ($i -ge 0 -and $script:farmAllyRows -and $i -lt @($script:farmAllyRows).Count) { $row = @($script:farmAllyRows)[$i] } } if (-not $row) { return } if (-not (Farm-RequirePaid "Messages need the paid Chat plan.")) { return } $id = Get-ChatIdentity try { $raw = Invoke-TrpcPost "raids.openDirectChat" @{ playerId = $id.playerId serverNumber = $id.serverNumber displayName = $id.displayName peerUserId = [string]$row.userId peerDisplayName = [string]$row.displayName } $data = Unwrap-Trpc $raw if (-not $data -or -not $data.conversationId) { if ($u.msgStatus) { $u.msgStatus.Text = "Could not open that chat." } return } $script:farmDmId = [string]$data.conversationId $script:farmDmName = [string]$row.displayName $script:farmDmLastId = "" if ($u.msgTitle) { $u.msgTitle.Text = [string]$row.displayName } Farm-PollDm } catch { if ($u.msgStatus) { $u.msgStatus.Text = "Could not open that chat." } } } function Farm-AddFriendFromAlliance { $u = $script:farmUi $i = 0 try { $i = [int]$u.msgAlliance.SelectedIndex } catch { return } if ($i -lt 0 -or -not $script:farmAllyRows) { return } $row = @($script:farmAllyRows)[$i] if (-not $row) { return } $social = Read-FarmSocial $next = @() foreach ($f in @($social.friends)) { if ([string]$f.userId -ne [string]$row.userId) { $next += $f } } $next = @(@{ userId = [string]$row.userId; displayName = [string]$row.displayName }) + @($next) $social.friends = @($next | Select-Object -First 80) Write-FarmSocial $social Refresh-FarmPeopleLists if ($u.msgStatus) { $u.msgStatus.Text = ("Friend: " + [string]$row.displayName) } } function Farm-PollDm { $u = $script:farmUi if (-not $u -or -not $u.msgLog -or -not $script:farmDmId) { return } try { $id = Get-ChatIdentity $raw = Invoke-TrpcGet "raids.getChat" @{ userId = $id.userId conversationId = $script:farmDmId preferredLang = (Get-UiLang) autoTranslate = $true } $data = Unwrap-Trpc $raw $msgs = @() if ($data -and $data.messages) { $msgs = @($data.messages) } if ($u.msgLog) { $u.msgLog.Text = Format-ChatLog $msgs } $last = $null foreach ($m in $msgs) { $last = $m } if (-not $last) { return } $mid = [string]$last.id if (-not $mid) { $mid = [string]$last.createdAt } $mine = [string]$last.userId -eq [string]$id.userId if ($script:farmDmLastId -and $mid -and $mid -ne $script:farmDmLastId -and -not $mine) { $social = Read-FarmSocial if ($social.popup -and $script:tray) { $script:tray.BalloonTipTitle = [string]$last.senderName $body = [string]$last.messageText if ($body.Length -gt 140) { $body = $body.Substring(0, 140) } $script:tray.BalloonTipText = $body $script:tray.ShowBalloonTip(6000) } } if ($mid) { $script:farmDmLastId = $mid } } catch {} } function Farm-SendDm { $u = $script:farmUi if (-not (Farm-RequirePaid "Messages need the paid Chat plan.")) { return } if (-not $script:farmDmId) { if ($u.msgStatus) { $u.msgStatus.Text = "Pick a friend or an alliance member first." } return } $text = "" try { $text = $u.msgInput.Text.Trim() } catch {} if (-not $text) { return } $u.msgInput.Text = "" $id = Get-ChatIdentity try { Invoke-TrpcPost "raids.sendChat" @{ userId = $id.userId displayName = $id.displayName phone = "" conversationId = $script:farmDmId messageText = $text sourceLang = (Get-UiLang) serverNumber = $id.serverNumber allianceName = $id.allianceName avatarUrl = "" } | Out-Null Farm-PollDm } catch { if ($u.msgStatus) { $u.msgStatus.Text = "Message was not sent." } } } function Get-FarmCaptureRect { $b = $script:farmBox if ($b -and [int]$b.sightW -gt 40 -and [int]$b.sightH -gt 40) { return @{ X = [int]$b.sightX; Y = [int]$b.sightY; W = [int]$b.sightW; H = [int]$b.sightH } } $s = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds return @{ X = [int]$s.X; Y = [int]$s.Y; W = [int]$s.Width; H = [int]$s.Height } } function Grab-FarmFrame { $r = Get-FarmCaptureRect $bmp = New-Object System.Drawing.Bitmap ([int]$r.W), ([int]$r.H) $g = [System.Drawing.Graphics]::FromImage($bmp) try { $g.CopyFromScreen([int]$r.X, [int]$r.Y, 0, 0, (New-Object System.Drawing.Size([int]$r.W, [int]$r.H))) } catch { $g.Dispose() $bmp.Dispose() return $null } $g.Dispose() return $bmp } function Stop-FarmCaptureTimer { try { if ($script:farmCapTimer) { $script:farmCapTimer.Stop(); $script:farmCapTimer.Dispose() } } catch {} $script:farmCapTimer = $null $script:farmCapLive = $false } function Farm-CaptureTick { if (-not $script:farmCapLive) { return } $bmp = Grab-FarmFrame if (-not $bmp) { return } $u = $script:farmUi try { if ($u -and $u.capPreview -and -not $u.capPreview.IsDisposed) { $old = $u.capPreview.Image $u.capPreview.Image = $bmp if ($old) { $old.Dispose() } } else { $bmp.Dispose() return } } catch { $bmp.Dispose() return } if (-not $script:farmCapRecording -or -not $script:farmClipDir) { return } try { $script:farmClipN = [int]$script:farmClipN + 1 $file = Join-Path $script:farmClipDir ("frame_{0:D5}.jpg" -f [int]$script:farmClipN) $u.capPreview.Image.Save($file, [System.Drawing.Imaging.ImageFormat]::Jpeg) } catch {} } function Farm-CaptureStart { $u = $script:farmUi if (-not (Farm-RequirePaid "Record and share needs the paid Chat plan.")) { return } $social = Read-FarmSocial if (-not $social.captureOn) { if ($u.capStatus) { $u.capStatus.Text = "Tick Enable record and share first." } return } Stop-FarmCaptureTimer $script:farmCapLive = $true $script:farmCapRecording = $true $script:farmClipN = 0 $script:farmClipDir = Join-Path $root ("farm-clips\" + (Get-Date -Format "yyyyMMdd-HHmmss")) New-Item -ItemType Directory -Force -Path $script:farmClipDir | Out-Null $timer = New-Object System.Windows.Forms.Timer $timer.Interval = 200 $timer.Add_Tick({ Farm-CaptureTick }) $timer.Start() $script:farmCapTimer = $timer if ($u.capStatus) { $u.capStatus.Text = "Live feed is on and recording. Farm Play can keep going." } } function Farm-CaptureStop { $script:farmCapRecording = $false Stop-FarmCaptureTimer $u = $script:farmUi $dir = [string]$script:farmClipDir $mp4 = "" if ($dir -and (Test-Path -LiteralPath $dir)) { $ff = Get-Command ffmpeg -ErrorAction SilentlyContinue if ($ff) { $mp4 = Join-Path $dir "raids-farm-clip.mp4" try { & $ff.Source -y -framerate 5 -i (Join-Path $dir "frame_%05d.jpg") -c:v libx264 -pix_fmt yuv420p $mp4 2>$null } catch { $mp4 = "" } } } $script:farmClipFile = $(if ($mp4 -and (Test-Path -LiteralPath $mp4)) { $mp4 } else { $dir }) if ($u.capStatus) { if ($script:farmClipFile) { $u.capStatus.Text = "Clip ready. Farm was not stopped. Save clip or send it to YouTube." } else { $u.capStatus.Text = "Stopped. Pick the game window, then start again." } } } function Farm-CaptureSave { $path = [string]$script:farmClipFile if (-not $path -or -not (Test-Path -LiteralPath $path)) { $u = $script:farmUi if ($u.capStatus) { $u.capStatus.Text = "Record a clip first." } return } if ((Get-Item -LiteralPath $path).PSIsContainer) { Start-Process explorer.exe $path } else { Start-Process explorer.exe ("/select,`"$path`"") } } function Farm-YouTube([string]$kind) { $u = $script:farmUi $channel = "" try { $channel = $u.ytBox.Text.Trim() } catch {} if (-not $channel) { if ($u.capStatus) { $u.capStatus.Text = "Paste your YouTube channel link first." } return } $social = Read-FarmSocial $social.youtube = $channel Write-FarmSocial $social if ($kind -eq "upload") { Farm-CaptureSave } $url = $(if ($kind -eq "upload") { "https://www.youtube.com/upload" } else { $channel }) Start-Process $url } function Paint-FarmGameSetup { $u = $script:farmUi if (-not $u -or -not $u.setup) { return } $row = Get-FarmGameRow if (-not $row) { return } $lines = @() if ($row.name) { $lines += [string]$row.name } if ($row.troops) { $lines += "Troops: " + (@($row.troops) -join " · ") } if ($row.map) { $lines += [string]$row.map } if ($row.setup) { $lines += (@($row.setup) -join "`r`n") } $u.setup.Text = ($lines -join "`r`n") } function Macro-MatchesGame($m, [string]$gid) { $mg = "" try { $mg = [string]$m.gameId } catch { $mg = "" } if (-not $mg) { return $true } return ($mg -eq $gid) } function Get-FarmMacrosForGame { $gid = "" try { $gid = [string](Get-FarmGameId) } catch { $gid = "" } $out = New-Object System.Collections.ArrayList foreach ($m in @(Read-FarmMacros)) { if (Macro-MatchesGame $m $gid) { [void]$out.Add($m) } } return @($out) } function Fill-FarmProfileCombo { $u = $script:farmUi if (-not $u -or -not $u.profile) { return } $profiles = @(Find-RaidsProfiles) $script:farmProfiles = $profiles $u.profile.Items.Clear() $sel = 0 $n = 0 $want = "" try { if ($script:cfg) { $want = [string]$script:cfg.code } } catch {} foreach ($p in $profiles) { [void]$u.profile.Items.Add((Format-ProfileLine $p)) if ($want -and [string]$p.code -eq $want) { $sel = $n } $n++ } if ($u.profile.Items.Count -gt 0) { $u.profile.SelectedIndex = $sel } } function Use-FarmProfilePick { $u = $script:farmUi if (-not $u -or -not $u.profile) { return } $idx = [int]$u.profile.SelectedIndex $profiles = @($script:farmProfiles) if ($idx -lt 0 -or $idx -ge $profiles.Count) { return } $pick = $profiles[$idx] Save-Cfg $pick.code $serverDefault $pick $true $script:cfg = Read-Cfg try { Update-IdleTip } catch {} $who = [string]$pick.displayName if (-not $who) { $who = "Commander" } $ally = [string]$pick.allianceName $srv = [string]$pick.serverNumber $logged = "Logged in as $who" if ($ally) { $logged = "$logged | alliance $ally" } if ($srv) { $logged = "$logged | server $srv" } if ($u.lead) { $u.lead.Text = "$logged`r`nRecord clicks and keys. Play repeats the play list. Click delay and Key delay default to 500 ms. Helper " + [string]$script:HelperVersion + "`r`n" + (Format-ChatPaidLine) } Set-FarmStatus ("Using " + (Format-ProfileLine $pick)) } function Fill-FarmGameCombo { $u = $script:farmUi if (-not $u -or -not $u.game) { return } $cat = Get-FarmGameCatalog $want = Get-FarmGameId $u.game.Items.Clear() $idx = 0 $sel = 0 foreach ($g in @($cat.games)) { $lab = [string]$g.name if (-not $lab) { $lab = [string]$g.id } [void]$u.game.Items.Add($lab) if ([string]$g.id -eq $want) { $sel = $idx } $idx++ } if ($u.game.Items.Count -gt 0) { $u.game.SelectedIndex = $sel } Paint-FarmGameSetup } function Get-WeekDayKeys { return @("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat") } function Get-TodayDayKey { switch ([int](Get-Date).DayOfWeek) { 0 { return "Sun" } 1 { return "Mon" } 2 { return "Tue" } 3 { return "Wed" } 4 { return "Thu" } 5 { return "Fri" } default { return "Sat" } } } function Get-MacroDays($m) { $keys = Get-WeekDayKeys $raw = @() try { $raw = @($m.days) } catch { $raw = @() } $out = New-Object System.Collections.Generic.List[string] foreach ($d in $raw) { $k = [string]$d if ($keys -contains $k) { [void]$out.Add($k) } } if ($out.Count -lt 1) { return $keys } return @($out) } function Macro-OnDay($m, $dayKey) { $days = Get-MacroDays $m return ($days -contains $dayKey) } function Get-FarmGameNameById([string]$gid) { if (-not $gid) { return "Any game" } $cat = Get-FarmGameCatalog foreach ($g in @($cat.games)) { if ([string]$g.id -eq $gid) { $n = [string]$g.name if ($n) { return $n } return $gid } } return $gid } function Get-FarmComboGameId($box) { if (-not $box) { return [string](Get-FarmGameId) } $i = -1 try { $i = [int]$box.SelectedIndex } catch { $i = -1 } $cat = Get-FarmGameCatalog $list = @($cat.games) if ($i -ge 0 -and $i -lt $list.Count) { return [string]$list[$i].id } return [string](Get-FarmGameId) } function Fill-FarmSaveGameCombo { $u = $script:farmUi if (-not $u -or -not $u.saveGame) { return } $cat = Get-FarmGameCatalog $want = Get-FarmGameId $u.saveGame.Items.Clear() $idx = 0 $sel = 0 foreach ($g in @($cat.games)) { $lab = [string]$g.name if (-not $lab) { $lab = [string]$g.id } [void]$u.saveGame.Items.Add($lab) if ([string]$g.id -eq $want) { $sel = $idx } $idx++ } if ($u.saveGame.Items.Count -gt 0) { $u.saveGame.SelectedIndex = $sel } } function Sync-FarmSaveGameComboFromList { $u = $script:farmUi $box = $script:farmList if (-not $u -or -not $u.saveGame -or -not $box -or $box.SelectedIndex -lt 0) { return } $all = @(Read-FarmMacros) if ($box.SelectedIndex -ge $all.Count) { return } $gid = "" try { $gid = [string]$all[$box.SelectedIndex].gameId } catch { $gid = "" } if (-not $gid) { $gid = Get-FarmGameId } $cat = Get-FarmGameCatalog $list = @($cat.games) $i = 0 foreach ($g in $list) { if ([string]$g.id -eq $gid) { $u.saveGame.SelectedIndex = $i return } $i++ } } function Set-FarmSelectedSaveGame { $box = $script:farmList $u = $script:farmUi if (-not $box -or $box.SelectedIndex -lt 0) { Set-FarmStatus "Pick a saved farm, then choose which game it is for." return } $all = @(Read-FarmMacros) if ($box.SelectedIndex -ge $all.Count) { return } $gid = Get-FarmComboGameId $u.saveGame $old = $all[$box.SelectedIndex] $dates = @() try { $dates = @($old.dates) } catch { $dates = @() } $row = [pscustomobject]@{ name = [string]$old.name events = $old.events days = @(Get-MacroDays $old) dates = $dates saved = [string]$old.saved gameId = $gid } $all[$box.SelectedIndex] = $row Write-FarmMacros $all Refresh-FarmMacroList $box if ($box.Items.Count -gt 0) { $box.SelectedIndex = [Math]::Min($box.SelectedIndex, $box.Items.Count - 1) } Set-FarmStatus ("This save is for " + (Get-FarmGameNameById $gid)) } function Format-FarmMacroLabel($m) { $nm = [string]$m.name if (-not $nm) { $nm = "macro" } $g = Get-FarmGameNameById ([string]$m.gameId) return ($nm + " · " + $g) } function Format-FarmPicQueueLabel([string]$file, [string]$name) { $rel = [string]$file try { $dir = Get-FarmGlassDir if ($rel.StartsWith($dir, [StringComparison]::OrdinalIgnoreCase)) { $rel = $rel.Substring($dir.Length).TrimStart('\', '/') } } catch {} if (-not $name) { $name = [IO.Path]::GetFileNameWithoutExtension($rel) } if (-not $name) { $name = "picture" } return ("pic:" + $rel + "|" + $name) } function Resolve-FarmPicFile([string]$label) { $fp = Get-FarmPicQueueFile $label if ($fp -and (Test-Path -LiteralPath $fp)) { return $fp } $name = "" $s = [string]$label if ($s.StartsWith("pic:")) { $rest = $s.Substring(4) $i = $rest.IndexOf("|") if ($i -ge 0) { $name = $rest.Substring($i + 1) } } $dir = Get-FarmGlassDir $match = "" $only = "" $n = 0 foreach ($row in @(Read-FarmGlassList)) { $f = [string]$row.file if (-not $f) { continue } if (-not [IO.Path]::IsPathRooted($f)) { $f = Join-Path $dir $f } if (-not (Test-Path -LiteralPath $f)) { continue } $n++ $only = $f if ($name -and [string]$row.name -eq $name) { $match = $f } } if ($match) { return $match } if ($n -eq 1) { return $only } return "" } function Get-FarmPicQueueFile([string]$label) { $s = [string]$label if (-not $s.StartsWith("pic:")) { return "" } $rest = $s.Substring(4) $i = $rest.IndexOf("|") $rel = $(if ($i -ge 0) { $rest.Substring(0, $i) } else { $rest }) if (-not $rel) { return "" } if (-not [IO.Path]::IsPathRooted($rel)) { return (Join-Path (Get-FarmGlassDir) $rel) } return $rel } function Import-FarmPictureFile([string]$path) { if (-not $path -or -not (Test-Path -LiteralPath $path)) { return "" } $bmp = $null try { $fs = [IO.File]::Open($path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::ReadWrite) $tmp = New-Object System.Drawing.Bitmap $fs $fs.Close() $bmp = New-Object System.Drawing.Bitmap $tmp $tmp.Dispose() } catch { return "" } $name = [IO.Path]::GetFileNameWithoutExtension($path) $ok = $false try { $ok = [bool](Add-FarmGlassBitmap $bmp $name) } catch { $ok = $false } try { if ($bmp) { $bmp.Dispose() } } catch {} if (-not $ok) { return "" } $all = @(Read-FarmGlassList) if ($all.Count -lt 1) { return "" } $row = $all[$all.Count - 1] return (Format-FarmPicQueueLabel ([string]$row.file) ([string]$row.name)) } function Insert-FarmQueueLabel([string]$label, $index) { $q = $script:farmQueue if (-not $q -or -not $label) { return $false } if ($q.Items.Count -ge (Get-FarmQueueMax)) { Show-FarmToast ("Play list is full (" + (Get-FarmQueueMax) + "). Remove one first.") return $false } if (-not (Add-FarmQueueRow $label $index $null)) { return $false } try { Save-FarmPlayOrderFromUi } catch {} try { Place-FarmQueueMsEditor } catch {} return $true } function Get-FarmMacroNameFromLabel([string]$label) { $s = [string]$label $i = $s.IndexOf(" | ") if ($i -gt 0) { $s = $s.Substring(0, $i).Trim() } $j = $s.IndexOf(" · ") if ($j -gt 0) { return $s.Substring(0, $j).Trim() } return $s.Trim() } function Get-FarmDayChecks { $keys = Get-WeekDayKeys $picked = New-Object System.Collections.Generic.List[string] $boxes = $script:farmDayBoxes if (-not $boxes) { return $keys } foreach ($k in $keys) { try { if ($boxes[$k] -and $boxes[$k].Checked) { [void]$picked.Add($k) } } catch {} } if ($picked.Count -lt 1) { return $keys } return @($picked) } function Set-FarmDayChecks($days) { $keys = Get-WeekDayKeys $want = @($days) if ($want.Count -lt 1) { $want = $keys } $boxes = $script:farmDayBoxes if (-not $boxes) { return } foreach ($k in $keys) { try { if ($boxes[$k]) { $boxes[$k].Checked = ($want -contains $k) } } catch {} } } function Find-FarmMacroByName([string]$nm) { $want = ([string]$nm).Trim() if (-not $want) { return $null } $gid = "" try { $gid = [string](Get-FarmGameId) } catch { $gid = "" } $fallback = $null $loose = $null foreach ($m in @(Read-FarmMacros)) { $have = ([string]$m.name).Trim() if (-not $have) { continue } $sameGame = $false try { $sameGame = [bool](Macro-MatchesGame $m $gid) } catch { $sameGame = $true } if ($have -eq $want) { if ($sameGame) { return $m } if (-not $fallback) { $fallback = $m } continue } if ($sameGame -and ($have.StartsWith($want) -or $want.StartsWith($have))) { if (-not $loose) { $loose = $m } } } if ($fallback) { return $fallback } return $loose } function Get-FarmPlayRowsNow { $rows = New-Object System.Collections.ArrayList $q = $null try { $q = $script:farmQueue } catch { $q = $null } if ($q -and $q.Items.Count -gt 0) { Ensure-FarmQueueMs $i = 0 foreach ($nm in @($q.Items)) { $s = [string]$nm if ($s) { [void]$rows.Add(@{ label = $s; ms = (Get-FarmQueueStepMs $i) }) } $i++ } return @($rows) } $map = $null try { $map = Read-FarmPlayOrderMap } catch { $map = $null } $gid = "" try { $gid = [string](Get-FarmGameId) } catch { $gid = "" } if (-not $gid) { $gid = "kingshot" } if ($map -and $map.ContainsKey($gid)) { foreach ($nm in @($map[$gid])) { $row = Split-FarmQueueStored $nm if ($row.item) { [void]$rows.Add(@{ label = [string]$row.item; ms = $row.ms }) } } } return @($rows) } function Get-FarmPlayLabelsNow { $labs = New-Object System.Collections.ArrayList foreach ($row in @(Get-FarmPlayRowsNow)) { $s = [string]$row.label if ($s) { [void]$labs.Add($s) } } return @($labs) } function Macro-OnCalendarDay($m, [datetime]$day) { $key = $day.ToString("yyyy-MM-dd") try { foreach ($d in @($m.dates)) { if ([string]$d -eq $key) { return $true } } } catch {} return $false } function Get-FarmCalendarMarks { $set = @{} foreach ($m in @(Read-FarmMacros)) { try { foreach ($d in @($m.dates)) { $s = [string]$d if ($s -match '^\d{4}-\d{2}-\d{2}$') { $set[$s] = $true } } } catch {} } $arr = New-Object System.Collections.Generic.List[datetime] foreach ($k in @($set.Keys)) { try { [void]$arr.Add([datetime]::ParseExact([string]$k, "yyyy-MM-dd", $null)) } catch {} } return @($arr) } function Update-FarmCalendarMarks { $cal = $script:farmCal if (-not $cal -or $cal.IsDisposed) { return } $marks = @(Get-FarmCalendarMarks) try { $cal.RemoveAllBoldedDates() if ($marks.Count -gt 0) { $cal.BoldedDates = [datetime[]]$marks } } catch {} } function Paint-FarmCalendarChecks { $box = $script:farmList $cal = $script:farmCal if (-not $box -or -not $cal) { return } $key = $cal.SelectionStart.Date.ToString("yyyy-MM-dd") $all = @(Read-FarmMacros) $script:farmCalPaint = $true try { $n = [Math]::Min([int]$box.Items.Count, [int]$all.Count) for ($i = 0; $i -lt $n; $i++) { $on = $false try { $on = [bool](Macro-OnCalendarDay $all[$i] $cal.SelectionStart.Date) } catch { $on = $false } try { $box.SetItemChecked($i, [bool]$on) } catch {} } } finally { $script:farmCalPaint = $false } } function Set-FarmMacroOnDate([int]$index, [datetime]$day, [bool]$on) { $all = @(Read-FarmMacros) if ($index -lt 0 -or $index -ge $all.Count) { return } $old = $all[$index] $key = $day.Date.ToString("yyyy-MM-dd") $dates = New-Object System.Collections.Generic.List[string] $seen = @{} try { foreach ($d in @($old.dates)) { $s = [string]$d if ($s -match '^\d{4}-\d{2}-\d{2}$' -and -not $seen.ContainsKey($s)) { $seen[$s] = $true [void]$dates.Add($s) } } } catch {} if ($on) { if (-not $seen.ContainsKey($key)) { [void]$dates.Add($key) } } else { try { [void]$dates.Remove($key) } catch {} } $row = [pscustomobject]@{ name = [string]$old.name events = $old.events days = @(Get-MacroDays $old) dates = @($dates) saved = [string]$old.saved gameId = [string]$old.gameId } $all[$index] = $row Write-FarmMacros $all try { Update-FarmCalendarMarks } catch {} } function Get-FarmCalendarDay { $day = (Get-Date).Date try { if ($script:farmCal -and -not $script:farmCal.IsDisposed) { $day = $script:farmCal.SelectionStart.Date } } catch {} return $day } function Get-FarmMacrosOnDay([datetime]$day) { $out = New-Object System.Collections.ArrayList foreach ($m in @(Read-FarmMacros)) { if (Macro-OnCalendarDay $m $day.Date) { [void]$out.Add($m) } } return @($out) } function Get-TodayFarmMacros { return @(Get-FarmMacrosOnDay (Get-Date).Date) } function Fill-FarmQueueForDay([datetime]$day) { $q = $script:farmQueue if (-not $q) { return 0 } Ensure-FarmQueueMs $keep = New-Object System.Collections.ArrayList try { $i = 0 foreach ($it in @($q.Items)) { $s = [string]$it if ($s.StartsWith("pic:")) { [void]$keep.Add(@{ item = $s; ms = (Get-FarmQueueStepMs $i) }) } $i++ } } catch {} $q.Items.Clear() $script:farmQueueMs = New-Object System.Collections.ArrayList foreach ($row in $keep) { if ($q.Items.Count -ge (Get-FarmQueueMax)) { break } [void](Add-FarmQueueRow ([string]$row.item) $null $row.ms) } $n = 0 $def = Get-FarmDefaultStepMs foreach ($m in @(Get-FarmMacrosOnDay $day.Date)) { if ($q.Items.Count -ge (Get-FarmQueueMax)) { break } [void](Add-FarmQueueRow (Format-FarmMacroLabel $m) $null $def) $n++ } try { Save-FarmPlayOrderFromUi } catch {} try { Place-FarmQueueMsEditor } catch {} return [int]$n } function Fill-TodayFarmQueue { return (Fill-FarmQueueForDay (Get-Date).Date) } function Save-FarmAutoLoad([bool]$on) { try { $c = Read-Cfg $ht = @{} if ($c) { foreach ($p in $c.PSObject.Properties) { $ht[$p.Name] = $p.Value } } $ht.farmAutoLoad = [bool]$on if ($on) { $ht.farmAutoLoadDay = (Get-Date).ToString("yyyy-MM-dd") } ($ht | ConvertTo-Json) | Set-Content -Path $cfgPath -Encoding UTF8 $script:cfg = Read-Cfg } catch {} } function Invoke-FarmAutoLoadToday { $c = $null try { $c = Read-Cfg } catch { $c = $null } $on = $false try { $on = [bool]$c.farmAutoLoad } catch { $on = $false } if (-not $on) { return 0 } $today = (Get-Date).ToString("yyyy-MM-dd") $did = "" try { $did = [string]$c.farmAutoLoadDay } catch { $did = "" } if ($did -eq $today) { return 0 } $n = Fill-TodayFarmQueue Save-FarmAutoLoad $true return $n } function Read-SocialLinks { $p = Join-Path $root "social-links.json" $blank = @{ facebook = ""; discord = ""; x = ""; tiktok = ""; instagram = "" } if (-not (Test-Path -LiteralPath $p)) { return $blank } try { $j = Get-Content -LiteralPath $p -Raw -Encoding UTF8 | ConvertFrom-Json foreach ($k in @("facebook", "discord", "x", "tiktok", "instagram")) { try { $blank[$k] = [string]$j.$k } catch {} } } catch {} return $blank } function Write-SocialLinks($row) { $p = Join-Path $root "social-links.json" $obj = @{ facebook = [string]$row.facebook discord = [string]$row.discord x = [string]$row.x tiktok = [string]$row.tiktok instagram = [string]$row.instagram } ($obj | ConvertTo-Json) | Set-Content -LiteralPath $p -Encoding UTF8 } function Open-HelperUrl([string]$url) { if (-not $url) { return } try { Start-Process $url | Out-Null } catch { try { [System.Diagnostics.Process]::Start($url) | Out-Null } catch {} } } function Copy-HelperText([string]$text) { try { [System.Windows.Forms.Clipboard]::SetText([string]$text) } catch {} } function Share-HelperNetwork([string]$which) { $site = Get-FarmSiteUrl $shareText = "Raids Timer - rally timers, Chat, and Auto Farm. $site" $links = Read-SocialLinks if ($script:shareBoxes) { foreach ($k in @("facebook", "discord", "x", "tiktok", "instagram")) { try { $links[$k] = [string]$script:shareBoxes[$k].Text } catch {} } } $enc = [uri]::EscapeDataString($shareText) $uenc = [uri]::EscapeDataString($site) if ($which -eq "facebook") { Open-HelperUrl ("https://www.facebook.com/sharer/sharer.php?u=" + $uenc) } elseif ($which -eq "x") { Open-HelperUrl ("https://twitter.com/intent/tweet?text=" + $enc) } elseif ($which -eq "discord") { Copy-HelperText $shareText if ($links.discord) { Open-HelperUrl $links.discord } else { Open-HelperUrl "https://discord.com/channels/@me" } } elseif ($which -eq "tiktok") { Copy-HelperText $shareText if ($links.tiktok) { Open-HelperUrl $links.tiktok } else { Open-HelperUrl "https://www.tiktok.com/" } } elseif ($which -eq "instagram") { Copy-HelperText $shareText if ($links.instagram) { Open-HelperUrl $links.instagram } else { Open-HelperUrl "https://www.instagram.com/" } } } function Show-ShareSite { $site = Get-FarmSiteUrl $shareText = "Raids Timer - rally timers, Chat, and Auto Farm. $site" $links = Read-SocialLinks $dlg = New-Object System.Windows.Forms.Form $dlg.Text = Helper-T "Share Raids Timer" $dlg.FormBorderStyle = "FixedDialog" $dlg.StartPosition = "CenterScreen" $dlg.MaximizeBox = $false $dlg.MinimizeBox = $false $dlg.TopMost = $true $dlg.ClientSize = New-Object System.Drawing.Size(520, 430) if ($script:appIcon) { $dlg.Icon = $script:appIcon } $lead = New-Object System.Windows.Forms.Label $lead.Location = New-Object System.Drawing.Point(12, 10) $lead.Size = New-Object System.Drawing.Size(496, 40) $lead.Text = (Helper-T "Share the website. Save your Facebook, Discord, X, TikTok, and Instagram links if you want.") $urlLab = New-Object System.Windows.Forms.Label $urlLab.Location = New-Object System.Drawing.Point(12, 54) $urlLab.Size = New-Object System.Drawing.Size(80, 20) $urlLab.Text = Helper-T "Link" $urlBox = New-Object System.Windows.Forms.TextBox $urlBox.Location = New-Object System.Drawing.Point(96, 52) $urlBox.Size = New-Object System.Drawing.Size(300, 22) $urlBox.ReadOnly = $true $urlBox.Text = $site $btnCopy = New-Object System.Windows.Forms.Button $btnCopy.Text = Helper-T "Copy link" $btnCopy.Location = New-Object System.Drawing.Point(404, 50) $btnCopy.Size = New-Object System.Drawing.Size(100, 26) $btnCopy.Add_Click({ Copy-HelperText $shareText [void][System.Windows.Forms.MessageBox]::Show((Helper-T "Link copied. Paste it in Discord, TikTok, or Instagram."), (Helper-T "Share Raids Timer")) }) $y = 90 $fields = @( @{ k = "facebook"; lab = "Facebook" }, @{ k = "discord"; lab = "Discord" }, @{ k = "x"; lab = "X" }, @{ k = "tiktok"; lab = "TikTok" }, @{ k = "instagram"; lab = "Instagram" } ) $boxes = @{} $script:shareBoxes = $boxes foreach ($f in $fields) { $lab = New-Object System.Windows.Forms.Label $lab.Text = $f.lab $lab.Location = New-Object System.Drawing.Point(12, $y) $lab.Size = New-Object System.Drawing.Size(80, 20) $tb = New-Object System.Windows.Forms.TextBox $tb.Location = New-Object System.Drawing.Point(96, $y) $tb.Size = New-Object System.Drawing.Size(300, 22) $tb.Text = [string]$links[$f.k] $boxes[$f.k] = $tb $btn = New-Object System.Windows.Forms.Button $btn.Text = Helper-T "Share" $btn.Location = New-Object System.Drawing.Point(404, ($y - 2)) $btn.Size = New-Object System.Drawing.Size(100, 26) $btn.Tag = [string]$f.k $btn.Add_Click({ Share-HelperNetwork ([string]$this.Tag) }) $dlg.Controls.Add($lab) $dlg.Controls.Add($tb) $dlg.Controls.Add($btn) $y += 32 } $dlg.Controls.Add($lead) $dlg.Controls.Add($urlLab) $dlg.Controls.Add($urlBox) $dlg.Controls.Add($btnCopy) $save = New-Object System.Windows.Forms.Button $save.Text = Helper-T "Save links" $save.Location = New-Object System.Drawing.Point(96, 260) $save.Size = New-Object System.Drawing.Size(140, 32) $save.Add_Click({ Write-SocialLinks @{ facebook = $boxes.facebook.Text.Trim() discord = $boxes.discord.Text.Trim() x = $boxes.x.Text.Trim() tiktok = $boxes.tiktok.Text.Trim() instagram = $boxes.instagram.Text.Trim() } [void][System.Windows.Forms.MessageBox]::Show((Helper-T "Saved on this PC."), (Helper-T "Share Raids Timer")) }) $close = New-Object System.Windows.Forms.Button $close.Text = Helper-T "Close" $close.Location = New-Object System.Drawing.Point(404, 380) $close.Size = New-Object System.Drawing.Size(100, 32) $close.Add_Click({ Close-ClickedHelperForm }) $hint = New-Object System.Windows.Forms.Label $hint.Location = New-Object System.Drawing.Point(12, 300) $hint.Size = New-Object System.Drawing.Size(496, 70) $hint.Text = Helper-T "Facebook and X open a share page with the Raids Timer link. Discord, TikTok, and Instagram copy the link so you can paste it. Profile boxes are optional." $dlg.Controls.Add($save) $dlg.Controls.Add($hint) $dlg.Controls.Add($close) $dlg.ShowDialog() | Out-Null } function Refresh-FarmMacroList($box) { if (-not $box) { return } $keep = -1 try { $keep = [int]$box.SelectedIndex } catch { $keep = -1 } $script:farmCalPaint = $true try { $box.Items.Clear() foreach ($m in @(Read-FarmMacros)) { [void]$box.Items.Add((Format-FarmMacroLabel $m)) } } finally { $script:farmCalPaint = $false } if ($keep -ge 0 -and $keep -lt $box.Items.Count) { try { $box.SelectedIndex = $keep } catch {} } try { Paint-FarmCalendarChecks } catch {} try { Update-FarmCalendarMarks } catch {} } function Fit-FarmWindowLayout { $f = $script:farmForm $u = $script:farmUi if (-not $f -or $f.IsDisposed -or -not $u) { return } if ($script:farmFitBusy) { return } $script:farmFitBusy = $true try { $visW = [int]$f.ClientSize.Width $visH = [int]$f.ClientSize.Height if ($visW -lt 1) { $visW = 560 } if ($visH -lt 1) { $visH = 720 } $needH = 1140 $i = 0 try { $i = [int]$u.tabs.SelectedIndex } catch { $i = 0 } $script:farmLastTabLayoutIndex = $i $wide = ($i -eq 2 -or $i -eq 3) if ($wide) { $needH = [Math]::Max(720, $visH) } $h = [Math]::Max($needH, $visH) $w = $visW if ($h -gt $visH) { $w = $visW - 22 } if ($w -lt 520) { $w = 520 } $script:farmContentW = $w $script:farmContentH = $h try { if ($u.scroll -and -not $u.scroll.IsDisposed) { $u.scroll.AutoScrollMinSize = New-Object System.Drawing.Size($w, $h) } } catch {} try { if ($u.lead) { $u.lead.Width = $w - 24 } } catch {} try { if ($script:farmStatus) { $script:farmStatus.Width = [Math]::Max(180, $w - 24) } } catch {} try { if ($u.profile) { $u.profile.Width = $w - 104 } } catch {} try { if ($u.game) { $u.game.Width = $w - 76 } } catch {} try { if ($u.setup) { $u.setup.Width = $w - 24 } } catch {} try { if ($u.playlistInfo) { $u.playlistInfo.Width = $w - 24 } } catch {} try { if ($u.playlistScreensLbl) { $u.playlistScreensLbl.Width = $w - 24 } } catch {} $screenBoxW = [Math]::Max(200, $w - 24 - 156) try { if ($u.playlistScreens -and -not $u.playlistScreens.IsDisposed) { $u.playlistScreens.Width = $screenBoxW $sx = 12 + $screenBoxW + 8 $sy = [int]$u.playlistScreens.Top if ($u.playlistSaveScreens) { $u.playlistSaveScreens.Location = New-Object System.Drawing.Point($sx, $sy); $u.playlistSaveScreens.Size = New-Object System.Drawing.Size([Math]::Max(108, $w - $sx - 12), 32) } if ($u.playlistLoadScreen) { $u.playlistLoadScreen.Location = New-Object System.Drawing.Point($sx, ($sy + 36)); $u.playlistLoadScreen.Size = New-Object System.Drawing.Size([Math]::Max(108, $w - $sx - 12), 32) } } } catch {} $bot = 44 $qTop = 430 try { if ($u.qLbl) { $u.qLbl.Location = New-Object System.Drawing.Point(12, ($qTop - 34)); $u.qLbl.Width = $w - 32 } } catch {} $q = $null try { $q = $u.qList } catch { $q = $null } if (-not $q) { try { $q = $script:farmQueue } catch { $q = $null } } $qh = 204 if ($q -and -not $q.IsDisposed) { $side = 156 $qw = [Math]::Max(200, $w - 24 - $side) $q.Location = New-Object System.Drawing.Point(12, $qTop) $q.Width = $qw $q.Height = $qh $qx = 12 + $qw + 8 try { if ($u.addQ) { $u.addQ.Location = New-Object System.Drawing.Point($qx, $qTop) } } catch {} try { if ($u.upQ) { $u.upQ.Location = New-Object System.Drawing.Point($qx, ($qTop + 36)) } } catch {} try { if ($u.downQ) { $u.downQ.Location = New-Object System.Drawing.Point($qx, ($qTop + 84)) } } catch {} try { if ($u.remQ) { $u.remQ.Location = New-Object System.Drawing.Point($qx, ($qTop + 132)) } } catch {} try { if ($u.addPicQ) { $u.addPicQ.Location = New-Object System.Drawing.Point($qx, ($qTop + 168)) } } catch {} $bw = [Math]::Max(108, $w - $qx - 12) try { if ($u.addQ) { $u.addQ.Size = New-Object System.Drawing.Size($bw, 32) } } catch {} try { if ($u.upQ) { $u.upQ.Size = New-Object System.Drawing.Size($bw, 44) } } catch {} try { if ($u.downQ) { $u.downQ.Size = New-Object System.Drawing.Size($bw, 44) } } catch {} try { if ($u.remQ) { $u.remQ.Size = New-Object System.Drawing.Size($bw, 32) } } catch {} try { if ($u.addPicQ) { $u.addPicQ.Size = New-Object System.Drawing.Size($bw, 32) } } catch {} try { Place-FarmQueueMsEditor } catch {} } $nameY = $qTop + $qh + 8 $sgY = $nameY + 30 $todayW = 118 $saveW = 70 $nameBoxW = [Math]::Max(72, $w - 12 - 48 - 8 - $saveW - 8 - $todayW - 12) $saveX = 12 + 48 + $nameBoxW + 8 $todayX = $saveX + $saveW + 8 try { if ($u.nameLbl) { $u.nameLbl.Location = New-Object System.Drawing.Point(12, ($nameY + 4)) } } catch {} try { if ($u.nameBox) { $u.nameBox.Location = New-Object System.Drawing.Point(60, $nameY); $u.nameBox.Width = $nameBoxW } } catch {} try { if ($u.save) { $u.save.Location = New-Object System.Drawing.Point($saveX, ($nameY - 2)); $u.save.Width = $saveW } } catch {} try { if ($u.today) { $u.today.Location = New-Object System.Drawing.Point($todayX, ($nameY - 2)); $u.today.Width = $todayW } } catch {} $setW = 88 $autoW = 92 $sgLblW = 108 $comboW = [Math]::Max(90, $w - 12 - $sgLblW - 8 - $setW - 8 - $autoW - 12) $comboX = 12 + $sgLblW + 8 $setX = $comboX + $comboW + 8 $autoX = $setX + $setW + 8 try { if ($u.saveGameLbl) { $u.saveGameLbl.Location = New-Object System.Drawing.Point(12, ($sgY + 4)); $u.saveGameLbl.Width = $sgLblW } } catch {} try { if ($u.saveGame) { $u.saveGame.Location = New-Object System.Drawing.Point($comboX, $sgY); $u.saveGame.Width = $comboW } } catch {} try { if ($u.setGame) { $u.setGame.Location = New-Object System.Drawing.Point($setX, ($sgY - 2)); $u.setGame.Width = $setW } } catch {} try { if ($u.autoLoad) { $u.autoLoad.Location = New-Object System.Drawing.Point($autoX, ($sgY + 2)); $u.autoLoad.Width = $autoW } } catch {} $calY = $sgY + 32 try { if ($u.savesHow) { $u.savesHow.Location = New-Object System.Drawing.Point(12, $calY); $u.savesHow.Width = $w - 24; $u.savesHow.Height = 22 } } catch {} $calY2 = $calY + 24 try { if ($u.cal) { $u.cal.Location = New-Object System.Drawing.Point(8, $calY2) } } catch {} $calW = 220 $calH = 162 try { if ($u.cal -and -not $u.cal.IsDisposed) { $calW = [Math]::Max(180, [int]$u.cal.Width); $calH = [Math]::Max(140, [int]$u.cal.Height) } } catch {} $listX = 8 + $calW + 8 if ($listX -gt ($w - 150)) { $listX = [Math]::Max(200, $w / 2) } $listW = [Math]::Max(140, $w - $listX - 12) try { if ($u.listHead) { $u.listHead.Location = New-Object System.Drawing.Point($listX, $calY2); $u.listHead.Width = $listW; $u.listHead.Height = 18 } } catch {} try { if ($u.listHow) { $u.listHow.Location = New-Object System.Drawing.Point($listX, ($calY2 + 18)); $u.listHow.Width = $listW; $u.listHow.Height = 36 } } catch {} $listTop = $calY2 + 56 $listH = [Math]::Max(88, $calH - 56) try { if ($script:farmList -and -not $script:farmList.IsDisposed) { $script:farmList.Location = New-Object System.Drawing.Point($listX, $listTop) $script:farmList.Size = New-Object System.Drawing.Size($listW, $listH) } } catch {} $blockH = [Math]::Max($calH, (56 + $listH)) $tabsY = $calY2 + $blockH + 8 $script:farmTabsY = $tabsY if (-not $wide) { $needH = [Math]::Max(1140, $tabsY + 230 + $bot) $h = [Math]::Max($needH, $visH) $script:farmContentH = $h try { if ($u.scroll -and -not $u.scroll.IsDisposed) { $u.scroll.AutoScrollMinSize = New-Object System.Drawing.Size($w, $h) } } catch {} } if ($wide) { $tabsY = 150 $script:farmTabsY = $tabsY } $tabsH = $h - $tabsY - $bot if ($tabsH -lt 180) { $tabsH = 180 } try { $u.tabs.Location = New-Object System.Drawing.Point(12, $tabsY) $u.tabs.Size = New-Object System.Drawing.Size(($w - 24), $tabsH) } catch {} try { if ($u.load) { $u.load.Location = New-Object System.Drawing.Point(12, ($h - 36)) } } catch {} try { if ($u.close) { $u.close.Location = New-Object System.Drawing.Point(($w - 124), ($h - 36)) } } catch {} Fit-FarmMainTabs } finally { $script:farmFitBusy = $false } } function Fit-FarmMainTabs { $u = $script:farmUi if (-not $u -or -not $u.tabs -or $u.tabs.IsDisposed) { return } $i = 0 try { $i = [int]$u.tabs.SelectedIndex } catch { $i = 0 } $wide = ($i -eq 2 -or $i -eq 3) $fw = 560 $fh = 1028 try { if ($script:farmContentW) { $fw = [int]$script:farmContentW } if ($script:farmContentH) { $fh = [int]$script:farmContentH } } catch {} try { if ((-not $script:farmContentW) -and $script:farmForm -and -not $script:farmForm.IsDisposed) { $fw = [int]$script:farmForm.ClientSize.Width $fh = [int]$script:farmForm.ClientSize.Height } } catch {} if ($fw -lt 520) { $fw = 520 } $tw = $fw - 24 $tabsY = 752 try { if ($script:farmTabsY) { $tabsY = [int]$script:farmTabsY } } catch {} if ($wide) { $tabsY = 150 } $th = $fh - $tabsY - 44 if ($th -lt 180) { $th = 180 } $u.tabs.Location = New-Object System.Drawing.Point(12, $tabsY) $u.tabs.Size = New-Object System.Drawing.Size($tw, $th) if ($wide) { $u.tabs.BringToFront() } $pw = [Math]::Max(200, $tw - 16) try { if ($u.picHow) { $u.picHow.Width = $pw } } catch {} try { if ($u.winHow) { $u.winHow.Width = $pw } } catch {} try { if ($u.glass) { $glW = [Math]::Max(140, [Math]::Min(240, $pw - 170)) $u.glass.Width = $glW $u.glass.Height = 68 if ($u.glassPreview) { $px = 8 + $glW + 8 $u.glassPreview.Location = New-Object System.Drawing.Point($px, 70) $u.glassPreview.Size = New-Object System.Drawing.Size([Math]::Max(90, $pw - $px), 86) } } } catch {} try { if ($u.autoBlue) { $u.autoBlue.Width = [Math]::Max(220, $pw - 148) } $wb = [Math]::Max(96, $pw - 272) if ($u.win) { $u.win.Location = New-Object System.Drawing.Point(104, 72); $u.win.Width = $wb } if ($u.winRef) { $u.winRef.Location = New-Object System.Drawing.Point((104 + $wb + 8), 70) } if ($u.winUse) { $u.winUse.Location = New-Object System.Drawing.Point((104 + $wb + 96), 70) } if ($u.sizeNameLbl) { $u.sizeNameLbl.Location = New-Object System.Drawing.Point(8, 106) } $nameW = [Math]::Max(70, $pw - 384) if ($u.sizeName) { $u.sizeName.Location = New-Object System.Drawing.Point(88, 104); $u.sizeName.Width = $nameW } $sx = 88 + $nameW + 8 if ($u.saveSize) { $u.saveSize.Location = New-Object System.Drawing.Point($sx, 102) } if ($u.saveSize) { $u.saveSize.Width = 132 } if ($u.restoreSize) { $u.restoreSize.Location = New-Object System.Drawing.Point(($sx + 140), 102); $u.restoreSize.Width = 148 } if ($u.sightLab) { $u.sightLab.Location = New-Object System.Drawing.Point(8, 138); $u.sightLab.Width = $pw; $u.sightLab.Height = 110 } } catch {} try { if ($u.msgHow) { $u.msgHow.Width = $pw } } catch {} try { if ($u.capHow) { $u.capHow.Width = $pw } } catch {} try { if ($u.msgFriends) { if ($wide) { if ($u.msgHow) { $u.msgHow.Size = New-Object System.Drawing.Size(490, 40) } if ($u.msgPopup) { $u.msgPopup.Location = New-Object System.Drawing.Point(8, 48) } if ($u.msgFriendLbl) { $u.msgFriendLbl.Location = New-Object System.Drawing.Point(8, 74) } $u.msgFriends.Location = New-Object System.Drawing.Point(8, 92) $u.msgFriends.Size = New-Object System.Drawing.Size(150, 280) if ($u.msgAllyLbl) { $u.msgAllyLbl.Location = New-Object System.Drawing.Point(8, 380) } $u.msgAlliance.Location = New-Object System.Drawing.Point(8, 398) $u.msgAlliance.Size = New-Object System.Drawing.Size(150, 200) if ($u.btnFriend) { $u.btnFriend.Location = New-Object System.Drawing.Point(8, 608) } if ($u.btnMsgRefresh) { $u.btnMsgRefresh.Location = New-Object System.Drawing.Point(82, 608) } if ($u.msgTitle) { $u.msgTitle.Location = New-Object System.Drawing.Point(168, 74) } $u.msgLog.Location = New-Object System.Drawing.Point(168, 92) $u.msgLog.Size = New-Object System.Drawing.Size(330, 500) $u.msgInput.Location = New-Object System.Drawing.Point(168, 600) if ($u.btnMsgSend) { $u.btnMsgSend.Location = New-Object System.Drawing.Point(414, 598) } $u.msgStatus.Location = New-Object System.Drawing.Point(168, 632) } else { if ($u.msgHow) { $u.msgHow.Size = New-Object System.Drawing.Size(490, 48) } if ($u.msgPopup) { $u.msgPopup.Location = New-Object System.Drawing.Point(8, 54) } if ($u.msgFriendLbl) { $u.msgFriendLbl.Location = New-Object System.Drawing.Point(8, 78) } $u.msgFriends.Location = New-Object System.Drawing.Point(8, 96) $u.msgFriends.Size = New-Object System.Drawing.Size(150, 90) if ($u.msgAllyLbl) { $u.msgAllyLbl.Location = New-Object System.Drawing.Point(8, 188) } $u.msgAlliance.Location = New-Object System.Drawing.Point(8, 206) $u.msgAlliance.Size = New-Object System.Drawing.Size(150, 70) if ($u.btnFriend) { $u.btnFriend.Location = New-Object System.Drawing.Point(8, 278) } if ($u.btnMsgRefresh) { $u.btnMsgRefresh.Location = New-Object System.Drawing.Point(82, 278) } if ($u.msgTitle) { $u.msgTitle.Location = New-Object System.Drawing.Point(168, 78) } $u.msgLog.Location = New-Object System.Drawing.Point(168, 98) $u.msgLog.Size = New-Object System.Drawing.Size(330, 150) $u.msgInput.Location = New-Object System.Drawing.Point(168, 254) if ($u.btnMsgSend) { $u.btnMsgSend.Location = New-Object System.Drawing.Point(414, 252) } $u.msgStatus.Location = New-Object System.Drawing.Point(168, 282) } } } catch {} try { if ($u.capPreview) { if ($wide) { if ($u.capHow) { $u.capHow.Size = New-Object System.Drawing.Size(490, 50) } if ($u.capEnable) { $u.capEnable.Location = New-Object System.Drawing.Point(8, 58) } $u.capPreview.Location = New-Object System.Drawing.Point(8, 86) $u.capPreview.Size = New-Object System.Drawing.Size(240, 280) if ($u.btnCapStart) { $u.btnCapStart.Location = New-Object System.Drawing.Point(258, 86) } if ($u.btnCapStop) { $u.btnCapStop.Location = New-Object System.Drawing.Point(404, 86) } if ($u.btnCapSave) { $u.btnCapSave.Location = New-Object System.Drawing.Point(258, 122) } if ($u.ytLbl) { $u.ytLbl.Location = New-Object System.Drawing.Point(258, 162) } if ($u.ytBox) { $u.ytBox.Location = New-Object System.Drawing.Point(258, 180) } if ($u.btnYtUp) { $u.btnYtUp.Location = New-Object System.Drawing.Point(258, 214) } if ($u.btnYtLive) { $u.btnYtLive.Location = New-Object System.Drawing.Point(258, 248) } if ($u.capStatus) { $u.capStatus.Location = New-Object System.Drawing.Point(8, 376) $u.capStatus.Size = New-Object System.Drawing.Size(492, 70) } } else { if ($u.capHow) { $u.capHow.Size = New-Object System.Drawing.Size(490, 58) } if ($u.capEnable) { $u.capEnable.Location = New-Object System.Drawing.Point(8, 66) } $u.capPreview.Location = New-Object System.Drawing.Point(8, 92) $u.capPreview.Size = New-Object System.Drawing.Size(240, 135) if ($u.btnCapStart) { $u.btnCapStart.Location = New-Object System.Drawing.Point(258, 92) } if ($u.btnCapStop) { $u.btnCapStop.Location = New-Object System.Drawing.Point(404, 92) } if ($u.btnCapSave) { $u.btnCapSave.Location = New-Object System.Drawing.Point(258, 126) } if ($u.ytLbl) { $u.ytLbl.Location = New-Object System.Drawing.Point(258, 162) } if ($u.ytBox) { $u.ytBox.Location = New-Object System.Drawing.Point(258, 180) } if ($u.btnYtUp) { $u.btnYtUp.Location = New-Object System.Drawing.Point(258, 208) } if ($u.btnYtLive) { $u.btnYtLive.Location = New-Object System.Drawing.Point(258, 240) } if ($u.capStatus) { $u.capStatus.Location = New-Object System.Drawing.Point(8, 236) $u.capStatus.Size = New-Object System.Drawing.Size(240, 70) } } } } catch {} } function Show-AutoFarm { try { if (-not $script:cfg) { $script:cfg = Read-Cfg } try { Sync-SavedCommanderFromBrowser | Out-Null } catch {} if ($script:farmForm -and -not $script:farmForm.IsDisposed) { $script:farmForm.WindowState = "Normal" $script:farmForm.StartPosition = "CenterScreen" $script:farmForm.Show() $script:farmForm.BringToFront() $script:farmForm.Activate() try { Apply-HelperToolLang } catch {} try { Fill-FarmGameCombo } catch {} try { Fill-FarmSaveGameCombo } catch {} try { Fill-FarmProfileCombo } catch {} try { Refresh-FarmMacroList $script:farmList } catch {} try { Invoke-FarmAutoLoadToday | Out-Null } catch {} try { $paid = $false try { $paid = Test-ChatPaid } catch {} try { if ($script:farmBox) { $script:farmBox.chatPaid = [bool]$paid } } catch {} if ($script:farmUi -and $script:farmUi.pay) { $script:farmUi.pay.Visible = ($script:chatPayState -eq "unpaid") } if ((Test-ChatNeedsPayPalPrompt) -and -not $script:payPalPrompted) { $script:payPalPrompted = $true Show-PayPalUnlockPrompt } } catch {} return } $dlg = New-Object System.Windows.Forms.Form $dlg.Text = "Auto Farm " + [string]$script:HelperVersion $startH = 980 try { $wa = [System.Windows.Forms.Screen]::FromPoint([System.Windows.Forms.Cursor]::Position).WorkingArea $startH = [Math]::Min(980, [Math]::Max(480, $wa.Height - 28)) } catch {} $dlg.Size = New-Object System.Drawing.Size(560, $startH) $dlg.MinimumSize = New-Object System.Drawing.Size(480, 400) $dlg.StartPosition = "CenterScreen" $dlg.TopMost = $true $dlg.MinimizeBox = $true $dlg.MaximizeBox = $true $dlg.ShowInTaskbar = $true $dlg.FormBorderStyle = "Sizable" $dlg.AutoScroll = $false $dlg.AcceptButton = $null $dlg.CancelButton = $null try { $dlg.Icon = $script:appIcon } catch {} $scroll = New-Object System.Windows.Forms.Panel $scroll.Dock = [System.Windows.Forms.DockStyle]::Fill $scroll.AutoScroll = $true $scroll.AutoScrollMinSize = New-Object System.Drawing.Size(536, 1140) $scroll.Add_MouseWheel({ param($sender, $e) try { $p = $sender.AutoScrollPosition $ny = (-1 * $p.Y) - $e.Delta if ($ny -lt 0) { $ny = 0 } $sender.AutoScrollPosition = New-Object System.Drawing.Point((-1 * $p.X), $ny) } catch {} }) $who = "Commander" $ally = "" if ($script:cfg -and $script:cfg.displayName) { $who = [string]$script:cfg.displayName } if ($script:cfg -and $script:cfg.allianceName) { $ally = [string]$script:cfg.allianceName } $logged = "Logged in as $who" if ($ally) { $logged = "Logged in as $who | alliance $ally" } $lead = New-Object System.Windows.Forms.Label $lead.Location = New-Object System.Drawing.Point(12, 8) $lead.Size = New-Object System.Drawing.Size(530, 72) $lead.Text = "$logged`r`nRecord clicks and keys. Play repeats the play list. Click delay and Key delay default to 500 ms. Helper " + [string]$script:HelperVersion + "`r`n" + (Format-ChatPaidLine) $status = New-Object System.Windows.Forms.Label $status.Location = New-Object System.Drawing.Point(12, 58) $status.Size = New-Object System.Drawing.Size(396, 28) $status.BackColor = [System.Drawing.Color]::Gold $status.ForeColor = [System.Drawing.Color]::Black $status.Text = "Ready" $btnRec = New-Object System.Windows.Forms.Button $btnRec.Text = "Record" $btnRec.Location = New-Object System.Drawing.Point(12, 86) $btnRec.Size = New-Object System.Drawing.Size(90, 28) $btnStopRec = New-Object System.Windows.Forms.Button $btnStopRec.Text = "Stop record" $btnStopRec.Location = New-Object System.Drawing.Point(108, 86) $btnStopRec.Size = New-Object System.Drawing.Size(100, 28) $btnPlay = New-Object System.Windows.Forms.Button $btnPlay.Text = "Play" $btnPlay.Location = New-Object System.Drawing.Point(214, 86) $btnPlay.Size = New-Object System.Drawing.Size(90, 28) $btnStopPlay = New-Object System.Windows.Forms.Button $btnStopPlay.Text = "Stop play" $btnStopPlay.Location = New-Object System.Drawing.Point(310, 86) $btnStopPlay.Size = New-Object System.Drawing.Size(100, 28) $btnHow = New-Object System.Windows.Forms.Button $btnHow.Text = "How to use" $btnHow.Location = New-Object System.Drawing.Point(416, 86) $btnHow.Size = New-Object System.Drawing.Size(96, 28) $btnChat = New-Object System.Windows.Forms.Button $btnChat.Text = "Chat" $btnChat.Location = New-Object System.Drawing.Point(138, 118) $btnChat.Size = New-Object System.Drawing.Size(70, 28) $btnShare = New-Object System.Windows.Forms.Button $btnShare.Text = "Share site" $btnShare.Location = New-Object System.Drawing.Point(214, 118) $btnShare.Size = New-Object System.Drawing.Size(90, 28) $btnPay = New-Object System.Windows.Forms.Button $btnPay.Text = "PayPal unlock" $btnPay.Location = New-Object System.Drawing.Point(12, 118) $btnPay.Size = New-Object System.Drawing.Size(120, 28) $loop = New-Object System.Windows.Forms.CheckBox $loop.Text = "Loop" $loop.Location = New-Object System.Drawing.Point(310, 120) $loop.Size = New-Object System.Drawing.Size(56, 22) $loop.Checked = $false $delayLbl = New-Object System.Windows.Forms.Label $delayLbl.Text = "Click delay (ms)" $delayLbl.Location = New-Object System.Drawing.Point(12, 152) $delayLbl.Size = New-Object System.Drawing.Size(110, 20) $delayBox = New-Object System.Windows.Forms.NumericUpDown $delayBox.Location = New-Object System.Drawing.Point(122, 148) $delayBox.Size = New-Object System.Drawing.Size(64, 22) $delayBox.Minimum = 0 $delayBox.Maximum = 5000 $delayBox.Increment = 50 $delayBox.Value = 500 $keyDelayLbl = New-Object System.Windows.Forms.Label $keyDelayLbl.Text = "Key delay (ms)" $keyDelayLbl.Location = New-Object System.Drawing.Point(196, 152) $keyDelayLbl.Size = New-Object System.Drawing.Size(100, 20) $keyDelayBox = New-Object System.Windows.Forms.NumericUpDown $keyDelayBox.Location = New-Object System.Drawing.Point(298, 148) $keyDelayBox.Size = New-Object System.Drawing.Size(64, 22) $keyDelayBox.Minimum = 0 $keyDelayBox.Maximum = 5000 $keyDelayBox.Increment = 50 $keyDelayBox.Value = 500 $delayHelp = New-Object System.Windows.Forms.Label $delayHelp.Text = "Default 500. Each play-list row has its own ms. Click the yellow ms to change it." $delayHelp.Location = New-Object System.Drawing.Point(368, 146) $delayHelp.Size = New-Object System.Drawing.Size(176, 36) $profLbl = New-Object System.Windows.Forms.Label $profLbl.Text = "Commander" $profLbl.Location = New-Object System.Drawing.Point(12, 186) $profLbl.Size = New-Object System.Drawing.Size(78, 20) $profBox = New-Object System.Windows.Forms.ComboBox $profBox.DropDownStyle = "DropDownList" $profBox.Location = New-Object System.Drawing.Point(92, 182) $profBox.Size = New-Object System.Drawing.Size(440, 24) $profBox.Add_SelectedIndexChanged({ try { Use-FarmProfilePick } catch {} }) $gameLbl = New-Object System.Windows.Forms.Label $gameLbl.Text = "Game" $gameLbl.Location = New-Object System.Drawing.Point(12, 218) $gameLbl.Size = New-Object System.Drawing.Size(50, 20) $gameBox = New-Object System.Windows.Forms.ComboBox $gameBox.DropDownStyle = "DropDownList" $gameBox.Location = New-Object System.Drawing.Point(64, 214) $gameBox.Size = New-Object System.Drawing.Size(468, 24) $gameBox.Add_SelectedIndexChanged({ try { $u = $script:farmUi if (-not $u -or -not $u.game) { return } $i = [int]$u.game.SelectedIndex $cat = Get-FarmGameCatalog $list = @($cat.games) if ($i -ge 0 -and $i -lt $list.Count) { Save-FarmGameId ([string]$list[$i].id) Paint-FarmGameSetup Refresh-FarmMacroList $script:farmList try { Load-FarmPlayOrderToUi } catch {} try { Refresh-FarmPlaylistStatus } catch {} try { Refresh-FarmPlaylistScreenBoxes } catch {} } } catch {} }) $qLbl = New-Object System.Windows.Forms.Label $qLbl.Text = "Play list rule: Play always starts at #1 and does each row once in this order. Only Loop repeats the list. Pictures stay saved and wait until found." $qLbl.Location = New-Object System.Drawing.Point(12, 396) $qLbl.Size = New-Object System.Drawing.Size(528, 32) $qList = New-Object System.Windows.Forms.ListBox $qList.Location = New-Object System.Drawing.Point(12, 430) $qList.Size = New-Object System.Drawing.Size(360, 204) $qList.AllowDrop = $true $qList.IntegralHeight = $false $qList.HorizontalScrollbar = $false $qList.ScrollAlwaysVisible = $true $qList.DrawMode = [System.Windows.Forms.DrawMode]::OwnerDrawFixed $qList.ItemHeight = 42 $qList.Add_DrawItem({ param($sender, $e) if ($e.Index -lt 0) { return } $e.DrawBackground() $t = [string]$sender.Items[$e.Index] $num = ([string]($e.Index + 1)) + "." $tx = [float]($e.Bounds.X + 28) $brush = New-Object System.Drawing.SolidBrush $e.ForeColor $e.Graphics.DrawString($num, $e.Font, $brush, [float]($e.Bounds.X + 4), [float]($e.Bounds.Y + 12)) if ($t.StartsWith("pic:")) { $bar = $t.IndexOf("|") $nm = $(if ($bar -ge 0) { $t.Substring($bar + 1) } else { "picture" }) $fp = Resolve-FarmPicFile $t if ($fp -and (Test-Path -LiteralPath $fp)) { $img = $null try { $fs = [IO.File]::Open($fp, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::ReadWrite) $img = New-Object System.Drawing.Bitmap $fs $fs.Close() $e.Graphics.DrawImage($img, ($e.Bounds.X + 26), ($e.Bounds.Y + 4), 34, 34) $tx = [float]($e.Bounds.X + 66) } catch {} try { if ($img) { $img.Dispose() } } catch {} } $t = "Picture · " + $nm } $e.Graphics.DrawString($t, $e.Font, $brush, $tx, [float]($e.Bounds.Y + 12)) $ms = 500 try { $ms = Get-FarmQueueStepMs ([int]$e.Index) } catch { $ms = 500 } $msText = ([string]$ms) + " ms" $msRect = New-Object System.Drawing.Rectangle (($e.Bounds.Right - 80), ($e.Bounds.Y + 10), 74, 22) $msBack = New-Object System.Drawing.SolidBrush ([System.Drawing.Color]::FromArgb(255, 232, 196, 40)) $msInk = New-Object System.Drawing.SolidBrush ([System.Drawing.Color]::Black) $e.Graphics.FillRectangle($msBack, $msRect) $e.Graphics.DrawString($msText, $e.Font, $msInk, [float]($msRect.X + 6), [float]($msRect.Y + 3)) $msBack.Dispose() $msInk.Dispose() $brush.Dispose() $e.DrawFocusRectangle() }) $qMsBox = New-Object System.Windows.Forms.NumericUpDown $qMsBox.Minimum = 0 $qMsBox.Maximum = 8000 $qMsBox.Increment = 50 $qMsBox.Value = 500 $qMsBox.Size = New-Object System.Drawing.Size(80, 22) $qMsBox.Visible = $false $qMsBox.Add_ValueChanged({ if ($script:farmQueueMsBusy) { return } $q = $script:farmQueue if (-not $q -or $q.SelectedIndex -lt 0) { return } Set-FarmQueueStepMs ([int]$q.SelectedIndex) $this.Value try { Save-FarmPlayOrderFromUi } catch {} try { $q.Invalidate() } catch {} }) $qList.Add_SelectedIndexChanged({ try { Place-FarmQueueMsEditor } catch {} }) $qList.Add_MouseEnter({ param($sender, $e) try { if ($script:farmNameBox -and $script:farmNameBox.Focused) { return } [void]$sender.Focus() } catch {} }) $qList.Add_MouseDown({ param($sender, $e) if ($e.Button -ne [System.Windows.Forms.MouseButtons]::Left) { return } $hit = $sender.IndexFromPoint($e.Location) if ($hit -ge 0) { $sender.SelectedIndex = $hit } $msHit = $false try { if ($hit -ge 0) { $ir = $sender.GetItemRectangle($hit) if ($e.X -ge ($ir.Right - 84)) { $msHit = $true } } } catch { $msHit = $false } if ($msHit) { $script:queueDragPt = $null try { Place-FarmQueueMsEditor } catch {} try { if ($script:farmUi -and $script:farmUi.qMs) { [void]$script:farmUi.qMs.Focus() } } catch {} return } $script:queueDragPt = $e.Location }) $qList.Add_MouseMove({ param($sender, $e) if ($e.Button -ne [System.Windows.Forms.MouseButtons]::Left -or -not $script:queueDragPt) { return } if ([Math]::Abs($e.X - $script:queueDragPt.X) -lt 8 -and [Math]::Abs($e.Y - $script:queueDragPt.Y) -lt 8) { return } $script:queueDragPt = $null $i = $qList.SelectedIndex if ($i -lt 0) { return } [void]$qList.DoDragDrop(("move:" + $i), [System.Windows.Forms.DragDropEffects]::Move) }) $qList.Add_MouseWheel({ param($sender, $e) if ($qList.Items.Count -lt 2) { return } $step = 1 if ($e.Delta -gt 0) { $step = -1 } $vis = [Math]::Max(1, [int][Math]::Floor($qList.ClientSize.Height / [Math]::Max(1, $qList.ItemHeight))) $maxTop = [Math]::Max(0, $qList.Items.Count - $vis) $next = [int]$qList.TopIndex + $step if ($next -lt 0) { $next = 0 } if ($next -gt $maxTop) { $next = $maxTop } $qList.TopIndex = $next try { Place-FarmQueueMsEditor } catch {} try { $e.Handled = $true } catch {} }) $qList.Add_KeyDown({ param($sender, $e) if (-not $e.Control) { return } if ($e.KeyCode -eq [System.Windows.Forms.Keys]::Up) { Move-FarmQueueSelected -1 try { $e.Handled = $true; $e.SuppressKeyPress = $true } catch {} } elseif ($e.KeyCode -eq [System.Windows.Forms.Keys]::Down) { Move-FarmQueueSelected 1 try { $e.Handled = $true; $e.SuppressKeyPress = $true } catch {} } }) $qList.Add_DragEnter({ param($sender, $e) $e.Effect = [System.Windows.Forms.DragDropEffects]::All }) $qList.Add_DragOver({ param($sender, $e) $e.Effect = [System.Windows.Forms.DragDropEffects]::All try { $p = $qList.PointToClient((New-Object System.Drawing.Point $e.X, $e.Y)) Scroll-FarmQueueToward ([int]$p.Y) } catch {} }) $qList.Add_DragDrop({ param($sender, $e) $p = $qList.PointToClient((New-Object System.Drawing.Point $e.X, $e.Y)) $to = $qList.IndexFromPoint($p) if ($to -lt 0) { $to = $qList.Items.Count } $text = "" try { $text = [string]$e.Data.GetData([System.Windows.Forms.DataFormats]::Text) } catch {} if (-not $text) { try { $text = [string]$e.Data.GetData([string]) } catch {} } if ($text.StartsWith("move:")) { $from = 0 try { $from = [int]$text.Substring(5) } catch { return } if ($from -lt 0 -or $from -ge $qList.Items.Count -or $from -eq $to) { return } $item = $qList.Items[$from] Ensure-FarmQueueMs $ms = Get-FarmQueueStepMs $from $qList.Items.RemoveAt($from) if ($from -lt $script:farmQueueMs.Count) { $script:farmQueueMs.RemoveAt($from) } if ($to -gt $from) { $to = $to - 1 } if ($to -lt 0) { $to = 0 } if ($to -gt $qList.Items.Count) { $to = $qList.Items.Count } $qList.Items.Insert($to, $item) $script:farmQueueMs.Insert($to, $ms) $qList.SelectedIndex = $to try { Save-FarmPlayOrderFromUi } catch {} try { Place-FarmQueueMsEditor } catch {} return } if ($text.StartsWith("pic:")) { if (Insert-FarmQueueLabel $text $to) { Show-FarmToast "Picture added. Play clicks it when that image shows, then the next step." } return } $files = @() try { $files = @($e.Data.GetData([System.Windows.Forms.DataFormats]::FileDrop)) } catch {} $added = 0 foreach ($fp in $files) { if ([string]$fp -notmatch '\.(png|jpg|jpeg|bmp|gif|webp)$') { continue } $lab = Import-FarmPictureFile ([string]$fp) if ($lab -and (Insert-FarmQueueLabel $lab $to)) { $added++; $to++ } } if ($added -gt 0) { Show-FarmToast ("Added " + $added + " picture(s). Play clicks each when that image shows, in this order.") } }) $btnAddQ = New-Object System.Windows.Forms.Button $btnAddQ.Text = "Add" $btnAddQ.Location = New-Object System.Drawing.Point(380, 430) $btnAddQ.Size = New-Object System.Drawing.Size(148, 32) $btnUpQ = New-Object System.Windows.Forms.Button $btnUpQ.Text = "Move up" $btnUpQ.Location = New-Object System.Drawing.Point(380, 466) $btnUpQ.Size = New-Object System.Drawing.Size(148, 44) $btnDownQ = New-Object System.Windows.Forms.Button $btnDownQ.Text = "Move down" $btnDownQ.Location = New-Object System.Drawing.Point(380, 514) $btnDownQ.Size = New-Object System.Drawing.Size(148, 44) $btnRemQ = New-Object System.Windows.Forms.Button $btnRemQ.Text = "Remove" $btnRemQ.Location = New-Object System.Drawing.Point(380, 562) $btnRemQ.Size = New-Object System.Drawing.Size(148, 32) $btnAddPicQ = New-Object System.Windows.Forms.Button $btnAddPicQ.Text = "Add picture" $btnAddPicQ.Location = New-Object System.Drawing.Point(380, 598) $btnAddPicQ.Size = New-Object System.Drawing.Size(148, 32) $nameLbl = New-Object System.Windows.Forms.Label $nameLbl.Text = "Name" $nameLbl.Location = New-Object System.Drawing.Point(12, 556) $nameLbl.Size = New-Object System.Drawing.Size(48, 20) $nameBox = New-Object System.Windows.Forms.TextBox $nameBox.Location = New-Object System.Drawing.Point(60, 552) $nameBox.Size = New-Object System.Drawing.Size(160, 22) $nameBox.Text = "Gather" $btnSave = New-Object System.Windows.Forms.Button $btnSave.Text = "Save" $btnSave.Location = New-Object System.Drawing.Point(228, 550) $btnSave.Size = New-Object System.Drawing.Size(70, 28) $btnToday = New-Object System.Windows.Forms.Button $btnToday.Text = "Queue today" $btnToday.Location = New-Object System.Drawing.Point(304, 550) $btnToday.Size = New-Object System.Drawing.Size(224, 28) $saveGameLbl = New-Object System.Windows.Forms.Label $saveGameLbl.Text = "This save is for" $saveGameLbl.Location = New-Object System.Drawing.Point(12, 584) $saveGameLbl.Size = New-Object System.Drawing.Size(108, 20) $saveGameBox = New-Object System.Windows.Forms.ComboBox $saveGameBox.DropDownStyle = "DropDownList" $saveGameBox.Location = New-Object System.Drawing.Point(122, 580) $saveGameBox.Size = New-Object System.Drawing.Size(190, 24) $btnSetGame = New-Object System.Windows.Forms.Button $btnSetGame.Text = "Set game" $btnSetGame.Location = New-Object System.Drawing.Point(318, 578) $btnSetGame.Size = New-Object System.Drawing.Size(88, 28) $autoLoad = New-Object System.Windows.Forms.CheckBox $autoLoad.Text = "Auto load" $autoLoad.Location = New-Object System.Drawing.Point(414, 582) $autoLoad.Size = New-Object System.Drawing.Size(120, 22) $autoOn = $false try { if ($script:cfg -and $script:cfg.farmAutoLoad) { $autoOn = [bool]$script:cfg.farmAutoLoad } } catch { $autoOn = $false } $autoLoad.Checked = $autoOn $savesHow = New-Object System.Windows.Forms.Label $savesHow.Text = "Left: pick a day. Right: tick which saved farms run on that day." $savesHow.Location = New-Object System.Drawing.Point(12, 610) $savesHow.Size = New-Object System.Drawing.Size(528, 22) $cal = New-Object System.Windows.Forms.MonthCalendar $cal.Location = New-Object System.Drawing.Point(8, 624) $cal.MaxSelectionCount = 1 $cal.ShowToday = $true $cal.ShowTodayCircle = $true $cal.CalendarDimensions = New-Object System.Drawing.Size(1, 1) try { $cal.Font = New-Object System.Drawing.Font("Segoe UI", 7) } catch {} $script:farmCal = $cal $listHead = New-Object System.Windows.Forms.Label $listHead.Text = "Saved farms" $listHead.Location = New-Object System.Drawing.Point(248, 634) $listHead.Size = New-Object System.Drawing.Size(284, 18) $listHow = New-Object System.Windows.Forms.Label $listHow.Text = "Tick = that day. Queue today fills the play list from this day. Add = one farm now." $listHow.Location = New-Object System.Drawing.Point(248, 652) $listHow.Size = New-Object System.Drawing.Size(284, 36) $list = New-Object System.Windows.Forms.CheckedListBox $list.Location = New-Object System.Drawing.Point(248, 688) $list.Size = New-Object System.Drawing.Size(284, 108) $list.CheckOnClick = $true $list.IntegralHeight = $false $script:farmList = $list Refresh-FarmMacroList $list $list.Add_SelectedIndexChanged({ try { Sync-FarmSaveGameComboFromList } catch {} }) $list.Add_ItemCheck({ param($sender, $e) if ($script:farmCalPaint) { return } $on = ($e.NewValue -eq [System.Windows.Forms.CheckState]::Checked) $day = (Get-Date).Date try { if ($script:farmCal) { $day = $script:farmCal.SelectionStart.Date } } catch {} Set-FarmMacroOnDate ([int]$e.Index) $day ([bool]$on) $nm = "" try { $nm = [string]$sender.Items[$e.Index] } catch { $nm = "farm" } $when = $day.ToString("ddd MMM d") if ($on) { Set-FarmStatus ($nm + " is on " + $when + ". Queue today puts that day's ticks on the play list.") } else { Set-FarmStatus ($nm + " is off " + $when + ".") } }) $cal.Add_DateChanged({ try { Paint-FarmCalendarChecks } catch {} try { $day = Get-FarmCalendarDay Set-FarmStatus ("Ticks on the right are for " + $day.ToString("ddd MMM d") + ". Queue today uses this day.") } catch {} }) $autoLoad.Add_CheckedChanged({ if ($script:farmCalPaint) { return } $on = $false try { $on = [bool]$this.Checked } catch { $on = $false } Save-FarmAutoLoad $on if ($on) { $n = Fill-TodayFarmQueue Set-FarmStatus ("Auto load is on. " + $n + " farm(s) ticked for today are on the play list.") } else { Set-FarmStatus "Auto load is off." } }) $tabs = New-Object System.Windows.Forms.TabControl $tabs.Location = New-Object System.Drawing.Point(12, 752) $tabs.Size = New-Object System.Drawing.Size(520, 230) $tabPics = New-Object System.Windows.Forms.TabPage $tabPics.Text = "Pictures" $tabWin = New-Object System.Windows.Forms.TabPage $tabWin.Text = "Window" $tabMsg = New-Object System.Windows.Forms.TabPage $tabMsg.Text = "Messages" $tabCap = New-Object System.Windows.Forms.TabPage $tabCap.Text = "Record & share" $tabInstances = New-Object System.Windows.Forms.TabPage $tabInstances.Text = "2-12 BlueStacks" $tabInstances.AutoScroll = $true $tabInstances.AutoScrollMinSize = New-Object System.Drawing.Size(0, 620) [void]$tabs.TabPages.Add($tabPics) [void]$tabs.TabPages.Add($tabWin) [void]$tabs.TabPages.Add($tabMsg) [void]$tabs.TabPages.Add($tabCap) [void]$tabs.TabPages.Add($tabInstances) $instanceCapacity = New-Object System.Windows.Forms.Label $instanceCapacity.Location = New-Object System.Drawing.Point(8, 8) $instanceCapacity.Size = New-Object System.Drawing.Size(490, 64) $instanceCapacity.Text = "Checking this PC..." $instanceNeed = New-Object System.Windows.Forms.Label $instanceNeed.Location = New-Object System.Drawing.Point(8, 74) $instanceNeed.Size = New-Object System.Drawing.Size(490, 40) $instanceNeed.Text = "Recommended RAM and CPU will show here." $instanceCountLbl = New-Object System.Windows.Forms.Label $instanceCountLbl.Text = "Screens 2-12" $instanceCountLbl.Location = New-Object System.Drawing.Point(8, 122) $instanceCountLbl.Size = New-Object System.Drawing.Size(86, 20) $instanceCount = New-Object System.Windows.Forms.NumericUpDown $instanceCount.Minimum = 2 $instanceCount.Maximum = 12 $instanceCount.Location = New-Object System.Drawing.Point(96, 118) $instanceCount.Size = New-Object System.Drawing.Size(52, 22) $instanceRamLbl = New-Object System.Windows.Forms.Label $instanceRamLbl.Text = "RAM each (GB)" $instanceRamLbl.Location = New-Object System.Drawing.Point(156, 122) $instanceRamLbl.Size = New-Object System.Drawing.Size(100, 20) $instanceRam = New-Object System.Windows.Forms.NumericUpDown $instanceRam.Minimum = 2 $instanceRam.Maximum = 8 $instanceRam.Location = New-Object System.Drawing.Point(258, 118) $instanceRam.Size = New-Object System.Drawing.Size(52, 22) $instanceDiskLbl = New-Object System.Windows.Forms.Label $instanceDiskLbl.Text = "Disk budget each" $instanceDiskLbl.Location = New-Object System.Drawing.Point(316, 122) $instanceDiskLbl.Size = New-Object System.Drawing.Size(116, 20) $instanceDisk = New-Object System.Windows.Forms.NumericUpDown $instanceDisk.Minimum = 8 $instanceDisk.Maximum = 64 $instanceDisk.Increment = 2 $instanceDisk.Location = New-Object System.Drawing.Point(430, 118) $instanceDisk.Size = New-Object System.Drawing.Size(60, 22) $instanceRamGraphLbl = New-Object System.Windows.Forms.Label $instanceRamGraphLbl.Text = "Planned RAM" $instanceRamGraphLbl.Location = New-Object System.Drawing.Point(8, 150) $instanceRamGraphLbl.Size = New-Object System.Drawing.Size(100, 18) $instanceRamGraph = New-Object System.Windows.Forms.ProgressBar $instanceRamGraph.Location = New-Object System.Drawing.Point(112, 148) $instanceRamGraph.Size = New-Object System.Drawing.Size(378, 18) $instanceDiskGraphLbl = New-Object System.Windows.Forms.Label $instanceDiskGraphLbl.Text = "Disk budget" $instanceDiskGraphLbl.Location = New-Object System.Drawing.Point(8, 174) $instanceDiskGraphLbl.Size = New-Object System.Drawing.Size(100, 18) $instanceDiskGraph = New-Object System.Windows.Forms.ProgressBar $instanceDiskGraph.Location = New-Object System.Drawing.Point(112, 172) $instanceDiskGraph.Size = New-Object System.Drawing.Size(378, 18) $instanceListLbl = New-Object System.Windows.Forms.Label $instanceListLbl.Text = "Each row is Screen 1-12. Tick rows here to run them. The play-list checkboxes above assign a list and pictures to a screen." $instanceListLbl.Location = New-Object System.Drawing.Point(8, 198) $instanceListLbl.Size = New-Object System.Drawing.Size(490, 20) $instanceList = New-Object System.Windows.Forms.CheckedListBox $instanceList.CheckOnClick = $true $instanceList.IntegralHeight = $false $instanceList.Location = New-Object System.Drawing.Point(8, 220) $instanceList.Size = New-Object System.Drawing.Size(490, 132) $btnInstanceSave = New-Object System.Windows.Forms.Button $btnInstanceSave.Text = "Save plan" $btnInstanceSave.Location = New-Object System.Drawing.Point(8, 360) $btnInstanceSave.Size = New-Object System.Drawing.Size(92, 30) $btnInstanceManager = New-Object System.Windows.Forms.Button $btnInstanceManager.Text = "Create instances" $btnInstanceManager.Location = New-Object System.Drawing.Point(106, 360) $btnInstanceManager.Size = New-Object System.Drawing.Size(120, 30) $btnInstanceRefresh = New-Object System.Windows.Forms.Button $btnInstanceRefresh.Text = "Refresh" $btnInstanceRefresh.Location = New-Object System.Drawing.Point(232, 360) $btnInstanceRefresh.Size = New-Object System.Drawing.Size(80, 30) $btnInstanceLaunch = New-Object System.Windows.Forms.Button $btnInstanceLaunch.Text = "Launch checked" $btnInstanceLaunch.Location = New-Object System.Drawing.Point(318, 360) $btnInstanceLaunch.Size = New-Object System.Drawing.Size(122, 30) $btnInstanceTile = New-Object System.Windows.Forms.Button $btnInstanceTile.Text = "Start split view" $btnInstanceTile.Location = New-Object System.Drawing.Point(8, 398) $btnInstanceTile.Size = New-Object System.Drawing.Size(110, 30) $btnInstanceLarge = New-Object System.Windows.Forms.Button $btnInstanceLarge.Text = "Open selected large" $btnInstanceLarge.Location = New-Object System.Drawing.Point(124, 398) $btnInstanceLarge.Size = New-Object System.Drawing.Size(136, 30) $btnInstanceTarget = New-Object System.Windows.Forms.Button $btnInstanceTarget.Text = "Use for Auto Farm" $btnInstanceTarget.Location = New-Object System.Drawing.Point(266, 398) $btnInstanceTarget.Size = New-Object System.Drawing.Size(126, 30) $btnInstancePlay = New-Object System.Windows.Forms.Button $btnInstancePlay.Text = "Play screen" $btnInstancePlay.Location = New-Object System.Drawing.Point(398, 398) $btnInstancePlay.Size = New-Object System.Drawing.Size(100, 30) $btnInstanceRunAll = New-Object System.Windows.Forms.Button $btnInstanceRunAll.Text = "Run checked in order" $btnInstanceRunAll.Location = New-Object System.Drawing.Point(8, 436) $btnInstanceRunAll.Size = New-Object System.Drawing.Size(168, 32) $btnInstanceAssign = New-Object System.Windows.Forms.Button $btnInstanceAssign.Text = "Assign chosen saved list" $btnInstanceAssign.Location = New-Object System.Drawing.Point(184, 436) $btnInstanceAssign.Size = New-Object System.Drawing.Size(166, 32) $btnInstanceHide = New-Object System.Windows.Forms.Button $btnInstanceHide.Text = "Hide helper" $btnInstanceHide.Location = New-Object System.Drawing.Point(356, 436) $btnInstanceHide.Size = New-Object System.Drawing.Size(142, 32) $btnInstanceSaveSizes = New-Object System.Windows.Forms.Button $btnInstanceSaveSizes.Text = "Save screen sizes" $btnInstanceSaveSizes.Location = New-Object System.Drawing.Point(8, 476) $btnInstanceSaveSizes.Size = New-Object System.Drawing.Size(140, 30) $instanceHelp = New-Object System.Windows.Forms.Label $instanceHelp.Location = New-Object System.Drawing.Point(154, 476) $instanceHelp.Size = New-Object System.Drawing.Size(344, 110) $instanceHelp.Text = "How to: tick screens next to the numbered play list, add that screen's pictures, Save for screens. Play screen farms that window's own list from #1. Run checked in order does one screen at a time. Split view tiles 2-4. Five or more (or more than this PC can run) opens one at a time. WARNING above names RAM/CPU/disk. Hide helper tucks this window; reopen Auto Farm from the tray." $tabInstances.Controls.AddRange(@($instanceCapacity, $instanceNeed, $instanceCountLbl, $instanceCount, $instanceRamLbl, $instanceRam, $instanceDiskLbl, $instanceDisk, $instanceRamGraphLbl, $instanceRamGraph, $instanceDiskGraphLbl, $instanceDiskGraph, $instanceListLbl, $instanceList, $btnInstanceSave, $btnInstanceManager, $btnInstanceRefresh, $btnInstanceLaunch, $btnInstanceTile, $btnInstanceLarge, $btnInstanceTarget, $btnInstancePlay, $btnInstanceRunAll, $btnInstanceAssign, $btnInstanceHide, $btnInstanceSaveSizes, $instanceHelp)) try { $instancePlan = Read-FarmInstancePlan $wantCount = 2 try { $wantCount = [int]$instancePlan.desiredCount } catch {} if ($wantCount -lt 2) { $wantCount = 2 } if ($wantCount -gt 12) { $wantCount = 12 } $instanceCount.Value = [decimal]$wantCount if ($instancePlan.ramGB) { $instanceRam.Value = [decimal][int]$instancePlan.ramGB } if ($instancePlan.diskGB) { $instanceDisk.Value = [decimal][int]$instancePlan.diskGB } } catch {} $playlistInfo = New-Object System.Windows.Forms.Label $playlistInfo.Location = New-Object System.Drawing.Point(12, 242) $playlistInfo.Size = New-Object System.Drawing.Size(520, 22) $playlistInfo.Text = "Types are templates. Tick screens below to give each BlueStacks window its own list and pictures." $playlistType = New-Object System.Windows.Forms.ComboBox $playlistType.DropDownStyle = "DropDownList" $playlistType.Location = New-Object System.Drawing.Point(12, 266) $playlistType.Size = New-Object System.Drawing.Size(170, 24) foreach ($type in @(Get-FarmPlaylistTypes)) { [void]$playlistType.Items.Add([string]$type.label) } if ($playlistType.Items.Count -gt 0) { $playlistType.SelectedIndex = 0 } $btnPlaylistSave = New-Object System.Windows.Forms.Button $btnPlaylistSave.Text = "Save list" $btnPlaylistSave.Location = New-Object System.Drawing.Point(190, 264) $btnPlaylistSave.Size = New-Object System.Drawing.Size(100, 28) $btnPlaylistLoad = New-Object System.Windows.Forms.Button $btnPlaylistLoad.Text = "Load list" $btnPlaylistLoad.Location = New-Object System.Drawing.Point(298, 264) $btnPlaylistLoad.Size = New-Object System.Drawing.Size(100, 28) $btnPlaylistPlay = New-Object System.Windows.Forms.Button $btnPlaylistPlay.Text = "Play saved" $btnPlaylistPlay.Location = New-Object System.Drawing.Point(406, 264) $btnPlaylistPlay.Size = New-Object System.Drawing.Size(126, 28) $playlistScreensLbl = New-Object System.Windows.Forms.Label $playlistScreensLbl.Location = New-Object System.Drawing.Point(12, 294) $playlistScreensLbl.Size = New-Object System.Drawing.Size(520, 20) $playlistScreensLbl.Text = "This list + pictures is for these screens. Tick, then Save for screens. Each screen can have different images." $playlistScreens = New-Object System.Windows.Forms.CheckedListBox $playlistScreens.CheckOnClick = $true $playlistScreens.IntegralHeight = $false $playlistScreens.Location = New-Object System.Drawing.Point(12, 314) $playlistScreens.Size = New-Object System.Drawing.Size(360, 78) $btnPlaylistSaveScreens = New-Object System.Windows.Forms.Button $btnPlaylistSaveScreens.Text = "Save for screens" $btnPlaylistSaveScreens.Location = New-Object System.Drawing.Point(380, 314) $btnPlaylistSaveScreens.Size = New-Object System.Drawing.Size(148, 32) $btnPlaylistLoadScreen = New-Object System.Windows.Forms.Button $btnPlaylistLoadScreen.Text = "Load screen" $btnPlaylistLoadScreen.Location = New-Object System.Drawing.Point(380, 350) $btnPlaylistLoadScreen.Size = New-Object System.Drawing.Size(148, 32) $picHow = New-Object System.Windows.Forms.Label $picHow.Text = "Pictures: 1 Mag glass 2 drag around the exact visible image 3 Add to farm. Play waits until found, then clicks the middle. Save each screen's list separately." $picHow.Location = New-Object System.Drawing.Point(8, 4) $picHow.Size = New-Object System.Drawing.Size(490, 32) $btnMag = New-Object System.Windows.Forms.Button $btnMag.Text = "Mag glass" $btnMag.Location = New-Object System.Drawing.Point(8, 38) $btnMag.Size = New-Object System.Drawing.Size(88, 28) $btnSavePic = New-Object System.Windows.Forms.Button $btnSavePic.Text = "Save picture" $btnSavePic.Location = New-Object System.Drawing.Point(100, 38) $btnSavePic.Size = New-Object System.Drawing.Size(100, 28) $waitImg = New-Object System.Windows.Forms.CheckBox $waitImg.Text = "Hit any picture" $waitImg.Location = New-Object System.Drawing.Point(208, 42) $waitImg.Size = New-Object System.Drawing.Size(128, 22) $timesLbl = New-Object System.Windows.Forms.Label $timesLbl.Text = "Times" $timesLbl.Location = New-Object System.Drawing.Point(340, 14) $timesLbl.Size = New-Object System.Drawing.Size(42, 18) $timesBox = New-Object System.Windows.Forms.NumericUpDown $timesBox.Location = New-Object System.Drawing.Point(384, 10) $timesBox.Size = New-Object System.Drawing.Size(60, 22) $timesBox.Minimum = 1 $timesBox.Maximum = 9999 $timesBox.Value = 1 $timesLbl.Visible = $false $timesBox.Visible = $false $glassLbl = New-Object System.Windows.Forms.Label $glassLbl.Text = "Pictures" $glassLbl.Location = New-Object System.Drawing.Point(8, 70) $glassLbl.Size = New-Object System.Drawing.Size(280, 18) $glassList = New-Object System.Windows.Forms.ListBox $glassList.Location = New-Object System.Drawing.Point(8, 88) $glassList.Size = New-Object System.Drawing.Size(220, 68) $glassList.Add_MouseDown({ param($sender, $e) if ($e.Button -eq [System.Windows.Forms.MouseButtons]::Left) { $script:glassDragPt = $e.Location } }) $glassList.Add_MouseMove({ param($sender, $e) if ($e.Button -ne [System.Windows.Forms.MouseButtons]::Left -or -not $script:glassDragPt) { return } if ([Math]::Abs($e.X - $script:glassDragPt.X) -lt 6 -and [Math]::Abs($e.Y - $script:glassDragPt.Y) -lt 6) { return } $script:glassDragPt = $null $i = $glassList.SelectedIndex if ($i -lt 0) { return } $all = @(Read-FarmGlassList) if ($i -ge $all.Count) { return } $lab = Format-FarmPicQueueLabel ([string]$all[$i].file) ([string]$all[$i].name) [void]$glassList.DoDragDrop($lab, [System.Windows.Forms.DragDropEffects]::Copy) }) $glassPreview = New-Object System.Windows.Forms.PictureBox $glassPreview.Location = New-Object System.Drawing.Point(236, 70) $glassPreview.Size = New-Object System.Drawing.Size(156, 68) $glassPreview.SizeMode = [System.Windows.Forms.PictureBoxSizeMode]::Zoom $glassPreview.BorderStyle = [System.Windows.Forms.BorderStyle]::FixedSingle $glassPreview.BackColor = [System.Drawing.Color]::FromArgb(18, 18, 22) $btnRemGlass = New-Object System.Windows.Forms.Button $btnRemGlass.Text = "Remove picture" $btnRemGlass.Location = New-Object System.Drawing.Point(8, 160) $btnRemGlass.Size = New-Object System.Drawing.Size(120, 28) $btnAddPicFarm = New-Object System.Windows.Forms.Button $btnAddPicFarm.Text = "Add to farm" $btnAddPicFarm.Location = New-Object System.Drawing.Point(132, 160) $btnAddPicFarm.Size = New-Object System.Drawing.Size(120, 28) $tabPics.Controls.AddRange(@($picHow, $btnMag, $btnSavePic, $waitImg, $timesLbl, $timesBox, $glassLbl, $glassList, $glassPreview, $btnRemGlass, $btnAddPicFarm)) $winHow = New-Object System.Windows.Forms.Label $winHow.Text = "BlueStacks: Launch it here, pick it and Use window, then Save size + location. Restore size + location puts it back in the same screen spot." $winHow.Location = New-Object System.Drawing.Point(8, 4) $winHow.Size = New-Object System.Drawing.Size(490, 32) $btnPick = New-Object System.Windows.Forms.Button $btnPick.Text = "Pick spot" $btnPick.Location = New-Object System.Drawing.Point(8, 70) $btnPick.Size = New-Object System.Drawing.Size(88, 28) $btnLaunchBlue = New-Object System.Windows.Forms.Button $btnLaunchBlue.Text = "Launch BlueStacks" $btnLaunchBlue.Location = New-Object System.Drawing.Point(8, 38) $btnLaunchBlue.Size = New-Object System.Drawing.Size(132, 28) $autoBlue = New-Object System.Windows.Forms.CheckBox $autoBlue.Text = "When helper opens: launch BlueStacks + restore saved size/location" $autoBlue.Location = New-Object System.Drawing.Point(148, 42) $autoBlue.Size = New-Object System.Drawing.Size(350, 22) try { if ($script:cfg -and $script:cfg.farmStartBlueStacks) { $autoBlue.Checked = [bool]$script:cfg.farmStartBlueStacks } } catch {} $winBox = New-Object System.Windows.Forms.ComboBox $winBox.DropDownStyle = "DropDownList" $winBox.Location = New-Object System.Drawing.Point(104, 72) $winBox.Size = New-Object System.Drawing.Size(224, 24) $btnWinRef = New-Object System.Windows.Forms.Button $btnWinRef.Text = "Windows" $btnWinRef.Location = New-Object System.Drawing.Point(336, 70) $btnWinRef.Size = New-Object System.Drawing.Size(80, 28) $btnWinUse = New-Object System.Windows.Forms.Button $btnWinUse.Text = "Use window" $btnWinUse.Location = New-Object System.Drawing.Point(420, 70) $btnWinUse.Size = New-Object System.Drawing.Size(80, 28) $sizeNameLbl = New-Object System.Windows.Forms.Label $sizeNameLbl.Text = "Size label" $sizeNameLbl.Location = New-Object System.Drawing.Point(8, 106) $sizeNameLbl.Size = New-Object System.Drawing.Size(76, 20) $sizeNameBox = New-Object System.Windows.Forms.TextBox $sizeNameBox.Location = New-Object System.Drawing.Point(88, 104) $sizeNameBox.Size = New-Object System.Drawing.Size(132, 22) $sizeNameBox.Text = "BlueStacks" $btnSaveSize = New-Object System.Windows.Forms.Button $btnSaveSize.Text = "Save size + location" $btnSaveSize.Location = New-Object System.Drawing.Point(228, 102) $btnSaveSize.Size = New-Object System.Drawing.Size(132, 28) $btnRestoreSize = New-Object System.Windows.Forms.Button $btnRestoreSize.Text = "Restore size + location" $btnRestoreSize.Location = New-Object System.Drawing.Point(368, 102) $btnRestoreSize.Size = New-Object System.Drawing.Size(148, 28) $sightLab = New-Object System.Windows.Forms.Label $sightLab.Location = New-Object System.Drawing.Point(8, 138) $sightLab.Size = New-Object System.Drawing.Size(492, 110) $tabWin.Controls.AddRange(@($winHow, $btnLaunchBlue, $autoBlue, $btnPick, $winBox, $btnWinRef, $btnWinUse, $sizeNameLbl, $sizeNameBox, $btnSaveSize, $btnRestoreSize, $sightLab)) $msgHow = New-Object System.Windows.Forms.Label $msgHow.Location = New-Object System.Drawing.Point(8, 6) $msgHow.Size = New-Object System.Drawing.Size(490, 48) $msgHow.Text = "Messages: 1 choose Friends or Alliance 2 tap a name 3 type your message 4 Send. Popup notifications shows new messages by the clock." $msgPopup = New-Object System.Windows.Forms.CheckBox $msgPopup.Text = "Popup notifications" $msgPopup.Location = New-Object System.Drawing.Point(8, 54) $msgPopup.Size = New-Object System.Drawing.Size(180, 22) $msgFriendLbl = New-Object System.Windows.Forms.Label $msgFriendLbl.Text = "Friends" $msgFriendLbl.Location = New-Object System.Drawing.Point(8, 78) $msgFriendLbl.Size = New-Object System.Drawing.Size(150, 16) $msgFriends = New-Object System.Windows.Forms.ListBox $msgFriends.Location = New-Object System.Drawing.Point(8, 96) $msgFriends.Size = New-Object System.Drawing.Size(150, 90) $msgAllyLbl = New-Object System.Windows.Forms.Label $msgAllyLbl.Text = "Alliance" $msgAllyLbl.Location = New-Object System.Drawing.Point(8, 188) $msgAllyLbl.Size = New-Object System.Drawing.Size(150, 16) $msgAlliance = New-Object System.Windows.Forms.ListBox $msgAlliance.Location = New-Object System.Drawing.Point(8, 206) $msgAlliance.Size = New-Object System.Drawing.Size(150, 70) $btnFriend = New-Object System.Windows.Forms.Button $btnFriend.Text = "Friend" $btnFriend.Location = New-Object System.Drawing.Point(8, 278) $btnFriend.Size = New-Object System.Drawing.Size(70, 26) $btnMsgRefresh = New-Object System.Windows.Forms.Button $btnMsgRefresh.Text = "Refresh" $btnMsgRefresh.Location = New-Object System.Drawing.Point(82, 278) $btnMsgRefresh.Size = New-Object System.Drawing.Size(76, 26) $msgTitle = New-Object System.Windows.Forms.Label $msgTitle.Text = "Pick a friend or an alliance member" $msgTitle.Location = New-Object System.Drawing.Point(168, 78) $msgTitle.Size = New-Object System.Drawing.Size(330, 18) $msgLog = New-Object System.Windows.Forms.TextBox $msgLog.Multiline = $true $msgLog.ReadOnly = $true $msgLog.ScrollBars = "Vertical" $msgLog.Location = New-Object System.Drawing.Point(168, 98) $msgLog.Size = New-Object System.Drawing.Size(330, 150) $msgInput = New-Object System.Windows.Forms.TextBox $msgInput.Location = New-Object System.Drawing.Point(168, 254) $msgInput.Size = New-Object System.Drawing.Size(240, 22) $btnMsgSend = New-Object System.Windows.Forms.Button $btnMsgSend.Text = "Send" $btnMsgSend.Location = New-Object System.Drawing.Point(414, 252) $btnMsgSend.Size = New-Object System.Drawing.Size(84, 26) $msgStatus = New-Object System.Windows.Forms.Label $msgStatus.Location = New-Object System.Drawing.Point(168, 282) $msgStatus.Size = New-Object System.Drawing.Size(330, 32) $tabMsg.Controls.AddRange(@($msgHow, $msgPopup, $msgFriendLbl, $msgFriends, $msgAllyLbl, $msgAlliance, $btnFriend, $btnMsgRefresh, $msgTitle, $msgLog, $msgInput, $btnMsgSend, $msgStatus)) $capHow = New-Object System.Windows.Forms.Label $capHow.Location = New-Object System.Drawing.Point(8, 6) $capHow.Size = New-Object System.Drawing.Size(490, 58) $capHow.Text = "Record & share: 1 Enable 2 Window tab → Use window 3 Start screen record 4 Stop 5 Save clip. Play can keep farming while recording." $capEnable = New-Object System.Windows.Forms.CheckBox $capEnable.Text = "Enable record and share" $capEnable.Location = New-Object System.Drawing.Point(8, 66) $capEnable.Size = New-Object System.Drawing.Size(200, 22) $capPreview = New-Object System.Windows.Forms.PictureBox $capPreview.Location = New-Object System.Drawing.Point(8, 92) $capPreview.Size = New-Object System.Drawing.Size(240, 135) $capPreview.SizeMode = [System.Windows.Forms.PictureBoxSizeMode]::Zoom $capPreview.BorderStyle = [System.Windows.Forms.BorderStyle]::FixedSingle $capPreview.BackColor = [System.Drawing.Color]::FromArgb(12, 14, 16) $btnCapStart = New-Object System.Windows.Forms.Button $btnCapStart.Text = "Start screen record" $btnCapStart.Location = New-Object System.Drawing.Point(258, 92) $btnCapStart.Size = New-Object System.Drawing.Size(140, 28) $btnCapStop = New-Object System.Windows.Forms.Button $btnCapStop.Text = "Stop" $btnCapStop.Location = New-Object System.Drawing.Point(404, 92) $btnCapStop.Size = New-Object System.Drawing.Size(90, 28) $btnCapSave = New-Object System.Windows.Forms.Button $btnCapSave.Text = "Save clip" $btnCapSave.Location = New-Object System.Drawing.Point(258, 126) $btnCapSave.Size = New-Object System.Drawing.Size(140, 28) $ytLbl = New-Object System.Windows.Forms.Label $ytLbl.Text = "Your YouTube channel" $ytLbl.Location = New-Object System.Drawing.Point(258, 162) $ytLbl.Size = New-Object System.Drawing.Size(230, 16) $ytBox = New-Object System.Windows.Forms.TextBox $ytBox.Location = New-Object System.Drawing.Point(258, 180) $ytBox.Size = New-Object System.Drawing.Size(236, 22) $btnYtUp = New-Object System.Windows.Forms.Button $btnYtUp.Text = "Send clip to YouTube" $btnYtUp.Location = New-Object System.Drawing.Point(258, 208) $btnYtUp.Size = New-Object System.Drawing.Size(160, 28) $btnYtLive = New-Object System.Windows.Forms.Button $btnYtLive.Text = "Open YouTube" $btnYtLive.Location = New-Object System.Drawing.Point(258, 240) $btnYtLive.Size = New-Object System.Drawing.Size(160, 28) $capStatus = New-Object System.Windows.Forms.Label $capStatus.Location = New-Object System.Drawing.Point(8, 236) $capStatus.Size = New-Object System.Drawing.Size(240, 70) $tabCap.Controls.AddRange(@($capHow, $capEnable, $capPreview, $btnCapStart, $btnCapStop, $btnCapSave, $ytLbl, $ytBox, $btnYtUp, $btnYtLive, $capStatus)) $btnLoad = New-Object System.Windows.Forms.Button $btnLoad.Text = "Load selected" $btnLoad.Location = New-Object System.Drawing.Point(12, 900) $btnLoad.Size = New-Object System.Drawing.Size(140, 32) $btnClose = New-Object System.Windows.Forms.Button $btnClose.Text = "Close" $btnClose.Location = New-Object System.Drawing.Point(420, 900) $btnClose.Size = New-Object System.Drawing.Size(112, 32) $btnRec.Add_Click({ if (Farm-StartRecord) { try { $script:farmForm.TopMost = $false } catch {} Show-FarmToast "Recording. Left-click the game. Right-click saves this step. Then press Record again." } }) $btnStopRec.Add_Click({ $ev = Farm-StopRecord $nm = Save-FarmRecording $ev Restore-FarmWindow if ($nm) { Show-FarmToast ("Saved " + $nm + ". " + @($ev).Count + " clicks. It is on the play list.") } else { Show-FarmToast "Nothing was recorded. Left-click the game, then right-click." } }) $btnPlay.Add_Click({ Reset-FarmPlayToNumberOne Hide-HelperOverGame if (Farm-PlayNow) { $mode = $(if ($script:farmLoop -and $script:farmLoop.Checked) { "Loop on: the list repeats only after its last row." } else { "Loop off: every list row runs once, then stops." }) Set-FarmStatus ("Starting at #1. " + $mode + " Right-click or Escape stops.") } else { Restore-FarmWindow $why = [string]$script:farmPlayFail if (-not $why) { $why = "Play did not start. Record a click step. Pictures are optional." } Show-FarmToast $why } }) $btnStopPlay.Add_Click({ Farm-StopPlay Restore-FarmWindow Set-FarmStatus "Stopped." }) $btnSave.Add_Click({ $ev = $script:lastFarmEvents if (-not $ev -or @($ev).Count -lt 1) { Set-FarmStatus "Record first, then Save." return } $nm = "macro" try { if ($script:farmNameBox) { $nm = $script:farmNameBox.Text.Trim() } } catch {} if (-not $nm) { $nm = "macro" } $all = @(Read-FarmMacros) $gid = Get-FarmComboGameId $(if ($script:farmUi) { $script:farmUi.saveGame } else { $null }) $keepDates = @() $next = New-Object System.Collections.ArrayList $hit = $false foreach ($old in $all) { if ([string]$old.name -eq $nm -and [string]$old.gameId -eq $gid) { try { $keepDates = @($old.dates) } catch { $keepDates = @() } $row = [pscustomobject]@{ name = $nm; events = $ev; days = @(Get-FarmDayChecks); dates = $keepDates; saved = (Get-Date).ToString("s"); gameId = $gid } [void]$next.Add($row) $hit = $true } else { [void]$next.Add($old) } } if (-not $hit) { $row = [pscustomobject]@{ name = $nm; events = $ev; days = @(Get-FarmDayChecks); dates = @(); saved = (Get-Date).ToString("s"); gameId = $gid } [void]$next.Add($row) } Write-FarmMacros @($next) Refresh-FarmMacroList $script:farmList Add-FarmPlayStep $row Set-FarmStatus ("Saved " + $nm + " for " + (Get-FarmGameNameById $gid) + ". Tick it on the right for a day, or Add it to the play list.") }) $btnLoad.Add_Click({ $box = $script:farmList if (-not $box -or $box.SelectedIndex -lt 0) { return } $all = @(Read-FarmMacros) if ($box.SelectedIndex -ge $all.Count) { return } $m = $all[$box.SelectedIndex] $script:lastFarmEvents = Convert-FarmEvents $m.events try { if ($script:farmNameBox) { $script:farmNameBox.Text = [string]$m.name } } catch {} try { Set-FarmDayChecks (Get-MacroDays $m) } catch {} Set-FarmStatus ("Loaded " + $m.name + " into Name. That does not put it on the play list. Use Add, or tick a day then Queue today.") }) $btnAddQ.Add_Click({ $box = $script:farmList $q = $script:farmQueue if (-not $box -or -not $q -or $box.SelectedIndex -lt 0) { return } if ($q.Items.Count -ge (Get-FarmQueueMax)) { Set-FarmStatus ("Play list is full (" + (Get-FarmQueueMax) + ")."); return } $all = @(Read-FarmMacros) if ($box.SelectedIndex -ge $all.Count) { return } [void](Add-FarmQueueRow (Format-FarmMacroLabel $all[$box.SelectedIndex]) $null $null) Save-FarmPlayOrderFromUi try { Place-FarmQueueMsEditor } catch {} Set-FarmStatus ("Added " + (Format-FarmMacroLabel $all[$box.SelectedIndex]) + " to the play list.") }) $btnRemQ.Add_Click({ $q = $script:farmQueue if (-not $q -or $q.SelectedIndex -lt 0) { return } Remove-FarmQueueRowAt ([int]$q.SelectedIndex) Save-FarmPlayOrderFromUi try { Place-FarmQueueMsEditor } catch {} }) $btnAddPicQ.Add_Click({ Add-FarmSelectedPicToFarm }) $btnUpQ.Add_Click({ Move-FarmQueueSelected -1 }) $btnDownQ.Add_Click({ Move-FarmQueueSelected 1 }) $btnSetGame.Add_Click({ Set-FarmSelectedSaveGame }) $btnHow.Add_Click({ Show-FarmHowTo }) $btnPick.Add_Click({ Show-FarmPickBox }) $btnMag.Add_Click({ Show-FarmMagGlass }) $btnSavePic.Add_Click({ Save-FarmWatchPicture }) $btnRemGlass.Add_Click({ Remove-FarmGlassSelected }) $btnAddPicFarm.Add_Click({ Add-FarmSelectedPicToFarm }) $glassList.Add_SelectedIndexChanged({ Show-FarmGlassListPreview }) $btnWinRef.Add_Click({ Fill-FarmWindowCombo; Set-FarmStatus "Window list updated." }) $btnWinUse.Add_Click({ Use-FarmWindowPick }) $btnLaunchBlue.Add_Click({ [void](Start-FarmBlueStacks) }) $autoBlue.Add_CheckedChanged({ try { Save-FarmStartBlueStacks ([bool]$this.Checked) } catch {} if ($this.Checked) { Set-FarmStatus "Automatic BlueStacks launch is on. The helper will launch it and restore the saved size next time." } else { Set-FarmStatus "Automatic BlueStacks launch is off." } }) $btnSaveSize.Add_Click({ Save-FarmWindowSizeLabel }) $btnRestoreSize.Add_Click({ Restore-FarmWindowSizeLabel }) $btnChat.Add_Click({ Show-Chat }) $btnShare.Add_Click({ Show-ShareSite }) $btnPay.Add_Click({ Open-PayPalUnlock }) $btnToday.Add_Click({ $day = Get-FarmCalendarDay $n = Fill-FarmQueueForDay $day $when = $day.ToString("ddd MMM d") if ($n -lt 1) { Set-FarmStatus ("No ticks on " + $when + ". Click that day, tick farms on the right, then Queue today.") } else { Set-FarmStatus ("Queued " + $n + " farm(s) for " + $when + ". Pictures already on the play list were kept.") } }) $msgFriends.Add_SelectedIndexChanged({ Farm-PickPerson "friend" }) $msgAlliance.Add_SelectedIndexChanged({ Farm-PickPerson "alliance" }) $btnFriend.Add_Click({ Farm-AddFriendFromAlliance }) $btnMsgRefresh.Add_Click({ Refresh-FarmPeopleLists }) $btnMsgSend.Add_Click({ Farm-SendDm }) $msgInput.Add_KeyDown({ param($sender, $e) if ($e.KeyCode -eq [System.Windows.Forms.Keys]::Enter) { $e.SuppressKeyPress = $true Farm-SendDm } }) $msgPopup.Add_CheckedChanged({ $social = Read-FarmSocial $social.popup = [bool]$msgPopup.Checked Write-FarmSocial $social }) $capEnable.Add_CheckedChanged({ $social = Read-FarmSocial $social.captureOn = [bool]$capEnable.Checked Write-FarmSocial $social }) $btnCapStart.Add_Click({ Farm-CaptureStart }) $btnCapStop.Add_Click({ Farm-CaptureStop }) $btnCapSave.Add_Click({ Farm-CaptureSave }) $btnYtUp.Add_Click({ Farm-YouTube "upload" }) $btnYtLive.Add_Click({ Farm-YouTube "live" }) $instanceCount.Add_ValueChanged({ try { Update-FarmInstanceCapacity } catch {} }) $instanceRam.Add_ValueChanged({ try { Update-FarmInstanceCapacity } catch {} }) $instanceDisk.Add_ValueChanged({ try { Update-FarmInstanceCapacity } catch {} }) $btnInstanceSave.Add_Click({ Save-FarmInstancePlanFromUi }) $btnInstanceManager.Add_Click({ Open-FarmBlueStacksManager }) $btnInstanceRefresh.Add_Click({ Refresh-FarmInstanceList; Set-FarmStatus "BlueStacks instance list refreshed." }) $btnInstanceLaunch.Add_Click({ Start-FarmLaunchCheckedInstances }) $btnInstanceTile.Add_Click({ [void](Start-FarmSplitView) }) $btnInstanceLarge.Add_Click({ Show-FarmSelectedInstanceLarge }) $instanceList.Add_DoubleClick({ Show-FarmSelectedInstanceLarge }) $btnInstanceTarget.Add_Click({ $row = Get-FarmSelectedInstance [void](Set-FarmTargetInstance $row) }) $btnInstancePlay.Add_Click({ [void](Start-FarmSelectedInstance) }) $btnInstanceAssign.Add_Click({ [void](Assign-FarmPlaylistToSelectedInstance) }) $btnInstanceHide.Add_Click({ Hide-FarmControlWindow }) $btnInstanceSaveSizes.Add_Click({ [void](Save-FarmInstanceLayoutsFromWindows) }) $btnInstanceRunAll.Add_Click({ Start-FarmInstancesSequential }) $playlistType.Add_SelectedIndexChanged({ try { Refresh-FarmPlaylistStatus } catch {} }) $btnPlaylistSave.Add_Click({ if (Save-CurrentFarmPlaylist) { Refresh-FarmPlaylistStatus } }) $btnPlaylistSaveScreens.Add_Click({ if (Save-FarmPlaylistForCheckedScreens) { Refresh-FarmPlaylistStatus } }) $btnPlaylistLoadScreen.Add_Click({ [void](Load-FarmPlaylistForSelectedScreen) Refresh-FarmPlaylistStatus }) $btnPlaylistLoad.Add_Click({ [void](Load-SelectedFarmPlaylist) Refresh-FarmPlaylistStatus }) $btnPlaylistPlay.Add_Click({ if (-not (Load-SelectedFarmPlaylist)) { Show-FarmToast "Save a numbered list under this type first." return } Reset-FarmPlayToNumberOne Hide-HelperOverGame if (Farm-PlayNow) { Set-FarmStatus "Playing the saved list from #1. Every row runs once unless Loop is checked." } else { Restore-FarmWindow $why = [string]$script:farmPlayFail if (-not $why) { $why = "The saved play list could not start." } Show-FarmToast $why } }) $btnClose.Add_Click({ Close-ClickedHelperForm }) $tick = New-Object System.Windows.Forms.Timer $tick.Interval = 400 $tick.Add_Tick({ try { $b = $script:farmBox if (-not $b) { return } if ($script:farmForm -and $script:farmForm.IsDisposed) { return } if ($script:farmInstanceSequence) { if ($script:farmInstanceSequenceWaiting -and $b.playing) { $script:farmInstanceSequenceSawPlaying = $true } if ($script:farmInstanceSequenceWaiting -and $script:farmInstanceSequenceSawPlaying -and -not $b.playing) { $script:farmInstanceSequenceWaiting = $false $script:farmInstanceSequenceSawPlaying = $false $done = $null try { $done = @($script:farmInstanceSequence)[$script:farmInstanceSequenceIndex] } catch {} $script:farmInstanceSequenceIndex++ if ($script:farmInstanceSequenceOneAtATime -and $done) { try { Stop-FarmBlueStacksInstance ([string]$done.id) } catch {} $script:farmInstanceSequenceCooldown = 10 $script:farmInstanceSequenceLaunchId = "" $script:farmInstanceSequenceLaunchTries = 0 } } if (-not $script:farmInstanceSequenceWaiting) { if ($script:farmInstanceSequenceIndex -ge @($script:farmInstanceSequence).Count) { $doneCount = @($script:farmInstanceSequence).Count $script:farmInstanceSequence = $null $script:farmInstanceSequenceOneAtATime = $false try { if ($script:farmLoop) { $script:farmLoop.Checked = [bool]$script:farmSequenceOldLoop } } catch {} Restore-FarmWindow Set-FarmStatus ("Finished the numbered play list once on all " + $doneCount + " checked instances.") try { if (-not (Test-FarmShouldRunOneAtATime)) { [void](Tile-FarmInstances) } } catch {} } else { $prepared = $null try { $prepared = Prepare-FarmSequenceTarget } catch {} $prepKind = "" try { $prepKind = [string]$prepared } catch {} if ($prepKind -eq "wait") { } elseif ($prepKind -eq "skip" -or -not $prepared) { $script:farmInstanceSequenceIndex++ } else { $target = $prepared if (Set-FarmTargetInstance $target) { $targetListReady = [bool](Load-FarmPlaylistForInstance ([string]$target.id)) if ($targetListReady) { Reset-FarmPlayToNumberOne Hide-HelperOverGame } if ($targetListReady -and (Farm-PlayNow)) { $script:farmInstanceSequenceWaiting = $true $script:farmInstanceSequenceSawPlaying = $false $sn = Get-FarmScreenNumberById ([string]$target.id) Set-FarmStatus ("Sequential Auto Farm " + ($script:farmInstanceSequenceIndex + 1) + " of " + @($script:farmInstanceSequence).Count + ": screen " + $sn + " " + [string]$target.label + " - that screen's own list and pictures, one picture at a time.") } else { $script:farmInstanceSequenceIndex++ } } else { $script:farmInstanceSequenceIndex++ } } } } } if ($b.crashLine) { Write-HelperCrashLog ([string]$b.crashLine) $b.crashLine = "" } if ($b.playError) { Write-HelperCrashLog ([string]$b.playError) Restore-FarmWindow Show-FarmToast ([string]$b.playError) $b.playError = "" $script:farmWasPlaying = $false } elseif ($b.playNotice) { Show-FarmToast ([string]$b.playNotice) -NoWindow Set-FarmStatus ([string]$b.playNotice) $b.playNotice = "" } elseif ($b.recording) { Set-FarmStatus (Helper-T "Recording... right-click to stop") } elseif ($b.playing) { $script:farmWasPlaying = $true try { Set-Content -Path (Join-Path $root "helper-alive.txt") -Value ((Get-Date).ToString("o") + " v" + $script:HelperVersion + " play") -Encoding UTF8 } catch {} $mini = $false try { $mini = Test-BlueStacksMinimized } catch { $mini = $false } if ($mini) { Set-FarmStatus "BlueStacks is minimized. Open the game window." } else { Set-FarmStatus (Helper-T "Playing... right-click or Escape to stop") } } elseif ($script:farmWasPlaying) { $script:farmWasPlaying = $false Restore-FarmWindow } } catch {} }) $tick.Start() $script:farmTick = $tick $dlg.Add_FormClosed({ try { Save-FarmPlayOrderFromUi } catch {} try { if ($script:farmSplitTimer) { $script:farmSplitTimer.Stop(); $script:farmSplitTimer.Dispose() } } catch {} $script:farmSplitTimer = $null try { if ($script:blueRestoreTimer) { $script:blueRestoreTimer.Stop(); $script:blueRestoreTimer.Dispose() } } catch {} $script:blueRestoreTimer = $null try { if ($script:farmTick) { $script:farmTick.Stop(); $script:farmTick.Dispose() } } catch {} $script:farmTick = $null try { Stop-FarmCaptureTimer } catch {} try { if ($script:farmDmTimer) { $script:farmDmTimer.Stop(); $script:farmDmTimer.Dispose() } } catch {} $script:farmDmTimer = $null $script:farmStatus = $null $script:farmLoop = $null $script:farmNameBox = $null $script:farmList = $null $script:farmQueue = $null $script:farmDelay = $null $script:farmKeyDelay = $null $script:farmUi = $null $script:farmTimes = $null $script:farmWaitImg = $null $script:farmDayBoxes = $null try { if ($script:glassListBmp) { $script:glassListBmp.Dispose() } } catch {} $script:glassListBmp = $null }) foreach ($c in @($lead, $status, $btnRec, $btnStopRec, $btnPlay, $btnStopPlay, $btnHow, $btnPay, $btnChat, $btnShare, $loop, $delayLbl, $delayBox, $keyDelayLbl, $keyDelayBox, $delayHelp, $profLbl, $profBox, $gameLbl, $gameBox, $playlistInfo, $playlistType, $btnPlaylistSave, $btnPlaylistLoad, $btnPlaylistPlay, $playlistScreensLbl, $playlistScreens, $btnPlaylistSaveScreens, $btnPlaylistLoadScreen, $qLbl, $qList, $qMsBox, $btnAddQ, $btnUpQ, $btnDownQ, $nameLbl, $nameBox, $btnSave, $btnRemQ, $btnAddPicQ, $btnToday, $saveGameLbl, $saveGameBox, $btnSetGame, $autoLoad, $savesHow, $cal, $listHead, $listHow, $list, $tabs, $btnLoad, $btnClose)) { $scroll.Controls.Add($c) } $dlg.Controls.Add($scroll) $script:farmForm = $dlg $script:farmScroll = $scroll $script:farmStatus = $status $script:farmLoop = $loop $script:farmNameBox = $nameBox $script:farmList = $list $script:farmQueue = $qList $script:farmDelay = $delayBox $script:farmKeyDelay = $keyDelayBox $script:farmTimes = $timesBox $script:farmWaitImg = $waitImg try { Load-FarmPlayOrderToUi } catch {} try { Invoke-FarmAutoLoadToday | Out-Null } catch {} $script:farmUi = @{ form = $dlg scroll = $scroll lead = $lead rec = $btnRec stopRec = $btnStopRec play = $btnPlay stopPlay = $btnStopPlay how = $btnHow loop = $loop delayLbl = $delayLbl keyDelayLbl = $keyDelayLbl delayHelp = $delayHelp qLbl = $qLbl savesHow = $savesHow listHead = $listHead listHow = $listHow picHow = $picHow winHow = $winHow qList = $qList qMs = $qMsBox addQ = $btnAddQ upQ = $btnUpQ downQ = $btnDownQ nameLbl = $nameLbl nameBox = $nameBox cal = $cal save = $btnSave remQ = $btnRemQ addPicQ = $btnAddPicQ load = $btnLoad close = $btnClose chat = $btnChat share = $btnShare pay = $btnPay today = $btnToday autoLoad = $autoLoad game = $gameBox gameLbl = $gameLbl profile = $profBox profileLbl = $profLbl saveGame = $saveGameBox saveGameLbl = $saveGameLbl setGame = $btnSetGame pick = $btnPick mag = $btnMag savePic = $btnSavePic waitImg = $waitImg glassLbl = $glassLbl glass = $glassList glassPreview = $glassPreview remGlass = $btnRemGlass addPicFarm = $btnAddPicFarm tabs = $tabs tabPics = $tabPics tabWin = $tabWin tabMsg = $tabMsg tabCap = $tabCap tabInstances = $tabInstances instanceCapacity = $instanceCapacity instanceNeed = $instanceNeed instanceCount = $instanceCount instanceRam = $instanceRam instanceDisk = $instanceDisk instanceRamGraph = $instanceRamGraph instanceDiskGraph = $instanceDiskGraph instanceList = $instanceList instancePlay = $btnInstancePlay instanceAssign = $btnInstanceAssign instanceHide = $btnInstanceHide instanceSaveSizes = $btnInstanceSaveSizes instanceHelp = $instanceHelp playlistType = $playlistType playlistInfo = $playlistInfo playlistSave = $btnPlaylistSave playlistLoad = $btnPlaylistLoad playlistPlay = $btnPlaylistPlay playlistScreensLbl = $playlistScreensLbl playlistScreens = $playlistScreens playlistSaveScreens = $btnPlaylistSaveScreens playlistLoadScreen = $btnPlaylistLoadScreen msgHow = $msgHow msgPopup = $msgPopup msgFriendLbl = $msgFriendLbl msgFriends = $msgFriends msgAllyLbl = $msgAllyLbl msgAlliance = $msgAlliance btnFriend = $btnFriend btnMsgRefresh = $btnMsgRefresh btnMsgSend = $btnMsgSend msgLog = $msgLog msgInput = $msgInput msgTitle = $msgTitle msgStatus = $msgStatus capHow = $capHow capEnable = $capEnable capPreview = $capPreview capStatus = $capStatus btnCapStart = $btnCapStart btnCapStop = $btnCapStop btnCapSave = $btnCapSave ytLbl = $ytLbl ytBox = $ytBox btnYtUp = $btnYtUp btnYtLive = $btnYtLive timesLbl = $timesLbl win = $winBox winRef = $btnWinRef winUse = $btnWinUse launchBlue = $btnLaunchBlue autoBlue = $autoBlue sizeNameLbl = $sizeNameLbl sizeName = $sizeNameBox saveSize = $btnSaveSize restoreSize = $btnRestoreSize sightLab = $sightLab } try { Refresh-FarmPlaylistStatus } catch {} try { Refresh-FarmInstanceList $savedPlan = Read-FarmInstancePlan if ($savedPlan.activeId) { foreach ($instanceRow in @($script:farmInstanceCatalog)) { if ([string]$instanceRow.id -eq [string]$savedPlan.activeId -and [long]$instanceRow.hwnd -ne 0) { [void](Set-FarmTargetInstance $instanceRow) break } } } } catch {} try { $tabs.Add_SelectedIndexChanged({ try { $selectedTab = [int]$this.SelectedIndex if ($script:farmLastTabLayoutIndex -eq $selectedTab) { return } $script:farmLastTabLayoutIndex = $selectedTab if ($selectedTab -eq 4) { return } Fit-FarmWindowLayout } catch {} }) $dlg.Add_Resize({ try { Fit-FarmWindowLayout } catch {} }) $dlg.Add_Shown({ try { Fit-FarmWindowLayout } catch {} }) Fit-FarmWindowLayout try { Place-FarmQueueMsEditor } catch {} } catch {} try { Apply-HelperToolLang } catch {} try { Fill-FarmGameCombo } catch {} try { Fill-FarmSaveGameCombo } catch {} try { Fill-FarmProfileCombo } catch {} try { Fill-FarmWindowCombo } catch {} try { Fill-FarmGlassList } catch {} try { Paint-FarmSightLabel } catch {} try { if ($autoBlue.Checked) { [void](Start-FarmBlueStacks) } } catch {} try { $social = Read-FarmSocial $msgPopup.Checked = [bool]$social.popup $capEnable.Checked = [bool]$social.captureOn if ($social.youtube) { $ytBox.Text = [string]$social.youtube } Refresh-FarmPeopleLists } catch {} $dmTimer = New-Object System.Windows.Forms.Timer $dmTimer.Interval = 8000 $dmTimer.Add_Tick({ try { Farm-PollDm } catch {} }) $dmTimer.Start() $script:farmDmTimer = $dmTimer $dlg.Show() $dlg.BringToFront() [void]$dlg.Activate() try { $paid = $false try { $paid = Test-ChatPaid } catch {} try { if ($script:farmBox) { $script:farmBox.chatPaid = [bool]$paid } } catch {} if ($script:farmUi -and $script:farmUi.pay) { $script:farmUi.pay.Visible = ($script:chatPayState -eq "unpaid") } if ((Test-ChatNeedsPayPalPrompt) -and -not $script:payPalPrompted) { $script:payPalPrompted = $true Show-PayPalUnlockPrompt } } catch {} } catch { [void][System.Windows.Forms.MessageBox]::Show( "Auto Farm could not open: " + $_, "Auto Farm", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Warning ) } } function Show-Chat { if (-not $script:cfg -or -not $script:cfg.code) { [System.Windows.Forms.MessageBox]::Show( "Pick a commander in Settings first.", "Raids Timer Chat", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information ) | Out-Null return } $sub = $null try { $sub = Get-ChatSubscription } catch { $sub = $null } if (-not $sub) { [System.Windows.Forms.MessageBox]::Show( "Could not check the Chat subscription. Try again in a moment.", "Raids Timer Chat", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information ) | Out-Null return } if ($sub.active -ne $true) { Show-NoChatSub return } if ($script:chatForm -and -not $script:chatForm.IsDisposed) { $script:chatForm.WindowState = "Normal" $script:chatForm.Show() $script:chatForm.Activate() try { Apply-HelperToolLang } catch {} try { Update-ChatLog } catch {} return } $id = Get-ChatIdentity if (-not $id.playerId -or -not $id.serverNumber) { [System.Windows.Forms.MessageBox]::Show( "This commander needs a player ID and server saved in the browser profile before Chat can open.", "Raids Timer Chat", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information ) | Out-Null return } $joined = $null try { $joined = Join-ChatRooms } catch { $joined = $null } $rooms = @() if ($joined -and $joined.rooms) { $rooms = @($joined.rooms) } if ($rooms.Count -lt 1) { [System.Windows.Forms.MessageBox]::Show( "Chat is unlocked, but the room list did not load. Try again in a moment.", "Raids Timer Chat", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information ) | Out-Null return } $script:chatRooms = $rooms $prefer = 0 for ($i = 0; $i -lt $rooms.Count; $i++) { if ([string]$rooms[$i].kind -eq "alliance") { $prefer = $i; break } } $script:chatRoomId = [string]$rooms[$prefer].id $script:chatStick = $true $dlg = New-Object System.Windows.Forms.Form $dlg.Text = "Raids Timer Chat" $dlg.StartPosition = "CenterScreen" $dlg.ClientSize = New-Object System.Drawing.Size(520, 640) $dlg.MinimumSize = New-Object System.Drawing.Size(420, 520) $dlg.TopMost = $true $dlg.ShowInTaskbar = $true if ($script:appIcon) { $dlg.Icon = $script:appIcon } $script:chatForm = $dlg $status = New-Object System.Windows.Forms.Label $who = $id.displayName if ($id.allianceName) { $who = "$who · $($id.allianceName)" } $status.Text = "Chat unlocked · $who · lang $(Get-UiLang)" $status.Dock = "Top" $status.Height = 40 $status.Padding = New-Object System.Windows.Forms.Padding(8, 8, 8, 0) $script:chatStatus = $status $roomsBox = New-Object System.Windows.Forms.ComboBox $roomsBox.DropDownStyle = "DropDownList" $roomsBox.Dock = "Top" $roomsBox.Height = 28 $script:chatFilling = $true foreach ($r in $rooms) { $label = [string]$r.name if (-not $label) { $label = [string]$r.kind } [void]$roomsBox.Items.Add($label) } $roomsBox.SelectedIndex = $prefer $script:chatFilling = $false $script:chatRoomsBox = $roomsBox $roomsBox.Add_SelectedIndexChanged({ if ($script:chatFilling) { return } $idx = $script:chatRoomsBox.SelectedIndex if ($idx -ge 0 -and $script:chatRooms.Count -gt $idx) { $script:chatRoomId = [string]$script:chatRooms[$idx].id $script:chatStick = $true if ($script:chatLog) { $script:chatLog.Text = "" } Update-ChatLog } }) $langBox = New-Object System.Windows.Forms.ComboBox $langBox.DropDownStyle = "DropDownList" $langBox.Dock = "Top" $langBox.Height = 28 $langList = @("en","es","pt","fr","de","it","ru","uk","zh","ja","ko","ar","hi","id","tr","pl","nl","vi","th","sv","da","fi") foreach ($L in $langList) { [void]$langBox.Items.Add($L) } $haveLang = Get-UiLang if ($langBox.Items.IndexOf($haveLang) -lt 0) { [void]$langBox.Items.Insert(0, $haveLang) } $langBox.SelectedItem = $haveLang $langBox.Add_SelectedIndexChanged({ if ($script:chatFillingLang) { return } $pick = [string]$langBox.SelectedItem if ($pick) { Set-HelperLang $pick | Out-Null try { Apply-HelperToolLang } catch {} Update-ChatLog } }) $script:chatLangBox = $langBox $switch = New-Object System.Windows.Forms.Panel $switch.Dock = "Top" $switch.Height = 36 $btnToFarm = New-Object System.Windows.Forms.Button $btnToFarm.Text = "Auto Farm" $btnToFarm.Dock = "Left" $btnToFarm.Width = 140 $btnToFarm.Add_Click({ Show-AutoFarm }) $btnToShare = New-Object System.Windows.Forms.Button $btnToShare.Text = "Share site" $btnToShare.Dock = "Left" $btnToShare.Width = 140 $btnToShare.Add_Click({ Show-ShareSite }) $switch.Controls.Add($btnToShare) $switch.Controls.Add($btnToFarm) $script:chatFarmBtn = $btnToFarm $script:chatShareBtn = $btnToShare $log = New-Object System.Windows.Forms.TextBox $log.Multiline = $true $log.ReadOnly = $true $log.ScrollBars = "Vertical" $log.Font = New-Object System.Drawing.Font("Segoe UI", 10) $log.Dock = "Fill" $script:chatLog = $log $bottom = New-Object System.Windows.Forms.Panel $bottom.Dock = "Bottom" $bottom.Height = 44 $composer = New-Object System.Windows.Forms.TextBox $composer.Dock = "Fill" $composer.Font = New-Object System.Drawing.Font("Segoe UI", 10) $script:chatInput = $composer $composer.Add_KeyDown({ param($sender, $e) if ($e.KeyCode -eq [System.Windows.Forms.Keys]::Enter) { $e.SuppressKeyPress = $true Send-ChatText } }) $send = New-Object System.Windows.Forms.Button $send.Text = "Send" $send.Dock = "Right" $send.Width = 96 $send.Add_Click({ Send-ChatText }) $script:chatSend = $send $bottom.Controls.Add($send) $bottom.Controls.Add($composer) $dlg.Controls.Add($log) $dlg.Controls.Add($bottom) $dlg.Controls.Add($roomsBox) $dlg.Controls.Add($langBox) $dlg.Controls.Add($status) $dlg.Controls.Add($switch) $dlg.Add_FormClosed({ try { if ($script:chatTimer) { $script:chatTimer.Stop() } } catch {} $script:chatForm = $null $script:chatLog = $null $script:chatInput = $null $script:chatSend = $null $script:chatRoomId = "" $script:chatLangBox = $null $script:chatStatus = $null $script:chatRoomsBox = $null $script:chatFarmBtn = $null $script:chatShareBtn = $null }) if (-not $script:chatTimer) { $script:chatTimer = New-Object System.Windows.Forms.Timer $script:chatTimer.Interval = 4000 $script:chatTimer.Add_Tick({ Update-ChatLog }) } $script:chatTimer.Start() try { Apply-HelperToolLang } catch {} $dlg.Show() Update-ChatLog Add-Content -Path (Join-Path $root "pc-banner.log") -Value ("chat-open " + $script:chatRoomId) -Encoding UTF8 } function Show-HelperTools { try { if ($script:toolsForm -and -not $script:toolsForm.IsDisposed) { $script:toolsForm.Close() } } catch {} $who = "Commander" if ($script:cfg -and $script:cfg.displayName) { $who = [string]$script:cfg.displayName } $dlg = New-Object System.Windows.Forms.Form $dlg.Text = "Raids Timer helper" $dlg.FormBorderStyle = "FixedDialog" $dlg.StartPosition = "CenterScreen" $dlg.MaximizeBox = $false $dlg.MinimizeBox = $true $dlg.TopMost = $true $dlg.ShowInTaskbar = $true $dlg.ClientSize = New-Object System.Drawing.Size(400, 280) if ($script:appIcon) { $dlg.Icon = $script:appIcon } $lead = New-Object System.Windows.Forms.Label $lead.Text = "Using $who. Auto Farm is the first tool:" $lead.Location = New-Object System.Drawing.Point(16, 12) $lead.Size = New-Object System.Drawing.Size(368, 40) $list = New-Object System.Windows.Forms.ListBox $list.Location = New-Object System.Drawing.Point(16, 56) $list.Size = New-Object System.Drawing.Size(368, 140) [void]$list.Items.Add("Auto Farm") [void]$list.Items.Add("Chat") [void]$list.Items.Add("How to use Auto Farm") [void]$list.Items.Add("Share website") [void]$list.Items.Add("Change commander") $list.SelectedIndex = 0 $go = New-Object System.Windows.Forms.Button $go.Text = "Open" $go.Location = New-Object System.Drawing.Point(16, 210) $go.Size = New-Object System.Drawing.Size(120, 36) $farmNow = New-Object System.Windows.Forms.Button $farmNow.Text = "Auto Farm" $farmNow.Location = New-Object System.Drawing.Point(148, 210) $farmNow.Size = New-Object System.Drawing.Size(120, 36) $closeBtn = New-Object System.Windows.Forms.Button $closeBtn.Text = "Close" $closeBtn.Location = New-Object System.Drawing.Point(280, 210) $closeBtn.Size = New-Object System.Drawing.Size(104, 36) $openSel = { $idx = -1 try { $idx = [int]$list.SelectedIndex } catch {} if ($idx -eq 0) { Show-AutoFarm } elseif ($idx -eq 1) { Show-Chat } elseif ($idx -eq 2) { Show-FarmHowTo } elseif ($idx -eq 3) { Show-ShareSite } elseif ($idx -eq 4) { Show-ProfileSettings } } $go.Add_Click($openSel) $list.Add_DoubleClick($openSel) $farmNow.Add_Click({ Show-AutoFarm }) $closeBtn.Add_Click({ Close-ClickedHelperForm }) $dlg.Controls.Add($lead) $dlg.Controls.Add($list) $dlg.Controls.Add($go) $dlg.Controls.Add($farmNow) $dlg.Controls.Add($closeBtn) $script:toolsForm = $dlg $script:toolsUi = @{ form = $dlg; lead = $lead; list = $list; go = $go; farmNow = $farmNow; close = $closeBtn } try { Apply-HelperToolLang } catch {} $dlg.Show() $dlg.BringToFront() [void]$dlg.Activate() } function Show-ProfileSettings { $profiles = @(Find-RaidsProfiles) $script:settingsProfiles = $profiles $script:openFarmAfterSettings = $false $dlg = New-Object System.Windows.Forms.Form $dlg.Text = "Raids Timer settings" $dlg.FormBorderStyle = "FixedDialog" $dlg.StartPosition = "CenterScreen" $dlg.MaximizeBox = $false $dlg.MinimizeBox = $false $dlg.TopMost = $true $dlg.ClientSize = New-Object System.Drawing.Size(440, 478) if ($script:appIcon) { $dlg.Icon = $script:appIcon } $script:settingsForm = $dlg $lead = New-Object System.Windows.Forms.Label $lead.Text = "If you have more than one commander, pick one. Then Auto Farm opens (Record / Play). You can also tap Auto Farm below. Check for update downloads a newer helper without erasing farm saves. Copy crash log is on this page." $lead.Location = New-Object System.Drawing.Point(16, 12) $lead.Size = New-Object System.Drawing.Size(408, 52) $list = New-Object System.Windows.Forms.ListBox $list.Location = New-Object System.Drawing.Point(16, 72) $list.Size = New-Object System.Drawing.Size(408, 176) $sel = 0 $n = 0 foreach ($p in $profiles) { [void]$list.Items.Add((Format-ProfileLine $p)) if ($script:cfg -and [string]$script:cfg.code -eq [string]$p.code) { $sel = $n } $n++ } if ($list.Items.Count -gt 0) { $list.SelectedIndex = $sel } $script:settingsList = $list $use = New-Object System.Windows.Forms.Button $use.Text = "Use this commander" $use.Location = New-Object System.Drawing.Point(16, 260) $use.Size = New-Object System.Drawing.Size(190, 36) $farmBtn = New-Object System.Windows.Forms.Button $farmBtn.Text = "Auto Farm" $farmBtn.Location = New-Object System.Drawing.Point(220, 260) $farmBtn.Size = New-Object System.Drawing.Size(204, 36) $closeBtn = New-Object System.Windows.Forms.Button $closeBtn.Text = "Close" $closeBtn.Location = New-Object System.Drawing.Point(16, 404) $closeBtn.Size = New-Object System.Drawing.Size(100, 36) $updBtn = New-Object System.Windows.Forms.Button $updBtn.Text = "Check for update" $updBtn.Location = New-Object System.Drawing.Point(128, 404) $updBtn.Size = New-Object System.Drawing.Size(296, 36) $crashBtn = New-Object System.Windows.Forms.Button $crashBtn.Text = "Copy crash log" $crashBtn.Location = New-Object System.Drawing.Point(16, 356) $crashBtn.Size = New-Object System.Drawing.Size(408, 36) $crashBtn.Add_Click({ try { Show-HelperCrashLog } catch { [void][System.Windows.Forms.MessageBox]::Show( "Could not open the crash log.", "Crash log", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Warning ) } }) $updBtn.Add_Click({ try { Check-PcHelperUpdate -Manual } catch { [void][System.Windows.Forms.MessageBox]::Show( [string]$_, "Helper update", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Warning ) } }) $use.Add_Click({ $idx = $script:settingsList.SelectedIndex if ($idx -ge 0 -and $script:settingsProfiles.Count -gt $idx) { $pick = $script:settingsProfiles[$idx] Save-Cfg $pick.code $serverDefault $pick $true $script:cfg = Read-Cfg $script:after = 0 $script:primed = $false $script:fireAt = 0 $script:popUntil = 0 Update-IdleTip $script:openFarmAfterSettings = $true } Close-ClickedHelperForm }) $farmBtn.Add_Click({ $idx = $script:settingsList.SelectedIndex if ($idx -ge 0 -and $script:settingsProfiles.Count -gt $idx) { $pick = $script:settingsProfiles[$idx] Save-Cfg $pick.code $serverDefault $pick $true $script:cfg = Read-Cfg Update-IdleTip } $script:openFarmAfterSettings = $true Close-ClickedHelperForm }) $closeBtn.Add_Click({ Close-ClickedHelperForm }) $dlg.Controls.Add($lead) $dlg.Controls.Add($list) $dlg.Controls.Add($use) $dlg.Controls.Add($farmBtn) $dlg.Controls.Add($crashBtn) $dlg.Controls.Add($closeBtn) $dlg.Controls.Add($updBtn) [void]$dlg.ShowDialog() $dlg.Dispose() if ($script:openFarmAfterSettings) { $script:openFarmAfterSettings = $false try { Hide-Card } catch {} Show-HelperTools Show-AutoFarm } } function Open-TrayClick { $profiles = @(Find-RaidsProfiles) $needPick = ($profiles.Count -gt 1 -and -not ($script:cfg -and $script:cfg.picked -eq $true)) if ($needPick) { Show-ProfileSettings return } Show-HelperTools Show-AutoFarm } $script:after = 0 $script:primed = $false $script:fireAt = 0 $script:clockBody = "" $script:orderFireAt = 0 $script:orderKind = "land" $script:orderBody = "" $script:orderTick = 0 $script:popUntil = 0 $script:dismissedFire = 0 $script:busy = $false Write-HelperBoot "cfg" try { Update-HelperFromWebsite } catch {} try { Start-NewestHelperAlways } catch {} Write-HelperBoot "ui" $form = New-Object System.Windows.Forms.Form $form.FormBorderStyle = "None" $form.TopMost = $true $form.ShowInTaskbar = $false $form.ControlBox = $false $form.StartPosition = "Manual" $script:allowExit = $false $form.Add_FormClosing({ param($sender, $e) if (-not $script:allowExit) { $e.Cancel = $true try { $sender.Hide() } catch {} } }) $form.BackColor = [System.Drawing.Color]::FromArgb(22, 48, 28) $form.Size = New-Object System.Drawing.Size(420, 248) try { $script:appIcon = Get-AppIcon } catch { $script:appIcon = [System.Drawing.SystemIcons]::Application } try { $form.Icon = $script:appIcon } catch {} try { Install-PcHelperOnThisPc } catch {} Write-HelperBoot "form" $iconBox = New-Object System.Windows.Forms.PictureBox $iconBox.Size = New-Object System.Drawing.Size(48, 48) $iconBox.Location = New-Object System.Drawing.Point(12, 32) $iconBox.SizeMode = "Zoom" $iconBox.Cursor = [System.Windows.Forms.Cursors]::Hand if ($script:cardBitmap) { $iconBox.Image = $script:cardBitmap } $iconBox.BackColor = [System.Drawing.Color]::FromArgb(22, 48, 28) $iconBox.Add_Click({ Open-TrayClick }) $script:iconBox = $iconBox $timeLabel = New-Object System.Windows.Forms.Label $timeLabel.ForeColor = [System.Drawing.Color]::FromArgb(244, 255, 228) $timeLabel.Font = New-Object System.Drawing.Font("Segoe UI", 16, [System.Drawing.FontStyle]::Bold) $timeLabel.AutoSize = $false $timeLabel.Size = New-Object System.Drawing.Size(300, 32) $timeLabel.Location = New-Object System.Drawing.Point(70, 10) $timeLabel.Text = "Raids Timer" $titleLabel = New-Object System.Windows.Forms.Label $titleLabel.ForeColor = [System.Drawing.Color]::FromArgb(244, 255, 228) $titleLabel.Font = New-Object System.Drawing.Font("Segoe UI", 10, [System.Drawing.FontStyle]::Bold) $titleLabel.AutoSize = $false $titleLabel.Size = New-Object System.Drawing.Size(300, 22) $titleLabel.Location = New-Object System.Drawing.Point(70, 42) $bodyLabel = New-Object System.Windows.Forms.Label $bodyLabel.ForeColor = [System.Drawing.Color]::FromArgb(244, 255, 228) $bodyLabel.Font = New-Object System.Drawing.Font("Segoe UI", 9) $bodyLabel.AutoSize = $false $bodyLabel.Size = New-Object System.Drawing.Size(300, 36) $bodyLabel.Location = New-Object System.Drawing.Point(70, 64) $form.Controls.Add($iconBox) $form.Controls.Add($timeLabel) $form.Controls.Add($titleLabel) $form.Controls.Add($bodyLabel) $sendBarBtn = New-Object System.Windows.Forms.Button $sendBarBtn.Text = "Send order" $sendBarBtn.Location = New-Object System.Drawing.Point(12, 108) $sendBarBtn.Size = New-Object System.Drawing.Size(396, 32) $sendBarBtn.FlatStyle = "Flat" $sendBarBtn.Font = New-Object System.Drawing.Font("Segoe UI", 10, [System.Drawing.FontStyle]::Bold) $sendBarBtn.BackColor = [System.Drawing.Color]::FromArgb(48, 72, 40) $sendBarBtn.ForeColor = [System.Drawing.Color]::FromArgb(244, 255, 228) $sendBarBtn.Add_Click({ Show-SendOrderDialog }) $form.Controls.Add($sendBarBtn) $script:sendBarBtn = $sendBarBtn $farmBarBtn = New-Object System.Windows.Forms.Button $farmBarBtn.Text = "Auto Farm" $farmBarBtn.Location = New-Object System.Drawing.Point(12, 144) $farmBarBtn.Size = New-Object System.Drawing.Size(396, 48) $farmBarBtn.FlatStyle = "Flat" $farmBarBtn.Font = New-Object System.Drawing.Font("Segoe UI", 14, [System.Drawing.FontStyle]::Bold) $farmBarBtn.BackColor = [System.Drawing.Color]::FromArgb(40, 90, 48) $farmBarBtn.ForeColor = [System.Drawing.Color]::FromArgb(244, 255, 228) $farmBarBtn.Add_Click({ Show-AutoFarm }) $form.Controls.Add($farmBarBtn) $farmBarBtn.BringToFront() $script:farmBarBtn = $farmBarBtn function Move-ToClock { $area = [System.Windows.Forms.Screen]::PrimaryScreen.WorkingArea $form.Location = New-Object System.Drawing.Point( ($area.Right - $form.Width - 12), ($area.Bottom - $form.Height - 12) ) } function Show-Card($timeText, $title, $body, $color) { Move-ToClock $timeLabel.Text = $timeText $titleLabel.Text = $title $bodyLabel.Text = $body $form.BackColor = $color if ($script:iconBox) { $script:iconBox.BackColor = $color } if (-not $form.Visible) { $form.Show() } } function Hide-Card { $who = "Raids Timer" if ($script:cfg -and $script:cfg.displayName) { $who = [string]$script:cfg.displayName } $timeLabel.Text = "Auto Farm" $titleLabel.Text = $who $bodyLabel.Text = "Send order shares the alliance board. Countdown shows when you get orders." $form.BackColor = [System.Drawing.Color]::FromArgb(22, 48, 28) if ($script:iconBox) { $script:iconBox.BackColor = $form.BackColor } if (-not $form.Visible) { $form.Show() } } function Set-TrayTip($text) { if (-not $script:tray) { return } $tip = [string]$text if ($tip.Length -gt 63) { $tip = $tip.Substring(0, 63) } $script:tray.Text = $tip } $form.Add_Click({ if ([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() -lt $script:popUntil) { $script:popUntil = 0 Paint-Clock } }) function Get-BannerPollIds { $out = New-Object System.Collections.Generic.List[string] $add = { param($raw) $x = ([string]$raw).Trim() if ($x.Length -lt 3) { return } foreach ($have in $out) { if ([string]::Equals($have, $x, [StringComparison]::OrdinalIgnoreCase)) { return } } [void]$out.Add($x) } try { $script:cfg = Read-Cfg } catch {} $id = Get-ChatIdentity & $add $id.userId if ($id.serverNumber -and $id.playerId) { & $add ("ks_s" + [string]$id.serverNumber + "_p" + [string]$id.playerId) } if ($id.serverNumber -and $id.displayName) { $slug = (([string]$id.displayName) -replace '[^A-Za-z0-9]', '_').ToLower() if ($slug) { & $add ("ks_s" + [string]$id.serverNumber + "_p" + $slug) } } return @($out) } function Paint-Clock { $now = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() if ($now -lt $script:popUntil) { return } $feed = [int64]$script:fireAt $ord = [int64]$script:orderFireAt $use = 0 $kind = "send" $body = [string]$script:clockBody if ($ord -gt 0 -and ($feed -le 0 -or $ord -le $feed)) { $use = $ord $kind = [string]$script:orderKind if (-not $kind) { $kind = "land" } $body = [string]$script:orderBody } elseif ($feed -gt 0) { $use = $feed $kind = "send" $body = [string]$script:clockBody } if ($use -le 0) { Hide-Card Set-TrayTip $script:idleTip return } $left = [Math]::Ceiling(($use - $now) / 1000.0) if ($left -lt -8) { $script:fireAt = 0 $script:orderFireAt = 0 Hide-Card Set-TrayTip $script:idleTip return } $span = [TimeSpan]::FromSeconds([Math]::Max(0, $left)) $clock = "{0:00}:{1:00}" -f [int]$span.TotalMinutes, $span.Seconds $isSend = ($kind -eq "send") if ($left -le 0) { if ($isSend) { Show-Card "SEND" "SEND NOW" "Send now" ([System.Drawing.Color]::FromArgb(74, 28, 20)) Set-TrayTip "SEND NOW" } else { Show-Card "LAND" "LAND NOW" $body ([System.Drawing.Color]::FromArgb(74, 28, 20)) Set-TrayTip "LAND NOW" } try { if ($script:farmForm -and -not $script:farmForm.IsDisposed) { $script:farmForm.TopMost = $false } $form.TopMost = $true $form.BringToFront() } catch {} } elseif ($left -le 60) { Show-Card $clock "GET READY" $body ([System.Drawing.Color]::FromArgb(58, 50, 16)) Set-TrayTip "$clock GET READY" try { if ($script:farmForm -and -not $script:farmForm.IsDisposed) { $script:farmForm.TopMost = $false } $form.TopMost = $true $form.BringToFront() } catch {} } else { $head = "Rally moving" if (-not $isSend) { $head = "Order land" } Show-Card $clock $head $body ([System.Drawing.Color]::FromArgb(22, 48, 28)) Set-TrayTip "$clock $head" } } function Apply-Feed($json) { $now = [int64]$json.now $cursor = [int64]$json.cursor if (-not $script:primed) { $script:primed = $true $script:after = $cursor } else { foreach ($ev in @($json.events)) { if (-not $ev) { continue } $id = [int64]$ev.id if ($id -gt $script:after) { $script:after = $id } $tag = [string]$ev.tag if ($tag.StartsWith("raids-live-send")) { continue } $script:popUntil = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() + 9000 Show-Card "Order" ([string]$ev.title) ([string]$ev.body) ([System.Drawing.Color]::FromArgb(22, 48, 28)) } if ($cursor -gt $script:after) { $script:after = $cursor } } $best = 0 $bestBody = "" foreach ($clock in @($json.clocks)) { if (-not $clock) { continue } $kind = [string]$clock.kind $title = [string]$clock.title $isSend = ($kind -eq "send" -or $kind -eq "" -or $title -match '(?i)SEND') if (-not $isSend) { continue } $fire = [int64]$clock.fireAt $left = [Math]::Ceiling(($fire - $now) / 1000.0) if ($left -gt 86400 -or $left -lt -8) { continue } if ($best -eq 0 -or $fire -lt $best) { $best = $fire $bestBody = [string]$clock.body } } $script:fireAt = $best $script:clockBody = $bestBody Paint-Clock } $timer = New-Object System.Windows.Forms.Timer $timer.Interval = 1000 $timer.Add_Tick({ try { Paint-Clock } catch {} if ($script:busy) { return } $script:busy = $true try { $script:orderTick++ if ($script:orderTick -ge 5) { $script:orderTick = 0 try { Refresh-AllianceOrderClock } catch {} } $base = Get-ServerBase $ids = @(Get-BannerPollIds) if ($ids.Count -lt 1) { return } $merged = $null foreach ($uid in $ids) { $code = [uri]::EscapeDataString([string]$uid) $url = "$base/api/raids-timer/banner/feed?userId=$code&after=$($script:after)" try { $res = Invoke-RestMethod -Uri $url -TimeoutSec 8 if ($res) { if (-not $merged) { $merged = $res } else { $merged.now = $res.now $merged.clocks = @($merged.clocks) + @($res.clocks) $merged.events = @($merged.events) + @($res.events) if ([int64]$res.cursor -gt [int64]$merged.cursor) { $merged.cursor = $res.cursor } } } } catch {} } if ($merged) { Apply-Feed $merged } } catch { } finally { $script:busy = $false } }) $timer.Start() $script:farmBox = [hashtable]::Synchronized(@{ recording = $false playing = $false playError = "" crashLine = "" playNotice = "" sawMinimized = $false stopPlay = $false openUi = $false uiAction = "" playLoop = $false playLoopForce = $false playDelay = 500 playDelayForce = $false playKeyDelay = 500 uiLang = "" langDirty = $false farmGame = "kingshot" farmGameDirty = $false chatPaid = $false chatPaidDirty = $false chatPaidPush = $false farmTicketPush = "" chatPaidUntilPush = 0 chatPaidSourcePush = "" events = [System.Collections.ArrayList]::Synchronized((New-Object System.Collections.ArrayList)) recT0 = 0 recWasDown = $false recNeedRightUp = $false recRightWasDown = $false recIgnoreRightUntil = 0 recLastMove = 0 recLastX = -1 recLastY = -1 sightX = 0 sightY = 0 sightW = 0 sightH = 0 winTitle = "" targetInstance = "" targetPid = 0 sizeName = "BlueStacks" sizeX = 0 sizeY = 0 sizeW = 0 sizeH = 0 }) try { if ($script:cfg -and $script:cfg.farmGame) { $script:farmBox.farmGame = [string]$script:cfg.farmGame } } catch {} try { $script:farmBox.chatPaid = [bool](Test-ChatPaid) } catch {} try { Load-FarmSightCfg } catch {} $script:farmHttpOn = $false $script:farmListener = $null $farmSample = New-Object System.Windows.Forms.Timer $farmSample.Interval = 12 $farmSample.Add_Tick({ try { $b = $script:farmBox if ($b.openUi) { $b.openUi = $false try { Show-AutoFarm } catch {} } $act = "" try { $act = [string]$b.uiAction } catch {} if ($act) { $b.uiAction = "" try { switch ($act) { "open" { Show-AutoFarm } "record" { Farm-StartRecord } "stoprec" { Farm-StopRecord | Out-Null } "play" { Farm-PlayNow | Out-Null } "stopplay" { Farm-StopPlay } "how" { Show-FarmHowTo } "today" { Farm-FillTodayQueue | Out-Null } "split" { Start-FarmSplitView | Out-Null } "savesizes" { Save-FarmInstanceLayoutsFromWindows | Out-Null } "refreshinstances" { Refresh-FarmInstanceList } "chat" { Show-Chat } "share" { Show-ShareSite } "pay" { Open-PayPalUnlock } "update" { Check-PcHelperUpdate -Manual } } } catch {} } if ($b.langDirty) { $b.langDirty = $false try { Set-HelperLang ([string]$b.uiLang) | Out-Null Apply-HelperToolLang Update-ChatLog } catch {} } if ($b.farmGameDirty) { $b.farmGameDirty = $false try { Save-FarmGameId ([string]$b.farmGame) Fill-FarmGameCombo } catch {} } try { Accept-SiteChatPaid | Out-Null } catch {} $script:paidPulse = [int]$script:paidPulse + 1 if ($script:paidPulse -ge 5000) { $script:paidPulse = 0 if (-not $b.recording -and -not $b.playing) { try { $b.chatPaid = [bool](Test-ChatPaid) } catch {} } } if (-not $b.recording) { return } try { if ($script:glassForm -and -not $script:glassForm.IsDisposed) { return } } catch {} $rightDown = (([RtFarmMouse]::GetAsyncKeyState(0x02) -band 0x8000) -ne 0) if ($b.recNeedRightUp -or [Environment]::TickCount -lt [int]$b.recIgnoreRightUntil) { if (-not $rightDown) { $b.recNeedRightUp = $false } $b.recRightWasDown = $rightDown $rightDown = $false } $rightPress = ($rightDown -and -not $b.recRightWasDown) $b.recRightWasDown = $rightDown if ($rightPress) { try { $ev = Farm-StopRecord $nm = Save-FarmRecording $ev Restore-FarmWindow $n = @($ev).Count Write-HelperCrashLog ("record right-click save name=" + $nm + " events=" + $n) if ($nm) { Show-FarmToast ("Saved " + $nm + ". " + $n + " clicks. Press Record again for the next step.") } else { Show-FarmToast "Nothing was recorded. Press Record, left-click the game, then right-click to save." } } catch { $b.recording = $false Restore-FarmWindow Write-HelperCrashLog ("record right-click failed: " + $_.Exception.Message) Show-FarmToast "Right-click stopped the step. It could not be saved." } return } if (([RtFarmMouse]::GetAsyncKeyState(0x1B) -band 0x8000)) { $b.recording = $false try { $script:lastFarmEvents = Convert-FarmEvents @($b.events) } catch {} try { Set-FarmStatus ("Stopped record. " + @($script:lastFarmEvents).Count + " moves. Not saved.") } catch {} return } $pt = New-Object RtFarmMouse+POINT [void][RtFarmMouse]::GetCursorPos([ref]$pt) $down = ([RtFarmMouse]::GetAsyncKeyState(0x01) -band 0x8000) -ne 0 $t = [Environment]::TickCount - [int]$b.recT0 $nx = -1.0 $ny = -1.0 $coordSpace = "screen" try { if ([int]$b.sightW -gt 20 -and [int]$b.sightH -gt 20) { $nx = ([double]$pt.X - [double][int]$b.sightX) / [double][int]$b.sightW $ny = ([double]$pt.Y - [double][int]$b.sightY) / [double][int]$b.sightH if ($nx -ge 0 -and $nx -le 1 -and $ny -ge 0 -and $ny -le 1) { $coordSpace = "target" } } } catch {} if ($down -and -not $b.recWasDown) { [void]$b.events.Add(@{ t = $t; type = "down"; x = $pt.X; y = $pt.Y; nx = $nx; ny = $ny; space = $coordSpace }) } elseif (-not $down -and $b.recWasDown) { [void]$b.events.Add(@{ t = $t; type = "up"; x = $pt.X; y = $pt.Y; nx = $nx; ny = $ny; space = $coordSpace }) } elseif (($pt.X -ne $b.recLastX -or $pt.Y -ne $b.recLastY) -and ($t - [int]$b.recLastMove -ge 16)) { [void]$b.events.Add(@{ t = $t; type = "move"; x = $pt.X; y = $pt.Y; nx = $nx; ny = $ny; space = $coordSpace }) $b.recLastMove = $t } $b.recWasDown = $down $b.recLastX = $pt.X $b.recLastY = $pt.Y $keyState = $b.recKeyDown if (-not $keyState) { return } for ($vk = 8; $vk -le 254; $vk++) { if ($vk -le 6 -or $vk -eq 0x1B) { continue } $kdown = ([RtFarmMouse]::GetAsyncKeyState($vk) -band 0x8000) -ne 0 if ($kdown -eq [bool]$keyState[$vk]) { continue } $keyState[$vk] = $kdown $kind = $(if ($kdown) { "keydown" } else { "keyup" }) [void]$b.events.Add(@{ t = $t; type = $kind; x = 0; y = 0; key = $vk; file = "" }) } } catch {} }) $farmSample.Start() $farmLeaseBeat = New-Object System.Windows.Forms.Timer $farmLeaseBeat.Interval = 45000 $farmLeaseBeat.Add_Tick({ try { $b = $script:farmBox if ($b -and ($b.recording -or $b.playing)) { if (-not (Request-FarmLease "beat")) { Request-FarmLease "start" | Out-Null } } } catch {} }) $farmLeaseBeat.Start() try { $listener = New-Object System.Net.HttpListener $listener.Prefixes.Add("http://127.0.0.1:18765/") $listener.Start() $script:farmListener = $listener $script:farmHttpOn = $true $farmPs = [powershell]::Create().AddScript({ param($listener, $box, $helperVer) function Send-FarmJson($res, $obj, $code = 200) { $json = $obj | ConvertTo-Json -Compress -Depth 8 $bytes = [Text.Encoding]::UTF8.GetBytes([string]$json) $res.StatusCode = $code $res.ContentType = "application/json; charset=utf-8" $res.Headers["Access-Control-Allow-Origin"] = "*" $res.Headers["Access-Control-Allow-Methods"] = "GET,POST,OPTIONS" $res.Headers["Access-Control-Allow-Headers"] = "Content-Type" $res.Headers["Access-Control-Allow-Private-Network"] = "true" $res.ContentLength64 = $bytes.Length $res.OutputStream.Write($bytes, 0, $bytes.Length) $res.OutputStream.Close() } while ($listener.IsListening) { try { $ctx = $listener.GetContext() } catch { break } $req = $ctx.Request $res = $ctx.Response if ($req.HttpMethod -eq "OPTIONS") { $res.StatusCode = 204 $res.Headers["Access-Control-Allow-Origin"] = "*" $res.Headers["Access-Control-Allow-Methods"] = "GET,POST,OPTIONS" $res.Headers["Access-Control-Allow-Headers"] = "Content-Type" $res.Headers["Access-Control-Allow-Private-Network"] = "true" $res.Close() continue } $path = $req.Url.AbsolutePath.TrimEnd("/").ToLowerInvariant() try { if ($path -eq "/health" -or $path -eq "") { $paid = $false try { $paid = [bool]$box.chatPaid } catch {} Send-FarmJson $res @{ ok = $true; recording = [bool]$box.recording; playing = [bool]$box.playing; helper = "pc-banner"; version = [string]$helperVer; lang = [string]$box.uiLang; farmGame = [string]$box.farmGame; chatPaid = $paid } continue } if ($path -eq "/ui/update") { $box.uiAction = "update" Send-FarmJson $res @{ ok = $true; action = "update" } continue } if ($path -eq "/ui/farmgame" -and $req.HttpMethod -eq "POST") { $reader = New-Object IO.StreamReader($req.InputStream, $req.ContentEncoding) $raw = $reader.ReadToEnd() $reader.Close() $gid = "kingshot" try { $body = $raw | ConvertFrom-Json if ($body.game) { $gid = [string]$body.game } } catch {} $gid = $gid.ToLower().Trim() $box.farmGame = $gid $box.farmGameDirty = $true Send-FarmJson $res @{ ok = $true; farmGame = $gid } continue } if ($path -eq "/ui/open") { $box.openUi = $true Send-FarmJson $res @{ ok = $true; open = $true } continue } if ($path -eq "/ui/chat-paid" -and $req.HttpMethod -eq "POST") { $reader = New-Object IO.StreamReader($req.InputStream, $req.ContentEncoding) $raw = $reader.ReadToEnd() $reader.Close() $body = $null try { $body = $raw | ConvertFrom-Json } catch { $body = $null } $on = $false try { if ($body -and ($body.active -eq $true -or $body.paid -eq $true)) { $on = $true } } catch { $on = $false } if ($on) { $box.chatPaid = $true $box.chatPaidPush = $true $box.chatPaidDirty = $true try { if ($body.farmTicket) { $box.farmTicketPush = [string]$body.farmTicket } } catch {} try { if ($body.expiresAt) { $box.chatPaidUntilPush = [int64]$body.expiresAt } } catch {} try { if ($body.source) { $box.chatPaidSourcePush = [string]$body.source } } catch {} } Send-FarmJson $res @{ ok = $true; chatPaid = [bool]$box.chatPaid } continue } if ($path -eq "/ui/farm-action" -and $req.HttpMethod -eq "POST") { $reader = New-Object IO.StreamReader($req.InputStream, $req.ContentEncoding) $raw = $reader.ReadToEnd() $reader.Close() $act = "open" try { $body = $raw | ConvertFrom-Json if ($body.action) { $act = [string]$body.action } if ($null -ne $body.loop) { $box.playLoop = [bool]$body.loop; $box.playLoopForce = $true } if ($null -ne $body.delay) { $box.playDelay = [int]$body.delay; $box.playDelayForce = $true } if ($null -ne $body.keyDelay) { $box.playKeyDelay = [int]$body.keyDelay } } catch {} $act = $act.ToLower().Trim() if ($act -eq "record" -or $act -eq "play" -or $act -eq "today") { $paid = $false try { $paid = [bool]$box.chatPaid } catch {} if (-not $paid) { $box.uiAction = $act Send-FarmJson $res @{ ok = $true; action = $act; chatPaid = $false } continue } } $box.uiAction = $act Send-FarmJson $res @{ ok = $true; action = [string]$box.uiAction; chatPaid = $true } continue } if ($path -eq "/ui/lang") { $reader = New-Object IO.StreamReader($req.InputStream, $req.ContentEncoding) $raw = $reader.ReadToEnd() $reader.Close() $lang = "en" try { $body = $raw | ConvertFrom-Json if ($body.lang) { $lang = [string]$body.lang } } catch {} $lang = $lang.Trim().ToLower().Replace("_", "-") if ($lang -match '^([a-z]{2})') { $lang = $Matches[1] } if ($lang.Length -lt 2) { $lang = "en" } $box.uiLang = $lang $box.langDirty = $true try { $lp = Join-Path $env:APPDATA "RaidsTimer\helper-lang.txt" Set-Content -LiteralPath $lp -Value $lang -Encoding UTF8 } catch {} Send-FarmJson $res @{ ok = $true; lang = $lang } continue } if ($path -eq "/record/start" -and $req.HttpMethod -eq "POST") { $box.events.Clear() $box.recT0 = [Environment]::TickCount $box.recWasDown = $false $box.recLastMove = 0 $box.recording = $true Send-FarmJson $res @{ ok = $true; recording = $true } continue } if ($path -eq "/record/stop" -and $req.HttpMethod -eq "POST") { $box.recording = $false Start-Sleep -Milliseconds 30 $list = @($box.events) Send-FarmJson $res @{ ok = $true; events = $list; count = $list.Count } continue } if ($path -eq "/stop" -and $req.HttpMethod -eq "POST") { $box.recording = $false $box.stopPlay = $true $box.playing = $false Send-FarmJson $res @{ ok = $true } continue } if ($path -eq "/play" -and $req.HttpMethod -eq "POST") { $reader = New-Object IO.StreamReader($req.InputStream, $req.ContentEncoding) $raw = $reader.ReadToEnd() $reader.Close() $body = $raw | ConvertFrom-Json $events = @($body.events) $loop = [bool]$body.loop $speed = [double]$body.speed if ($speed -le 0) { $speed = 1 } $box.stopPlay = $false $play = [powershell]::Create().AddScript({ param($events, $loop, $speed, $box) $box.playing = $true $heldKeys = @{} try { do { $prevT = 0 foreach ($e in $events) { if ($box.stopPlay) { break } if ([RtFarmMouse]::GetAsyncKeyState(0x1B) -band 0x8000) { $box.stopPlay = $true; break } if ([RtFarmMouse]::GetAsyncKeyState(0x02) -band 0x8000) { $box.stopPlay = $true; break } $wait = [int]((([int]$e.t) - $prevT) / $speed) if ($wait -gt 0 -and $wait -lt 120000) { Start-Sleep -Milliseconds $wait } $prevT = [int]$e.t if ([string]$e.type -eq "keydown") { $vk = [int]$e.key [RtFarmKeys179]::Down([byte]$vk) $heldKeys[$vk] = $true Start-Sleep -Milliseconds 500 continue } if ([string]$e.type -eq "keyup") { $vk = [int]$e.key [RtFarmKeys179]::Up([byte]$vk) [void]$heldKeys.Remove($vk) Start-Sleep -Milliseconds 500 continue } [void][RtFarmMouse]::SetCursorPos([int]$e.x, [int]$e.y) if ($e.type -eq "down") { [RtFarmMouse]::Down() } elseif ($e.type -eq "up") { [RtFarmMouse]::Up() } } } while ($loop -and -not $box.stopPlay) } finally { foreach ($heldVk in @($heldKeys.Keys)) { try { [RtFarmKeys179]::Up([byte][int]$heldVk) } catch {} } } $box.playing = $false }).AddArgument($events).AddArgument($loop).AddArgument($speed).AddArgument($box) $play.Runspace = [runspacefactory]::CreateRunspace() $play.Runspace.Open() try { $box.playJob = $play } catch {} [void]$play.BeginInvoke() Send-FarmJson $res @{ ok = $true; playing = $true } continue } Send-FarmJson $res @{ ok = $false; error = "not found" } 404 } catch { try { Send-FarmJson $res @{ ok = $false; error = $_.ToString() } 500 } catch { $res.Close() } } } }).AddArgument($listener).AddArgument($script:farmBox).AddArgument([string]$script:HelperVersion) $farmPs.Runspace = [runspacefactory]::CreateRunspace() $farmPs.Runspace.Open() $script:farmHttpJob = $farmPs [void]$farmPs.BeginInvoke() } catch { $script:farmHttpOn = $false } Move-ToClock $script:tray = New-Object System.Windows.Forms.NotifyIcon $script:tray.Icon = $script:appIcon $script:tray.Visible = $true try { Set-Content -Path (Join-Path $root "helper-ready.txt") -Value ((Get-Date).ToString("o") + " v" + $script:HelperVersion) -Encoding UTF8 Write-HelperBoot "ready" Write-HelperCrashLog ("helper ready v" + [string]$script:HelperVersion) } catch {} $menu = New-Object System.Windows.Forms.ContextMenuStrip $miFarm = $menu.Items.Add("Auto Farm") $miChat = $menu.Items.Add("Chat") $miShare = $menu.Items.Add("Share website") $miFarmHow = $menu.Items.Add("How to use Auto Farm") $miWinHelp = $menu.Items.Add("If Windows blocked this") $miFarmOn = $menu.Items.Add("Auto Farm is on") $miFarmOn.Enabled = $false $miCrashLog = $menu.Items.Add("Copy crash log") $miSettings = $menu.Items.Add("Settings") $miExit = $menu.Items.Add("Exit") $miFarm.Add_Click({ Show-AutoFarm }) $miChat.Add_Click({ Show-Chat }) $miShare.Add_Click({ Show-ShareSite }) $miFarmHow.Add_Click({ Show-FarmHowTo }) $miCrashLog.Add_Click({ Show-HelperCrashLog }) $miWinHelp.Add_Click({ Show-WindowsBlockHelp }) $miSettings.Add_Click({ Show-ProfileSettings }) $miExit.Add_Click({ $script:allowExit = $true try { if ($script:tray) { $script:tray.Visible = $false } } catch {} try { if ($form -and -not $form.IsDisposed) { $form.Close() } } catch {} }) $script:tray.ContextMenuStrip = $menu $script:tray.Add_MouseClick({ param($sender, $e) if ($e.Button -eq [System.Windows.Forms.MouseButtons]::Left) { Open-TrayClick } }) Update-IdleTip try { $script:tray.Visible = $false $script:tray.Visible = $true $script:tray.BalloonTipTitle = "Raids Timer is on" $script:tray.BalloonTipText = "Click the icon: pick your commander if you have more than one, then Auto Farm opens. Right-click also lists Auto Farm first." $script:tray.ShowBalloonTip(15000) } catch {} if ($script:farmHttpOn) { $script:updLater = New-Object System.Windows.Forms.Timer $script:updLater.Interval = 2500 $script:updLater.Add_Tick({ try { $script:updLater.Stop() } catch {} try { Check-PcHelperUpdate } catch {} }) $script:updLater.Start() } else { $miFarmOn.Text = "Auto Farm off" } $who = "" if ($script:cfg) { $who = [string]$script:cfg.displayName } Set-Content -Path (Join-Path $root "pc-banner.log") -Value ("started following=" + $who) -Encoding UTF8 if ($OpenChat) { $script:openChatTimer = New-Object System.Windows.Forms.Timer $script:openChatTimer.Interval = 500 $script:openChatTimer.Add_Tick({ $script:openChatTimer.Stop() Show-Chat }) $script:openChatTimer.Start() } if ($OpenFarm) { $script:openFarmTimer = New-Object System.Windows.Forms.Timer $script:openFarmTimer.Interval = 400 $script:openFarmTimer.Add_Tick({ $script:openFarmTimer.Stop() Show-AutoFarm }) $script:openFarmTimer.Start() } $form.Add_FormClosed({ try { if ($script:farmListener) { $script:farmListener.Stop() } } catch {} if ($script:tray) { try { $script:tray.Visible = $false } catch {} try { $script:tray.Dispose() } catch {} } }) $script:helperUiUp = $true $ErrorActionPreference = "Continue" try { [void][System.Windows.Forms.Application]::SetUnhandledExceptionMode([System.Windows.Forms.UnhandledExceptionMode]::CatchException) } catch {} try { [System.Windows.Forms.Application]::add_ThreadException({ param($sender, $e) }) } catch {} try { Show-AutoFarm } catch {} $script:pickLater = New-Object System.Windows.Forms.Timer $script:pickLater.Interval = 700 $script:pickLater.Add_Tick({ try { $script:pickLater.Stop() } catch {} try { $more = @(Find-RaidsProfiles) if ($more.Count -gt 1 -and -not ($script:cfg -and $script:cfg.picked -eq $true)) { Show-ProfileSettings Update-IdleTip } } catch {} }) $script:pickLater.Start() [System.Windows.Forms.Application]::Run($form)