Compare commits

...

10 Commits

35 changed files with 2454 additions and 432 deletions

View File

@ -1,4 +1,4 @@
Ruen UI - ESDF key map (2026.11.21.5-beta.1)
Ruen UI - ESDF key map (2026.11.22.6-beta.1)
MOVEMENT
Q W [E] R T
@ -29,10 +29,15 @@ are preserved during setup. Ruen manages bar positions; duplicate its Edit Mode
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.
Right group: bottom bar = numbers (utility profile) or Ctrl + numbers (pet profile);
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.
Hunter/Warlock default to the pet profile: plain 1–0 controls the ten native pet
slots; - and = activate the two extensions. Other classes default to the utility
profile: pet controls use Ctrl+1–0, Ctrl+- and Ctrl+=.
/ruen keys auto|pet|utility selects a per-character profile. Native vehicle and
possession controls take priority. Pet death/dismissal and forms do not remap keys.
The two extra buttons fill with eligible missing active pet abilities 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.
@ -49,7 +54,7 @@ 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)
1..0 Pet controls on Hunter/Warlock; utility actions on other classes
U Interact with target
Shift+U Assist target (select its target)
Ctrl+Shift+U Select your target's target's target, when present
@ -98,7 +103,7 @@ 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.
ESDF is preserved. Alt is now the fourth combat row, not a forced-self-cast modifier. F1-F5 retains party targeting; number keys follow the character profile.
BAG WINDOW
Combined inventory opens to the left of the right-side quest/utility column,
@ -116,7 +121,7 @@ LANGUAGE AND HELP
/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.
/ruen bindings Deliberately reapply mouse/menu and utility mappings.
English/Russian full names and enUS/ruRU also work. Spoken and Spoken_Quests are
required dependencies. Narration changes the active Spoken profile immediately;
@ -151,14 +156,26 @@ languages must be downloaded through Battle.net. See docs/INSTALL.md for command
TIMERS AND OPTIMIZATION
/ruen swing on|off|preview
/ruen optimize [world|raid|pause|resume|status|restore]
/ruen optimize [FPS] — measure/tune the current area; 60 by default, then remembers your target.
/ruen optimize [world|dungeon|raid|battleground] [FPS]
/ruen optimize pause|resume|status|changes|restore
/ruen bench [pause|resume|stop|status] — every-frame timings, worst hitch and 1% low.
Hardware evaluation: Ruen-Setup.exe --optimize (Windows), ./Ruen-Setup --optimize (Linux).
See docs/INSTALL.md for the measured world/raid calibration workflow.
See docs/INSTALL.md. Keep WoW focused during measurement; pause before switching apps.
Quality changes print actual before/after values; status shows progress/waits.
/ruen optimize changes repeats the latest applied/final change summary.
World, dungeon, raid and battleground profiles learn separately. Run optimize again
in a troublesome area. Settings change outside combat; there is no idle sampling.
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.
/ruen role auto|healer|tank|damage selects the role used by auto mouseover.
Auto uses a reliable native specialization/assigned role when available; only
HEALER enables mouseover. Unknown roles remain off. Explicit on/off wins.
Upgrades preserve the old effective mouseover choice; selecting a role explicitly
opts into the new automatic behavior. Cooldown/meter modes are per character.
Fresh installs start with duplicate cooldown viewers off; upgrades retain choices.
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.
@ -166,7 +183,7 @@ 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
Pet extras (-/=, or Ctrl+-/= with the utility profile): 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.
@ -174,3 +191,12 @@ 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.
LAYOUT RECOVERY (outside combat, with Edit Mode closed)
/ruen chat reset Restore readable, screen-sized chat; reposition nearby bars.
/ruen layout reset Reset all native Edit Mode positions, Ruen controls and
supported bundled windows (Spoken/Compendium/world map).
Bags/tooltips/alerts reflow; unsupported resets are listed.
Both save the active Ruen layout; graphics, bindings and placed abilities stay.
Other characters using this same layout see the saved geometry too.
/reload loads updated code; it does not undo saved layout edits.

View File

@ -4,7 +4,7 @@ A compact, class-aware **WoW: Forever** interface with ESDF controls, English/Ru
**[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.
Choose **Ruen-UI-2026.11.22.6-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
@ -19,18 +19,23 @@ Ruen changes movement to **E forward, D backward, S/F strafe**. Turn using the r
## 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.
- Per-character number-key profiles: Hunters/Warlocks use numbers for pets; other classes use numbers for utility actions. `/ruen keys auto|pet|utility` changes this without rewriting account bindings.
- Native forms, stances, totems, casting and pet controls. A centered pet row adds two configurable extra pet actions on **-** and **=** (Ctrl-modified with the utility profile) when spare native action slots are available. These are extensions of the native ten-slot bar, not additional native pet slots.
- 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.
- Optional native cooldown displays and role-based 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.
- On-demand graphics calibration for world/dungeon/raid/battleground play, with a configurable FPS target and explicit hitch checks. 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).
See the [staged update checklist](docs/UPDATE-PLAN.md) for implementation and release gates.
## 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.
Installer transaction tests, Lua regressions, source review and local gameplay checks inform this release. The user verified the beta8 pet selected-state fix in game across native and extra stance buttons. **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.
A focused local follow-up showed worse low-FPS readings than the baseline; performance verification remains open. `/ruen bench` now records every gameplay frame, brief hitches, worst-frame time and slowest-1% FPS, plus native addon CPU diagnostics. `/ruen optimize 60` retunes the area you are playing in; use `30` for a lower target. See the [measurement workflow](docs/INSTALL.md#optional-optimization).
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.

169
RuenUI/Benchmark.lua Normal file
View File

@ -0,0 +1,169 @@
local _, P = ...
-- Read the client's already-running profiler only during /ruen bench.
-- Frame recording is bounded and manual; no scriptProfile or graphics edits.
local fields = {"gxApi", "gxAdapter", "RenderScale", "maxFPS", "maxFPSBk", "vsync",
"useTargetFPS", "graphicsShadowQuality", "graphicsSSAO", "graphicsViewDistance",
"graphicsEnvironmentDetail", "graphicsGroundClutter", "graphicsComputeEffects",
"graphicsLightMode", "graphicsPBRLiquidDetail", "graphicsLiquidDetail", "RAIDsettingsEnabled",
"graphicsParticleDensity", "graphicsSpellDensity", "graphicsProjectedTextures",
"graphicsDepthEffects", "graphicsTextureResolution", "MSAAQuality", "msaaAlphaTest", "ffxAntiAliasingMode"}
local counters = {"CountTimeOver1Ms", "CountTimeOver5Ms", "CountTimeOver10Ms", "CountTimeOver50Ms"}
local function number(fn, ...)
if type(fn) ~= "function" then return end
local ok, value = pcall(fn, ...)
if ok and not (issecretvalue and issecretvalue(value)) and type(value) == "number"
and value == value and value >= 0 and value < math.huge then return value end
end
local function settings()
local result = {}
if C_CVar and C_CVar.GetCVar then
for _, key in ipairs(fields) do result[key] = C_CVar.GetCVar(key) end
end
if GetPhysicalScreenSize then result.width, result.height = GetPhysicalScreenSize() end
local optimizer = RuenUIDB.optimizer
if optimizer then
result.calibrationEnabled = optimizer.enabled
for _, mode in ipairs({"world", "dungeon", "raid", "battleground"}) do
local profile = optimizer.profiles and optimizer.profiles[mode]
if profile then result[mode.."Tier"] = profile.tier; result[mode.."Calibrated"] = profile.calibrated end
end
end
return result
end
local function metric(name)
local api, enum = C_AddOnProfiler, Enum and Enum.AddOnProfilerMetric
if not api or not enum or enum[name] == nil then return end
if api.IsEnabled then
local ok, enabled = pcall(api.IsEnabled)
if not ok or not enabled then return end
end
return number(api.GetAddOnMetric, "RuenUI", enum[name])
end
function P.StartBenchmarkDiagnostics()
local data = {release=P.release, settingsStart=settings(), samples={}, countersStart={}}
for _, name in ipairs(counters) do data.countersStart[name] = metric(name) end
return data
end
function P.SampleBenchmarkDiagnostics(data, fps, worstMS)
if #data.samples >= 180 then return end
local row = {fps=fps, worstFrameMS=worstMS, ruenRecentMS=metric("RecentAverageTime")}
if row.ruenRecentMS ~= nil and C_AddOnProfiler.GetOverallMetric then
row.allAddonsRecentMS = number(C_AddOnProfiler.GetOverallMetric, Enum.AddOnProfilerMetric.RecentAverageTime)
end
-- Keep the relevant neighbors on slow readings, not a scan of every addon.
if (fps < 30 or (worstMS or 0) > 50) and row.ruenRecentMS ~= nil and C_AddOnProfiler.GetTopKAddOnsForMetric then
local ok, top = pcall(C_AddOnProfiler.GetTopKAddOnsForMetric, Enum.AddOnProfilerMetric.RecentAverageTime, 3)
if ok and type(top) == "table" then row.topAddons = top end
end
data.samples[#data.samples+1] = row
end
local frame, capture
local function say(en, ru) print('|cff60d5ffRuen UI:|r '..P.Localized(en,ru or en)) end
function P.IsBenchmarkRunning() return capture ~= nil end
local function finishCapture(partial)
local c=capture
frame:SetScript('OnUpdate',nil); capture=nil
local r=P.FrameSampleSummary(c.sample)
r.time=time(); r.partial=partial or nil; r.diagnostics=c.diagnostics
r.excludedLoadingSeconds=c.excluded; r.focusVerified=false
r.note='Gameplay OnUpdate intervals; 1% low is reciprocal of mean slowest 1% frame time (0.25 ms bins). Loading excluded; window focus unverified.'
local cpuMessage=P.FinishBenchmarkDiagnostics(c.diagnostics)
RuenUIDB.reports=RuenUIDB.reports or {}
table.insert(RuenUIDB.reports,r)
while #RuenUIDB.reports>5 do table.remove(RuenUIDB.reports,1) end
if r.frames>0 then
say(('Frame bench%s: %.1f FPS avg; 1%% low %.1f FPS; p99 %.1f ms; worst %.1f ms. Frames >50/>100/>250 ms: %d/%d/%d over %.1f s.'):format(
partial and ' (partial)' or '',r.meanFPS,r.low1FPS,r.p99MS,r.worstMS,r.over50,r.over100,r.over250,r.seconds),
('Замер кадров%s: среднее %.1f FPS; 1%% low %.1f FPS; p99 %.1f мс; максимум %.1f мс. Кадров >50/>100/>250 мс: %d/%d/%d за %.1f с.'):format(
partial and ' (неполный)' or '',r.meanFPS,r.low1FPS,r.p99MS,r.worstMS,r.over50,r.over100,r.over250,r.seconds))
if r.histogramClipped then say('A stall exceeded 10 seconds: histogram percentiles are capped; worst-frame time is exact.') end
else say('Benchmark stopped without gameplay frames.','Замер остановлен без игровых кадров.') end
say(cpuMessage)
say('Saved on logout/reload. Loading is excluded; app switching is NOT detected. These frame times cannot identify network lag or prove GPU/thermal causes.',
'Сохранится при выходе или /reload. Загрузка исключена; переключение окон НЕ определяется. Замер не устанавливает причину сетевых задержек или перегрева.')
if P.OptimizerBenchmarkEnded then P.OptimizerBenchmarkEnded() end
end
local function update(_,dt)
local c=capture
if not c then return end
if c.paused then return end
if c.loading or c.settle>0 then
c.excluded=c.excluded+dt; c.settle=math.max(0,c.settle-dt); return
end
P.AddFrameSample(c.sample,dt)
c.interval=c.interval+dt; c.worst=math.max(c.worst,dt*1000)
if c.interval>=1 then
P.SampleBenchmarkDiagnostics(c.diagnostics,GetFramerate(),c.worst)
c.interval=0; c.worst=0
end
if c.sample.seconds>=180 then finishCapture() end
end
function P.BenchmarkCommand(arg)
arg=arg or ''
if arg=='status' then
say(capture and ('Benchmark '..(capture.paused and 'paused' or 'running')..': '..math.floor(capture.sample.seconds)..'/180 seconds recorded.') or 'No benchmark running.'); return
elseif arg=='stop' then
if capture then finishCapture(true) else say('No benchmark running.') end; return
elseif arg=='pause' or arg=='resume' then
if not capture then say('No benchmark running.'); return end
capture.paused=arg=='pause'; capture.settle=1
say(capture.paused and 'Benchmark paused.' or 'Benchmark resumed; keep WoW focused.'); return
elseif arg~='' then say('/ruen bench [pause|resume|stop|status]'); return end
if capture then say('A benchmark is already running.'); return end
if P.IsOptimizerCalibrating and P.IsOptimizerCalibrating() then
say('Let optimization finish, or /ruen optimize pause, before benchmarking.',
'Дождитесь окончания настройки или /ruen optimize pause перед замером.'); return
end
if not frame then
frame=CreateFrame('Frame')
frame:RegisterEvent('PLAYER_LEAVING_WORLD'); frame:RegisterEvent('PLAYER_ENTERING_WORLD')
frame:SetScript('OnEvent',function(_,event)
if capture then
capture.loading=event=='PLAYER_LEAVING_WORLD'; capture.settle=2
capture.sample.inHitch=false
end
end)
end
capture={sample=P.NewFrameSample(),diagnostics=P.StartBenchmarkDiagnostics(),interval=0,worst=0,excluded=0,settle=1}
frame:SetScript('OnUpdate',update)
say('Recording every gameplay frame for 3 minutes, including brief hitches. Keep WoW focused; /ruen bench pause before switching apps. No graphics changes.',
'Запись каждого кадра в течение 3 минут, включая короткие рывки. Не переключайте окно; перед переключением /ruen bench pause. Графика не изменяется.')
end
function P.FinishBenchmarkDiagnostics(data)
data.settingsEnd = settings()
data.settingsChanged = false
for key, value in pairs(data.settingsStart) do
if data.settingsEnd[key] ~= value then data.settingsChanged = true end
end
for key, value in pairs(data.settingsEnd) do
if data.settingsStart[key] ~= value then data.settingsChanged = true end
end
local total, count, maximum = 0, 0, 0
for _, row in ipairs(data.samples) do
if row.ruenRecentMS ~= nil then
total=total+row.ruenRecentMS; count=count+1; maximum=math.max(maximum,row.ruenRecentMS)
end
end
if count > 0 then data.sampledMeanMS=total/count; data.maxSampledRecentMS=maximum end
data.ticksOver = {}
for _, name in ipairs(counters) do
local before, after = data.countersStart[name], metric(name)
if before ~= nil and after ~= nil and after >= before then data.ticksOver[name] = after-before end
end
data.note = "Native recent metrics average the last 60 ticks; sampled about once/second. Threshold deltas cover this run's wall time (including pause/loading), not the whole login. Slow-frame correlation is not proof of causation."
local message
if data.sampledMeanMS then
local slow = data.ticksOver.CountTimeOver5Ms
message = string.format("Ruen CPU: sampled mean %.3f ms/tick; largest sampled recent average %.3f ms; ticks over 5 ms: %s.",
data.sampledMeanMS, data.maxSampledRecentMS, slow ~= nil and tostring(slow) or "unavailable")
else message = "Ruen CPU timing unavailable on this client; FPS alone cannot identify addon cost." end
if data.settingsChanged then message = message.." Graphics/calibration settings changed during this sample; comparison is inconclusive." end
return message
end

82
RuenUI/ButtonStyle.lua Normal file
View File

@ -0,0 +1,82 @@
local _, P = ...
-- Presentation only: never replace Blizzard's secure button mixins or scripts.
-- Modern action templates expose named regions even when a texture getter is
-- absent. Copying only the getter left the pet extensions with a generic glow.
local defaults = {
Normal = "UI-HUD-ActionBar-IconFrame",
Pushed = "UI-HUD-ActionBar-IconFrame-Down",
Highlight = "UI-HUD-ActionBar-IconFrame-Mouseover",
Checked = "UI-HUD-ActionBar-IconFrame-Mouseover",
}
local function region(frame, kind)
if not frame then return end
local getter = frame["Get" .. kind .. "Texture"]
-- The getter is the region the widget actually draws; a named XML region
-- may survive a later replacement. Older templates expose only the name.
return (type(getter) == "function" and getter(frame)) or frame[kind .. "Texture"]
end
function P.StyleActionButton(button, prototype)
for _, kind in ipairs({"Normal", "Pushed", "Highlight", "Checked"}) do
local source = region(prototype, kind)
local atlas = source and source:GetAtlas()
local texture = source and source:GetTexture()
if not atlas and not texture then atlas = defaults[kind] end
-- CheckButton has SetCheckedTexture, but not SetCheckedAtlas on this
-- client. Register a texture with the widget, then apply the atlas to
-- that texture. The atlas file ID alone renders the whole sprite sheet.
button["Set" .. kind .. "Texture"](button, texture or "Interface\\Buttons\\UI-Quickslot2")
local target = region(button, kind)
if target then
if atlas then target:SetAtlas(atlas) end
target:ClearAllPoints()
-- Native small buttons anchor the art at TOPLEFT, not CENTER.
-- Match its size relative to the icon at any pet/UI scale.
local point, relative, relativePoint, x, y
if source and source.GetPoint then point, relative, relativePoint, x, y = source:GetPoint(1) end
if point and (relative == prototype or relative == prototype.icon) then
local ratio = button:GetWidth() / prototype:GetWidth()
target:SetPoint(point, button, relativePoint, (x or 0) * ratio, (y or 0) * ratio)
else target:SetPoint("TOPLEFT", button, "TOPLEFT", 0, 0) end
local w, h = button:GetWidth(), button:GetHeight()
if source and prototype:GetWidth() > 0 and prototype:GetHeight() > 0 then
target:SetSize(source:GetWidth() / prototype:GetWidth() * w,
source:GetHeight() / prototype:GetHeight() * h)
-- SetAtlas owns the subregion coordinates. File-backed native
-- artwork still needs its explicit cropping copied.
if not atlas then target:SetTexCoord(source:GetTexCoord()) end
if source.GetBlendMode and target.SetBlendMode then target:SetBlendMode(source:GetBlendMode()) end
if source.GetDrawLayer and target.SetDrawLayer then target:SetDrawLayer(source:GetDrawLayer()) end
else target:SetSize(w * 46 / 45, h) end
-- Do not inherit the prototype's transient attack-flash alpha.
if target.SetAlpha then target:SetAlpha(1) end
end
end
if prototype and prototype.Flash then
local source = prototype.Flash
if not button.Flash then button.Flash = button:CreateTexture(nil, "OVERLAY"); button.Flash:Hide() end
local flash = button.Flash
if source:GetAtlas() and flash.SetAtlas then flash:SetAtlas(source:GetAtlas()) else flash:SetTexture(source:GetTexture()) end
flash:ClearAllPoints(); flash:SetPoint("TOPLEFT", button, "TOPLEFT", 0, 0)
flash:SetSize(source:GetWidth() / prototype:GetWidth() * button:GetWidth(),
source:GetHeight() / prototype:GetHeight() * button:GetHeight())
end
end
function P.SetActionButtonSelected(button, selected, attack)
-- Pass an engine value straight to the widget; do not inspect secret values.
button:SetChecked(selected)
local checked = region(button, "Checked")
if checked and checked.SetAlpha then checked:SetAlpha(attack and .5 or 1) end
if button.Flash and UIFrameFlash and UIFrameFlashStop then
local flashing = false
if not (issecretvalue and issecretvalue(selected)) then flashing = attack and selected or false end
if flashing ~= button.ruenAttackFlashing then
if flashing then UIFrameFlash(button.Flash, .5, .5, -1, false)
else UIFrameFlashStop(button.Flash); button.Flash:Hide() end
button.ruenAttackFlashing = flashing
end
end
end

View File

@ -0,0 +1,233 @@
local _, P = ...
local numbers = {"1","2","3","4","5","6","7","8","9","0","-","="}
local petClasses = {HUNTER=true, WARLOCK=true}
local healClasses = {PRIEST=true, PALADIN=true, SHAMAN=true, DRUID=true}
local owner, listener, queued, signature
local effective, hooked = {}, {}
-- Executed by SecureHandlerStateTemplate, including transitions IN combat.
-- Never intercept native vehicle/possession/override controls. Ordinary rogue
-- stealth and druid forms keep the same utility keys and native main-bar paging.
local bindingSnippet = [[
self:ClearBindings()
if self:GetAttribute("state-ruencontrols") == "normal" then
for i = 1, self:GetAttribute("bindingCount") or 0 do
self:SetBinding(false, self:GetAttribute("key"..i), self:GetAttribute("action"..i))
end
end
]]
local conditions = "[vehicleui][overridebar][possessbar] special; normal"
function P.EnsureCharacterProfile()
if not RuenUICharacter or not RuenUIDB then return end
if RuenUICharacter.profileVersion == 1 then return end
-- Older releases recorded these shared migrations separately. Establish
-- their ownership before any fresh-character setup can replay them.
if not RuenUIDB.combatBindingsVersion and RuenUIDB.extraBindingsVersion == 1 and RuenUIDB.controlsVersion == 1 then
RuenUIDB.combatBindingsVersion = 2
end
-- Preserve the EFFECTIVE old modes, including explicit off. Fresh installs
-- start without duplicate cooldown icons; upgrades retain their choice.
RuenUICharacter.cooldownsMode = RuenUICharacter.cooldownsMode or RuenUIDB.cooldownsMode
or (RuenUICharacter.version and "auto" or "off")
RuenUICharacter.damageMeterMode = RuenUICharacter.damageMeterMode or RuenUIDB.damageMeterMode or "auto"
if (not RuenUICharacter.mouseoverMode or RuenUICharacter.mouseoverMode == "auto") and RuenUICharacter.version then
local old = RuenUICharacter.mouseoverApplied
local _, class = UnitClass("player")
local enabled = old and old.enabled
if enabled == nil then enabled = healClasses[class] or false end
local identity = (UnitGUID and UnitGUID("player")) or (UnitName("player")..":"..class)
if RuenUIDB.mouseoverLastCharacter == identity and C_CVar and C_CVar.GetCVar then
local current = C_CVar.GetCVar("enableMouseoverCast")
if current == "0" or current == "1" then enabled = current == "1" end
end
RuenUICharacter.mouseoverMode = enabled and "on" or "off"
end
RuenUICharacter.profileVersion = 1
end
function P.NumberProfile()
local preference = RuenUICharacter and RuenUICharacter.numberProfile
if preference == "pet" or preference == "utility" then return preference end
local _, class = UnitClass("player")
return petClasses[class] and "pet" or "utility"
end
function P.CharacterRole()
local role = RuenUICharacter and RuenUICharacter.rolePreference
if role == "HEALER" or role == "TANK" or role == "DAMAGER" then return role end
role = nil
if GetSpecialization and GetSpecializationRole then
local spec = GetSpecialization()
if spec then role = GetSpecializationRole(spec) end
end
if not role or role == "NONE" then role = UnitGroupRolesAssigned and UnitGroupRolesAssigned("player") end
if role == "HEALER" or role == "TANK" or role == "DAMAGER" then return role end
return "UNKNOWN" -- never infer a healing input scheme from class or form
end
local petSeen = {}
function P.NeedsPetRow()
local _, class = UnitClass("player")
if petClasses[class] or P.NumberProfile() == "pet" then return true end
local identity = (UnitGUID and UnitGUID("player")) or class
local spec = GetSpecialization and GetSpecialization() or 0
local key = tostring(identity)..":"..tostring(spec)
local shown = PetActionBar and PetActionBar:IsShown()
if shown and UnitExists and UnitExists("pet") then petSeen[key] = true end
-- Keep the acquired row stable through dismissal/death this session. A
-- petless Mage does not reserve it merely because of its class name.
return shown or petSeen[key] or false
end
function P.EffectiveBindingKey(action)
for _, key in ipairs(effective[action] or {}) do
if GetBindingAction(key, true) == action then return key end
end
for _, key in ipairs({GetBindingKey(action)}) do
if GetBindingAction(key, true) == action then return key end
end
end
local function label(button, action)
if not button or not button.HotKey then return end
local key = P.EffectiveBindingKey(action)
button.HotKey:SetText(key and GetBindingText(key, true) or "")
if key then button.HotKey:Show() else button.HotKey:Hide() end
end
function P.RefreshProfileHotkeys()
for i = 1, 12 do
local entries = {{_G["MultiBarLeftButton"..i], "MULTIACTIONBAR4BUTTON"..i, "UpdateHotkeys"}}
if i <= 10 then entries[#entries+1] = {_G["PetActionButton"..i], "BONUSACTIONBUTTON"..i, "SetHotkeys"}
else entries[#entries+1] = {_G["RuenPetExtraButton"..i], "CLICK RuenPetExtraButton"..i..":LeftButton"} end
for _, entry in ipairs(entries) do
local button, action, method = unpack(entry)
if button and not hooked[button] and method and type(button[method]) == "function" then
hooksecurefunc(button, method, function() label(button, action) end)
hooked[button] = true
end
label(button, action)
end
end
end
function P.ClearCharacterBindings()
if InCombatLockdown() then return false end
if owner then
UnregisterStateDriver(owner, "ruencontrols")
owner:SetAttribute("bindingCount", 0)
owner:Execute(bindingSnippet)
end
effective, signature = {}, nil
P.RefreshProfileHotkeys()
return true
end
function P.ApplyCharacterBindings(force)
if InCombatLockdown() then return false end
if not RuenUICharacter or not RuenUIDB then return false end
if RuenUIDB.disabled then return P.ClearCharacterBindings() end
P.EnsureCharacterProfile()
if not RegisterStateDriver or not UnregisterStateDriver then
RuenUICharacter.numberProfileStatus = "secure binding support unavailable"
return false
end
if not owner then
owner = CreateFrame("Frame", "RuenCharacterBindings", UIParent, "SecureHandlerStateTemplate")
owner:SetAttribute("_onstate-ruencontrols", bindingSnippet)
owner:HookScript("OnAttributeChanged", function(_, key)
if key == "state-ruencontrols" then P.RefreshProfileHotkeys() end
end)
end
local records = RuenUICharacter.numberBindingBases or {}
RuenUICharacter.numberBindingBases = records
local scope = GetCurrentBindingSet() == 1 and RuenUIDB or RuenUICharacter
local profile, wanted, parts, conflicts = P.NumberProfile(), {}, {}, {}
effective = {}
for i, number in ipairs(numbers) do
local pet = i <= 10 and "BONUSACTIONBUTTON"..i or "CLICK RuenPetExtraButton"..i..":LeftButton"
local utility = "MULTIACTIONBAR4BUTTON"..i
for _, entry in ipairs({{number, profile == "pet" and pet or utility, pet},
{"CTRL-"..number, profile == "pet" and utility or pet, utility}}) do
local key, action, oldDefault = unpack(entry)
local base = GetBindingAction(key) or ""
local record = records[key]
local change = RuenUICharacter.bindingChanges and RuenUICharacter.bindingChanges[key]
if not record or force then
record = {base=base, managed=force or base == "" or
(change and change.applied == base) or (scope.petBindingsVersion == 2 and base == oldDefault) or false}
records[key] = record
elseif record.base ~= base then
record.base, record.managed = base, false -- later user edits win
end
if record.managed then
wanted[#wanted+1] = {key, action}
parts[#parts+1] = key.."="..action
effective[action] = effective[action] or {}
effective[action][#effective[action]+1] = key
else conflicts[#conflicts+1] = key end
end
end
local nextSignature = table.concat(parts, ";")
if signature ~= nextSignature then
owner:SetAttribute("bindingCount", #wanted)
for i, entry in ipairs(wanted) do
owner:SetAttribute("key"..i, entry[1]); owner:SetAttribute("action"..i, entry[2])
end
RegisterStateDriver(owner, "ruencontrols", conditions)
owner:Execute(bindingSnippet)
signature = nextSignature
end
RuenUICharacter.numberProfileStatus = profile
RuenUICharacter.numberBindingConflicts = conflicts
P.RefreshProfileHotkeys()
return true
end
function P.CharacterProfileSummary()
return P.Localized("Numbers: ", "Цифры: ")..P.NumberProfile()
..P.Localized("; role: ", "; роль: ")..P.CharacterRole()
..P.Localized("; custom keys preserved: ", "; сохранены свои клавиши: ")
..table.concat(RuenUICharacter.numberBindingConflicts or {}, ", ")
end
function P.CharacterProfileCommand(command, argument)
P.EnsureCharacterProfile()
if command == "keys" and (argument == "auto" or argument == "pet" or argument == "utility") then
RuenUICharacter.numberProfile = argument
elseif command == "role" then
local roles = {auto="auto", healer="HEALER", tank="TANK", damage="DAMAGER"}
if roles[argument] then
RuenUICharacter.rolePreference = roles[argument]
RuenUICharacter.mouseoverMode = "auto"
P.mouseoverPending = true
end
end
P.ApplyCharacterBindings(false)
if P.ApplyMouseover then P.ApplyMouseover() end
if P.RefreshClassAssist then P.RefreshClassAssist() end
return P.CharacterProfileSummary()..P.Localized(
". /ruen keys auto|pet|utility; /ruen role auto|healer|tank|damage. Changes wait until combat ends.",
". /ruen keys auto|pet|utility; /ruen role auto|healer|tank|damage. Изменения применяются после боя.")
end
function P.InitializeCharacterProfiles()
P.EnsureCharacterProfile()
if listener then return end
listener = CreateFrame("Frame")
for _, event in ipairs({"UPDATE_BINDINGS", "PLAYER_REGEN_ENABLED", "PLAYER_ENTERING_WORLD",
"PLAYER_SPECIALIZATION_CHANGED", "GROUP_ROSTER_UPDATE", "PLAYER_ROLES_ASSIGNED"}) do
pcall(listener.RegisterEvent, listener, event)
end
listener:SetScript("OnEvent", function()
if queued then return end
queued = true
C_Timer.After(.1, function()
queued = false
if RuenUIDB.disabled then P.ClearCharacterBindings(); return end
P.ApplyCharacterBindings(false)
if P.ApplyMouseover then P.ApplyMouseover() end
end)
end)
end

View File

@ -4,7 +4,6 @@ local _, P = ...
-- 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
@ -17,7 +16,7 @@ local function settingsOpen()
end
local function mode()
return RuenUIDB.cooldownsMode or "auto"
return RuenUICharacter.cooldownsMode or RuenUIDB.cooldownsMode or "auto"
end
local function set(system, key, value)
@ -152,12 +151,13 @@ function P.ApplyMouseover(force)
end
local _, class = UnitClass("player")
local preference = RuenUICharacter.mouseoverMode or "auto"
local enabled = preference == "on" or (preference == "auto" and healers[class]) or false
local role = P.CharacterRole()
local enabled = preference == "on" or (preference == "auto" and role == "HEALER") 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
if not force and previous and previous.class == class and previous.mode == preference and previous.role == role
and RuenUIDB.mouseoverLastCharacter == character then
-- A deliberate later change in Options is respected, even after reload.
RuenUICharacter.mouseoverStatus = current == "1" and "on" or "off"
@ -176,7 +176,7 @@ function P.ApplyMouseover(force)
Settings.SetValue("MOUSEOVERCAST", old)
else SetModifiedClick("MOUSEOVERCAST", old) end
end
RuenUICharacter.mouseoverApplied = {class=class, mode=preference, enabled=enabled}
RuenUICharacter.mouseoverApplied = {class=class, role=role, mode=preference, enabled=enabled}
RuenUIDB.mouseoverLastCharacter = character
P.mouseoverPending = nil
RuenUICharacter.mouseoverStatus = enabled and "on" or "off"
@ -265,6 +265,11 @@ local function refresh()
end
end
function P.ResetClassAssistLayoutState()
appliedContext = nil
P.classAssistReserved = {}
end
function P.RefreshClassAssist()
if busy or not owns then return end
if InCombatLockdown() then return end -- native code handles combat visibility
@ -296,7 +301,7 @@ function P.ClassAssistCommand(command, argument)
if argument == "settings" and CooldownViewerSettings and not InCombatLockdown() then
CooldownViewerSettings:ShowUIPanel()
elseif argument == "auto" or argument == "show" or argument == "off" then
RuenUIDB.cooldownsMode = argument
RuenUICharacter.cooldownsMode = argument
P.RefreshClassAssist()
end
return P.Localized("Cooldowns: ","Перезарядки: ") .. mode() .. P.Localized(

View File

@ -2,7 +2,7 @@ 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.classLayoutVersion = 8
P.petIconSize = 8 -- native 130%: pet icons now nearly match the combat buttons
P.classFrameNames = {
"PartyFrame", "CompactRaidFrameContainer",
@ -37,8 +37,7 @@ local function makePlan(base)
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")
local petActive = P.NeedsPetRow()
-- 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
@ -50,12 +49,14 @@ local function makePlan(base)
}
-- 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}
-- Measure each occupied row. A 30-unit minimum inflated native 24-unit
-- stance/aspect rows, needlessly pushing pets, casts and group frames up.
local rows, row = {}, {width = 0, height = 0}
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
rows[#rows + 1] = row; row = {width = 0, height = 0}; gap = 0
end
row[#row + 1] = group
row.width = row.width + gap + group.width
@ -172,6 +173,10 @@ function P.MigrateClassLayout()
end
local widgetBaseScale,widgetAppliedScale
function P.ResetClassLayoutState()
widgetBaseScale, widgetAppliedScale = 1, nil
end
function P.PositionEncounterWidgets(place,edge)
local f=UIWidgetTopCenterContainerFrame
if not f then return end

View File

@ -105,6 +105,8 @@ end
function P.Help()
say(P.BarHelp())
say(P.Localized("/ruen role auto|healer|tank|damage: mouseover default follows the selected role. /ruen mouseover on|off overrides it. Cooldown and meter modes are per character.",
"/ruen role auto|healer|tank|damage: наведение зависит от выбранной роли. /ruen mouseover on|off задаёт свой режим. Перезарядки и счётчики настраиваются для каждого персонажа."))
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.",
@ -112,7 +114,7 @@ function P.Help()
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 optimize [FPS]: retune this area (default 60 or your saved target). optimize pause|resume|status|changes|restore. /ruen bench: frame times and hitches.","/ruen optimize [FPS]: настройка текущей зоны (60 или сохранённая цель). optimize pause|resume|status|changes|restore. /ruen bench: время кадров и рывки."))
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.")
@ -124,7 +126,9 @@ function P.Help()
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.")
say(P.Localized("/ruen chat reset: restore chat size/position. /ruen layout reset: reset native UI, Ruen and bundled window positions; keep graphics, keys and assigned abilities.",
"/ruen chat reset: сброс размера и положения чата. /ruen layout reset: сброс положения стандартных элементов, Ruen и окон комплекта; графика, клавиши и способности сохраняются."))
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 reapplies gameplay/key defaults and selects the saved Ruen layout.")
end
local aliases = {en = "enUS", english = "enUS", enus = "enUS", ru = "ruRU", russian = "ruRU", ruru = "ruRU"}

View File

@ -1,6 +1,5 @@
local _, P = ...
local frame = CreateFrame("Frame")
local ticker
local function say(s) print("|cff60d5ffRuen UI:|r " .. P.Translate(s)) end
local function init()
RuenUIDB = RuenUIDB or {original = {}, reports = {}}
@ -8,6 +7,7 @@ local function init()
RuenUIDB.reports = RuenUIDB.reports or {}
RuenUICharacter = RuenUICharacter or {original = {}}
RuenUICharacter.original = RuenUICharacter.original or {}
P.EnsureCharacterProfile()
end
-- Merge the narration profile once, preserving unrelated settings and live AceDB references.
local function mergePreferences(target, values)
@ -174,8 +174,14 @@ local function setupThirdTarget()
RegisterUnitWatch(f)
end
local function applyCombatBindings()
local function applyCombatBindings(force)
if InCombatLockdown() then error("leave combat before applying bindings") end
local scope = GetCurrentBindingSet() == 1 and RuenUIDB or RuenUICharacter
if not force and (scope.combatBindingsVersion == 2 or (GetCurrentBindingSet() == 2 and scope.bindingsVersion == 2)) then
RuenUICharacter.bindingsVersion = 2
P.ApplyUtilityBindings(false)
return false
end
RuenUICharacter.bindingChanges = RuenUICharacter.bindingChanges or {}
local changes = RuenUICharacter.bindingChanges
local function bind(key, action)
@ -224,7 +230,9 @@ local function applyCombatBindings()
bind("CTRL-I", "SITORSTAND"); bind("SHIFT-I", "TOGGLESHEATH")
SaveBindings(GetCurrentBindingSet())
RuenUICharacter.bindingsVersion = 2
scope.combatBindingsVersion = 2
P.ApplyUtilityBindings(true)
return true
end
local function restoreCombatBindings()
@ -299,18 +307,33 @@ local function placeRelative(f, point, relative, relativePoint, x, y)
set(f, point, UIParent, "BOTTOMLEFT", (rx + x) / scale, (ry + y) / scale)
end
local chatBaseWidth,chatAppliedWidth
local chatBaseWidth,chatAppliedWidth,chatAppliedHeight,chatUsesDefaults
local function fitChat()
local chat=ChatFrame1
if not chat or not MainActionBar then return end
local current=chat:GetWidth()
if not chatBaseWidth or (chatAppliedWidth and math.abs(current-chatAppliedWidth)>.5) then chatBaseWidth=current end
local current,height=chat:GetWidth(),chat:GetHeight()
local left=frameEdge(chat,"GetLeft") or 20
local right=frameEdge(MainActionBar,"GetLeft")
if not right then return end
local width=math.min(chatBaseWidth,math.max(240,(right-left-16)/uiRatio(chat)))
local saved=RuenUIDB.chatDefaultSize
-- Native layout activation restores the saved size; our last fitted size
-- instead survives a display change. Both still represent an untouched
-- default. Any other size/anchor belongs to the player's manual edit.
local function same(w,h) return w and h and math.abs(current-w)<.5 and math.abs(height-h)<.5 end
local defaultLeft,defaultBottom=P.DefaultChatOrigin()
chatUsesDefaults=P.IsDefaultChatSystem(chat.systemInfo) and math.abs(left-defaultLeft)<.5
and math.abs((frameEdge(chat,"GetBottom") or 0)-defaultBottom)<.5
and (same(saved.width,saved.height) or (chatUsesDefaults and same(chatAppliedWidth,chatAppliedHeight)))
if chatUsesDefaults then
chatBaseWidth,height=P.DefaultChatSize()
if math.abs(chat:GetHeight()-height)>.5 then chat:SetHeight(height) end
elseif not chatBaseWidth or (chatAppliedWidth and math.abs(current-chatAppliedWidth)>.5) then
chatBaseWidth=current
end
local policy=P.layoutPolicy.chat
local width=math.min(chatBaseWidth,math.max(policy.minimumWidth,(right-left-policy.edgeGap)/uiRatio(chat)))
if math.abs(current-width)>.5 then chat:SetWidth(width) end
chatAppliedWidth=width
chatAppliedWidth,chatAppliedHeight=width,height
end
local trackerBaseWidth,trackerAppliedWidth
@ -396,13 +419,10 @@ local function queueCombinedBags()
end)
end
local function refreshUILayout()
P.RefreshPetExtras()
function P.ReconcileControlGeometry()
if not ownsLayout() or InCombatLockdown() or EditModeManagerFrame:IsShown() then return end
P.MigrateExtraBars()
P.MigrateClassLayout()
placeRelative(MultiBarBottomLeft, "BOTTOMLEFT", MainActionBar, "TOPLEFT", 0, 4)
placeRelative(MultiBarBottomRight, "BOTTOMLEFT", MultiBarBottomLeft, "TOPLEFT", 0, 4)
placeRelative(MultiBarBottomLeft, "BOTTOMLEFT", MainActionBar, "TOPLEFT", 0, P.layoutPolicy.actionRowGap)
placeRelative(MultiBarBottomRight, "BOTTOMLEFT", MultiBarBottomLeft, "TOPLEFT", 0, P.layoutPolicy.actionRowGap)
alignCornerWidths()
placeRelative(BagsBar, "BOTTOMRIGHT", MicroMenuContainer, "TOPRIGHT", 0, 10)
placeRelative(MultiBarLeft, "BOTTOMRIGHT", BagsBar, "TOPRIGHT", 0, 14)
@ -414,6 +434,14 @@ local function refreshUILayout()
placeRelative(ObjectiveTrackerFrame, "TOPRIGHT", MinimapCluster, "BOTTOMRIGHT", 0, -24)
fitTracker()
P.PositionGroupFrames(placeRelative, frameEdge)
end
local function refreshUILayout()
P.RefreshPetExtras()
if not ownsLayout() or InCombatLockdown() or EditModeManagerFrame:IsShown() then return end
P.MigrateExtraBars()
P.MigrateClassLayout()
P.ReconcileControlGeometry()
P.RefreshClassAssist()
P.RefreshDamageMeters()
queueCombinedBags()
@ -656,21 +684,26 @@ local function restoreClickBar()
end
end
local function configureLayout()
local manager = EditModeManagerFrame
if not manager or not manager.layoutInfo or not EditModePresetLayoutManager then
error("Edit Mode is not ready; use /ruen apply after loading")
end
if RuenUICharacter.oldLayout == nil then RuenUICharacter.oldLayout = manager.layoutInfo.activeLayout end
for i, layout in ipairs(manager:GetLayouts()) do
if P.IsOurLayout(layout) then
C_EditMode.SetActiveLayout(i)
RuenUIDB.layoutExport = C_EditMode.ConvertLayoutInfoToString(layout)
return
local function configureChatSystem(system)
system.anchorInfo2 = nil
local width,height=P.DefaultChatSize()
changeSetting(system, Enum.EditModeChatFrameSetting.WidthHundreds, math.floor(width/100))
changeSetting(system, Enum.EditModeChatFrameSetting.WidthTensAndOnes, width%100)
changeSetting(system, Enum.EditModeChatFrameSetting.HeightHundreds, math.floor(height/100))
changeSetting(system, Enum.EditModeChatFrameSetting.HeightTensAndOnes, height%100)
anchor(system, "BOTTOMLEFT", "BOTTOMLEFT", 20, 45)
-- Keep this outside the native layout table. Matching saved geometry is
-- the ownership check for automatic resizing; manual edits opt out.
RuenUIDB.chatDefaultSize={width=width,height=height}
end
local function configureDefaultLayout(layout, chatOnly)
if chatOnly then
for _, system in ipairs(layout.systems) do
if system.system == Enum.EditModeSystem.ChatFrame then configureChatSystem(system) end
end
return
end
if manager:AreLayoutsOfTypeMaxed(Enum.EditModeLayoutType.Account) then error("account Edit Mode layouts are full; none removed") end
local layout = CopyTable(EditModePresetLayoutManager:GetCopyOfPresetLayouts()[1])
local E, A, U = Enum.EditModeSystem, Enum.EditModeActionBarSetting, Enum.EditModeUnitFrameSystemIndices
for _, system in ipairs(layout.systems) do
local index = system.systemIndex
@ -728,16 +761,30 @@ local function configureLayout()
changeSetting(system, Enum.EditModeMinimapSetting.Size, 4) -- 90%
anchor(system, "TOPRIGHT", "TOPRIGHT", -22, -40)
elseif system.system == E.ChatFrame then
changeSetting(system, Enum.EditModeChatFrameSetting.WidthHundreds, 3)
changeSetting(system, Enum.EditModeChatFrameSetting.WidthTensAndOnes, 80)
changeSetting(system, Enum.EditModeChatFrameSetting.HeightHundreds, 1)
changeSetting(system, Enum.EditModeChatFrameSetting.HeightTensAndOnes, 50)
anchor(system, "BOTTOMLEFT", "BOTTOMLEFT", 20, 45)
configureChatSystem(system)
end
end
P.ConfigureClassSystems(layout)
P.ConfigureClassAssistSystems(layout)
P.ConfigureExtraBars(layout)
end
local function configureLayout()
local manager = EditModeManagerFrame
if not manager or not manager.layoutInfo or not EditModePresetLayoutManager then
error("Edit Mode is not ready; use /ruen apply after loading")
end
if RuenUICharacter.oldLayout == nil then RuenUICharacter.oldLayout = manager.layoutInfo.activeLayout end
for i, layout in ipairs(manager:GetLayouts()) do
if P.IsOurLayout(layout) then
C_EditMode.SetActiveLayout(i)
RuenUIDB.layoutExport = C_EditMode.ConvertLayoutInfoToString(layout)
return
end
end
if manager:AreLayoutsOfTypeMaxed(Enum.EditModeLayoutType.Account) then error("account Edit Mode layouts are full; none removed") end
local layout = CopyTable(EditModePresetLayoutManager:GetCopyOfPresetLayouts()[1])
configureDefaultLayout(layout)
manager:CreateLayoutTbls()
manager:MakeNewLayout(layout, Enum.EditModeLayoutType.Account, P.layoutName, false)
for i, saved in ipairs(manager:GetLayouts()) do
@ -764,6 +811,7 @@ end
local function recordLayoutStatus(announce)
local status = {bars = {}, time = time(), verified = true, release=P.release,
uiWidth=UIParent:GetWidth(),uiHeight=UIParent:GetHeight(),uiScale=UIParent:GetEffectiveScale()}
status.layoutReset = RuenUICharacter.layoutResetStatus
status.cooldowns={}
for _,name in ipairs({"EssentialCooldownViewer","UtilityCooldownViewer","BuffIconCooldownViewer","BuffBarCooldownViewer"}) do
local f=_G[name]
@ -813,6 +861,13 @@ local function recordLayoutStatus(announce)
end
end
status.classLayoutVersion = RuenUIDB.classLayoutVersion
status.characterProfile = {numbers=P.NumberProfile(), role=P.CharacterRole(),
bindings=RuenUICharacter.numberProfileStatus, customKeys=CopyTable(RuenUICharacter.numberBindingConflicts or {})}
status.petExtras = {nativeSlots=10, extensionSlots=2, errors={}}
for i, entry in pairs((RuenUICharacter.petExtraStatus or {}).abilities or {}) do
if entry.error then status.petExtras.errors[i]=entry.error;status.verified=false end
end
if RuenUICharacter.numberProfileStatus == "secure binding support unavailable" then status.verified=false end
status.intentionalOverlaps={}
if P.bagOverHUD and ContainerFrameCombinedBags and ContainerFrameCombinedBags:IsShown() then status.intentionalOverlaps[#status.intentionalOverlaps+1]="Oversized inventory temporarily covers HUD information; action/chat/quest controls remain clear" end
if P.tooltipOverInventory then status.intentionalOverlaps[#status.intentionalOverlaps+1]="Comparison tooltips over other inventory slots (hovered item kept clear)" end
@ -823,7 +878,7 @@ local function recordLayoutStatus(announce)
for alert in pairs(P.overlayOverOptional or {}) do status.intentionalOverlaps[#status.intentionalOverlaps+1]=(alert:GetName() or "Alert").." temporarily over optional cooldown/meter area in a crowded layout" end
status.attachments=P.AttachedHUDRegions()
status.classFrames = {}
local combatNames = {"MainActionBar", "MultiBarBottomLeft", "MultiBarBottomRight", "MultiBar5", "MultiBarLeft", "MultiBarRight", "MultiBar6", "MultiBar7", "BagsBar", "MicroMenuContainer"}
local combatNames = P.controlFrameNames
for _, name in ipairs(P.classFrameNames) do
local f = _G[name]
if f then
@ -863,16 +918,72 @@ local function recordLayoutStatus(announce)
end
RuenUICharacter.verification = status
if announce then
say("Ruen UI "..P.release.."; UI "..math.floor(status.uiWidth).." x "..math.floor(status.uiHeight)..". Cooldowns: "..(RuenUIDB.cooldownsMode or "auto")..".")
say("Ruen UI "..P.release.."; UI "..math.floor(status.uiWidth).." x "..math.floor(status.uiHeight)..". Cooldowns: "..(RuenUICharacter.cooldownsMode or RuenUIDB.cooldownsMode or "auto")..".")
for _,note in ipairs(status.intentionalOverlaps) do say(note) end
if status.verified then
say("ESDF ready: Q W R T / A G H / Z X C V B. Rows bottom to top: base, Shift, Ctrl, Alt. Utility bars are above bags and chat. /ruen bars lists shortcuts; /ruen lock or unlock controls dragging.")
else
say("Layout needs a spacing check: " .. table.concat(status.overlaps, ", ") .. ". /ruen status checks again.")
local issues=CopyTable(status.overlaps)
for i,err in pairs(status.petExtras.errors) do issues[#issues+1]="Pet extra "..i..": "..err end
if status.characterProfile.bindings=="secure binding support unavailable" then issues[#issues+1]=status.characterProfile.bindings end
say(P.Localized("Ruen needs attention: ","Ruen требует проверки: ")..table.concat(issues, ", ")..". /ruen status")
end
end
end
local function resetLayout(chatOnly)
local manager = EditModeManagerFrame
if InCombatLockdown() then
say(P.Localized("Reset the layout after combat.", "Сбросьте расположение после боя.")); return
end
if not manager or not manager.layoutInfo or manager:IsShown() or manager.overrideLayoutInfo then
say(P.Localized("Close Edit Mode and wait for the interface to finish loading before resetting.",
"Закройте режим редактирования и дождитесь загрузки интерфейса перед сбросом.")); return
end
if RuenUIDB.disabled or not P.IsOurLayout(manager:GetActiveLayoutInfo()) then
say(P.Localized("Select the Ruen UI layout in Edit Mode and enable Ruen before resetting.",
"Перед сбросом выберите расположение Ruen UI в режиме редактирования и включите Ruen.")); return
end
-- Keep the active layout identity, other layouts and unrelated native
-- settings. Never edit the manager's shared systemInfo tables in place.
local data = P.CopyEditModeLayouts()
local layout = data.layouts[data.activeLayout]
local before = C_EditMode.ConvertLayoutInfoToString(layout)
local report = not chatOnly and P.ResetNativeLayoutPositions(layout)
configureDefaultLayout(layout, chatOnly)
chatBaseWidth, chatAppliedWidth, chatAppliedHeight, chatUsesDefaults = nil, nil, nil, nil
if not chatOnly then
trackerBaseWidth, trackerAppliedWidth = nil, nil
bagBaseScale, bagAppliedScale = 1, nil
P.ResetClassLayoutState()
P.ResetOverlayLayoutState()
P.ResetClassAssistLayoutState()
end
P.SaveEditModeLayouts(data)
-- Bounded recovery export, available for native Edit Mode import.
RuenUICharacter.layoutBeforeReset = before
if report then
P.ResetNativePanelPositions(report)
P.ResetCompanionPositions(report)
RuenUICharacter.layoutResetStatus = report
end
C_Timer.After(0.5, function()
refreshUILayout()
if not chatOnly and not InCombatLockdown() and ownsLayout() and GameTooltip:IsShown() then
positionCombinedBags()
P.PositionTooltip(GameTooltip, true)
end
recordLayoutStatus(false)
say(chatOnly and P.Localized("Chat size and position reset; nearby bars repositioned. Layout saved.",
"Размер и положение чата сброшены; соседние панели перемещены. Расположение сохранено.")
or P.Localized("UI positions reset and saved: native frames, Ruen controls and bundled windows. Graphics, keybindings and assigned abilities preserved.",
"Положение элементов интерфейса сброшено и сохранено: стандартные элементы, панели Ruen и окна комплекта. Графика, клавиши и способности сохранены."))
if report and #report.unavailable > 0 then
say(P.Localized("Position reset unavailable for: ", "Не удалось сбросить положение: ") .. table.concat(report.unavailable, ", "))
end
end)
end
local function mask(key, enum, names)
if not enum or saveCVar(key) == nil then return end
local value = tonumber(C_CVar.GetCVar(key)) or 0
@ -882,7 +993,7 @@ local function mask(key, enum, names)
end
put(key, value)
end
local function apply()
local function apply(forceBindings)
if InCombatLockdown() then say("Wait until combat ends, then /ruen apply."); return end
P.InitializeGunAudio()
RuenUIDB.results = RuenUIDB.results or {}
@ -908,8 +1019,8 @@ local function apply()
-- Retain existing extra bars and refresh Blizzard's cached visibility settings.
setBarVisibility(bars)
setupThirdTarget()
applyCombatBindings()
P.ApplyExtraBindings(true)
local changedBindings = applyCombatBindings(forceBindings)
P.ApplyExtraBindings(forceBindings or changedBindings)
local ok, err = pcall(configureLayout)
RuenUICharacter.layoutStatus = ok and "saved" or tostring(err)
if not ok then say("Bars enabled; layout needs attention: " .. tostring(err)); return end
@ -924,6 +1035,8 @@ local function apply()
end
local function restore()
if InCombatLockdown() then say("Leave combat before restoring."); return end
P.ClearCharacterBindings()
P.RestoreChatDefaults()
if RuenUIDB.optimizer then P.OptimizerCommand("restore") end
P.StopGunAudio()
P.StopSwingTimers()
@ -964,25 +1077,6 @@ local function restore()
say("Original settings restored for this character; automatic setup disabled account-wide. The extra saved layout is retained for reuse.")
if addonRestore then say("Type /reload once to finish restoring addon preferences.") end
end
local function bench()
if ticker then say("An FPS sample is already running."); return end
local samples, total, below = {}, 0, 0
say("Sampling FPS once per second for 3 minutes. Play normally and keep WoW focused.")
ticker = C_Timer.NewTicker(1, function()
local fps = GetFramerate()
samples[#samples + 1] = fps; total = total + fps
if fps < 30 then below = below + 1 end
if #samples == 180 then
ticker:Cancel(); ticker = nil
table.sort(samples)
local r = {time = time(), count = 180, mean = total / 180, minimum = samples[1], p10 = samples[18], below30 = below, note = "1-second FPS readings, not a per-frame 1% low"}
local reports = RuenUIDB.reports
reports[#reports + 1] = r
while #reports > 5 do table.remove(reports, 1) end
say(string.format("FPS sample: avg %.1f, minimum %.1f, 10th percentile %.1f; %d/180 readings below 30. Saved on logout/reload.", r.mean, r.minimum, r.p10, below))
end
end)
end
SLASH_RUENUI1 = "/ruen"
SLASH_RUENUI2 = "/ruenui"
SlashCmdList.RUENUI = function(message)
@ -992,6 +1086,7 @@ SlashCmdList.RUENUI = function(message)
if message == "unlock" or message == "lock" then
setSlotsLocked(message == "lock"); return
elseif message == "bars" then say(P.BarHelp()); return
elseif command == "keys" or command == "role" then say(P.CharacterProfileCommand(command,argument)); return
elseif command == "cooldowns" or command == "mouseover" then say(P.ClassAssistCommand(command,argument)); return
elseif command == "guns" then
local reply = P.GunAudioCommand(argument)
@ -999,6 +1094,12 @@ SlashCmdList.RUENUI = function(message)
return
elseif command == "meters" then say(P.DamageMeterCommand(argument)); return
elseif command == "optimize" then P.OptimizerCommand(argument); return
elseif command == "bench" then P.BenchmarkCommand(argument); return
elseif command == "layout" or command == "chat" then
if argument ~= "reset" then say("/ruen layout reset | /ruen chat reset"); return end
local ok, err = pcall(resetLayout, command == "chat")
if not ok then say(P.Localized("Layout reset failed: ", "Не удалось сбросить расположение: ") .. tostring(err)) end
return
elseif message == "swing" or message:match("^swing%s") then
say(P.SwingCommand(message:match("^swing%s+(%S+)") or "status")); return
end
@ -1021,10 +1122,9 @@ SlashCmdList.RUENUI = function(message)
else queueCombinedBags() end
return
end
if message == "apply" then RuenUIDB.disabled = nil; apply()
if message == "apply" then RuenUIDB.disabled = nil; apply(true)
elseif message == "restore" then restore()
elseif message == "bench" then bench()
elseif message == "status" then recordLayoutStatus(true)
elseif message == "status" then recordLayoutStatus(true); say(P.CharacterProfileSummary())
elseif message == "balanced" or message == "performance" then
if InCombatLockdown() then say("Leave combat before changing graphics."); return end
P.StopOptimizer()
@ -1053,6 +1153,8 @@ local function setupAfterLogin()
if RuenUIDB.disabled then return end
local ok, err = pcall(function()
P.MigrateBrand()
P.InitializeCharacterProfiles()
P.ApplyChatDefaults()
setupThirdTarget()
P.InitializeSwingTimers(function()
return ownsLayout() and not EditModeManagerFrame:IsShown()

View File

@ -10,7 +10,7 @@ local function editing()
end
local function mode()
return RuenUIDB and RuenUIDB.damageMeterMode or "auto"
return (RuenUICharacter and RuenUICharacter.damageMeterMode) or (RuenUIDB and RuenUIDB.damageMeterMode) or "auto"
end
function P.WantsDamageMeters()
@ -164,7 +164,7 @@ end
function P.DamageMeterCommand(argument)
if argument == "auto" or argument == "show" or argument == "off" then
RuenUIDB.damageMeterMode = argument
RuenUICharacter.damageMeterMode = argument
P.RefreshDamageMeters()
end
return P.Localized("Damage meter: ", "Счётчик урона: ") .. mode() .. P.Localized(

View File

@ -21,6 +21,10 @@ end
local function leftDock(edge, rows, saved)
local x=edge(ChatFrame1,"GetLeft") or 20
-- Keep the shelf on the layout margin, not the text inset introduced by
-- native chat clamping. Those extra 12 units matter to a compact raid grid.
local chatOrigin=P.DefaultChatOrigin()
x=math.max(P.layoutPolicy.gap,x-math.max(0,chatOrigin-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
@ -161,31 +165,10 @@ 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
P.ApplyCharacterBindings(force)
-- The caller may also have changed ordinary row bindings. Profile bindings
-- themselves are session-local and never written into the account set.
if force then SaveBindings(GetCurrentBindingSet()) end
end
function P.ApplyExtraBindings(force)
@ -235,14 +218,14 @@ function P.UtilityTop()
end
function P.PositionExtraBars(place,edge)
place(MultiBarRight,"BOTTOMRIGHT",MultiBarLeft,"TOPRIGHT",0,6)
place(MultiBar5,"BOTTOMLEFT",MultiBarBottomRight,"TOPLEFT",0,4)
place(MultiBarRight,"BOTTOMRIGHT",MultiBarLeft,"TOPRIGHT",0,P.layoutPolicy.utilityRowGap)
place(MultiBar5,"BOTTOMLEFT",MultiBarBottomRight,"TOPLEFT",0,P.layoutPolicy.actionRowGap)
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)
place(MultiBar7,"BOTTOMLEFT",MultiBar6,"TOPLEFT",0,P.layoutPolicy.utilityRowGap)
end
local groupScales={}
@ -304,6 +287,10 @@ function P.PositionGroupFrames(place,edge)
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 > Назначение клавиш.")
local pet = P.NumberProfile() == "pet"
local mapping = pet and P.Localized("1–= pets; Ctrl+1–= right utility.", "1–= — питомец; Ctrl+1–= — нижняя правая панель.")
or P.Localized("1–= right utility; Ctrl+1–= pets.", "1–= — нижняя правая панель; Ctrl+1–= — питомец.")
return P.Localized("96 slots: 48 ESDF combat (base/Shift/Ctrl/Alt). ", "96 ячеек: 48 боевых ESDF (без модификатора/Shift/Ctrl/Alt). ")
..mapping..P.Localized(" Upper right: Shift+numbers; left: Alt+numbers, Ctrl+Shift+numbers. /ruen keys auto|pet|utility; /ruen lock | unlock. Custom bindings are preserved.",
" Верхняя правая: Shift+цифры; слева: Alt+цифры, Ctrl+Shift+цифры. /ruen keys auto|pet|utility; /ruen lock | unlock. Свои назначения сохраняются.")
end

45
RuenUI/FrameTiming.lua Normal file
View File

@ -0,0 +1,45 @@
local _, P = ...
-- Bounded histograms shared by the two explicit measurements. No timers, API
-- queries, sorting, or per-frame table allocations in the recording path.
local scale, lastBin = 4000, 40000 -- quarter-millisecond bins, through ten seconds
function P.NewFrameSample()
return {bins={}, frames=0, seconds=0, worstMS=0, over50=0, over100=0, over250=0, hitchEpisodes=0}
end
function P.AddFrameSample(s, dt)
if type(dt) ~= 'number' or dt <= 0 or dt ~= dt or dt == math.huge then return end
local bin = math.min(lastBin, math.ceil(dt * scale))
s.bins[bin] = (s.bins[bin] or 0) + 1
s.frames = s.frames + 1; s.seconds = s.seconds + dt
local ms = dt * 1000
if ms > s.worstMS then s.worstMS = ms end
if ms > 50 then
s.over50 = s.over50 + 1
if not s.inHitch then s.hitchEpisodes = s.hitchEpisodes + 1 end
end
s.inHitch = ms > 50
if ms > 100 then s.over100 = s.over100 + 1 end
if ms > 250 then s.over250 = s.over250 + 1 end
end
function P.FrameSampleSummary(s)
local r = {frames=s.frames, seconds=s.seconds, worstMS=s.worstMS,
over50=s.over50, over100=s.over100, over250=s.over250, hitchEpisodes=s.hitchEpisodes}
if s.frames == 0 then return r end
r.meanFPS = s.frames / s.seconds
local count = 0
for bin=1,lastBin do
count = count + (s.bins[bin] or 0)
if not r.p90MS and count >= math.ceil(s.frames * .90) then r.p90MS = bin / 4 end
if count >= math.ceil(s.frames * .99) then r.p99MS = bin / 4; break end
end
-- Mean of the slowest 1% of frames, explicitly different from p99.
local remaining, tailMS = math.max(1, math.ceil(s.frames * .01)), 0
local tailCount = remaining
for bin=lastBin,1,-1 do
local n = math.min(remaining, s.bins[bin] or 0)
tailMS = tailMS + n * bin / 4; remaining = remaining - n
if remaining == 0 then break end
end
r.low1FPS = 1000 / (tailMS / tailCount)
r.histogramClipped = s.worstMS > 10000
return r
end

86
RuenUI/LayoutPolicy.lua Normal file
View File

@ -0,0 +1,86 @@
local _, P = ...
-- Shared reservations used by placement AND diagnostics. Hidden/empty buttons
-- still occupy their block, so overlays cannot land in a temporarily blank slot.
P.layoutPolicy = {
gap = 12, actionRowGap = 4, utilityRowGap = 6,
chat = {maximumWidth = 620, minimumHeight = 190, maximumHeight = 260,
minimumWidth = 240, fontSize = 14, edgeGap = 16},
controls = {
{name="Center controls", "MainActionBar","MultiBarBottomLeft","MultiBarBottomRight","MultiBar5"},
{name="Right controls", "MultiBarLeft","MultiBarRight","BagsBar","MicroMenuContainer"},
{name="Left controls", "MultiBar6","MultiBar7"},
},
panels = {"BankFrame","GuildBankFrame","MerchantFrame","QuestFrame","GossipFrame","MailFrame","TradeFrame",
"ProfessionsFrame","TradeSkillFrame","PlayerSpellsFrame","SpellBookFrame","WorldMapFrame","QuestLogFrame",
"CharacterFrame","AuctionHouseFrame"},
}
P.controlFrameNames, P.controlFrameSet = {}, {}
for _, group in ipairs(P.layoutPolicy.controls) do
for _, name in ipairs(group) do
P.controlFrameNames[#P.controlFrameNames+1] = name
P.controlFrameSet[name] = true
end
end
function P.DefaultChatSize()
-- Use logical UI dimensions: a 4K screen with a larger UI scale may have
-- the same usable space as 1080p. Unchanged defaults can follow a viewport
-- resize; ordinary refreshes keep custom sizes. Core separately fits
-- the width against the actual combat row, including custom positions.
local chat=P.layoutPolicy.chat
local width=math.max(chat.minimumWidth,math.min(chat.maximumWidth,UIParent:GetWidth()*.30))
local height=math.max(chat.minimumHeight,math.min(chat.maximumHeight,UIParent:GetHeight()*.22))
return math.floor(width/10)*10,math.floor(height/10)*10
end
function P.DefaultChatOrigin()
-- The native chat selection includes its tabs/buttons. The engine clamps
-- the requested 20-unit anchor to 32 on this client; that is not a manual
-- move. Read native insets so another client/scale can use its own margin.
local frame=ChatFrame1
local x,y=20,45
if frame and frame.GetClampRectInsets then
local left,right,top,bottom=frame:GetClampRectInsets()
local scale=frame:GetEffectiveScale()/UIParent:GetEffectiveScale()
x=math.max(x,-(left or 0)*scale)
y=math.max(y,-(bottom or 0)*scale)
end
return x,y
end
function P.IsDefaultChatSystem(system)
local saved=RuenUIDB.chatDefaultSize
local a=system and system.anchorInfo
if not saved or not a or a.point~="BOTTOMLEFT" or a.relativeTo~="UIParent"
or a.relativePoint~="BOTTOMLEFT" then return false end
local x,y=P.DefaultChatOrigin()
-- Native saves can retain either the requested or the clamped origin.
if not (a.offsetX==20 or (a.offsetX and math.abs(a.offsetX-x)<.5))
or not (a.offsetY==45 or (a.offsetY and math.abs(a.offsetY-y)<.5)) then return false end
local S=Enum.EditModeChatFrameSetting
local values={}
for _,v in ipairs(system.settings or {}) do values[v.setting]=v.value end
return (values[S.WidthHundreds] or 0)*100+(values[S.WidthTensAndOnes] or 0)==saved.width
and (values[S.HeightHundreds] or 0)*100+(values[S.HeightTensAndOnes] or 0)==saved.height
end
function P.ApplyChatDefaults()
-- Fresh installs only. Do not overwrite an existing player's font choice.
if RuenUICharacter.chatDefaultsVersion or RuenUICharacter.version then return end
if ChatFrame1 and ChatFrame1.GetFont and FCF_SetChatWindowFontSize then
local font,size,flags=ChatFrame1:GetFont()
RuenUICharacter.chatFontOriginal={font=font,size=size,flags=flags}
FCF_SetChatWindowFontSize(nil,ChatFrame1,P.layoutPolicy.chat.fontSize)
end
RuenUICharacter.chatDefaultsVersion=1
end
function P.RestoreChatDefaults()
local old=RuenUICharacter.chatFontOriginal
if not old or not ChatFrame1 or not ChatFrame1.GetFont then return end
local font,size=ChatFrame1:GetFont()
if font==old.font and size==P.layoutPolicy.chat.fontSize and FCF_SetChatWindowFontSize then
FCF_SetChatWindowFontSize(nil,ChatFrame1,old.size)
end
end

97
RuenUI/LayoutRecovery.lua Normal file
View File

@ -0,0 +1,97 @@
local _, P = ...
-- Explicit recovery only: no recurring work and no edits to live systemInfo.
-- Cover every native system, including ones this class has not displayed yet.
function P.ResetNativeLayoutPositions(layout)
local manager = EditModePresetLayoutManager
local defaults = manager and manager:GetCopyOfPresetLayouts()
assert(defaults and defaults[1], "Native layout defaults are not ready")
local index = {}
for _, system in ipairs(defaults[1].systems or {}) do
local key = system.system .. ":" .. tostring(system.systemIndex or 0)
index[key] = system
end
local report = {native = 0, unavailable = {}, companions = {}}
for _, system in ipairs(layout.systems or {}) do
local key = system.system .. ":" .. tostring(system.systemIndex or 0)
local preset = index[key]
local position = preset and preset.anchorInfo
if not position and manager.GetDefaultSystemAnchorInfo then
local ok, result = pcall(manager.GetDefaultSystemAnchorInfo, manager, system.system, system.systemIndex)
if ok then position = result end
end
if position then
system.anchorInfo = CopyTable(position)
system.anchorInfo2 = nil -- discard secondary snap anchors too
system.isInDefaultPosition = true
report.native = report.native + 1
else
report.unavailable[#report.unavailable + 1] = "native system " .. key
end
end
return report
end
local function attempt(report, label, fn)
local ok, result = pcall(fn)
if not ok or result == false then
report.unavailable[#report.unavailable + 1] = label
else
report.companions[#report.companions + 1] = label
end
end
function P.ResetCompanionPositions(report)
local spoken = SpokenEnv
if spoken and spoken.Options and spoken.Options.ResetPositions then
-- Upstream's position-only reset preserves narration, volume and style.
attempt(report, "Spoken narration", function() spoken.Options:ResetPositions() end)
end
local compendium = SpokenCompendium and SpokenCompendium.window
if compendium then
attempt(report, "Compendium", function()
compendium:ClearAllPoints()
compendium:SetPoint("CENTER", UIParent, "CENTER", 0, 0)
if compendium.SetUserPlaced then compendium:SetUserPlaced(false) end
end)
end
if C_AddOns and C_AddOns.IsAddOnLoaded("Leatrix_Maps") then
-- Leatrix keeps a private live copy of its DB and overwrites saved
-- values at logout. Use its own position-only reset, not a DB write
-- that appears to work and is then silently undone. The pinned build
-- exposes this button on its main panel; tiptext is locale-independent.
attempt(report, "Leatrix Maps", function()
for _, name in ipairs(UISpecialFrames or {}) do
local panel = _G[name]
if panel and panel.GetChildren and not (panel.IsForbidden and panel:IsForbidden()) then
for _, child in ipairs({panel:GetChildren()}) do
if not (child.IsForbidden and child:IsForbidden())
and child.tiptext == "Click to reset the map position and scale to the game default." then
local click = child:GetScript("OnClick")
if not click or (child.IsEnabled and not child:IsEnabled()) then return false end
click(child, "LeftButton")
return true
end
end
end
end
return false
end)
end
end
function P.ResetNativePanelPositions(report)
-- Hand ordinary windows (bank, professions, spellbook, merchant, etc.)
-- back to Blizzard's panel manager. Never replace protected handlers or
-- write UIPanelWindows/UIPanelLayout attributes from addon code.
if not UpdateUIPanelPositions then return end
attempt(report, "Native panels", function()
for name in pairs(UIPanelWindows or {}) do
local panel = _G[name]
if panel and panel.SetUserPlaced and not (panel.IsForbidden and panel:IsForbidden()) then
panel:SetUserPlaced(false)
end
end
UpdateUIPanelPositions()
end)
end

View File

@ -1,236 +1,410 @@
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
-- Explicit, bounded scene calibration. No idle polling after a profile settles.
-- Graphics are reversible; hardware/thermal evidence is supplied by the companion.
local f, running, session, pendingLoad, loading, deferredEnvironment
local modes = {'world', 'dungeon', 'raid', 'battleground'}
local function say(en, ru) print('|cff60d5ffRuen UI:|r '..P.Localized(en, ru or en)) end
local function validFPS(value)
local n = tonumber(value)
if n and n >= 20 and n <= 240 and n == math.floor(n) then return n end
end
local function db()
RuenUIDB.optimizer=RuenUIDB.optimizer or {original={},profiles={}}
return RuenUIDB.optimizer
RuenUIDB.optimizer = RuenUIDB.optimizer or {original={}, profiles={}}
local d = RuenUIDB.optimizer
d.original = d.original or {}; d.profiles = d.profiles or {}
for _, name in ipairs(modes) do d.profiles[name] = d.profiles[name] or {tier=1} end
return d
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
local inside, kind = IsInInstance()
if inside and kind == 'raid' then return 'raid' end
if inside and (kind == 'pvp' or kind == 'arena') then return 'battleground' end
if inside then return 'dungeon' end
return 'world'
end
local function fingerprint()
local w,h=GetPhysicalScreenSize()
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
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
local fields = {'ShadowQuality','SSAO','ViewDistance','EnvironmentDetail','GroundClutter',
'LiquidDetail','ComputeEffects','LightMode','PBRLiquidDetail'}
local tiers = {
{0,0,1,1,1,0,0,0,0}, {1,0,2,2,2,1,1,0,0}, {2,1,3,3,3,2,2,1,0},
{2,1,5,5,4,3,2,1,1}, {3,2,7,6,5,3,3,2,1},
}
local settings = {
{'graphicsShadowQuality','Shadows','Тени',{'Low','Fair','Good','High','Ultra','Ultra High'}},
{'graphicsSSAO','Ambient shading','Рассеянное затенение',{'Off','Low','Good','High','Ultra'}},
{'graphicsLightMode','Lighting','Освещение',{'Fair','Good','High','Ultra'}},
{'graphicsViewDistance','View distance','Дальность видимости','distance'},
{'graphicsEnvironmentDetail','Environment detail','Детализация окружения','distance'},
{'graphicsGroundClutter','Ground clutter','Детализация земли','distance'},
{'graphicsLiquidDetail','Water','Вода',{'Low','Fair','Good','High'}},
{'graphicsPBRLiquidDetail','Modern water','Современная вода',{'Low','High','Ultra'}},
{'graphicsComputeEffects','Compute effects','Вычисляемые эффекты',{'Low','Fair','Good','High','Ultra'}},
{'graphicsProjectedTextures','Ground spell indicators','Наземные эффекты заклинаний','toggle'},
{'graphicsParticleDensity','Particle detail','Детализация частиц'},
{'graphicsSpellDensity','Spell density','Плотность заклинаний',{'Essential','Reduced','Everything'}},
{'graphicsDepthEffects','Depth effects','Эффекты глубины',{'Off','Low','Good','High'}},
{'RAIDsettingsEnabled','Native raid override','Встроенные настройки рейда','toggle'},
{'MSAAQuality','MSAA','MSAA'}, {'msaaAlphaTest','MSAA alpha test','MSAA alpha test','toggle'},
{'ffxAntiAliasingMode','Anti-aliasing mode','Режим сглаживания'},
{'vsync','VSync','Вертикальная синхронизация','toggle'},
{'useTargetFPS','Dynamic FPS control','Динамическое управление FPS','toggle'},
{'useMaxFPS','FPS limiter','Ограничение FPS','toggle'}, {'maxFPS','FPS cap','Лимит FPS'},
}
local function snapshot()
local values={}
for _,spec in ipairs(settings) do values[spec[1]]=C_CVar.GetCVar(spec[1]) end
return values
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')
local function equivalent(a,b)
return a==b or (tonumber(a)~=nil and tonumber(a)==tonumber(b))
end
local function differences(before,after)
local result={}
for _,spec in ipairs(settings) do
local key=spec[1]
if not equivalent(before[key],after[key]) then
result[#result+1]={key=key,before=before[key],after=after[key]}
end
end
return result
end
local function describe(change)
local spec
for _,entry in ipairs(settings) do if entry[1]==change.key then spec=entry; break end end
local function value(v)
if v==nil then return P.Localized('unavailable','недоступно') end
local n=tonumber(v)
if spec[4]=='distance' and n then return tostring(n+1)..'/10' end
if spec[4]=='toggle' and n then return n==0 and P.Localized('off','выкл') or P.Localized('on','вкл') end
if type(spec[4])=='table' and n and spec[4][n+1] then
local text=spec[4][n+1]
local ru={Off='Выкл',Low='Низко',Fair='Удовлетворительно',Good='Хорошо',High='Высоко',
Ultra='Ультра',['Ultra High']='Максимум',Essential='Необходимые',Reduced='Меньше',Everything='Все'}
return P.Localized(text,ru[text] or text)
end
if spec[1]=='MSAAQuality' and v=='0,0' then return P.Localized('off','выкл') end
return tostring(v)
end
return P.Localized(spec[2],spec[3])..': '..value(change.before)..' → '..value(change.after)
end
local function showChanges(changes)
if #changes==0 then
say('No graphics values changed in this step.',
'На этом шаге значения графики не изменились.'); return
end
for first=1,#changes,4 do
local parts={}
for i=first,math.min(first+3,#changes) do parts[#parts+1]=describe(changes[i]) end
say(table.concat(parts,'; '))
end
end
local function showUnavailable(failures)
if failures and next(failures) then
local names={}
for _,spec in ipairs(settings) do if failures[spec[1]] then names[#names+1]=P.Localized(spec[2],spec[3]) end end
say('Unavailable/not applied: '..table.concat(names,', '),'Недоступно/не применено: '..table.concat(names,', '))
end
end
local function reportApplication(before,heading,ru,failures)
local d=db(); local changes=differences(before,snapshot())
d.lastChange={time=time(),release=P.release,mode=mode(),heading=heading,headingRU=ru,changes=changes,unavailable=failures}
say(heading,ru); showChanges(changes)
showUnavailable(failures)
end
local function write(key, value)
local before = C_CVar.GetCVar(key)
if before == nil then return false end
if key:find('^graphics') and IsGraphicsSettingValueSupported then
local ok, reason = pcall(IsGraphicsSettingValueSupported, key, value, false)
if not ok or (reason and reason ~= 0) then return false end
end
if equivalent(before,tostring(value)) then return true end
local d = db()
if d.original[key] == nil then d.original[key] = before end
local ok = pcall(C_CVar.SetCVar, key, tostring(value))
if not ok then return false end
return equivalent(C_CVar.GetCVar(key),tostring(value))
end
local function profile(tier)
local failures = {}
tier = math.max(1, math.min(#tiers, tier or 1))
-- Own environment switching explicitly: the native raid preset must not
-- silently replace the settings being measured in a dungeon/BG/raid.
if not write('RAIDsettingsEnabled', 0) then failures.RAIDsettingsEnabled = true end
for i, suffix in ipairs(fields) do
local key = 'graphics'..suffix
if not write(key, tiers[tier][i]) then failures[key] = true end
end
for key, value in pairs({graphicsProjectedTextures=1, graphicsParticleDensity=2,
graphicsSpellDensity=0, graphicsDepthEffects=0}) do
if not write(key, value) then failures[key] = true end
end
-- Keep render scale, texture resolution and UI scale as the player chose.
-- These low-cost AA choices take effect without replacing GPU/API/drivers.
write('MSAAQuality', '0,0'); write('msaaAlphaTest', 0)
write('ffxAntiAliasingMode', 1); write('vsync', 0); write('useTargetFPS', 0)
return failures
end
local function cap(value)
write('useMaxFPS',1);write('maxFPS',value)
write('useMaxFPSBk',1);write('maxFPSBk',15)
write('useMaxFPS', 1); write('maxFPS', value)
end
local function reset(seconds)
warmup,elapsed,frames,histogram=seconds or 15,0,0,{}
local function resetSample(seconds)
if session then session.sample=P.NewFrameSample(); session.warmup=seconds or 8 end
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
local function applyTier(tier, phase)
local s, d = session, db()
local before=snapshot()
s.tier=tier; s.phase=phase or 'search'; s.pending=nil; s.good=0; s.waitNotified=nil
s.unsupported=profile(tier)
cap(s.phase == 'validate' and d.target or math.ceil(d.target * 1.1))
resetSample(8)
reportApplication(before,
('%s %s tier %d/5; FPS cap %d%s.'):format(s.phase=='validate' and 'Verifying' or 'Testing',s.mode,tier,
s.phase=='validate' and d.target or math.ceil(d.target*1.1),s.phase=='validate' and ' (final)' or ' (temporary)'),
('%s %s, уровень %d/5; лимит FPS %d%s.'):format(s.phase=='validate' and 'Итоговая проверка' or 'Проверка',s.mode,tier,
s.phase=='validate' and d.target or math.ceil(d.target*1.1),s.phase=='validate' and ' (итоговый)' or ' (временный)'),s.unsupported)
end
local function passed(r, target, validate)
-- Tail latency and explicit hitches matter even when 99% of frames are fast.
-- At most one >50ms frame per 20s, and no >100ms frame, passes this window.
return r.frames > 0 and 1000/r.p90MS >= target * (validate and .95 or 1.02)
and 1000/r.p99MS >= target * .80 and r.over100 == 0
and r.over50 <= math.floor(r.seconds / 20 + .01)
end
local function finish(r)
local s, d = session, db()
local saved = d.profiles[s.mode]
saved.tier=s.tier; saved.calibrated=true; saved.fingerprint=fingerprint(); saved.time=time()
saved.revision=2; saved.metTarget=passed(r,d.target,true); saved.last=r
saved.history=s.history; saved.unsupported=s.unsupported
saved.zone=GetRealZoneText and GetRealZoneText() or nil
saved.subzone=GetSubZoneText and GetSubZoneText() or nil
saved.requestedFPS=d.requestedFPS
cap(d.target)
say(('Graphics %s: tier %d/5 saved at %d FPS. p99 %.1f ms; worst %.1f ms; >100 ms frames: %d. %s'):format(
s.mode, s.tier, d.target, r.p99MS or 0, r.worstMS, r.over100,
saved.metTarget and 'Smoothness checks passed in this sample.' or 'Target/smoothness NOT met. Settings alone may not resolve these stalls.'),
('Графика %s: уровень %d/5, цель %d FPS. p99 %.1f мс; максимум %.1f мс; кадров >100 мс: %d. %s'):format(
s.mode, s.tier, d.target, r.p99MS or 0, r.worstMS, r.over100,
saved.metTarget and 'Проверка плавности пройдена для этого замера.' or 'Цель НЕ достигнута. Настройки графики могут не устранить задержки.'))
if next(s.unsupported) then
say('Some graphics controls are unavailable on this client/GPU; the result measures the settings actually accepted.',
'Некоторые настройки недоступны; результат получен с фактически применёнными значениями.')
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
reportApplication(s.before,'Final changes compared with the start of this run:',
'Итоговые изменения относительно начала этой проверки:',s.unsupported)
session=nil; f:SetScript('OnUpdate',nil)
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
local s = session
if not s or not s.pending or loading then return end
if InCombatLockdown() then
if not s.waitNotified then
say('Sample complete; waiting for combat to end before applying the next step.',
'Замер завершён; следующий шаг будет применён после окончания боя.')
s.waitNotified=true
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
if s.pending == 'finish' then finish(s.last)
else local nextStep=s.pending; applyTier(nextStep.tier,nextStep.phase) end
end
local function result()
local s, d = session, db()
local r=P.FrameSampleSummary(s.sample); r.tier=s.tier; r.phase=s.phase
s.last=r; s.history[#s.history+1]=r
local pass=passed(r,d.target,s.phase=='validate')
say(('Tier %d/5 check: %s; p99 %.1f ms, worst %.1f ms, frames >100 ms: %d.'):format(
s.tier,pass and 'passed' or 'target/smoothness missed',r.p99MS or 0,r.worstMS,r.over100),
('Проверка уровня %d/5: %s; p99 %.1f мс, максимум %.1f мс, кадров >100 мс: %d.'):format(
s.tier,pass and 'пройдена' or 'цель/плавность не достигнута',r.p99MS or 0,r.worstMS,r.over100))
if s.phase == 'validate' then
if not passed(r,d.target,true) and s.tier > 1 then
s.pending={tier=s.tier-1,phase='validate'}
else s.pending='finish' end
else
s.windows=s.windows+1
if passed(r,d.target,false) then s.good=s.good+1 else s.good=0 end
if s.good >= 2 then
s.best=s.tier
if s.tier < d.ceiling and s.windows < 10 then s.pending={tier=s.tier+1}
else s.pending={tier=s.best,phase='validate'} end
elseif not passed(r,d.target,false) then
if s.best then s.pending={tier=s.best,phase='validate'}
elseif s.tier > 1 then s.pending={tier=s.tier-1}
elseif s.windows >= 2 then s.pending={tier=1,phase='validate'} end
end
if s.windows >= 10 then s.pending={tier=s.best or 1,phase='validate'} end
end
resetSample(0); commit()
end
local update
local function start(which)
local d=db(); local saved=d.profiles[which]
session={mode=which,tier=math.min(saved.tier or 1,2,d.ceiling),windows=0,good=0,history={},before=snapshot()}
applyTier(session.tier)
f:SetScript('OnUpdate',update)
say(('Optimizing %s for %d FPS: move/fight in this area for about 2–5 minutes. Keep WoW focused; /ruen optimize pause before switching apps. Changes wait for combat to end.'):format(which,d.target),
('Настройка %s для %d FPS: играйте здесь 2–5 минут. Не переключайте окно; перед переключением /ruen optimize pause. Изменения применяются вне боя.'):format(which,d.target))
end
local function activate()
if not running or loading then return end
if P.IsBenchmarkRunning and P.IsBenchmarkRunning() then deferredEnvironment=true; return end
deferredEnvironment=nil
if InCombatLockdown() then
if pendingLoad~=activate then say('Environment changed; waiting for combat to end before applying its graphics.',
'Зона изменилась; графика будет применена после окончания боя.') end
pendingLoad=activate; return
end
local d=db(); local which=mode(); local r=d.profiles[which]
session=nil
if r.calibrated and r.revision==2 and r.fingerprint==fingerprint() then
local before=snapshot()
profile(r.tier); cap(d.target); f:SetScript('OnUpdate',nil)
if #differences(before,snapshot())>0 then
reportApplication(before,'Applied saved '..which..' graphics.','Применён сохранённый профиль '..which..'.')
end
else start(which) end
end
update = function(_, dt)
if not running or RuenUIDB.disabled then session=nil; f:SetScript('OnUpdate',nil); return end
if loading then return end
local s=session
if not s then f:SetScript('OnUpdate',nil); return end
if s.mode ~= mode() then
-- Discard the entire old window; never let a different environment
-- validate the old profile, even while changes are deferred by combat.
session=nil; f:SetScript('OnUpdate',nil); activate(); return
end
if s.pending then commit(); return end
if s.warmup > 0 then s.warmup=math.max(0,s.warmup-dt); return end
P.AddFrameSample(s.sample,dt) -- includes real long stalls, not just percentiles
if s.sample.seconds >= 20 then result() end
end
function P.IsOptimizerCalibrating() return session ~= nil or (running and pendingLoad ~= nil) end
function P.OptimizerBenchmarkEnded()
if deferredEnvironment then activate() 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)
local d=db(); running=false; d.enabled=false; pendingLoad=nil; deferredEnvironment=nil
if session then
local s=session; local tier=s.best or s.tier
d.profiles[s.mode].tier=tier
profile(tier)
end
context,pending=nil,nil
session=nil
if f then f:SetScript('OnUpdate',nil) end
cap(d.target or 60)
end
function P.OptimizerCommand(arg)
arg=(arg or ''):lower():match('^%s*(.-)%s*$')
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 'не проверен'))
if arg=='changes' then
local last=d.lastChange
if last then say(last.heading,last.headingRU); showChanges(last.changes); showUnavailable(last.unavailable)
else say('No recorded changes yet. This command does not start optimization.',
'Изменения ещё не записаны. Эта команда не запускает настройку.') end
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=='status' then
local which=mode(); local r=d.profiles[which]
local state=loading and 'loading' or session and (session.pending and
(InCombatLockdown() and 'waiting for combat to end' or 'applying next step') or session.warmup>0 and
('settling: '..math.ceil(session.warmup)..' seconds') or ('recording: '..math.floor(session.sample.seconds)..'/20 seconds'))
or pendingLoad and 'waiting for combat to end' or deferredEnvironment and 'waiting for benchmark'
say(('Optimizer [%s]: %s; %s; target %d FPS (requested %d). %s. Thermal evidence: %s.'):format(P.release or 'unknown',
running and 'ON' or 'OFF',which,d.target or validFPS(d.requestedFPS) or 60,
validFPS(d.requestedFPS) or 60,session and ('measuring tier '..session.tier..'/5 ('..session.phase..')')
or r.calibrated and ('saved tier '..r.tier..'/5; '..(r.metTarget and 'sample passed' or 'target NOT met')) or 'not measured',
hardware().evidence or 'not measured'))
if state then say(state) end
if d.lastChange then say('Last update: '..d.lastChange.heading..' /ruen optimize changes lists the settings.',
'Последнее изменение: '..(d.lastChange.headingRU or d.lastChange.heading)..' Список: /ruen optimize changes.') end
if r.last then say(('Last saved sample: p99 %.1f ms; worst %.1f ms; >50/>100/>250 ms frames: %d/%d/%d.'):format(
r.last.p99MS or 0,r.last.worstMS or 0,r.last.over50 or 0,r.last.over100 or 0,r.last.over250 or 0)) end
return
end
if InCombatLockdown() then say('Change optimization outside combat.','Меняйте оптимизацию вне боя.'); return end
if arg=='off' or arg=='pause' then
local before=snapshot(); P.StopOptimizer()
reportApplication(before,'Calibration paused; settled/current quality retained.','Калибровка приостановлена; текущие настройки сохранены.'); return
end
if arg=='restore' then
local before=snapshot()
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
for key,value in pairs(d.original) do pcall(C_CVar.SetCVar,key,value) end
reportApplication(before,'Restored pre-optimization graphics:','Исходная графика восстановлена:')
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
local cmd, fpsText=arg:match('^(%S+)%s+(%S+)$')
cmd=cmd or arg
if validFPS(cmd) and not fpsText then fpsText=cmd; cmd='' end
local fps=fpsText and validFPS(fpsText)
if (fpsText and not fps) or (cmd~='' and cmd~='start' and cmd~='resume' and not d.profiles[cmd]) then
say('/ruen optimize [20–240 FPS] | world|dungeon|raid|battleground [FPS] | pause|resume|status|changes|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
if P.IsBenchmarkRunning and P.IsBenchmarkRunning() then
say('Finish the benchmark or /ruen bench stop before changing graphics.','Завершите замер или /ruen bench stop перед настройкой графики.'); 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
if d.profiles[cmd] and mode()~=cmd then
say('Run this in the requested environment; a solo sample cannot validate raid performance.',
'Запустите в соответствующей зоне; соло-замер не проверяет производительность рейда.'); return
end
d.profiles.world=d.profiles.world or {tier=2};d.profiles.raid=d.profiles.raid or {tier=1}
if session then P.StopOptimizer() end
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
d.requestedFPS=fps or validFPS(d.requestedFPS) or 60
local target=h.thermalPressure and math.min(d.requestedFPS,45) or d.requestedFPS
local ceiling=(h.thermalPressure or h.performancePressure) and 2 or 5
if d.target~=target or d.ceiling~=ceiling then
for _,r in pairs(d.profiles) do r.calibrated=false 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))
d.target=target; d.ceiling=ceiling
-- A plain command is a fresh measurement HERE, even if the outdoor profile
-- previously passed elsewhere. Other environments retain their own evidence.
if cmd~='resume' then d.profiles[mode()].calibrated=false end
running=true; d.enabled=true
activate()
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')
for _,event in ipairs({'PLAYER_ENTERING_WORLD','PLAYER_LEAVING_WORLD','PLAYER_REGEN_ENABLED',
'DISPLAY_SIZE_CHANGED','ZONE_CHANGED_NEW_AREA'}) do f:RegisterEvent(event) end
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=='PLAYER_LEAVING_WORLD' then
loading=true; resetSample(8); return
elseif event=='PLAYER_REGEN_ENABLED' then
if pendingLoad then local fn=pendingLoad; pendingLoad=nil; fn() end
commit(); return
elseif event=='PLAYER_ENTERING_WORLD' then loading=false end
if running then
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
for _,r in pairs(db().profiles) do r.calibrated=false end
end
-- Immediately stop measuring; apply the next environment only once
-- safe. A loading screen is never charged as a gameplay hitch.
session=nil; f:SetScript('OnUpdate',nil); activate()
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
local key=h.checkedAt and (tostring(h.checkedAt)..':'..(validFPS(h.targetFPS) or 60))
if h.autoStart and RuenUIDB.hardwareImport~=key then
db().requestedFPS=validFPS(h.targetFPS) or 60
P.OptimizerCommand('start'); RuenUIDB.hardwareImport=key; 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
if d and d.enabled then P.OptimizerCommand('resume')
elseif d then cap(d.target or 60) end -- recover interrupted trial cap
end
if InCombatLockdown() then pendingLoad=initializeSaved else initializeSaved() end
end

View File

@ -3,13 +3,13 @@ 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 gap = P.layoutPolicy.gap
local hudNames = {
"MainActionBar", "MultiBarBottomLeft", "MultiBarBottomRight", "MultiBar5",
"MultiBarLeft", "MultiBarRight", "MultiBar6", "MultiBar7", "BagsBar", "MicroMenuContainer",
"DamageMeter",
"BuffFrame", "DebuffFrame", "MirrorTimer1", "MirrorTimer2", "MirrorTimer3",
"ChatFrame1", "MinimapCluster", "ObjectiveTrackerFrame", "PartyFrame", "CompactRaidFrameContainer",
"ChatFrame1", "ChatFrame1EditBox", "ChatFrame1Tab", "MinimapCluster", "ObjectiveTrackerFrame", "PartyFrame", "CompactRaidFrameContainer",
"PlayerFrame", "PetFrame", "TargetFrame", "TargetFrameToT", "RuenTargetTargetTarget", "FocusFrame",
"StanceBar", "PetActionBar", "MultiCastActionBarFrame", "PossessActionBar",
"MainMenuBarVehicleLeaveButton", "PlayerCastingBarFrame", "RuenSwingTimers", "ExtraAbilityContainer",
@ -17,10 +17,8 @@ local hudNames = {
"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 blockMembers = P.controlFrameSet
local panels = P.layoutPolicy.panels
local hooked, queued, placing = {}, false, false
local place, edge, enabled, schedule
local alertHooks={}
@ -130,11 +128,7 @@ end
-- 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
for _,group in ipairs(P.layoutPolicy.controls) do
local region
for _,name in ipairs(group) do
local r=rect(_G[name],true)
@ -301,6 +295,13 @@ end
local tooltipPositions=setmetatable({},{__mode="k"})
function P.ResetOverlayLayoutState()
tooltipPositions = setmetatable({},{__mode="k"})
for _, state in pairs(alertScales) do state.base=1 end
P.tooltipUnplaced, P.tooltipOverInventory, P.tooltipOverSocial = nil, nil, nil
P.overlayRevision = (P.overlayRevision or 0) + 1
end
function P.ResetTooltipPosition(tooltip)
tooltipPositions[tooltip]=nil
P.tooltipUnplaced=nil
@ -516,7 +517,7 @@ function P.InitializeOverlayLayout(placeFrame,frameEdge,owns)
end
schedule=queue
local function watch()
for _,name in ipairs({"AlertFrame","GroupLootContainer","TalkingHeadFrame"}) do
for _,name in ipairs({"AlertFrame","GroupLootContainer","TalkingHeadFrame","ChatFrame1EditBox","ChatFrame1Tab"}) do
local f=_G[name]
if f and not hooked[f] then
hooked[f]=true

View File

@ -168,13 +168,14 @@ end
local function visuals(button)
local item = button.item
button:SetChecked(false)
if not item then
P.SetActionButtonSelected(button, false)
button.AutoCastOverlay:Hide()
button.cooldown:Clear()
return
end
if not button.actionSlot then
P.SetActionButtonSelected(button, false)
button.icon:SetVertexColor(.4,.4,.4)
button.AutoCastOverlay:Hide();button.cooldown:Clear()
return
@ -183,6 +184,7 @@ local function visuals(button)
-- 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
P.SetActionButtonSelected(button, false)
button.icon:SetVertexColor(.4, .4, .4)
button.AutoCastOverlay:Hide()
button.cooldown:Clear()
@ -190,12 +192,13 @@ local function visuals(button)
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
local selected = false
if C_ActionBar and C_ActionBar.IsCurrentAction then selected = C_ActionBar.IsCurrentAction(button.actionSlot) end
P.SetActionButtonSelected(button, selected, item.command == "/petattack")
button.AutoCastOverlay:Hide();button.cooldown:Clear()
return
end
P.SetActionButtonSelected(button, false)
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)
@ -219,7 +222,9 @@ end
local function hotkeys()
for _, button in ipairs(buttons or {}) do
local key = GetBindingKey("CLICK " .. button:GetName() .. ":LeftButton")
local binding = "CLICK " .. button:GetName() .. ":LeftButton"
local key
if P.EffectiveBindingKey then key = P.EffectiveBindingKey(binding) else key = GetBindingKey(binding) end
button.HotKey:SetText(key and GetBindingText(key, true) or "")
end
end
@ -229,26 +234,6 @@ local function updateVisuals(self,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
@ -300,7 +285,7 @@ function P.RefreshPetExtras()
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
P.StyleActionButton(button, PetActionButton1)
button:SetAttribute("type1", actionSlot and "action" or nil)
button:SetAttribute("action1", actionSlot)
button:SetAttribute("type2", nil) -- right-click is autocast, not a cast
@ -393,9 +378,6 @@ function P.InitializePetExtras(isEnabled)
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")

View File

@ -1,6 +1,6 @@
local _, P = ...
P.version = 5
P.release = "2026.11.21.5-beta.1"
P.release = "2026.11.22.6-beta.1"
P.graphicsVersion = 2
P.layoutName = "Ruen UI - Clear ESDF"
function P.IsOurLayout(layout)
@ -18,6 +18,10 @@ function P.SaveEditModeLayouts(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
-- A native layout reload restores ALL saved anchors and tracker height,
-- even when the only change was an optional cooldown/meter setting.
-- Reconcile owned control geometry before placing those optional viewers.
if P.ReconcileControlGeometry then P.ReconcileControlGeometry() end
end
-- Values verified against Blizzard's Forever (Camelot) SettingsDefinitions.
-- Quality sliders are zero-based; do not set the master preset afterward.

View File

@ -1,7 +1,7 @@
## 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
## Version: 2026.11.22.6-beta.1
## Author: Ruen UI contributors
## SavedVariables: RuenUIDB
## SavedVariablesPerCharacter: RuenUICharacter
@ -12,8 +12,11 @@ Locale.lua
Brand.lua
LanguageDefaults.lua
Controls.lua
CharacterProfiles.lua
LayoutPolicy.lua
GunAudio.lua
ClassLayout.lua
ButtonStyle.lua
PetExtras.lua
SwingTimers.lua
ExtraBars.lua
@ -21,6 +24,9 @@ OverlayLayout.lua
DamageMeters.lua
ClassAssist.lua
HardwareProfile.lua
FrameTiming.lua
Optimizer.lua
Benchmark.lua
AddonPresets.lua
LayoutRecovery.lua
Core.lua

View File

@ -26,6 +26,7 @@ CooldownViewer.lua
CooldownViewerSettingsDataProvider.lua
ActionButtonUtil.lua
Blizzard_SpellSearchUtil.lua
AddOnProfilerConstantsDocumentation.lua
```
Example:
@ -35,6 +36,7 @@ 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-benchmark.lua "$PWD/RuenUI/"
luajit tests/check-timers-optimizer.lua "$PWD/RuenUI/"
```
@ -46,6 +48,17 @@ 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.
The coordinated release runner requires all runtimes and fixtures explicitly, records each suite's exit status, and stops at the first failure:
```sh
python3 scripts/check_release.py --native-ui /path/to/matching-native-fixtures \
--audio-fixtures /path/to/test-addons --pwsh /path/to/pwsh --output /path/to/check-results
```
The two new standalone checks are `luajit tests/check-profiles.lua "$PWD/RuenUI/"` and `luajit tests/check-layout-policy.lua "$PWD/RuenUI/"`. The profile fixture executes the actual restricted binding snippet against a modeled engine, including native-control transitions in combat. It does not emulate the live secure VM or certify binding priority there.
For a pure geometry comparison, preserve the preceding `OverlayLayout.lua` and run `luajit tests/benchmark-layout.lua "$PWD/RuenUI/" /path/to/baseline/OverlayLayout.lua`. This measures only bounded rectangle searches, not live FPS, GPU load or allocations from the complete UI. A live `/ruen bench` comparison needs the same scene/settings and a continuously focused game window.
Build the downloadable installer:
```sh
@ -55,3 +68,6 @@ 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.
The frame recorder is in `FrameTiming.lua` and must precede both `Optimizer.lua` and `Benchmark.lua` in fixtures and the TOC. `check-benchmark.lua` includes smooth reported FPS with sparse 200 ms stalls, partial/pause/loading behavior, multi-second stalls, bounded persistence and no idle updates. `check-timers-optimizer.lua` exercises scene retuning, four independent environment profiles, targets, capped final validation, sparse-hitch rejection, loading/combat deferral, unsupported controls and exact restore. These simulations establish detection/selection behavior, not real GPU responsiveness or improvement in the user's cave.

View File

@ -1,7 +1,7 @@
# Установка 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**. Для скачивания регистрация не нужна.
2. Откройте [Releases](https://scm.bstein.dev/bstein/ruen-ui/releases) и скачайте **Ruen-UI-2026.11.22.2-beta.1.zip**. Для скачивания регистрация не нужна.
3. Полностью распакуйте ZIP. Закройте WoW.
4. Для русского варианта запустите **Install-Russian.cmd**. Обычная установка: **Ruen-Setup.exe**. Установщик сам ищет игру; если нужно, укажите папку `_forever_`, в которой находится `Wow.exe`.
5. В Battle.net выберите WoW: Forever → шестерёнка → изменение установки. Установите английские и русские файлы игры. Выберите русский язык текста и речи в настройках **игры**, а не приложения Battle.net. Дождитесь 100% загрузки.
@ -18,6 +18,36 @@
Аддоны и записи скачиваются непосредственно у их авторов. Английский + русский вариант требует примерно **2,26 ГБ загрузок**, а также место для распаковки и резервных копий. Файлы языка самой игры скачиваются отдельно через Battle.net.
Это первая публичная бета: чистая установка и работа на Windows ещё требуют проверки. Программа не меняет видеодрайверы. Исполняемый файл не подписан; его исходный код включён. Не отключайте защиту Windows ради установки.
Это публичная бета: чистая установка и работа на Windows ещё требуют проверки. Программа не меняет видеодрайверы. Исполняемый файл не подписан; его исходный код включён. Не отключайте защиту Windows ради установки.
Инструкции по обновлению, резервным копиям и оптимизации: [INSTALL.md](INSTALL.md). Ошибки: [Issues](https://scm.bstein.dev/bstein/ruen-ui/issues).
## Управление классами и обновление
Обновление сохраняет способности на панелях, свои назначения клавиш, язык и настройки графики. Не запускайте `/ruen apply` для обычного обновления: эта команда намеренно применяет стандартные настройки заново.
- Охотник и чернокнижник: **1–0, -, =** — питомец; **Ctrl + цифры** — нижняя правая дополнительная панель.
- Остальные классы: **цифры** — дополнительная панель, **Ctrl + цифры** — питомец, если он есть. Незаметность, формы и исчезновение питомца не меняют эти клавиши. Управление транспортом и одержимостью временно получает приоритет.
- `/ruen keys auto|pet|utility` — профиль цифровых клавиш для этого персонажа. Свои назначения сохраняются; `/ruen status` показывает исключения.
- `/ruen role auto|healer|tank|damage` — роль для автоматического применения заклинаний по наведению. Режим auto включает его только при достоверной роли лекаря. Если игра не сообщает роль, выберите её командой. `/ruen mouseover on|off` — прямой выбор. При обновлении сохраняется прежний эффективный режим.
- Режимы индикаторов перезарядки и урона теперь отдельные для каждого персонажа. `/ruen cooldowns show|hide|auto`; `/ruen meters auto|show|off`. У нового персонажа индикаторы перезарядки выключены, счётчик урона включается в подземельях и рейдах.
Панель питомца — это **10 стандартных ячеек и 2 расширения** с использованием свободных ячеек второй страницы панели действий. Игра не получает дополнительные стандартные ячейки питомца. Если свободных ячеек нет, Ruen сообщает об этом и не затирает существующие способности.
Чтобы отменить увеличение или перемещение чата, закройте режим редактирования, выйдите из боя и введите `/ruen chat reset`. Команда восстановит удобный размер чата внизу слева с учётом доступного места и переместит соседние панели. Ширина занимает до 30% доступной области интерфейса (не более 620 единиц), не перекрывая центральные панели; высота — 190–260 единиц. Например, для области интерфейса 1920×1080 размер чата будет 570×230, а для 2133×1200 — 620×260. Масштаб интерфейса учитывается. Проверены доступные области интерфейса от 1280×720, включая форматы 16:10, 4:3 и сверхширокие экраны. Более крупный масштаб, оставляющий меньше места, не проверен; Ruen не уменьшает шрифт или общий масштаб автоматически. Размер по умолчанию автоматически подстраивается при изменении доступного места. Ручное изменение размера или положения отключает эту подстройку; ширина по-прежнему ограничивается, чтобы не закрывать центральные панели. Выбранный шрифт сохраняется. Обе команды сброса используют одинаковые размеры по умолчанию. `/ruen layout reset` сбрасывает положение всех элементов режима редактирования WoW, включая эффекты, питомца, боссов, арену и предупреждения рейда, затем применяет расположение и размеры Ruen. Также пересчитываются сумки, подсказки и уведомления, перемещаются открытые стандартные окна, сбрасывается положение окон Spoken/Compendium и карты Leatrix Maps. Неподдерживаемые элементы перечисляются в чате; сторонние аддоны вне комплекта управляют своим расположением самостоятельно. Графика, клавиши, способности, шрифт и фильтры чата, режимы перезарядок и счётчиков сохраняются. Другие расположения не меняются. Сохранённое расположение Ruen используется всеми персонажами, выбравшими его. Предыдущая строка экспорта хранится в `RuenUICharacter.layoutBeforeReset`. `/reload` загружает обновлённый код, но не отменяет сохранённые изменения расположения.
После обновления проверьте `/ruen status`, цифровые клавиши, смену защитной/пассивной стойки, вызов питомца и сумки при выбранной цели. Для сравнения FPS запустите `/ruen bench` и три минуты играйте, не переключаясь в другое окно: фоновое ограничение FPS иначе исказит результат. Следующая строка показывает время CPU Ruen, если встроенный профилировщик доступен. При рывках сообщите обе строки; измерение не меняет настройки графики. Подробные ограничения беты: [RELEASE-REVIEW.md](RELEASE-REVIEW.md).
## Рывки и настройка графики в текущей зоне
Вне боя введите `/ruen optimize 60` (или `30` для цели 30 FPS), затем 2–5 минут двигайтесь и сражайтесь в этой зоне. Без числа команда использует 60 FPS либо сохранённую цель. Повторный запуск заново проверяет текущую зону. Мир, подземелье, рейд и поле боя измеряются отдельно. Изменения применяются вне боя; после завершения постоянного опроса кадров нет.
Проверяются время кадров и отдельные задержки, включая редкие кадры дольше 100 мс. Если минимальные настройки не обеспечили цель, Ruen прямо сообщает об этом. Разрешение, масштаб отрисовки, текстуры, интерфейс и драйверы сохраняются; настраиваются в том числе освещение и тени. Пока оптимизатор включён, он сам переключает профили и отключает встроенную замену графики для рейдов. Датчики температуры по-прежнему проверяет внешняя утилита.
`/ruen optimize status` — состояние; `pause` — остановить измерение; `resume` — продолжить работу профилей; `restore` — вернуть исходную графику. Перед переключением в другое приложение используйте `pause`: активность окна автоматически не определяется.
После настройки `/ruen bench` записывает каждый игровой кадр за три минуты: средний FPS, 1% low, p99, максимальную задержку и количество кадров дольше 50/100/250 мс. Загрузочные экраны исключаются, реальные многосекундные рывки учитываются. `/ruen bench pause|resume|stop|status` управляет замером; `stop` сохраняет неполный результат. Одновременная настройка графики и замер запрещены. Последние пять отчётов сохраняются при выходе или `/reload`. Старые секундные выборки FPS нельзя напрямую сравнивать с новыми процентилями кадров.
Оптимизатор теперь выводит фактические значения «до → после» при изменении настроек, результат каждого 20-секундного замера и однократное сообщение об ожидании окончания боя. Временный лимит FPS помечается отдельно. Итоговый список сравнивается с началом запуска; если значения не изменились, это указано явно. `/ruen optimize changes` повторяет последний список, `/ruen optimize status` показывает версию, ход замера и причину ожидания.

View File

@ -2,7 +2,7 @@
## 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.
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 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:
@ -42,9 +42,53 @@ Do not run with sudo. Discovery checks common Wine, Steam compatibility and Game
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.
## Class controls after updating
This update keeps existing actions, personal keybindings and saved language/graphics settings. It does not rerun the full preset on every character. Do not use `/ruen apply` just to update: that command deliberately reapplies defaults. Log in normally, or use `/reload` if only the addon files were updated during a running session.
- Hunters and Warlocks: **1–0, -, =** control pets; **Ctrl + numbers** controls the lower right utility bar.
- Other classes: **numbers** control that utility bar; **Ctrl + numbers** controls pets when present. Stealth, forms and pet dismissal do not change this mapping. Native vehicle/possession controls take over temporarily.
- `/ruen keys auto|pet|utility` chooses a character's number-key profile. Existing custom bindings win; `/ruen status` lists keys preserved instead of reassigned. `/ruen bindings` deliberately reapplies Ruen's mouse/menu/utility mappings.
- `/ruen role auto|healer|tank|damage` selects the role used for automatic mouseover casting. Auto enables it only when the native game reports a healing role. If this client does not report a role, choose one explicitly. `/ruen mouseover on|off` remains the direct override. Upgrades preserve the previous effective mouseover choice.
- Cooldown and meter modes are now per character. Existing choices migrate once; fresh characters start with duplicate cooldown viewers off and meters automatic in dungeons/raids. `/ruen cooldowns show|hide|auto` and `/ruen meters auto|show|off` change them.
The pet bar is **ten native pet slots plus two extensions**, backed by spare slots on unused action page 2. It cannot create native pet slots 11 and 12. If the backing page is full, Ruen reports the limitation and preserves the existing actions. The two extensions use the same selected-state artwork as native buttons; the game determines which stance is active.
To undo an enlarged or moved chatbox, close Edit Mode and leave combat, then use `/ruen chat reset`. This restores a readable, screen-sized chatbox at the lower left and repositions the nearby bars. The default uses up to 30% of the usable UI width (capped at 620), fits clear of the center action bars, and is 190–260 UI units tall depending on screen space. For example, a 1920×1080 usable UI gets 570×230; 2133×1200 gets 620×260. Larger UI scales reduce the usable space. Layout checks cover usable UI areas of at least 1280×720, including 16:10, 4:3 and ultrawide displays; larger UI scales that leave less space are not validated. Ruen respects your UI scale and font instead of shrinking text automatically. An untouched default follows viewport changes automatically. Manual size/position edits opt out of that automatic sizing; width still fits clear of the center bars. Font preferences are preserved. Both chat reset and full layout reset use this same sizing policy. `/ruen layout reset` restores every native Edit Mode system position (including buffs/debuffs, pet/boss/arena frames, raid warnings and hidden class elements), then applies Ruen's default controls and sizes. It also resets bag/tooltip/alert placement caches, repositions the current native panels, restores Spoken narration/Compendium positions and invokes Leatrix Maps' own map-position reset. Frames that are not currently visible receive their saved native positions when they appear. Unsupported native systems or changed companion APIs are reported explicitly instead of silently claiming success; unrelated third-party addons retain their own layout controls. Both save the result without changing graphics, keybindings, assigned abilities, chat font/filter preferences or the selected cooldown/meter modes. Other Edit Mode layouts are retained. Ruen layouts are shared, so their saved geometry also applies to other characters using that layout. The previous layout export is retained in `RuenUICharacter.layoutBeforeReset` for recovery. `/reload` loads updated code; it does not itself undo your saved layout edits. `/ruen apply` reapplies gameplay/key defaults and selects the existing saved layout, so it is not the command for undoing a chat resize.
Before relying on new bindings in combat, check `/ruen status`, press the number keys, and verify the indicated actions. On a pet character, test Defensive on an extra button, then Passive on a native button: only the active stance should remain selected. Check click/key activation, right-click autocast where supported, dismissal/resummon, bags with a selected target, and an item comparison tooltip. The release review distinguishes automated checks from live coverage.
## Optional optimization
Run while playing a representative area, with the laptop powered and cooled as you normally use it:
For stuttering in the current area, run this **outside combat**, then move and fight in the same area with WoW focused:
```text
/ruen optimize 60
```
Use `/ruen optimize 30` for a 30 FPS target (accepted range 20–240). `/ruen optimize` alone uses 60 initially, then remembers your requested target. It **remeasures the current environment even if an earlier sample elsewhere passed**. World, dungeon, raid and battleground profiles are separate; a cave outside an instance is a world sample. Saved profiles apply on environment changes, outside combat. While enabled, Ruen owns the base graphics settings and disables the native raid override so an unseen preset cannot replace the measured settings.
Calibration usually takes 2–5 minutes of gameplay (up to roughly seven if several final checks fail), plus time waiting for combat to end. It searches five ordered quality presets, requiring two passing 20-second windows before raising quality, then verifies the selected preset at your final FPS cap. Trial caps are at most 10% above the effective target. Smoothness checks include the 90th/99th percentile frame time and explicit counts above 50/100 ms; infrequent hitches cannot disappear behind a good average. At the lowest tier it reports an unmet target honestly if stalls persist. This finds the highest passing tested preset in the sampled scene, not a mathematically optimal configuration or a guarantee for every later fight.
The presets include shadows, ambient shading, secondary lighting, water, compute effects, visibility and scenery detail. Essential spell effects/projected textures remain enabled; render scale, texture resolution, UI geometry and GPU/API/driver selection are retained. The optimizer uses no per-frame loop after settling. It does not change fans, voltages or drivers. Shader compilation, asset streaming, other software, network stalls and overheating may require investigation outside graphics settings.
- `/ruen optimize status`: running release, environment, target, phase/saved tier, seconds recorded in the current window and any wait for combat/loading/benchmark.
- `/ruen optimize changes`: repeat the latest before/after summary. Each applied test prints real read-back changes, labels temporary FPS caps, and lists unavailable/rejected controls. Each 20-second check reports its result; waiting for combat is announced once. The final summary compares settings with the start of that run, excluding temporary changes that were undone. A step with no changes says so explicitly.
- `/ruen optimize pause`: stop measuring and retain the current/best tested settings; use this **before switching apps**.
- `/ruen optimize resume`: enable environment profiles and finish an unmeasured profile.
- `/ruen optimize restore`: stop calibration and restore the graphics values saved before optimization.
For a three-minute **read-only** measurement after optimization finishes:
```text
/ruen bench
```
This records every gameplay frame interval and reports actual frames/elapsed-time average FPS, the reciprocal of the mean slowest 1% frame time, p99 frame time, worst frame, and counts above 50/100/250 ms. Histogram percentiles use 0.25 ms bins, capped at 10 seconds; larger stalls are flagged and their worst duration is retained. Known loading screens are excluded, but ordinary multi-second gameplay stalls are counted. Window focus cannot be verified: use `/ruen bench pause` before switching apps and `/ruen bench resume` when back. `/ruen bench stop` saves a clearly marked partial run; `status` reports progress. Benchmarking and active calibration cannot run together.
The following line reports Ruen CPU time from the built-in profiler when available. Its recent timings are rolling averages; correlation does not prove the cause of a hitch. CPU threshold deltas cover wall time, including pauses/loading. The saved report includes up to 180 diagnostic snapshots and graphics settings at both endpoints; the latest five reports are retained on logout/reload. Compare the same route, activity, settings and window size. The old one-second FPS benchmarks are not directly comparable to the new frame percentiles.
Optional **hardware/thermal evidence** still comes from the external companion, run while playing normally with the laptop powered/cooled as usual:
```powershell
.\Ruen-Setup.exe --optimize 30 -Seconds 600
@ -54,7 +98,7 @@ Run while playing a representative area, with the laptop powered and cooled as y
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.
Type `/reload` afterward to import its report. Recent thermal/performance pressure limits the quality search; thermal pressure can lower a requested target above 45 to 45 FPS. Missing sensors are reported as unavailable, never proof of safe temperatures. No stress test or driver installation is performed.
## Undo

View File

@ -1,8 +1,68 @@
# Release review — 2026.11.21.5-beta.1
# Release review — 2026.11.22.6-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.
## Chat resolution follow-up (2026-11-22)
## Changes made for public distribution
- Kept the user-approved sizing limits: up to 30% of usable UI width (620 maximum), 190–260 height, with width fitted against the combat bars. The cap keeps long lines manageable on wide screens; the shorter laptop default leaves room for notifications and group controls. This is a balanced default, not a claim of one optimal size for every reader/font.
- Corrected a real native compatibility gap: the chat selection extends 32 units to the left, so the engine clamps a requested x=20 to x=32. The former exact x=20 ownership check interpreted this as a manual move and stopped adaptive sizing. The default origin now reads the frame's clamp insets, accounts for scale and accepts both requested and clamped saved origins. Deliberate size/position edits still opt out. Native selection geometry and clamp behavior were checked against the [client's UI source](https://github.com/Gethe/wow-ui-source/blob/bebcb6bf309cf41b41bd74f8ca651e6a105b2676/Interface/AddOns/Blizzard_EditMode/Shared/EditModeSystemTemplates.xml#L171).
- The left control shelf follows the layout margin rather than the chat's extra text inset. Class rows now reserve their measured height instead of imposing a 30-unit floor on 24-unit stance/aspect controls. This recovers six vertical units for the full hunter HUD at 720p while preserving button size and the cast-label/swing gap.
- Regression fixtures now model native chat clamping and current Forever bar dimensions: 505.8×40.5 center rows and 252×82.8 side bars. The full matrix covers 20 display/scale/reset configurations, including 16:10, 4:3, ultrawide and 4K at multiple scales. Repeated shrink/grow cycles, combat deferral, clamped native save/reload and custom-size preservation are exercised separately. The previous simplified unclamped fixture missed the resize bug; it is no longer used for the matrix.
- The user confirmed the roomier chat looks better before this follow-up. These compatibility fixes still require a live reload; repeated live monitor/scale switching and every class/raid combination have not been observed. No per-frame layout work was added.
## Readable chat defaults (2026-11-22)
- New layouts and both reset commands replace the fixed 380×150 chatbox with a default based on usable UI dimensions: up to 30% width, capped at 620, and 190–260 height. Width still fits against the actual center action row. Examples: 570×230 at 1920×1080 UI units; 620×260 at 2133×1200. High UI scales are accounted for without relying on physical resolution alone.
- Placement remains at the lower left, with notification space and the compact utility bars reflowed above it. An untouched default also adapts on viewport changes; saved native geometry is read without modification and a bounded account record identifies the default. Manual size/position edits opt out of automatic sizing (width still respects the center-bar clearance), and font preferences are retained. No polling, new hooks or additional idle work were added.
- Checks cover fresh installation, both explicit resets, native layout reactivation, all nine classes, custom dimensions, unrelated settings, and the largest saved default surviving a switch to 720p. Existing installations receive the new size with `/reload` followed by `/ruen chat reset` (or full layout reset). The user confirmed the larger chat is better.
## Complete layout recovery follow-up (2026-11-22)
- Full reset now starts with every native Edit Mode system anchor, including pet/boss/arena unit frames, buff/debuff groups, raid warnings, timer/resource displays, durability and hidden class features. Secondary snap anchors are discarded. Native defaults come from this client's preset; existing functional settings and other saved layouts are retained.
- Ruen's control/class geometry is then reapplied. Bag scaling, encounter-widget scaling, tooltip caches, alert scaling and optional cooldown layout caches are reset before reflow; meter/cooldown visibility preferences stay unchanged.
- Standard loaded panels are returned to the native panel manager without replacing protected handlers. Spoken's position-only reset and the Compendium window are included. Leatrix Maps uses its pinned upstream reset button (identified by its locale-independent tooltip property) so the private live settings are saved correctly; writing its public DB alone would be undone on logout.
- Unknown native systems and unavailable companion reset APIs are reported in chat and saved diagnostics. Arbitrary third-party addons are outside this reset's ownership. The operation is explicit, guarded out of combat/Edit Mode, and adds no recurring per-frame work. Chat-only reset remains available.
- Regression coverage exercises all 31 native system kinds, indexed unit/action/aura systems, snap-anchor removal, persistence, companion handoff/failures, all nine class layouts and preservation of unrelated settings/actions/bindings. The user has exercised full reset in game; the resulting undersized chat prompted this sizing update. Other unobserved native/companion panels still require live checks.
Reviewed 22 November 2026. **Opt-in public beta; not a general-availability certification.** This release improves the chat dimensions used by explicit chat/layout recovery, alongside the existing graphics feedback and frame-timing updates. It retains the user-confirmed beta8 pet highlight fix and coordinated layout/profile work. The optimizer has detected roughly 0.6-second stalls even at its lowest graphics tier and reports the target as unmet; this layout update does not claim to resolve those stalls.
## Frame timing and scene optimization
- Setting changes are derived from CVar read-back snapshots; rejected writes are not reported as applied. Temporary trial caps are labeled. Final summaries compare against run-start values, with no-change cases explicit. Status includes the running release and progress/wait state. Progress is emitted only at measurement boundaries; combat waits are announced once, not per frame. Regression checks cover these distinctions and report commands perform no writes.
- Manual benchmarking records bounded 0.25 ms frame histograms, true frames/elapsed-time average, mean slowest-1% FPS, p99, worst duration, and explicit >50/100/250 ms frame counts. Sparse hitches remain visible even when smoothed FPS and p99 look healthy. Only known loading is excluded; >2-second gameplay stalls no longer disappear.
- The optimizer accepts an in-game FPS target and retests the current environment. Dungeon and battleground profiles are now separate from world/raid profiles. It explicitly owns the active base settings, disabling native raid overrides, and includes cave-relevant secondary lighting plus PBR water controls omitted by the old tuner.
- Five quality presets, two passing 20-second windows before upgrades, up to ten search windows plus bounded capped validation. Final checks include explicit hitch counts. Persistent stalls at the minimum tier are reported as unmet; the search cannot guarantee an optimal setting combination or solve all external causes.
- Changes wait until outside combat. Loading/environment changes discard cross-scene evidence. Benchmarking and active tuning are mutually exclusive. Settled profiles remove their OnUpdate handler. Restore retains original values; render scale, UI scale, texture resolution and GPU/API/drivers are not modified.
- Focus is not automatically known: explicit pause/resume commands and instructions prevent knowingly counting app switching as gameplay. Native profiler snapshots stay bounded and run only during the manual benchmark.
## Coordinated update
- Custom pet extensions copy native named texture regions, including selected-state geometry, opacity and blend mode. Live beta7 diagnostics confirmed correct action/checked state but an absent atlas on the extension texture. This client lacks the widget-level checked-atlas setter; copying only the atlas file ID draws the wrong region. The fix applies the native atlas directly to the checked texture and leaves atlas coordinates under the engine’s control. Regression fixtures now cover the missing widget setter as well as plain native file textures. They display the engine's active command, rather than remembering the last click; Passive/Defensive/Aggressive selections remain mutually exclusive. Attack gets its separate flash treatment.
- Number-key profiles are per character. Hunters/Warlocks default to pets on plain numbers; the other seven classes default to utility actions. Secure, non-priority overrides leave account bindings intact and hand off during possession/vehicles. Custom assignments win. Pet dismissal, rogue stealth and druid forms do not flip the profile.
- Role-aware mouseover defaults use a reported specialization/assigned role or an explicit choice. Unknown roles do not imply healing. Existing effective choices survive migration. Group-role changes are observed without polling.
- Cooldown/meter choices migrate from account defaults to character settings. New characters start with duplicate cooldown viewers off. Existing characters keep their selections; auto meters remain dungeon/raid only.
- Placement and diagnostics share the same ten-frame control reservations, common spacing and chat defaults. Chat tabs/input and native profession/spellbook/map/auction panels are additional obstacles. Fresh chat starts at font size 14; existing fonts are retained.
- Native layout saves now reconcile the owned control geometry immediately, including the tracker height. Changing optional cooldown/meter settings no longer leaves the saved tracker overlapping utility controls until another layout event.
- A fresh alt on an already-configured account no longer replays shared combat/menu defaults. Existing action assignments, settings and binding backups remain intact. The main preset revision stays unchanged to avoid a full reset; the targeted class-layout migration advances independently.
## Class-by-class result and remaining live checks
All rows below passed modeled geometry and binding behavior. None constitutes a complete live level-60/spec certification.
| Class | Main concern addressed or retained | Live test still needed |
| --- | --- | --- |
| Warrior | Numbers are useful utility keys; native stances/main-bar paging and swing lanes remain intact. | Swap all learned stances in combat; verify rage, off-hand and possession controls. |
| Paladin | Utility numbers; native aura controls; healing input follows role rather than class alone. | Aura changes, tank/damage/healer roles and party mouseover casts. |
| Hunter | Plain-number pet profile; centered ten-plus-two row; consistent stance selection and real backing actions. | Both extensions by key/click, native-to-extra stance transitions, autocast, pet death/swap. |
| Rogue | Numbers no longer default to an absent pet; native stealth paging and combo-point attachment are retained. | Enter/leave stealth and temporary override states; confirm ability paging and combo visibility. |
| Priest | Utility numbers; learned forms remain native; healing input is explicit or role-based. | Shadow/healing roles, forms, mouseover casts and possession return. |
| Shaman | Separate totem reservations; optional cooldowns do not replace totem controls; role-based mouseover. | Maximum totems/recall, melee/caster/healer roles and temporary pet overlap. |
| Mage | Utility numbers; petless specs do not reserve an unconditional pet row; acquired pets use a stable row. | Temporary pet acquisition/dismissal, cooldown availability and combat appearance. |
| Warlock | Plain-number demon controls; extra actions track pet knowledge/rank and preserve occupied player slots. | Swap demon types, two extra actions, autocast and resummon in combat. |
| Druid | Utility numbers remain stable across forms; native form paging/combo points; role-based input. | All learned forms, tank/healer/damage roles and changed native action pages. |
The common 96-button action layout is retained. It provides capacity, not automatic spell or rotation assignment. Class-only controls remain native wherever possible. `/ruen keys`, `/ruen role`, `/ruen mouseover`, cooldown and meter commands provide explicit exceptions without changing another character.
## Distribution protections retained
- 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.
@ -17,17 +77,20 @@ Reviewed 21 November 2026. **Suitable for an opt-in public beta, not a general-a
| 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. |
| Windows scripts | PowerShell 7.7 on Linux executed filesystem fixtures. Syntax parsed successfully. The unchanged unsigned x64 executable and its included C source retain the preceding release review; this update does not change the launcher binary. **Native Windows PowerShell 5.1, SmartScreen and GUI execution remain untested.** |
| Dependencies | The previous distribution review downloaded, hashed and extracted all four base archives against the unchanged lock, and installed them through PowerShell in a disposable game path containing spaces and Cyrillic characters. The preceding beta8 review checked all seven unchanged pinned download endpoints: HTTPS 200 and matching byte counts. This HEAD check does not replace archive hashing; current installations verify the full pinned downloads. 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. |
| Character profiles | Nine classes × 24 effective number/Ctrl-number mappings; underlying account bindings unchanged, personal edits preserved, actual restricted snippet executed in a modeled engine, combat handoff/deferred changes, role events, capability reservations, restore, and full new-alt login with customized shared keys. **Live secure VM/priority behavior remains unverified.** |
| Layout policy | Shared control reservations, responsive chat size, fresh/reset/persistence/manual-size checks and chat font preservation/conditional restore; chat input/tabs and native panels counted without relocating their secure managers. |
| Layout matrix | 9 classes × 8 environments × 20 display/scale/reset cases, repeated with native aura/cast/combo/BG-widget footprints: **2,880 scenarios, zero modeled unintended intersections, offscreen controls, undersized group frames or wrong meter visibility**. Each display exercises its new chat defaults, plus a large saved chat on a smaller display without resetting it. 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. |
| 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. Native selected artwork, opacity/layer/blend parity, mutual stance state and 500 visual-only transitions passed. 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. |
| Timers/optimization | Swing lanes, idle sleep, secret values, four environment profiles, requested FPS parsing, sparse-hitch rejection, capped validation, long-stall counting, loading/combat deferral, unsupported controls, thermal input, pause and exact undo passed. No native Windows hardware/thermal validation is claimed. |
| Benchmark diagnostics | Simulated 60 FPS readings with repeated 200 ms frame stalls expose the old blind spot. Per-frame capture, tail calculation, long stalls, loading/pause exclusion, five-report bounds and mutual exclusion passed alongside native profiler API availability/opaque values, per-run slow-tick deltas, 180-snapshot bound and graphics-change warnings. Recent timing is a rolling 60-tick mean, not an exact per-frame maximum. |
| 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.
Environments: solo, outdoor party, dungeon, 10/20/40-player raid and 10/40-player battleground. Displays: 1280×720 (fresh default and retained large-screen chat), 1366×768, 1920×1080 at two scales, 2133×1200, 2560×1440 at two scales, 3840×2160 at three scales, 1280×800, 1440×900, 1600×900, 1920×1200, 2560×1600, 1280×1024, 3440×1440 at two scales and 5120×1440. The smallest tested usable UI area is 1280×720; a high UI scale that leaves less space is outside this matrix. Ruen does not change UI scale or shrink text to claim a fit.
## Performance review
@ -35,6 +98,10 @@ Layout work is event-driven and coalesced; there is no idle geometry-search loop
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.
The added character profile and style helpers have no idle polling loop. Native button changes and role/binding events drive their work; repeated bindings use a cached signature. Selected-state updates do not write action slots. A pure Lua geometry microbenchmark is retained in `tests/benchmark-layout.lua`; it is not a game FPS benchmark and does not establish GPU/thermal behavior.
The focused local pre-update sample reported **56.1 FPS average, 47.5 minimum, 52.9 at the tenth percentile, and 0/180 readings below 30**. A preceding sample with uncertain window focus reached the configured 15 FPS background cap and was excluded as a reliable baseline. These are user-reported, one-second FPS readings, not per-frame lows. The user then reported a focused, comparable post-update run: **53.1 average, 21.4 minimum, 35.9 tenth percentile, 13/180 below 30**. This is an unresolved performance regression signal, not a passing gate. Its cause has not yet been attributed to Ruen, another addon or rendering/system load. No FPS improvement or performance parity is claimed. The follow-up benchmark samples the existing native profiler once per second and records per-run slow-tick counter deltas plus start/end graphics settings. It neither enables the expensive legacy script profiler nor changes graphics. A subsequent saved beta7 run reported **54.1 average, 15.0 minimum, 39.2 tenth percentile, 14/180 below 30**, with unchanged graphics endpoints. Native Ruen CPU timing averaged **0.0038 ms/tick** across sampled rolling averages; the largest sampled recent average was **0.291 ms**, and one tick exceeded 5 ms. Ruen registered zero recent CPU time at all 14 low-FPS readings; total addon timing there was approximately 0.011–0.059 ms/tick. These observations do not support sustained addon CPU work as the cause of those sampled dips. They do not exclude isolated stalls, rendering costs or background/system effects; the run reached the configured 15 FPS background cap and its focus history is unconfirmed. The original focused regression signal therefore remains unresolved. A hardware snapshot showed heavy GPU utilization without active GPU thermal slowdown; one snapshot cannot rule out intermittent throttling.
## 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.
@ -46,9 +113,9 @@ These are code and simulation findings. They do **not** guarantee an FPS budget,
## 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.
- The user confirmed that the actions work and beta7 reports the correct active/checked stance, but the selected border is absent. The missing-atlas cause was observed live. After installing beta8 and reloading, the user confirmed that Passive (`0`), Defensive (`-`) and Aggressive (`=`) all display the selected border correctly. Other pet types, autocast, pet swaps and live secure binding handoff remain incompletely tested.
- 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.
- Investigate the worse focused local FPS result with native addon CPU data; performance verification remains open. Sustained performance and available thermal telemetry on the destination laptop also remain untested.
- 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.

13
docs/UPDATE-PLAN.md Normal file
View File

@ -0,0 +1,13 @@
# Coordinated update stages
This sequence is the release checklist for the class-controls update. The [release review](RELEASE-REVIEW.md) records the actual coverage; a simulated pass is never recorded as live gameplay or native Windows validation.
1. **Preserve the baseline.** Record the current commit/release, installed addon, account/character binding files, relevant SavedVariables and native layout/config files. Keep the preceding public release available. Request a focused, representative FPS baseline without changing graphics.
2. **Correct pet presentation and behavior.** Keep ten native slots plus two real action-backed extensions. Share native visual treatment, test mutually exclusive stance state and Attack flashing, and exercise activation, autocast, ranks, pet changes, occupied slots and rejected placements. Never fill visible player bars with fallback copies.
3. **Isolate character controls.** Add explicit pet/utility profiles and role preferences. Preserve shared and personal bindings; hand off to native vehicle/possession controls. Migrate existing effective preferences once and verify undo and new-alt login. Keep form/stealth paging native.
4. **Use shared placement reservations.** Centralize control footprints, spacing and chat defaults. Treat bags, tooltips, input tabs, native panels and social notifications together. Keep low-resolution controls readable, and report unavoidable or player-created overlap rather than claiming every configuration can fit.
5. **Verify each class and scenario.** Run the nine-class matrix across solo/party/dungeon/raid/BG and 720p–4K scale fixtures. Run actual native methods in the harness where available. Separately check real pet visuals/actions, stealth/forms, roles, bags/target tooltips and populated group frames. Record unavailable live classes/specs explicitly.
6. **Review cost and installation.** Check idle/event behavior and bounded update rates; compare a matched focused FPS sample when available. Run Linux and PowerShell installer transactions, preservation, corruption, lock and rollback checks. Native Windows launcher/SmartScreen/driver/thermal behavior requires a real destination-machine test.
7. **Publish a reversible beta.** Build the first-party allowlisted ZIP with file manifest and ZIP checksum; verify its contents and reproducibility. Publish a new Gitea prerelease and English/Russian instructions without replacing the previous tag/assets. Download the assets anonymously and verify their checksums. A release remains beta while the material native Windows/live-class checks are open.
Public distribution does not certify every laptop, third-party addon combination or level-60 specialization. A failure in automated controls/installer checks blocks the candidate; unavailable live coverage is disclosed prominently and is not a pass. Reproduce automated checks using [DEVELOPMENT.md](DEVELOPMENT.md). Install/update/restore using [INSTALL.md](INSTALL.md).

View File

@ -7,7 +7,7 @@ from pathlib import Path
import zipfile
ROOT = Path(__file__).resolve().parents[1]
VERSION = '2026.11.21.5-beta.1'
VERSION = '2026.11.22.6-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',

50
scripts/check_release.py Normal file
View File

@ -0,0 +1,50 @@
#!/usr/bin/env python3
"""Reproduce release checks, with explicit required fixture/runtime inputs."""
import argparse
import json
import os
from pathlib import Path
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--native-ui', required=True, type=Path)
parser.add_argument('--audio-fixtures', required=True, type=Path)
parser.add_argument('--pwsh', required=True, type=Path)
parser.add_argument('--output', required=True, type=Path)
args = parser.parse_args()
args.output.mkdir(parents=True, exist_ok=True)
env = dict(os.environ, RUEN_NATIVE_UI=str(args.native_ui.resolve()),
RUEN_PWSH=str(args.pwsh.resolve()), PYTHONDONTWRITEBYTECODE='1')
addon = str(ROOT / 'RuenUI') + '/'
checks = [
('profiles', ['luajit', 'tests/check-profiles.lua', addon]),
('layout-policy', ['luajit', 'tests/check-layout-policy.lua', addon]),
('layout-recovery', ['luajit', 'tests/check-layout-recovery.lua', addon]),
('pets', ['luajit', 'tests/check-pet-actions.lua', addon]),
('layout', ['luajit', 'tests/check-layout.lua', addon, 'unused', str(args.output.resolve() / 'matrix.txt')]),
('meter', ['luajit', 'tests/check-meter.lua', addon]),
('timers-optimizer', ['luajit', 'tests/check-timers-optimizer.lua', addon]),
('benchmark', ['luajit', 'tests/check-benchmark.lua', addon]),
('audio', ['luajit', 'tests/check-gun-audio.lua', str(args.audio_fixtures.resolve())]),
('installers', [sys.executable, '-m', 'unittest', 'discover', '-s', 'tests', '-v']),
]
results = {'platform': sys.platform, 'nativeWindowsTested': False, 'liveGameTested': False, 'checks': []}
for name, command in checks:
with (args.output / (name + '.log')).open('w') as log:
result = subprocess.run(command, cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT)
results['checks'].append({'name': name, 'exitCode': result.returncode})
(args.output / 'results.json').write_text(json.dumps(results, indent=2) + '\n')
print(name, 'PASS' if result.returncode == 0 else 'FAIL', flush=True)
if result.returncode:
print((args.output / (name + '.log')).read_text()[-4000:])
return result.returncode
return 0
if __name__ == '__main__':
raise SystemExit(main())

View File

@ -0,0 +1,26 @@
-- Pure geometry benchmark. This measures neither live FPS nor secure/UI work.
local root,baseline=assert(arg[1]),assert(arg[2])
local function loadPlacement(path)
local p={};assert(loadfile(root..'LayoutPolicy.lua'))('RuenUI',p)
assert(loadfile(path))('RuenUI',p);return p.FindOverlayPosition
end
local old,new=loadPlacement(baseline),loadPlacement(root..'OverlayLayout.lua')
local crowded={}
for i=1,16 do
local x=(i-1)%4*330;local y=math.floor((i-1)/4)*180
crowded[#crowded+1]={left=x,right=x+210,bottom=y,top=y+115}
end
local function measure(fn,obstacles)
for i=1,200 do fn(240,100,900,350,obstacles,1366,768)end
local runs={}
for n=1,7 do
collectgarbage('collect');local start=os.clock()
for i=1,1500 do fn(240,100,900,350,obstacles,1366,768)end
runs[n]=(os.clock()-start)*1000/1500
end
table.sort(runs);return runs[4],runs[7]
end
for _,case in ipairs({{'clear',{}},{'crowded',crowded}})do
local before=measure(old,case[2]);local after,worst=measure(new,case[2])
print(string.format('%s search: baseline median %.4f ms; candidate median %.4f ms; slowest run %.4f ms',case[1],before,after,worst))
end

100
tests/check-benchmark.lua Normal file
View File

@ -0,0 +1,100 @@
local root=assert(arg[1])
local P={release='test',Localized=function(a)return a end}
local cvars={maxFPS='60',maxFPSBk='15'}
RuenUIDB={optimizer={enabled=true,profiles={world={tier=2,calibrated=true}}}}
C_CVar={GetCVar=function(k)return cvars[k]end,SetCVar=function()error('benchmark must not change graphics')end}
function GetPhysicalScreenSize()return 1920,1080 end
-- No frame creation, timer, expensive script profiler or idle work is allowed.
local made={}
function CreateFrame()
local f={scripts={},events={}}
function f:SetScript(k,v)self.scripts[k]=v end
function f:RegisterEvent(e)self.events[e]=true end
made[#made+1]=f;return f
end
local opaque={};function issecretvalue(v)return v==opaque end
Enum={};APIDocumentation={AddDocumentationTable=function(_,d)
for _,t in ipairs(d.Tables or {})do if t.Type=='Enumeration'then
Enum[t.Name]={};for _,f in ipairs(t.Fields)do Enum[t.Name][f.Name]=f.EnumValue end
end end
end}
dofile(assert(os.getenv('RUEN_NATIVE_UI'))..'/AddOnProfilerConstantsDocumentation.lua')
local E=Enum.AddOnProfilerMetric
local readings={[E.RecentAverageTime]=.1,[E.CountTimeOver1Ms]=70,[E.CountTimeOver5Ms]=50,[E.CountTimeOver10Ms]=20,[E.CountTimeOver50Ms]=10}
local calls,topCalls=0,0
C_AddOnProfiler={IsEnabled=function()return true end,
GetAddOnMetric=function(name,k)assert(name=='RuenUI');calls=calls+1;return readings[k]end,
GetOverallMetric=function(k)assert(k==E.RecentAverageTime);return .4 end,
GetTopKAddOnsForMetric=function(k,n)assert(k==E.RecentAverageTime and n==3);topCalls=topCalls+1;return {{addOnName='Other',metricValue=.3}}end}
assert(loadfile(root..'FrameTiming.lua'))('RuenUI',P)
assert(loadfile(root..'Benchmark.lua'))('RuenUI',P)
assert(calls==0,'loading diagnostics started profiler work')
local d=P.StartBenchmarkDiagnostics()
for i=1,180 do
readings[E.RecentAverageTime]=i<=90 and .1 or .3
P.SampleBenchmarkDiagnostics(d,i<=167 and 60 or 25)
end
local before=calls;P.SampleBenchmarkDiagnostics(d,25)
assert(calls==before and #d.samples==180 and topCalls==13,'unbounded capture or top-addon scans')
readings[E.CountTimeOver5Ms]=53
local message=P.FinishBenchmarkDiagnostics(d)
assert(math.abs(d.sampledMeanMS-.2)<.0001 and d.maxSampledRecentMS==.3)
assert(d.ticksOver.CountTimeOver5Ms==3 and not d.settingsChanged,'used whole-session slow count')
assert(message:find('ticks over 5 ms: 3',1,true))
assert(d.samples[180].fps==25 and d.samples[180].allAddonsRecentMS==.4 and d.samples[180].topAddons)
assert(d.release=='test' and d.settingsStart.width==1920)
local changed=P.StartBenchmarkDiagnostics();cvars.maxFPS='72'
P.FinishBenchmarkDiagnostics(changed);assert(changed.settingsChanged and changed.settingsStart.maxFPS=='60')
-- Disabled/missing/restricted profiler never turns an FPS run into a Lua error
-- or invents a zero-cost report. Reset counters do not become negative counts.
for _,mode in ipairs({'disabled','missing','throws','opaque','nan'})do
local api=C_AddOnProfiler
if mode=='disabled'then C_AddOnProfiler={IsEnabled=function()return false end}
elseif mode=='missing'then C_AddOnProfiler=nil
elseif mode=='throws'then C_AddOnProfiler={GetAddOnMetric=function()error('unavailable')end}
elseif mode=='opaque'then C_AddOnProfiler={GetAddOnMetric=function()return opaque end}
else C_AddOnProfiler={GetAddOnMetric=function()return 0/0 end}end
local no=P.StartBenchmarkDiagnostics();P.SampleBenchmarkDiagnostics(no,25)
assert(P.FinishBenchmarkDiagnostics(no):find('unavailable') and not no.sampledMeanMS)
C_AddOnProfiler=api
end
local reset=P.StartBenchmarkDiagnostics();readings[E.CountTimeOver5Ms]=1
P.FinishBenchmarkDiagnostics(reset);assert(reset.ticksOver.CountTimeOver5Ms==nil)
print('PASS: bounded native profiler snapshots, per-benchmark slow-tick deltas, low-FPS attribution, graphics-change detection, unavailable/opaque data and no idle or graphics writes')
-- Fast smoothed FPS with sparse visible freezes: the old once/second FPS
-- sampling would pass, while frame recording must show their true duration.
function time()return 123456 end
function GetFramerate()return 60 end
P.BenchmarkCommand('');local f=made[#made]
assert(P.IsBenchmarkRunning())
local function frames(n,dt)for _=1,n do if f.scripts.OnUpdate then f.scripts.OnUpdate(f,dt)end end end
frames(60,1/60) -- initial settling
for i=1,11000 do frames(1,i%600==0 and .2 or 1/60)end
assert(not P.IsBenchmarkRunning() and not f.scripts.OnUpdate)
local report=RuenUIDB.reports[#RuenUIDB.reports]
assert(report.over100>=17 and report.worstMS==200 and report.p99MS<18,'sub-second hitches disappeared')
assert(report.low1FPS<report.meanFPS and report.meanFPS<60 and not report.partial)
assert(#report.diagnostics.samples<=180 and not report.diagnostics.settingsChanged)
assert(not report.focusVerified and report.diagnostics.samples[1].fps==60)
-- Loading and explicit pause exclude time, but unknown 3s stalls count.
P.BenchmarkCommand('');frames(120,1/60)
P.BenchmarkCommand('pause');frames(30,1);P.BenchmarkCommand('resume');frames(120,1/60)
f.scripts.OnEvent(f,'PLAYER_LEAVING_WORLD');frames(10,5)
f.scripts.OnEvent(f,'PLAYER_ENTERING_WORLD');frames(180,1/60)
frames(1,3);P.BenchmarkCommand('stop')
report=RuenUIDB.reports[#RuenUIDB.reports]
assert(report.partial and report.worstMS==3000 and report.over250==1 and report.excludedLoadingSeconds>=50)
assert(report.seconds<8 and not f.scripts.OnUpdate)
P.IsOptimizerCalibrating=function()return true end
P.BenchmarkCommand('');assert(not P.IsBenchmarkRunning())
P.IsOptimizerCalibrating=nil
for i=1,7 do P.BenchmarkCommand('');frames(120,1/60);P.BenchmarkCommand('stop')end
assert(#RuenUIDB.reports==5,'reports unbounded')
-- Histogram tail definition and invalid frame guard.
local sample=P.NewFrameSample()
for i=1,99 do P.AddFrameSample(sample,.01)end
P.AddFrameSample(sample,.2);P.AddFrameSample(sample,0);P.AddFrameSample(sample,math.huge)
local summary=P.FrameSampleSummary(sample)
assert(summary.frames==100 and summary.p99MS==10 and summary.low1FPS==5 and summary.over100==1)
print('PASS: every-frame stutter capture despite smooth FPS, actual slowest-1% average, loading/pause exclusion, long stalls, bounded reports, benchmark/optimizer mutual exclusion and no idle frames')

View File

@ -0,0 +1,42 @@
local root=assert(arg[1])
local P={}
assert(loadfile(root..'LayoutPolicy.lua'))('RuenUI',P)
local width,height
UIParent={GetWidth=function()return width end,GetHeight=function()return height end}
for _,case in ipairs({{1280,720,380,190},{1366,768,400,190},
{1920,1080,570,230},{2133,1200,620,260},{3840,2160,620,260},
{3840/2.8125,2160/2.8125,400,190}})do
width,height=case[1],case[2]
local w,h=P.DefaultChatSize()
assert(w==case[3] and h==case[4],'incorrect chat size for '..width..'x'..height)
end
-- Native selection margins clamp chat without the player moving it. Accept
-- both native serializations, scale the margin, and reject actual saved moves.
UIParent.GetEffectiveScale=function()return .64 end
ChatFrame1={GetClampRectInsets=function()return -32,25,60,-32 end,
GetEffectiveScale=function()return .64 end}
local x,y=P.DefaultChatOrigin();assert(x==32 and y==45)
Enum={EditModeChatFrameSetting={WidthHundreds=0,WidthTensAndOnes=1,HeightHundreds=2,HeightTensAndOnes=3}}
RuenUIDB={chatDefaultSize={width=620,height=260}}
local system={anchorInfo={point='BOTTOMLEFT',relativeTo='UIParent',relativePoint='BOTTOMLEFT',offsetX=20,offsetY=45},
settings={{setting=0,value=6},{setting=1,value=20},{setting=2,value=2},{setting=3,value=60}}}
assert(P.IsDefaultChatSystem(system));system.anchorInfo.offsetX=32;assert(P.IsDefaultChatSystem(system))
system.anchorInfo.offsetX=60;assert(not P.IsDefaultChatSystem(system),'custom anchor misidentified as default')
ChatFrame1.GetEffectiveScale=function()return .96 end
x,y=P.DefaultChatOrigin();assert(x==48 and y==48,'native margins were not scaled')
system.anchorInfo.offsetX=48;system.anchorInfo.offsetY=48;assert(P.IsDefaultChatSystem(system))
system.settings[4].value=10;assert(not P.IsDefaultChatSystem(system),'custom height misidentified as default')
ChatFrame1.GetClampRectInsets=nil;x,y=P.DefaultChatOrigin();assert(x==20 and y==45,'missing margin API fallback')
local font,size,flags='native-cyrillic-capable-font',12,'OUTLINE'
local changes=0
ChatFrame1={GetFont=function()return font,size,flags end}
function FCF_SetChatWindowFontSize(_,frame,value)assert(frame==ChatFrame1);size=value;changes=changes+1 end
RuenUICharacter={};P.ApplyChatDefaults()
assert(size==14 and changes==1 and RuenUICharacter.chatFontOriginal.size==12)
P.ApplyChatDefaults();assert(changes==1,'font defaults reapplied')
size=16;P.RestoreChatDefaults();assert(size==16,'restore overwrote later font choice')
size=14;P.RestoreChatDefaults();assert(size==12,'font restore failed')
RuenUICharacter={version=5};size=18;P.ApplyChatDefaults();assert(size==18,'upgrade changed existing font')
local count=0;for _ in pairs(P.controlFrameSet)do count=count+1 end
assert(count==10 and #P.controlFrameNames==10,'control declarations inconsistent/duplicated')
print('PASS: responsive chat defaults at 720p-4K/logical UI scale; shared ten-frame reservations, readable fresh-install chat font, idempotency, custom font and upgrade preservation, conditional restore')

View File

@ -0,0 +1,86 @@
local root=assert(arg[1])
local P={}
function CopyTable(t)
if type(t)~='table'then return t end
local r={};for k,v in pairs(t)do r[k]=CopyTable(v)end;return r
end
Enum={EditModePresetLayouts={Modern=1}}
APIDocumentation={AddDocumentationTable=function(_,d)
for _,t in ipairs(d.Tables or {})do
if t.Type=='Enumeration'then
Enum[t.Name]={};for _,v in ipairs(t.Fields)do Enum[t.Name][v.Name]=v.EnumValue end
end
end
end}
dofile(assert(os.getenv('RUEN_NATIVE_UI'))..'/EditModeManagerConstantsDocumentation.lua')
local systems={}
for name,kind in pairs(Enum.EditModeSystem)do
local count=name=='UnitFrame' and 8 or name=='ActionBar' and 13 or name=='AuraFrame' and 2 or 1
for i=1,count do
systems[#systems+1]={system=kind,systemIndex=i,anchorInfo={point='TOPLEFT',relativeTo='UIParent',relativePoint='TOPLEFT',offsetX=kind,offsetY=-i},
settings={{setting=999,value='PRESERVE PREFERENCE'}}}
end
end
EditModePresetLayoutManager={GetCopyOfPresetLayouts=function()return {{systems=systems}}end}
assert(loadfile(root..'LayoutRecovery.lua'))('RuenUI',P)
local layout={systems=CopyTable(systems)}
for _,s in ipairs(layout.systems)do s.anchorInfo={offsetX=9999};s.anchorInfo2={offsetY=9999};s.isInDefaultPosition=false end
local report=P.ResetNativeLayoutPositions(layout)
assert(report.native==#systems and #report.unavailable==0)
for i,s in ipairs(layout.systems)do
assert(s.anchorInfo.offsetX==systems[i].anchorInfo.offsetX and s.anchorInfo.offsetY==systems[i].anchorInfo.offsetY)
assert(s.anchorInfo~=systems[i].anchorInfo and s.anchorInfo2==nil and s.isInDefaultPosition)
assert(s.settings[1].value=='PRESERVE PREFERENCE','position reset changed a functional setting')
end
layout.systems[1].anchorInfo.offsetX=222
assert(systems[1].anchorInfo.offsetX~=222,'reset retained shared native anchors')
-- New/unsupported native systems are reported; never assigned guessed points.
layout={systems={{system=999,anchorInfo={offsetX=123}}}}
report=P.ResetNativeLayoutPositions(layout)
assert(#report.unavailable==1 and layout.systems[1].anchorInfo.offsetX==123)
function EditModePresetLayoutManager:GetDefaultSystemAnchorInfo()return {offsetX=456}end
report=P.ResetNativeLayoutPositions(layout)
assert(report.native==1 and #report.unavailable==0 and layout.systems[1].anchorInfo.offsetX==456)
UIParent={}
local spokenReset=0
SpokenEnv={Options={ResetPositions=function()spokenReset=spokenReset+1 end}}
local window={}
function window:ClearAllPoints()self.point=nil end
function window:SetPoint(...)self.point={...}end
function window:SetUserPlaced(v)self.userPlaced=v end
SpokenCompendium={window=window}
local liveMap={x=999,scale=2,language='ruRU',key='N'}
local clicks=0
local button={tiptext='Click to reset the map position and scale to the game default.'}
function button:GetScript(event)
assert(event=='OnClick')
return function()clicks=clicks+1;liveMap.x=16;liveMap.scale=1 end
end
function button:IsEnabled()return true end
-- Random panel names and localized button labels must not affect discovery.
F123random={GetChildren=function()return button end}
UISpecialFrames={'F123random'}
C_AddOns={IsAddOnLoaded=function(name)return name=='Leatrix_Maps'end}
report={unavailable={},companions={}}
P.ResetCompanionPositions(report)
assert(spokenReset==1 and clicks==1 and #report.unavailable==0)
assert(window.point[1]=='CENTER' and window.userPlaced==false)
assert(liveMap.x==16 and liveMap.scale==1 and liveMap.language=='ruRU' and liveMap.key=='N')
function button:IsEnabled()return false end
P.ResetCompanionPositions(report)
assert(clicks==1 and report.unavailable[1]=='Leatrix Maps','locked map reset was not reported')
button.IsEnabled=nil;F123random.GetChildren=function()return end
P.ResetCompanionPositions(report)
assert(clicks==1 and #report.unavailable==2,'unavailable upstream reset was silently claimed')
local panels=0
BankFrame={SetUserPlaced=function(_,v)assert(v==false);panels=panels+1 end}
OtherFrame={IsForbidden=function()return true end,SetUserPlaced=function()error('forbidden frame touched')end}
UIPanelWindows={BankFrame={},OtherFrame={},UnloadedPanel={}}
local updates=0
function UpdateUIPanelPositions()updates=updates+1 end
local original=UIPanelWindows.BankFrame
P.ResetNativePanelPositions(report)
assert(panels==1 and updates==1 and UIPanelWindows.BankFrame==original,'panel reset replaced native bookkeeping')
print('PASS: all 31 native system kinds, indexed pet/boss/arena/aura/action frames, secondary anchors, native fallback, independent preferences, companion live reset and panel-manager handoff')

View File

@ -82,6 +82,7 @@ for i=1,12 do bindings[tostring(i)]='ACTIONBUTTON'..i end
local initialBindings=CopyTable(bindings)
function GetBindingKey(action) local k={}; for key,a in pairs(bindings) do if a==action then k[#k+1]=key end end; return unpack(k) end
function GetBindingAction(k) return bindings[k] or '' end
local profileEngine=dofile('tests/secure-binding-fixture.lua')
function SetBinding(k,a) bindings[k]=a; return true end
function SaveBindings() end
function GetCurrentBindingSet() return 1 end
@ -168,7 +169,13 @@ local function enrich(f,name)
if not self.point then return 0,0,w,h end
local p,relative,rp,x,y=unpack(self.point)
local l,b,rw,rh=relative:rect()
return l+rw*fraction(rp,'x')+x*scale-w*fraction(p,'x'),b+rh*fraction(rp,'y')+y*scale-h*fraction(p,'y'),w,h
l,b=l+rw*fraction(rp,'x')+x*scale-w*fraction(p,'x'),b+rh*fraction(rp,'y')+y*scale-h*fraction(p,'y')
if self.clampInsets then
local cl,cr,ct,cb=unpack(self.clampInsets)
l=math.max(-cl*scale,math.min(l,UIParent.w-w-cr*scale))
b=math.max(-cb*scale,math.min(b,UIParent.h-h-ct*scale))
end
return l,b,w,h
end
function f:GetLeft() local l=self:rect();return l/(self:GetEffectiveScale()/UIParent.scale) end
function f:GetBottom() local _,b=self:rect();return b/(self:GetEffectiveScale()/UIParent.scale) end
@ -183,6 +190,10 @@ for _,name in ipairs(barNames) do enrich(_G[name],name) end
for _,name in ipairs({'ChatFrame1','PartyFrame','CompactRaidFrameContainer','UIParent','MinimapCluster','BagsBar','MicroMenuContainer','ObjectiveTrackerFrame','GameTooltip','StanceBar','PetActionBar','PossessActionBar','MultiCastActionBarFrame','MainMenuBarVehicleLeaveButton','ExtraAbilityContainer','PlayerCastingBarFrame','PlayerFrame','PetFrame','TargetFrame','TargetFrameToT','FocusFrame'}) do CreateFrame('Frame',name) end
UIParent.w,UIParent.h,UIParent.scale=1706.4,960,1.25
ChatFrame1.w,ChatFrame1.h=380,150;ChatFrame1:SetPoint('BOTTOMLEFT',UIParent,'BOTTOMLEFT',20,45)
-- Native EditModeChatFrameSystemTemplate.Selection extends beyond the text
-- area (-32, +25, +60, -32). UpdateClampOffsets uses those actual bounds.
ChatFrame1.clampInsets={-32,25,60,-32}
function ChatFrame1:GetClampRectInsets()return unpack(self.clampInsets)end
PartyFrame.w,PartyFrame.h=230,300;CompactRaidFrameContainer.w,CompactRaidFrameContainer.h=360,304
PartyFrame.shown=false;CompactRaidFrameContainer.shown=false
GameTooltip.w,GameTooltip.h=220,120;GameTooltip.shown=false
@ -203,6 +214,8 @@ TargetFrameToT.w,TargetFrameToT.h=130,45;TargetFrameToT:SetPoint('TOPRIGHT',Targ
local byKind={[Enum.EditModeSystem.ActionBar]={MainActionBar,MultiBarBottomLeft,MultiBarBottomRight,MultiBarRight,MultiBarLeft,MultiBar5,MultiBar6,MultiBar7},[Enum.EditModeSystem.Minimap]={MinimapCluster},[Enum.EditModeSystem.Bags]={BagsBar},[Enum.EditModeSystem.MicroMenu]={MicroMenuContainer},[Enum.EditModeSystem.ObjectiveTracker]={ObjectiveTrackerFrame}}
local function setting(s,k) for _,v in ipairs(s.settings) do if v.setting==k then return v.value end end end
byKind[Enum.EditModeSystem.ActionBar][Enum.EditModeActionBarSystemIndices.PetActionBar]=PetActionBar
byKind[Enum.EditModeSystem.ChatFrame]={ChatFrame1}
local actualBarGeometry=false
C_EditMode.SetActiveLayout=function(i)
manager.layoutInfo.activeLayout=i
for _,s in ipairs(manager:GetActiveLayoutInfo().systems) do
@ -212,10 +225,15 @@ C_EditMode.SetActiveLayout=function(i)
if s.system==Enum.EditModeSystem.ActionBar and (s.systemIndex or 1)<=8 then
local rows=setting(s,Enum.EditModeActionBarSetting.NumRows) or 1
f.w=(rows==1 and 495 or 252);f.h=rows*36+(rows-1)*2
if actualBarGeometry then f.w=(rows==1 and 505.8 or 252);f.h=rows*40.5+(rows-1)*1.8 end
elseif f==PetActionBar then
local scale=(50+10*(setting(s,Enum.EditModeActionBarSetting.IconSize) or 3))/100
-- Native small buttons are 30px; padding is between containers.
f.localScale=1;f.w=10*30*scale+9*(2+(setting(s,Enum.EditModeActionBarSetting.IconPadding) or 2));f.h=30*scale
elseif f==ChatFrame1 then
local S=Enum.EditModeChatFrameSetting
f.w=100*setting(s,S.WidthHundreds)+setting(s,S.WidthTensAndOnes)
f.h=100*setting(s,S.HeightHundreds)+setting(s,S.HeightTensAndOnes)
elseif f==MinimapCluster then f.w,f.h=215,256
elseif f==BagsBar then f.w,f.h=315,45;f.localScale=0.8
elseif f==MicroMenuContainer then f.w,f.h=241.6,32
@ -247,9 +265,11 @@ C_Container={GetContainerNumSlots=function(bag) return bag==0 and 4 or 0 end,Get
local P={Translate=function(s) return s end, Localized=function(en) return en end}
assert(loadfile(root..'Profile.lua'))('RuenUI',P)
assert(loadfile(root..'Controls.lua'))('RuenUI',P)
assert(loadfile(root..'CharacterProfiles.lua'))('RuenUI',P)
assert(loadfile(root..'LayoutPolicy.lua'))('RuenUI',P)
assert(loadfile(root..'Brand.lua'))('RuenUI',P)
assert(loadfile(root..'ClassLayout.lua'))('RuenUI',P)
for _,file in ipairs({'PetExtras.lua','SwingTimers.lua','ExtraBars.lua','OverlayLayout.lua','DamageMeters.lua','ClassAssist.lua','HardwareProfile.lua','Optimizer.lua','GunAudio.lua'}) do assert(loadfile(root..file))('RuenUI',P) end
for _,file in ipairs({'ButtonStyle.lua','PetExtras.lua','SwingTimers.lua','ExtraBars.lua','OverlayLayout.lua','DamageMeters.lua','ClassAssist.lua','HardwareProfile.lua','FrameTiming.lua','Optimizer.lua','GunAudio.lua','Benchmark.lua'}) do assert(loadfile(root..file))('RuenUI',P) end
local available={'JUMP','TARGETNEARESTENEMY','TARGETPREVIOUSENEMY'}
for _,entry in ipairs(P.menuBindings) do available[#available+1]=entry[2] end
function GetNumBindings() return #available end
@ -261,6 +281,7 @@ ContainerFrameCombinedBags.shown=false
ContainerFrameCombinedBags.SetScale=ContainerFrameCombinedBags.SetScaleBase
if bundled then assert(loadfile(root..'AddonPresets.lua'))('RuenUI',P) end
assert(loadfile(root..'LayoutRecovery.lua'))('RuenUI',P)
assert(loadfile(root..'Core.lua'))('RuenUI',P)
RuenUICharacter={original={},version=2,addedBindings={['ALT-F']='INTERACTTARGET'}}
RuenUIDB={original={},reports={},graphicsVersion=P.graphicsVersion}
@ -270,6 +291,7 @@ assert(RuenUICharacter.version==P.version,RuenUICharacter.layoutStatus)
assert(cvars.graphicsLightMode=='1','UI update reset graphics')
assert(cvars.lockActionBars=='0' and settings.lockActionBars==false,'action and pet slots must be unlocked in both CVar and Settings')
assert(RuenUICharacter.verification.verified,'visible bar verification failed')
assert(ChatFrame1:GetWidth()==510 and ChatFrame1:GetHeight()==210,'fresh layout did not use the responsive chat default')
assert(math.abs(PetActionBar:GetWidth()-408)<.01 and math.abs(PetActionBar:GetHeight()-39)<.01,'native larger pet geometry missing')
for i=1,7 do assert(bars[i], 'all 96 slots must be enabled') end
local keys={'Q','W','R','T','A','G','H','Z','X','C','V','B'}
@ -287,7 +309,7 @@ local numberKeys={'1','2','3','4','5','6','7','8','9','0','-','='}
for _,r in ipairs({{'CTRL-','4'},{'SHIFT-','3'},{'ALT-','6'},{'CTRL-SHIFT-','7'}}) do for i,key in ipairs(numberKeys) do assert(bindings[r[1]..key]=='MULTIACTIONBAR'..r[2]..'BUTTON'..i,'missing utility binding') end end
assert(modified=='NONE' and cvars.autoSelfCast=='1','Alt abilities must not force self-cast')
assert(bindings.F1=='TARGETSELF')
for i=1,10 do assert(bindings[numberKeys[i]]=='BONUSACTIONBUTTON'..i,'missing direct pet shortcut') end
for i=1,10 do assert(GetBindingAction(numberKeys[i],true)=='MULTIACTIONBAR4BUTTON'..i,'non-pet class needs utility numbers'); assert(GetBindingAction('CTRL-'..numberKeys[i],true)=='BONUSACTIONBUTTON'..i) end
assert(actions[37][1]=='spell' and actions[37][2]==999,'existing click slot overwritten')
assert(actions[3][2]==117,'original food shortcut moved')
assert(actions[38][2]==6948 and actions[39][2]==117 and actions[40][2]==453,'hearth/food copies missing')
@ -337,7 +359,7 @@ local scenarios={
possessed={'PossessActionBar','PetActionBar','MainMenuBarVehicleLeaveButton'},
maximum={'StanceBar','PetActionBar','PetFrame','MultiCastActionBarFrame','PossessActionBar','MainMenuBarVehicleLeaveButton'},
}
assert(RuenUIDB.classLayoutVersion==7 and classSaves==2,'class migration missing or repeated')
assert(RuenUIDB.classLayoutVersion==8 and classSaves==2,'class migration missing or repeated')
for _,name in ipairs({'PartyFrame','CompactRaidFrameContainer'}) do
_G[name].shown=true;UIParent.scripts.OnSizeChanged()
assert(not intersects(_G[name],MultiBar7),'group overlaps reserve bars')
@ -789,7 +811,9 @@ SlashCmdList.RUENUI('help');SlashCmdList.RUENUI('language')
local before=changes
eventFrame.scripts.OnEvent(eventFrame,'PLAYER_ENTERING_WORLD')
assert(changes==before,'subsequent login reapplied settings')
-- Existing installs must upgrade despite already having the 96-slot binding migration.
-- Profile migration on both account/character binding sets preserves persisted
-- keys, custom keys, action assignments and graphics while changing only the
-- current character's effective number controls.
local savedBindings,savedCharacter,savedDB=CopyTable(bindings),CopyTable(RuenUICharacter),CopyTable(RuenUIDB)
local originalSet=GetCurrentBindingSet
local activeSet=1
@ -797,48 +821,35 @@ function GetCurrentBindingSet()return activeSet end
for _,bindingSet in ipairs({1,2}) do
activeSet=bindingSet
RuenUIDB=CopyTable(savedDB);RuenUICharacter=CopyTable(savedCharacter)
RuenUICharacter.numberBindingBases=nil;RuenUICharacter.numberProfile='utility'
local scope=bindingSet==1 and RuenUIDB or RuenUICharacter
scope.petBindingsVersion=nil;scope.extraBindingsVersion=1
scope.petBindingsVersion=2;scope.extraBindingsVersion=1
for i,key in ipairs(numberKeys) do
bindings[key]='MULTIACTIONBAR4BUTTON'..i
bindings['CTRL-'..key]=i<=10 and 'BONUSACTIONBUTTON'..i or nil
bindings[key]=i<=10 and 'BONUSACTIONBUTTON'..i or 'CLICK RuenPetExtraButton'..i..':LeftButton'
bindings['CTRL-'..key]='MULTIACTIONBAR4BUTTON'..i
end
bindings['ALT-Q']='MY_ALT_SPELL';bindings['SHIFT-1']='MY_SHIFT_SPELL'
bindings['-']='PERSONAL_MINUS'
bindings['ALT-Q']='MY_ALT_SPELL';bindings['SHIFT-1']='MY_SHIFT_SPELL';bindings['-']='PERSONAL_MINUS'
local persistent=CopyTable(bindings)
local actionSnapshot=CopyTable(actions);local graphicsBefore=changes
combat=true;P.ApplyExtraBindings(false)
assert(not scope.petBindingsVersion and bindings['1']=='MULTIACTIONBAR4BUTTON1','combat migration was not deferred')
assert(not RuenUICharacter.numberBindingBases,'combat migration was not deferred')
combat=false;P.ApplyExtraBindings(false)
for i,key in ipairs(numberKeys) do
assert(bindings['CTRL-'..key]=='MULTIACTIONBAR4BUTTON'..i,'missed utility migration')
if i<=10 then assert(bindings[key]=='BONUSACTIONBUTTON'..i,'missed pet migration') end
for i=1,10 do
assert(GetBindingAction(numberKeys[i],true)=='MULTIACTIONBAR4BUTTON'..i)
assert(GetBindingAction('CTRL-'..numberKeys[i],true)=='BONUSACTIONBUTTON'..i)
end
assert(bindings['-']=='CLICK RuenPetExtraButton11:LeftButton' and bindings['=']=='CLICK RuenPetExtraButton12:LeftButton','missing extra-pet keys')
assert(bindings['ALT-Q']=='MY_ALT_SPELL' and bindings['SHIFT-1']=='MY_SHIFT_SPELL','migration reset unrelated rows')
assert(GetBindingAction('-',true)=='PERSONAL_MINUS','custom minus stolen')
for k,v in pairs(persistent)do assert(bindings[k]==v,'profile mutated persisted binding '..k)end
assert(changes==graphicsBefore,'binding migration changed graphics')
for slot,a in pairs(actionSnapshot) do assert(actions[slot][1]==a[1] and actions[slot][2]==a[2],'binding migration moved a slot')end
assert(scope.petBindingsVersion==2)
bindings['1']='PERSONAL_PET_KEY';bindings['CTRL-2']='PERSONAL_UTILITY_KEY'
for _,class in ipairs({'HUNTER','SHAMAN','WARLOCK','MAGE','DRUID','WARRIOR','PALADIN','PRIEST','ROGUE'}) do
currentClass=class;PetActionBar.shown=not PetActionBar.shown
P.ApplyExtraBindings(false)
assert(bindings['1']=='PERSONAL_PET_KEY' and bindings['CTRL-2']=='PERSONAL_UTILITY_KEY','reload/class/pet transition overwrote custom bindings')
end
end
for _,bindingSet in ipairs({1,2}) do
activeSet=bindingSet
local scope=bindingSet==1 and RuenUIDB or RuenUICharacter
scope.petBindingsVersion=1
bindings['1']='PERSONAL_PET_KEY';bindings['CTRL-2']='PERSONAL_UTILITY_KEY'
bindings['-']='OLD_MINUS';bindings['=']='OLD_EQUALS'
P.ApplyPetBindings(false)
assert(bindings['1']=='PERSONAL_PET_KEY' and bindings['CTRL-2']=='PERSONAL_UTILITY_KEY','two-key upgrade reset existing controls')
assert(bindings['-']=='CLICK RuenPetExtraButton11:LeftButton' and bindings['=']=='CLICK RuenPetExtraButton12:LeftButton')
bindings['-']='CUSTOM_MINUS';P.ApplyPetBindings(false)
assert(bindings['-']=='CUSTOM_MINUS','reload reset customized extra-pet key')
for slot,a in pairs(actionSnapshot) do assert(actions[slot][1]==a[1] and actions[slot][2]==a[2],'binding migration changed actions')end
bindings['1']='PERSONAL_KEY';P.ApplyPetBindings(false)
assert(GetBindingAction('1',true)=='PERSONAL_KEY','later manual change was overridden')
P.ClearCharacterBindings()
assert(GetBindingAction('CTRL-1',true)=='MULTIACTIONBAR4BUTTON1','profile restore left override')
end
GetCurrentBindingSet=originalSet;bindings=savedBindings;RuenUICharacter=savedCharacter;RuenUIDB=savedDB
print('PASS: one-time pet/utility swap on account and character bindings; combat deferral, personal keys, action slots, no-pet class consistency and later customizations')
P.ApplyCharacterBindings(false)
print('PASS: account/character base bindings unchanged by profile migration; custom keys, action slots, combat deferral and override restoration')
-- A graphics-only upgrade must not replace the existing UI layout or custom keys.
RuenUIDB.graphicsVersion=1
@ -856,6 +867,121 @@ assert(changes==afterGraphics,'graphics upgrade reapplied every login')
SlashCmdList.RUENUI('apply'); assert(#manager:GetLayouts()==2)
combat=true;before=changes;SlashCmdList.RUENUI('apply');assert(changes==before)
combat=false
-- Exercise the actual reset commands with enlarged, moved and saved chat.
do
local function equal(a,b)
if type(a)~=type(b) then return false end
if type(a)~='table' then return a==b end
for k,v in pairs(a)do if not equal(v,b[k])then return false end end
for k in pairs(b)do if a[k]==nil then return false end end
return true
end
local originalClass=currentClass
local priorKey,priorFPS,priorShadow=bindings.Z,cvars.maxFPS,cvars.graphicsShadowQuality
bindings.Z='MY_CUSTOM_BINDING';cvars.maxFPS='37';cvars.graphicsShadowQuality='0'
local originalCvars,originalBindings,originalActions=CopyTable(cvars),CopyTable(bindings),CopyTable(actions)
local otherLayout=CopyTable(manager.layoutInfo.layouts[1])
local function enlargeChat()
for _,s in ipairs(manager:GetActiveLayoutInfo().systems)do
if s.system==Enum.EditModeSystem.ChatFrame then
local S=Enum.EditModeChatFrameSetting
for _,v in ipairs(s.settings)do
if v.setting==S.HeightHundreds then v.value=5 end
if v.setting==S.HeightTensAndOnes then v.value=50 end
end
s.anchorInfo.offsetX=60;s.anchorInfo.offsetY=120
end
end
C_EditMode.SetActiveLayout(manager.layoutInfo.activeLayout)
end
enlargeChat()
local shared=manager.layoutInfo;local prior=CopyTable(shared)
local function assertChat()
local width,height=P.DefaultChatSize()
assert(ChatFrame1:GetHeight()==height,'chat reset did not restore responsive height')
assert(ChatFrame1:GetWidth()<=width and ChatFrame1:GetWidth()>=P.layoutPolicy.chat.minimumWidth,'chat reset did not fit responsive width')
assert(ChatFrame1:GetLeft()==32 and ChatFrame1:GetBottom()==45,'chat reset did not restore native-clamped anchor')
end
SlashCmdList.RUENUI('chat reset');assertChat()
assert(equal(shared,prior),'chat reset mutated shared layout data')
for i,s in ipairs(prior.layouts[prior.activeLayout].systems)do
if s.system~=Enum.EditModeSystem.ChatFrame then
assert(equal(s,manager:GetActiveLayoutInfo().systems[i]),'chat reset altered another saved system')
end
end
assert(not intersects(ChatFrame1,MultiBar6) and not intersects(ChatFrame1,MultiBar7),'reset left chat/bar overlap')
assert(RuenUICharacter.layoutBeforeReset=='simulation-export','missing recovery export')
C_EditMode.SetActiveLayout(manager.layoutInfo.activeLayout);assertChat()
-- Resolution changes must work repeatedly, with the real native chat clamp,
-- without another reset/save. Also accept native serialization of the clamp.
local originalDisplay={UIParent.w,UIParent.h,UIParent.scale}
for _,s in ipairs(manager:GetActiveLayoutInfo().systems)do
if s.system==Enum.EditModeSystem.ChatFrame then s.anchorInfo.offsetX=32 end
end
C_EditMode.SetActiveLayout(manager.layoutInfo.activeLayout);hooks.UpdateSystems()
local savedLayout=CopyTable(manager.layoutInfo)
for round=1,3 do
for _,display in ipairs({{1920,1080,1,570,230},{1280,720,1,344.5,190},
{3440,1440,1.875,550,190},{3840,2160,2,570,230},
{2560,1440,2,344.5,190},{2133,1200,1,620,260}})do
UIParent.w,UIParent.h,UIParent.scale=display[1]/display[3],display[2]/display[3],display[3]
UIParent.scripts.OnSizeChanged()
assert(math.abs(ChatFrame1:GetWidth()-display[4])<.1 and ChatFrame1:GetHeight()==display[5],
'chat did not follow viewport '..table.concat(display,','))
assert(ChatFrame1:GetLeft()==32 and ChatFrame1:GetBottom()==45,'native chat margin lost')
assert(equal(manager.layoutInfo,savedLayout),'display resize wrote shared native layout state')
end
end
local w,h=ChatFrame1:GetSize()
combat=true;UIParent.w,UIParent.h=1280,720;UIParent.scripts.OnSizeChanged()
assert(ChatFrame1:GetWidth()==w and ChatFrame1:GetHeight()==h,'chat resize ignored combat deferral')
combat=false;hooks.UpdateSystems();assert(ChatFrame1:GetHeight()==190,'deferred chat resize lost')
UIParent.w,UIParent.h,UIParent.scale=unpack(originalDisplay);hooks.UpdateSystems()
-- Routine reflow must not turn a responsive default into a mandatory size.
ChatFrame1:SetSize(330,210);ChatFrame1:SetPoint('BOTTOMLEFT',UIParent,'BOTTOMLEFT',60,45)
hooks.UpdateSystems();hooks.UpdateSystems()
assert(ChatFrame1:GetWidth()==330 and ChatFrame1:GetHeight()==210 and ChatFrame1:GetLeft()==60,
'ordinary refresh replaced the player\'s chat size/position')
-- An actual saved custom size also wins after native layout activation.
for _,s in ipairs(manager:GetActiveLayoutInfo().systems)do
if s.system==Enum.EditModeSystem.ChatFrame then
local S=Enum.EditModeChatFrameSetting
for _,v in ipairs(s.settings)do
if v.setting==S.WidthHundreds then v.value=3 end
if v.setting==S.WidthTensAndOnes then v.value=30 end
if v.setting==S.HeightHundreds then v.value=2 end
if v.setting==S.HeightTensAndOnes then v.value=10 end
end
end
end
C_EditMode.SetActiveLayout(manager.layoutInfo.activeLayout);hooks.UpdateSystems();hooks.UpdateSystems()
assert(ChatFrame1:GetWidth()==330 and ChatFrame1:GetHeight()==210,'native reactivation replaced saved custom chat dimensions')
for _,class in ipairs({'HUNTER','WARLOCK','ROGUE','DRUID','WARRIOR','PALADIN','PRIEST','MAGE','SHAMAN'})do
currentClass=class;enlargeChat()
manager:GetActiveLayoutInfo().systems[1].anchorInfo.offsetY=400
SlashCmdList.RUENUI('layout reset');assertChat()
assert(manager:GetActiveLayoutInfo().systems[1].anchorInfo.offsetY==48,'main bar reset failed for '..class)
assert(#manager:GetLayouts()==layoutsBefore and equal(manager.layoutInfo.layouts[1],otherLayout),'reset replaced unrelated layouts')
end
currentClass=originalClass
assert(equal(cvars,originalCvars),'layout reset changed graphics/gameplay CVars')
assert(equal(bindings,originalBindings) and equal(actions,originalActions),'layout reset changed keys/actions')
bindings.Z=priorKey;cvars.maxFPS=priorFPS;cvars.graphicsShadowQuality=priorShadow
for _,guard in ipairs({'combat','edit','override','disabled','other'})do
local shown=manager.IsShown;local savedName=manager:GetActiveLayoutInfo().layoutName
if guard=='combat'then combat=true
elseif guard=='edit'then manager.IsShown=function()return true end
elseif guard=='override'then manager.overrideLayoutInfo={}
elseif guard=='disabled'then RuenUIDB.disabled=true
else manager:GetActiveLayoutInfo().layoutName='Personal Layout' end
local prior=CopyTable(manager.layoutInfo);local saves=classSaves
SlashCmdList.RUENUI('chat reset');SlashCmdList.RUENUI('layout reset')
assert(equal(manager.layoutInfo,prior) and saves==classSaves,'reset ignored guard: '..guard)
combat=false;manager.IsShown=shown;manager.overrideLayoutInfo=nil;RuenUIDB.disabled=nil
manager:GetActiveLayoutInfo().layoutName=savedName
end
print('PASS: native-clamped chat resize cycles at six viewport/scales, normalized saved anchors, combat deferral, manual size preservation; saved chat and nine-class layout reset, detached native state, persistence, unrelated layout/CVar/key/action preservation and reset guards')
end
bindings.Z='USER_NEW_ACTION';actions[39]={'item',888}
SlashCmdList.RUENUI('restore')
for k,a in pairs(initialBindings) do if k~='ALT-F' then assert(bindings[k]==a,'undo mismatch '..k) end end
@ -1025,7 +1151,9 @@ for _,l in ipairs(manager.layoutInfo.layouts)do
for i=1,4 do l.systems[#l.systems+1]={system=Enum.EditModeSystem.CooldownViewer,systemIndex=i,settings={}}end
end
spellSet({6,5,3,2})
SlashCmdList.RUENUI('apply');C_EditMode.SetActiveLayout(2)
SlashCmdList.RUENUI('apply')
assert(gap(ObjectiveTrackerFrame,MultiBarRight)>=23.9,'native cooldown configuration restored tracker over utility controls')
C_EditMode.SetActiveLayout(2)
P.RefreshClassAssist();assert(not RuenUICharacter.classAssistError,RuenUICharacter.classAssistError)
assert(cvars.cooldownViewerEnabled=='1')
for _,name in ipairs(cdNames)do assert(not _G[name]:IsShown(),'auto viewer visible out of combat')end
@ -1036,6 +1164,7 @@ P.ClassAssistCommand('cooldowns','off');assert(classSaves==saveCount and Essenti
combat=false;P.classAssistListener.scripts.OnEvent(nil,'PLAYER_REGEN_ENABLED')
for _,name in ipairs(cdNames)do assert(not _G[name]:IsShown(),'off visibility')end
P.ClassAssistCommand('cooldowns','show');assert(EssentialCooldownViewer:IsShown())
assert(gap(ObjectiveTrackerFrame,MultiBarRight)>=23.9,'cooldown mode change restored tracker over utility controls')
assert(#EssentialCooldownViewer:GetCooldownIDs()==6,'unknown spells leaked into native category')
assert(#P.classAssistReserved==4 and #RuenUICharacter.classAssistUnplaced==0)
-- Geometry stress is deliberately synthetic; lists remain native, not Ruen spell lists.
@ -1101,6 +1230,23 @@ P.RefreshClassAssist();assert(RuenUICharacter.classAssistError)
C_CooldownViewer.IsCooldownViewerAvailable=getAvail;P.RefreshClassAssist();assert(not RuenUICharacter.classAssistError)
print('PASS: native cooldown selection/unknown filtering, combat visibility, empty categories, talent/learned changes, settings handoff, error recovery; '..cdSamples..' class/resolution/full-HUD cooldown+meter+tooltip clearance cases')
-- Display choices belong to each character; changing one does not change the
-- legacy account defaults inherited by an unvisited alt.
do
local original=RuenUICharacter
local dbCooldown,dbMeter=RuenUIDB.cooldownsMode,RuenUIDB.damageMeterMode
RuenUIDB.cooldownsMode='auto';RuenUIDB.damageMeterMode='auto'
P.ClassAssistCommand('cooldowns','off');P.DamageMeterCommand('off')
local first=RuenUICharacter
RuenUICharacter={version=5,original={}};P.EnsureCharacterProfile()
assert(RuenUICharacter.cooldownsMode=='auto' and RuenUICharacter.damageMeterMode=='auto')
P.ClassAssistCommand('cooldowns','show');P.DamageMeterCommand('show')
assert(first.cooldownsMode=='off' and first.damageMeterMode=='off')
assert(RuenUIDB.cooldownsMode=='auto' and RuenUIDB.damageMeterMode=='auto')
RuenUICharacter=original;RuenUIDB.cooldownsMode=dbCooldown;RuenUIDB.damageMeterMode=dbMeter
P.ClassAssistCommand('cooldowns','off');P.DamageMeterCommand('auto')
end
-- Class defaults, native modifiers, account/character transitions and overrides.
function IsMouseoverCastSupported()return true end
local nativeSetting=Settings.SetValue
@ -1110,7 +1256,7 @@ local guid='player-1';function UnitGUID()return guid end
local chars={};local keysBefore=CopyTable(bindings);local selfBefore=modified
for _,class in ipairs({'PRIEST','DRUID','PALADIN','SHAMAN','HUNTER','WARLOCK','MAGE','ROGUE','WARRIOR'})do
currentClass=class;guid='player-'..class
RuenUICharacter={original={}};chars[class]=RuenUICharacter
RuenUICharacter={original={},rolePreference=({PRIEST=true,DRUID=true,PALADIN=true,SHAMAN=true})[class] and 'HEALER' or 'DAMAGER'};chars[class]=RuenUICharacter
cvars.enableMouseoverCast='0';mouseModifier='SHIFT'
P.ApplyMouseover(false)
local expected=({PRIEST=true,DRUID=true,PALADIN=true,SHAMAN=true})[class] and '1' or '0'
@ -1161,7 +1307,7 @@ for _,case in ipairs({{2133,1200,1,2},{1920,1080,1,2},{1920,1080,1.40625,2},{136
P.MigrateLeftBars();hooks.UpdateSystems();UIParent.scripts.OnSizeChanged()
assert(RuenUIDB.leftBarRows==case[4],'wrong responsive row count')
assert(MultiBar6.h==(case[4]==1 and 36 or 74) and MultiBar7.h==MultiBar6.h,'wrong native shape')
assert(math.abs(MultiBar6:GetLeft()-ChatFrame1:GetLeft())<.01,'left shelf not aligned with chat')
assert(math.abs(MultiBar6:GetLeft()-(ChatFrame1:GetLeft()-12))<.01,'left shelf not aligned with the chat layout margin')
assert(math.abs(MultiBar6:GetLeft()-MultiBar7:GetLeft())<.01 and math.abs(MultiBar6:GetRight()-MultiBar7:GetRight())<.01)
assert(gap(MultiBar7,MultiBar6)>=5.9,'left row gap')
local dockPoint=CopyTable(MultiBar6.point);MultiBar6:SetPoint('BOTTOMLEFT',UIParent,'BOTTOMLEFT',20,215)
@ -1175,9 +1321,13 @@ for _,case in ipairs({{2133,1200,1,2},{1920,1080,1,2},{1920,1080,1.40625,2},{136
if s.system==Enum.EditModeSystem.ActionBar and (s.systemIndex==7 or s.systemIndex==8)then
assert(setting(s,Enum.EditModeActionBarSetting.NumRows)==case[4])
assert(s.anchorInfo.relativeTo=='UIParent' and not s.isInDefaultPosition)
assert(s.anchorInfo.offsetY>=socialSpace.top+11.9,'saved native anchor fell into notification space')
end
end
-- Saved anchors seed native placement. Viewport-dependent chat/notification
-- geometry must reflow on activation without rewriting that saved layout.
C_EditMode.SetActiveLayout(manager.layoutInfo.activeLayout);hooks.UpdateSystems()
socialSpace=P.SocialNotificationSpace(function(f,m)return f[m](f)*f:GetEffectiveScale()/UIParent.scale end)
assert(MultiBar6:GetBottom()>=socialSpace.top+11.9,'layout reactivation left the shelf in notification space')
saves=classSaves;P.MigrateLeftBars();assert(saves==classSaves,'left migration repeated without width change')
end
assert(eq(bindings,keysSnapshot) and eq(actions,actionSnapshot),'shelf migration changed keybindings or actions')
@ -1237,6 +1387,7 @@ for _,display in ipairs({{1920,1080,1},{2133,1200,1},{1366,768,1}})do
currentClass='SHAMAN';inside=false;kind='none';CompactRaidFrameContainer.shown=false;PartyFrame.shown=false
for _,n in ipairs(controls)do _G[n].shown=false end
PlayerFrame.shown=true;TargetFrame.shown=true;MultiCastActionBarFrame.shown=true
SlashCmdList.RUENUI('chat reset')
nativeSocial();hooks.UpdateSystems();P.RefreshDamageMeters()
ContainerFrameCombinedBags.shown=true;ContainerFrameCombinedBags.w,ContainerFrameCombinedBags.h=430,550
ContainerFrameCombinedBags.localScale=1;SlashCmdList.RUENUI('bags')
@ -1418,7 +1569,7 @@ P.OverlayObstacles(true) -- forbidden child is never read
for _,class in ipairs({'WARRIOR','PALADIN','HUNTER','ROGUE','PRIEST','SHAMAN','MAGE','WARLOCK','DRUID'})do
currentClass=class;spellSet({1,1,0,0})
P.ClassAssistCommand('cooldowns','show');assert(cvars.cooldownViewerEnabled=='1')
P.ClassAssistCommand('cooldowns','hide');assert(cvars.cooldownViewerEnabled=='0' and RuenUIDB.cooldownsMode=='off')
P.ClassAssistCommand('cooldowns','hide');assert(cvars.cooldownViewerEnabled=='0' and RuenUICharacter.cooldownsMode=='off')
for _,name in ipairs(cdNames)do assert(not _G[name]:IsShown(),'hide left '..name..' visible')end
end
print('PASS: '..cases..' restricted-aura bag cases (target/focus/bank, 720p-4K, three pet/totem classes), no control overlaps; forbidden frames skipped; show/hide in all nine classes')
@ -1426,10 +1577,14 @@ print('PASS: '..cases..' restricted-aura bag cases (target/focus/bank, 720p-4K,
end)()
-- Reset the prior restricted-aura stress fixture before the base matrix.
-- Earlier compatibility fixtures use smaller buttons. This full matrix uses
-- Forever's measured 90% native geometry: 505.8x40.5 center rows and 252x82.8
-- side bars. The compact legacy model understated the vertical HUD footprint.
actualBarGeometry=true
TargetFrame.GetAuraContainer=nil;FocusFrame.GetAuraContainer=nil
;(function()
local report=assert(io.open(arg[3] or '/tmp/ruen-audit-matrix.txt','w'))
local configs={{1366,768,1},{1920,1080,1.40625},{1920,1080,1},{2560,1440,1.875},{2560,1440,1},{3840,2160,2.8125},{3840,2160,1.5},{1280,720,1}}
local configs={{1366,768,1},{1920,1080,1.40625},{1920,1080,1},{2560,1440,1.875},{2560,1440,1},{3840,2160,2.8125},{3840,2160,1.5},{1280,720,1},{2133,1200,1},{1280,720,1,true},{1280,800,1},{1440,900,1},{1600,900,1},{1920,1200,1},{2560,1600,1.5},{3440,1440,1},{3440,1440,1.875},{5120,1440,1.875},{3840,2160,2},{1280,1024,1}}
local envs={{'solo',false,'none',0},{'party',false,'none',5},{'dungeon',true,'party',5},{'raid10',true,'raid',10},{'raid20',true,'raid',20},{'raid40',true,'raid',40},{'bg10',true,'pvp',10},{'bg40',true,'pvp',40}}
local seen,issues,cases={},0,0
local function note(text)
@ -1439,11 +1594,15 @@ TargetFrame.GetAuraContainer=nil;FocusFrame.GetAuraContainer=nil
local function rectangle(f) local l,b,w,h=f:rect();return {left=l,bottom=b,right=l+w,top=b+h} end
local function hit(a,b) return a.left<b.right-1 and a.right>b.left+1 and a.bottom<b.top-1 and a.top>b.bottom+1 end
local controlsList={'MainActionBar','MultiBarBottomLeft','MultiBarBottomRight','MultiBar5','MultiBarLeft','MultiBarRight','MultiBar6','MultiBar7','BagsBar','MicroMenuContainer','ChatFrame1','PlayerFrame','TargetFrame','FocusFrame','PetFrame','TargetFrameToT','RuenTargetTargetTarget','StanceBar','PetActionBar','MultiCastActionBarFrame','PossessActionBar','MainMenuBarVehicleLeaveButton','PlayerCastingBarFrame','RuenSwingTimers','PartyFrame','CompactRaidFrameContainer','MinimapCluster','ObjectiveTrackerFrame'}
RuenUIDB.cooldownsMode='off';RuenUIDB.damageMeterMode='auto';inEdit=false;combat=false
RuenUICharacter.cooldownsMode='off';RuenUICharacter.damageMeterMode='auto';inEdit=false;combat=false
activeAlerts={}
for _,f in ipairs({roll,talking,loot1,loot2,achievement,breath,buffs,ContainerFrameCombinedBags,GameTooltip,ShoppingTooltip1,ShoppingTooltip2,unpack(rolls)})do f.shown=false end
for _,display in ipairs(configs)do
-- A large-screen saved default must refit after shrinking the viewport,
-- without another reset or changing the saved native layout.
if display[4] then UIParent.w,UIParent.h=3840,2160;SlashCmdList.RUENUI('chat reset') end
UIParent.w,UIParent.h,UIParent.scale=display[1]/display[3],display[2]/display[3],display[3]
if not display[4] then SlashCmdList.RUENUI('chat reset') end
for class,names in pairs(scenarios)do if class~='maximum' and class~='possessed' then
currentClass=class:upper()
for _,env in ipairs(envs)do
@ -1455,7 +1614,8 @@ TargetFrame.GetAuraContainer=nil;FocusFrame.GetAuraContainer=nil
PartyFrame.shown=env[4]==5;PartyFrame.w,PartyFrame.h=102,260
CompactRaidFrameContainer.shown=env[4]>5;CompactRaidFrameContainer.w=math.ceil(env[4]/8)*72;CompactRaidFrameContainer.h=math.min(8,env[4])*38
nativeSocial();hooks.UpdateSystems();hooks.UpdateSystems() -- settle the native layout activation callback
local tag=display[1]..'x'..display[2]..'/'..display[3]..' '..class..' '..env[1]
if display[4] then assert(ChatFrame1:GetHeight()==190,'saved default did not follow the smaller viewport') end
local tag=display[1]..'x'..display[2]..'/'..display[3]..(display[4] and ' saved-large-chat' or '')..' '..class..' '..env[1]
for i,n in ipairs(controlsList)do
local f=_G[n]
if f and f:IsShown() then
@ -1499,7 +1659,7 @@ end)()
end)()
;(function()
local report=assert(io.open((arg[3] or '/tmp/ruen-audit-matrix.txt')..'.native','w'))
local configs={{1366,768,1},{1920,1080,1.40625},{1920,1080,1},{2560,1440,1.875},{2560,1440,1},{3840,2160,2.8125},{3840,2160,1.5},{1280,720,1}}
local configs={{1366,768,1},{1920,1080,1.40625},{1920,1080,1},{2560,1440,1.875},{2560,1440,1},{3840,2160,2.8125},{3840,2160,1.5},{1280,720,1},{2133,1200,1},{1280,720,1,true},{1280,800,1},{1440,900,1},{1600,900,1},{1920,1200,1},{2560,1600,1.5},{3440,1440,1},{3440,1440,1.875},{5120,1440,1.875},{3840,2160,2},{1280,1024,1}}
local envs={{'solo',false,'none',0},{'party',false,'none',5},{'dungeon',true,'party',5},{'raid10',true,'raid',10},{'raid20',true,'raid',20},{'raid40',true,'raid',40},{'bg10',true,'pvp',10},{'bg40',true,'pvp',40}}
local seen,issues,cases={},0,0
local function note(text)
@ -1509,11 +1669,13 @@ end)()
local function rectangle(f) local l,b,w,h=f:rect();return {left=l,bottom=b,right=l+w,top=b+h} end
local function hit(a,b) return a.left<b.right-1 and a.right>b.left+1 and a.bottom<b.top-1 and a.top>b.bottom+1 end
local controlsList={'MainActionBar','MultiBarBottomLeft','MultiBarBottomRight','MultiBar5','MultiBarLeft','MultiBarRight','MultiBar6','MultiBar7','BagsBar','MicroMenuContainer','ChatFrame1','PlayerFrame','TargetFrame','FocusFrame','PetFrame','TargetFrameToT','RuenTargetTargetTarget','StanceBar','PetActionBar','MultiCastActionBarFrame','PossessActionBar','MainMenuBarVehicleLeaveButton','PlayerCastingBarFrame','RuenSwingTimers','PartyFrame','CompactRaidFrameContainer','MinimapCluster','ObjectiveTrackerFrame','AuditTargetCast','AuditFocusCast','AuditFocusTarget','AuditTargetAuras','AuditFocusAuras','AuditCombo1','AuditCombo2','AuditCombo3','AuditCombo4','AuditCombo5','UIWidgetTopCenterContainerFrame'}
RuenUIDB.cooldownsMode='off';RuenUIDB.damageMeterMode='auto';inEdit=false;combat=false
RuenUICharacter.cooldownsMode='off';RuenUICharacter.damageMeterMode='auto';inEdit=false;combat=false
activeAlerts={}
for _,f in ipairs({roll,talking,loot1,loot2,achievement,breath,buffs,ContainerFrameCombinedBags,GameTooltip,ShoppingTooltip1,ShoppingTooltip2,unpack(rolls)})do f.shown=false end
for _,display in ipairs(configs)do
if display[4] then UIParent.w,UIParent.h=3840,2160;SlashCmdList.RUENUI('chat reset') end
UIParent.w,UIParent.h,UIParent.scale=display[1]/display[3],display[2]/display[3],display[3]
if not display[4] then SlashCmdList.RUENUI('chat reset') end
for class,names in pairs(scenarios)do if class~='maximum' and class~='possessed' then
currentClass=class:upper()
for _,env in ipairs(envs)do
@ -1528,7 +1690,8 @@ end)()
PartyFrame.shown=env[4]==5;PartyFrame.w,PartyFrame.h=102,260
CompactRaidFrameContainer.shown=env[4]>5;CompactRaidFrameContainer.w=math.ceil(env[4]/8)*72;CompactRaidFrameContainer.h=math.min(8,env[4])*38
nativeSocial();hooks.UpdateSystems();hooks.UpdateSystems() -- settle the native layout activation callback
local tag=display[1]..'x'..display[2]..'/'..display[3]..' '..class..' '..env[1]
if display[4] then assert(ChatFrame1:GetHeight()==190,'saved default did not follow the smaller viewport') end
local tag=display[1]..'x'..display[2]..'/'..display[3]..(display[4] and ' saved-large-chat' or '')..' '..class..' '..env[1]
for i,n in ipairs(controlsList)do
local f=_G[n]
if f and f:IsShown() then
@ -1550,3 +1713,75 @@ end)()
report:write('CASES ',cases,'; FINDINGS ',issues,'\n');report:close()
print('AUDIT MATRIX',cases,issues);assert(issues==0,'Matrix findings require review')
end)()
-- Whole-login regression: a new alt using shared bindings must not replay
-- account defaults over another character's custom combat/menu keys.
do
local previousCharacter=RuenUICharacter
local previousBindings=CopyTable(bindings)
local previousClass=currentClass
RuenUIDB.disabled=nil;RuenUIDB.combatBindingsVersion=2
RuenUIDB.controlsVersion=1;RuenUIDB.extraBindingsVersion=1
bindings.Q='CUSTOM_SHARED_COMBAT';bindings.N='CUSTOM_SHARED_MENU'
bindings['1']='CUSTOM_SHARED_NUMBER';bindings['ALT-Q']='CUSTOM_SHARED_UTILITY'
local before=CopyTable(bindings)
RuenUICharacter={original={}};currentClass='ROGUE'
combat=false;inEdit=false
UIParent.w,UIParent.h,UIParent.scale=1920,1080,1
inside=false;kind='none';activeAlerts={}
for _,f in ipairs({ContainerFrameCombinedBags,GameTooltip,ShoppingTooltip1,ShoppingTooltip2,CompactRaidFrameContainer,PartyFrame,PetActionBar,MultiCastActionBarFrame,unpack(rolls)})do f.shown=false end
ObjectiveTrackerFrame.h=300
eventFrame.scripts.OnEvent(eventFrame,'PLAYER_ENTERING_WORLD')
assert(RuenUICharacter.version==P.version,'fresh-alt setup did not finish')
for key,value in pairs(before)do assert(bindings[key]==value,'fresh alt rewrote shared key '..key)end
assert(GetBindingAction('1',true)=='CUSTOM_SHARED_NUMBER')
RuenUICharacter=previousCharacter;bindings=previousBindings;currentClass=previousClass
P.ApplyCharacterBindings(false)
print('PASS: full first-login setup on a new alt preserves shared combat/menu/utility/custom number bindings')
end
-- The same obstacle policy protects chat entry and newly included native
-- windows. This is placement coverage, not permission to move native panels.
do
local edit=CreateFrame('Frame','ChatFrame1EditBox');edit.w,edit.h=360,28
edit:SetPoint('BOTTOMLEFT',UIParent,'BOTTOMLEFT',20,8);edit.shown=true
local tab=CreateFrame('Frame','ChatFrame1Tab');tab.w,tab.h=140,20
tab:SetPoint('BOTTOMLEFT',ChatFrame1,'TOPLEFT',0,0);tab.shown=true
for _,name in ipairs({'ProfessionsFrame','PlayerSpellsFrame','WorldMapFrame','CharacterFrame','AuctionHouseFrame'})do
local panel=CreateFrame('Frame',name);panel.w,panel.h=460,350
panel:SetPoint('TOPLEFT',UIParent,'TOPLEFT',20,-45);panel.shown=true
local found={}
for _,r in ipairs(P.OverlayObstacles(true))do found[r.name]=r end
assert(found[name] and found.ChatFrame1EditBox and found.ChatFrame1Tab,'missing panel/chat reservation '..name)
local anchor=CopyTable(panel.point)
P.PositionOverlayFrames()
assert(eq(panel.point,anchor),'overlay moved native panel '..name)
panel.shown=false
end
edit.shown=false;tab.shown=false
print('PASS: shared obstacle reservations cover chat input/tabs and native profession/spellbook/map/character/auction panels without moving them')
end
-- Exercise real slash dispatch with the frame recorder, no native profiler.
do
local oldCreate=CreateFrame; local captureFrame,created
CreateFrame=function(...)
local f=oldCreate(...);captureFrame=f;created=(created or 0)+1;return f
end
function GetFramerate()return 55 end
local before=CopyTable(cvars)
for run=1,7 do
SlashCmdList.RUENUI('bench');SlashCmdList.RUENUI('bench')
assert(created==1 and P.IsBenchmarkRunning(),'duplicate benchmark frame')
for i=1,55*183 do
if captureFrame.scripts.OnUpdate then captureFrame.scripts.OnUpdate(captureFrame,1/55)end
end
assert(not captureFrame.scripts.OnUpdate and not P.IsBenchmarkRunning() and #RuenUIDB.reports<=5,'frame/report retention leak')
local report=RuenUIDB.reports[#RuenUIDB.reports]
assert(math.abs(report.meanFPS-55)<.001 and report.seconds>=180 and #report.diagnostics.samples<=180)
assert(report.diagnostics.release==P.release and report.over100==0)
end
CreateFrame=oldCreate
assert(eq(cvars,before),'benchmark changed graphics')
print('PASS: real bench slash dispatch, single reused frame, per-frame report, native diagnostics, five-report bound and no graphics changes')
end

View File

@ -28,7 +28,13 @@ local function frame(name,parent)
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:GetAtlas()return self.atlas end
function f:SetAtlas(v)self.atlas=v;self.texture='atlas-file-'..v end
function f:SetAlpha(v)self.alpha=v end
function f:GetBlendMode()return self.blend or 'BLEND'end
function f:SetBlendMode(v)self.blend=v end
function f:GetDrawLayer()return 'OVERLAY',1 end
function f:SetDrawLayer(a,b)self.layer={a,b}end
function f:GetTexCoord()return 0,1,0,1 end
function f:SetTexCoord()end
function f:SetVertexColor(...)self.color={...}end
@ -47,7 +53,10 @@ local function frame(name,parent)
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
f['Set'..kind..'Texture']=function(self,t)self[kind]=frame(nil,self);self[kind].texture=t;self[kind..'Texture']=self[kind] end
-- Live buttons expose BOTH setters. Omitting atlas setters hid the bug where
-- a texture-backed native highlight was replaced by the fallback atlas.
f['Set'..kind..'Atlas']=function(self,t)self[kind]=frame(nil,self);self[kind]:SetAtlas(t);self[kind..'Texture']=self[kind] end
end
frames[#frames+1]=f;if name then _G[name]=f end;return f
end
@ -55,6 +64,9 @@ 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
PetActionButton1.Flash=frame();PetActionButton1.Flash:SetTexture('native-Flash')
function UIFrameFlash(f)f.flashing=true end
function UIFrameFlashStop(f)f.flashing=false end
EditModeManagerFrame=frame('EditModeManagerFrame',UIParent)
RuenUIDB={};RuenUICharacter={}
Enum={SpellBookSpellBank={Pet=1},SpellBookItemType={Spell=1,PetAction=3},ActionBarSet={Mkb=0,Gamepad=1}}
@ -89,6 +101,12 @@ 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 activeStance,activeOrder,attacking
local function activate(id)
if id>=100663296 and id<=100663300 then activeStance=id
elseif id==117440514 then attacking=true
elseif id==117440512 or id==117440513 then activeOrder=id;attacking=false end
end
local engineActions={}
local rejectPlacement=false
storedType='engine_pet'
@ -101,7 +119,7 @@ function PlaceAction(slot)
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,
IsCurrentAction=function(slot)local a=actions[slot];return a and (a[2]==activeStance or a[2]==activeOrder or (a[2]==117440514 and attacking)) or false end,
GetBonusBarIndexForSlot=function()return nil end,
GetActionBarPage=function()return currentPage end,
FindPetActionButtons=function(id)
@ -140,6 +158,7 @@ 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
activate(actions[slot][2])
end
C_Macro={RunMacroText=function()error('must not use macrotext for pet activation')end}
assert(loadfile((assert(os.getenv('RUEN_NATIVE_UI'))..'/SecureTemplates.lua')))()
@ -159,6 +178,7 @@ local function click(button,mouse)
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..'ButtonStyle.lua'))('RuenUI',P)
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')
@ -178,7 +198,23 @@ 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.Normal.texture=='native-Normal' and a.Checked.texture=='native-Checked','missing getter must use native named selected region, not generic glow')
assert(a.Checked.alpha==1 and a.Checked.blend==PetActionButton1.Checked:GetBlendMode(),'selected artwork opacity/blending mismatch')
assert(a.Checked.points[1][1]=='TOPLEFT' and a.Checked.layer[1]=='OVERLAY','native artwork anchor/layer mismatch')
-- A modern atlas remains authoritative too; fallback art is used only when
-- neither a native atlas nor a native file texture exists.
local prototype,probe=frame(),frame()
prototype:SetCheckedAtlas('native-selected-atlas')
P.StyleActionButton(probe,prototype)
assert(probe.Checked:GetAtlas()=='native-selected-atlas','native atlas replaced by fallback')
-- Live beta7 evidence: Checked=true, texture file matches the native button,
-- but GetAtlas() is nil on the extension. CheckButton lacks SetCheckedAtlas;
-- its checked TEXTURE still supports SetAtlas. Copying the file ID is not enough.
probe.SetCheckedAtlas=nil
P.StyleActionButton(probe,prototype)
assert(probe.Checked:GetAtlas()=='native-selected-atlas','checked texture lost atlas without widget atlas setter')
P.StyleActionButton(probe,nil)
assert(probe.Checked:GetAtlas()=='UI-HUD-ActionBar-IconFrame-Mouseover','missing-art fallback unavailable')
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
@ -339,6 +375,7 @@ 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..'ButtonStyle.lua'))('RuenUI',Q)
assert(loadfile(root..'PetExtras.lua'))('RuenUI',Q)
Q.InitializePetExtras(function()return true end)
assert(places==before+1,'reload retried rejected placement')
@ -362,6 +399,20 @@ assert(GetActionInfo(c.actionSlot)=='spell' and select(2,GetActionInfo(c.actionS
for _,button in ipairs({c,d}) do
local count=#uses;click(button,'LeftButton');assert(#uses==count+1 and uses[#uses]==button.actionSlot)
end
-- State belongs to the engine, not the last extra button clicked. Native
-- Passive (slot 0), a macro or a pet change must clear a selected extra stance.
click(c,'LeftButton');c.scripts.OnUpdate(c,.2);d.scripts.OnUpdate(d,.2)
assert(c.checked and not d.checked and c.Checked.alpha==1)
activate(100663296);c.scripts.OnUpdate(c,.2);d.scripts.OnUpdate(d,.2)
assert(not c.checked and not d.checked,'native Passive did not clear extra stance highlight')
click(d,'LeftButton');c.scripts.OnUpdate(c,.2);d.scripts.OnUpdate(d,.2)
assert(not c.checked and d.checked,'mutually exclusive stance highlights')
local startPlaces=places
for i=1,500 do activate(i%2==0 and 100663300 or 100663296);c.scripts.OnUpdate(c,.2)end
assert(places==startPlaces,'visual refresh altered action assignments')
print('PASS: native selected artwork without getters, alpha/blend/layer parity, native/extra mutually exclusive stance state and 500 visual-only transitions')
P.SetActionButtonSelected(c,true,true);assert(c.Flash.flashing and c.Checked.alpha==.5,'attack indication missing')
P.SetActionButtonSelected(c,true,false);assert(not c.Flash.flashing and c.Checked.alpha==1,'stance inherited attack flashing')
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')

100
tests/check-profiles.lua Normal file
View File

@ -0,0 +1,100 @@
local root=assert(arg[1], 'Pass addon directory with trailing slash')
local base,saves,combat,class,role,spec={},0,false,'HUNTER','NONE',nil
local frames={}
UIParent={}
function CreateFrame(_,name)
local frame={events={},scripts={}}
function frame:RegisterEvent(e)self.events[e]=true end
function frame:SetScript(k,v)self.scripts[k]=v end
function frame:HookScript(k,v)self.scripts[k]=v end
frames[#frames+1]=frame
if name then _G[name]=frame end
return frame
end
function InCombatLockdown()return combat end
function UnitClass()return class,class end
function UnitName()return 'Test' end
function UnitGUID()return 'player-'..class end
function UnitGroupRolesAssigned()return role end
function GetSpecialization()return spec end
function GetSpecializationRole()return role end
function GetCurrentBindingSet()return 1 end
function GetBindingAction(key)return base[key] or '' end
function GetBindingKey(action)for k,v in pairs(base)do if v==action then return k end end end
function GetBindingText(key)return key end
function SaveBindings()saves=saves+1 end
function hooksecurefunc(object,key,fn)local old=object[key];object[key]=function(...)old(...);fn(...)end end
C_Timer={After=function(_,fn)fn()end}
PetActionBar={IsShown=function()return false end}
function UnitExists(unit)return unit=='pet' and PetActionBar:IsShown()end
local fixture=dofile('tests/secure-binding-fixture.lua')
local P={Localized=function(en)return en end}
assert(loadfile(root..'CharacterProfiles.lua'))('RuenUI',P)
RuenUIDB={petBindingsVersion=2,cooldownsMode='off',damageMeterMode='auto'}
local numbers={'1','2','3','4','5','6','7','8','9','0','-','='}
for i,key in ipairs(numbers)do
base[key]=i<=10 and 'BONUSACTIONBUTTON'..i or 'CLICK RuenPetExtraButton'..i..':LeftButton'
base['CTRL-'..key]='MULTIACTIONBAR4BUTTON'..i
end
base.Q='ACTIONBUTTON1';base.F1='TARGETSELF'
local function font()return {SetText=function(self,s)self.text=s end,Show=function(self)self.shown=true end,Hide=function(self)self.shown=false end}end
PetActionButton1={HotKey=font(),SetHotkeys=function()end}
MultiBarLeftButton1={HotKey=font(),UpdateHotkeys=function()end}
RuenPetExtraButton11={HotKey=font()}
local chars={}
for _,value in ipairs({'HUNTER','WARLOCK','ROGUE','WARRIOR','MAGE','DRUID','PALADIN','SHAMAN','PRIEST'})do
class=value;RuenUICharacter={version=5};chars[class]=RuenUICharacter
P.InitializeCharacterProfiles();P.ApplyCharacterBindings(false)
local pet=class=='HUNTER' or class=='WARLOCK'
for i,key in ipairs(numbers)do
local action=i<=10 and 'BONUSACTIONBUTTON'..i or 'CLICK RuenPetExtraButton'..i..':LeftButton'
assert(GetBindingAction(key,true)==(pet and action or 'MULTIACTIONBAR4BUTTON'..i))
assert(GetBindingAction('CTRL-'..key,true)==(pet and 'MULTIACTIONBAR4BUTTON'..i or action))
end
assert(PetActionButton1.HotKey.text==(pet and '1' or 'CTRL-1'))
assert(MultiBarLeftButton1.HotKey.text==(pet and 'CTRL-1' or '1'))
assert(RuenPetExtraButton11.HotKey.text==(pet and '-' or 'CTRL--'))
assert(base['1']=='BONUSACTIONBUTTON1' and base['CTRL-1']=='MULTIACTIONBAR4BUTTON1' and saves==0,'profile rewrote shared bindings')
assert(RuenUICharacter.cooldownsMode=='off' and RuenUICharacter.damageMeterMode=='auto')
end
-- Manual changes after a profile was applied immediately supersede it.
base['1']='CUSTOM';P.ApplyCharacterBindings(false)
assert(GetBindingAction('1',true)=='CUSTOM' and RuenUICharacter.numberBindingConflicts[1]=='1')
base['1']='BONUSACTIONBUTTON1';P.ApplyCharacterBindings(false)
assert(GetBindingAction('1',true)=='BONUSACTIONBUTTON1','reclaimed a customized key automatically')
P.ApplyCharacterBindings(true);assert(GetBindingAction('1',true)=='MULTIACTIONBAR4BUTTON1')
-- Config changes defer in combat; native handoff still executes its secure
-- snippet immediately, without an insecure SetAttribute call.
combat=true
P.CharacterProfileCommand('keys','pet')
assert(GetBindingAction('1',true)=='MULTIACTIONBAR4BUTTON1')
fixture.transition(true);assert(next(fixture.active())==nil,'native control handoff retained overrides')
fixture.transition(false);assert(GetBindingAction('1',true)=='MULTIACTIONBAR4BUTTON1')
combat=false;P.ApplyCharacterBindings(false);assert(GetBindingAction('1',true)=='BONUSACTIONBUTTON1')
-- Mage capability: no unconditional empty pet shelf, but no disappearing row
-- after a temporary pet dies during the same session.
class='MAGE';RuenUICharacter=chars.MAGE;P.ApplyCharacterBindings(false)
assert(not P.NeedsPetRow())
PetActionBar.IsShown=function()return true end;assert(P.NeedsPetRow())
PetActionBar.IsShown=function()return false end;assert(P.NeedsPetRow())
spec=2;assert(not P.NeedsPetRow());spec=nil
-- Roles do not follow forms or class guesses, and manual choices win.
RuenUICharacter={};P.EnsureCharacterProfile();assert(P.CharacterRole()=='UNKNOWN' and RuenUICharacter.cooldownsMode=='off')
role='HEALER';assert(P.CharacterRole()=='HEALER')
P.CharacterProfileCommand('role','damage');assert(P.CharacterRole()=='DAMAGER' and RuenUICharacter.mouseoverMode=='auto')
role='TANK';assert(P.CharacterRole()=='DAMAGER')
P.CharacterProfileCommand('role','auto');assert(P.CharacterRole()=='TANK')
-- Assigned roles can change without a specialization change on this client.
local roleSeen
P.ApplyMouseover=function()roleSeen=P.CharacterRole()end
role='HEALER'
for _,frame in ipairs(frames)do
if frame.events.PLAYER_ROLES_ASSIGNED then frame.scripts.OnEvent(frame,'PLAYER_ROLES_ASSIGNED')end
end
assert(roleSeen=='HEALER','assigned role changes must refresh the auto input preference')
RuenUIDB.disabled=true;P.ApplyCharacterBindings(false)
assert(next(fixture.active())==nil and GetBindingAction('1',true)==base['1'])
RuenUIDB.disabled=nil;P.ApplyCharacterBindings(false)
assert(next(fixture.active())~=nil)
P.ClearCharacterBindings();assert(next(fixture.active())==nil and saves==0)
print('PASS: nine-class 24-key profiles, no account writes, actual secure snippet combat handoff, manual key preservation, effective hotkeys, deferred changes, role/capability defaults, migration and restore')

View File

@ -32,32 +32,130 @@ event(dock,'PLAYER_SWING',2,1);speeds={2};event(dock,'UNIT_INVENTORY_CHANGED','p
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
local cvars={RenderScale='0.9',graphicsTextureResolution='2'};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
function GetRealZoneText()return 'Test zone' end
function GetSubZoneText()return 'Test cave' end
assert(loadfile(root..'FrameTiming.lua'))('test',P)
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)
P.OptimizerCommand('start')
assert(cvars.RAIDsettingsEnabled=='0' and cvars.RenderScale=='0.9','native overrides active or resolution changed')
assert(cvars.graphicsLightMode=='0' and cvars.graphicsPBRLiquidDetail=='0','expensive lighting omitted')
frames(66*600,1/66)
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)
assert(d.profiles.world.tier==5 and d.profiles.world.revision==2,'did not search/validate highest allowed tier')
assert(d.profiles.world.last.phase=='validate' and d.profiles.world.subzone=='Test cave')
assert(not d.profiles.raid.calibrated and not d.profiles.dungeon.calibrated,'solo validated instance')
assert(cvars.maxFPS=='60' and not f.scripts.OnUpdate,'trial cap or idle polling leaked')
local before=writes;frames(600,1/60);assert(writes==before)
-- A plain command must remeasure this cave despite previous world success.
P.OptimizerCommand('');assert(P.IsOptimizerCalibrating() and not d.profiles.world.calibrated)
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')
-- Entering a dungeon must measure/apply dungeon settings, not ignore it.
where='party';P.OptimizerCommand('30');assert(d.requestedFPS==30 and d.target==30)
frames(33*600,1/33)
assert(d.profiles.dungeon.calibrated and d.profiles.dungeon.metTarget and cvars.maxFPS=='30')
assert(d.profiles.dungeon.tier==5 and cvars.graphicsShadowQuality=='3')
-- Combat defers ALL writes, including environment handoff and restore.
where='raid';combat=true;before=writes;f.scripts.OnEvent(f,'ZONE_CHANGED_NEW_AREA')
frames(33*120,1/33);assert(writes==before,'combat edits occurred')
P.OptimizerCommand('restore');assert(RuenUIDB.optimizer==d)
combat=false;f.scripts.OnEvent(f,'PLAYER_REGEN_ENABLED');frames(33*600,1/33)
assert(d.profiles.raid.calibrated and not d.profiles.battleground.calibrated)
where='pvp';f.scripts.OnEvent(f,'ZONE_CHANGED_NEW_AREA');frames(33*600,1/33)
assert(d.profiles.battleground.calibrated and not f.scripts.OnUpdate)
P.OptimizerCommand('restore');assert(not RuenUIDB.optimizer and cvars.RAIDsettingsEnabled=='2')
assert(cvars.RenderScale=='0.9' and cvars.graphicsTextureResolution=='2','clarity settings lost')
-- Sparse 200ms hitches escape p99 but MUST reject a candidate. Only low tiers
-- are smooth here, so the chosen tier should stop at 2, with a capped validation.
where='none';P.hardwareProfile={};P.OptimizerCommand('60')
for i=1,66*600 do
local dt=(tonumber(cvars.graphicsShadowQuality)>=2 and i%330==0) and .2 or 1/66
frames(1,dt)
end
d=RuenUIDB.optimizer
assert(d.profiles.world.metTarget and d.profiles.world.tier==2,'brief stutters did not reject higher tier')
local rejected=false
for _,r in ipairs(d.profiles.world.history)do if r.over100>0 then rejected=true end end
assert(rejected,'hitches not retained as evidence')
-- Even a >2 second gameplay stall is counted; never silently drop it.
P.OptimizerCommand('60')
for i=1,66*400 do frames(1,i%330==0 and 2.5 or 1/66)end
assert(d.profiles.world.calibrated and not d.profiles.world.metTarget and d.profiles.world.tier==1)
assert(d.profiles.world.last.worstMS>=2500 and d.profiles.world.last.over250>0)
-- Known loading periods are not gameplay; a fresh window follows them.
P.OptimizerCommand('60');frames(66*12,1/66)
f.scripts.OnEvent(f,'PLAYER_LEAVING_WORLD');frames(5,5)
f.scripts.OnEvent(f,'PLAYER_ENTERING_WORLD');frames(66*600,1/66)
assert(d.profiles.world.metTarget and d.profiles.world.last.worstMS<20)
-- Invalid requests do not change target or start a measurement.
before=writes;P.OptimizerCommand('19');P.OptimizerCommand('999');P.OptimizerCommand('world bad');P.OptimizerCommand('60 30')
assert(writes==before and not P.IsOptimizerCalibrating())
-- FPS changed explicitly, report freshness/thermal ceiling, clean pause/undo.
P.hardwareProfile={checkedAt=clock,loaded=true,thermalPressure=true}
P.OptimizerCommand('60');assert(d.target==45 and d.ceiling==2)
P.OptimizerCommand('30');assert(d.target==30 and d.requestedFPS==30)
P.OptimizerCommand('pause');assert(not f.scripts.OnUpdate and not d.enabled)
P.IsBenchmarkRunning=function()return true end;before=writes
P.OptimizerCommand('60');assert(writes==before and not d.enabled)
P.IsBenchmarkRunning=nil
-- Unsupported options remain unchanged; a rejected write cannot be called applied.
IsGraphicsSettingValueSupported=function(k)return k=='graphicsLightMode' and 1 or 0 end
cvars.graphicsLightMode='2';P.OptimizerCommand('30');frames(33*600,1/33)
assert(d.profiles.world.unsupported.graphicsLightMode and cvars.graphicsLightMode=='2')
P.OptimizerCommand('pause')
print('PASS: headroom calibration, separate real-world/raid tests, actual frame percentiles, combat deferral, thermal input, pause and exact undo')
print('PASS: real frame tails/hitches, scene retest, capped validation, four environments, combat/loading guards, target parsing, unsupported settings, hardware evidence, exact restore and idle sleep')
-- A different environment reached during a benchmark must wait until it ends.
P.OptimizerCommand('resume');frames(33*600,1/33)
P.IsBenchmarkRunning=function()return true end
where='party';before=writes;f.scripts.OnEvent(f,'ZONE_CHANGED_NEW_AREA')
assert(writes==before and not f.scripts.OnUpdate)
P.IsBenchmarkRunning=nil;P.OptimizerBenchmarkEnded()
assert(P.IsOptimizerCalibrating() and writes>before)
frames(33*600,1/33);P.OptimizerCommand('pause')
print('PASS: deferred environment handoff resumes after read-only benchmark')
-- Feedback is based on read-back differences, not attempted writes. Progress
-- appears at window boundaries, and waiting notices cannot spam each frame.
local oldPrint=print;local messages={}
print=function(message)messages[#messages+1]=message end
local function contains(text)
for _,message in ipairs(messages)do if message:find(text,1,true)then return true end end
end
local function changesHave(key)
for _,change in ipairs(d.lastChange.changes)do if change.key==key then return change end end
end
P.hardwareProfile={};where='none'
IsGraphicsSettingValueSupported=function()return 0 end
local realSet=C_CVar.SetCVar
C_CVar.SetCVar=function(k,v)if k~='graphicsSSAO' then realSet(k,v) end end
cvars.graphicsShadowQuality='4';cvars.graphicsSSAO='2';cvars.maxFPS='60'
P.OptimizerCommand('60')
assert(changesHave('graphicsShadowQuality').before=='4')
assert(changesHave('maxFPS').after=='66' and contains('(temporary)'))
assert(not changesHave('graphicsSSAO') and d.lastChange.unavailable.graphicsSSAO,'rejected write described as applied')
assert(contains('Unavailable/not applied: Ambient shading'))
C_CVar.SetCVar=realSet
combat=true;frames(66*60,1/66)
assert(contains('waiting for combat to end'))
local count=#messages;frames(66*60,1/66)
assert(#messages==count,'waiting notice repeated every frame')
P.OptimizerCommand('status');assert(contains('waiting for combat to end'))
combat=false;f.scripts.OnEvent(f,'PLAYER_REGEN_ENABLED');frames(66*600,1/66)
assert(d.lastChange.heading=='Final changes compared with the start of this run:')
assert(d.lastChange.mode=='world' and changesHave('graphicsShadowQuality').after==cvars.graphicsShadowQuality)
assert(not changesHave('maxFPS'),'final summary included temporary trial cap')
before=writes;P.OptimizerCommand('changes');P.OptimizerCommand('status')
assert(writes==before,'report commands changed graphics')
count=#messages;frames(66*120,1/66);assert(#messages==count and not f.scripts.OnUpdate)
-- Resume identical saved values must not invent a change or flood chat.
P.OptimizerCommand('resume');assert(#messages==count)
P.OptimizerCommand('pause');assert(contains('No graphics values changed in this step.'))
print=oldPrint
print('PASS: real before/after values, rejected writes excluded, temporary/final distinction, net-run summary, bounded progress/wait notices and read-only status/changes')

View File

@ -0,0 +1,51 @@
-- Executes Ruen's actual restricted snippet against a modeled binding engine.
-- This does not claim to reproduce the live secure VM or native priority rules.
local frames, active, special = {}, {}, false
local create, getAction = CreateFrame, GetBindingAction
CreateFrame = function(kind,name,parent,template)
local frame = create(kind,name,parent,template)
if template == "SecureHandlerStateTemplate" then
frames[#frames+1]=frame
frame.profileAttributes={}
function frame:SetAttribute(key,value)
assert(not InCombatLockdown(),'insecure profile attribute write in combat')
self.profileAttributes[key]=value
end
function frame:GetAttribute(key)return self.profileAttributes[key]end
function frame:SetBinding(priority,key,action)
assert(self.inSecureSnippet and priority==false,'must use non-priority secure binding')
active[key]=action
end
function frame:ClearBindings()
assert(self.inSecureSnippet,'clear must execute through secure snippet')
active={}
end
function frame:Execute(body)
self.inSecureSnippet=true
local fn=assert(loadstring(body));setfenv(fn,{self=self});fn()
self.inSecureSnippet=false
end
end
return frame
end
function RegisterStateDriver(frame,key,conditions)
assert(not InCombatLockdown())
assert(conditions=='[vehicleui][overridebar][possessbar] special; normal')
frame.profileState=key
frame.profileAttributes['state-'..key]=special and 'special' or 'normal'
frame:Execute(frame.profileAttributes['_onstate-'..key])
end
function UnregisterStateDriver(frame,key)frame.profileState=nil end
GetBindingAction=function(key,withOverrides)
if withOverrides and active[key] then return active[key] end
return getAction(key,withOverrides)
end
return {transition=function(value)
special=value
for _,frame in ipairs(frames)do
if frame.profileState then
frame.profileAttributes['state-'..frame.profileState]=value and 'special' or 'normal'
frame:Execute(frame.profileAttributes['_onstate-'..frame.profileState])
end
end
end, active=function()return active end}