diff --git a/AddOns/!!!ClassicAPI/!!!ClassicAPI.toc b/AddOns/!!!ClassicAPI/!!!ClassicAPI.toc
index 8d741ae2..1e2ce3fa 100644
--- a/AddOns/!!!ClassicAPI/!!!ClassicAPI.toc
+++ b/AddOns/!!!ClassicAPI/!!!ClassicAPI.toc
@@ -45,6 +45,7 @@ Util\Vector3D.lua
Util\Vector4D.lua
Util\UiMapPoint.lua
Util\UIParent.lua
+Util\ActionButton.lua
Util\WorldMap.lua
Util\AuraDurationModifiers.lua
Util\AuraUtil.lua
diff --git a/AddOns/!!!ClassicAPI/Util/ActionButton.lua b/AddOns/!!!ClassicAPI/Util/ActionButton.lua
new file mode 100644
index 00000000..8af37ecc
--- /dev/null
+++ b/AddOns/!!!ClassicAPI/Util/ActionButton.lua
@@ -0,0 +1,98 @@
+-- ActionButtonUseKeyDown: action-bar key bindings act on the key press when
+-- the cvar is set, on the release otherwise -- 4.3.4's FrameXML handlers
+-- (ActionButton.lua, MultiActionBars.lua, PetActionBarFrame.lua). Each keeps
+-- 1.12's own body; 4.3.4 adds only the cvar test: the press always shows the
+-- button pushed and acts when the cvar is set, the release shows it normal
+-- and acts when it is not. The engine registers the cvar (default 0, so the
+-- release stays the default).
+
+local GetCVarBool = ClassicAPI.C_CVar.GetCVarBool;
+
+local function UseKeyDown()
+ return GetCVarBool("ActionButtonUseKeyDown");
+end
+
+-- 1.12's ActionButtonUp / MultiActionButtonUp body.
+local function UseActionButton(button, onSelf)
+ if ( MacroFrame_SaveMacro ) then
+ MacroFrame_SaveMacro();
+ end
+ UseAction(ActionButton_GetPagedID(button), 0, onSelf);
+ if ( IsCurrentAction(ActionButton_GetPagedID(button)) ) then
+ button:SetChecked(1);
+ else
+ button:SetChecked(0);
+ end
+end
+
+local function MainBarButton(id)
+ if ( BonusActionBarFrame:IsShown() ) then
+ return getglobal("BonusActionButton"..id), true;
+ end
+ return getglobal("ActionButton"..id), false;
+end
+
+function ActionButtonDown(id)
+ local button = MainBarButton(id);
+ if ( button:GetButtonState() == "NORMAL" ) then
+ button:SetButtonState("PUSHED");
+ end
+ if ( UseKeyDown() ) then
+ UseActionButton(button);
+ end
+end
+
+function ActionButtonUp(id, onSelf)
+ local button, bonus = MainBarButton(id);
+ if ( button:GetButtonState() == "PUSHED" ) then
+ button:SetButtonState("NORMAL");
+ if ( not UseKeyDown() ) then
+ -- 1.12's bonus-bar branch uses the action without onSelf.
+ if ( bonus ) then
+ UseActionButton(button);
+ else
+ UseActionButton(button, onSelf);
+ end
+ end
+ end
+end
+
+function MultiActionButtonDown(bar, id)
+ local button = getglobal(bar.."Button"..id);
+ if ( button:GetButtonState() == "NORMAL" ) then
+ button:SetButtonState("PUSHED");
+ end
+ if ( UseKeyDown() ) then
+ UseActionButton(button);
+ end
+end
+
+function MultiActionButtonUp(bar, id, onSelf)
+ local button = getglobal(bar.."Button"..id);
+ if ( button:GetButtonState() == "PUSHED" ) then
+ button:SetButtonState("NORMAL");
+ if ( not UseKeyDown() ) then
+ UseActionButton(button, onSelf);
+ end
+ end
+end
+
+function PetActionButtonDown(id)
+ local button = getglobal("PetActionButton"..id);
+ if ( button:GetButtonState() == "NORMAL" ) then
+ button:SetButtonState("PUSHED");
+ end
+ if ( UseKeyDown() ) then
+ CastPetAction(id);
+ end
+end
+
+function PetActionButtonUp(id)
+ local button = getglobal("PetActionButton"..id);
+ if ( button:GetButtonState() == "PUSHED" ) then
+ button:SetButtonState("NORMAL");
+ if ( not UseKeyDown() ) then
+ CastPetAction(id);
+ end
+ end
+end
diff --git a/AddOns/!!!ClassicAPI/Util/MacroOptions.lua b/AddOns/!!!ClassicAPI/Util/MacroOptions.lua
index f9c53efc..4830d74b 100644
--- a/AddOns/!!!ClassicAPI/Util/MacroOptions.lua
+++ b/AddOns/!!!ClassicAPI/Util/MacroOptions.lua
@@ -218,21 +218,19 @@ CONDITIONS.spec = function(target, args)
return true;
end
+-- [mod:X/Y] passes when any value is a held modified click: a modifier string
+-- ("shift", "lctrl", "alt-shift") or a modified-click action ("SELFCAST"), as
+-- 4.3.4's EvaluateModifier asks IsModifiedClick. Bare [mod] is any of them.
+local IsModifiedClick = ClassicAPI.IsModifiedClick;
+
CONDITIONS.modifier = function(target, args)
if args then
for i = 1, args.n do
- local a = strlower(args[i]);
- if a == "shift" then
- if IsShiftKeyDown() then return true; end
- elseif a == "ctrl" then
- if IsControlKeyDown() then return true; end
- elseif a == "alt" then
- if IsAltKeyDown() then return true; end
- end
+ if IsModifiedClick(args[i]) then return true; end
end
return false;
end
- return IsShiftKeyDown() or IsControlKeyDown() or IsAltKeyDown();
+ return IsModifiedClick() ~= nil;
end
-- [button:N] numbers the mouse buttons the way the rest of the modern API
diff --git a/README.md b/README.md
index f9332b71..975c61b8 100644
--- a/README.md
+++ b/README.md
@@ -62,7 +62,7 @@ reference in **[docs/API.md](docs/API.md)**.
| [AddOns](docs/API.md#addons) | `C_AddOns.DoesAddOnExist`, `C_AddOns.GetAddOnLocalTable`, `C_AddOns.GetAddOnName`, `C_AddOns.GetAddOnNotes`, `C_AddOns.GetAddOnOptionalDependencies`, `C_AddOns.GetAddOnSecurity`, `C_AddOns.GetAddOnTitle`, `C_AddOns.IsAddOnLoadable`, `C_AddOns.IsAddOnLoaded`, `C_AddOns.LoadAddOn` |
| [APIDocumentation](docs/API.md#apidocumentation) | `/classicapi` in-game browser, `C_APIDocumentation.GetSystem`, `C_APIDocumentation.GetSystems` |
| [AuctionHouse](docs/API.md#auctionhouse) | `C_AuctionHouse.PostItem` |
-| [Bindings](docs/API.md#bindings) | `SetBindingSpell`, `SetBindingItem`, `SetBindingMacro`, `SetBindingClick`, `SetOverrideBinding`, `SetOverrideBindingSpell`, `SetOverrideBindingItem`, `SetOverrideBindingMacro`, `SetOverrideBindingClick`, `ClearOverrideBindings` |
+| [Bindings](docs/API.md#bindings) | `SetBindingSpell`, `SetBindingItem`, `SetBindingMacro`, `SetBindingClick`, `SetOverrideBinding`, `SetOverrideBindingSpell`, `SetOverrideBindingItem`, `SetOverrideBindingMacro`, `SetOverrideBindingClick`, `ClearOverrideBindings`, `GetBindingAction` (`checkOverride`), `IsModifiedClick`, `GetModifiedClick`, `SetModifiedClick`, `GetNumModifiedClickActions`, `GetModifiedClickAction`, `ActionButtonUseKeyDown` (cvar) |
| [Chat](docs/API.md#chat) | `GetCurrentChatGUID` |
| [ChatBubbles](docs/API.md#chatbubbles) | `C_ChatBubbles.GetAllChatBubbles` |
| [Class](docs/API.md#class) | `FillLocalizedClassList` |
diff --git a/docs/API.md b/docs/API.md
index bff1fc12..e3e1efa4 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -42,6 +42,14 @@ build instructions.
- [`AuraUtil.FindAuraByName`](#aurautilfindaurabyname)
- [`AuraUtil.UnpackAuraData`](#aurautilunpackauradata)
+- [Bindings](#bindings)
+ - [Direct-action bindings](#direct-action-bindings)
+ - [Modifier keys during a binding](#modifier-keys-during-a-binding)
+ - [Override bindings](#override-bindings)
+ - [`GetBindingAction(key [, checkOverride])`](#getbindingactionkey--checkoverride)
+ - [Modified clicks](#modified-clicks)
+ - [`ActionButtonUseKeyDown`](#actionbuttonusekeydown)
+
- [CharacterList](#characterlist)
- [`GetSavedCharacterOrder(realm)` / `SetSavedCharacterOrder(realm, order)` — GlueXML only](#getsavedcharacterorderrealm--setsavedcharacterorderrealm-order--gluexml-only)
@@ -5438,111 +5446,150 @@ as `"player"` / `"party*"` / `"raid*"` / `"nameplate*"` / `"target"`.
## Bindings
-The direct-action and temporary override binding APIs. The permanent helpers
-write action command strings into the native binding table; the override
-helpers add a separate, session-only layer in front of that table.
+Key bindings that cast a spell, use an item, run a macro or click a button;
+temporary override bindings; and modified clicks.
-### Permanent direct-action bindings
+### Direct-action bindings
-| Function | Equivalent command |
-|----------|--------------------|
-| `ok = SetBindingSpell(key, spell)` | `SetBinding(key, "SPELL " .. spell)` |
-| `ok = SetBindingItem(key, item)` | `SetBinding(key, "ITEM " .. item)` |
-| `ok = SetBindingMacro(key, macroNameOrIndex)` | `SetBinding(key, "MACRO " .. macroNameOrIndex)` |
-| `ok = SetBindingClick(key, buttonName [, mouseButton])` | `SetBinding(key, "CLICK " .. buttonName .. (mouseButton and ":" .. mouseButton or ""))` |
+| Function | Command it binds |
+|----------|------------------|
+| `ok = SetBindingSpell(key, spell)` | `"SPELL " .. spell` |
+| `ok = SetBindingItem(key, item)` | `"ITEM " .. item` |
+| `ok = SetBindingMacro(key, macro)` | `"MACRO " .. macro` |
+| `ok = SetBindingClick(key, buttonName [, mouseButton])` | `"CLICK " .. buttonName .. ":" .. (mouseButton or "LeftButton")` |
-`key` is any binding string accepted by the client, such as `"CTRL-F"`,
-`"SHIFT-BUTTON4"`, or `"F8"`. `spell`, `item`, `macroNameOrIndex`, and
-`buttonName` identify the action to perform. `macroNameOrIndex` accepts either
-a saved macro's name or its decimal index. `mouseButton` is passed to the
-button's click handler and defaults to `"LeftButton"`; when supplied, it is
-stored as the `:MouseButton` suffix of the `CLICK` command.
+Each function binds `key` in the current binding set, as `SetBinding` does.
+It returns `1` when the binding changed, else `nil`, and fires
+`UPDATE_BINDINGS`. Call `SaveBindings` to keep the change.
-Each helper returns `1` if the stock `SetBinding` changed the binding and
-`nil` otherwise. It changes whichever binding set is currently loaded, fires
-the normal `UPDATE_BINDINGS` notification, and is not persisted until
-the addon calls `SaveBindings`. Use `SetBinding(key)` to unbind a key;
-the typed helpers always require an action argument.
+A key bound to one of these commands does this:
-The command hook also understands manually constructed `SPELL`, `ITEM`,
-`MACRO`, and `CLICK` strings passed directly to `SetBinding`.
+| Command | When | What |
+|---------|------|------|
+| `SPELL name` | Key release | Casts the spell from your spellbook. |
+| `ITEM name` | Key release | Uses the item with that name that you carry. |
+| `MACRO macro` | Key release | Runs the macro. A number is a macro index; other text is a macro name. |
+| `CLICK name:button` | Key press and key release | Sends the frame a mouse down on press and a mouse up on release. |
-### Temporary override bindings
+`SPELL` and `ITEM` cast at you when the `SELFCAST` modified click is held,
+and at your focus when `FOCUSCAST` is held. Otherwise they use your target.
+
+For `CLICK`, a button acts as if it was clicked with the mouse. It clicks
+on press when it is registered for any `...Down` click, and on release when
+it is registered for any `...Up` click. Its pushed look, `OnMouseDown`,
+`OnMouseUp`, `PreClick`, `OnClick`, `PostClick` and `OnDoubleClick` all run.
+The cursor does not have to be over the button.
+
+`RunBinding` does not run these four commands.
+
+### Modifier keys during a binding
+
+While a key binding runs, the modifier keys that are part of its key do
+not count as held. For a binding on `ALT-1`:
+
+- `IsAltKeyDown()`, `IsLeftAltKeyDown()` and the other modifier functions
+ return `nil` for ALT.
+- `IsModifiedClick("SELFCAST")` is false when SELFCAST is ALT, so the binding
+ does not cast at you.
+- `[mod:alt]` does not pass.
+
+This applies to every key binding, including ones that run Lua.
+
+### Override bindings
```lua
SetOverrideBinding(owner, isPriority, key [, command])
SetOverrideBindingSpell(owner, isPriority, key, spell)
SetOverrideBindingItem(owner, isPriority, key, item)
-SetOverrideBindingMacro(owner, isPriority, key, macroNameOrIndex)
+SetOverrideBindingMacro(owner, isPriority, key, macro)
SetOverrideBindingClick(owner, isPriority, key, buttonName [, mouseButton])
ClearOverrideBindings(owner)
```
-`owner` must be a frame and `isPriority` must be a Boolean. The typed helpers
-construct the same four action strings shown above. The generic
-`SetOverrideBinding` also accepts ordinary Bindings.xml command names, which
-are delegated to the engine's command executor. Override setters and
-`ClearOverrideBindings` return no values.
+An override binding replaces the saved binding of `key` until it is
+removed. It is never saved.
-Passing no `command` (or `nil`) to `SetOverrideBinding` removes that owner's
-override for `key`. `ClearOverrideBindings(owner)` removes every override
-belonging to that owner. Overrides never change or save the native binding
-table and are cleared whenever the FrameScript Lua state is recreated, such
-as on `/reload` or logout.
+- `owner` must be a frame.
+- `isPriority` is any value. A true value makes a priority override.
+- `key` is matched without regard to case. Write the modifiers in the order
+ the game uses: `ALT-CTRL-SHIFT-X`.
+- A `command` of `nil` or `""` removes the owner's override for `key`.
+- `ClearOverrideBindings(owner)` removes all of the owner's overrides.
-Resolution order is:
+For each key, the newest priority override wins. With no priority override,
+the newest normal override wins. With no override, the saved binding is
+used. When you remove an override, the next one is used again.
-1. Priority override bindings.
-2. Non-priority override bindings.
-3. The normal native binding.
+When no binding matches a key with modifiers, the game tries the key without
+its first modifier. Overrides follow the same rule: with no binding on
+`ALT-SHIFT-1`, an override on `SHIFT-1` is used.
-When multiple owners set the same key at the same priority, the most recently
-set override wins. Removing it immediately reveals the next matching override
-or the unchanged native binding.
+All overrides are removed on `/reload` and logout.
-`key` is matched case-insensitively, and its modifiers are accepted in any
-order: `"ctrl-alt-F"`, `"ALT-CTRL-F"`, and `"Alt-Ctrl-F"` all bind the same
-key. The override layer normalizes the key to the engine's own keypress form
-(`ALT-CTRL-SHIFT-` before the base key) before matching, so the override fires
-regardless of how the caller spelled it.
+### `GetBindingAction(key [, checkOverride])`
-A generic `SetOverrideBinding` command that is an ordinary Bindings.xml command
-runs through the engine's own command executor with the same execution context
-a native keypress establishes, so it behaves like the equivalent permanent
-binding.
+Returns the command bound to `key`. With `checkOverride` true, an override
+binding is returned first when one is active.
-### Action execution
+### Modified clicks
-| Command | Execution path |
-|---------|----------------|
-| `SPELL name` | Calls the stock `CastSpellByName(name)`. The usual `/cast` spell-name syntax is accepted. |
-| `ITEM item` | Calls `C_Item.UseItemByName(item)`, accepting the names, item strings, and item IDs supported by that API. |
-| `MACRO nameOrIndex` | Resolves a saved macro by name or decimal index. An addon-provided `RunMacro` is used when available; otherwise ClassicAPI resolves it with `GetMacroInfo` and dispatches its body through `ChatEdit_ParseText`. |
-| `CLICK ButtonName[:MouseButton]` | Resolves the named global frame and calls its ordinary `:Click(mouseButton)` method. The default is `LeftButton`. |
-
-`SetBindingMacro` and `SetOverrideBindingMacro` take a saved macro identifier,
-not literal macro text. To bind literal macro text, bind a named button whose
-ClassicAPI attributes describe a macro action:
+A modified click is an action that is active while a set of modifier keys,
+and optionally a mouse button, is held.
```lua
-local button = CreateFrame("Button", "MyMacroTextBindingButton")
-button:SetAttribute("type", "macro")
-button:SetAttribute("macrotext", "/say Bound macro text")
-
-SetBindingClick("CTRL-F7", button:GetName())
+IsModifiedClick([action]) -- 1 or nil
+GetModifiedClick(action) -- "ALT", "SHIFT-BUTTON1", "NONE", ...
+SetModifiedClick(action, binding)
+GetNumModifiedClickActions()
+GetModifiedClickAction(index)
```
-### 1.12 compatibility notes
+- `IsModifiedClick(action)` returns `1` when the action's keys are held. It
+ also takes modifier names: `IsModifiedClick("SHIFT")`,
+ `IsModifiedClick("LCTRL")`. With no argument, it returns `1` when any
+ modifier key is held.
+- `SetModifiedClick` changes the current binding set. Call `SaveBindings` to
+ keep the change. `binding` is modifier names joined with `-`, optionally
+ followed by `BUTTON1` to `BUTTON5`, or `"NONE"`. An unknown action or
+ binding raises an error.
+- A `` line in an addon's
+ `Bindings.xml` adds an action.
-- There is no combat lockdown or secure execution. These functions remain
- callable in combat, and `CLICK` invokes the frame's ordinary click path.
-- Direct actions run on key-down. The corresponding key-up is consumed; a
- click binding does not deliver separate mouse-down and mouse-up events.
-- The override layer is not reflected by `GetBindingAction`.
- The `GetBindingAction(key, true)` override query is not backported.
-- Override ownership is explicit. Call `ClearOverrideBindings(owner)` when the
- addon's owner is no longer needed; all remaining overrides are also cleared
- when the Lua state is recreated.
+The actions and their defaults:
+
+| Action | Default |
+|--------|---------|
+| `SELFCAST` | `ALT` |
+| `FOCUSCAST` | `NONE` |
+| `AUTOLOOTTOGGLE` | `SHIFT` |
+| `MAILAUTOLOOTTOGGLE` | `SHIFT` |
+| `STICKYCAMERA` | `CTRL` |
+| `CHATLINK` | `SHIFT-BUTTON1` |
+| `DRESSUP` | `CTRL-BUTTON1` |
+| `SOCKETITEM` | `SHIFT-BUTTON2` |
+| `SPLITSTACK` | `SHIFT` |
+| `PICKUPACTION` | `SHIFT` |
+| `PICKUPITEM` | `SHIFT` |
+| `COMPAREITEMS` | `SHIFT` |
+| `OPENALLBAGS` | `SHIFT` |
+| `QUESTWATCHTOGGLE` | `SHIFT` |
+| `TOKENWATCHTOGGLE` | `SHIFT` |
+| `SHOWITEMFLYOUT` | `ALT` |
+| `SHOWMULTICASTFLYOUT` | `ALT` |
+| `TRADESEARCHADD` | `SHIFT` |
+
+The `[mod:...]` macro condition takes the same values as `IsModifiedClick`:
+`[mod:shift]`, `[mod:lctrl]`, `[mod:SELFCAST]`.
+
+### `ActionButtonUseKeyDown`
+
+A setting for the action-bar key bindings (main bar, side bars, pet bar).
+`1` uses the action when the key is pressed. `0` (the default) uses it when
+the key is released.
+
+```
+/console ActionButtonUseKeyDown 1
+```
### Predefined focus bindings (`FOCUSTARGET` / `TARGETFOCUS`)
diff --git a/src/Game.cpp b/src/Game.cpp
index b72ce37a..58aba8ab 100644
--- a/src/Game.cpp
+++ b/src/Game.cpp
@@ -161,11 +161,8 @@ void *ResolveChecked(void *L, int idx, const uintptr_t *typeIdVars, int count,
Error(L, EngineString(Offsets::STR_FS_THIS_NON_OBJECT));
return nullptr;
}
- auto **vtable = *reinterpret_cast(obj);
- auto IsA = reinterpret_cast(
- vtable[Offsets::OFF_VMT_FRAMESCRIPT_ISA / sizeof(void *)]);
for (int i = 0; i < count; ++i) {
- if (IsA(obj, FrameScriptTypeId(typeIdVars[i])))
+ if (IsA(obj, typeIdVars[i]))
return obj;
}
if (raiseError)
@@ -184,6 +181,13 @@ int FrameScriptTypeId(uintptr_t typeIdVar) {
return typeId;
}
+bool IsA(void *object, uintptr_t typeIdVar) {
+ auto **vtable = *reinterpret_cast(object);
+ auto isA = reinterpret_cast(
+ vtable[Offsets::OFF_VMT_FRAMESCRIPT_ISA / sizeof(void *)]);
+ return isA(object, FrameScriptTypeId(typeIdVar)) != 0;
+}
+
void *ResolveTypedObject(void *L, int idx, uintptr_t typeIdVar, bool raiseError) {
return ResolveChecked(L, idx, &typeIdVar, 1, raiseError);
}
diff --git a/src/Game.h b/src/Game.h
index b29fdc68..555dcf0e 100644
--- a/src/Game.h
+++ b/src/Game.h
@@ -387,6 +387,9 @@ void *ResolveTypedObjectAny(void *L, int idx, const uintptr_t *typeIdVars,
// directly only when calling a type-specific vtable slot.
int FrameScriptTypeId(uintptr_t typeIdVar);
+// The object's `IsA(typeId)` vmethod for a class's `VAR_*_LUA_TYPE_ID`.
+bool IsA(void *object, uintptr_t typeIdVar);
+
// Per-type sugar over `ResolveTypedObject`, so a call site cannot pair a
// method with the wrong class's id. `idx` defaults to the `self` slot.
void *ResolveTooltip(void *L, int idx = 1, bool raiseError = true);
diff --git a/src/Offsets.h b/src/Offsets.h
index 779f5e30..dea1153b 100644
--- a/src/Offsets.h
+++ b/src/Offsets.h
@@ -86,6 +86,63 @@ enum Offsets {
VAR_FRAMESCRIPT_EXEC_CONTEXT = 0x00CEEAC0,
VAR_FRAMESCRIPT_EXEC_CONTEXT_DEPTH = 0x00CEEAC4,
+ // The binding manager — 4.3.4's CGUIBindings, minus its modified clicks.
+ // `*VAR_BINDINGS_MANAGER`, a 0xDC-byte object made by FUN_004B6050 (FrameXML
+ // init FUN_0048FBF0) and destroyed by FUN_004B6100 (UI teardown
+ // FUN_00490BD0), so it is rebuilt on every world load and /reload. Binding
+ // sets as 4.3.4 numbers them: 0 default, 1 account, 2 character, 3 current;
+ // set N's table is at `mgr + 0x30 + N*0x28` (list head at +0x3C).
+ // OFF_BINDINGS_SAVE_SET (+0xD0) is m_saveSet (1 or 2, what
+ // GetCurrentBindingSet returns); +0xD4 the dirty-set mask.
+ VAR_BINDINGS_MANAGER = 0x00B71290,
+ OFF_BINDINGS_SAVE_SET = 0xD0,
+ BINDING_SET_DEFAULT = 0,
+ BINDING_SET_ACCOUNT = 1,
+ BINDING_SET_CHARACTER = 2,
+ BINDING_SET_CURRENT = 3,
+ BINDING_SET_COUNT = 4,
+ // CGUIBindings::Load — `int __thiscall(mgr, const char *path, MD5_CTX *md5,
+ // CStatus *status)`, `ret 0xC` (the caller at 0x00490006 loads ECX from
+ // VAR_BINDINGS_MANAGER; the prologue saves it); a null status means
+ // VAR_BINDINGS_LOAD_STATUS. Reads the file with FUN_FILE_READ, builds a tree
+ // with FUN_XML_TREE_LOAD and loads every root ``; any other node
+ // gets "Unknown node type %s in %s". Called for FrameXML's Bindings.xml
+ // (0x00490018) and for each addon's (FUN_0051F240).
+ FUN_BINDINGS_LOAD_FILE = 0x004B6F70,
+ VAR_BINDINGS_LOAD_STATUS = 0x00B7124C,
+ // CGUIBindings::LoadBindings — `void __fastcall(int set, const char *text)`:
+ // clears the set, then binds every `bind KEY COMMAND` line. Sources:
+ // WTF\DefaultBindings.wtf into set 0 (FUN_004B62B0), then the account /
+ // character binding files into sets 1 / 2 (FUN_004B6240, which finishes
+ // with FUN_004B64B0 — 4.3.4's FinishLoadBindings).
+ FUN_BINDINGS_LOAD_SET = 0x004B6140,
+ // CGUIBindings::SaveBindings — `void __thiscall(mgr, int set, HANDLE file)`,
+ // `ret 8`: writes the set's `bind %s %s\r\n` lines through
+ // FUN_OS_WRITE_FILE. Called by the binding-file writer FUN_004B65B0.
+ FUN_BINDINGS_SAVE_SET = 0x004B6520,
+ // CGUIBindings::CopyBindings — `void __thiscall(mgr, int source, int dest)`,
+ // `ret 8`. Its gate FUN_00494A50(8) always passes (only actions 0, 2, 4,
+ // 10 and 11 are gated). Fires UPDATE_BINDINGS (0x182) when dest is current.
+ FUN_BINDINGS_COPY_SET = 0x004B6310,
+ // CGUIBindings::GetCommandAction for the current set — `const char
+ // *__thiscall(mgr, const char *key)`: the command bound to exactly `key`,
+ // or null. Script_GetBindingAction (FUN_SCRIPT_GET_BINDING_ACTION, which
+ // pushes "" for null) is its only Lua caller.
+ FUN_BINDINGS_GET_COMMAND_ACTION = 0x004B7DA0,
+ FUN_SCRIPT_GET_BINDING_ACTION = 0x004B8120,
+ // CGGameUI::IsKeyDown for the merged modifiers — `int __fastcall(int
+ // which)`: 0 shift, 1 ctrl, 2 alt. IsShiftKeyDown / IsControlKeyDown /
+ // IsAltKeyDown (0x00488590..0x00488600) and the engine's own modifier
+ // reads (edit boxes, world clicks, mouse events, action use) call it.
+ // 4.3.4's version answers from the binding manager's held-modifier mask
+ // while a key binding runs; `Input::Modifier` co-hooks it to do the same.
+ FUN_GAMEUI_IS_KEY_DOWN = 0x0041F8F0,
+ // OsWriteFile — `int __fastcall(HANDLE /*ecx*/, const void *buffer /*edx*/,
+ // uint32_t size, uint32_t *written)`, `ret 8`.
+ FUN_OS_WRITE_FILE = 0x0042A5D0,
+ // " " — the token delimiter LoadBindings splits a `bind` line's key with.
+ VAR_STR_SPACE_DELIM = 0x0082EE00,
+
// GameTooltip script-method prologue helpers (used to resolve self → CFrameScriptObject*).
// Underlying Lua C API names per [[docs/LuaCAPI.md]] are `lua_rawgeti`
// (0x6F3BC0) and `lua_touserdata` (0x6F3740). The Set* method prologue's
@@ -2707,6 +2764,31 @@ enum Offsets {
// Lua stack and tail-calls this, so the engine's parser, setter and error
// text stay in force.
FUN_SCRIPT_BUTTON_REGISTERFORCLICKS = 0x00782490,
+ // CSimpleButton's mouse handlers, Button vtable 0x0081C7F8 (ctor 0x00778733)
+ // slots +0x68 OnLayerMouseDown (0x00779210) / +0x6C OnLayerMouseUp
+ // (0x007792D0), each `__thiscall(button, CMouseEvent *)` over the base
+ // frame's (0x0076BF70 / 0x0076C040: drag, then OnMouseDown / OnMouseUp with
+ // the button name). Same logic as 4.3.4's, minus its `btn` argument (the
+ // virtual click that skips the hit test): a button not disabled clicks on
+ // press when the press bit of the mouse button is in OFF_BUTTON_CLICK_MASK
+ // and the cursor is in the hit rect, then goes pushed unless locked; on
+ // release, a pushed button clicks for the release bit (or double-clicks
+ // when OnDoubleClick is set and the last click is within 300 ms), then
+ // goes normal unless locked. VAR_BUTTON_IN_CLICK is set around the click.
+ OFF_BUTTON_STATE = 0x328, // 0 disabled, 1 normal, 2 pushed
+ OFF_BUTTON_STATE_LOCKED = 0x32C,
+ OFF_BUTTON_CLICK_MASK = 0x330, // press bits low byte, release bits << 8
+ OFF_BUTTON_LAST_CLICK_MS = 0x334,
+ BUTTON_STATE_DISABLED = 0,
+ BUTTON_STATE_NORMAL = 1,
+ BUTTON_STATE_PUSHED = 2,
+ // Button vmethods: Click(mask, 0) — FUN_BUTTON_CLICK — DoubleClick(mask,
+ // 0) and SetButtonState(state, 0).
+ VTBL_BUTTON_CLICK = 0x94,
+ VTBL_BUTTON_DOUBLE_CLICK = 0x98,
+ VTBL_BUTTON_SET_STATE = 0x9C,
+ VAR_BUTTON_IN_CLICK = 0x00CF4DA0,
+ BUTTON_DOUBLE_CLICK_MS = 300,
// Button::SetClickMask — __thiscall(button, mask): writes +0x330. The
// ctors call it with the type default (Button 0x100 = LeftButtonUp;
// hyperlink button 0x500). Reference only.
@@ -2746,6 +2828,8 @@ enum Offsets {
// VAR_*_METHOD_REGISTRY values above.
VAR_GAMETOOLTIP_LUA_TYPE_ID = 0x00C0D414,
VAR_FRAME_LUA_TYPE_ID = 0x00CF0C10,
+ // Button's (Button:RegisterForClicks reads it at 0x00782496).
+ VAR_BUTTON_LUA_TYPE_ID = 0x00CF4D88,
VAR_REGION_LUA_TYPE_ID = 0x00CF0C3C,
VAR_TEXTURE_LUA_TYPE_ID = 0x00CF4CDC,
VAR_FONTSTRING_LUA_TYPE_ID = 0x00CF2CCC,
@@ -9413,6 +9497,12 @@ enum Offsets {
OFF_XML_NODE_CHILD = 0x4,
OFF_XML_NODE_SIBLING = 0x1C,
FUN_XML_NODE_GET_ATTRIBUTE = 0x006F2CF0,
+ // XMLTree_Load — `XMLTree *__fastcall(const char *data, uint32_t size)`,
+ // null when the text does not parse; the root node is `*(XMLNode **)tree`.
+ // XMLTree_Free — `void __fastcall(XMLTree *)`. The bindings loader's own
+ // pair (0x004B6FDE / its exit).
+ FUN_XML_TREE_LOAD = 0x006F2A30,
+ FUN_XML_TREE_FREE = 0x006F2AC0,
// The loaders' status sink (their `status` argument): vtable +0xC is
// `Add(status, level, fmt, ...)` (__cdecl, variadic) — e.g. the frame
// loader's "Couldn't find inherited node: %s" at level 1. Levels as 4.3.4
diff --git a/src/action/UseKeyDown.cpp b/src/action/UseKeyDown.cpp
new file mode 100644
index 00000000..67656798
--- /dev/null
+++ b/src/action/UseKeyDown.cpp
@@ -0,0 +1,33 @@
+// 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 .
+
+// The `ActionButtonUseKeyDown` cvar — registered by 4.3.4's engine
+// (GameUI_CVar.cpp, "Activate the action button on a keydown") and read only
+// by FrameXML's action-button key handlers, which this project's addon ports
+// (Util/ActionButton.lua). The engine half is the registration. The default
+// is 0, keeping 1.12's action buttons firing on key release; 4.3.4 shipped 1.
+
+#include "Game.h"
+#include "cvar/Factory.h"
+
+namespace Action::UseKeyDown {
+
+namespace {
+
+void Register() { CVar::Factory::Register("ActionButtonUseKeyDown", "0"); }
+
+const Game::ModuleAutoRegister _autoreg{&Register};
+
+} // namespace
+
+} // namespace Action::UseKeyDown
diff --git a/src/bindings/Api.cpp b/src/bindings/Api.cpp
index df862ec4..21959f3e 100644
--- a/src/bindings/Api.cpp
+++ b/src/bindings/Api.cpp
@@ -12,391 +12,189 @@
// You should have received a copy of the GNU General Public License along with
// ClassicAPI. If not, see .
-// Backports the direct-action and override binding APIs introduced in 2.0.
-// Normal bindings are stored by vanilla's SetBinding implementation using the
-// later-client SPELL/ITEM/MACRO/CLICK command strings. The resolved-command
-// hook executes those four command families; every native binding command is
-// passed through unchanged.
+// The binding API 4.3.4 has and 1.12 lacks (decomp Ui/UIBindings.cpp,
+// UIBindings_Scripts.cpp):
//
-// Override bindings live in a separate owner-scoped layer in front of the
-// native key lookup. They are deliberately never written to the saved binding
-// table, so clearing an owner immediately reveals the next override or the
-// unchanged native binding underneath it.
+// SetBindingSpell / Item / Macro / Click — "SPELL x" etc. into the
+// current set through the engine's own SetBinding.
+// SetOverrideBinding[Spell / Item / Macro / Click], ClearOverrideBindings
+// — owner-scoped bindings in front of the saved ones, never saved.
+// GetBindingAction(key [, checkOverride]) — sees overrides when asked.
+//
+// Overrides — 4.3.4's OVERRIDEKEYBINDING: per key (case-insensitive), two
+// lists (normal, priority) of {owner, command}; setting an owner's binding
+// unlinks its old one from both and links the new one at the head of its
+// priority's list, so the newest priority binding wins, then the newest
+// normal one. 4.3.4 consults them inside its key lookup, before the saved
+// binding, for every key it tries. 1.12's key dispatch (FUN_BINDING_KEY_DISPATCH)
+// tries two keys — the pressed one, then the pressed one minus its first
+// modifier — so the co-hook tries an override, then the saved binding
+// (FUN_BINDINGS_GET_COMMAND_ACTION), for each in turn, and lets the engine
+// run a saved binding it finds.
+//
+// Around whatever runs, the key-state override (Input::Modifier) hides the
+// matched key's own modifiers, as 4.3.4's ExecKey does. Direct actions
+// (Bindings::Command) run only for a key: the command co-hook acts while the
+// manager's executing flag — set by the key dispatch, not by RunBinding — is
+// up, which is 4.3.4's ExecKey / ExecCommand split.
#include "Game.h"
#include "Offsets.h"
-#include "macro/Execute.h"
+#include "bindings/Command.h"
+#include "input/Modifier.h"
-#include
-#include
#include
#include
+#include
#include
-#include
#include
namespace Bindings::Api {
namespace {
-constexpr const char kSpellPrefix[] = "SPELL ";
-constexpr const char kItemPrefix[] = "ITEM ";
-constexpr const char kMacroPrefix[] = "MACRO ";
-constexpr const char kClickPrefix[] = "CLICK ";
-constexpr const char kDefaultMouseButton[] = "LeftButton";
+using KeyDispatch_t = int(__fastcall *)(void *mgr, void *edx, const char *key, int isDown);
+using CommandExecute_t = int(__fastcall *)(void *mgr, void *edx, const char *cmd, int isDown);
+using GetCommandAction_t = const char *(__thiscall *)(void *mgr, const char *key);
+using ScriptFn_t = int(__fastcall *)(void *L);
+using ToBool_t = int(__fastcall *)(void *L, int idx, int dflt);
-using ScriptSetBinding_t = int(__fastcall *)(void *L);
-using KeyDispatch_t = int(__thiscall *)(void *mgr, const char *key, int isDown);
-using CommandExecute_t = int(__thiscall *)(void *mgr, const char *cmd, int isDown);
+KeyDispatch_t g_keyDispatchOriginal = nullptr;
+CommandExecute_t g_commandExecuteOriginal = nullptr;
-KeyDispatch_t KeyDispatch_o = nullptr;
-CommandExecute_t CommandExecute_o = nullptr;
+// --- override table (OVERRIDEKEYBINDING) ------------------------------------
-enum class CommandType {
- None,
- Spell,
- Item,
- Macro,
- Click,
-};
-
-struct ParsedCommand {
- CommandType type = CommandType::None;
- const char *argument = nullptr;
-};
-
-struct OverrideEntry {
- const void *owner = nullptr;
- std::string key;
+struct Entry {
+ const void *owner;
std::string command;
- bool priority = false;
- uint64_t sequence = 0;
};
-std::vector g_overrides;
-std::unordered_map g_activeOverrides;
-uint64_t g_nextSequence = 0;
+struct OverrideKey {
+ std::string key;
+ std::list lists[2]; // [0] normal, [1] priority; head = newest
+};
-// Normalizes a binding key to the engine's own canonical form so a stored
-// override matches the string FUN_BINDING_KEY_DISPATCH builds at keypress. The
-// engine's key-string builder (FUN_004b6630) always emits modifiers in the
-// fixed order ALT-CTRL-SHIFT- ahead of the base key, regardless of the order
-// the caller passed them; vanilla SetBinding never reorders, so the override
-// layer does it here. Both the store and the lookup run through this, so they
-// stay consistent while also matching the engine's keypress form.
-std::string CanonicalKey(const char *key) {
- std::string result = key ? key : "";
- for (char &character : result) {
- if (character >= 'a' && character <= 'z')
- character = static_cast(character - 'a' + 'A');
+std::vector g_overrides;
+
+OverrideKey *FindKey(const char *key) {
+ for (OverrideKey &entry : g_overrides)
+ if (_stricmp(entry.key.c_str(), key) == 0)
+ return &entry;
+ return nullptr;
+}
+
+// OVERRIDEKEYBINDING::SetOverrideBinding.
+void SetOverride(OverrideKey &binding, const void *owner, bool priority, const char *command) {
+ for (auto &list : binding.lists)
+ list.remove_if([owner](const Entry &entry) { return entry.owner == owner; });
+ if (command != nullptr && *command != '\0')
+ binding.lists[priority ? 1 : 0].push_front(Entry{owner, command});
+}
+
+// OVERRIDEKEYBINDING::GetActiveBinding.
+const char *ActiveOverride(const char *key) {
+ const OverrideKey *binding = FindKey(key);
+ if (binding == nullptr)
+ return nullptr;
+ for (int i = 1; i >= 0; --i)
+ if (!binding->lists[i].empty())
+ return binding->lists[i].front().command.c_str();
+ return nullptr;
+}
+
+// CGUIBindings::SetOverrideBinding.
+void SetOverrideBinding(const void *owner, bool priority, const char *key, const char *command) {
+ OverrideKey *binding = FindKey(key);
+ if (binding == nullptr) {
+ g_overrides.push_back(OverrideKey{key, {}});
+ binding = &g_overrides.back();
}
-
- // Strip the three modifier prefixes in whatever order/repetition they
- // appear, then re-emit them in the engine's fixed order. Prefix-stripping
- // (rather than splitting on '-') keeps the minus base key correct, e.g.
- // "SHIFT--" -> modifier SHIFT + base "-".
- bool alt = false, ctrl = false, shift = false;
- size_t base = 0;
- for (bool matched = true; matched;) {
- matched = false;
- if (result.compare(base, 4, "ALT-") == 0) {
- alt = true;
- base += 4;
- matched = true;
- } else if (result.compare(base, 5, "CTRL-") == 0) {
- ctrl = true;
- base += 5;
- matched = true;
- } else if (result.compare(base, 6, "SHIFT-") == 0) {
- shift = true;
- base += 6;
- matched = true;
- }
- }
-
- if (!alt && !ctrl && !shift)
- return result;
-
- std::string canonical;
- if (alt)
- canonical += "ALT-";
- if (ctrl)
- canonical += "CTRL-";
- if (shift)
- canonical += "SHIFT-";
- canonical += result.substr(base);
-
- return canonical;
+ SetOverride(*binding, owner, priority, command);
}
-std::string MakeCommand(const char *prefix, const char *arg) {
- std::string cmd = prefix;
- cmd += arg;
- return cmd;
+// --- key dispatch -------------------------------------------------------------
+
+void *Manager() { return Game::Read(Offsets::VAR_BINDINGS_MANAGER); }
+
+const char *SavedCommand(void *mgr, const char *key) {
+ return reinterpret_cast(Offsets::FUN_BINDINGS_GET_COMMAND_ACTION)(mgr,
+ key);
}
-std::string MakeClickCommand(const char *btnName, const char *mouseBtn) {
- std::string cmd = MakeCommand(kClickPrefix, btnName);
- if (mouseBtn != nullptr) {
- cmd += ':';
- cmd += mouseBtn;
- }
-
- return cmd;
+int ExecuteCommand(void *mgr, const char *command, int isDown) {
+ if (Command::IsDirectAction(command))
+ return Command::RunKey(command, isDown);
+ return g_commandExecuteOriginal(mgr, nullptr, command, isDown);
}
-ParsedCommand ParseCommand(const char *cmd) {
- if (cmd == nullptr)
- return {};
-
- struct PrefixEntry {
- const char *prefix;
- size_t length;
- CommandType type;
- };
-
- static constexpr PrefixEntry prefixes[] = {
- {kSpellPrefix, sizeof(kSpellPrefix) - 1, CommandType::Spell},
- {kItemPrefix, sizeof(kItemPrefix) - 1, CommandType::Item},
- {kMacroPrefix, sizeof(kMacroPrefix) - 1, CommandType::Macro},
- {kClickPrefix, sizeof(kClickPrefix) - 1, CommandType::Click},
- };
-
- for (const PrefixEntry &entry : prefixes) {
- if (std::strncmp(cmd, entry.prefix, entry.length) == 0)
- return {entry.type, cmd + entry.length};
- }
-
- return {};
-}
-
-bool CallGlobalString(void *L, const char *func, const char *arg) {
- const int top = Game::Lua::GetTop(L);
- if (!Game::Lua::PushGlobalFunction(L, func)) {
- Game::Lua::SetTop(L, top);
- return false;
- }
-
- Game::Lua::PushString(L, arg);
- const bool ok = Game::Lua::PCall(L, 1, 0, 0) == 0;
- Game::Lua::SetTop(L, top);
-
- return ok;
-}
-
-bool CallTableString(void *L, const char *table, const char *func, const char *arg) {
- const int top = Game::Lua::GetTop(L);
-
- Game::Lua::PushString(L, table);
- Game::Lua::GetTable(L, Game::Lua::GLOBALS_INDEX);
- if (Game::Lua::Type(L, -1) != Game::Lua::TYPE_TABLE) {
- Game::Lua::SetTop(L, top);
- return false;
- }
-
- const int tableIndex = Game::Lua::GetTop(L);
-
- Game::Lua::PushString(L, func);
- Game::Lua::GetTable(L, tableIndex);
- if (Game::Lua::Type(L, -1) != Game::Lua::TYPE_FUNCTION) {
- Game::Lua::SetTop(L, top);
- return false;
- }
-
- Game::Lua::PushString(L, arg);
- const bool ok = Game::Lua::PCall(L, 1, 0, 0) == 0;
- Game::Lua::SetTop(L, top);
-
- return ok;
-}
-
-void InvokeButtonClick(void *L, const char *btnName, size_t btnNameLength, const char *mouseBtn) {
- const int top = Game::Lua::GetTop(L);
-
- Game::Lua::PushLString(L, btnName, static_cast(btnNameLength));
- Game::Lua::GetTable(L, Game::Lua::GLOBALS_INDEX);
- if (Game::Lua::Type(L, -1) != Game::Lua::TYPE_TABLE) {
- Game::Lua::SetTop(L, top);
- return;
- }
-
- const int frameIndex = Game::Lua::GetTop(L);
- Game::Lua::PushString(L, "Click");
- Game::Lua::GetTable(L, frameIndex);
- if (Game::Lua::Type(L, -1) == Game::Lua::TYPE_FUNCTION) {
- Game::Lua::PushValue(L, frameIndex);
- Game::Lua::PushString(L, mouseBtn);
- Game::Lua::PCall(L, 2, 0, 0);
- }
-
- Game::Lua::SetTop(L, top);
-}
-
-void ExecuteClick(void *L, const char *arg) {
- const char *separator = std::strrchr(arg, ':');
- if (separator == arg || (separator != nullptr && separator[1] == '\0'))
- return;
-
- const char *mouseBtn = kDefaultMouseButton;
- size_t btnNameLength = std::strlen(arg);
- if (separator != nullptr) {
- btnNameLength = static_cast(separator - arg);
- mouseBtn = separator + 1;
- }
-
- if (btnNameLength == 0)
- return;
-
- InvokeButtonClick(L, arg, btnNameLength, mouseBtn);
-}
-
-// Returns true for every recognized direct-action command, including malformed
-// or stale commands. Vanilla cannot execute these namespaces, so a bad command
-// is consumed as a no-op instead of falling through to an unrelated handler.
-bool ExecuteSpecialCommand(const char *cmd, int isDown) {
- const ParsedCommand parsed = ParseCommand(cmd);
- if (parsed.type == CommandType::None)
- return false;
-
- if (!isDown || parsed.argument == nullptr || *parsed.argument == '\0')
- return true;
-
- void *L = Game::Lua::State();
- if (L == nullptr)
- return true;
-
- switch (parsed.type) {
- case CommandType::Spell:
- CallGlobalString(L, "CastSpellByName", parsed.argument);
- break;
- case CommandType::Item:
- CallTableString(L, "C_Item", "UseItemByName", parsed.argument);
- break;
- case CommandType::Macro:
- Macro::Execute::Saved(L, parsed.argument);
- break;
- case CommandType::Click:
- ExecuteClick(L, parsed.argument);
- break;
- default:
- break;
- }
-
- return true;
-}
-
-const OverrideEntry *FindEffectiveOverride(const std::string &key) {
- const OverrideEntry *best = nullptr;
- for (const OverrideEntry &entry : g_overrides) {
- if (entry.key != key)
- continue;
-
- if (best == nullptr || entry.priority > best->priority ||
- (entry.priority == best->priority && entry.sequence > best->sequence))
- best = &entry;
- }
-
- return best;
-}
-
-void SetOverride(const void *owner, bool priority, const std::string &key, const std::string &cmd) {
- auto existing =
- std::find_if(g_overrides.begin(), g_overrides.end(),
- [&](const OverrideEntry &entry) {
- return entry.owner == owner && entry.key == key;
- });
-
- if (existing == g_overrides.end()) {
- g_overrides.push_back(
- {owner, key, cmd, priority, ++g_nextSequence});
- return;
- }
-
- existing->command = cmd;
- existing->priority = priority;
- existing->sequence = ++g_nextSequence;
-}
-
-void RemoveOverride(const void *owner, const std::string &key) {
- g_overrides.erase(std::remove_if(g_overrides.begin(), g_overrides.end(),
- [&](const OverrideEntry &entry) {
- return entry.owner == owner &&
- entry.key == key;
- }),
- g_overrides.end());
-}
-
-int ExecuteCommand(void *mgr, const char *cmd, int isDown) {
- if (ExecuteSpecialCommand(cmd, isDown))
- return 1;
-
- return CommandExecute_o(mgr, cmd, isDown);
-}
-
-int __fastcall CommandExecute_h(void *mgr, void *, const char *cmd, int isDown) {
- return ExecuteCommand(mgr, cmd, isDown);
-}
-
-// Runs an override-resolved command with the same execution context the engine
-// wraps around a native keypress. FUN_BINDING_KEY_DISPATCH saves the frame-
-// script exec-context, zeroes it for the nested command, marks the manager as
-// mid-command (`+0xD8`), then restores the context and floors the nesting
-// depth. Native-table bindings already run inside this (the engine sets it up
-// before calling FUN_BINDING_COMMAND_EXECUTE, which we co-hook); overrides
-// bypass that path, so we mirror it here. Without it, a native Bindings.xml
-// command dispatched through an override would run without the context its
-// handler expects. Special SPELL/ITEM/MACRO/CLICK commands run harmlessly
-// inside the same wrapper.
-int DispatchOverrideCommand(void *mgr, const char *cmd, int isDown) {
- volatile uint32_t *context =
- reinterpret_cast(Offsets::VAR_FRAMESCRIPT_EXEC_CONTEXT);
- volatile uint32_t *depth = reinterpret_cast(
- Offsets::VAR_FRAMESCRIPT_EXEC_CONTEXT_DEPTH);
- volatile uint32_t *executing =
- Game::Ptr(mgr, Offsets::OFF_BINDING_MANAGER_EXECUTING);
-
- const uint32_t savedContext = *context;
- *depth = *depth + 1;
- if (*depth != 0)
- *context = 0;
-
- *executing = 1;
- const int result = ExecuteCommand(mgr, cmd, isDown);
- *executing = 0;
-
- if (*depth != 0)
- *context = savedContext;
- if (static_cast(*depth) - 1 > 0)
- *depth = *depth - 1;
- else
- *depth = 0;
-
+// An override's command, run in the frame the engine dispatch gives a saved
+// one: exec context saved and cleared, depth bumped, the manager's executing
+// flag up (FUN_BINDING_KEY_DISPATCH, see Offsets.h).
+int RunOverride(void *mgr, const char *command, int isDown) {
+ const std::string copy = command; // the command may clear its own override
+ auto &context = Game::Ref(Offsets::VAR_FRAMESCRIPT_EXEC_CONTEXT);
+ auto &depth = Game::Ref(Offsets::VAR_FRAMESCRIPT_EXEC_CONTEXT_DEPTH);
+ auto &executing = Game::Ref(mgr, Offsets::OFF_BINDING_MANAGER_EXECUTING);
+ const uint32_t saved = context;
+ if (++depth != 0)
+ context = 0;
+ executing = 1;
+ const int result = ExecuteCommand(mgr, copy.c_str(), isDown);
+ executing = 0;
+ if (depth != 0)
+ context = saved;
+ depth = depth - 1 > 0 ? depth - 1 : 0;
return result;
}
-int __fastcall KeyDispatch_h(void *mgr, void *, const char *key, int isDown) {
- const std::string canonicalKey = CanonicalKey(key);
+int __fastcall KeyDispatch_h(void *mgr, void *edx, const char *key, int isDown) {
+ if (key == nullptr || *key == '\0')
+ return g_keyDispatchOriginal(mgr, edx, key, isDown);
- // Keep a key-down paired with its override command even if that override is
- // cleared while the command executes. The newly revealed native binding
- // must not receive only the key-up half of the same physical press.
- if (!isDown) {
- auto active = g_activeOverrides.find(canonicalKey);
- if (active != g_activeOverrides.end()) {
- DispatchOverrideCommand(mgr, active->second.c_str(), 0);
- g_activeOverrides.erase(active);
- return 1;
+ // The engine's two keys: as pressed, then without its first modifier.
+ const char *dash = std::strchr(key, '-');
+ const char *candidates[2] = {key, (dash != nullptr && dash[1] != '\0') ? dash + 1 : nullptr};
+ for (const char *candidate : candidates) {
+ if (candidate == nullptr)
+ break;
+ if (const char *command = ActiveOverride(candidate)) {
+ const Input::Modifier::KeyStateOverride keyState(candidate);
+ return RunOverride(mgr, command, isDown);
+ }
+ if (SavedCommand(mgr, candidate) != nullptr) {
+ const Input::Modifier::KeyStateOverride keyState(candidate);
+ return g_keyDispatchOriginal(mgr, edx, key, isDown);
}
}
+ return g_keyDispatchOriginal(mgr, edx, key, isDown);
+}
- const OverrideEntry *entry = FindEffectiveOverride(canonicalKey);
- if (entry == nullptr)
- return KeyDispatch_o(mgr, key, isDown);
+// Direct actions only for a key (executing flag up); RunBinding reaches the
+// engine's command table, which has none of them — as in 4.3.4.
+int __fastcall CommandExecute_h(void *mgr, void *edx, const char *command, int isDown) {
+ if (Game::Read(mgr, Offsets::OFF_BINDING_MANAGER_EXECUTING) != 0 &&
+ Command::IsDirectAction(command))
+ return Command::RunKey(command, isDown);
+ return g_commandExecuteOriginal(mgr, edx, command, isDown);
+}
- if (isDown)
- g_activeOverrides[canonicalKey] = entry->command;
+// --- Lua ----------------------------------------------------------------------
- return DispatchOverrideCommand(mgr, entry->command.c_str(), isDown);
+bool LooseBool(void *L, int idx) {
+ return reinterpret_cast(Offsets::FUN_LUA_TO_BOOLEAN_LOOSE)(L, idx, 0) != 0;
+}
+
+const char *OptString(void *L, int idx) {
+ return Game::Lua::IsString(L, idx) ? Game::Lua::ToString(L, idx) : nullptr;
+}
+
+// SetBinding(key, command) through the engine's own Script_SetBinding: its
+// key normalization, current-set write, UPDATE_BINDINGS and 1/nil result.
+int SetBinding(void *L, const std::string &key, const std::string &command) {
+ Game::Lua::SetTop(L, 0);
+ Game::Lua::PushString(L, key.c_str());
+ Game::Lua::PushString(L, command.c_str());
+ return reinterpret_cast(Offsets::FUN_SCRIPT_SET_BINDING)(L);
}
int SetBindingCommand(void *L, const char *prefix, const char *usage) {
@@ -404,216 +202,136 @@ int SetBindingCommand(void *L, const char *prefix, const char *usage) {
Game::Lua::Error(L, usage);
return 0;
}
-
- const std::string key = Game::Lua::ToString(L, 1);
- const std::string command = MakeCommand(prefix, Game::Lua::ToString(L, 2));
-
- // Preserve the stock SetBinding return value, binding-set selection,
- // key normalization, UPDATE_BINDINGS event, and SaveBindings behavior.
- Game::Lua::SetTop(L, 0);
- Game::Lua::PushString(L, key.c_str());
- Game::Lua::PushString(L, command.c_str());
- auto setBinding =
- reinterpret_cast(Offsets::FUN_SCRIPT_SET_BINDING);
-
- return setBinding(L);
-}
-
-const char *OptionalMouseButton(void *L, int index, const char *usage) {
- if (Game::Lua::GetTop(L) < index || Game::Lua::Type(L, index) == Game::Lua::TYPE_NIL)
- return nullptr;
-
- if (!Game::Lua::IsString(L, index)) {
- Game::Lua::Error(L, usage);
- return nullptr;
- }
-
- return Game::Lua::ToString(L, index);
+ return SetBinding(L, Game::Lua::ToString(L, 1),
+ std::string(prefix) + Game::Lua::ToString(L, 2));
}
int __fastcall Script_SetBindingSpell(void *L) {
- return SetBindingCommand(L, kSpellPrefix, "Usage: SetBindingSpell(key, spell)");
+ return SetBindingCommand(L, "SPELL ", "Usage: SetBindingSpell(\"KEY\", \"spellname\")");
}
-
int __fastcall Script_SetBindingItem(void *L) {
- return SetBindingCommand(L, kItemPrefix, "Usage: SetBindingItem(key, item)");
+ return SetBindingCommand(L, "ITEM ", "Usage: SetBindingItem(\"KEY\", \"itemname\")");
+}
+int __fastcall Script_SetBindingMacro(void *L) {
+ return SetBindingCommand(L, "MACRO ",
+ "Usage: SetBindingMacro(\"KEY\", \"macroname\"|macroid)");
}
-int __fastcall Script_SetBindingMacro(void *L) {
- return SetBindingCommand(L, kMacroPrefix, "Usage: SetBindingMacro(key, macro)");
+std::string ClickCommand(const char *button, const char *mouseButton) {
+ return std::string("CLICK ") + button + ":" +
+ (mouseButton != nullptr ? mouseButton : "LeftButton");
}
int __fastcall Script_SetBindingClick(void *L) {
- constexpr const char *usage = "Usage: SetBindingClick(key, buttonName [, mouseButton])";
if (!Game::Lua::IsString(L, 1) || !Game::Lua::IsString(L, 2)) {
- Game::Lua::Error(L, usage);
+ Game::Lua::Error(
+ L, "Usage: SetBindingClick(\"KEY\", \"buttonName\"[, \"mouseButton\"])");
return 0;
}
-
- const std::string key = Game::Lua::ToString(L, 1);
- const char *buttonName = Game::Lua::ToString(L, 2);
- const char *mouseButton = OptionalMouseButton(L, 3, usage);
- const std::string command = MakeClickCommand(buttonName, mouseButton);
-
- Game::Lua::SetTop(L, 0);
- Game::Lua::PushString(L, key.c_str());
- Game::Lua::PushString(L, command.c_str());
- auto setBinding =
- reinterpret_cast(Offsets::FUN_SCRIPT_SET_BINDING);
-
- return setBinding(L);
+ return SetBinding(L, Game::Lua::ToString(L, 1),
+ ClickCommand(Game::Lua::ToString(L, 2), OptString(L, 3)));
}
-bool ReadOverrideHeader(void *L, const char *usage, const void **owner,
- bool *priority, std::string *key) {
- *owner = Game::Lua::ResolveObject(L, 1);
- if (*owner == nullptr || Game::Lua::Type(L, 2) != Game::Lua::TYPE_BOOLEAN ||
- !Game::Lua::IsString(L, 3)) {
- Game::Lua::Error(L, usage);
- return false;
- }
+// The owner argument: a frame, as 4.3.4 requires.
+const void *Owner(void *L) { return Game::Lua::ResolveFrame(L, 1, /*raiseError*/ false); }
- *priority = Game::Lua::ToBoolean(L, 2) != 0;
- *key = CanonicalKey(Game::Lua::ToString(L, 3));
- return true;
-}
-
-int SetOverrideBindingCommand(void *L, const char *prefix, const char *usage) {
- const void *owner = nullptr;
- bool priority = false;
-
- std::string key;
- if (!ReadOverrideHeader(L, usage, &owner, &priority, &key))
- return 0;
-
- if (!Game::Lua::IsString(L, 4)) {
- Game::Lua::Error(L, usage);
+int __fastcall Script_SetOverrideBinding(void *L) {
+ const void *owner = Owner(L);
+ if (owner == nullptr || !Game::Lua::IsString(L, 3)) {
+ Game::Lua::Error(L, "Usage: SetOverrideBinding(owner, isPriority, \"KEY\"[, \"COMMAND\"])");
return 0;
}
-
- SetOverride(owner, priority, key,
- MakeCommand(prefix, Game::Lua::ToString(L, 4)));
-
+ SetOverrideBinding(owner, LooseBool(L, 2), Game::Lua::ToString(L, 3), OptString(L, 4));
return 0;
}
-int __fastcall Script_SetOverrideBinding(void *L) {
- constexpr const char *usage = "Usage: SetOverrideBinding(owner, isPriority, key [, command])";
- const void *owner = nullptr;
- bool priority = false;
-
- std::string key;
- if (!ReadOverrideHeader(L, usage, &owner, &priority, &key))
- return 0;
-
- if (Game::Lua::GetTop(L) < 4 ||
- Game::Lua::Type(L, 4) == Game::Lua::TYPE_NIL) {
- RemoveOverride(owner, key);
- return 0;
- }
-
- if (!Game::Lua::IsString(L, 4)) {
+int SetOverrideCommand(void *L, const char *prefix, const char *usage) {
+ const void *owner = Owner(L);
+ if (owner == nullptr || !Game::Lua::IsString(L, 3) || !Game::Lua::IsString(L, 4)) {
Game::Lua::Error(L, usage);
return 0;
}
-
- SetOverride(owner, priority, key, Game::Lua::ToString(L, 4));
+ const std::string command = std::string(prefix) + Game::Lua::ToString(L, 4);
+ SetOverrideBinding(owner, LooseBool(L, 2), Game::Lua::ToString(L, 3), command.c_str());
return 0;
}
int __fastcall Script_SetOverrideBindingSpell(void *L) {
- return SetOverrideBindingCommand(
- L, kSpellPrefix,
- "Usage: SetOverrideBindingSpell(owner, isPriority, key, spell)");
+ return SetOverrideCommand(
+ L, "SPELL ", "Usage: SetOverrideBindingSpell(owner, isPriority, \"KEY\", \"spellname\")");
}
-
int __fastcall Script_SetOverrideBindingItem(void *L) {
- return SetOverrideBindingCommand(
- L, kItemPrefix,
- "Usage: SetOverrideBindingItem(owner, isPriority, key, item)");
+ return SetOverrideCommand(
+ L, "ITEM ", "Usage: SetOverrideBindingItem(owner, isPriority, \"KEY\", \"itemname\")");
}
-
int __fastcall Script_SetOverrideBindingMacro(void *L) {
- return SetOverrideBindingCommand(
- L, kMacroPrefix,
- "Usage: SetOverrideBindingMacro(owner, isPriority, key, macro)");
+ return SetOverrideCommand(
+ L, "MACRO ",
+ "Usage: SetOverrideBindingMacro(owner, isPriority, \"KEY\", \"macroname\"|macroid)");
}
int __fastcall Script_SetOverrideBindingClick(void *L) {
- constexpr const char *usage =
- "Usage: SetOverrideBindingClick(owner, "
- "isPriority, key, buttonName [, mouseButton])";
-
- const void *owner = nullptr;
- bool priority = false;
-
- std::string key;
- if (!ReadOverrideHeader(L, usage, &owner, &priority, &key))
- return 0;
-
- if (!Game::Lua::IsString(L, 4)) {
- Game::Lua::Error(L, usage);
+ const void *owner = Owner(L);
+ if (owner == nullptr || !Game::Lua::IsString(L, 3) || !Game::Lua::IsString(L, 4)) {
+ Game::Lua::Error(L, "Usage: SetOverrideBindingClick(owner, isPriority, \"KEY\", "
+ "\"buttonName\"[, \"mouseButton\"])");
return 0;
}
-
- const char *buttonName = Game::Lua::ToString(L, 4);
- const char *mouseButton = OptionalMouseButton(L, 5, usage);
- SetOverride(owner, priority, key,
- MakeClickCommand(buttonName, mouseButton));
-
+ const std::string command = ClickCommand(Game::Lua::ToString(L, 4), OptString(L, 5));
+ SetOverrideBinding(owner, LooseBool(L, 2), Game::Lua::ToString(L, 3), command.c_str());
return 0;
}
int __fastcall Script_ClearOverrideBindings(void *L) {
- const void *owner = Game::Lua::ResolveObject(L, 1);
+ const void *owner = Owner(L);
if (owner == nullptr) {
Game::Lua::Error(L, "Usage: ClearOverrideBindings(owner)");
return 0;
}
-
- g_overrides.erase(std::remove_if(g_overrides.begin(), g_overrides.end(),
- [&](const OverrideEntry &entry) {
- return entry.owner == owner;
- }),
- g_overrides.end());
+ for (OverrideKey &binding : g_overrides)
+ SetOverride(binding, owner, false, nullptr);
return 0;
}
-void RegisterLuaFunctions() {
- // A fresh FrameScript state makes every owner pointer from the previous
- // state stale. Permanent bindings remain in vanilla's binding table.
- g_overrides.clear();
- g_activeOverrides.clear();
- g_nextSequence = 0;
+// GetBindingAction(key [, checkOverride]): 4.3.4's GetCommandAction checks the
+// override first when asked; the saved binding is the engine's own answer.
+int __fastcall Script_GetBindingAction(void *L) {
+ if (Game::Lua::IsString(L, 1) && LooseBool(L, 2)) {
+ if (const char *command = ActiveOverride(Game::Lua::ToString(L, 1))) {
+ Game::Lua::PushString(L, command);
+ return 1;
+ }
+ }
+ return reinterpret_cast(Offsets::FUN_SCRIPT_GET_BINDING_ACTION)(L);
+}
+void RegisterLuaFunctions() {
Game::Lua::RegisterGlobalFunction("SetBindingSpell", &Script_SetBindingSpell);
Game::Lua::RegisterGlobalFunction("SetBindingItem", &Script_SetBindingItem);
Game::Lua::RegisterGlobalFunction("SetBindingMacro", &Script_SetBindingMacro);
Game::Lua::RegisterGlobalFunction("SetBindingClick", &Script_SetBindingClick);
- Game::Lua::RegisterGlobalFunction("SetOverrideBinding",
- &Script_SetOverrideBinding);
- Game::Lua::RegisterGlobalFunction("SetOverrideBindingSpell",
- &Script_SetOverrideBindingSpell);
- Game::Lua::RegisterGlobalFunction("SetOverrideBindingItem",
- &Script_SetOverrideBindingItem);
- Game::Lua::RegisterGlobalFunction("SetOverrideBindingMacro",
- &Script_SetOverrideBindingMacro);
- Game::Lua::RegisterGlobalFunction("SetOverrideBindingClick",
- &Script_SetOverrideBindingClick);
- Game::Lua::RegisterGlobalFunction("ClearOverrideBindings",
- &Script_ClearOverrideBindings);
+ Game::Lua::RegisterGlobalFunction("SetOverrideBinding", &Script_SetOverrideBinding);
+ Game::Lua::RegisterGlobalFunction("SetOverrideBindingSpell", &Script_SetOverrideBindingSpell);
+ Game::Lua::RegisterGlobalFunction("SetOverrideBindingItem", &Script_SetOverrideBindingItem);
+ Game::Lua::RegisterGlobalFunction("SetOverrideBindingMacro", &Script_SetOverrideBindingMacro);
+ Game::Lua::RegisterGlobalFunction("SetOverrideBindingClick", &Script_SetOverrideBindingClick);
+ Game::Lua::RegisterGlobalFunction("ClearOverrideBindings", &Script_ClearOverrideBindings);
+ Game::Lua::RegisterGlobalFunction("GetBindingAction", &Script_GetBindingAction);
}
const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
-const Game::HookAutoRegister _hookKeyDispatch{
- Offsets::FUN_BINDING_KEY_DISPATCH, reinterpret_cast(&KeyDispatch_h),
- reinterpret_cast(&KeyDispatch_o)};
+// Owners are frames of the Lua state being torn down; their overrides go with it.
+void PrepareForReload() { g_overrides.clear(); }
+const Game::ReloadAutoRegister _reload{&PrepareForReload};
+
+const Game::HookAutoRegister _hookKeyDispatch{Offsets::FUN_BINDING_KEY_DISPATCH,
+ reinterpret_cast(&KeyDispatch_h),
+ reinterpret_cast(&g_keyDispatchOriginal)};
const Game::HookAutoRegister _hookCommandExecute{
- Offsets::FUN_BINDING_COMMAND_EXECUTE,
- reinterpret_cast(&CommandExecute_h),
- reinterpret_cast(&CommandExecute_o)};
+ Offsets::FUN_BINDING_COMMAND_EXECUTE, reinterpret_cast(&CommandExecute_h),
+ reinterpret_cast(&g_commandExecuteOriginal)};
} // namespace
diff --git a/src/bindings/Bindings.xml b/src/bindings/Bindings.xml
index 94b4bbed..5055d7cc 100644
--- a/src/bindings/Bindings.xml
+++ b/src/bindings/Bindings.xml
@@ -15,4 +15,24 @@
C_Loot.LootAllCorpses()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/bindings/Command.cpp b/src/bindings/Command.cpp
new file mode 100644
index 00000000..51d89d45
--- /dev/null
+++ b/src/bindings/Command.cpp
@@ -0,0 +1,252 @@
+// 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 .
+
+// The SPELL / ITEM / MACRO / CLICK binding commands — 4.3.4's
+// CGUIBindings::ExecKey branches (decomp UIBindings.cpp), on 1.12's own
+// primitives:
+//
+// SPELL x on release: the spellbook slot named x (FUN_RESOLVE_SPELL_NAME_TO_SLOT)
+// cast through FUN_SPELL_CAST_DISPATCH at you when SELFCAST is held,
+// at your focus when FOCUSCAST is, else with no explicit target.
+// ITEM x on release: the item named x you carry (equipment, then bags)
+// used through FUN_ITEM_USE with the same target.
+// MACRO x on release: macro index x when x is all digits, else the macro
+// named x, run through FUN_MACRO_RUN_BODY.
+// CLICK f:b press and release: the frame named f gets a mouse down and a
+// mouse up for button b.
+//
+// The release timing is 4.3.4's (and vanilla action buttons'): the command
+// runs when the key comes back up.
+//
+// CLICK: 4.3.4's frames take a `btn` argument on OnLayerMouseDown / Up that
+// marks a virtual click — no hit test, and a button clicks for ANY press
+// (down) or release (up) bit it is registered for. 1.12's take only the mouse
+// event and hit-test it, so the virtual branch is built from the button's own
+// pieces, in 4.3.4's order: the frame's OnMouseDown / OnMouseUp script with
+// the button name, then the Button state machine (click / double-click
+// vmethods, SetButtonState). Only frames that are Buttons get the second part,
+// as only CSimpleButton overrides the handlers 4.3.4 runs.
+
+#include "bindings/Command.h"
+
+#include "Game.h"
+#include "Offsets.h"
+#include "bindings/ModifiedClick.h"
+#include "frame/ClickFrame.h"
+#include "item/Arg.h"
+#include "item/Location.h"
+#include "time/Clock.h"
+#include "unit/Focus.h"
+#include "unit/Identity.h"
+
+#include
+#include
+#include
+
+namespace Bindings::Command {
+
+namespace {
+
+constexpr const char kSpell[] = "SPELL ";
+constexpr const char kItem[] = "ITEM ";
+constexpr const char kMacro[] = "MACRO ";
+constexpr const char kClick[] = "CLICK ";
+
+bool HasPrefix(const char *command, const char *prefix) {
+ return _strnicmp(command, prefix, std::strlen(prefix)) == 0;
+}
+
+// The target 4.3.4 picks for SPELL / ITEM: you for SELFCAST, your focus for
+// FOCUSCAST, else none (the engine then uses your target).
+uint64_t ModifiedTarget() {
+ if (ModifiedClick::IsModifiedClick("SELFCAST"))
+ return Unit::Identity::PlayerGuid();
+ if (ModifiedClick::IsModifiedClick("FOCUSCAST"))
+ return Unit::Focus::Get();
+ return 0;
+}
+
+void CastSpell(const char *name) {
+ using NameToSlot_t = int(__fastcall *)(const char *name, int *outBookType);
+ using CastDispatch_t = void(__fastcall *)(unsigned slot, int bookType, unsigned guidLo,
+ unsigned guidHi);
+ int book = 0;
+ const int slot =
+ reinterpret_cast(Offsets::FUN_RESOLVE_SPELL_NAME_TO_SLOT)(name, &book);
+ if (slot < 0)
+ return;
+ const uint64_t target = ModifiedTarget();
+ reinterpret_cast(Offsets::FUN_SPELL_CAST_DISPATCH)(
+ static_cast(slot), book, static_cast(target),
+ static_cast(target >> 32));
+}
+
+void UseItem(const char *name) {
+ using UseItem_t = unsigned(__thiscall *)(const void *item, const uint64_t *targetGuid,
+ int flag);
+ const Item::Arg::Resolved byName{0, 0, name};
+ Item::Location::ByGUIDResult found{};
+ if (!Item::Location::FindByArgNoLua(byName, &found) || found.item == nullptr)
+ return;
+ const uint64_t target = ModifiedTarget();
+ reinterpret_cast(Offsets::FUN_ITEM_USE)(found.item, &target, 0);
+}
+
+void RunMacro(const char *name) {
+ using SlotToEntry_t = const uint8_t *(__fastcall *)(unsigned slot);
+ using NameToSlot_t = uint32_t(__fastcall *)(const char *name);
+ using RunBody_t = void(__fastcall *)(const uint8_t *entry);
+ const char *digit = name;
+ while (*digit >= '0' && *digit <= '9')
+ ++digit;
+ const uint32_t slot =
+ (*name != '\0' && *digit == '\0')
+ ? static_cast(std::atoi(name) - 1)
+ : reinterpret_cast(Offsets::FUN_MACRO_NAME_TO_SLOT)(name);
+ const uint8_t *entry =
+ reinterpret_cast(Offsets::FUN_MACRO_SLOT_TO_ENTRY)(slot);
+ if (entry != nullptr)
+ reinterpret_cast(Offsets::FUN_MACRO_RUN_BODY)(entry);
+}
+
+// StringToMouseButton: the click mask for a button name, 0 for any other
+// (the click vmethod then names it "UNKNOWN").
+uint32_t MaskForButton(const char *button) {
+ static const struct {
+ uintptr_t name;
+ uint32_t mask;
+ } kButtons[] = {
+ {Offsets::VAR_BUTTON_NAME_LEFT, 0x01}, {Offsets::VAR_BUTTON_NAME_RIGHT, 0x04},
+ {Offsets::VAR_BUTTON_NAME_MIDDLE, 0x02}, {Offsets::VAR_BUTTON_NAME_4, 0x08},
+ {Offsets::VAR_BUTTON_NAME_5, 0x10},
+ };
+ for (const auto &entry : kButtons)
+ if (_stricmp(reinterpret_cast(entry.name), button) == 0)
+ return entry.mask;
+ return 0;
+}
+
+// The frame's OnMouseDown / OnMouseUp, fired as the engine fires them.
+void FireMouseScript(void *frame, uintptr_t slotOffset, const char *button) {
+ using FireVariadic_t = void(__cdecl *)(void *frame, uint32_t *slotPtr, const char *fmt, ...);
+ uint32_t *slot = Game::Ptr(frame, slotOffset);
+ if (slot[0] == 0)
+ return;
+ void *L = Game::Lua::State();
+ const int top = L != nullptr ? Game::Lua::GetTop(L) : 0;
+ reinterpret_cast(Offsets::FUN_FRAME_RUN_SCRIPT_VARIADIC)(
+ frame, slot, reinterpret_cast(Offsets::VAR_SCRIPT_FMT_S), button);
+ if (L != nullptr)
+ Game::Lua::SetTop(L, top);
+}
+
+using ButtonMethod_t = void(__thiscall *)(void *button, uint32_t arg, int flag);
+
+void CallButton(void *button, uintptr_t slot, uint32_t arg) {
+ auto *vtable = Game::Read(button, 0);
+ reinterpret_cast(vtable[slot / sizeof(uintptr_t)])(button, arg, 0);
+}
+
+int &ButtonState(void *button) { return Game::Ref(button, Offsets::OFF_BUTTON_STATE); }
+bool StateLocked(void *button) {
+ return Game::Read(button, Offsets::OFF_BUTTON_STATE_LOCKED) != 0;
+}
+
+// The button's click under the engine's "in click" flag.
+template void InClick(Fn fn) {
+ auto &flag = Game::Ref(Offsets::VAR_BUTTON_IN_CLICK);
+ flag = 1;
+ fn();
+ flag = 0;
+}
+
+// CSimpleButton::OnLayerMouseDown with a `btn`.
+void VirtualMouseDown(void *frame, const char *button) {
+ FireMouseScript(frame, Offsets::OFF_FRAME_ONMOUSEDOWN_SLOT, button);
+ if (!Game::Lua::IsA(frame, Offsets::VAR_BUTTON_LUA_TYPE_ID) ||
+ ButtonState(frame) == Offsets::BUTTON_STATE_DISABLED)
+ return;
+ if (Game::Read(frame, Offsets::OFF_BUTTON_CLICK_MASK) & 0xFF)
+ InClick([&] { CallButton(frame, Offsets::VTBL_BUTTON_CLICK, MaskForButton(button)); });
+ if (!StateLocked(frame) && ButtonState(frame) != Offsets::BUTTON_STATE_DISABLED)
+ CallButton(frame, Offsets::VTBL_BUTTON_SET_STATE, Offsets::BUTTON_STATE_PUSHED);
+}
+
+// CSimpleButton::OnLayerMouseUp with a `btn`.
+void VirtualMouseUp(void *frame, const char *button) {
+ FireMouseScript(frame, Offsets::OFF_FRAME_ONMOUSEUP_SLOT, button);
+ if (!Game::Lua::IsA(frame, Offsets::VAR_BUTTON_LUA_TYPE_ID) ||
+ ButtonState(frame) != Offsets::BUTTON_STATE_PUSHED)
+ return;
+ if (Game::Read(frame, Offsets::OFF_BUTTON_CLICK_MASK) & 0xFF00) {
+ InClick([&] {
+ const uint32_t now = Time::Clock::NowMs();
+ auto &last = Game::Ref(frame, Offsets::OFF_BUTTON_LAST_CLICK_MS);
+ const uint32_t mask = MaskForButton(button);
+ if (Game::Read(frame, Offsets::OFF_BUTTON_ONDOUBLECLICK_HANDLER) != 0 &&
+ last != 0 && Time::Clock::Elapsed(last, now) <= Offsets::BUTTON_DOUBLE_CLICK_MS) {
+ CallButton(frame, Offsets::VTBL_BUTTON_DOUBLE_CLICK, mask);
+ last = 0;
+ } else {
+ CallButton(frame, Offsets::VTBL_BUTTON_CLICK, mask);
+ last = now;
+ }
+ });
+ }
+ if (!StateLocked(frame) && ButtonState(frame) != Offsets::BUTTON_STATE_DISABLED)
+ CallButton(frame, Offsets::VTBL_BUTTON_SET_STATE, Offsets::BUTTON_STATE_NORMAL);
+}
+
+int Click(const char *target, int isDown) {
+ const char *separator = std::strchr(target, ':');
+ if (separator == nullptr)
+ return 0;
+ void *frame = Frame::ClickFrame::Find(Game::Lua::State(), target,
+ static_cast(separator - target));
+ if (frame == nullptr || frame == Game::Read(Offsets::VAR_GAME_STATE_PTR))
+ return 0; // no such frame, or the world frame
+ const char *button = separator + 1;
+ if (isDown)
+ VirtualMouseDown(frame, button);
+ else
+ VirtualMouseUp(frame, button);
+ return 1;
+}
+
+} // namespace
+
+bool IsDirectAction(const char *command) {
+ return command != nullptr && (HasPrefix(command, kSpell) || HasPrefix(command, kItem) ||
+ HasPrefix(command, kMacro) || HasPrefix(command, kClick));
+}
+
+int RunKey(const char *command, int isDown) {
+ if (HasPrefix(command, kSpell)) {
+ if (!isDown)
+ CastSpell(command + sizeof kSpell - 1);
+ return 1;
+ }
+ if (HasPrefix(command, kItem)) {
+ if (!isDown)
+ UseItem(command + sizeof kItem - 1);
+ return 1;
+ }
+ if (HasPrefix(command, kMacro)) {
+ if (!isDown)
+ RunMacro(command + sizeof kMacro - 1);
+ return 1;
+ }
+ return Click(command + sizeof kClick - 1, isDown);
+}
+
+} // namespace Bindings::Command
diff --git a/src/bindings/Command.h b/src/bindings/Command.h
new file mode 100644
index 00000000..804ecdb5
--- /dev/null
+++ b/src/bindings/Command.h
@@ -0,0 +1,29 @@
+// 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 Bindings::Command {
+
+// True for the direct-action command families a key binding can hold:
+// "SPELL x", "ITEM x", "MACRO x", "CLICK frame:button" (case-insensitive
+// prefix, as 4.3.4 tests them).
+bool IsDirectAction(const char *command);
+
+// Runs a direct-action command for a key press or release, as 4.3.4's
+// CGUIBindings::ExecKey does. Returns the engine's handled flag: 1 for SPELL,
+// ITEM and MACRO, 1 for CLICK when the frame exists, else 0. Only call it for
+// IsDirectAction commands.
+int RunKey(const char *command, int isDown);
+
+} // namespace Bindings::Command
diff --git a/src/bindings/ModifiedClick.cpp b/src/bindings/ModifiedClick.cpp
new file mode 100644
index 00000000..fdbcd63a
--- /dev/null
+++ b/src/bindings/ModifiedClick.cpp
@@ -0,0 +1,456 @@
+// 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 .
+
+// Modified clicks — 4.3.4's MODIFIEDCLICK system (decomp Ui/MODIFIEDCLICK.cpp,
+// UIBindings.cpp, UIBindings_Scripts.cpp), which 1.12's binding manager lacks.
+//
+// An action ("SELFCAST", "CHATLINK", …) is bound to a modifier set and/or a
+// mouse button ("ALT", "SHIFT-BUTTON1", "NONE"), once per binding set (0
+// default, 1 account, 2 character, 3 current), exactly like key bindings. 1.12
+// has 4.3.4's binding sets, file format and load / save / copy steps, so each
+// gains the modified-click half 4.3.4 has, through a co-hook on the step:
+//
+// - Load (Bindings.xml): `` defines
+// an action and its default. The engine loader warns on the node it does
+// not know; we register the actions from the same file first.
+// - LoadBindings (a binding file into a set): the set starts from the
+// defaults, then `modifiedclick BINDING ACTION` lines apply.
+// - SaveBindings: `modifiedclick` lines for every action not left at its
+// default.
+// - CopyBindings: the set's bindings are copied with the key bindings.
+//
+// The actions live as long as the binding manager: the engine builds it on
+// every world load and /reload, so the table is cleared with the Lua state.
+// Key state comes from Input::Modifier (the left/right bits 4.3.4's
+// CGGameUI::IsKeyDown reads) and the clicked button from Frame::ClickEvents
+// (4.3.4's CSimpleTop::m_mouseButtonName).
+
+#include "bindings/ModifiedClick.h"
+
+#include "Game.h"
+#include "Offsets.h"
+#include "addons/EngineIO.h"
+#include "frame/ClickEvents.h"
+#include "input/Modifier.h"
+#include "xml/FrameLoad.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+namespace Bindings::ModifiedClick {
+
+namespace {
+
+// 4.3.4's modifier bits, = Input::Modifier's left/right key bits (and what
+// Input::Modifier::ParseModifiers returns).
+constexpr uint32_t kLShift = 0x01, kRShift = 0x02, kLCtrl = 0x04, kRCtrl = 0x08,
+ kLAlt = 0x10, kRAlt = 0x20;
+constexpr int kKeyCount = 6;
+
+// MODIFIEDCLICK_DATA. Flag 1 = the set holds the default (never saved).
+constexpr uint32_t kFlagDefault = 0x1;
+struct Data {
+ uint32_t flags = 0;
+ uint32_t modifiers = 0;
+ const char *button = nullptr;
+};
+
+struct Click {
+ std::string action;
+ Data data[Offsets::BINDING_SET_COUNT];
+};
+
+std::vector g_clicks;
+
+Click *Find(const char *action) {
+ if (action == nullptr)
+ return nullptr;
+ for (Click &click : g_clicks)
+ if (_stricmp(click.action.c_str(), action) == 0)
+ return &click;
+ return nullptr;
+}
+
+bool KeyDown(int key) { return (Input::Modifier::CurrentMask() & (1u << key)) != 0; }
+
+bool PrefixIs(const char *s, const char *prefix) {
+ return _strnicmp(s, prefix, std::strlen(prefix)) == 0;
+}
+
+// CGUIBindings::AddMetaPrefix, appended to `out`.
+void AddMetaPrefix(uint32_t modifiers, std::string &out) {
+ const auto side = [&](uint32_t left, uint32_t right, const char *both, const char *l,
+ const char *r) {
+ if ((modifiers & (left | right)) == (left | right))
+ out += both;
+ else if (modifiers & left)
+ out += l;
+ else if (modifiers & right)
+ out += r;
+ };
+ side(kLAlt, kRAlt, "ALT-", "LALT-", "RALT-");
+ side(kLCtrl, kRCtrl, "CTRL-", "LCTRL-", "RCTRL-");
+ side(kLShift, kRShift, "SHIFT-", "LSHIFT-", "RSHIFT-");
+}
+
+// BUTTONn <-> mouse-button name (IndexToMouseButton / MouseButtonToIndex).
+// 1..5 are the engine's own name literals, the strings GetMouseButtonClicked
+// and the click scope hold.
+const char *const kExtraButtons[] = {"Button6", "Button7", "Button8", "Button9"};
+
+const char *ButtonForIndex(int index) {
+ switch (index) {
+ case 1: return reinterpret_cast(Offsets::VAR_BUTTON_NAME_LEFT);
+ case 2: return reinterpret_cast(Offsets::VAR_BUTTON_NAME_RIGHT);
+ case 3: return reinterpret_cast(Offsets::VAR_BUTTON_NAME_MIDDLE);
+ case 4: return reinterpret_cast(Offsets::VAR_BUTTON_NAME_4);
+ case 5: return reinterpret_cast(Offsets::VAR_BUTTON_NAME_5);
+ case 6: case 7: case 8: case 9: return kExtraButtons[index - 6];
+ default: return nullptr;
+ }
+}
+
+int IndexForButton(const char *button) {
+ for (int index = 1; index <= 9; ++index)
+ if (_stricmp(ButtonForIndex(index), button) == 0)
+ return index;
+ return 0;
+}
+
+// MODIFIEDCLICK::SetBinding.
+bool SetBinding(Click &click, int set, const char *binding) {
+ const char *button = nullptr;
+ uint32_t modifiers = 0;
+ if (binding != nullptr && *binding != '\0' && _stricmp(binding, "NONE") != 0) {
+ modifiers = Input::Modifier::ParseModifiers(binding);
+ if (PrefixIs(binding, "BUTTON")) {
+ binding += 6;
+ button = ButtonForIndex(std::atoi(binding));
+ ++binding;
+ }
+ if (*binding != '\0')
+ return false;
+ }
+ Data &data = click.data[set];
+ if (set != Offsets::BINDING_SET_DEFAULT)
+ data.flags &= ~kFlagDefault;
+ else
+ data.flags |= kFlagDefault;
+ data.button = button;
+ data.modifiers = modifiers;
+ return true;
+}
+
+// MODIFIEDCLICK::GetBinding.
+std::string GetBinding(const Click &click, int set) {
+ const Data &data = click.data[set];
+ if (data.modifiers == 0 && data.button == nullptr)
+ return "NONE";
+ std::string out;
+ AddMetaPrefix(data.modifiers, out);
+ if (data.button != nullptr)
+ out += "BUTTON" + std::to_string(IndexForButton(data.button));
+ else
+ out.pop_back(); // the prefix's trailing '-'
+ return out;
+}
+
+// MODIFIEDCLICK::IsActive.
+bool IsActive(const Click &click, int set) {
+ const Data &data = click.data[set];
+ if (data.modifiers != 0) {
+ int key = 0;
+ while (!((1u << key) & data.modifiers) || !KeyDown(key)) {
+ if (++key >= kKeyCount)
+ return false;
+ }
+ if (data.button == nullptr)
+ return true;
+ } else if (data.button == nullptr) {
+ return false;
+ }
+ const char *current = Frame::ClickEvents::CurrentButton();
+ return current == nullptr || std::strcmp(current, data.button) == 0;
+}
+
+// One side of a modifier test: left only, right only, or either.
+bool SideHeld(uint32_t modifiers, uint32_t left, uint32_t right, int leftKey, int rightKey) {
+ const uint32_t bits = modifiers & (left | right);
+ if (bits == left)
+ return KeyDown(leftKey);
+ if (bits == right || (bits == (left | right) && !KeyDown(leftKey)))
+ return KeyDown(rightKey);
+ return true;
+}
+
+// --- Bindings.xml: ---------------------------
+
+using LoadFile_t = int(__fastcall *)(void *mgr, void *edx, const char *path, void *md5,
+ void *status);
+LoadFile_t g_loadFileOriginal = nullptr;
+
+using TreeLoad_t = void *(__fastcall *)(const char *data, uint32_t size);
+using TreeFree_t = void(__fastcall *)(void *tree);
+
+// CGUIBindings::LoadModifiedClick for every root node of the file.
+void LoadModifiedClicks(const char *path, void *status) {
+ void *data = nullptr;
+ size_t size = 0;
+ if (!reinterpret_cast(Offsets::FUN_FILE_READ)(0, path, &data,
+ &size, 0, 1, 0))
+ return;
+ void *tree = reinterpret_cast(Offsets::FUN_XML_TREE_LOAD)(
+ static_cast(data), static_cast(size));
+ reinterpret_cast(Offsets::FUN_STORM_SMEM_FREE)(data, __FILE__,
+ __LINE__, 0);
+ if (tree == nullptr)
+ return; // the engine loader reports the parse error
+ const void *root = Game::Read(tree, 0);
+ for (const void *node = root ? Xml::FirstChild(root) : nullptr; node != nullptr;
+ node = Xml::NextSibling(node)) {
+ if (!Xml::TagIs(node, "ModifiedClick"))
+ continue;
+ const char *action = Xml::Attr(node, "action");
+ if (action == nullptr || *action == '\0') {
+ Xml::Warn(status, "Found modified click with no action in %s", path);
+ continue;
+ }
+ if (Find(action) != nullptr) {
+ Xml::Warn(status, "Modified click %s is defined more than once in %s", action, path);
+ continue;
+ }
+ g_clicks.push_back(Click{action, {}});
+ const char *binding = Xml::Attr(node, "default");
+ if (binding != nullptr && *binding != '\0')
+ SetBinding(g_clicks.back(), Offsets::BINDING_SET_DEFAULT, binding);
+ }
+ reinterpret_cast(Offsets::FUN_XML_TREE_FREE)(tree);
+}
+
+int __fastcall LoadFile_h(void *mgr, void *edx, const char *path, void *md5, void *status) {
+ if (path != nullptr)
+ LoadModifiedClicks(path, status != nullptr
+ ? status
+ : reinterpret_cast(Offsets::VAR_BINDINGS_LOAD_STATUS));
+ return g_loadFileOriginal(mgr, edx, path, md5, status);
+}
+
+// --- binding files: modifiedclick lines -----------------------------------
+
+using LoadSet_t = void(__fastcall *)(int set, const char *text);
+LoadSet_t g_loadSetOriginal = nullptr;
+
+using Tokenize_t = void(__stdcall *)(const char **cursor, char *out, unsigned outSize,
+ const char *delims, int *outQuoted);
+
+// The modified-click half of 4.3.4's LoadBindings: start from the defaults,
+// then apply `modifiedclick BINDING ACTION` lines.
+void __fastcall LoadSet_h(int set, const char *text) {
+ g_loadSetOriginal(set, text);
+ if (set < 0 || set >= Offsets::BINDING_SET_COUNT)
+ return;
+ if (set != Offsets::BINDING_SET_DEFAULT)
+ for (Click &click : g_clicks)
+ click.data[set] = click.data[Offsets::BINDING_SET_DEFAULT];
+
+ auto tokenize = reinterpret_cast(Offsets::FUN_STORM_STR_TOKENIZE);
+ const char *lineDelims = reinterpret_cast(Offsets::VAR_MACRO_LINE_DELIMS);
+ const char *spaceDelims = reinterpret_cast(Offsets::VAR_STR_SPACE_DELIM);
+ char line[1024];
+ char key[32];
+ const char *cursor = text;
+ while (cursor != nullptr && *cursor != '\0') {
+ tokenize(&cursor, line, sizeof line, lineDelims, nullptr);
+ const char *p = line;
+ while (*p == ' ' || *p == '\t')
+ ++p;
+ if (!PrefixIs(p, "modifiedclick "))
+ continue;
+ const char *action = p + 14;
+ tokenize(&action, key, sizeof key, spaceDelims, nullptr);
+ if (action != nullptr)
+ if (Click *click = Find(action))
+ SetBinding(*click, set, key);
+ }
+}
+
+using SaveSet_t = void(__fastcall *)(void *mgr, void *edx, int set, void *file);
+SaveSet_t g_saveSetOriginal = nullptr;
+
+using WriteFile_t = int(__fastcall *)(void *file, const void *buffer, uint32_t size,
+ uint32_t *written);
+
+void __fastcall SaveSet_h(void *mgr, void *edx, int set, void *file) {
+ g_saveSetOriginal(mgr, edx, set, file);
+ if (set < 0 || set >= Offsets::BINDING_SET_COUNT)
+ return;
+ auto write = reinterpret_cast(Offsets::FUN_OS_WRITE_FILE);
+ for (const Click &click : g_clicks) {
+ if (click.data[set].flags & kFlagDefault)
+ continue;
+ const std::string line =
+ "modifiedclick " + GetBinding(click, set) + " " + click.action + "\r\n";
+ uint32_t written = 0;
+ write(file, line.data(), static_cast(line.size()), &written);
+ }
+}
+
+using CopySet_t = void(__fastcall *)(void *mgr, void *edx, int source, int dest);
+CopySet_t g_copySetOriginal = nullptr;
+
+void __fastcall CopySet_h(void *mgr, void *edx, int source, int dest) {
+ g_copySetOriginal(mgr, edx, source, dest);
+ if (source < 0 || source >= Offsets::BINDING_SET_COUNT || dest < 0 ||
+ dest >= Offsets::BINDING_SET_COUNT)
+ return;
+ for (Click &click : g_clicks)
+ click.data[dest] = click.data[source];
+}
+
+const Game::HookAutoRegister _loadFileHook{Offsets::FUN_BINDINGS_LOAD_FILE,
+ reinterpret_cast(&LoadFile_h),
+ reinterpret_cast(&g_loadFileOriginal)};
+const Game::HookAutoRegister _loadSetHook{Offsets::FUN_BINDINGS_LOAD_SET,
+ reinterpret_cast(&LoadSet_h),
+ reinterpret_cast(&g_loadSetOriginal)};
+const Game::HookAutoRegister _saveSetHook{Offsets::FUN_BINDINGS_SAVE_SET,
+ reinterpret_cast(&SaveSet_h),
+ reinterpret_cast(&g_saveSetOriginal)};
+const Game::HookAutoRegister _copySetHook{Offsets::FUN_BINDINGS_COPY_SET,
+ reinterpret_cast(&CopySet_h),
+ reinterpret_cast(&g_copySetOriginal)};
+
+// The binding manager is rebuilt with every Lua state; so are its actions.
+void PrepareForReload() { g_clicks.clear(); }
+const Game::ReloadAutoRegister _reload{&PrepareForReload};
+
+// --- Lua --------------------------------------------------------------------
+
+int __fastcall Script_GetNumModifiedClickActions(void *L) {
+ Game::Lua::PushNumber(L, static_cast(g_clicks.size()));
+ return 1;
+}
+
+int __fastcall Script_GetModifiedClickAction(void *L) {
+ if (!Game::Lua::IsNumber(L, 1)) {
+ Game::Lua::Error(L, "Usage: GetModifiedClickAction(index)");
+ return 0;
+ }
+ const int index = static_cast(Game::Lua::ToNumber(L, 1)) - 1;
+ Game::Lua::PushString(L, index >= 0 && index < static_cast(g_clicks.size())
+ ? g_clicks[index].action.c_str()
+ : nullptr);
+ return 1;
+}
+
+int __fastcall Script_SetModifiedClick(void *L) {
+ if (!Game::Lua::IsString(L, 1)) {
+ Game::Lua::Error(L, "Usage: SetModifiedClick(\"action\", \"binding\")");
+ return 0;
+ }
+ const char *action = Game::Lua::ToString(L, 1);
+ const char *binding = Game::Lua::IsString(L, 2) ? Game::Lua::ToString(L, 2) : nullptr;
+ Click *click = Find(action);
+ if (click == nullptr || !SetBinding(*click, Offsets::BINDING_SET_CURRENT, binding)) {
+ char message[256];
+ std::snprintf(message, sizeof message,
+ "SetModifiedClick(): Unknown action (%s) or binding (%s)", action,
+ binding != nullptr ? binding : "(null)");
+ Game::Lua::Error(L, "%s", message);
+ }
+ return 0;
+}
+
+int __fastcall Script_GetModifiedClick(void *L) {
+ if (!Game::Lua::IsString(L, 1)) {
+ Game::Lua::Error(L, "Usage: GetModifiedClick(\"action\")");
+ return 0;
+ }
+ const Click *click = Find(Game::Lua::ToString(L, 1));
+ if (click == nullptr) {
+ Game::Lua::PushNil(L);
+ return 1;
+ }
+ Game::Lua::PushString(L, GetBinding(*click, Offsets::BINDING_SET_CURRENT).c_str());
+ return 1;
+}
+
+int __fastcall Script_IsModifiedClick(void *L) {
+ const char *action = Game::Lua::IsString(L, 1) ? Game::Lua::ToString(L, 1) : nullptr;
+ if (IsModifiedClick(action))
+ Game::Lua::PushNumber(L, 1.0);
+ else
+ Game::Lua::PushNil(L);
+ return 1;
+}
+
+const Game::Doc::Field kIndexArgs[] = {Game::Doc::Req("index", "luaIndex")};
+const Game::Doc::Field kActionArgs[] = {Game::Doc::Req("action", "string")};
+const Game::Doc::Field kSetArgs[] = {Game::Doc::Req("action", "string"),
+ Game::Doc::Opt("binding", "string")};
+const Game::Doc::Field kIsArgs[] = {Game::Doc::Opt("action", "string")};
+const Game::Doc::Field kCountRets[] = {Game::Doc::Req("count", "number")};
+const Game::Doc::Field kActionRets[] = {Game::Doc::Opt("action", "string")};
+const Game::Doc::Field kBindingRets[] = {Game::Doc::Opt("binding", "string")};
+const Game::Doc::Field kIsRets[] = {Game::Doc::Opt("isModified", "number")};
+
+const Game::Doc::Function kGetNum{"Returns the number of modified-click actions.", {},
+ kCountRets, "BindingsGlobals"};
+const Game::Doc::Function kGetAction{"Returns the name of the modified-click action at an index.",
+ kIndexArgs, kActionRets, "BindingsGlobals"};
+const Game::Doc::Function kSet{"Sets the modifier keys and mouse button for an action.",
+ kSetArgs, {}, "BindingsGlobals"};
+const Game::Doc::Function kGet{"Returns the modifier keys and mouse button set for an action.",
+ kActionArgs, kBindingRets, "BindingsGlobals"};
+const Game::Doc::Function kIs{"Returns 1 when the keys and mouse button for an action are held.",
+ kIsArgs, kIsRets, "BindingsGlobals"};
+
+void RegisterLuaFunctions() {
+ Game::Lua::RegisterGlobalFunction("GetNumModifiedClickActions",
+ &Script_GetNumModifiedClickActions, &kGetNum);
+ Game::Lua::RegisterGlobalFunction("GetModifiedClickAction", &Script_GetModifiedClickAction,
+ &kGetAction);
+ Game::Lua::RegisterGlobalFunction("SetModifiedClick", &Script_SetModifiedClick, &kSet);
+ Game::Lua::RegisterGlobalFunction("GetModifiedClick", &Script_GetModifiedClick, &kGet);
+ Game::Lua::RegisterGlobalFunction("IsModifiedClick", &Script_IsModifiedClick, &kIs);
+}
+
+const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
+
+} // namespace
+
+bool IsModifiedClick(const char *action) {
+ if (action != nullptr) {
+ const char *rest = action;
+ const uint32_t modifiers = Input::Modifier::ParseModifiers(rest);
+ if (modifiers == 0) {
+ const Click *click = Find(action);
+ return click != nullptr && IsActive(*click, Offsets::BINDING_SET_CURRENT);
+ }
+ return SideHeld(modifiers, kLShift, kRShift, 0, 1) &&
+ SideHeld(modifiers, kLCtrl, kRCtrl, 2, 3) &&
+ SideHeld(modifiers, kLAlt, kRAlt, 4, 5);
+ }
+ if ((Input::Modifier::CurrentMask() & 0x3F) != 0)
+ return true;
+ for (const Click &click : g_clicks)
+ if (IsActive(click, Offsets::BINDING_SET_CURRENT))
+ return true;
+ return false;
+}
+
+} // namespace Bindings::ModifiedClick
diff --git a/src/bindings/ModifiedClick.h b/src/bindings/ModifiedClick.h
new file mode 100644
index 00000000..208d894f
--- /dev/null
+++ b/src/bindings/ModifiedClick.h
@@ -0,0 +1,24 @@
+// 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 Bindings::ModifiedClick {
+
+// 4.3.4's CGUIBindings::IsModifiedClick. `action` null: any modifier key is
+// held or any modified-click action is active. A modifier string ("SHIFT",
+// "LCTRL-ALT"): those keys are held. Otherwise: the named action's binding in
+// the current set is active.
+bool IsModifiedClick(const char *action);
+
+} // namespace Bindings::ModifiedClick
diff --git a/src/frame/ClickEvents.cpp b/src/frame/ClickEvents.cpp
index 9c1f4542..edfa91fd 100644
--- a/src/frame/ClickEvents.cpp
+++ b/src/frame/ClickEvents.cpp
@@ -331,4 +331,6 @@ void PrepareForReload() {
static const Game::ReloadAutoRegister _reloadReg{&PrepareForReload};
+const char *CurrentButton() { return g_clickedButton; }
+
} // namespace Frame::ClickEvents
diff --git a/src/frame/ClickEvents.h b/src/frame/ClickEvents.h
index 73b727bf..d1367050 100644
--- a/src/frame/ClickEvents.h
+++ b/src/frame/ClickEvents.h
@@ -22,4 +22,9 @@ namespace Frame::ClickEvents {
// the other per-reload cleaners.
void PrepareForReload();
+// The button name of the innermost click / mouse dispatch running now (one of
+// the engine's static name literals), or null outside one — what
+// GetMouseButtonClicked returns; 4.3.4's CSimpleTop::m_mouseButtonName.
+const char *CurrentButton();
+
} // namespace Frame::ClickEvents
diff --git a/src/frame/ClickFrame.cpp b/src/frame/ClickFrame.cpp
index 1c90b3f6..7eeba664 100644
--- a/src/frame/ClickFrame.cpp
+++ b/src/frame/ClickFrame.cpp
@@ -38,10 +38,13 @@
// `CFrameScriptObject` subtype, so calling it after `ResolveObject` is
// safe without the RTTI subtype gate `Script_GetName` does first.
+#include "frame/ClickFrame.h"
+
#include "Game.h"
#include "Offsets.h"
#include
+#include
namespace Frame::ClickFrame {
@@ -96,4 +99,25 @@ static void RegisterLuaFunctions() {
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
+void *Find(void *L, const char *name, size_t length) {
+ using namespace Game::Lua;
+ if (L == nullptr || name == nullptr || length == 0)
+ return nullptr;
+ const std::string key(name, length);
+ const int top = GetTop(L);
+ PushString(L, key.c_str());
+ RawGet(L, GLOBALS_INDEX);
+ void *frame = nullptr;
+ if (Type(L, -1) == TYPE_TABLE) {
+ void *obj = ResolveObject(L, -1);
+ if (obj != nullptr && IsA(obj, Offsets::VAR_FRAME_LUA_TYPE_ID)) {
+ const char *objName = ObjectName(obj);
+ if (std::strcmp(objName != nullptr ? objName : "", key.c_str()) == 0)
+ frame = obj;
+ }
+ }
+ SetTop(L, top);
+ return frame;
+}
+
} // namespace Frame::ClickFrame
diff --git a/src/frame/ClickFrame.h b/src/frame/ClickFrame.h
new file mode 100644
index 00000000..79f27f1c
--- /dev/null
+++ b/src/frame/ClickFrame.h
@@ -0,0 +1,26 @@
+// 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
+
+#include
+
+namespace Frame::ClickFrame {
+
+// 4.3.4's GetClickFrame (UIBindings.cpp), for CLICK binding commands: the
+// frame named by the first `length` bytes of `name` — `_G[name]` read raw,
+// a frame, and its own name equal to `name` — or null. Leaves the Lua stack
+// as it found it.
+void *Find(void *L, const char *name, size_t length);
+
+} // namespace Frame::ClickFrame
diff --git a/src/input/Modifier.cpp b/src/input/Modifier.cpp
index 7071459c..f9159e59 100644
--- a/src/input/Modifier.cpp
+++ b/src/input/Modifier.cpp
@@ -14,9 +14,11 @@
#include "input/Modifier.h"
#include "Game.h"
+#include "Offsets.h"
#include "event/Custom.h"
#include
+#include
#include
@@ -81,6 +83,11 @@ constexpr const char *kModifierStateChanged = "MODIFIER_STATE_CHANGED";
const Event::Custom::AutoReserve _reserveModifierStateChanged{kModifierStateChanged};
uint32_t g_modifierMask = 0;
+
+// 4.3.4's m_keyStateOverride / m_heldModifiers (see KeyStateOverride).
+bool g_overrideActive = false;
+uint32_t g_overrideMask = 0;
+
HHOOK g_msgHook = nullptr;
HHOOK g_wndProcHook = nullptr;
@@ -113,17 +120,38 @@ void SetBit(int bitIdx, bool down) {
template
int __fastcall Script_IsKeyDown(void *L) {
- const bool down = (g_modifierMask & (1u << BitIdx)) != 0;
+ const bool down = (CurrentMask() & (1u << BitIdx)) != 0;
PushDown(L, down);
return 1;
}
int __fastcall Script_IsModifierKeyDown(void *L) {
- const bool down = (g_modifierMask & MASK_ANY_MODIFIER) != 0;
+ const bool down = (CurrentMask() & MASK_ANY_MODIFIER) != 0;
PushDown(L, down);
return 1;
}
+// The engine's IsKeyDown for shift / ctrl / alt (0 / 1 / 2) answers from the
+// override while a binding runs, as 4.3.4's does — so IsShiftKeyDown & co. and
+// every engine modifier read agree with the L/R functions above.
+using IsKeyDown_t = int(__fastcall *)(int which);
+IsKeyDown_t g_isKeyDownOriginal = nullptr;
+
+int __fastcall IsKeyDown_h(int which) {
+ if (!g_overrideActive)
+ return g_isKeyDownOriginal(which);
+ static const uint32_t kPairs[3] = {(1u << BIT_LSHIFT) | (1u << BIT_RSHIFT),
+ (1u << BIT_LCTRL) | (1u << BIT_RCTRL),
+ (1u << BIT_LALT) | (1u << BIT_RALT)};
+ if (which < 0 || which > 2)
+ return g_isKeyDownOriginal(which);
+ return (g_overrideMask & kPairs[which]) != 0;
+}
+
+const Game::HookAutoRegister _isKeyDownHook{Offsets::FUN_GAMEUI_IS_KEY_DOWN,
+ reinterpret_cast(&IsKeyDown_h),
+ reinterpret_cast(&g_isKeyDownOriginal)};
+
// Decode the L/R bit position from a key message.
// - `VK_SHIFT` (the merged virtual key the OS sends for either key)
// resolves via `MapVirtualKeyA(scancode, MAPVK_VSC_TO_VK_EX)` —
@@ -244,7 +272,54 @@ const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
} // namespace
uint32_t CurrentMask() {
- return g_modifierMask;
+ return g_overrideActive ? g_overrideMask : g_modifierMask;
+}
+
+uint32_t ParseModifiers(const char *&text) {
+ static const struct {
+ const char *name;
+ uint32_t bits;
+ } kNames[] = {
+ {"LSHIFT", 1u << BIT_LSHIFT},
+ {"RSHIFT", 1u << BIT_RSHIFT},
+ {"SHIFT", (1u << BIT_LSHIFT) | (1u << BIT_RSHIFT)},
+ {"LCTRL", 1u << BIT_LCTRL},
+ {"RCTRL", 1u << BIT_RCTRL},
+ {"CTRL", (1u << BIT_LCTRL) | (1u << BIT_RCTRL)},
+ {"LALT", 1u << BIT_LALT},
+ {"RALT", 1u << BIT_RALT},
+ {"ALT", (1u << BIT_LALT) | (1u << BIT_RALT)},
+ };
+ uint32_t modifiers = 0;
+ while (*text != '\0') {
+ bool matched = false;
+ for (const auto &entry : kNames) {
+ const size_t length = std::strlen(entry.name);
+ if (_strnicmp(text, entry.name, length) == 0) {
+ modifiers |= entry.bits;
+ text += length;
+ matched = true;
+ break;
+ }
+ }
+ if (!matched)
+ break;
+ if (*text == '-')
+ ++text;
+ }
+ return modifiers;
+}
+
+KeyStateOverride::KeyStateOverride(const char *boundKey)
+ : m_wasActive(g_overrideActive), m_previousMask(g_overrideMask) {
+ const char *rest = boundKey != nullptr ? boundKey : "";
+ g_overrideMask = g_modifierMask & ~ParseModifiers(rest);
+ g_overrideActive = true;
+}
+
+KeyStateOverride::~KeyStateOverride() {
+ g_overrideActive = m_wasActive;
+ g_overrideMask = m_previousMask;
}
} // namespace Input::Modifier
diff --git a/src/input/Modifier.h b/src/input/Modifier.h
index f3db4a0a..0b0aa321 100644
--- a/src/input/Modifier.h
+++ b/src/input/Modifier.h
@@ -24,6 +24,32 @@ namespace Input::Modifier {
// evaluator) compare it across ticks to re-evaluate `[mod:...]`
// conditionals the frame a modifier changes, instead of waiting for the
// periodic pass.
+//
+// While a KeyStateOverride is in scope this returns the held mask minus the
+// binding key's own modifiers instead — 4.3.4's CGGameUI::IsKeyDown under
+// CGUIBindings::m_keyStateOverride.
uint32_t CurrentMask();
+// CGUIBindings::AddModifiers: consumes leading modifier names from `text`
+// ("SHIFT", "LCTRL", "RALT", … each optionally followed by '-') and returns
+// their bits. `text` is left at the first character that is not one.
+uint32_t ParseModifiers(const char *&text);
+
+// 4.3.4's key-state override around a key binding's command
+// (CGUIBindings::ExecKey): for its lifetime every modifier read — CurrentMask,
+// the Is*KeyDown functions, and the engine's own IsKeyDown — sees the keys
+// held now minus the modifiers named in `boundKey`, the binding that matched
+// (StripModifiers). Nestable; restores the previous state.
+class KeyStateOverride {
+ public:
+ explicit KeyStateOverride(const char *boundKey);
+ ~KeyStateOverride();
+ KeyStateOverride(const KeyStateOverride &) = delete;
+ KeyStateOverride &operator=(const KeyStateOverride &) = delete;
+
+ private:
+ bool m_wasActive;
+ uint32_t m_previousMask;
+};
+
} // namespace Input::Modifier