diff --git a/README.md b/README.md
index 4ef505af..4bf5cbd6 100644
--- a/README.md
+++ b/README.md
@@ -81,7 +81,7 @@ reference in **[docs/API.md](docs/API.md)**.
| [Expansion](docs/API.md#expansion) | `ClassicExpansionAtLeast`, `ClassicExpansionAtMost`, `GetClassicExpansionLevel` |
| [Faction](docs/API.md#faction) | `C_Reputation.GetFactionDataByID`, `C_Reputation.GetFactionDataByIndex`, `C_Reputation.GetFactionStandings`, `C_Reputation.GetLastStandingChange`, `C_Reputation.GetWatchedFactionData`, `C_Reputation.IsFactionActive`, `C_Reputation.IsFactionActiveByID`, `C_Reputation.IsFactionInactive`, `C_Reputation.SetFactionActive`, `C_Reputation.SetFactionActiveByID`, `C_Reputation.SetFactionInactive`, `C_Reputation.SetFactionInactiveByID`, `C_Reputation.SetSelectedFaction`, `C_Reputation.SetSelectedFactionByID`, `C_Reputation.SetWatchedFactionByID`, `C_Reputation.ToggleFactionAtWar`, `C_Reputation.ToggleFactionAtWarByID`, `GetFactionIDByIndex`, `GetFactionInfoByID`, `GetFactionParentID` |
| [Focus](docs/API.md#focus) | `ClearFocus`, `FocusUnit` |
-| [Frame](docs/API.md#frame) | `region:SetPoint("point")` (one-arg form), `region:SetSize`, `region:GetSize`, `region:IsMouseOver`, `region:GetRect`, `region:IsDragging`, `GetMouseFoci`, `CreateFrame` template lists and `id`, `CreateFrame("Cooldown")`, `cooldown:SetCooldown`, `cooldown:SetReverse`, `cooldown:GetReverse`, `cooldown:SetDrawEdge`, `cooldown:GetDrawEdge`, `frame:SetShown`, `frame:SetClampRectInsets`, `frame:GetClampRectInsets`, `smf:SetHyperlinksEnabled`, `smf:GetHyperlinksEnabled`, `editBox:SetCountInvisibleLetters`, `editBox:IsCountInvisibleLetters`, `fontstring:GetStringHeight`, `fontstring:GetUnboundedStringWidth`, `fontstring:GetWrappedWidth`, `fontstring:GetNumLines`, `fontstring:GetLineHeight`, `fontstring:IsTruncated`, `fontstring:SetMaxLines`, `fontstring:GetMaxLines`, `fontstring:SetFormattedText`, `texture:SetRotation`, `texture:GetRotation`, `texture:SetVertexOffset`, `texture:GetVertexOffset`, `texture:SetColorTexture`, `texture:SetAtlas`, `texture:GetAtlas`, `texture:ResetTexCoord`, `texture:SetSpriteSheetCell`, `texture:SetDesaturation`, `texture:GetDesaturation`, `texture:SetMask`, `frame:CreateMaskTexture`, `texture:AddMaskTexture`, `texture:RemoveMaskTexture`, `texture:GetNumMaskTextures`, `texture:GetMaskTexture`, `fontstring:SetRotation`, `fontstring:GetRotation`, `editBox:SetCursorPosition`, `editBox:GetCursorPosition`, `editBox:GetUTF8CursorPosition`, `editBox:ClearHighlightText`, `editBox:HasFocus`, `editBox:HasText`, `editBox:SetHighlightColor`, `editBox:GetHighlightColor`, `editBox:ClearHistory`, `frame:SetResizeBounds`, `frame:HookScript`, `region:IsProtected`, `region:CanChangeProtectedState`, `frame:CanChangeAttribute`, `frame:AllowAttributeChanges`, `frame:SetPropagateKeyboardInput`, `frame:GetPropagateKeyboardInput`, `frame:SetDontSavePosition`, `frame:GetDontSavePosition`, `frame:GetBoundsRect`, `button:SetNormalFontObject`, `button:GetNormalFontObject`, `frame:IsEventRegistered`, `frame:RegisterUnitEvent`, `frame:GetEffectiveAlpha`, `frame:SetAttribute`, `frame:SetAttributeNoHandler`, `frame:ClearAttribute`, `frame:GetAttribute`, `OnAttributeChanged` (script), `SetModernScriptArgs`, `GetModernScriptArgs`, `PreClick` (script), `PostClick` (script), `button:RegisterForClicks("AnyUp"/"AnyDown")`, `GetClickFrame` |
+| [Frame](docs/API.md#frame) | `region:SetPoint("point")` (one-arg form), `region:SetSize`, `region:GetSize`, `region:IsMouseOver`, `region:GetRect`, `region:IsDragging`, `GetMouseFoci`, `CreateFrame` template lists and `id`, `CreateFrame("Cooldown")`, `cooldown:SetCooldown`, `cooldown:SetReverse`, `cooldown:GetReverse`, `cooldown:SetDrawEdge`, `cooldown:GetDrawEdge`, `frame:SetShown`, `frame:SetClampRectInsets`, `frame:GetClampRectInsets`, `smf:SetHyperlinksEnabled`, `smf:GetHyperlinksEnabled`, `editBox:SetCountInvisibleLetters`, `editBox:IsCountInvisibleLetters`, `fontstring:GetStringHeight`, `fontstring:GetUnboundedStringWidth`, `fontstring:GetWrappedWidth`, `fontstring:GetNumLines`, `fontstring:GetLineHeight`, `fontstring:IsTruncated`, `fontstring:SetMaxLines`, `fontstring:GetMaxLines`, `fontstring:SetFormattedText`, `texture:SetRotation`, `texture:GetRotation`, `texture:SetVertexOffset`, `texture:GetVertexOffset`, `texture:SetColorTexture`, `texture:SetAtlas`, `texture:GetAtlas`, `texture:ResetTexCoord`, `texture:SetSpriteSheetCell`, `texture:SetDesaturation`, `texture:GetDesaturation`, `texture:SetMask`, `frame:CreateMaskTexture`, `texture:AddMaskTexture`, `texture:RemoveMaskTexture`, `texture:GetNumMaskTextures`, `texture:GetMaskTexture`, `fontstring:SetRotation`, `fontstring:GetRotation`, `editBox:SetCursorPosition`, `editBox:GetCursorPosition`, `editBox:GetUTF8CursorPosition`, `editBox:ClearHighlightText`, `editBox:HasFocus`, `editBox:HasText`, `editBox:SetHighlightColor`, `editBox:GetHighlightColor`, `editBox:ClearHistory`, `editBox:Enable`, `editBox:Disable`, `editBox:IsEnabled`, `editBox:IsInIMECompositionMode`, `OnEnable` (script), `OnDisable` (script), `OnCharComposition` (script), `OnTextChanged` `userInput`, `frame:SetResizeBounds`, `frame:HookScript`, `region:IsProtected`, `region:CanChangeProtectedState`, `frame:CanChangeAttribute`, `frame:AllowAttributeChanges`, `frame:SetPropagateKeyboardInput`, `frame:GetPropagateKeyboardInput`, `frame:SetDontSavePosition`, `frame:GetDontSavePosition`, `frame:GetBoundsRect`, `button:SetNormalFontObject`, `button:GetNormalFontObject`, `frame:IsEventRegistered`, `frame:RegisterUnitEvent`, `frame:GetEffectiveAlpha`, `frame:SetAttribute`, `frame:SetAttributeNoHandler`, `frame:ClearAttribute`, `frame:GetAttribute`, `OnAttributeChanged` (script), `SetModernScriptArgs`, `GetModernScriptArgs`, `PreClick` (script), `PostClick` (script), `button:RegisterForClicks("AnyUp"/"AnyDown")`, `GetClickFrame` |
| [FriendList](docs/API.md#friendlist) | `C_FriendList.GetFriendInfo`, `C_FriendList.GetFriendInfoByIndex`, `C_FriendList.GetNumFriends`, `C_FriendList.GetNumOnlineFriends`, `C_FriendList.GetNumWhoResults`, `C_FriendList.GetWhoInfo`, `C_FriendList.IsFriend`, `C_FriendList.IsIgnored`, `C_FriendList.IsIgnoredByGuid`, `C_FriendList.IsWhoQueryPending`, `C_FriendList.SendWhoQueryByName`, `C_FriendList.SetFriendNotes`, `C_FriendList.SetFriendNotesByIndex` |
| [GameObject](docs/API.md#gameobject) | `C_GameObjectInfo.GetGameObjectInfoByID`, `C_GameObjectInfo.RequestLoadGameObjectByID`, `ClosestGameObjectPosition` |
| [Glue](docs/API.md#glue) | `C_Glue.IsOnGlueScreen` |
diff --git a/docs/API.md b/docs/API.md
index 00de991c..71a98893 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -280,6 +280,12 @@ build instructions.
- [`editBox:GetHighlightColor()`](#editboxgethighlightcolor)
- [`editBox:SetCountInvisibleLetters(count)` / `editBox:IsCountInvisibleLetters()`](#editboxsetcountinvisibleletterscount--editboxiscountinvisibleletters)
- [`editBox:ClearHistory()`](#editboxclearhistory)
+ - [`editBox:Enable()` / `editBox:Disable()` / `editBox:IsEnabled()`](#editboxenable--editboxdisable--editboxisenabled)
+ - [`OnEnable` and `OnDisable` (scripts)](#onenable-and-ondisable-scripts)
+ - [`editBox:IsInIMECompositionMode()`](#editboxisinimecompositionmode)
+ - [`OnCharComposition(self, text)` (script)](#oncharcompositionself-text-script)
+ - [`OnTextChanged(self, userInput)` (script)](#ontextchangedself-userinput-script)
+ - [Edit box caret fixes](#edit-box-caret-fixes)
- [`frame:SetResizeBounds(minWidth, minHeight [, maxWidth, maxHeight])`](#framesetresizeboundsminwidth-minheight--maxwidth-maxheight)
- [`frame:SetClampRectInsets(left, right, top, bottom)` / `frame:GetClampRectInsets()`](#framesetclamprectinsetsleft-right-top-bottom--framegetclamprectinsets)
- [`button:SetNormalFontObject(font)` / `button:GetNormalFontObject()`](#buttonsetnormalfontobjectfont--buttongetnormalfontobject)
@@ -6421,6 +6427,64 @@ Removes every line from the up/down input history. The history line limit
(`SetHistoryLines`) stays, so the box keeps recording new lines afterward.
Does nothing when the box has no history.
+### `editBox:Enable()` / `editBox:Disable()` / `editBox:IsEnabled()`
+
+`editBox:Disable()` removes the keyboard focus from the box and runs its
+`OnDisable` script. `editBox:Enable()` runs its `OnEnable` script.
+`editBox:IsEnabled()` returns `true` or `false`.
+
+- A disabled box still gets the focus when the user clicks it, or when you
+ call `editBox:SetFocus()`.
+- Each call runs the script, also when the box is already in that state.
+
+### `OnEnable` and `OnDisable` (scripts)
+
+Every frame can have an `OnEnable` and an `OnDisable` script. Set them with
+`SetScript`, `HookScript`, or in XML. A button runs `OnEnable` when
+`button:Enable()` enables it, and `OnDisable` when `button:Disable()`
+disables it. A button does not run them when its state does not change. An
+edit box runs them from `editBox:Enable()` and `editBox:Disable()`.
+
+```lua
+button:SetScript("OnDisable", function(self) self:SetAlpha(0.5) end)
+button:SetScript("OnEnable", function(self) self:SetAlpha(1) end)
+```
+
+### `editBox:IsInIMECompositionMode()`
+
+Returns `1` while an input method (for example, one for Chinese, Japanese,
+or Korean) composes text in the box. Returns `nil` at other times.
+
+### `OnCharComposition(self, text)` (script)
+
+An edit box runs this script each time an input method changes the text
+that it composes. `text` is the composed text at that time.
+
+### `OnTextChanged(self, userInput)` (script)
+
+The `OnTextChanged` script gets one argument. `userInput` is `true` when the
+user changed the text: by typing, deleting, pasting, with an input method,
+or with `editBox:Insert`. It is `false` when `SetText` or `SetNumber`
+changed the text. Handlers that read globals find the same value in `arg1`.
+
+```lua
+searchBox:SetScript("OnTextChanged", function(self, userInput)
+ if userInput then
+ RunSearch(self:GetText())
+ end
+end)
+```
+
+### Edit box caret fixes
+
+- A text that ends with a color code (`|cffffffff`), or that has a link with
+ no end, does not freeze the client when the user presses Right or Delete.
+ `SetText` can give a box such a text.
+- In a single-line box, the caret moves over `|n` as two characters, as the
+ box shows them.
+- In a right-justified box, a click puts the caret on the correct character
+ when the line has color codes, links, or characters that are not ASCII.
+
### `frame:SetResizeBounds(minWidth, minHeight [, maxWidth, maxHeight])`
A rename of the `SetMinResize` / `SetMaxResize` pair.
diff --git a/src/Offsets.h b/src/Offsets.h
index 24b1cd1a..e0bfdec2 100644
--- a/src/Offsets.h
+++ b/src/Offsets.h
@@ -2935,6 +2935,12 @@ enum Offsets {
BUTTON_STATE_DISABLED = 0,
BUTTON_STATE_NORMAL = 1,
BUTTON_STATE_PUSHED = 2,
+ // CSimpleButton::Enable — `void __thiscall(button, int enable)`, `ret 4`,
+ // vtable+0x90 of the four button-family vtables; Script Enable / Disable
+ // and the constructor reach it, and CheckButton's override 0x00785490
+ // calls it first. Like 4.3.4's, it returns at once when the state would
+ // not change (enable with OFF_BUTTON_STATE nonzero, disable with it 0).
+ FUN_BUTTON_ENABLE = 0x00779160,
// Button vmethods: Click(mask, 0) — FUN_BUTTON_CLICK — DoubleClick(mask,
// 0) and SetButtonState(state, 0).
VTBL_BUTTON_CLICK = 0x94,
@@ -3457,8 +3463,11 @@ enum Offsets {
// on)`, `ret 8`: sets or clears `mask` in OFF_FRAME_FLAGS. Every write of
// the word goes through it (benilla-re ui/layoutcache). Its 14 callers
// pass only 0x1, 0x10, 0x100, 0x200, 0x1000, 0x2000 and 0x4000, so the
- // two 4.3.4 bits below are free in 1.12.
+ // 4.3.4 bits below are free in 1.12.
FUN_FRAME_SET_FRAME_FLAG = 0x0076A3C0,
+ // 4.3.4's disabled bit: CSimpleFrame::RunOnEnableScript sets it for a
+ // disabled Button or EditBox, and EditBox:IsEnabled reads it.
+ FRAME_FLAG_DISABLED = 0x400,
// 4.3.4's SetDontSavePosition bit: its layout-cache writer
// (PlacedFrameCallback) skips a frame that has it.
FRAME_FLAG_DONT_SAVE_POSITION = 0x80000,
@@ -10776,6 +10785,10 @@ enum Offsets {
// cleared by ClearFocus (FUN_0077e410). See the editbox vtable at
// 0x0081c8c0 / FUN_0077e410.
VAR_FOCUSED_EDITBOX = 0x00CF4DC8,
+ // 4.3.4's CSimpleEditBox::ClearKeyboardFocus — `void __thiscall(editbox)`:
+ // when the box holds the focus, runs its focus change (0x0077AF50) and
+ // clears VAR_FOCUSED_EDITBOX. What Script ClearFocus (0x00798F1A) calls.
+ FUN_EDITBOX_CLEAR_FOCUS = 0x0077E410,
// CSimpleEditBox cursor / selection internals (backs EditBox::Methods'
// SetCursorPosition / GetCursorPosition). Verified from the engine's own
@@ -10814,6 +10827,27 @@ enum Offsets {
// (a `|` that starts no code) are visible; the rest are markup - color
// codes, the hyperlink's `|H...|h` and closing `|h` - which it skips.
OFF_EDITBOX_CHAR_CLASS = 0x330,
+ // 4.3.4's CSimpleEditBox::GetNumToLen — `int __thiscall(editbox, int
+ // byteOffset, int steps, int atomic)`, `ret 0xC`: the bytes from
+ // byteOffset that `steps` cursor steps cover (backwards for a negative
+ // count), walking OFF_EDITBOX_CHAR_CLASS. A forward step skips leading
+ // colour (class 0) and link-start (4) tokens, with `atomic` the whole of
+ // a link, then absorbs trailing colour-restore (1) and link-stop (5)
+ // tokens. Every keyboard move and delete goes through it (benilla-re
+ // ui/editboxmarkup "Steps").
+ FUN_EDITBOX_STEP_BYTES = 0x0077BB30,
+ // The visible lines (4.3.4's m_visibleLines): a count at +0x37C and an
+ // array at +0x380 of each line's first byte, the last entry the end. The
+ // hit test 0x0077D0D0 picks line i by the click's y and reads entries i
+ // and i + 1.
+ OFF_EDITBOX_LINE_COUNT = 0x37C,
+ OFF_EDITBOX_LINE_STARTS = 0x380,
+ // The right-justified hit test's conversion (0x0077D29B): it measures how
+ // many glyphs fit from the line's right end, then turns them into bytes
+ // with `FUN_EDITBOX_STEP_BYTES(lineStart, glyphs, 0)` - counted from the
+ // line's start - and takes the index as lineEnd minus that. 4.3.4's
+ // ConvertCoordinateToIndex does the same.
+ CALL_EDITBOX_HIT_RIGHT_STEP = 0x0077D29B,
// SetMaxLetters stores its limit here (Script 0x00799110); the insert
// path FUN_0077BEE0 enforces it after splicing text in: it counts the
// text with FUN_EDITBOX_COUNT_CHARS (calls at 0x0077C09A, 0x0077C0BC,
@@ -10844,6 +10878,61 @@ enum Offsets {
// {size@+0x390, alloc@+0x394, data@+0x398} of {char* text, int exec}
// entries. AddHistoryLine writes at +0x38c and advances modulo +0x388.
OFF_EDITBOX_HISTORY_MAX = 0x388,
+ // 4.3.4's m_imeComposition: nonzero while an input method composes text.
+ // The input-method slot 0x0077AFC0 sets it on composition start (action 1,
+ // 0x0077B0F9) and clears it on end (actions 5 and 6, 0x0077B118), at the
+ // same points as 4.3.4's OnLayerIme; mouse-down reads it (0x0077B81E).
+ OFF_EDITBOX_IME_COMPOSITION = 0x3CC,
+ // 4.3.4's CSimpleEditBox::Insert without its `script` argument —
+ // `void __thiscall(editbox, const char *text, const char *context, int
+ // runScripts, int highlight)`, `ret 0x10`. Script Insert passes (text,
+ // context, 1, 0), SetText's internal (text, context, 0, 0).
+ FUN_EDITBOX_INSERT = 0x0077BEE0,
+ // The input-method slot's insert of the composition string: `call
+ // FUN_EDITBOX_INSERT` with (buffer, 0, 0, 1), where 4.3.4's OnLayerIme
+ // then runs OnCharComposition with the same buffer.
+ CALL_EDITBOX_IME_COMPOSITION_INSERT = 0x0077B097,
+ // Text-change bookkeeping (4.3.4's dirty bit 0x8, OnTextChanged's
+ // `userInput`). FUN_EDITBOX_REBUILD_CHAR_CLASS (4.3.4's UpdateTextInfo,
+ // `void __thiscall(editbox)`) has one caller, FUN_EDITBOX_INSERT's tail
+ // (0x0077C022), so it runs once per insert that went ahead (the insert
+ // returns early for a cursor inside a link or a non-digit in a numeric
+ // box). FUN_EDITBOX_DELETE_RANGE (4.3.4's DeleteSubstring, `void
+ // __thiscall(editbox, int from, int to)`, `ret 8`) is every deletion: the
+ // character deletes (0x0077C2B8, 0x0077C2C8), the selection delete
+ // (0x0077CD7E) and FUN_EDITBOX_CLEAR (`void __thiscall(editbox)`, delete
+ // all, 0x0077C509). SetText's internal 0x0077BE00 clears with
+ // FUN_EDITBOX_CLEAR and inserts with FUN_EDITBOX_INSERT; these are its two
+ // return addresses, the calls 4.3.4 makes with `script` = 1.
+ FUN_EDITBOX_REBUILD_CHAR_CLASS = 0x0077BA90,
+ CALL_EDITBOX_INSERT_REBUILD_CHAR_CLASS = 0x0077C022,
+ // What the rebuild reads: the text (+0x32C), the class table's size in
+ // dwords (+0x344, zeroed first) and OFF_EDITBOX_CHAR_CLASS. It walks the
+ // text with FUN_TEXT_TOKENIZER and a decoder flag word of 0 (0x0077BAD9).
+ OFF_EDITBOX_TEXT = 0x32C,
+ OFF_EDITBOX_CHAR_CLASS_SIZE = 0x344,
+ // The box's own font string - SetMultiLine (0x0077A5C3) sets flag 0x4000
+ // (no |n) in its OFF_FONTSTRING_FLAGS for a single-line box, clears it
+ // for a multi-line one.
+ OFF_EDITBOX_FONTSTRING = 0x328,
+ // A font string's flags (the constructor sets 0x212, 0x00770DD3). Its
+ // measure and draw hand FUN_TEXT_TOKENIZER the decoder flag word built
+ // from them (0x0044D6A9..0x0044D6FC); the escape bits map 0x2000 -> 0x100
+ // (no |c |r), 0x4000 -> 0x200 (no |n), 0x8000 -> 0x400 (no |H |h),
+ // 0x0080 -> 0x800 (none) (benilla-re ui/editboxmarkup "Which escapes are
+ // on").
+ OFF_FONTSTRING_FLAGS = 0x120,
+ FUN_EDITBOX_DELETE_RANGE = 0x0077C510,
+ FUN_EDITBOX_CLEAR = 0x0077C500,
+ RET_EDITBOX_SET_TEXT_CLEAR = 0x0077BE5B,
+ RET_EDITBOX_SET_TEXT_INSERT = 0x0077BE6B,
+ // The edit box's text update 0x0077D3E0 fires OnTextChanged (slot at
+ // OFF_EDITBOX_ONTEXTCHANGED_SLOT) when the text changed, with the 24
+ // bytes at PATCH_EDITBOX_TEXT_CHANGED_FIRE: load the handler, skip when 0,
+ // `push &slot; mov ecx, esi; call 0x00702690` (the no-argument fire),
+ // ending at 0x0077D49D.
+ PATCH_EDITBOX_TEXT_CHANGED_FIRE = 0x0077D485,
+ OFF_EDITBOX_ONTEXTCHANGED_SLOT = 0x418,
// `void __thiscall(editbox, int maxLines)` — the SetHistoryLines internal
// (FUN_0077cd90). Reallocates the history ring to maxLines; maxLines == 0
// frees the whole buffer and zeroes the container. ClearHistory calls it
diff --git a/src/editbox/CharClass.cpp b/src/editbox/CharClass.cpp
new file mode 100644
index 00000000..49c66408
--- /dev/null
+++ b/src/editbox/CharClass.cpp
@@ -0,0 +1,97 @@
+// 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 edit box's class table, read with the escapes its text is drawn with.
+//
+// Every caret move, delete, click and character count walks the class table
+// (OFF_EDITBOX_CHAR_CLASS): one dword per token of the text, built by
+// FUN_EDITBOX_REBUILD_CHAR_CLASS with the engine's tokenizer. The rebuild
+// passes the tokenizer a decoder flag word of 0, so it reads every escape,
+// while the box's font string draws and measures the same text with the
+// decoder flags built from its own flags. Those differ in one case: a
+// single-line box turns |n off (font string flag 0x4000, decoder 0x200).
+// There the table reads "|n" as one line-break token while the box draws the
+// two characters `|` and `n`, so the caret steps over both at once and sits
+// one glyph off after it (benilla-re ui/editboxmarkup "Faults"). 4.3.4 builds
+// its table the same way and has the same fault.
+//
+// The rebuild below is the engine's, with the decoder flag word its font
+// string uses, so the table and the drawn text agree.
+
+#include "Game.h"
+#include "Offsets.h"
+
+#include
+#include
+
+namespace EditBox::CharClass {
+
+namespace {
+
+constexpr uint32_t kClassLinkStart = 4;
+constexpr uint32_t kClassLinkStop = 5;
+constexpr uint32_t kInsideLink = 0x80000000u;
+
+using Tokenize_t = uint32_t(__fastcall *)(const char *text, int *length, uint32_t *color, uint32_t decoderFlags,
+ uint32_t *payload);
+using Rebuild_t = void(__fastcall *)(void *editBox);
+Rebuild_t g_origRebuild = nullptr;
+
+// The escape bits of the decoder flag word a font string builds from its
+// flags (0x0044D6E0, 0x0044D6EA, 0x0044D6F3, 0x0044D6FC).
+uint32_t DecoderEscapeFlags(const void *fontString) {
+ const uint32_t flags = Game::Read(fontString, Offsets::OFF_FONTSTRING_FLAGS);
+ uint32_t decoder = 0;
+ if (flags & 0x2000)
+ decoder |= 0x100;
+ if (flags & 0x4000)
+ decoder |= 0x200;
+ if (flags & 0x8000)
+ decoder |= 0x400;
+ if (flags & 0x0080)
+ decoder |= 0x800;
+ return decoder;
+}
+
+// FUN_EDITBOX_REBUILD_CHAR_CLASS: zero the table, then store at each token's
+// first byte `length | class << 16`, with bit 31 from a link's start through
+// its stop.
+void __fastcall Rebuild_h(void *editBox) {
+ const void *fontString = Game::Read(editBox, Offsets::OFF_EDITBOX_FONTSTRING);
+ const uint32_t decoderFlags = fontString != nullptr ? DecoderEscapeFlags(fontString) : 0;
+ uint32_t *table = Game::Read(editBox, Offsets::OFF_EDITBOX_CHAR_CLASS);
+ const uint32_t size = Game::Read(editBox, Offsets::OFF_EDITBOX_CHAR_CLASS_SIZE);
+ std::memset(table, 0, size * sizeof(uint32_t));
+ const char *text = Game::Read(editBox, Offsets::OFF_EDITBOX_TEXT);
+ uint32_t link = 0;
+ for (uint32_t at = 0; text != nullptr && *text != '\0';) {
+ int length = 0;
+ uint32_t payload = 0;
+ const uint32_t cls =
+ reinterpret_cast(Offsets::FUN_TEXT_TOKENIZER)(text, &length, nullptr, decoderFlags, &payload);
+ if (cls == kClassLinkStart)
+ link |= kInsideLink;
+ table[at] = (static_cast(length) & 0xFFFF) | (cls << 16) | link;
+ at += length;
+ text += length;
+ if (cls == kClassLinkStop)
+ link &= ~kInsideLink;
+ }
+}
+
+const Game::HookAutoRegister _hook{Offsets::FUN_EDITBOX_REBUILD_CHAR_CLASS, reinterpret_cast(&Rebuild_h),
+ reinterpret_cast(&g_origRebuild)};
+
+} // namespace
+
+} // namespace EditBox::CharClass
diff --git a/src/editbox/CursorStep.cpp b/src/editbox/CursorStep.cpp
new file mode 100644
index 00000000..9c276acc
--- /dev/null
+++ b/src/editbox/CursorStep.cpp
@@ -0,0 +1,123 @@
+// 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 .
+
+// Two edit box caret faults in the step from glyphs to bytes.
+//
+// The freeze on a text that ends in markup.
+//
+// FUN_EDITBOX_STEP_BYTES turns cursor steps into bytes. A forward step first
+// skips every leading colour (class 0) and link-start (class 4) token, and
+// with `atomic` (every keyboard move and delete) every token inside a link,
+// until it has consumed a visible one. That loop has no end test. The slot
+// after the last byte holds 0, which reads as a colour token of length 0, so
+// a text whose last token is a colour escape (`|cffffffff`), or that ends
+// inside an unclosed link, makes one Right arrow or Delete spin forever.
+// Typing cannot build such a text (a typed `|` is stored as `||`), but
+// SetText and Insert can (benilla-re ui/editboxmarkup "Faults").
+//
+// 4.3.4's GetNumToLen has the same loop, but its classes start with
+// CODE_INVALIDCODE = 0 for a plain character, so the terminator's 0 is a
+// class the loop does not skip, and the step stops there. This hook replaces
+// the forward branch with the engine's walk plus that stop; a backward step
+// is already bounded by the table's start and runs the engine's own code.
+//
+// The right-justified click. The hit test finds how many glyphs fit between
+// the click and the line's right end, then converts that count to bytes by
+// stepping forward from the line's START and subtracts the result from the
+// line's end. With markup or multibyte characters the first N glyphs of a
+// line and the last N cover different byte counts, so the caret lands on the
+// wrong character (benilla-re ui/editboxmarkup "Faults"; 4.3.4 has the same
+// fault). Its one conversion call is redirected to step back from the line's
+// end instead.
+
+#include "Common.h"
+#include "Game.h"
+#include "Offsets.h"
+
+#include
+
+namespace EditBox::CursorStep {
+
+namespace {
+
+constexpr uint32_t kClassColorOn = 0;
+constexpr uint32_t kClassColorRestore = 1;
+constexpr uint32_t kClassLinkStart = 4;
+constexpr uint32_t kClassLinkStop = 5;
+
+using StepBytes_t = int(__fastcall *)(void *editBox, void *edx, int offset, int steps, int atomic);
+StepBytes_t g_origStepBytes = nullptr;
+
+uint32_t ClassOf(uint32_t info) { return (info >> 16) & 0xFF; }
+uint32_t LengthOf(uint32_t info) { return info & 0xFFFF; }
+
+int __fastcall StepBytes_h(void *editBox, void *edx, int offset, int steps, int atomic) {
+ if (steps <= 0)
+ return g_origStepBytes(editBox, edx, offset, steps, atomic);
+
+ // The engine's forward walk (0x0077BB52..0x0077BBC3), token by token.
+ const uint32_t *info = Game::Read(editBox, Offsets::OFF_EDITBOX_CHAR_CLASS) + offset;
+ const bool linkAtomic = static_cast(atomic) != 0;
+ int bytes = 0;
+ while (steps-- > 0) {
+ if (*info == 0)
+ break;
+ uint32_t token;
+ do {
+ token = *info;
+ bytes += LengthOf(token);
+ info += LengthOf(token);
+ // 4.3.4's stop: the terminator ends the skip.
+ if (token == 0)
+ break;
+ } while (ClassOf(token) == kClassColorOn || ClassOf(token) == kClassLinkStart ||
+ (linkAtomic && (token & 0x80000000u) != 0 && ClassOf(token) != kClassLinkStop));
+ while (ClassOf(*info) == kClassColorRestore || ClassOf(*info) == kClassLinkStop) {
+ bytes += LengthOf(*info);
+ info += LengthOf(*info);
+ }
+ }
+ return bytes;
+}
+
+const Game::HookAutoRegister _hook{Offsets::FUN_EDITBOX_STEP_BYTES, reinterpret_cast(&StepBytes_h),
+ reinterpret_cast(&g_origStepBytes)};
+
+// Called as `FUN_EDITBOX_STEP_BYTES(lineStart, glyphs, 0)`; returns the bytes
+// that `glyphs` steps cover backwards from the end of the line that starts at
+// lineStart, which the hit test subtracts from that end.
+int __fastcall RightJustifiedStep(void *editBox, void *edx, int lineStart, int glyphs, int atomic) {
+ if (glyphs <= 0)
+ return 0;
+ const int count = Game::Read(editBox, Offsets::OFF_EDITBOX_LINE_COUNT);
+ const int *starts = Game::Read(editBox, Offsets::OFF_EDITBOX_LINE_STARTS);
+ // A line that fits a glyph is not empty, so its start is followed by a
+ // larger entry: its end.
+ for (int i = 0; i + 1 < count; ++i) {
+ if (starts[i] == lineStart && starts[i + 1] > lineStart)
+ return reinterpret_cast(Offsets::FUN_EDITBOX_STEP_BYTES)(editBox, edx, starts[i + 1],
+ -glyphs, atomic);
+ }
+ return reinterpret_cast(Offsets::FUN_EDITBOX_STEP_BYTES)(editBox, edx, lineStart, glyphs, atomic);
+}
+
+void PatchCode() {
+ Common::RedirectCall(Offsets::CALL_EDITBOX_HIT_RIGHT_STEP, Offsets::FUN_EDITBOX_STEP_BYTES,
+ reinterpret_cast(&RightJustifiedStep));
+}
+
+const Game::ModuleAutoRegister _autoreg{&PatchCode};
+
+} // namespace
+
+} // namespace EditBox::CursorStep
diff --git a/src/editbox/Enable.cpp b/src/editbox/Enable.cpp
new file mode 100644
index 00000000..f2e8c878
--- /dev/null
+++ b/src/editbox/Enable.cpp
@@ -0,0 +1,95 @@
+// 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 .
+
+// `editBox:Enable()`, `editBox:Disable()` and `editBox:IsEnabled()`.
+//
+// 4.3.4's CSimpleEditBox::Enable(enabled): a disable first clears the box's
+// keyboard focus, then either runs CSimpleFrame::RunOnEnableScript - frame
+// flag 0x400 and the OnEnable / OnDisable script - on every call, changed or
+// not. IsEnabled reads the flag. That is all a disable does in 4.3.4: the
+// mouse-down and SetFocus paths never read the flag, so a click still
+// focuses a disabled box.
+
+#include "Game.h"
+#include "Offsets.h"
+#include "frame/EnableScripts.h"
+
+#include
+
+namespace EditBox::Enable {
+
+namespace {
+
+using ClearFocus_t = void(__fastcall *)(void *editBox);
+
+void Enable(void *editBox, bool enabled) {
+ if (!enabled)
+ reinterpret_cast(Offsets::FUN_EDITBOX_CLEAR_FOCUS)(editBox);
+ Frame::EnableScripts::RunOnEnableScript(editBox, !enabled);
+}
+
+int __fastcall Script_Enable(void *L) {
+ void *editBox = Game::Lua::ResolveEditBox(L);
+ if (editBox != nullptr)
+ Enable(editBox, true);
+ return 0;
+}
+
+int __fastcall Script_Disable(void *L) {
+ void *editBox = Game::Lua::ResolveEditBox(L);
+ if (editBox != nullptr)
+ Enable(editBox, false);
+ return 0;
+}
+
+int __fastcall Script_IsEnabled(void *L) {
+ void *editBox = Game::Lua::ResolveEditBox(L);
+ if (editBox == nullptr)
+ return 0;
+ const uint32_t flags = Game::Read(editBox, Offsets::OFF_FRAME_FLAGS);
+ Game::Lua::PushBool(L, (flags & Offsets::FRAME_FLAG_DISABLED) == 0);
+ return 1;
+}
+
+const Game::Lua::FrameMethodEntry g_methods[] = {
+ {"Enable", &Script_Enable},
+ {"Disable", &Script_Disable},
+ {"IsEnabled", &Script_IsEnabled},
+};
+
+const Game::Doc::Field kIsEnabledRets[] = {
+ Game::Doc::Req("enabled", "boolean"),
+};
+const Game::Doc::Function kEnable{"Enables the edit box and runs its OnEnable script.", {}, {}};
+const Game::Doc::Function kDisable{
+ "Disables the edit box: clears its keyboard focus and runs its OnDisable script.", {}, {}};
+const Game::Doc::Function kIsEnabled{"Returns whether the edit box is enabled.", {}, kIsEnabledRets};
+
+const Game::Doc::Method g_methodDocs[] = {
+ {"Enable", &kEnable},
+ {"Disable", &kDisable},
+ {"IsEnabled", &kIsEnabled},
+};
+
+void RegisterLuaFunctions() {
+ Game::Lua::RegisterFrameMethods(
+ reinterpret_cast(Offsets::VAR_EDITBOX_METHOD_REGISTRY), g_methods,
+ static_cast(sizeof(g_methods) / sizeof(g_methods[0])), g_methodDocs,
+ static_cast(sizeof(g_methodDocs) / sizeof(g_methodDocs[0])));
+}
+
+const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
+
+} // namespace
+
+} // namespace EditBox::Enable
diff --git a/src/editbox/Ime.cpp b/src/editbox/Ime.cpp
new file mode 100644
index 00000000..779690fb
--- /dev/null
+++ b/src/editbox/Ime.cpp
@@ -0,0 +1,98 @@
+// 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 .
+
+// Input-method composition: `editBox:IsInIMECompositionMode()` and the
+// `OnCharComposition(self, text)` script.
+//
+// 1.12's edit box already handles input-method events the way 4.3.4's
+// OnLayerIme does, and keeps the same composition flag
+// (OFF_EDITBOX_IME_COMPOSITION), so IsInIMECompositionMode reads it as
+// 4.3.4's does: 1 or nil.
+//
+// When the composition string changes, both clients insert it into the box;
+// 4.3.4 then runs OnCharComposition with that string. 1.12 has no such
+// script. It is an EditBox Frame::ExtraScripts script, and the input-method
+// slot's one insert call is redirected to a function that makes the same
+// insert and then runs the script.
+
+#include "Common.h"
+#include "Game.h"
+#include "Offsets.h"
+#include "frame/ExtraScripts.h"
+#include "frame/ScriptArgs.h"
+
+#include
+
+namespace EditBox::Ime {
+
+namespace {
+
+const Frame::ExtraScripts::Script g_onCharComposition{"oncharcomposition", Offsets::VAR_EDITBOX_LUA_TYPE_ID};
+
+using Insert_t = void(__fastcall *)(void *editBox, void *edx, const char *text, const char *context, int runScripts,
+ int highlight);
+
+void __fastcall CompositionInsert(void *editBox, void *edx, const char *text, const char *context, int runScripts,
+ int highlight) {
+ reinterpret_cast(Offsets::FUN_EDITBOX_INSERT)(editBox, edx, text, context, runScripts, highlight);
+ const uint32_t *slot = g_onCharComposition.Slot(editBox);
+ if (slot == nullptr || slot[0] == 0)
+ return;
+ void *L = Game::Lua::State();
+ if (L == nullptr)
+ return;
+ const int top = Game::Lua::GetTop(L);
+ Game::Lua::PushString(L, text);
+ Frame::ScriptArgs::RunSlotWithValues(L, slot, editBox, top + 1, 1);
+ Game::Lua::SetTop(L, top);
+}
+
+int __fastcall Script_IsInIMECompositionMode(void *L) {
+ void *editBox = Game::Lua::ResolveEditBox(L);
+ if (editBox == nullptr)
+ return 0;
+ if (Game::Read(editBox, Offsets::OFF_EDITBOX_IME_COMPOSITION) != 0)
+ Game::Lua::PushNumber(L, 1.0);
+ else
+ Game::Lua::PushNil(L);
+ return 1;
+}
+
+const Game::Lua::FrameMethodEntry g_methods[] = {
+ {"IsInIMECompositionMode", &Script_IsInIMECompositionMode},
+};
+
+const Game::Doc::Field kRets[] = {
+ Game::Doc::Opt("composing", "number", nullptr, "1 while an input method composes text in the box, else nil."),
+};
+const Game::Doc::Function kIsInIMECompositionMode{
+ "Returns whether an input method is composing text in the edit box.", {}, kRets};
+
+const Game::Doc::Method g_methodDocs[] = {
+ {"IsInIMECompositionMode", &kIsInIMECompositionMode},
+};
+
+void RegisterLuaFunctions() {
+ Common::RedirectCall(Offsets::CALL_EDITBOX_IME_COMPOSITION_INSERT, Offsets::FUN_EDITBOX_INSERT,
+ reinterpret_cast(&CompositionInsert));
+ Game::Lua::RegisterFrameMethods(
+ reinterpret_cast(Offsets::VAR_EDITBOX_METHOD_REGISTRY), g_methods,
+ static_cast(sizeof(g_methods) / sizeof(g_methods[0])), g_methodDocs,
+ static_cast(sizeof(g_methodDocs) / sizeof(g_methodDocs[0])));
+}
+
+const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
+
+} // namespace
+
+} // namespace EditBox::Ime
diff --git a/src/editbox/TextChanged.cpp b/src/editbox/TextChanged.cpp
new file mode 100644
index 00000000..595984e3
--- /dev/null
+++ b/src/editbox/TextChanged.cpp
@@ -0,0 +1,158 @@
+// 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 .
+
+// `OnTextChanged(self, userInput)`.
+//
+// 4.3.4 runs OnTextChanged with one argument, true when the change came from
+// the user and false when SetText made it. The answer is dirty bit 0x8: an
+// insert or delete passed `script` = 0 sets it, an insert with `script` = 1
+// clears it (a delete with 1 leaves it), and the fire clears it after the
+// script ran. Only SetText (SetNumber goes through it) passes 1, for its
+// delete-all and its insert; typing, pasting, deleting, the input method and
+// Lua's Insert all pass 0.
+//
+// 1.12 fires OnTextChanged with no argument and has no `script` argument to
+// carry. The bit is kept here, per edit box, at the same points: the class
+// rebuild at the end of each insert that went ahead (its one call,
+// redirected; EditBox::CharClass owns the rebuild itself), and each delete. An
+// insert or a clear reached from SetText's internal is the `script` = 1 case,
+// told apart by its return address. The fire block in the text update is
+// replaced by a call that runs the script with the bit, as 4.3.4's
+// RunOnTextChangedScript does, then clears it.
+
+#include "Common.h"
+#include "Game.h"
+#include "Offsets.h"
+#include "frame/ScriptArgs.h"
+
+#include
+#include
+#include
+#include
+
+namespace EditBox::TextChanged {
+
+namespace {
+
+// Edit boxes whose last text change came from the user (4.3.4's bit 0x8).
+std::unordered_set g_userInput;
+
+// The edit box SetText's internal is inserting into or clearing right now.
+const void *g_scripted = nullptr;
+
+using Insert_t = void(__fastcall *)(void *editBox, void *edx, const char *text, const char *context, int runScripts,
+ int highlight);
+using Clear_t = void(__fastcall *)(void *editBox);
+using DeleteRange_t = void(__fastcall *)(void *editBox, void *edx, int from, int to);
+using Rebuild_t = void(__fastcall *)(void *editBox);
+
+Insert_t g_origInsert = nullptr;
+Clear_t g_origClear = nullptr;
+DeleteRange_t g_origDeleteRange = nullptr;
+
+void __fastcall Insert_h(void *editBox, void *edx, const char *text, const char *context, int runScripts,
+ int highlight) {
+ if (reinterpret_cast(_ReturnAddress()) != Offsets::RET_EDITBOX_SET_TEXT_INSERT) {
+ g_origInsert(editBox, edx, text, context, runScripts, highlight);
+ return;
+ }
+ const void *saved = g_scripted;
+ g_scripted = editBox;
+ g_origInsert(editBox, edx, text, context, runScripts, highlight);
+ g_scripted = saved;
+}
+
+void __fastcall Clear_h(void *editBox) {
+ if (reinterpret_cast(_ReturnAddress()) != Offsets::RET_EDITBOX_SET_TEXT_CLEAR) {
+ g_origClear(editBox);
+ return;
+ }
+ const void *saved = g_scripted;
+ g_scripted = editBox;
+ g_origClear(editBox);
+ g_scripted = saved;
+}
+
+// 4.3.4's DeleteSubstring: `if (!script) bit |= 0x8`.
+void __fastcall DeleteRange_h(void *editBox, void *edx, int from, int to) {
+ g_origDeleteRange(editBox, edx, from, to);
+ if (editBox != g_scripted)
+ g_userInput.insert(editBox);
+}
+
+// 4.3.4's Insert, after UpdateTextInfo: `script ? bit &= ~0x8 : bit |= 0x8`.
+void __fastcall InsertRebuild(void *editBox) {
+ reinterpret_cast(Offsets::FUN_EDITBOX_REBUILD_CHAR_CLASS)(editBox);
+ if (editBox == g_scripted)
+ g_userInput.erase(editBox);
+ else
+ g_userInput.insert(editBox);
+}
+
+const Game::HookAutoRegister _insertHook{Offsets::FUN_EDITBOX_INSERT, reinterpret_cast(&Insert_h),
+ reinterpret_cast(&g_origInsert)};
+const Game::HookAutoRegister _clearHook{Offsets::FUN_EDITBOX_CLEAR, reinterpret_cast(&Clear_h),
+ reinterpret_cast(&g_origClear)};
+const Game::HookAutoRegister _deleteHook{Offsets::FUN_EDITBOX_DELETE_RANGE, reinterpret_cast(&DeleteRange_h),
+ reinterpret_cast(&g_origDeleteRange)};
+
+// 4.3.4's RunOnTextChangedScript and the clear after it.
+void __fastcall FireTextChanged(void *editBox) {
+ const bool userInput = g_userInput.count(editBox) != 0;
+ const uint32_t *slot = Game::Ptr(editBox, Offsets::OFF_EDITBOX_ONTEXTCHANGED_SLOT);
+ void *L = Game::Lua::State();
+ if (slot[0] != 0 && L != nullptr) {
+ const int top = Game::Lua::GetTop(L);
+ Game::Lua::PushBool(L, userInput);
+ Frame::ScriptArgs::RunSlotWithValues(L, slot, editBox, top + 1, 1);
+ Game::Lua::SetTop(L, top);
+ }
+ g_userInput.erase(editBox);
+}
+
+// The engine's fire block, and what replaces it: `mov ecx, esi; call
+// FireTextChanged`, then NOPs to 0x0077D49D.
+constexpr size_t kFireBlockSize = 24;
+constexpr uint8_t kFireBlock[kFireBlockSize] = {0x8B, 0x8E, 0x18, 0x04, 0x00, 0x00, 0x85, 0xC9,
+ 0x8D, 0x86, 0x18, 0x04, 0x00, 0x00, 0x74, 0x08,
+ 0x50, 0x8B, 0xCE, 0xE8, 0xF3, 0x51, 0xF8, 0xFF};
+
+void PatchCode() {
+ Common::RedirectCall(Offsets::CALL_EDITBOX_INSERT_REBUILD_CHAR_CLASS, Offsets::FUN_EDITBOX_REBUILD_CHAR_CLASS,
+ reinterpret_cast(&InsertRebuild));
+ auto *site = reinterpret_cast(Offsets::PATCH_EDITBOX_TEXT_CHANGED_FIRE);
+ if (std::memcmp(site, kFireBlock, kFireBlockSize) != 0)
+ return; // already patched, or not the code this was derived from
+ uint8_t bytes[kFireBlockSize];
+ std::memset(bytes, 0x90, sizeof bytes);
+ bytes[0] = 0x8B; // mov ecx, esi
+ bytes[1] = 0xCE;
+ bytes[2] = 0xE8; // call rel32
+ const int32_t rel = static_cast(reinterpret_cast(&FireTextChanged) -
+ (Offsets::PATCH_EDITBOX_TEXT_CHANGED_FIRE + 7));
+ std::memcpy(bytes + 3, &rel, sizeof rel);
+ Common::PatchBytes(site, bytes, sizeof bytes);
+}
+
+const Game::ModuleAutoRegister _autoreg{&PatchCode};
+
+void PrepareForReload() {
+ g_userInput.clear();
+ g_scripted = nullptr;
+}
+
+const Game::ReloadAutoRegister _reload{&PrepareForReload};
+
+} // namespace
+
+} // namespace EditBox::TextChanged
diff --git a/src/frame/EnableScripts.cpp b/src/frame/EnableScripts.cpp
new file mode 100644
index 00000000..89cdac95
--- /dev/null
+++ b/src/frame/EnableScripts.cpp
@@ -0,0 +1,77 @@
+// 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 OnEnable and OnDisable scripts.
+//
+// 4.3.4 gives every frame the two scripts and one runner,
+// CSimpleFrame::RunOnEnableScript(disabled): set or clear frame flag 0x400,
+// then run OnDisable or OnEnable. Two classes call it: CSimpleButton::Enable,
+// after the state change and only when the state changed, and
+// CSimpleEditBox::Enable (EditBox::Enable, a separate module) on every call.
+// 1.12 has neither script. The scripts are Frame::ExtraScripts scripts; the
+// Button side co-hooks 1.12's CSimpleButton::Enable, which returns early in
+// the same two cases 4.3.4's does, so the runner runs exactly when the
+// button's state changed.
+//
+// 4.3.4 also skips the script while the frame is loading from XML. 1.12's
+// Button constructor enables the button before any script is loaded, so no
+// handler can exist yet at that point.
+
+#include "frame/EnableScripts.h"
+
+#include "Game.h"
+#include "Offsets.h"
+#include "frame/ExtraScripts.h"
+#include "frame/ScriptArgs.h"
+
+#include
+
+namespace Frame::EnableScripts {
+
+namespace {
+
+const Frame::ExtraScripts::Script g_onEnable{"onenable", Offsets::VAR_FRAME_LUA_TYPE_ID};
+const Frame::ExtraScripts::Script g_onDisable{"ondisable", Offsets::VAR_FRAME_LUA_TYPE_ID};
+
+using SetFrameFlag_t = void(__fastcall *)(void *frame, void *edx, uint32_t mask, int on);
+using ButtonEnable_t = void(__fastcall *)(void *button, void *edx, int enable);
+
+ButtonEnable_t g_origButtonEnable = nullptr;
+
+void __fastcall ButtonEnable_h(void *button, void *edx, int enable) {
+ const bool wasEnabled = Game::Read(button, Offsets::OFF_BUTTON_STATE) != Offsets::BUTTON_STATE_DISABLED;
+ g_origButtonEnable(button, edx, enable);
+ const bool isEnabled = Game::Read(button, Offsets::OFF_BUTTON_STATE) != Offsets::BUTTON_STATE_DISABLED;
+ if (isEnabled != wasEnabled)
+ RunOnEnableScript(button, !isEnabled);
+}
+
+const Game::HookAutoRegister _buttonEnableHook{Offsets::FUN_BUTTON_ENABLE,
+ reinterpret_cast(&ButtonEnable_h),
+ reinterpret_cast(&g_origButtonEnable)};
+
+} // namespace
+
+void RunOnEnableScript(void *frame, bool disabled) {
+ reinterpret_cast(Offsets::FUN_FRAME_SET_FRAME_FLAG)(frame, nullptr,
+ Offsets::FRAME_FLAG_DISABLED, disabled);
+ const uint32_t *slot = (disabled ? g_onDisable : g_onEnable).Slot(frame);
+ if (slot == nullptr || slot[0] == 0)
+ return;
+ void *L = Game::Lua::State();
+ if (L == nullptr)
+ return;
+ Frame::ScriptArgs::RunSlotWithValues(L, slot, frame, Game::Lua::GetTop(L) + 1, 0);
+}
+
+} // namespace Frame::EnableScripts
diff --git a/src/frame/EnableScripts.h b/src/frame/EnableScripts.h
new file mode 100644
index 00000000..439357ed
--- /dev/null
+++ b/src/frame/EnableScripts.h
@@ -0,0 +1,22 @@
+// This file is part of ClassicAPI.
+//
+// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
+// of the GNU General Public License as published by the Free Software Foundation, either
+// version 3 of the License, or (at your option) any later version.
+//
+// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+// PURPOSE. See the GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along with
+// ClassicAPI. If not, see .
+
+#pragma once
+
+namespace Frame::EnableScripts {
+
+// 4.3.4's CSimpleFrame::RunOnEnableScript: sets or clears FRAME_FLAG_DISABLED
+// and runs the frame's OnDisable or OnEnable script.
+void RunOnEnableScript(void *frame, bool disabled);
+
+} // namespace Frame::EnableScripts