ruen-ui/RuenUI/ClassAssist.lua

340 lines
17 KiB
Lua

local _, P = ...
-- Blizzard selects the learned spells, ranks, overrides and talent-specific
-- categories. Ruen only supplies presentation and a class-aware input default.
-- Do not write C_CooldownViewer layout data or replace its secure aura handlers.
local names = {"EssentialCooldownViewer", "UtilityCooldownViewer", "BuffIconCooldownViewer", "BuffBarCooldownViewer"}
local owns, place, edge, put, queue
local busy, queued, hooked = false, false, {}
local appliedContext
local diagnosticSignature, diagnosticSpells
P.classAssistReserved = {}
local function settingsOpen()
return (EditModeManagerFrame and EditModeManagerFrame:IsShown())
or (CooldownViewerSettings and CooldownViewerSettings:IsShown())
end
local function mode()
return RuenUICharacter.cooldownsMode or RuenUIDB.cooldownsMode or "auto"
end
local function set(system, key, value)
if key == nil then return end
system.settings = system.settings or {}
for _, entry in ipairs(system.settings) do
if entry.setting == key then entry.value = value; return end
end
system.settings[#system.settings+1] = {setting=key, value=value}
end
local function counts()
local result, signature, groups = {}, {}, {}
for i, name in ipairs(names) do
local f = _G[name]
if not f or not f.GetCooldownIDs then return end
local ok, ids = pcall(f.GetCooldownIDs, f)
if not ok or type(ids) ~= "table" then return end -- data not loaded yet
groups[i] = ids
result[i] = #ids
signature[i] = table.concat(ids, ",")
end
return result, table.concat(signature, "/"), groups
end
-- Query static spell metadata only after the native list changes, out of combat.
-- These are diagnostics, not an independent cooldown or combat-log tracker.
local function describeSpells(signature, groups)
local _,class=UnitClass("player")
local key=class..":"..(GetLocale and GetLocale() or "")..":"..signature
if diagnosticSignature==key then return diagnosticSpells end
local result,complete={},true
for i,ids in ipairs(groups) do
result[i]={}
for _,id in ipairs(ids) do
local info
if C_CooldownViewer.GetCooldownViewerCooldownInfo then
local ok,value=pcall(C_CooldownViewer.GetCooldownViewerCooldownInfo,id)
if ok then info=value end
end
local spellID=info and (info.overrideTooltipSpellID or info.overrideSpellID or info.spellID)
local spell
if spellID and C_Spell and C_Spell.GetSpellInfo then
local ok,value=pcall(C_Spell.GetSpellInfo,spellID)
if ok then spell=value end
end
local name=spell and spell.name
result[i][#result[i]+1]={cooldownID=id,spellID=spellID,name=name}
if not name then complete=false end
end
end
if complete then diagnosticSignature,diagnosticSpells=key,result end
return result
end
function P.CooldownSummary()
local status=RuenUICharacter.classAssistStatus or {}
local lines={P.Localized("Native cooldown list (not every ability):", "Список клиента (не все способности):")}
if status.available==false then lines[#lines+1]=P.Localized("Unavailable: ","Недоступно: ")..tostring(status.reason) end
local labels={P.Localized("Essential","Основные"), P.Localized("Utility","Вспомогательные"),
P.Localized("Buff icons","Эффекты"), P.Localized("Buff durations","Длительность эффектов")}
for i,label in ipairs(labels) do
local spells={}
for _,entry in ipairs((status.spells or {})[i] or {}) do
spells[#spells+1]=entry.name or ("ID "..tostring(entry.spellID or entry.cooldownID))
end
lines[#lines+1]=label.." ("..tostring((status.counts or {})[i] or 0).."): "..table.concat(spells,", ")
end
lines[#lines+1]=P.Localized("auto/on: combat only; show: preview outside combat; hide/off: hidden; settings: choose from the client's eligible spells.",
"auto/on: только в бою; show: показ вне боя; hide/off: скрыть; settings: выбор из доступных клиенту способностей.")
return table.concat(lines,"\n")
end
function P.ConfigureClassAssistSystems(layout, itemCounts)
local E, S, V = Enum.EditModeSystem, Enum.EditModeCooldownViewerSetting, Enum.CooldownViewerVisibleSetting
if not S or not V then return end
for _, system in ipairs(layout.systems or {}) do
if system.system == E.CooldownViewer and names[system.systemIndex] then
local i = system.systemIndex
-- Release Blizzard's bottom-frame stacking through detached saved
-- layout data. Otherwise showing a viewer in combat can snap it
-- back over the pet/action rows despite our out-of-combat anchor.
system.isInDefaultPosition = false
system.anchorInfo = {point="BOTTOM", relativeTo="UIParent", relativePoint="BOTTOM",
offsetX=({0,280,0,-280})[i], offsetY=({300,300,350,300})[i]}
set(system, S.Orientation, i == 4 and Enum.CooldownViewerOrientation.Vertical or Enum.CooldownViewerOrientation.Horizontal)
set(system, S.IconDirection, Enum.CooldownViewerIconDirection.Right)
set(system, S.IconLimit, i == 1 and 6 or 8)
-- IconSize uses (stored * 10 + 50)%, unlike IconLimit/Padding.
-- Native base sizes: essential 50, utility 30, buff 40, bar 30.
set(system, S.IconSize, ({1,4,1,3})[i]) -- 30 / 27 / 24 / 24 units
set(system, S.IconPadding, i == 4 and 4 or 8) -- visual gaps 2 / 4
set(system, S.BarWidthScale, 75) -- 125% * 220 * .8 = 220 units
set(system, S.Opacity, 50) -- 100%, encoded from the 50% minimum
set(system, S.HideWhenInactive, i >= 3 and 1 or 0)
set(system, S.ShowTimer, 1)
set(system, S.ShowTooltips, 1)
set(system, S.BarContent, Enum.CooldownViewerBarContent.IconAndName)
local visible = mode() == "show" and V.Always or V.InCombat
if mode() == "off" or (itemCounts and itemCounts[i] == 0) then visible = V.Hidden end
set(system, S.VisibleSetting, visible)
end
end
end
local function configureViewers(itemCounts, signature)
local _, class = UnitClass("player")
local context = class .. ":" .. mode() .. ":" .. signature
if appliedContext == context then return end
local data = P.CopyEditModeLayouts()
local found = false
for _, layout in ipairs(data.layouts or {}) do
if P.IsOurLayout(layout) then
RuenUIDB.beforeClassAssist = RuenUIDB.beforeClassAssist or C_EditMode.ConvertLayoutInfoToString(layout)
P.ConfigureClassAssistSystems(layout, itemCounts)
found = true
end
end
if found then
appliedContext = context
P.SaveEditModeLayouts(data)
end
end
function P.ApplyMouseover(force)
if InCombatLockdown() or RuenUIDB.disabled then return end
force = force or P.mouseoverPending
if not GetModifiedClick or not SetModifiedClick or not C_CVar.GetCVar("enableMouseoverCast")
or (IsMouseoverCastSupported and not IsMouseoverCastSupported()) then
RuenUICharacter.mouseoverStatus = "unavailable"
return
end
local _, class = UnitClass("player")
local preference = RuenUICharacter.mouseoverMode or "auto"
local 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 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"
return
end
RuenUICharacter.mouseoverOriginal = RuenUICharacter.mouseoverOriginal or {value=current, modifier=modifier}
RuenUIDB.results = RuenUIDB.results or {}
put("enableMouseoverCast", value)
if enabled then
if Settings and Settings.GetSetting and Settings.GetSetting("MOUSEOVERCAST") then
Settings.SetValue("MOUSEOVERCAST", "NONE")
else SetModifiedClick("MOUSEOVERCAST", "NONE") end
elseif previous and previous.enabled and modifier == "NONE" then
local old = RuenUICharacter.mouseoverOriginal.modifier or "NONE"
if Settings and Settings.GetSetting and Settings.GetSetting("MOUSEOVERCAST") then
Settings.SetValue("MOUSEOVERCAST", old)
else SetModifiedClick("MOUSEOVERCAST", old) end
end
RuenUICharacter.mouseoverApplied = {class=class, role=role, mode=preference, enabled=enabled}
RuenUIDB.mouseoverLastCharacter = character
P.mouseoverPending = nil
RuenUICharacter.mouseoverStatus = enabled and "on" or "off"
end
function P.RestoreClassAssist()
if InCombatLockdown() then return end
P.classAssistReserved = {}
appliedContext = nil
local old = RuenUICharacter.mouseoverOriginal
if old and SetModifiedClick then
if Settings and Settings.GetSetting and Settings.GetSetting("MOUSEOVERCAST") then
Settings.SetValue("MOUSEOVERCAST", old.modifier)
else SetModifiedClick("MOUSEOVERCAST", old.modifier) end
end
RuenUICharacter.mouseoverApplied = nil
RuenUIDB.mouseoverLastCharacter = nil
P.mouseoverPending = nil
end
local function positionViewers(itemCounts)
local obstacles = {}
P.classAssistReserved = {} -- don't collide with last pass's own reservations
for _, r in ipairs(P.OverlayObstacles(false)) do
-- Cooldowns are gameplay information; the meter fits around them.
if not r.name or not r.name:match("^DamageMeter") then obstacles[#obstacles+1] = r end
end
local center = UIParent:GetWidth()/2
local base = (edge(PlayerCastingBarFrame,"GetTop") or 280)+12
local nextCenter = base
RuenUICharacter.classAssistUnplaced = {}
-- Essential abilities are closest to the cast bar; buffs just above them.
-- Utility and duration bars use nearby free space, without moving controls.
-- A tall duration stack needs a contiguous lane before small icon groups
-- fragment it. Normal short stacks retain the closest-to-center layout.
local order = itemCounts[4] > 4 and {4,1,3,2} or {1,3,2,4}
for _, i in ipairs(order) do
local f = _G[names[i]]
if itemCounts[i] > 0 and mode() ~= "off" then
local scale = f:GetEffectiveScale()/UIParent:GetEffectiveScale()
local w, h = f:GetWidth()*scale, f:GetHeight()*scale
if w > 0 and h > 0 then
local x, y = center-w/2, nextCenter
if i == 2 then x, y = center+130, base end
if i == 4 then x, y = center-130-w, base end
-- Account for the native icon border/glow beyond its frame.
local target = P.FindOverlayPosition(w+12,h+12,x-6,y-6,obstacles,UIParent:GetWidth(),UIParent:GetHeight())
if target then
target.name = names[i]
place(f,"BOTTOMLEFT",UIParent,"BOTTOMLEFT",target.left+6,target.bottom+6)
obstacles[#obstacles+1] = target
P.classAssistReserved[#P.classAssistReserved+1] = target
if i == 1 or i == 3 then nextCenter = target.top+12 end
else
-- Do not silently omit learned spells or move protected bars.
RuenUICharacter.classAssistUnplaced[#RuenUICharacter.classAssistUnplaced+1] = names[i]
end
end
end
end
end
local function refresh()
P.ApplyMouseover(false)
if C_CooldownViewer and C_CooldownViewer.IsCooldownViewerAvailable then
local available, reason = C_CooldownViewer.IsCooldownViewerAvailable()
local itemCounts, signature, groups = counts()
RuenUICharacter.classAssistStatus = {available=available, reason=reason, mode=mode(), counts=itemCounts,
spells=groups and describeSpells(signature,groups), enabled=C_CVar.GetCVar("cooldownViewerEnabled")}
if available and itemCounts then
RuenUIDB.results = RuenUIDB.results or {}
local enabled = mode() == "off" and "0" or "1"
if C_CVar.GetCVar("cooldownViewerEnabled") ~= enabled then put("cooldownViewerEnabled",enabled) end
RuenUICharacter.classAssistStatus.enabled=enabled
configureViewers(itemCounts,signature)
for _,name in ipairs(names) do
local f = _G[name]
if not hooked[f] then
hooked[f] = true
f:HookScript("OnSizeChanged",queue)
if f.OnUpdateSystem then hooksecurefunc(f,"OnUpdateSystem",queue) end
end
end
positionViewers(itemCounts)
elseif not available then P.classAssistReserved = {} end
end
end
function P.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
if not owns() or settingsOpen() then P.classAssistReserved = {}; return end
busy = true
local ok, err = pcall(refresh)
busy = false -- an unavailable native subsystem must not disable future retries
if not ok and RuenUICharacter.classAssistError ~= tostring(err) then
RuenUICharacter.classAssistError = tostring(err)
if geterrorhandler then geterrorhandler()(err) end
elseif ok then RuenUICharacter.classAssistError = nil end
end
function P.ClassAssistCommand(command, argument)
if command == "mouseover" then
if argument == "auto" or argument == "on" or argument == "off" then
RuenUICharacter.mouseoverMode = argument
P.mouseoverPending = true
P.ApplyMouseover(true)
end
return P.Localized("Mouseover preference: ","Настройка наведения: ") .. (RuenUICharacter.mouseoverMode or "auto")
.. P.Localized("; active: ","; сейчас: ") .. (RuenUICharacter.mouseoverStatus or "pending") .. P.Localized(
". /ruen mouseover auto|on|off. When enabled, hover a valid unit and press the spell key; no extra modifier. Combat changes wait.",
". /ruen mouseover auto|on|off. Когда включено, наведите на подходящую цель и нажмите клавишу заклинания; без модификатора. Изменения — после боя.")
end
if argument == "on" then argument="auto" end
if argument == "hide" then argument="off" end
if argument == "status" then P.RefreshClassAssist();return P.CooldownSummary() end
if argument == "settings" and CooldownViewerSettings and not InCombatLockdown() then
CooldownViewerSettings:ShowUIPanel()
elseif argument == "auto" or argument == "show" or argument == "off" then
RuenUICharacter.cooldownsMode = argument
P.RefreshClassAssist()
end
return P.Localized("Cooldowns: ","Перезарядки: ") .. mode() .. P.Localized(
". /ruen cooldowns auto (combat), show, hide/off, settings, status. Spells follow your class, talents and training; changes wait until combat ends.",
". /ruen cooldowns auto (в бою), show, hide/off, settings, status. Способности зависят от класса, талантов и обучения; изменения — после боя.")
end
function P.InitializeClassAssist(isOurs, placeFrame, frameEdge, setCVar)
owns, place, edge, put = isOurs, placeFrame, frameEdge, setCVar
if P.classAssistListener then return end
local listener = CreateFrame("Frame"); P.classAssistListener = listener
queue = function()
if busy or queued then return end
queued = true
C_Timer.After(.25,function()
queued = false
P.RefreshClassAssist()
if P.RefreshDamageMeters then P.RefreshDamageMeters() end
if P.PositionOverlayFrames then P.PositionOverlayFrames() end
end)
end
for _,event in ipairs({"PLAYER_ENTERING_WORLD","PLAYER_REGEN_ENABLED","SPELLS_CHANGED","PLAYER_TALENT_UPDATE",
"PLAYER_SPECIALIZATION_CHANGED","COOLDOWN_VIEWER_DATA_LOADED","COOLDOWN_VIEWER_TABLE_HOTFIXED",
"DISPLAY_SIZE_CHANGED","UI_SCALE_CHANGED","ADDON_LOADED"}) do listener:RegisterEvent(event) end
listener:SetScript("OnEvent",queue)
if EventRegistry then
for _,event in ipairs({"CooldownViewerSettings.OnShow","CooldownViewerSettings.OnHide"}) do
EventRegistry:RegisterCallback(event,queue,listener)
end
end
if EditModeManagerFrame then
EditModeManagerFrame:HookScript("OnHide",function() appliedContext=nil;queue() end)
end
queue()
end