feat(frame): add frame:RegisterUnitEvent, unit-aware IsEventRegistered

Modern ports call frame:RegisterUnitEvent("UNIT_HEALTH", "player") to receive
an event for one unit instead of for every unit. Vanilla has no such method, so
the call errored, and FrameUtil.RegisterFrameForUnitEvents was left out of the
FrameXML backport for the same reason.

The engine already owns registration and dispatch, so this is only a filter.
Chain membership delegates to the engine's own Script_RegisterEvent; the filter
is stored per frame here; the check is one gate on the per-frame OnEvent fire,
where the dispatcher has already set _G.event and calls the arg'd script runner
with the OnEvent slot. Suppressing there also covers HookScript chains and
Frame::ScriptArgs' positional path, both downstream, as retail does.

Semantics follow Blizzard's 5.4.8 implementation, where the filter lives on the
subscriber node and the node's kind is fixed at creation: RegisterEvent over a
filtered registration keeps the filter, RegisterUnitEvent over a plain one stays
plain, RegisterUnitEvent over a filtered one replaces the units, and no usable
unit is a plain RegisterEvent. The filter dies with the node, through co-hooks
on Frame::UnregisterEvent and Frame::UnregisterAllEvents -- the latter also
being the CScriptObject destructor's path, so frame destruction is covered.

Two divergences from 5.4.8, both additive. Unit tokens are kept as strings and
compared case-insensitively, since focus/nameplateN/markN are not in the
engine's canonical token table. And the unit count is not capped: 5.4.8 reads
exactly two units and folds each token index into a byte of one dword, and
retail later filled that dword and documents four, but we have no dword to fill,
so every string argument past the event name is a unit.

The filter applies only when the event's first argument is a string. A
number-first event, or a no-arg event (dispatched through a runner this never
sees), fires as with RegisterEvent -- one rule that holds on every dispatch
path, and one that fails toward an extra event rather than a lost one.

FUN_FRAME_RUN_SCRIPT_WITH_CONTEXT was already hooked by Frame::ClickEvents for
PreClick/PostClick, and MinHook allows only one hook per address -- a second
aborts the entire install. Frame::RunnerHook now owns that hook and fans out to
subscribers claiming disjoint slot addresses; ClickEvents moves onto it with no
behavior change.

Verified in-game: 28 assertions over the branch table above, the
PreClick/OnClick/PostClick bracket still firing in order through the shared
runner, and a capture window in which a filtered frame received only its own
token (20 of 20) while a plain control frame on the same events took 115 fires
across six token spellings.
This commit is contained in:
Brues
2026-09-08 00:10:22 -05:00
parent 66c878d03e
commit be03d45f0c
9 changed files with 605 additions and 97 deletions
+8 -2
View File
@@ -3,8 +3,8 @@
-- Only the dependency-light, commonly-called helpers are ported. Omitted:
-- - the fade/flash functions (UIFrameFade*/UIFrameFlash*) are already
-- native in 1.12.
-- - RegisterFrameForUnitEvents (no RegisterUnitEvent in 1.12), and the
-- scale/layout/secure/EventRegistry helpers (rely on APIs absent here).
-- - the scale/layout/secure/EventRegistry helpers (rely on APIs absent
-- here).
FrameUtil = FrameUtil or {};
@@ -14,6 +14,12 @@ function FrameUtil.RegisterFrameForEvents(frame, events)
end
end
function FrameUtil.RegisterFrameForUnitEvents(frame, events, ...)
for i, event in ipairs(events) do
frame:RegisterUnitEvent(event, unpack(arg));
end
end
function FrameUtil.UnregisterFrameForEvents(frame, events)
for i, event in ipairs(events) do
frame:UnregisterEvent(event);
+1 -1
View File
@@ -71,7 +71,7 @@ reference in **[docs/API.md](docs/API.md)**.
| [Expansion](docs/API.md#expansion) | `ClassicExpansionAtLeast`, `ClassicExpansionAtMost`, `GetClassicExpansionLevel` |
| [Faction](docs/API.md#faction) | `C_Reputation.GetFactionDataByID`, `C_Reputation.GetFactionDataByIndex`, `C_Reputation.GetFactionStandings`, `C_Reputation.GetLastStandingChange`, `C_Reputation.GetWatchedFactionData`, `C_Reputation.IsFactionActive`, `C_Reputation.IsFactionActiveByID`, `C_Reputation.IsFactionInactive`, `C_Reputation.SetFactionActive`, `C_Reputation.SetFactionActiveByID`, `C_Reputation.SetFactionInactive`, `C_Reputation.SetFactionInactiveByID`, `C_Reputation.SetSelectedFaction`, `C_Reputation.SetSelectedFactionByID`, `C_Reputation.SetWatchedFactionByID`, `C_Reputation.ToggleFactionAtWar`, `C_Reputation.ToggleFactionAtWarByID`, `GetFactionIDByIndex`, `GetFactionInfoByID`, `GetFactionParentID` |
| [Focus](docs/API.md#focus) | `ClearFocus`, `FocusUnit` |
| [Frame](docs/API.md#frame) | `region:SetPoint("point")` (one-arg form), `region:SetSize`, `region:GetSize`, `region:IsMouseOver`, `region:GetRect`, `region:IsDragging`, `GetMouseFoci`, `frame:SetShown`, `fontstring:GetStringHeight`, `fontstring:GetUnboundedStringWidth`, `fontstring:GetWrappedWidth`, `fontstring:GetNumLines`, `fontstring:GetLineHeight`, `fontstring:IsTruncated`, `fontstring:SetMaxLines`, `fontstring:GetMaxLines`, `fontstring:SetFormattedText`, `texture:SetRotation`, `texture:GetRotation`, `texture:SetVertexOffset`, `texture:GetVertexOffset`, `texture:SetColorTexture`, `texture:SetAtlas`, `texture:GetAtlas`, `texture:ResetTexCoord`, `texture:SetSpriteSheetCell`, `texture:SetMask`, `frame:CreateMaskTexture`, `texture:AddMaskTexture`, `texture:RemoveMaskTexture`, `texture:GetNumMaskTextures`, `texture:GetMaskTexture`, `fontstring:SetRotation`, `fontstring:GetRotation`, `editBox:SetCursorPosition`, `editBox:GetCursorPosition`, `editBox:GetUTF8CursorPosition`, `editBox:ClearHighlightText`, `editBox:HasFocus`, `editBox:HasText`, `editBox:SetHighlightColor`, `editBox:GetHighlightColor`, `editBox:ClearHistory`, `frame:SetResizeBounds`, `frame:HookScript`, `frame:IsEventRegistered`, `frame:GetEffectiveAlpha`, `frame:SetAttribute`, `frame:SetAttributeNoHandler`, `frame:ClearAttribute`, `frame:GetAttribute`, `OnAttributeChanged` (script), `SetModernScriptArgs`, `GetModernScriptArgs`, `PreClick` (script), `PostClick` (script), `GetClickFrame` |
| [Frame](docs/API.md#frame) | `region:SetPoint("point")` (one-arg form), `region:SetSize`, `region:GetSize`, `region:IsMouseOver`, `region:GetRect`, `region:IsDragging`, `GetMouseFoci`, `frame:SetShown`, `fontstring:GetStringHeight`, `fontstring:GetUnboundedStringWidth`, `fontstring:GetWrappedWidth`, `fontstring:GetNumLines`, `fontstring:GetLineHeight`, `fontstring:IsTruncated`, `fontstring:SetMaxLines`, `fontstring:GetMaxLines`, `fontstring:SetFormattedText`, `texture:SetRotation`, `texture:GetRotation`, `texture:SetVertexOffset`, `texture:GetVertexOffset`, `texture:SetColorTexture`, `texture:SetAtlas`, `texture:GetAtlas`, `texture:ResetTexCoord`, `texture:SetSpriteSheetCell`, `texture:SetMask`, `frame:CreateMaskTexture`, `texture:AddMaskTexture`, `texture:RemoveMaskTexture`, `texture:GetNumMaskTextures`, `texture:GetMaskTexture`, `fontstring:SetRotation`, `fontstring:GetRotation`, `editBox:SetCursorPosition`, `editBox:GetCursorPosition`, `editBox:GetUTF8CursorPosition`, `editBox:ClearHighlightText`, `editBox:HasFocus`, `editBox:HasText`, `editBox:SetHighlightColor`, `editBox:GetHighlightColor`, `editBox:ClearHistory`, `frame:SetResizeBounds`, `frame:HookScript`, `frame:IsEventRegistered`, `frame:RegisterUnitEvent`, `frame:GetEffectiveAlpha`, `frame:SetAttribute`, `frame:SetAttributeNoHandler`, `frame:ClearAttribute`, `frame:GetAttribute`, `OnAttributeChanged` (script), `SetModernScriptArgs`, `GetModernScriptArgs`, `PreClick` (script), `PostClick` (script), `GetClickFrame` |
| [FriendList](docs/API.md#friendlist) | `C_FriendList.GetFriendInfo`, `C_FriendList.GetFriendInfoByIndex`, `C_FriendList.GetNumFriends`, `C_FriendList.GetNumOnlineFriends`, `C_FriendList.GetNumWhoResults`, `C_FriendList.GetWhoInfo`, `C_FriendList.IsFriend`, `C_FriendList.IsIgnored`, `C_FriendList.IsIgnoredByGuid`, `C_FriendList.IsWhoQueryPending`, `C_FriendList.SendWhoQueryByName`, `C_FriendList.SetFriendNotes`, `C_FriendList.SetFriendNotesByIndex` |
| [GameObject](docs/API.md#gameobject) | `C_GameObjectInfo.GetGameObjectInfoByID`, `C_GameObjectInfo.RequestLoadGameObjectByID`, `ClosestGameObjectPosition` |
| [Glue](docs/API.md#glue) | `C_Glue.IsOnGlueScreen` |
+55 -6
View File
@@ -234,6 +234,7 @@ build instructions.
- [`frame:SetResizeBounds(minWidth, minHeight [, maxWidth, maxHeight])`](#framesetresizeboundsminwidth-minheight--maxwidth-maxheight)
- [`frame:HookScript(scriptType, handler)`](#framehookscriptscripttype-handler)
- [`frame:IsEventRegistered(event)`](#frameiseventregisteredevent)
- [`frame:RegisterUnitEvent(event, ...units)`](#frameregisteruniteventevent-units)
- [`frame:GetEffectiveAlpha()`](#framegeteffectivealpha)
- [`frame:SetAttribute` / `SetAttributeNoHandler` / `ClearAttribute` / `GetAttribute` (+ unit-frame mouseover)](#framesetattributename-value--framesetattributenohandlername-value--frameclearattributename--framegetattribute)
- [`SetModernScriptArgs(enable)` / `GetModernScriptArgs()`](#setmodernscriptargsenable--getmodernscriptargs)
@@ -5327,20 +5328,68 @@ end)
### `frame:IsEventRegistered(event)`
The engine ships `RegisterEvent` / `UnregisterEvent` but not the query.
Returns `true` if the frame is currently registered for `event`,
`false` otherwise (including for an unknown event name). Reuses the
engine's own subscriber-chain membership check — the same walk
`RegisterEvent` performs before appending — so the answer is exactly
what the event dispatcher sees. Works on any frame.
Returns `true` if the frame is registered for `event`, else `false` (also
`false` for an unknown event name). If the registration came from
`frame:RegisterUnitEvent`, the unit tokens follow as extra returns, in the
order they were given. Works on any frame.
```lua
local f = CreateFrame("Frame")
f:RegisterEvent("PLAYER_LOGIN")
f:IsEventRegistered("PLAYER_LOGIN") -- true
f:IsEventRegistered("PLAYER_LOGOUT") -- false
f:RegisterUnitEvent("UNIT_HEALTH", "player", "target")
f:IsEventRegistered("UNIT_HEALTH") -- true, "player", "target"
```
### `frame:RegisterUnitEvent(event, ...units)`
Registers the frame for `event`, but the frame's `OnEvent` runs only when the
event's first argument (the unit token) is one of `units`. Use it in place of
`RegisterEvent` for `UNIT_*` events, so a handler for one unit does not receive
every other unit's events. Returns whether the frame is now registered.
```lua
local f = CreateFrame("Frame")
f:RegisterUnitEvent("UNIT_HEALTH", "player")
f:SetScript("OnEvent", function(self, event, unit)
-- unit is always "player" here
end)
```
Unit tokens compare without regard to case. Every token that names a unit
works, including `focus`, `nameplateN`, and `markN`. A unit that is several
tokens at once (your target who is also `party1`) fires the event once for
each token that matches.
Pass as many units as you need. Other clients take at most four, so keep to
four for code you also run elsewhere — accepting more is a ClassicAPI
extension.
```lua
f:RegisterUnitEvent("UNIT_HEALTH", "player", "party1", "party2", "party3")
```
Behavior notes:
- A registration keeps its kind until you unregister it. `RegisterEvent` on a
unit-filtered registration keeps the filter. `RegisterUnitEvent` on a plain
registration keeps it plain. `RegisterUnitEvent` on a unit-filtered
registration replaces the units. To switch kinds, call `UnregisterEvent`
first.
- If you give no unit, or no unit argument is a string, the call acts as
`RegisterEvent`.
- The filter applies only when the event's first argument is a string. For an
event whose first argument is a number, or that has no arguments, the frame
receives the event as with `RegisterEvent`.
- `UnregisterEvent` and `UnregisterAllEvents` remove the filter with the
registration.
- `frame:IsEventRegistered(event)` returns the unit tokens after the boolean.
`FrameUtil.RegisterFrameForUnitEvents(frame, events, ...units)` calls
`RegisterUnitEvent` for each event in the `events` table.
### `frame:GetEffectiveAlpha()`
Returns the frame's **effective** alpha — its own `GetAlpha()` multiplied
+41 -8
View File
@@ -246,10 +246,15 @@ enum Offsets {
// (the arg'd runner Frame::ScriptArgs hooks) and restores. Every arg'd
// input-script fire funnels through here via FUN_007026F0 (its variadic
// forwarder); the event dispatcher FUN_00703F50 is the only other caller.
// `Frame::ClickEvents` co-hooks it, gates on `slotPtr == frame +
// OFF_BUTTON_ONCLICK_HANDLER` (an exact OnClick match — no other fire passes
// that slot address), and fires PreClick before / PostClick after by
// re-invoking with the same (fmt, vaPtr) so the button-name arg is reused.
// ONE hook, owned by `Frame::RunnerHook`, fans out to subscribers that each
// claim a disjoint slot address (a second MinHook here would abort the
// whole install — subscribe instead): `Frame::ClickEvents` gates on
// `slotPtr == frame + OFF_BUTTON_ONCLICK_HANDLER` (an exact OnClick match —
// no other fire passes that slot) and brackets OnClick with PreClick /
// PostClick by re-invoking with the same (fmt, vaPtr) so the button-name
// arg is reused; `Frame::UnitEvent` gates on `slotPtr == frame +
// OFF_FRAME_ONEVENT_SLOT` (the dispatcher's per-frame OnEvent fire) and
// suppresses the call when a RegisterUnitEvent filter rejects arg1.
// Deliberately NOT the button click vmethod FUN_00779540, which SuperWoW
// inline-hooks for click-casting (a second hook there faults, ERROR #132 —
// see the note near FUN_SCRIPT_FRAME_GET_STRATA); this runner is uncontested.
@@ -2258,6 +2263,16 @@ enum Offsets {
FUN_SCRIPT_FRAME_SETMAXRESIZE = 0x007762A0,
FUN_SCRIPT_FRAME_GETSCRIPT = 0x00774780,
FUN_SCRIPT_FRAME_SETSCRIPT = 0x007748D0,
// `frame:RegisterEvent(event)` (Frame registry, `Script_RegisterEvent`) —
// standard `int __fastcall(void *L)`: resolves self at 1, reads the event
// name at 2, calls FUN_FRAME_REGISTER_EVENT. `Frame::UnitEvent` delegates
// `RegisterUnitEvent` to it by stack reshape so chain membership stays
// engine-owned (self typecheck, error text, and DllMain's RegisterEvent
// hook all run as for a plain call). Siblings from the same method table,
// referenced in comments only: UnregisterEvent 0x00774B30 (calls
// FUN_FRAME_UNREGISTER_EVENT), RegisterAllEvents 0x00774C20,
// UnregisterAllEvents 0x00774CF0 (calls FUN_FRAME_UNREGISTER_ALL_EVENTS).
FUN_SCRIPT_FRAME_REGISTEREVENT = 0x00774A40,
// `frame:EnableMouse(enable)` (Frame registry) — `Frame::Attributes` calls
// it so a unit-attributed frame registers as the mouse-focus (bare frames
// otherwise never hover). Standard `int __fastcall(void *L)` Script_* shape.
@@ -5549,11 +5564,29 @@ enum Offsets {
// `Frame::RegisterEvent` — the C++ helper called by the Lua
// `frame:RegisterEvent(eventName)` method (`Script_RegisterEvent` at
// `0x00774A40`). `__thiscall` with `(this=frame, eventName)`. Walks
// the entry array at `[VAR_EVENT_TABLE_BASE_PTR]`, case-insensitively
// strcmps against each entry's name, and appends `frame` to the
// matching entry's chain.
// `0x00774A40` = FUN_SCRIPT_FRAME_REGISTEREVENT). `__thiscall` with
// `(this=frame, eventName)`. Walks the entry array at
// `[VAR_EVENT_TABLE_BASE_PTR]`, case-insensitively strcmps against each
// entry's name, appends `frame` to the matching entry's chain, and appends
// the event index to the frame's own registered-event list (`+0x14` cap,
// `+0x18` count, `+0x1C` int[]). Returns 1 when the frame was ALREADY on
// that chain (no-op), 0 after appending.
FUN_FRAME_REGISTER_EVENT = 0x00702140,
// `Frame::UnregisterEvent` — `__thiscall(this=frame, eventName)`. Walks
// the frame's registered-event list backwards for the entry whose name
// matches (SStrCmpI), unlinks + frees the frame's `__AUEVENTLISTENERNODE__`
// from that chain, and compacts the list. Sole caller is the Lua wrapper
// `Script_UnregisterEvent` (0x00774B30). `Frame::UnitEvent` co-hooks it to
// drop the (frame, event) unit filter exactly when the engine drops the
// node — mirroring 5.4.8, where the filter LIVES on the node.
FUN_FRAME_UNREGISTER_EVENT = 0x00702280,
// `Frame::UnregisterAllEvents` — `__fastcall(frame)`. Unlinks the frame's
// node from every chain in its registered-event list, frees the list, and
// zeroes `+0x14/+0x18/+0x1C`. Callers: the Lua wrapper
// `Script_UnregisterAllEvents` (0x00774CF0) and the CScriptObject
// destructor FUN_00701B40 — so a hook here also sees frame destruction.
// `Frame::UnitEvent` co-hooks it to drop all of the frame's unit filters.
FUN_FRAME_UNREGISTER_ALL_EVENTS = 0x007024F0,
// `RebuildEventTable` — the engine's bulk event-table population
// routine. `__fastcall(const char **names, int count) -> void`
+19 -22
View File
@@ -29,10 +29,11 @@
//
// - The engine fires a button's OnClick through the arg'd script runner
// FUN_FRAME_RUN_SCRIPT_WITH_CONTEXT(frame, frame+0x4CC, "%s", &buttonName).
// We co-hook that runner and, when the fired slot IS the OnClick slot,
// re-invoke the runner for our PreClick cell first, then let OnClick run,
// then re-invoke for PostClick — reusing the SAME (fmt, varargs) so
// PreClick/PostClick receive arg1 = the button name exactly like OnClick.
// We intercept that runner (through `Frame::RunnerHook`, the shared single
// hook on it) and, when the fired slot IS the OnClick slot, re-invoke the
// runner for our PreClick cell first, then let OnClick run, then re-invoke
// for PostClick — reusing the SAME (fmt, varargs) so PreClick/PostClick
// receive arg1 = the button name exactly like OnClick.
//
// Why the runner and not the button click vmethod (FUN_00779540): SuperWoW
// inline-hooks that vmethod for click-casting, and a second MinHook there
@@ -50,6 +51,7 @@
#include "Game.h"
#include "Offsets.h"
#include "frame/RunnerHook.h"
#include <cstdint>
#include <unordered_map>
@@ -122,13 +124,12 @@ int __fastcall Resolver_h(void *self, void *edx, const char *name) {
return 0;
}
// --- Runner co-hook (fire PreClick before / PostClick after OnClick) ---
using RunScript_t = void(__cdecl *)(void *frame, uint32_t *slotPtr,
const char *fmt, void *varargs);
RunScript_t g_runOriginal = nullptr;
// --- Runner interceptor (fire PreClick before / PostClick after OnClick) ---
// Subscribed to `Frame::RunnerHook`, the single shared hook on
// FUN_FRAME_RUN_SCRIPT_WITH_CONTEXT (MinHook allows one hook per address).
// Fire the handler (if any) for `kind` on `frame`, reusing the OnClick fire's
// own (fmt, varargs) so arg1 = the button name. We call the original runner
// own (fmt, varargs) so arg1 = the button name. We call the engine runner
// directly (its exec-context stamp is valid at this dispatch level). The runner
// balances the Lua stack itself; we snapshot/restore the top as cheap insurance
// against any imbalance leaking to the still-running button click code.
@@ -138,26 +139,25 @@ void FireCell(void *frame, int kind, const char *fmt, void *varargs) {
return;
void *L = Game::Lua::State();
const int savedTop = (L != nullptr) ? Game::Lua::GetTop(L) : 0;
g_runOriginal(frame, slot, fmt, varargs);
Frame::RunnerHook::Original(frame, slot, fmt, varargs);
if (L != nullptr)
Game::Lua::SetTop(L, savedTop);
}
void __cdecl RunScript_h(void *frame, uint32_t *slotPtr, const char *fmt,
void *varargs) {
// Falls through (false) for every fire that isn't a top-level OnClick;
// otherwise runs the whole bracket itself and reports it handled (true).
bool OnRun(void *frame, uint32_t *slotPtr, const char *fmt, void *varargs) {
const auto onClickSlot = reinterpret_cast<uint32_t *>(
reinterpret_cast<char *>(frame) + Offsets::OFF_BUTTON_ONCLICK_HANDLER);
if (slotPtr != onClickSlot || g_firing > 0) {
g_runOriginal(frame, slotPtr, fmt, varargs);
return;
}
if (slotPtr != onClickSlot || g_firing > 0)
return false;
++g_firing;
FireCell(frame, SK_PRECLICK, fmt, varargs);
g_runOriginal(frame, slotPtr, fmt, varargs); // the button's OnClick
Frame::RunnerHook::Original(frame, slotPtr, fmt, varargs); // the button's OnClick
FireCell(frame, SK_POSTCLICK, fmt, varargs);
--g_firing;
return true;
}
static const Game::HookAutoRegister _resolverHook{
@@ -165,10 +165,7 @@ static const Game::HookAutoRegister _resolverHook{
reinterpret_cast<void *>(&Resolver_h),
reinterpret_cast<void **>(&g_resolverOriginal)};
static const Game::HookAutoRegister _runnerHook{
Offsets::FUN_FRAME_RUN_SCRIPT_WITH_CONTEXT,
reinterpret_cast<void *>(&RunScript_h),
reinterpret_cast<void **>(&g_runOriginal)};
static const Frame::RunnerHook::AutoSubscribe _runnerSub{&OnRun};
} // namespace
-58
View File
@@ -331,63 +331,6 @@ int __fastcall Script_HookScript(void *L) {
return 0;
}
// ---- IsEventRegistered (Frame) ---------------------------------------------
// `frame:IsEventRegistered("event")` — vanilla has RegisterEvent /
// UnregisterEvent but not the query. There's no engine Script_* to
// delegate to, so we replicate the membership check that lives inside
// Frame::RegisterEvent (FUN_00702140): find the event by name in the live
// event table, then walk that entry's subscriber chain for this frame.
// The frame pointer we compare against is the same CFrameScriptObject*
// the engine stores (Game::Lua::ResolveObject resolves self exactly as
// Script_RegisterEvent does).
using SStrCmpI_t = int(__stdcall *)(const char *a, const char *b, int n);
bool FrameHasEvent(void *frame, const char *eventName) {
const uint32_t count = Game::Read<uint32_t>(
static_cast<uintptr_t>(Offsets::VAR_EVENT_TABLE_COUNT));
auto *base = Game::Read<const uint8_t *>(
static_cast<uintptr_t>(Offsets::VAR_EVENT_TABLE_BASE_PTR));
if (count == 0 || base == nullptr)
return false;
auto sstrcmpi = reinterpret_cast<SStrCmpI_t>(
static_cast<uintptr_t>(Offsets::FUN_SSTR_CMP_I));
for (uint32_t i = 0; i < count; ++i) {
const uint8_t *entry = base + i * Offsets::EVENT_ENTRY_STRIDE;
const char *name = Game::Read<const char *>(
entry, Offsets::OFF_EVENT_ENTRY_NAME);
if (name == nullptr)
continue;
if (sstrcmpi(name, eventName, 0x7FFFFFFF) != 0)
continue;
// Names are unique, so this is the one entry — walk its chain.
uintptr_t node = Game::Read<uintptr_t>(
entry, Offsets::OFF_EVENT_ENTRY_HEAD);
while ((node & 1) == 0 && node != 0) {
if (Game::Read<void *>(node + Offsets::OFF_EVENT_NODE_FRAME) == frame)
return true;
node = Game::Read<uintptr_t>(node + Offsets::OFF_EVENT_NODE_NEXT);
}
return false;
}
return false;
}
int __fastcall Script_IsEventRegistered(void *L) {
if (!Game::Lua::IsString(L, 2)) {
Game::Lua::Error(L, "Usage: frame:IsEventRegistered(\"event\")");
return 0;
}
void *frame = Game::Lua::ResolveObject(L, 1);
const char *eventName = Game::Lua::ToString(L, 2);
const bool registered =
frame != nullptr && eventName != nullptr && FrameHasEvent(frame, eventName);
Game::Lua::PushBool(L, registered);
return 1;
}
// ---- SetPoint one-arg form (Script_SetPoint co-hook) -----------------------
// Vanilla's Script_SetPoint accepts every modern form except the bare
@@ -427,7 +370,6 @@ const Game::Lua::FrameMethodEntry g_frameMethods[] = {
Offsets::FUN_SCRIPT_FRAME_HIDE>},
{"SetResizeBounds", &Script_SetResizeBounds},
{"HookScript", &Script_HookScript},
{"IsEventRegistered", &Script_IsEventRegistered},
{"GetEffectiveAlpha", &Script_GetEffectiveAlpha},
};
+51
View File
@@ -0,0 +1,51 @@
// 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 <https://www.gnu.org/licenses/>.
#include "frame/RunnerHook.h"
#include "Game.h"
#include "Offsets.h"
namespace Frame::RunnerHook {
namespace {
// Chained at static-init time by each `AutoSubscribe` constructor, before
// `DllMain`. Zero-initialized (namespace static) ahead of any dynamic init, so
// the head is valid when subscribers link in.
AutoSubscribe *g_head = nullptr;
using Runner_t = void(__cdecl *)(void *frame, uint32_t *slotPtr, const char *fmt,
void *varargs);
Runner_t g_orig = nullptr;
void __cdecl Hook(void *frame, uint32_t *slotPtr, const char *fmt, void *varargs) {
for (AutoSubscribe *s = g_head; s != nullptr; s = s->next)
if (s->fn(frame, slotPtr, fmt, varargs))
return; // handled — suppressed, or the subscriber ran Original itself
g_orig(frame, slotPtr, fmt, varargs);
}
const Game::HookAutoRegister _hook{
Offsets::FUN_FRAME_RUN_SCRIPT_WITH_CONTEXT, reinterpret_cast<void *>(&Hook),
reinterpret_cast<void **>(&g_orig)};
} // namespace
AutoSubscribe::AutoSubscribe(Interceptor f) : fn(f), next(g_head) { g_head = this; }
void Original(void *frame, uint32_t *slotPtr, const char *fmt, void *varargs) {
g_orig(frame, slotPtr, fmt, varargs);
}
} // namespace Frame::RunnerHook
+56
View File
@@ -0,0 +1,56 @@
// 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 <https://www.gnu.org/licenses/>.
#pragma once
#include <cstdint>
// Shared interceptor for the engine's arg'd frame-script runner
// `FUN_FRAME_RUN_SCRIPT_WITH_CONTEXT` (0x00702710) — `__cdecl(frame, slotPtr,
// fmt, vaPtr)`: stamps the exec context from `slotPtr[1]`, runs the handler in
// `slotPtr[0]` through FUN_FRAME_RUN_SCRIPT_ARGS, restores. Exactly two engine
// paths funnel through it: every arg'd input-script fire (OnClick,
// OnMouseWheel, … via the variadic forwarder FUN_007026F0) and the event
// dispatcher FUN_FIRE_EVENT's per-frame OnEvent fire, which passes
// `slotPtr == frame + OFF_FRAME_ONEVENT_SLOT`.
//
// MinHook allows ONE hook per address, and more than one feature needs this
// runner: `Frame::ClickEvents` brackets OnClick with PreClick/PostClick, and
// `Frame::UnitEvent` suppresses OnEvent fires that a RegisterUnitEvent filter
// rejects. So — exactly like `Event::SignalHook` and `Tick::WorldTick` — this
// module owns the single hook and fans out. Declare a file-scope
// static const Frame::RunnerHook::AutoSubscribe _sub{&interceptor};
//
// An interceptor returns `true` when it has fully handled the fire — either
// suppressed it, or already ran the engine itself through `Original` (the
// bracketing case). `false` falls through to the next subscriber and finally
// the original. The FIRST `true` wins, so subscribers must claim disjoint slot
// addresses; subscriber order is static-init order and must not matter.
namespace Frame::RunnerHook {
using Interceptor = bool (*)(void *frame, uint32_t *slotPtr, const char *fmt,
void *varargs);
struct AutoSubscribe {
explicit AutoSubscribe(Interceptor fn);
Interceptor fn;
AutoSubscribe *next;
};
// The engine's runner (the MinHook trampoline) — for interceptors that run the
// fire themselves, e.g. to bracket it, rather than suppress it. Valid only once
// hooks are installed, i.e. from inside an interceptor.
void Original(void *frame, uint32_t *slotPtr, const char *fmt, void *varargs);
} // namespace Frame::RunnerHook
+374
View File
@@ -0,0 +1,374 @@
// 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 <https://www.gnu.org/licenses/>.
// `frame:RegisterUnitEvent(event, ...units)` — register for an event but only
// receive it for the given unit tokens — plus the unit-aware
// `frame:IsEventRegistered(event)` (registered [, unit…]).
//
// Vanilla owns everything except the filter, so the filter is all this adds:
//
// - Chain membership stays the engine's. RegisterUnitEvent delegates to the
// engine's own `Script_RegisterEvent` (stack cut to (self, event)), so the
// frame lands on the event's subscriber chain through the same code every
// RegisterEvent uses — self typecheck, error text, and DllMain's
// RegisterEvent hook included.
// - The filter is stored here, keyed by frame, and dropped exactly where the
// engine drops the frame's subscriber node: co-hooks on the C++ helpers
// `Frame::UnregisterEvent` (FUN_FRAME_UNREGISTER_EVENT) and
// `Frame::UnregisterAllEvents` (FUN_FRAME_UNREGISTER_ALL_EVENTS — also the
// CScriptObject destructor's path, so frame destruction is covered).
// - The check is one gate on the per-frame OnEvent fire. The dispatcher
// FUN_FIRE_EVENT sets `_G.event`, walks the chain, and per frame calls the
// runner FUN_FRAME_RUN_SCRIPT_WITH_CONTEXT(frame, frame+OFF_FRAME_ONEVENT_SLOT,
// fmt, va). We subscribe to that runner through `Frame::RunnerHook` (it is
// shared with Frame::ClickEvents — one MinHook per address), and when the
// frame has a filter for the event being dispatched and arg1 matches none
// of its tokens, we return without invoking the handler. Suppressing at the
// runner also suppresses HookScript chains and Frame::ScriptArgs' positional
// path — they all live downstream of it, which is what retail does too.
//
// Semantics mirror Blizzard's 5.4.8 implementation (Ghidra-verified), where the
// filter lives ON the subscriber node and the node's kind is fixed when it is
// created: RegisterEvent on a filtered registration leaves the filter;
// RegisterUnitEvent on a plain registration stays plain; RegisterUnitEvent on a
// filtered registration replaces the units; RegisterUnitEvent with no usable
// unit is a plain RegisterEvent. Switching kinds takes UnregisterEvent first.
//
// Two places we deliberately don't mirror 5.4.8, both additive:
//
// - UNIT COUNT. 5.4.8 reads exactly two units (a hardcoded two-iteration loop
// over Lua indices 3 and 4) and folds each token's table index into a byte
// of one dword on the node — `filter = filter * 0x100 + idx`. Retail later
// filled that dword and documents "up to four units", which its 5.4.8
// reader already anticipated by walking all four bytes generically. We
// store strings in our own map, so there is no dword to fill and no reason
// to pick a number: every argument past the event name that is a string is
// taken as a unit. Retail's four are covered by definition.
// - TOKEN VALIDATION. 5.4.8 looks each unit up in a static canonical token
// table (case-sensitive) and drops unknowns; we keep the string and compare
// case-insensitively, because ClassicAPI's own tokens (`focus`,
// `nameplateN`, `markN`) are not in the engine's table.
//
// Filter rule: the filter applies only when the event's first argument is a
// string (every UNIT_* event fires as "%s" + token). A first spec that isn't
// `%s`, or a no-arg event (those go through FUN_FIRE_EVENT_NO_ARGS → a runner
// we never see), fires as with RegisterEvent — one rule that holds on every
// dispatch path, whose failure mode is an extra event rather than a lost one.
#include "Game.h"
#include "Offsets.h"
#include "frame/RunnerHook.h"
#include <cstdint>
#include <cstring>
#include <string>
#include <unordered_map>
#include <vector>
namespace Frame::UnitEvent {
namespace {
using ScriptFn_t = int(__fastcall *)(void *L);
// Storm SStrCmpI — `__stdcall`, RET 0xC (see Offsets.h; a __cdecl declaration
// drifts ESP by 12 per call).
using SStrCmpI_t = int(__stdcall *)(const char *a, const char *b, int n);
int CallScript(uintptr_t fn, void *L) { return reinterpret_cast<ScriptFn_t>(fn)(L); }
bool EqualsIgnoreCase(const char *a, const char *b) {
if (a == nullptr || b == nullptr)
return false;
auto cmp = reinterpret_cast<SStrCmpI_t>(static_cast<uintptr_t>(Offsets::FUN_SSTR_CMP_I));
return cmp(a, b, 0x7FFFFFFF) == 0;
}
// One filtered registration — the unit filter 5.4.8 keeps on the event's
// subscriber node for this frame. `event` is the CANONICAL name copied from the
// event-table entry, so the fire-time compare against the dispatcher-set
// `_G.event` (which is that same entry name) is a plain strcmp.
struct Filter {
std::string event;
std::vector<std::string> units; // never empty; a filter with no unit is no filter
};
// Keyed by frame. Entries die with the frame's subscriber node (the two
// unregister co-hooks) and on /reload (PrepareForReload).
std::unordered_map<const void *, std::vector<Filter>> g_filters;
// ---- event table -----------------------------------------------------------
// The live event-table entry whose name matches `eventName` (case-insensitive,
// as Frame::RegisterEvent matches), or nullptr for an unknown event.
const uint8_t *FindEventEntry(const char *eventName) {
if (eventName == nullptr)
return nullptr;
const uint32_t count = Game::Read<uint32_t>(
static_cast<uintptr_t>(Offsets::VAR_EVENT_TABLE_COUNT));
auto *base = Game::Read<const uint8_t *>(
static_cast<uintptr_t>(Offsets::VAR_EVENT_TABLE_BASE_PTR));
if (count == 0 || base == nullptr)
return nullptr;
for (uint32_t i = 0; i < count; ++i) {
const uint8_t *entry = base + i * Offsets::EVENT_ENTRY_STRIDE;
const char *name = Game::Read<const char *>(entry, Offsets::OFF_EVENT_ENTRY_NAME);
if (name != nullptr && EqualsIgnoreCase(name, eventName))
return entry; // names are unique
}
return nullptr;
}
// Is `frame` on `entry`'s subscriber chain — the membership walk
// Frame::RegisterEvent performs before appending.
bool ChainHas(const uint8_t *entry, const void *frame) {
uintptr_t node = Game::Read<uintptr_t>(entry, Offsets::OFF_EVENT_ENTRY_HEAD);
while ((node & 1) == 0 && node != 0) {
if (Game::Read<const void *>(node + Offsets::OFF_EVENT_NODE_FRAME) == frame)
return true;
node = Game::Read<uintptr_t>(node + Offsets::OFF_EVENT_NODE_NEXT);
}
return false;
}
// ---- filter map --------------------------------------------------------------
Filter *FindFilter(const void *frame, const char *eventName) {
auto it = g_filters.find(frame);
if (it == g_filters.end())
return nullptr;
for (Filter &f : it->second)
if (EqualsIgnoreCase(f.event.c_str(), eventName))
return &f;
return nullptr;
}
void EraseFilter(const void *frame, const char *eventName) {
auto it = g_filters.find(frame);
if (it == g_filters.end())
return;
std::vector<Filter> &v = it->second;
for (size_t i = 0; i < v.size(); ++i) {
if (EqualsIgnoreCase(v[i].event.c_str(), eventName)) {
v.erase(v.begin() + static_cast<ptrdiff_t>(i));
break;
}
}
if (v.empty())
g_filters.erase(it);
}
// ---- Lua methods --------------------------------------------------------------
// `frame:RegisterUnitEvent(event, ...units)` → registered.
int __fastcall Script_RegisterUnitEvent(void *L) {
if (!Game::Lua::IsString(L, 2)) {
Game::Lua::Error(L, "Usage: frame:RegisterUnitEvent(\"event\" [, \"unit1\", ...])");
return 0;
}
void *frame = Game::Lua::ResolveObject(L, 1);
if (frame == nullptr) {
// Not a frame — hand it to the engine so it raises its own error, so
// the message stays the engine's rather than a copy of it.
Game::Lua::SetTop(L, 2);
return CallScript(Offsets::FUN_SCRIPT_FRAME_REGISTEREVENT, L);
}
// Read everything BEFORE reshaping the stack for the delegate — including
// the top, which the reshape destroys. Like 5.4.8 we take only real strings
// as units (a number is not coerced) and silently skip anything else.
const std::string eventName = Game::Lua::ToString(L, 2);
const int argTop = Game::Lua::GetTop(L);
std::vector<std::string> units;
for (int idx = 3; idx <= argTop; ++idx) {
if (Game::Lua::Type(L, idx) != Game::Lua::TYPE_STRING)
continue;
const char *s = Game::Lua::ToString(L, idx);
if (s != nullptr && *s != '\0')
units.push_back(s);
}
const uint8_t *entry = FindEventEntry(eventName.c_str());
const bool wasRegistered = entry != nullptr && ChainHas(entry, frame);
// Chain membership is the engine's: (self, event) → Script_RegisterEvent.
Game::Lua::SetTop(L, 2);
CallScript(Offsets::FUN_SCRIPT_FRAME_REGISTEREVENT, L);
// 5.4.8 node semantics (see the header). No usable unit → this was a plain
// RegisterEvent and an existing filter is left alone; an unknown event has
// no node to attach a filter to.
if (entry != nullptr && !units.empty()) {
if (Filter *f = FindFilter(frame, eventName.c_str())) {
f->units = units; // filtered → replace the units
} else if (!wasRegistered) {
Filter fresh;
fresh.event = Game::Read<const char *>(entry, Offsets::OFF_EVENT_ENTRY_NAME);
fresh.units = units;
g_filters[frame].push_back(fresh);
}
// else: already registered plainly → stays plain
}
Game::Lua::PushBool(L, entry != nullptr && ChainHas(entry, frame));
return 1;
}
// `frame:IsEventRegistered(event)` → registered [, unit…]. Vanilla has
// RegisterEvent / UnregisterEvent but not the query; the membership check is
// the same chain walk Frame::RegisterEvent performs, so the answer is exactly
// what the dispatcher sees. Units come back in registration order.
int __fastcall Script_IsEventRegistered(void *L) {
if (!Game::Lua::IsString(L, 2)) {
Game::Lua::Error(L, "Usage: frame:IsEventRegistered(\"event\")");
return 0;
}
void *frame = Game::Lua::ResolveObject(L, 1);
const char *eventName = Game::Lua::ToString(L, 2);
const uint8_t *entry = (frame != nullptr) ? FindEventEntry(eventName) : nullptr;
const bool registered = entry != nullptr && ChainHas(entry, frame);
Game::Lua::PushBool(L, registered);
if (!registered)
return 1;
const Filter *f = FindFilter(frame, eventName);
if (f == nullptr)
return 1;
if (Game::Lua::CheckStack(L, static_cast<int>(f->units.size()) + 1) == 0)
return 1; // can't grow the stack — report registered, drop the units
int pushed = 1;
for (const std::string &u : f->units) {
Game::Lua::PushString(L, u.c_str());
++pushed;
}
return pushed;
}
// ---- the gate ------------------------------------------------------------------
// True (and `*out` = arg1) when the runner's first conversion spec is `%s` —
// the unit token of every unit event. Anything else means arg1 isn't a string
// and the filter does not apply.
bool FirstArgIsString(const char *fmt, const void *varargs, const char **out) {
if (fmt == nullptr || varargs == nullptr)
return false;
const char *p = std::strchr(fmt, '%');
if (p == nullptr || p[1] != 's')
return false;
*out = *static_cast<const char *const *>(varargs);
return true;
}
// Frame::RunnerHook interceptor. Returns true ONLY to suppress a fire (the
// engine runner is then never called for it); every other path returns false
// and the fire proceeds untouched. Touches no Lua code: `_G.event` is read with
// RawGet so an `__index` metatable on _G can never run script here, and no
// reference into g_filters outlives the call.
bool OnRun(void *frame, uint32_t *slotPtr, const char *fmt, void *varargs) {
// Only the dispatcher's OnEvent fire passes the OnEvent slot.
if (frame == nullptr ||
slotPtr != reinterpret_cast<uint32_t *>(static_cast<uint8_t *>(frame) +
Offsets::OFF_FRAME_ONEVENT_SLOT))
return false;
// Frames without filters pay one probe and leave.
if (g_filters.empty())
return false;
auto it = g_filters.find(frame);
if (it == g_filters.end())
return false;
// Which event? The dispatcher has just set `_G.event` to the entry's name.
void *L = Game::Lua::State();
if (L == nullptr)
return false;
Game::Lua::PushString(L, "event");
Game::Lua::RawGet(L, Game::Lua::GLOBALS_INDEX);
const char *ev = Game::Lua::ToString(L, -1);
const Filter *match = nullptr;
if (ev != nullptr) {
for (const Filter &f : it->second) {
if (std::strcmp(f.event.c_str(), ev) == 0) {
match = &f;
break;
}
}
}
Game::Lua::SetTop(L, -2);
if (match == nullptr)
return false;
// The filter applies only when arg1 is a string.
const char *arg1 = nullptr;
if (!FirstArgIsString(fmt, varargs, &arg1))
return false;
if (arg1 != nullptr) {
for (const std::string &u : match->units)
if (EqualsIgnoreCase(arg1, u.c_str()))
return false;
}
return true; // no token matched — suppress
}
// ---- unregister co-hooks (the filter dies with the node) ------------------------
// `__thiscall(frame, eventName)` mimicked as `__fastcall(ecx, edx_unused, …)`.
using UnregisterEvent_t = void(__fastcall *)(void *frame, void *edx, const char *eventName);
UnregisterEvent_t g_origUnregisterEvent = nullptr;
void __fastcall UnregisterEvent_h(void *frame, void *edx, const char *eventName) {
if (frame != nullptr && !g_filters.empty())
EraseFilter(frame, eventName);
g_origUnregisterEvent(frame, edx, eventName);
}
// `__fastcall(frame)`; the Lua wrapper has dead `(0)` calls after lua_error, so
// tolerate a null frame.
using UnregisterAll_t = void(__fastcall *)(void *frame, void *edx);
UnregisterAll_t g_origUnregisterAll = nullptr;
void __fastcall UnregisterAllEvents_h(void *frame, void *edx) {
if (frame != nullptr && !g_filters.empty())
g_filters.erase(frame);
g_origUnregisterAll(frame, edx);
}
// ---- registration -----------------------------------------------------------------
const Game::Lua::FrameMethodEntry g_frameMethods[] = {
{"RegisterUnitEvent", &Script_RegisterUnitEvent},
{"IsEventRegistered", &Script_IsEventRegistered},
};
void RegisterLuaFunctions() {
Game::Lua::RegisterFrameMethods(
reinterpret_cast<void *>(Offsets::VAR_FRAME_METHOD_REGISTRY), g_frameMethods,
static_cast<int>(sizeof(g_frameMethods) / sizeof(g_frameMethods[0])));
}
// Frames survive /reload but the engine rebuilds the event table with empty
// chains and every frame re-registers from scratch, so the filters start over
// too — and a recycled frame pointer can never inherit a stale one.
void PrepareForReload() { g_filters.clear(); }
const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
const Game::ReloadAutoRegister _reloadReg{&PrepareForReload};
const Frame::RunnerHook::AutoSubscribe _runnerSub{&OnRun};
const Game::HookAutoRegister _hookUnregister{
Offsets::FUN_FRAME_UNREGISTER_EVENT, reinterpret_cast<void *>(&UnregisterEvent_h),
reinterpret_cast<void **>(&g_origUnregisterEvent)};
const Game::HookAutoRegister _hookUnregisterAll{
Offsets::FUN_FRAME_UNREGISTER_ALL_EVENTS,
reinterpret_cast<void *>(&UnregisterAllEvents_h),
reinterpret_cast<void **>(&g_origUnregisterAll)};
} // namespace
} // namespace Frame::UnitEvent