From fdae686cc9f32ea231b830dba3b54aab2b3b9b52 Mon Sep 17 00:00:00 2001 From: Brues <5278969+brues-code@users.noreply.github.com> Date: Mon, 19 Oct 2026 00:52:28 -0500 Subject: [PATCH] feat(console): add pitchLimit, AppendLogToFile and 4.3.4's Tab completion Cross-checked against the 4.3.4 decompilation (wowdecomp15595): - The handler's first argument is the command name, not unused (the shared CVar handler looks its CVar up by it); Game::Console::Write takes 4.3.4's COLOR_T, and Game::Console::Printf is the engine's own ConsolePrintf (0x0063CD50). - pitchLimit : writes the camera pitch clamp, which 1.12 keeps as two .rdata floats read only by camera code. - Ctrl+Tab lists every command containing the typed text; Tab after set/cvar_reset/cvar_default completes CVar names (extension). Our key handler registers at the console's own priority 7.0, which the engine's tie rule runs first, so no hook is needed. - AppendLogToFile [file] [numLines]: implements the contract 4.3.4's help text documents (the shipped command prints "Access Denied"). - The command-list walk moves into console/Registry.h, and EnsureParentDirs into Common. --- README.md | 3 + docs/API.md | 48 +++++++ src/Common.cpp | 14 ++ src/Common.h | 5 + src/Game.cpp | 9 +- src/Game.h | 42 ++++-- src/Offsets.h | 99 +++++++++++++- src/camera/PitchLimit.cpp | 61 +++++++++ src/console/Commands.cpp | 59 ++------- src/console/Completion.cpp | 259 +++++++++++++++++++++++++++++++++++++ src/console/Log.cpp | 137 ++++++++++++++++++++ src/console/Registry.h | 62 +++++++++ src/console/Shell.cpp | 5 +- src/interface/Export.cpp | 27 +--- 14 files changed, 738 insertions(+), 92 deletions(-) create mode 100644 src/camera/PitchLimit.cpp create mode 100644 src/console/Completion.cpp create mode 100644 src/console/Log.cpp create mode 100644 src/console/Registry.h diff --git a/README.md b/README.md index 939131bf..31e0de69 100644 --- a/README.md +++ b/README.md @@ -201,6 +201,9 @@ when launching with `-console`), not as Lua functions. See the | `ExportInterfaceFiles art` | Extracts Blizzard's UI art (`.blp`/`.tga`) from the MPQs to `BlizzardInterfaceArt\` | | `ExportDBCFiles` | Extracts the client's `.dbc` tables from the MPQs to `DBFilesClient\` | | `ExportSoundFiles [subpath]` | Extracts the client's sound files from the MPQs to `BlizzardSound\`; the optional subpath narrows it (the full tree is ~1 GB) | +| `pitchLimit degrees` | Sets how far the camera can tilt up and down (default 89) | +| `AppendLogToFile [filename] [numLines]` | Writes the console output to a text file (default `ConsoleLogs\Log.txt`) | +| Tab / Ctrl+Tab | Tab completes CVar names after `set`, `cvar_reset` and `cvar_default`; Ctrl+Tab lists every command that contains the typed text | diff --git a/docs/API.md b/docs/API.md index f7c3092f..a9a2b0a3 100644 --- a/docs/API.md +++ b/docs/API.md @@ -90,6 +90,9 @@ build instructions. - [`ExportInterfaceFiles art|code` (console command)](#exportinterfacefiles-artcode-console-command) - [`ExportDBCFiles` (console command)](#exportdbcfiles-console-command) - [`ExportSoundFiles [subpath]` (console command)](#exportsoundfiles-subpath-console-command) + - [`pitchLimit degrees` (console command)](#pitchlimit-degrees-console-command) + - [`AppendLogToFile [filename] [numLines]` (console command)](#appendlogtofile-filename-numlines-console-command) + - [Tab completion in the console](#tab-completion-in-the-console) - [Container](#container) - [`C_Container.GetContainerItemID(bagIndex, slotIndex)`](#c_containergetcontaineritemidbagindex-slotindex) @@ -2130,6 +2133,51 @@ Notes: so exporting into `Sound\` would shadow the archives with a gigabyte of duplicates that get re-indexed at every launch. +### `pitchLimit degrees` (console command) + +Sets how far the camera can tilt up and down. The limit is in degrees and +applies in both directions. The default limit is 89 degrees. + +``` +> pitchLimit 60 +``` + +The command does not validate the value. A bare `pitchLimit` sets the limit +to 0, which holds the camera level. The limit stays until you change it or +restart the client. + +### `AppendLogToFile [filename] [numLines]` (console command) + +Writes the console output to a text file. This is a ClassicAPI extension. + +- `filename` is relative to the client's working directory (next to + `WoW.exe`). The default is `ConsoleLogs\Log.txt`. The command + makes missing folders. If the file exists, the command adds the lines to + the end of it. +- `numLines` limits the output to the most recent lines. Without it, the + command writes all lines. + +The file has the oldest line first. The line that you type at the time is +not part of the output. + +``` +> AppendLogToFile +AppendLogToFile: wrote 212 line(s) to ConsoleLogs\Log20261019_143022.txt +``` + +### Tab completion in the console + +The console has three Tab functions: + +- **Tab** on a command name completes the name. Press Tab again for the + next match. Press Shift+Tab for the previous match. +- **Tab** after `set`, `cvar_reset` or `cvar_default` completes the CVar + name. Matches cycle in alphabetical order, the same as for command names. + This is a ClassicAPI extension. +- **Ctrl+Tab** lists every command whose name contains the typed text, in + alphabetical order. Case is not important. After `set`, `cvar_reset` or + `cvar_default`, it lists the CVar names that start with the typed text. + ## Container ### `C_Container.GetContainerItemID(bagIndex, slotIndex)` diff --git a/src/Common.cpp b/src/Common.cpp index 35394ead..635c68bd 100644 --- a/src/Common.cpp +++ b/src/Common.cpp @@ -14,6 +14,7 @@ #include "Common.h" #include +#include #include namespace Common { @@ -40,4 +41,17 @@ void BoundedCopy(char *dst, const char *src, size_t n) { dst[i] = '\0'; } +void EnsureParentDirs(const char *relPath) { + std::string accum; + for (const char *p = relPath; *p != '\0'; ++p) { + if (*p == '\\' || *p == '/') { + if (!accum.empty()) + CreateDirectoryA(accum.c_str(), nullptr); + accum.push_back('\\'); + } else { + accum.push_back(*p); + } + } +} + } // namespace Common diff --git a/src/Common.h b/src/Common.h index a7ba9d8a..31bdf847 100644 --- a/src/Common.h +++ b/src/Common.h @@ -23,4 +23,9 @@ bool PatchBytes(void *dst, const void *src, size_t len); // (C4996) and which does not terminate on truncation. void BoundedCopy(char *dst, const char *src, size_t n); +// Creates every parent directory of `relPath` (backslash- or slash-separated, +// e.g. "BlizzardInterfaceCode\FrameXML\Foo.lua"), relative to the working +// directory. Directories that already exist are a no-op. +void EnsureParentDirs(const char *relPath); + } // namespace Common diff --git a/src/Game.cpp b/src/Game.cpp index 58aba8ab..c206e544 100644 --- a/src/Game.cpp +++ b/src/Game.cpp @@ -505,7 +505,7 @@ namespace Console { namespace { using RegisterCommand_t = int(__fastcall *)(const char *name, void *handler, int category, const char *description); -using Write_t = void(__fastcall *)(const char *line, int colorFlag); +using Write_t = void(__fastcall *)(const char *line, int color); } // namespace void RegisterCommand(const char *name, CommandHandler handler, int category, @@ -514,10 +514,13 @@ void RegisterCommand(const char *name, CommandHandler handler, int category, fn(name, reinterpret_cast(handler), category, description); } -void Write(const char *line) { +void Write(const char *line, Color color) { auto fn = reinterpret_cast(Offsets::FUN_CONSOLE_WRITE); - fn(line, 0); + fn(line, color); } + +void(__cdecl *const Printf)(const char *format, ...) = + reinterpret_cast(Offsets::FUN_CONSOLE_PRINTF); } // namespace Console namespace { diff --git a/src/Game.h b/src/Game.h index 555dcf0e..6905b3ff 100644 --- a/src/Game.h +++ b/src/Game.h @@ -543,16 +543,17 @@ bool CallGlobalString(void *L, const char *name, const char *arg); // section in CLAUDE.md for the underlying offsets and ABI. namespace Console { -// Console-command handler ABI: `args` is the command-line text after -// the command name (empty string when invoked bare). The engine -// ignores the return value; return 1 by convention. -using CommandHandler = int(__fastcall *)(void *unused, const char *args); +// Console-command handler ABI — 4.3.4's `COMMANDHANDLER(command, +// arguments)`. `command` is the name the command was invoked by, which +// is how one handler serves several names: every CVar is registered with +// the shared FUN_CONSOLE_CVAR_COMMAND_HANDLER, which looks the CVar up by +// `command`. `args` is the text after the name (empty string when +// invoked bare). The engine ignores the return value; return 1. +using CommandHandler = int(__fastcall *)(const char *command, const char *args); -// Help-grouping categories — the engine's `help` enumerates these nine -// (in this order). Cosmetic: the value only affects which group `help` -// lists the command under; the engine doesn't validate it. Values are -// sequential table indices (graphics=1 confirmed via FUN_0066F6C0, the -// rest follow the displayed order). +// Help-grouping categories — 4.3.4's `CATEGORY` enum, which matches the +// nine-entry table the 1.12 `help` command lists (VAR_CONSOLE_CATEGORY_TABLE). +// Cosmetic: only `help` grouping reads it; the registrar doesn't validate it. enum Category { CATEGORY_DEBUG = 0, CATEGORY_GRAPHICS = 1, @@ -574,9 +575,30 @@ enum Category { void RegisterCommand(const char *name, CommandHandler handler, int category, const char *description); +// Line colour types — 4.3.4's `COLOR_T`, indexing the nine-entry +// VAR_CONSOLE_COLORS table. The engine's `help` writes WARNING (yellow), +// its failures ERROR (red), and its plain output DEFAULT. +enum Color { + COLOR_DEFAULT = 0, + COLOR_INPUT = 1, + COLOR_ECHO = 2, + COLOR_ERROR = 3, + COLOR_WARNING = 4, + COLOR_GLOBAL = 5, + COLOR_ADMIN = 6, + COLOR_HIGHLIGHT = 7, + COLOR_BACKGROUND = 8, +}; + // Writes a line to the console output buffer. No-ops cleanly when the // console isn't active, so it's always safe to call. -void Write(const char *line); +void Write(const char *line, Color color = COLOR_DEFAULT); + +// The engine's own `ConsolePrintf` (FUN_CONSOLE_PRINTF): formats with +// Storm's printf into a 1024-byte buffer, then writes it in +// COLOR_DEFAULT. Exposed as the engine's entry itself rather than a +// wrapper, because a cdecl varargs call cannot be forwarded. +extern void(__cdecl *const Printf)(const char *format, ...); } // namespace Console diff --git a/src/Offsets.h b/src/Offsets.h index 707b3105..29d9630e 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -134,6 +134,9 @@ enum Offsets { // 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. + // It is 4.3.4's EventIsKeyDown, taking any KEY code — 0..2 are 1.12's + // merged meta keys — and the console's key handler asks it whether the + // console toggle key is held. // 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, @@ -7421,12 +7424,17 @@ enum Offsets { // command node is never freed for a static-literal name, so we // don't need SStrDup the way the event table does. // - // The handler is `int __fastcall(void *unused /*ecx*/, const char - // *args /*edx*/)`; `args` is the text after the command name - // (`*args == '\0'` when invoked bare). Return 1. Categories seen in - // the binary: graphics=1, help=2, misc=5 (we use 5, matching - // 4.3.4's `ExportInterfaceFiles`); the value is cosmetic (only - // affects `help` grouping) and unvalidated by the registrar. + // The handler is `int __fastcall(const char *command /*ecx*/, const + // char *args /*edx*/)` — 4.3.4's COMMANDHANDLER. `command` is the + // invoked name (the shared CVar handler FUN_CONSOLE_CVAR_COMMAND_HANDLER + // looks its CVar up by it); `args` is the text after the name + // (`*args == '\0'` when invoked bare). Return 1. The category is + // 4.3.4's CATEGORY enum (see VAR_CONSOLE_CATEGORY_TABLE); cosmetic, + // only `help` grouping reads it, and the registrar doesn't validate it. + // + // The node layout is 4.3.4's CONSOLECOMMAND up to +0x20. 4.3.4 adds a + // +0x24 argument-completion callback this registrar has no slot for — + // and no 4.3.4 command fills it (every registration passes NULL). // // Self-initializes the command hash table on first use, so it is // safe to call any time after the engine's own console subsystem @@ -7512,6 +7520,68 @@ enum Offsets { // Console font height as a fraction of screen height, 0.02 by default. VAR_CONSOLE_FONT_HEIGHT = 0x0086455C, + // --- Console input: key handling and Tab completion ----------------------- + // EventRegisterEx — `void __fastcall(int eventId /*ecx*/, Handler handler + // /*edx*/, void *param, float priority)`, into the current event context. + // Handlers are `int __fastcall(const void *data, void *param)`; returning 0 + // stops the dispatch. The list is kept in DESCENDING priority, and a new + // handler is linked in front of the first one whose priority is <= its own + // (FUN_00424F00, 4.3.4's IEvtQueueRegister) — so a handler registered + // later at an EQUAL priority runs first. Does not dedup. + FUN_EVENT_REGISTER_EX = 0x0041FCA0, + // Event id of a key press. The console's RegisterHandlers (FUN_0063BC90) + // registers ids 1, 5, 8, 9, 10, 11, 14, 12 in 4.3.4's order CHAR, IDLE, + // KEYDOWN, KEYUP, KEYDOWN_REPEATING, MOUSEDOWN, MOUSEUP, MOUSEMOVE; id 8's + // handler FUN_CONSOLE_ON_KEY_DOWN is the one with the Tab/Enter/Escape + // switch. Its data is 4.3.4's EVENT_DATA_KEY: `{ int key; uint32_t meta; }`. + EVENT_ID_KEYDOWN = 8, + // Every console input handler is registered at priority 7.0 (stored here + // as the integer; the registrar takes it as a float). + CONSOLE_EVENT_PRIORITY = 7, + FUN_CONSOLE_ON_KEY_DOWN = 0x0063C480, + // 4.3.4's KEY enum, unchanged in 1.12: the console's switch tests 0x200 + // Escape, 0x201 Enter, 0x203 Tab. + KEY_TAB = 0x203, + // The key event's modifier mask is 4.3.4's `1 << key` over the meta keys, + // but 1.12 has three merged meta keys (KEY 0 SHIFT, 1 CTRL, 2 ALT — the + // FUN_GAMEUI_IS_KEY_DOWN codes) where 4.3.4 has six per-side ones. So: + // SHIFT 1, CTRL 2, ALT 4. Read off the binding-prefix builder FUN_004B6630 + // (bit 0 "SHIFT-", 1 "CTRL-", 2 "ALT-"), and consistent with the console + // handler's own tests (`meta == 1` reverses Tab completion, `meta == 2` is + // Ctrl+C / Ctrl+V). + EVENT_META_SHIFT = 0x1, + EVENT_META_CTRL = 0x2, + // The line being typed — 4.3.4's GetInputLine; makes one if the head line + // is not an input line. `CONSOLELINE *__fastcall()`. + FUN_CONSOLE_GET_INPUT_LINE = 0x0063BAA0, + // 4.3.4's MakeCommandCurrent: `void __fastcall(CONSOLELINE *line, const + // char *text)` — replaces the typed text (from m_inputstart) with `text`, + // growing the buffer as needed, and leaves the caret at its end. + FUN_CONSOLE_MAKE_COMMAND_CURRENT = 0x00638E40, + // 4.3.4's SetInputString: `void __fastcall(const char *wholeLine)` — + // rebuilds the drawn input string. The key handler calls it with the + // line's whole buffer after every edit. + FUN_CONSOLE_SET_INPUT_STRING = 0x00638D10, + // 4.3.4's s_completionMode: set by the first Tab of a completion run, and + // cleared by the key handler on any key but Tab, Shift (KEY 0), Alt (KEY + // 2) or a Ctrl chord — 4.3.4's exact rule with merged meta keys. Read by + // Console::Completion to tell when a run has ended. + VAR_CONSOLE_COMPLETION_MODE = 0x00C4EC28, + // 4.3.4's CONSOLELINE (0x24 bytes, allocated as "CONSOLELINE"): link at + // +0, m_buffer +0x08, m_chars +0x0C, m_inputpos +0x14, m_inputstart +0x18, + // m_colorType +0x1C. Matches the key handler's and ConsoleWrite's reads. + OFF_CONSOLE_LINE_BUFFER = 0x08, + OFF_CONSOLE_LINE_INPUT_POS = 0x14, + OFF_CONSOLE_LINE_INPUT_START = 0x18, + // The output lines (4.3.4's s_linelist): newest first, the same tagged + // Storm list as the command registry — link offset, then the head's + // `next` pointer. A head with a non-zero m_inputpos is the line being + // typed. ConsoleWrite (FUN_CONSOLE_WRITE) holds the critical section at + // VAR_CONSOLE_LINE_LOCK while it links a line in. + VAR_CONSOLE_LINE_LIST_LINK_OFFSET = 0x00C4E9A4, + VAR_CONSOLE_LINE_LIST_HEAD = 0x00C4E9AC, + VAR_CONSOLE_LINE_LOCK = 0x00C4E64C, + // `ConsoleWrite(const char *line /*ecx*/, int colorFlag /*edx*/)` — // appends a line to the developer console's output buffer. No-ops // cleanly when the console isn't active (gated on the console-init @@ -7519,6 +7589,12 @@ enum Offsets { // unconditionally from a console-command handler. `colorFlag` 0 = // default. Used by `Interface::Export` for "wrote N files" feedback. FUN_CONSOLE_WRITE = 0x0063CB50, + // `void __cdecl ConsolePrintf(const char *format, ...)` — formats via + // Storm's vsnprintf (FUN_0064A8B0) into a 1024-byte stack buffer and + // passes it to FUN_CONSOLE_WRITE in colour 0. Gated on DAT_00C4EC1C (the + // console being initialised). The shared CVar handler prints + // `CVar "%s" is "%s"` through it. Matches 4.3.4's ConsolePrintf. + FUN_CONSOLE_PRINTF = 0x0063CD50, // TOC parser — `__fastcall(this=addonName)`. Already documented in // CLAUDE.md under "AddOn registry & hot-reload". Dedup-safe: if @@ -8440,6 +8516,17 @@ enum Offsets { // last-applied buffers); we read the primary at `+0xF0`. OFF_CAMERA_RELATIVE_YAW = 0xF0, + // Camera pitch clamp, radians: +/-1.55334306 (89 degrees). 4.3.4's + // MAX_PITCH_ANGLE / MIN_PITCH_ANGLE, which its `pitchLimit` console + // command writes. In 1.12 they are the same two floats but sit in + // .rdata, so writing them needs the page unprotected. Every one of their + // 31 readers is camera code (0x0050B380..0x005115B8) — the pitch clamps, + // the smooth-pitch target clamp, and FUN_0050B380, the cameraPitch CVar + // range check that 4.3.4 calls ValidateCameraPitch — so no unrelated + // constant shares the slot. + VAR_CAMERA_MAX_PITCH = 0x008089D8, + VAR_CAMERA_MIN_PITCH = 0x008089DC, + // UI input controller — heap-allocated struct holding the // engine's master input-state bitfield (mouselook / free-look / // turn-key / autorun / strafe-modifier / etc.). The slot at diff --git a/src/camera/PitchLimit.cpp b/src/camera/PitchLimit.cpp new file mode 100644 index 00000000..fd62a8de --- /dev/null +++ b/src/camera/PitchLimit.cpp @@ -0,0 +1,61 @@ +// 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 . + +// `pitchLimit ` — 4.3.4's console command (CGCamera::CCommand_PitchLimit) +// that sets how far the camera may pitch up and down. +// +// 4.3.4 writes `degrees` (and its negation) into the two globals every camera +// pitch clamp reads. 1.12 reads the very same pair, so this writes them and the +// engine's own clamps, smooth-pitch target and cameraPitch range check all +// follow. The only difference is that 1.12 keeps them in .rdata, hence the +// unprotected write. +// +// Like 4.3.4 there is no validation: a bare `pitchLimit` parses as 0 and locks +// the camera level, and values past 90 degrees are taken as given. + +#include "Common.h" +#include "Game.h" +#include "Offsets.h" + +namespace Camera::PitchLimit { + +namespace { + +using ToFloat_t = float(__stdcall *)(const char *); + +constexpr float kDegreesToRadians = 0.017453292f; // 4.3.4's own constant + +int __fastcall Console_PitchLimit(const char * /*command*/, const char *args) { + const float limit = + reinterpret_cast(Offsets::FUN_SSTR_TO_FLOAT)(args) * kDegreesToRadians; + const float max = limit; + const float min = -limit; + Common::PatchBytes(reinterpret_cast(Offsets::VAR_CAMERA_MAX_PITCH), &max, + sizeof(max)); + Common::PatchBytes(reinterpret_cast(Offsets::VAR_CAMERA_MIN_PITCH), &min, + sizeof(min)); + return 1; +} + +// Process-global, so the first glue boot covers the session; the registrar +// dedups the repeat on each logout. +void Register() { + Game::Console::RegisterCommand("pitchLimit", &Console_PitchLimit, + Game::Console::CATEGORY_GAME, nullptr); +} + +const Game::GlueModuleAutoRegister _autoreg{&Register}; + +} // namespace + +} // namespace Camera::PitchLimit diff --git a/src/console/Commands.cpp b/src/console/Commands.cpp index a37b7a66..b9c8888f 100644 --- a/src/console/Commands.cpp +++ b/src/console/Commands.cpp @@ -44,9 +44,7 @@ // so it needs no translation. #include "Game.h" -#include "Offsets.h" - -#include +#include "console/Registry.h" namespace Console::Commands { @@ -57,12 +55,6 @@ namespace { constexpr int kCommandTypeCvar = 0; constexpr int kCommandTypeCommand = 1; -using ConsoleWrite_t = void(__fastcall *)(const char *line, int colorType); - -// A list node, or 0 once the walk reaches the end. The low bit tags the -// sentinel, the same convention the addon registry and the parser lists use. -bool IsNode(uintptr_t node) { return node != 0 && (node & 1) == 0; } - char Lower(char c) { return (c >= 'A' && c <= 'Z') ? static_cast(c - 'A' + 'a') : c; } bool StartsWithIgnoreCase(const char *name, const char *prefix) { @@ -90,41 +82,19 @@ int __fastcall Script_GetAllCommands(void *L) { Game::Lua::SetTop(L, 0); Game::Lua::NewTable(L); - const uintptr_t linkOffset = - Game::Read(Offsets::VAR_CONSOLE_COMMAND_LINK_OFFSET); - uintptr_t node = Game::Read(Offsets::VAR_CONSOLE_COMMAND_LIST_HEAD); - int count = 0; - while (IsNode(node)) { - const auto *name = - Game::Read(node + Offsets::OFF_CONSOLE_COMMAND_NAME); - const auto *help = - Game::Read(node + Offsets::OFF_CONSOLE_COMMAND_HELP); - const uintptr_t handler = - Game::Read(node + Offsets::OFF_CONSOLE_COMMAND_HANDLER); - const int category = - Game::Read(node + Offsets::OFF_CONSOLE_COMMAND_CATEGORY); - - // Step before building the entry: the walk stays correct even if a - // field read below is skipped. - node = Game::Read(node + linkOffset + 4); - - if (name == nullptr) - continue; // a node the registrar never finished; nothing to report - + Console::Registry::ForEach([&](const Console::Registry::Command &command) { Game::Lua::PushNumber(L, ++count); Game::Lua::NewTable(L); - SetStringField(L, "command", name); - SetStringField(L, "help", help); - SetIntField(L, "category", category); + SetStringField(L, "command", command.name); + SetStringField(L, "help", command.help); + SetIntField(L, "category", command.category); SetIntField(L, "commandType", - handler == Offsets::FUN_CONSOLE_CVAR_COMMAND_HANDLER - ? kCommandTypeCvar - : kCommandTypeCommand); + command.IsCvar() ? kCommandTypeCvar : kCommandTypeCommand); SetStringField(L, "scriptContents", ""); SetStringField(L, "scriptParameters", ""); Game::Lua::SetTable(L, -3); - } + }); return 1; } @@ -148,17 +118,10 @@ int __fastcall Script_ConsolePrintAllMatchingCommands(void *L) { if (prefix == nullptr || prefix[0] == '\0') return 0; - auto write = reinterpret_cast(Offsets::FUN_CONSOLE_WRITE); - const uintptr_t linkOffset = - Game::Read(Offsets::VAR_CONSOLE_COMMAND_LINK_OFFSET); - uintptr_t node = Game::Read(Offsets::VAR_CONSOLE_COMMAND_LIST_HEAD); - while (IsNode(node)) { - const auto *name = - Game::Read(node + Offsets::OFF_CONSOLE_COMMAND_NAME); - node = Game::Read(node + linkOffset + 4); - if (name != nullptr && StartsWithIgnoreCase(name, prefix)) - write(name, 0); - } + Console::Registry::ForEach([&](const Console::Registry::Command &command) { + if (StartsWithIgnoreCase(command.name, prefix)) + Game::Console::Write(command.name); + }); return 0; } diff --git a/src/console/Completion.cpp b/src/console/Completion.cpp new file mode 100644 index 00000000..92076e38 --- /dev/null +++ b/src/console/Completion.cpp @@ -0,0 +1,259 @@ +// 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 two Tab behaviours 4.3.4's console has and 1.12's lacks. +// +// 1.12's Tab completes command NAMES only (FUN_0063FC60). 4.3.4's key handler +// adds two branches in front of that, and this restores both: +// +// Ctrl+Tab lists every command whose name CONTAINS the typed text +// (ConsoleCommandPrintAllMatching with substring = true): sorted, +// case-insensitive, one per line. With a space in the line it +// lists the argument completions instead. +// Tab with a space in the line, completes the ARGUMENT, cycling +// forward (Shift+Tab backward) through sorted matches — 4.3.4's +// ConsoleCommandComplete argument branch. +// +// 4.3.4 drives argument completion from a per-command callback, but no +// command in 4.3.4 registers one, so its argument branch never fires there. +// This gives it the one source that obviously fits — CVar names after `set`, +// `cvar_reset` and `cvar_default`, the commands whose argument is a CVar name. +// That part is a ClassicAPI extension; the mechanics around it are 4.3.4's. +// +// HOW IT GETS IN FIRST, WITHOUT A HOOK. The console's key handler is an +// ordinary event handler registered at priority 7.0, and the engine links a +// new handler in front of the first one whose priority is <= its own. So +// registering ours at the same 7.0 after the console's runs ours first; it +// returns 0 (consumed) for the Tab presses it handles and 1 for everything +// else, which the console then sees exactly as before. The console registers +// during client startup (FUN_0063B460 from 0x00402858), long before the first +// glue boot, which is when this registers — once, since the registrar does +// not dedup. +// +// THE RUN STATE IS THE ENGINE'S. A completion run is the engine's own +// s_completionMode flag: the first Tab sets it, and the console's handler +// clears it on any other key. An argument run sets that flag too, so the +// engine's rule for when a run ends applies to it unchanged, and Tab during an +// engine name-completion run is left to the engine. + +#include "Game.h" +#include "Offsets.h" +#include "console/Registry.h" + +#include +#include +#include +#include +#include + +namespace Console::Completion { + +namespace { + +using Handler_t = int(__fastcall *)(const void *data, void *param); +using RegisterEx_t = void(__fastcall *)(int eventId, Handler_t handler, void *param, + float priority); +using IsKeyDown_t = int(__fastcall *)(int key); +using GetInputLine_t = uintptr_t(__fastcall *)(); +using MakeCommandCurrent_t = void(__fastcall *)(uintptr_t line, const char *text); +using SetInputString_t = void(__fastcall *)(const char *text); + +// 4.3.4's EVENT_DATA_KEY, first two fields. +struct KeyEvent { + int key; + uint32_t meta; +}; + +// The commands whose argument is a CVar name (registered in FUN_0063D380). +const char *const kCvarArgumentCommands[] = {"set", "cvar_reset", "cvar_default"}; + +char Lower(char c) { return (c >= 'A' && c <= 'Z') ? static_cast(c - 'A' + 'a') : c; } + +bool StartsWithIgnoreCase(const char *text, const char *prefix) { + for (size_t i = 0; prefix[i] != '\0'; ++i) { + if (text[i] == '\0' || Lower(text[i]) != Lower(prefix[i])) + return false; + } + return true; +} + +bool ContainsIgnoreCase(const char *text, const char *needle) { + for (; *text != '\0'; ++text) { + if (StartsWithIgnoreCase(text, needle)) + return true; + } + return needle[0] == '\0'; +} + +// 4.3.4's CompareCompletions: _stricmp order. +void SortNames(std::vector &names) { + std::sort(names.begin(), names.end(), + [](const char *a, const char *b) { return _stricmp(a, b) < 0; }); +} + +// 4.3.4's ParseCommand: the name runs to the first space; the arguments are +// the rest with leading spaces skipped and trailing spaces trimmed. +struct Parsed { + std::string command; + std::string arguments; +}; + +Parsed Parse(const char *line) { + Parsed parsed; + const char *space = std::strchr(line, ' '); + if (space == nullptr) { + parsed.command = line; + return parsed; + } + parsed.command.assign(line, space); + while (*space == ' ') + ++space; + parsed.arguments = space; + while (!parsed.arguments.empty() && parsed.arguments.back() == ' ') + parsed.arguments.pop_back(); + return parsed; +} + +bool TakesCvarArgument(const std::string &command) { + for (const char *name : kCvarArgumentCommands) { + if (_stricmp(command.c_str(), name) == 0) + return true; + } + return false; +} + +// The argument completions for `arguments`, sorted — what 4.3.4's completion +// callback would return. Empty for a command that has none. +std::vector ArgumentMatches(const Parsed &parsed) { + std::vector matches; + if (!TakesCvarArgument(parsed.command)) + return matches; + Console::Registry::ForEach([&](const Console::Registry::Command &command) { + if (command.IsCvar() && StartsWithIgnoreCase(command.name, parsed.arguments.c_str())) + matches.push_back(command.name); + }); + SortNames(matches); + return matches; +} + +// Ctrl+Tab — 4.3.4's ConsoleCommandPrintAllMatching(partial, substring = true). +void PrintAllMatching(const char *partial) { + std::vector matches; + if (std::strchr(partial, ' ') != nullptr) { + matches = ArgumentMatches(Parse(partial)); + } else { + Console::Registry::ForEach([&](const Console::Registry::Command &command) { + if (ContainsIgnoreCase(command.name, partial)) + matches.push_back(command.name); + }); + SortNames(matches); + } + for (const char *name : matches) + Game::Console::Printf("%s", name); +} + +// The argument run in progress: the line as it was on the run's first Tab, and +// the index into its matches. Valid only while `g_ownRun` is set. +bool g_ownRun = false; +std::string g_partial; +int g_index = -1; + +// 4.3.4's ConsoleCommandComplete, argument branch. Writes "command match" to +// `out` and returns true when the index lands on a match; otherwise clamps the +// index and returns false, leaving the line as it is. +bool CompleteArgument(bool backward, std::string &out) { + const Parsed parsed = Parse(g_partial.c_str()); + const std::vector matches = ArgumentMatches(parsed); + const int count = static_cast(matches.size()); + + if (g_index < 0) + g_index = 0; + else + g_index += backward ? -1 : 1; + + if (g_index >= 0 && g_index < count) { + out = parsed.command + " " + matches[g_index]; + return true; + } + if (g_index < 0) + g_index = 0; + if (g_index >= count) + g_index = count - 1; + return false; +} + +int __fastcall OnKeyDown(const void *data, void * /*param*/) { + const auto *event = static_cast(data); + if (event->key != Offsets::KEY_TAB) + return 1; + + // The console handler's own gates, in its order: its toggle key is its + // business, and nothing reaches the input line while it is closed or + // while that key is held. + const int toggleKey = Game::Read(Offsets::VAR_CONSOLE_TOGGLE_KEY); + if (event->key == toggleKey) + return 1; + if (Game::Read(Offsets::VAR_CONSOLE_VISIBLE) == 0) + return 1; + if (reinterpret_cast(Offsets::FUN_GAMEUI_IS_KEY_DOWN)(toggleKey) != 0) + return 1; + + const uintptr_t line = + reinterpret_cast(Offsets::FUN_CONSOLE_GET_INPUT_LINE)(); + const char *typed = Game::Read(line + Offsets::OFF_CONSOLE_LINE_BUFFER) + + Game::Read(line + Offsets::OFF_CONSOLE_LINE_INPUT_START); + + if ((event->meta & Offsets::EVENT_META_CTRL) != 0) { + PrintAllMatching(typed); + return 0; + } + + auto &mode = Game::Ref(Offsets::VAR_CONSOLE_COMPLETION_MODE); + if (mode == 0) + g_ownRun = false; + if (!g_ownRun) { + if (mode != 0) + return 1; // the engine's own name-completion run + if (std::strchr(typed, ' ') == nullptr) + return 1; // a command name: the engine's completion + mode = 1; + g_ownRun = true; + g_partial = typed; + g_index = -1; + } + + std::string completed; + if (CompleteArgument((event->meta & Offsets::EVENT_META_SHIFT) != 0, completed)) + reinterpret_cast(Offsets::FUN_CONSOLE_MAKE_COMMAND_CURRENT)( + line, completed.c_str()); + // Re-read the buffer: MakeCommandCurrent may have reallocated it. + reinterpret_cast(Offsets::FUN_CONSOLE_SET_INPUT_STRING)( + Game::Read(line + Offsets::OFF_CONSOLE_LINE_BUFFER)); + return 0; +} + +void Register() { + static bool registered = false; + if (registered) + return; + registered = true; + reinterpret_cast(Offsets::FUN_EVENT_REGISTER_EX)( + Offsets::EVENT_ID_KEYDOWN, &OnKeyDown, nullptr, + static_cast(Offsets::CONSOLE_EVENT_PRIORITY)); +} + +const Game::GlueModuleAutoRegister _autoreg{&Register}; + +} // namespace + +} // namespace Console::Completion diff --git a/src/console/Log.cpp b/src/console/Log.cpp new file mode 100644 index 00000000..fc22cf25 --- /dev/null +++ b/src/console/Log.cpp @@ -0,0 +1,137 @@ +// 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 . + +// `AppendLogToFile [filename] [numLines]` — saves the console's output to a +// text file. +// +// 4.3.4 registers this command with the console's own commands and documents +// it as "[filename = ConsoleLogs/Log.txt] [numLines = all]", but in +// the shipped client it only prints "Access Denied". This implements the +// contract that help text describes, so it is a ClassicAPI extension: +// +// - `filename` is relative to the client's working directory (where +// ExportInterfaceFiles writes too); missing directories are created, and +// an existing file is appended to, as the name says. +// - `numLines` keeps the most recent N lines; without it, every line. +// - Lines are written oldest first, one per line. +// +// The lines are the engine's own list, read under the lock ConsoleWrite takes +// to link a line in. The line being typed is not output and is skipped. + +#include "Common.h" +#include "Game.h" +#include "Offsets.h" +#include "console/Registry.h" + +#include + +#include +#include +#include +#include +#include + +namespace Console::Log { + +namespace { + +// The console's output lines, oldest first, copied out under the console's +// own lock so a concurrent ConsoleWrite cannot change the list mid-walk. +std::vector SnapshotLines() { + std::vector lines; + auto *lock = reinterpret_cast(Offsets::VAR_CONSOLE_LINE_LOCK); + EnterCriticalSection(lock); + const uintptr_t linkOffset = + Game::Read(Offsets::VAR_CONSOLE_LINE_LIST_LINK_OFFSET); + uintptr_t node = Game::Read(Offsets::VAR_CONSOLE_LINE_LIST_HEAD); + bool head = true; + while (Console::Registry::IsNode(node)) { + const bool typing = + head && Game::Read(node + Offsets::OFF_CONSOLE_LINE_INPUT_POS) != 0; + const auto *text = Game::Read(node + Offsets::OFF_CONSOLE_LINE_BUFFER); + if (!typing && text != nullptr) + lines.emplace_back(text); + head = false; + node = Game::Read(node + linkOffset + 4); + } + LeaveCriticalSection(lock); + // The list is newest first. + return std::vector(lines.rbegin(), lines.rend()); +} + +std::string DefaultFileName() { + SYSTEMTIME now; + GetLocalTime(&now); + char name[64]; + std::snprintf(name, sizeof(name), "ConsoleLogs\\Log%04u%02u%02u_%02u%02u%02u.txt", + now.wYear, now.wMonth, now.wDay, now.wHour, now.wMinute, now.wSecond); + return name; +} + +int __fastcall Console_AppendLogToFile(const char * /*command*/, const char *args) { + // [filename] [numLines] + std::string fileName; + const char *p = args; + while (*p == ' ') + ++p; + while (*p != '\0' && *p != ' ') + fileName.push_back(*p++); + while (*p == ' ') + ++p; + const long requested = *p != '\0' ? std::strtol(p, nullptr, 10) : 0; + if (fileName.empty()) + fileName = DefaultFileName(); + + std::vector lines = SnapshotLines(); + if (requested > 0 && static_cast(requested) < lines.size()) + lines.erase(lines.begin(), lines.end() - requested); + + Common::EnsureParentDirs(fileName.c_str()); + HANDLE file = CreateFileA(fileName.c_str(), FILE_APPEND_DATA, FILE_SHARE_READ, nullptr, + OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) { + Game::Console::Printf("AppendLogToFile: could not open %s", fileName.c_str()); + return 1; + } + std::string text; + for (const std::string &line : lines) { + text += line; + text += "\r\n"; + } + DWORD written = 0; + const bool ok = WriteFile(file, text.data(), static_cast(text.size()), &written, + nullptr) != 0 && + written == text.size(); + CloseHandle(file); + if (!ok) { + Game::Console::Printf("AppendLogToFile: could not write %s", fileName.c_str()); + return 1; + } + Game::Console::Printf("AppendLogToFile: wrote %u line(s) to %s", + static_cast(lines.size()), fileName.c_str()); + return 1; +} + +// 4.3.4 registers it with the console's own commands: category console, with +// its help text. +void Register() { + Game::Console::RegisterCommand( + "AppendLogToFile", &Console_AppendLogToFile, Game::Console::CATEGORY_CONSOLE, + "[filename = ConsoleLogs/Log.txt] [numLines = all]"); +} + +const Game::GlueModuleAutoRegister _autoreg{&Register}; + +} // namespace + +} // namespace Console::Log diff --git a/src/console/Registry.h b/src/console/Registry.h new file mode 100644 index 00000000..2ae77333 --- /dev/null +++ b/src/console/Registry.h @@ -0,0 +1,62 @@ +// 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 + +// The console command registry, walked the way the engine's `help` command +// walks it: a Storm intrusive list filled by FUN_CONSOLE_COMMAND_REGISTER, in +// registration order. Every CVar is in it too (see +// FUN_CONSOLE_CVAR_COMMAND_HANDLER), so this is the one list of everything the +// console can run. + +#include "Game.h" +#include "Offsets.h" + +#include + +namespace Console::Registry { + +struct Command { + const char *name; + const char *help; // may be null + uintptr_t handler; + int category; + + // Every CVar shares the one handler the CVar registrar passes. + bool IsCvar() const { return handler == Offsets::FUN_CONSOLE_CVAR_COMMAND_HANDLER; } +}; + +// A list node, or 0 once the walk reaches the end. The low bit tags the +// sentinel, the same convention the addon registry and the parser lists use. +inline bool IsNode(uintptr_t node) { return node != 0 && (node & 1) == 0; } + +// Calls `fn(const Command &)` for every registered command. Steps to the next +// node before the call, so the walk does not depend on what `fn` does. +template void ForEach(Fn &&fn) { + const uintptr_t linkOffset = + Game::Read(Offsets::VAR_CONSOLE_COMMAND_LINK_OFFSET); + uintptr_t node = Game::Read(Offsets::VAR_CONSOLE_COMMAND_LIST_HEAD); + while (IsNode(node)) { + const Command command{ + Game::Read(node + Offsets::OFF_CONSOLE_COMMAND_NAME), + Game::Read(node + Offsets::OFF_CONSOLE_COMMAND_HELP), + Game::Read(node + Offsets::OFF_CONSOLE_COMMAND_HANDLER), + Game::Read(node + Offsets::OFF_CONSOLE_COMMAND_CATEGORY), + }; + node = Game::Read(node + linkOffset + 4); + if (command.name != nullptr) // a node the registrar never finished + fn(command); + } +} + +} // namespace Console::Registry diff --git a/src/console/Shell.cpp b/src/console/Shell.cpp index 7d740046..fdb35584 100644 --- a/src/console/Shell.cpp +++ b/src/console/Shell.cpp @@ -45,7 +45,6 @@ namespace Console::Shell { namespace { using ConsoleExec_t = void(__fastcall *)(const char *line, int addToHistory); -using ConsoleWrite_t = void(__fastcall *)(const char *line, int colorType); using ConsoleSetKey_t = void(__fastcall *)(int keyCode); // `ConsoleExec(command)` — run a console command line. @@ -74,8 +73,8 @@ int __fastcall Script_ConsoleEcho(void *L) { if (colorType < 0 || colorType >= Offsets::CONSOLE_COLOR_COUNT) colorType = 0; } - reinterpret_cast(Offsets::FUN_CONSOLE_WRITE)(Game::Lua::ToString(L, 1), - colorType); + Game::Console::Write(Game::Lua::ToString(L, 1), + static_cast(colorType)); return 0; } diff --git a/src/interface/Export.cpp b/src/interface/Export.cpp index d8aa722e..bcc6e5eb 100644 --- a/src/interface/Export.cpp +++ b/src/interface/Export.cpp @@ -89,6 +89,7 @@ // on-disk addons live in no archive's listfile, so they're never // enumerated and never re-exported. +#include "Common.h" #include "Game.h" #include "Offsets.h" #include "debug/Log.h" @@ -154,26 +155,8 @@ bool HasExtension(const char *name, const char *const *exts, int count) { return false; } -// Create every parent directory of `relPath` (a backslash-separated -// path, e.g. "BlizzardInterfaceCode\FrameXML\Foo.lua"). Each component -// is created relative to the working directory; existing dirs are a -// no-op. -void EnsureParentDirs(const std::string &relPath) { - std::string accum; - for (size_t i = 0; i < relPath.size(); ++i) { - const char c = relPath[i]; - if (c == '\\' || c == '/') { - if (!accum.empty()) - CreateDirectoryA(accum.c_str(), nullptr); - accum.push_back('\\'); - } else { - accum.push_back(c); - } - } -} - bool WriteFileToDisk(const std::string &relPath, const void *data, unsigned int size) { - EnsureParentDirs(relPath); + Common::EnsureParentDirs(relPath.c_str()); HANDLE h = CreateFileA(relPath.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (h == INVALID_HANDLE_VALUE) @@ -516,7 +499,7 @@ bool FirstTokenEquals(const char *s, const char *token) { return end == '\0' || end == ' ' || end == '\t'; } -int __fastcall Console_ExportInterfaceFiles(void * /*unused*/, const char *args) { +int __fastcall Console_ExportInterfaceFiles(const char * /*command*/, const char *args) { const char *p = (args != nullptr) ? args : ""; while (*p == ' ' || *p == '\t') ++p; @@ -553,7 +536,7 @@ int __fastcall Console_ExportInterfaceFiles(void * /*unused*/, const char *args) // working directory. No subcommand — there's only one thing to export. // Unions the MPQ (listfile) with a `.text` path-getter scan so it gets // the complete set the client loads, including DBCs the listfile omits. -int __fastcall Console_ExportDBCFiles(void * /*unused*/, const char * /*args*/) { +int __fastcall Console_ExportDBCFiles(const char * /*command*/, const char * /*args*/) { int skipped = 0; const int written = ExportDBC("DBFilesClient", &skipped); @@ -572,7 +555,7 @@ int __fastcall Console_ExportDBCFiles(void * /*unused*/, const char * /*args*/) // the order of a gigabyte and takes a while. The argument can only // restrict which archive entries match — every written path comes from // the listfile, never from the argument. -int __fastcall Console_ExportSoundFiles(void * /*unused*/, const char *args) { +int __fastcall Console_ExportSoundFiles(const char * /*command*/, const char *args) { static const char kRoot[] = "Sound\\"; constexpr size_t kRootLen = sizeof(kRoot) - 1;