From 5962ccc83dc0d90137f51577cc4991770de705dc Mon Sep 17 00:00:00 2001 From: Brues <5278969+brues-code@users.noreply.github.com> Date: Sun, 18 Oct 2026 05:08:57 -0500 Subject: [PATCH] fix(frame): follow 4.3.4's attribute system and unit-frame mouseover Compared against 4.3.4's CSimpleFrame attribute code and CGWorldFrame::OnLayerUpdate: - OnAttributeChanged gets (self, name, value) as real arguments, like 4.3.4's RunOnAttributeChangedScript, plus the this/arg1/arg2 globals. It used to fire through the no-argument invoker with globals only, so a modern function(self, name, value) saw name == nil. The engine's runners only carry %d/%s values, so Frame::ScriptArgs gains RunWithValues for arguments already on the Lua stack. - No recursion guard: a handler that sets attributes fires their handlers too, as in 4.3.4. The guard silenced every nested OnAttributeChanged on every frame. - SetAttribute requires the value argument; the 3-arg GetAttribute form needs exactly four arguments and treats a nil prefix/suffix as empty; usage errors name the frame like the engine's (GetName ?: ). - The mouseover unit of a hovered frame comes from FrameXML's SecureButton_GetModifiedUnit, pcalled under the engine's error handler, as 4.3.4 does, so unitsuffix and modifier-qualified unit attributes count. 4.3.4 asks protected frames; with no protection in 1.12 the analog is a frame that has attributes. The mouseover tooltip stays (4.3.4 shows it only over the world frame). - SecureStateDriver.lua is 4.3.4's file again: it drives itself through SecureStateDriverManager attributes and reads OnUpdate's elapsed, both of which the guard and the old no-argument handlers had ruled out. - Game::Lua::ObjectLuaRef / PushObject / ObjectDisplayName replace the copies in ScriptArgs and Modern. Verified in-game: handler arguments and globals, a nested handler firing, both usage errors, the nil-prefix lookup, mouseover following shift-unit / unit, and a visibility state driver. --- .../!!!ClassicAPI/Util/SecureStateDriver.lua | 367 +++++++++--------- src/Game.cpp | 21 + src/Game.h | 11 + src/frame/Attributes.cpp | 211 +++++----- src/frame/Modern.cpp | 13 +- src/frame/ScriptArgs.cpp | 106 +++-- src/frame/ScriptArgs.h | 27 ++ 7 files changed, 429 insertions(+), 327 deletions(-) create mode 100644 src/frame/ScriptArgs.h diff --git a/AddOns/!!!ClassicAPI/Util/SecureStateDriver.lua b/AddOns/!!!ClassicAPI/Util/SecureStateDriver.lua index 0cdbf36a..eff0a48a 100644 --- a/AddOns/!!!ClassicAPI/Util/SecureStateDriver.lua +++ b/AddOns/!!!ClassicAPI/Util/SecureStateDriver.lua @@ -1,222 +1,219 @@ --- SecureStateDriver: automatic frame state / visibility from macro conditionals. -- --- Backports FrameXML's SecureStateDriverManager. A registered driver re-runs --- SecureCmdOptionParse (Util/MacroOptions.lua) on a 0.2s poll (plus an instant --- rescan on the events below) and applies the result: --- * RegisterStateDriver(frame, "visibility", "[combat] hide; show") -> the --- value "show"/"hide" drives frame:Show()/Hide(); --- * RegisterStateDriver / RegisterAttributeDriver for any other state -> --- frame:SetAttribute("state-"..state, value), so an OnAttributeChanged --- handler reacts to it; --- * RegisterUnitWatch(frame [, asState]) -> shows/hides (or sets --- "state-unitexists") as the frame's `unit` attribute comes and goes. +-- SecureStateDriverManager +-- Automatically sets states based on macro options for state driver frames +-- Also handled showing/hiding frames based on unit existence (code originally by Tem) -- --- Base: 3.3.5 FrameXML/SecureStateDriver.lua, with the anniversary refinements --- grafted in (the resolveDriver() consolidation, tonumber() coercion of driver --- values, the literal string 'nil' -> nil, and the "statehidden" attribute). +-- 4.3.4 FrameXML/SecureStateDriver.lua, with three changes this client needs: +-- * Each handler falls back to the vanilla globals (`this`, `arg1`, `arg2`) +-- when called without arguments, so it keeps working while modern script +-- arguments are switched off (SetModernScriptArgs(false)). +-- * `string.match` instead of `strmatch`, which this client does not define. +-- * Events this client does not define (UPDATE_STEALTH, ...) are skipped +-- instead of registered, and UPDATE_SHAPESHIFT_FORMS (the 1.12 name) is +-- registered alongside UPDATE_SHAPESHIFT_FORM. +-- SecureCmdOptionParse is Util/MacroOptions.lua; SecureButton_GetUnit is +-- SecureTemplates.lua (loaded earlier). + +-- Register a frame attribute to be set automatically with changes in game state +function RegisterAttributeDriver(frame, attribute, values) + if ( attribute and values and attribute:sub(1, 1) ~= "_" ) then + SecureStateDriverManager:SetAttribute("setframe", frame); + SecureStateDriverManager:SetAttribute("setstate", attribute.." "..values); + end +end + +-- Unregister a frame from the state driver manager. +function UnregisterAttributeDriver(frame, attribute) + if ( attribute ) then + SecureStateDriverManager:SetAttribute("setframe", frame); + SecureStateDriverManager:SetAttribute("setstate", attribute); + else + SecureStateDriverManager:SetAttribute("delframe", frame); + end +end + +-- Bridge functions for compatibility +function RegisterStateDriver(frame, state, values) + return RegisterAttributeDriver(frame, "state-"..state, values); +end + +function UnregisterStateDriver(frame, state) + return UnregisterAttributeDriver(frame, "state-"..state); +end + +-- Register a frame to be notified when a unit's existence changes, the +-- unit is obtained from the frame's attributes. If asState is true then +-- notification is via the 'state-unitexists' attribute with values +-- true and false. Otherwise it's via :Show() and :Hide() +function RegisterUnitWatch(frame, asState) + if ( asState ) then + SecureStateDriverManager:SetAttribute("addwatchstate", frame); + else + SecureStateDriverManager:SetAttribute("addwatch", frame); + end +end + +-- Unregister a frame from the unit existence monitor. +function UnregisterUnitWatch(frame) + SecureStateDriverManager:SetAttribute("removewatch", frame); +end + -- --- Three deliberate deviations from upstream, all because 1.12 has no taint and --- our attribute system fires OnAttributeChanged SYNCHRONOUSLY: --- 1. No attribute-bootstrap manager. Upstream drives itself through --- SecureStateDriverManager:SetAttribute("setframe"/"setstate"/...) -- a --- taint-boundary trick. Our SetAttribute has a recursion guard (a nested --- SetAttribute stores the value but does NOT fire the handler, see --- src/frame/Attributes.cpp), so doing the registration-time resolve from --- inside that handler would silently swallow the target frame's own --- OnAttributeChanged. Instead the public Register* functions write plain --- local tables and resolve immediately at top level. Public signatures are --- unchanged from retail. --- 2. GetTime()-deadline throttle instead of the OnUpdate `elapsed` arg (1.12 --- handlers take no parameters). --- 3. UpdateUnitWatch guards its "statehidden"/"state-unitexists" writes on a --- real change, so a watched frame's handler is not fired at 5 Hz. - --- --------------------------------------------------------------------------- --- SecureButton_* (minimal -- no taint, no modifier/button suffix machinery) --- --------------------------------------------------------------------------- - --- SecureButton_GetAttribute and SecureButton_GetUnit are defined in --- SecureTemplates.lua (loaded earlier via SecureTemplates.xml). - --- --------------------------------------------------------------------------- --- Private state --- --------------------------------------------------------------------------- - -local secureAttributeDrivers = {}; -- [frame][attribute] = optionsString -local unitExistsWatchers = {}; -- [frame] = doState (boolean) -local unitExistsCache = setmetatable({}, { - __index = function(t, k) - local v = (UnitExists(k) and true) or false; - t[k] = v; - return v; - end, -}); - +-- Private implementation +-- +local secureAttributeDrivers = {}; +local unitExistsWatchers = {}; +local unitExistsCache = setmetatable({}, + { __index = function(t,k) + local v = UnitExists(k) or false; + t[k] = v; + return v; + end + }); local STATE_DRIVER_UPDATE_THROTTLE = 0.2; -local nextUpdate = 0; +local timer = 0; + +local wipe = table.wipe; + +-- Check to see if a frame is registered +function UnitWatchRegistered(frame) + return not (unitExistsWatchers[frame] == nil); +end + +local function SecureStateDriverManager_UpdateUnitWatch(frame, doState) + local unit = SecureButton_GetUnit(frame); + local exists = (unit and unitExistsCache[unit]); + if ( doState ) then + local attr = exists or false; + if ( frame:GetAttribute("state-unitexists") ~= attr ) then + frame:SetAttribute("state-unitexists", attr); + end + else + if ( exists ) then + frame:Show(); + frame:SetAttribute("statehidden", nil); + else + frame:Hide(); + frame:SetAttribute("statehidden", true); + end + end +end local pairs = pairs; -function UnitWatchRegistered(frame) - return unitExistsWatchers[frame] ~= nil; -end - --- --------------------------------------------------------------------------- --- Resolvers --- --------------------------------------------------------------------------- - -local function UpdateUnitWatch(frame, doState) - local unit = SecureButton_GetUnit(frame); - local exists = (unit and unitExistsCache[unit]) or false; - if doState then - if frame:GetAttribute("state-unitexists") ~= exists then - frame:SetAttribute("state-unitexists", exists); - end - else - if exists then - frame:Show(); - else - frame:Hide(); - end - local hidden = (not exists) or nil; - if frame:GetAttribute("statehidden") ~= hidden then - frame:SetAttribute("statehidden", hidden); - end - end -end - +-- consolidate duplicated code for footprint and maintainability local function resolveDriver(frame, attribute, values) - local newValue = SecureCmdOptionParse(values); + local newValue = SecureCmdOptionParse(values); - if attribute == "state-visibility" then - if newValue == "show" then - frame:Show(); - if frame:GetAttribute("statehidden") ~= nil then - frame:SetAttribute("statehidden", nil); - end - elseif newValue == "hide" then - frame:Hide(); - if frame:GetAttribute("statehidden") ~= true then - frame:SetAttribute("statehidden", true); + if ( attribute == "state-visibility" ) then + if ( newValue == "show" ) then + frame:Show(); + frame:SetAttribute("statehidden", nil); + elseif ( newValue == "hide" ) then + frame:Hide(); + frame:SetAttribute("statehidden", true); + end + elseif ( newValue ) then + if ( newValue == 'nil' ) then + newValue = nil; + else + newValue = tonumber(newValue) or newValue; + end + local oldValue = frame:GetAttribute(attribute); + if ( newValue ~= oldValue ) then + frame:SetAttribute(attribute, newValue); + end + end +end + +local function SecureStateDriverManager_OnUpdate(self,elapsed) + elapsed = elapsed or arg1; + timer = timer - elapsed; + if ( timer <= 0 ) then + timer = STATE_DRIVER_UPDATE_THROTTLE; + + -- Handle state driver updates + for frame,drivers in pairs(secureAttributeDrivers) do + for attribute,values in pairs(drivers) do + resolveDriver(frame, attribute, values); end end - elseif newValue then - if newValue == "nil" then - newValue = nil; - else - newValue = tonumber(newValue) or newValue; + + -- Handle unit existence changes + wipe(unitExistsCache); + for k in pairs(unitExistsCache) do + unitExistsCache[k] = nil; end - if frame:GetAttribute(attribute) ~= newValue then - frame:SetAttribute(attribute, newValue); + for frame,doState in pairs(unitExistsWatchers) do + SecureStateDriverManager_UpdateUnitWatch(frame, doState); end end end --- --------------------------------------------------------------------------- --- Manager frame --- --------------------------------------------------------------------------- +local function SecureStateDriverManager_OnEvent(self, event) + timer = 0; +end -SecureStateDriverManager = CreateFrame("Frame", "SecureStateDriverManager"); -SecureStateDriverManager:Hide(); -- hidden -> no OnUpdate until a driver exists - -SecureStateDriverManager:SetScript("OnUpdate", function() - local now = GetTime(); - if now < nextUpdate then +local function SecureStateDriverManager_OnAttributeChanged(self, name, value) + if ( not self ) then + self, name, value = this, arg1, arg2; + end + if ( not value ) then return; end - nextUpdate = now + STATE_DRIVER_UPDATE_THROTTLE; - - for frame, drivers in pairs(secureAttributeDrivers) do - for attribute, values in pairs(drivers) do + if ( name == "setframe" ) then + if ( not secureAttributeDrivers[value] ) then + secureAttributeDrivers[value] = {}; + end + SecureStateDriverManager:Show(); + elseif ( name == "delframe" ) then + secureAttributeDrivers[value] = nil; + elseif ( name == "setstate" ) then + local frame = self:GetAttribute("setframe"); + local attribute, values = string.match(value, "^(%S+)%s*(.*)$"); + if ( values == "" ) then + secureAttributeDrivers[frame][attribute] = nil; + else + secureAttributeDrivers[frame][attribute] = values; resolveDriver(frame, attribute, values); end + elseif ( name == "addwatch" or name == "addwatchstate" ) then + local doState = (name == "addwatchstate"); + unitExistsWatchers[value] = doState; + SecureStateDriverManager:Show(); + SecureStateDriverManager_UpdateUnitWatch(value, doState); + elseif ( name == "removewatch" ) then + unitExistsWatchers[value] = nil; + elseif ( name == "updatetime" ) then + STATE_DRIVER_UPDATE_THROTTLE = value; end +end - for k in pairs(unitExistsCache) do - unitExistsCache[k] = nil; - end - for frame, doState in pairs(unitExistsWatchers) do - UpdateUnitWatch(frame, doState); - end -end); +SecureStateDriverManager = CreateFrame("Frame", "SecureStateDriverManager", nil, "SecureFrameTemplate"); +SecureStateDriverManager:Hide(); +SecureStateDriverManager:SetScript("OnUpdate", SecureStateDriverManager_OnUpdate); +SecureStateDriverManager:SetScript("OnEvent", SecureStateDriverManager_OnEvent); +SecureStateDriverManager:SetScript("OnAttributeChanged", SecureStateDriverManager_OnAttributeChanged); -SecureStateDriverManager:SetScript("OnEvent", function() - nextUpdate = 0; -- force a rescan on the next frame -end); - -SecureStateDriverManager:SetScript("OnAttributeChanged", function() - if arg1 == "updatetime" and tonumber(arg2) then - STATE_DRIVER_UPDATE_THROTTLE = tonumber(arg2); - end -end); - --- Events that warrant an early rescan. Each is guarded so a name this client --- doesn't define (e.g. UPDATE_STEALTH) is simply skipped. -local rescanEvents = { - "MODIFIER_STATE_CHANGED", -- ClassicAPI-fired - "PLAYER_FOCUS_CHANGED", -- ClassicAPI-fired - "UPDATE_SHAPESHIFT_FORM", -- ClassicAPI-fired (singular) - "UPDATE_SHAPESHIFT_FORMS", -- native 1.12 (plural) +-- Events that trigger early rescans +for _, event in ipairs({ + "MODIFIER_STATE_CHANGED", "ACTIONBAR_PAGE_CHANGED", "UPDATE_BONUS_ACTIONBAR", "PLAYER_ENTERING_WORLD", + "UPDATE_SHAPESHIFT_FORM", + "UPDATE_SHAPESHIFT_FORMS", "UPDATE_STEALTH", "PLAYER_TARGET_CHANGED", + "PLAYER_FOCUS_CHANGED", "PLAYER_REGEN_DISABLED", "PLAYER_REGEN_ENABLED", "UNIT_PET", "RAID_ROSTER_UPDATE", "PARTY_MEMBERS_CHANGED", -}; -for _, event in ipairs(rescanEvents) do - if C_EventUtils.IsEventValid(event) then +}) do + if ( C_EventUtils.IsEventValid(event) ) then SecureStateDriverManager:RegisterEvent(event); end end - --- --------------------------------------------------------------------------- --- Public API --- --------------------------------------------------------------------------- - -function RegisterAttributeDriver(frame, attribute, values) - if attribute and values and string.sub(attribute, 1, 1) ~= "_" then - local drivers = secureAttributeDrivers[frame]; - if not drivers then - drivers = {}; - secureAttributeDrivers[frame] = drivers; - end - drivers[attribute] = values; - SecureStateDriverManager:Show(); - resolveDriver(frame, attribute, values); - end -end - -function UnregisterAttributeDriver(frame, attribute) - if attribute then - local drivers = secureAttributeDrivers[frame]; - if drivers then - drivers[attribute] = nil; - end - else - secureAttributeDrivers[frame] = nil; - end -end - -function RegisterStateDriver(frame, state, values) - RegisterAttributeDriver(frame, "state-" .. state, values); -end - -function UnregisterStateDriver(frame, state) - UnregisterAttributeDriver(frame, state and ("state-" .. state)); -end - -function RegisterUnitWatch(frame, asState) - local doState = (asState and true) or false; - unitExistsWatchers[frame] = doState; - SecureStateDriverManager:Show(); - UpdateUnitWatch(frame, doState); -end - -function UnregisterUnitWatch(frame) - unitExistsWatchers[frame] = nil; -end +-- Deliberately ignoring mouseover and others' target changes because they change so much diff --git a/src/Game.cpp b/src/Game.cpp index e14d70e0..48507787 100644 --- a/src/Game.cpp +++ b/src/Game.cpp @@ -118,6 +118,27 @@ void *ResolveObject(void *L, int idx) { return result; } +int ObjectLuaRef(void *object) { + using ScriptRegister_t = void(__thiscall *)(void *object, void *nameOrNull); + if (Game::Read(object, Offsets::OFF_COBJECT_LUA_REFCOUNT) == 0) + reinterpret_cast( + Offsets::FUN_FRAMESCRIPT_OBJECT_SCRIPT_REGISTER)(object, nullptr); + return Game::Read(object, Offsets::OFF_COBJECT_LUA_REF); +} + +void PushObject(void *L, void *object) { + RawGetI(L, REGISTRY_INDEX, ObjectLuaRef(object)); +} + +const char *ObjectDisplayName(void *object) { + using GetName_t = const char *(__thiscall *)(void *); + const void *vtable = Game::Read(object, 0); + const char *name = Game::Read( + vtable, Offsets::VTBL_SCRIPTOBJECT_GET_NAME)(object); + return name != nullptr ? name + : reinterpret_cast(Offsets::VAR_STR_UNNAMED); +} + namespace { using FrameScriptIsA_t = char(__thiscall *)(void *self, int typeId); diff --git a/src/Game.h b/src/Game.h index 9000ba9c..96d66e4e 100644 --- a/src/Game.h +++ b/src/Game.h @@ -341,6 +341,17 @@ void *State(); // the `self` slot of any `frame:method(...)` invocation. void *ResolveObject(void *L, int idx); +// The inverse: the object's Lua-registry ref, created on first use exactly as +// the engine does it (GetMouseFocus and the script runners register an +// object with FUN_FRAMESCRIPT_OBJECT_SCRIPT_REGISTER when its refcount is 0). +int ObjectLuaRef(void *object); +// Pushes the object's Lua table (registry[ObjectLuaRef(object)]). +void PushObject(void *L, void *object); + +// How the engine names an object in its frame-script usage errors: +// `GetName() ?: ""` (VTBL_SCRIPTOBJECT_GET_NAME). +const char *ObjectDisplayName(void *object); + // Same resolve, then the type gate every engine frame method applies to its // `self` before touching it: `lua_type == table`, resolve to the object, then // the `IsA(typeId)` vmethod at vtable+0x10. `ResolveObject` alone is not diff --git a/src/frame/Attributes.cpp b/src/frame/Attributes.cpp index 24da4b79..6e380f18 100644 --- a/src/frame/Attributes.cpp +++ b/src/frame/Attributes.cpp @@ -34,12 +34,15 @@ // Installing OnEnter/OnLeave would be clobbered by an addon's own // `SetScript("OnEnter", …)` (pfUI sets `unit` before its scripts), and there's // nothing to read from Lua anyway — the mouseover unit is an engine global. So -// we mirror retail / SuperWoW's `SetMouseoverUnit`: watch the engine's -// mouse-focus frame (`*(*VAR_UI_CONTEXT_PTR + OFF_UI_CONTEXT_MOUSE_FOCUS)`, the -// CFrameScriptObject* `GetMouseFocus` returns) once per frame on the shared -// WorldTick, and when it's a `unit`-attributed frame call the engine's FULL -// mouseover setter (FUN_00492890) — 1:1 with hovering the unit's 3D model: -// model highlight, mouseover tooltip, UPDATE_MOUSEOVER_UNIT, and the GUID slot. +// we mirror 4.3.4's CGWorldFrame::OnLayerUpdate: once per frame (the shared +// WorldTick) read the engine's mouse-focus frame +// (`*(*VAR_UI_CONTEXT_PTR + OFF_UI_CONTEXT_MOUSE_FOCUS)`, the +// CFrameScriptObject* `GetMouseFocus` returns), ask FrameXML's +// `SecureButton_GetModifiedUnit` for its unit (see ModifiedUnit), and hand +// that to the engine's FULL mouseover setter (FUN_00492890) — 1:1 with +// hovering the unit's 3D model: model highlight, UPDATE_MOUSEOVER_UNIT, the +// GUID slot, and the mouseover tooltip. The tooltip is a deliberate +// difference: 4.3.4 shows it only when the world frame has the focus. // Stomp-proof: the engine's own 3D-hover setter is event-driven, so nothing // overwrites the slot while the cursor is over UI. // @@ -98,12 +101,13 @@ // `RegisterForClicks("RightButtonUp")`, which real unit frames do. // // `OnAttributeChanged` is a real SetScript-able handler: SetAttribute (not -// SetAttributeNoHandler) fires it with `this` = frame, `arg1` = name, `arg2` = -// value. Implemented by co-hooking the base-frame script-name resolver +// SetAttributeNoHandler) fires it as `(self, name, value)` with the vanilla +// `this` / `arg1` / `arg2` globals set too (see FireAttributeChanged). Implemented by co-hooking the base-frame script-name resolver // (`FUN_FRAME_SCRIPT_RESOLVER`) and handing out an external per-frame cell for // that name — the `Tooltip::SetEvents` analog, applied to every frame. #include "frame/Attributes.h" +#include "frame/ScriptArgs.h" #include "Common.h" #include "Game.h" @@ -125,6 +129,7 @@ #include #include #include +#include namespace Frame::Attributes { @@ -314,10 +319,10 @@ bool CallTableFunc2Str(void *L, const char *table, const char *method, // ---- mouse-focus poll (drives the native mouseover slot) ------------------- -// frame CFrameScriptObject* → current `unit` token, for the mouse-focus poll. -// Keyed by the same pointer the engine stores at the mouse-focus slot. Single- -// threaded (Lua + WorldTick on the main thread), so no synchronization needed. -std::unordered_map g_unitByFrame; +// Frames whose mouse we enabled when their `unit` attribute was first set +// (a bare frame never becomes the mouse focus otherwise). Keyed by the C +// object. Single-threaded (Lua + WorldTick on the main thread). +std::unordered_set g_unitFrames; // The last GUID *we* wrote into the mouseover slot. We only touch the slot on a // change of our own value, so when the cursor isn't over a unit frame (guid 0) @@ -387,16 +392,51 @@ void BuildRosterUnitTooltip(uint64_t guid) { static_cast(Offsets::FUN_GAMETOOLTIP_BUILD_UNIT))(tooltip, packed); } +// The unit a hovered frame stands for — 4.3.4's CGWorldFrame::OnLayerUpdate: +// for the mouse-focus frame it pcalls the FrameXML function +// `SecureButton_GetModifiedUnit(frame, macroRunning)` under the engine's +// script error handler and uses the token it returns, so `unitsuffix` and +// modifier-qualified `unit` attributes count. 4.3.4 asks protected frames; +// 1.12 has no protection, so the analog is a frame that has attributes at +// all. macroRunning is nil while hovering (no macro is executing), so the +// call passes the frame alone. Returns "" for no unit. +std::string ModifiedUnit(void *L, void *frame) { + std::string token; + const int top = Game::Lua::GetTop(L); + Game::Lua::PushObject(L, frame); // [frame] + const int fi = Game::Lua::GetTop(L); + if (PushSub(L, fi, /*create*/ false)) { // [frame, attrs] + Game::Lua::SetTop(L, fi); + int errIdx = 0; + const int errRef = Game::Read( + static_cast(Offsets::VAR_FRAMESCRIPT_ERROR_HANDLER_REF)); + if (errRef > 0) { + Game::Lua::RawGetI(L, Game::Lua::REGISTRY_INDEX, errRef); + errIdx = Game::Lua::GetTop(L); + } + Game::Lua::PushString(L, "SecureButton_GetModifiedUnit"); + Game::Lua::RawGet(L, Game::Lua::GLOBALS_INDEX); + if (Game::Lua::Type(L, -1) == Game::Lua::TYPE_FUNCTION) { + Game::Lua::PushValue(L, fi); + if (Game::Lua::PCall(L, 1, 1, errIdx) == 0 && + Game::Lua::Type(L, -1) == Game::Lua::TYPE_STRING) + token = Game::Lua::ToString(L, -1); + } + } + Game::Lua::SetTop(L, top); + return token; +} + void MouseoverTick() { - const void *focus = CurrentMouseFocus(); + void *focus = const_cast(CurrentMouseFocus()); uint64_t guid = 0; - std::string token; // a copy: handlers run below may rewrite the map + std::string token; if (focus != nullptr) { - auto it = g_unitByFrame.find(focus); - if (it != g_unitByFrame.end()) { - token = it->second; - guid = Unit::Identity::GuidForToken(token.c_str()); // live — follows target changes + if (void *L = Game::Lua::State()) { + token = ModifiedUnit(L, focus); + if (!token.empty()) + guid = Unit::Identity::GuidForToken(token.c_str()); // live — follows target changes } } @@ -894,60 +934,31 @@ const Game::HookAutoRegister _attrResolverHook{ reinterpret_cast(&FrameResolver_h), reinterpret_cast(&g_frameResolverOriginal)}; -// Fire OnAttributeChanged on `frame`, with arg1 = name and arg2 = the new value -// (still at stack[3] in DoSet). Recursion-guarded so a handler that itself calls -// SetAttribute doesn't loop. The invoker (FUN_FRAME_INVOKE_SCRIPT) binds `this` -// and runs the handler under its own protected pcall; it doesn't restore the -// stack top, so snapshot/restore around it (as Tooltip::SetEvents does). -int g_firingAttr = 0; - -using InvokeAttrScript_t = void(__fastcall *)(uint32_t handler, void *frame); - +// Fire OnAttributeChanged on `frame` — 4.3.4's +// CSimpleFrame::RunOnAttributeChangedScript: the handler gets the lowercased +// name and the new value (still at stack[3] in DoSet) as real arguments, +// `(self, name, value)`, plus the vanilla `this`/`arg1`/`arg2` globals. +// RunWithValues carries arbitrary Lua values, which the engine's +// printf-style runners cannot, and restores the stack and globals. +// +// No recursion guard, as in 4.3.4: a handler that sets attributes — its own +// or another frame's — fires their handlers too. Secure headers and the +// state driver depend on that. A runaway loop ends at Lua's C-call limit as +// an ordinary, reported script error. void FireAttributeChanged(void *L, void *frame, const char *name) { - if (frame == nullptr || g_firingAttr > 0) + if (frame == nullptr) return; uint32_t *slot = AttrSlotFor(frame, /*create*/ false); if (slot == nullptr || slot[0] == 0) return; - - const int savedTop = Game::Lua::GetTop(L); - - // Snapshot the caller's arg1/arg2 first. SetAttribute can be called from - // inside a running script handler that still needs them, and the invoker - // below neither saves the globals nor restores the stack top — so we save - // (onto the stack, below anything the invoker pushes), overwrite, fire, - // then put them back. 1.12 passes handler args as globals, not params. - Game::Lua::PushString(L, "arg1"); - Game::Lua::GetTable(L, Game::Lua::GLOBALS_INDEX); // [.., oldArg1] - Game::Lua::PushString(L, "arg2"); - Game::Lua::GetTable(L, Game::Lua::GLOBALS_INDEX); // [.., oldArg1, oldArg2] - const int oldArg1 = savedTop + 1; - const int oldArg2 = savedTop + 2; - - Game::Lua::PushString(L, "arg1"); + const int top = Game::Lua::GetTop(L); Game::Lua::PushString(L, name); - Game::Lua::RawSet(L, Game::Lua::GLOBALS_INDEX); // _G.arg1 = name - Game::Lua::PushString(L, "arg2"); - if (savedTop >= 3) - Game::Lua::PushValue(L, 3); // the new value + if (top >= 3) + Game::Lua::PushValue(L, 3); // the new value else Game::Lua::PushNil(L); - Game::Lua::RawSet(L, Game::Lua::GLOBALS_INDEX); // _G.arg2 = value - - ++g_firingAttr; - reinterpret_cast(Offsets::FUN_FRAME_INVOKE_SCRIPT)(slot[0], frame); - --g_firingAttr; - - // Restore arg1/arg2 from the snapshot (the fired handler may also have - // written them; the caller's values win). - Game::Lua::PushString(L, "arg1"); - Game::Lua::PushValue(L, oldArg1); - Game::Lua::RawSet(L, Game::Lua::GLOBALS_INDEX); - Game::Lua::PushString(L, "arg2"); - Game::Lua::PushValue(L, oldArg2); - Game::Lua::RawSet(L, Game::Lua::GLOBALS_INDEX); - - Game::Lua::SetTop(L, savedTop); + Frame::ScriptArgs::RunWithValues(L, static_cast(slot[0]), frame, top + 1, 2); + Game::Lua::SetTop(L, top); } // ---- the methods ----------------------------------------------------------- @@ -979,11 +990,18 @@ void EnableFrameMouse(void *L) { Game::Lua::SetTop(L, top); // restore the caller's stack } -int DoSet(void *L, bool fireHandler) { // (self, name, value) - if (!Game::Lua::IsString(L, 2)) { - Game::Lua::Error(L, "Usage: frame:SetAttribute(\"name\", value)"); +// (self, name, value). `usage` is the method's error text; 4.3.4 requires +// the value argument to be present (`lua_type(L, 3) != LUA_TNONE`), so +// `SetAttribute("x")` is an error while `SetAttribute("x", nil)` clears. +int DoSet(void *L, bool fireHandler, const char *usage) { + void *frame = Game::Lua::ResolveFrame(L); + if (frame == nullptr) + return 0; + if (!Game::Lua::IsString(L, 2) || Game::Lua::GetTop(L) < 3) { + Game::Lua::Error(L, usage, Game::Lua::ObjectDisplayName(frame)); return 0; } + Game::Lua::SetTop(L, 3); char lname[256]; LowerCopy(lname, Game::Lua::ToString(L, 2), sizeof lname); @@ -1001,17 +1019,11 @@ int DoSet(void *L, bool fireHandler) { // (self, name, value) // (the key the mouse-focus poll uses) and enable its mouse so it can be // hovered. if (std::strcmp(lname, "unit") == 0) { - void *obj = Game::Lua::ResolveFrame(L); - if (obj != nullptr) { - if (isString) { - const char *tok = Game::Lua::ToString(L, 3); - const bool isNew = g_unitByFrame.find(obj) == g_unitByFrame.end(); - g_unitByFrame[obj] = tok ? tok : ""; - if (isNew) - EnableFrameMouse(L); - } else { - g_unitByFrame.erase(obj); - } + if (isString) { + if (g_unitFrames.insert(frame).second) + EnableFrameMouse(L); + } else { + g_unitFrames.erase(frame); } } // A `type*` attribute makes the frame a clickable unit button: (re)install @@ -1029,12 +1041,17 @@ int DoSet(void *L, bool fireHandler) { // (self, name, value) } if (fireHandler) - FireAttributeChanged(L, Game::Lua::ResolveFrame(L), lname); + FireAttributeChanged(L, frame, lname); return 0; } -int __fastcall Script_SetAttribute(void *L) { return DoSet(L, /*fireHandler*/ true); } -int __fastcall Script_SetAttributeNoHandler(void *L) { return DoSet(L, /*fireHandler*/ false); } +int __fastcall Script_SetAttribute(void *L) { + return DoSet(L, /*fireHandler*/ true, "Usage: %s:SetAttribute(\"name\", value)"); +} +int __fastcall Script_SetAttributeNoHandler(void *L) { + return DoSet(L, /*fireHandler*/ false, + "Usage: %s:SetAttributeNoHandler(\"name\", value)"); +} // `cleared = frame:ClearAttribute("name")` — retail (11.2.0) attribute removal; // `cleared` is true iff the attribute was set (and is now gone). Routes through @@ -1042,8 +1059,12 @@ int __fastcall Script_SetAttributeNoHandler(void *L) { return DoSet(L, /*fireHan // NOT fire OnAttributeChanged — verified against retail (a live 12.0 test showed // ClearAttribute firing no handler, unlike SetAttribute). int __fastcall Script_ClearAttribute(void *L) { + void *frame = Game::Lua::ResolveFrame(L); + if (frame == nullptr) + return 0; if (!Game::Lua::IsString(L, 2)) { - Game::Lua::Error(L, "Usage: frame:ClearAttribute(\"name\")"); + Game::Lua::Error(L, "Usage: %s:ClearAttribute(\"name\")", + Game::Lua::ObjectDisplayName(frame)); return 0; } char lname[256]; @@ -1055,19 +1076,21 @@ int __fastcall Script_ClearAttribute(void *L) { Game::Lua::SetTop(L, 2); // (self, name) Game::Lua::PushNil(L); // (self, name, nil) → value = nil clears the key - DoSet(L, /*fireHandler*/ false); // retail ClearAttribute fires no OnAttributeChanged + DoSet(L, /*fireHandler*/ false, ""); // retail ClearAttribute fires no OnAttributeChanged Game::Lua::PushBool(L, existed); return 1; } +// 4.3.4's Script_GetAttribute. The 3-arg form `(prefix, name, suffix)` is +// taken only with exactly those three arguments and a string name; a nil +// prefix or suffix counts as empty. Lookup order: prefix..name..suffix, +// "*"..name..suffix, prefix..name.."*", "*"..name.."*", then name. int __fastcall Script_GetAttribute(void *L) { - if (!Game::Lua::IsString(L, 2)) { - Game::Lua::Error(L, "Usage: frame:GetAttribute(\"name\")"); + void *frame = Game::Lua::ResolveFrame(L); + if (frame == nullptr) return 0; - } - // 3-arg form: (prefix, name, suffix) with wildcard precedence. - if (Game::Lua::GetTop(L) >= 4 && Game::Lua::IsString(L, 3)) { + if (Game::Lua::GetTop(L) == 4 && Game::Lua::IsString(L, 3)) { const char *pfx = Game::Lua::IsString(L, 2) ? Game::Lua::ToString(L, 2) : ""; const char *nm = Game::Lua::ToString(L, 3); const char *sfx = Game::Lua::IsString(L, 4) ? Game::Lua::ToString(L, 4) : ""; @@ -1085,6 +1108,11 @@ int __fastcall Script_GetAttribute(void *L) { Game::Lua::PushNil(L); return 1; } + if (!Game::Lua::IsString(L, 2)) { + Game::Lua::Error(L, "Usage: %s:GetAttribute(\"name\")", + Game::Lua::ObjectDisplayName(frame)); + return 0; + } char lname[256]; LowerCopy(lname, Game::Lua::ToString(L, 2), sizeof lname); @@ -1126,12 +1154,11 @@ const Tick::WorldTick::AutoSubscribe _tick{&MouseoverTick}; // session, so there's always at least one entry to go stale). This was the // "SetAttribute occasionally errors after /reload" report; same class of // bug as Tooltip::SetEvents issue #33. -// * g_unitByFrame maps a frame to its `unit` token for the mouse-focus poll; -// a stale entry at a reused address would point the mouseover at the wrong -// unit and mislead the isNew mouse-enable gate. +// * g_unitFrames records which frames already had their mouse enabled; a +// stale entry at a reused address would skip enabling a new frame's. void PrepareForReload() { g_attrHandlers.clear(); - g_unitByFrame.clear(); + g_unitFrames.clear(); } static const Game::ReloadAutoRegister _reloadReg{&PrepareForReload}; diff --git a/src/frame/Modern.cpp b/src/frame/Modern.cpp index 7bff275c..0aaf85c5 100644 --- a/src/frame/Modern.cpp +++ b/src/frame/Modern.cpp @@ -294,17 +294,6 @@ int __fastcall Script_SetResizeBounds(void *L) { // handlers either way. Script lookup, the unknown-script error and storage // stay the engine's own GetScript / SetScript, whose texts match 4.3.4's. -// `GetName() ?: ""` — how the engine names an object in its -// frame-script usage errors (VTBL_SCRIPTOBJECT_GET_NAME). -const char *DisplayName(void *object) { - using GetName_t = const char *(__thiscall *)(void *); - const void *vtable = Game::Read(object, 0); - const char *name = Game::Read( - vtable, Offsets::VTBL_SCRIPTOBJECT_GET_NAME)(object); - return name != nullptr ? name - : reinterpret_cast(Offsets::VAR_STR_UNNAMED); -} - int __fastcall Script_HookScript(void *L) { void *frame = Game::Lua::ResolveFrame(L); if (frame == nullptr) @@ -312,7 +301,7 @@ int __fastcall Script_HookScript(void *L) { if (!Game::Lua::IsString(L, 2) || Game::Lua::Type(L, 3) != Game::Lua::TYPE_FUNCTION) { Game::Lua::Error(L, "Usage: %s:HookScript(\"type\", function)", - DisplayName(frame)); + Game::Lua::ObjectDisplayName(frame)); return 0; } diff --git a/src/frame/ScriptArgs.cpp b/src/frame/ScriptArgs.cpp index dfc0dc6e..929fa659 100644 --- a/src/frame/ScriptArgs.cpp +++ b/src/frame/ScriptArgs.cpp @@ -64,6 +64,8 @@ // valve, since this lands on the hottest Lua path in the engine // (FUN_FRAME_RUN_SCRIPT_ARGS fires for every OnUpdate frame). +#include "frame/ScriptArgs.h" + #include "Game.h" #include "HookSecureFunc.h" #include "Offsets.h" @@ -82,22 +84,8 @@ bool g_enabled = true; // Engine cap: the runner stops setting arg globals at index 19 (arg1..arg19). constexpr int kMaxArgs = 19; -// --- raw engine primitives not exposed via Game::Lua ----------------------- -// FUN_FRAMESCRIPT_OBJECT_SCRIPT_REGISTER — __thiscall(frame, nameOrNull); -// lazily materializes the frame's Lua-registry ref at frame+OFF_COBJECT_LUA_REF. -using ScriptRegister_t = void(__thiscall *)(void *frame, void *nameOrNull); - using Game::Lua::RawGetI; -// Returns the frame's Lua object ref (frame+0x08), lazily creating it exactly -// as the engine runner does (`if (refcount == 0) ScriptRegister(frame, 0)`). -int EnsureLuaRef(void *frame) { - if (Game::Read(frame, Offsets::OFF_COBJECT_LUA_REFCOUNT) == 0) - reinterpret_cast( - Offsets::FUN_FRAMESCRIPT_OBJECT_SCRIPT_REGISTER)(frame, nullptr); - return Game::Read(frame, Offsets::OFF_COBJECT_LUA_REF); -} - // Writes "arg" + k (k in 1..19) into buf; buf must hold at least 6 bytes. void ArgName(char *buf, int k) { buf[0] = 'a'; @@ -117,7 +105,6 @@ void ArgName(char *buf, int k) { // Numbers ('d'/'u'/'f') land in `num`; strings ('s') keep the char* the engine // handed us (stable for the duration of the call). struct Arg { - char name[6]; // "arg1".."arg19" char kind; // 'd' | 'u' | 'f' | 's' double num; const char *str; @@ -161,7 +148,6 @@ int ParseArgs(const char *fmt, const void *vaPtr, Arg *out) { continue; // unknown spec — consume nothing } a.kind = *p; - ArgName(a.name, n + 1); ++n; } return n; @@ -175,6 +161,21 @@ void PushArg(void *L, const Arg &a) { Game::Lua::PushNumber(L, a.num); } +// Where RunCore's arguments come from: the runner's parsed printf-style +// list, or `n` Lua values already on the stack from absolute index +// `stackBase` (they sit below everything RunCore pushes, so the index holds). +struct ArgSource { + const Arg *parsed = nullptr; + int stackBase = 0; + int n = 0; + void Push(void *L, int k) const { + if (parsed != nullptr) + PushArg(L, parsed[k]); + else + Game::Lua::PushValue(L, stackBase + k); + } +}; + // Reimplements the runner tail: set the `this`/`arg1..argN` globals, invoke the // handler with modern positional args `(self, [event,] arg1..argN)` under the // engine's own message-handler errfunc, then restore the globals. `fmt`/`vaPtr` @@ -191,13 +192,14 @@ void PushArg(void *L, const Arg &a) { // Returns false WITHOUT side effects when it declines (no Lua state, or the // stack can't grow); the caller then runs the original. Every false path is // before the first push, so falling back never double-runs the handler. -bool RunModern(int handlerRef, void *frame, const char *fmt, const void *vaPtr) { +// +// `positional` false sets the globals but calls the handler with no +// arguments — the vanilla shape, for RunWithValues while the switch is off. +bool RunCore(void *L, int handlerRef, void *frame, const ArgSource &src, + bool positional) { using namespace Game::Lua; - void *L = State(); - if (L == nullptr) - return false; // Headroom for the saved-old block plus the transient set/call pushes. - if (CheckStack(L, 2 * kMaxArgs + 16) == 0) + if (CheckStack(L, 2 * src.n + 16) == 0) return false; const bool haveThis = frame != nullptr; @@ -208,10 +210,10 @@ bool RunModern(int handlerRef, void *frame, const char *fmt, const void *vaPtr) const bool isOnEvent = haveThis && Game::Read(frame, Offsets::OFF_FRAME_ONEVENT_SLOT) == handlerRef; - const int selfRef = haveThis ? EnsureLuaRef(frame) : 0; + const int selfRef = haveThis ? Game::Lua::ObjectLuaRef(frame) : 0; - Arg args[kMaxArgs]; - const int n = ParseArgs(fmt, vaPtr, args); + const int n = src.n; + char argName[6]; // --- save the globals we're about to clobber, onto the stack ------------ // Absolute indices, live until the closing SetTop(base): @@ -224,7 +226,8 @@ bool RunModern(int handlerRef, void *frame, const char *fmt, const void *vaPtr) } const int savedArgBase = base + (haveThis ? 1 : 0); for (int k = 0; k < n; ++k) { - PushString(L, args[k].name); + ArgName(argName, k + 1); + PushString(L, argName); GetTable(L, GLOBALS_INDEX); // [.. oldArgk] } @@ -235,8 +238,9 @@ bool RunModern(int handlerRef, void *frame, const char *fmt, const void *vaPtr) SetTable(L, GLOBALS_INDEX); } for (int k = 0; k < n; ++k) { - PushString(L, args[k].name); - PushArg(L, args[k]); + ArgName(argName, k + 1); + PushString(L, argName); + src.Push(L, k); SetTable(L, GLOBALS_INDEX); } @@ -250,22 +254,27 @@ bool RunModern(int handlerRef, void *frame, const char *fmt, const void *vaPtr) errIdx = callBase + 1; // absolute index of the errfunc } RawGetI(L, REGISTRY_INDEX, handlerRef); // handler - if (haveThis) - RawGetI(L, REGISTRY_INDEX, selfRef); // self - else - PushNil(L); - if (isOnEvent) { // event goes before the args, retail-style - PushString(L, "event"); - GetTable(L, GLOBALS_INDEX); + int nargs = 0; + if (positional) { + if (haveThis) + RawGetI(L, REGISTRY_INDEX, selfRef); // self + else + PushNil(L); + if (isOnEvent) { // event goes before the args, retail-style + PushString(L, "event"); + GetTable(L, GLOBALS_INDEX); + } + for (int k = 0; k < n; ++k) + src.Push(L, k); + nargs = 1 + (isOnEvent ? 1 : 0) + n; } - for (int k = 0; k < n; ++k) - PushArg(L, args[k]); - PCall(L, 1 + (isOnEvent ? 1 : 0) + n, 0, errIdx); + PCall(L, nargs, 0, errIdx); SetTop(L, callBase); // drop the message handler + any leftover error object // --- restore globals from the saved block, then drop it ----------------- for (int k = 0; k < n; ++k) { - PushString(L, args[k].name); + ArgName(argName, k + 1); + PushString(L, argName); PushValue(L, savedArgBase + 1 + k); SetTable(L, GLOBALS_INDEX); } @@ -278,6 +287,18 @@ bool RunModern(int handlerRef, void *frame, const char *fmt, const void *vaPtr) return true; } +// The runner path: arguments from the engine's printf-style format. +bool RunModern(int handlerRef, void *frame, const char *fmt, const void *vaPtr) { + void *L = Game::Lua::State(); + if (L == nullptr) + return false; + Arg args[kMaxArgs]; + ArgSource src; + src.parsed = args; + src.n = ParseArgs(fmt, vaPtr, args); + return RunCore(L, handlerRef, frame, src, /*positional*/ true); +} + // Lua 5.0 internal offsets for reading a handler's arity — verified against the // engine's own luaD_precall (0x006F6050) / lua_dump (0x006F4370) / // lua_iscfunction (0x006F34A0): @@ -416,4 +437,13 @@ const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; } // namespace +void RunWithValues(void *L, int handlerRef, void *frame, int firstArgIdx, int nargs) { + if (handlerRef == 0 || frame == nullptr) + return; + ArgSource src; + src.stackBase = firstArgIdx; + src.n = nargs; + RunCore(L, handlerRef, frame, src, /*positional*/ g_enabled); +} + } // namespace Frame::ScriptArgs diff --git a/src/frame/ScriptArgs.h b/src/frame/ScriptArgs.h new file mode 100644 index 00000000..a7a3b843 --- /dev/null +++ b/src/frame/ScriptArgs.h @@ -0,0 +1,27 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +#pragma once + +namespace Frame::ScriptArgs { + +// Runs a frame-script handler with arbitrary Lua values as its arguments — +// the engine's runners can only pass %d/%u/%f/%s. `nargs` values at absolute +// stack index `firstArgIdx` become `arg1..argN` (globals, saved and restored +// around the call) and, while modern script args are on, the positional +// `(self, ...)`. Sets `this`, runs under the engine's script error handler, +// and leaves the stack as it found it. For scripts the engine itself never +// fires, such as OnAttributeChanged (4.3.4: RunScript with 2 stack args). +void RunWithValues(void *L, int handlerRef, void *frame, int firstArgIdx, int nargs); + +} // namespace Frame::ScriptArgs