Prepare first public Ruen UI beta with verified upstream downloads and reversible installers

This commit is contained in:
Ruen UI contributors 2026-11-21 12:10:42 -06:00
commit 7fa88a2ecf
54 changed files with 9028 additions and 0 deletions

7
.gitattributes vendored Normal file
View File

@ -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

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
__pycache__/
*.pyc
/dist/
/manifest.json
*.part

View File

@ -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%

9
Install-Ruen-UI.cmd Normal file
View File

@ -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%

469
Install-Ruen-UI.ps1 Normal file
View File

@ -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() }
}

3
Install-Russian.cmd Normal file
View File

@ -0,0 +1,3 @@
@echo off
call "%~dp0Install-Ruen-UI-Russian.cmd" %*
exit /b %errorlevel%

3
Install-Windows.cmd Normal file
View File

@ -0,0 +1,3 @@
@echo off
call "%~dp0Install-Ruen-UI.cmd" %*
exit /b %errorlevel%

176
KEYBINDINGS.txt Normal file
View File

@ -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.

222
LAYOUT-AUDIT.txt Normal file
View File

@ -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.

25
LICENSE Normal file
View File

@ -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.

10
Optimize-Ruen-UI.ps1 Normal file
View File

@ -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

45
README.md Normal file
View File

@ -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.

250
Ruen-Setup Executable file
View File

@ -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)

BIN
Ruen-Setup.exe Executable file

Binary file not shown.

292
RuenUI/AddonPresets.lua Normal file
View File

@ -0,0 +1,292 @@
local _, P = ...
P.addonPresetVersion = 1
P.addonPresets = {
["Leatrix_Plus"] = { variable = "LeaPlusDB", values = {
["AcceptPartyFriends"] = "Off",
["AddonLanguage"] = 1,
["AutoAcceptRes"] = "Off",
["AutoAcceptSummon"] = "Off",
["AutoQuestCompleted"] = "On",
["AutoQuestDaily"] = "On",
["AutoQuestKeyMenu"] = 1,
["AutoQuestRegular"] = "On",
["AutoQuestShift"] = "Off",
["AutoQuestWeekly"] = "On",
["AutoReleaseDelay"] = 0,
["AutoReleaseNoAlterac"] = "Off",
["AutoReleasePvP"] = "Off",
["AutoRepairGear"] = "On",
["AutoRepairGuildFunds"] = "Off",
["AutoRepairShowSummary"] = "On",
["AutoResNoAfterlife"] = "Off",
["AutoResNoCombat"] = "On",
["AutoSellExcludeList"] = "",
["AutoSellJunk"] = "On",
["AutoSellNoGreyGear"] = "Off",
["AutoSellShowSummary"] = "On",
["AutomateGossip"] = "Off",
["AutomateQuests"] = "Off",
["BlockDrunkenSpam"] = "Off",
["BlockDuelSpam"] = "Off",
["BlockSpellLinks"] = "Off",
["BordersAlpha"] = 0,
["BordersBottom"] = 0,
["BordersLeft"] = 0,
["BordersRight"] = 0,
["BordersTop"] = 0,
["ClassColChain"] = "On",
["ClassColFrames"] = "Off",
["ClassColPlayer"] = "On",
["ClassColPlayerBorder"] = "On",
["ClassColTarget"] = "On",
["ClassColTargetBorder"] = "On",
["CombatPlates"] = "Off",
["DressupAnimControl"] = "On",
["DressupFasterZoom"] = 3,
["DressupItemButtons"] = "On",
["DressupMoreZoomOut"] = "Off",
["DressupTransmogAnim"] = "Off",
["DurabilityStatus"] = "Off",
["EasyItemDestroy"] = "Off",
["EditModeLayoutName"] = "",
["EnhanceDressup"] = "Off",
["EnhanceFlightMap"] = "Off",
["FasterLooting"] = "On",
["FasterMovieSkip"] = "Off",
["FilterChatMessages"] = "Off",
["FirstRunMessageSeen"] = true,
["FlightBarA"] = "TOP",
["FlightBarBackground"] = "On",
["FlightBarContribute"] = "On",
["FlightBarDestination"] = "On",
["FlightBarFillBar"] = "Off",
["FlightBarFontSize"] = 10,
["FlightBarNextHop"] = "On",
["FlightBarR"] = "TOP",
["FlightBarScale"] = 2,
["FlightBarSpeech"] = "Off",
["FlightBarWidth"] = 230,
["FlightBarX"] = 0,
["FlightBarY"] = -66,
["FlightMapA"] = "TOPLEFT",
["FlightMapR"] = "TOPLEFT",
["FlightMapX"] = 16,
["FlightMapY"] = -48,
["FriendlyCommunities"] = "Off",
["FriendlyGuild"] = "On",
["HideBossBanner"] = "Off",
["HideCleanupBtns"] = "Off",
["HideErrorMessages"] = "Off",
["HideEventToasts"] = "Off",
["HideKeybindText"] = "Off",
["HideMacroText"] = "Off",
["HideMiniAddonButtons"] = "On",
["HideMiniAddonMenu"] = "On",
["HideZoneText"] = "Off",
["InfoCardKey"] = "",
["InvKey"] = "inv",
["InviteFriendsOnly"] = "Off",
["InviteFromWhisper"] = "Off",
["KeepAudioSynced"] = "Off",
["KeyBindFlare1"] = "",
["KeyBindFlare2"] = "",
["KeyBindFlare3"] = "",
["KeyBindFlare4"] = "",
["KeyBindFlare5"] = "",
["KeyBindFlare6"] = "",
["KeyBindFlare7"] = "",
["KeyBindFlare8"] = "",
["KeyBindFlare9"] = "",
["KeyBindMountSpecial"] = "",
["KeyBindRare"] = "",
["KeyBindRecentChat"] = "",
["KeyBindToggle"] = "",
["LeaPlusFasterLootDelay"] = 0.3,
["LeaPlusQuestFontSize"] = 12,
["LeaPlusTaxiIconSize"] = 16,
["LeaPlusTaxiMapScale"] = 1,
["LeaPlusTipSize"] = 1,
["LeaStartPage"] = 7,
["MainPanelA"] = "CENTER",
["MainPanelR"] = "CENTER",
["MainPanelX"] = 0,
["MainPanelY"] = 0,
["ManageWidgetTop"] = "Off",
["MaxCameraZoom"] = "Off",
["MiniClusterScale"] = 1,
["MiniExcludeList"] = "",
["MiniHeaderAlpha"] = 0.5,
["MiniHeaderOnHover"] = "Off",
["MinimapBorderWidth"] = 3,
["MinimapButtonBag"] = "Off",
["MinimapEffect"] = 1,
["MinimapModder"] = "Off",
["MoreChatFontSizes"] = "Off",
["MoveChatEditBoxToTop"] = "Off",
["MusicContinent"] = "Zones",
["MuteAirships"] = "Off",
["MuteChimes"] = "Off",
["MuteCustomList"] = "",
["MuteCustomSounds"] = "Off",
["MuteFizzle"] = "Off",
["MuteGameSounds"] = "Off",
["MuteHorsesteps"] = "Off",
["MuteInterface"] = "Off",
["MuteLogin"] = "Off",
["MuteMechSteps"] = "Off",
["MuteMountSounds"] = "Off",
["MutePiccolo"] = "Off",
["MuteReady"] = "Off",
["MuteStriders"] = "Off",
["MuteTrains"] = "Off",
["MuteVaults"] = "Off",
["MuteYawns"] = "Off",
["MuteZeppelins"] = "Off",
["NoAlerts"] = "Off",
["NoChatButtons"] = "Off",
["NoChatFade"] = "On",
["NoClassBar"] = "Off",
["NoCombatLogTab"] = "Off",
["NoConfirmLoot"] = "Off",
["NoDrunkenHaze"] = "Off",
["NoDuelRequests"] = "Off",
["NoFriendRequests"] = "Off",
["NoHitIndicators"] = "Off",
["NoPartyInvites"] = "Off",
["NoRaidRestrictions"] = "Off",
["NoRequestedInvites"] = "Off",
["NoRestedEmotes"] = "Off",
["NoRestedSleep"] = "Off",
["NoScreenEffects"] = "Off",
["NoSharedQuests"] = "Off",
["NoSocialButton"] = "Off",
["NoStickyChat"] = "Off",
["NoTransforms"] = "Off",
["PlayerChainMenu"] = 1,
["PlusPanelAlpha"] = 0,
["PlusPanelScale"] = 1,
["QuestFontChange"] = "Off",
["RecentChatA"] = "BOTTOM",
["RecentChatFontSize"] = 0,
["RecentChatR"] = "BOTTOM",
["RecentChatSize"] = 192,
["RecentChatWindow"] = "Off",
["RecentChatX"] = 0,
["RecentChatY"] = 130,
["RestoreChatMessages"] = "Off",
["SetEditModeLayout"] = "Off",
["SetKeybindings"] = "Off",
["SetWeatherDensity"] = "Off",
["ShowBorders"] = "Off",
["ShowChatMenuButton"] = "Off",
["ShowDruidPowerBar"] = "Off",
["ShowFlightTimes"] = "Off",
["ShowInfoCards"] = "Off",
["ShowMinimapIcon"] = "On",
["ShowPlayerChain"] = "Off",
["ShowRaidToggle"] = "Off",
["ShowRangeColoring"] = "Off",
["ShowReadyTimer"] = "Off",
["ShowTrainAllButton"] = "Off",
["ShowVoiceButtons"] = "Off",
["ShowVolume"] = "Off",
["ShowVolumeInFrame"] = "Off",
["ShowWowheadLinks"] = "Off",
["SimpleAddonListing"] = "Off",
["SquareMinimap"] = "On",
["TipBackSimple"] = "Off",
["TipCursorX"] = 0,
["TipCursorY"] = 0,
["TipHideInCombat"] = "Off",
["TipHideShiftOverride"] = "On",
["TipModEnable"] = "Off",
["TipNoHealthBar"] = "Off",
["TipShowOtherRank"] = "Off",
["TipShowRank"] = "On",
["TipShowTarget"] = "On",
["TooltipAnchorMenu"] = 1,
["TransHallowed"] = "Off",
["TransLantern"] = "Off",
["TransNobleBunny"] = "Off",
["TransNoggenfogger"] = "Off",
["TransTurkey"] = "Off",
["UnclampChat"] = "Off",
["UnclampMinimap"] = "Off",
["UnivGroupColor"] = "Off",
["UseArrowKeysInChat"] = "On",
["UseEasyChatResizing"] = "Off",
["WeatherLevel"] = 3,
["WidgetTopA"] = "TOP",
["WidgetTopR"] = "TOP",
["WidgetTopScale"] = 1,
["WidgetTopX"] = 0,
["WidgetTopY"] = -15,
["WowheadLinkComments"] = "Off",
["hide"] = false,
} },
["Leatrix_Maps"] = { variable = "LeaMapsDB", values = {
["AddonLanguage"] = 1,
["BattleGroupIconSize"] = 8,
["BattleMapA"] = "BOTTOMRIGHT",
["BattleMapOpacity"] = 1,
["BattleMapR"] = "BOTTOMRIGHT",
["BattleMapX"] = -47,
["BattleMapY"] = 83,
["BattlePlayerArrowSize"] = 12,
["CoordsBackground"] = "On",
["EnableMovement"] = "On",
["EnhanceBattleMap"] = "Off",
["FirstRunMessageSeen"] = true,
["GemBest"] = 0,
["GemGame"] = "",
["HideBlackoutFrame"] = "On",
["HideTownCity"] = "Off",
["KeyBindToggle"] = "",
["MainPanelA"] = "CENTER",
["MainPanelR"] = "CENTER",
["MainPanelX"] = 0,
["MainPanelY"] = 0,
["MapPosA"] = "TOPLEFT",
["MapPosR"] = "TOPLEFT",
["MapPosX"] = 188.9998168945313,
["MapPosY"] = -88.99999237060547,
["MapScale"] = 1,
["MapTheme"] = 12,
["MaxMapPosA"] = "CENTER",
["MaxMapPosR"] = "CENTER",
["MaxMapPosX"] = 0,
["MaxMapPosY"] = 0,
["MaxMapScale"] = 1,
["NoFilterResetBtn"] = "On",
["NoMapFade"] = "On",
["RevTint"] = "On",
["RevealMap"] = "Off",
["ScaleWorldMap"] = "Off",
["SetKeybindings"] = "Off",
["ShowBoatZeppTram"] = "On",
["ShowCoords"] = "On",
["ShowDungeonIcons"] = "On",
["ShowDungeonMaps"] = "On",
["ShowFishingLevels"] = "Off",
["ShowFlightPoints"] = "On",
["ShowMinimapIcon"] = "On",
["ShowOpposingPoi"] = "Off",
["ShowPointsOfInterest"] = "On",
["ShowPortals"] = "On",
["ShowSpiritHealers"] = "Off",
["ShowZoneCrossings"] = "On",
["ShowZoneLevels"] = "On",
["ShowZoneMenu"] = "On",
["SimpleMapFrame"] = "On",
["UnlockBattlefield"] = "On",
["UnlockMap"] = "On",
["hide"] = false,
["minimapPos"] = 204,
["tintAlpha"] = 1,
["tintBlue"] = 1,
["tintGreen"] = 0.6,
["tintRed"] = 0.6,
} },
["Spoken"] = {["variable"] = "SpokenSettings", ["values"] = {}, ["profile"] = {["Frame"] = {["Style"] = "none"}, ["Language"] = {["Voice"] = "enUS", ["Fallback"] = "enUS"}, ["Audio"] = {["SoundChannel"] = "Master", ["ReadInBattlegrounds"] = false, ["LowerOthers"] = {["Enabled"] = true, ["Music"] = 0.3, ["Ambience"] = 0.4, ["SFX"] = 0.6, ["Dialog"] = 1}}, ["Parts"] = {["places"] = false, ["readables"] = false, ["bosses"] = false}, ["Transcript"] = {["Enabled"] = false}, ["Contribute"] = {["HideButtons"] = true}}, ["global"] = {["NewCharacterProfile"] = "Ruen Narration", ["Welcomed"] = true}},
["Spoken_Quests"] = {["variable"] = "SpokenQuestsSettings", ["values"] = {}, ["profile"] = {["Audio"] = {["Autoplay"] = true, ["GossipFrequency"] = 4, ["FollowupLines"] = false, ["ProgressText"] = true, ["StopAudioOnDisengage"] = false, ["VoiceLanguage"] = "enUS", ["FallbackLanguage"] = "enUS"}, ["QuestLogPlayButton"] = true, ["TrackerPlayButton"] = false, ["DebugEnabled"] = false}, ["global"] = {}},
}

7
RuenUI/Bindings.xml Normal file
View File

@ -0,0 +1,7 @@
<Bindings>
<Binding name="RUENUI_MACROS" header="RUENUI">RuenUI_OpenMenu("macros");</Binding>
<Binding name="RUENUI_SETTINGS">RuenUI_OpenMenu("settings");</Binding>
<Binding name="RUENUI_KEYBINDINGS">RuenUI_OpenMenu("keybindings");</Binding>
<Binding name="RUENUI_HELP">SlashCmdList.RUENUI("help");</Binding>
<Binding name="RUENUI_SUPPORT">RuenUI_OpenMenu("support");</Binding>
</Bindings>

44
RuenUI/Brand.lua Normal file
View File

@ -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

334
RuenUI/ClassAssist.lua Normal file
View File

@ -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

226
RuenUI/ClassLayout.lua Normal file
View File

@ -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

223
RuenUI/Controls.lua Normal file
View File

@ -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

1106
RuenUI/Core.lua Normal file

File diff suppressed because it is too large Load Diff

199
RuenUI/DamageMeters.lua Normal file
View File

@ -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

309
RuenUI/ExtraBars.lua Normal file
View File

@ -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 x<r+12 and x+width>l-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<score then target,fit,score=candidate,candidateFit,cost end
if cost==0 then break end
end
end
if target then
local scale=base*fit
if math.abs(f:GetScale()-scale)>.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

65
RuenUI/GunAudio.lua Normal file
View File

@ -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

View File

@ -0,0 +1,3 @@
-- Generated locally by the optional Ruen hardware evaluator. No donor machine settings.
local _, P = ...
P.hardwareProfile = {}

View File

@ -0,0 +1,2 @@
local _, P = ...
-- The Windows installer can write an explicit first-login language choice here.

46
RuenUI/Locale.lua Normal file
View File

@ -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

236
RuenUI/Optimizer.lua Normal file
View File

@ -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()<h.checkedAt then return {} end
return h
end
local function write(key,value,raid)
local d=db();local before=C_CVar.GetCVar(key)
if before==nil then return false end
if key:find('Graphics') or key:find('^graphics') then
local reason=IsGraphicsSettingValueSupported and IsGraphicsSettingValueSupported(key,value,raid or false)
if reason and reason~=0 then return false end
end
if d.original[key]==nil then d.original[key]=before end
if before==tostring(value) then return true end
local ok=pcall(C_CVar.SetCVar,key,tostring(value))
return ok
end
local function profile(which,tier)
local prefix=which=='raid' and 'raidGraphics' or 'graphics'
for i,suffix in ipairs(fields) do write(prefix..suffix,tiers[tier][i],which=='raid') end
-- Preserve readable surfaces, full-size UI and ground telegraphs.
write(prefix..'ProjectedTextures',1,which=='raid')
write(prefix..'ParticleDensity',2,which=='raid')
write(prefix..'SpellDensity',which=='raid' and 0 or 1,which=='raid')
write(prefix..'DepthEffects',0,which=='raid')
end
local function cap(value)
write('useMaxFPS',1);write('maxFPS',value)
write('useMaxFPSBk',1);write('maxFPSBk',15)
end
local function reset(seconds)
warmup,elapsed,frames,histogram=seconds or 15,0,0,{}
end
local function percent(p)
local count=0
for tenthMS=1,20000 do
count=count+(histogram[tenthMS] or 0)
if count>=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.tier<d.ceiling and windows<8) and r.tier+1 or 'finish'
elseif not passed then
if r.best then pending='finish'
elseif r.tier>1 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

533
RuenUI/OverlayLayout.lua Normal file
View File

@ -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<gap or maxY<gap then return end
local function clamp(v,a,b) return math.max(a,math.min(b,v)) end
x,y=clamp(x,gap,maxX),clamp(y,gap,maxY)
local xs,ys={x,gap,maxX},{y,gap,maxY}
local seenX,seenY={[x]=true,[gap]=true,[maxX]=true},{[y]=true,[gap]=true,[maxY]=true}
local function add(list,seen,value) if not seen[value] then seen[value]=true;list[#list+1]=value end end
for _,o in ipairs(obstacles) do
add(xs,seenX,clamp(o.right+gap,gap,maxX));add(xs,seenX,clamp(o.left-gap-width,gap,maxX))
add(ys,seenY,clamp(o.top+gap,gap,maxY));add(ys,seenY,clamp(o.bottom-gap-height,gap,maxY))
end
local best,score
for _,cx in ipairs(xs) do for _,cy in ipairs(ys) do
local d=(cx-x)^2+(cy-y)^2
if not score or d<score then
local candidate={left=cx,right=cx+width,bottom=cy,top=cy+height}
local free=true
for _,o in ipairs(obstacles) do if overlaps(candidate,o,gap-0.1) then free=false;break end end
if free then
if d==0 then return candidate end -- preferred position is already optimal
best,score=candidate,d
end
end
end end
return best
end
-- Native attachments can extend well beyond their parent unit frame. Keep
-- their own secure layout; overlays must account for their visible footprint.
function P.AttachedHUDRegions()
local list={}
local function add(f,name)
local r=rect(f)
if r then r.name=name or r.name;list[#list+1]=r end
end
for _,name in ipairs({"TargetFrame","FocusFrame"}) do
local f=_G[name]
if f and f:IsShown() then
add(f.spellbar,name.." cast")
if name=="FocusFrame" then add(f.totFrame,"Focus target") end
if f.GetAuraContainer then
local aura=f:GetAuraContainer()
local r,restricted=rect(aura)
if restricted then
-- Reserve the public maximum footprint, never infer aura
-- counts from restricted values. 48 icons in constrained
-- five-icon rows plus native spacing fit in 264 units.
r=rect(f)
if r then
local height=264*f:GetEffectiveScale()/UIParent:GetEffectiveScale()
local below=f.buffsOnTop
below=not (issecretvalue and issecretvalue(below)) and below==false
if below then r.bottom=r.bottom-height else r.top=r.top+height end
end
end
if r then r.name=name.." auras";list[#list+1]=r end
end
end
end
if ComboFrame and ComboFrame:IsShown() then
for i,f in ipairs(ComboFrame.ComboPoints or {}) do add(f,"Combo point "..i) end
end
for i=11,12 do add(_G["RuenPetExtraButton"..i],"Pet extra "..i) end
return list
end
function P.SocialNotificationSpace(frameEdge)
local function height(name,fallback)
local f=_G[name]
return f and math.max(fallback,f:GetHeight()*f:GetEffectiveScale()/UIParent:GetEffectiveScale()) or fallback
end
-- Quick Join expands horizontally; BN and time-limit notifications stack
-- above it. The shard-transfer notice and toast hover card need room too.
local base=(frameEdge(ChatFrame1,"GetTop") or 195)+27
local native=frameEdge(ChatAlertFrame,"GetBottom")
base=math.max(base,native or base)
local stack=height("QuickJoinToastButton",32)+height("BNToastFrame",63)+height("TimeAlertFrame",50)
return {left=0,right=math.max(340,(frameEdge(ChatFrame1,"GetLeft") or 20)+320),
bottom=base-5,top=base+math.max(160,stack+20),name="Social notifications"}
end
-- Reserve entire control blocks, including empty slots and gaps. Visibility
-- of individual buttons must never create a landing space for a bag or tooltip.
function P.ControlRegions()
local result={}
for _,group in ipairs({
{name="Center controls", "MainActionBar","MultiBarBottomLeft","MultiBarBottomRight","MultiBar5"},
{name="Right controls", "MultiBarLeft","MultiBarRight","BagsBar","MicroMenuContainer"},
{name="Left controls", "MultiBar6","MultiBar7"},
}) do
local region
for _,name in ipairs(group) do
local r=rect(_G[name],true)
if r then
if not region then region=r;region.name=group.name
else
region.left=math.min(region.left,r.left);region.right=math.max(region.right,r.right)
region.bottom=math.min(region.bottom,r.bottom);region.top=math.max(region.top,r.top)
end
end
end
if region then result[#result+1]=region end
end
return result
end
function P.OverlayObstacles(includePanels)
local list=P.ControlRegions()
list[#list+1]=P.SocialNotificationSpace(edge)
for _,r in ipairs(P.classAssistReserved or {}) do list[#list+1]=r end
-- The three complete control rectangles already include their members.
-- Duplicating every button bar makes the placement search much more costly.
for _,name in ipairs(hudNames) do
if not blockMembers[name] then
local r=rect(_G[name],name=="PlayerCastingBarFrame" or name=="RuenSwingTimers")
if r then
if name=="PetActionBar" and P.PetExtraGeometry then r.right=r.right+select(3,P.PetExtraGeometry()) end
list[#list+1]=r
end
end
end
for _,r in ipairs(P.AttachedHUDRegions()) do list[#list+1]=r end
if DamageMeter and DamageMeter:IsShown() then
for i=2,3 do local r=rect(_G["DamageMeterSessionWindow"..i]);if r then list[#list+1]=r end end
end
if includePanels then
for _,name in ipairs(panels) do local r=rect(_G[name]);if r then list[#list+1]=r end end
end
return list
end
local function collectAlerts()
local result,seen={},{}
-- Roll cards can wrap into a second column instead of reserving one tall
-- mostly-empty container over the combat HUD. Native roll actions stay intact.
local rolls=GroupLootContainer and GroupLootContainer.rollFrames
if rolls then
seen[GroupLootContainer]=true
for _,f in pairs(rolls) do
if f:IsShown() then seen[f]=true;result[#result+1]=f end
end
end
local function add(f)
if f and not seen[f] and f:IsShown() then seen[f]=true;result[#result+1]=f end
end
add(GroupLootContainer);add(TalkingHeadFrame)
for _,system in ipairs(AlertFrame and AlertFrame.alertFrameSubSystems or {}) do
add(system.anchorFrame)
if system.alertFramePool and system.alertFramePool.EnumerateActive then
for f in system.alertFramePool:EnumerateActive() do add(f) end
end
end
return result
end
local function alertPadding(f)
if f==GroupLootContainer then return 22 end
for _,roll in pairs(GroupLootContainer and GroupLootContainer.rollFrames or {}) do
if f==roll then return 6 end
end
return 0
end
local alertScales=setmetatable({},{__mode="k"})
local function fitFrame(f,obstacles,x,y,padding)
if not f or not f:IsShown() or (f.IsProtected and f:IsProtected() and InCombatLockdown()) then return false end
local current=f:GetScale()
local saved=alertScales[f]
if not saved or math.abs(current-saved.applied)>.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

465
RuenUI/PetExtras.lua Normal file
View File

@ -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

76
RuenUI/Profile.lua Normal file
View File

@ -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},
}

26
RuenUI/RuenUI.toc Normal file
View File

@ -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

162
RuenUI/SwingTimers.lua Normal file
View File

@ -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

View File

@ -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.'

44
Tools/Migrate-RuenUI.ps1 Normal file
View File

@ -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)
}
}

View File

@ -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 }
}

36
Tools/Ruen-Setup.c Normal file
View File

@ -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);
}

13
Tools/kernel32.def Normal file
View File

@ -0,0 +1,13 @@
LIBRARY KERNEL32.dll
EXPORTS
GetModuleFileNameW
GetCommandLineW
GetWindowsDirectoryW
CreateProcessW
WaitForSingleObject
GetExitCodeProcess
CloseHandle
ExitProcess
GetStdHandle
WriteFile
ReadFile

148
Tools/ruen_dependencies.py Normal file
View File

@ -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

108
Tools/ruen_hardware.py Executable file
View File

@ -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<value<130: continue
crit=read(p.with_name(p.name.replace('_input','_crit')))
ceiling=min(90 if name not in ('amdgpu','nouveau') else 83, float(crit)/1000-10) if crit else (90 if name not in ('amdgpu','nouveau') else 83)
temps.append({'sensor':name+'/'+p.stem, 'celsius':value,'headroomLimit':ceiling})
hot=hot or value>=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()

53
Tools/ruen_migrate.py Normal file
View File

@ -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())

98
dependencies.lock.json Normal file
View File

@ -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"
}
]
}

19
docs/DEPENDENCIES.md Normal file
View File

@ -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.

57
docs/DEVELOPMENT.md Normal file
View File

@ -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.

23
docs/INSTALL-RU.md Normal file
View File

@ -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).

75
docs/INSTALL.md Normal file
View File

@ -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.

56
docs/RELEASE-REVIEW.md Normal file
View File

@ -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).

53
scripts/build_release.py Normal file
View File

@ -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)

102
tests/check-gun-audio.lua Normal file
View File

@ -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).')

1552
tests/check-layout.lua Normal file

File diff suppressed because it is too large Load Diff

133
tests/check-meter.lua Normal file
View File

@ -0,0 +1,133 @@
-- A taint-propagation simulation, not a substitute for the game's secure VM.
-- Execute the actual Blizzard visibility/timer methods against tracked state.
local root=assert(arg[1]);local P={}
local native=(assert(os.getenv('RUEN_NATIVE_UI'))..'/')
Enum={DamageMeterVisibility={Always=0,InCombat=1,Hidden=2,InGroup=3},
EditModeSystem={DamageMeter=29},EditModeDamageMeterSetting={Visibility=0},DamageMeterSessionType={Expired=3}}
local tainted=false;local combat,inside,kind,available,edit,room=false,false,'none',true,false,true
local saves,updates,nativeRefreshes=0,0,0;local jobs={};local hooks={}
local function copy(t)if type(t)~='table'then return t end;local r={};for k,v in pairs(t)do r[k]=copy(v)end;return r end
CopyTable=copy
local function invoke(t,fn,...)local prior=tainted;tainted=t;local r={pcall(fn,...)};tainted=prior;assert(r[1],r[2]);return unpack(r,2)end
local function flush()local n=0;while #jobs>0 do n=n+1;assert(n<40,'refresh loop');local j=table.remove(jobs,1);invoke(j.t,j.fn)end end
local function addon(fn,...)invoke(true,fn,...);flush()end
local function nativeEvent()invoke(false,function() DamageMeter:UpdateShownState()end)end
local function frame()
local data,marks={},{};local f={}
return setmetatable(f,{__index=function(_,k)if marks[k] then tainted=true end;return data[k]end,
__newindex=function(_,k,v)data[k]=v;marks[k]=tainted end}),data,marks
end
local meter,data,marks=frame();DamageMeter=meter
local g={w=400,h=200,x=50,y=70};local shown=false
local function engineMethod(k,fn)data[k]=fn end
engineMethod('GetWidth',function()return g.w end);engineMethod('GetHeight',function()return g.h end)
engineMethod('GetEffectiveScale',function()return 1 end)
engineMethod('GetNumPoints',function()return 1 end)
engineMethod('GetPoint',function()return 'BOTTOMLEFT',UIParent,'BOTTOMLEFT',g.x,g.y end)
engineMethod('GetLeft',function()return g.x end);engineMethod('GetBottom',function()return g.y end)
engineMethod('GetRight',function()return g.x+g.w end);engineMethod('GetTop',function()return g.y+g.h end)
engineMethod('SetSize',function(_,w,h)assert(not combat);g.w,g.h=w,h end)
engineMethod('ClearAllPoints',function()assert(not combat)end)
engineMethod('SetPoint',function(_,_,_,_,x,y)assert(not combat);g.x,g.y=x,y end)
engineMethod('HookScript',function()end)
engineMethod('SetShown',function(_,v)shown=v end);engineMethod('IsShown',function()return shown end)
engineMethod('IsEditing',function()return edit end)
engineMethod('IsPlayerInCombat',function()return combat end)
engineMethod('IsPlayerInGroup',function()return true end)
engineMethod('RefreshLayout',function()nativeRefreshes=nativeRefreshes+1 end)
engineMethod('UpdateSystemSettingVisibility',function()end);engineMethod('OnUpdateSystem',function()end)
local layout={layoutName='Ruen UI - Clear ESDF',systems={{system=29,settings={{setting=0,value=1}}}}}
local manager={layoutInfo={activeLayout=1,layouts={copy(layout)}}};EditModeManagerFrame=manager
function manager:IsShown()return edit end
function manager:HookScript()end
function manager:GetActiveLayoutInfo()return self.layoutInfo.layouts[self.layoutInfo.activeLayout]end
UIParent={GetWidth=function()return 1400 end,GetHeight=function()return 900 end,GetEffectiveScale=function()return 1 end}
local cv='1';C_CVar={GetCVar=function()return cv end}
CVarCallbackRegistry={SetCVarCachable=function()end,GetCVarValueBool=function()return cv=='1'end}
C_DamageMeter={IsDamageMeterAvailable=function()return available,'restricted'end}
function IsInInstance()return inside,kind end
function InCombatLockdown()return combat end
function UnitAffectingCombat()return combat end
function issecurevariable(_,k)return not marks[k]end
function CreateFrame()return {RegisterEvent=function()end,SetScript=function(self,k,v)self[k]=v end}end
C_Timer={After=function(_,fn)jobs[#jobs+1]={t=true,fn=fn}end}
function hooksecurefunc(_,k,fn)hooks[k]=fn end
function P.Localized(en)return en end
assert(loadfile(root..'/Profile.lua'))('RuenUI',P)
C_EditMode={}
function C_EditMode.GetLayouts()return copy(manager.layoutInfo)end
function C_EditMode.SaveLayouts(info)
assert(not combat and not edit,'layout persisted during combat/Edit Mode')
assert(info~=manager.layoutInfo and info.layouts~=manager.layoutInfo.layouts,'shared native table passed to save')
saves=saves+1;manager.layoutInfo=copy(info)
end
function C_EditMode.SetActiveLayout(index)
-- Engine round-trip: the native event gets a fresh, clean serialized table.
local saved=copy(manager.layoutInfo)
jobs[#jobs+1]={t=false,fn=function()
manager.layoutInfo=saved
meter.visibility=saved.layouts[index].systems[1].settings[1].value
nativeEvent()
if hooks.OnUpdateSystem then invoke(true,hooks.OnUpdateSystem)end
end}
end
assert(loadfile(native..'DamageMeter.lua'))()
data.visibility=1
for _,k in ipairs({'ShouldBeShown','UpdateShownState','UpdateSessionTimerState','ForEachSessionWindow'})do data[k]=DamageMeterMixin[k]end
local f=assert(io.open(native..'DamageMeterSessionWindow.lua'));local source=f:read('*a');f:close()
DamageMeterSessionWindowMixin={}
for _,k in ipairs({'SetSessionDuration','ShowSessionTimerFromCombatSession','ShowSessionTimer','ClearSessionTimer','UpdateSessionTimerState'})do
local fn=assert(source:match('(function DamageMeterSessionWindowMixin:'..k..'%b().-\nend)'))
assert(loadstring(fn))()
end
local timerRule=assert(source:match('(local function ShouldDisplaySessionTimer%b().-\nend)'))
-- The extracted native methods resolve this through their environment.
assert(loadstring(timerRule:gsub('local function','function',1)))()
local session={};for k,v in pairs(DamageMeterSessionWindowMixin)do session[k]=v end
session.GetCombatSession=function()return {durationSeconds=3}end
session.GetSessionType=function()return 1 end;session.GetSessionID=function()end
session.IsPlayerInCombat=function()return combat end
session.SetOnUpdateReason=function()end
session.GetSessionTimerFontString=function()return {SetText=function()end}end
function SecondsToClock(n)
assert(not(combat and tainted),'secret durationSeconds comparison/format under RuenUI taint')
updates=updates+1;return tostring(n)
end
data.windowDataList={{sessionWindow=session}}
RuenUIDB={};RuenUICharacter={}
function P.OverlayObstacles()return {}end
function P.UtilityTop()return {GetRight=function()return 1380 end,GetTop=function()return 260 end}end
function P.FindOverlayPosition(w,h,x,y)if room then return {left=x,bottom=y,right=x+w,top=y+h}end end
local own=true
assert(loadfile(root..'/DamageMeters.lua'))('RuenUI',P)
addon(P.InitializeDamageMeters,function()return own end,function(_,_,_,_,x,y)assert(not combat);g.x,g.y=x,y end,function(f,k)return f[k](f)end,function(_,value)cv=tostring(value)end)
-- Reading a tainted visibility field must poison the real native combat chain,
-- even when the meter is hidden. The old code fails here.
combat=true;nativeEvent();combat=false
assert(not shown and not marks.visibility,'outdoors should hide without field taint')
local baseline=saves
for i=1,100 do addon(P.RefreshDamageMeters)end
assert(saves==baseline,'idle refresh saves repeatedly')
for _,case in ipairs({{true,'party',true},{true,'raid',true},{true,'pvp',false},{true,'arena',false},{false,'none',false}})do
inside,kind=case[1],case[2];addon(P.RefreshDamageMeters)
assert(shown==case[3],'incorrect zone visibility: '..kind)
for i=1,200 do combat=true;nativeEvent();combat=false;nativeEvent()end
assert(not marks.visibility,'visibility contaminated by addon')
end
inside,kind=true,'party';addon(P.RefreshDamageMeters)
combat=true;inside=false;addon(P.RefreshDamageMeters);assert(shown,'combat transition not deferred')
combat=false;addon(P.RefreshDamageMeters);assert(not shown)
addon(P.DamageMeterCommand,'show');assert(shown)
addon(P.DamageMeterCommand,'off');assert(not shown)
addon(P.DamageMeterCommand,'auto');inside=true;addon(P.RefreshDamageMeters);assert(shown)
room=false;addon(P.RefreshDamageMeters);assert(not shown and RuenUICharacter.damageMeterStatus.reason=='no free space')
baseline=saves;for i=1,100 do addon(P.RefreshDamageMeters)end;assert(saves==baseline,'no-space save loop')
room=true;addon(P.RefreshDamageMeters);assert(shown)
available=false;addon(P.RefreshDamageMeters);assert(not shown)
available=true;addon(P.RefreshDamageMeters);assert(shown)
edit=true;baseline=saves;addon(P.RefreshDamageMeters);assert(saves==baseline and g.w==400,'Edit Mode handoff')
edit=false;addon(P.RefreshDamageMeters);assert(shown and g.w==260)
addon(P.StopDamageMeters)
assert(not marks.visibility and nativeRefreshes==0,'native mutable refresh called from addon')
assert(updates>=1000,'combat loop did not execute native timer')
print('PASS: 1000 combat starts; native timer with tracked taint; auto PvE/PvP/manual modes; no-room recovery; idle/no-room idempotency; combat deferral; Edit Mode handoff; no native refresh calls')

367
tests/check-pet-actions.lua Normal file
View File

@ -0,0 +1,367 @@
local root=assert(arg[1], 'Pass the RuenUI directory with a trailing slash')
local combat=false
local cursor
function GetCursorInfo()if cursor then return unpack(cursor)end end
function ClearCursor()cursor=nil end
function hooksecurefunc(object,key,fn)
if type(object)=='string' then return end
local original=object[key]
object[key]=function(...)local r={original(...)};fn(...);return unpack(r)end
end
local frames,timers={},{}
local function frame(name,parent)
local f={name=name,parent=parent,w=39,h=39,shown=true,attrs={},scripts={},events={}}
function f:GetName()return self.name end
function f:GetWidth()return self.w end
function f:GetHeight()return self.h end
function f:GetEffectiveScale()return self.parent and self.parent:GetEffectiveScale() or 1.25 end
function f:SetSize(w,h)assert(not combat);self.w,self.h=w,h end
function f:SetAttribute(k,v)assert(not combat,'protected attribute write during combat');self.attrs[k]=v end
function f:ClearAllPoints()assert(not combat);self.points={} end
function f:SetPoint(...)assert(not combat);self.points=self.points or {};self.points[#self.points+1]={...} end
function f:SetAllPoints()end
function f:Show()self.shown=true end
function f:Hide()self.shown=false end
function f:SetShown(v)self.shown=v end
function f:IsShown()return self.shown and (not self.parent or self.parent:IsShown()) end
function f:SetChecked(v)self.checked=v end
function f:GetID()return 0 end
function f:SetTexture(t)self.texture=t end
function f:GetTexture()return self.texture end
function f:GetAtlas()return nil end
function f:GetTexCoord()return 0,1,0,1 end
function f:SetTexCoord()end
function f:SetVertexColor(...)self.color={...}end
function f:SetText(t)self.text=t end
function f:SetTextColor()end
function f:SetScript(k,v)self.scripts[k]=v end
function f:HookScript(k,v)self.scripts[k]=v end
function f:RegisterForClicks(...)self.clicks={...}end
function f:RegisterForDrag()end
function f:RegisterEvent(e)self.events[e]=true end
function f:UnregisterEvent(e)self.events[e]=nil end
function f:CreateTexture()return frame(nil,self)end
function f:CreateFontString()return frame(nil,self)end
function f:ShowAutoCastEnabled(v)self.auto=v end
function f:Clear()self.cd=nil end
function f:SetCooldown(...)self.cd={...}end
for _,kind in ipairs({'Normal','Pushed','Highlight','Checked'})do
f['Get'..kind..'Texture']=function(self)return self[kind]end
f['Set'..kind..'Texture']=function(self,t)self[kind]=frame(nil,self);self[kind].texture=t end
end
frames[#frames+1]=f;if name then _G[name]=f end;return f
end
CreateFrame=function(_,name,parent)return frame(name,parent)end
UIParent=frame('UIParent');PetActionBar=frame('PetActionBar',UIParent);PetActionBar.w=408
for i=1,10 do frame('PetActionButton'..i,PetActionBar)end
for _,kind in ipairs({'Normal','Pushed','Highlight','Checked'})do PetActionButton1['Set'..kind..'Texture'](PetActionButton1,'native-'..kind)end
EditModeManagerFrame=frame('EditModeManagerFrame',UIParent)
RuenUIDB={};RuenUICharacter={}
Enum={SpellBookSpellBank={Pet=1},SpellBookItemType={Spell=1,PetAction=3},ActionBarSet={Mkb=0,Gamepad=1}}
NUM_PET_ACTION_SLOTS=10
function InCombatLockdown()return combat end
C_Timer={After=function(_,fn)timers[#timers+1]=fn end}
local function flush()local t=timers;timers={};for _,fn in ipairs(t)do fn()end end
local book,native={},{}
local function pet(prefix,count)
book={};native={}
for i=1,count do book[i]={actionID=9000+i,spellID=9000+i,name=prefix..i,iconID=100+i,isPassive=false,itemType=3} end
book[count+1]={actionID=9900,spellID=9900,name='Passive',isPassive=true}
book[count+2]={actionID=2,name='Follow',itemType=3,isPassive=false}
for i=1,math.min(count,4)do native[i]={name=prefix..i,id=9000+i} end
end
function GetPetActionInfo(i)local p=native[i];if p then return p.name,nil,false,nil,nil,nil,p.id end end
C_Spell={GetSpellInfo=function(id)for _,p in ipairs(book)do if p.spellID==id then return p end end end}
local cooldown={startTime=10,duration=5,modRate=1}
local auto=true
local picked
C_SpellBook={HasPetSpells=function()return #book end,GetSpellBookItemInfo=function(i)return book[i]end,
IsSpellBookItemPassive=function(i)return book[i].isPassive end,
GetSpellBookItemName=function(i)return book[i].name end,
IsSpellBookItemUsable=function()return true end,IsSpellBookItemInRange=function()return true end,
GetSpellBookItemAutoCast=function()return true,auto end,
GetSpellBookItemCooldown=function()return cooldown end,
PickupSpellBookItem=function(i,b)assert(not combat and b==1);picked=i;cursor={'petaction',book[i].actionID} end}
local locked=false
C_CVar={GetCVar=function()return locked and '1' or '0'end}
function IsModifiedClick()return false end
function GetBindingKey(action)return action:find('11:') and '-' or '='end
function GetBindingText(k)return k end
local actions={[25]={'spell',99999},[1]={'spell',100},[37]={'item',6948},[145]={'spell',222}}
local places,uses,toggles=0,{},0
local engineActions={}
local rejectPlacement=false
storedType='engine_pet'
local currentPage=1
function GetActionInfo(slot)local a=actions[slot];if a then if a[1]==storedType and a[2]>100000000 then return 'spell',0,'pet' end return unpack(a)end end
function PickupAction(slot)assert(not combat and not cursor);cursor=actions[slot];actions[slot]=nil end
function PlaceAction(slot)
assert(not combat and slot>=13 and slot<=24 and cursor and cursor[1]=='petaction')
places=places+1;local old=actions[slot];actions[slot]={storedType,cursor[2]};cursor=old
end
C_ActionBar={IsAutoCastPetAction=function(slot)local k,id=GetActionInfo(slot);return k==storedType and id<100000 end,
ToggleAutoCastPetAction=function(slot)assert(C_ActionBar.IsAutoCastPetAction(slot));auto=not auto;toggles=toggles+1 end,
IsCurrentAction=function(slot)return uses[#uses]==slot end,
GetBonusBarIndexForSlot=function()return nil end,
GetActionBarPage=function()return currentPage end,
FindPetActionButtons=function(id)
if rejectPlacement then return end
local result={}
for slot,action in pairs(actions)do
if action[1]==storedType and action[2]%16777216==id%16777216 then result[#result+1]=slot end
end
return #result>0 and result or nil
end}
-- Use Blizzard's actual page map, including visible page 3.
for _,name in ipairs({'MultiBarBottomLeft','MultiBarBottomRight','MultiBarLeft','MultiBarRight','MultiBar5','MultiBar6','MultiBar7'})do frame(name,UIParent)end
dofile((assert(os.getenv('RUEN_NATIVE_UI'))..'/MultiActionBars.lua'))
assert(MultiActionBar_GetBarForPage(3)==MultiBarRight and MultiActionBar_GetBarForPage(2)==nil)
-- Native prototypes can lack texture accessors. Reproduce the reported crash.
PetActionButton1.GetCheckedTexture=nil
PetActionButton1.GetPushedTexture=nil
C_PetInfo={GetSpellForPetAction=function(id)return id%16777216 end}
local function Copy(t)local n={};for k,v in pairs(t)do n[k]=v end;return n end
CopyTable=Copy
function GetFrameMetatable()return {__index={GetParent=function(f)return f.parent end,GetAttribute=function(f,a,n,s)
if not n then return f.attrs[a] end
return f.attrs[a..n..s] or f.attrs['*'..n..s] or f.attrs[n..s] or f.attrs[n]
end}}end
C_PaperDollInfo={GetInventorySlotInfo=function()return 1 end,IsRangedSlotShown=function()return false end}
function IsShiftKeyDown()return false end
function IsAltKeyDown()return false end
function IsControlKeyDown()return false end
local keyDown=true
function GetCVarBool(k)return k=='ActionButtonUseKeyDown' and keyDown end
function securecallfunction(fn,...)return fn(...)end
function SpellCanTargetItem()return false end
function SpellCanTargetItemID()return false end
SpellFlyout={Hide=function()end}
function UseAction(slot,unit,button,isKeyPress)
assert(button=='LeftButton');assert(actions[slot][1]==storedType,'no native pet action')
uses[#uses+1]=slot
end
C_Macro={RunMacroText=function()error('must not use macrotext for pet activation')end}
assert(loadfile((assert(os.getenv('RUEN_NATIVE_UI'))..'/SecureTemplates.lua')))()
local create=CreateFrame
CreateFrame=function(kind,name,parent,template)
local f=create(kind,name,parent)
if template=='SecureActionButtonTemplate' then f.CalculateAction=SecureActionButtonMixin.CalculateAction;f.scripts.OnClick=SecureActionButton_OnClick end
return f
end
local function assertAction(button,id)
assert(button.attrs.type1=='action' and button.attrs.action1 and not button.attrs.macrotext1,'extra needs a real action')
local kind,actual=GetActionInfo(button.attrs.action1)
assert(kind==storedType and C_PetInfo.GetSpellForPetAction(actual)==id,'wrong stored action')
end
local function click(button,mouse)
button.scripts.OnClick(button,mouse,true);if button.scripts.PostClick then button.scripts.PostClick(button,mouse,true)end
button.scripts.OnClick(button,mouse,false);if button.scripts.PostClick then button.scripts.PostClick(button,mouse,false)end
end
local P={Localized=function(en)return en end}
assert(loadfile(root..'PetExtras.lua'))('RuenUI',P)
pet('Bear',5)
local choices=P.PetExtraChoices();assert(#choices==1 and choices[1].id==9005,'missing bear ability was not found')
-- Same-name ranks and passive/command entries must not consume extra slots.
book[#book+1]={spellID=9001,actionID=9001,name='Bear1',iconID=101,isPassive=false}
assert(#P.PetExtraChoices()==1)
P.InitializePetExtras(function()return true end)
local a,b=RuenPetExtraButton11,RuenPetExtraButton12
assert(a and b and a.parent==PetActionBar and NUM_PET_ACTION_SLOTS==10)
assert(a.w==39 and a.h==39 and P.PetExtraGeometry()==39)
assert(select(3,P.PetExtraGeometry())==82 and PetActionBar.w+select(3,P.PetExtraGeometry())==490)
assert(a.points[1][2]==PetActionButton10 and a.points[1][4]==2)
assert(b.points[1][2]==a and b.points[1][4]==2)
assertAction(a,9005)
assert(not a.attrs.type2 and not a.attrs.macrotext2)
assert(not b.attrs.type1 and not b.attrs.macrotext1)
assert(a.scripts.OnUpdate and not b.scripts.OnUpdate,'empty pet slot still polling')
assert(a.HotKey.text=='-' and b.HotKey.text=='=')
assert(a.AutoCastOverlay.auto and a.cooldown.cd[2]==5)
assert(a.Normal.texture=='native-Normal' and a.Checked.texture,'missing native art accessor must not break setup')
assert(a.clicks[1]=='AnyDown' and a.clicks[2]=='AnyUp')
PetActionBar:Hide();assert(not a:IsShown() and not b:IsShown(),'petless/vehicle visibility must follow native bar');PetActionBar:Show()
local listener
for _,f in ipairs(frames)do if f.events.PET_BAR_UPDATE then listener=f end end
assert(listener)
-- A new pet arrives during combat: no secure writes until combat ends.
combat=true;pet('Demon',6)
listener.scripts.OnEvent(listener,'UNIT_PET','player');flush()
P.RefreshPetExtras()
a.scripts.OnUpdate(a,.25)
assert(listener.events.PLAYER_REGEN_ENABLED);assertAction(a,9005)
combat=false;listener.scripts.OnEvent(listener,'PLAYER_REGEN_ENABLED');flush()
assert(not listener.events.PLAYER_REGEN_ENABLED)
assertAction(a,9005);assertAction(b,9006)
-- Native rearrangement exposes a different missing ability, never overwrites native slots.
native[1]={name='Demon5',id=9005};listener.scripts.OnEvent(listener,'PET_BAR_UPDATE');flush()
assert(a.item.id==9001 and b.item.id==9006 and native[1].id==9005)
-- Right-click autocast appearance follows the actual spellbook state.
auto=false;a.scripts.OnUpdate(a,.2);assert(not a.AutoCastOverlay.auto)
picked=nil;locked=true;a.scripts.OnDragStart(a);assert(not picked)
locked=false;a.scripts.OnDragStart(a);assert(picked==1)
picked=nil;combat=true;a.scripts.OnDragStart(a);assert(not picked);combat=false
-- Localized pet spells store stable action IDs, and petless states clear actions.
ClearCursor();pet('Медведь',5);P.RefreshPetExtras();assertAction(a,9005)
book={};native={};P.RefreshPetExtras();assert(not a.attrs.type1 and not a.attrs.type2 and not a.attrs.macrotext2)
assert(not a.scripts.OnUpdate and not b.scripts.OnUpdate,'petless polling')
-- A real native ResizeLayout bar includes every visible non-ignored child.
local included={}
for _,f in ipairs(frames)do if f.parent==PetActionBar and not f.ignoreInLayout then included[#included+1]=f end end
assert(#included==10 and a.ignoreInLayout and b.ignoreInLayout,'extras enlarged native ten-slot width')
pet('Demon',6);locked=false;P.RefreshPetExtras()
C_SpellBook.PickupSpellBookItem(2,1);a.scripts.OnReceiveDrag(a)
assert(not cursor and a.item.id==9002 and RuenUICharacter.petExtraAssignments[1].id==9002,'drop did not pin pet spell')
assertAction(a,9002)
P.RefreshPetExtras();assert(a.item.id==9002,'pinned assignment did not survive refresh')
-- Book commands are valid too; other classes' player spells/passives/items are not.
book[#book+1]={actionID=117440516,name='Move To',iconID=10,isPassive=false,itemType=3}
C_SpellBook.PickupSpellBookItem(#book,1);b.scripts.OnReceiveDrag(b)
assert(b.item.command=='/petmoveto' and actions[b.attrs.action1][2]==117440516 and not b.attrs.type2)
local pinned=a.item.id
cursor={'item',123};a.scripts.OnReceiveDrag(a);assert(a.item.id==pinned and cursor)
cursor={'spell',4,'spell',99999};a.scripts.OnReceiveDrag(a);assert(a.item.id==pinned and cursor)
locked=true;C_SpellBook.PickupSpellBookItem(3,1);a.scripts.OnReceiveDrag(a);assert(a.item.id==pinned and cursor)
locked=false;combat=true;a.scripts.OnReceiveDrag(a);assert(a.item.id==pinned and cursor);combat=false
-- Missing learned abilities cannot leave a command targeting a former demon.
ClearCursor();book={};native={};P.RefreshPetExtras();assert(not a.attrs.type1 and not b.attrs.type1)
pet('Demon',6);P.RefreshPetExtras();assert(a.item.id==9002,'preference was lost when pet disappeared')
P.ResetPetExtras();assert(a.item.id==9005 and b.item.id==9006 and not RuenUICharacter.petExtraAssignments)
RuenUIDB.disabled=true;P.RefreshPetExtras();assert(not a.shown and not b.shown)
print('PASS: ten native slots intact, twelve-button geometry, extra active spells, passive/command filtering, two-key native actions, autocast/cooldowns, pet/class/localization changes, combat deferral, lock-aware copy drag and disabled restore')
-- Reproduce restrictions during combat on a populated extra pet button.
RuenUIDB.disabled=false;pet('Hunter',5);P.RefreshPetExtras()
local restricted=newproxy(true)
getmetatable(restricted).__lt=function()error('restricted cooldown comparison')end
getmetatable(restricted).__le=function()error('restricted cooldown comparison')end
getmetatable(restricted).__mul=function()error('restricted cooldown arithmetic')end
getmetatable(restricted).__sub=function()error('restricted cooldown arithmetic')end
getmetatable(restricted).__add=function()error('restricted cooldown arithmetic')end
local durationObject={}
function a.cooldown:SetCooldownFromDurationObject(object,clearIfZero)
assert(object==durationObject and clearIfZero==true)
self.durationObject=object
end
C_SpellBook.GetSpellBookItemCooldownDuration=function(slot,bank)
assert(slot==a.item.slot and bank==1);return durationObject
end
cooldown={startTime=restricted,duration=restricted,modRate=restricted}
combat=true
for i=1,600 do a.scripts.OnUpdate(a,.2)end
assert(a.cooldown.durationObject==durationObject,'native duration renderer not used')
C_SpellBook.GetSpellBookItemCooldownDuration=function()return nil end
a.cooldown.cd={1,5,1};a.scripts.OnUpdate(a,.2);assert(not a.cooldown.cd,'missing duration did not clear stale swipe')
-- Older API fallback still hands opaque values straight to the native widget.
C_SpellBook.GetSpellBookItemCooldownDuration=nil
for i=1,600 do a.scripts.OnUpdate(a,.2)end
assert(rawequal(a.cooldown.cd[1],restricted) and rawequal(a.cooldown.cd[2],restricted))
cooldown=nil;a.scripts.OnUpdate(a,.2);assert(not a.cooldown.cd)
combat=false
print('PASS: 1200 combat refreshes with opaque cooldown values, native duration object path, nil/finished cleanup, legacy direct-native fallback; no secure attribute changes')
-- Execute Blizzard's actual secure dispatcher (mouse and key-down/up settings).
pet('Hunter',6);P.ResetPetExtras();cooldown=nil
for _,setting in ipairs({true,false})do
keyDown=setting
for _,button in ipairs({a,b})do
local before=#uses;combat=true;click(button,'LeftButton');combat=false
assert(#uses==before+1 and uses[#uses]==button.actionSlot,'native activation must execute exactly once')
end
local before=#uses;local toggleBefore=toggles
click(a,'RightButton');assert(#uses==before and toggles==toggleBefore+1,'right click must toggle, not cast')
end
assert(actions[25][1]=='spell' and actions[25][2]==99999 and actions[1][2]==100 and actions[37][2]==6948 and actions[145][2]==222,'player actions changed')
local count=places;for i=1,200 do P.RefreshPetExtras()end;assert(places==count,'unchanged refresh rewrites action slots')
-- Autocast bits can change in a packed pet action without changing the spell.
local slot=a.actionSlot;actions[slot][2]=actions[slot][2]+2147483648
P.RefreshPetExtras();assert(a.actionSlot==slot and places==count,'autocast flags leaked a reserved slot')
-- Respect a user replacement in a previously owned slot.
actions[slot]={'spell',55555};P.RefreshPetExtras()
assert(actions[slot][2]==55555 and not a.actionSlot,'user replacement overwritten')
P.ResetPetExtras()
-- Cursor contents defer background assignment and remain untouched.
cursor={'item',777};pet('NewPet',5);book[5].actionID=12345;book[5].spellID=12345
P.RefreshPetExtras();assert(cursor[1]=='item' and cursor[2]==777 and not a.attrs.type1)
ClearCursor();listener.scripts.OnEvent(listener,'CURSOR_CHANGED');flush();assertAction(a,12345)
-- Full spare pages are not an excuse to overwrite anything.
RuenUIDB.disabled=true;P.RefreshPetExtras();RuenUIDB.disabled=false
for i=13,36 do actions[i]={'spell',70000+i}end
P.RefreshPetExtras();assert(not a.attrs.type1 and a.activationError=='no unused paging slots')
for i=13,36 do assert(actions[i][2]==70000+i)end
print('PASS: actual native secure click dispatcher, both click phases, combat, right-click autocast, real action records, packed-ID changes, cursor preservation, occupied-slot preservation, idempotency and graceful full-page handling')
-- Exercise the native spellbook's discovery/classification functions too.
for i=13,24 do actions[i]=nil end
actions[25]={'spell',99999}
pet('Hunter',6);P.ResetPetExtras()
MainActionBar=frame('MainActionBar',UIParent)
Enum.ActionBarSet={Mkb=0,Gamepad=1}
InputUtil={IsMKBUIEnabled=function()return true end}
function TableIsEmpty(t)return next(t)==nil end
assert(MultiActionBar_GetBarForPage(3)==MultiBarRight)
LE_ACTIONBAR_STATE_MAIN=0
function ActionBarController_GetCurrentActionBarState()return 0 end
C_ActionBar.GetVehicleBarIndex=function()return 11 end
C_ActionBar.GetOverrideBarIndex=function()return 12 end
C_ActionBar.GetTempShapeshiftBarIndex=function()return 13 end
C_ActionBar.GetBonusBarIndex=function()return 0 end
C_ActionBar.HasBonusActionBar=function()return false end
C_ActionBar.HasOverrideActionBar=function()return false end
C_ActionBar.HasVehicleActionBar=function()return false end
C_ActionBar.HasTempShapeshiftActionBar=function()return false end
C_ActionBar.GetPetActionPetBarIndices=function()end
C_PetInfo.IsPetActionPassive=function()return false end
local source=(assert(os.getenv('RUEN_NATIVE_UI'))..'/')
dofile(source..'ActionButtonUtil.lua');dofile(source..'Blizzard_SpellSearchUtil.lua')
for _,button in ipairs({a,b})do
local info=book[button.item.slot]
assert(SpellSearchUtil.GetActionbarStatusForSpellBookItemInfo(info)==ActionButtonUtil.ActionBarActionStatus.NotMissing,'native spellbook does not recognize extra')
local saved=actions[button.actionSlot];actions[button.actionSlot]=nil
assert(SpellSearchUtil.GetActionbarStatusForSpellBookItemInfo(info)==ActionButtonUtil.ActionBarActionStatus.MissingFromAllBars,'negative control must be missing')
actions[button.actionSlot]=saved
end
print('PASS: actual Blizzard spellbook discovery recognizes both extra action slots; removing their backing records reproduces missing-from-bars status')
-- Reject after the engine accepted a cursor payload: one write only, even if
-- action/cursor events storm, and even across addon reload (saved failure).
RuenUIDB.disabled=true;P.RefreshPetExtras();RuenUIDB.disabled=false
pet('Reject',5);rejectPlacement=true
local before=places
P.ResetPetExtras()
local failed=RuenUICharacter.petExtraActions[1]
assert(failed and failed.failed and failed.payload and not a.attrs.type1)
for i=1,250 do
listener.scripts.OnEvent(listener,'ACTIONBAR_SLOT_CHANGED',failed.slot)
listener.scripts.OnEvent(listener,'CURSOR_CHANGED');flush()
P.RefreshPetExtras()
end
assert(places==before+1,'rejected placement wrote more than once')
assert(actions[25] and actions[25][1]=='spell' and actions[25][2]==99999,'visible page 3 changed')
local Q={Localized=P.Localized}
assert(loadfile(root..'PetExtras.lua'))('RuenUI',Q)
Q.InitializePetExtras(function()return true end)
assert(places==before+1,'reload retried rejected placement')
rejectPlacement=false
-- Active page 2 belongs to the player, not the allocator.
RuenUICharacter.petExtraActions={};currentPage=2
local snapshotPlaces=places
Q.RefreshPetExtras();assert(places==snapshotPlaces and not RuenPetExtraButton11.attrs.type1)
print('PASS: actual native page map, absent texture getters, distinct cursor/action types, one persisted attempt through 500 events/reload, no edits to visible/active pages')
-- Distinguish commands even though ALL report spell/0/pet to GetActionInfo.
currentPage=1;rejectPlacement=false;RuenUICharacter.petExtraActions={}
for i=13,24 do actions[i]=nil end
book={{actionID=100663300,name='Defensive',iconID=1,isPassive=false},
{actionID=100663298,name='Aggressive',iconID=2,isPassive=false}}
native={}
RuenUICharacter.petExtraAssignments={{id=100663300},{id=100663298}}
Q.RefreshPetExtras()
local c,d=RuenPetExtraButton11,RuenPetExtraButton12
assert(c.actionSlot and d.actionSlot and c.actionSlot~=d.actionSlot)
assert(GetActionInfo(c.actionSlot)=='spell' and select(2,GetActionInfo(c.actionSlot))==0 and select(3,GetActionInfo(c.actionSlot))=='pet')
for _,button in ipairs({c,d}) do
local count=#uses;click(button,'LeftButton');assert(#uses==count+1 and uses[#uses]==button.actionSlot)
end
local slot=c.actionSlot;actions[slot]={storedType,100663298}
Q.RefreshPetExtras();assert(not c.actionSlot and actions[slot][2]==100663298,'another command with spell/0/pet was treated as owned')
print('PASS: observed spell/0/pet payload activates both stance commands through native dispatcher and cannot confuse ownership of different commands')

View File

@ -0,0 +1,63 @@
local root=assert(arg[1]);local clock=100;local combat=false;local where='none';local width=1920
local P={Localized=function(a)return a end,hardwareProfile={checkedAt=100,loaded=true,thermalCoverage="full"}}
Enum={PlayerSwingType={MainHand=0,OffHand=1,Ranged=2}}
RuenUIDB={};RuenUICharacter={};UIParent={}
local made={};local function noop()end
function CreateFrame(_,name)
local f={scripts={},shown=false}
for _,k in ipairs({'SetSize','SetPoint','SetFrameStrata','EnableMouse','SetHeight','SetMinMaxValues','SetStatusBarTexture','SetStatusBarColor','RegisterEvent','RegisterUnitEvent','SetWidth','ClearAllPoints','SetAllPoints','SetColorTexture'})do f[k]=noop end
function f:SetScript(k,v)self.scripts[k]=v end
function f:Show()self.shown=true end;function f:Hide()self.shown=false end
function f:SetValue(v)self.value=v end;function f:SetAlpha(v)self.alpha=v end
function f:CreateTexture()return CreateFrame('Texture')end
made[#made+1]=f;if name then _G[name]=f end;return f
end
function GetTime()return clock end;function time()return clock end
function InCombatLockdown()return combat end
local speeds={2,2.5,3};function UnitAttackSpeed()return unpack(speeds)end
local secret={};function issecretvalue(v)return v==secret end
assert(loadfile(root..'SwingTimers.lua'))('test',P)
P.InitializeSwingTimers(function()return true end)
local dock=RuenSwingTimers
local event=dock.scripts.OnEvent
assert(not dock.shown and not dock.scripts.OnUpdate)
event(dock,'PLAYER_SWING',2,0);assert(dock.shown and dock.byType[0].shown)
clock=101;dock.scripts.OnUpdate();assert(dock.byType[0].value==.5)
event(dock,'PLAYER_SWING',3,2);event(dock,'PLAYER_SWING',2.5,1)
assert(dock.byType[1].shown and dock.byType[2].shown)
clock=105;dock.scripts.OnUpdate();assert(not dock.shown and not dock.scripts.OnUpdate)
event(dock,'PLAYER_SWING',secret,0);event(dock,'PLAYER_SWING',3,secret);assert(not dock.shown)
event(dock,'PLAYER_SWING',2,0);event(dock,'PLAYER_REGEN_ENABLED');assert(not dock.shown)
event(dock,'PLAYER_SWING',2,1);speeds={2};event(dock,'UNIT_INVENTORY_CHANGED','player');assert(not dock.shown)
combat=true;P.SwingCommand('preview');assert(not dock.shown);combat=false
P.SwingCommand('preview');assert(dock.shown);P.SwingCommand('off');assert(not dock.shown and not dock.scripts.OnUpdate)
print('PASS: three native swing lanes, progress, fade, no idle ticks, equipment, combat end, secret values, preview and off')
local cvars={};local writes=0
C_CVar={GetCVar=function(k)return cvars[k] or '2'end,SetCVar=function(k,v)assert(not combat,'graphics modified in combat');writes=writes+1;cvars[k]=tostring(v)end}
function IsGraphicsSettingValueSupported()return 0 end
function IsInInstance()return where~='none',where end
function GetPhysicalScreenSize()return width,1080 end
assert(loadfile(root..'Optimizer.lua'))('test',P);P.InitializeOptimizer();local f=made[#made]
P.OptimizerCommand('start');assert(cvars.RAIDsettingsEnabled=='1' and cvars.RenderScale=='1')
local function frames(n,dt)for _=1,n do clock=clock+dt; if f.scripts.OnUpdate then f.scripts.OnUpdate(f,dt)end end end
-- Two passing windows per tier, bounded at eight windows.
frames(72*600,1/72)
local d=RuenUIDB.optimizer
assert(d.profiles.world.calibrated and d.profiles.world.metTarget,'world should pass')
assert(not d.profiles.raid.calibrated,'solo must not validate raid')
assert(cvars.maxFPS=='60','trial cap leaked')
assert(not f.scripts.OnUpdate,'settled optimizer must not poll every frame')
where='raid';f.scripts.OnEvent(f,'ZONE_CHANGED_NEW_AREA');frames(72*61,1/72)
combat=true;local before=writes;frames(72*120,1/72);assert(writes==before,'combat edits occurred')
combat=false;f.scripts.OnEvent(f,'PLAYER_REGEN_ENABLED');frames(72*500,1/72)
assert(d.profiles.raid.calibrated,'raid did not calibrate')
assert(not f.scripts.OnUpdate,'settled raid optimizer must sleep')
P.OptimizerCommand('restore');assert(not RuenUIDB.optimizer and cvars.RAIDsettingsEnabled=='2')
-- Sustained low performance chooses the low tier and reports unmet target.
where='none';P.hardwareProfile={};P.OptimizerCommand('start');frames(25*600,1/25)
d=RuenUIDB.optimizer;assert(d.profiles.world.calibrated and not d.profiles.world.metTarget and d.profiles.world.tier==1)
P.OptimizerCommand('pause');assert(not f.scripts.OnUpdate and not d.enabled)
P.hardwareProfile={checkedAt=clock,loaded=true,thermalPressure=true};P.OptimizerCommand('start')
assert(d.target==45 and d.ceiling==2,'thermal evidence ignored')
P.OptimizerCommand('pause')
print('PASS: headroom calibration, separate real-world/raid tests, actual frame percentiles, combat deferral, thermal input, pause and exact undo')

216
tests/test_installers.py Normal file
View File

@ -0,0 +1,216 @@
"""Offline installer transactions. Set RUEN_PWSH to also exercise PowerShell.
These fixtures do not establish native Windows GUI/PowerShell 5.1 compatibility.
Run: PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tests -v
"""
import hashlib
import importlib.machinery
import importlib.util
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import types
import unittest
from unittest.mock import patch
import zipfile
sys.dont_write_bytecode = True
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'Tools'))
sys.path.insert(0, str(ROOT / 'scripts'))
import ruen_dependencies as deps
import build_release
def load_setup(bundle):
loader = importlib.machinery.SourceFileLoader('ruen_setup', str(bundle / 'Ruen-Setup'))
spec = importlib.util.spec_from_loader(loader.name, loader)
module = importlib.util.module_from_spec(spec); loader.exec_module(module)
module.closed = lambda root: None # Fake install must not interact with running games.
module.CONFIG = bundle.parent / 'install.json'
return module
def fingerprint(root):
return {p.relative_to(root).as_posix(): deps.digest(p) for p in root.rglob('*') if p.is_file()
and 'Ruen-UI-Backups' not in p.parts and p.name != '.ruen-install.lock'}
class InstallerTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix='ruen-release-test-')
self.base = Path(self.temp.name); self.bundle = self.base / 'bundle'
self.game = self.base / 'game/_forever_'; self.game.mkdir(parents=True)
(self.game / 'Wow.exe').write_bytes(b'fixture')
self.cache = self.base / 'cache'; self.cache.mkdir()
for name, data in build_release.payload().items():
p = self.bundle / name; p.parent.mkdir(parents=True, exist_ok=True); p.write_bytes(data)
lock = json.loads((self.bundle / 'dependencies.lock.json').read_text())
for package in lock['packages']:
archive = self.base / 'fixture.zip'
with zipfile.ZipFile(archive, 'w') as z:
for name in package['folders']:
z.writestr(name + '/' + name + '.toc', '## Interface: 16001\n')
z.writestr(name + '/fixture.lua', '-- upstream fixture\n')
package['sha256'] = deps.digest(archive); package['bytes'] = archive.stat().st_size
package['max_unpacked_bytes'] = 10000
package['url'] = 'https://127.0.0.1:1/not-a-real-download'
shutil.copy2(archive, self.cache / (package['id'] + '-' + package['sha256'][:12] + '.zip'))
(self.bundle / 'dependencies.lock.json').write_text(json.dumps(lock))
self.seal()
self.account = self.game / 'WTF/Account/TEST'
self.character = self.account / 'Realm/Character'; self.character.mkdir(parents=True)
for p, text in [(self.account / 'bindings-cache.wtf', 'bind F1 ORIGINAL\n'),
(self.character / 'AddOns.txt', 'Unrelated: enabled\nRuenUI: disabled\n'),
(self.account / 'SavedVariables/Spoken.lua', 'custom = "keep me"\n')]:
p.parent.mkdir(parents=True, exist_ok=True); p.write_text(text)
unrelated = self.game / 'Interface/AddOns/Unrelated/hello.lua'
unrelated.parent.mkdir(parents=True); unrelated.write_text('-- untouched')
self.original = fingerprint(self.game)
self.setup = load_setup(self.bundle)
self.args = types.SimpleNamespace(cache=str(self.cache), voice_packs='none', language='auto')
def tearDown(self): self.temp.cleanup()
def seal(self):
data = {p.relative_to(self.bundle).as_posix(): p.read_bytes() for p in self.bundle.rglob('*') if p.is_file() and p.name != 'manifest.json'}
(self.bundle / 'manifest.json').write_bytes(build_release.manifest(data))
def test_linux_install_repeat_preserve_and_restore(self):
self.setup.verify(self.bundle); self.setup.install(self.game, self.args)
self.assertEqual((self.account / 'SavedVariables/Spoken.lua').read_text(), 'custom = "keep me"\n')
backups = list((self.game / 'Ruen-UI-Backups').iterdir()); self.assertEqual(len(backups), 1)
report = self.game / 'Interface/AddOns/RuenUI/HardwareProfile.lua'
report.write_text('-- this laptop only\n')
self.setup.install(self.game, self.args)
self.assertEqual(len(list((self.game / 'Ruen-UI-Backups').iterdir())), 1)
self.assertEqual(report.read_text(), '-- this laptop only\n')
(self.account / 'bindings-cache.wtf').write_text('bind F1 NEW\n')
self.setup.restore(self.game, backups[0])
self.assertEqual(fingerprint(self.game), self.original)
def test_linux_reject_missing_backup_before_mutation(self):
self.setup.install(self.game, self.args)
backup = next((self.game / 'Ruen-UI-Backups').iterdir())
(backup / 'original/WTF/Account/TEST/bindings-cache.wtf').unlink()
before = fingerprint(self.game)
with self.assertRaises(ValueError): self.setup.restore(self.game, backup)
self.assertEqual(fingerprint(self.game), before)
def test_tampered_package(self):
(self.bundle / 'RuenUI/Core.lua').write_text('-- corrupted')
with self.assertRaises(ValueError): self.setup.verify(self.bundle)
self.assertEqual(fingerprint(self.game), self.original)
def test_incompatible_dependency(self):
folder = self.game / 'Interface/AddOns/Spoken'; folder.mkdir()
(folder / 'Spoken.toc').write_text('## Interface: 120000\n')
before = fingerprint(self.game)
with self.assertRaises(ValueError): self.setup.install(self.game, self.args)
self.assertEqual(fingerprint(self.game), before)
def test_download_failure_has_no_game_changes(self):
for path in self.cache.glob('*.zip'): path.unlink()
with self.assertRaises(Exception): self.setup.install(self.game, self.args)
self.assertEqual(fingerprint(self.game), self.original)
self.assertFalse(list(self.cache.glob('*.part')))
def test_partial_install_rolls_back(self):
original_copy = self.setup.copy
failed = False
def fail_once(src, dst):
nonlocal failed
if Path(dst) == self.game / 'Interface/AddOns/Spoken' and not failed:
failed = True
Path(dst).mkdir(); (Path(dst) / 'partial.lua').write_text('partial')
raise OSError('simulated disk write failure')
return original_copy(src, dst)
with patch.object(self.setup, 'copy', side_effect=fail_once), self.assertRaises(OSError):
self.setup.install(self.game, self.args)
self.assertTrue(failed)
self.assertEqual(fingerprint(self.game), self.original)
def test_parallel_install_lock(self):
with self.setup.locked(self.cache / '.install.lock'):
with self.assertRaises(RuntimeError): self.setup.install(self.game, self.args)
self.assertEqual(fingerprint(self.game), self.original)
def test_dependency_links_are_rejected(self):
(self.game / 'Interface/AddOns/Spoken').symlink_to(self.base / 'outside', target_is_directory=True)
with self.assertRaises(ValueError): self.setup.install(self.game, self.args)
def test_legacy_migration_and_restore(self):
old = self.account / 'SavedVariables/BradStockUI.lua.bak'; old.write_text('BradStockUIDB = {}\n')
before = fingerprint(self.game)
self.setup.install(self.game, self.args)
self.assertFalse(old.exists())
self.assertIn('RuenUIDB', (old.parent / 'RuenUI.lua.bak').read_text())
self.setup.restore(self.game, next((self.game / 'Ruen-UI-Backups').iterdir()))
self.assertEqual(fingerprint(self.game), before)
@unittest.skipUnless(os.environ.get('RUEN_PWSH'), 'Set RUEN_PWSH for PowerShell fixture tests')
def test_powershell_install_repeat_restore_and_integrity(self):
def run(*args, success=True):
r = subprocess.run([os.environ['RUEN_PWSH'], '-NoLogo', '-NoProfile', '-File', str(self.bundle / 'Install-Ruen-UI.ps1'), '-NonInteractive', *args], capture_output=True, text=True)
self.assertEqual(r.returncode == 0, success, r.stdout + r.stderr)
return r
install_args = ('-WoWPath', str(self.game), '-VoicePacks', 'none', '-CachePath', str(self.cache))
run(*install_args)
self.assertEqual((self.account / 'SavedVariables/Spoken.lua').read_text(), 'custom = "keep me"\n')
backups = list((self.game / 'Ruen-UI-Backups').iterdir()); self.assertEqual(len(backups), 1)
report = self.game / 'Interface/AddOns/RuenUI/HardwareProfile.lua'; report.write_text('-- retain report\n')
run(*install_args)
self.assertEqual(len(list((self.game / 'Ruen-UI-Backups').iterdir())), 1)
(self.account / 'bindings-cache.wtf').write_text('changed')
run('-Restore', '-BackupPath', str(backups[0]))
self.assertEqual(fingerprint(self.game), self.original)
(self.bundle / 'RuenUI/Core.lua').write_text('-- corrupt')
run(*install_args, success=False)
self.assertEqual(fingerprint(self.game), self.original)
@unittest.skipUnless(os.environ.get('RUEN_PWSH'), 'Set RUEN_PWSH for PowerShell fixture tests')
def test_powershell_failed_download_and_incomplete_restore(self):
def run(*args):
return subprocess.run([os.environ['RUEN_PWSH'], '-NoLogo', '-NoProfile', '-File', str(self.bundle / 'Install-Ruen-UI.ps1'), '-NonInteractive', *args], capture_output=True, text=True)
args = ('-WoWPath', str(self.game), '-VoicePacks', 'none', '-CachePath', str(self.cache))
missing = next(self.cache.glob('Leatrix_Plus-*.zip')); archive = missing.read_bytes(); missing.unlink()
r = run(*args); self.assertNotEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertEqual(fingerprint(self.game), self.original)
missing.write_bytes(archive)
r = run(*args); self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
backup = next((self.game / 'Ruen-UI-Backups').iterdir())
(backup / 'original/WTF/Account/TEST/bindings-cache.wtf').unlink()
before = fingerprint(self.game)
r = run('-Restore', '-BackupPath', str(backup)); self.assertNotEqual(r.returncode, 0)
self.assertEqual(fingerprint(self.game), before)
@unittest.skipUnless(os.environ.get('RUEN_PWSH'), 'Set RUEN_PWSH for PowerShell fixture tests')
def test_powershell_archive_path_checks(self):
# Dot-source the helper only; each invalid path must fail without touching disk.
script = ". '" + str(self.bundle / 'Tools/Resolve-RuenDependencies.ps1') + "'; "
script += "foreach ($p in @('../escape','/absolute','C:/file','a/../b','a\\b','NUL.txt','a:stream','a./file','a//b')) { $caught=$false; try { Get-RuenArchivePath $p > $null } catch { $caught=$true }; if (-not $caught) { throw ('Accepted: '+$p) } }; Write-Output 'PASS'"
r = subprocess.run([os.environ['RUEN_PWSH'], '-NoProfile', '-Command', script], capture_output=True, text=True)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
class ArchiveTests(unittest.TestCase):
def test_unsafe_paths(self):
for name in ('../escape', '/absolute', 'C:/file', 'a/../b', 'a\\b', 'NUL.txt', 'a:stream', 'a./file', 'a//b'):
with self.subTest(name=name), self.assertRaises(ValueError): deps.safe_relative(name)
def test_archive_case_collision_and_traversal(self):
with tempfile.TemporaryDirectory() as d:
root = Path(d); archive = root / 'fixture.zip'; stage = root / 'stage'; stage.mkdir()
p = {'folders': ['Spoken'], 'max_unpacked_bytes': 1000}
for entries in [('Spoken/a', 'Spoken/A'), ('Spoken/a', '../escape')]:
with zipfile.ZipFile(archive, 'w') as z:
for entry in entries: z.writestr(entry, 'x')
with self.assertRaises(ValueError): deps.extract(p, archive, stage)
self.assertFalse(list(stage.rglob('*')))
if __name__ == '__main__': unittest.main()