ruen-ui/RuenUI/PetExtras.lua

448 lines
21 KiB
Lua
Raw Permalink Normal View History

local _, P = ...
-- WoW owns exactly ten pet-bar slots. Two real pet actions on unused page-2
-- slots back the extra buttons, so execution and spellbook discovery use
-- the engine's action system. Never change the ten native slots or live bars.
local buttons, listener, enabled, queued
local bank = Enum.SpellBookSpellBank and Enum.SpellBookSpellBank.Pet
local commandMacros = {
[117440514]="/petattack", [117440513]="/petfollow", [117440512]="/petstay",
[117440516]="/petmoveto", [100663298]="/petaggressive", [100663299]="/petassist",
[100663300]="/petdefensive", [100663296]="/petpassive",
}
local cursorItem, nativeItems = nil, {}
-- Validate against the engine's pet-action search, not the cursor payload's
-- type string. GetActionInfo and GetCursorInfo do not use the same types.
local function containsAction(slot, actionID)
if not C_ActionBar or not C_ActionBar.FindPetActionButtons then return false end
local slots=C_ActionBar.FindPetActionButtons(actionID,Enum.ActionBarSet and Enum.ActionBarSet.Mkb)
for _,candidate in ipairs(slots or {}) do if candidate==slot then return true end end
return false
end
local function snapshot(slot)
local kind,id,subType=GetActionInfo(slot)
return {kind=kind,id=id,subType=subType}
end
local function matches(record)
if not record then return false end
-- Commands all report ("spell", 0, "pet") on this client. That payload
-- cannot establish ownership: use the engine's command-specific lookup.
return containsAction(record.slot,record.actionID)
end
local function spareSlot(slot)
-- Only page 2 is a potential reserve. Page 3 is MultiBarRight; the other
-- pages include displayed bars and class/vehicle/override action pages.
if type(slot)~="number" or slot<13 or slot>24 or slot%1~=0 then return false end
if not MultiActionBar_GetBarForPage or MultiActionBar_GetBarForPage(2) then return false end
if C_ActionBar then
local bonus=C_ActionBar.GetBonusBarIndexForSlot and C_ActionBar.GetBonusBarIndexForSlot(slot)
if bonus and bonus~=0 then return false end
for _,name in ipairs({"GetVehicleBarIndex","GetOverrideBarIndex","GetTempShapeshiftBarIndex","GetActionBarPage"}) do
if C_ActionBar[name] and C_ActionBar[name]()==2 then return false end
end
end
return true
end
local function releaseAction(index)
local records=RuenUICharacter.petExtraActions
local record=records and records[index]
if not record then return true end
if GetCursorInfo() then return false end
-- A failed transaction is evidence, not permission to delete an unknown
-- payload or try another slot. Keep it until explicitly reassigned.
if record.failed then return false end
if record.owned and spareSlot(record.slot) and matches(record) then
PickupAction(record.slot);ClearCursor()
end
records[index]=nil -- a player's replacement/borrowed action is never removed
return true
end
local function syncAction(index,item)
if not item then releaseAction(index);return end
local records=RuenUICharacter.petExtraActions or {}
RuenUICharacter.petExtraActions=records
local record=records[index]
if record and record.failed then return nil,record.failed end
if record and not spareSlot(record.slot) then return nil,"reserved page is in use" end
if record and matches(record) and containsAction(record.slot,item.actionID) then
record.actionID=item.actionID;record.payload=snapshot(record.slot)
return record.slot
end
if GetCursorInfo() then return nil,"cursor busy" end
if record and GetActionInfo(record.slot) and not matches(record) then
record.failed="reserved action changed; reassign the extra button"
return nil,record.failed
end
if not releaseAction(index) then return nil,"assignment paused" end
-- An existing matching action can be borrowed without changing it. This
-- also allows a previously placed action to survive an interrupted setup.
local slot
for candidate=13,24 do
if spareSlot(candidate) and containsAction(candidate,item.actionID) then
records[index]={slot=candidate,actionID=item.actionID,payload=snapshot(candidate),owned=false}
return candidate
end
if not slot and spareSlot(candidate) and not GetActionInfo(candidate) then slot=candidate end
end
if not slot then return nil,"no unused paging slots" end
-- Save intent BEFORE any cursor or slot write. A failed/missing API cannot
-- fan out into additional slots on PET_BAR_UPDATE or CURSOR_CHANGED.
record={slot=slot,actionID=item.actionID,owned=true,failed="pet action placement interrupted"}
records[index]=record
local ok,err=pcall(function()
C_SpellBook.PickupSpellBookItem(item.slot,bank)
local kind=GetCursorInfo()
if kind~="petaction" then
if kind then ClearCursor() end
record.failed="pet action unavailable";return
end
PlaceAction(slot)
ClearCursor() -- slot was empty, so no player action can be displaced
record.payload=snapshot(slot)
if containsAction(slot,item.actionID) then record.failed=nil
else record.failed="pet action placement rejected; automatic retries stopped" end
end)
if not ok then record.failed=tostring(err) end
if record.failed then return nil,record.failed end
return slot
end
local function learnedItems()
local items={}
if not bank or not C_SpellBook or not C_SpellBook.HasPetSpells then return items end
for slot=1,C_SpellBook.HasPetSpells() or 0 do
local info=C_SpellBook.GetSpellBookItemInfo(slot,bank)
if info and not info.isPassive and not C_SpellBook.IsSpellBookItemPassive(slot,bank) then
local id=info.spellID or info.actionID
local name=C_SpellBook.GetSpellBookItemName(slot,bank)
local command=commandMacros[info.actionID]
local spell=not command and id and C_Spell.GetSpellInfo(id)
if name and name~="" and (command or (spell and spell.name==name)) then
items[#items+1]={id=id,actionID=info.actionID,name=name,slot=slot,
command=command,icon=info.iconID or (spell and spell.iconID)}
end
end
end
return items
end
function P.PetExtraGeometry()
local bar, first = PetActionBar, PetActionButton1
local scale = UIParent:GetEffectiveScale()
local size = first and first:GetWidth() * first:GetEffectiveScale() / scale or 39
local width = bar and bar:GetWidth() * bar:GetEffectiveScale() / scale or 408
local gap = math.max(0, (width - size * 10) / 9)
return size, gap, 2 * (size + gap)
end
function P.PetExtraChoices()
local choices, used = {}, {}
if not bank or not C_SpellBook or not C_SpellBook.HasPetSpells then return choices end
for i = 1, 10 do
local name, _, token, _, _, _, id = GetPetActionInfo(i)
if id then used[id] = true end
if name then used[token and _G[name] or name] = true end
end
for slot = 1, C_SpellBook.HasPetSpells() or 0 do
local info = C_SpellBook.GetSpellBookItemInfo(slot, bank)
if info and not info.isPassive and not C_SpellBook.IsSpellBookItemPassive(slot, bank) then
local id = info.spellID or info.actionID
local spell = id and C_Spell.GetSpellInfo(id)
-- Pet command tokens (Attack/Follow/Stance) are not spell IDs.
-- Validate the name before treating a PetAction's actionID as one.
local name = C_SpellBook.GetSpellBookItemName(slot, bank)
if spell and name and name ~= "" and spell.name == name and not used[id] and not used[name] then
choices[#choices + 1] = {id = id, actionID = info.actionID, name = name, slot = slot,
icon = info.iconID or spell.iconID}
used[id], used[name] = true, true
end
end
end
return choices
end
local function visuals(button)
local item = button.item
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
end
-- A pet or rank can change during combat. Do not read a different spell
-- through a stale slot; secure attributes are rebuilt after combat ends.
local info = C_SpellBook.GetSpellBookItemInfo(item.slot, bank)
if not info or (info.spellID or info.actionID) ~= item.id then
P.SetActionButtonSelected(button, false)
button.icon:SetVertexColor(.4, .4, .4)
button.AutoCastOverlay:Hide()
button.cooldown:Clear()
return
end
if item.command then
button.icon:SetVertexColor(1,1,1)
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)
elseif usable then button.icon:SetVertexColor(1, 1, 1)
else button.icon:SetVertexColor(.4, .4, .4) end
local allowed, active = C_SpellBook.GetSpellBookItemAutoCast(item.slot, bank)
button.AutoCastOverlay:SetShown(allowed)
button.AutoCastOverlay:ShowAutoCastEnabled(active)
-- Combat cooldown values may be secret. Let the native widget render the
-- opaque duration; Lua must not compare, format or do arithmetic on it.
if C_SpellBook.GetSpellBookItemCooldownDuration and button.cooldown.SetCooldownFromDurationObject then
local duration=C_SpellBook.GetSpellBookItemCooldownDuration(item.slot,bank)
if duration then button.cooldown:SetCooldownFromDurationObject(duration,true)
else button.cooldown:Clear() end
else
local cd=C_SpellBook.GetSpellBookItemCooldown(item.slot,bank)
if cd then button.cooldown:SetCooldown(cd.startTime,cd.duration,cd.modRate)
else button.cooldown:Clear() end
end
end
local function hotkeys()
for _, button in ipairs(buttons or {}) do
local 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
local function updateVisuals(self,dt)
self.visualElapsed=(self.visualElapsed or 0)+dt
if self.visualElapsed>=.2 then self.visualElapsed=0;visuals(self) end
end
function P.RefreshPetExtras()
if not buttons or InCombatLockdown() then return end
if P.RecoverLegacyPetActions and not P.RecoverLegacyPetActions() then return end
local active = not RuenUIDB.disabled and enabled()
if not active then
for i, button in ipairs(buttons) do releaseAction(i);button:Hide() end
return
end
local choices = P.PetExtraChoices()
local learned=learnedItems()
local selected,used={},{}
nativeItems={}
for _,item in ipairs(learned) do
for i=1,10 do
local name,_,token,_,_,_,id=GetPetActionInfo(i)
if name then name=token and _G[name] or name end
if id==item.id or name==item.name then nativeItems[i]=item end
end
for i,saved in pairs(RuenUICharacter.petExtraAssignments or {}) do
if saved.id==item.id or (not item.command and saved.name==item.name) then
selected[i]=item;used[item.id]=true
end
end
end
local nextChoice=1
for i=1,2 do
if not selected[i] then
while choices[nextChoice] and used[choices[nextChoice].id] do nextChoice=nextChoice+1 end
selected[i]=choices[nextChoice]
if selected[i] then used[selected[i].id]=true;nextChoice=nextChoice+1 end
end
end
local size, gap = P.PetExtraGeometry()
local ratio = UIParent:GetEffectiveScale() / PetActionBar:GetEffectiveScale()
local previous = PetActionButton10
local status = {nativeSlots = 10, visibleSlots = 12, abilities = {}, spellBook = {}, actions={}}
for slot=13,36 do status.actions[slot]=snapshot(slot) end
for slot = 1, C_SpellBook.HasPetSpells() or 0 do
status.spellBook[slot] = C_SpellBook.GetSpellBookItemInfo(slot, bank)
end
for i, button in ipairs(buttons) do
local item = selected[i]
local actionSlot,reason=syncAction(i,item)
button.item = item
button.actionSlot=actionSlot
button.activationError=reason
button:SetScript("OnUpdate",item and updateVisuals or nil)
button:SetSize(size * ratio, size * ratio)
button:ClearAllPoints()
button:SetPoint("LEFT", previous, "RIGHT", gap * ratio, 0)
previous = button
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
button:SetAttribute("macrotext1", nil)
button:SetAttribute("macrotext2", nil)
button.icon:SetTexture(item and item.icon or nil)
button:Show() -- Parent is the native pet bar: native pet/vehicle visibility still applies.
visuals(button)
if item then status.abilities[i] = {spellID = item.id, name = item.name,
actionID=item.actionID,actionSlot=actionSlot,error=reason} end
end
if RuenUICharacter then RuenUICharacter.petExtraStatus = status end
hotkeys()
end
local function receive(button)
if InCombatLockdown() or (C_CVar.GetCVar("lockActionBars")=="1" and not IsModifiedClick("PICKUPACTION")) then return end
local kind,id,book,spellID=GetCursorInfo()
if kind~="petaction" and kind~="spell" then return end
local selected
for _,item in ipairs(learnedItems()) do
if (kind=="petaction" and (id==item.actionID or id==item.id
or (cursorItem and cursorItem.id==item.id)))
or (kind=="spell" and (spellID==item.id
or ((book==bank or book=="pet") and id==item.slot))) then
selected=item;break
end
end
if not selected then return end -- player spells/items never become pet actions
RuenUICharacter.petExtraAssignments=RuenUICharacter.petExtraAssignments or {}
local assignments=RuenUICharacter.petExtraAssignments
local previous=assignments[button.extraIndex]
for i,saved in pairs(assignments) do
if i~=button.extraIndex and saved.id==selected.id then assignments[i]=previous end
end
assignments[button.extraIndex]={id=selected.id,name=selected.name}
local actions=RuenUICharacter.petExtraActions
if actions and actions[button.extraIndex] and actions[button.extraIndex].failed then
-- Preserve the failure receipt, and leave its engine slot untouched.
RuenUICharacter.petExtraLastFailure=actions[button.extraIndex]
actions[button.extraIndex]=nil
end
ClearCursor();cursorItem=nil
P.RefreshPetExtras()
end
function P.ResetPetExtras()
if InCombatLockdown() then return false end
RuenUICharacter.petExtraAssignments=nil
for i,record in pairs(RuenUICharacter.petExtraActions or {}) do
if record.failed then
RuenUICharacter.petExtraLastFailure=record
RuenUICharacter.petExtraActions[i]=nil
end
end
P.RefreshPetExtras()
return true
end
local function queue()
if queued then return end
queued = true
C_Timer.After(.1, function()
queued = false
if InCombatLockdown() then listener:RegisterEvent("PLAYER_REGEN_ENABLED"); return end
listener:UnregisterEvent("PLAYER_REGEN_ENABLED")
P.RefreshPetExtras()
end)
end
function P.InitializePetExtras(isEnabled)
enabled = isEnabled
if buttons or not bank or not PetActionButton10 or not C_SpellBook then return end
if InCombatLockdown() then return end
buttons = {}
for i = 11, 12 do
local button = CreateFrame("CheckButton", "RuenPetExtraButton" .. i, PetActionBar, "SecureActionButtonTemplate")
-- ResizeLayoutMixin otherwise counts these children in the native ten
-- slots' width, then our twelve-slot centering counts them a second time.
button.ignoreInLayout=true
button.extraIndex=i-10
_G["BINDING_NAME_CLICK RuenPetExtraButton" .. i .. ":LeftButton"] = P.Localized("Pet: extra ability ", "Питомец: дополнительная способность ") .. (i - 10)
button:RegisterForClicks("AnyDown", "AnyUp")
-- Same release-only autocast path as native ordinary pet-action buttons.
-- Casting remains in SecureActionButtonTemplate's original OnClick.
button:SetScript("PostClick",function(self,mouseButton,down)
if mouseButton=="RightButton" and not down and self.actionSlot and C_ActionBar
and C_ActionBar.IsAutoCastPetAction(self.actionSlot) then
C_ActionBar.ToggleAutoCastPetAction(self.actionSlot)
end
if not down then visuals(self) end
end)
button.icon = button:CreateTexture(nil, "BACKGROUND")
button.icon:SetAllPoints()
button.cooldown = CreateFrame("Cooldown", nil, button, "CooldownFrameTemplate")
button.cooldown:SetAllPoints()
button.AutoCastOverlay = CreateFrame("Frame", nil, button, "AutoCastOverlayTemplate")
button.AutoCastOverlay:SetPoint("TOPLEFT", 1, -1)
button.AutoCastOverlay:SetPoint("BOTTOMRIGHT", -1, 1)
button.HotKey = button:CreateFontString(nil, "OVERLAY", "NumberFontNormalSmall")
button.HotKey:SetPoint("TOPRIGHT", -1, -2)
button.HotKey:SetTextColor(.8, .8, .8)
button:SetScript("OnEnter", function(self)
GameTooltip_SetDefaultAnchor(GameTooltip, self)
if self.item and not self.item.command then GameTooltip:SetSpellByID(self.item.id)
else
GameTooltip:SetText(self.item and self.item.name or P.Localized("Extra pet ability", "Дополнительная способность питомца"))
end
GameTooltip:AddLine(P.Localized("Drag a learned pet ability or command here while unlocked. /ruen pet auto restores automatic overflow.",
"Перетащите способность или команду питомца при снятой блокировке. /ruen pet auto — автоматический выбор."),1,1,1,true)
if self.activationError then
GameTooltip:AddLine(P.Localized("Not ready: ","Не готово: ")..self.activationError,1,.3,.3,true)
end
GameTooltip:Show()
end)
button:SetScript("OnLeave", function(self) if GameTooltip:GetOwner() == self then GameTooltip:Hide() end end)
-- Copying back to the native bar is safe and follows its lock setting.
-- The extras then automatically expose whichever abilities are missing.
button:RegisterForDrag("LeftButton")
button:SetScript("OnReceiveDrag",receive)
button:SetScript("OnDragStart", function(self)
if not InCombatLockdown() and self.item and
(C_CVar.GetCVar("lockActionBars") ~= "1" or IsModifiedClick("PICKUPACTION")) then
C_SpellBook.PickupSpellBookItem(self.item.slot, bank)
end
end)
buttons[#buttons + 1] = button
end
listener = CreateFrame("Frame")
for _, event in ipairs({"UNIT_PET", "PET_BAR_UPDATE", "PET_UI_UPDATE", "SPELLS_CHANGED", "SPELL_TEXT_UPDATE", "PLAYER_ENTERING_WORLD", "ACTIONBAR_SLOT_CHANGED", "ACTIONBAR_PAGE_CHANGED"}) do
listener:RegisterEvent(event)
end
listener:RegisterEvent("UPDATE_BINDINGS")
listener:RegisterEvent("CURSOR_CHANGED")
listener:SetScript("OnEvent", function(_, event, unit)
if event == "UPDATE_BINDINGS" then hotkeys(); return end
if event == "CURSOR_CHANGED" then
if not GetCursorInfo() then cursorItem=nil;queue() end
return
end
if event=="ACTIONBAR_SLOT_CHANGED" and unit and unit~=0 and (unit<13 or unit>24) then return end
if event == "UNIT_PET" and unit ~= "player" then return end
queue()
end)
-- Cursor payloads differ between native pet-slot and spellbook dragging.
-- Remember the source without replacing either native drag handler.
hooksecurefunc(C_SpellBook,"PickupSpellBookItem",function(slot,spellBank)
if spellBank~=bank or InCombatLockdown() then return end
for _,item in ipairs(learnedItems()) do if item.slot==slot then cursorItem=item;break end end
end)
if PickupPetAction then hooksecurefunc("PickupPetAction",function(index)
if not InCombatLockdown() then cursorItem=nativeItems[index] end
end) end
PetActionBar:HookScript("OnShow", queue)
PetActionBar:HookScript("OnSizeChanged", queue)
EditModeManagerFrame:HookScript("OnShow", queue)
EditModeManagerFrame:HookScript("OnHide", queue)
P.RefreshPetExtras()
end