From 7fa88a2ecf24cf693b367299db095c4d55967fcf Mon Sep 17 00:00:00 2001 From: Ruen UI contributors Date: Sat, 21 Nov 2026 12:10:42 -0600 Subject: [PATCH] Prepare first public Ruen UI beta with verified upstream downloads and reversible installers --- .gitattributes | 7 + .gitignore | 5 + Install-Ruen-UI-Russian.cmd | 9 + Install-Ruen-UI.cmd | 9 + Install-Ruen-UI.ps1 | 469 +++++++++ Install-Russian.cmd | 3 + Install-Windows.cmd | 3 + KEYBINDINGS.txt | 176 ++++ LAYOUT-AUDIT.txt | 222 ++++ LICENSE | 25 + Optimize-Ruen-UI.ps1 | 10 + README.md | 45 + Ruen-Setup | 250 +++++ Ruen-Setup.exe | Bin 0 -> 3072 bytes RuenUI/AddonPresets.lua | 292 ++++++ RuenUI/Bindings.xml | 7 + RuenUI/Brand.lua | 44 + RuenUI/ClassAssist.lua | 334 ++++++ RuenUI/ClassLayout.lua | 226 ++++ RuenUI/Controls.lua | 223 ++++ RuenUI/Core.lua | 1106 ++++++++++++++++++++ RuenUI/DamageMeters.lua | 199 ++++ RuenUI/ExtraBars.lua | 309 ++++++ RuenUI/GunAudio.lua | 65 ++ RuenUI/HardwareProfile.lua | 3 + RuenUI/LanguageDefaults.lua | 2 + RuenUI/Locale.lua | 46 + RuenUI/Optimizer.lua | 236 +++++ RuenUI/OverlayLayout.lua | 533 ++++++++++ RuenUI/PetExtras.lua | 465 +++++++++ RuenUI/Profile.lua | 76 ++ RuenUI/RuenUI.toc | 26 + RuenUI/SwingTimers.lua | 162 +++ Tools/Measure-RuenHardware.ps1 | 79 ++ Tools/Migrate-RuenUI.ps1 | 44 + Tools/Resolve-RuenDependencies.ps1 | 146 +++ Tools/Ruen-Setup.c | 36 + Tools/kernel32.def | 13 + Tools/ruen_dependencies.py | 148 +++ Tools/ruen_hardware.py | 108 ++ Tools/ruen_migrate.py | 53 + dependencies.lock.json | 98 ++ docs/DEPENDENCIES.md | 19 + docs/DEVELOPMENT.md | 57 + docs/INSTALL-RU.md | 23 + docs/INSTALL.md | 75 ++ docs/RELEASE-REVIEW.md | 56 + scripts/build_release.py | 53 + tests/check-gun-audio.lua | 102 ++ tests/check-layout.lua | 1552 ++++++++++++++++++++++++++++ tests/check-meter.lua | 133 +++ tests/check-pet-actions.lua | 367 +++++++ tests/check-timers-optimizer.lua | 63 ++ tests/test_installers.py | 216 ++++ 54 files changed, 9028 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 Install-Ruen-UI-Russian.cmd create mode 100644 Install-Ruen-UI.cmd create mode 100644 Install-Ruen-UI.ps1 create mode 100644 Install-Russian.cmd create mode 100644 Install-Windows.cmd create mode 100644 KEYBINDINGS.txt create mode 100644 LAYOUT-AUDIT.txt create mode 100644 LICENSE create mode 100644 Optimize-Ruen-UI.ps1 create mode 100644 README.md create mode 100755 Ruen-Setup create mode 100755 Ruen-Setup.exe create mode 100644 RuenUI/AddonPresets.lua create mode 100644 RuenUI/Bindings.xml create mode 100644 RuenUI/Brand.lua create mode 100644 RuenUI/ClassAssist.lua create mode 100644 RuenUI/ClassLayout.lua create mode 100644 RuenUI/Controls.lua create mode 100644 RuenUI/Core.lua create mode 100644 RuenUI/DamageMeters.lua create mode 100644 RuenUI/ExtraBars.lua create mode 100644 RuenUI/GunAudio.lua create mode 100644 RuenUI/HardwareProfile.lua create mode 100644 RuenUI/LanguageDefaults.lua create mode 100644 RuenUI/Locale.lua create mode 100644 RuenUI/Optimizer.lua create mode 100644 RuenUI/OverlayLayout.lua create mode 100644 RuenUI/PetExtras.lua create mode 100644 RuenUI/Profile.lua create mode 100644 RuenUI/RuenUI.toc create mode 100644 RuenUI/SwingTimers.lua create mode 100644 Tools/Measure-RuenHardware.ps1 create mode 100644 Tools/Migrate-RuenUI.ps1 create mode 100644 Tools/Resolve-RuenDependencies.ps1 create mode 100644 Tools/Ruen-Setup.c create mode 100644 Tools/kernel32.def create mode 100644 Tools/ruen_dependencies.py create mode 100755 Tools/ruen_hardware.py create mode 100644 Tools/ruen_migrate.py create mode 100644 dependencies.lock.json create mode 100644 docs/DEPENDENCIES.md create mode 100644 docs/DEVELOPMENT.md create mode 100644 docs/INSTALL-RU.md create mode 100644 docs/INSTALL.md create mode 100644 docs/RELEASE-REVIEW.md create mode 100644 scripts/build_release.py create mode 100644 tests/check-gun-audio.lua create mode 100644 tests/check-layout.lua create mode 100644 tests/check-meter.lua create mode 100644 tests/check-pet-actions.lua create mode 100644 tests/check-timers-optimizer.lua create mode 100644 tests/test_installers.py diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..b50a403 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,7 @@ +* text=auto +*.cmd text eol=crlf +*.ps1 text eol=lf +Ruen-Setup text eol=lf +*.lua text eol=lf +*.py text eol=lf +*.exe binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c14e11e --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +__pycache__/ +*.pyc +/dist/ +/manifest.json +*.part diff --git a/Install-Ruen-UI-Russian.cmd b/Install-Ruen-UI-Russian.cmd new file mode 100644 index 0000000..8cb8b4d --- /dev/null +++ b/Install-Ruen-UI-Russian.cmd @@ -0,0 +1,9 @@ +@echo off +setlocal +title Ruen UI Setup +"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -ExecutionPolicy Bypass -File "%~dp0Install-Ruen-UI.ps1" -Language ru -VoicePacks enru %* +set "wow_setup_exit=%errorlevel%" +echo. +if not "%wow_setup_exit%"=="0" echo Setup did not finish. See the message above. +pause +exit /b %wow_setup_exit% diff --git a/Install-Ruen-UI.cmd b/Install-Ruen-UI.cmd new file mode 100644 index 0000000..c4d60ee --- /dev/null +++ b/Install-Ruen-UI.cmd @@ -0,0 +1,9 @@ +@echo off +setlocal +title Ruen UI Setup +"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -ExecutionPolicy Bypass -File "%~dp0Install-Ruen-UI.ps1" %* +set "wow_setup_exit=%errorlevel%" +echo. +if not "%wow_setup_exit%"=="0" echo Installation did not finish. See the message above. +pause +exit /b %wow_setup_exit% diff --git a/Install-Ruen-UI.ps1 b/Install-Ruen-UI.ps1 new file mode 100644 index 0000000..186cfc9 --- /dev/null +++ b/Install-Ruen-UI.ps1 @@ -0,0 +1,469 @@ +# Requires Windows PowerShell 5.1 or newer. Native language downloads use Battle.net. +[CmdletBinding()] +param( + [string]$WoWPath, + [ValidateSet("none", "en", "enru")][string]$VoicePacks = "en", + [string]$CachePath, + [switch]$Restore, + [string]$BackupPath, + [ValidateSet("auto", "en", "ru")][string]$Language = "auto", + [switch]$LanguageOnly, + [switch]$NonInteractive +) +Set-StrictMode -Version 2.0 +$ErrorActionPreference = 'Stop' +$bundle = $PSScriptRoot +$utf8 = New-Object System.Text.UTF8Encoding($false) +# RuenUI is the current addon ID. Legacy saves and bindings migrate during setup. +$addonNames = @('RuenUI') +$stage = $null; $gameLock = $null; $cacheLock = $null + +function Write-Utf8([string]$Path, [string]$Text) { + [System.IO.File]::WriteAllText($Path, $Text, $utf8) +} +function Assert-GameClosed { + if (@(Get-Process -Name Wow, WowClassic -ErrorAction SilentlyContinue).Count -gt 0) { + throw 'Close World of Warcraft before installing or restoring. Battle.net can stay open.' + } +} +function Assert-NoLinks([string]$Path) { + $current = $Path + while ($current) { + if (Test-Path -LiteralPath $current) { + $item = Get-Item -LiteralPath $current -Force + if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { + throw "This path uses a link/junction. Use the actual game folder: $current" + } + } + $parent = Split-Path -Parent $current + if ($parent -eq $current) { break } + $current = $parent + } +} +function Assert-NoNestedLinks([string]$Path) { + Assert-NoLinks $Path + if (Test-Path -LiteralPath $Path -PathType Container) { + foreach ($item in @(Get-ChildItem -LiteralPath $Path -Recurse -Force)) { + if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Linked content cannot be replaced safely: $($item.FullName)" } + } + } +} +function Resolve-Forever([string]$Candidate) { + if (-not $Candidate) { return } + $Candidate = $Candidate.Trim().Trim('"') + if (Test-Path -LiteralPath $Candidate -PathType Container) { $Candidate = (Get-Item -LiteralPath $Candidate).FullName.TrimEnd([char[]]'\/') } + foreach ($p in @($Candidate, (Join-Path $Candidate '_forever_'))) { + if ((Split-Path -Leaf $p) -eq '_forever_' -and (Test-Path -LiteralPath (Join-Path $p 'Wow.exe') -PathType Leaf)) { + return (Get-Item -LiteralPath $p).FullName + } + } +} +function Find-Forever { + if ($WoWPath) { + $found = Resolve-Forever $WoWPath + if (-not $found) { throw 'The supplied folder must contain _forever_\Wow.exe, or be the _forever_ folder itself.' } + return $found + } + $candidates = New-Object 'System.Collections.Generic.List[string]' + foreach ($base in @($env:ProgramFiles, ${env:ProgramFiles(x86)})) { + if ($base) { $candidates.Add((Join-Path $base 'World of Warcraft')) } + } + $registryPaths = @( + 'HKLM:\SOFTWARE\Blizzard Entertainment\World of Warcraft', + 'HKLM:\SOFTWARE\WOW6432Node\Blizzard Entertainment\World of Warcraft', + 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\World of Warcraft', + 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\World of Warcraft' + ) + foreach ($key in $registryPaths) { + $entry = Get-ItemProperty -LiteralPath $key -ErrorAction SilentlyContinue + if ($entry) { + foreach ($property in @('InstallPath', 'InstallLocation')) { + $p = $entry.PSObject.Properties[$property] + if ($p -and $p.Value) { $candidates.Add([string]$p.Value) } + } + } + } + foreach ($drive in @(Get-PSDrive -PSProvider FileSystem)) { + foreach ($relative in @('World of Warcraft', 'Games\World of Warcraft', 'Battle.net\World of Warcraft', 'Program Files (x86)\World of Warcraft', 'Program Files\World of Warcraft')) { + $candidates.Add((Join-Path $drive.Root $relative)) + } + } + $found = @($candidates | ForEach-Object { Resolve-Forever $_ } | Sort-Object -Unique) + if ($found.Count -eq 1) { return $found[0] } + if ($found.Count -gt 1) { + Write-Host 'Several Forever installations were found:' + for ($i = 0; $i -lt $found.Count; $i++) { Write-Host ("{0}: {1}" -f ($i + 1), $found[$i]) } + if ($NonInteractive) { throw 'Several installations found. Supply -WoWPath.' } + $selection = Read-Host 'Enter the number to configure' + $number = 0 + if ([int]::TryParse($selection, [ref]$number) -and $number -ge 1 -and $number -le $found.Count) { return $found[$number - 1] } + throw 'No valid installation selected. Nothing changed.' + } + if ($NonInteractive) { throw 'No unique installation found. Supply -WoWPath.' } + $chosen = Read-Host 'Paste the World of Warcraft folder path (Forever must already be installed)' + $result = Resolve-Forever $chosen + if (-not $result) { throw 'Could not find _forever_\Wow.exe. Nothing changed.' } + return $result +} +function Test-LanguageSelection([string]$Root) { + $info = Join-Path (Split-Path -Parent $Root) '.build.info' + if (-not (Test-Path -LiteralPath $info -PathType Leaf)) { return $false } + $rows = @(Get-Content -LiteralPath $info | ConvertFrom-Csv -Delimiter '|') + foreach ($row in $rows) { + $product = $row.PSObject.Properties | Where-Object { $_.Name -like 'Product!*' } | Select-Object -First 1 + $active = $row.PSObject.Properties | Where-Object { $_.Name -like 'Active!*' } | Select-Object -First 1 + $tags = $row.PSObject.Properties | Where-Object { $_.Name -like 'Tags!*' } | Select-Object -First 1 + if ($product -and $product.Value -eq 'wowf' -and $active -and $active.Value -eq '1' -and $tags) { + foreach ($locale in @('enUS', 'ruRU')) { + foreach ($kind in @('text', 'speech')) { + if ($tags.Value -notmatch ($locale + '\s+' + $kind + '\?')) { return $false } + } + } + return $true + } + } + return $false +} +function Prepare-Languages([string]$Root) { + if (Test-LanguageSelection $Root) { + Write-Host 'English + Russian are selected in the game installation. Wait for Battle.net to finish any active download before playing.' + return + } + Write-Host 'One-time game language preparation / Однократная загрузка языков игры' -ForegroundColor Yellow + Write-Host 'Battle.net > WoW: Forever > gear next to Play > Modify Install.' + Write-Host 'For immediate Russian startup, select Russian for BOTH default Text and Speech languages in the same dialog.' + Write-Host 'Keep BOTH English and Russian checked. Start Update and wait until the download reaches 100%, even if Play appears earlier.' + Write-Host 'Battle.net > WoW: Forever > шестерёнка > Изменить установку.' + Write-Host 'Оставьте английский и русский. Начните обновление и дождитесь 100%, даже если «Играть» появится раньше.' + Write-Host 'The addon recordings are bundled; Blizzard game files are downloaded by Battle.net once on this PC.' + if ($NonInteractive) { throw 'English and Russian native game files have not both been selected. Complete Modify Install, then run this installer again.' } + foreach ($base in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) { + if (-not $base) { continue } + $launcher = Join-Path $base 'Battle.net/Battle.net Launcher.exe' + if (Test-Path -LiteralPath $launcher -PathType Leaf) { Start-Process -FilePath $launcher; break } + } + $answer = Read-Host 'When the download finishes, press Enter; type cancel to stop / После загрузки нажмите Enter (cancel — отмена)' + if ($answer -eq 'cancel') { throw 'Cancelled before changing files.' } + Assert-GameClosed + if (-not (Test-LanguageSelection $Root)) { throw 'Both languages are still not selected for WoW: Forever. Complete Modify Install, then run this installer again.' } +} +function Language-Config([string]$Root, [string]$Locale) { + $file = Join-Path $Root 'WTF/Config.wtf' + $text = if (Test-Path -LiteralPath $file -PathType Leaf) { [IO.File]::ReadAllText($file) } else { '' } + $lines = @($text -split '\r?\n' | Where-Object { $_ -notmatch '^SET\s+(textLocale|audioLocale)\s' -and $_ -ne '' }) + $lines += 'SET textLocale "' + $Locale + '"' + $lines += 'SET audioLocale "' + $Locale + '"' + return ($lines -join "`r`n") + "`r`n" +} + +function Safe-RelativePath([string]$Root, [string]$Relative) { + if ([IO.Path]::IsPathRooted($Relative) -or $Relative -match '(^|[\\/])\.\.([\\/]|$)' -or $Relative.Contains(':')) { + throw "Invalid relative path in package: $Relative" + } + $path = Join-Path $Root $Relative + Assert-NoLinks $path + return $path +} +function Verify-Package { + $manifest = Get-Content -LiteralPath (Join-Path $bundle 'manifest.json') -Raw | ConvertFrom-Json + if ($manifest.format -ne 1) { throw 'Unsupported package format.' } + $listed = @{} + Assert-NoNestedLinks $bundle + foreach ($entry in $manifest.files) { + if ($listed.ContainsKey($entry.path)) { throw 'Duplicate manifest entry.' }; $listed[$entry.path] = $true + $path = Safe-RelativePath $bundle $entry.path + if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { throw "Package file missing: $($entry.path). Extract the whole ZIP first." } + $hash = (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash + if ($hash -ne $entry.sha256) { throw "Package integrity check failed: $($entry.path). Extract a fresh copy." } + } + foreach ($file in @(Get-ChildItem -LiteralPath $bundle -File -Recurse -Force)) { + $rel = $file.FullName.Substring($bundle.Length).TrimStart([char[]]'\/').Replace('\','/') + if ($rel -ne 'manifest.json' -and -not $listed.ContainsKey($rel)) { throw ('Unexpected package file: ' + $rel) } + } + if (-not (Select-String -LiteralPath (Join-Path $bundle 'RuenUI/RuenUI.toc') -Pattern '^## Interface:.*16001' -Quiet)) { + throw 'This release is not marked compatible with Forever.' + } +} +function Restore-Receipt([string]$Backup) { + $receiptPath = Join-Path $Backup 'receipt.json' + $receipt = Get-Content -LiteralPath $receiptPath -Raw | ConvertFrom-Json + if ($receipt.format -ne 1) { throw 'Unsupported backup format.' } + $root = Resolve-Forever $receipt.gameRoot + if (-not $root -or $root -ne $receipt.gameRoot) { throw 'The backup game path is no longer valid.' } + Assert-NoLinks $root + Assert-NoNestedLinks $Backup + $restoreLock = Join-Path $root '.ruen-install.lock' + Assert-NoLinks $restoreLock + $script:gameLock = [IO.File]::Open($restoreLock, [IO.FileMode]::OpenOrCreate, [IO.FileAccess]::ReadWrite, [IO.FileShare]::None) + $seen = @{} + $backupRoots = @((Join-Path $root 'Ruen-UI-Backups'), (Join-Path $root 'Brad-Setup-Backups')) + if ((Split-Path -Parent (Get-Item -LiteralPath $Backup).FullName) -notin $backupRoots) { throw 'Use an original backup inside this game install.' } + foreach ($entry in @($receipt.entries)) { + $relative = [string]$entry.path + if ($seen.ContainsKey($relative)) { throw 'Duplicate backup target.' }; $seen[$relative] = $true + if ($relative -notmatch '^(Interface/AddOns/((?:RuenUI|BradStockUI)(?:/LanguageDefaults\.lua)?|GunSilencerForever|Leatrix_Plus|Leatrix_Maps|Spoken|Spoken_Quests|SpokenQuestsAudioAlliance|SpokenQuestsAudioShared|SpokenQuestsAudio_ruRU|VoiceQuest)|WTF/Config\.wtf|WTF/Account/[^/]+/(config-cache\.wtf|bindings-cache\.wtf|AddOns\.txt|edit-mode-cache-account\.txt|SavedVariables/(GunSilencerForever|Leatrix_Plus|Leatrix_Maps|VoiceQuest|RuenUI|BradStockUI|Spoken|Spoken_Quests)\.lua(?:\.bak)?)|WTF/Account/[^/]+/[^/]+/[^/]+/(AddOns\.txt|config-cache\.wtf|bindings-cache\.wtf|edit-mode-cache-character\.txt|SavedVariables/(VoiceQuest|RuenUI|BradStockUI)\.lua(?:\.bak)?))$') { + throw "Unexpected backup target: $relative" + } + $target = Safe-RelativePath $root $relative + $old = Safe-RelativePath (Join-Path $Backup 'original') $relative + if ($entry.existed -and -not (Test-Path -LiteralPath $old)) { throw "Backup missing: $relative" } + Assert-NoNestedLinks $target + Assert-NoNestedLinks $old + } + $restoreArchive = Join-Path $Backup ('before-restore-' + [guid]::NewGuid().ToString('N')) + New-Item -ItemType Directory -Path $restoreArchive | Out-Null + foreach ($entry in @($receipt.entries)) { + $relative = [string]$entry.path + $target = Safe-RelativePath $root $relative + $old = Safe-RelativePath (Join-Path $Backup 'original') $relative + if (Test-Path -LiteralPath $target) { + $retained = Safe-RelativePath $restoreArchive $relative + New-Item -ItemType Directory -Path (Split-Path -Parent $retained) -Force | Out-Null + Move-Item -LiteralPath $target -Destination $retained + } + if ($entry.existed) { + New-Item -ItemType Directory -Path (Split-Path -Parent $target) -Force | Out-Null + Copy-Item -LiteralPath $old -Destination $target -Recurse + } + } + Write-Host "Restored the pre-install files. Later files were retained in: $restoreArchive" -ForegroundColor Green +} +function Add-BackupOnly([string]$Relative) { + $plan.Add([pscustomobject]@{path = $Relative; source = $null; text = $null; backupOnly = $true}) +} +function Matches-Source([string]$Source, [string]$Target) { + if (-not (Test-Path -LiteralPath $Target)) { return $false } + if (Test-Path -LiteralPath $Source -PathType Leaf) { + if (-not (Test-Path -LiteralPath $Target -PathType Leaf)) { return $false } + return (Get-FileHash -LiteralPath $Source -Algorithm SHA256).Hash -eq (Get-FileHash -LiteralPath $Target -Algorithm SHA256).Hash + } + if (-not (Test-Path -LiteralPath $Target -PathType Container)) { return $false } + $files = @(Get-ChildItem -LiteralPath $Source -File -Recurse -Force) + if ($files.Count -ne @(Get-ChildItem -LiteralPath $Target -File -Recurse -Force).Count) { return $false } + foreach ($file in $files) { + $relative = $file.FullName.Substring($Source.Length).TrimStart([char[]]'\/') + if (-not (Matches-Source $file.FullName (Join-Path $Target $relative))) { return $false } + } + return $true +} + +try { + Assert-GameClosed + if ($Restore) { + if (-not $BackupPath) { throw 'Supply -BackupPath with the backup folder printed by the installer.' } + Restore-Receipt $BackupPath + exit 0 + } + Verify-Package + . (Join-Path $bundle 'Tools/Migrate-RuenUI.ps1') + . (Join-Path $bundle 'Tools/Resolve-RuenDependencies.ps1') + $gameRoot = Find-Forever + Assert-NoLinks $gameRoot + $lockPath = Join-Path $gameRoot '.ruen-install.lock' + Assert-NoLinks $lockPath + $gameLock = [IO.File]::Open($lockPath, [IO.FileMode]::OpenOrCreate, [IO.FileAccess]::ReadWrite, [IO.FileShare]::None) + Write-Host "Configuring: $gameRoot" + if ($LanguageOnly -and $Language -eq 'auto') { throw 'Use -Language en or -Language ru with -LanguageOnly.' } + if ($LanguageOnly -and -not (Test-Path -LiteralPath (Join-Path $gameRoot 'Interface/AddOns/RuenUI/Controls.lua'))) { throw 'Install the Ruen UI package before switching its language.' } + if ($Language -ne 'auto') { Prepare-Languages $gameRoot } + + $plan = New-Object 'System.Collections.Generic.List[object]' + if ($Language -eq 'auto') { Add-BackupOnly 'WTF/Config.wtf' } + else { + $locale = if ($Language -eq 'ru') { 'ruRU' } else { 'enUS' } + $plan.Add([pscustomobject]@{path = 'WTF/Config.wtf'; source = $null; text = (Language-Config $gameRoot $locale)}) + } + if (-not $LanguageOnly) { + if (-not $CachePath) { $CachePath = Join-Path $env:LOCALAPPDATA 'RuenUI/Downloads' } + Assert-NoLinks $CachePath + [void][IO.Directory]::CreateDirectory($CachePath) + $cacheLockPath = Join-Path $CachePath '.install.lock' + Assert-NoLinks $cacheLockPath + $cacheLock = [IO.File]::Open($cacheLockPath, [IO.FileMode]::OpenOrCreate, [IO.FileAccess]::ReadWrite, [IO.FileShare]::None) + $stage = Join-Path $CachePath ('stage-' + [guid]::NewGuid().ToString('N')) + [void][IO.Directory]::CreateDirectory($stage) + Write-Host 'Ruen beta installs an ESDF layout and keybindings on each character. /ruen restore undoes its in-game preferences.' + Write-Host 'Companion addons are fetched directly from their authors. Existing compatible addons and saved preferences are retained.' + Write-Host 'Gun audio uses a suppressed recording at 100%; nearby stock gunfire is muted. /ruen guns off restores native sound.' + $payload = Prepare-RuenDependencies $bundle $gameRoot $stage $VoicePacks $CachePath + $stagedRuen = Join-Path $stage 'RuenUI' + Copy-Item -LiteralPath $payload.Sources['RuenUI'] -Destination $stagedRuen -Recurse + foreach ($name in @('HardwareProfile.lua', 'LanguageDefaults.lua')) { + $existing = Join-Path $gameRoot ('Interface/AddOns/RuenUI/' + $name) + Assert-NoLinks $existing + if (Test-Path -LiteralPath $existing -PathType Leaf) { Copy-Item -LiteralPath $existing -Destination (Join-Path $stagedRuen $name) -Force } + } + $payload.Sources['RuenUI'] = $stagedRuen + $addonNames = @($payload.Enabled) + Assert-GameClosed + foreach ($addon in @($payload.Sources.Keys | Sort-Object)) { + $plan.Add([pscustomobject]@{path = 'Interface/AddOns/' + $addon; source = $payload.Sources[$addon]; text = $null}) + } + $accountRoot = Join-Path $gameRoot 'WTF/Account' + $accounts = @() + if (Test-Path -LiteralPath $accountRoot) { + Assert-NoLinks $accountRoot + $accounts = @(Get-ChildItem -LiteralPath $accountRoot -Directory | Where-Object { $_.Name -ne 'SavedVariables' }) + } + foreach ($account in $accounts) { + Assert-NoLinks $account.FullName + foreach ($relative in @('config-cache.wtf', 'bindings-cache.wtf', 'edit-mode-cache-account.txt', 'SavedVariables/RuenUI.lua', 'SavedVariables/GunSilencerForever.lua', 'SavedVariables/Leatrix_Plus.lua', 'SavedVariables/Leatrix_Maps.lua', 'SavedVariables/Spoken.lua', 'SavedVariables/Spoken_Quests.lua')) { + Add-BackupOnly ('WTF/Account/' + $account.Name + '/' + $relative) + } + $accountAddons = Join-Path $account.FullName 'AddOns.txt' + if (Test-Path -LiteralPath $accountAddons -PathType Leaf) { + $lines = @(Get-Content -LiteralPath $accountAddons | Where-Object { (($_ -split ':', 2)[0].Trim()) -notin @($addonNames + 'BradStockUI') }) + $lines += @($addonNames | ForEach-Object { $_ + ': enabled' }) + $plan.Add([pscustomobject]@{path = 'WTF/Account/' + $account.Name + '/AddOns.txt'; source = $null; text = ($lines -join "`r`n") + "`r`n"}) + } + # First-login Ruen preferences merge in-game and retain originals for /ruen restore. + # Never replace an existing companion addon's entire SavedVariables file. + foreach ($realm in @(Get-ChildItem -LiteralPath $account.FullName -Directory | Where-Object { $_.Name -ne 'SavedVariables' })) { + Assert-NoLinks $realm.FullName + foreach ($character in @(Get-ChildItem -LiteralPath $realm.FullName -Directory | Where-Object { $_.Name -ne 'SavedVariables' })) { + Assert-NoLinks $character.FullName + $base = 'WTF/Account/' + $account.Name + '/' + $realm.Name + '/' + $character.Name + foreach ($relative in @('config-cache.wtf', 'bindings-cache.wtf', 'edit-mode-cache-character.txt', 'SavedVariables/RuenUI.lua')) { + Add-BackupOnly ($base + '/' + $relative) + } + $addonFile = Join-Path $character.FullName 'AddOns.txt' + $lines = @() + if (Test-Path -LiteralPath $addonFile) { $lines = @(Get-Content -LiteralPath $addonFile) } + $lines = @($lines | Where-Object { (($_ -split ':', 2)[0].Trim()) -notin @($addonNames + 'BradStockUI') }) + $lines += @($addonNames | ForEach-Object { $_ + ': enabled' }) + $plan.Add([pscustomobject]@{path = $base + '/AddOns.txt'; source = $null; text = ($lines -join "`r`n") + "`r`n"}) + } + } + } + Add-RuenMigration $gameRoot $plan + } # Full package installation + if ($LanguageOnly) { + $accountRoot = Join-Path $gameRoot 'WTF/Account' + if (Test-Path -LiteralPath $accountRoot) { + Assert-NoLinks $accountRoot + foreach ($account in @(Get-ChildItem -LiteralPath $accountRoot -Directory | Where-Object { $_.Name -ne 'SavedVariables' })) { + foreach ($addon in @('RuenUI', 'Spoken')) { + Add-BackupOnly ('WTF/Account/' + $account.Name + '/SavedVariables/' + $addon + '.lua') + } + } + } + } + if ($Language -ne 'auto') { + $request = [guid]::NewGuid().ToString('N') + $defaults = "local _, P = ...`nP.installLanguage = `"$locale`"`nP.installLanguageRequest = `"$request`"`n" + if ($LanguageOnly) { + $plan.Add([pscustomobject]@{path = 'Interface/AddOns/RuenUI/LanguageDefaults.lua'; source = $null; text = $defaults}) + } else { + $ruenItem = $plan | Where-Object { $_.path -eq 'Interface/AddOns/RuenUI' } | Select-Object -First 1 + $ruenItem | Add-Member -NotePropertyName languageDefaults -NotePropertyValue $defaults + } + } + # Validate every destination before making any changes. + $needsChange = $false + foreach ($item in $plan) { + $target = Safe-RelativePath $gameRoot $item.path + Assert-NoNestedLinks $target + if ($item.PSObject.Properties['backupOnly']) { continue } + if ($item.PSObject.Properties['languageDefaults']) { $needsChange = $true } + if ($item.PSObject.Properties['removeOnly']) { + if (Test-Path -LiteralPath $target) { $needsChange = $true } + continue + } + if ($null -ne $item.text) { + if (-not (Test-Path -LiteralPath $target -PathType Leaf) -or [IO.File]::ReadAllText($target) -ne $item.text) { $needsChange = $true } + } elseif (-not (Matches-Source $item.source $target)) { $needsChange = $true } + } + if (-not $needsChange) { + Write-Host 'This exact package and its preferences are already installed. No files or backups added.' -ForegroundColor Green + exit 0 + } + [long]$required = 134217728 + foreach ($item in $plan) { + $target = Safe-RelativePath $gameRoot $item.path + foreach ($path in @($target, $item.source)) { + if ($path -and (Test-Path -LiteralPath $path)) { + if (Test-Path -LiteralPath $path -PathType Leaf) { $required += (Get-Item -LiteralPath $path).Length } + else { foreach ($file in @(Get-ChildItem -LiteralPath $path -File -Recurse)) { $required += $file.Length } } + } + } + } + Assert-RuenSpace $gameRoot $required + $stamp = (Get-Date -Format 'yyyyMMdd-HHmmss') + '-' + [guid]::NewGuid().ToString('N').Substring(0, 8) + $backup = Join-Path $gameRoot ('Ruen-UI-Backups/' + $stamp) + Assert-NoLinks $backup + New-Item -ItemType Directory -Path $backup -Force | Out-Null + $entries = New-Object 'System.Collections.Generic.List[object]' + $changed = New-Object 'System.Collections.Generic.List[object]' + foreach ($item in $plan) { + $target = Safe-RelativePath $gameRoot $item.path + $existed = Test-Path -LiteralPath $target + $entries.Add([pscustomobject]@{path = $item.path; existed = [bool]$existed}) + if ($existed) { + $old = Safe-RelativePath (Join-Path $backup 'original') $item.path + New-Item -ItemType Directory -Path (Split-Path -Parent $old) -Force | Out-Null + Copy-Item -LiteralPath $target -Destination $old -Recurse + } + } + $receipt = [ordered]@{format = 1; gameRoot = $gameRoot; created = (Get-Date).ToString('o'); status = 'prepared'; entries = @($entries.ToArray())} + Write-Utf8 (Join-Path $backup 'receipt.json') ($receipt | ConvertTo-Json -Depth 8) + try { + foreach ($item in $plan) { + if ($item.PSObject.Properties['backupOnly']) { continue } + Assert-GameClosed + $target = Safe-RelativePath $gameRoot $item.path + $entry = $entries | Where-Object { $_.path -eq $item.path } | Select-Object -First 1 + $changed.Add($entry) + New-Item -ItemType Directory -Path (Split-Path -Parent $target) -Force | Out-Null + if (Test-Path -LiteralPath $target) { Remove-Item -LiteralPath $target -Recurse -Force } + if ($item.PSObject.Properties['removeOnly']) { continue } + if ($null -ne $item.text) { Write-Utf8 $target $item.text } + else { Copy-Item -LiteralPath $item.source -Destination $target -Recurse } + if ($item.PSObject.Properties['languageDefaults']) { Write-Utf8 (Join-Path $target 'LanguageDefaults.lua') $item.languageDefaults } + } + $receipt.status = 'installed' + Write-Utf8 (Join-Path $backup 'receipt.json') ($receipt | ConvertTo-Json -Depth 8) + } catch { + $installError = $_ + foreach ($entry in @($changed.ToArray())) { + $target = Safe-RelativePath $gameRoot $entry.path + if (Test-Path -LiteralPath $target) { Remove-Item -LiteralPath $target -Recurse -Force } + if ($entry.existed) { + Copy-Item -LiteralPath (Join-Path (Join-Path $backup 'original') $entry.path) -Destination $target -Recurse + } + } + $receipt.status = 'rolled_back' + Write-Utf8 (Join-Path $backup 'receipt.json') ($receipt | ConvertTo-Json -Depth 8) + throw $installError + } + if ($LanguageOnly) { + Write-Host "Language request saved: $locale. Enter a character once so Ruen UI updates Battle.net; then fully exit and relaunch WoW if the text is still in the old language." -ForegroundColor Green + Write-Host "Backup: $backup" + exit 0 + } + # Remember this installation for the reusable optimizer; each PC measures itself. + if ($env:LOCALAPPDATA) { + $localConfig = Join-Path $env:LOCALAPPDATA 'Ruen-UI' + New-Item -ItemType Directory -Path $localConfig -Force | Out-Null + Write-Utf8 (Join-Path $localConfig 'install.json') (@{gameRoot=$gameRoot} | ConvertTo-Json) + } + Write-Host 'For sustained optimization: launch WoW, then run Ruen-Setup.exe --optimize. Play normally; /reload imports the result.' + Write-Host 'Installed: Ruen UI stock UI/graphics profile, Leatrix Plus, Leatrix Maps, Spoken with selected voice packs, Gun Silencer Forever.' -ForegroundColor Green + Write-Host 'Launch WoW: Forever and enter a character. Settings apply automatically.' + Write-Host 'A fresh account may request one /reload. Future changes are retained.' + Write-Host 'Quest narration uses the voice packs you selected. /ruen language en or ru changes text/audio/narration (restart); /ruen voice en or ru changes narration immediately.' + if ($Language -ne 'auto') { Write-Host "Language request: $locale. After download, enter a character once; Ruen UI updates the launcher. Fully exit/relaunch if text is still in the old language." } + Write-Host "Backup: $backup" + Write-Host 'To undo: run this script with -Restore -BackupPath followed by that folder in quotes.' +} catch { + Write-Host ("Setup stopped: " + $_.Exception.Message) -ForegroundColor Red + if ($_.Exception -is [UnauthorizedAccessException] -or $_.Exception.Message -match 'access.+denied|permission denied') { + Write-Host 'Run Install-Ruen-UI.cmd as administrator for this installation, or use a game folder you can write to.' + } + exit 1 +} + +finally { + if ($stage -and (Test-Path -LiteralPath $stage)) { Remove-Item -LiteralPath $stage -Recurse -Force } + if ($cacheLock) { $cacheLock.Dispose() } + if ($gameLock) { $gameLock.Dispose() } +} diff --git a/Install-Russian.cmd b/Install-Russian.cmd new file mode 100644 index 0000000..ab69560 --- /dev/null +++ b/Install-Russian.cmd @@ -0,0 +1,3 @@ +@echo off +call "%~dp0Install-Ruen-UI-Russian.cmd" %* +exit /b %errorlevel% diff --git a/Install-Windows.cmd b/Install-Windows.cmd new file mode 100644 index 0000000..15179fc --- /dev/null +++ b/Install-Windows.cmd @@ -0,0 +1,3 @@ +@echo off +call "%~dp0Install-Ruen-UI.cmd" %* +exit /b %errorlevel% diff --git a/KEYBINDINGS.txt b/KEYBINDINGS.txt new file mode 100644 index 0000000..4a4af9e --- /dev/null +++ b/KEYBINDINGS.txt @@ -0,0 +1,176 @@ +Ruen UI - ESDF key map (2026.11.21.5-beta.1) + +MOVEMENT + Q W [E] R T + A [S] [D] [F] G H + Z X C V B + +E = forward; D = backward; S/F = strafe left/right. +Grave/tilde key (` without Shift) = autorun, if previously unbound. +Turn with the right mouse button. Space AND middle mouse = jump. +Middle mouse and thumb targeting also work with Shift/Ctrl/Alt held. +ESDF also works while holding Shift, Ctrl, Alt or Ctrl+Shift. + +COMBAT ROWS (each row follows the same keyboard order) +Slot 1 2 3 4 | 5 6 7 | 8 9 10 11 12 +Key Q W R T | A G H | Z X C V B +Keyboard top row | home row | bottom row + +Bottom combat row = key alone +Middle combat row = Shift + key +Third combat row = Ctrl + key +Top combat row = Alt + key + +This is keyboard order, not a ranking from easiest to hardest. Put the most +frequent abilities on keys that feel easiest to YOUR hand. Reserve outer keys +or modifiers for less frequent actions. The same column uses the same key on +all four rows. Drag abilities to arrange them; their original positions +are preserved during setup. Ruen manages bar positions; duplicate its Edit Mode layout under another name for free placement. + +UTILITY BARS (48 slots; all still clickable) +Each bar uses 1 2 3 4 5 6 / 7 8 9 0 - = in two rows of six. +Right group: bottom bar = Ctrl + numbers; upper bar = Shift + numbers. +Left group: bottom bar = Alt + numbers; upper bar = Ctrl + Shift + numbers. +Plain 1–0 controls the ten native pet slots. - and = cast up to two learned +active pet abilities missing from those ten slots; they fill automatically. +Right-click an extra ability to toggle its autocast when supported. +Drag a learned pet ability/command onto either extra button while unlocked. +/ruen pet auto restores automatic overflow. Player spells/items are not pet actions. +Assignments persist per character, require the current pet to know the ability, +and update outside combat. +The left group is for less +frequent actions; nothing requires holding a three-modifier combination. +Existing slots are preserved. Drag food, hearthstone or abilities into any slot. +/ruen lock hides empty utility buttons and blocks ordinary dragging. +/ruen unlock shows all slots and permits dragging outside combat, including pets. +Native Shift-drag overrides the lock temporarily. + +TARGETING AND INTERACTION +Tab / front thumb Next enemy (Mouse Button 5) +Shift+Tab / rear thumb Previous enemy (Mouse Button 4) +F1-F5 Self/party targeting (existing bindings retained) +1..0 Pet controls (centered row, larger icons) +U Interact with target +Shift+U Assist target (select its target) +Ctrl+Shift+U Select your target's target's target, when present +Alt+U Ping listener + +PANELS AND OTHER CONTROLS +N World map (M deliberately unbound) +Shift+N Battlefield / zone map +I All bags +J Quest log +Alt+J Azeroth's Compendium (quest browser; press again to close) +Shift+J Adventure guide +Ctrl+J Achievements, if this game branch supports the menu +K Character +Shift+K Talents +Ctrl+K Reputation +Alt+K Currency +P Spellbook +Shift+P Professions +Ctrl+P Pet spellbook +L Looking for group +Shift+L Legacy progression +O Friends / social +Shift+O Guild +Ctrl+O Raid panel +Alt+O Who +Y Collections +Shift+Y Mounts +Ctrl+Y Toys +Alt+Y Appearances +F6 Enemy nameplates +Shift+F6 All nameplates +Ctrl+F6 Friendly nameplates +F8 Macros +F9 Settings +Shift+F9 Keybinding settings +F10 Housing dashboard, where supported/unlocked +F12 Ruen UI help and key map +Shift+F12 Blizzard support +Esc Game menu (existing binding retained) +Ctrl+I Sit / stand +Shift+I Sheathe / unsheathe +Enter Chat; /r replies + +The store deliberately has no shortcut. Menus absent from this game branch +are skipped and reported; level/account restrictions still apply normally. +I/J/K/L group inventory, journal, character and group finder. P is spellbook, +with profession/pet variants; O groups social panels. Shift/Ctrl combat rows, +ESDF is preserved. Alt is now the fourth combat row, not a forced-self-cast modifier. F1-F5 retains party targeting; plain 1..0 controls pets. + +BAG WINDOW +Combined inventory opens to the left of the right-side quest/utility column, +with its bottom above the utility and combat rows. Measured screen coordinates +adapt to resolution/UI scale. Oversized inventories shrink only as needed to +fit available space. Position changes defer until combat ends. /ruen bags +repositions an open bag; choosing another Edit Mode layout stops this helper. + +LANGUAGE AND HELP +/ruen help Complete command/key reference (also /ruen alone or F12) +/ruen language Show running/selected text, game audio, narration, and + both regional menu choices and full client language support. +/ruen language en Select English game text/audio and Spoken narration. +/ruen language ru Select Russian game text/audio and Spoken narration. +/ruen language toggle Switch English/Russian game text/audio and narration. +/ruen voice en English narration only; leave game text/audio unchanged. +/ruen voice ru Russian narration only; leave game text/audio unchanged. +/ruen bindings Reapply only the new mouse/menu controls. + +English/Russian full names and enUS/ruRU also work. Spoken and Spoken_Quests are +required dependencies. Narration changes the active Spoken profile immediately; +English remains the fallback for recordings missing in Russian. +Full game text/audio uses Blizzard's native settings and requires a COMPLETE +WoW exit/relaunch, not /reload. The command will not fake GetLocale, translate +chat, change realms or change preferred social/layer language. The native dropdown may be region-filtered; the command checks the full +client catalog. If the client rejects or does not support a language, it reports that game text/audio did not +change and explains the Battle.net language installation step. The installed +Spoken audio packs are separate from Blizzard's game language files. +To install game languages: Battle.net > WoW > gear > Game Settings / Modify +Install; add the desired text and spoken language and let downloads finish. +Battle.net launch-language settings may need to match the chosen game language. + +Default main-bar number bindings and manual page-switch shortcuts are removed +so buttons display the new keys. Conflicting old bindings are recorded for undo. +Pet and form/vehicle behavior is retained. Unspecified bindings stay as they are. +Alt+combat keys select the fourth row. Automatic self-cast is enabled; F1 selects yourself explicitly. Ctrl+Shift+F11 replaces Alt+Z for hiding the UI. + +UNDO / CUSTOMIZE +/ruen restore restores the recorded native setup and changed keys. Any key +manually reassigned since setup is retained. Copied click-bar shortcuts are +removed only when they still match the item placed by the helper. +/ruen apply opts back in. Options > Keybindings / Quick Keybind Mode adjusts +individual keys. The mouse/menu upgrade applies once per account binding set (or per character +when character-specific bindings are enabled). Later manual edits are retained. +/ruen bindings deliberately reapplies mouse/menu and utility mappings. +The Windows installer includes this mapping, without private account data. + +Windows: Install-Russian.cmd installs the selected Russian setup. Both native +languages must be downloaded through Battle.net. See docs/INSTALL.md for commands. + +TIMERS AND OPTIMIZATION +/ruen swing on|off|preview +/ruen optimize [world|raid|pause|resume|status|restore] +Hardware evaluation: Ruen-Setup.exe --optimize (Windows), ./Ruen-Setup --optimize (Linux). +See docs/INSTALL.md for the measured world/raid calibration workflow. + +CLASS ASSIST COMMANDS (no new keybindings) +/ruen cooldowns auto|show|hide|off|settings — native class cooldown/buff displays. +/ruen mouseover auto|on|off — per-character hover casting. +Auto mouseover: priest/druid/paladin/shaman ON; other classes OFF. +When enabled, hover a valid friendly or enemy unit/frame and use the spell key. +No added modifier; existing Shift/Ctrl/Alt rows and mouse buttons stay unchanged. + +Left utility layout: two compact bars, each with two rows of six at every screen +size. Alt+1–= remains the lower bar; Ctrl+Shift+1–= remains the upper bar. +All 24 slots and their shortcuts are retained; only arrangement changes. + +Pet extras (-/=): real pet actions; left-click/key activates, right-click toggles +autocast when supported. The addon uses two free slots on unused page 2 and +preserves all visible player slots. /ruen unlock to assign; /ruen pet auto to reset. + +Gun audio (no new hotkeys): +/ruen guns on | off | settings | status +/ruen guns 100 Default replacement volume; range 10–100 in steps of 10. +Nearby stock gunfire is muted while enabled; off restores native audio. diff --git a/LAYOUT-AUDIT.txt b/LAYOUT-AUDIT.txt new file mode 100644 index 0000000..418424e --- /dev/null +++ b/LAYOUT-AUDIT.txt @@ -0,0 +1,222 @@ +HISTORICAL DEVELOPMENT AUDIT (through 2026.11.21.2) +Current public release evaluation: docs/RELEASE-REVIEW.md +Earlier pending checks below describe their status at the time. + +RUEN UI LAYOUT AUDIT — 2026.11.21.2 +WoW: Forever / Camelot, interface 16001. Audited 20 November 2026. + +WHAT THIS AUDIT ESTABLISHES +Code review, pinned native UI source review, executable API/geometry regressions, +and inspection of the current hunter screen/saved diagnostics. This is not a +claim that all nine classes were played in every raid on both operating systems. +The Lua layout is shared by Windows and Linux. This release does not change the +installer executable, proprietary drivers, game renderer, or hardware settings. + +DISPLAY / CONTENT COVERAGE +Nine classes x eight environments x eight display/scale cases = 576 base cases. +A second 576-case matrix adds target/focus casts and aura rows, focus-target, +rogue/druid combo-point footprints, and a large battleground score widget. +Both matrices passed with zero modeled unintended intersections, offscreen +frames, undersized group frames, or wrong automatic meter visibility. +Both the portable and installed addon copies passed independently. + +Environments: solo, outdoor five-player party, five-player dungeon, 10/20/40 +player raid, 10/40 player battleground. Auto meters are only for dungeon/raid. +Displays: 1280x720; 1366x768; 1920x1080 at 1.0 and 1.40625 scale; +2560x1440 at 1.0 and 1.875; 3840x2160 at 1.5 and 2.8125. The enlarged-UI +configurations deliberately reduce usable space to about 1365x768 UI units. +Arbitrary ultrawide/aspect ratios, larger font mods, and every possible window +combination are not certified by these finite fixtures. + +CLASS REVIEW +Warrior: native stances, native main/off-hand swings, rage/target information. +Paladin: native aura/stance controls; class mouseover default enabled. +Hunter: aspects plus centered 12-button pet row, pet health, ranged/melee swings. +Rogue: native stealth/form paging and target-portrait combo-point display. +Priest: native form controls when learned; class mouseover default enabled. +Shaman: four totem slots plus summon/recall; visible controls centered; melee +and off-hand swings when supplied by the client. Totem controls are independent +of the optional cooldown viewer. Class mouseover default enabled. +Mage: normal action layout and native pet controls when a pet is available. +Warlock: native demon commands/health plus two assignable extra pet buttons. +Druid: native form paging and combo-point display; mouseover default enabled. +Talent/spec/learned-spell changes retain native selection and paging. Ruen does +not guess a rotation, assign spells to your existing action slots, or force a +healer's input scheme to change on each talent switch. Other classes default +mouseover off; /ruen mouseover on|off overrides the character's default. + +COMMON CONTROLS +96 distinct normal action bindings, four 12-button combat rows, two 6x2 bars on +each side. ESDF, its movement modifiers, mouse targeting/jump, map N, bags I, +quest/Compendium shortcuts and menus remain unchanged by this release. +Pet 1-0 remain ten native slots. -/= are secure buttons exposing up to two active +pet spells absent from those slots; manual pet-spell/command drops are supported. +They are additional secure buttons, not server-side pet slots. Native +reordering and form/pet/possession paging remain intact. F1-F5 and unspecified +native class shortcuts are retained, not reassigned. Personal bindings/action +assignments are preserved; explicit /ruen apply intentionally reapplies setup. +Use /ruen lock to hide empty utility slots and reduce clutter. Shift-drag remains +available; /ruen unlock shows all slots. See KEYBINDINGS.txt for the complete map. + +FIXES IN THIS RELEASE +- Party/raid placement searches for readable space; it no longer squeezes the + raid down to roughly half-size just to occupy a fixed patch above the bars. + Raid: five columns/eight rows at 40 players; local fit floor is 75% of its base. +- At short widths, chat/quest width and unit offsets adapt to avoid the central + actions, right utility block, native combo points, and pet/cast collisions. +- Focus uses a compact central slot above the primary unit frames. Target and + focus aura growth is set upward through detached native Edit Mode settings. + Third-target information clears the native target cast bar. +- On short screens, battleground score widgets use the top area immediately + left of the minimap, leaving readable space for the full raid. The widget + keeps 90% scale below 1366 UI units; larger viewports retain full scale. +- Overlays measure attached casts/auras/combo points, both extra pet buttons, + exposed boss/arena/encounter widgets, and entire action blocks including gaps. +- Completed graphics calibration sleeps until an environment/resolution event. + Empty extra pet buttons have no OnUpdate handler. Third-target UNIT_TARGET + events filter unrelated raid/nameplate units. No new combat-log parser. +- Unchanged frame anchors are not cleared/reapplied. Placement candidates are + deduplicated, and already-optimal positions finish early. Layout work remains + event driven, coalesced, and deferred outside combat for protected frames. +- The prior bag/spell tooltip anti-flicker behavior is retained. Native tooltip + reanchors are repaired synchronously using one cached owner/footprint. + +COOLDOWN VIEWER: WHAT IT DOES AND DOES NOT DO +The viewer is optional: a nearby reminder of selected eligible cooldowns/buffs, +not a second action bar and not a complete catalogue of all learned abilities. +The native client supplies its available/selected entries for the character. +Ruen does not filter spell schools and has no shaman/fire-only rule. +The ordinary action bars continue to show cooldowns with this viewer disabled. +Default essential/utility/buff icon sizes are 30/27/24 UI units, versus roughly +36-unit normal action icons; OS/UI scale and old native settings can affect what +was actually displayed before the profile loaded. + +/ruen cooldowns auto Combat-only display +/ruen cooldowns on Alias of auto (previously unrecognized) +/ruen cooldowns show Out-of-combat preview as well as combat +/ruen cooldowns off Disable the optional display +/ruen cooldowns settings Native editor; choose from the eligible spells +/ruen cooldowns status Named essential/utility/buff lists, counts and mode + +The pre-update saved hunter list contained two essential and two utility entries; +the shaman had four essential and one utility. Neither recorded spell names. +That establishes hunter support and differing selections, but does NOT establish +why the user saw only fire icons or why a particular combat session was blank. +A fire-only appearance may reflect the native selected list or the separate +shaman totem controls. The new named diagnostics and a live preview distinguish +those cases. auto is expected to be hidden outside combat; on now works. +No viewer preference is silently changed by this update. It is reasonable to +leave it off when the action bars provide sufficient information. + +DAMAGE METERS +The native meter auto mode requests display in party/raid instances only, not +outdoor groups or battlegrounds. show/off are explicit account-wide overrides. +Native availability/level restrictions still apply. If even the compact meter +cannot fit, it hides with a 'no free space' diagnostic and retries on layout +events. Native collection may remain enabled while its window is hidden; Ruen +adds no duplicate collection or per-frame meter layout loop. + +INTENTIONAL / NECESSARY OVERLAP POLICIES +No normal action/control overlap is accepted in the matrices above. These +fallbacks are explicit and reported by /ruen status: +1. When a primary tooltip plus equipment comparisons cannot fit together, the + comparison group may cover other bag contents; the hovered item stays clear. +2. A very large tooltip may use chat/social-notification space after fully clear + positions are exhausted. Action, unit, cast and inventory controls stay clear. +3. A crowded raid's loot/achievement notices may temporarily cover chat, then + optional duplicate cooldown/meter information. Health/cast/action controls, + social toasts and other interactive notices remain protected by that search. +4. A bag that cannot fit at readable scale may cover HUD information temporarily. + Action blocks, chat, social space, quest column, minimap and open native panels + are still obstacles. /ruen status lists the actual HUD intersections as well. +5. Native modal panels such as world map, quest dialogue and bank can cover the + world/HUD or side reserve bars while open. Their native secure panel manager + is not replaced. Native unit-frame art deliberately layers its own portrait, + combo points, target-of-target and borders; those internal layers are retained. + +If all placements fail, diagnostics report it; the addon does not silently hide +required loot decisions or pretend the layout is verified. Exceptionally large +custom tracker lists (stress tested up to 58 entries) can exhaust a small screen; +optional meter hiding/unplaced reports are then expected, not a clean-layout pass. +Manually placed layouts belong under a different Edit Mode layout name. Ruen +manages its own named layout, and preserves custom bindings until reapplied. + +VALIDATION AND LIMITS +Additional tests: 200 class/resolution/custom cooldown-list scenarios; 50 native +meter scenarios; action migrations/restore/combat guards; same-class alt and +manual mouseover preference retention; pet extras in both languages; 480 spell +and 480 bag refresh cycles per copy, including combat and comparison cards; +calibration headroom, sleep/wake, separate world/raid samples and exact undo. +Saturated cases explicitly check their reported fallback policy rather than +claiming every optional overlay can always be displayed without obstruction. +All 31 installed/portable Lua chunks compiled. Installer binaries were not +rebuilt because this release changes addon code and documentation only. + +A small synthetic LuaJIT geometry benchmark on this workstation measured about +0.009 ms for a free-position search and 0.017 ms for a crowded search (1500 calls +per case); the prior crowded search was about 0.021 ms. These are geometry-only +CPU timings, not an in-game FPS, thermal, memory-leak or latency guarantee. +There is no idle layout ticker. Swing updates run only while a swing is visible; +up to two populated pet extras and a visible third-target frame update at 5 Hz. +The optimizer samples every frame only during active calibration. + +Live reload/preview verification for this new release is pending. Full live +level-60, raid, battleground and Windows play-throughs were not performed. Native +boss/arena and encounter-specific panels retain native secure behavior; their +measured bounds are reserved when available, but every encounter's transitions +are not represented in the fixtures. Native/protected frames that appear or +change during combat may need the post-combat reflow; no combat-lockdown bypass +is used. Large optional viewers/windows and future client UI changes require +checking /ruen status rather than a promise of universal compatibility. + +TARGET/BAG AND PET FOLLOW-UP (2026.11.20.3) +Previous geometry mocks used ordinary numbers for aura rectangles. Live testing +confirmed secret target aura dimensions even outside combat. Geometry reads +now reject these before arithmetic and skip forbidden frames. A conservative +public 264-unit aura allowance is reserved above target/focus (below if the +native setting says so); no aura contents are read or inferred. Bags/tooltips +share this fix. Target/focus changes queue overlay placement, with combat +deferral. Huge inventories retain the previously reported HUD-overlap fallback. +The added regression covers 120 target/focus/bank cases at 720p through 4K +for hunter/warlock/shaman, bags plus tooltips, and all-nine-class cooldown +show/hide commands. The old geometry reader fails the restricted-value test. +Pet extras opt out of native parent sizing and accept learned pet spell/command +drops. Tests cover lock/combat guards, missing-pet cleanup, restored preferences, +secure macro content, and rejection of player spells/items. +Live confirmation: after reload, the user verified targeted bags and tooltips +stay clear, the twelve-button pet row is centered, and dropping a pet ability +on the extra buttons works. Other classes remain simulation-tested. + +PET COMBAT FOLLOW-UP (2026.11.20.4) +New regression passes opaque cooldown values through 1,200 combat refreshes, +including native duration rendering and compatibility forwarding. The previous +code fails the comparison case. Manual assignments, command/spell validation, +pet changes, lock/combat guards and parent sizing regression tests still pass. +Repeated Lua-error popup source is pending a live stack or post-reload check; +this reproduced pet-button defect is fixed, not hidden by suppressing errors. + +Damage meter taint follow-up (2026.11.20.5) +A subsequent live stack identified native damage-meter timer taint separately from +the pet cooldown defect. Removed direct native meter state writes and refresh +calls. A taint-tracking simulation executing the native visibility/timer methods +fails with the prior implementation and passes 1,000 combat starts with this fix. +Idle/no-room idempotency, PvE auto/PvP exclusion, manual modes, combat deferral and +Edit Mode handoff pass. The overlay regression suite also passes (including 50 +class/resolution meter/bag/tooltip/loot cases and restricted target aura cases). +The secure game VM still requires an in-game reload/combat confirmation. This is +not a claim that a Lua simulation reproduces every engine taint propagation rule. + +Pet activation correction (2026.11.21.2) +The .21.1 simulation assumed that pages 2 AND 3 were unused and that stored pet +actions had the cursor type "petaction". Live testing disproved both assumptions. +The corrected tests load Blizzard's actual MultiActionBar page map and model the +observed ("spell", 0, "pet") command payload separately from engine identity. +They exercise missing texture getters, the native secure click dispatcher, +spellbook lookup, cursor preservation, active/occupied page exclusion, ownership, +pet/rank changes, and opaque combat cooldown rendering. Rejected placement makes +one persisted attempt, with no fanout through 500 events or a simulated reload. +The local one-time recovery is restricted to the affected character, command and +slot range; other commands with identical GetActionInfo payloads are retained. +All checks are simulations except the explicitly recorded user confirmations. +The correction needs live reload/activation confirmation; successful simulations +do not establish execution inside the game's secure VM. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..390f055 --- /dev/null +++ b/LICENSE @@ -0,0 +1,25 @@ +MIT License + +Copyright (c) 2026 Ruen UI contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +This license covers first-party Ruen code and documentation only. Separately +downloaded companion addons, libraries, recordings, and Blizzard assets retain +their owners' licenses. See docs/DEPENDENCIES.md. diff --git a/Optimize-Ruen-UI.ps1 b/Optimize-Ruen-UI.ps1 new file mode 100644 index 0000000..2c18148 --- /dev/null +++ b/Optimize-Ruen-UI.ps1 @@ -0,0 +1,10 @@ +[CmdletBinding()] +param([string]$WoWPath,[ValidateRange(1,1800)][int]$Seconds=600,[ValidatePattern('^\d+$')][ValidateRange(20,240)][string]$FPS='60') +$ErrorActionPreference='Stop' +if (!$WoWPath) { + $receipt=Join-Path $env:LOCALAPPDATA 'Ruen-UI/install.json' + if(Test-Path -LiteralPath $receipt){$WoWPath=(Get-Content -Raw -LiteralPath $receipt|ConvertFrom-Json).gameRoot} +} +if (!$WoWPath) {$WoWPath=Read-Host 'Paste the WoW Forever folder (containing Wow.exe)'} +Write-Host "Requested graphics target: $FPS FPS. Thermal limits may lower it." +& (Join-Path $PSScriptRoot 'Tools/Measure-RuenHardware.ps1') -WoWPath $WoWPath -Seconds $Seconds -FPS $FPS diff --git a/README.md b/README.md new file mode 100644 index 0000000..e96fb89 --- /dev/null +++ b/README.md @@ -0,0 +1,45 @@ +# Ruen UI — public beta + +A compact, class-aware **WoW: Forever** interface with ESDF controls, English/Russian narration, native class and pet bars, and optional performance calibration. + +**[Download the beta](https://scm.bstein.dev/bstein/ruen-ui/releases)** · **[Windows installation](docs/INSTALL.md)** · **[Инструкция на русском](docs/INSTALL-RU.md)** · **[Release review](docs/RELEASE-REVIEW.md)** · **[Report a problem](https://scm.bstein.dev/bstein/ruen-ui/issues)** + +Choose **Ruen-UI-2026.11.21.5-beta.1.zip** under release assets, not Gitea's automatic source ZIP. No account is needed to download. The download is small; setup then retrieves the selected companion addons directly from their authors. + +## Windows quick start + +1. Install **WoW: Forever** through Battle.net and let its update finish. This package targets interface **16001**; it is not for Retail or other Classic branches. +2. Close WoW. Download the release ZIP and **extract the entire folder**. +3. Run **Ruen-Setup.exe** inside the extracted folder. It uses Windows PowerShell already on the PC. The executable is unsigned; its source is included in `Tools/Ruen-Setup.c`. The alternative entry point is `Install-Windows.cmd`. +4. Setup checks standard locations and the Windows registry. If it finds several installs, choose one. If it cannot find yours, paste the folder containing `_forever_`, or `_forever_` itself. Keep the console open while dependencies download. +5. Launch the game and enter a character. Allow one `/reload` if requested. Type `/ruen help` or press **F12** for controls. + +Ruen changes movement to **E forward, D backward, S/F strafe**. Turn using the right mouse button. **N** opens the map, **I** bags, **P** the spellbook, and **Alt+J** the Compendium. Read [KEYBINDINGS.txt](KEYBINDINGS.txt) before playing. `/ruen restore` restores recorded preferences and stops automatic setup. + +## What is included + +- Four central combat rows and four compact utility bars: **96 action buttons** with consistent modifier keys. +- Native forms, stances, totems, casting and pet controls. A centered pet row adds two configurable extra pet actions on **-** and **=** when spare native action slots are available. +- Layout rules for bags, tooltips, notifications, party/raid frames and native damage meters. Meters appear automatically in dungeons and raids; `/ruen meters off` disables them. +- Optional native cooldown displays and class defaults for mouseover casting. Cooldown coverage comes from the game; it is not an exhaustive tracker for every learned spell. +- Spoken quest narration with English or English + Russian recordings. Game text and spoken language files must be installed separately through Battle.net. +- Optional graphics calibration for world/raid play, with a configurable FPS target. Hardware reports are generated on the destination PC; no donor hardware profile is shipped. +- Gun Silencer Forever integration, default replacement volume **100**. Its softer shot is still a gunshot. **Nearby original gunfire is muted while enabled**; `/ruen guns off` restores native audio. + +The installer downloads Leatrix Plus, Leatrix Maps, Spoken, Gun Silencer Forever and your chosen narration packs from pinned upstream releases. Existing Forever-compatible copies and saved settings are retained. See [dependencies and licenses](docs/DEPENDENCIES.md). + +## Beta status + +Installer transaction tests, Lua regressions, source review and prior local gameplay checks inform this release. **A clean native Windows installation and every class/spec in live raids have not been verified.** Automated layout simulations are not a guarantee against every possible addon or window combination. See the [release review](docs/RELEASE-REVIEW.md) for the tested scope and remaining limitations. + +Ruen does not install graphics drivers, change GPU drivers, or install a background service. Its optimizer cannot guarantee temperatures or sustained FPS on every laptop. + +## Linux and development + +Linux requires Python 3.10+ and an existing working Wine/Proton Forever installation: + +```sh +python3 Ruen-Setup --wow '/path/to/World of Warcraft/_forever_' +``` + +Source is hosted here in Gitea. First-party code is MIT-licensed. Tests: `PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tests -v`. Set `RUEN_PWSH` to a PowerShell executable to include its installer fixtures. Build: `python3 scripts/build_release.py /path/to/output`. Companion archives and personal game data are never included in the release. diff --git a/Ruen-Setup b/Ruen-Setup new file mode 100755 index 0000000..40e25e5 --- /dev/null +++ b/Ruen-Setup @@ -0,0 +1,250 @@ +#!/usr/bin/env python3 +"""Install the Ruen public beta on Linux; run without sudo.""" +import argparse +import contextlib +import fcntl +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import shutil +import sys +import tempfile +import time +import uuid + +sys.dont_write_bytecode = True + +BUNDLE = Path(__file__).resolve().parent +sys.path.insert(0, str(BUNDLE / 'Tools')) +import ruen_dependencies as deps +import ruen_migrate as migration +CONFIG = Path.home() / '.config/ruen-ui/install.json' +SAVES = ('RuenUI', 'GunSilencerForever', 'Leatrix_Plus', 'Leatrix_Maps', 'Spoken', 'Spoken_Quests') + + +def no_links(path): + deps.no_links(path) + if path.is_dir(): + for child in path.rglob('*'): + if child.is_symlink(): raise ValueError('Linked content cannot be replaced: ' + str(child)) + + +def game_path(value): + root = Path(value).expanduser().absolute() + no_links(root) + if root.name != '_forever_': root = root / '_forever_' + if not (root / 'Wow.exe').is_file(): raise ValueError('Choose the Forever folder containing Wow.exe.') + return root + + +def closed(root): + for path in Path('/proc').glob('[0-9]*/cmdline'): + try: + args = path.read_bytes().decode(errors='replace').split('\0')[:2] + if any(x.replace('\\', '/').rsplit('/', 1)[-1].lower() in {'wow.exe', 'wowclassic.exe', 'wow-64.exe'} for x in args): + raise RuntimeError('Close WoW before installing or restoring. Hardware evaluation can run while playing.') + except OSError: pass + + +@contextlib.contextmanager +def locked(path): + deps.no_links(path) + with path.open('a') as lock: + try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: raise RuntimeError('Another Ruen installer is using this folder: ' + str(path.parent)) + yield + + +def verify(bundle): + manifest = json.loads((bundle / 'manifest.json').read_text()) + if manifest.get('format') != 1: raise ValueError('Unsupported package manifest') + expected = set() + for entry in manifest['files']: + rel = deps.safe_relative(entry['path']); path = bundle / rel; deps.no_links(path) + if rel.as_posix() in expected: raise ValueError('Duplicate package entry') + expected.add(rel.as_posix()) + if not path.is_file() or deps.digest(path) != entry['sha256']: + raise ValueError('Package integrity check failed: ' + str(rel)) + actual = {p.relative_to(bundle).as_posix() for p in bundle.rglob('*') if p.is_file() and p != bundle / 'manifest.json'} + if actual != expected: raise ValueError('Package file list differs from its manifest; extract a fresh ZIP.') + if not deps.compatible(bundle / 'RuenUI'): raise ValueError('Ruen is not marked compatible with Forever.') + + +def copy(src, dst): + dst.parent.mkdir(parents=True, exist_ok=True) + if src.is_dir(): shutil.copytree(src, dst) + else: shutil.copy2(src, dst) + + +def remove(path): + if path.is_dir(): shutil.rmtree(path) + elif path.exists(): path.unlink() + + +def save_paths(root): + yield 'WTF/Config.wtf' + accounts = root / 'WTF/Account' + if not accounts.exists(): return + for account in accounts.iterdir(): + if not account.is_dir() or account.name == 'SavedVariables': continue + for name in ['config-cache.wtf', 'bindings-cache.wtf', 'edit-mode-cache-account.txt']: + yield (account / name).relative_to(root).as_posix() + for addon in SAVES: + yield (account / 'SavedVariables' / (addon + '.lua')).relative_to(root).as_posix() + for realm in account.iterdir(): + if not realm.is_dir() or realm.name == 'SavedVariables': continue + for character in realm.iterdir(): + if not character.is_dir() or character.name == 'SavedVariables': continue + for rel in ['config-cache.wtf', 'bindings-cache.wtf', 'edit-mode-cache-character.txt', 'SavedVariables/RuenUI.lua']: + yield (character / rel).relative_to(root).as_posix() + + +def allowed_restore(rel, managed): + path = deps.safe_relative(rel) + if path.parts[:2] == ('Interface', 'AddOns'): + return len(path.parts) == 3 and path.name in managed + if rel == 'WTF/Config.wtf': return True + if path.parts[:2] != ('WTF', 'Account'): return False + if len(path.parts) in (4, 6) and path.name in {'AddOns.txt', 'config-cache.wtf', 'bindings-cache.wtf', 'edit-mode-cache-account.txt', 'edit-mode-cache-character.txt'}: return True + return len(path.parts) in (5, 7) and path.parts[-2] == 'SavedVariables' and path.name in {x + suffix for x in (*SAVES, migration.LEGACY_ADDON) for suffix in ('.lua', '.lua.bak')} + + +def restore(root, backup): + backup = backup.absolute(); no_links(backup) + receipt = json.loads((backup / 'receipt.json').read_text()) + if receipt.get('format') != 2 or receipt['gameRoot'] != str(root) or backup.parent != root / 'Ruen-UI-Backups': + raise ValueError('Use a public-beta backup belonging to this installation.') + known = {'RuenUI', migration.LEGACY_ADDON} + for p in deps.selected(BUNDLE, 'enru'): known.update(p['folders']) + managed = set(receipt['managed']) + if not managed <= known: raise ValueError('Unknown addon in backup receipt') + seen = set() + for entry in receipt['entries']: + rel = entry['path'] + if rel in seen or not allowed_restore(rel, managed): raise ValueError('Unsafe backup target: ' + rel) + seen.add(rel); no_links(root / rel); no_links(backup / 'original' / rel) + if entry['existed'] and not (backup / 'original' / rel).exists(): raise ValueError('Incomplete backup: ' + rel) + retained = backup / ('before-restore-' + uuid.uuid4().hex) + for entry in receipt['entries']: + closed(root); rel = entry['path']; target = root / rel + if target.exists(): + dest = retained / rel; dest.parent.mkdir(parents=True, exist_ok=True); shutil.move(str(target), dest) + if entry['existed']: copy(backup / 'original' / rel, target) + print('Pre-install files restored; later files retained in:', retained) + + +def install(root, args): + cache = Path(args.cache).expanduser().absolute(); deps.no_links(cache); cache.mkdir(parents=True, exist_ok=True) + with locked(cache / '.install.lock'), tempfile.TemporaryDirectory(prefix='stage-', dir=cache) as temporary: + print('Ruen beta applies ESDF controls and a native-frame layout. /ruen restore undoes its preferences.', flush=True) + sources, enabled = deps.prepare(BUNDLE, root, Path(temporary), args.voice_packs, cache) + closed(root) + # Keep machine-specific reports and a previously requested language on upgrades. + staged_ruen = Path(temporary) / 'RuenUI' + copy(sources['RuenUI'], staged_ruen) + for name in ('HardwareProfile.lua', 'LanguageDefaults.lua'): + old = root / 'Interface/AddOns/RuenUI' / name + if old.is_file(): shutil.copy2(old, staged_ruen / name) + sources['RuenUI'] = staged_ruen + entries = {rel: {'path': rel, 'backupOnly': True} for rel in save_paths(root)} + for name, source in sources.items(): entries['Interface/AddOns/' + name] = {'path': 'Interface/AddOns/' + name, 'source': str(source)} + accounts = root / 'WTF/Account' + enable_files = list(accounts.rglob('AddOns.txt')) if accounts.exists() else [] + # Fresh characters use WoW's default-enabled behavior for newly installed addons. + for path in enable_files: + no_links(path) + kept = [line for line in path.read_text().splitlines() if line.split(':', 1)[0].strip() not in (*enabled, migration.LEGACY_ADDON)] + rel = path.relative_to(root).as_posix() + entries[rel] = {'path': rel, 'text': '\n'.join(kept + [n + ': enabled' for n in enabled]) + '\n'} + for rel, text in migration.plan(root, include_addons=False): entries[rel] = {'path': rel, 'text': text} + legacy = 'Interface/AddOns/' + migration.LEGACY_ADDON + if (root / legacy).exists(): entries[legacy] = {'path': legacy, 'text': None} + for entry in entries.values(): no_links(root / entry['path']) + changes = [e for e in entries.values() if not e.get('backupOnly')] + def matches(e): + target = root / e['path'] + if 'source' in e: + source = Path(e['source']) + if not target.is_dir(): return False + a = {p.relative_to(source): deps.digest(p) for p in source.rglob('*') if p.is_file()} + b = {p.relative_to(target): deps.digest(p) for p in target.rglob('*') if p.is_file()} + return a == b + if e['text'] is None: return not target.exists() + return target.is_file() and target.read_text() == e['text'] + if args.language == 'auto' and all(matches(e) for e in changes): + print('This package is already installed. No files or backups added.'); return + needed = sum(p.stat().st_size for e in entries.values() for p in + ([root / e['path']] if (root / e['path']).is_file() else (root / e['path']).rglob('*')) if p.is_file()) + needed += sum(p.stat().st_size for source in sources.values() for p in source.rglob('*') if p.is_file()) + if shutil.disk_usage(root).free < needed + 128 * 1024**2: + raise OSError('Not enough game-drive space for installation and rollback backup.') + backup = root / 'Ruen-UI-Backups' / (time.strftime('%Y%m%d-%H%M%S') + '-' + uuid.uuid4().hex[:8]) + deps.no_links(backup); backup.mkdir(parents=True) + receipt = {'format': 2, 'gameRoot': str(root), 'managed': list(sources), 'status': 'prepared', 'entries': []} + for entry in entries.values(): + target = root / entry['path']; entry['existed'] = target.exists() + receipt['entries'].append({'path': entry['path'], 'existed': entry['existed']}) + if target.exists(): copy(target, backup / 'original' / entry['path']) + receipt_path = backup / 'receipt.json'; receipt_path.write_text(json.dumps(receipt, indent=2)) + changed = [] + try: + for entry in entries.values(): + if entry.get('backupOnly'): continue + closed(root); target = root / entry['path']; changed.append(entry); remove(target) + if 'source' in entry: copy(Path(entry['source']), target) + elif entry['text'] is not None: + target.parent.mkdir(parents=True, exist_ok=True); target.write_text(entry['text'], encoding='utf-8') + if args.language != 'auto': + locale = 'ruRU' if args.language == 'ru' else 'enUS' + (root / 'Interface/AddOns/RuenUI/LanguageDefaults.lua').write_text('local _, P = ...\nP.installLanguage = "' + locale + '"\nP.installLanguageRequest = "public-' + uuid.uuid4().hex + '"\n') + receipt['status'] = 'installed'; receipt_path.write_text(json.dumps(receipt, indent=2)) + except Exception: + for entry in reversed(changed): + target = root / entry['path']; remove(target) + if entry['existed']: copy(backup / 'original' / entry['path'], target) + receipt['status'] = 'rolled_back'; receipt_path.write_text(json.dumps(receipt, indent=2)); raise + try: + CONFIG.parent.mkdir(parents=True, exist_ok=True); CONFIG.write_text(json.dumps({'gameRoot': str(root)})) + except OSError as error: print('Installed, but could not remember the game path:', error) + print('Ruen installed. Backup:', backup) + print('Launch WoW. /ruen help shows controls; /ruen guns off restores nearby gunfire.') + print('For English/Russian game text and speech, install both languages through Battle.net.') + + +def main(): + spec = importlib.util.spec_from_file_location('hardware', BUNDLE / 'Tools/ruen_hardware.py') + hardware = importlib.util.module_from_spec(spec); spec.loader.exec_module(hardware) + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--wow'); parser.add_argument('--voice-packs', choices=('none', 'en', 'enru'), default='en') + parser.add_argument('--cache', default=str(Path.home() / '.cache/ruen-ui/downloads')) + parser.add_argument('--language', choices=('auto', 'en', 'ru'), default='auto') + parser.add_argument('--restore', type=Path); parser.add_argument('--non-interactive', action='store_true') + parser.add_argument('--optimize', nargs='?', const=60, type=hardware.fps_target, metavar='FPS') + parser.add_argument('--seconds', type=int, default=600); args = parser.parse_args() + value = args.wow + if not value and CONFIG.is_file(): value = json.loads(CONFIG.read_text())['gameRoot'] + if not value: + candidates = [] + for base, pattern in [(Path('/opt/games'), '*/*/compatdata/pfx/drive_c/Program Files*/World of Warcraft/_forever_/Wow.exe'), (Path.home() / '.wine', 'drive_c/Program Files*/World of Warcraft/_forever_/Wow.exe'), (Path.home() / '.local/share/Steam/steamapps/compatdata', '*/pfx/drive_c/Program Files*/World of Warcraft/_forever_/Wow.exe'), (Path.home() / 'Games', '**/_forever_/Wow.exe')]: + if base.exists(): candidates.extend(base.glob(pattern)) + found = list(dict.fromkeys(str(p.parent) for p in candidates)) + if len(found) == 1: value = found[0] + elif args.non_interactive: parser.error('Supply --wow; no unique Forever installation was found.') + else: value = input('Paste the Forever folder containing Wow.exe: ') + root = game_path(value) + if args.optimize is not None: + if not 1 <= args.seconds <= 1800: parser.error('--seconds must be 1–1800') + result = hardware.evaluate(args.seconds); hardware.write_report(root, result, True, args.optimize) + print(result['evidence']); print('Type /reload to import the hardware report.'); return + closed(root) + with locked(root / '.ruen-install.lock'): + if args.restore: restore(root, args.restore) + else: verify(BUNDLE); install(root, args) + + +if __name__ == '__main__': + try: main() + except Exception as error: + print('Setup stopped:', error, file=sys.stderr); sys.exit(1) diff --git a/Ruen-Setup.exe b/Ruen-Setup.exe new file mode 100755 index 0000000000000000000000000000000000000000..f21ac92a5bae12d256ae274dbc6841a9f2cd29c9 GIT binary patch literal 3072 zcmeHJTWl0%6h6Ccx%4(b*awi7X|C&gG&^tX112`#F4+(c~wqUft7e_&pqda7_%7mHagXdNItiM(8= zr8|jMv5v7U$qOz!riA)NmV@kAAd4i+f@5t9t8}T3XuGBTy_cSPqP{<&^cc#p0sjoQ zf(zn3EbkpE4-pg|Jt`YA(K*J!U}4rkt{7hQ$Ww&T83ORp70wkZaJd!B|JDC+2Yd$) zc6W71BlCPBr0nkbtwfD8l6k{7PN#_quEQIM%;{;ryT<_pjDdjWY$;4itnMo|ZD8>YEPsl+(m7 z7VGzj;_^iJ0S&u*anQniI-iB1;9|d;d6Lp6gzaT-flgvNVMlNs)~B%+cC3=dlTmHR zQ&o)>w#b;w*QxXv-~mIbs?o$hWF;2Y=e zSddOYM#H?_&CsNg4|DJwe(w1rz9UnkWwkXWe5xFLsDw8z?!9}8$S1r$=@UOkQwg2$ zonCUJpD=UbY$Y1}MQe7;0X1lrZVn1#{sYeD>>(@G5JHZNp^-bkBEH$Ys?Yizvu0Ut zO9`1dJQDkerY`-p(Up{s#ud@f#FQcHhS(kBW~Ib7ZAj5O29$W*Bevu99ZJFrYotG7)Tn5&S@fXEropi zp)h3SVr&C`8V!;`F-l+_Ck5fX)IrB61*-zoVISRA}|~?>@`-;C`OZ(NB|y=B^3t1!jL9>kp2#1 zYqJ(j$CY3#uC&Mr3(D3GBYH0xuk8oLAJdhHq3Or0ob8Gn + RuenUI_OpenMenu("macros"); + RuenUI_OpenMenu("settings"); + RuenUI_OpenMenu("keybindings"); + SlashCmdList.RUENUI("help"); + RuenUI_OpenMenu("support"); + diff --git a/RuenUI/Brand.lua b/RuenUI/Brand.lua new file mode 100644 index 0000000..c743753 --- /dev/null +++ b/RuenUI/Brand.lua @@ -0,0 +1,44 @@ +local _, P = ... + +-- Compatibility with layouts and narration profiles from older releases. +-- Addon IDs, saved variables and binding names are migrated by the installer. +P.legacyLayoutName = "Brad - Clear ESDF" +local function renameNarration(saved, database) + if not saved then return end + local old, new = "Brad Narration", "Ruen Narration" + local profiles = saved.profiles + if not profiles or not profiles[old] then return end + -- Never replace an independently created destination profile. + if profiles[new] and profiles[new] ~= profiles[old] then return end + profiles[new] = profiles[old] + if database and database.GetCurrentProfile and database:GetCurrentProfile() == old then + -- Use AceDB's own callbacks to refresh active references. + database:SetProfile(new) + end + for character, name in pairs(saved.profileKeys or {}) do + if name == old then saved.profileKeys[character] = new end + end + if saved.global and saved.global.NewCharacterProfile == old then + saved.global.NewCharacterProfile = new + end + profiles[old] = nil +end + +function P.MigrateBrand() + if InCombatLockdown() then return end + local manager = EditModeManagerFrame + if manager and not manager:IsShown() and not manager.overrideLayoutInfo then + local info = CopyTable(C_EditMode.GetLayouts()) + local old, collision + for _, layout in ipairs(info.layouts or {}) do + if layout.layoutName == P.legacyLayoutName then old = layout end + if layout.layoutName == P.layoutName then collision = true end + end + if old and not collision then + old.layoutName = P.layoutName + C_EditMode.SaveLayouts(info) + end + end + renameNarration(SpokenSettings, SpokenEnv and SpokenEnv.Addon and SpokenEnv.Addon.db) + renameNarration(SpokenQuestsSettings, VoiceOver and VoiceOver.Addon and VoiceOver.Addon.db) +end diff --git a/RuenUI/ClassAssist.lua b/RuenUI/ClassAssist.lua new file mode 100644 index 0000000..60779aa --- /dev/null +++ b/RuenUI/ClassAssist.lua @@ -0,0 +1,334 @@ +local _, P = ... + +-- Blizzard selects the learned spells, ranks, overrides and talent-specific +-- categories. Ruen only supplies presentation and a class-aware input default. +-- Do not write C_CooldownViewer layout data or replace its secure aura handlers. +local names = {"EssentialCooldownViewer", "UtilityCooldownViewer", "BuffIconCooldownViewer", "BuffBarCooldownViewer"} +local healers = {PRIEST=true, DRUID=true, PALADIN=true, SHAMAN=true} +local owns, place, edge, put, queue +local busy, queued, hooked = false, false, {} +local appliedContext +local diagnosticSignature, diagnosticSpells +P.classAssistReserved = {} + +local function settingsOpen() + return (EditModeManagerFrame and EditModeManagerFrame:IsShown()) + or (CooldownViewerSettings and CooldownViewerSettings:IsShown()) +end + +local function mode() + return RuenUIDB.cooldownsMode or "auto" +end + +local function set(system, key, value) + if key == nil then return end + system.settings = system.settings or {} + for _, entry in ipairs(system.settings) do + if entry.setting == key then entry.value = value; return end + end + system.settings[#system.settings+1] = {setting=key, value=value} +end + +local function counts() + local result, signature, groups = {}, {}, {} + for i, name in ipairs(names) do + local f = _G[name] + if not f or not f.GetCooldownIDs then return end + local ok, ids = pcall(f.GetCooldownIDs, f) + if not ok or type(ids) ~= "table" then return end -- data not loaded yet + groups[i] = ids + result[i] = #ids + signature[i] = table.concat(ids, ",") + end + return result, table.concat(signature, "/"), groups +end + +-- Query static spell metadata only after the native list changes, out of combat. +-- These are diagnostics, not an independent cooldown or combat-log tracker. +local function describeSpells(signature, groups) + local _,class=UnitClass("player") + local key=class..":"..(GetLocale and GetLocale() or "")..":"..signature + if diagnosticSignature==key then return diagnosticSpells end + local result,complete={},true + for i,ids in ipairs(groups) do + result[i]={} + for _,id in ipairs(ids) do + local info + if C_CooldownViewer.GetCooldownViewerCooldownInfo then + local ok,value=pcall(C_CooldownViewer.GetCooldownViewerCooldownInfo,id) + if ok then info=value end + end + local spellID=info and (info.overrideTooltipSpellID or info.overrideSpellID or info.spellID) + local spell + if spellID and C_Spell and C_Spell.GetSpellInfo then + local ok,value=pcall(C_Spell.GetSpellInfo,spellID) + if ok then spell=value end + end + local name=spell and spell.name + result[i][#result[i]+1]={cooldownID=id,spellID=spellID,name=name} + if not name then complete=false end + end + end + if complete then diagnosticSignature,diagnosticSpells=key,result end + return result +end + +function P.CooldownSummary() + local status=RuenUICharacter.classAssistStatus or {} + local lines={P.Localized("Native cooldown list (not every ability):", "Список клиента (не все способности):")} + if status.available==false then lines[#lines+1]=P.Localized("Unavailable: ","Недоступно: ")..tostring(status.reason) end + local labels={P.Localized("Essential","Основные"), P.Localized("Utility","Вспомогательные"), + P.Localized("Buff icons","Эффекты"), P.Localized("Buff durations","Длительность эффектов")} + for i,label in ipairs(labels) do + local spells={} + for _,entry in ipairs((status.spells or {})[i] or {}) do + spells[#spells+1]=entry.name or ("ID "..tostring(entry.spellID or entry.cooldownID)) + end + lines[#lines+1]=label.." ("..tostring((status.counts or {})[i] or 0).."): "..table.concat(spells,", ") + end + lines[#lines+1]=P.Localized("auto/on: combat only; show: preview outside combat; hide/off: hidden; settings: choose from the client's eligible spells.", + "auto/on: только в бою; show: показ вне боя; hide/off: скрыть; settings: выбор из доступных клиенту способностей.") + return table.concat(lines,"\n") +end + +function P.ConfigureClassAssistSystems(layout, itemCounts) + local E, S, V = Enum.EditModeSystem, Enum.EditModeCooldownViewerSetting, Enum.CooldownViewerVisibleSetting + if not S or not V then return end + for _, system in ipairs(layout.systems or {}) do + if system.system == E.CooldownViewer and names[system.systemIndex] then + local i = system.systemIndex + -- Release Blizzard's bottom-frame stacking through detached saved + -- layout data. Otherwise showing a viewer in combat can snap it + -- back over the pet/action rows despite our out-of-combat anchor. + system.isInDefaultPosition = false + system.anchorInfo = {point="BOTTOM", relativeTo="UIParent", relativePoint="BOTTOM", + offsetX=({0,280,0,-280})[i], offsetY=({300,300,350,300})[i]} + set(system, S.Orientation, i == 4 and Enum.CooldownViewerOrientation.Vertical or Enum.CooldownViewerOrientation.Horizontal) + set(system, S.IconDirection, Enum.CooldownViewerIconDirection.Right) + set(system, S.IconLimit, i == 1 and 6 or 8) + -- IconSize uses (stored * 10 + 50)%, unlike IconLimit/Padding. + -- Native base sizes: essential 50, utility 30, buff 40, bar 30. + set(system, S.IconSize, ({1,4,1,3})[i]) -- 30 / 27 / 24 / 24 units + set(system, S.IconPadding, i == 4 and 4 or 8) -- visual gaps 2 / 4 + set(system, S.BarWidthScale, 75) -- 125% * 220 * .8 = 220 units + set(system, S.Opacity, 50) -- 100%, encoded from the 50% minimum + set(system, S.HideWhenInactive, i >= 3 and 1 or 0) + set(system, S.ShowTimer, 1) + set(system, S.ShowTooltips, 1) + set(system, S.BarContent, Enum.CooldownViewerBarContent.IconAndName) + local visible = mode() == "show" and V.Always or V.InCombat + if mode() == "off" or (itemCounts and itemCounts[i] == 0) then visible = V.Hidden end + set(system, S.VisibleSetting, visible) + end + end +end + +local function configureViewers(itemCounts, signature) + local _, class = UnitClass("player") + local context = class .. ":" .. mode() .. ":" .. signature + if appliedContext == context then return end + local data = P.CopyEditModeLayouts() + local found = false + for _, layout in ipairs(data.layouts or {}) do + if P.IsOurLayout(layout) then + RuenUIDB.beforeClassAssist = RuenUIDB.beforeClassAssist or C_EditMode.ConvertLayoutInfoToString(layout) + P.ConfigureClassAssistSystems(layout, itemCounts) + found = true + end + end + if found then + appliedContext = context + P.SaveEditModeLayouts(data) + end +end + +function P.ApplyMouseover(force) + if InCombatLockdown() or RuenUIDB.disabled then return end + force = force or P.mouseoverPending + if not GetModifiedClick or not SetModifiedClick or not C_CVar.GetCVar("enableMouseoverCast") + or (IsMouseoverCastSupported and not IsMouseoverCastSupported()) then + RuenUICharacter.mouseoverStatus = "unavailable" + return + end + local _, class = UnitClass("player") + local preference = RuenUICharacter.mouseoverMode or "auto" + local enabled = preference == "on" or (preference == "auto" and healers[class]) or false + local value = enabled and "1" or "0" + local previous = RuenUICharacter.mouseoverApplied + local current, modifier = C_CVar.GetCVar("enableMouseoverCast"), GetModifiedClick("MOUSEOVERCAST") + local character = (UnitGUID and UnitGUID("player")) or (UnitName("player") .. ":" .. class) + if not force and previous and previous.class == class and previous.mode == preference + and RuenUIDB.mouseoverLastCharacter == character then + -- A deliberate later change in Options is respected, even after reload. + RuenUICharacter.mouseoverStatus = current == "1" and "on" or "off" + return + end + RuenUICharacter.mouseoverOriginal = RuenUICharacter.mouseoverOriginal or {value=current, modifier=modifier} + RuenUIDB.results = RuenUIDB.results or {} + put("enableMouseoverCast", value) + if enabled then + if Settings and Settings.GetSetting and Settings.GetSetting("MOUSEOVERCAST") then + Settings.SetValue("MOUSEOVERCAST", "NONE") + else SetModifiedClick("MOUSEOVERCAST", "NONE") end + elseif previous and previous.enabled and modifier == "NONE" then + local old = RuenUICharacter.mouseoverOriginal.modifier or "NONE" + if Settings and Settings.GetSetting and Settings.GetSetting("MOUSEOVERCAST") then + Settings.SetValue("MOUSEOVERCAST", old) + else SetModifiedClick("MOUSEOVERCAST", old) end + end + RuenUICharacter.mouseoverApplied = {class=class, mode=preference, enabled=enabled} + RuenUIDB.mouseoverLastCharacter = character + P.mouseoverPending = nil + RuenUICharacter.mouseoverStatus = enabled and "on" or "off" +end + +function P.RestoreClassAssist() + if InCombatLockdown() then return end + P.classAssistReserved = {} + appliedContext = nil + local old = RuenUICharacter.mouseoverOriginal + if old and SetModifiedClick then + if Settings and Settings.GetSetting and Settings.GetSetting("MOUSEOVERCAST") then + Settings.SetValue("MOUSEOVERCAST", old.modifier) + else SetModifiedClick("MOUSEOVERCAST", old.modifier) end + end + RuenUICharacter.mouseoverApplied = nil + RuenUIDB.mouseoverLastCharacter = nil + P.mouseoverPending = nil +end + +local function positionViewers(itemCounts) + local obstacles = {} + P.classAssistReserved = {} -- don't collide with last pass's own reservations + for _, r in ipairs(P.OverlayObstacles(false)) do + -- Cooldowns are gameplay information; the meter fits around them. + if not r.name or not r.name:match("^DamageMeter") then obstacles[#obstacles+1] = r end + end + local center = UIParent:GetWidth()/2 + local base = (edge(PlayerCastingBarFrame,"GetTop") or 280)+12 + local nextCenter = base + RuenUICharacter.classAssistUnplaced = {} + -- Essential abilities are closest to the cast bar; buffs just above them. + -- Utility and duration bars use nearby free space, without moving controls. + -- A tall duration stack needs a contiguous lane before small icon groups + -- fragment it. Normal short stacks retain the closest-to-center layout. + local order = itemCounts[4] > 4 and {4,1,3,2} or {1,3,2,4} + for _, i in ipairs(order) do + local f = _G[names[i]] + if itemCounts[i] > 0 and mode() ~= "off" then + local scale = f:GetEffectiveScale()/UIParent:GetEffectiveScale() + local w, h = f:GetWidth()*scale, f:GetHeight()*scale + if w > 0 and h > 0 then + local x, y = center-w/2, nextCenter + if i == 2 then x, y = center+130, base end + if i == 4 then x, y = center-130-w, base end + -- Account for the native icon border/glow beyond its frame. + local target = P.FindOverlayPosition(w+12,h+12,x-6,y-6,obstacles,UIParent:GetWidth(),UIParent:GetHeight()) + if target then + target.name = names[i] + place(f,"BOTTOMLEFT",UIParent,"BOTTOMLEFT",target.left+6,target.bottom+6) + obstacles[#obstacles+1] = target + P.classAssistReserved[#P.classAssistReserved+1] = target + if i == 1 or i == 3 then nextCenter = target.top+12 end + else + -- Do not silently omit learned spells or move protected bars. + RuenUICharacter.classAssistUnplaced[#RuenUICharacter.classAssistUnplaced+1] = names[i] + end + end + end + end +end + +local function refresh() + P.ApplyMouseover(false) + if C_CooldownViewer and C_CooldownViewer.IsCooldownViewerAvailable then + local available, reason = C_CooldownViewer.IsCooldownViewerAvailable() + local itemCounts, signature, groups = counts() + RuenUICharacter.classAssistStatus = {available=available, reason=reason, mode=mode(), counts=itemCounts, + spells=groups and describeSpells(signature,groups), enabled=C_CVar.GetCVar("cooldownViewerEnabled")} + if available and itemCounts then + RuenUIDB.results = RuenUIDB.results or {} + local enabled = mode() == "off" and "0" or "1" + if C_CVar.GetCVar("cooldownViewerEnabled") ~= enabled then put("cooldownViewerEnabled",enabled) end + RuenUICharacter.classAssistStatus.enabled=enabled + configureViewers(itemCounts,signature) + for _,name in ipairs(names) do + local f = _G[name] + if not hooked[f] then + hooked[f] = true + f:HookScript("OnSizeChanged",queue) + if f.OnUpdateSystem then hooksecurefunc(f,"OnUpdateSystem",queue) end + end + end + positionViewers(itemCounts) + elseif not available then P.classAssistReserved = {} end + end +end + +function P.RefreshClassAssist() + if busy or not owns then return end + if InCombatLockdown() then return end -- native code handles combat visibility + if not owns() or settingsOpen() then P.classAssistReserved = {}; return end + busy = true + local ok, err = pcall(refresh) + busy = false -- an unavailable native subsystem must not disable future retries + if not ok and RuenUICharacter.classAssistError ~= tostring(err) then + RuenUICharacter.classAssistError = tostring(err) + if geterrorhandler then geterrorhandler()(err) end + elseif ok then RuenUICharacter.classAssistError = nil end +end + +function P.ClassAssistCommand(command, argument) + if command == "mouseover" then + if argument == "auto" or argument == "on" or argument == "off" then + RuenUICharacter.mouseoverMode = argument + P.mouseoverPending = true + P.ApplyMouseover(true) + end + return P.Localized("Mouseover preference: ","Настройка наведения: ") .. (RuenUICharacter.mouseoverMode or "auto") + .. P.Localized("; active: ","; сейчас: ") .. (RuenUICharacter.mouseoverStatus or "pending") .. P.Localized( + ". /ruen mouseover auto|on|off. When enabled, hover a valid unit and press the spell key; no extra modifier. Combat changes wait.", + ". /ruen mouseover auto|on|off. Когда включено, наведите на подходящую цель и нажмите клавишу заклинания; без модификатора. Изменения — после боя.") + end + if argument == "on" then argument="auto" end + if argument == "hide" then argument="off" end + if argument == "status" then P.RefreshClassAssist();return P.CooldownSummary() end + if argument == "settings" and CooldownViewerSettings and not InCombatLockdown() then + CooldownViewerSettings:ShowUIPanel() + elseif argument == "auto" or argument == "show" or argument == "off" then + RuenUIDB.cooldownsMode = argument + P.RefreshClassAssist() + end + return P.Localized("Cooldowns: ","Перезарядки: ") .. mode() .. P.Localized( + ". /ruen cooldowns auto (combat), show, hide/off, settings, status. Spells follow your class, talents and training; changes wait until combat ends.", + ". /ruen cooldowns auto (в бою), show, hide/off, settings, status. Способности зависят от класса, талантов и обучения; изменения — после боя.") +end + +function P.InitializeClassAssist(isOurs, placeFrame, frameEdge, setCVar) + owns, place, edge, put = isOurs, placeFrame, frameEdge, setCVar + if P.classAssistListener then return end + local listener = CreateFrame("Frame"); P.classAssistListener = listener + queue = function() + if busy or queued then return end + queued = true + C_Timer.After(.25,function() + queued = false + P.RefreshClassAssist() + if P.RefreshDamageMeters then P.RefreshDamageMeters() end + if P.PositionOverlayFrames then P.PositionOverlayFrames() end + end) + end + for _,event in ipairs({"PLAYER_ENTERING_WORLD","PLAYER_REGEN_ENABLED","SPELLS_CHANGED","PLAYER_TALENT_UPDATE", + "PLAYER_SPECIALIZATION_CHANGED","COOLDOWN_VIEWER_DATA_LOADED","COOLDOWN_VIEWER_TABLE_HOTFIXED", + "DISPLAY_SIZE_CHANGED","UI_SCALE_CHANGED","ADDON_LOADED"}) do listener:RegisterEvent(event) end + listener:SetScript("OnEvent",queue) + if EventRegistry then + for _,event in ipairs({"CooldownViewerSettings.OnShow","CooldownViewerSettings.OnHide"}) do + EventRegistry:RegisterCallback(event,queue,listener) + end + end + if EditModeManagerFrame then + EditModeManagerFrame:HookScript("OnHide",function() appliedContext=nil;queue() end) + end + queue() +end diff --git a/RuenUI/ClassLayout.lua b/RuenUI/ClassLayout.lua new file mode 100644 index 0000000..aafd5e4 --- /dev/null +++ b/RuenUI/ClassLayout.lua @@ -0,0 +1,226 @@ +local _, P = ... + +-- Separate from profile/version migrations: never reset spells, bindings, +-- graphics, language or the user's ordinary action-bar assignments. +P.classLayoutVersion = 7 +P.petIconSize = 8 -- native 130%: pet icons now nearly match the combat buttons +P.classFrameNames = { + "PartyFrame", "CompactRaidFrameContainer", + "UIWidgetTopCenterContainerFrame", "UIWidgetBelowMinimapContainerFrame", "UIWidgetPowerBarContainerFrame", + "BossTargetFrameContainer", "PlayerPowerBarAlt", + "StanceBar", "PetActionBar", "PossessActionBar", "MultiCastActionBarFrame", + "MainMenuBarVehicleLeaveButton", "ExtraAbilityContainer", "PlayerCastingBarFrame", + "PlayerFrame", "PetFrame", "TargetFrame", "TargetFrameToT", "RuenTargetTargetTarget", "FocusFrame", +} + +local function setting(system, key, value) + if key == nil then return end + for _, entry in ipairs(system.settings or {}) do + if entry.setting == key then entry.value = value; return end + end + system.settings = system.settings or {} + system.settings[#system.settings + 1] = {setting = key, value = value} +end + +local function anchor(system, point, x, y) + system.anchorInfo = {point = point, relativeTo = "UIParent", relativePoint = "BOTTOM", offsetX = x, offsetY = y} + system.isInDefaultPosition = false +end + +local function makePlan(base) + local _, class = UnitClass("player") + local function dimension(name, method, fallback) + local f = _G[name] + if not f then return fallback end + local value = f[method](f) * f:GetEffectiveScale() / UIParent:GetEffectiveScale() + return value > 1 and value or fallback + end + local function shown(name) return _G[name] and _G[name]:IsShown() end + local hasForms = GetNumShapeshiftForms and GetNumShapeshiftForms() > 0 + local petClass = class == "HUNTER" or class == "WARLOCK" or class == "MAGE" + local petActive = petClass or shown("PetActionBar") + -- Use six units of the twelve-unit clearance above the combat rows for + -- the larger pet icons, keeping the cast/unit HUD at its compact height. + if petActive then base = base - 6 end + local extraWidth = P.PetExtraGeometry and select(3, P.PetExtraGeometry()) or 82 + local groups = { + {name = "StanceBar", active = hasForms or shown("StanceBar"), width = dimension("StanceBar", "GetWidth", 30), height = dimension("StanceBar", "GetHeight", 30)}, + {name = "PetActionBar", active = petActive, width = dimension("PetActionBar", "GetWidth", 408) + extraWidth, height = dimension("PetActionBar", "GetHeight", 39)}, + {name = "MultiCastActionBarFrame", active = class == "SHAMAN" or shown("MultiCastActionBarFrame"), width = dimension("MultiCastActionBarFrame", "GetWidth", 230), height = dimension("MultiCastActionBarFrame", "GetHeight", 38)}, + } + -- Compact rows stay inside the space between player/target subframes. Known + -- class controls retain their slot when temporarily hidden during combat. + local rows, row = {}, {width = 0, height = 30} + for _, group in ipairs(groups) do + if group.active then + local gap = #row > 0 and 10 or 0 + if #row > 0 and row.width + gap + group.width > 300 then + rows[#rows + 1] = row; row = {width = 0, height = 30}; gap = 0 + end + row[#row + 1] = group + row.width = row.width + gap + group.width + row.height = math.max(row.height, group.height) + end + end + if #row > 0 then rows[#rows + 1] = row end + local plan, top = {}, base + for _, current in ipairs(rows) do + local left = -current.width / 2 + for _, group in ipairs(current) do + plan[group.name] = {"BOTTOM", left + group.width / 2, top} + left = left + group.width + 10 + end + -- Larger pet icons need less surrounding whitespace. Keep a clear + -- five-unit gap above their row without pushing the unit HUD upward. + local rowGap = #current == 1 and current[1].name == "PetActionBar" and 5 or 8 + top = top + current.height + rowGap + end + local cast = math.max(228, top + (P.swingDockHeight or 13) + (P.swingCastGap or 18)) + plan.RuenSwingTimers = {"BOTTOM", 0, cast - (P.swingCastGap or 18) - (P.swingDockHeight or 13)} + local castHeight = dimension("PlayerCastingBarFrame", "GetHeight", 20) + local units = math.max(258, cast + castHeight + 10) + -- Unused class frames also receive safe, non-overlapping anchors. If a + -- quest reveals an unusual pet/form in combat, it appears in the center + -- gap above the cast bar; reflow compacts it after combat. + local spare = units + 32 + for _, group in ipairs(groups) do + if not plan[group.name] then + plan[group.name] = {"BOTTOM", 0, spare} + spare = spare + group.height + 10 + end + end + -- Native ten buttons occupy the left part of the centered twelve-button row. + plan.PetActionBar[2] = plan.PetActionBar[2] - extraWidth / 2 + local right = dimension("MultiBarBottomRight", "GetWidth", 495) / 2 + 14 + plan.PossessActionBar = {"BOTTOMLEFT", right, base - 70} + plan.MainMenuBarVehicleLeaveButton = {"BOTTOMLEFT", right + dimension("PossessActionBar", "GetWidth", 54) + 10, base - 70} + plan.ExtraAbilityContainer = {"BOTTOM", shown("FocusFrame") and -300 or 0, units + 126} + plan.PlayerCastingBarFrame = {"BOTTOM", 0, cast} + -- At laptop widths the fixed 165-unit offset can push target information + -- into the quest/right-utility column. Keep symmetric unit frames inside it. + local unitWidth=math.max(dimension("PlayerFrame","GetWidth",232),dimension("TargetFrame","GetWidth",232)) + local offset=math.min(165,math.max(132,UIParent:GetWidth()/2-unitWidth-dimension("MultiBarLeft","GetWidth",252)-62)) + plan.PlayerFrame = {"BOTTOMRIGHT", -offset, units} + plan.TargetFrame = {"BOTTOMLEFT", offset, units} + -- The native target cast bar occupies the space under target-of-target. + -- Put the optional third-target readout in the clear middle gap instead. + plan.RuenTargetTargetTarget = {"BOTTOM",0,units+10} + -- Focus uses the middle lane above the cast/target chain. Target auras + -- keep their own right column; focus casts clear the primary unit frames. + plan.FocusFrame = {"BOTTOM", UIParent:GetWidth()<1366 and 16 or 0, units + 110} + return plan +end + +function P.ConfigureClassSystems(layout, base) + local plan = makePlan(base or 222) + local E, A, I, U = Enum.EditModeSystem, Enum.EditModeActionBarSetting, + Enum.EditModeActionBarSystemIndices, Enum.EditModeUnitFrameSystemIndices + for _, system in ipairs(layout.systems or {}) do + local kind, index, name = system.system, system.systemIndex + if kind == E.ActionBar then + if index == I.StanceBar then name = "StanceBar" + elseif index == I.PetActionBar then name = "PetActionBar" + elseif index == I.PossessActionBar then name = "PossessActionBar" end + if name then + setting(system, A.Orientation, Enum.ActionBarOrientation.Horizontal) + setting(system, A.NumRows, 1) + setting(system, A.IconPadding, name == "PetActionBar" and 0 or 2) + setting(system, A.IconSize, name == "PetActionBar" and P.petIconSize or 3) + end + elseif kind == E.TotemActionBar then name = "MultiCastActionBarFrame" + elseif kind == E.VehicleLeaveButton then name = "MainMenuBarVehicleLeaveButton" + elseif kind == E.ExtraAbilities then name = "ExtraAbilityContainer" + elseif kind == E.CastBar then name = "PlayerCastingBarFrame" + elseif kind == E.UnitFrame then + if index == U.Player then name = "PlayerFrame" + elseif index == U.Target then name = "TargetFrame" + elseif index == U.Focus then name = "FocusFrame" end + end + if name == "FocusFrame" then setting(system, Enum.EditModeUnitFrameSetting.UseLargerFrame, 0) end + if name == "TargetFrame" or name == "FocusFrame" then + -- Native aura layout grows away from the action rows. Do not move + -- secure aura children or hook their frequent updates. + setting(system, Enum.EditModeUnitFrameSetting.BuffsOnTop, 1) + end + if name then anchor(system, unpack(plan[name])) end + end +end + +function P.MigrateClassLayout() + if InCombatLockdown() or not RuenUIDB or RuenUIDB.disabled then return end + local _, class = UnitClass("player") + if RuenUIDB.classLayoutVersion == P.classLayoutVersion and RuenUIDB.classLayoutClass == class then return end + local manager = EditModeManagerFrame + if not manager or manager:IsShown() or manager.overrideLayoutInfo then return end + local active = manager:GetActiveLayoutInfo() + if not P.IsOurLayout(active) then return end + -- Only submit detached data to the native API. Mutating frame.systemInfo or + -- the manager's shared layout table taints protected positioning in combat. + local info = P.CopyEditModeLayouts() + local found + for _, layout in ipairs(info.layouts or {}) do + if P.IsOurLayout(layout) then + RuenUIDB.beforeClassLayout = RuenUIDB.beforeClassLayout or C_EditMode.ConvertLayoutInfoToString(layout) + P.ConfigureClassSystems(layout) + found = true + end + end + if not found then return end + P.SaveEditModeLayouts(info) + RuenUIDB.classLayoutVersion = P.classLayoutVersion + RuenUIDB.classLayoutClass = class +end + +local widgetBaseScale,widgetAppliedScale +function P.PositionEncounterWidgets(place,edge) + local f=UIWidgetTopCenterContainerFrame + if not f then return end + local current=f:GetScale() + if not widgetBaseScale or (widgetAppliedScale and math.abs(current-widgetAppliedScale)>.001) then widgetBaseScale=current end + local width=UIParent:GetWidth() + local fit=width<1366 and .9 or 1 + widgetAppliedScale=widgetBaseScale*fit + if math.abs(current-widgetAppliedScale)>.001 then (f.SetScaleBase or f.SetScale)(f,widgetAppliedScale) end + if width<1600 then + -- Leave the upper left field for the full raid. The objective score + -- stays at the top, immediately left of the minimap on short screens. + local right=(edge(MinimapCluster,"GetLeft") or width-240)-12 + place(f,"TOPRIGHT",UIParent,"TOPLEFT",right,-12) + else place(f,"TOP",UIParent,"TOP",0,-12) end +end + +-- Reflow only after events, outside combat; never alter native visibility or +-- paging. Size is measured in UIParent units, so 1080p/1440p share the same plan. +function P.RefreshClassLayout(place, edge, ratio) + local top = edge(MultiBar5 or MultiBarBottomRight, "GetTop") + if not top or InCombatLockdown() then return end + local plan = makePlan(math.max(180, top + 12)) + for name, position in pairs(plan) do + local f = _G[name] + if f then place(f, position[1], UIParent, "BOTTOM", position[2], position[3]) end + end + if P.PositionSwingTimers then + local cast = PlayerCastingBarFrame + local width = cast and cast:GetWidth() * ratio(cast) or 208 + P.PositionSwingTimers(plan, width, place) + end + -- The totem frame reserves all four slots even when only one is learned. + -- Center the visible buttons, including summon/recall, instead of its empty + -- full-level footprint. Their secure click handlers/visibility stay native. + local bar = MultiCastActionBarFrame + if bar and bar:IsShown() then + local left, right + for _, name in ipairs({"MultiCastSlotButton1", "MultiCastSlotButton2", "MultiCastSlotButton3", "MultiCastSlotButton4", "MultiCastSummonSpellButton", "MultiCastRecallSpellButton"}) do + local button = _G[name] + if button and button:IsShown() then + local l, r = edge(button, "GetLeft"), edge(button, "GetRight") + if l and r then left = left and math.min(left, l) or l; right = right and math.max(right, r) or r end + end + end + if left and right then + local position = plan.MultiCastActionBarFrame + local center = UIParent:GetWidth() / 2 + position[2] + place(bar, position[1], UIParent, "BOTTOM", position[2] + center - (left + right) / 2, position[3]) + end + end +end diff --git a/RuenUI/Controls.lua b/RuenUI/Controls.lua new file mode 100644 index 0000000..b4cc287 --- /dev/null +++ b/RuenUI/Controls.lua @@ -0,0 +1,223 @@ +local _, P = ... + +-- Only this small set migrates on an existing character: combat slots, graphics, +-- ESDF, pet controls and personal action assignments are left alone. +P.controlsVersion = 1 +P.menuBindings = { + {"N", "TOGGLEWORLDMAP"}, {"SHIFT-N", "TOGGLEBATTLEFIELDMINIMAP"}, + {"I", "OPENALLBAGS"}, {"J", "TOGGLEQUESTLOG"}, {"ALT-J", "SPOKEN_COMPENDIUM"}, + {"K", "TOGGLECHARACTER0"}, {"SHIFT-K", "TOGGLETALENTS"}, + {"CTRL-K", "TOGGLECHARACTER2"}, {"ALT-K", "TOGGLECURRENCY"}, + {"P", "TOGGLESPELLBOOK"}, {"SHIFT-P", "TOGGLEPROFESSIONBOOK"}, + {"CTRL-P", "TOGGLEPETBOOK"}, + {"L", "TOGGLEGROUPFINDER"}, {"SHIFT-L", "TOGGLELEGACYSYSTEM"}, + {"O", "TOGGLESOCIAL"}, {"SHIFT-O", "TOGGLEGUILDTAB"}, + {"CTRL-O", "TOGGLERAIDTAB"}, {"ALT-O", "TOGGLEWHOTAB"}, + {"Y", "TOGGLECOLLECTIONS"}, {"SHIFT-Y", "TOGGLECOLLECTIONSMOUNTJOURNAL"}, + {"CTRL-Y", "TOGGLECOLLECTIONSTOYBOX"}, {"ALT-Y", "TOGGLECOLLECTIONSWARDROBE"}, + {"SHIFT-J", "TOGGLEENCOUNTERJOURNAL"}, {"CTRL-J", "TOGGLEACHIEVEMENT"}, + {"F6", "NAMEPLATES"}, {"SHIFT-F6", "ALLNAMEPLATES"}, {"CTRL-F6", "FRIENDNAMEPLATES"}, + {"F8", "RUENUI_MACROS"}, {"F9", "RUENUI_SETTINGS"}, + {"SHIFT-F9", "RUENUI_KEYBINDINGS"}, {"F10", "TOGGLEHOUSINGDASHBOARD"}, + {"F12", "RUENUI_HELP"}, {"SHIFT-F12", "RUENUI_SUPPORT"}, +} + +local function say(text) print("|cff60d5ffRuen UI:|r " .. P.Translate(text)) end + +function P.ApplyUtilityBindings(force) + if InCombatLockdown() then return false end + local scope = GetCurrentBindingSet() == 1 and RuenUIDB or RuenUICharacter + -- Independent one-time addition: never replay the existing menu migration + -- or take over a key already used by the player or an active override. + if not scope.graveAutorunChecked then + local previous = GetBindingAction("`", true) + if not previous or previous == "" then + if not SetBinding("`", "TOGGLEAUTORUN") then return false end + RuenUICharacter.bindingChanges = RuenUICharacter.bindingChanges or {} + local changes = RuenUICharacter.bindingChanges + changes["`"] = changes["`"] or {before = ""} + changes["`"].applied = "TOGGLEAUTORUN" + SaveBindings(GetCurrentBindingSet()) + say("Grave (`) now toggles autorun.") + elseif previous ~= "TOGGLEAUTORUN" then + say("Grave (`) is already bound; its shortcut was preserved.") + end + scope.graveAutorunChecked = true + end + local available = {} + for i = 1, GetNumBindings() do + local action = GetBinding(i) + available[action] = true + end + RuenUICharacter.bindingChanges = RuenUICharacter.bindingChanges or {} + local changes = RuenUICharacter.bindingChanges + local missing = {} + local function bind(key, action) + if action and not available[action] then missing[#missing + 1] = key .. ": " .. action; return end + local before = GetBindingAction(key) + if before == (action or "") then return end + if not SetBinding(key, action) then error("Could not bind " .. key) end + changes[key] = changes[key] or {before = before} + changes[key].applied = action or "" + end + -- Add the Compendium key to already-configured binding sets without + -- replaying other menu defaults. Retry later if Spoken is not available. + if (force or scope.compendiumBindingVersion ~= 1) and available.SPOKEN_COMPENDIUM then + bind("ALT-J", "SPOKEN_COMPENDIUM") + SaveBindings(GetCurrentBindingSet()) + scope.compendiumBindingVersion = 1 + end + if not force and scope.controlsVersion == P.controlsVersion then return false end + -- M is deliberately free. N is navigation; nameplates move off the letter keys. + bind("M", nil) + bind("SPACE", "JUMP") + for _, modifier in ipairs({"", "SHIFT-", "CTRL-", "CTRL-SHIFT-"}) do + bind(modifier .. "BUTTON3", "JUMP") + bind(modifier .. "BUTTON4", "TARGETPREVIOUSENEMY") + bind(modifier .. "BUTTON5", "TARGETNEARESTENEMY") + end + bind("TAB", "TARGETNEARESTENEMY") + bind("SHIFT-TAB", "TARGETPREVIOUSENEMY") + for _, entry in ipairs(P.menuBindings) do bind(entry[1], entry[2]) end + SaveBindings(GetCurrentBindingSet()) + scope.controlsVersion = P.controlsVersion + RuenUICharacter.unavailableMenuBindings = missing + say("Mouse: middle = jump; rear thumb = previous enemy; front thumb = next. N = map; M is free. /ruen help shows shortcuts.") + if #missing > 0 then say("Menus unavailable in this client: " .. table.concat(missing, "; ")) end + return true +end + +function P.OpenMenu(which) + if InCombatLockdown() then say("Open this menu after combat."); return end + if which == "macros" then + if C_AddOns.LoadAddOn then C_AddOns.LoadAddOn("Blizzard_MacroUI") end + if ShowMacroFrame then ShowMacroFrame() end + elseif which == "settings" then + if Settings and Settings.OpenToCategory and Settings.INTERFACE_CATEGORY_ID then + Settings.OpenToCategory(Settings.INTERFACE_CATEGORY_ID) + elseif ToggleGameMenu then ToggleGameMenu() end + elseif which == "keybindings" then + if Settings and Settings.OpenToCategory and Settings.KEYBINDINGS_CATEGORY_ID then + Settings.OpenToCategory(Settings.KEYBINDINGS_CATEGORY_ID) + elseif ToggleGameMenu then ToggleGameMenu() end + elseif which == "support" and ToggleHelpFrame then ToggleHelpFrame() end +end + +function P.Help() + say(P.BarHelp()) + say(P.Localized("/ruen guns on|off|settings|status; /ruen guns 100: softer gunshots, volume 10–100. Nearby stock gunshots are muted while enabled.", + "/ruen guns on|off|settings|status; /ruen guns 100: тихие выстрелы, громкость 10–100. Стандартные выстрелы окружающих при включении заглушаются.")) + say(P.Localized("/ruen cooldowns auto|show|hide|off|settings|status: class-aware timers. /ruen mouseover auto|on|off: per-character casting preference.", + "/ruen cooldowns auto|show|hide|off|settings|status: таймеры класса. /ruen mouseover auto|on|off: наведение для персонажа.")) + say(P.Localized("/ruen meters auto|show|off: native damage/healing meter; auto shows in dungeons and raids.", + "/ruen meters auto|show|off: встроенный счётчик урона/исцеления; auto — в подземельях и рейдах.")) + say(P.Localized("Alt now selects action buttons. Automatic self-cast stays on; use F1 to target yourself. Ctrl+Shift+F11 hides/shows the UI.", "Alt выбирает кнопки действий. Автовыбор себя включён; F1 — выбрать себя. Ctrl+Shift+F11 скрывает интерфейс.")) + say(P.Localized("/ruen optimize: measure world/raid performance. optimize pause|resume|status|restore. Hardware check: bundled Optimize tool.","/ruen optimize: проверка мира/рейда. optimize pause|resume|status|restore. Датчики: утилита Optimize из комплекта.")) + say(P.Localized("/ruen swing on|off|preview: thin attack timers. /ruen lock | unlock: lock or drag action and pet abilities normally outside combat.", + "/ruen swing on|off|preview: таймеры атак. /ruen unlock: свободное перемещение способностей, включая питомца, вне боя.")) + say("Grave (`): autorun, added only if the key was unbound.") + say("ESDF movement; Space/middle mouse jump. Rear thumb/Shift-Tab previous enemy; front thumb/Tab next enemy.") + say(P.Localized("Combat: Q W R T / A G H / Z X C V B. Rows bottom to top: base, Shift, Ctrl, Alt. /ruen lock | unlock.", "Бой: Q W R T / A G H / Z X C V B. Ряды снизу вверх: без модификатора, Shift, Ctrl, Alt. /ruen lock | unlock.")) + say("N map, Shift-N zone map; I bags; J quests, Alt-J Compendium; K character; Shift-K talents; Ctrl-K reputation; Alt-K currency.") + say("P spells, Shift-P professions, Ctrl-P pet spells; L group finder, Shift-L legacy; O friends, Shift-O guild, Ctrl-O raid, Alt-O Who.") + say("Y collections, Shift-Y mounts, Ctrl-Y toys, Alt-Y appearances; Shift-J adventure guide; Ctrl-J achievements (where available).") + say("F6 enemy nameplates, Shift-F6 all, Ctrl-F6 friendly; F8 macros; F9 settings; Shift-F9 keybindings; F10 housing (where available); Esc game menu.") + say("U interact, Shift-U assist, Alt-U ping; Ctrl-I sit, Shift-I sheathe. F12 this help; Shift-F12 support.") + say("/ruen language en|ru: game text/audio + narration; client restart required. /ruen voice en|ru: narration only, immediate. /ruen language: status.") + say("/ruen bindings: reapply mouse/menu keys; /ruen bags: reposition bags; /ruen pet auto: reset the two extra pet buttons. /ruen status | balanced | performance | bench | export | restore. /ruen apply resets the whole UI profile.") +end + +local aliases = {en = "enUS", english = "enUS", enus = "enUS", ru = "ruRU", russian = "ruRU", ruru = "ruRU"} + +local function spokenProfile() + -- Spoken 3.9 exposes reads in its public API; this is the same active AceDB + -- table its own language dropdown updates. Do not replace the table. + return SpokenEnv and SpokenEnv.Addon and SpokenEnv.Addon.db and SpokenEnv.Addon.db.profile +end + +function P.LanguageStatus() + local voice, fallback + if Spoken and Spoken.GetLanguageChoice then voice, fallback = Spoken:GetLanguageChoice() end + local regional = GetAvailableLocales and {GetAvailableLocales()} or {} + local available = GetAvailableLocales and {GetAvailableLocales(true)} or {} + say("Running text: " .. tostring(GetLocale()) .. "; selected text/audio: " .. tostring(C_CVar.GetCVar("textLocale")) .. "/" .. tostring(C_CVar.GetCVar("audioLocale")) .. "; narration: " .. tostring(voice or "auto") .. "; fallback: " .. tostring(fallback or "enUS") .. ".") + say("Regional menu: " .. table.concat(regional, ", ") .. ". Full client language support: " .. table.concat(available, ", ") .. ".") + say("/ruen language en|ru changes game text/audio and narration; restart required. /ruen voice en|ru changes narration only. Available does not mean the language files have finished downloading.") +end + +function P.SetLanguage(value, voiceOnly) + if value == "toggle" then value = (voiceOnly and RuenUIDB.narrationLanguage or C_CVar.GetCVar("textLocale")) == "ruRU" and "en" or "ru" end + local code = aliases[value] + if not code then say("Choose en (English) or ru (Russian). /ruen language shows current settings."); return end + local profile = spokenProfile() + if not profile or not Spoken or not Spoken.GetLanguageChoice then + say("Spoken has not initialized. Enable Spoken and Spoken_Quests, then /reload."); return + end + if Spoken.StopAll then Spoken:StopAll() end + profile.Language = profile.Language or {} + profile.Language.Voice, profile.Language.Fallback = code, "enUS" + if SpokenEnv.Options and SpokenEnv.Options.UpdateRows then SpokenEnv.Options:UpdateRows() end + RuenUIDB.narrationLanguage = code + say(P.Localized("Narration: ", "Озвучка: ") .. code .. P.Localized("; missing recordings fall back to English. Open a quest to hear the new language.", "; отсутствующие записи заменяются английскими, если они есть. Откройте задание для проверки.")) + if voiceOnly then return true end + if InCombatLockdown() then say("Narration changed. Run the command after combat to change game text/audio too."); return end + local supported = code == GetLocale() + if GetAvailableLocales then + -- The default list is region-filtered, not an installed/supported locale list. + -- Battle.net lists ruRU among wowf supported_text_languages for this US install. + -- Query the full client catalog; do not spoof GetLocale or replace native APIs. + for _, locale in ipairs({GetAvailableLocales(true)}) do if locale == code then supported = true end end + end + if not supported then + say("Game text/audio did NOT change: the full client language catalog does not include " .. code .. ". In Battle.net > WoW > gear > Game Settings / Modify Install, add that text and spoken language, then restart. Narration is already changed.") + return + end + local oldText, oldAudio = C_CVar.GetCVar("textLocale"), C_CVar.GetCVar("audioLocale") + local function set(key, text) + if Settings and Settings.GetSetting and Settings.GetSetting(key) then Settings.SetValue(key, text) + else C_CVar.SetCVar(key, text) end + if C_CVar.GetCVar(key) ~= text then error(key .. " was rejected") end + end + local function setPair(text, audio) + -- English text forces English audio inside the client. If text changes + -- first, that implicit audio update can skip the Agent notification. + -- English audio is valid with Russian text, so set it explicitly first. + if text == "enUS" then set("audioLocale", audio); set("textLocale", text) + else set("textLocale", text); set("audioLocale", audio) end + end + local ok, err = pcall(setPair, code, code) + if not ok then + pcall(setPair, oldText, oldAudio) + say("Game language change failed: " .. tostring(err) .. ". Use Battle.net's game language settings. Narration changed successfully."); return + end + RuenUIDB.requestedGameLanguage = code + say(P.Localized("Game text and audio selected: ", "Текст и звук игры: ") .. code .. P.Localized(". Fully exit WoW and relaunch through Battle.net; /reload is insufficient. If language files are missing, use Modify Install and keep English + Russian checked. Chat is not translated.", ". Полностью закройте WoW и запустите через Battle.net; /reload недостаточно. Если файлов языка нет: «Изменить установку», оставить английский и русский. Чат не переводится.")) + return true +end + +BINDING_HEADER_RUENUI = "Ruen UI" +BINDING_NAME_RUENUI_MACROS = P.Translate("Open macros") +BINDING_NAME_RUENUI_SETTINGS = P.Translate("Open settings") +BINDING_NAME_RUENUI_KEYBINDINGS = P.Translate("Open keybindings") +BINDING_NAME_RUENUI_HELP = P.Translate("Ruen UI help and key map") +BINDING_NAME_RUENUI_SUPPORT = P.Translate("Open Blizzard support") +-- Binding handlers only execute on the user's keypress. +RuenUI_OpenMenu = P.OpenMenu + +-- Runs after the portable presets, once per account or explicit installer request. +-- A plain addon-folder copy follows the running client language on first use. +function P.InitializeLanguage() + local profile = spokenProfile() + if not profile or not Spoken or not Spoken.GetLanguageChoice then return end + local request = P.installLanguageRequest + if request and RuenUIDB.installerLanguageRequest ~= request then + -- Battle.net overrides offline Config.wtf edits. A live CVar change + -- makes the game notify the Agent of its selected text/audio locales. + -- First login may therefore need one further full game restart. + if P.SetLanguage(P.installLanguage == "ruRU" and "ru" or "en", false) then + RuenUIDB.installerLanguageRequest = request + end + elseif not RuenUIDB.narrationLanguage then + P.SetLanguage(GetLocale() == "ruRU" and "ru" or "en", true) + end +end diff --git a/RuenUI/Core.lua b/RuenUI/Core.lua new file mode 100644 index 0000000..40bd55d --- /dev/null +++ b/RuenUI/Core.lua @@ -0,0 +1,1106 @@ +local _, P = ... +local frame = CreateFrame("Frame") +local ticker +local function say(s) print("|cff60d5ffRuen UI:|r " .. P.Translate(s)) end +local function init() + RuenUIDB = RuenUIDB or {original = {}, reports = {}} + RuenUIDB.original = RuenUIDB.original or {} + RuenUIDB.reports = RuenUIDB.reports or {} + RuenUICharacter = RuenUICharacter or {original = {}} + RuenUICharacter.original = RuenUICharacter.original or {} +end +-- Merge the narration profile once, preserving unrelated settings and live AceDB references. +local function mergePreferences(target, values) + local changed = false + for key, value in pairs(values) do + if type(value) == "table" then + if type(target[key]) ~= "table" then target[key] = {}; changed = true end + if mergePreferences(target[key], value) then changed = true end + elseif target[key] ~= value then + target[key] = value; changed = true + end + end + return changed +end +local function applyAddonPresets() + if not P.addonPresets then return false end + local changed = false + RuenUIDB.addonPresetVersions = RuenUIDB.addonPresetVersions or {} + RuenUIDB.addonOriginal = RuenUIDB.addonOriginal or {} + for addon, preset in pairs(P.addonPresets) do + if C_AddOns.IsAddOnLoaded(addon) and RuenUIDB.addonPresetVersions[addon] ~= P.addonPresetVersion then + local db = _G[preset.variable] or {} + if RuenUIDB.addonOriginal[preset.variable] == nil then + RuenUIDB.addonOriginal[preset.variable] = CopyTable(db) + end + for key, value in pairs(preset.values) do + if db[key] ~= value then db[key] = value; changed = true end + end + if preset.profile then + db.profiles = db.profiles or {} + db.profiles["Ruen Narration"] = db.profiles["Ruen Narration"] or {} + for _, profile in pairs(db.profiles) do + if mergePreferences(profile, preset.profile) then changed = true end + end + db.global = db.global or {} + if mergePreferences(db.global, preset.global or {}) then changed = true end + end + if addon == "VoiceQuest" then + -- Voice IDs belong to the destination PC. Let VoiceQuest choose locally. + for _, key in ipairs({"maleVoice", "femaleVoice", "narratorVoice"}) do + if db[key] ~= nil then db[key] = nil; changed = true end + end + end + _G[preset.variable] = db + RuenUIDB.addonPresetVersions[addon] = P.addonPresetVersion + end + end + if C_AddOns.IsAddOnLoaded("VoiceQuest") and not RuenUICharacter.voiceQuestProfileSeeded then + VoiceQuestCharDB = VoiceQuestCharDB or {} + RuenUICharacter.oldVoiceQuestCharDB = CopyTable(VoiceQuestCharDB) + if VoiceQuestCharDB.useOwn then VoiceQuestCharDB.useOwn = false; changed = true end + RuenUICharacter.voiceQuestProfileSeeded = true + end + return changed +end +local function watchBlockedActions() + local lastNotice + local diagnostic = CreateFrame("Frame") + diagnostic:RegisterEvent("ADDON_ACTION_BLOCKED") + diagnostic:RegisterEvent("ADDON_ACTION_FORBIDDEN") + for _, event in ipairs({"VOICE_CHAT_TTS_PLAYBACK_STARTED", "VOICE_CHAT_TTS_PLAYBACK_FINISHED", "VOICE_CHAT_TTS_PLAYBACK_FAILED"}) do + pcall(diagnostic.RegisterEvent, diagnostic, event) + end + diagnostic:SetScript("OnEvent", function(_, event, addon, operation) + init() + if event:find("^VOICE_CHAT_TTS_") then + RuenUICharacter.ttsPlayback = RuenUICharacter.ttsPlayback or {} + RuenUICharacter.ttsPlayback[event] = time() + return + end + local records = RuenUICharacter.blockedActions or {} + RuenUICharacter.blockedActions = records + records[#records + 1] = {time = time(), event = event, addon = addon, operation = operation, stack = debugstack and debugstack(2, 24, 0) or ""} + while #records > 12 do table.remove(records, 1) end + if not lastNotice or time() - lastNotice >= 10 then + lastNotice = time() + say("Blocked action: " .. tostring(addon) .. " / " .. tostring(operation)) + end + end) +end +watchBlockedActions() +local function saveCVar(key) + local value = C_CVar.GetCVar(key) + if value == nil then return nil end + if RuenUIDB.original[key] == nil then RuenUIDB.original[key] = value end + if RuenUICharacter.original[key] == nil then RuenUICharacter.original[key] = value end + return value +end +local function put(key, value, validate) + if saveCVar(key) == nil then + RuenUIDB.results[key] = "unavailable" + return + end + if validate and IsGraphicsSettingValueSupported then + local reason = IsGraphicsSettingValueSupported(key, tonumber(value), false) + -- Blizzard uses a nil error label for supported settings (normally result 0). + if reason and reason ~= 0 then + RuenUIDB.results[key] = "unsupported: " .. tostring(reason) + return + end + end + local ok, err = pcall(C_CVar.SetCVar, key, tostring(value)) + RuenUIDB.results[key] = ok and C_CVar.GetCVar(key) or ("error: " .. tostring(err)) +end +local function applyList(list) + for _, entry in ipairs(list) do put(entry[1], entry[2], entry[1]:match("^graphics") ~= nil) end +end +local function changeSetting(system, setting, value) + if not setting then return end + for _, item in ipairs(system.settings) do + if item.setting == setting then item.value = value; return end + end + table.insert(system.settings, {setting = setting, value = value}) +end +local function anchor(system, point, relativePoint, x, y) + system.anchorInfo = {point = point, relativeTo = "UIParent", relativePoint = relativePoint, offsetX = x, offsetY = y} + system.isInDefaultPosition = false +end +local function setupThirdTarget() + if RuenTargetTargetTarget then RegisterUnitWatch(RuenTargetTargetTarget); return end + if not TargetFrameToT then return end + local f = CreateFrame("Button", "RuenTargetTargetTarget", UIParent, "SecureUnitButtonTemplate") + f:SetSize(150, 28) + f:SetPoint("TOPRIGHT", TargetFrameToT, "BOTTOMRIGHT", 0, -4) + f:SetAttribute("unit", "targettargettarget") + f:SetAttribute("type1", "target") + f:RegisterForClicks("AnyUp") + local bg = f:CreateTexture(nil, "BACKGROUND") + bg:SetAllPoints(); bg:SetColorTexture(0.03, 0.03, 0.04, 0.85) + local label = f:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall") + label:SetPoint("TOPLEFT", 4, -3); label:SetText("ToToT") + f.nameText = f:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall") + f.nameText:SetPoint("TOPLEFT", 42, -3); f.nameText:SetWidth(104); f.nameText:SetJustifyH("LEFT") + f.health = CreateFrame("StatusBar", nil, f) + f.health:SetPoint("BOTTOMLEFT", 4, 3); f.health:SetSize(142, 6) + f.health:SetStatusBarTexture("Interface\\TargetingFrame\\UI-StatusBar") + f.health:SetStatusBarColor(0.25, 0.7, 0.4) + local function refresh() + local unit = "targettargettarget" + if UnitExists(unit) then + f.nameText:SetText(UnitName(unit)) + f.health:SetMinMaxValues(0, UnitHealthMax(unit)) + f.health:SetValue(UnitHealth(unit)) + end + end + f:SetScript("OnShow", refresh) + f:SetScript("OnEvent", function(_,event,unit) + -- UNIT_TARGET also fires for every raid/nameplate unit. Only the two + -- links feeding this display can change its target. + if event=="UNIT_TARGET" and unit~="target" and unit~="targettarget" then return end + refresh() + end) + f:RegisterEvent("PLAYER_TARGET_CHANGED") + f:RegisterEvent("UNIT_TARGET") + f:RegisterUnitEvent("UNIT_HEALTH", "targettargettarget") + f:RegisterUnitEvent("UNIT_MAXHEALTH", "targettargettarget") + -- Five inexpensive refreshes/second only while this small frame is visible; + -- secure unit watching handles visibility, including target changes in combat. + local elapsedTime = 0 + f:SetScript("OnUpdate", function(_, elapsed) + elapsedTime = elapsedTime + elapsed + if elapsedTime >= 0.2 then elapsedTime = 0; refresh() end + end) + RegisterUnitWatch(f) +end + +local function applyCombatBindings() + if InCombatLockdown() then error("leave combat before applying bindings") end + RuenUICharacter.bindingChanges = RuenUICharacter.bindingChanges or {} + local changes = RuenUICharacter.bindingChanges + local function bind(key, action) + local previous = GetBindingAction(key) + if not changes[key] then changes[key] = {before = previous, applied = action or ""} end + if not SetBinding(key, action) then error("could not bind " .. key) end + changes[key].applied = action or "" + end + local base = {"Q", "W", "R", "T", "A", "G", "H", "Z", "X", "C", "V", "B"} + -- Remove paging, not class/form/vehicle behavior. All action assignments stay put. + for _, action in ipairs({"ACTIONPAGE1", "ACTIONPAGE2", "ACTIONPAGE3", "ACTIONPAGE4", "ACTIONPAGE5", "ACTIONPAGE6", "NEXTACTIONPAGE", "PREVACTIONPAGE"}) do + local keys = {GetBindingKey(action)} + for _, key in ipairs(keys) do bind(key, nil) end + end + for key, action in pairs(RuenUICharacter.addedBindings or {}) do + if GetBindingAction(key) == action then bind(key, nil) end + end + -- Make the new keys the displayed shortcuts, and preserve every old key for undo. + for _, prefix in ipairs({"ACTIONBUTTON", "MULTIACTIONBAR1BUTTON", "MULTIACTIONBAR2BUTTON", "MULTIACTIONBAR3BUTTON", "MULTIACTIONBAR4BUTTON"}) do + for i = 1, 12 do + local keys = {GetBindingKey(prefix .. i)} + for _, key in ipairs(keys) do bind(key, nil) end + end + end + for i = 1, 12 do + bind(base[i], "ACTIONBUTTON" .. i) + bind("SHIFT-" .. base[i], "MULTIACTIONBAR1BUTTON" .. i) + bind("CTRL-" .. base[i], "MULTIACTIONBAR2BUTTON" .. i) + end + -- Remove obsolete modified movement keys from the earlier RDFG setup. + for _, key in ipairs({"CTRL-SHIFT-R", "CTRL-SHIFT-G"}) do + local old = GetBindingAction(key) + if old == "MOVEFORWARD" or old == "STRAFERIGHT" then bind(key, nil) end + end + -- ESDF movement remains available while holding either combat-row modifier. + for _, prefix in ipairs({"", "SHIFT-", "CTRL-", "CTRL-SHIFT-"}) do + bind(prefix .. "E", "MOVEFORWARD"); bind(prefix .. "D", "MOVEBACKWARD") + bind(prefix .. "S", "STRAFELEFT"); bind(prefix .. "F", "STRAFERIGHT") + end + bind("U", "INTERACTTARGET"); bind("ALT-U", "TOGGLEPINGLISTENER") + bind("SHIFT-U", "ASSISTTARGET") + if RuenTargetTargetTarget then bind("CTRL-SHIFT-U", "CLICK RuenTargetTargetTarget:LeftButton") end + bind("I", "OPENALLBAGS"); bind("K", "TOGGLECHARACTER0") + bind("J", "TOGGLEQUESTLOG"); bind("N", "NAMEPLATES") + bind("SHIFT-N", "ALLNAMEPLATES") + bind("CTRL-I", "SITORSTAND"); bind("SHIFT-I", "TOGGLESHEATH") + SaveBindings(GetCurrentBindingSet()) + RuenUICharacter.bindingsVersion = 2 + P.ApplyUtilityBindings(true) +end + +local function restoreCombatBindings() + for key, change in pairs(RuenUICharacter.bindingChanges or {}) do + if GetBindingAction(key) == change.applied then + SetBinding(key, change.before ~= "" and change.before or nil) + end + end + if RuenTargetTargetTarget then + UnregisterUnitWatch(RuenTargetTargetTarget) + RuenTargetTargetTarget:Hide() + end +end + +local layoutHelpersInstalled = false +local function ownsLayout() + if not RuenUIDB or RuenUIDB.disabled then return false end + local manager = EditModeManagerFrame + local active = manager and manager:GetActiveLayoutInfo() + return manager and not manager.overrideLayoutInfo and P.IsOurLayout(active) +end + +local function setSlotsLocked(locked) + if InCombatLockdown() then say(P.Localized("Change the bar lock after combat.", "Измените блокировку панелей после боя.")); return end + RuenUIDB.results = RuenUIDB.results or {} + put("lockActionBars", locked and 1 or 0) + -- Pet dragging reads the Settings value, not merely the raw CVar. + if Settings.GetSetting and Settings.GetSetting("lockActionBars") then + Settings.SetValue("lockActionBars", locked) + end + RuenUIDB.unlockedSlotsVersion = 1 + say(locked and P.Localized("Action and pet buttons locked. Shift-drag temporarily overrides the lock.", "Кнопки и панель питомца заблокированы. Shift позволяет временно перемещать кнопки.") or P.Localized("Action and pet buttons unlocked: drag to rearrange outside combat.", "Кнопки и панель питомца разблокированы: перемещайте их вне боя.")) + P.MigrateExtraBars(true) +end + +local function uiRatio(f) + return f:GetEffectiveScale() / UIParent:GetEffectiveScale() +end + +local function frameEdge(f, method) + if f and f.IsForbidden and f:IsForbidden() then return end + local value = f and f[method] and f[method](f) + -- Target/focus aura layouts publish secret coordinates, even out of combat. + -- Never perform arithmetic on these; overlays reserve a fixed public area. + if issecretvalue and issecretvalue(value) then return end + return value and value * uiRatio(f) +end + +local function placeRelative(f, point, relative, relativePoint, x, y) + if not f or not relative then return end + -- Measure the neighbor, but anchor to UIParent. Never link protected action + -- frames into Blizzard's unprotected panel containers or mutate systemInfo. + local function axis(which, low, high) + if relativePoint:find(low) then return frameEdge(relative, which == "x" and "GetLeft" or "GetBottom") end + if relativePoint:find(high) then return frameEdge(relative, which == "x" and "GetRight" or "GetTop") end + local first = frameEdge(relative, which == "x" and "GetLeft" or "GetBottom") + local last = frameEdge(relative, which == "x" and "GetRight" or "GetTop") + return first and last and (first + last) / 2 + end + local rx, ry = axis("x", "LEFT", "RIGHT"), axis("y", "BOTTOM", "TOP") + if not rx or not ry then return end + local scale = uiRatio(f) + if f.GetPoint and (not f.GetNumPoints or f:GetNumPoints()==1) then + local p,r,rp,px,py=f:GetPoint(1) + if p==point and r==UIParent and rp=="BOTTOMLEFT" and px and py + and math.abs(px-(rx+x)/scale)<.01 and math.abs(py-(ry+y)/scale)<.01 then return end + end + -- These original methods avoid Edit Mode's shared snap/anchor bookkeeping. + local clear = f.ClearAllPointsBase or f.ClearAllPoints + local set = f.SetPointBase or f.SetPoint + clear(f) + set(f, point, UIParent, "BOTTOMLEFT", (rx + x) / scale, (ry + y) / scale) +end + +local chatBaseWidth,chatAppliedWidth +local function fitChat() + local chat=ChatFrame1 + if not chat or not MainActionBar then return end + local current=chat:GetWidth() + if not chatBaseWidth or (chatAppliedWidth and math.abs(current-chatAppliedWidth)>.5) then chatBaseWidth=current end + local left=frameEdge(chat,"GetLeft") or 20 + local right=frameEdge(MainActionBar,"GetLeft") + if not right then return end + local width=math.min(chatBaseWidth,math.max(240,(right-left-16)/uiRatio(chat))) + if math.abs(current-width)>.5 then chat:SetWidth(width) end + chatAppliedWidth=width +end + +local trackerBaseWidth,trackerAppliedWidth +local function fitTracker() + if not ObjectiveTrackerFrame or not ownsLayout() or InCombatLockdown() or EditModeManagerFrame:IsShown() then return end + local current=ObjectiveTrackerFrame:GetWidth() + if not trackerBaseWidth or (trackerAppliedWidth and math.abs(current-trackerAppliedWidth)>.5) then trackerBaseWidth=current end + local width=math.min(trackerBaseWidth,math.max(220,UIParent:GetWidth()-1134)/uiRatio(ObjectiveTrackerFrame)) + if math.abs(current-width)>.5 then ObjectiveTrackerFrame:SetWidth(width) end + trackerAppliedWidth=width + local top = frameEdge(ObjectiveTrackerFrame, "GetTop") + local clickTop = frameEdge(P.UtilityTop(), "GetTop") + if top and clickTop then + local available = math.max(80, (top - clickTop - 24) / uiRatio(ObjectiveTrackerFrame)) + local height = math.min(400, available) + if math.abs(ObjectiveTrackerFrame:GetHeight() - height) > 0.5 then ObjectiveTrackerFrame:SetHeight(height) end + end +end + +-- Match the short menu row to the bags using the original frame method. +-- Avoid Edit Mode's SetScale override and never mutate shared systemInfo. +local function alignCornerWidths() + if not BagsBar or not MicroMenuContainer then return end + local target = BagsBar:GetWidth() * uiRatio(BagsBar) + local menu = MicroMenuContainer + local current = menu:GetWidth() * uiRatio(menu) + local right, bottom = frameEdge(menu, "GetRight"), frameEdge(menu, "GetBottom") + if current > 0 and target > 0 and right and bottom and math.abs(current - target) > 0.1 then + local setScale = menu.SetScaleBase or menu.SetScale + setScale(menu, menu:GetScale() * target / current) + placeRelative(menu, "BOTTOMRIGHT", UIParent, "BOTTOMLEFT", right, bottom) + end +end + +-- Inventory opens inward of the quest column and above the action rows. All +-- anchors use measured UIParent coordinates, never protected action-bar parents. +local bagBaseScale, bagAppliedScale +local bagPlacing=false +local function positionCombinedBags() + local bag = ContainerFrameCombinedBags + if not ownsLayout() or InCombatLockdown() or EditModeManagerFrame:IsShown() then return end + if not bag or not bag:IsShown() or bag:GetParent() ~= UIParent then return end + local currentScale=bag:GetScale() + if not bagBaseScale or (bagAppliedScale and math.abs(currentScale-bagAppliedScale)>.001) then + bagBaseScale=currentScale + end + local screenWidth = UIParent:GetWidth() + local right = (frameEdge(MultiBarLeft, "GetLeft") or screenWidth - 280) - 20 + if ObjectiveTrackerFrame and ObjectiveTrackerFrame:IsShown() then + right = math.min(right, (frameEdge(ObjectiveTrackerFrame, "GetLeft") or right + 20) - 20) + end + local bottom = math.max(frameEdge(P.UtilityTop(), "GetTop") or 180, + frameEdge(MultiBar5 or MultiBarBottomRight, "GetTop") or 180) + 22 + local ratio = uiRatio(bag)*bagBaseScale/currentScale + local width, height = bag:GetWidth()*ratio, bag:GetHeight()*ratio + if width<=0 or height<=0 then return end + local target,fit=P.FindBagPosition(width,height,right-width,bottom) + P.bagUnplaced=not target + if not target then return end + local moved=math.abs((frameEdge(bag,"GetLeft") or -1)-target.left)>.5 + or math.abs((frameEdge(bag,"GetBottom") or -1)-target.bottom)>.5 + or math.abs(currentScale-bagBaseScale*fit)>.001 + bagPlacing=true + bagAppliedScale=bagBaseScale*fit + if math.abs(currentScale-bagAppliedScale)>.001 then bag:SetScale(bagAppliedScale) end + placeRelative(bag,"BOTTOMLEFT",UIParent,"BOTTOMLEFT",target.left,target.bottom) + bag:SetClampedToScreen(true) + bagPlacing=false + if moved then P.overlayRevision=(P.overlayRevision or 0)+1 end +end + +local bagQueued=false +local function queueCombinedBags() + if bagQueued or bagPlacing then return end + bagQueued=true + -- Never run Blizzard's bag manager from addon context. In particular bank + -- OnShow opens the backpack before its protected first-tab initialization. + -- Leave that native call stack alone; move only our visible bag afterward. + C_Timer.After(0,function() + bagQueued=false + positionCombinedBags() + P.PositionOverlayFrames() + end) +end + +local function refreshUILayout() + P.RefreshPetExtras() + if not ownsLayout() or InCombatLockdown() or EditModeManagerFrame:IsShown() then return end + P.MigrateExtraBars() + P.MigrateClassLayout() + placeRelative(MultiBarBottomLeft, "BOTTOMLEFT", MainActionBar, "TOPLEFT", 0, 4) + placeRelative(MultiBarBottomRight, "BOTTOMLEFT", MultiBarBottomLeft, "TOPLEFT", 0, 4) + alignCornerWidths() + placeRelative(BagsBar, "BOTTOMRIGHT", MicroMenuContainer, "TOPRIGHT", 0, 10) + placeRelative(MultiBarLeft, "BOTTOMRIGHT", BagsBar, "TOPRIGHT", 0, 14) + P.PositionExtraBars(placeRelative, frameEdge) + fitChat() + P.RefreshClassLayout(placeRelative, frameEdge, uiRatio) + P.PositionLeftBars(placeRelative, frameEdge) + P.PositionEncounterWidgets(placeRelative,frameEdge) + placeRelative(ObjectiveTrackerFrame, "TOPRIGHT", MinimapCluster, "BOTTOMRIGHT", 0, -24) + fitTracker() + P.PositionGroupFrames(placeRelative, frameEdge) + P.RefreshClassAssist() + P.RefreshDamageMeters() + queueCombinedBags() + P.PositionOverlayFrames() +end + +local function anchorTooltip(tooltip,settled) + if not ownsLayout() or EditModeManagerFrame:IsShown() or not MultiBarLeft then return end + P.PositionTooltip(tooltip,settled) +end + +local function installUILayoutHelpers() + if layoutHelpersInstalled then return end + layoutHelpersInstalled = true + P.InitializeOverlayLayout(placeRelative,frameEdge,function() + return ownsLayout() and not EditModeManagerFrame:IsShown() + end) + P.InitializeClassAssist(ownsLayout, placeRelative, frameEdge, put) + P.InitializeDamageMeters(ownsLayout, placeRelative, frameEdge, put) + local listener = CreateFrame("Frame") + local queued = false + local function queue() + if queued then return end + queued = true + C_Timer.After(0.3, function() + queued = false + if InCombatLockdown() then listener:RegisterEvent("PLAYER_REGEN_ENABLED"); return end + listener:UnregisterEvent("PLAYER_REGEN_ENABLED") + refreshUILayout() + end) + end + if UpdateContainerFrameAnchors then + hooksecurefunc("UpdateContainerFrameAnchors", function() + if InCombatLockdown() then listener:RegisterEvent("PLAYER_REGEN_ENABLED") + else queueCombinedBags() end + end) + end + local watchedBag + local function watchBag() + local bag=ContainerFrameCombinedBags + if not bag or watchedBag==bag then return end + watchedBag=bag + local function changed() + if bagPlacing then return end + P.overlayRevision=(P.overlayRevision or 0)+1 + if not bag:IsShown() then P.bagUnplaced=nil end + queueCombinedBags() + end + for _,script in ipairs({"OnShow","OnHide","OnSizeChanged"}) do bag:HookScript(script,changed) end + hooksecurefunc(bag,"SetPoint",queueCombinedBags) + end + watchBag() + local hookedClassFrames = {} + local function watchClassFrames() + for _, name in ipairs(P.classFrameNames) do + local f = _G[name] + if f and not hookedClassFrames[f] then + hookedClassFrames[f] = true + f:HookScript("OnShow", queue) + f:HookScript("OnSizeChanged", queue) + end + end + end + watchClassFrames() + -- Repair late native restores of the left shelf outside combat, including + -- reloads, layout changes, and bars becoming visible after a class change. + for _,name in ipairs({"MultiBar6","MultiBar7"}) do + local f=_G[name] + if f then + f:HookScript("OnShow",queue) + f:HookScript("OnSizeChanged",queue) + if f.OnUpdateSystem then hooksecurefunc(f,"OnUpdateSystem",queue) end + end + end + listener:RegisterEvent("EDIT_MODE_LAYOUTS_UPDATED") + for _, event in ipairs({"ADDON_LOADED", "PLAYER_ENTERING_WORLD", "UPDATE_SHAPESHIFT_FORMS", "UPDATE_SHAPESHIFT_FORM", "UPDATE_MULTI_CAST_ACTIONBAR", "SPELLS_CHANGED", "UNIT_PET", "GROUP_ROSTER_UPDATE"}) do + pcall(listener.RegisterEvent, listener, event) + end + if EditModeManagerFrame.UpdateBottomActionBarPositions then + hooksecurefunc(EditModeManagerFrame, "UpdateBottomActionBarPositions", queue) + end + listener:RegisterEvent("DISPLAY_SIZE_CHANGED") + listener:RegisterEvent("UI_SCALE_CHANGED") + listener:RegisterEvent("PLAYER_TARGET_CHANGED") + listener:RegisterEvent("PLAYER_FOCUS_CHANGED") + listener:SetScript("OnEvent", function(_, event, unit) + if event == "UNIT_PET" and unit ~= "player" then return end + if event=="PLAYER_TARGET_CHANGED" or event=="PLAYER_FOCUS_CHANGED" then + P.overlayRevision=(P.overlayRevision or 0)+1 + if InCombatLockdown() then listener:RegisterEvent("PLAYER_REGEN_ENABLED") + else queueCombinedBags() end + return + end + if event == "ADDON_LOADED" then watchClassFrames();watchBag() end + queue() + end) + UIParent:HookScript("OnSizeChanged", queue) + EditModeManagerFrame:HookScript("OnHide", queue) + hooksecurefunc(EditModeManagerFrame, "UpdateSystems", queue) + hooksecurefunc(ObjectiveTrackerFrame, "UpdateHeight", function() + if InCombatLockdown() then listener:RegisterEvent("PLAYER_REGEN_ENABLED") + else fitTracker() end + end) + local defaultTooltipOwner + local tooltipPlacing=false + local function managesTooltip(tooltip) + local owner = tooltip:GetOwner() + if not owner then return false end + if owner==defaultTooltipOwner or owner==UIParent or owner==WorldFrame then return true end + -- Bag/menu tooltips can use their own anchor instead of the default one. + for _ = 1, 8 do + if not owner then break end + if owner == BagsBar or owner == ContainerFrameCombinedBags or owner == MicroMenuContainer or owner == MainActionBar or owner == MultiBarBottomLeft or owner == MultiBarBottomRight or owner == MultiBarLeft or owner == MultiBarRight or owner == MultiBar5 or owner == MultiBar6 or owner == MultiBar7 or owner == PetActionBar or owner == StanceBar or owner == MultiCastActionBarFrame or owner == PossessActionBar then + return true + end + owner = owner:GetParent() + end + return false + end + local function restoreTooltipAnchor(tooltip,settled) + if tooltipPlacing or not managesTooltip(tooltip) then return end + tooltipPlacing=true + anchorTooltip(tooltip,settled) + tooltipPlacing=false + end + local tooltipQueued=false + local function queueTooltip(tooltip) + if tooltipQueued or tooltipPlacing then return end + tooltipQueued=true + C_Timer.After(0,function() + tooltipQueued=false + if not tooltip:IsShown() then + P.ResetTooltipPosition(tooltip) + defaultTooltipOwner=nil + else + restoreTooltipAnchor(tooltip,true) + end + end) + end + hooksecurefunc("GameTooltip_SetDefaultAnchor", function(tooltip,owner) + defaultTooltipOwner=owner or tooltip:GetOwner() + restoreTooltipAnchor(tooltip,false) + queueTooltip(tooltip) + end) + -- The native bag calculator runs on every item-tooltip refresh, after + -- SetOwner. Reclaim its anchor in the same call, before the next paint. + if ContainerFrameItemButton_CalculateItemTooltipAnchors then + hooksecurefunc("ContainerFrameItemButton_CalculateItemTooltipAnchors",function(_,tooltip) + if tooltip==GameTooltip then restoreTooltipAnchor(tooltip,false);queueTooltip(tooltip) end + end) + end + GameTooltip:HookScript("OnShow",function(tooltip) + if managesTooltip(tooltip) then restoreTooltipAnchor(tooltip,false);queueTooltip(tooltip) end + end) + GameTooltip:HookScript("OnSizeChanged",queueTooltip) + -- SetOwner may hide/show during a refresh. Reset only if it remains hidden + -- after that native call, not on the intermediate OnHide event. + GameTooltip:HookScript("OnHide",queueTooltip) + hooksecurefunc(GameTooltip,"SetPoint",function() + -- A deferred repair alone can show the native position for a frame. + -- Restore only the cached anchor here; defer measuring rebuilt text. + restoreTooltipAnchor(GameTooltip,false) + queueTooltip(GameTooltip) + end) + for _,name in ipairs({"ShoppingTooltip1","ShoppingTooltip2"}) do + local comparison=_G[name] + if comparison then + for _,script in ipairs({"OnShow","OnHide","OnSizeChanged"}) do + comparison:HookScript(script,function() queueTooltip(GameTooltip) end) + end + end + end + if GameTooltip_ShowCompareItem then + hooksecurefunc("GameTooltip_ShowCompareItem",function(tooltip) + if not tooltip or tooltip==GameTooltip then + restoreTooltipAnchor(GameTooltip,true) + queueTooltip(GameTooltip) + end + end) + end + queue() +end + +local function seedClickBar() + if RuenUICharacter.clickBarSeeded or InCombatLockdown() or GetCursorInfo() then return end + local pickup = C_Item and C_Item.PickupItem or PickupItem + if not pickup or not C_Item or not C_Item.GetItemInfoInstant then return end + local items, seen, empty = {}, {}, {} + local function add(id, hearth) + if not id or seen[id] then return end + local _, _, _, _, _, class, subclass = C_Item.GetItemInfoInstant(id) + if hearth or (class == 0 and subclass == 5) then + seen[id] = true; items[#items + 1] = id + end + end + local count = C_Item.GetItemCount or GetItemCount + for i = 1, 12 do + local button = _G["MultiBarLeftButton" .. i] + if button and button.action then + local kind, id = GetActionInfo(button.action) + if not kind then empty[#empty + 1] = button.action + elseif kind == "item" then seen[id] = true end + end + end + if count and count(6948) > 0 then add(6948, true) end + if C_Container then + for bag = 0, 4 do + for slot = 1, C_Container.GetContainerNumSlots(bag) do + add(C_Container.GetContainerItemID(bag, slot)) + end + end + end + RuenUICharacter.seededClickSlots = RuenUICharacter.seededClickSlots or {} + local slotIndex = 1 + for _, id in ipairs(items) do + local destination = empty[slotIndex] + if not destination then break end + -- Recheck both cursor and destination; never replace another assignment. + if GetCursorInfo() or GetActionInfo(destination) then return end + pickup(id) + local kind, cursorID = GetCursorInfo() + if kind == "item" and cursorID == id then + PlaceAction(destination) + local placedKind, placedID = GetActionInfo(destination) + if placedKind == "item" and placedID == id then + RuenUICharacter.seededClickSlots[destination] = id + slotIndex = slotIndex + 1 + end + end + ClearCursor() + end + RuenUICharacter.clickBarSeeded = true +end + +local function restoreClickBar() + if GetCursorInfo() then return end + for slot, id in pairs(RuenUICharacter.seededClickSlots or {}) do + local kind, currentID = GetActionInfo(slot) + if kind == "item" and currentID == id then PickupAction(slot); ClearCursor() end + end +end + +local function configureLayout() + local manager = EditModeManagerFrame + if not manager or not manager.layoutInfo or not EditModePresetLayoutManager then + error("Edit Mode is not ready; use /ruen apply after loading") + end + if RuenUICharacter.oldLayout == nil then RuenUICharacter.oldLayout = manager.layoutInfo.activeLayout end + for i, layout in ipairs(manager:GetLayouts()) do + if P.IsOurLayout(layout) then + C_EditMode.SetActiveLayout(i) + RuenUIDB.layoutExport = C_EditMode.ConvertLayoutInfoToString(layout) + return + end + end + if manager:AreLayoutsOfTypeMaxed(Enum.EditModeLayoutType.Account) then error("account Edit Mode layouts are full; none removed") end + local layout = CopyTable(EditModePresetLayoutManager:GetCopyOfPresetLayouts()[1]) + local E, A, U = Enum.EditModeSystem, Enum.EditModeActionBarSetting, Enum.EditModeUnitFrameSystemIndices + for _, system in ipairs(layout.systems) do + local index = system.systemIndex + if system.system == E.ActionBar and index and index <= 5 then + changeSetting(system, A.NumIcons, 12) + changeSetting(system, A.IconPadding, 2) + changeSetting(system, A.VisibleSetting, Enum.ActionBarVisibleSetting.Always) + changeSetting(system, A.Orientation, Enum.ActionBarOrientation.Horizontal) + if index <= 3 then + changeSetting(system, A.AlwaysShowButtons, 1) + changeSetting(system, A.NumRows, 1) + changeSetting(system, A.IconSize, 4) -- 90%, encoded (90-50)/10 + anchor(system, "BOTTOM", "BOTTOM", 0, 48 + (index - 1) * 42) + else + changeSetting(system, A.AlwaysShowButtons, 1) -- visible, unbound click slots + changeSetting(system, A.NumRows, 2) -- six columns, two rows + changeSetting(system, A.IconSize, 4) -- 90%, comfortable mouse targets + anchor(system, "BOTTOMRIGHT", "BOTTOMRIGHT", -22, 100) + end + if index == 1 then + changeSetting(system, A.HideBarArt, 1) + changeSetting(system, A.HideBarScrolling, 1) + end + elseif system.system == E.ActionBar and index == Enum.EditModeActionBarSystemIndices.PetActionBar then + changeSetting(system, A.IconSize, P.petIconSize) + anchor(system, "BOTTOM", "BOTTOM", 0, 185) + elseif system.system == E.ActionBar and index == Enum.EditModeActionBarSystemIndices.StanceBar then + changeSetting(system, A.IconSize, 3) + anchor(system, "BOTTOMRIGHT", "BOTTOM", -250, 185) + elseif system.system == E.MainActionBarEndCap then + changeSetting(system, Enum.EditModeMainActionBarEndCapSetting.Hidden, 1) + elseif system.system == E.UnitFrame then + if index == U.Player then anchor(system, "BOTTOMRIGHT", "BOTTOM", -110, 258) + elseif index == U.Target then anchor(system, "BOTTOMLEFT", "BOTTOM", 110, 258) + elseif index == U.Focus then anchor(system, "BOTTOMLEFT", "BOTTOM", 110, 340) + elseif index == U.Party then + changeSetting(system, Enum.EditModeUnitFrameSetting.UseRaidStylePartyFrames, 1) + anchor(system, "LEFT", "LEFT", 25, 25) + end + elseif system.system == E.CastBar then + anchor(system, "BOTTOM", "BOTTOM", 0, 228) + elseif system.system == E.StatusTrackingBar then + changeSetting(system, Enum.EditModeStatusTrackingBarSetting.Size, 0) -- native minimum 50% + anchor(system, "BOTTOM", "BOTTOM", 0, (index == 1) and 5 or 24) + elseif system.system == E.MicroMenu then + changeSetting(system, Enum.EditModeMicroMenuSetting.Size, 2) -- 80% + anchor(system, "BOTTOMRIGHT", "BOTTOMRIGHT", -22, 8) + elseif system.system == E.Bags then + changeSetting(system, Enum.EditModeBagsSetting.Size, 1) -- 80% + anchor(system, "BOTTOMRIGHT", "BOTTOMRIGHT", -22, 50) + elseif system.system == E.ObjectiveTracker then + changeSetting(system, Enum.EditModeObjectiveTrackerSetting.Height, 0) -- native minimum, 400 UI units + anchor(system, "TOPRIGHT", "TOPRIGHT", -22, -322) + elseif system.system == E.Minimap then + changeSetting(system, Enum.EditModeMinimapSetting.Size, 4) -- 90% + anchor(system, "TOPRIGHT", "TOPRIGHT", -22, -40) + elseif system.system == E.ChatFrame then + changeSetting(system, Enum.EditModeChatFrameSetting.WidthHundreds, 3) + changeSetting(system, Enum.EditModeChatFrameSetting.WidthTensAndOnes, 80) + changeSetting(system, Enum.EditModeChatFrameSetting.HeightHundreds, 1) + changeSetting(system, Enum.EditModeChatFrameSetting.HeightTensAndOnes, 50) + anchor(system, "BOTTOMLEFT", "BOTTOMLEFT", 20, 45) + end + end + P.ConfigureClassSystems(layout) + P.ConfigureClassAssistSystems(layout) + P.ConfigureExtraBars(layout) + manager:CreateLayoutTbls() + manager:MakeNewLayout(layout, Enum.EditModeLayoutType.Account, P.layoutName, false) + for i, saved in ipairs(manager:GetLayouts()) do + if P.IsOurLayout(saved) then + C_EditMode.SetActiveLayout(i) + RuenUIDB.layoutExport = C_EditMode.ConvertLayoutInfoToString(saved) + return + end + end + error("Edit Mode did not save the new layout") +end + +local function setBarVisibility(bars) + -- The Blizzard Settings proxy owns the cached value AND the refresh callback. + -- Raw SetActionBarToggles alone changes server state without updating frames. + for i = 1, 7 do + local key = "PROXY_SHOW_ACTIONBAR_" .. (i + 1) + assert(Settings.GetSetting(key), "Action bar settings not ready") + Settings.SetValue(key, bars[i] and true or false) + end + MultiActionBar_Update() +end + +local function recordLayoutStatus(announce) + local status = {bars = {}, time = time(), verified = true, release=P.release, + uiWidth=UIParent:GetWidth(),uiHeight=UIParent:GetHeight(),uiScale=UIParent:GetEffectiveScale()} + status.cooldowns={} + for _,name in ipairs({"EssentialCooldownViewer","UtilityCooldownViewer","BuffIconCooldownViewer","BuffBarCooldownViewer"}) do + local f=_G[name] + if f then status.cooldowns[name]={shown=f:IsShown(),visibleSetting=f.visibleSetting, + systemIndex=f.systemIndex,settings=f.systemInfo and CopyTable(f.systemInfo.settings), + left=frameEdge(f,"GetLeft"),bottom=frameEdge(f,"GetBottom"),width=f:GetWidth(),height=f:GetHeight()} end + end + for _, name in ipairs({"MainActionBar", "MultiBarBottomLeft", "MultiBarBottomRight", "MultiBar5", "MultiBarLeft", "MultiBarRight", "MultiBar6", "MultiBar7"}) do + local bar = _G[name] + local shown = bar and bar:IsShown() or false + local info = {shown = shown} + if bar then + info.width, info.height = bar:GetSize() + info.left, info.bottom = bar:GetLeft(), bar:GetBottom() + end + status.bars[name] = info + if not shown then status.verified = false end + end + local manager = EditModeManagerFrame + local active = manager and manager:GetActiveLayoutInfo() + status.movement = {E = GetBindingAction("E"), S = GetBindingAction("S"), D = GetBindingAction("D"), F = GetBindingAction("F")} + status.controlsVersion = (GetCurrentBindingSet() == 1 and RuenUIDB or RuenUICharacter).controlsVersion + status.utilityBindings = {} + for _, key in ipairs({"`", "BUTTON3", "BUTTON4", "BUTTON5", "SPACE", "N", "M", "I", "L", "P", "F8"}) do + status.utilityBindings[key] = GetBindingAction(key) + end + if ContainerFrameCombinedBags and ContainerFrameCombinedBags:IsShown() then + status.bagWindow = {left = frameEdge(ContainerFrameCombinedBags, "GetLeft"), + right = frameEdge(ContainerFrameCombinedBags, "GetRight"), + bottom = frameEdge(ContainerFrameCombinedBags, "GetBottom"), top = frameEdge(ContainerFrameCombinedBags, "GetTop")} + end + status.thirdTargetShown = RuenTargetTargetTarget and RuenTargetTargetTarget:IsShown() or false + status.layout = active and active.layoutName or "unknown" + if status.layout ~= P.layoutName then status.verified = false end + status.frames, status.overlaps = {}, {} + for _, name in ipairs({"MainActionBar", "MultiBarBottomLeft", "MultiBarBottomRight", "MultiBar5", "MultiBarLeft", "MultiBarRight", "MultiBar6", "MultiBar7", "ChatFrame1", "BagsBar", "MicroMenuContainer", "MinimapCluster", "ObjectiveTrackerFrame", "ContainerFrameCombinedBags", "GameTooltip", "ShoppingTooltip1", "ShoppingTooltip2"}) do + local f = _G[name] + if f then + status.frames[name] = {shown=f:IsShown(), left = frameEdge(f, "GetLeft"), right = frameEdge(f, "GetRight"), bottom = frameEdge(f, "GetBottom"), top = frameEdge(f, "GetTop")} + end + end + for _, pair in ipairs({{"BagsBar", "MicroMenuContainer"}, {"MultiBarLeft", "BagsBar"}, {"MinimapCluster", "ObjectiveTrackerFrame"}, {"ObjectiveTrackerFrame", "MultiBarLeft"}, {"MultiBarBottomLeft", "MainActionBar"}, {"MultiBarBottomRight", "MultiBarBottomLeft"}}) do + local upper, lower = status.frames[pair[1]], status.frames[pair[2]] + if upper and lower and upper.bottom and lower.top and upper.bottom < lower.top - 1 then + status.overlaps[#status.overlaps + 1] = pair[1] .. "/" .. pair[2] + status.verified = false + end + end + status.classLayoutVersion = RuenUIDB.classLayoutVersion + status.intentionalOverlaps={} + if P.bagOverHUD and ContainerFrameCombinedBags and ContainerFrameCombinedBags:IsShown() then status.intentionalOverlaps[#status.intentionalOverlaps+1]="Oversized inventory temporarily covers HUD information; action/chat/quest controls remain clear" end + if P.tooltipOverInventory then status.intentionalOverlaps[#status.intentionalOverlaps+1]="Comparison tooltips over other inventory slots (hovered item kept clear)" end + if P.tooltipOverSocial then status.intentionalOverlaps[#status.intentionalOverlaps+1]="Large tooltip over chat/social space because no fully clear position fits" end + for alert in pairs(P.overlayOverChat or {}) do + status.intentionalOverlaps[#status.intentionalOverlaps+1]=(alert:GetName() or "Alert").." temporarily over chat in a crowded layout" + end + for alert in pairs(P.overlayOverOptional or {}) do status.intentionalOverlaps[#status.intentionalOverlaps+1]=(alert:GetName() or "Alert").." temporarily over optional cooldown/meter area in a crowded layout" end + status.attachments=P.AttachedHUDRegions() + status.classFrames = {} + local combatNames = {"MainActionBar", "MultiBarBottomLeft", "MultiBarBottomRight", "MultiBar5", "MultiBarLeft", "MultiBarRight", "MultiBar6", "MultiBar7", "BagsBar", "MicroMenuContainer"} + for _, name in ipairs(P.classFrameNames) do + local f = _G[name] + if f then + status.classFrames[name] = {shown = f:IsShown(), left = frameEdge(f, "GetLeft"), + right = frameEdge(f, "GetRight"), bottom = frameEdge(f, "GetBottom"), top = frameEdge(f, "GetTop")} + end + end + for _,issue in ipairs(P.OverlayAudit()) do + status.overlaps[#status.overlaps+1]=issue + status.verified=false + end + local function intersects(a, b) + return a and b and a.left and a.right and a.bottom and a.top and b.left and b.right and b.bottom and b.top + and math.min(a.right, b.right) - math.max(a.left, b.left) > 1 + and math.min(a.top, b.top) - math.max(a.bottom, b.bottom) > 1 + end + for name, rect in pairs(status.classFrames) do + if rect.shown then + for _, other in ipairs(combatNames) do + local f = _G[other] + if f and f:IsShown() and intersects(rect, status.frames[other]) then + status.overlaps[#status.overlaps + 1] = name .. "/" .. other + status.verified = false + end + end + end + end + status.graphics = {} + for _, entry in ipairs(P.graphics) do status.graphics[entry[1]] = C_CVar.GetCVar(entry[1]) end + for _, key in ipairs({"GxApi", "GxFullscreenResolution", "useUiScale", "uiScale", "shadowTextureSize", "shadowNumCascades", "farclip", "groundEffectDist", "gxTripleBuffer", "graphicsOutlineMode", "textureFilteringMode", "ffxGlow"}) do + status.graphics[key] = C_CVar.GetCVar(key) + end + if GetFramerate then status.fps = GetFramerate() end + if C_VoiceChat and C_VoiceChat.GetTtsVoices then + local ok, voices = pcall(C_VoiceChat.GetTtsVoices) + if ok then status.ttsVoices = voices end + end + RuenUICharacter.verification = status + if announce then + say("Ruen UI "..P.release.."; UI "..math.floor(status.uiWidth).." x "..math.floor(status.uiHeight)..". Cooldowns: "..(RuenUIDB.cooldownsMode or "auto")..".") + for _,note in ipairs(status.intentionalOverlaps) do say(note) end + if status.verified then + say("ESDF ready: Q W R T / A G H / Z X C V B. Rows bottom to top: base, Shift, Ctrl, Alt. Utility bars are above bags and chat. /ruen bars lists shortcuts; /ruen lock or unlock controls dragging.") + else + say("Layout needs a spacing check: " .. table.concat(status.overlaps, ", ") .. ". /ruen status checks again.") + end + end +end + +local function mask(key, enum, names) + if not enum or saveCVar(key) == nil then return end + local value = tonumber(C_CVar.GetCVar(key)) or 0 + for _, name in ipairs(names) do + local flag = enum[name] + if flag and flag > 0 then value = bit.bor(value, bit.lshift(1, flag - 1)) end + end + put(key, value) +end +local function apply() + if InCombatLockdown() then say("Wait until combat ends, then /ruen apply."); return end + P.InitializeGunAudio() + RuenUIDB.results = RuenUIDB.results or {} + if RuenUIDB.graphicsVersion ~= (P.graphicsVersion or P.version) then + applyList(P.graphics) + RuenUIDB.graphicsVersion = P.graphicsVersion or P.version + end + applyList(P.gameplay) + put("softTargetInteract", Enum.SoftTargetEnableFlags.Any) + mask("nameplateStackingTypes", Enum.NamePlateStackType, {"Enemy"}) + mask("nameplateThreatDisplay", Enum.NamePlateThreatDisplay, {"Progressive", "HealthBarColor"}) + if C_Minimap and MinimapUtil and Enum.MinimapTrackingFilter then + local filter = Enum.MinimapTrackingFilter.TrivialQuests + local index = MinimapUtil.GetFilterIndexForFilterID(filter) + if index then + if RuenUICharacter.oldTrivial == nil then RuenUICharacter.oldTrivial = not C_Minimap.IsFilteredOut(filter) end + C_Minimap.SetTracking(index, true) + end + end + if not RuenUICharacter.oldBars then RuenUICharacter.oldBars = {GetActionBarToggles()} end + local bars = {GetActionBarToggles()} + for i=1,7 do bars[i]=true end + -- Retain existing extra bars and refresh Blizzard's cached visibility settings. + setBarVisibility(bars) + setupThirdTarget() + applyCombatBindings() + P.ApplyExtraBindings(true) + local ok, err = pcall(configureLayout) + RuenUICharacter.layoutStatus = ok and "saved" or tostring(err) + if not ok then say("Bars enabled; layout needs attention: " .. tostring(err)); return end + RuenUICharacter.version = P.version + C_Timer.After(1, function() + refreshUILayout() + local seeded, seedError = pcall(seedClickBar) + if not seeded then say("Click bar is ready; drag items into its empty slots. " .. tostring(seedError)) end + recordLayoutStatus(true) + say("Settings saved. Type /reload once to finish native frame setup.") + end) +end +local function restore() + if InCombatLockdown() then say("Leave combat before restoring."); return end + if RuenUIDB.optimizer then P.OptimizerCommand("restore") end + P.StopGunAudio() + P.StopSwingTimers() + P.StopDamageMeters() + P.RestoreClassAssist() + for key, value in pairs(RuenUIDB.original) do pcall(C_CVar.SetCVar, key, value) end + for key, value in pairs(RuenUICharacter.original) do pcall(C_CVar.SetCVar, key, value) end + if Settings.GetSetting("lockActionBars") then + Settings.SetValue("lockActionBars",C_CVar.GetCVar("lockActionBars")=="1") + end + if RuenUICharacter.oldBars then setBarVisibility(RuenUICharacter.oldBars) end + if RuenUICharacter.oldLayout then pcall(C_EditMode.SetActiveLayout, RuenUICharacter.oldLayout) end + if RuenUICharacter.oldTrivial ~= nil then + local index = MinimapUtil.GetFilterIndexForFilterID(Enum.MinimapTrackingFilter.TrivialQuests) + if index then C_Minimap.SetTracking(index, RuenUICharacter.oldTrivial) end + end + restoreClickBar() + restoreCombatBindings() + if RuenUIDB.oldSelfCast and SetModifiedClick then + if Settings.GetSetting("SELFCAST") then Settings.SetValue("SELFCAST",RuenUIDB.oldSelfCast) + else SetModifiedClick("SELFCAST",RuenUIDB.oldSelfCast) end + end + for key, action in pairs(RuenUICharacter.addedBindings or {}) do + if GetBindingAction(key) == action then SetBinding(key) end + end + SaveBindings(GetCurrentBindingSet()) + RuenUIDB.disabled = true + P.RefreshPetExtras() + local addonRestore = false + for variable, original in pairs(RuenUIDB.addonOriginal or {}) do + _G[variable] = CopyTable(original) + addonRestore = true + end + if RuenUICharacter.oldVoiceQuestCharDB then + VoiceQuestCharDB = CopyTable(RuenUICharacter.oldVoiceQuestCharDB) + addonRestore = true + end + say("Original settings restored for this character; automatic setup disabled account-wide. The extra saved layout is retained for reuse.") + if addonRestore then say("Type /reload once to finish restoring addon preferences.") end +end +local function bench() + if ticker then say("An FPS sample is already running."); return end + local samples, total, below = {}, 0, 0 + say("Sampling FPS once per second for 3 minutes. Play normally and keep WoW focused.") + ticker = C_Timer.NewTicker(1, function() + local fps = GetFramerate() + samples[#samples + 1] = fps; total = total + fps + if fps < 30 then below = below + 1 end + if #samples == 180 then + ticker:Cancel(); ticker = nil + table.sort(samples) + local r = {time = time(), count = 180, mean = total / 180, minimum = samples[1], p10 = samples[18], below30 = below, note = "1-second FPS readings, not a per-frame 1% low"} + local reports = RuenUIDB.reports + reports[#reports + 1] = r + while #reports > 5 do table.remove(reports, 1) end + say(string.format("FPS sample: avg %.1f, minimum %.1f, 10th percentile %.1f; %d/180 readings below 30. Saved on logout/reload.", r.mean, r.minimum, r.p10, below)) + end + end) +end +SLASH_RUENUI1 = "/ruen" +SLASH_RUENUI2 = "/ruenui" +SlashCmdList.RUENUI = function(message) + init() + message = message:lower():match("^%s*(.-)%s*$") + local command, argument = message:match("^(%S+)%s*(.-)$") + if message == "unlock" or message == "lock" then + setSlotsLocked(message == "lock"); return + elseif message == "bars" then say(P.BarHelp()); return + elseif command == "cooldowns" or command == "mouseover" then say(P.ClassAssistCommand(command,argument)); return + elseif command == "guns" then + local reply = P.GunAudioCommand(argument) + if reply then say(reply) end + return + elseif command == "meters" then say(P.DamageMeterCommand(argument)); return + elseif command == "optimize" then P.OptimizerCommand(argument); return + elseif message == "swing" or message:match("^swing%s") then + say(P.SwingCommand(message:match("^swing%s+(%S+)") or "status")); return + end + if message == "" or message == "help" then P.Help(); return + elseif command == "language" or command == "lang" then + if argument == "" then P.LanguageStatus() else P.SetLanguage(argument, false) end + return + elseif command == "voice" then + if argument == "" then P.LanguageStatus() else P.SetLanguage(argument, true) end + return + elseif message == "bindings" then + if InCombatLockdown() then say("Reapply bindings after combat.") else P.ApplyUtilityBindings(true); P.ApplyExtraBindings(true) end + return + elseif message == "pet auto" then + if P.ResetPetExtras() then say(P.Localized("Extra pet buttons use automatic overflow again.","Дополнительные кнопки питомца снова выбираются автоматически.")) + else say(P.Localized("Change pet buttons after combat.","Измените кнопки питомца после боя.")) end + return + elseif message == "bags" then + if InCombatLockdown() then say("Reposition bags after combat.") + else queueCombinedBags() end + return + end + if message == "apply" then RuenUIDB.disabled = nil; apply() + elseif message == "restore" then restore() + elseif message == "bench" then bench() + elseif message == "status" then recordLayoutStatus(true) + elseif message == "balanced" or message == "performance" then + if InCombatLockdown() then say("Leave combat before changing graphics."); return end + P.StopOptimizer() + RuenUIDB.results = RuenUIDB.results or {} + applyList(P.graphics) + if message == "performance" then applyList(P.performance) end + say(message .. " graphics applied at 100% render scale; use /ruen bench to measure.") + elseif message == "export" then + local manager = EditModeManagerFrame + if manager and manager:GetActiveLayoutInfo() then + local text = C_EditMode.ConvertLayoutInfoToString(manager:GetActiveLayoutInfo()) + RuenUIDB.layoutExport = text + if CopyToClipboard then CopyToClipboard(text) end + say("Current native layout copied; also available through Edit Mode > Share > Copy to Clipboard.") + end + else + say("/ruen apply | status | balanced | performance | bench | export | restore. Setup runs once per character. The small third-target display refreshes only while visible.") + end +end +frame:RegisterEvent("PLAYER_ENTERING_WORLD") +local function setupAfterLogin() + if InCombatLockdown() then frame:RegisterEvent("PLAYER_REGEN_ENABLED"); return end + frame:UnregisterEvent("PLAYER_REGEN_ENABLED") + init() + P.InitializeGunAudio() + if RuenUIDB.disabled then return end + local ok, err = pcall(function() + P.MigrateBrand() + setupThirdTarget() + P.InitializeSwingTimers(function() + return ownsLayout() and not EditModeManagerFrame:IsShown() + end) + if RuenUIDB.unlockedSlotsVersion ~= 1 then setSlotsLocked(false) end + P.InitializePetExtras(function() + return ownsLayout() and not EditModeManagerFrame:IsShown() + end) + installUILayoutHelpers() + P.InitializeOptimizer() + if RuenUIDB.graphicsVersion ~= P.graphicsVersion then + RuenUIDB.results = RuenUIDB.results or {} + applyList(P.graphics) + RuenUIDB.graphicsVersion = P.graphicsVersion + say("Long-session graphics applied: 60 FPS cap, lighter effects/distance, 100% render scale.") + end + -- Apply the chat preference to existing installs without resetting the + -- UI profile. Preserve the old value for /ruen restore and honor later + -- manual changes after this one-time upgrade. + if RuenUIDB.chatFilterVersion ~= 1 then + RuenUIDB.results = RuenUIDB.results or {} + put("profanityFilter", 0) + if C_CVar.GetCVar("profanityFilter") == "0" then RuenUIDB.chatFilterVersion = 1 end + end + local changed = applyAddonPresets() + P.InitializeLanguage() + P.ApplyUtilityBindings(false) + P.ApplyExtraBindings(false) + if RuenUICharacter.version ~= P.version then apply() + else + C_Timer.After(1, function() + refreshUILayout() + local seeded, seedError = pcall(seedClickBar) + if not seeded then say("Click bar: " .. tostring(seedError)) end + recordLayoutStatus(false) + end) + end + if changed then + say("Addon preferences saved. Type /reload once to finish setup.") + end + end) + if not ok then say("Setup paused: " .. tostring(err) .. ". /ruen apply retries native UI setup.") end +end +frame:SetScript("OnEvent", function(self, event) + self:UnregisterEvent(event) + if event == "PLAYER_ENTERING_WORLD" then + C_Timer.After(3, setupAfterLogin) + else + setupAfterLogin() + end +end) diff --git a/RuenUI/DamageMeters.lua b/RuenUI/DamageMeters.lua new file mode 100644 index 0000000..59ebf8b --- /dev/null +++ b/RuenUI/DamageMeters.lua @@ -0,0 +1,199 @@ +local _, P = ... + +-- Use Blizzard's collection, session selector and localized view menus. No +-- combat-log parser, secure handler replacement or per-frame layout polling. +local owns, place, edge, put, queue +local busy, queued, managed, hooked = false, false, nil, {} + +local function editing() + return EditModeManagerFrame and EditModeManagerFrame:IsShown() +end + +local function mode() + return RuenUIDB and RuenUIDB.damageMeterMode or "auto" +end + +function P.WantsDamageMeters() + if mode() == "off" then return false end + if mode() == "show" then return true end + local inside, kind = IsInInstance() + return inside and (kind == "party" or kind == "raid") or false +end + +local function snapshot(meter) + local old = {visibility = meter.visibility, + layout = EditModeManagerFrame.layoutInfo.activeLayout, + width = meter:GetWidth(), height = meter:GetHeight(), points = {}} + for i = 1, meter:GetNumPoints() do old.points[i] = {meter:GetPoint(i)} end + return old +end + +-- Never assign meter.visibility/systemInfo or call its Lua refresh methods. +-- Even out of combat, those writes taint the later native session timer. +-- Serialize a detached layout through the engine; Blizzard applies the resulting +-- EDIT_MODE_LAYOUTS_UPDATED event in its own clean execution context. +local function setVisibility(value) + local info = P.CopyEditModeLayouts() + local layout = info.layouts and info.layouts[info.activeLayout] + if not P.IsOurLayout(layout) then return false end + for _, system in ipairs(layout.systems or {}) do + if system.system == Enum.EditModeSystem.DamageMeter then + local key = Enum.EditModeDamageMeterSetting.Visibility + local setting + for _, item in ipairs(system.settings or {}) do + if item.setting == key then setting = item; break end + end + if setting and setting.value == value then return true end + if setting then setting.value = value else + system.settings = system.settings or {} + system.settings[#system.settings + 1] = {setting = key, value = value} + end + P.SaveEditModeLayouts(info) + return true, true + end + end + return false +end + +local function release() + local meter, old = DamageMeter, managed + managed = nil + if not meter or not old then return end + -- A different layout may have already supplied its own anchors/settings. + local manager = EditModeManagerFrame + local sameLayout = manager.layoutInfo.activeLayout == old.layout + and P.IsOurLayout(manager:GetActiveLayoutInfo()) + if sameLayout then + meter:SetSize(old.width, old.height) + local clear, set = meter.ClearAllPointsBase or meter.ClearAllPoints, meter.SetPointBase or meter.SetPoint + clear(meter) + for _, p in ipairs(old.points) do set(meter, unpack(p)) end + if not editing() and old.visibility ~= nil then setVisibility(old.visibility) end + end +end + +local function hookMeter(meter) + if hooked[meter] then return end + hooked[meter] = true + -- Native Edit Mode can reapply visibility/geometry at login or on layout + -- changes. Reconcile later, outside its call stack; never rewrite systemInfo. + for _, method in ipairs({"UpdateSystemSettingVisibility", "OnUpdateSystem"}) do + if meter[method] then hooksecurefunc(meter, method, queue) end + end + meter:HookScript("OnSizeChanged", queue) +end + +function P.PositionDamageMeters() + local meter = DamageMeter + if not meter or not managed or InCombatLockdown() or editing() then return end + local obstacles = {} + for _, r in ipairs(P.OverlayObstacles(false)) do + if r.name ~= "DamageMeter" then obstacles[#obstacles + 1] = r end + end + -- Preserve the central play field. Prefer the right edge above utility + -- buttons, then the nearest genuinely free rectangle in the existing HUD. + local x = (edge(P.UtilityTop(), "GetRight") or UIParent:GetWidth() - 22) - 260 + local y = (edge(P.UtilityTop(), "GetTop") or 260) + 12 + local target, width, height + for _, size in ipairs({{260, 172}, {240, 152}, {220, 132}}) do + width, height = size[1], size[2] + target = P.FindOverlayPosition(width, height, x, y, obstacles, UIParent:GetWidth(), UIParent:GetHeight()) + if target then break end + end + if not target then + -- Never cover an action or unit frame if an exceptionally crowded + -- layout cannot fit even the compact window. Retry after layout events. + RuenUICharacter.damageMeterStatus.reason = "no free space" + return false + end + local ratio = meter:GetEffectiveScale() / UIParent:GetEffectiveScale() + local changed = math.abs(meter:GetWidth() * ratio - width) > .5 + or math.abs(meter:GetHeight() * ratio - height) > .5 + if changed then meter:SetSize(width / ratio, height / ratio) end + local left, bottom = edge(meter, "GetLeft"), edge(meter, "GetBottom") + if not left or not bottom or math.abs(left - target.left) > .5 or math.abs(bottom - target.bottom) > .5 then + place(meter, "BOTTOMLEFT", UIParent, "BOTTOMLEFT", target.left, target.bottom) + end + RuenUICharacter.damageMeterStatus.rect = target + return true +end + +function P.RefreshDamageMeters() + if busy or not owns then return end + if InCombatLockdown() then + P.damageMeterListener:RegisterEvent("PLAYER_REGEN_ENABLED") + return + end + busy = true + local meter = DamageMeter + if not owns() or editing() then + release() + elseif meter and Enum.DamageMeterVisibility and C_DamageMeter then + hookMeter(meter) + if not managed then managed = snapshot(meter) end + local want = P.WantsDamageMeters() + if want and C_CVar.GetCVar("damageMeterEnabled") ~= "1" then + RuenUIDB.results = RuenUIDB.results or {} + put("damageMeterEnabled", 1) + end + local available, reason = C_DamageMeter.IsDamageMeterAvailable() + RuenUICharacter.damageMeterStatus = {mode = mode(), requested = want, available = available, reason = reason} + local show = want and available and P.PositionDamageMeters() + local ready, changed = setVisibility(show and Enum.DamageMeterVisibility.Always or Enum.DamageMeterVisibility.Hidden) + if not ready then + RuenUICharacter.damageMeterStatus.reason = "native layout not ready" + end + -- Selecting the serialized layout can also restore its saved anchors. + if changed and show then P.PositionDamageMeters() end + RuenUICharacter.damageMeterStatus.shown = meter:IsShown() + if issecurevariable then + RuenUICharacter.damageMeterStatus.nativeVisibilitySecure = issecurevariable(meter, "visibility") + end + else + RuenUICharacter.damageMeterStatus = {mode = mode(), reason = "native meter unavailable"} + end + busy = false +end + +function P.StopDamageMeters() + if InCombatLockdown() then return end + busy = true + release() + busy = false +end + +function P.DamageMeterCommand(argument) + if argument == "auto" or argument == "show" or argument == "off" then + RuenUIDB.damageMeterMode = argument + P.RefreshDamageMeters() + end + return P.Localized("Damage meter: ", "Счётчик урона: ") .. mode() .. P.Localized( + ". /ruen meters auto (dungeons/raids), show (everywhere), off. Changes during combat wait until it ends.", + ". /ruen meters auto (подземелья/рейды), show (везде), off (скрыть). Изменения в бою применяются после боя.") +end + +function P.InitializeDamageMeters(isOurs, placeFrame, frameEdge, setCVar) + owns, place, edge, put = isOurs, placeFrame, frameEdge, setCVar + if P.damageMeterListener then return end + local listener = CreateFrame("Frame") + P.damageMeterListener = listener + queue = function() + if busy or queued then return end + queued = true + C_Timer.After(.2, function() + queued = false + P.RefreshDamageMeters() + if P.PositionOverlayFrames then P.PositionOverlayFrames() end + end) + end + for _, event in ipairs({"PLAYER_ENTERING_WORLD", "ZONE_CHANGED_NEW_AREA", "GROUP_ROSTER_UPDATE", + "PLAYER_REGEN_ENABLED", "ADDON_LOADED", "EDIT_MODE_LAYOUTS_UPDATED", "DISPLAY_SIZE_CHANGED", "UI_SCALE_CHANGED", "PLAYER_LEVEL_UP"}) do + listener:RegisterEvent(event) + end + listener:SetScript("OnEvent", queue) + if EditModeManagerFrame then + EditModeManagerFrame:HookScript("OnShow", queue) + EditModeManagerFrame:HookScript("OnHide", queue) + end + queue() +end diff --git a/RuenUI/ExtraBars.lua b/RuenUI/ExtraBars.lua new file mode 100644 index 0000000..0febb96 --- /dev/null +++ b/RuenUI/ExtraBars.lua @@ -0,0 +1,309 @@ +local _, P = ... +local letters = {"Q","W","R","T","A","G","H","Z","X","C","V","B"} +local numbers = {"1","2","3","4","5","6","7","8","9","0","-","="} +-- Plain numbers control pets; the corresponding utility slots use Ctrl. +local keys = {{"MultiBarLeft", "CTRL-", "MULTIACTIONBAR4BUTTON"}, + {"MultiBarRight", "SHIFT-", "MULTIACTIONBAR3BUTTON"}, + {"MultiBar5", "ALT-", "MULTIACTIONBAR5BUTTON"}, + {"MultiBar6", "ALT-", "MULTIACTIONBAR6BUTTON"}, + {"MultiBar7", "CTRL-SHIFT-", "MULTIACTIONBAR7BUTTON"}} + +local function uiEdge(f, method) + local v=f and f[method] and f[method](f) + return v and v*f:GetEffectiveScale()/UIParent:GetEffectiveScale() +end + +local function leftRows() + -- Two compact 6x2 blocks at every resolution, matching the right utility + -- bars. Wider monitors must not stretch these into distracting long strips. + return 2 +end + +local function leftDock(edge, rows, saved) + local x=edge(ChatFrame1,"GetLeft") or 20 + local width=(rows or leftRows())==1 and 495 or 252 + local y=P.SocialNotificationSpace(edge).top+12 + -- During first installation Blizzard's player frame may still be at the + -- top-left. It must not push the new shelf off screen before Ruen is active. + if saved and not P.IsOurLayout(EditModeManagerFrame:GetActiveLayoutInfo()) then return x,y end + -- On narrow screens the wider shelf reaches under the player/pet HUD. + -- Use the whole unit footprint, including its normal combat visibility. + for _,name in ipairs({"PlayerFrame","PetFrame","PlayerCastingBarFrame","StanceBar","PetActionBar","MultiCastActionBarFrame","PossessActionBar","MainMenuBarVehicleLeaveButton","ExtraAbilityContainer"}) do + local f=_G[name] + if f and (name=="PlayerFrame" or f:IsShown()) then + local l,r,t=edge(f,"GetLeft"),edge(f,"GetRight"),edge(f,"GetTop") + if l and r and t and xl-12 then y=math.max(y,t+12) end + end + end + return x,y +end + +function P.ConfigureLeftBarSystems(layout) + local A=Enum.EditModeActionBarSetting + local rows=leftRows() + local height=rows==1 and 36 or 74 + local x,y=leftDock(uiEdge,rows,true) + local function set(s,k,v) + for _,e in ipairs(s.settings) do if e.setting==k then e.value=v;return end end + s.settings[#s.settings+1]={setting=k,value=v} + end + for _,s in ipairs(layout.systems or {}) do + if s.system==Enum.EditModeSystem.ActionBar and (s.systemIndex==7 or s.systemIndex==8) then + set(s,A.NumRows,rows);set(s,A.Orientation,Enum.ActionBarOrientation.Horizontal) + s.isInDefaultPosition=false + s.anchorInfo={point="BOTTOMLEFT",relativeTo="UIParent",relativePoint="BOTTOMLEFT", + offsetX=x,offsetY=y+(s.systemIndex-7)*(height+6)} + elseif s.system==Enum.EditModeSystem.UnitFrame and (s.systemIndex==Enum.EditModeUnitFrameSystemIndices.Party + or s.systemIndex==Enum.EditModeUnitFrameSystemIndices.Raid) then + if s.systemIndex==Enum.EditModeUnitFrameSystemIndices.Raid then + set(s,Enum.EditModeUnitFrameSetting.RowSize,8) -- compact five-column grid at 40 players + end + s.isInDefaultPosition=false + s.anchorInfo={point="BOTTOMLEFT",relativeTo="UIParent",relativePoint="BOTTOMLEFT",offsetX=x,offsetY=y+height*2+38} + end + end +end + +function P.MigrateLeftBars() + if InCombatLockdown() or RuenUIDB.disabled then return end + local m=EditModeManagerFrame + if not m or m:IsShown() or m.overrideLayoutInfo or not P.IsOurLayout(m:GetActiveLayoutInfo()) then return end + local rows=leftRows() + if RuenUIDB.leftBarsVersion==3 and RuenUIDB.leftBarRows==rows then return end + local data=P.CopyEditModeLayouts() + for _,layout in ipairs(data.layouts or {}) do + if P.IsOurLayout(layout) then + RuenUIDB.beforeLeftBars=RuenUIDB.beforeLeftBars or C_EditMode.ConvertLayoutInfoToString(layout) + P.ConfigureLeftBarSystems(layout) + end + end + P.SaveEditModeLayouts(data) + RuenUIDB.leftBarsVersion=3 + RuenUIDB.leftBarRows=rows +end + +function P.ConfigureExtraBars(layout) + local A = Enum.EditModeActionBarSetting + local function set(s,k,v) + if not k then return end + for _,e in ipairs(s.settings) do if e.setting==k then e.value=v; return end end + s.settings[#s.settings+1]={setting=k,value=v} + end + for _,s in ipairs(layout.systems or {}) do + local U,I=Enum.EditModeUnitFrameSetting,Enum.EditModeUnitFrameSystemIndices + if s.system==Enum.EditModeSystem.UnitFrame and (s.systemIndex==I.Party or s.systemIndex==I.Raid) then + s.anchorInfo={point="BOTTOMLEFT",relativeTo="UIParent",relativePoint="BOTTOMLEFT",offsetX=20,offsetY=407} + s.isInDefaultPosition=false + if s.systemIndex==I.Raid then + set(s,U.FrameWidth,0);set(s,U.FrameHeight,0) + set(s,U.RaidGroupDisplayType,Enum.RaidGroupDisplayType.CombineGroupsVertical) + set(s,U.RowSize,8) -- 40 players: five columns, eight rows; native minimum is 72x36 + end + end + if s.system==Enum.EditModeSystem.ActionBar and s.systemIndex>=4 and s.systemIndex<=8 then + set(s,A.NumIcons,12); set(s,A.NumRows,s.systemIndex==6 and 1 or 2); set(s,A.IconPadding,2); set(s,A.IconSize,4) + set(s,A.Orientation,Enum.ActionBarOrientation.Horizontal) + set(s,A.VisibleSetting,Enum.ActionBarVisibleSetting.Always) + set(s,A.AlwaysShowButtons,s.systemIndex==6 and 1 or (C_CVar.GetCVar("lockActionBars")=="1" and 0 or 1)) + local left=s.systemIndex>=7 + s.anchorInfo={point=left and "BOTTOMLEFT" or "BOTTOMRIGHT",relativeTo="UIParent", + relativePoint=left and "BOTTOMLEFT" or "BOTTOMRIGHT", offsetX=left and 20 or -22, + offsetY=left and (215+(s.systemIndex-7)*82) or (s.systemIndex==5 and 100 or s.systemIndex==4 and 182 or 264)} + if s.systemIndex==6 then + s.anchorInfo={point="BOTTOM",relativeTo="UIParent",relativePoint="BOTTOM",offsetX=0,offsetY=174} + end + s.isInDefaultPosition=false + end + end + P.ConfigureLeftBarSystems(layout) +end + +function P.MigrateExtraBars(force) + if InCombatLockdown() or RuenUIDB.disabled then return end + local m=EditModeManagerFrame + if not m or m:IsShown() or m.overrideLayoutInfo or not P.IsOurLayout(m:GetActiveLayoutInfo()) then return end + -- Layout geometry is shared, but enableMultiActionBars is per character. + -- Older alts need their own visibility upgrade even after another character + -- migrated the account layout. Do this once, preserving later manual choices. + if RuenUICharacter.extraBarsVisibilityVersion~=1 then + local bars={GetActionBarToggles()} + RuenUICharacter.oldBars=RuenUICharacter.oldBars or CopyTable(bars) + for i=2,8 do + if not bars[i-1] then Settings.SetValue("PROXY_SHOW_ACTIONBAR_"..i,true) end + end + MultiActionBar_Update() + RuenUICharacter.extraBarsVisibilityVersion=1 + end + if not force and RuenUIDB.extraBarsVersion==1 then P.MigrateLeftBars();return end + local data=P.CopyEditModeLayouts() + for _,layout in ipairs(data.layouts or {}) do + if P.IsOurLayout(layout) then + if force and RuenUIDB.extraBarsVersion==1 then + for _,s in ipairs(layout.systems or {}) do + if s.system==Enum.EditModeSystem.ActionBar and s.systemIndex>=4 and s.systemIndex<=8 and s.systemIndex~=6 then + for _,e in ipairs(s.settings or {}) do + if e.setting==Enum.EditModeActionBarSetting.AlwaysShowButtons then + e.value=C_CVar.GetCVar("lockActionBars")=="1" and 0 or 1 + end + end + end + end + else P.ConfigureExtraBars(layout) end + P.ConfigureLeftBarSystems(layout) + end + end + P.SaveEditModeLayouts(data) + MultiActionBar_Update() + RuenUIDB.extraBarsVersion=1 + RuenUIDB.leftBarsVersion=3 + RuenUIDB.leftBarRows=leftRows() +end + +function P.ApplyPetBindings(force) + if InCombatLockdown() or RuenUIDB.disabled then return end + local scope=GetCurrentBindingSet()==1 and RuenUIDB or RuenUICharacter + if scope.petBindingsVersion==2 and not force then return end + local changes=RuenUICharacter.bindingChanges or {} + RuenUICharacter.bindingChanges=changes + local function bind(key,action) + local old=GetBindingAction(key) + if old==(action or "") then return end + if not SetBinding(key,action) then error("Could not bind "..key) end + changes[key]=changes[key] or {before=old} + changes[key].applied=action or "" + end + -- Migrate only these keys, once per binding set. Leave the other action + -- rows, personal shortcuts and every spell/item slot exactly where they are. + -- Keep the mapping identical with no pet, a temporary pet, or another class. + -- Existing 1-0 / Ctrl-number customizations survive this two-key upgrade. + if force or scope.petBindingsVersion~=1 then + for i,key in ipairs(numbers) do + bind("CTRL-"..key,"MULTIACTIONBAR4BUTTON"..i) + if i<=10 then bind(key,"BONUSACTIONBUTTON"..i) end + end + end + bind("-","CLICK RuenPetExtraButton11:LeftButton") + bind("=","CLICK RuenPetExtraButton12:LeftButton") + SaveBindings(GetCurrentBindingSet()) + scope.petBindingsVersion=2 +end + +function P.ApplyExtraBindings(force) + if InCombatLockdown() then return end + local scope=GetCurrentBindingSet()==1 and RuenUIDB or RuenUICharacter + if scope.extraBindingsVersion==1 and not force then + P.ApplyPetBindings(false) + return + end + local changes=RuenUICharacter.bindingChanges or {} + RuenUICharacter.bindingChanges=changes + local function bind(key,action) + local old=GetBindingAction(key) + if old==(action or "") then return end + if not SetBinding(key,action) then error("Could not bind "..key) end + changes[key]=changes[key] or {before=old} + changes[key].applied=action or "" + end + for _,row in ipairs(keys) do + for i,key in ipairs(row[1]=="MultiBar5" and letters or numbers) do + local action=row[3]..i + for _,old in ipairs({GetBindingKey(action)}) do bind(old,nil) end + bind(row[2]..key,action) + end + end + for _,key in ipairs({"E","D","S","F"}) do + local action=({E="MOVEFORWARD",D="MOVEBACKWARD",S="STRAFELEFT",F="STRAFERIGHT"})[key] + bind("ALT-"..key,action) + end + bind("ALT-BUTTON3","JUMP");bind("ALT-BUTTON4","TARGETPREVIOUSENEMY");bind("ALT-BUTTON5","TARGETNEARESTENEMY") + bind("CTRL-SHIFT-F11","TOGGLEUI") + -- Alt is an action-row modifier now, so it must not also force friendly + -- spells onto the player. Automatic self-cast and F1 targeting stay available. + if GetModifiedClick and SetModifiedClick then + RuenUIDB.oldSelfCast=RuenUIDB.oldSelfCast or GetModifiedClick("SELFCAST") + if Settings.GetSetting("SELFCAST") then Settings.SetValue("SELFCAST","NONE") + else SetModifiedClick("SELFCAST","NONE") end + RuenUIDB.original.autoSelfCast=RuenUIDB.original.autoSelfCast or C_CVar.GetCVar("autoSelfCast") + C_CVar.SetCVar("autoSelfCast","1") + end + P.ApplyPetBindings(true) -- also saves the bindings changed above + scope.extraBindingsVersion=1 +end + +function P.UtilityTop() + return MultiBarRight or MultiBarLeft +end + +function P.PositionExtraBars(place,edge) + place(MultiBarRight,"BOTTOMRIGHT",MultiBarLeft,"TOPRIGHT",0,6) + place(MultiBar5,"BOTTOMLEFT",MultiBarBottomRight,"TOPLEFT",0,4) +end + +function P.PositionLeftBars(place,edge) + local x,y=leftDock(edge) + place(MultiBar6,"BOTTOMLEFT",UIParent,"BOTTOMLEFT",x,y) + place(MultiBar7,"BOTTOMLEFT",MultiBar6,"TOPLEFT",0,6) +end + +local groupScales={} +function P.PositionGroupFrames(place,edge) + local top=math.max((edge(MultiBar7,"GetTop") or 375)+32,(edge(PlayerFrame,"GetTop") or 397)+16) + local obstacles={} + for _,r in ipairs(P.OverlayObstacles(false)) do + if r.name~="PartyFrame" and r.name~="CompactRaidFrameContainer" and not (r.name or ""):match("^DamageMeter") + and not (r.name or ""):find("CooldownViewer") then obstacles[#obstacles+1]=r end + end + -- Preserve a useful central sightline/tooltip lane on short viewports. + -- Large battleground objective widgets already reserve that area and may + -- require the group to use the clear space underneath them instead. + local instanceType + if IsInInstance then local inside;inside,instanceType=IsInInstance() end + if instanceType~="pvp" and not (FocusFrame and FocusFrame:IsShown()) then + obstacles[#obstacles+1]={left=UIParent:GetWidth()/2-150,right=UIParent:GetWidth()/2+150, + bottom=(edge(PlayerFrame,"GetTop") or 400)+12,top=UIParent:GetHeight(),name="Central sightline"} + end + P.groupLayoutIssues={} + for _,name in ipairs({"PartyFrame","CompactRaidFrameContainer"}) do + local f=_G[name] + if f then + groupScales[f]=groupScales[f] or f:GetScale() + local base=groupScales[f] + local ratio=f:GetEffectiveScale()/UIParent:GetEffectiveScale()*base/f:GetScale() + local width,height=f:GetWidth()*ratio,f:GetHeight()*ratio + local x=edge(ChatFrame1,"GetLeft") or 20 + if width>8 and height>8 and f:IsShown() then + local target,fit,score + -- Try relocating the complete group before reducing readability. + -- Never turn a 40-player raid into half-size health bars. + for step=0,5 do + local candidateFit=1-step*.05 + local candidate=P.FindOverlayPosition(width*candidateFit,height*candidateFit,x,top,obstacles,UIParent:GetWidth(),UIParent:GetHeight()) + if candidate then + -- A modest size reduction at the left edge is preferable + -- to a large raid grid spreading across the play field. + local cost=(candidate.left-x)^2+(candidate.bottom-top)^2+((1-candidateFit)*600)^2 + if not score or cost.001 then (f.SetScaleBase or f.SetScale)(f,scale) end + place(f,"BOTTOMLEFT",UIParent,"BOTTOMLEFT",target.left,target.bottom) + target.name=name;obstacles[#obstacles+1]=target + else + P.groupLayoutIssues[#P.groupLayoutIssues+1]=name.." cannot fit at readable scale" + end + else + -- Empty native containers grow on GROUP_ROSTER_UPDATE/OnShow. + if math.abs(f:GetScale()-base)>.001 then (f.SetScaleBase or f.SetScale)(f,base) end + place(f,"BOTTOMLEFT",UIParent,"BOTTOMLEFT",x,top) + end + end + end +end + +function P.BarHelp() + return P.Localized("96 slots: 48 ESDF combat (base/Shift/Ctrl/Alt); right utility bottom to top: Ctrl+1–=, Shift+1–=; left: Alt+1–=, Ctrl+Shift+1–=. 1–= controls pets (last two auto-fill missing abilities). /ruen lock | unlock. Customize in Esc > Key Bindings.", + "96 ячеек: 48 боевых ESDF (без модификатора/Shift/Ctrl/Alt); справа снизу вверх: Ctrl+1–=, Shift+1–=; слева: Alt+1–=, Ctrl+Shift+1–=. 1–= — питомец (две последние кнопки — недостающие способности). /ruen lock | unlock. Настройка: Esc > Назначение клавиш.") +end diff --git a/RuenUI/GunAudio.lua b/RuenUI/GunAudio.lua new file mode 100644 index 0000000..01a4261 --- /dev/null +++ b/RuenUI/GunAudio.lua @@ -0,0 +1,65 @@ +local _, P = ... + +-- GunSilencerForever owns sound playback and its saved settings. Use its public +-- commands so toggles immediately update the mute list and the options window. +-- No sound hooks, polling, frame movement, or global SFX-volume changes here. +local function ready() + return type(GunSilencerForeverDB) == "table" + and SlashCmdList and type(SlashCmdList.GUNSILENCERFOREVER) == "function" +end + +local function run(command) + SlashCmdList.GUNSILENCERFOREVER(command) +end + +function P.InitializeGunAudio() + if not RuenUIDB or not ready() then return false end + if RuenUIDB.gunAudioVersion == 1 then return true end + if RuenUIDB.disabled then + run("off") + return false + end + -- Once per account. Later /gsf and /ruen guns choices survive login, alts, + -- reloads, and /ruen apply. Bow and crossbow draw sounds stay native. + run("draw off") + run("volume 100") + run("guns on") + run("on") + RuenUIDB.gunAudioVersion = 1 + return true +end + +function P.StopGunAudio() + if ready() then run("off") end +end + +function P.GunAudioCommand(argument) + if not ready() then + return P.Localized( + "Gun Silencer Forever is not loaded. Fully exit WoW and relaunch after installing the complete Ruen package; enable GunSilencerForever in AddOns.", + "Gun Silencer Forever не загружен. Полностью закройте и запустите WoW после установки полного комплекта Ruen; включите GunSilencerForever в списке модификаций.") + end + local arg = (argument or ""):lower():match("^%s*(.-)%s*$") + local volume = tonumber(arg:match("^(%d+)$") or arg:match("^volume%s+(%d+)$")) + if not (arg == "" or arg == "status" or arg == "on" or arg == "off" + or arg == "settings" or (volume and volume >= 10 and volume <= 100)) then + return P.Localized("/ruen guns on|off|status|settings; /ruen guns 10–100 (rounded to tens).", + "/ruen guns on|off|status|settings; /ruen guns 10–100 (округляется до десятков).") + end + P.InitializeGunAudio() + if arg == "on" then + run("draw off") + run("guns on") + run("on") + RuenUIDB.gunAudioVersion = 1 + elseif arg == "off" then + run("off") + RuenUIDB.gunAudioVersion = 1 + elseif arg == "settings" then + run("") + elseif volume then + run("volume " .. volume) + else + run("status") + end +end diff --git a/RuenUI/HardwareProfile.lua b/RuenUI/HardwareProfile.lua new file mode 100644 index 0000000..6ae2131 --- /dev/null +++ b/RuenUI/HardwareProfile.lua @@ -0,0 +1,3 @@ +-- Generated locally by the optional Ruen hardware evaluator. No donor machine settings. +local _, P = ... +P.hardwareProfile = {} diff --git a/RuenUI/LanguageDefaults.lua b/RuenUI/LanguageDefaults.lua new file mode 100644 index 0000000..272b8d1 --- /dev/null +++ b/RuenUI/LanguageDefaults.lua @@ -0,0 +1,2 @@ +local _, P = ... +-- The Windows installer can write an explicit first-login language choice here. diff --git a/RuenUI/Locale.lua b/RuenUI/Locale.lua new file mode 100644 index 0000000..b7a9281 --- /dev/null +++ b/RuenUI/Locale.lua @@ -0,0 +1,46 @@ +local _, P = ... +local ru = { + ["Grave (`) now toggles autorun."] = "Клавиша ` теперь включает и выключает автоматический бег.", + ["Grave (`) is already bound; its shortcut was preserved."] = "Клавиша ` уже назначена; прежнее действие сохранено.", + ["Grave (`): autorun, added only if the key was unbound."] = "Клавиша ` — автоматический бег; назначается, только если клавиша была свободна.", + ["ESDF movement; Space/middle mouse jump. Rear thumb/Shift-Tab previous enemy; front thumb/Tab next enemy."] = "Движение: ESDF. Прыжок: пробел/средняя кнопка мыши. Задняя боковая/Shift-Tab: предыдущий враг; передняя/Tab: следующий.", + ["Combat: Q W R T / A G H / Z X C V B. Shift = middle row, Ctrl = upper row. Slots are unlocked."] = "Способности: Q W R T / A G H / Z X C V B. Shift — средний ряд, Ctrl — верхний. Ячейки не заблокированы.", + ["N map, Shift-N zone map; I bags; J quests, Alt-J Compendium; K character; Shift-K talents; Ctrl-K reputation; Alt-K currency."] = "N — карта, Shift-N — карта зоны; I — сумки; J — задания, Alt-J — компендиум; K — персонаж; Shift-K — таланты; Ctrl-K — репутация; Alt-K — валюта.", + ["P spells, Shift-P professions, Ctrl-P pet spells; L group finder, Shift-L legacy; O friends, Shift-O guild, Ctrl-O raid, Alt-O Who."] = "P — заклинания, Shift-P — профессии, Ctrl-P — питомец; L — поиск группы, Shift-L — наследие; O — друзья, Shift-O — гильдия, Ctrl-O — рейд, Alt-O — поиск игроков.", + ["Y collections, Shift-Y mounts, Ctrl-Y toys, Alt-Y appearances; Shift-J adventure guide; Ctrl-J achievements (where available)."] = "Y — коллекции, Shift-Y — транспорт, Ctrl-Y — игрушки, Alt-Y — облики; Shift-J — путеводитель; Ctrl-J — достижения (если доступны).", + ["F6 enemy nameplates, Shift-F6 all, Ctrl-F6 friendly; F8 macros; F9 settings; Shift-F9 keybindings; F10 housing (where available); Esc game menu."] = "F6 — полосы здоровья врагов, Shift-F6 — всех, Ctrl-F6 — союзников; F8 — макросы; F9 — настройки; Shift-F9 — клавиши; F10 — жильё (если доступно); Esc — меню.", + ["U interact, Shift-U assist, Alt-U ping; Ctrl-I sit, Shift-I sheathe. F12 this help; Shift-F12 support."] = "U — взаимодействие, Shift-U — помощь, Alt-U — метка; Ctrl-I — сесть, Shift-I — убрать оружие. F12 — справка; Shift-F12 — поддержка.", + ["/ruen language en|ru: game text/audio + narration; client restart required. /ruen voice en|ru: narration only, immediate. /ruen language: status."] = "/ruen language en|ru — текст, звук игры и озвучка заданий (нужен перезапуск игры). /ruen voice en|ru — только озвучка, сразу. /ruen language — состояние.", + ["/ruen bindings: reapply mouse/menu keys; /ruen bags: reposition bags. /ruen status | balanced | performance | bench | export | restore. /ruen apply resets the whole UI profile."] = "/ruen bindings — восстановить клавиши мыши/меню; /ruen bags — переместить сумки. /ruen status | balanced | performance | bench | export | restore. /ruen apply — сбросить весь профиль интерфейса.", + ["Open this menu after combat."] = "Откройте это меню после боя.", + ["Choose en (English) or ru (Russian). /ruen language shows current settings."] = "Укажите en (английский), ru (русский) или toggle (переключить). /ruen language — текущие настройки.", + ["Spoken has not initialized. Enable Spoken and Spoken_Quests, then /reload."] = "Spoken не запущен. Включите Spoken и Spoken_Quests, затем введите /reload.", + ["Narration changed. Run the command after combat to change game text/audio too."] = "Озвучка изменена. Для смены текста и звука игры повторите команду после боя.", + ["/ruen language en|ru changes game text/audio and narration; restart required. /ruen voice en|ru changes narration only. Available does not mean the language files have finished downloading."] = "/ruen language en|ru меняет текст, звук и озвучку; нужен перезапуск игры. /ruen voice en|ru — только озвучка. Наличие языка в списке не подтверждает завершение загрузки файлов.", + ["Open macros"] = "Открыть макросы", + ["Open settings"] = "Открыть настройки", + ["Open keybindings"] = "Назначение клавиш", + ["Ruen UI help and key map"] = "Справка Ruen UI и клавиши", + ["Open Blizzard support"] = "Поддержка Blizzard", + ["ESDF ready: Q W R T / A G H / Z X C V B. Rows bottom to top: base, Shift, Ctrl, Alt. Utility bars are above bags and chat. /ruen bars lists shortcuts; /ruen lock or unlock controls dragging."] = "ESDF готово: Q W R T / A G H / Z X C V B. Ряды снизу вверх: без модификатора, Shift, Ctrl, Alt. Дополнительные панели над сумками и чатом. /ruen bars — клавиши; /ruen lock или unlock — блокировка значков.", + ["Wait until combat ends, then /ruen apply."] = "Дождитесь конца боя, затем /ruen apply.", + ["Settings saved. Type /reload once to finish native frame setup."] = "Настройки сохранены. Введите /reload для завершения настройки интерфейса.", + ["Leave combat before restoring."] = "Восстановление доступно после боя.", + ["Original settings restored for this character; automatic setup disabled account-wide. The extra saved layout is retained for reuse."] = "Исходные настройки персонажа восстановлены; автоматическая настройка отключена для учётной записи. Сохранённый макет оставлен для повторного использования.", + ["Type /reload once to finish restoring addon preferences."] = "Введите /reload для завершения восстановления настроек аддонов.", + ["An FPS sample is already running."] = "Замер FPS уже запущен.", + ["Sampling FPS once per second for 3 minutes. Play normally and keep WoW focused."] = "Замер FPS раз в секунду в течение 3 минут. Играйте как обычно, не сворачивая WoW.", + ["Reapply bindings after combat."] = "Изменить клавиши можно после боя.", + ["Reposition bags after combat."] = "Переместить сумки можно после боя.", + ["Leave combat before changing graphics."] = "Изменить графику можно после боя.", + ["Current native layout copied; also available through Edit Mode > Share > Copy to Clipboard."] = "Текущий макет скопирован. Также доступно: режим редактирования > поделиться > скопировать.", + ["Long-session graphics applied: 60 FPS cap, lighter effects/distance, 100% render scale."] = "Графика для долгих сеансов: до 60 FPS, снижены эффекты и дальность, масштаб рендера 100%.", + ["Addon preferences saved. Type /reload once to finish setup."] = "Настройки аддонов сохранены. Для завершения введите /reload.", +} +function P.Translate(text) + if GetLocale() == "ruRU" then return ru[text] or text end + return text +end +function P.Localized(en, ruText) + return GetLocale() == "ruRU" and ruText or en +end diff --git a/RuenUI/Optimizer.lua b/RuenUI/Optimizer.lua new file mode 100644 index 0000000..3dc6eb4 --- /dev/null +++ b/RuenUI/Optimizer.lua @@ -0,0 +1,236 @@ +local _, P = ... +-- Bounded, opt-in frame-time calibration. Hardware telemetry comes from the +-- companion, never from a guess based on FPS. No resolution/API/fan/voltage edits. +local f, run, pending, context, warmup, elapsed, frames, histogram, windows, good, pendingLoad +local function say(en,ru) print('|cff60d5ffRuen UI:|r '..P.Localized(en,ru or en)) end +local function db() + RuenUIDB.optimizer=RuenUIDB.optimizer or {original={},profiles={}} + return RuenUIDB.optimizer +end +local function targetFPS(value) + local n=tonumber(value) + if n and n>=20 and n<=240 and n==math.floor(n) then return n end + return 60 +end +local tiers={ + {0,0,1,1,1,1,1}, {1,0,2,2,2,2,1}, {2,1,3,3,3,2,2}, + {2,1,5,5,4,3,2}, {3,2,7,6,5,3,3}, +} +local fields={'ShadowQuality','SSAO','ViewDistance','EnvironmentDetail','GroundClutter','LiquidDetail','ComputeEffects'} +local function mode() + local inside,kind=IsInInstance() + if inside and (kind=='raid' or kind=='pvp') then return 'raid' end + if not inside then return 'world' end + return nil -- a dungeon is not evidence for open-world or raid calibration +end +local function fingerprint() + local w,h=GetPhysicalScreenSize() + return w..'x'..h..':'..(C_CVar.GetCVar('gxAdapter') or '')..':'..(C_CVar.GetCVar('gxApi') or '') +end +local function hardware() + local h=P.hardwareProfile or {} + if not h.checkedAt or time()-h.checkedAt>604800 or time()=frames*p then return 10000/tenthMS end + end + return 0 +end +local function finish() + local d=db(); local r=d.profiles[context] + profile(context,r.best or 1);r.tier=r.best or 1;r.calibrated=true;r.fingerprint=fingerprint();r.time=time() + r.metTarget=r.best~=nil + pending=nil;cap(d.target) + say(('Graphics %s: tier %d/5 saved; %d FPS cap. %s'):format(context,r.tier,d.target, + r.metTarget and 'Measured headroom passed.' or 'Target not sustained at the lowest tier; this profile is a compromise.'), + ('Графика %s: уровень %d/5, лимит %d FPS. %s'):format(context,r.tier,d.target, + r.metTarget and 'Запас производительности подтверждён.' or 'Минимальные настройки не обеспечили целевую частоту кадров.')) + context=nil;reset(30) + f:SetScript("OnUpdate",nil) -- sleep until an environment/resolution event +end +local function commit() + if not run or InCombatLockdown() or not pending then return end + if mode()~=context then pending=nil;context=nil;cap(db().target);reset(30);return end + local r=db().profiles[context] + if pending=='finish' then finish();return end + r.tier=pending;pending=nil;profile(context,r.tier);reset(15) +end +local function result() + local d=db();local r=d.profiles[context] + windows=windows+1 + local p10,low=percent(.90),percent(.99) + r.last={p10=p10,low1=low,frames=frames,seconds=elapsed,tier=r.tier} + -- Require two complete windows at the same tier and about 10% headroom. + local passed=p10>=d.target*1.08 and low>=d.target*.80 + if passed then good=good+1 else good=0 end + if good>=2 then + r.best=r.tier;good=0 + pending=(r.tier1 then pending=r.tier-1 + elseif windows>=4 then pending='finish' end + end + if windows>=8 then pending='finish' end + reset(0);commit() +end +local function startContext(which) + local d=db();local r=d.profiles[which] + if r.calibrated and r.fingerprint==fingerprint() then return false end + if InCombatLockdown() then return false end + context=which;windows,good=0,0;r.tier=math.min(r.tier or 2,d.ceiling);r.best=nil + profile(which,r.tier);cap(math.ceil(d.target*1.2));reset(60) + say('Calibrating '..which..': play normally, keep WoW focused. Quality changes wait for combat to end; /ruen optimize pause before switching apps.', + 'Калибровка '..which..': играйте в активном окне. Изменения применяются вне боя. Перед переключением окон: /ruen optimize pause.') + return true +end +local function update(_,dt) + if not run or RuenUIDB.disabled then f:SetScript("OnUpdate",nil);return end + local d=db() + local which=mode() + if not context and (not which or (d.profiles[which].calibrated and d.profiles[which].fingerprint==fingerprint())) then + f:SetScript("OnUpdate",nil);return + end + if which~=context then + if InCombatLockdown() then reset(30); return end + if context then context=nil;pending=nil;cap(d.target);reset(30) end + if which then startContext(which) end + return + end + if not context then return end + if pending then commit();return end + if dt>2 then reset(15);return end -- loading/suspended frame is not a valid sample + if warmup>0 then warmup=warmup-dt;return end + if dt<=0 then return end + -- 0.1 ms bins avoid rounding a healthy high-FPS sample below its target. + local bin=math.min(20000,math.max(1,math.ceil(dt*10000))) + histogram[bin]=(histogram[bin] or 0)+1;frames=frames+1;elapsed=elapsed+dt + if elapsed>=45 then result() end +end +function P.StopOptimizer() + if not RuenUIDB or not RuenUIDB.optimizer then return end + local d=db();run=false;d.enabled=false + if context then + local r=d.profiles[context];profile(context,r.best or 1) + end + context,pending=nil,nil + if f then f:SetScript('OnUpdate',nil) end + cap(d.target or 60) +end +function P.OptimizerCommand(arg) + local d=db() + if arg=='status' then + local h=hardware() + say(('Optimizer: %s. Requested: %d FPS; effective: %d FPS. Thermal evidence: %s. World: %s; raid: %s.'):format(run and 'ON' or 'OFF',targetFPS(d.requestedFPS),d.target or targetFPS(d.requestedFPS), + h.evidence or 'not measured',d.profiles.world and d.profiles.world.calibrated and 'measured' or 'provisional', + d.profiles.raid and d.profiles.raid.calibrated and 'measured' or 'provisional'), + ('Калибровка: %s. Запрошено: %d FPS; текущая цель: %d FPS. Температуры: %s. Мир: %s; рейд: %s.'):format(run and 'ВКЛ' or 'ВЫКЛ',targetFPS(d.requestedFPS),d.target or targetFPS(d.requestedFPS), + h.evidence or 'не измерены',d.profiles.world and d.profiles.world.calibrated and 'проверен' or 'не проверен', + d.profiles.raid and d.profiles.raid.calibrated and 'проверен' or 'не проверен')) + return + end + if InCombatLockdown() then say('Change optimization outside combat.','Меняйте оптимизацию вне боя.');return end + if arg=='off' or arg=='pause' then P.StopOptimizer();say('Calibration paused; current settled quality retained.','Калибровка приостановлена.');return end + if arg=='restore' then + P.StopOptimizer() + for k,v in pairs(d.original) do pcall(C_CVar.SetCVar,k,v) end + RuenUIDB.optimizer=nil;say('Pre-optimization graphics restored.','Исходные настройки графики восстановлены.');return + end + if arg~='' and arg~='start' and arg~='resume' and arg~='world' and arg~='raid' then + say('/ruen optimize [world|raid|pause|resume|status|restore]');return + end + if (arg=='world' or arg=='raid') and mode()~=arg then + say('Run this in the requested environment. A solo test cannot validate raid performance.','Запустите в соответствующей зоне. Соло-тест не проверяет производительность в рейде.');return + end + if arg~='resume' then + if context then P.StopOptimizer() end + if arg=='world' or arg=='raid' then d.profiles[arg]={tier=2} + else d.profiles={world={tier=2},raid={tier=1}} end + end + d.profiles.world=d.profiles.world or {tier=2};d.profiles.raid=d.profiles.raid or {tier=1} + local h=hardware() + d.requestedFPS=targetFPS(d.requestedFPS) + local nextTarget=h.thermalPressure and math.min(d.requestedFPS,45) or d.requestedFPS + local nextCeiling=(h.thermalPressure or h.performancePressure) and 2 or (h.loaded and h.thermalCoverage=="full") and 5 or 3 + if d.target~=nextTarget or d.ceiling~=nextCeiling then + for _,r in pairs(d.profiles) do + r.calibrated=false;r.best=nil;r.tier=math.min(r.tier or 1,nextCeiling) + end + end + d.target=nextTarget;d.ceiling=nextCeiling + write('RAIDsettingsEnabled',1);write('RenderScale',1);write('MSAAQuality','0,0');write('msaaAlphaTest',0) + write('ffxAntiAliasingMode',1);write('vsync',0);write('useTargetFPS',0) + profile('world',d.profiles.world.tier);profile('raid',d.profiles.raid.tier);cap(d.target) + run=true;d.enabled=true;context=nil;reset(30) + f:SetScript('OnUpdate',update) + say('Adaptive calibration enabled. World and raid learn separately. Thermal monitoring must be run from the bundled Optimize tool; /reload imports its report.', + 'Калибровка включена. Мир и рейд проверяются отдельно. Температуры проверяет утилита Optimize из комплекта; /reload загружает отчёт.') + say(('Requested target: %d FPS; effective target: %d FPS.'):format(d.requestedFPS,d.target), + ('Запрошенная цель: %d FPS; текущая цель: %d FPS.'):format(d.requestedFPS,d.target)) +end +function P.InitializeOptimizer() + if f then return end + f=CreateFrame('Frame') + f:RegisterEvent('PLAYER_ENTERING_WORLD');f:RegisterEvent('PLAYER_REGEN_ENABLED');f:RegisterEvent('DISPLAY_SIZE_CHANGED');f:RegisterEvent('ZONE_CHANGED_NEW_AREA') + f:SetScript('OnEvent',function(_,event) + if event=='PLAYER_REGEN_ENABLED' then + if pendingLoad then local load=pendingLoad;pendingLoad=nil;load() end + commit() + elseif run then + if InCombatLockdown() then reset(60);return end + -- Never compare frames from different resolutions or loading screens. + context,pending=nil,nil;cap(db().target);reset(60) + if event=='DISPLAY_SIZE_CHANGED' then + for _,p in pairs(db().profiles) do p.calibrated=false;p.best=nil end + say('Resolution changed: calibration will measure this resolution.','Разрешение изменено: калибровка будет повторена.') end + end + if run then f:SetScript('OnUpdate',update) end + end) + local function initializeSaved() + local h=hardware() + local importKey=h.checkedAt and (tostring(h.checkedAt)..':'..targetFPS(h.targetFPS)) + if h.autoStart and RuenUIDB.hardwareImport~=importKey then + db().requestedFPS=targetFPS(h.targetFPS) + P.OptimizerCommand('start');RuenUIDB.hardwareImport=importKey + return + end + local d=RuenUIDB.optimizer + if d then + cap(d.target or 60) -- recover a benchmark cap after logout/crash + if d.enabled then P.OptimizerCommand('resume') end + end + end + if InCombatLockdown() then pendingLoad=initializeSaved else initializeSaved() end +end diff --git a/RuenUI/OverlayLayout.lua b/RuenUI/OverlayLayout.lua new file mode 100644 index 0000000..fab8079 --- /dev/null +++ b/RuenUI/OverlayLayout.lua @@ -0,0 +1,533 @@ +local _, P = ... + +-- Notification space is reserved even when no toast is visible. Protected bars +-- never chase a popup during combat. Blizzard still owns every alert's content, +-- lifecycle, queue, click handler and bank transaction. +local gap = 12 +local hudNames = { + "MainActionBar", "MultiBarBottomLeft", "MultiBarBottomRight", "MultiBar5", + "MultiBarLeft", "MultiBarRight", "MultiBar6", "MultiBar7", "BagsBar", "MicroMenuContainer", + "DamageMeter", + "BuffFrame", "DebuffFrame", "MirrorTimer1", "MirrorTimer2", "MirrorTimer3", + "ChatFrame1", "MinimapCluster", "ObjectiveTrackerFrame", "PartyFrame", "CompactRaidFrameContainer", + "PlayerFrame", "PetFrame", "TargetFrame", "TargetFrameToT", "RuenTargetTargetTarget", "FocusFrame", + "StanceBar", "PetActionBar", "MultiCastActionBarFrame", "PossessActionBar", + "MainMenuBarVehicleLeaveButton", "PlayerCastingBarFrame", "RuenSwingTimers", "ExtraAbilityContainer", + "BossTargetFrameContainer", "ArenaEnemyFrames", "CompactArenaFrame", + "UIWidgetTopCenterContainerFrame", "UIWidgetBelowMinimapContainerFrame", "UIWidgetPowerBarContainerFrame", + "PlayerPowerBarAlt", "TotemFrame", "ClassNameplateBarRogueFrame", "ClassNameplateBarDruidFrame", +} +local blockMembers = {} +for _,name in ipairs({"MainActionBar","MultiBarBottomLeft","MultiBarBottomRight","MultiBar5", + "MultiBarLeft","MultiBarRight","MultiBar6","MultiBar7","BagsBar","MicroMenuContainer"}) do blockMembers[name]=true end +local panels = {"BankFrame", "GuildBankFrame", "MerchantFrame", "QuestFrame", "GossipFrame", "MailFrame", "TradeFrame"} +local hooked, queued, placing = {}, false, false +local place, edge, enabled, schedule +local alertHooks={} + +local function rect(f, reserveHidden) + if not f then return end + if f.IsForbidden and f:IsForbidden() then return nil,true end + if not reserveHidden then + local shown=f:IsShown() + if issecretvalue and issecretvalue(shown) then return nil,true end + if not shown then return end + end + local l, r, b, t = edge(f,"GetLeft"), edge(f,"GetRight"), edge(f,"GetBottom"), edge(f,"GetTop") + if not l or not r or not b or not t then return nil,true end + if l and r and b and t and r>l and t>b then return {left=l,right=r,bottom=b,top=t,name=f.GetName and f:GetName()} end +end + +local function overlaps(a,b,pad) + return a.left < b.right+pad and a.right > b.left-pad and a.bottom < b.top+pad and a.top > b.bottom-pad +end + +-- Pure geometry: choose the nearest free rectangle, considering obstacle edges +-- rather than assuming that one fixed pixel offset works at every resolution. +function P.FindOverlayPosition(width,height,x,y,obstacles,screenWidth,screenHeight) + local maxX,maxY=screenWidth-gap-width,screenHeight-gap-height + if maxX.001 then saved={base=current,applied=current};alertScales[f]=saved end + local scale=f:GetEffectiveScale()/UIParent:GetEffectiveScale()*saved.base/current + padding=padding or 0 + local w,h=f:GetWidth()*scale+padding*2,f:GetHeight()*scale + if w<=0 or h<=0 then return false end + local target,fit + for step=0,3 do + fit=1-step*.05 + target=P.FindOverlayPosition(w*fit,h*fit,x-padding,y,obstacles,UIParent:GetWidth(),UIParent:GetHeight()) + if target then break end + end + if not target then return false end + local nextScale=saved.base*fit + if math.abs(current-nextScale)>.001 then (f.SetScaleBase or f.SetScale)(f,nextScale) end + saved.applied=nextScale + local old=rect(f) + if not old or math.abs(old.left-target.left-padding*fit)>.5 or math.abs(old.bottom-target.bottom)>.5 then + place(f,"BOTTOMLEFT",UIParent,"BOTTOMLEFT",target.left+padding*fit,target.bottom) + end + target.name=f.GetName and f:GetName() or "Alert" + obstacles[#obstacles+1]=target + return true +end + +function P.PositionOverlayFrames() + if placing or not enabled or not enabled() then return end + placing=true + local obstacles=P.OverlayObstacles(true) + local bag=rect(ContainerFrameCombinedBags);if bag then obstacles[#obstacles+1]=bag end + for _,name in ipairs({"GameTooltip","ShoppingTooltip1","ShoppingTooltip2"}) do + local r=rect(_G[name]);if r then obstacles[#obstacles+1]=r end + end + P.overlayUnplaced={} + P.overlayOverChat={} + P.overlayOverOptional={} + local alerts=collectAlerts() + -- Place wide/tall alerts first so small loot notices do not fragment the + -- remaining space. Stable names break ties between equal-size alerts. + table.sort(alerts,function(a,b) + local sa,sb=a:GetEffectiveScale(),b:GetEffectiveScale() + local aa,ab=a:GetWidth()*a:GetHeight()*sa*sa,b:GetWidth()*b:GetHeight()*sb*sb + if aa==ab then return (a:GetName() or tostring(a))<(b:GetName() or tostring(b)) end + return aa>ab + end) + for _,f in ipairs(alerts) do + if schedule and not alertHooks[f] then + alertHooks[f]=true + f:HookScript("OnHide",schedule) + f:HookScript("OnSizeChanged",schedule) + end + local scale=f:GetEffectiveScale()/UIParent:GetEffectiveScale() + -- Use the open upper field, clear of the combat HUD and minimap. + -- The left bars occupy the middle of the screen, not this upper row. + -- Let collision checks account for their actual height instead of + -- excluding a full-height column; four roll cards can then wrap cleanly. + local raidRight=CompactRaidFrameContainer and CompactRaidFrameContainer:IsShown() + and edge(CompactRaidFrameContainer,"GetRight") or 20 + local x=math.max(20,raidRight or 20)+gap + local y=UIParent:GetHeight()-f:GetHeight()*scale-gap + if not fitFrame(f,obstacles,x,y,alertPadding(f)) then + -- Short-lived native notices may use chat's text area in a crowded + -- raid. They still avoid social toasts, controls and other notices. + local fallback={} + for _,r in ipairs(obstacles) do if r.name~="ChatFrame1" then fallback[#fallback+1]=r end end + if fitFrame(f,fallback,x,y,alertPadding(f)) then + P.overlayOverChat[f]=true + obstacles[#obstacles+1]=fallback[#fallback] + else + -- Interactive loot decisions outrank optional duplicate cooldown + -- displays/meters. Health, casts, actions and social remain clear. + local minimal={} + for _,r in ipairs(fallback) do + if not (r.name or ""):find("CooldownViewer") and not (r.name or ""):match("^DamageMeter") then minimal[#minimal+1]=r end + end + if fitFrame(f,minimal,x,y,alertPadding(f)) then + P.overlayOverChat[f]=true;P.overlayOverOptional[f]=true + obstacles[#obstacles+1]=minimal[#minimal] + else + P.overlayUnplaced[#P.overlayUnplaced+1]=f.GetName and f:GetName() or "Alert" + end + end + end + end + placing=false +end + +local tooltipPositions=setmetatable({},{__mode="k"}) + +function P.ResetTooltipPosition(tooltip) + tooltipPositions[tooltip]=nil + P.tooltipUnplaced=nil + P.tooltipOverInventory=nil + P.tooltipOverSocial=nil +end + +function P.PositionTooltip(tooltip,settled) + if not edge or not enabled() then return false end + -- SetPoint alone does not release the tooltip engine's automatic owner- + -- relative anchor. Bag refreshes reinstate ANCHOR_LEFT/RIGHT repeatedly; + -- ANCHOR_NONE gives this tooltip one positioning authority without the + -- hide/content-reset side effects of calling SetOwner again. + if tooltip.GetAnchorType and tooltip.SetAnchorType and tooltip:GetAnchorType()~="ANCHOR_NONE" then + tooltip:SetAnchorType("ANCHOR_NONE") + end + local screenW,screenH=UIParent:GetWidth(),UIParent:GetHeight() + local uiScale=UIParent:GetEffectiveScale() + local scale=tooltip:GetEffectiveScale()/uiScale + local owner=tooltip:GetOwner() + local pos=tooltipPositions[tooltip] + if not pos or pos.owner~=owner or pos.screenW~=screenW or pos.screenH~=screenH + or pos.uiScale~=uiScale or pos.scale~=scale then + pos={owner=owner,screenW=screenW,screenH=screenH,uiScale=uiScale,scale=scale, + right=edge(P.UtilityTop(),"GetRight") or screenW-22, + bottom=(edge(P.UtilityTop(),"GetTop") or 250)+18,width=0,height=0,extraWidth=0} + tooltipPositions[tooltip]=pos + end + local comparisons={} + -- Fit comparison cards as one block; a correctly placed primary tooltip + -- alone does not protect the bars from its secondary equipment tooltips. + local extraWidth,extraHeight=0,0 + if tooltip==GameTooltip and settled then + for _,name in ipairs({"ShoppingTooltip1","ShoppingTooltip2"}) do + local f=_G[name] + if f and f:IsShown() then + local ratio=f:GetEffectiveScale()/uiScale + local w,h=f:GetWidth()*ratio,f:GetHeight()*ratio + if w>0 and h>0 then + comparisons[#comparisons+1]={frame=f,width=w,height=h} + extraWidth=extraWidth+w+gap;extraHeight=math.max(extraHeight,h) + end + end + end + end + -- DefaultAnchor runs before text is rebuilt. Only measure settled sizes and + -- retain the high-water footprint until the mouse leaves this owner. + if settled and tooltip:IsShown() then + local w,h=tooltip:GetWidth()*scale,tooltip:GetHeight()*scale + local needs=not pos.fitted or w>pos.width+1 or h>pos.height+1 + or extraWidth>pos.extraWidth+1 or extraHeight>pos.height+1 + or pos.revision~=(P.overlayRevision or 0) + if w>0 and h>0 and needs then + w,h=math.max(w,pos.width),math.max(h,pos.height,extraHeight) + extraWidth=math.max(extraWidth,pos.extraWidth) + local totalWidth=w+extraWidth + local obstacles=P.OverlayObstacles(true) + local bag=rect(ContainerFrameCombinedBags) + local withoutBag=CopyTable(obstacles) + -- In a packed small viewport, comparison cards may cover other bag + -- contents, but must keep the hovered item and all controls clear. + local hover=rect(owner);if hover then withoutBag[#withoutBag+1]=hover end + if bag then obstacles[#obstacles+1]=bag end + for _,f in ipairs(collectAlerts()) do local r=rect(f);if r then obstacles[#obstacles+1]=r end end + local candidate={left=pos.right-w,right=pos.right+extraWidth,bottom=pos.bottom,top=pos.bottom+h} + local free=candidate.left>=gap and candidate.right<=screenW-gap + and candidate.bottom>=gap and candidate.top<=screenH-gap + for _,o in ipairs(obstacles) do if overlaps(candidate,o,gap-0.1) then free=false;break end end + P.tooltipOverInventory=nil + P.tooltipOverSocial=nil + if not free then + local target=P.FindOverlayPosition(totalWidth,h,candidate.left,pos.bottom,obstacles,screenW,screenH) + if not target and bag and extraWidth>0 then + target=P.FindOverlayPosition(totalWidth,h,candidate.left,pos.bottom,withoutBag,screenW,screenH) + P.tooltipOverInventory=target and true or nil + end + if not target then + -- A full raid plus a long tooltip can saturate a laptop + -- viewport. Temporarily cover chat/notification space only + -- after proving no fully clear position exists. Never cover + -- controls, health/cast bars, objectives or the hovered item. + local fallback={} + for _,o in ipairs(obstacles) do + if o.name~="ChatFrame1" and o.name~="Social notifications" then fallback[#fallback+1]=o end + end + if hover then fallback[#fallback+1]=hover end + target=P.FindOverlayPosition(totalWidth,h,candidate.left,pos.bottom,fallback,screenW,screenH) + P.tooltipOverSocial=target and true or nil + end + if target then pos.right,pos.bottom=target.left+w,target.bottom;free=true end + end + P.tooltipUnplaced=not free + pos.width,pos.height,pos.extraWidth,pos.fitted=w,h,extraWidth,true + pos.revision=P.overlayRevision or 0 + end + end + local point,relative,relativePoint,x,y + if tooltip.GetPoint then point,relative,relativePoint,x,y=tooltip:GetPoint(1) end + if point~="BOTTOMRIGHT" or relative~=UIParent or relativePoint~="BOTTOMLEFT" + or not x or not y or math.abs(x-pos.right/scale)>.01 or math.abs(y-pos.bottom/scale)>.01 + or (tooltip.GetNumPoints and tooltip:GetNumPoints()~=1) then + place(tooltip,"BOTTOMRIGHT",UIParent,"BOTTOMLEFT",pos.right,pos.bottom) + end + local left=pos.right+gap + for _,card in ipairs(comparisons) do + if card.frame.GetAnchorType and card.frame.SetAnchorType and card.frame:GetAnchorType()~="ANCHOR_NONE" then + card.frame:SetAnchorType("ANCHOR_NONE") + end + local r=rect(card.frame) + if not r or math.abs(r.left-left)>.5 or math.abs(r.bottom-pos.bottom)>.5 then + place(card.frame,"BOTTOMLEFT",UIParent,"BOTTOMLEFT",left,pos.bottom) + end + left=left+card.width+gap + end + return not P.tooltipUnplaced +end + +function P.FindBagPosition(width,height,x,y) + if not edge then return end + local obstacles=P.OverlayObstacles(true) + P.bagOverHUD=nil + local screenW,screenH=UIParent:GetWidth(),UIParent:GetHeight() + -- Prefer full readability; reduce only if the complete inventory does not + -- fit. Never fall back to an anchor sitting on top of utility buttons. + for step=0,10 do + local scale=1-step*.035 + local target=P.FindOverlayPosition(width*scale,height*scale,x,y,obstacles,screenW,screenH) + if target then return target,scale end + end + -- An unusually tall inventory is a modal panel. Keep it on screen and + -- preserve every action/chat/quest control; allow temporary HUD coverage + -- only after the fully clear placements are exhausted. Report this fallback. + local essential=P.ControlRegions() + for _,o in ipairs(obstacles) do + if o.name=="ChatFrame1" or o.name=="Social notifications" or o.name=="ObjectiveTrackerFrame" + or o.name=="MinimapCluster" then essential[#essential+1]=o end + end + for _,name in ipairs(panels) do local r=rect(_G[name]);if r then essential[#essential+1]=r end end + for step=0,10 do + local scale=1-step*.035 + local target=P.FindOverlayPosition(width*scale,height*scale,x,y,essential,screenW,screenH) + if target then P.bagOverHUD=true;return target,scale end + end +end + +function P.OverlayAudit() + local issues={} + if not edge then return issues end + for _,issue in ipairs(P.groupLayoutIssues or {}) do issues[#issues+1]=issue end + for _,name in ipairs(RuenUICharacter.classAssistUnplaced or {}) do + issues[#issues+1]=name.." has no free space" + end + if RuenUICharacter.classAssistError then issues[#issues+1]="Cooldown setup: "..RuenUICharacter.classAssistError end + local social=P.SocialNotificationSpace(edge) + for _,name in ipairs({"MultiBar6","MultiBar7","PartyFrame","CompactRaidFrameContainer"}) do + local r=rect(_G[name]);if r and overlaps(r,social,0) then issues[#issues+1]=name.."/social notifications" end + end + local controls=P.ControlRegions() + local chat=rect(ChatFrame1) + if chat then + for _,r in ipairs(controls) do + if overlaps(chat,r,0) then issues[#issues+1]="ChatFrame1/"..r.name end + end + end + local obstacles=P.OverlayObstacles(false) + local bag=rect(ContainerFrameCombinedBags) + if P.bagUnplaced then issues[#issues+1]="Inventory has no clear space at readable scale" end + if P.tooltipUnplaced then issues[#issues+1]="Tooltip group has no clear space" end + if bag then + for _,o in ipairs(obstacles) do + if overlaps(bag,o,0) then issues[#issues+1]="ContainerFrameCombinedBags/"..(o.name or "HUD") end + end + obstacles[#obstacles+1]=bag + end + for _,name in ipairs({"GameTooltip","ShoppingTooltip1","ShoppingTooltip2"}) do + local t=rect(_G[name]) + if t then + for _,o in ipairs(obstacles) do + if not (P.tooltipOverInventory and o.name=="ContainerFrameCombinedBags") + and not (P.tooltipOverSocial and (o.name=="ChatFrame1" or o.name=="Social notifications")) and overlaps(t,o,0) then + issues[#issues+1]=name.."/"..(o.name or "HUD") + end + end + end + end + for _,name in ipairs(P.overlayUnplaced or {}) do issues[#issues+1]=name.." has no free space" end + for _,f in ipairs(collectAlerts()) do + local r=rect(f) + if r then + if r.left<0 or r.bottom<0 or r.right>UIParent:GetWidth()+1 or r.top>UIParent:GetHeight()+1 then + issues[#issues+1]=(r.name or "Alert").." off screen" + end + for _,o in ipairs(obstacles) do + if not (P.overlayOverChat and P.overlayOverChat[f] and o.name=="ChatFrame1") + and not (P.overlayOverOptional and P.overlayOverOptional[f] and ((o.name or ""):find("CooldownViewer") or (o.name or ""):match("^DamageMeter"))) and overlaps(r,o,0) then + issues[#issues+1]=(r.name or "Alert").."/"..(o.name or "HUD") + end + end + obstacles[#obstacles+1]=r + end + end + return issues +end + +function P.InitializeOverlayLayout(placeFrame,frameEdge,owns) + place,edge,enabled=placeFrame,frameEdge,owns + if P.overlayListener then return end + local listener=CreateFrame("Frame");P.overlayListener=listener + local function queue() + if placing or queued then return end + queued=true + C_Timer.After(0,function() queued=false;P.PositionOverlayFrames() end) + end + schedule=queue + local function watch() + for _,name in ipairs({"AlertFrame","GroupLootContainer","TalkingHeadFrame"}) do + local f=_G[name] + if f and not hooked[f] then + hooked[f]=true + f:HookScript("OnShow",queue);f:HookScript("OnHide",queue);f:HookScript("OnSizeChanged",queue) + hooksecurefunc(f,"SetPoint",queue) + if f.UpdateAnchors then hooksecurefunc(f,"UpdateAnchors",queue) end + end + end + end + for _,event in ipairs({"ADDON_LOADED","DISPLAY_SIZE_CHANGED","UI_SCALE_CHANGED","PLAYER_REGEN_ENABLED"}) do listener:RegisterEvent(event) end + listener:SetScript("OnEvent",function() watch();queue() end) + if GroupLootContainer_Update then hooksecurefunc("GroupLootContainer_Update",queue) end + watch();queue() +end diff --git a/RuenUI/PetExtras.lua b/RuenUI/PetExtras.lua new file mode 100644 index 0000000..71a6c10 --- /dev/null +++ b/RuenUI/PetExtras.lua @@ -0,0 +1,465 @@ +local _, P = ... +-- WoW owns exactly ten pet-bar slots. Two real pet actions on unused page-2 +-- slots back the extra buttons, so execution and spellbook discovery use +-- the engine's action system. Never change the ten native slots or live bars. +local buttons, listener, enabled, queued +local bank = Enum.SpellBookSpellBank and Enum.SpellBookSpellBank.Pet +local commandMacros = { + [117440514]="/petattack", [117440513]="/petfollow", [117440512]="/petstay", + [117440516]="/petmoveto", [100663298]="/petaggressive", [100663299]="/petassist", + [100663300]="/petdefensive", [100663296]="/petpassive", +} +local cursorItem, nativeItems = nil, {} + +-- Validate against the engine's pet-action search, not the cursor payload's +-- type string. GetActionInfo and GetCursorInfo do not use the same types. +local function containsAction(slot, actionID) + if not C_ActionBar or not C_ActionBar.FindPetActionButtons then return false end + local slots=C_ActionBar.FindPetActionButtons(actionID,Enum.ActionBarSet and Enum.ActionBarSet.Mkb) + for _,candidate in ipairs(slots or {}) do if candidate==slot then return true end end + return false +end + +local function snapshot(slot) + local kind,id,subType=GetActionInfo(slot) + return {kind=kind,id=id,subType=subType} +end + +local function matches(record) + if not record then return false end + -- Commands all report ("spell", 0, "pet") on this client. That payload + -- cannot establish ownership: use the engine's command-specific lookup. + return containsAction(record.slot,record.actionID) +end + +local function spareSlot(slot) + -- Only page 2 is a potential reserve. Page 3 is MultiBarRight; the other + -- pages include displayed bars and class/vehicle/override action pages. + if type(slot)~="number" or slot<13 or slot>24 or slot%1~=0 then return false end + if not MultiActionBar_GetBarForPage or MultiActionBar_GetBarForPage(2) then return false end + if C_ActionBar then + local bonus=C_ActionBar.GetBonusBarIndexForSlot and C_ActionBar.GetBonusBarIndexForSlot(slot) + if bonus and bonus~=0 then return false end + for _,name in ipairs({"GetVehicleBarIndex","GetOverrideBarIndex","GetTempShapeshiftBarIndex","GetActionBarPage"}) do + if C_ActionBar[name] and C_ActionBar[name]()==2 then return false end + end + end + return true +end + +local function releaseAction(index) + local records=RuenUICharacter.petExtraActions + local record=records and records[index] + if not record then return true end + if GetCursorInfo() then return false end + -- A failed transaction is evidence, not permission to delete an unknown + -- payload or try another slot. Keep it until explicitly reassigned. + if record.failed then return false end + if record.owned and spareSlot(record.slot) and matches(record) then + PickupAction(record.slot);ClearCursor() + end + records[index]=nil -- a player's replacement/borrowed action is never removed + return true +end + +local function syncAction(index,item) + if not item then releaseAction(index);return end + local records=RuenUICharacter.petExtraActions or {} + RuenUICharacter.petExtraActions=records + local record=records[index] + if record and record.failed then return nil,record.failed end + if record and not spareSlot(record.slot) then return nil,"reserved page is in use" end + if record and matches(record) and containsAction(record.slot,item.actionID) then + record.actionID=item.actionID;record.payload=snapshot(record.slot) + return record.slot + end + if GetCursorInfo() then return nil,"cursor busy" end + if record and GetActionInfo(record.slot) and not matches(record) then + record.failed="reserved action changed; reassign the extra button" + return nil,record.failed + end + if not releaseAction(index) then return nil,"assignment paused" end + -- An existing matching action can be borrowed without changing it. This + -- also allows a previously placed action to survive an interrupted setup. + local slot + for candidate=13,24 do + if spareSlot(candidate) and containsAction(candidate,item.actionID) then + records[index]={slot=candidate,actionID=item.actionID,payload=snapshot(candidate),owned=false} + return candidate + end + if not slot and spareSlot(candidate) and not GetActionInfo(candidate) then slot=candidate end + end + if not slot then return nil,"no unused paging slots" end + -- Save intent BEFORE any cursor or slot write. A failed/missing API cannot + -- fan out into additional slots on PET_BAR_UPDATE or CURSOR_CHANGED. + record={slot=slot,actionID=item.actionID,owned=true,failed="pet action placement interrupted"} + records[index]=record + local ok,err=pcall(function() + C_SpellBook.PickupSpellBookItem(item.slot,bank) + local kind=GetCursorInfo() + if kind~="petaction" then + if kind then ClearCursor() end + record.failed="pet action unavailable";return + end + PlaceAction(slot) + ClearCursor() -- slot was empty, so no player action can be displaced + record.payload=snapshot(slot) + if containsAction(slot,item.actionID) then record.failed=nil + else record.failed="pet action placement rejected; automatic retries stopped" end + end) + if not ok then record.failed=tostring(err) end + if record.failed then return nil,record.failed end + return slot +end + +local function learnedItems() + local items={} + if not bank or not C_SpellBook or not C_SpellBook.HasPetSpells then return items end + for slot=1,C_SpellBook.HasPetSpells() or 0 do + local info=C_SpellBook.GetSpellBookItemInfo(slot,bank) + if info and not info.isPassive and not C_SpellBook.IsSpellBookItemPassive(slot,bank) then + local id=info.spellID or info.actionID + local name=C_SpellBook.GetSpellBookItemName(slot,bank) + local command=commandMacros[info.actionID] + local spell=not command and id and C_Spell.GetSpellInfo(id) + if name and name~="" and (command or (spell and spell.name==name)) then + items[#items+1]={id=id,actionID=info.actionID,name=name,slot=slot, + command=command,icon=info.iconID or (spell and spell.iconID)} + end + end + end + return items +end + +function P.PetExtraGeometry() + local bar, first = PetActionBar, PetActionButton1 + local scale = UIParent:GetEffectiveScale() + local size = first and first:GetWidth() * first:GetEffectiveScale() / scale or 39 + local width = bar and bar:GetWidth() * bar:GetEffectiveScale() / scale or 408 + local gap = math.max(0, (width - size * 10) / 9) + return size, gap, 2 * (size + gap) +end + +function P.PetExtraChoices() + local choices, used = {}, {} + if not bank or not C_SpellBook or not C_SpellBook.HasPetSpells then return choices end + for i = 1, 10 do + local name, _, token, _, _, _, id = GetPetActionInfo(i) + if id then used[id] = true end + if name then used[token and _G[name] or name] = true end + end + for slot = 1, C_SpellBook.HasPetSpells() or 0 do + local info = C_SpellBook.GetSpellBookItemInfo(slot, bank) + if info and not info.isPassive and not C_SpellBook.IsSpellBookItemPassive(slot, bank) then + local id = info.spellID or info.actionID + local spell = id and C_Spell.GetSpellInfo(id) + -- Pet command tokens (Attack/Follow/Stance) are not spell IDs. + -- Validate the name before treating a PetAction's actionID as one. + local name = C_SpellBook.GetSpellBookItemName(slot, bank) + if spell and name and name ~= "" and spell.name == name and not used[id] and not used[name] then + choices[#choices + 1] = {id = id, actionID = info.actionID, name = name, slot = slot, + icon = info.iconID or spell.iconID} + used[id], used[name] = true, true + end + end + end + return choices +end + +local function visuals(button) + local item = button.item + button:SetChecked(false) + if not item then + button.AutoCastOverlay:Hide() + button.cooldown:Clear() + return + end + if not button.actionSlot then + button.icon:SetVertexColor(.4,.4,.4) + button.AutoCastOverlay:Hide();button.cooldown:Clear() + return + end + -- A pet or rank can change during combat. Do not read a different spell + -- through a stale slot; secure attributes are rebuilt after combat ends. + local info = C_SpellBook.GetSpellBookItemInfo(item.slot, bank) + if not info or (info.spellID or info.actionID) ~= item.id then + button.icon:SetVertexColor(.4, .4, .4) + button.AutoCastOverlay:Hide() + button.cooldown:Clear() + return + end + if item.command then + button.icon:SetVertexColor(1,1,1) + if C_ActionBar and C_ActionBar.IsCurrentAction then + button:SetChecked(C_ActionBar.IsCurrentAction(button.actionSlot)) + end + button.AutoCastOverlay:Hide();button.cooldown:Clear() + return + end + local usable = C_SpellBook.IsSpellBookItemUsable(item.slot, bank) + local inRange = C_SpellBook.IsSpellBookItemInRange(item.slot, bank, "target") + if inRange == false then button.icon:SetVertexColor(1, .25, .25) + elseif usable then button.icon:SetVertexColor(1, 1, 1) + else button.icon:SetVertexColor(.4, .4, .4) end + local allowed, active = C_SpellBook.GetSpellBookItemAutoCast(item.slot, bank) + button.AutoCastOverlay:SetShown(allowed) + button.AutoCastOverlay:ShowAutoCastEnabled(active) + -- Combat cooldown values may be secret. Let the native widget render the + -- opaque duration; Lua must not compare, format or do arithmetic on it. + if C_SpellBook.GetSpellBookItemCooldownDuration and button.cooldown.SetCooldownFromDurationObject then + local duration=C_SpellBook.GetSpellBookItemCooldownDuration(item.slot,bank) + if duration then button.cooldown:SetCooldownFromDurationObject(duration,true) + else button.cooldown:Clear() end + else + local cd=C_SpellBook.GetSpellBookItemCooldown(item.slot,bank) + if cd then button.cooldown:SetCooldown(cd.startTime,cd.duration,cd.modRate) + else button.cooldown:Clear() end + end +end + +local function hotkeys() + for _, button in ipairs(buttons or {}) do + local key = GetBindingKey("CLICK " .. button:GetName() .. ":LeftButton") + button.HotKey:SetText(key and GetBindingText(key, true) or "") + end +end + +local function updateVisuals(self,dt) + self.visualElapsed=(self.visualElapsed or 0)+dt + if self.visualElapsed>=.2 then self.visualElapsed=0;visuals(self) end +end + +local function copyArt(button, prototype, kind) + local getter=prototype["Get" .. kind .. "Texture"] + local setter=button["Set" .. kind .. "Texture"] + local targetGetter=button["Get" .. kind .. "Texture"] + if type(getter)~="function" or type(setter)~="function" or type(targetGetter)~="function" then return end + local source=getter(prototype) + if not source then return end + local atlas = source:GetAtlas() + local atlasSetter=button["Set" .. kind .. "Atlas"] + if atlas and type(atlasSetter)=="function" then atlasSetter(button,atlas) + else setter(button,source:GetTexture()) end + local target=targetGetter(button) + if not target then return end + target:ClearAllPoints() + target:SetPoint("CENTER") + target:SetSize(source:GetWidth() / prototype:GetWidth() * button:GetWidth(), + source:GetHeight() / prototype:GetHeight() * button:GetHeight()) + target:SetTexCoord(source:GetTexCoord()) +end + +function P.RefreshPetExtras() + if not buttons or InCombatLockdown() then return end + if P.RecoverLegacyPetActions and not P.RecoverLegacyPetActions() then return end + local active = not RuenUIDB.disabled and enabled() + if not active then + for i, button in ipairs(buttons) do releaseAction(i);button:Hide() end + return + end + local choices = P.PetExtraChoices() + local learned=learnedItems() + local selected,used={},{} + nativeItems={} + for _,item in ipairs(learned) do + for i=1,10 do + local name,_,token,_,_,_,id=GetPetActionInfo(i) + if name then name=token and _G[name] or name end + if id==item.id or name==item.name then nativeItems[i]=item end + end + for i,saved in pairs(RuenUICharacter.petExtraAssignments or {}) do + if saved.id==item.id or (not item.command and saved.name==item.name) then + selected[i]=item;used[item.id]=true + end + end + end + local nextChoice=1 + for i=1,2 do + if not selected[i] then + while choices[nextChoice] and used[choices[nextChoice].id] do nextChoice=nextChoice+1 end + selected[i]=choices[nextChoice] + if selected[i] then used[selected[i].id]=true;nextChoice=nextChoice+1 end + end + end + local size, gap = P.PetExtraGeometry() + local ratio = UIParent:GetEffectiveScale() / PetActionBar:GetEffectiveScale() + local previous = PetActionButton10 + local status = {nativeSlots = 10, visibleSlots = 12, abilities = {}, spellBook = {}, actions={}} + for slot=13,36 do status.actions[slot]=snapshot(slot) end + for slot = 1, C_SpellBook.HasPetSpells() or 0 do + status.spellBook[slot] = C_SpellBook.GetSpellBookItemInfo(slot, bank) + end + for i, button in ipairs(buttons) do + local item = selected[i] + local actionSlot,reason=syncAction(i,item) + button.item = item + button.actionSlot=actionSlot + button.activationError=reason + button:SetScript("OnUpdate",item and updateVisuals or nil) + button:SetSize(size * ratio, size * ratio) + button:ClearAllPoints() + button:SetPoint("LEFT", previous, "RIGHT", gap * ratio, 0) + previous = button + for _, kind in ipairs({"Normal", "Pushed", "Highlight", "Checked"}) do copyArt(button, PetActionButton1, kind) end + button:SetAttribute("type1", actionSlot and "action" or nil) + button:SetAttribute("action1", actionSlot) + button:SetAttribute("type2", nil) -- right-click is autocast, not a cast + button:SetAttribute("macrotext1", nil) + button:SetAttribute("macrotext2", nil) + button.icon:SetTexture(item and item.icon or nil) + button:Show() -- Parent is the native pet bar: native pet/vehicle visibility still applies. + visuals(button) + if item then status.abilities[i] = {spellID = item.id, name = item.name, + actionID=item.actionID,actionSlot=actionSlot,error=reason} end + end + if RuenUICharacter then RuenUICharacter.petExtraStatus = status end + hotkeys() +end + +local function receive(button) + if InCombatLockdown() or (C_CVar.GetCVar("lockActionBars")=="1" and not IsModifiedClick("PICKUPACTION")) then return end + local kind,id,book,spellID=GetCursorInfo() + if kind~="petaction" and kind~="spell" then return end + local selected + for _,item in ipairs(learnedItems()) do + if (kind=="petaction" and (id==item.actionID or id==item.id + or (cursorItem and cursorItem.id==item.id))) + or (kind=="spell" and (spellID==item.id + or ((book==bank or book=="pet") and id==item.slot))) then + selected=item;break + end + end + if not selected then return end -- player spells/items never become pet actions + RuenUICharacter.petExtraAssignments=RuenUICharacter.petExtraAssignments or {} + local assignments=RuenUICharacter.petExtraAssignments + local previous=assignments[button.extraIndex] + for i,saved in pairs(assignments) do + if i~=button.extraIndex and saved.id==selected.id then assignments[i]=previous end + end + assignments[button.extraIndex]={id=selected.id,name=selected.name} + local actions=RuenUICharacter.petExtraActions + if actions and actions[button.extraIndex] and actions[button.extraIndex].failed then + -- Preserve the failure receipt, and leave its engine slot untouched. + RuenUICharacter.petExtraLastFailure=actions[button.extraIndex] + actions[button.extraIndex]=nil + end + ClearCursor();cursorItem=nil + P.RefreshPetExtras() +end + +function P.ResetPetExtras() + if InCombatLockdown() then return false end + RuenUICharacter.petExtraAssignments=nil + for i,record in pairs(RuenUICharacter.petExtraActions or {}) do + if record.failed then + RuenUICharacter.petExtraLastFailure=record + RuenUICharacter.petExtraActions[i]=nil + end + end + P.RefreshPetExtras() + return true +end + +local function queue() + if queued then return end + queued = true + C_Timer.After(.1, function() + queued = false + if InCombatLockdown() then listener:RegisterEvent("PLAYER_REGEN_ENABLED"); return end + listener:UnregisterEvent("PLAYER_REGEN_ENABLED") + P.RefreshPetExtras() + end) +end + +function P.InitializePetExtras(isEnabled) + enabled = isEnabled + if buttons or not bank or not PetActionButton10 or not C_SpellBook then return end + if InCombatLockdown() then return end + buttons = {} + for i = 11, 12 do + local button = CreateFrame("CheckButton", "RuenPetExtraButton" .. i, PetActionBar, "SecureActionButtonTemplate") + -- ResizeLayoutMixin otherwise counts these children in the native ten + -- slots' width, then our twelve-slot centering counts them a second time. + button.ignoreInLayout=true + button.extraIndex=i-10 + _G["BINDING_NAME_CLICK RuenPetExtraButton" .. i .. ":LeftButton"] = P.Localized("Pet: extra ability ", "Питомец: дополнительная способность ") .. (i - 10) + button:RegisterForClicks("AnyDown", "AnyUp") + -- Same release-only autocast path as native ordinary pet-action buttons. + -- Casting remains in SecureActionButtonTemplate's original OnClick. + button:SetScript("PostClick",function(self,mouseButton,down) + if mouseButton=="RightButton" and not down and self.actionSlot and C_ActionBar + and C_ActionBar.IsAutoCastPetAction(self.actionSlot) then + C_ActionBar.ToggleAutoCastPetAction(self.actionSlot) + end + if not down then visuals(self) end + end) + -- Some client button templates have no checked-texture getter. + -- Give our own check button a selected-state texture independently. + button:SetCheckedTexture("Interface\\Buttons\\CheckButtonHilight") + button.icon = button:CreateTexture(nil, "BACKGROUND") + button.icon:SetAllPoints() + button.cooldown = CreateFrame("Cooldown", nil, button, "CooldownFrameTemplate") + button.cooldown:SetAllPoints() + button.AutoCastOverlay = CreateFrame("Frame", nil, button, "AutoCastOverlayTemplate") + button.AutoCastOverlay:SetPoint("TOPLEFT", 1, -1) + button.AutoCastOverlay:SetPoint("BOTTOMRIGHT", -1, 1) + button.HotKey = button:CreateFontString(nil, "OVERLAY", "NumberFontNormalSmall") + button.HotKey:SetPoint("TOPRIGHT", -1, -2) + button.HotKey:SetTextColor(.8, .8, .8) + button:SetScript("OnEnter", function(self) + GameTooltip_SetDefaultAnchor(GameTooltip, self) + if self.item and not self.item.command then GameTooltip:SetSpellByID(self.item.id) + else + GameTooltip:SetText(self.item and self.item.name or P.Localized("Extra pet ability", "Дополнительная способность питомца")) + end + GameTooltip:AddLine(P.Localized("Drag a learned pet ability or command here while unlocked. /ruen pet auto restores automatic overflow.", + "Перетащите способность или команду питомца при снятой блокировке. /ruen pet auto — автоматический выбор."),1,1,1,true) + if self.activationError then + GameTooltip:AddLine(P.Localized("Not ready: ","Не готово: ")..self.activationError,1,.3,.3,true) + end + GameTooltip:Show() + end) + button:SetScript("OnLeave", function(self) if GameTooltip:GetOwner() == self then GameTooltip:Hide() end end) + -- Copying back to the native bar is safe and follows its lock setting. + -- The extras then automatically expose whichever abilities are missing. + button:RegisterForDrag("LeftButton") + button:SetScript("OnReceiveDrag",receive) + button:SetScript("OnDragStart", function(self) + if not InCombatLockdown() and self.item and + (C_CVar.GetCVar("lockActionBars") ~= "1" or IsModifiedClick("PICKUPACTION")) then + C_SpellBook.PickupSpellBookItem(self.item.slot, bank) + end + end) + buttons[#buttons + 1] = button + end + listener = CreateFrame("Frame") + for _, event in ipairs({"UNIT_PET", "PET_BAR_UPDATE", "PET_UI_UPDATE", "SPELLS_CHANGED", "SPELL_TEXT_UPDATE", "PLAYER_ENTERING_WORLD", "ACTIONBAR_SLOT_CHANGED", "ACTIONBAR_PAGE_CHANGED"}) do + listener:RegisterEvent(event) + end + listener:RegisterEvent("UPDATE_BINDINGS") + listener:RegisterEvent("CURSOR_CHANGED") + listener:SetScript("OnEvent", function(_, event, unit) + if event == "UPDATE_BINDINGS" then hotkeys(); return end + if event == "CURSOR_CHANGED" then + if not GetCursorInfo() then cursorItem=nil;queue() end + return + end + if event=="ACTIONBAR_SLOT_CHANGED" and unit and unit~=0 and (unit<13 or unit>24) then return end + if event == "UNIT_PET" and unit ~= "player" then return end + queue() + end) + -- Cursor payloads differ between native pet-slot and spellbook dragging. + -- Remember the source without replacing either native drag handler. + hooksecurefunc(C_SpellBook,"PickupSpellBookItem",function(slot,spellBank) + if spellBank~=bank or InCombatLockdown() then return end + for _,item in ipairs(learnedItems()) do if item.slot==slot then cursorItem=item;break end end + end) + if PickupPetAction then hooksecurefunc("PickupPetAction",function(index) + if not InCombatLockdown() then cursorItem=nativeItems[index] end + end) end + PetActionBar:HookScript("OnShow", queue) + PetActionBar:HookScript("OnSizeChanged", queue) + EditModeManagerFrame:HookScript("OnShow", queue) + EditModeManagerFrame:HookScript("OnHide", queue) + P.RefreshPetExtras() +end diff --git a/RuenUI/Profile.lua b/RuenUI/Profile.lua new file mode 100644 index 0000000..629752c --- /dev/null +++ b/RuenUI/Profile.lua @@ -0,0 +1,76 @@ +local _, P = ... +P.version = 5 +P.release = "2026.11.21.5-beta.1" +P.graphicsVersion = 2 +P.layoutName = "Ruen UI - Clear ESDF" +function P.IsOurLayout(layout) + return layout and (layout.layoutName == P.layoutName or layout.layoutName == P.legacyLayoutName) +end +-- Save uses the full native layout list, including preset slots. Work on a +-- detached copy: writing manager/systemInfo tables contaminates secure handlers. +function P.CopyEditModeLayouts() + local manager = EditModeManagerFrame + if manager and manager.layoutInfo then return CopyTable(manager.layoutInfo) end + return CopyTable(C_EditMode.GetLayouts()) +end +function P.SaveEditModeLayouts(info) + C_EditMode.SaveLayouts(info) + -- Saving persists the data; explicitly select it to refresh native systems + -- now, rather than showing their previous settings until the next reload. + if info.activeLayout then C_EditMode.SetActiveLayout(info.activeLayout) end +end +-- Values verified against Blizzard's Forever (Camelot) SettingsDefinitions. +-- Quality sliders are zero-based; do not set the master preset afterward. +P.graphics = { + {"graphicsShadowQuality", 2}, -- Good + {"graphicsSSAO", 1}, -- Low ambient shading; cheaper at 1440p + {"graphicsComputeEffects", 2}, -- Good + {"graphicsLightMode", 1}, -- Good secondary lighting + {"graphicsLiquidDetail", 2}, -- Good legacy water + {"graphicsPBRLiquidDetail", 1}, -- High new water + {"graphicsTextureResolution", 2}, -- High + {"graphicsParticleDensity", 2}, -- Good; keep combat cues + {"graphicsSpellDensity", 0}, -- Essential + {"graphicsProjectedTextures", 1}, + {"graphicsDepthEffects", 0}, + {"MSAAQuality", "0,0"}, -- No expensive multisampling/supersampling + {"msaaAlphaTest", 0}, + {"ffxAntiAliasingMode", 1}, -- Low-cost FXAA + {"graphicsViewDistance", 3}, -- 4/10 to reduce CPU/draw-call load + {"graphicsEnvironmentDetail", 3}, -- 4/10 + {"graphicsGroundClutter", 4}, -- 5/10 grass distance + {"groundEffectDensity", 24}, + {"RenderScale", 1}, + {"bloomUserMult", 0.4}, + {"maxFPS", 60}, {"useMaxFPS", 1}, + {"maxFPSBk", 15}, {"useMaxFPSBk", 1}, + {"targetFPS", 60}, {"useTargetFPS", 1}, + {"vsync", 0}, + {"RAIDsettingsEnabled", 0}, -- Same tested profile in groups; no stale preset 2 +} +P.performance = { + {"graphicsComputeEffects", 2}, {"graphicsLightMode", 1}, + {"graphicsShadowQuality", 1}, {"graphicsSSAO", 1}, + {"graphicsViewDistance", 2}, {"graphicsEnvironmentDetail", 2}, + {"graphicsGroundClutter", 4}, {"groundEffectDensity", 24}, + {"maxFPS", 45}, -- Cooler fallback for busy areas or long sessions + {"RenderScale", 1}, -- Preserve clarity in the fallback too +} +P.gameplay = { + {"profanityFilter", 0}, -- show chat without mature-language substitutions + {"autoLootDefault", 1}, {"combinedBags", 1}, + {"cameraSmoothStyle", 0}, {"cameraDistanceMaxZoomFactor", 4}, + {"lockActionBars", 0}, {"countdownForCooldowns", 1}, {"UberTooltips", 1}, + {"statusText", 1}, {"statusTextDisplay", "BOTH"}, + {"showTargetOfTarget", 1}, + {"raidFramesDisplayPowerBars", 1}, + {"raidFramesDisplayOnlyHealerPowerBars", 0}, + {"raidFramesDisplayClassColor", 1}, + {"raidFramesDisplayAggroHighlight", 1}, + {"raidFramesDisplayIncomingHeals", 1}, + {"raidFramesHealthText", "perc"}, + {"nameplateShowEnemies", 1}, {"nameplateShowAll", 1}, + {"enablePings", 1}, + {"cooldownViewerEnabled", 1}, {"showSwingTimer", 0}, + {"Sound_EnableSoundWhenGameIsInBG", 1}, +} diff --git a/RuenUI/RuenUI.toc b/RuenUI/RuenUI.toc new file mode 100644 index 0000000..39e07f8 --- /dev/null +++ b/RuenUI/RuenUI.toc @@ -0,0 +1,26 @@ +## Interface: 16001 +## Title: Ruen UI +## Notes: ESDF, mouse and menu controls, inventory layout and Spoken language controls. /ruen help +## Version: 2026.11.21.5-beta.1 +## Author: Ruen UI contributors +## SavedVariables: RuenUIDB +## SavedVariablesPerCharacter: RuenUICharacter +## Dependencies: Spoken, Spoken_Quests +## OptionalDeps: Leatrix_Plus, Leatrix_Maps, GunSilencerForever +Profile.lua +Locale.lua +Brand.lua +LanguageDefaults.lua +Controls.lua +GunAudio.lua +ClassLayout.lua +PetExtras.lua +SwingTimers.lua +ExtraBars.lua +OverlayLayout.lua +DamageMeters.lua +ClassAssist.lua +HardwareProfile.lua +Optimizer.lua +AddonPresets.lua +Core.lua diff --git a/RuenUI/SwingTimers.lua b/RuenUI/SwingTimers.lua new file mode 100644 index 0000000..416b69d --- /dev/null +++ b/RuenUI/SwingTimers.lua @@ -0,0 +1,162 @@ +local _, P = ... + +-- PLAYER_SWING supplies the client's own duration for each weapon, including +-- druid forms and ranged/wand attacks. No combat-log guesses or attack macros. +P.swingDockHeight = 13 +P.swingCastGap = 18 -- the native cast's spell name extends below its frame +local dock, allowed, lanes +local FADE = 0.25 +local colors = {{0.78, 0.64, 0.34}, {0.42, 0.67, 0.70}, {0.60, 0.72, 0.43}} + +local function enabled() + return RuenUIDB and not RuenUIDB.disabled + and RuenUIDB.swingTimersEnabled ~= false and allowed and allowed() +end + +local function number(value) + return not (issecretvalue and issecretvalue(value)) and type(value) == "number" + and value == value and value > 0 and value < 120 +end + +local function clear() + if not dock then return end + for _, lane in ipairs(lanes) do + lane.finish, lane.duration = nil, nil + lane:Hide() + end + dock.preview = nil + dock:SetScript("OnUpdate", nil) + dock:Hide() +end +P.StopSwingTimers = clear + +local function paint() + if not enabled() then clear(); return end + local now, row = GetTime(), 0 + for _, lane in ipairs(lanes) do + if lane.finish and now >= lane.finish + FADE then + lane.finish, lane.duration = nil, nil + end + if lane.finish then + local value = math.min(1, math.max(0, 1 - (lane.finish - now) / lane.duration)) + lane:SetValue(value) + lane:SetAlpha(math.min(1, math.max(0, (lane.finish + FADE - now) / FADE))) + if lane.row ~= row then + lane:ClearAllPoints() + lane:SetPoint("TOPLEFT", dock, "TOPLEFT", 0, -row * 5) + lane:SetPoint("TOPRIGHT", dock, "TOPRIGHT", 0, -row * 5) + lane.row = row + end + lane:Show() + row = row + 1 + else + lane:Hide() + end + end + if row == 0 then clear() end +end + +local function start(duration, swingType) + if not enabled() or not number(duration) then return end + if issecretvalue and issecretvalue(swingType) then return end + local lane = dock.byType[swingType] + if not lane then return end + lane.duration, lane.finish = duration, GetTime() + duration + dock:Show() + paint() + -- Only runs while at least one short timer/fade is visible; zero idle tickers. + dock:SetScript("OnUpdate", paint) +end + +local function equipmentChanged() + if not lanes then return end + local speed = {UnitAttackSpeed("player")} + for i, lane in ipairs(lanes) do + if not number(speed[i]) then lane.finish, lane.duration = nil, nil end + end + paint() +end + +function P.InitializeSwingTimers(predicate) + allowed = predicate + if dock then return end + if not Enum.PlayerSwingType then return end + dock = CreateFrame("Frame", "RuenSwingTimers", UIParent) + dock:SetSize(208, P.swingDockHeight) + dock:SetPoint("BOTTOM", UIParent, "BOTTOM", 197) + dock:SetFrameStrata("MEDIUM") + dock:EnableMouse(false) + lanes, dock.byType = {}, {} + local types = {Enum.PlayerSwingType.MainHand, Enum.PlayerSwingType.OffHand, Enum.PlayerSwingType.Ranged} + for i, swingType in ipairs(types) do + local lane = CreateFrame("StatusBar", nil, dock) + lane:SetHeight(3) + lane:SetMinMaxValues(0, 1) + lane:SetStatusBarTexture("Interface\\Buttons\\WHITE8X8") + lane:SetStatusBarColor(unpack(colors[i])) + lane:EnableMouse(false) + local background = lane:CreateTexture(nil, "BACKGROUND") + background:SetAllPoints() + background:SetColorTexture(0.02, 0.025, 0.03, 0.75) + lane:Hide() + lanes[i], dock.byType[swingType] = lane, lane + end + dock:SetScript("OnEvent", function(_, event, a, b) + if event == "PLAYER_SWING" then + if dock.preview then clear() end + start(a, b) + if RuenUICharacter and number(a) and not (issecretvalue and issecretvalue(b)) then + RuenUICharacter.lastSwing = {duration = a, swingType = b, time = time()} + end + elseif event == "UNIT_INVENTORY_CHANGED" or event == "UNIT_ATTACK_SPEED" then + if a == "player" then equipmentChanged() end + elseif event == "WEAPON_SLOT_CHANGED" then + -- The native bar restarts an in-progress timer after a weapon swap. + local speeds = {UnitAttackSpeed("player")} + for i, lane in ipairs(lanes) do + if lane.finish then + if number(speeds[i]) then start(speeds[i], types[i]) + else lane.finish, lane.duration = nil, nil end + end + end + paint() + else + clear() -- zoning, death, combat ending, or changing form + end + end) + for _, event in ipairs({"PLAYER_SWING", "PLAYER_ENTERING_WORLD", "PLAYER_DEAD", + "PLAYER_REGEN_ENABLED", "UPDATE_SHAPESHIFT_FORM", "WEAPON_SLOT_CHANGED"}) do + pcall(dock.RegisterEvent, dock, event) + end + dock:RegisterUnitEvent("UNIT_INVENTORY_CHANGED", "player") + dock:RegisterUnitEvent("UNIT_ATTACK_SPEED", "player") + clear() +end + +function P.PositionSwingTimers(plan, width, place) + if not dock then return end + dock:SetWidth(width) + local point = plan.RuenSwingTimers + place(dock, point[1], UIParent, "BOTTOM", point[2], point[3]) +end + +function P.SwingCommand(option) + if not dock then return P.Localized("Swing timing is unavailable in this client.", "Таймеры атак недоступны в этом клиенте.") end + if option == "off" then + RuenUIDB.swingTimersEnabled = false + clear() + elseif option == "on" then + RuenUIDB.swingTimersEnabled = true + elseif option == "preview" then + if InCombatLockdown() then return P.Localized("Preview is available outside combat.", "Предпросмотр доступен вне боя.") end + if not enabled() then return P.Localized("Enable the Ruen layout and /ruen swing on first.", "Сначала включите макет Ruen и /ruen swing on.") end + clear() + for swingType in pairs(dock.byType) do start(6, swingType) end + dock.preview = true + return P.Localized("Swing preview: gold main hand, blue off hand, green ranged. Only active attacks appear during play.", + "Таймеры: золотой — основная рука, голубой — вторая, зелёный — дальний бой. В игре видны только активные атаки.") + end + return P.Localized("Swing timers: ", "Таймеры атак: ") + .. (RuenUIDB.swingTimersEnabled == false and "OFF" or "ON") + .. ". /ruen swing on | off | preview" +end diff --git a/Tools/Measure-RuenHardware.ps1 b/Tools/Measure-RuenHardware.ps1 new file mode 100644 index 0000000..b8877cc --- /dev/null +++ b/Tools/Measure-RuenHardware.ps1 @@ -0,0 +1,79 @@ +[CmdletBinding()] +param([Parameter(Mandatory=$true)][string]$WoWPath,[ValidateRange(1,1800)][int]$Seconds=600,[switch]$Baseline,[ValidatePattern('^\d+$')][ValidateRange(20,240)][string]$FPS='60') +$ErrorActionPreference='Stop' +$game=(Get-Item -LiteralPath $WoWPath).FullName +if ((Split-Path -Leaf $game) -ne '_forever_') { $game=Join-Path $game '_forever_' } +$addon=Join-Path $game 'Interface/AddOns/RuenUI' +if (!(Test-Path -LiteralPath (Join-Path $addon 'RuenUI.toc'))) { throw 'Install Ruen UI in this Forever folder first.' } +$nvidia=Get-Command nvidia-smi.exe -ErrorAction SilentlyContinue +$nvidiaPath=if ($nvidia) {$nvidia.Source} else { Join-Path $env:ProgramFiles 'NVIDIA Corporation/NVSMI/nvidia-smi.exe' } +function Get-Nvidia { + if (!(Test-Path -LiteralPath $nvidiaPath)) { return $null } + $p=New-Object System.Diagnostics.Process + $p.StartInfo.FileName=$nvidiaPath + $p.StartInfo.Arguments='--query-gpu=name,temperature.gpu,utilization.gpu,clocks_event_reasons.hw_thermal_slowdown,clocks_event_reasons.sw_thermal_slowdown --format=csv,noheader,nounits' + $p.StartInfo.UseShellExecute=$false;$p.StartInfo.RedirectStandardOutput=$true;$p.StartInfo.RedirectStandardError=$true;$p.StartInfo.CreateNoWindow=$true + try { + if (!$p.Start()) { return $null } + if (!$p.WaitForExit(4000)) { $p.Kill();return $null } + $rows=@($p.StandardOutput.ReadToEnd() -split "`n" | Where-Object { $_.Trim() } | ConvertFrom-Csv -Header Name,Temp,Load,HW,SW) + if (!$rows.Count) {return $null} + $temps=@();$loads=@();$thermal=$false + foreach($r in $rows){ + $x=0.0;if([double]::TryParse($r.Temp,[ref]$x)){$temps+=$x} + $x=0.0;if([double]::TryParse($r.Load,[ref]$x)){$loads+=$x} + if($r.HW.Trim() -eq 'Active' -or $r.SW.Trim() -eq 'Active'){$thermal=$true} + } + if (!$temps.Count) {return $null} + return @{temperature=($temps|Measure-Object -Maximum).Maximum;load=($loads|Measure-Object -Maximum).Maximum;thermal=$thermal} + } catch {return $null} finally {$p.Dispose()} +} +function Get-Temperatures { + # Use an already running hardware monitor, if present. Never install a driver. + foreach($ns in @('root/LibreHardwareMonitor','root/OpenHardwareMonitor')){ + try { + $sensors=Get-CimInstance -Namespace $ns -ClassName Sensor -OperationTimeoutSec 2 -ErrorAction Stop + return @($sensors|Where-Object {$_.SensorType -eq 'Temperature' -and $_.Identifier -match 'cpu|gpu|intel|amd' -and $_.Value -gt 0 -and $_.Value -lt 130}|ForEach-Object { + @{sensor=[string]$_.Identifier;celsius=[double]$_.Value;limit=$(if($_.Identifier -match 'gpu'){83}else{90})} + }) + }catch{} + } + return @() +} +$samples=New-Object 'System.Collections.Generic.List[object]' +$clock=[Diagnostics.Stopwatch]::StartNew();$hotCount=0;$thermal=$false;$limitedCount=0 +Write-Host 'Play normally in WoW. Checking this PC for up to 10 minutes; no stress test or driver changes.' +do { + $temps=@(Get-Temperatures);$g=Get-Nvidia + $cpu=Get-CimInstance Win32_PerfFormattedData_Counters_ProcessorInformation -Filter "Name='_Total'" -OperationTimeoutSec 3 -ErrorAction SilentlyContinue + # Low clock under load is performance limiting, not proof of thermal throttling. + $limited=$cpu -and $cpu.PercentProcessorUtility -ge 80 -and $cpu.PercentPerformance -lt 80 + if($limited){$limitedCount++} + $hot=@($temps|Where-Object {$_.celsius -ge $_.limit}).Count -gt 0 + if($g){$hot=$hot -or $g.temperature -ge 83;$thermal=$thermal -or $g.thermal} + $hotCount=if($hot){$hotCount+1}else{0} + $samples.Add(@{time=[DateTimeOffset]::UtcNow.ToUnixTimeSeconds();temperatures=$temps;gpu=$g;performanceLimited=[bool]$limited; + cpuLoad=$(if($cpu){$cpu.PercentProcessorUtility}else{$null});gameRunning=[bool](Get-Process Wow,WowClassic -ErrorAction SilentlyContinue)}) + if($clock.Elapsed.TotalSeconds -ge $Seconds -or $thermal -or $hotCount -ge 3){break} + Start-Sleep -Seconds ([Math]::Min(5,[Math]::Ceiling($Seconds-$clock.Elapsed.TotalSeconds))) +}while($true) +$underLoad=@($samples|Where-Object {$_.gameRunning -and ($_.cpuLoad -gt 15 -or ($_.gpu -and $_.gpu.load -gt 20))}).Count +$loaded=$clock.Elapsed.TotalSeconds -ge 180 -and $underLoad -ge $samples.Count*.6 +$cpuSeen=@($temps|Where-Object {$_.sensor -match 'cpu'}).Count -gt 0 +$gpuSeen=[bool]$g -or @($temps|Where-Object {$_.sensor -match 'gpu'}).Count -gt 0 +$coverage=if($cpuSeen -and $gpuSeen){'full'}elseif($cpuSeen -or $gpuSeen){'partial'}else{'unavailable'} +$evidence=if($thermal){'thermal throttling observed'}elseif($hotCount -ge 3){'temperature headroom low'}elseif($g -or $temps.Count){'no thermal limit observed in sample; CPU coverage depends on available sensors'}else{'thermal sensors unavailable'} +$now=[DateTimeOffset]::UtcNow.ToUnixTimeSeconds() +$report=@{format=1;platform='Windows';checkedAt=$now;duration=[Math]::Round($clock.Elapsed.TotalSeconds,1);loaded=$loaded;targetFPS=[int]$FPS; + thermalCoverage=$coverage;thermalPressure=($thermal -or $hotCount -ge 3);performancePressure=($limitedCount -ge 6);evidence=$evidence;samples=@($samples.ToArray())} +$reports=Join-Path $game 'Ruen-UI-Reports';New-Item -ItemType Directory -Path $reports -Force|Out-Null +$dest=Join-Path $reports 'hardware.json' +if(Test-Path -LiteralPath $dest){Copy-Item -LiteralPath $dest -Destination (Join-Path $reports 'hardware.previous.json') -Force} +$utf8=New-Object Text.UTF8Encoding($false) +[IO.File]::WriteAllText($dest,($report|ConvertTo-Json -Depth 8),$utf8) +function Lua-Bool($v){if($v){'true'}else{'false'}} +$text="local _, P = ...`nP.hardwareProfile = { targetFPS = $([int]$FPS), thermalCoverage = `"$coverage`", checkedAt = $now, loaded = $(Lua-Bool $loaded), thermalPressure = $(Lua-Bool $report.thermalPressure), performancePressure = $(Lua-Bool $report.performancePressure), autoStart = $(Lua-Bool (!$Baseline)), evidence = `"$evidence`" }`n" +$tmp=Join-Path $addon 'HardwareProfile.lua.tmp';[IO.File]::WriteAllText($tmp,$text,$utf8) +Move-Item -LiteralPath $tmp -Destination (Join-Path $addon 'HardwareProfile.lua') -Force +Write-Host $evidence +Write-Host 'Report saved locally. /reload imports this PC report; a full evaluation also starts in-game calibration.' diff --git a/Tools/Migrate-RuenUI.ps1 b/Tools/Migrate-RuenUI.ps1 new file mode 100644 index 0000000..fb3a842 --- /dev/null +++ b/Tools/Migrate-RuenUI.ps1 @@ -0,0 +1,44 @@ +# Legacy names are used only to discover and migrate older installations. +function Convert-RuenLegacyText([string]$Text) { + return $Text.Replace('BradStockUI','RuenUI').Replace('BRADSTOCKUI','RUENUI').Replace('BRADUI','RUENUI').Replace('BradTargetTargetTarget','RuenTargetTargetTarget') +} +function Add-RuenMigration([string]$Root, $Plan) { + $changes = New-Object 'System.Collections.Generic.List[object]' + $legacy = 'BradStockUI' + $oldAddon = 'Interface/AddOns/' + $legacy + if (Test-Path -LiteralPath (Join-Path $Root $oldAddon)) { + $changes.Add([pscustomobject]@{path=$oldAddon;source=$null;text=$null;removeOnly=$true}) + } + $accounts = Join-Path $Root 'WTF/Account' + if (Test-Path -LiteralPath $accounts) { + Assert-NoNestedLinks $accounts + $files = @(Get-ChildItem -LiteralPath $accounts -Recurse -File) + foreach ($file in $files) { + $relative = $file.FullName.Substring($Root.Length).TrimStart([char[]]'\/').Replace('\','/') + if ($file.Directory.Name -eq 'SavedVariables' -and $file.Name -in @(($legacy+'.lua'),($legacy+'.lua.bak'))) { + $newPath = $relative.Replace($legacy+'.lua','RuenUI.lua') + if (-not (Test-Path -LiteralPath (Join-Path $Root $newPath))) { + $changes.Add([pscustomobject]@{path=$newPath;source=$null;text=(Convert-RuenLegacyText ([IO.File]::ReadAllText($file.FullName)))}) + } + $changes.Add([pscustomobject]@{path=$relative;source=$null;text=$null;removeOnly=$true}) + } elseif ($file.Name -eq 'bindings-cache.wtf' -or ($file.Directory.Name -eq 'SavedVariables' -and $file.Name -in @('RuenUI.lua','RuenUI.lua.bak'))) { + $text = [IO.File]::ReadAllText($file.FullName) + $updated = Convert-RuenLegacyText $text + if ($updated -ne $text) { $changes.Add([pscustomobject]@{path=$relative;source=$null;text=$updated}) } + } elseif ($file.Name -eq 'AddOns.txt') { + $text = [IO.File]::ReadAllText($file.FullName) + if ($text -match '(?m)^BradStockUI\s*:') { + $lines = @($text -split '\r?\n' | Where-Object { $_ -and $_ -notmatch '^(BradStockUI|RuenUI)\s*:' }) + $changes.Add([pscustomobject]@{path=$relative;source=$null;text=(($lines + 'RuenUI: enabled') -join "`r`n")+"`r`n"}) + } + } + } + } + foreach ($change in $changes) { + $existing = @($Plan | Where-Object { $_.path -eq $change.path }) + # A full install may already have a more complete enabled-addon list. + if (@($existing | Where-Object { -not $_.PSObject.Properties['backupOnly'] }).Count) { continue } + foreach ($item in $existing) { [void]$Plan.Remove($item) } + $Plan.Add($change) + } +} diff --git a/Tools/Resolve-RuenDependencies.ps1 b/Tools/Resolve-RuenDependencies.ps1 new file mode 100644 index 0000000..b174352 --- /dev/null +++ b/Tools/Resolve-RuenDependencies.ps1 @@ -0,0 +1,146 @@ +function Assert-RuenSpace([string]$Path, [long]$Required) { + $item = Get-Item -LiteralPath $Path + $free = $item.PSDrive.Free + if ($null -ne $free -and $free -lt $Required) { throw ('Not enough disk space at ' + $Path + ' for download, extraction and backups.') } +} + +# Download directly from addon authors. Called only after package verification. +function Get-RuenDependencyList([string]$Bundle, [string]$Voices) { + $lock = Get-Content -LiteralPath (Join-Path $Bundle 'dependencies.lock.json') -Raw | ConvertFrom-Json + if ($lock.format -ne 1 -or $lock.interface -ne 16001) { throw 'Unsupported dependency lock.' } + $groups = @('base') + if ($Voices -ne 'none') { $groups += 'en' } + if ($Voices -eq 'enru') { $groups += 'ru' } + $names = @{} + foreach ($p in @($lock.packages | Where-Object { $_.group -in $groups })) { + if ($p.id -notmatch '^[A-Za-z0-9_]+$' -or $p.sha256 -notmatch '^[0-9a-f]{64}$' -or + ([uri]$p.url).Scheme -ne 'https' -or $p.bytes -le 0 -or $p.bytes -gt 2000000000) { + throw 'Invalid pinned dependency.' + } + foreach ($name in $p.folders) { + if ($name -notmatch '^[A-Za-z0-9_]+$' -or $names.ContainsKey($name) -or $name -eq 'RuenUI') { throw 'Invalid addon folder.' } + $names[$name] = $true + } + $p + } +} + +function Test-RuenDependency([string]$Folder) { + $toc = Join-Path $Folder ((Split-Path -Leaf $Folder) + '.toc') + return (Test-Path -LiteralPath $toc -PathType Leaf) -and + [bool](Select-String -LiteralPath $toc -Pattern '^## Interface:.*\b16001\b' -Quiet) +} + +function Get-RuenArchive($Package, [string]$Cache) { + $file = Join-Path $Cache ($Package.id + '-' + $Package.sha256.Substring(0, 12) + '.zip') + Assert-NoLinks $file + if (Test-Path -LiteralPath $file -PathType Leaf) { + if ((Get-Item -LiteralPath $file).Length -eq $Package.bytes -and + (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -eq $Package.sha256) { return $file } + } + Assert-RuenSpace $Cache ($Package.bytes + $Package.max_unpacked_bytes + 134217728) + $part = [IO.Path]::ChangeExtension($file, '.part') + Assert-NoLinks $part + Write-Host ("Downloading {0} ({1} MB)..." -f $Package.id, [math]::Round($Package.bytes / 1000000)) + [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + $request = [Net.HttpWebRequest]::Create($Package.url) + $request.UserAgent = 'RuenUI-Installer/1' + $request.Timeout = 60000 + $request.ReadWriteTimeout = 60000 + $response = $null; $inputStream = $null; $outputStream = $null + try { + $response = $request.GetResponse() + if ($response.ResponseUri.Scheme -ne 'https') { throw 'Refusing a non-HTTPS download redirect.' } + $inputStream = $response.GetResponseStream() + $outputStream = [IO.File]::Create($part) + $buffer = New-Object byte[] 1048576 + [long]$total = 0 + while (($n = $inputStream.Read($buffer, 0, $buffer.Length)) -gt 0) { + $total += $n + if ($total -gt $Package.bytes) { throw 'Download exceeds pinned size.' } + $outputStream.Write($buffer, 0, $n) + } + $outputStream.Dispose(); $outputStream = $null + if ($total -ne $Package.bytes -or (Get-FileHash -LiteralPath $part -Algorithm SHA256).Hash -ne $Package.sha256) { + throw ('Dependency checksum mismatch: ' + $Package.id) + } + Move-Item -LiteralPath $part -Destination $file -Force + # Bound this cache to one archive per locked addon package. + foreach ($old in @(Get-ChildItem -LiteralPath $Cache -File)) { + if ($old.FullName -ne $file -and $old.Name -match ('^' + [regex]::Escape($Package.id) + '-[0-9a-f]{12}\.zip$')) { + Assert-NoLinks $old.FullName + Remove-Item -LiteralPath $old.FullName + } + } + return $file + } finally { + if ($outputStream) { $outputStream.Dispose() } + if ($inputStream) { $inputStream.Dispose() } + if ($response) { $response.Dispose() } + if (Test-Path -LiteralPath $part) { Remove-Item -LiteralPath $part } + } +} + +function Get-RuenArchivePath([string]$Name) { + if (-not $Name -or $Name.Contains('\') -or $Name.Contains(':') -or $Name.StartsWith('/')) { throw 'Unsafe archive filename.' } + $parts = $Name.TrimEnd('/').Split('/') + foreach ($part in $parts) { + if (-not $part -or $part -in @('.', '..') -or $part -match '[\x00-\x1f<>"|?*]' -or + $part -match '[ .]$' -or $part -match '^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\..*)?$') { + throw ('Unsafe archive filename: ' + $Name) + } + } + return $Name.TrimEnd('/') +} + +function Expand-RuenArchive($Package, [string]$Archive, [string]$Stage) { + Add-Type -AssemblyName System.IO.Compression.FileSystem + $zip = [IO.Compression.ZipFile]::OpenRead($Archive) + try { + if ($zip.Entries.Count -gt 100000) { throw 'Archive has too many entries.' } + $seen = @{}; [long]$total = 0 + foreach ($entry in $zip.Entries) { + $rel = Get-RuenArchivePath $entry.FullName + if ($seen.ContainsKey($rel)) { throw ('Duplicate archive filename: ' + $rel) } + $seen[$rel] = $true + if ((($entry.ExternalAttributes -shr 16) -band 61440) -eq 40960) { throw 'Archive links are not allowed.' } + $total += $entry.Length + if ($total -gt $Package.max_unpacked_bytes) { throw 'Archive expands beyond its limit.' } + } + Assert-RuenSpace $Stage ($total + 134217728) + foreach ($entry in $zip.Entries) { + $rel = Get-RuenArchivePath $entry.FullName + if ($rel.Split('/')[0] -notin $Package.folders) { continue } + $target = Safe-RelativePath $Stage $rel + if ($entry.FullName.EndsWith('/')) { [void][IO.Directory]::CreateDirectory($target); continue } + [void][IO.Directory]::CreateDirectory((Split-Path -Parent $target)) + [IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $target, $false) + } + } finally { $zip.Dispose() } + foreach ($folder in $Package.folders) { + if (-not (Test-RuenDependency (Join-Path $Stage $folder))) { throw ('Missing Forever TOC: ' + $folder) } + } +} + +function Prepare-RuenDependencies([string]$Bundle, [string]$Game, [string]$Stage, [string]$Voices, [string]$Cache) { + $sources = @{ RuenUI = (Join-Path $Bundle 'RuenUI') } + $enabled = @('RuenUI') + foreach ($package in @(Get-RuenDependencyList $Bundle $Voices)) { + $missing = @() + foreach ($folder in $package.folders) { + $target = Join-Path $Game ('Interface/AddOns/' + $folder) + Assert-NoNestedLinks $target + if (Test-Path -LiteralPath $target) { + if (-not (Test-RuenDependency $target)) { throw ("Existing $folder is not marked compatible with Forever. Update it from its author first.") } + Write-Host ("Keeping existing $folder") + } else { $missing += $folder } + $enabled += $folder + } + if ($missing.Count) { + $archive = Get-RuenArchive $package $Cache + Expand-RuenArchive $package $archive $Stage + foreach ($folder in $missing) { $sources[$folder] = Join-Path $Stage $folder } + } + } + return @{ Sources = $sources; Enabled = $enabled } +} diff --git a/Tools/Ruen-Setup.c b/Tools/Ruen-Setup.c new file mode 100644 index 0000000..a3926a4 --- /dev/null +++ b/Tools/Ruen-Setup.c @@ -0,0 +1,36 @@ +/* Tiny native Windows entry point: uses the installed Windows PowerShell. + No runtime download, no elevation, no background service. Source is bundled. */ +typedef unsigned short W; typedef unsigned long D; typedef int B; typedef void *H; +typedef struct {D cb;W *reserved,*desktop,*title;D x,y,cx,cy,xc,yc,fill,flags;unsigned short show,reserved2;void *r2;H in,out,err;} STARTUP; +typedef struct {H process,thread;D pid,tid;} PROCESS; +#define API __declspec(dllimport) +API D GetModuleFileNameW(H,W*,D);API W* GetCommandLineW(void);API D GetWindowsDirectoryW(W*,D); +API B CreateProcessW(const W*,W*,void*,void*,B,D,void*,const W*,STARTUP*,PROCESS*); +API D WaitForSingleObject(H,D);API B GetExitCodeProcess(H,D*);API B CloseHandle(H);API void ExitProcess(D); +API B ReadFile(H,void*,D,D*,void*); +API H GetStdHandle(D);API B WriteFile(H,const void*,D,D*,void*); +static W module[32768],exe[32768],cmd[32768];static unsigned pos; +static STARTUP si;static PROCESS pi; +static void add(const W *s){while(*s && pos<32766)cmd[pos++]=*s++;cmd[pos]=0;} +static int starts(const W *p,const W *s){while(*s)if(*p++!=*s++)return 0;return !*p||*p==32;} +void entry(void){ + D n=GetModuleFileNameW(0,module,32768),code=1; + if(!n||n>=32768)ExitProcess(1); + while(n && module[n-1]!=92)--n;module[n]=0; + D m=GetWindowsDirectoryW(exe,32000);const W *suffix=L"\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"; + if(!m||m>=32000)ExitProcess(1);while(*suffix)exe[m++]=*suffix++;exe[m]=0; + W *args=GetCommandLineW();if(*args==34){++args;while(*args&&*args!=34)++args;if(*args)++args;}else while(*args&&*args!=32)++args; + while(*args==32)++args; + int optimize=starts(args,L"--optimize");if(optimize){args+=10;while(*args==32)++args;} + add(L"\"");add(exe);add(L"\" -NoLogo -NoProfile -ExecutionPolicy Bypass -File \"");add(module); + add(optimize?L"Optimize-Ruen-UI.ps1":L"Install-Ruen-UI.ps1");add(L"\" "); + /* --optimize [FPS] is shared with Linux; named PowerShell options still work. */ + if(optimize && *args && (*args!=45 || (args[1]>=48 && args[1]<=57)))add(L"-FPS "); + add(args); + si.cb=sizeof(si); + if(CreateProcessW(exe,cmd,0,0,1,0,0,module,&si,&pi)){ + WaitForSingleObject(pi.process,0xffffffff);GetExitCodeProcess(pi.process,&code);CloseHandle(pi.thread);CloseHandle(pi.process); + }else{const char msg[]="Unable to start Windows PowerShell. Run Install-Ruen-UI.cmd from the extracted package.\r\n";D written;WriteFile(GetStdHandle((D)-12),msg,sizeof(msg)-1,&written,0);} + if(!*args){const char msg[]="\r\nPress Enter to close this window.\r\n";char key;D n;WriteFile(GetStdHandle((D)-11),msg,sizeof(msg)-1,&n,0);ReadFile(GetStdHandle((D)-10),&key,1,&n,0);} + ExitProcess(code); +} diff --git a/Tools/kernel32.def b/Tools/kernel32.def new file mode 100644 index 0000000..2e33d7e --- /dev/null +++ b/Tools/kernel32.def @@ -0,0 +1,13 @@ +LIBRARY KERNEL32.dll +EXPORTS +GetModuleFileNameW +GetCommandLineW +GetWindowsDirectoryW +CreateProcessW +WaitForSingleObject +GetExitCodeProcess +CloseHandle +ExitProcess +GetStdHandle +WriteFile +ReadFile diff --git a/Tools/ruen_dependencies.py b/Tools/ruen_dependencies.py new file mode 100644 index 0000000..fc58a16 --- /dev/null +++ b/Tools/ruen_dependencies.py @@ -0,0 +1,148 @@ +"""Fetch pinned upstream addons for personal installation; never mirror them.""" +import hashlib +import json +import os +from pathlib import Path, PurePosixPath +import re +import shutil +import stat +import urllib.parse +import urllib.request +import zipfile + + +def digest(path): + h = hashlib.sha256() + with Path(path).open('rb') as stream: + for block in iter(lambda: stream.read(1024 * 1024), b''): + h.update(block) + return h.hexdigest() + + +def no_links(path): + path = Path(path).absolute() + if any(p.is_symlink() for p in (path, *path.parents)): + raise ValueError('Use a real folder, not a symbolic link: ' + str(path)) + + +def safe_relative(value): + if not isinstance(value, str) or not value or '\\' in value or ':' in value: + raise ValueError('Unsafe archive/package path') + rel = PurePosixPath(value.rstrip('/')) + if rel.is_absolute() or not rel.parts or any(p in ('', '.', '..') for p in value.rstrip('/').split('/')): + raise ValueError('Unsafe archive/package path: ' + value) + for part in rel.parts: + if part.endswith((' ', '.')) or re.search(r'[\x00-\x1f<>"|?*]', part): + raise ValueError('Unsupported Windows filename: ' + value) + if re.fullmatch(r'(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\..*)?', part, re.I): + raise ValueError('Reserved Windows filename: ' + value) + return Path(*rel.parts) + + +def selected(bundle, voices): + if voices not in ('none', 'en', 'enru'): + raise ValueError('Voice packs must be none, en, or enru') + lock = json.loads((Path(bundle) / 'dependencies.lock.json').read_text()) + if lock.get('format') != 1 or lock.get('interface') != 16001: + raise ValueError('Unsupported dependency lock') + groups = {'base'} | ({'en'} if voices != 'none' else set()) | ({'ru'} if voices == 'enru' else set()) + packages = [p for p in lock['packages'] if p['group'] in groups] + folders = set() + for p in packages: + if not re.fullmatch(r'[A-Za-z0-9_]+', p['id']) or not re.fullmatch(r'[0-9a-f]{64}', p['sha256']): + raise ValueError('Invalid dependency identity') + if urllib.parse.urlsplit(p['url']).scheme != 'https' or not 0 < p['bytes'] <= 2_000_000_000: + raise ValueError('Invalid dependency URL or size') + for name in p['folders']: + if not re.fullmatch(r'[A-Za-z0-9_]+', name) or name in folders or name == 'RuenUI': + raise ValueError('Invalid or duplicate addon folder') + folders.add(name) + return packages + + +def compatible(folder): + toc = Path(folder) / (Path(folder).name + '.toc') + return toc.is_file() and bool(re.search(r'^## Interface:.*\b16001\b', toc.read_text(encoding='utf-8-sig'), re.M)) + + +def download(package, cache): + cache = Path(cache); no_links(cache); cache.mkdir(parents=True, exist_ok=True) + target = cache / (package['id'] + '-' + package['sha256'][:12] + '.zip') + no_links(target) + if target.is_file() and target.stat().st_size == package['bytes'] and digest(target) == package['sha256']: + return target + # Keep one verified archive per package; other applications' files are untouched. + for stale in cache.glob(package['id'] + '-*.zip'): + if stale != target and re.fullmatch(re.escape(package['id']) + r'-[0-9a-f]{12}\.zip', stale.name): + no_links(stale); stale.unlink() + required = package['bytes'] + package['max_unpacked_bytes'] + 128 * 1024 * 1024 + if shutil.disk_usage(cache).free < required: + raise OSError('Not enough free space to download and unpack ' + package['id']) + part = target.with_suffix('.part'); no_links(part) + print('Downloading ' + package['id'] + ' (' + str(round(package['bytes'] / 1_000_000)) + ' MB)...', flush=True) + try: + request = urllib.request.Request(package['url'], headers={'User-Agent': 'RuenUI-Installer/1'}) + with urllib.request.urlopen(request, timeout=60) as response, part.open('wb') as out: + if urllib.parse.urlsplit(response.url).scheme != 'https': + raise ValueError('Refusing a non-HTTPS download redirect') + total = 0 + while True: + block = response.read(1024 * 1024) + if not block: break + total += len(block) + if total > package['bytes']: raise ValueError('Download exceeds pinned size') + out.write(block) + if part.stat().st_size != package['bytes'] or digest(part) != package['sha256']: + raise ValueError('Dependency checksum mismatch: ' + package['id']) + os.replace(part, target) + return target + finally: + if part.exists(): part.unlink() + + +def extract(package, archive, stage): + stage = Path(stage); no_links(stage); stage.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(archive) as z: + entries = z.infolist(); total = 0; seen = set() + if len(entries) > 100_000: raise ValueError('Archive has too many entries') + for entry in entries: + rel = safe_relative(entry.filename) + key = rel.as_posix().casefold() + if key in seen: raise ValueError('Duplicate archive filename: ' + entry.filename) + seen.add(key) + mode = entry.external_attr >> 16 + if stat.S_ISLNK(mode): raise ValueError('Archive links are not allowed') + total += entry.file_size + if total > package['max_unpacked_bytes']: raise ValueError('Archive expands beyond its limit') + if shutil.disk_usage(stage).free < total + 128 * 1024 * 1024: + raise OSError('Not enough free space to unpack ' + package['id']) + for entry in entries: + rel = safe_relative(entry.filename) + if rel.parts[0] not in package['folders']: continue + target = stage / rel; no_links(target) + if entry.is_dir(): target.mkdir(parents=True, exist_ok=True); continue + target.parent.mkdir(parents=True, exist_ok=True) + with z.open(entry) as src, target.open('wb') as dst: shutil.copyfileobj(src, dst) + for folder in package['folders']: + if not compatible(stage / folder): + raise ValueError('Dependency is missing its Forever TOC: ' + folder) + + +def prepare(bundle, game, stage, voices, cache): + packages = selected(bundle, voices) + sources = {'RuenUI': Path(bundle) / 'RuenUI'} + enabled = ['RuenUI'] + for package in packages: + missing = [] + for folder in package['folders']: + target = Path(game) / 'Interface/AddOns' / folder; no_links(target) + if target.exists(): + if not compatible(target): + raise ValueError('Existing ' + folder + ' is not marked compatible with Forever; update it from its author first.') + print('Keeping existing ' + folder, flush=True) + else: missing.append(folder) + enabled.append(folder) + if missing: + extract(package, download(package, cache), stage) + for folder in missing: sources[folder] = Path(stage) / folder + return sources, enabled diff --git a/Tools/ruen_hardware.py b/Tools/ruen_hardware.py new file mode 100755 index 0000000..7664fb3 --- /dev/null +++ b/Tools/ruen_hardware.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Local, read-only Linux telemetry; bounded report + Lua handoff. No driver changes.""" +import argparse, json, math, os, platform, shutil, subprocess, time +from pathlib import Path + +def fps_target(value): + try: + fps=int(str(value)) + except (TypeError, ValueError): + raise argparse.ArgumentTypeError('FPS must be a whole number from 20 to 240.') + if not 20<=fps<=240: + raise argparse.ArgumentTypeError('FPS must be a whole number from 20 to 240.') + return fps + +def read(p): + try: return Path(p).read_text().strip() + except (OSError, ValueError): return '' + +def throttles(): + out={} + for p in Path('/sys/devices/system/cpu').glob('cpu*/thermal_throttle/*throttle_count'): + try: out[str(p)]=int(read(p)) + except ValueError: pass + return out + +def gpu(): + exe=shutil.which('nvidia-smi') + if not exe: return {} + q='name,temperature.gpu,utilization.gpu,clocks_event_reasons.hw_thermal_slowdown,clocks_event_reasons.sw_thermal_slowdown' + try: + r=subprocess.run([exe,'--query-gpu='+q,'--format=csv,noheader,nounits'],capture_output=True,text=True,timeout=4) + rows=[line.split(', ') for line in r.stdout.splitlines() if len(line.split(', '))==5] + if not rows: return {} + return {'gpuTemp':max(float(row[1]) for row in rows), 'gpuLoad':max(float(row[2]) for row in rows), + 'gpuThermal':any(v.strip()=='Active' for row in rows for v in row[3:]), 'gpuNames':[row[0] for row in rows]} + except (OSError,ValueError,subprocess.TimeoutExpired): return {} + +def sample(): + temps=[]; hot=False + for h in Path('/sys/class/hwmon').glob('*'): + name=read(h/'name') + if name not in ('coretemp','k10temp','zenpower','cpu_thermal','amdgpu','nouveau'): continue + for p in h.glob('temp*_input'): + try: + value=int(read(p))/1000 + if not 0=ceiling + except ValueError: pass + g=gpu();hot=hot or g.get('gpuTemp',0)>=83 or g.get('gpuThermal',False) + return {'time':int(time.time()),'temperatures':temps,'temperaturePressure':hot, **g} + +def game_running(): + names={'wow.exe','wowclassic.exe','wow-64.exe'} + for p in Path('/proc').glob('[0-9]*/cmdline'): + args=read(p).split('\0')[:2] + if any(a.replace('\\','/').rsplit('/',1)[-1].lower() in names for a in args):return True + return False + +def evaluate(seconds=600, interval=5): + before=throttles(); start=time.monotonic(); samples=[]; hot_count=0; lastcpu=None; thermal=False + while True: + s=sample(); raw=read('/proc/stat').splitlines()[0].split()[1:] + nums=list(map(int,raw[:8])); total=sum(nums); idle=nums[3]+nums[4] + if lastcpu and total>lastcpu[0]: s['cpuLoad']=100*(1-(idle-lastcpu[1])/(total-lastcpu[0])) + lastcpu=(total,idle);s['gameRunning']=game_running();samples.append(s) + hot_count=hot_count+1 if s['temperaturePressure'] else 0 + thermal=thermal or any(value>before.get(key,value) for key,value in throttles().items()) or s.get('gpuThermal',False) + age=time.monotonic()-start + if age>=seconds or thermal or hot_count>=3: break + time.sleep(min(interval,seconds-age)) + duration=time.monotonic()-start + load=sum(s['gameRunning'] and (s.get('gpuLoad',0)>20 or s.get('cpuLoad',0)>15) for s in samples) + loaded=duration>=180 and load>=len(samples)*.6 + cpu_seen=bool(before) or any(t['sensor'].split('/')[0] in ('coretemp','k10temp','zenpower','cpu_thermal') for t in samples[-1]['temperatures']) + gpu_seen='gpuTemp' in samples[-1] or any(t['sensor'].split('/')[0] in ('amdgpu','nouveau') for t in samples[-1]['temperatures']) + coverage='full' if cpu_seen and gpu_seen else 'partial' if cpu_seen or gpu_seen else 'unavailable' + evidence='thermal throttling observed' if thermal else 'temperature headroom low' if hot_count>=3 else 'no thermal limit observed in sample' if samples[-1]['temperatures'] or 'gpuTemp' in samples[-1] else 'thermal sensors unavailable' + return {'format':1,'platform':platform.platform(),'cpu':next((l.split(':',1)[1].strip() for l in read('/proc/cpuinfo').splitlines() if l.startswith('model name')),''), + 'checkedAt':int(time.time()),'duration':round(duration,1),'loaded':loaded,'thermalCoverage':coverage,'thermalPressure':thermal or hot_count>=3,'evidence':evidence, + 'cpuThermalCountersAvailable':bool(before),'samples':samples} + +def write_report(game,report,auto_start,target_fps=60): + target_fps=fps_target(target_fps) + report=dict(report,targetFPS=target_fps) + addon=game/'Interface/AddOns/RuenUI' + if not (addon/'RuenUI.toc').is_file(): raise ValueError('Install Ruen UI in this game folder first.') + reports=game/'Ruen-UI-Reports';reports.mkdir(exist_ok=True) + dest=reports/'hardware.json';old=reports/'hardware.previous.json' + if dest.exists(): os.replace(dest,old) + dest.write_text(json.dumps(report,indent=2)+'\n') + profile={k:report[k] for k in ('checkedAt','loaded','thermalCoverage','thermalPressure','evidence','targetFPS')};profile['autoStart']=auto_start + lua='local _, P = ...\nP.hardwareProfile = {\n'+''.join(' '+k+' = '+('true' if v is True else 'false' if v is False else str(v) if isinstance(v,int) else json.dumps(v))+',\n' for k,v in profile.items())+'}\n' + tmp=addon/'HardwareProfile.lua.tmp';tmp.write_text(lua);os.replace(tmp,addon/'HardwareProfile.lua') + return dest + +def main(): + p=argparse.ArgumentParser();p.add_argument('--wow',required=True,type=Path);p.add_argument('--seconds',type=int,default=600);p.add_argument('--baseline',action='store_true') + p.add_argument('--fps',type=fps_target,default=60,help='Requested FPS target (20–240; default: 60).') + a=p.parse_args();game=a.wow.expanduser().resolve();game=game if game.name=='_forever_' else game/'_forever_' + if not (game/'Wow.exe').is_file():p.error('Expected the Forever game directory containing Wow.exe.') + if not 1<=a.seconds<=1800:p.error('--seconds must be 1–1800') + print('Play normally in WoW while this window collects thermal evidence. No stress test or driver changes.',flush=True) + r=evaluate(a.seconds);print(write_report(game,r,not a.baseline,a.fps));print(r['evidence']) + print('Reload WoW to import this machine report'+(' and start world/raid calibration.' if not a.baseline else '.')) +if __name__=='__main__': main() diff --git a/Tools/ruen_migrate.py b/Tools/ruen_migrate.py new file mode 100644 index 0000000..01c62c1 --- /dev/null +++ b/Tools/ruen_migrate.py @@ -0,0 +1,53 @@ +"""Offline upgrade of legacy addon IDs. No Lua execution; callers back up first.""" +import re +from pathlib import Path + +LEGACY_ADDON = 'BradStockUI' +RENAMES = (('BradStockUI', 'RuenUI'), ('BRADSTOCKUI', 'RUENUI'), + ('BRADUI', 'RUENUI'), ('BradTargetTargetTarget', 'RuenTargetTargetTarget')) + +def converted(text): + for old, new in RENAMES: + text = text.replace(old, new) + return text + +def valid_save_path(relative): + if Path(relative).is_absolute() or '\\' in relative or any(p in ('.', '..') for p in relative.split('/')): + return False + return bool(re.fullmatch( + r'WTF/Account/(?:[^/]+/)+(?:(?:SavedVariables/(?:RuenUI|BradStockUI)\.lua(?:\.bak)?)|bindings-cache\.wtf|AddOns\.txt)', relative)) + +def plan(root, include_addons=True): + """Return (relative path, new text or None for removal); never overwrite new saves.""" + root = Path(root) + account = root/'WTF/Account' + changes = {} + if not account.exists(): + return [] + # Resolve the destination first so mixed/new installs keep their current settings. + for old in sorted(account.rglob(LEGACY_ADDON+'.lua*')): + if old.parent.name != 'SavedVariables' or old.name not in (LEGACY_ADDON+'.lua', LEGACY_ADDON+'.lua.bak'): + continue + new = old.with_name(old.name.replace(LEGACY_ADDON, 'RuenUI', 1)) + if not new.exists(): + changes[new.relative_to(root).as_posix()] = converted(old.read_text(encoding='utf-8-sig')) + changes[old.relative_to(root).as_posix()] = None + candidates = list(account.rglob('bindings-cache.wtf')) + candidates += [p for p in account.rglob('RuenUI.lua*') + if p.parent.name == 'SavedVariables' and p.name in ('RuenUI.lua', 'RuenUI.lua.bak')] + if include_addons: + candidates += list(account.rglob('AddOns.txt')) + for path in candidates: + text = path.read_text(encoding='utf-8-sig') + if path.name == 'AddOns.txt': + lines = text.splitlines() + if not any(re.match(r'^'+LEGACY_ADDON+r'\s*:', line) for line in lines): + continue + lines = [line for line in lines if not re.match(r'^(?:'+LEGACY_ADDON+r'|RuenUI)\s*:', line)] + new_text = '\n'.join(lines+['RuenUI: enabled'])+'\n' + else: + new_text = converted(text) + if new_text != text: + changes[path.relative_to(root).as_posix()] = new_text + assert all(valid_save_path(p) for p in changes), 'Unexpected migration path' + return sorted(changes.items()) diff --git a/dependencies.lock.json b/dependencies.lock.json new file mode 100644 index 0000000..6aa6e47 --- /dev/null +++ b/dependencies.lock.json @@ -0,0 +1,98 @@ +{ + "format": 1, + "interface": 16001, + "packages": [ + { + "id": "Leatrix_Plus", + "group": "base", + "url": "https://edge.forgecdn.net/files/9565/653/Leatrix_Plus-1.60.30-forever.zip", + "sha256": "8b72e586e4fd5f4a4e4ed78e4bf03252a2b557d736d6ddd433bd7107c87b63e7", + "bytes": 618471, + "max_unpacked_bytes": 100000000, + "folders": [ + "Leatrix_Plus" + ], + "project": "https://www.curseforge.com/wow/addons/leatrix-plus", + "license": "All Rights Reserved; fetched from author, not redistributed" + }, + { + "id": "Leatrix_Maps", + "group": "base", + "url": "https://edge.forgecdn.net/files/9571/295/Leatrix_Maps-1.60.31-forever.zip", + "sha256": "3f4a7e5d1519a2b99b8baa9dcddc559a2fb1e29f806621451cc1bb7255ac935a", + "bytes": 24471761, + "max_unpacked_bytes": 100000000, + "folders": [ + "Leatrix_Maps" + ], + "project": "https://www.curseforge.com/wow/addons/leatrix-maps", + "license": "All Rights Reserved; fetched from author, not redistributed" + }, + { + "id": "Spoken", + "group": "base", + "url": "https://github.com/rusty-key/spoken-wow/releases/download/spoken/v3.9.0/Spoken-3.9.0.zip", + "sha256": "f3903b305781b44099990393d81ed77f6db8091b44049943aa0179c1a4c83f41", + "bytes": 72268027, + "max_unpacked_bytes": 180000000, + "folders": [ + "Spoken", + "Spoken_Quests" + ], + "project": "https://www.curseforge.com/wow/addons/spoken", + "license": "MIT code; upstream audio and library terms retained" + }, + { + "id": "GunSilencerForever", + "group": "base", + "url": "https://edge.forgecdn.net/files/9589/004/GunSilencerForever-v0.1.4.zip", + "sha256": "2e92aca673cb7b6982d9eddc3adc7be48eaf21ca28e09fa983da6bdc93d05948", + "bytes": 79253, + "max_unpacked_bytes": 1000000, + "folders": [ + "GunSilencerForever" + ], + "project": "https://www.curseforge.com/wow/addons/gun-silencer-forever", + "license": "All Rights Reserved; fetched from author, not redistributed" + }, + { + "id": "SpokenQuestsAudioAlliance", + "group": "en", + "url": "https://mediafilez.forgecdn.net/files/9602/705/SpokenQuestsAudioAlliance-2.7.1.zip", + "sha256": "906be1791fb7b34240ea559f1027654e6b4747138a77e191250ed917d77ad50d", + "bytes": 476984293, + "max_unpacked_bytes": 953968586, + "folders": [ + "SpokenQuestsAudioAlliance" + ], + "project": "https://www.curseforge.com/wow/addons/spoken", + "license": "Upstream audio terms; fetched from author, not redistributed" + }, + { + "id": "SpokenQuestsAudioShared", + "group": "en", + "url": "https://mediafilez.forgecdn.net/files/9602/751/SpokenQuestsAudioShared-2.7.1.zip", + "sha256": "5e0c2ee9243dd0732d95579b3305f3250f325c3f7ddc0f8ff77f933091056575", + "bytes": 451316980, + "max_unpacked_bytes": 902633960, + "folders": [ + "SpokenQuestsAudioShared" + ], + "project": "https://www.curseforge.com/wow/addons/spoken", + "license": "Upstream audio terms; fetched from author, not redistributed" + }, + { + "id": "SpokenQuestsAudio_ruRU", + "group": "ru", + "url": "https://github.com/rusty-key/spoken-wow/releases/download/quests-audio-ruRU/v0.0.3/SpokenQuestsAudio_ruRU-0.0.3.zip", + "sha256": "4a6b9805b33a04f96e09ff7b6c66acdb6cab5d659600e69a54dd5033769e31a4", + "bytes": 1237936364, + "max_unpacked_bytes": 2475872728, + "folders": [ + "SpokenQuestsAudio_ruRU" + ], + "project": "https://www.curseforge.com/wow/addons/spoken", + "license": "Upstream audio terms; fetched from author, not redistributed" + } + ] +} diff --git a/docs/DEPENDENCIES.md b/docs/DEPENDENCIES.md new file mode 100644 index 0000000..535b8d0 --- /dev/null +++ b/docs/DEPENDENCIES.md @@ -0,0 +1,19 @@ +# Companion sources and licenses + +The public ZIP contains first-party Ruen files only. Setup downloads the following pinned archives directly from their authors. Existing compatible installations are retained; companions are not republished by this repository. + +| Package | Source | License notice | Download size | +| --- | --- | --- | --- | +| Leatrix_Plus | [Project](https://www.curseforge.com/wow/addons/leatrix-plus) · [Pinned archive](https://edge.forgecdn.net/files/9565/653/Leatrix_Plus-1.60.30-forever.zip) | All Rights Reserved; fetched from author, not redistributed | 0.6 MB | +| Leatrix_Maps | [Project](https://www.curseforge.com/wow/addons/leatrix-maps) · [Pinned archive](https://edge.forgecdn.net/files/9571/295/Leatrix_Maps-1.60.31-forever.zip) | All Rights Reserved; fetched from author, not redistributed | 24.5 MB | +| Spoken | [Project](https://www.curseforge.com/wow/addons/spoken) · [Pinned archive](https://github.com/rusty-key/spoken-wow/releases/download/spoken/v3.9.0/Spoken-3.9.0.zip) | MIT code; upstream audio and library terms retained | 72.3 MB | +| GunSilencerForever | [Project](https://www.curseforge.com/wow/addons/gun-silencer-forever) · [Pinned archive](https://edge.forgecdn.net/files/9589/004/GunSilencerForever-v0.1.4.zip) | All Rights Reserved; fetched from author, not redistributed | 0.1 MB | +| SpokenQuestsAudioAlliance | [Project](https://www.curseforge.com/wow/addons/spoken) · [Pinned archive](https://mediafilez.forgecdn.net/files/9602/705/SpokenQuestsAudioAlliance-2.7.1.zip) | Upstream audio terms; fetched from author, not redistributed | 477.0 MB | +| SpokenQuestsAudioShared | [Project](https://www.curseforge.com/wow/addons/spoken) · [Pinned archive](https://mediafilez.forgecdn.net/files/9602/751/SpokenQuestsAudioShared-2.7.1.zip) | Upstream audio terms; fetched from author, not redistributed | 451.3 MB | +| SpokenQuestsAudio_ruRU | [Project](https://www.curseforge.com/wow/addons/spoken) · [Pinned archive](https://github.com/rusty-key/spoken-wow/releases/download/quests-audio-ruRU/v0.0.3/SpokenQuestsAudio_ruRU-0.0.3.zip) | Upstream audio terms; fetched from author, not redistributed | 1237.9 MB | + +Exact sizes and SHA-256 checksums are recorded in [dependencies.lock.json](../dependencies.lock.json). These are integrity checks against the reviewed lock file, not code signatures. Release ZIP checksums are published separately in SHA256SUMS.txt. + +Leatrix and Gun Silencer Forever reserve redistribution rights. Spoken code and its libraries/audio have distinct licensing considerations; an addon project license does not automatically grant rights to every recording or game asset. Downloading upstream avoids mirroring these materials. Consult each project for its current terms. Ruen is not affiliated with or endorsed by Blizzard or the companion authors. + +No Blizzard game files, account SavedVariables, language archives, personal hardware reports, screenshots, private repair scripts or account identifiers are shipped. The older private all-in-one bundle is not the public release. diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md new file mode 100644 index 0000000..ad0a27f --- /dev/null +++ b/docs/DEVELOPMENT.md @@ -0,0 +1,57 @@ +# Reproducing checks + +Run installer tests from the repository root: + +```sh +PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tests -v +RUEN_PWSH=/path/to/pwsh PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tests -v +``` + +These use tiny offline companion archives and disposable fake game directories, never the installed game. Native Windows remains a separate manual test requirement. + +Lua harnesses require LuaJIT (Lua 5.1 semantics and `bit`). `tests/check-timers-optimizer.lua` runs with the addon directory as its first argument, including a trailing slash. + +The other layout/pet/meter harnesses load selected matching Blizzard UI source files. Those files are **not redistributed**. Set `RUEN_NATIVE_UI` to a directory containing the matching Forever client exports: + +```text +EditModeManagerConstantsDocumentation.lua +NamePlateConstantsDocumentation.lua +Mainline-ContainerFrame.lua +PetActionBar.lua +MultiActionBars.lua +SecureTemplates.lua +DamageMeter.lua +DamageMeterSessionWindow.lua +CooldownViewer.lua +CooldownViewerSettingsDataProvider.lua +ActionButtonUtil.lua +Blizzard_SpellSearchUtil.lua +``` + +Example: + +```sh +export RUEN_NATIVE_UI=/path/to/matching-native-fixtures +luajit tests/check-layout.lua "$PWD/RuenUI/" unused /tmp/ruen-matrix.txt +luajit tests/check-pet-actions.lua "$PWD/RuenUI/" +luajit tests/check-meter.lua "$PWD/RuenUI/" +luajit tests/check-timers-optimizer.lua "$PWD/RuenUI/" +``` + +The gun test accepts a directory containing both `RuenUI/` and an author-downloaded `GunSilencerForever/`: + +```sh +luajit tests/check-gun-audio.lua /path/to/test-addons +``` + +These harnesses simulate engine state and execute selected native methods. They are not a substitute for live rendering or the secure game VM. Review changes against the exact client UI revision rather than making tests pass against a different branch. + +Build the downloadable installer: + +```sh +python3 scripts/build_release.py /path/to/output +``` + +The allowlist excludes tests, third-party payloads, caches, account saves and Git metadata. The ZIP includes the launcher source and installer helpers. `SHA256SUMS.txt` verifies the ZIP; `manifest.json` verifies its extracted files. Neither is a digital signature. Publish the named ZIP and checksum as Gitea prerelease assets. A Gitea source archive is for development and lacks the generated installer manifest. + +The Windows launcher can be rebuilt with Clang targeting x86_64-pc-windows-msvc and LLD in link mode. Compile `Tools/Ruen-Setup.c` with `-Os -ffreestanding -fno-stack-protector -fshort-wchar`; create a KERNEL32 import library from `Tools/kernel32.def`; link with `/entry:entry /subsystem:console /machine:x64 /nodefaultlib /opt:ref /timestamp:0`. It uses only KERNEL32 imports, no bundled runtime. The included binary is unsigned. diff --git a/docs/INSTALL-RU.md b/docs/INSTALL-RU.md new file mode 100644 index 0000000..1cd4f27 --- /dev/null +++ b/docs/INSTALL-RU.md @@ -0,0 +1,23 @@ +# Установка Ruen UI — бета + +1. Установите **WoW: Forever** через Battle.net и дождитесь окончания загрузки. +2. Откройте [Releases](https://scm.bstein.dev/bstein/ruen-ui/releases) и скачайте **Ruen-UI-2026.11.21.5-beta.1.zip**. Для скачивания регистрация не нужна. +3. Полностью распакуйте ZIP. Закройте WoW. +4. Для русского варианта запустите **Install-Russian.cmd**. Обычная установка: **Ruen-Setup.exe**. Установщик сам ищет игру; если нужно, укажите папку `_forever_`, в которой находится `Wow.exe`. +5. В Battle.net выберите WoW: Forever → шестерёнка → изменение установки. Установите английские и русские файлы игры. Выберите русский язык текста и речи в настройках **игры**, а не приложения Battle.net. Дождитесь 100% загрузки. +6. Войдите в игру. При необходимости выполните `/reload` один раз. Команда `/ruen help` или клавиша **F12** показывает справку. + +**Управление изменится:** E — вперёд, D — назад, S/F — движение влево/вправо. Поворот — правой кнопкой мыши. N — карта, I — сумки, P — книга заклинаний, Alt+J — компендиум. Подробности в `KEYBINDINGS.txt`. + +- `/ruen language ru` — запросить русский текст, речь и озвучку заданий. После этого полностью закройте и запустите WoW заново. +- `/ruen language en` — английский вариант. Если язык не изменился, проверьте язык текста и речи WoW в Battle.net. +- `/ruen voice ru` — изменить только озвучку заданий, без перезапуска. +- `/ruen lock` / `/ruen unlock` — заблокировать / разблокировать перетаскивание способностей. +- `/ruen guns off` — вернуть обычные звуки оружия. При включённом глушителе стандартные выстрелы других персонажей не слышны. +- `/ruen restore` — восстановить сохранённые настройки и отключить автоматическую настройку. + +Аддоны и записи скачиваются непосредственно у их авторов. Английский + русский вариант требует примерно **2,26 ГБ загрузок**, а также место для распаковки и резервных копий. Файлы языка самой игры скачиваются отдельно через Battle.net. + +Это первая публичная бета: чистая установка и работа на Windows ещё требуют проверки. Программа не меняет видеодрайверы. Исполняемый файл не подписан; его исходный код включён. Не отключайте защиту Windows ради установки. + +Инструкции по обновлению, резервным копиям и оптимизации: [INSTALL.md](INSTALL.md). Ошибки: [Issues](https://scm.bstein.dev/bstein/ruen-ui/issues). diff --git a/docs/INSTALL.md b/docs/INSTALL.md new file mode 100644 index 0000000..476576f --- /dev/null +++ b/docs/INSTALL.md @@ -0,0 +1,75 @@ +# Install, update and restore + +## Windows + +Download the named installer ZIP from [Releases](https://scm.bstein.dev/bstein/ruen-ui/releases), extract it completely, close WoW, and run `Ruen-Setup.exe`. Windows 10/11 x64 with Windows PowerShell 5.1 is the intended target. Native Windows testing is pending for this first beta; PowerShell filesystem tests have run on Linux. + +The installer checks Program Files, common game folders and Blizzard registry entries. It prompts when discovery is ambiguous. A custom location can always be supplied: + +```powershell +.\Ruen-Setup.exe -WoWPath 'D:\Games\World of Warcraft\_forever_' +``` + +Run from a folder you can write to, with a game installation you can modify. No administrator access is requested automatically. If the game folder is protected, use an account with access or the existing Windows permissions flow. Do not disable antivirus or change system-wide execution policy. The launcher uses a process-local PowerShell policy setting; it is not code-signed. + +By default, setup downloads English quest recordings. Choose both narration languages with `Install-Russian.cmd`, or explicitly: + +```powershell +.\Ruen-Setup.exe -WoWPath 'D:\Games\World of Warcraft\_forever_' -VoicePacks enru +``` + +`-VoicePacks none` installs the core companions without the large quest voice packs. `en` adds Alliance + Shared English packs; `enru` also adds Russian. These bundled selections focus on Alliance; other English faction audio is not included. + +Fresh download sizes are roughly 97 MB for core companions, 1.03 GB with English, or 2.26 GB with English + Russian. Allow additional room for extraction, installed audio and rollback copies. Downloads are cached under `%LOCALAPPDATA%\RuenUI\Downloads`, with one pinned archive per companion. Setup verifies byte counts and SHA-256 before extraction. Failed staging does not change the game. If a publisher removes a pinned file, setup stops; it never silently substitutes a different release. + +Existing compatible companion installations are kept. This preserves custom versions but means that combination may differ from the pinned beta test set. Update those addons from their authors if necessary. Unrelated addons are retained; other layout addons may conflict. + +## Russian game setup + +In Battle.net, choose **WoW: Forever → gear beside Play → Modify Install**, keep English and Russian installed, and wait for the download to finish. Set the game's **Text Language** and **Spoken Language** as desired in its Game Settings. Changing the Battle.net application's own language does not change WoW. + +`Install-Russian.cmd` selects Russian narration and prepares the language request. In game, `/ruen language ru` or `/ruen language en` requests text, game audio and narration together. **Fully exit and restart WoW**; `/reload` is not enough. If Battle.net overrides the request, match both of the game's language settings there. `/ruen voice ru` changes only narration, immediately. Missing translated recordings can fall back to installed English audio. Chat is not translated; the profanity filter is disabled by Ruen's preset. + +## Linux + +```sh +python3 Ruen-Setup --wow '/path/to/World of Warcraft/_forever_' --voice-packs enru +``` + +Do not run with sudo. Discovery checks common Wine, Steam compatibility and Games folders; `--wow` works for other locations. Downloads are cached in `~/.cache/ruen-ui/downloads`. Use `--language ru` to request Russian on first login after installing the native language files through Battle.net. + +## Update + +Close WoW, extract the new release into a fresh folder, and run its installer against the same game. Existing narration files are reused; machine-specific hardware reports and language requests are preserved. A repeat install of identical files does not create another backup. The installer does not erase companion SavedVariables or unrelated addons. + +## Optional optimization + +Run while playing a representative area, with the laptop powered and cooled as you normally use it: + +```powershell +.\Ruen-Setup.exe --optimize 30 -Seconds 600 +``` + +```sh +python3 Ruen-Setup --wow '/path/to/_forever_' --optimize 30 --seconds 600 +``` + +The FPS target defaults to 60 (accepted range 20–240). Type `/reload` afterward to import the local hardware report. World and raid settings learn separately; a quiet outdoor sample cannot establish raid performance. Missing temperature/throttling counters are reported as unavailable, not proof of safe temperatures. `/ruen optimize status`, `pause`, `resume`, and `restore` control in-game calibration. No stress test or driver installation is performed. + +## Undo + +In game, `/ruen restore` restores recorded settings and bindings and stops automatic setup. Do this on each affected character, then fully close WoW. Keep the backup path printed during installation; a rollback also restores settings saved on disk before that installation: + +```powershell +.\Ruen-Setup.exe -Restore -BackupPath 'D:\Games\World of Warcraft\_forever_\Ruen-UI-Backups\TIMESTAMP' +``` + +```sh +python3 Ruen-Setup --wow '/path/to/_forever_' --restore '/path/to/_forever_/Ruen-UI-Backups/TIMESTAMP' +``` + +Use the installer for the same operating system that made the backup. Rollback restores the recorded files, including account-wide keybindings; preferences changed after installation may revert. Later files are retained inside the backup under `before-restore-*`. It does not restore characters created after the backup or remove unrelated addons. Backups remain until you delete ones you no longer need. Do not delete the only backup until you are satisfied with the update. + +## Reporting a beta problem + +Use [Gitea issues](https://scm.bstein.dev/bstein/ruen-ui/issues) or send your friend the report if you do not have an account. Include Ruen version (`/ruen status`), game build, class, resolution/UI scale, reproduction steps and the exact Lua error. Redact chat, character/account names and paths. Do not attach your entire WTF folder, account credentials or hardware report by default. diff --git a/docs/RELEASE-REVIEW.md b/docs/RELEASE-REVIEW.md new file mode 100644 index 0000000..dd3f136 --- /dev/null +++ b/docs/RELEASE-REVIEW.md @@ -0,0 +1,56 @@ +# Release review — 2026.11.21.5-beta.1 + +Reviewed 21 November 2026. **Suitable for an opt-in public beta, not a general-availability certification.** The previous private bundle received targeted fixes and gameplay checks; this review adds the packaging, installer, dependency, privacy and rollback checks needed for sharing it. + +## Changes made for public distribution + +- A small first-party ZIP replaces redistribution of the private multi-gigabyte bundle. Installers fetch pinned companion releases directly from their authors. Download size, SHA-256, archive paths and expanded-size bounds are checked before game files change. +- Existing compatible companion addons and their SavedVariables are preserved. The old Windows installer could replace companion settings wholesale; it no longer does. +- Account-wide keybindings are now included in backups, alongside character bindings, layout/config files and affected addon settings. +- Existing per-machine hardware reports and language requests survive updates. A fresh package contains an empty hardware profile and no language request from the developer's machine. +- Install/cache locks prevent concurrent setup. Both installers stage first, preflight destinations, retain rollback receipts, and undo partial installation failures. An identical repeat install adds no backup. +- First-party source, English/Russian instructions, locked dependency provenance and checksums are published. No account saves, character-specific repair script, screenshots, credentials, or personal hardware report are packaged. +- Silencer default remains **100**; existing user volume choices are preserved. Nearby stock gunfire is muted while enabled. This tradeoff is documented prominently. + +## Validation completed + +| Area | Evidence and limits | +| --- | --- | +| Installer transactions | 14 automated tests: Linux fresh/repeat install, saved-setting/profile preservation, account-binding restore, legacy migration, partial-write rollback, locking, missing backups, incompatible companions, download failure, symlink rejection, package corruption and archive-path validation. PowerShell fixtures include fresh/repeat install, preservation, restore, corruption, download failure, missing backup and unsafe paths. | +| Windows scripts | PowerShell 7.7 on Linux executed filesystem fixtures. Syntax parsed successfully. The unsigned x64 executable was rebuilt from the included small PowerShell launcher source (no runtime behavior changes). **Native Windows PowerShell 5.1, SmartScreen and GUI execution remain untested.** | +| Dependencies | All four base archives downloaded, hashed and extracted successfully against the lock; the final ZIP also installed those actual archives through PowerShell into a disposable game path containing spaces and Cyrillic characters. English/Russian audio endpoints returned HTTPS 200 with the expected sizes. Large audio hashes retain prior verification records; the full audio payload was not downloaded again during this review. Every fresh installation independently checks its full downloads. | +| Layout matrix | 9 classes × 8 environments × 8 display/scale cases, repeated with native aura/cast/combo/BG-widget footprints: **1,152 scenarios, zero modeled unintended intersections, offscreen controls, undersized group frames or wrong meter visibility**. Prior restricted-aura stress fixtures are reset before the base matrix. This is geometry/API simulation, not screenshots of every live class. | +| Overlay regressions | 50 meter/bag/tooltip/loot scenarios, 200 cooldown/class/full-HUD scenarios, 120 restricted-aura inventory cases, and repeated late tooltip reanchors. Custom tooltip owners, combat deferral, editor handoff and comparison cards were exercised. | +| Pet controls | Native ten-button row plus two extras: actual native page map and secure-dispatch code used in a simulated client; tests cover spellbook discovery, command identity, localization, rank/pet changes, occupied slots and rejection. 1,200 opaque-cooldown refreshes passed; rejected placement remains one attempt through 500 events/reload. This does not establish every action in the live secure VM. | +| Damage meter | Native timer/visibility code with tracked-taint simulation passed 1,000 combat starts; no direct writes to native visibility state or calls to its refresh methods. PvE auto, PvP exclusion, manual modes, no-room recovery and combat deferral passed. The previous live error was also reported resolved after reload. | +| Audio | 94 checks against the pinned Gun Silencer Forever code and Ruen bridge passed, including default volume, existing choices, off/restore, failed playback and missing dependency. | +| Timers/optimization | Swing lanes, idle sleep, secret values, world/raid separation, frame sampling, thermal input, pause and undo tests passed. No native Windows hardware/thermal validation is claimed. | +| Privacy/package | First-party allowlist, blank hardware defaults, dependency-license review and scan for local paths/account data. Only legacy migration identifiers retain the former addon name. Release ZIP has a per-file SHA-256 manifest and a separate ZIP checksum. | + +Environments: solo, outdoor party, dungeon, 10/20/40-player raid and 10/40-player battleground. Displays: 1280×720, 1366×768, 1920×1080 at two scales, 2560×1440 at two scales and 3840×2160 at two scales. + +## Performance review + +Layout work is event-driven and coalesced; there is no idle geometry-search loop. Pet extras refresh at a bounded cadence while populated/visible. Swing updates stop when their display is inactive. Calibration samples frame times only while learning and sleeps after settling; the manual FPS benchmark stops after three minutes. Overlay searches are bounded, and stationary tooltip placement is cached. Native meters handle collection rather than a second addon combat-log parser. + +These are code and simulation findings. They do **not** guarantee an FPS budget, memory-leak freedom or safe temperature on every laptop. Missing hardware counters remain unknown. The installer changes no drivers and installs no persistent service. + +## Intentional overlap and capacity limits + +1. An oversized item-comparison group can cover other bag contents while keeping the hovered item accessible. Very large tooltips may use chat/notification space after clear positions are exhausted. +2. Crowded loot/achievement notifications may temporarily cover chat or optional duplicate cooldown/meter information. +3. A bag that cannot fit at readable scale may cover some HUD information; action blocks, chat, social space, quest column, minimap and open native panels remain placement obstacles. +4. Native modal panels (map, quest dialogue, bank/professions) can cover the world/HUD or side reserve bars. Ruen does not replace their secure panel manager. Native portrait/combo-point/target-of-target artwork keeps its intentional internal layering. +5. An optional meter can hide when no clear rectangle is available, including on small displays with conservative restricted-aura footprints or unusually large trackers. `/ruen status` reports placement trouble; more screen space or a smaller tracker may be needed. + +## Remaining beta checks + +- Clean Windows 10/11 installation, launcher double-click, custom game path, narration downloads and real rollback on the destination machine. +- Live pet activation/autocast on both extra buttons across pet types, including combat and pet swaps. Earlier bugs demonstrate why native simulation alone is insufficient. +- Live level-60 class/spec coverage and crowded raids/BGs, particularly healer mouseover workflows and low-resolution displays. +- Sustained performance and available thermal telemetry on the destination laptop. +- Other addon combinations, arbitrary aspect ratios, accessibility font sizes and all simultaneous window combinations. + +Cooldown displays only expose lists supplied by WoW; they are not exhaustive or identical across classes. English audio selection is Alliance + Shared. Russian narration can fall back to installed English. Battle.net game-language choices can override an addon request and may need matching manually. + +The public beta should be tested on a backed-up installation by a willing tester. Use `/ruen restore` and the printed installer backup path to undo it. See [INSTALL.md](INSTALL.md). diff --git a/scripts/build_release.py b/scripts/build_release.py new file mode 100644 index 0000000..57f9c0f --- /dev/null +++ b/scripts/build_release.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +"""Build a small first-party installer package; companion archives stay upstream.""" +import argparse +import hashlib +import json +from pathlib import Path +import zipfile + +ROOT = Path(__file__).resolve().parents[1] +VERSION = '2026.11.21.5-beta.1' +FILES = ['Ruen-Setup', 'Ruen-Setup.exe', 'Install-Ruen-UI.ps1', 'Install-Ruen-UI.cmd', + 'Install-Ruen-UI-Russian.cmd', 'Install-Windows.cmd', 'Install-Russian.cmd', + 'Optimize-Ruen-UI.ps1', 'dependencies.lock.json', 'README.md', 'LICENSE', + 'KEYBINDINGS.txt', 'LAYOUT-AUDIT.txt'] + + +def payload(root=ROOT): + files = [root / x for x in FILES] + for directory in ('RuenUI', 'Tools', 'docs'): + files += [p for p in (root / directory).rglob('*') if p.is_file() and p.suffix in ('.lua', '.toc', '.xml', '.ps1', '.py', '.c', '.def', '.md', '.json')] + data = {p.relative_to(root).as_posix(): p.read_bytes() for p in sorted(files)} + data = {name: (b.replace(b'\r\n', b'\n').replace(b'\n', b'\r\n') if name.endswith('.cmd') else b.replace(b'\r\n', b'\n') if not name.endswith('.exe') else b) for name, b in data.items()} + assert not any(p.is_symlink() for p in files), 'Linked package content' + assert all(len(b) < 2_000_000 for b in data.values()), 'Unexpected large payload' + return data + + +def manifest(data): + return json.dumps({'format': 1, 'version': VERSION, 'files': [ + {'path': p, 'sha256': hashlib.sha256(b).hexdigest()} for p, b in sorted(data.items()) + ]}, indent=2).encode() + b'\n' + + +def build(destination): + data = payload(); data['manifest.json'] = manifest(data) + destination.mkdir(parents=True, exist_ok=True) + output = destination / ('Ruen-UI-' + VERSION + '.zip') + with zipfile.ZipFile(output, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=9) as z: + for name, content in sorted(data.items()): + entry = zipfile.ZipInfo('Ruen-UI/' + name, (2026, 11, 21, 0, 0, 0)) + entry.compress_type = zipfile.ZIP_DEFLATED + entry.create_system = 3 + entry.external_attr = (0o100755 if name == 'Ruen-Setup' else 0o100644) << 16 + z.writestr(entry, content) + checksum = hashlib.sha256(output.read_bytes()).hexdigest() + (destination / 'SHA256SUMS.txt').write_text(checksum + ' ' + output.name + '\n') + print(output, output.stat().st_size, checksum) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('destination', type=Path) + build(parser.parse_args().destination) diff --git a/tests/check-gun-audio.lua b/tests/check-gun-audio.lua new file mode 100644 index 0000000..cd53966 --- /dev/null +++ b/tests/check-gun-audio.lua @@ -0,0 +1,102 @@ +local bundle = assert(arg[1]) +local tests = 0 +local function check(ok, message) + assert(ok, message); tests = tests + 1 +end +local function newClient(savedRuen, savedGun) + local e = setmetatable({}, {__index = _G}) + e._G = e + e.RuenUIDB = savedRuen or {} + e.GunSilencerForeverDB = savedGun + e.SlashCmdList = {} + e.UIParent, e.WorldFrame = {}, {} + e.frames, e.muted, e.played, e.messages = {}, {}, {}, {} + e.weaponSubclass, e.item = 3, 12345 + e.locale = 'enUS' + e.print = function(message) e.messages[#e.messages+1] = message end + e.issecretvalue = function(value) return type(value) == 'table' and value.secret == true end + e.CreateFrame = function(kind, name, parent, template) + local f = {events = {}, scripts = {}} + function f:RegisterEvent(event) self.events[event] = true end + function f:RegisterUnitEvent(event, unit) self.events[event] = unit end + function f:SetScript(script, callback) self.scripts[script] = callback end + function f:SetOwner() end + function f:SetInventoryItem() end + function f:Hide() end + e.frames[#e.frames+1] = f + return f + end + e.GetInventoryItemID = function(unit, slot) check(slot == 18, 'use ranged equipment slot'); return e.item end + e.C_Item = {GetItemInfoInstant = function() return nil,nil,nil,nil,nil,2,e.weaponSubclass end} + e.C_EventUtils = {IsEventValid = function() return true end} + e.C_Timer = {After = function(delay, callback) + check(delay == 0.5 or delay == 2 or delay == 5, 'bounded appearance refresh only') + end} + e.C_Spell = {GetSpellInfo = function(id) + if id == 75 then return {name=e.locale == 'ruRU' and 'Автоматическая стрельба' or 'Auto Shot'} end + if id == 3044 or id == 14281 then return {name='Arcane Shot'} end + if id == 999 then return {name='Other spell'} end + return nil + end} + e.MuteSoundFile = function(id) e.muted[id] = true end + e.UnmuteSoundFile = function(id) e.muted[id] = nil end + e.PlaySoundFile = function(path, channel) + e.played[#e.played+1] = {path=path,channel=channel} + return not e.failPlayback + end + local upstream = assert(loadfile(bundle..'/GunSilencerForever/GunSilencerForever.lua')) + setfenv(upstream,e);upstream('GunSilencerForever') + e.event = function(event,...) + for _, f in ipairs(e.frames) do + if f.events[event] then f.scripts.OnEvent(f,event,...) end + end + end + e.event('ADDON_LOADED','GunSilencerForever') + e.P = {Localized=function(en,ru) return e.locale == 'ruRU' and ru or en end} + local bridge=assert(loadfile(bundle..'/RuenUI/GunAudio.lua')) + setfenv(bridge,e);bridge('RuenUI',e.P) + return e +end +local e=newClient() +check(e.P.InitializeGunAudio(), 'first-time setup succeeds') +check(e.GunSilencerForeverDB.enabled and e.GunSilencerForeverDB.guns, 'guns enabled') +check(e.GunSilencerForeverDB.volume==100, 'audible starting volume') +check(not e.GunSilencerForeverDB.muteBowDraw, 'bow draw preserved') +for _,id in ipairs({567721,567718,567722}) do check(e.muted[id], 'original gunshot muted') end +for _,id in ipairs({567677,567675,567676,567719,567720,567723}) do check(not e.muted[id], 'bows and gun reload untouched') end +for _,f in ipairs(e.frames) do check(not f.scripts.OnUpdate, 'no frame polling');check(not f.events.COMBAT_LOG_EVENT_UNFILTERED,'no restricted combat log') end +e.event('UNIT_SPELLCAST_SUCCEEDED','player','shot-1',75) +check(#e.played==1 and e.played[1].path:match('Shot_100.ogg$') and e.played[1].channel=='SFX','audible replacement on SFX') +e.event('UNIT_SPELLCAST_SUCCEEDED','player','shot-1',75) +check(#e.played==1,'duplicate cast suppressed') +e.event('UNIT_SPELLCAST_SUCCEEDED','pet','pet-1',75) +e.event('UNIT_SPELLCAST_SUCCEEDED','player','other-1',999) +e.event('UNIT_SPELLCAST_SUCCEEDED','player','secret-1',{secret=true}) +check(#e.played==1,'non-player, non-shot, secret casts ignored') +e.P.GunAudioCommand('40');check(e.GunSilencerForeverDB.volume==40,'volume command') +e.P.GunAudioCommand('volume 65');check(e.GunSilencerForeverDB.volume==70,'rounded volume command') +check(e.P.GunAudioCommand('0')~=nil and e.GunSilencerForeverDB.volume==70,'reject accidental mute') +e.P.GunAudioCommand('off');check(not next(e.muted),'off restores all original audio') +e.event('UNIT_SPELLCAST_SUCCEEDED','player','off-1',75);check(#e.played==1,'off does not replay') +e.P.InitializeGunAudio();check(not e.GunSilencerForeverDB.enabled,'setup does not override user toggle') +local reloaded=newClient(e.RuenUIDB,e.GunSilencerForeverDB) +reloaded.P.InitializeGunAudio();check(not next(reloaded.muted) and reloaded.GunSilencerForeverDB.volume==70,'reload preserves off and volume') +e.P.GunAudioCommand('on');check(e.GunSilencerForeverDB.enabled and e.GunSilencerForeverDB.volume==70 and not e.GunSilencerForeverDB.muteBowDraw,'on keeps volume and original bow draw') +e.event('UNIT_SPELLCAST_SUCCEEDED','player','rank-1',14281);check(#e.played==2,'other spell ranks recognized') +for _,subclass in ipairs({2,18,19,0}) do + e.weaponSubclass=subclass;e.event('PLAYER_EQUIPMENT_CHANGED',18) + e.event('UNIT_SPELLCAST_SUCCEEDED','player','non-gun-'..subclass,75) + check(#e.played==2,'bows/crossbows/wands/melee receive no rifle replacement') +end +e.weaponSubclass=3;e.locale='ruRU';e.event('PLAYER_ENTERING_WORLD') +e.event('UNIT_SPELLCAST_SUCCEEDED','player','ru-1',75);check(#e.played==3,'localized Auto Shot recognized') +e.failPlayback=true;e.event('UNIT_SPELLCAST_SUCCEEDED','player','bad-file',75) +check(not next(e.muted),'failed playback restores originals') +e.failPlayback=false;e.P.GunAudioCommand('on');check(e.muted[567721],'on retries failed playback') +e.P.StopGunAudio();check(not next(e.muted),'ruen restore restores native audio') +local disabled=newClient({disabled=true});disabled.P.InitializeGunAudio() +check(not next(disabled.muted),'disabled Ruen does not introduce sound changes') +local missing=newClient();missing.GunSilencerForeverDB=nil +check(not missing.P.InitializeGunAudio(),'missing dependency leaves Ruen available') +check(missing.P.GunAudioCommand('on'):find('Fully exit WoW',1,true),'missing addon gives restart instructions') +print('PASS: '..tests..' checks (actual upstream addon and Ruen bridge, Lua 5.1).') diff --git a/tests/check-layout.lua b/tests/check-layout.lua new file mode 100644 index 0000000..989ffdb --- /dev/null +++ b/tests/check-layout.lua @@ -0,0 +1,1552 @@ +-- API simulation: checks configuration/undo, not rendering or gameplay performance. +local root = assert(arg[1], 'Pass the RuenUI directory with a trailing slash') +local bundled = true +local source = (assert(os.getenv('RUEN_NATIVE_UI'))..'/') +Enum = {EditModePresetLayouts = {Modern = 1}} +APIDocumentation = {AddDocumentationTable = function(_, d) + for _, t in ipairs(d.Tables or {}) do + if t.Type == 'Enumeration' then + Enum[t.Name] = {}; for _, f in ipairs(t.Fields) do Enum[t.Name][f.Name] = f.EnumValue end + end + end +end} +dofile(source .. 'EditModeManagerConstantsDocumentation.lua') +dofile(source .. 'NamePlateConstantsDocumentation.lua') +Enum.PlayerSwingType = {MainHand=0, OffHand=1, Ranged=2} +Enum.SoftTargetEnableFlags = {Any = 3}; bit = require('bit'); SlashCmdList = {} +function CopyTable(t) + if type(t) ~= 'table' then return t end + local r = {}; for k,v in pairs(t) do r[k] = CopyTable(v) end; return r +end +local eventFrame +local function noop() end +function CreateFrame(_, name) + local f = {scripts = {}, shown = true, attributes = {}} + function f:SetScript(event, fn) self.scripts[event] = fn end + function f:SetSize(w,h) self.w,self.h=w,h end + function f:GetSize() return self.w or 430,self.h or 36 end + function f:IsShown() return self.shown end + function f:Hide() self.shown=false end + function f:Show() self.shown=true end + function f:SetAlpha(a) self.alpha=a end + function f:SetFrameStrata() end + function f:EnableMouse() end + function f:GetLeft() return 100 end + function f:GetBottom() return 50 end + function f:SetAttribute(k,v) self.attributes[k]=v end + function f:CreateTexture() return CreateFrame('Texture') end + function f:CreateFontString() return CreateFrame('Font') end + for _,k in ipairs({'RegisterEvent','UnregisterEvent','SetPoint','RegisterForClicks','SetAllPoints','SetColorTexture','SetText','SetWidth','SetJustifyH','SetStatusBarTexture','SetStatusBarColor','SetMinMaxValues','SetValue','RegisterUnitEvent'}) do f[k]=noop end + if name then _G[name]=f end + eventFrame=eventFrame or f + return f +end +UIParent={}; TargetFrameToT={} +function RegisterUnitWatch(f) f.watched=true end +function UnregisterUnitWatch(f) f.watched=false end +local currentClass="SHAMAN" +function UnitClass() return currentClass,currentClass end +function GetNumShapeshiftForms() return StanceBar and StanceBar.shown and 10 or 0 end +function UnitExists() return false end +function UnitName() return 'Test' end +function UnitHealthMax() return 100 end +function UnitHealth() return 50 end +-- Core's first anonymous frame must own the login event. +local realCreate=CreateFrame +eventFrame=CreateFrame('Frame') +local bootstrap=true +function CreateFrame(kind,name,...) + if bootstrap and kind=='Frame' and not name then bootstrap=false; return eventFrame end + return realCreate(kind,name,...) +end +local barNames={'MainActionBar','MultiBarBottomLeft','MultiBarBottomRight','MultiBarRight','MultiBarLeft','MultiBar5','MultiBar6','MultiBar7'} +for _,name in ipairs(barNames) do realCreate('Frame',name) end +local bars={false,false,false,false,true,false,false} +local initialBars=CopyTable(bars) +local settings={lockActionBars=true} +for i=1,7 do settings['PROXY_SHOW_ACTIONBAR_'..(i+1)]=bars[i] end +function GetActionBarToggles() return unpack(bars) end +function MultiActionBar_Update() + for i=2,8 do _G[barNames[i]].shown=settings['PROXY_SHOW_ACTIONBAR_'..i] end +end +Settings={GetSetting=function(k) return settings[k]~=nil end, SetValue=function(k,v) + assert(type(v)=='boolean'); settings[k]=v; if k=='lockActionBars' then return end; bars[tonumber(k:match('(%d+)$'))-1]=v; MultiActionBar_Update() +end} +local modified='ALT' +local mouseModifier='SHIFT' +function GetModifiedClick(k)return k=='MOUSEOVERCAST' and mouseModifier or modified end +function SetModifiedClick(k,v)if k=='MOUSEOVERCAST' then mouseModifier=v else modified=v end end +function IsMouseoverCastSupported()return false end +local bindings={W='MOVEFORWARD',S='MOVEBACKWARD',A='TURNLEFT',D='TURNRIGHT',Q='STRAFELEFT',E='STRAFERIGHT',R='REPLY',F='ASSISTTARGET',G='TARGETLASTTARGET',B='OPENALLBAGS',C='TOGGLECHARACTER0',F1='TARGETSELF',['CTRL-1']='BONUSACTIONBUTTON1',['SHIFT-1']='ACTIONPAGE1',['SHIFT-MOUSEWHEELUP']='PREVACTIONPAGE',['ALT-F']='INTERACTTARGET'} +for i=1,12 do bindings[tostring(i)]='ACTIONBUTTON'..i end +local initialBindings=CopyTable(bindings) +function GetBindingKey(action) local k={}; for key,a in pairs(bindings) do if a==action then k[#k+1]=key end end; return unpack(k) end +function GetBindingAction(k) return bindings[k] or '' end +function SetBinding(k,a) bindings[k]=a; return true end +function SaveBindings() end +function GetCurrentBindingSet() return 1 end +local combat=false +function InCombatLockdown() return combat end +function time() return 1 end +local changes,cvars=0,{lockActionBars='1'} +C_CVar={GetCVar=function(k) return cvars[k] or '0' end,SetCVar=function(k,v) changes=changes+1; cvars[k]=tostring(v) end} +function IsGraphicsSettingValueSupported() return 0 end +C_Timer={After=function(_,fn) fn() end} +local reloads=0 +function ReloadUI() reloads=reloads+1 end +C_AddOns={IsAddOnLoaded=function() return true end} +LeaPlusDB={AutoSellJunk='Off'}; LeaMapsDB={ShowCoords='Off'} +VoiceQuestDB={enabled=false,maleVoice=999}; VoiceQuestCharDB={useOwn=true} +local layout={layoutName='Modern',layoutType=Enum.EditModeLayoutType.Preset,systems={}} +local function add(kind,index) layout.systems[#layout.systems+1]={system=Enum.EditModeSystem[kind],systemIndex=index,settings={}} end +for i=1,8 do add('ActionBar',i) end +for i=1,5 do add('UnitFrame',i) end +for _,i in ipairs({11,12,13}) do add('ActionBar',i) end +for _,kind in ipairs({'TotemActionBar','VehicleLeaveButton','ExtraAbilities'}) do add(kind,1) end +for _,kind in ipairs({'MainActionBarEndCap','StatusTrackingBar'}) do add(kind,1); add(kind,2) end +for _,kind in ipairs({'CastBar','ChatFrame','MicroMenu','Bags','ObjectiveTracker','Minimap','DamageMeter'}) do add(kind,1) end +local manager={layoutInfo={activeLayout=1,layouts={layout}}}; EditModeManagerFrame=manager +function manager:GetLayouts() return self.layoutInfo.layouts end +function manager:GetActiveLayoutInfo() return self.layoutInfo.layouts[self.layoutInfo.activeLayout] end +function manager:AreLayoutsOfTypeMaxed() return false end +function manager:CreateLayoutTbls() self.ready=true end +function manager:MakeNewLayout(l,t,n) assert(self.ready); l.layoutName=n; l.layoutType=t; table.insert(self.layoutInfo.layouts,l) end +EditModePresetLayoutManager={GetCopyOfPresetLayouts=function() return {CopyTable(layout)} end} +C_EditMode={SetActiveLayout=function(i) manager.layoutInfo.activeLayout=i end,ConvertLayoutInfoToString=function() return 'simulation-export' end} + +-- Add deterministic frame geometry, tooltip hooks and inventory cursor behavior. +local hooks={} +local objectHooks=setmetatable({},{__mode='k'}) +function hooksecurefunc(object,key,fn) + if type(object)=='string' then hooks[object]=key else + hooks[key]=fn + objectHooks[object]=objectHooks[object] or {} + objectHooks[object][key]=fn + end +end +function GameTooltip_SetDefaultAnchor() end +function GameTooltip_ShowCompareItem() end +function GetScreenWidth() return UIParent:GetWidth() end +local cf=assert(io.open((assert(os.getenv('RUEN_NATIVE_UI'))..'/Mainline-ContainerFrame.lua'))) +local nativeContainer=cf:read('*a');cf:close() +assert(loadstring(assert(nativeContainer:match('(function ContainerFrameItemButton_CalculateItemTooltipAnchors%b().-\nend)'))))() + +local function enrich(f,name) + f.name=name + function f:GetName() return self.name end + function f:GetParent() return self.parent or UIParent end + function f:GetOwner() return self.owner end + function f:GetAnchorType() return self.anchorType or 'ANCHOR_NONE' end + function f:SetAnchorType(value) self.anchorType=value end + function f:GetEffectiveScale() return (self==UIParent and self.scale or UIParent.scale)*(self.localScale or 1) end + function f:GetScale() return self.localScale or 1 end + function f:SetScaleBase(value) self.localScale=value end + function f:SetScale() error('must not call taint-prone native scale override') end + function f:SetWidth(w) self.w=w end + function f:GetWidth() return self.w or 100 end + function f:GetHeight() return self.h or 36 end + function f:SetHeight(h) self.h=h end + function f:GetSize() return self:GetWidth(),self:GetHeight() end + function f:ClearAllPoints() assert(not combat or not self.name or self.name=='RuenSwingTimers' or self.name=='GameTooltip' or self.name:match('^ShoppingTooltip'),'protected geometry changed in combat'); self.point=nil end + function f:SetPoint(point,relative,relativePoint,x,y) + if type(relative)=='string' then relative=_G[relative] end + self.point={point,relative,relativePoint,x or 0,y or 0} + end + f.ClearAllPointsBase=f.ClearAllPoints; f.SetPointBase=f.SetPoint + function f:GetPoint() if self.point then return unpack(self.point) end end + function f:GetNumPoints() return self.point and 1 or 0 end + function f:HookScript(event,fn) self.scripts[event]=fn end + function f:SetClampedToScreen() end + local function fraction(point,axis) + if axis=='x' then return point:find('LEFT') and 0 or point:find('RIGHT') and 1 or 0.5 end + return point:find('BOTTOM') and 0 or point:find('TOP') and 1 or 0.5 + end + function f:rect() + local scale=self:GetEffectiveScale()/UIParent.scale + local w,h=self:GetWidth()*scale,self:GetHeight()*scale + if self==UIParent then return 0,0,w,h end + if not self.point then return 0,0,w,h end + local p,relative,rp,x,y=unpack(self.point) + local l,b,rw,rh=relative:rect() + return l+rw*fraction(rp,'x')+x*scale-w*fraction(p,'x'),b+rh*fraction(rp,'y')+y*scale-h*fraction(p,'y'),w,h + end + function f:GetLeft() local l=self:rect();return l/(self:GetEffectiveScale()/UIParent.scale) end + function f:GetBottom() local _,b=self:rect();return b/(self:GetEffectiveScale()/UIParent.scale) end + function f:GetTop() local _,b,_,h=self:rect();return (b+h)/(self:GetEffectiveScale()/UIParent.scale) end + function f:GetRight() local l,_,w=self:rect();return (l+w)/(self:GetEffectiveScale()/UIParent.scale) end + function f:UpdateHeight() self.h=self.editModeHeight end + return f +end +local previousCreate=CreateFrame +function CreateFrame(kind,name,...) return enrich(previousCreate(kind,name,...),name) end +for _,name in ipairs(barNames) do enrich(_G[name],name) end +for _,name in ipairs({'ChatFrame1','PartyFrame','CompactRaidFrameContainer','UIParent','MinimapCluster','BagsBar','MicroMenuContainer','ObjectiveTrackerFrame','GameTooltip','StanceBar','PetActionBar','PossessActionBar','MultiCastActionBarFrame','MainMenuBarVehicleLeaveButton','ExtraAbilityContainer','PlayerCastingBarFrame','PlayerFrame','PetFrame','TargetFrame','TargetFrameToT','FocusFrame'}) do CreateFrame('Frame',name) end +UIParent.w,UIParent.h,UIParent.scale=1706.4,960,1.25 +ChatFrame1.w,ChatFrame1.h=380,150;ChatFrame1:SetPoint('BOTTOMLEFT',UIParent,'BOTTOMLEFT',20,45) +PartyFrame.w,PartyFrame.h=230,300;CompactRaidFrameContainer.w,CompactRaidFrameContainer.h=360,304 +PartyFrame.shown=false;CompactRaidFrameContainer.shown=false +GameTooltip.w,GameTooltip.h=220,120;GameTooltip.shown=false +function manager:IsShown() return false end +function manager:HookScript() end +function manager:UpdateSystems() end +StanceBar.w,StanceBar.h,StanceBar.localScale=338,30,0.8 +PetActionBar.w,PetActionBar.h,PetActionBar.localScale=338,30,0.8 +PossessActionBar.w,PossessActionBar.h,PossessActionBar.localScale=66,30,0.8 +MultiCastActionBarFrame.w,MultiCastActionBarFrame.h=230,38 +MainMenuBarVehicleLeaveButton.w,MainMenuBarVehicleLeaveButton.h=32,32 +ExtraAbilityContainer.w,ExtraAbilityContainer.h=250,120 +PlayerCastingBarFrame.w,PlayerCastingBarFrame.h=240,20 +PlayerFrame.w,PlayerFrame.h=232,100;TargetFrame.w,TargetFrame.h=232,100 +FocusFrame.w,FocusFrame.h=232,100;FocusFrame.localScale=.75 +PetFrame.w,PetFrame.h=130,45;PetFrame:SetPoint('TOPRIGHT',PlayerFrame,'BOTTOMRIGHT',0,-4) +TargetFrameToT.w,TargetFrameToT.h=130,45;TargetFrameToT:SetPoint('TOPRIGHT',TargetFrame,'BOTTOMRIGHT',0,-4) +local byKind={[Enum.EditModeSystem.ActionBar]={MainActionBar,MultiBarBottomLeft,MultiBarBottomRight,MultiBarRight,MultiBarLeft,MultiBar5,MultiBar6,MultiBar7},[Enum.EditModeSystem.Minimap]={MinimapCluster},[Enum.EditModeSystem.Bags]={BagsBar},[Enum.EditModeSystem.MicroMenu]={MicroMenuContainer},[Enum.EditModeSystem.ObjectiveTracker]={ObjectiveTrackerFrame}} +local function setting(s,k) for _,v in ipairs(s.settings) do if v.setting==k then return v.value end end end +byKind[Enum.EditModeSystem.ActionBar][Enum.EditModeActionBarSystemIndices.PetActionBar]=PetActionBar +C_EditMode.SetActiveLayout=function(i) + manager.layoutInfo.activeLayout=i + for _,s in ipairs(manager:GetActiveLayoutInfo().systems) do + local list=byKind[s.system];local f=list and list[s.systemIndex or 1] + if f and s.anchorInfo then + f.systemInfo=s + if s.system==Enum.EditModeSystem.ActionBar and (s.systemIndex or 1)<=8 then + local rows=setting(s,Enum.EditModeActionBarSetting.NumRows) or 1 + f.w=(rows==1 and 495 or 252);f.h=rows*36+(rows-1)*2 + elseif f==PetActionBar then + local scale=(50+10*(setting(s,Enum.EditModeActionBarSetting.IconSize) or 3))/100 + -- Native small buttons are 30px; padding is between containers. + f.localScale=1;f.w=10*30*scale+9*(2+(setting(s,Enum.EditModeActionBarSetting.IconPadding) or 2));f.h=30*scale + elseif f==MinimapCluster then f.w,f.h=215,256 + elseif f==BagsBar then f.w,f.h=315,45;f.localScale=0.8 + elseif f==MicroMenuContainer then f.w,f.h=241.6,32 + elseif f==ObjectiveTrackerFrame then f.w,f.h=250,400 end + local a=s.anchorInfo + f:SetPoint(a.point,a.relativeTo,a.relativePoint,a.offsetX/f:GetScale(),a.offsetY/f:GetScale()) + end + end +end +C_EditMode.GetLayouts=function() return CopyTable(manager.layoutInfo) end +local classSaves=0 +C_EditMode.SaveLayouts=function(info) + assert(info~=manager.layoutInfo and info.layouts~=manager.layoutInfo.layouts,'shared layout was passed instead of detached copy') + assert(not combat,'native layout saved in combat') + classSaves=classSaves+1 + manager.layoutInfo=CopyTable(info) + C_EditMode.SetActiveLayout(info.activeLayout) +end +local cursor,actions=nil,{[37]={'spell',999},[3]={'item',117}} +for i=1,12 do _G['MultiBarLeftButton'..i]={action=36+i} end +function GetActionInfo(slot) local a=actions[slot]; if a then return unpack(a) end end +function GetCursorInfo() if cursor then return unpack(cursor) end end +function ClearCursor() cursor=nil end +function PickupItem(id) cursor={'item',id} end +function PlaceAction(slot) actions[slot]=cursor;cursor=nil end +function PickupAction(slot) cursor=actions[slot];actions[slot]=nil end +C_Item={PickupItem=PickupItem,GetItemCount=function(id) return id==6948 and 1 or 0 end,GetItemInfoInstant=function(id) return id,'','',nil,nil,id==99999 and 7 or 0,(id==117 or id==453) and 5 or 0 end} +C_Container={GetContainerNumSlots=function(bag) return bag==0 and 4 or 0 end,GetContainerItemID=function(_,slot) return ({117,453,117,99999})[slot] end} +local P={Translate=function(s) return s end, Localized=function(en) return en end} +assert(loadfile(root..'Profile.lua'))('RuenUI',P) +assert(loadfile(root..'Controls.lua'))('RuenUI',P) +assert(loadfile(root..'Brand.lua'))('RuenUI',P) +assert(loadfile(root..'ClassLayout.lua'))('RuenUI',P) +for _,file in ipairs({'PetExtras.lua','SwingTimers.lua','ExtraBars.lua','OverlayLayout.lua','DamageMeters.lua','ClassAssist.lua','HardwareProfile.lua','Optimizer.lua','GunAudio.lua'}) do assert(loadfile(root..file))('RuenUI',P) end +local available={'JUMP','TARGETNEARESTENEMY','TARGETPREVIOUSENEMY'} +for _,entry in ipairs(P.menuBindings) do available[#available+1]=entry[2] end +function GetNumBindings() return #available end +function GetBinding(i) return available[i] end +function UpdateContainerFrameAnchors() if hooks.UpdateContainerFrameAnchors then hooks.UpdateContainerFrameAnchors() end end +CreateFrame('Frame','ContainerFrameCombinedBags') +ContainerFrameCombinedBags.w,ContainerFrameCombinedBags.h=420,330 +ContainerFrameCombinedBags.shown=false +ContainerFrameCombinedBags.SetScale=ContainerFrameCombinedBags.SetScaleBase + +if bundled then assert(loadfile(root..'AddonPresets.lua'))('RuenUI',P) end +assert(loadfile(root..'Core.lua'))('RuenUI',P) +RuenUICharacter={original={},version=2,addedBindings={['ALT-F']='INTERACTTARGET'}} +RuenUIDB={original={},reports={},graphicsVersion=P.graphicsVersion} +cvars.graphicsLightMode='1' +eventFrame.scripts.OnEvent(eventFrame,'PLAYER_ENTERING_WORLD') +assert(RuenUICharacter.version==P.version,RuenUICharacter.layoutStatus) +assert(cvars.graphicsLightMode=='1','UI update reset graphics') +assert(cvars.lockActionBars=='0' and settings.lockActionBars==false,'action and pet slots must be unlocked in both CVar and Settings') +assert(RuenUICharacter.verification.verified,'visible bar verification failed') +assert(math.abs(PetActionBar:GetWidth()-408)<.01 and math.abs(PetActionBar:GetHeight()-39)<.01,'native larger pet geometry missing') +for i=1,7 do assert(bars[i], 'all 96 slots must be enabled') end +local keys={'Q','W','R','T','A','G','H','Z','X','C','V','B'} +for i,k in ipairs(keys) do + assert(bindings[k]=='ACTIONBUTTON'..i,k) + assert(bindings['SHIFT-'..k]=='MULTIACTIONBAR1BUTTON'..i) + assert(bindings['CTRL-'..k]=='MULTIACTIONBAR2BUTTON'..i) + assert(bindings['ALT-'..k]=='MULTIACTIONBAR5BUTTON'..i, 'near-hand fourth row missing') +end +for _,prefix in ipairs({'','SHIFT-','CTRL-','CTRL-SHIFT-'}) do + assert(bindings[prefix..'E']=='MOVEFORWARD' and bindings[prefix..'D']=='MOVEBACKWARD') + assert(bindings[prefix..'S']=='STRAFELEFT' and bindings[prefix..'F']=='STRAFERIGHT') +end +local numberKeys={'1','2','3','4','5','6','7','8','9','0','-','='} +for _,r in ipairs({{'CTRL-','4'},{'SHIFT-','3'},{'ALT-','6'},{'CTRL-SHIFT-','7'}}) do for i,key in ipairs(numberKeys) do assert(bindings[r[1]..key]=='MULTIACTIONBAR'..r[2]..'BUTTON'..i,'missing utility binding') end end +assert(modified=='NONE' and cvars.autoSelfCast=='1','Alt abilities must not force self-cast') +assert(bindings.F1=='TARGETSELF') +for i=1,10 do assert(bindings[numberKeys[i]]=='BONUSACTIONBUTTON'..i,'missing direct pet shortcut') end +assert(actions[37][1]=='spell' and actions[37][2]==999,'existing click slot overwritten') +assert(actions[3][2]==117,'original food shortcut moved') +assert(actions[38][2]==6948 and actions[39][2]==117 and actions[40][2]==453,'hearth/food copies missing') +assert(not actions[41],'duplicate or nonfood item seeded') +local function gap(upper,lower) return upper:GetBottom()*(upper:GetEffectiveScale()/UIParent.scale)-lower:GetTop()*(lower:GetEffectiveScale()/UIParent.scale) end +for _,display in ipairs({{1920,1080,1.40625},{2560,1440,1.875},{2133,1200,1.25}}) do + UIParent.scale=display[3];UIParent.w=display[1]/display[3];UIParent.h=display[2]/display[3] + local originalAnchor=MultiBarLeft.systemInfo.anchorInfo + local originalHeight=ObjectiveTrackerFrame.editModeHeight + UIParent.scripts.OnSizeChanged() + assert(MultiBarLeft.systemInfo.anchorInfo==originalAnchor,'runtime must not mutate shared native layout state') + assert(ObjectiveTrackerFrame.editModeHeight==originalHeight,'runtime must not mutate native tracker configuration') + assert(MultiBarLeft.point[2]==UIParent and BagsBar.point[2]==UIParent,'protected controls must not anchor to layout-managed frames') + local function edge(f,method) return f[method](f)*f:GetEffectiveScale()/UIParent.scale end + for _,method in ipairs({'GetLeft','GetRight'}) do + assert(math.abs(edge(BagsBar,method)-edge(MicroMenuContainer,method))<0.01,'corner row edges misaligned') + assert(math.abs(edge(BagsBar,method)-edge(MultiBarLeft,method))<0.01,'click/bags edges misaligned') + end + assert(gap(BagsBar,MicroMenuContainer)>=9.9,'bags/menu overlap') + assert(gap(MultiBarLeft,BagsBar)>=13.9,'click/bags overlap') + assert(gap(MinimapCluster,ObjectiveTrackerFrame)>=23.9,'map/quests overlap') + assert(gap(ObjectiveTrackerFrame,MultiBarRight)>=23.9,'quests/click overlap') + assert(gap(MultiBarBottomLeft,MainActionBar)>=3.9,'combat rows overlap') + assert(gap(PlayerCastingBarFrame,RuenSwingTimers)>=17.9,'swing covers cast spell label') + assert(math.abs(RuenSwingTimers:GetWidth()-PlayerCastingBarFrame:GetWidth())<0.01,'swing/cast widths differ') + GameTooltip.owner=UIParent;GameTooltip.shown=true + hooks.GameTooltip_SetDefaultAnchor(GameTooltip,UIParent) + local tx,ty,tw,th=GameTooltip:rect() + for _,name in ipairs({'MultiBarRight','MultiBarLeft','ObjectiveTrackerFrame','PlayerFrame','TargetFrame'}) do + local x,y,w,h=_G[name]:rect() + assert(math.min(tx+tw,x+w)<=math.max(tx,x)+1 or math.min(ty+th,y+h)<=math.max(ty,y)+1,'tooltip overlaps '..name) + end +end + +-- Validate all class-control combinations, with maximum native stance/pet counts. +local function intersects(a,b) + local al,ab,aw,ah=a:rect();local bl,bb,bw,bh=b:rect() + if a==PetActionBar then aw=aw+select(3,P.PetExtraGeometry()) end + if b==PetActionBar then bw=bw+select(3,P.PetExtraGeometry()) end + return math.min(al+aw,bl+bw)-math.max(al,bl)>1 and math.min(ab+ah,bb+bh)-math.max(ab,bb)>1 +end +local controls={'RuenSwingTimers','StanceBar','PetActionBar','PossessActionBar','MultiCastActionBarFrame','MainMenuBarVehicleLeaveButton','ExtraAbilityContainer','PlayerCastingBarFrame','PlayerFrame','PetFrame','TargetFrame','TargetFrameToT','RuenTargetTargetTarget','FocusFrame'} +local scenarios={ + warrior={'StanceBar'}, paladin={'StanceBar'}, hunter={'StanceBar','PetActionBar','PetFrame'}, + rogue={'StanceBar'}, priest={'StanceBar'}, shaman={'MultiCastActionBarFrame'}, + mage={'PetActionBar','PetFrame'}, warlock={'PetActionBar','PetFrame'}, druid={'StanceBar'}, + possessed={'PossessActionBar','PetActionBar','MainMenuBarVehicleLeaveButton'}, + maximum={'StanceBar','PetActionBar','PetFrame','MultiCastActionBarFrame','PossessActionBar','MainMenuBarVehicleLeaveButton'}, +} +assert(RuenUIDB.classLayoutVersion==7 and classSaves==2,'class migration missing or repeated') +for _,name in ipairs({'PartyFrame','CompactRaidFrameContainer'}) do + _G[name].shown=true;UIParent.scripts.OnSizeChanged() + assert(not intersects(_G[name],MultiBar7),'group overlaps reserve bars') + assert(_G[name]:GetTop()<=UIParent.h,'group is offscreen') + _G[name].shown=false +end +local standardAnchor=CopyTable(manager:GetActiveLayoutInfo().systems[1].anchorInfo) +for _,display in ipairs({{1920,1080,1.40625},{2560,1440,1.875},{2133,1200,1.25}}) do + UIParent.scale=display[3];UIParent.w=display[1]/display[3];UIParent.h=display[2]/display[3] + UIParent.scripts.OnSizeChanged() + for class,names in pairs(scenarios) do + currentClass=class:upper() + for _,n in ipairs(controls) do _G[n].shown=false end + for _,n in ipairs(names) do _G[n].shown=true end + for _,n in ipairs({'RuenSwingTimers','PlayerCastingBarFrame','PlayerFrame','TargetFrame','TargetFrameToT','RuenTargetTargetTarget','FocusFrame','ExtraAbilityContainer'}) do _G[n].shown=true end + CompactRaidFrameContainer.shown=class~='maximum' + UIParent.scripts.OnSizeChanged() + assert(not CompactRaidFrameContainer.shown or CompactRaidFrameContainer:GetTop()*CompactRaidFrameContainer:GetScale()<=UIParent.h,'full raid offscreen '..class..' '..table.concat(display,',')..' '..table.concat(P.groupLayoutIssues or {},';')) + if PetActionBar.shown then + local l,b,w,h=PetActionBar:rect() + assert(math.abs(l+(w+select(3,P.PetExtraGeometry()))/2-UIParent.w/2)<.01,class..' twelve-button pet row not centered') + UIParent.scripts.OnSizeChanged() + local l2,b2=PetActionBar:rect() + assert(math.abs(l-l2)<.01 and math.abs(b-b2)<.01,'pet layout drifts on refresh') + end + for _,n in ipairs(controls) do + local f=_G[n] + if f.shown then + local l,b,w,h=f:rect() + assert(l>=0 and b>=0 and l+w<=UIParent.w and b+h<=UIParent.h,class..' offscreen '..n) + assert(not CompactRaidFrameContainer.shown or not intersects(f,CompactRaidFrameContainer),class..' full raid overlap '..n) + for _,other in ipairs({'MainActionBar','MultiBarBottomLeft','MultiBarBottomRight','MultiBarLeft','MultiBarRight','MultiBar5','MultiBar6','MultiBar7','BagsBar','MicroMenuContainer'}) do + assert(not intersects(f,_G[other]),class..' overlaps combat/corner '..n..'/'..other) + end + end + end + for i,n in ipairs(controls) do + for j=i+1,#controls do + local other=controls[j] + if _G[n].shown and _G[other].shown then assert(not intersects(_G[n],_G[other]),class..' controls overlap '..n..'/'..other..' '..table.concat({_G[n]:rect()},',')..' vs '..table.concat({_G[other]:rect()},',')) end + end + end + end +end +CompactRaidFrameContainer.shown=false +-- Partial and fully learned totems center the actual controls, not empty slots. +currentClass='SHAMAN' +for _,n in ipairs(controls) do _G[n].shown=false end +MultiCastActionBarFrame.shown=true +for i=1,4 do + local f=CreateFrame('Button','MultiCastSlotButton'..i) + f.w,f.h=32,32;f:SetPoint('BOTTOMLEFT',MultiCastActionBarFrame,'BOTTOMLEFT',36+(i-1)*40,3) +end +for _,count in ipairs({1,2,4}) do + for i=1,4 do _G['MultiCastSlotButton'..i].shown=i<=count end + UIParent.scripts.OnSizeChanged() + local left=MultiCastSlotButton1:GetLeft() + local right=_G['MultiCastSlotButton'..count]:GetRight() + assert(math.abs((left+right)/2-UIParent.w/2)<0.01,'visible totems not centered') + assert(PlayerFrame:GetBottom()<360,'single class row left excessive vertical space') + local before=MultiCastActionBarFrame:GetLeft() + UIParent.scripts.OnSizeChanged() + assert(math.abs(MultiCastActionBarFrame:GetLeft()-before)<0.01,'totem centering drifted') +end +for i=1,4 do _G['MultiCastSlotButton'..i].shown=false end +-- A form learned in combat must already have its reserved anchor. Hooks defer. +local stancePoint=StanceBar.point;combat=true +StanceBar.scripts.OnShow();assert(StanceBar.point==stancePoint,'form show moved secure geometry in combat') +combat=false;UIParent.scripts.OnSizeChanged() +local previous=classSaves;P.MigrateClassLayout();assert(classSaves==previous,'migration repeated') +local oldShared=manager.layoutInfo;RuenUIDB.classLayoutVersion=nil +bindings.Q='MY_SPELL';local cv=changes +P.MigrateClassLayout() +assert(oldShared.layouts[2].systems[1].anchorInfo.offsetY==standardAnchor.offsetY,'migration changed main bars') +assert(bindings.Q=='MY_SPELL' and cv==changes,'class migration reset controls/graphics') +bindings.Q='ACTIONBUTTON1' +print('PASS: maximum class controls, all 9 class profiles, possession/exit, live frame growth, 1080p/1440p, combat guard and detached per-class migration') + +-- Notification and native-panel regression coverage, injected into the full HUD simulation. +local function makePopup(name,w,h) + local f=CreateFrame('Frame',name);f.w,f.h,f.shown=w,h,false + function f:IsProtected()return false end + function f:ClearAllPoints()self.point=nil end + f.ClearAllPointsBase=f.ClearAllPoints + return f +end +local buffs=makePopup('BuffFrame',300,45) +local breath=makePopup('MirrorTimer1',260,30) +local social=makePopup('ChatAlertFrame',10,10) +local quick=makePopup('QuickJoinToastButton',32,32) +local bn=makePopup('BNToastFrame',250,63) +local timeAlert=makePopup('TimeAlertFrame',250,50) +local shard=makePopup('ShardTransferImminentFrame',250,50) +local roll=makePopup('GroupLootContainer',256,400) +local rolls={} +for i=1,4 do rolls[i]=makePopup('GroupLootFrame'..i,286,80) end +roll.rollFrames=rolls +local talking=makePopup('TalkingHeadFrame',570,155) +local alertHost=makePopup('AlertFrame',10,10) +local loot1=makePopup('LootTest1',326,80) +local loot2=makePopup('LootTest2',326,80) +local achievement=makePopup('AchievementTest',360,104) +local activeAlerts={} +alertHost.alertFrameSubSystems={{alertFramePool={EnumerateActive=function() + local i=0;return function()i=i+1;return activeAlerts[i] end +end}}} +local function nativeSocial() + social.shown=true;social:SetPoint('BOTTOMLEFT',ChatFrame1,'TOPLEFT',-20,27) + quick.shown=true;quick:SetPoint('BOTTOMLEFT',social,'BOTTOMLEFT',0,0) + bn.shown=true;bn:SetPoint('BOTTOMLEFT',quick,'TOPLEFT',0,0) + timeAlert.shown=true;timeAlert:SetPoint('BOTTOMLEFT',bn,'TOPLEFT',0,0) + shard.shown=true;shard:SetPoint('BOTTOMLEFT',social,'TOPLEFT',30,55) +end +for _,display in ipairs({{1920,1080,1.40625},{2560,1440,1.875},{1920,1080,1},{2560,1440,1},{1366,768,1}}) do + UIParent.scale=display[3];UIParent.w=display[1]/display[3];UIParent.h=display[2]/display[3] + for class,names in pairs(scenarios) do if class~='maximum' then + currentClass=class:upper() + for _,n in ipairs(controls)do _G[n].shown=false end + for _,n in ipairs(names)do _G[n].shown=true end + for _,n in ipairs({'PlayerCastingBarFrame','PlayerFrame','TargetFrame','TargetFrameToT','RuenTargetTargetTarget','FocusFrame'})do _G[n].shown=true end + ExtraAbilityContainer.shown=false + CompactRaidFrameContainer.shown=true + buffs.shown=true;buffs:SetPoint('TOPRIGHT',UIParent,'TOPRIGHT',-240,-8) + breath.shown=true;breath:SetPoint('TOP',UIParent,'TOP',0,-75) + nativeSocial();UIParent.scripts.OnSizeChanged() + for _,popup in ipairs({quick,bn,timeAlert,shard})do + for _,n in ipairs({'MultiBar6','MultiBar7','PartyFrame','CompactRaidFrameContainer'})do + if _G[n].shown then assert(not intersects(popup,_G[n]),class..': toast blocked by '..n)end + end + end + -- No protected control may move when a social alert appears during combat. + local reserveAnchor=MultiBar6.point;combat=true + bn.shown=true;P.PositionOverlayFrames();assert(MultiBar6.point==reserveAnchor) + combat=false + -- Every combat/utility/bag tooltip is rechecked after its text grows. + local oldOwner=GameTooltip.owner + GameTooltip.shown=false;GameTooltip.scripts.OnHide(GameTooltip) + GameTooltip.owner=MultiBar6;GameTooltip.shown=true + for _,size in ipairs({{220,120},{300,260}})do + GameTooltip.w,GameTooltip.h=size[1],size[2] + GameTooltip.scripts.OnSizeChanged(GameTooltip) + for _,obstacle in ipairs(P.OverlayObstacles(false))do + local l,b,w,h=GameTooltip:rect() + assert((P.tooltipOverSocial and (obstacle.name=='ChatFrame1' or obstacle.name=='Social notifications')) or not (lobstacle.left and bobstacle.bottom),'tooltip blocks '..(obstacle.name or '?')..' '..class..' '..table.concat(display,',')..' '..tostring(P.tooltipUnplaced)..' tip '..table.concat({GameTooltip:rect()},',')..' raid '..table.concat({CompactRaidFrameContainer:rect()},',')) + end + end + GameTooltip.owner=oldOwner;GameTooltip.w,GameTooltip.h=220,120 + GameTooltip.shown=false -- independent notification cases; saturation is checked separately + for _,case in ipairs({'loot','rolls','talking'})do + breath.shown=case~='talking' + activeAlerts={};loot1.shown=false;loot2.shown=false;achievement.shown=false;roll.shown=false;talking.shown=false + if case=='loot' or case=='mixed' then + loot1.shown=true;loot2.shown=true;achievement.shown=true;activeAlerts={loot1,loot2,achievement} + end + if case=='rolls' or case=='mixed' then roll.shown=true end + if case=='talking' or case=='mixed' then talking.shown=true end + for _,f in ipairs(rolls)do f.shown=roll.shown end + P.PositionOverlayFrames() + assert(#P.overlayUnplaced==0,display[1]..'/'..class..'/'..case..': no room for '..table.concat(P.overlayUnplaced,',')) + -- A later native reanchor/late addon event is repaired, including combat + -- notifications, without moving secure action buttons. + if case=='loot' then + loot1:SetPoint('BOTTOMLEFT',UIParent,'BOTTOMLEFT',450,48) + local anchor=MainActionBar.point;combat=true + P.overlayListener.scripts.OnEvent(nil,'ADDON_LOADED') + assert(MainActionBar.point==anchor,'alert event moved protected bars') + combat=false + end + local problems=P.OverlayAudit() + assert(#problems==0,display[1]..'/'..class..'/'..case..': '..table.concat(problems,',')) + local popupList={talking,loot1,loot2,achievement,unpack(rolls)} + for i,f in ipairs(popupList)do if f.shown then + for j=i+1,#popupList do if popupList[j].shown then assert(not intersects(f,popupList[j]),'alerts overlap each other')end end + end end + end + for _,f in ipairs(rolls)do f.shown=false end + roll.shown=false;talking.shown=false;loot1.shown=false;loot2.shown=false;achievement.shown=false;activeAlerts={} + end end +end +-- Reflow bag geometry after the native bank OnShow stack has returned; never +-- recursively invoke Blizzard's bag manager from a Ruen event or command. +-- Saturated layouts must fail visibly in diagnostics without hiding an alert, +-- dropping its content, changing protected controls or crashing. +ExtraAbilityContainer.shown=true;UIParent.scripts.OnSizeChanged() +local huge=makePopup('OversizeTest',UIParent.w+100,UIParent.h+100) +huge.shown=true;activeAlerts={huge};local hugePoint=huge.point +P.PositionOverlayFrames() +assert(#P.overlayUnplaced==1 and huge.shown and huge.point==hugePoint) +assert(#P.OverlayAudit()>0,'unplaced alert absent from diagnostics') +huge.shown=false;activeAlerts={};ExtraAbilityContainer.shown=false +local nativeAnchors=UpdateContainerFrameAnchors +UpdateContainerFrameAnchors=function()error('Ruen called native bag manager')end +local nativeAfter=C_Timer.After;local pending={} +C_Timer.After=function(_,fn)pending[#pending+1]=fn end +ContainerFrameCombinedBags.shown=true;ContainerFrameCombinedBags.h=330 +local before=ContainerFrameCombinedBags.point +hooks.UpdateContainerFrameAnchors() +assert(ContainerFrameCombinedBags.point==before and #pending==1,'bag hook ran inline in bank OnShow') +while #pending>0 do local f=table.remove(pending,1);f()end +SlashCmdList.RUENUI('bags') +while #pending>0 do local f=table.remove(pending,1);f()end +C_Timer.After=nativeAfter;UpdateContainerFrameAnchors=nativeAnchors +ContainerFrameCombinedBags.shown=false +CompactRaidFrameContainer.shown=false +for _,f in ipairs({buffs,breath,social,quick,bn,timeAlert,shard,roll,talking,loot1,loot2,achievement})do f.shown=false end +print('PASS: social stack reserved in/out of combat; loot/achievement stacks, four loot rolls, dialogue popups; saturated layouts reported without hiding alerts; all clear every class HUD at 1080p/1440p/1366x768; bank hook deferred with no native manager invocation') + +-- Simulate the native sequence: SetOwner/default anchor -> blank/partial text +-- -> SetAction final text -> next-frame callbacks. Rendering happens afterward. +local oldAfter=C_Timer.After +local pending={} +C_Timer.After=function(_,fn) pending[#pending+1]=fn end +local function flush() + local n=0 + while #pending>0 do + n=n+1;assert(n<=8,'tooltip resize feedback loop') + table.remove(pending,1)() + end + return n +end +local owner=CreateFrame('Button','TooltipSpellTest');owner.parent=MainActionBar +local secondOwner=CreateFrame('Button','TooltipOtherSpellTest');secondOwner.parent=MultiBarLeft +local originalClear,originalSet=GameTooltip.ClearAllPointsBase,GameTooltip.SetPointBase +local placements=0 +GameTooltip.ClearAllPointsBase=function(self)self.point=nil end +GameTooltip.SetPointBase=function(self,...) + placements=placements+1;originalSet(self,...) + -- A layout pass may itself emit a size notification. It must settle. + self.scripts.OnSizeChanged(self) +end +local originalFind=P.FindOverlayPosition;local searches=0 +P.FindOverlayPosition=function(...)searches=searches+1;return originalFind(...)end +local function nativeRefresh(button,width,height) + GameTooltip.owner=button + GameTooltip.shown=false;GameTooltip.scripts.OnHide(GameTooltip) + GameTooltip.w,GameTooltip.h=0,0 + -- Native anchoring happens before text is repopulated every refresh. + originalSet(GameTooltip,'BOTTOMRIGHT',UIParent,'BOTTOMRIGHT',-13,13) + hooks.GameTooltip_SetDefaultAnchor(GameTooltip,button) + GameTooltip.scripts.OnSizeChanged(GameTooltip) + GameTooltip.w,GameTooltip.h=320,16 + GameTooltip.scripts.OnSizeChanged(GameTooltip) + GameTooltip.w,GameTooltip.h=width,height;GameTooltip.shown=true + GameTooltip.scripts.OnShow(GameTooltip) + GameTooltip.scripts.OnSizeChanged(GameTooltip) + assert(#pending==1,'tooltip refresh was not coalesced') + flush() +end +local function anchor() + local point,relative,rp,x,y=GameTooltip:GetPoint(1) + assert(point=='BOTTOMRIGHT' and relative==UIParent and rp=='BOTTOMLEFT') + return x,y +end +GameTooltip.shown=false;GameTooltip.scripts.OnHide(GameTooltip);flush() +for _,display in ipairs({{1920,1080,1.40625},{2560,1440,1.875},{2560,1440,1}})do + UIParent.scale=display[3];UIParent.w=display[1]/display[3];UIParent.h=display[2]/display[3] + UIParent.scripts.OnSizeChanged();flush() + nativeRefresh(owner,240,180) + local x,y=anchor();local count=searches + combat=true + for i=1,100 do + nativeRefresh(owner,240,180) + local nx,ny=anchor() + assert(math.abs(nx-x)<.001 and math.abs(ny-y)<.001,'stationary spell tooltip jittered') + end + combat=false + assert(searches==count,'refreshes repeatedly searched for another tooltip position') + -- A genuinely larger finished tooltip may reflow once; shrinking afterward + -- must not send it back to a different anchor every cooldown refresh. + nativeRefresh(owner,290,300) + x,y=anchor();count=searches + for i=1,30 do + nativeRefresh(owner,240,180);local nx,ny=anchor() + assert(nx==x and ny==y,'shrinking tooltip oscillated') + nativeRefresh(owner,290,300);nx,ny=anchor() + assert(nx==x and ny==y,'returning tooltip oscillated') + end + assert(searches==count,'settled footprint was not retained') + local before=placements + GameTooltip.scripts.OnSizeChanged(GameTooltip);flush() + assert(placements==before,'unchanged tooltip rewrote its own anchor') + nativeRefresh(secondOwner,220,120) + assert(GameTooltip.owner==secondOwner,'moving to a different button lost its owner') + -- Real dismissal ends the hover. The next tooltip must measure afresh. + GameTooltip.shown=false;GameTooltip.scripts.OnHide(GameTooltip);flush() + nativeRefresh(owner,220,120) +end +-- Custom anchors belonging to another UI/addon remain under that owner's control. +local custom=CreateFrame('Frame','CustomTooltipOwner');custom.parent=UIParent +GameTooltip.shown=false;GameTooltip.scripts.OnHide(GameTooltip);flush() +GameTooltip.owner=custom;GameTooltip.shown=true +originalSet(GameTooltip,'TOPLEFT',custom,'BOTTOMLEFT',5,-5) +local customPoint=GameTooltip.point +GameTooltip.scripts.OnShow(GameTooltip);GameTooltip.scripts.OnSizeChanged(GameTooltip);flush() +assert(GameTooltip.point==customPoint,'unmanaged custom tooltip was moved') +GameTooltip.shown=false;GameTooltip.scripts.OnHide(GameTooltip);flush() +GameTooltip.ClearAllPointsBase,GameTooltip.SetPointBase=originalClear,originalSet +P.FindOverlayPosition=originalFind;C_Timer.After=oldAfter +GameTooltip.w,GameTooltip.h=220,120;GameTooltip.owner=UIParent;GameTooltip.shown=true +print('PASS: 480 native spell refreshes stable across resolutions and combat; temporary blank/partial text ignored; growth/shrink stable; no resize feedback or repeated searches; new owners and custom anchors respected') + +-- Regression: an old alt still has mask 11 after a different character has +-- completed the account-wide layout migration (mask 127). +local originalCharacter=RuenUICharacter +local originalBars={GetActionBarToggles()} +local originalQ=bindings.Q +local function setLegacyBars() + for i=1,7 do Settings.SetValue('PROXY_SHOW_ACTIONBAR_'..(i+1),i==1 or i==2 or i==4) end +end +local function assertExpanded() + local visible={GetActionBarToggles()} + for i=1,7 do assert(visible[i],'old character still missing action bar '..(i+1))end + assert(RuenUICharacter.extraBarsVisibilityVersion==1,'visibility not marked per character') +end +assert(RuenUIDB.extraBarsVersion==1,'fixture needs already-migrated account') +local saves,graphics=classSaves,changes +local existingSpell=actions[37] +bindings.Q='MY_PERSONAL_HUNTER_BINDING' +local oldBackup={false,false,false,false,false,false,false} +RuenUICharacter={version=P.version,oldBars=oldBackup,personalSetting='keep'} +setLegacyBars();P.MigrateExtraBars() +assertExpanded() +assert(RuenUICharacter.oldBars==oldBackup,'original restore snapshot overwritten') +assert(classSaves==saves,'visibility repair rewrote shared Edit Mode layout') +assert(changes==graphics and actions[37]==existingSpell and bindings.Q=='MY_PERSONAL_HUNTER_BINDING','visibility repair reset graphics, abilities or bindings') +assert(RuenUICharacter.personalSetting=='keep') +-- Subsequent refreshes, reloads and lock/unlock may not undo manual choices. +Settings.SetValue('PROXY_SHOW_ACTIONBAR_7',false) +P.MigrateExtraBars();P.MigrateExtraBars(true) +assert(not bars[6],'migration repeated after completion') +-- A second character gets its own migration and backup, not the first alt's. +RuenUICharacter={version=P.version};setLegacyBars();P.MigrateExtraBars() +assertExpanded() +for i=1,7 do assert(RuenUICharacter.oldBars[i]==(i==1 or i==2 or i==4),'wrong pre-upgrade bar snapshot')end +-- A guarded attempt must not mark completion before it can enable anything. +for _,guard in ipairs({'combat','disabled','edit','override','foreign'})do + RuenUICharacter={version=P.version};setLegacyBars() + local name=manager:GetActiveLayoutInfo().layoutName + local shown=manager.IsShown + if guard=='combat' then combat=true + elseif guard=='disabled' then RuenUIDB.disabled=true + elseif guard=='edit' then manager.IsShown=function()return true end + elseif guard=='override' then manager.overrideLayoutInfo={} + else manager:GetActiveLayoutInfo().layoutName='Personal Layout' end + P.MigrateExtraBars() + assert(not bars[5] and not RuenUICharacter.extraBarsVisibilityVersion,'guarded migration changed or marked state: '..guard) + combat=false;RuenUIDB.disabled=nil;manager.IsShown=shown;manager.overrideLayoutInfo=nil + manager:GetActiveLayoutInfo().layoutName=name + P.MigrateExtraBars();assertExpanded() +end +RuenUICharacter=originalCharacter;bindings.Q=originalQ +for i=1,7 do Settings.SetValue('PROXY_SHOW_ACTIONBAR_'..(i+1),originalBars[i]) end +print('PASS: old mask-11 characters upgrade independently on migrated accounts; original backups, actions, custom bindings and graphics preserved; repeat/manual choices and combat/edit/disabled/foreign-layout guards respected') + +-- Rebranding preserves a pre-existing layout and narration choices. +local savedLayout=CopyTable(manager:GetActiveLayoutInfo()) +manager:GetActiveLayoutInfo().layoutName=P.legacyLayoutName +local voice={Language={Voice='ruRU',Fallback='enUS'},personal=17} +SpokenSettings={profiles={['Brad Narration']=voice},profileKeys={Tester='Brad Narration',Other='Personal'},global={NewCharacterProfile='Brad Narration'}} +local activeVoice='Brad Narration' +SpokenEnv={Addon={db={GetCurrentProfile=function() return activeVoice end,SetProfile=function(_,name) activeVoice=name end}}} +local keyBefore=bindings.Q;local graphicsBefore=changes +P.MigrateBrand() +assert(manager:GetActiveLayoutInfo().layoutName=='Ruen UI - Clear ESDF') +assert(manager:GetActiveLayoutInfo().systems[1].anchorInfo.offsetY==savedLayout.systems[1].anchorInfo.offsetY) +assert(SpokenSettings.profiles['Ruen Narration']==voice and not SpokenSettings.profiles['Brad Narration']) +assert(activeVoice=='Ruen Narration' and voice.Language.Voice=='ruRU' and voice.personal==17) +assert(SpokenSettings.profileKeys.Tester=='Ruen Narration' and SpokenSettings.profileKeys.Other=='Personal') +assert(bindings.Q==keyBefore and changes==graphicsBefore) +local savesBefore=classSaves;P.MigrateBrand();assert(classSaves==savesBefore) +assert(SLASH_RUENUI1=='/ruen' and SLASH_RUENUI2=='/ruenui' and SLASH_RUENUI3==nil) +print('PASS: Ruen UI name migration preserves geometry, bindings, graphics and Russian narration; old command remains an alias') + +-- Native pet dragging must work without Shift; keep native right-click behavior. +Settings.GetValue=function(key) return settings[key] end +local pickedPet +function PickupPetAction(id) pickedPet=id end +function IsModifiedClick() return false end +BaseActionButtonMixin={BaseActionButtonMixin_OnDragStart=function() end} +assert(loadfile((assert(os.getenv('RUEN_NATIVE_UI'))..'/PetActionBar.lua')))() +PetActionBar.Update=function() end +PetActionButtonMixin.PetActionButtonMixin_OnDragStart({SetChecked=function() end,GetID=function() return 4 end}) +assert(pickedPet==4,'native pet dragging still requires Shift') +-- Explicit unlock is combat guarded and does not change assignments or bindings. +settings.lockActionBars=true;combat=true;SlashCmdList.RUENUI('unlock') +assert(settings.lockActionBars==true,'unlock changed settings in combat') +combat=false;SlashCmdList.RUENUI('unlock');assert(settings.lockActionBars==false) +SlashCmdList.RUENUI('lock');assert(settings.lockActionBars and cvars.lockActionBars=='1') +local locks=changes;eventFrame.scripts.OnEvent(eventFrame,'PLAYER_ENTERING_WORLD');assert(settings.lockActionBars and changes==locks,'login reset user lock') +SlashCmdList.RUENUI('unlock');assert(not settings.lockActionBars) +print('PASS: native pet ability drag without Shift, and guarded unlock command') + +-- New mouse/menu migration and native inventory clearance. +assert(bindings.BUTTON3=='JUMP' and bindings.SPACE=='JUMP') +assert(bindings.BUTTON4=='TARGETPREVIOUSENEMY' and bindings.BUTTON5=='TARGETNEARESTENEMY') +assert(bindings.N=='TOGGLEWORLDMAP' and not bindings.M) +assert(bindings.P=='TOGGLESPELLBOOK' and bindings['SHIFT-P']=='TOGGLEPROFESSIONBOOK') +assert(bindings.L=='TOGGLEGROUPFINDER' and bindings.F8=='RUENUI_MACROS') +ContainerFrameCombinedBags.shown=true +for _,display in ipairs({{1920,1080,1.40625},{2560,1440,1.875},{2133,1200,1.25}}) do + UIParent.scale=display[3];UIParent.w=display[1]/display[3];UIParent.h=display[2]/display[3] + ContainerFrameCombinedBags.localScale=1 + UIParent.scripts.OnSizeChanged() + local function edge(f,m) return f[m](f)*f:GetEffectiveScale()/UIParent.scale end + assert(edge(ContainerFrameCombinedBags,'GetBottom')>=edge(MultiBarLeft,'GetTop')+21.9,'bag covers click bar') + assert(edge(ContainerFrameCombinedBags,'GetBottom')>=edge(MultiBarBottomRight,'GetTop')+21.9,'bag covers combat rows') + assert(not intersects(ContainerFrameCombinedBags,ObjectiveTrackerFrame),'bag covers quest column') + assert(edge(ContainerFrameCombinedBags,'GetLeft')>=0 and edge(ContainerFrameCombinedBags,'GetTop')<=UIParent.h,'bag extends off screen') + assert(ContainerFrameCombinedBags.point[2]==UIParent,'bag must not anchor to protected bar') +end +local bagPoint=ContainerFrameCombinedBags.point +combat=true;UpdateContainerFrameAnchors();assert(ContainerFrameCombinedBags.point==bagPoint,'bag moved in combat');combat=false +-- Large inventory must still fit above controls. +ContainerFrameCombinedBags.h=900 +UpdateContainerFrameAnchors() +assert(ContainerFrameCombinedBags:GetTop()*ContainerFrameCombinedBags:GetEffectiveScale()/UIParent.scale<=UIParent.h, 'large bag top='..ContainerFrameCombinedBags:GetTop()..' scale='..ContainerFrameCombinedBags:GetScale()..' ui='..UIParent.h..' unplaced='..tostring(P.bagUnplaced)) +ContainerFrameCombinedBags.h=330;ContainerFrameCombinedBags.shown=false +-- A control-only migration leaves a user's combat keys/CVars/layout intact. +RuenUIDB.controlsVersion=nil +bindings.Q='PERSONAL_COMBAT';bindings.P='OLD_SPELL_KEY' +local oldGraphics=changes;local oldLayout=manager:GetActiveLayoutInfo() +eventFrame.scripts.OnEvent(eventFrame,'PLAYER_ENTERING_WORLD') +assert(bindings.Q=='PERSONAL_COMBAT' and changes==oldGraphics and manager:GetActiveLayoutInfo()==oldLayout) +assert(bindings.P=='TOGGLESPELLBOOK') +bindings.P='PERSONAL_MENU' +eventFrame.scripts.OnEvent(eventFrame,'PLAYER_ENTERING_WORLD') +assert(bindings.P=='PERSONAL_MENU','one-time migration overwritten personal menu key') +SlashCmdList.RUENUI('bindings');assert(bindings.P=='TOGGLESPELLBOOK') +-- Language changes use Spoken's live profile and native CVars, no API spoofing. +local voiceProfile={Language={Voice='enUS',Fallback='enUS'}} +SpokenEnv={Addon={db={profile=voiceProfile}}} +Spoken={GetLanguageChoice=function() return voiceProfile.Language.Voice,voiceProfile.Language.Fallback end,StopAll=function() end} +function GetLocale() return 'enUS' end +function GetAvailableLocales() return 'enUS','ruRU' end +cvars.textLocale,cvars.audioLocale='enUS','enUS' +SlashCmdList.RUENUI('voice ru') +assert(voiceProfile.Language.Voice=='ruRU' and cvars.textLocale=='enUS') +SlashCmdList.RUENUI('language ru') +assert(cvars.textLocale=='ruRU' and cvars.audioLocale=='ruRU') +SlashCmdList.RUENUI('language en') +assert(cvars.textLocale=='enUS' and cvars.audioLocale=='enUS' and voiceProfile.Language.Voice=='enUS') +function GetAvailableLocales() return 'enUS' end +SlashCmdList.RUENUI('language ru') +assert(cvars.textLocale=='enUS' and cvars.audioLocale=='enUS' and voiceProfile.Language.Voice=='ruRU','unsupported locale must not change game CVars') +local prior=changes;SlashCmdList.RUENUI('language nonsense');assert(changes==prior) +function GetAvailableLocales() return 'enUS','ruRU' end +combat=true;SlashCmdList.RUENUI('language ru');assert(cvars.textLocale=='enUS');combat=false +SlashCmdList.RUENUI('help');SlashCmdList.RUENUI('language') +local before=changes +eventFrame.scripts.OnEvent(eventFrame,'PLAYER_ENTERING_WORLD') +assert(changes==before,'subsequent login reapplied settings') +-- Existing installs must upgrade despite already having the 96-slot binding migration. +local savedBindings,savedCharacter,savedDB=CopyTable(bindings),CopyTable(RuenUICharacter),CopyTable(RuenUIDB) +local originalSet=GetCurrentBindingSet +local activeSet=1 +function GetCurrentBindingSet()return activeSet end +for _,bindingSet in ipairs({1,2}) do + activeSet=bindingSet + RuenUIDB=CopyTable(savedDB);RuenUICharacter=CopyTable(savedCharacter) + local scope=bindingSet==1 and RuenUIDB or RuenUICharacter + scope.petBindingsVersion=nil;scope.extraBindingsVersion=1 + for i,key in ipairs(numberKeys) do + bindings[key]='MULTIACTIONBAR4BUTTON'..i + bindings['CTRL-'..key]=i<=10 and 'BONUSACTIONBUTTON'..i or nil + end + bindings['ALT-Q']='MY_ALT_SPELL';bindings['SHIFT-1']='MY_SHIFT_SPELL' + bindings['-']='PERSONAL_MINUS' + local actionSnapshot=CopyTable(actions);local graphicsBefore=changes + combat=true;P.ApplyExtraBindings(false) + assert(not scope.petBindingsVersion and bindings['1']=='MULTIACTIONBAR4BUTTON1','combat migration was not deferred') + combat=false;P.ApplyExtraBindings(false) + for i,key in ipairs(numberKeys) do + assert(bindings['CTRL-'..key]=='MULTIACTIONBAR4BUTTON'..i,'missed utility migration') + if i<=10 then assert(bindings[key]=='BONUSACTIONBUTTON'..i,'missed pet migration') end + end + assert(bindings['-']=='CLICK RuenPetExtraButton11:LeftButton' and bindings['=']=='CLICK RuenPetExtraButton12:LeftButton','missing extra-pet keys') + assert(bindings['ALT-Q']=='MY_ALT_SPELL' and bindings['SHIFT-1']=='MY_SHIFT_SPELL','migration reset unrelated rows') + assert(changes==graphicsBefore,'binding migration changed graphics') + for slot,a in pairs(actionSnapshot) do assert(actions[slot][1]==a[1] and actions[slot][2]==a[2],'binding migration moved a slot')end + assert(scope.petBindingsVersion==2) + bindings['1']='PERSONAL_PET_KEY';bindings['CTRL-2']='PERSONAL_UTILITY_KEY' + for _,class in ipairs({'HUNTER','SHAMAN','WARLOCK','MAGE','DRUID','WARRIOR','PALADIN','PRIEST','ROGUE'}) do + currentClass=class;PetActionBar.shown=not PetActionBar.shown + P.ApplyExtraBindings(false) + assert(bindings['1']=='PERSONAL_PET_KEY' and bindings['CTRL-2']=='PERSONAL_UTILITY_KEY','reload/class/pet transition overwrote custom bindings') + end +end +for _,bindingSet in ipairs({1,2}) do + activeSet=bindingSet + local scope=bindingSet==1 and RuenUIDB or RuenUICharacter + scope.petBindingsVersion=1 + bindings['1']='PERSONAL_PET_KEY';bindings['CTRL-2']='PERSONAL_UTILITY_KEY' + bindings['-']='OLD_MINUS';bindings['=']='OLD_EQUALS' + P.ApplyPetBindings(false) + assert(bindings['1']=='PERSONAL_PET_KEY' and bindings['CTRL-2']=='PERSONAL_UTILITY_KEY','two-key upgrade reset existing controls') + assert(bindings['-']=='CLICK RuenPetExtraButton11:LeftButton' and bindings['=']=='CLICK RuenPetExtraButton12:LeftButton') + bindings['-']='CUSTOM_MINUS';P.ApplyPetBindings(false) + assert(bindings['-']=='CUSTOM_MINUS','reload reset customized extra-pet key') +end +GetCurrentBindingSet=originalSet;bindings=savedBindings;RuenUICharacter=savedCharacter;RuenUIDB=savedDB +print('PASS: one-time pet/utility swap on account and character bindings; combat deferral, personal keys, action slots, no-pet class consistency and later customizations') + +-- A graphics-only upgrade must not replace the existing UI layout or custom keys. +RuenUIDB.graphicsVersion=1 +bindings.Z='USER_PREFERENCE' +local layoutsBefore=#manager:GetLayouts() +eventFrame.scripts.OnEvent(eventFrame,'PLAYER_ENTERING_WORLD') +assert(RuenUIDB.graphicsVersion==P.graphicsVersion) +assert(cvars.graphicsComputeEffects=='2' and cvars.graphicsLightMode=='1') +assert(cvars.maxFPS=='60' and cvars.maxFPSBk=='15' and cvars.RenderScale=='1') +assert(cvars.MSAAQuality=='0,0' and cvars.groundEffectDensity=='24') +assert(bindings.Z=='USER_PREFERENCE' and #manager:GetLayouts()==layoutsBefore,'graphics upgrade reset user UI') +local afterGraphics=changes +eventFrame.scripts.OnEvent(eventFrame,'PLAYER_ENTERING_WORLD') +assert(changes==afterGraphics,'graphics upgrade reapplied every login') +SlashCmdList.RUENUI('apply'); assert(#manager:GetLayouts()==2) +combat=true;before=changes;SlashCmdList.RUENUI('apply');assert(changes==before) +combat=false +bindings.Z='USER_NEW_ACTION';actions[39]={'item',888} +SlashCmdList.RUENUI('restore') +for k,a in pairs(initialBindings) do if k~='ALT-F' then assert(bindings[k]==a,'undo mismatch '..k) end end +assert(bindings.Z=='USER_NEW_ACTION' and not bindings['ALT-F']) +assert(actions[39][2]==888 and not actions[38] and not actions[40],'seeded action undo changed user edits') +assert(actions[37][2]==999 and actions[3][2]==117) +assert(RuenUIDB.disabled and manager.layoutInfo.activeLayout==1) +assert(reloads==0,'never reload the game from a timer') +print('PASS: '..(bundled and 'portable' or 'live')..' ESDF, 96 bindings, action/pet lock, four combat rows and two utility groups, inventory-safe seeding, undo, geometry at 1080p/1440p/scaled desktop, tooltip clearance, graphics retention and combat guard') + +-- Exercise the native visibility methods, not a model of their conditions. +local meterSource=(assert(os.getenv('RUEN_NATIVE_UI'))..'/DamageMeter.lua') +CVarCallbackRegistry={SetCVarCachable=noop,GetCVarValueBool=function(_,k)return cvars[k]=='1'end} +assert(loadfile(meterSource))() +local inside,kind,available,inEdit=true,'party',true,false +function IsInInstance()return inside,kind end +C_DamageMeter={IsDamageMeterAvailable=function()return available,available and nil or 'restricted'end} +local meter=makePopup('DamageMeter',400,200) +meter.systemInfo={settings={}};meter.visibility=Enum.DamageMeterVisibility.InCombat +meter:SetPoint('TOPLEFT',UIParent,'TOPLEFT',50,-70) +local originalMeterPoint=meter.point +meter.ShouldBeShown=DamageMeterMixin.ShouldBeShown +meter.UpdateShownState=DamageMeterMixin.UpdateShownState +function meter:IsEditing()return inEdit end +function meter:IsPlayerInCombat()return combat end +function meter:IsPlayerInGroup()return true end +function meter:SetShown(v)self.shown=v end +function meter:UpdateSessionTimerState()end +function meter:RefreshLayout()end +local nativeMeterSelect=C_EditMode.SetActiveLayout +C_EditMode.SetActiveLayout=function(index) + nativeMeterSelect(index) + for _,s in ipairs(manager:GetActiveLayoutInfo().systems)do + if s.system==Enum.EditModeSystem.DamageMeter then + meter.systemInfo=s + meter.visibility=setting(s,Enum.EditModeDamageMeterSetting.Visibility) or Enum.DamageMeterVisibility.InCombat + meter:UpdateShownState() + end + end +end +function meter:UpdateSystemSettingVisibility() + self.visibility=setting(self.systemInfo,Enum.EditModeDamageMeterSetting.Visibility) or Enum.DamageMeterVisibility.InCombat + self:UpdateShownState() +end +function meter:OnUpdateSystem()end +function manager:IsShown()return inEdit end +-- Never leave unrelated popup stress fixtures enabled for these scenarios. +activeAlerts={} +for _,f in ipairs({roll,talking,loot1,loot2,achievement,breath,buffs,ContainerFrameCombinedBags,GameTooltip,unpack(rolls)})do f.shown=false end +SlashCmdList.RUENUI('apply') +assert(cvars.damageMeterEnabled=='1' and RuenUIDB.original.damageMeterEnabled=='0') +for _,case in ipairs({{false,'none',false},{true,'party',true},{true,'raid',true},{true,'pvp',false},{true,'arena',false},{true,'scenario',false},{false,'party',false}})do + inside,kind=case[1],case[2] + P.damageMeterListener.scripts.OnEvent(nil,'PLAYER_ENTERING_WORLD') + assert(meter:IsShown()==case[3],'instance gate '..kind) +end +inside,kind=true,'party';P.RefreshDamageMeters() +local p=meter.point;combat=true;inside=false;P.damageMeterListener.scripts.OnEvent(nil,'ZONE_CHANGED_NEW_AREA') +assert(meter:IsShown() and p==meter.point,'combat change was not deferred') +combat=false;P.damageMeterListener.scripts.OnEvent(nil,'PLAYER_REGEN_ENABLED');assert(not meter:IsShown()) +SlashCmdList.RUENUI('meters show');assert(meter:IsShown()) +SlashCmdList.RUENUI('meters off');assert(not meter:IsShown()) +SlashCmdList.RUENUI('meters auto');inside=true +available=false;P.RefreshDamageMeters();assert(not meter:IsShown(),'native availability bypassed') +available=true;P.RefreshDamageMeters();assert(meter:IsShown()) +inEdit=true;P.RefreshDamageMeters();assert(meter.w==400 and meter.h==200,'Edit Mode did not regain dimensions') +inEdit=false;P.RefreshDamageMeters();assert(meter.w<=260) +-- A native layout refresh must not overwrite its shared settings table. +local info=meter.systemInfo;local infoBefore=CopyTable(info) +meter:UpdateSystemSettingVisibility();hooks.UpdateSystemSettingVisibility() +assert(meter:IsShown() and meter.systemInfo==info and setting(info,Enum.EditModeDamageMeterSetting.Visibility)==setting(infoBefore,Enum.EditModeDamageMeterSetting.Visibility)) +local samples=0 +for _,display in ipairs({{1920,1080,1.40625},{2560,1440,1.875},{1920,1080,1},{2560,1440,1},{1366,768,1}})do + UIParent.scale=display[3];UIParent.w=display[1]/display[3];UIParent.h=display[2]/display[3] + for class,names in pairs(scenarios)do if class~='maximum' then + currentClass=class:upper() + for _,n in ipairs(controls)do _G[n].shown=false end + for _,n in ipairs(names)do _G[n].shown=true end + for _,n in ipairs({'PlayerCastingBarFrame','PlayerFrame','TargetFrame','TargetFrameToT','RuenTargetTargetTarget','FocusFrame'})do _G[n].shown=true end + ExtraAbilityContainer.shown=false;CompactRaidFrameContainer.shown=true + nativeSocial();UIParent.scripts.OnSizeChanged();P.RefreshDamageMeters() + assert(meter:IsShown(),display[1]..'/'..class..': '..tostring(RuenUICharacter.damageMeterStatus.reason)) + local l,b,w,h=meter:rect() + assert(l>=0 and b>=0 and l+w<=UIParent.w and b+h<=UIParent.h) + for _,o in ipairs(P.OverlayObstacles(false))do if o.name~='DamageMeter' then + assert(not(lo.left and bo.bottom),'meter blocks '..(o.name or '?')..' '..class) + end end + GameTooltip.owner=MainActionBar;GameTooltip.shown=true;GameTooltip.w,GameTooltip.h=240,150 + P.ResetTooltipPosition(GameTooltip);P.PositionTooltip(GameTooltip,true) + assert(not intersects(meter,GameTooltip),'tooltip overlaps meter') + GameTooltip.shown=false + ContainerFrameCombinedBags.shown=true;ContainerFrameCombinedBags.w,ContainerFrameCombinedBags.h=400,200 + SlashCmdList.RUENUI('bags');assert(P.bagOverHUD or not intersects(meter,ContainerFrameCombinedBags),'bag overlaps meter') + ContainerFrameCombinedBags.shown=false + for _,f in ipairs(rolls)do f.shown=true end + P.PositionOverlayFrames() + assert(#P.overlayUnplaced==0,'no room for rolls with meter '..class) + for _,f in ipairs(rolls)do assert((P.overlayOverOptional and P.overlayOverOptional[f]) or not intersects(meter,f),'loot roll overlaps meter');f.shown=false end + samples=samples+1 + end end +end +-- Restore returns native geometry/visibility and the original collection CVar. +SlashCmdList.RUENUI('restore') +assert(cvars.damageMeterEnabled=='0' and meter.w==400 and meter.h==200) +assert(meter.visibility==Enum.DamageMeterVisibility.InCombat) +print('PASS: native damage meter instance gate, PvP exclusion, manual modes, native availability, combat deferral, Edit Mode handoff, restore; '..samples..' all-class/resolution meter/bag/tooltip/loot clearance scenarios') + +-- Native cooldown selection and visibility, including unknown spell filtering. +local cdSource=(assert(os.getenv('RUEN_NATIVE_UI'))..'/') +local function nativeMethods(file,receiver,methods,prefix) + local f=assert(io.open(cdSource..file));local text=f:read('*a');f:close() + for _,method in ipairs(methods)do + local body=assert(text:match('(function '..receiver..':'..method..'%b().-\nend)'),method) + assert(loadstring((prefix or '')..'\n'..body))() + end +end +CooldownViewerMixin={};CooldownViewerSettingsDataProviderMixin={} +nativeMethods('CooldownViewer.lua','CooldownViewerMixin',{'ShouldBeShown','UpdateShownState','GetCooldownIDs','GetItemCount','GetStride'},'local cooldownViewerEnabledCVar="cooldownViewerEnabled"') +nativeMethods('CooldownViewerSettingsDataProvider.lua','CooldownViewerSettingsDataProviderMixin',{'GetOrderedCooldownIDsForCategory'}) +local provider={order={},spells={}} +provider.GetOrderedCooldownIDsForCategory=CooldownViewerSettingsDataProviderMixin.GetOrderedCooldownIDsForCategory +function provider:GetOrderedCooldownIDs()return self.order end +function provider:GetCooldownInfoForID(id)return self.spells[id]end +local cdSettingsOpen,cdAvailable=false,true +CooldownViewerSettings={GetDataProvider=function()return provider end,IsVisible=function()return cdSettingsOpen end,IsShown=function()return cdSettingsOpen end,ShowUIPanel=function()cdSettingsOpen=true end} +function UnitAffectingCombat()return combat end +function assertsafe(v,msg)assert(v,msg)end +C_CooldownViewer={IsCooldownViewerAvailable=function()return cdAvailable end,SetLayoutData=function()error('must not overwrite custom cooldown spells/layouts')end} +local cdNames={'EssentialCooldownViewer','UtilityCooldownViewer','BuffIconCooldownViewer','BuffBarCooldownViewer'} +for i,name in ipairs(cdNames)do + local f=CreateFrame('Frame',name);f.cooldownViewerCategory=i-1 + f.GetCooldownIDs=CooldownViewerMixin.GetCooldownIDs + f.ShouldBeShown=CooldownViewerMixin.ShouldBeShown + f.UpdateShownState=CooldownViewerMixin.UpdateShownState + f.GetItemCount=CooldownViewerMixin.GetItemCount + function f:GetCategory()return self.cooldownViewerCategory end + function f:IsEditing()return inEdit end + function f:SetShown(v)self.shown=v end + function f:RefreshData()end + function f:OnUpdateSystem()end +end +-- Decode the actual native slider encoding and sizes, not saved table guesses. +local nativeSetActive=C_EditMode.SetActiveLayout +C_EditMode.SetActiveLayout=function(index) + nativeSetActive(index) + local S=Enum.EditModeCooldownViewerSetting + for _,s in ipairs(manager:GetActiveLayoutInfo().systems)do if s.system==Enum.EditModeSystem.CooldownViewer then + local i=s.systemIndex;local f=_G[cdNames[i]] + if s.settings[1] then assert(s.isInDefaultPosition==false and s.anchorInfo.relativeTo=='UIParent','viewer still owned by bottom stacking manager')end + local n=f:GetItemCount();local scale=(50+10*(setting(s,S.IconSize) or 0))/100 + local stride=(i==3 or i==4) and n or (setting(s,S.IconLimit) or 6) + local gap=(setting(s,S.IconPadding) or 8)-(i==4 and 2 or 4) + local size=({50,30,40,30})[i]*scale + if i==4 then f.w=220*((setting(s,S.BarWidthScale) or 50)+50)/100*scale;f.h=n*size+(n-1)*gap + else f.w=math.min(n,stride)*size+(math.min(n,stride)-1)*gap;f.h=math.ceil(n/stride)*size+(math.ceil(n/stride)-1)*gap end + f.visibleSetting=setting(s,S.VisibleSetting);f:UpdateShownState() + end end +end +local function spellSet(counts) + provider.order={};provider.spells={} + for i,count in ipairs(counts)do for j=1,count do + local id=i*100+j;provider.order[#provider.order+1]=id;provider.spells[id]={category=i-1,isKnown=true} + end end + provider.order[#provider.order+1]=9999;provider.spells[9999]={category=0,isKnown=false} +end +for _,l in ipairs(manager.layoutInfo.layouts)do + for i=1,4 do l.systems[#l.systems+1]={system=Enum.EditModeSystem.CooldownViewer,systemIndex=i,settings={}}end +end +spellSet({6,5,3,2}) +SlashCmdList.RUENUI('apply');C_EditMode.SetActiveLayout(2) +P.RefreshClassAssist();assert(not RuenUICharacter.classAssistError,RuenUICharacter.classAssistError) +assert(cvars.cooldownViewerEnabled=='1') +for _,name in ipairs(cdNames)do assert(not _G[name]:IsShown(),'auto viewer visible out of combat')end +combat=true +for _,name in ipairs(cdNames)do _G[name]:UpdateShownState();assert(_G[name]:IsShown(),'native combat visibility')end +local saveCount=classSaves;local beforePoint=EssentialCooldownViewer.point +P.ClassAssistCommand('cooldowns','off');assert(classSaves==saveCount and EssentialCooldownViewer.point==beforePoint,'cooldowns mutated during combat') +combat=false;P.classAssistListener.scripts.OnEvent(nil,'PLAYER_REGEN_ENABLED') +for _,name in ipairs(cdNames)do assert(not _G[name]:IsShown(),'off visibility')end +P.ClassAssistCommand('cooldowns','show');assert(EssentialCooldownViewer:IsShown()) +assert(#EssentialCooldownViewer:GetCooldownIDs()==6,'unknown spells leaked into native category') +assert(#P.classAssistReserved==4 and #RuenUICharacter.classAssistUnplaced==0) +-- Geometry stress is deliberately synthetic; lists remain native, not Ruen spell lists. +local cdSamples=0 +for _,display in ipairs({{1920,1080,1.40625},{2560,1440,1.875},{1920,1080,1},{2560,1440,1},{1366,768,1}})do + UIParent.scale=display[3];UIParent.w=display[1]/display[3];UIParent.h=display[2]/display[3] + for class,controlNames in pairs(scenarios)do if class~='maximum' then + currentClass=class:upper() + for _,n in ipairs(controls)do _G[n].shown=false end + for _,n in ipairs(controlNames)do _G[n].shown=true end + for _,n in ipairs({'PlayerCastingBarFrame','PlayerFrame','TargetFrame','TargetFrameToT','RuenTargetTargetTarget','FocusFrame'})do _G[n].shown=true end + ExtraAbilityContainer.shown=false;CompactRaidFrameContainer.shown=true;inside=true;kind='raid' + for _,count in ipairs({{1,1,0,0},{6,5,3,2},{12,12,8,6},{16,16,16,10}})do + spellSet(count);nativeSocial();UIParent.scripts.OnSizeChanged();P.RefreshClassAssist();hooks.UpdateSystems();P.RefreshDamageMeters() + assert(not RuenUICharacter.classAssistError,RuenUICharacter.classAssistError) + assert(count[1]>6 or #RuenUICharacter.classAssistUnplaced==0,'unplaced viewer '..class..' '..display[1]..' '..table.concat(count,',')) + for _,r in ipairs(P.classAssistReserved)do + assert(r.left>=0 and r.bottom>=0 and r.right<=UIParent.w and r.top<=UIParent.h,'offscreen '..r.name) + for _,o in ipairs(P.OverlayObstacles(false))do if o.name~=r.name then + assert(not(r.lefto.left and r.bottomo.bottom),'viewer '..r.name..' blocks '..(o.name or '?')..' '..class) + end end + end + assert(meter:IsShown() or (count[1]>6 and RuenUICharacter.damageMeterStatus.reason=='no free space'),'meter cannot fit with cooldowns '..class..' '..table.concat(count,',')..' '..display[1]) + GameTooltip.owner=MainActionBar;GameTooltip.shown=true;GameTooltip.w,GameTooltip.h=220,130 + P.ResetTooltipPosition(GameTooltip);P.PositionTooltip(GameTooltip,true) + for _,r in ipairs(P.classAssistReserved)do assert(not intersects(GameTooltip,_G[r.name]),'tooltip overlaps cooldowns')end + GameTooltip.shown=false + if count[1]<=6 then + ContainerFrameCombinedBags.shown=true;ContainerFrameCombinedBags.w,ContainerFrameCombinedBags.h=400,200 + SlashCmdList.RUENUI('bags') + for _,r in ipairs(P.classAssistReserved)do assert(P.bagOverHUD or not intersects(ContainerFrameCombinedBags,_G[r.name]),'bags overlap cooldowns '..class..' '..display[1]..' '..table.concat(count,','))end + ContainerFrameCombinedBags.shown=false + for _,f in ipairs(rolls)do f.shown=true end + P.PositionOverlayFrames() + if #P.overlayUnplaced>0 then + print('FAILED DISPLAY',unpack(display));print('SPELL COUNTS',unpack(count)) + for _,o in ipairs(P.OverlayObstacles(false))do print('RECT',o.name,o.left,o.bottom,o.right-o.left,o.top-o.bottom)end + for _,f in ipairs(rolls)do print('ROLL',f.name,f:rect())end + end + assert(#P.overlayUnplaced==0,'loot rolls cannot fit with normal cooldown groups '..class) + for _,f in ipairs(rolls)do + for _,r in ipairs(P.classAssistReserved)do assert((P.overlayOverOptional and P.overlayOverOptional[f]) or not intersects(f,_G[r.name]),'loot overlaps cooldowns')end + f.shown=false + end + end + cdSamples=cdSamples+1 + end + end end +end +-- Known spell/talent changes are reflected and custom category ordering is retained. +spellSet({2,0,0,0});P.classAssistListener.scripts.OnEvent(nil,'SPELLS_CHANGED') +assert(#P.classAssistReserved==1 and not UtilityCooldownViewer:IsShown(),'empty categories left placeholders') +provider.spells[9999].isKnown=true;provider.spells[9999].category=1 +P.classAssistListener.scripts.OnEvent(nil,'PLAYER_TALENT_UPDATE') +assert(UtilityCooldownViewer:GetCooldownIDs()[1]==9999 and #P.classAssistReserved==2) +P.ClassAssistCommand('cooldowns','settings');assert(cdSettingsOpen) +saveCount=classSaves;P.RefreshClassAssist();assert(saveCount==classSaves and #P.classAssistReserved==0,'settings editor not respected') +cdSettingsOpen=false;P.RefreshClassAssist();assert(#P.classAssistReserved==2) +-- Failed optional subsystem recovers without disabling later refreshes. +local getAvail=C_CooldownViewer.IsCooldownViewerAvailable +C_CooldownViewer.IsCooldownViewerAvailable=function()error('fixture unavailable')end +P.RefreshClassAssist();assert(RuenUICharacter.classAssistError) +C_CooldownViewer.IsCooldownViewerAvailable=getAvail;P.RefreshClassAssist();assert(not RuenUICharacter.classAssistError) +print('PASS: native cooldown selection/unknown filtering, combat visibility, empty categories, talent/learned changes, settings handoff, error recovery; '..cdSamples..' class/resolution/full-HUD cooldown+meter+tooltip clearance cases') + +-- Class defaults, native modifiers, account/character transitions and overrides. +function IsMouseoverCastSupported()return true end +local nativeSetting=Settings.SetValue +settings.MOUSEOVERCAST='SHIFT' +Settings.SetValue=function(k,v)if k=='MOUSEOVERCAST' then settings[k]=v;mouseModifier=v else nativeSetting(k,v)end end +local guid='player-1';function UnitGUID()return guid end +local chars={};local keysBefore=CopyTable(bindings);local selfBefore=modified +for _,class in ipairs({'PRIEST','DRUID','PALADIN','SHAMAN','HUNTER','WARLOCK','MAGE','ROGUE','WARRIOR'})do + currentClass=class;guid='player-'..class + RuenUICharacter={original={}};chars[class]=RuenUICharacter + cvars.enableMouseoverCast='0';mouseModifier='SHIFT' + P.ApplyMouseover(false) + local expected=({PRIEST=true,DRUID=true,PALADIN=true,SHAMAN=true})[class] and '1' or '0' + assert(cvars.enableMouseoverCast==expected,'class mouseover '..class) + assert(mouseModifier==(expected=='1' and 'NONE' or 'SHIFT')) + local changesBefore=changes;P.ApplyMouseover(false);assert(changes==changesBefore,'mouseover reapplied repeatedly') + cvars.enableMouseoverCast=expected=='1' and '0' or '1';P.ApplyMouseover(false) + assert(cvars.enableMouseoverCast~=expected,'manual Options preference overwritten') +end +currentClass='SHAMAN';guid='player-SHAMAN';RuenUICharacter=chars.SHAMAN;P.ApplyMouseover(false) +assert(cvars.enableMouseoverCast=='1' and mouseModifier=='NONE','returning to hybrid did not restore class default') +local oldChar=RuenUICharacter;guid='player-SHAMAN-2';RuenUICharacter={original={}};P.ApplyMouseover(false) +P.ClassAssistCommand('mouseover','off');assert(cvars.enableMouseoverCast=='0') +guid='player-SHAMAN';RuenUICharacter=oldChar;P.ApplyMouseover(false);assert(cvars.enableMouseoverCast=='1','same-class characters interfered') +combat=true;P.ClassAssistCommand('mouseover','off');assert(cvars.enableMouseoverCast=='1') +combat=false;P.classAssistListener.scripts.OnEvent(nil,'PLAYER_REGEN_ENABLED');assert(cvars.enableMouseoverCast=='0' and mouseModifier=='SHIFT','deferred disable lost original modifier') +P.ClassAssistCommand('mouseover','on');assert(cvars.enableMouseoverCast=='1' and mouseModifier=='NONE') +P.ClassAssistCommand('mouseover','auto');assert(RuenUICharacter.mouseoverMode=='auto') +P.RestoreClassAssist();assert(mouseModifier=='SHIFT' and not RuenUICharacter.mouseoverApplied and not P.mouseoverPending) +for k,v in pairs(keysBefore)do assert(bindings[k]==v,'mouseover altered binding '..k)end +for k,v in pairs(bindings)do assert(keysBefore[k]==v,'mouseover introduced binding '..k)end +assert(modified==selfBefore,'mouseover replaced self-cast controls') +print('PASS: mouseover defaults for all nine classes, no extra modifier, independent character preferences, manual Options edits, combat deferral, recovery/undo; all action/movement/mouse/self-cast bindings unchanged') + +-- Left shelf migration and resize: no shortcut or action slot changes. +RuenUICharacter.original=RuenUICharacter.original or {} +RuenUIDB.disabled=false +local keysSnapshot=CopyTable(bindings);local actionSnapshot=CopyTable(actions) +local nativeSnapshot=CopyTable(manager:GetActiveLayoutInfo()) +local tracked={} +for _,s in ipairs(nativeSnapshot.systems)do if s.system==Enum.EditModeSystem.ActionBar and s.systemIndex<=6 then + tracked[s.systemIndex]=CopyTable(s) +end end +local function eq(a,b) + if type(a)~=type(b)then return false end + if type(a)~='table'then return a==b end + for k,v in pairs(a)do if not eq(v,b[k])then return false end end + for k in pairs(b)do if a[k]==nil then return false end end + return true +end +RuenUIDB.leftBarsVersion=nil;RuenUIDB.leftBarRows=nil +combat=true;local saves=classSaves;P.MigrateLeftBars();assert(classSaves==saves,'left migration ran in combat') +combat=false;inEdit=true;P.MigrateLeftBars();assert(classSaves==saves,'left migration ran in edit mode');inEdit=false +for _,case in ipairs({{2133,1200,1,2},{1920,1080,1,2},{1920,1080,1.40625,2},{1366,768,1,2},{2560,1440,1.875,2},{2560,1440,1,2}})do + UIParent.scale=case[3];UIParent.w=case[1]/case[3];UIParent.h=case[2]/case[3] + currentClass='HUNTER';for _,n in ipairs(controls)do _G[n].shown=false end + PlayerFrame.shown=true;TargetFrame.shown=true;PetFrame.shown=true;PetActionBar.shown=true + P.MigrateLeftBars();hooks.UpdateSystems();UIParent.scripts.OnSizeChanged() + assert(RuenUIDB.leftBarRows==case[4],'wrong responsive row count') + assert(MultiBar6.h==(case[4]==1 and 36 or 74) and MultiBar7.h==MultiBar6.h,'wrong native shape') + assert(math.abs(MultiBar6:GetLeft()-ChatFrame1:GetLeft())<.01,'left shelf not aligned with chat') + assert(math.abs(MultiBar6:GetLeft()-MultiBar7:GetLeft())<.01 and math.abs(MultiBar6:GetRight()-MultiBar7:GetRight())<.01) + assert(gap(MultiBar7,MultiBar6)>=5.9,'left row gap') + local dockPoint=CopyTable(MultiBar6.point);MultiBar6:SetPoint('BOTTOMLEFT',UIParent,'BOTTOMLEFT',20,215) + MultiBar6.scripts.OnShow();assert(MultiBar6:GetBottom()>215,'late native show not repaired') + local beforeCombat=MultiBar6.point;combat=true;MultiBar6.scripts.OnShow();assert(MultiBar6.point==beforeCombat,'shelf moved in combat');combat=false + hooks.UpdateSystems() + local socialSpace=P.SocialNotificationSpace(function(f,m)return f[m](f)*f:GetEffectiveScale()/UIParent.scale end) + assert(MultiBar6:GetBottom()>=socialSpace.top+11.9,'social area not clear') + for _,n in ipairs({'PlayerFrame','PetFrame','PetActionBar','MainActionBar','MultiBar5'})do assert(not intersects(MultiBar6,_G[n]) and not intersects(MultiBar7,_G[n]),'left shelf overlaps '..n)end + for _,s in ipairs(manager:GetActiveLayoutInfo().systems)do + if s.system==Enum.EditModeSystem.ActionBar and (s.systemIndex==7 or s.systemIndex==8)then + assert(setting(s,Enum.EditModeActionBarSetting.NumRows)==case[4]) + assert(s.anchorInfo.relativeTo=='UIParent' and not s.isInDefaultPosition) + assert(s.anchorInfo.offsetY>=socialSpace.top+11.9,'saved native anchor fell into notification space') + end + end + saves=classSaves;P.MigrateLeftBars();assert(saves==classSaves,'left migration repeated without width change') +end +assert(eq(bindings,keysSnapshot) and eq(actions,actionSnapshot),'shelf migration changed keybindings or actions') +for _,s in ipairs(manager:GetActiveLayoutInfo().systems)do if s.system==Enum.EditModeSystem.ActionBar and s.systemIndex<=6 then + assert(eq(s,tracked[s.systemIndex]),'left migration changed unrelated action bar settings') +end end +-- A fresh preset's native player frame starts top-left, before Ruen activates. +local oldIndex=manager.layoutInfo.activeLayout;manager.layoutInfo.activeLayout=1 +PlayerFrame:SetPoint('TOPLEFT',UIParent,'TOPLEFT',20,-20) +local preset=CopyTable(manager.layoutInfo.layouts[1]);P.ConfigureLeftBarSystems(preset) +for _,s in ipairs(preset.systems)do if s.system==Enum.EditModeSystem.ActionBar and s.systemIndex>=7 and s.systemIndex<=8 then + assert(s.anchorInfo.offsetY