From 14b4469779c60fc157fbf40deb814a7acbefa612 Mon Sep 17 00:00:00 2001 From: Jason Falk Date: Sun, 6 Sep 2026 14:12:37 -0700 Subject: [PATCH] Improve minimap lifecycle, ownership, diagnostics, and quality checks for v1.6.0 --- .gitattributes | 2 + .github/ISSUE_TEMPLATE/bug_report.md | 5 +- .github/PULL_REQUEST_TEMPLATE.md | 13 +- .github/workflows/quality.yml | 68 +++ .luacheckrc | 101 +++- .pkgmeta | 28 ++ AGENTS.md | 66 +-- CHANGELOG.md | 22 + CONTRIBUTING.md | 64 ++- ClassyMap.lua | 720 +++++++++++++++++++-------- ClassyMap.toc | 4 +- Core/core_spec.lua | 85 +++- Core/init.lua | 113 +++-- Libs/libs.json | 10 +- Locales/deDE.lua | 3 +- Locales/enUS.lua | 49 ++ Locales/esES.lua | 3 +- Locales/esMX.lua | 3 +- Locales/koKR.lua | 3 +- Locales/ptBR.lua | 3 +- Locales/ruRU.lua | 6 +- Locales/zhCN.lua | 3 +- Locales/zhTW.lua | 3 +- Mechanic.lua | 253 ++++++---- README.md | 58 ++- Settings.lua | 110 ++-- docs/quality-review.md | 42 ++ docs/runtime-design.md | 47 ++ tests/ace_integration.lua | 180 +++++++ tests/check_repo.py | 71 +++ tests/mechanic_regressions.lua | 211 ++++++++ tests/run_core.lua | 85 ++++ tests/runtime_regressions.lua | 403 +++++++++++++++ tests/settings_regressions.lua | 149 ++++++ tests/support/assertions.lua | 44 ++ tests/support/wow_mock.lua | 662 ++++++++++++++++++++++++ 36 files changed, 3231 insertions(+), 461 deletions(-) create mode 100644 .gitattributes create mode 100644 .github/workflows/quality.yml create mode 100644 docs/quality-review.md create mode 100644 docs/runtime-design.md create mode 100644 tests/ace_integration.lua create mode 100644 tests/check_repo.py create mode 100644 tests/mechanic_regressions.lua create mode 100644 tests/run_core.lua create mode 100644 tests/runtime_regressions.lua create mode 100644 tests/settings_regressions.lua create mode 100644 tests/support/assertions.lua create mode 100644 tests/support/wow_mock.lua diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..c592792 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Keep Lua formatter output stable across Windows development and Linux CI. +*.lua text eol=lf diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 145a1e7..64da740 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -26,9 +26,10 @@ What actually happened. ## Environment -- **WoW Version**: (e.g., 11.0.5 Retail, Midnight Beta) -- **Interface Version**: (from TOC) +- **Addon Version**: (from ClassyMap.toc) +- **WoW Version / Build / Client**: (actual game version and build, Retail or Beta) - **Other Addons**: (list any that might interact, or "none") +- **Context**: (in combat, using Edit Mode, switching profiles, or after a reload) ## Lua Errors diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 82f8850..7dbbc76 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -15,19 +15,22 @@ Fixes # (issue number, if applicable) ## Testing Done -- [ ] Tested on WoW Retail -- [ ] Tested on Midnight Beta (if available) +List commands/results and the exact client version/build tested. Mark live checks N/A for documentation-only changes, or state what remains unverified. + +- [ ] Relevant offline checks from CONTRIBUTING.md pass +- [ ] Tested runtime changes on the client targeted by ClassyMap.toc - [ ] Addon loads without errors - [ ] Minimap mask is square +- [ ] `GetMinimapShape()` reports `SQUARE` - [ ] Border displays correctly and settings update live -- [ ] No Lua errors in combat +- [ ] Settings persist and profile switching/copying/resetting refreshes correctly +- [ ] Combat changes apply after combat without Lua errors ## Checklist - [ ] My code follows the project's style guidelines -- [ ] I have read [CONTRIBUTING.md](CONTRIBUTING.md) +- [ ] I have read [CONTRIBUTING.md](../CONTRIBUTING.md) - [ ] I have updated documentation if needed -- [ ] I have tested my changes in-game ## Screenshots diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml new file mode 100644 index 0000000..7f005c2 --- /dev/null +++ b/.github/workflows/quality.yml @@ -0,0 +1,68 @@ +name: Quality + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + lua: + name: Lua 5.1, manifest, tests, lint, and format + runs-on: ubuntu-24.04 + env: + LUACHECK_VERSION: "0.23.0" + STYLUA_VERSION: "2.3.1" + + steps: + - name: Check out repository + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + persist-credentials: false + + - name: Install Lua tooling + shell: bash + run: | + set -euo pipefail + sudo apt-get update + sudo apt-get install --no-install-recommends --yes curl liblua5.1-0-dev lua5.1 luarocks unzip + luarocks --lua-version=5.1 --tree "$RUNNER_TEMP/luarocks" install luacheck "$LUACHECK_VERSION" + echo "$RUNNER_TEMP/luarocks/bin" >> "$GITHUB_PATH" + curl --fail --location --silent --show-error \ + --output "$RUNNER_TEMP/stylua.zip" \ + "https://github.com/JohnnyMorganz/StyLua/releases/download/v${STYLUA_VERSION}/stylua-linux-x86_64.zip" + unzip -q "$RUNNER_TEMP/stylua.zip" -d "$RUNNER_TEMP/stylua" + chmod +x "$RUNNER_TEMP/stylua/stylua" + echo "$RUNNER_TEMP/stylua" >> "$GITHUB_PATH" + + - name: Verify tool versions + run: | + set -euo pipefail + lua5.1 -v + luacheck --version + stylua --version + + - name: Run offline regression tests + run: | + set -euo pipefail + lua5.1 tests/run_core.lua + lua5.1 tests/run_core.lua --fencore + lua5.1 tests/runtime_regressions.lua + lua5.1 tests/settings_regressions.lua + lua5.1 tests/ace_integration.lua + lua5.1 tests/mechanic_regressions.lua + + - name: Validate manifest, dependencies, and localization + run: python3 tests/check_repo.py --lua lua5.1 + + - name: Lint first-party Lua + run: luacheck . --config .luacheckrc + + - name: Check first-party Lua formatting + shell: bash + run: | + set -euo pipefail + stylua --check --syntax Lua51 \ + ClassyMap.lua Settings.lua Mechanic.lua Core/init.lua Locales/*.lua diff --git a/.luacheckrc b/.luacheckrc index 2908dd8..279da41 100644 --- a/.luacheckrc +++ b/.luacheckrc @@ -1,18 +1,97 @@ --- ClassyMap Luacheck configuration --- Extends the central configuration +-- ClassyMap Luacheck configuration. +-- +-- Use the shared configuration when this repository is checked out beside +-- ADDON_DEV. Keep a small fallback here so a standalone clone can still run +-- Luacheck without requiring the wider development workspace. -local base = dofile("../ADDON_DEV/Linting/.luacheckrc") +local function add_unique(list, value) + for _, existing in ipairs(list) do + if existing == value then + return + end + end + table.insert(list, value) +end + +local addon_globals = { + "ClassyMap", + "ClassyMapDB", + "ClassyMapCore", + "ClassyMapMechanic", + "GetMinimapShape", +} + +-- WoW frames and APIs referenced by the minimap integration. Keeping this +-- list explicit preserves Luacheck's useful undefined-global warnings. +local addon_read_globals = { + "AddonCompartmentFrame", + "C_AddOns", + "C_Texture", + "C_Timer", + "CreateFrame", + "debugprofilestop", + "ExpansionLandingPage", + "ExpansionLandingPageMinimapButton", + "GameTimeFrame", + "GameTooltip", + "GetTime", + "geterrorhandler", + "hooksecurefunc", + "HybridMinimap", + "InCombatLockdown", + "IsLoggedIn", + "Minimap", + "MinimapCluster", + "MinimapCompassTexture", + "Minimap_Update", + "MinimapZoneText", + "TimeManagerClockButton", + "TimeManagerClockTicker", + "ToggleEncounterJournal", +} + +local ok, shared = pcall(dofile, "../ADDON_DEV/Linting/.luacheckrc") +local base = ok and type(shared) == "table" and shared or { + std = "lua51", + max_line_length = false, + codes = true, + quiet = 1, + exclude_files = { + "**/Libs/**", + "**/*_spec.lua", + "tests/**", + ".luacheckrc", + }, + globals = { "_G", "SlashCmdList" }, + read_globals = { + "LibStub", + "wipe", + table = { fields = { "unpack", "wipe" } }, + }, + ignore = { + "212/self", + "212/_.*", + "631", + }, +} --- Inherit everything from base std = base.std max_line_length = base.max_line_length codes = base.codes -ignore = base.ignore -exclude_files = base.exclude_files -read_globals = base.read_globals +quiet = base.quiet +exclude_files = base.exclude_files or {} +globals = base.globals or {} +read_globals = base.read_globals or {} +ignore = base.ignore or {} + +for _, name in ipairs(addon_globals) do + add_unique(globals, name) +end --- Addon-specific globals -globals = base.globals -table.insert(globals, "ClassyMap") -table.insert(globals, "ClassyMapDB") +for _, name in ipairs(addon_read_globals) do + add_unique(read_globals, name) +end +-- Busted-style specs live beside the pure Core implementation and are not +-- first-party addon runtime code. +add_unique(exclude_files, "**/*_spec.lua") diff --git a/.pkgmeta b/.pkgmeta index 0d04d7d..867e3f2 100644 --- a/.pkgmeta +++ b/.pkgmeta @@ -6,14 +6,42 @@ ignore: - .git - .github - .gitignore + - .cursorignore + - .gitattributes - .luacheckrc - .markdownlint.json - .vscode - AGENTS.md - CHANGELOG.md + - CONTRIBUTING.md - LICENSE - README.md + # Development tests and review notes are not part of the addon package. + - tests + - docs + - Core/core_spec.lua + + # FenCore's development-only material is not loaded by FenCore.xml. + - Libs/FenCore/AGENTS.md + - Libs/FenCore/Docs + - Libs/FenCore/PLAN + - Libs/FenCore/Tests + - Libs/FenCore/README.md + - Libs/FenCore/Core/!sandbox_bootstrap.lua + - Libs/FenCore/Core/zz_sandbox_domains.lua + - Libs/FenCore/FenCore.toc + + # Libraries retained in the checkout from the original template but not + # referenced by embeds.xml or the addon source. + - Libs/AceHook-3.0 + - Libs/LibDataBroker-1.1 + - Libs/LibDBIcon-1.0 + - Assets/classymap-logo-400.png + + # Dependency tracking is for the repository and Mechanic tooling only. + - Libs/libs.json + manual-changelog: filename: CHANGELOG.md markup-type: markdown diff --git a/AGENTS.md b/AGENTS.md index 972c7d7..e2cf858 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,7 @@ Technical reference for AI agents modifying this addon. -For shared patterns, library references, and development guides, see **[Mechanic](../Mechanic/AGENTS.md)**. +In the shared addon workspace, also follow **[Mechanic](../Mechanic/AGENTS.md)** for tooling and diagnostic guidance. Standalone clones can use the offline workflow in [CONTRIBUTING.md](CONTRIBUTING.md) without that sibling checkout. --- @@ -22,7 +22,7 @@ A simple addon that transforms the default circular minimap into a clean square - Provides a modern, flat aesthetic for the minimap - Integrates with Blizzard's addon compartment system -- Maintains compatibility with other minimap-aware addons +- Reports the square shape and cooperates with observable changes from other addons --- @@ -30,19 +30,24 @@ A simple addon that transforms the default circular minimap into a clean square | File | Purpose | |------|---------| -| `ClassyMap.lua` | Main addon entry, minimap modification, UI | +| `ClassyMap.lua` | Lifecycle, scoped refresh scheduler, frame ownership, minimap UI | | `Core/init.lua` | Pure Lua core layer (validation, combat queue) - sandbox-compatible | | `Core/core_spec.lua` | Busted unit tests for Core layer | | `Settings.lua` | AceConfig settings UI | | `Mechanic.lua` | Mechanic integration for debugging/testing | | `Locales/` | 11 locale files (enUS baseline + 10 translations) | | `ClassyMap.toc` | Metadata | +| `embeds.xml` / `Libs/libs.json` | Library load order / dependency inventory | +| `tests/` | Standalone offline regression and manifest checks | +| `.github/workflows/quality.yml` | CI commands and tool versions | +| `docs/quality-review.md` | Review findings, resolved issues, and live verification limits | +| `docs/runtime-design.md` | Refresh scopes, ownership policy, metric semantics, and test boundaries | --- ## Tooling & Workflow -This addon uses **Mechanic** for development tooling: +Use connected **Mechanic MCP** tools when available. Names below are registry names; inspect current schemas through `commands.list` for exposed tool names and arguments. | Task | MCP Tool | |------|----------| @@ -55,18 +60,24 @@ This addon uses **Mechanic** for development tooling: | Locale Check | `locale.validate` with addon="ClassyMap" | **Development Loop:** -1. Make code changes -2. Ask user to `/reload` in WoW -3. Wait for confirmation -4. Call `addon.output` with agent_mode=true to get errors/logs + +1. Make changes and run the relevant offline checks in [CONTRIBUTING.md](CONTRIBUTING.md). +2. For runtime changes, identify the intended installed client and diagnostic target, then install/sync the changed addon. A development checkout is not automatically installed. +3. Ask the user to `/reload` in that client and wait for confirmation. +4. Only then call `addon.output` with `agent_mode=true` and the same explicit diagnostic target to inspect errors/logs. + +Documentation-only changes do not require a game reload. If Mechanic MCP is unavailable, report that limitation and use source inspection and isolated offline checks; do not substitute live CLI operations or claim installed-game verification. ### Localization + All user-facing strings must be wrapped in `L["KEY"]`. -**Coverage:** 34 keys across 11 locales (enUS baseline + 10 translations). +**Coverage:** `Locales/enUS.lua` defines the baseline for 11 locales. New Mechanic diagnostic strings use English fallback until translated in the other 10 locales. Validate with: `locale.validate` with addon="ClassyMap" +When Mechanic MCP is unavailable, use the isolated offline checks in [CONTRIBUTING.md](CONTRIBUTING.md). These do not validate installed game state. + --- ## FenCore Integration @@ -77,12 +88,7 @@ ClassyMap uses **FenCore** for pure logic in the Core layer: |--------|-------| | `FenCore.Math` | `Clamp()` for settings validation (border size, font size, colors) | -**Pattern:** Core/init.lua delegates to FenCore with graceful fallbacks: -```lua -local FenCore = _G.FenCore -local Math = FenCore and FenCore.Math -local Clamp = Math and Math.Clamp or function(n, min, max) ... end -``` +**Pattern:** [Core/init.lua](Core/init.lua) validates finite numeric inputs and delegates clamping to `FenCore.Math.Clamp` when available, with a local fallback. Keep this layer independent of WoW UI APIs; run the Core tests both with and without bundled FenCore. **Libraries:** See `Libs/libs.json` for dependency tracking. @@ -90,23 +96,26 @@ local Clamp = Math and Math.Clamp or function(n, min, max) ... end ## Architecture +See [runtime-design.md](docs/runtime-design.md) for the current scheduling and ownership contract. + +- Route UI and profile updates through `ClassyMap:RequestRefresh(scope)`, using `all`, `border`, `fonts`, `visibility`, or `layout`. Full refreshes subsume partial work; visibility also requests layout. Read the active profile when executing queued work. +- Modify observable Blizzard frame properties through `OwnSet`; addon-created textures/buttons may be updated directly inside a refresh. Mask and blob properties without readable originals have explicit restoration limits. +- Preserve generation cancellation, combat deferral, and conditional hooks when changing lifecycle behavior. +- `OnDisable` restores eligible observable geometry/styles. Square mask effects and shape reporting remain until reload; do not advertise complete runtime disable. +- Record executed categories, including independent font/layout work. `Refresh` is an inclusive metric and must not be summed with its components. Mechanic breakdown values are rates in ms/s; see the diagnostic snapshot for cumulative durations and counts. + ### How It Works -1. On load, applies a square mask texture to the minimap -2. Globally overrides `GetMinimapShape()` so other addons know the minimap is square -3. Creates a clean border frame around the minimap -4. Registers with the addon compartment for easy access +1. Initializes AceDB, settings, slash commands, and the native addon compartment entry. +2. Schedules changes after enable/world readiness and outside combat. +3. Applies the square mask and manages `GetMinimapShape()` reporting, respecting a detected replacement by another addon. +4. Draws the border with four ARTWORK textures, styles text, and lays out the selected minimap controls. -### Key Implementation +### Updating Settings ```lua --- Square mask -Minimap:SetMaskTexture("Interface\\BUTTONS\\WHITE8X8") - --- Shape override for other addons -function GetMinimapShape() - return "SQUARE" -end +-- After validating and storing a border setting in the active profile: +ClassyMap:RequestRefresh("border") ``` --- @@ -114,5 +123,6 @@ end ## SavedVariables - **Root**: `ClassyMapDB` -- Settings stored via AceDB profile system +- **Active settings**: `ns.ClassyMap.db.profile`; do not read a presumed `ClassyMapDB.profile` directly. +- AceDB profile changes, copies, and resets request a full refresh and notify the settings UI. diff --git a/CHANGELOG.md b/CHANGELOG.md index c136af2..61051cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,28 @@ All notable changes to ClassyMap will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +## [Unreleased] + +## [1.6.0] - 2026-09-06 + +### Added + +- Scoped refresh scheduling that combines pending work and waits for login/combat readiness. +- Observable frame ownership and conditional hooks, with safe partial restoration on disable. Full removal of square mask effects still requires reload. +- Performance invocation counts, cumulative/average/maximum durations, rate reporting, and a Reset Metrics tool. +- Strict offline UI mocks, integration tests using bundled Ace libraries, and automated quality checks. +- AceDB profile controls for creating, copying, resetting, and switching settings profiles. + +### Changed + +- Updated user and contributor documentation for current settings, runtime behavior, and offline/live validation workflows. + +### Fixed + +- Combat queue event registration, nested actions, and nil arguments. +- Recursive layout updates, clock text targeting, and zone-color restoration. +- Settings validation and profile refreshes; misleading diagnostic controls and performance units. + ## [1.5.0] - 2026-04-30 ### Changed diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2bff923..617ec00 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,22 +5,24 @@ Thanks for your interest in contributing! ClassyMap is a simple addon that trans ## Getting Started 1. **Fork and clone** the repository -2. **Place the addon** in your WoW addons directory: +2. **Run the offline checks** below after making code changes. +3. **Install or sync the changed addon** to the client you will test. Ensure `ClassyMap.toc` sits directly in: ``` World of Warcraft\_retail_\Interface\AddOns\ClassyMap\ ``` -3. **Test in-game** with `/reload` after making changes +4. **Test runtime changes in-game**. Restart for a first installation; use `/reload` for updates to an already loaded addon. Documentation-only changes need document checks, not a game reload. ## Development Guidelines ### Read the Docs First -- [AGENTS.md](AGENTS.md) – Project intent, conventions, and technical reference -- [ADDON_DEV/AGENTS.md](../../ADDON_DEV/AGENTS.md) – Shared development library index +- [AGENTS.md](AGENTS.md) – Addon-specific conventions and validation workflow +- [runtime-design.md](docs/runtime-design.md) – Refresh scheduling, ownership, metrics, and test boundaries +- [Mechanic/AGENTS.md](../Mechanic/AGENTS.md) – Additional tooling guidance when using the shared workspace; not required for standalone offline checks ### Code Style -- **Lua 5.1** syntax (WoW's embedded Lua version) +- **Lua 5.1-compatible** syntax; offline mocks cover only the WoW APIs explicitly modeled by the tests - **Local variables** – Prefer `local` for performance and scope control - **Ace3 Framework** – Use the included Ace3 libraries for settings and initialization @@ -28,15 +30,18 @@ Thanks for your interest in contributing! ClassyMap is a simple addon that trans This addon prioritizes a minimal footprint: -- **CPU**: Minimal impact as it primarily modifies frame masks and applies a border - Avoid per-frame table allocations or `OnUpdate` polling +- Route changes through `RequestRefresh` with the smallest appropriate scope so repeated requests coalesce +- Use Mechanic's invocation counts and cumulative/peak durations to assess refresh work. Reported ms/s values are observation-window averages, not instantaneous CPU measurements. -### Midnight Compatibility +### Current Client Compatibility -The addon targets Interface 120001 (Midnight). When adding features: +The declared client target is Interface 120100 in [ClassyMap.toc](ClassyMap.toc). Record the actual client version/build used for live testing. When adding features: - Ensure modifications are resilient to UI updates -- Use established patterns for frame hijacking and mask application +- Follow the `OwnSet` ownership and conditional-restoration contract; preserve combat deferral and stale-callback cancellation +- Keep required library load order in `embeds.xml` aligned with `Libs/libs.json` and packaging rules in `.pkgmeta` +- Wrap user-facing strings in `L["KEY"]`, define the English baseline, and preserve the locale registration guards ## Submitting Changes @@ -44,7 +49,7 @@ The addon targets Interface 120001 (Midnight). When adding features: Open an issue with: -- WoW version and client (Retail/Beta) +- Addon version, WoW version/build, and client (Retail or Beta) - Steps to reproduce - Any Lua errors from BugSack/BugGrabber @@ -59,7 +64,7 @@ Open an issue describing: 1. **Create a branch** from `main` 2. **Keep changes focused** – one feature or fix per PR -3. **Test in-game** on both Retail and Beta if possible +3. **Run relevant offline checks** and test runtime changes on the target client; record any live testing still outstanding 4. **Update docs** if adding settings or slash commands 5. **Describe your changes** in the PR description @@ -68,18 +73,45 @@ Open an issue describing: | File | Purpose | |------|---------| | `ClassyMap.toc` | Addon manifest | -| `Core.lua` | Minimap mask, border, and shape logic | +| `ClassyMap.lua` | Minimap mask, border, shape, and layout logic | +| `Core/init.lua` | Pure validation and combat queue logic | | `Settings.lua` | AceConfig settings panel | +| `Mechanic.lua` | Optional Mechanic integration and diagnostics | +| `Core/core_spec.lua` / `tests/` | Core tests, strict UI mocks, real Ace integration, and repository checks | +| `.github/workflows/quality.yml` | Automated checks and tool versions | ## Testing Checklist -Before submitting: +For runtime changes, exercise the affected behavior in-game after offline checks: - [ ] Addon loads without errors (`/reload`) - [ ] Minimap is correctly masked as a square -- [ ] Border appears and updates correctly via settings -- [ ] Settings persist across sessions -- [ ] No Lua errors in combat +- [ ] Border, fonts, and visibility settings update correctly; border size 0 hides it +- [ ] Settings persist across reloads and profile switching/copying/resetting refreshes the UI +- [ ] Repeated settings changes in combat apply after combat without Lua errors +- [ ] Affected layouts work with Edit Mode, late-loaded clock/hybrid minimap UI, and other minimap addons + +Offline tests cannot establish taint safety, actual rendering, or compatibility with every addon. The Mechanic mask diagnostic requires manual visual confirmation. Fully removing square mask effects requires disabling ClassyMap and reloading. + +### Offline Checks + +Run these from the repository root with Lua 5.1, Python 3.9+, Luacheck 0.23.0, and StyLua 2.3.1 available, matching [CI](.github/workflows/quality.yml). The commands below use a POSIX shell; substitute executable paths and expand locale file arguments as needed for your shell. + +```sh +lua5.1 tests/run_core.lua +lua5.1 tests/run_core.lua --fencore +lua5.1 tests/runtime_regressions.lua +lua5.1 tests/settings_regressions.lua +lua5.1 tests/ace_integration.lua +lua5.1 tests/mechanic_regressions.lua +python3 tests/check_repo.py --lua lua5.1 +luacheck . --config .luacheckrc +stylua --check --syntax Lua51 ClassyMap.lua Settings.lua Mechanic.lua Core/init.lua Locales/*.lua +``` + +The Core suite runs with both fallback math and bundled FenCore. Runtime and settings suites use strict UI mocks; the Ace integration suite loads the bundled lifecycle/profile libraries. Repository checks validate manifest paths, Lua syntax, packaging exclusions, and localization. These checks do not read installed game state. + +For documentation-only changes, check descriptions against source, verify local links and command paths, and run `git diff --check`. ## Questions? diff --git a/ClassyMap.lua b/ClassyMap.lua index d6f1135..d846bd5 100644 --- a/ClassyMap.lua +++ b/ClassyMap.lua @@ -1,4 +1,4 @@ -local addonName, ns = ... +local _, ns = ... local ClassyMap = LibStub("AceAddon-3.0"):NewAddon("ClassyMap", "AceConsole-3.0", "AceEvent-3.0") local L = LibStub("AceLocale-3.0"):GetLocale("ClassyMap") local LSM = LibStub("LibSharedMedia-3.0") @@ -10,6 +10,216 @@ local Core = ClassyMapCore local hiddenFrame = CreateFrame("Frame") hiddenFrame:Hide() +-- Capture observable Blizzard state before writing it. Once another owner changes +-- a property, leave that property alone until the next enable cycle. +local unpackValues = unpack +local function Pack(...) + return { n = select("#", ...), ... } +end +local function Equal(a, b) + if a.n ~= b.n then + return false + end + for i = 1, a.n do + if type(a[i]) == "table" and a[i].n then + if type(b[i]) ~= "table" or not Equal(a[i], b[i]) then + return false + end + elseif a[i] ~= b[i] then + return false + end + end + return true +end +local getters = { + SetUseMaskTexture = "GetUseMaskTexture", + SetParent = "GetParent", + SetWidth = "GetWidth", + SetHeight = "GetHeight", + SetFrameStrata = "GetFrameStrata", + SetScale = "GetScale", + SetAlpha = "GetAlpha", + SetFont = "GetFont", + SetTextColor = "GetTextColor", + SetTexture = "GetTexture", + SetJustifyH = "GetJustifyH", + SetJustifyV = "GetJustifyV", + SetWordWrap = "CanWordWrap", + SetClampedToScreen = "IsClampedToScreen", + SetClampRectInsets = "GetClampRectInsets", +} +local function ReadProperty(frame, key) + if key == "points" then + if not frame.GetNumPoints or not frame.GetPoint then + return nil + end + local points = { n = frame:GetNumPoints() } + for i = 1, points.n do + points[i] = Pack(frame:GetPoint(i)) + end + return points + elseif key == "shown" then + return frame.IsShown and Pack(frame:IsShown()) + end + local getter = getters[key] + return getter and frame[getter] and Pack(frame[getter](frame)) +end +function ClassyMap:OwnSet(frame, method, ...) + if not frame then + return + end + local key = (method == "ClearAllPoints" or method == "SetPoint" or method == "SetAllPoints") and "points" + or (method == "Show" or method == "Hide") and "shown" + or method + self.ownedFrames = self.ownedFrames or {} + self.frameOriginals = self.frameOriginals or {} + if not self.frameOriginals[frame] then + -- Capture geometry before parenting/anchoring changes can alter derived + -- dimensions; only properties actually written are restored later. + self.frameOriginals[frame] = { + points = ReadProperty(frame, "points"), + SetParent = ReadProperty(frame, "SetParent"), + SetWidth = ReadProperty(frame, "SetWidth"), + SetHeight = ReadProperty(frame, "SetHeight"), + } + end + local properties = self.ownedFrames[frame] or {} + self.ownedFrames[frame] = properties + local current = ReadProperty(frame, key) + local state = properties[key] + if state then + if state.released then + return + end + if current and not Equal(current, state.last) then + state.released = true + return + end + elseif current then + local geometry = key == "points" or key == "SetParent" or key == "SetWidth" or key == "SetHeight" + state = { original = geometry and self.frameOriginals[frame][key] or current, last = current } + properties[key] = state + end + if state and HybridMinimap and (frame == HybridMinimap.CircleMask or frame == HybridMinimap.MapCanvas) then + -- Hybrid and base masks must continue to agree with square shape reporting + -- until reload; base mask state cannot be restored from an API getter. + state.keepOnDisable = key == "SetTexture" or key == "SetUseMaskTexture" + end + -- Remember which other properties still belong to us before this mutation. + local retained = {} + for otherKey, otherState in pairs(properties) do + local value = ReadProperty(frame, otherKey) + if not otherState.released and otherState.last and value and Equal(value, otherState.last) then + retained[otherKey] = true + end + end + frame[method](frame, ...) + if state then + state.last = ReadProperty(frame, key) + end + for otherKey in pairs(retained) do + properties[otherKey].last = ReadProperty(frame, otherKey) + end +end +local restoreOrder = { + "SetParent", + "SetScale", + "SetWidth", + "SetHeight", + "points", + "SetFrameStrata", + "SetClampedToScreen", + "SetClampRectInsets", + "SetFont", + "SetJustifyH", + "SetJustifyV", + "SetWordWrap", + "SetTextColor", + "SetTexture", + "SetUseMaskTexture", + "SetAlpha", + "shown", +} +function ClassyMap:RestoreOwnedFrames() + -- Decide ownership before restoring anything: a parent/anchor restoration can + -- itself change derived dimensions on a different frame. + local eligible = {} + for frame, properties in pairs(self.ownedFrames or {}) do + eligible[frame] = {} + for key, state in pairs(properties) do + local current = ReadProperty(frame, key) + eligible[frame][key] = not state.released + and not state.keepOnDisable + and current + and Equal(current, state.last) + end + end + for _, key in ipairs(restoreOrder) do + for frame, properties in pairs(self.ownedFrames or {}) do + local state = properties[key] + if state and eligible[frame][key] then + local values = state.original + if key == "points" then + frame:ClearAllPoints() + for i = 1, values.n do + frame:SetPoint(unpackValues(values[i], 1, values[i].n)) + end + elseif key == "shown" then + if values[1] then + frame:Show() + else + frame:Hide() + end + else + frame[key](frame, unpackValues(values, 1, values.n)) + end + end + end + end + self.ownedFrames = nil + self.frameOriginals = nil + self.zoomParentIn = nil + self.zoomParentOut = nil + self.zoneColorOverridden = nil + -- Mask and blob APIs expose no matching getters. Keep square shape reporting + -- consistent with the remaining square mask; a reload fully removes these. + for _, texture in pairs(self.borders or {}) do + texture:Hide() + end + if self.expansionReplacementBtn then + self.expansionReplacementBtn:Hide() + end + self.restorePending = nil +end + +-- Native color/visibility updates are expected while we own their policy. +-- Refresh the comparison baseline only from the corresponding Blizzard hook. +function ClassyMap:AcceptNativeUpdate(frame, key) + local properties = self.ownedFrames and self.ownedFrames[frame] + local state = properties and properties[key] + if state and not state.released then + local value = ReadProperty(frame, key) + if value then + state.last = value + state.original = value + end + return true + end +end + +function ClassyMap:OwnsProperty(frame, key) + local properties = self.ownedFrames and self.ownedFrames[frame] + local state = properties and properties[key] + local current = state and ReadProperty(frame, key) + if state and not state.released and current and Equal(current, state.last) then + return true + end + if state then + state.released = true + end + return false +end + -- ============================================================================= -- Default Configuration -- ============================================================================= @@ -48,32 +258,44 @@ local defaults = { -- ============================================================================= function ClassyMap:RunSafe(func, ...) + if self.runtimeEnabled == false then + return + end + local generation = self.refreshGeneration if InCombatLockdown() then -- Queue action for when combat ends Core:QueueAction(function(...) - func(self, ...) - end, { ... }) - self:RegisterEvent("PLAYER_REGEN_ENABLED") + if generation == self.refreshGeneration and self.runtimeEnabled ~= false then + func(self, ...) + end + end, { n = select("#", ...), ... }) + self:RegisterEvent("PLAYER_REGEN_ENABLED", "ProcessCombatQueue") else func(self, ...) end end function ClassyMap:ProcessCombatQueue() - local count = Core:GetQueueLength() - if count > 0 then - for i = 1, count do - local item = Core.combatQueue[i] - if item then - local success, err = pcall(item.func, unpack(item.args)) - if not success then - geterrorhandler()(err) - end + if InCombatLockdown() then + return + end + if self.restorePending then + self:RestoreOwnedFrames() + end + Core:ProcessQueue(geterrorhandler()) + if self.pendingRefresh then + self:RequestRefresh(next(self.pendingRefresh)) + end + if Core:GetQueueLength() == 0 then + self:UnregisterEvent("PLAYER_REGEN_ENABLED") + else + local generation = self.refreshGeneration + C_Timer.After(0, function() + if generation == self.refreshGeneration then + self:ProcessCombatQueue() end - end - Core:ClearQueue() + end) end - self:UnregisterEvent("PLAYER_REGEN_ENABLED") end -- ============================================================================= @@ -96,39 +318,33 @@ function ClassyMap:OnInitialize() }) end - self:RegisterEvent("PLAYER_REGEN_ENABLED", "ProcessCombatQueue") - - -- Defensive Patch for Blizzard Midnight Beta Bug: - -- Blizzard's LandingPageRenownButtonMixin:UpdateButtonTextures crashes if covenantData is nil. - -- We hook it to ensure it only runs if data is valid. - self:RegisterEvent("ADDON_LOADED", function(_, addon) - if addon == "Blizzard_LandingSoulbinds" then - if LandingPageRenownButtonMixin and LandingPageRenownButtonMixin.UpdateButtonTextures then - local old = LandingPageRenownButtonMixin.UpdateButtonTextures - LandingPageRenownButtonMixin.UpdateButtonTextures = function(self) - local id = C_Covenants.GetActiveCovenantID() - if id and id ~= 0 then - local data = C_Covenants.GetCovenantData(id) - if data and data.textureKit then - return old(self) - end - end - -- If we get here, data is missing or invalid. Hide the button to prevent crash. - self:Hide() - end - end - end - end) - self:Print(L["Loaded. Type /classymap or /cm for options."]) end function ClassyMap:OnEnable() + self.runtimeEnabled = true + self.refreshGeneration = (self.refreshGeneration or 0) + 1 + self.refreshScheduled = nil + self.restorePending = nil + if self.restoreFrame then + self.restoreFrame:UnregisterEvent("PLAYER_REGEN_ENABLED") + end + self.worldReady = IsLoggedIn() + self:RegisterEvent("ADDON_LOADED", "OnBlizzardAddonLoaded") + if Minimap_Update and not self.hookedZoneColor then + hooksecurefunc("Minimap_Update", function() + if self.runtimeEnabled and self:AcceptNativeUpdate(MinimapZoneText, "SetTextColor") then + self:RequestRefresh("fonts") + end + end) + self.hookedZoneColor = true + end if IsLoggedIn() then - self:RunSafe(self.ApplyMinimapChanges) + self:RequestRefresh("all") else self:RegisterEvent("PLAYER_ENTERING_WORLD", function() - self:RunSafe(self.ApplyMinimapChanges) + self.worldReady = true + self:RequestRefresh("all") self:UnregisterEvent("PLAYER_ENTERING_WORLD") end) end @@ -139,7 +355,123 @@ function ClassyMap:OnEnable() self:RegisterEvent("ZONE_CHANGED_NEW_AREA", "ApplyFontStyles") end -function ClassyMap:SlashHandler(msg) +function ClassyMap:OnDisable() + self.runtimeEnabled = false + self.refreshGeneration = (self.refreshGeneration or 0) + 1 + self.refreshScheduled = nil + self.pendingRefresh = nil + Core:ClearQueue() + self:UnregisterAllEvents() + if InCombatLockdown() then + self.restorePending = true + -- AceEvent unregisters addon events after OnDisable returns. A private frame + -- owns this one-shot restoration event so it survives that library cleanup. + if not self.restoreFrame then + self.restoreFrame = CreateFrame("Frame") + self.restoreFrame:SetScript("OnEvent", function(frame) + if not InCombatLockdown() then + frame:UnregisterEvent("PLAYER_REGEN_ENABLED") + if self.restorePending and not self.runtimeEnabled then + self:RestoreOwnedFrames() + end + end + end) + end + self.restoreFrame:RegisterEvent("PLAYER_REGEN_ENABLED") + else + self:RestoreOwnedFrames() + end +end + +function ClassyMap:RequestRefresh(scope) + if not self.runtimeEnabled then + return + end + scope = scope or "all" + if scope == "full" then + scope = "all" + end + assert( + scope == "all" or scope == "border" or scope == "fonts" or scope == "visibility" or scope == "layout", + "Unknown refresh scope" + ) + self.pendingRefresh = self.pendingRefresh or {} + self.pendingRefresh[scope] = true + if self.refreshScheduled or not self.worldReady then + return + end + if InCombatLockdown() then + self:RegisterEvent("PLAYER_REGEN_ENABLED", "ProcessCombatQueue") + return + end + self.refreshScheduled = true + local generation = self.refreshGeneration + C_Timer.After(0, function() + if generation ~= self.refreshGeneration or not self.runtimeEnabled then + return + end + self.refreshScheduled = nil + if InCombatLockdown() then + self:RegisterEvent("PLAYER_REGEN_ENABLED", "ProcessCombatQueue") + return + end + local pending = self.pendingRefresh + self.pendingRefresh = nil + if not pending then + return + end + self.executingRefresh = true + local started = debugprofilestop() + local ok, err = pcall(function() + if pending.all then + self:ApplyMinimapChanges() + else + if pending.border then + self:MeasureRefresh("CreateBorder", self.CreateBorder) + end + if pending.visibility then + self:MeasureRefresh("HideClutter", self.HideMinimapClutter) + end + if pending.fonts then + self:MeasureRefresh("ApplyFontStyles", self.ApplyFontStyles) + end + if pending.layout or pending.visibility then + self:MeasureRefresh("FixLayout", self.FixLayout) + end + end + end) + self.executingRefresh = nil + if ClassyMapMechanic then + ClassyMapMechanic:RecordPerfMetric("Refresh", debugprofilestop() - started) + end + if not ok then + geterrorhandler()(err) + end + end) +end + +function ClassyMap:MeasureRefresh(name, action) + local started = debugprofilestop() + local ok, err = pcall(action, self) + if ClassyMapMechanic then + ClassyMapMechanic:RecordPerfMetric(name, debugprofilestop() - started) + end + if not ok then + geterrorhandler()(err) + end +end + +function ClassyMap:OnBlizzardAddonLoaded(_, addon) + if + addon == "Blizzard_TimeManager" + or addon == "Blizzard_HybridMinimap" + or addon == "Blizzard_ExpansionLandingPage" + then + self:ApplyMinimapChanges() + end +end + +function ClassyMap:SlashHandler() ns.Settings:OpenOptions() end @@ -150,12 +482,12 @@ function ClassyMap:SatStyles(f) if not f then return end - f:SetParent(Minimap) - f:SetFrameStrata("DIALOG") - f:Show() + self:OwnSet(f, "SetParent", Minimap) + self:OwnSet(f, "SetFrameStrata", "DIALOG") + self:OwnSet(f, "Show") end -function ClassyMap:FixLayout() +local function ApplyLayout(self) local db = self.db.profile local MARGIN = 4 local STACK_GAP = 2 @@ -163,35 +495,34 @@ function ClassyMap:FixLayout() -- Cluster & Map if MinimapCluster then - MinimapCluster:SetWidth(Minimap:GetWidth()) - MinimapCluster:SetHeight(Minimap:GetHeight()) - MinimapCluster:SetClampedToScreen(false) + self:OwnSet(MinimapCluster, "SetWidth", Minimap:GetWidth()) + self:OwnSet(MinimapCluster, "SetHeight", Minimap:GetHeight()) end if Minimap then - Minimap:ClearAllPoints() - Minimap:SetPoint("CENTER", MinimapCluster, "CENTER", 0, 0) + self:OwnSet(Minimap, "ClearAllPoints") + self:OwnSet(Minimap, "SetPoint", "CENTER", MinimapCluster, "CENTER", 0, 0) end -- Zone Text (Top Center) if MinimapCluster.ZoneTextButton then if not db.hideZoneText then self:SatStyles(MinimapCluster.ZoneTextButton) - MinimapCluster.ZoneTextButton:ClearAllPoints() + self:OwnSet(MinimapCluster.ZoneTextButton, "ClearAllPoints") -- Header Row Alignment (User Tweak: Down 2px from +2 -> 0) - MinimapCluster.ZoneTextButton:SetPoint("TOP", Minimap, "TOP", 0, 0) - MinimapCluster.ZoneTextButton:SetHeight(ICON_SIZE) -- Match Icon Height (24) - MinimapCluster.ZoneTextButton:SetAlpha(1) + self:OwnSet(MinimapCluster.ZoneTextButton, "SetPoint", "TOP", Minimap, "TOP", 0, 0) + self:OwnSet(MinimapCluster.ZoneTextButton, "SetHeight", ICON_SIZE) -- Match Icon Height (24) + self:OwnSet(MinimapCluster.ZoneTextButton, "SetAlpha", 1) -- Centering Text if MinimapZoneText then - MinimapZoneText:ClearAllPoints() - MinimapZoneText:SetAllPoints(MinimapCluster.ZoneTextButton) - MinimapZoneText:SetJustifyH("CENTER") - MinimapZoneText:SetJustifyV("MIDDLE") - MinimapZoneText:SetWordWrap(false) + self:OwnSet(MinimapZoneText, "ClearAllPoints") + self:OwnSet(MinimapZoneText, "SetAllPoints", MinimapCluster.ZoneTextButton) + self:OwnSet(MinimapZoneText, "SetJustifyH", "CENTER") + self:OwnSet(MinimapZoneText, "SetJustifyV", "MIDDLE") + self:OwnSet(MinimapZoneText, "SetWordWrap", false) end else - MinimapCluster.ZoneTextButton:Hide() + self:OwnSet(MinimapCluster.ZoneTextButton, "Hide") end end @@ -199,14 +530,14 @@ function ClassyMap:FixLayout() if TimeManagerClockButton then if not db.hideClock then self:SatStyles(TimeManagerClockButton) - TimeManagerClockButton:ClearAllPoints() - if MinimapCluster.ZoneTextButton then - TimeManagerClockButton:SetPoint("TOP", MinimapCluster.ZoneTextButton, "BOTTOM", 0, 0) + self:OwnSet(TimeManagerClockButton, "ClearAllPoints") + if MinimapCluster.ZoneTextButton and not db.hideZoneText then + self:OwnSet(TimeManagerClockButton, "SetPoint", "TOP", MinimapCluster.ZoneTextButton, "BOTTOM", 0, 0) else - TimeManagerClockButton:SetPoint("TOP", Minimap, "TOP", 0, -MARGIN) + self:OwnSet(TimeManagerClockButton, "SetPoint", "TOP", Minimap, "TOP", 0, -MARGIN) end else - TimeManagerClockButton:Hide() + self:OwnSet(TimeManagerClockButton, "Hide") end end @@ -215,10 +546,10 @@ function ClassyMap:FixLayout() if MinimapCluster.Tracking then if not db.hideTracking then self:SatStyles(MinimapCluster.Tracking) - MinimapCluster.Tracking:ClearAllPoints() - MinimapCluster.Tracking:SetPoint("TOPLEFT", Minimap, "TOPLEFT", MARGIN, -MARGIN) + self:OwnSet(MinimapCluster.Tracking, "ClearAllPoints") + self:OwnSet(MinimapCluster.Tracking, "SetPoint", "TOPLEFT", Minimap, "TOPLEFT", MARGIN, -MARGIN) else - MinimapCluster.Tracking:Hide() + self:OwnSet(MinimapCluster.Tracking, "Hide") end end @@ -229,12 +560,12 @@ function ClassyMap:FixLayout() if GameTimeFrame then if not db.hideCalendar then self:SatStyles(GameTimeFrame) - GameTimeFrame:ClearAllPoints() - GameTimeFrame:SetPoint("TOPRIGHT", Minimap, "TOPRIGHT", -MARGIN, -MARGIN) - GameTimeFrame:SetScale(1.0) + self:OwnSet(GameTimeFrame, "ClearAllPoints") + self:OwnSet(GameTimeFrame, "SetPoint", "TOPRIGHT", Minimap, "TOPRIGHT", -MARGIN, -MARGIN) + self:OwnSet(GameTimeFrame, "SetScale", 1.0) lastFrame = GameTimeFrame else - GameTimeFrame:Hide() + self:OwnSet(GameTimeFrame, "Hide") end end @@ -242,19 +573,16 @@ function ClassyMap:FixLayout() if AddonCompartmentFrame then if not db.hideAddonBtn then self:SatStyles(AddonCompartmentFrame) - AddonCompartmentFrame:ClearAllPoints() + self:OwnSet(AddonCompartmentFrame, "ClearAllPoints") if lastFrame then -- Center align with manual tweak (User requested revert to previous -> -2) - AddonCompartmentFrame:SetPoint("TOP", lastFrame, "BOTTOM", -2, -STACK_GAP) + self:OwnSet(AddonCompartmentFrame, "SetPoint", "TOP", lastFrame, "BOTTOM", -2, -STACK_GAP) else - AddonCompartmentFrame:SetPoint("TOPRIGHT", Minimap, "TOPRIGHT", -MARGIN, -MARGIN) - end - AddonCompartmentFrame:SetScale(1.0) - if not lastFrame then - lastFrame = AddonCompartmentFrame + self:OwnSet(AddonCompartmentFrame, "SetPoint", "TOPRIGHT", Minimap, "TOPRIGHT", -MARGIN, -MARGIN) end + self:OwnSet(AddonCompartmentFrame, "SetScale", 1.0) else - AddonCompartmentFrame:Hide() + self:OwnSet(AddonCompartmentFrame, "Hide") end end @@ -263,7 +591,7 @@ function ClassyMap:FixLayout() if diffFrame then if not db.hideInstance then self:SatStyles(diffFrame) - diffFrame:ClearAllPoints() + self:OwnSet(diffFrame, "ClearAllPoints") local topFrame = nil if GameTimeFrame and GameTimeFrame:IsShown() then topFrame = GameTimeFrame @@ -272,13 +600,13 @@ function ClassyMap:FixLayout() end if topFrame then - diffFrame:SetPoint("RIGHT", topFrame, "LEFT", -STACK_GAP, 0) + self:OwnSet(diffFrame, "SetPoint", "RIGHT", topFrame, "LEFT", -STACK_GAP, 0) else - diffFrame:SetPoint("TOPRIGHT", Minimap, "TOPRIGHT", -MARGIN, -MARGIN) + self:OwnSet(diffFrame, "SetPoint", "TOPRIGHT", Minimap, "TOPRIGHT", -MARGIN, -MARGIN) end - diffFrame:SetScale(1.0) + self:OwnSet(diffFrame, "SetScale", 1.0) else - diffFrame:Hide() + self:OwnSet(diffFrame, "Hide") end end @@ -296,84 +624,80 @@ function ClassyMap:FixLayout() end end -function ClassyMap:ApplyMinimapChanges() - local totalStart = debugprofilestop() - - -- 1. Apply Square Mask - Minimap:SetMaskTexture("Interface\\BUTTONS\\WHITE8X8") - - -- 2. Hybrid Minimap - if HybridMinimap then - HybridMinimap.MapCanvas:SetUseMaskTexture(false) - HybridMinimap.CircleMask:SetTexture("Interface\\BUTTONS\\WHITE8X8") - HybridMinimap.MapCanvas:SetUseMaskTexture(true) +function ClassyMap:RequestLayout() + if not self.resizing then + self:RequestRefresh("layout") end +end - -- 3. Border - local borderStart = debugprofilestop() - self:CreateBorder() - if ClassyMapMechanic then - ClassyMapMechanic:RecordPerfMetric("CreateBorder", (debugprofilestop() - borderStart) / 1000) - end - - -- 4. Hide Clutter - local clutterStart = debugprofilestop() - self:HideMinimapClutter() - if ClassyMapMechanic then - ClassyMapMechanic:RecordPerfMetric("HideClutter", (debugprofilestop() - clutterStart) / 1000) - end - - -- 5. Blobs (disable ring effects that don't work well with square minimap) - Minimap:SetArchBlobRingScalar(0) - Minimap:SetArchBlobRingAlpha(0) - Minimap:SetQuestBlobRingScalar(0) - Minimap:SetQuestBlobRingAlpha(0) - Minimap:SetTaskBlobRingScalar(0) - Minimap:SetTaskBlobRingAlpha(0) - - -- 6. Shape - GetMinimapShape = function() - return "SQUARE" +function ClassyMap:FixLayout() + if not self.executingRefresh then + self:RequestRefresh("layout") + return end - - -- 7. Clamping - if MinimapCluster then - MinimapCluster:SetClampedToScreen(true) - MinimapCluster:SetClampRectInsets(0, -60, 0, -60) + if InCombatLockdown() then + self:RequestLayout() + return end - if Minimap then - Minimap:SetClampedToScreen(false) + if self.resizing then + return end - - -- 8. Fonts - local fontStart = debugprofilestop() - self:ApplyFontStyles() - if ClassyMapMechanic then - ClassyMapMechanic:RecordPerfMetric("ApplyFontStyles", (debugprofilestop() - fontStart) / 1000) + self.resizing = true + local ok, err = pcall(ApplyLayout, self) + self.resizing = nil + if not ok then + geterrorhandler()(err) end +end - -- 9. Layout - local layoutStart = debugprofilestop() - self:FixLayout() - if ClassyMapMechanic then - ClassyMapMechanic:RecordPerfMetric("FixLayout", (debugprofilestop() - layoutStart) / 1000) +function ClassyMap:ApplyMinimapChanges() + if not self.executingRefresh then + self:RequestRefresh("all") + return end + self:MeasureRefresh("Setup", function() + -- Relinquish mask changes together with shape reporting if another addon takes over. + if not self.shapeOverride or GetMinimapShape == self.shapeOverride then + -- Mask/blob scalar APIs have no observable original state; reload restores them. + Minimap:SetMaskTexture("Interface\\BUTTONS\\WHITE8X8") + if HybridMinimap then + self:OwnSet(HybridMinimap.MapCanvas, "SetUseMaskTexture", false) + self:OwnSet(HybridMinimap.CircleMask, "SetTexture", "Interface\\BUTTONS\\WHITE8X8") + self:OwnSet(HybridMinimap.MapCanvas, "SetUseMaskTexture", true) + end + Minimap:SetArchBlobRingScalar(0) + Minimap:SetArchBlobRingAlpha(0) + Minimap:SetQuestBlobRingScalar(0) + Minimap:SetQuestBlobRingAlpha(0) + Minimap:SetTaskBlobRingScalar(0) + Minimap:SetTaskBlobRingAlpha(0) + if not self.shapeOverride then + self.shapeOverride = function() + return "SQUARE" + end + GetMinimapShape = self.shapeOverride + end + end + if MinimapCluster then + self:OwnSet(MinimapCluster, "SetClampedToScreen", true) + self:OwnSet(MinimapCluster, "SetClampRectInsets", 0, -60, 0, -60) + end + self:OwnSet(Minimap, "SetClampedToScreen", false) + end) + self:MeasureRefresh("CreateBorder", self.CreateBorder) + self:MeasureRefresh("HideClutter", self.HideMinimapClutter) + self:MeasureRefresh("ApplyFontStyles", self.ApplyFontStyles) + self:MeasureRefresh("FixLayout", self.FixLayout) if not self.hookedLayout then hooksecurefunc(MinimapCluster, "SetWidth", function() - if not self.resizing then - self.resizing = true - self:FixLayout() - self.resizing = false - end + self:RequestLayout() + end) + hooksecurefunc(MinimapCluster, "SetHeight", function() + self:RequestLayout() end) self.hookedLayout = true end - - -- Record total time - if ClassyMapMechanic then - ClassyMapMechanic:RecordPerfMetric("ApplyMinimapChanges", (debugprofilestop() - totalStart) / 1000) - end end function ClassyMap:CreateBorder() @@ -382,10 +706,7 @@ function ClassyMap:CreateBorder() return end - -- "The Background Container" Strategy failed via Frame. - -- New Strategy: 4 Textures DIRECTLY on the Minimap object. - -- Layer: BACKGROUND, SubLevel: -5 (Lowest possible). - -- This guarantees they are "painted" onto the map canvas before anything else. + -- Textures on the map keep the border below child frames and buttons. self.borders = {} local function CreateLine() @@ -461,8 +782,8 @@ function ClassyMap:HideMinimapClutter() -- Force Hide Compass if MinimapCompassTexture then - MinimapCompassTexture:Hide() - MinimapCompassTexture:SetAlpha(0) + self:OwnSet(MinimapCompassTexture, "Hide") + self:OwnSet(MinimapCompassTexture, "SetAlpha", 0) end -- Zoom Buttons @@ -473,24 +794,26 @@ function ClassyMap:HideMinimapClutter() if not self.zoomParentOut then self.zoomParentOut = Minimap.ZoomOut:GetParent() end - Minimap.ZoomIn:SetParent(hiddenFrame) - Minimap.ZoomOut:SetParent(hiddenFrame) + self:OwnSet(Minimap.ZoomIn, "SetParent", hiddenFrame) + self:OwnSet(Minimap.ZoomOut, "SetParent", hiddenFrame) else if self.zoomParentIn then - Minimap.ZoomIn:SetParent(self.zoomParentIn) + self:OwnSet(Minimap.ZoomIn, "SetParent", self.zoomParentIn) end if self.zoomParentOut then - Minimap.ZoomOut:SetParent(self.zoomParentOut) + self:OwnSet(Minimap.ZoomOut, "SetParent", self.zoomParentOut) end end -- Expansion Landing Page (Always Replace Native) if ExpansionLandingPageMinimapButton then - ExpansionLandingPageMinimapButton:Hide() - ExpansionLandingPageMinimapButton:SetAlpha(0) + self:OwnSet(ExpansionLandingPageMinimapButton, "Hide") + self:OwnSet(ExpansionLandingPageMinimapButton, "SetAlpha", 0) if not self.expHooked then - hooksecurefunc(ExpansionLandingPageMinimapButton, "Show", function(self) - self:Hide() + hooksecurefunc(ExpansionLandingPageMinimapButton, "Show", function(button) + if self.runtimeEnabled and self:AcceptNativeUpdate(button, "shown") then + self:RequestRefresh("visibility") + end end) self.expHooked = true end @@ -510,16 +833,16 @@ function ClassyMap:HideMinimapClutter() -- Tracking if MinimapCluster.Tracking then if db.hideTracking then - MinimapCluster.Tracking:Hide() + self:OwnSet(MinimapCluster.Tracking, "Hide") else - MinimapCluster.Tracking:Show() + self:OwnSet(MinimapCluster.Tracking, "Show") end end -- BorderTop if MinimapCluster.BorderTop then - MinimapCluster.BorderTop:Hide() - MinimapCluster.BorderTop:SetAlpha(0) + self:OwnSet(MinimapCluster.BorderTop, "Hide") + self:OwnSet(MinimapCluster.BorderTop, "SetAlpha", 0) end end @@ -594,8 +917,8 @@ function ClassyMap:CreateExpansionReplacement() end end) - btn:SetScript("OnEnter", function(self) - GameTooltip:SetOwner(self, "ANCHOR_LEFT") + btn:SetScript("OnEnter", function(button) + GameTooltip:SetOwner(button, "ANCHOR_LEFT") GameTooltip:AddLine(L["Expansion Summary"]) GameTooltip:AddLine(L["Click to open expansion summary"], 0.8, 0.8, 0.8) GameTooltip:Show() @@ -607,47 +930,48 @@ function ClassyMap:CreateExpansionReplacement() self.expansionReplacementBtn = btn end +function ClassyMap:ApplyZoneColor() + if not self.runtimeEnabled then + return + end + if MinimapZoneText and self.db.profile.overrideZoneColor then + local c = Core:ValidateColor(self.db.profile.zoneTextColor) + self:OwnSet(MinimapZoneText, "SetTextColor", c.r, c.g, c.b, c.a) + self.zoneColorOverridden = true + end +end + function ClassyMap:ApplyFontStyles() + if not self.executingRefresh then + self:RequestRefresh("fonts") + return + end local db = self.db.profile local fontPath = LSM:Fetch("font", db.font) or "Fonts\\FRIZQT__.TTF" if MinimapZoneText then -- Use Core layer for validation local zoneFontSize = Core:ValidateFontSize(db.zoneFontSize) - MinimapZoneText:SetFont(fontPath, zoneFontSize, "OUTLINE") - - -- Only override color if enabled. Otherwise let Blizzard handle it (Sanctuary/Contested colors). - if db.overrideZoneColor then - local c = Core:ValidateColor(db.zoneTextColor) - MinimapZoneText:SetTextColor(c.r, c.g, c.b, c.a) + self:OwnSet(MinimapZoneText, "SetFont", fontPath, zoneFontSize, "OUTLINE") + + self:ApplyZoneColor() + if not db.overrideZoneColor and self.zoneColorOverridden and Minimap_Update then + self.zoneColorOverridden = nil + if self:OwnsProperty(MinimapZoneText, "SetTextColor") then + Minimap_Update() + self.ownedFrames[MinimapZoneText].SetTextColor = nil + end end end if TimeManagerClockButton then - local region = TimeManagerClockButton:GetRegions() -- Usually the first region is the text - if region then + local region = TimeManagerClockTicker + if region and region.SetFont then -- Use Core layer for validation local clockFontSize = Core:ValidateFontSize(db.clockFontSize) local c = Core:ValidateColor(db.clockTextColor) - region:SetFont(fontPath, clockFontSize, "OUTLINE") - region:SetTextColor(c.r, c.g, c.b, c.a) + self:OwnSet(region, "SetFont", fontPath, clockFontSize, "OUTLINE") + self:OwnSet(region, "SetTextColor", c.r, c.g, c.b, c.a) end end end - -local function OnHybridMinimapLoaded() - if HybridMinimap then - HybridMinimap.MapCanvas:SetUseMaskTexture(false) - HybridMinimap.CircleMask:SetTexture("Interface\\BUTTONS\\WHITE8X8") - HybridMinimap.MapCanvas:SetUseMaskTexture(true) - end -end - -local loader = CreateFrame("Frame") -loader:RegisterEvent("ADDON_LOADED") -loader:SetScript("OnEvent", function(self, event, addon) - if addon == "Blizzard_HybridMinimap" then - OnHybridMinimapLoaded() - self:UnregisterEvent("ADDON_LOADED") - end -end) diff --git a/ClassyMap.toc b/ClassyMap.toc index 6034133..590caee 100644 --- a/ClassyMap.toc +++ b/ClassyMap.toc @@ -1,8 +1,8 @@ ## Interface: 120100 ## Title: ClassyMap -## Notes: A minimalist square minimap with a simple border and button drawer. +## Notes: A minimalist square minimap with a customizable border and clutter controls. ## Author: Jason Falk -## Version: 1.5.1 +## Version: 1.6.0 ## SavedVariables: ClassyMapDB ## IconTexture: Interface\Icons\INV_Misc_Map02 ## X-License: GPL-3.0 diff --git a/Core/core_spec.lua b/Core/core_spec.lua index 3273f0e..d378e96 100644 --- a/Core/core_spec.lua +++ b/Core/core_spec.lua @@ -32,8 +32,9 @@ describe("ClassyMap Core", function() count = count + 1 end, {}) - local processed = ClassyMapCore:ProcessQueue() + local processed, failed = ClassyMapCore:ProcessQueue() assert.equals(2, processed) + assert.equals(0, failed) assert.equals(0, ClassyMapCore:GetQueueLength()) assert.equals(2, count) end) @@ -48,6 +49,70 @@ describe("ClassyMap Core", function() assert.equals(30, result) end) + it("should preserve nil arguments", function() + local argumentCount + local secondArgument + ClassyMapCore:QueueAction(function(...) + argumentCount = select("#", ...) + secondArgument = select(2, ...) + end, { "first", nil, "third", n = 3 }) + + ClassyMapCore:ProcessQueue() + assert.equals(3, argumentCount) + assert.is_nil(secondArgument) + end) + + it("should continue after an action fails", function() + local reportedError + local finalActionCalled = false + ClassyMapCore:QueueAction(function() + error("expected failure") + end) + ClassyMapCore:QueueAction(function() + finalActionCalled = true + end) + + local processed, failed = ClassyMapCore:ProcessQueue(function(err) + reportedError = err + end) + assert.equals(2, processed) + assert.equals(1, failed) + assert.is_truthy(reportedError:match("expected failure")) + assert.is_true(finalActionCalled) + assert.equals(0, ClassyMapCore:GetQueueLength()) + end) + + it("should leave actions queued during processing for the next drain", function() + local callCount = 0 + ClassyMapCore:QueueAction(function() + callCount = callCount + 1 + ClassyMapCore:QueueAction(function() + callCount = callCount + 1 + end) + end) + + assert.equals(1, ClassyMapCore:ProcessQueue()) + assert.equals(1, callCount) + assert.equals(1, ClassyMapCore:GetQueueLength()) + assert.equals(1, ClassyMapCore:ProcessQueue()) + assert.equals(2, callCount) + end) + + it("should reject invalid queue entries immediately", function() + assert.has_error(function() + ClassyMapCore:QueueAction(nil) + end, "QueueAction requires a function") + assert.has_error(function() + ClassyMapCore:QueueAction(function() end, "invalid") + end, "QueueAction args must be a table or nil") + assert.has_error(function() + ClassyMapCore:QueueAction(function() end, { n = -1 }) + end, "QueueAction args.n must be a non-negative integer") + assert.has_error(function() + ClassyMapCore:QueueAction(function() end, { n = math.huge }) + end, "QueueAction args.n must be a non-negative integer") + end) + it("should clear queue without processing", function() local called = false ClassyMapCore:QueueAction(function() @@ -87,6 +152,11 @@ describe("ClassyMap Core", function() it("should floor decimal values", function() assert.equals(2, ClassyMapCore:ValidateBorderSize(2.7)) end) + + it("should return default for non-finite numbers", function() + assert.equals(1, ClassyMapCore:ValidateBorderSize(0 / 0)) + assert.equals(1, ClassyMapCore:ValidateBorderSize(math.huge)) + end) end) describe("ValidateFontSize", function() @@ -106,6 +176,11 @@ describe("ClassyMap Core", function() assert.equals(10, ClassyMapCore:ValidateFontSize(10)) assert.equals(16, ClassyMapCore:ValidateFontSize(16)) end) + + it("should return default for non-finite numbers", function() + assert.equals(11, ClassyMapCore:ValidateFontSize(0 / 0)) + assert.equals(11, ClassyMapCore:ValidateFontSize(-math.huge)) + end) end) describe("ValidateColor", function() @@ -132,6 +207,14 @@ describe("ClassyMap Core", function() assert.equals(1, color.b) -- default assert.equals(1, color.a) -- default end) + + it("should default non-finite channels", function() + local color = ClassyMapCore:ValidateColor({ r = 0 / 0, g = math.huge, b = -math.huge, a = 0.5 }) + assert.equals(1, color.r) + assert.equals(1, color.g) + assert.equals(1, color.b) + assert.equals(0.5, color.a) + end) end) end) end) diff --git a/Core/init.lua b/Core/init.lua index d9a5dac..9321037 100644 --- a/Core/init.lua +++ b/Core/init.lua @@ -4,13 +4,19 @@ -- FenCore integration for pure logic local FenCore = _G.FenCore local Math = FenCore and FenCore.Math +local unpackArgs = table.unpack or unpack -- Delegate to FenCore.Math.Clamp with fallback -local Clamp = Math and Math.Clamp or function(n, minV, maxV) - if n < minV then return minV end - if n > maxV then return maxV end - return n -end +local Clamp = Math and Math.Clamp + or function(n, minV, maxV) + if n < minV then + return minV + end + if n > maxV then + return maxV + end + return n + end ---@class ClassyMapCore ClassyMapCore = ClassyMapCore or {} @@ -20,32 +26,68 @@ ClassyMapCore = ClassyMapCore or {} -- Stores actions to execute when combat ends (no WoW dependencies here) -- ============================================================================= -ClassyMapCore.combatQueue = {} +ClassyMapCore.combatQueue = ClassyMapCore.combatQueue or {} + +local function ClearTable(tbl) + -- Use wipe if available (WoW), otherwise standard Lua clear. + if table.wipe then + table.wipe(tbl) + else + for key in pairs(tbl) do + tbl[key] = nil + end + end +end --- Queue an action for later execution ---@param func function The function to execute ---@param args table|nil Optional arguments to pass function ClassyMapCore:QueueAction(func, args) - table.insert(self.combatQueue, { func = func, args = args or {} }) + assert(type(func) == "function", "QueueAction requires a function") + assert(args == nil or type(args) == "table", "QueueAction args must be a table or nil") + + args = args or {} + if args.n == nil then + args.n = #args + end + assert( + type(args.n) == "number" + and args.n == args.n + and args.n ~= math.huge + and args.n >= 0 + and args.n == math.floor(args.n), + "QueueAction args.n must be a non-negative integer" + ) + + table.insert(self.combatQueue, { func = func, args = args }) end ---- Process all queued actions and clear the queue +--- Process the actions that are currently queued +--- Actions queued by a callback remain queued for the next drain. +---@param onError function|nil Optional error reporter called for each failed action ---@return number processed Number of actions processed -function ClassyMapCore:ProcessQueue() +---@return number failed Number of actions that failed +function ClassyMapCore:ProcessQueue(onError) + assert(onError == nil or type(onError) == "function", "ProcessQueue error handler must be a function or nil") + + local queue = self.combatQueue + self.combatQueue = {} local processed = 0 - for _, item in ipairs(self.combatQueue) do - item.func(unpack(item.args)) + local failed = 0 + for _, item in ipairs(queue) do + local args = item.args + local success, err = pcall(item.func, unpackArgs(args, 1, args.n or #args)) processed = processed + 1 - end - -- Use wipe if available (WoW), otherwise standard Lua clear - if table.wipe then - table.wipe(self.combatQueue) - else - for k in pairs(self.combatQueue) do - self.combatQueue[k] = nil + if not success then + failed = failed + 1 + if onError then + -- An error reporter must not prevent the remaining actions from running. + pcall(onError, err) + end end end - return processed + ClearTable(queue) + return processed, failed end --- Get the current queue length @@ -56,14 +98,7 @@ end --- Clear the queue without processing function ClassyMapCore:ClearQueue() - -- Use wipe if available (WoW), otherwise standard Lua clear - if table.wipe then - table.wipe(self.combatQueue) - else - for k in pairs(self.combatQueue) do - self.combatQueue[k] = nil - end - end + ClearTable(self.combatQueue) end -- ============================================================================= @@ -71,11 +106,23 @@ end -- Pure validation logic for settings values -- ============================================================================= +local function IsFiniteNumber(value) + return type(value) == "number" and value == value and value ~= math.huge and value ~= -math.huge +end + +local function ValidateChannel(value) + value = tonumber(value) + if not IsFiniteNumber(value) then + return 1 + end + return Clamp(value, 0, 1) +end + --- Validate border size setting ---@param size number|nil The border size to validate ---@return number validSize Clamped border size (0-8) function ClassyMapCore:ValidateBorderSize(size) - if type(size) ~= "number" then + if not IsFiniteNumber(size) then return 1 -- default end return Clamp(math.floor(size), 0, 8) @@ -85,7 +132,7 @@ end ---@param size number|nil The font size to validate ---@return number validSize Clamped font size (6-24) function ClassyMapCore:ValidateFontSize(size) - if type(size) ~= "number" then + if not IsFiniteNumber(size) then return 11 -- default end return Clamp(math.floor(size), 6, 24) @@ -99,10 +146,10 @@ function ClassyMapCore:ValidateColor(color) return { r = 1, g = 1, b = 1, a = 1 } end return { - r = Clamp(tonumber(color.r) or 1, 0, 1), - g = Clamp(tonumber(color.g) or 1, 0, 1), - b = Clamp(tonumber(color.b) or 1, 0, 1), - a = Clamp(tonumber(color.a) or 1, 0, 1), + r = ValidateChannel(color.r), + g = ValidateChannel(color.g), + b = ValidateChannel(color.b), + a = ValidateChannel(color.a), } end diff --git a/Libs/libs.json b/Libs/libs.json index 6b1562f..7b4b506 100644 --- a/Libs/libs.json +++ b/Libs/libs.json @@ -14,15 +14,15 @@ "AceEvent-3.0": "latest", "AceGUI-3.0": "latest", "AceGUI-3.0-SharedMediaWidgets": "latest", - "AceHook-3.0": "latest", "AceLocale-3.0": "latest", - "LibSharedMedia-3.0": "latest", - "LibDataBroker-1.1": "latest", - "LibDBIcon-1.0": "latest" + "LibSharedMedia-3.0": "latest" }, "notes": { "LibStub": "Required for all Ace3 libraries", "FenCore": "Pure logic domains (Math.Clamp for validation)", - "LibDBIcon-1.0": "Minimap button support" + "AceConfig-3.0": "Settings registration and AceConfigDialog UI", + "AceDB-3.0": "SavedVariables and profile storage", + "AceDBOptions-3.0": "Profile management controls", + "LibSharedMedia-3.0": "Font selection in the settings panel" } } diff --git a/Locales/deDE.lua b/Locales/deDE.lua index cf53dd8..7ebbb9f 100644 --- a/Locales/deDE.lua +++ b/Locales/deDE.lua @@ -16,8 +16,7 @@ L["A minimalist square minimap with a simple border and button drawer.\n"] = "Eine minimalistische quadratische Minikarte mit einfachem Rahmen und Schaltflächenleiste.\n" L["Border"] = "Rahmen" L["Border Size"] = "Rahmengröße" -L["Thickness of the minimap border. Set to 0 to hide."] = - "Dicke des Minikartenrahmens. Auf 0 setzen zum Ausblenden." +L["Thickness of the minimap border. Set to 0 to hide."] = "Dicke des Minikartenrahmens. Auf 0 setzen zum Ausblenden." L["Border Color"] = "Rahmenfarbe" L["Color of the minimap border."] = "Farbe des Minikartenrahmens." L["Fonts"] = "Schriftarten" diff --git a/Locales/enUS.lua b/Locales/enUS.lua index e13a063..a6abeb0 100644 --- a/Locales/enUS.lua +++ b/Locales/enUS.lua @@ -41,3 +41,52 @@ L["Hide the large expansion button and replace with a smaller icon."] = L["Hide Calendar"] = "Hide Calendar" L["Hide Addon Drawer"] = "Hide Addon Drawer" L["Hide Instance Difficulty"] = "Hide Instance Difficulty" + +-- Mechanic diagnostics (English fallback for untranslated keys) +L["ClassyMap Tools"] = "ClassyMap Tools" +L["Quick actions for minimap customization."] = "Quick actions for minimap customization." +L["Addon:"] = "Addon:" +L["Reapply"] = "Reapply" +L["|cffff0000ClassyMap:|r Not initialized yet"] = "|cffff0000ClassyMap:|r Not initialized yet" +L["|cffff0000ClassyMap:|r Settings not available"] = "|cffff0000ClassyMap:|r Settings not available" +L["Border:"] = "Border:" +L["|cff00ff00ClassyMap:|r Border hidden"] = "|cff00ff00ClassyMap:|r Border hidden" +L["|cff00ff00ClassyMap:|r Border = 1px"] = "|cff00ff00ClassyMap:|r Border = 1px" +L["|cff00ff00ClassyMap:|r Border = 2px"] = "|cff00ff00ClassyMap:|r Border = 2px" +L["|cff00ff00ClassyMap:|r Border = 4px"] = "|cff00ff00ClassyMap:|r Border = 4px" +L["Debug:"] = "Debug:" +L["Debug Mode"] = "Debug Mode" +L["Use /classymap or /cm for more options."] = "Use /classymap or /cm for more options." +L["Minimap Shape Override"] = "Minimap Shape Override" +L["Verifies GetMinimapShape returns SQUARE."] = "Verifies GetMinimapShape returns SQUARE." +L["Border Textures"] = "Border Textures" +L["Checks border textures are created and visible."] = "Checks border textures are created and visible." +L["Square Mask Applied"] = "Square Mask Applied" +L["Verifies the square mask is applied to Minimap."] = "Verifies the square mask is applied to Minimap." +L["GetMinimapShape() = %s"] = "GetMinimapShape() = %s" +L["Shape"] = "Shape" +L["Expected"] = "Expected" +L["borders."] = "borders." +L["Shown"] = "Shown" +L["Hidden"] = "Hidden" +L["Missing"] = "Missing" +L["Border visibility matches the configured size: %s"] = "Border visibility matches the configured size: %s" +L["Visual check required: confirm the minimap and hybrid minimap have square corners."] = + "Visual check required: confirm the minimap and hybrid minimap have square corners." +L["Unknown test ID: %s"] = "Unknown test ID: %s" +L["Create Border"] = "Create Border" +L["Border texture setup"] = "Border texture setup" +L["Hide Clutter"] = "Hide Clutter" +L["Hide minimap buttons"] = "Hide minimap buttons" +L["Apply Fonts"] = "Apply Fonts" +L["Font styling"] = "Font styling" +L["Fix Layout"] = "Fix Layout" +L["Layout adjustments"] = "Layout adjustments" +L["Other Apply Work"] = "Other Apply Work" +L["Mask, shape, and remaining setup"] = "Mask, shape, and remaining setup" +L["Settings"] = "Settings" +L["Toggle Debug"] = "Toggle Debug" +L["Reset Metrics"] = "Reset Metrics" +L["Map Setup"] = "Map Setup" +L["%d calls; %.3f ms total; %.3f ms average; %.3f ms max; %.3f ms last"] = + "%d calls; %.3f ms total; %.3f ms average; %.3f ms max; %.3f ms last" diff --git a/Locales/esES.lua b/Locales/esES.lua index 7149684..4830173 100644 --- a/Locales/esES.lua +++ b/Locales/esES.lua @@ -16,8 +16,7 @@ L["A minimalist square minimap with a simple border and button drawer.\n"] = "Un minimapa cuadrado minimalista con un borde simple y cajón de botones.\n" L["Border"] = "Borde" L["Border Size"] = "Tamaño del borde" -L["Thickness of the minimap border. Set to 0 to hide."] = - "Grosor del borde del minimapa. Establece en 0 para ocultar." +L["Thickness of the minimap border. Set to 0 to hide."] = "Grosor del borde del minimapa. Establece en 0 para ocultar." L["Border Color"] = "Color del borde" L["Color of the minimap border."] = "Color del borde del minimapa." L["Fonts"] = "Fuentes" diff --git a/Locales/esMX.lua b/Locales/esMX.lua index 2def9ba..a262386 100644 --- a/Locales/esMX.lua +++ b/Locales/esMX.lua @@ -16,8 +16,7 @@ L["A minimalist square minimap with a simple border and button drawer.\n"] = "Un minimapa cuadrado minimalista con un borde simple y cajón de botones.\n" L["Border"] = "Borde" L["Border Size"] = "Tamaño del borde" -L["Thickness of the minimap border. Set to 0 to hide."] = - "Grosor del borde del minimapa. Establece en 0 para ocultar." +L["Thickness of the minimap border. Set to 0 to hide."] = "Grosor del borde del minimapa. Establece en 0 para ocultar." L["Border Color"] = "Color del borde" L["Color of the minimap border."] = "Color del borde del minimapa." L["Fonts"] = "Fuentes" diff --git a/Locales/koKR.lua b/Locales/koKR.lua index c97c54f..9790dc1 100644 --- a/Locales/koKR.lua +++ b/Locales/koKR.lua @@ -5,7 +5,8 @@ end -- Core.lua L["ClassyMap"] = "ClassyMap" -L["Loaded. Type /classymap or /cm for options."] = "로드됨. 옵션을 보려면 /classymap 또는 /cm을 입력하세요." +L["Loaded. Type /classymap or /cm for options."] = + "로드됨. 옵션을 보려면 /classymap 또는 /cm을 입력하세요." L["Enabled"] = "활성화됨" L["Disabled"] = "비활성화됨" L["Expansion Summary"] = "확장팩 요약" diff --git a/Locales/ptBR.lua b/Locales/ptBR.lua index 5bbb98c..b5dceb0 100644 --- a/Locales/ptBR.lua +++ b/Locales/ptBR.lua @@ -16,8 +16,7 @@ L["A minimalist square minimap with a simple border and button drawer.\n"] = "Um minimapa quadrado minimalista com uma borda simples e gaveta de botões.\n" L["Border"] = "Borda" L["Border Size"] = "Tamanho da borda" -L["Thickness of the minimap border. Set to 0 to hide."] = - "Espessura da borda do minimapa. Defina como 0 para ocultar." +L["Thickness of the minimap border. Set to 0 to hide."] = "Espessura da borda do minimapa. Defina como 0 para ocultar." L["Border Color"] = "Cor da borda" L["Color of the minimap border."] = "Cor da borda do minimapa." L["Fonts"] = "Fontes" diff --git a/Locales/ruRU.lua b/Locales/ruRU.lua index fe9425d..c2cd863 100644 --- a/Locales/ruRU.lua +++ b/Locales/ruRU.lua @@ -5,7 +5,8 @@ end -- Core.lua L["ClassyMap"] = "ClassyMap" -L["Loaded. Type /classymap or /cm for options."] = "Загружено. Введите /classymap или /cm для настроек." +L["Loaded. Type /classymap or /cm for options."] = + "Загружено. Введите /classymap или /cm для настроек." L["Enabled"] = "Включено" L["Disabled"] = "Отключено" L["Expansion Summary"] = "Обзор дополнения" @@ -35,7 +36,8 @@ L["Hide Zone Text"] = "Скрыть текст зоны" L["Hide Clock"] = "Скрыть часы" L["Hide the time display."] = "Скрыть отображение времени." L["Hide Zoom Buttons"] = "Скрыть кнопки масштаба" -L["Hide the minimap zoom in/out buttons."] = "Скрыть кнопки масштабирования миникарты." +L["Hide the minimap zoom in/out buttons."] = + "Скрыть кнопки масштабирования миникарты." L["Hide Expansion Button"] = "Скрыть кнопку дополнения" L["Hide the large expansion button and replace with a smaller icon."] = "Скрыть большую кнопку дополнения и заменить маленьким значком." diff --git a/Locales/zhCN.lua b/Locales/zhCN.lua index e9d08ff..0297e67 100644 --- a/Locales/zhCN.lua +++ b/Locales/zhCN.lua @@ -16,8 +16,7 @@ L["A minimalist square minimap with a simple border and button drawer.\n"] = "一个极简的方形小地图,带有简洁边框和按钮抽屉。\n" L["Border"] = "边框" L["Border Size"] = "边框大小" -L["Thickness of the minimap border. Set to 0 to hide."] = - "小地图边框的厚度。设置为 0 以隐藏。" +L["Thickness of the minimap border. Set to 0 to hide."] = "小地图边框的厚度。设置为 0 以隐藏。" L["Border Color"] = "边框颜色" L["Color of the minimap border."] = "小地图边框的颜色。" L["Fonts"] = "字体" diff --git a/Locales/zhTW.lua b/Locales/zhTW.lua index cc695c3..2faf4f5 100644 --- a/Locales/zhTW.lua +++ b/Locales/zhTW.lua @@ -16,8 +16,7 @@ L["A minimalist square minimap with a simple border and button drawer.\n"] = "一個極簡的方形小地圖,帶有簡潔邊框和按鈕抽屜。\n" L["Border"] = "邊框" L["Border Size"] = "邊框大小" -L["Thickness of the minimap border. Set to 0 to hide."] = - "小地圖邊框的厚度。設定為 0 以隱藏。" +L["Thickness of the minimap border. Set to 0 to hide."] = "小地圖邊框的厚度。設定為 0 以隱藏。" L["Border Color"] = "邊框顏色" L["Color of the minimap border."] = "小地圖邊框的顏色。" L["Fonts"] = "字型" diff --git a/Mechanic.lua b/Mechanic.lua index abb3490..2d9ab48 100644 --- a/Mechanic.lua +++ b/Mechanic.lua @@ -3,6 +3,12 @@ local addonName, ns = ... local MechanicLib = LibStub("MechanicLib-1.0", true) +local L = LibStub("AceLocale-3.0"):GetLocale("ClassyMap") + +local function GetProfile() + local addon = ns.ClassyMap + return addon and addon.db and addon.db.profile +end ---@class ClassyMapMechanic ClassyMapMechanic = {} @@ -16,7 +22,8 @@ local logThrottle = {} local LOG_INTERVAL = 0.1 -- seconds between identical messages function ClassyMapMechanic:Log(msg, category) - if not ClassyMapDB or not ClassyMapDB.profile or not ClassyMapDB.profile.debugMode then + local profile = GetProfile() + if not profile or not profile.debugMode then return end @@ -29,7 +36,10 @@ function ClassyMapMechanic:Log(msg, category) -- Store in internal buffer for Mechanic's pull model table.insert(self.debugBuffer, { msg = msg, time = now }) if #self.debugBuffer > 500 then - table.remove(self.debugBuffer, 1) + local removed = table.remove(self.debugBuffer, 1) + if logThrottle[removed.msg] == removed.time then + logThrottle[removed.msg] = nil + end end -- Log to Mechanic's console only (no chat spam) @@ -42,12 +52,6 @@ end -- Tools Panel (Button-based) -- ============================================================================= --- Helper to safely get addon's db profile (AceDB wraps ClassyMapDB) -local function GetProfile() - local addon = ns.ClassyMap - return addon and addon.db and addon.db.profile -end - local function CreateToolButton(parent, x, y, width, text, onClick) local btn = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate") btn:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y) @@ -61,52 +65,47 @@ function ClassyMapMechanic:CreateToolsPanel(container) -- Title local title = container:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge") title:SetPoint("TOPLEFT", 10, -10) - title:SetText("ClassyMap Tools") + title:SetText(L["ClassyMap Tools"]) -- Description local desc = container:CreateFontString(nil, "OVERLAY", "GameFontHighlight") desc:SetPoint("TOPLEFT", 10, -35) - desc:SetText("Quick actions for minimap customization.") + desc:SetText(L["Quick actions for minimap customization."]) - -- Row 1: Toggle & Settings + -- Row 1: Reapply & Settings (the addon does not implement runtime disable) local row1Label = container:CreateFontString(nil, "OVERLAY", "GameFontNormal") row1Label:SetPoint("TOPLEFT", 10, -65) - row1Label:SetText("Addon:") + row1Label:SetText(L["Addon:"]) - CreateToolButton(container, 80, -60, 80, "Toggle", function() - local profile = GetProfile() - if profile then - profile.enabled = not profile.enabled - if ns.ClassyMap then - ns.ClassyMap:RunSafe(ns.ClassyMap.ApplyMinimapChanges) - end - print("|cff00ff00ClassyMap:|r " .. (profile.enabled and "Enabled" or "Disabled")) + CreateToolButton(container, 80, -60, 80, L["Reapply"], function() + if GetProfile() then + ns.ClassyMap:RequestRefresh("all") else - print("|cffff0000ClassyMap:|r Not initialized yet") + print(L["|cffff0000ClassyMap:|r Not initialized yet"]) end end) - CreateToolButton(container, 165, -60, 80, "Settings", function() + CreateToolButton(container, 165, -60, 80, L["Settings"], function() if ns.Settings then ns.Settings:OpenOptions() else - print("|cffff0000ClassyMap:|r Settings not available") + print(L["|cffff0000ClassyMap:|r Settings not available"]) end end) -- Row 2: Border Size local row2Label = container:CreateFontString(nil, "OVERLAY", "GameFontNormal") row2Label:SetPoint("TOPLEFT", 10, -100) - row2Label:SetText("Border:") + row2Label:SetText(L["Border:"]) CreateToolButton(container, 80, -95, 50, "0", function() local profile = GetProfile() if profile then profile.borderSize = 0 if ns.ClassyMap then - ns.ClassyMap:UpdateBorderStyle() + ns.ClassyMap:RequestRefresh("border") end - print("|cff00ff00ClassyMap:|r Border hidden") + print(L["|cff00ff00ClassyMap:|r Border hidden"]) end end) @@ -115,9 +114,9 @@ function ClassyMapMechanic:CreateToolsPanel(container) if profile then profile.borderSize = 1 if ns.ClassyMap then - ns.ClassyMap:UpdateBorderStyle() + ns.ClassyMap:RequestRefresh("border") end - print("|cff00ff00ClassyMap:|r Border = 1px") + print(L["|cff00ff00ClassyMap:|r Border = 1px"]) end end) @@ -126,9 +125,9 @@ function ClassyMapMechanic:CreateToolsPanel(container) if profile then profile.borderSize = 2 if ns.ClassyMap then - ns.ClassyMap:UpdateBorderStyle() + ns.ClassyMap:RequestRefresh("border") end - print("|cff00ff00ClassyMap:|r Border = 2px") + print(L["|cff00ff00ClassyMap:|r Border = 2px"]) end end) @@ -137,29 +136,33 @@ function ClassyMapMechanic:CreateToolsPanel(container) if profile then profile.borderSize = 4 if ns.ClassyMap then - ns.ClassyMap:UpdateBorderStyle() + ns.ClassyMap:RequestRefresh("border") end - print("|cff00ff00ClassyMap:|r Border = 4px") + print(L["|cff00ff00ClassyMap:|r Border = 4px"]) end end) -- Row 3: Debug local row3Label = container:CreateFontString(nil, "OVERLAY", "GameFontNormal") row3Label:SetPoint("TOPLEFT", 10, -135) - row3Label:SetText("Debug:") + row3Label:SetText(L["Debug:"]) - CreateToolButton(container, 80, -130, 100, "Toggle Debug", function() + CreateToolButton(container, 80, -130, 100, L["Toggle Debug"], function() local profile = GetProfile() if profile then profile.debugMode = not profile.debugMode - print("|cff00ff00ClassyMap:|r Debug " .. (profile.debugMode and "ON" or "OFF")) + print(L["Debug Mode"] .. ": " .. (profile.debugMode and L["Enabled"] or L["Disabled"])) end end) + CreateToolButton(container, 190, -130, 110, L["Reset Metrics"], function() + self:ResetPerformanceMetrics() + end) + -- Footer local footer = container:CreateFontString(nil, "OVERLAY", "GameFontDisableSmall") footer:SetPoint("BOTTOM", 0, 10) - footer:SetText("Use /classymap or /cm for more options.") + footer:SetText(L["Use /classymap or /cm for more options."]) end -- ============================================================================= @@ -169,24 +172,24 @@ end ClassyMapMechanic.tests = { { id = "minimap_shape", - name = "Minimap Shape Override", + name = L["Minimap Shape Override"], category = "API", type = "auto", - description = "Verifies GetMinimapShape returns SQUARE when enabled.", + description = L["Verifies GetMinimapShape returns SQUARE."], }, { id = "border_textures", - name = "Border Textures", + name = L["Border Textures"], category = "UI", type = "auto", - description = "Checks border textures are created and visible.", + description = L["Checks border textures are created and visible."], }, { id = "mask_texture", - name = "Square Mask Applied", + name = L["Square Mask Applied"], category = "UI", - type = "auto", - description = "Verifies the square mask is applied to Minimap.", + type = "manual", + description = L["Verifies the square mask is applied to Minimap."], }, } @@ -207,75 +210,143 @@ function ClassyMapMechanic:GetTestResult(id) if id == "minimap_shape" then local shape = GetMinimapShape and GetMinimapShape() or "UNKNOWN" - -- AceDB defaults enabled=true, so check ~= false - local enabled = profile and profile.enabled ~= false - local expected = enabled and "SQUARE" or "ROUND" + local expected = "SQUARE" return { passed = (shape == expected), - message = "GetMinimapShape() = " .. shape, + message = L["GetMinimapShape() = %s"]:format(tostring(shape)), details = { - { label = "Shape", value = shape, status = (shape == expected) and "pass" or "fail" }, - { label = "Expected", value = expected, status = "pass" }, - { label = "Addon Enabled", value = enabled and "Yes" or "No", status = "pass" }, + { label = L["Shape"], value = shape, status = (shape == expected) and "pass" or "fail" }, + { label = L["Expected"], value = expected, status = "pass" }, }, } elseif id == "border_textures" then local cm = ns.ClassyMap - local hasBorders = cm and cm.borders and cm.borders.top ~= nil - local borderSize = profile and profile.borderSize or 1 + local borderSize = ClassyMapCore:ValidateBorderSize(profile and profile.borderSize) local visible = borderSize > 0 + local passed = true + local details = {} + for _, side in ipairs({ "top", "bottom", "left", "right" }) do + local texture = cm and cm.borders and cm.borders[side] + local matches = texture ~= nil and texture:IsShown() == visible + passed = passed and matches + details[#details + 1] = { + label = L["borders."] .. side, + value = texture and (texture:IsShown() and L["Shown"] or L["Hidden"]) or L["Missing"], + status = matches and "pass" or "fail", + } + end return { - passed = hasBorders, - message = hasBorders and "Border textures initialized" or "No borders found", - details = { - { label = "borders.top", value = hasBorders and "OK" or "nil", status = hasBorders and "pass" or "fail" }, - { - label = "borders.bottom", - value = (cm and cm.borders and cm.borders.bottom) and "OK" or "nil", - status = (cm and cm.borders and cm.borders.bottom) and "pass" or "fail", - }, - { label = "Border Size", value = tostring(borderSize) .. "px", status = "pass" }, - { label = "Should Show", value = visible and "Yes" or "No", status = "pass" }, - }, + passed = passed, + message = L["Border visibility matches the configured size: %s"]:format(tostring(borderSize)), + details = details, } elseif id == "mask_texture" then - -- AceDB defaults enabled=true, so check ~= false - local enabled = profile and profile.enabled ~= false return { - passed = enabled, - message = enabled and "Square mask should be active" or "Addon disabled, round mask active", - details = { - { label = "Addon Enabled", value = enabled and "Yes" or "No", status = enabled and "pass" or "warn" }, - { - label = "Expected Mask", - value = enabled and "WHITE8X8 (Square)" or "MinimapMask (Round)", - status = "pass", - }, - }, + message = L["Visual check required: confirm the minimap and hybrid minimap have square corners."], } end - return { passed = false, message = "Unknown test ID: " .. tostring(id) } + return { passed = false, message = L["Unknown test ID: %s"]:format(tostring(id)) } end -- ============================================================================= -- Performance Profiling -- ============================================================================= +-- Only executed work is measured. Fixed names keep memory bounded for the session. +local metricDefinitions = { + { id = "CreateBorder", name = L["Create Border"] }, + { id = "HideClutter", name = L["Hide Clutter"] }, + { id = "ApplyFontStyles", name = L["Apply Fonts"] }, + { id = "FixLayout", name = L["Fix Layout"] }, + { id = "Setup", name = L["Map Setup"] }, +} +local knownMetrics = { Refresh = true } +for _, definition in ipairs(metricDefinitions) do + knownMetrics[definition.id] = true +end local perfMetrics = {} +local metricsStartedAt = GetTime() + +local function EmptyMetric() + return { count = 0, totalMs = 0, maxMs = 0, lastMs = 0 } +end function ClassyMapMechanic:RecordPerfMetric(name, duration) - perfMetrics[name] = duration + if + not knownMetrics[name] + or type(duration) ~= "number" + or duration ~= duration + or duration < 0 + or duration == math.huge + then + return false + end + local metric = perfMetrics[name] + local total = (metric and metric.totalMs or 0) + duration + if total == math.huge then + return false + end + if not metric then + metric = EmptyMetric() + perfMetrics[name] = metric + end + metric.count = metric.count + 1 + metric.totalMs = total + metric.maxMs = math.max(metric.maxMs, duration) + metric.lastMs = duration + return true +end + +function ClassyMapMechanic:ResetPerformanceMetrics() + wipe(perfMetrics) + metricsStartedAt = GetTime() +end + +-- A detached snapshot is safe for diagnostic consumers to retain or modify. +-- Refresh is an inclusive batch total; it is never added to the category breakdown. +function ClassyMapMechanic:GetPerformanceStats() + local elapsed = math.max(0, GetTime() - metricsStartedAt) + local snapshot = { elapsedSeconds = elapsed, metrics = {} } + for name in pairs(knownMetrics) do + local source = perfMetrics[name] or EmptyMetric() + snapshot.metrics[name] = { + count = source.count, + totalMs = source.totalMs, + maxMs = source.maxMs, + lastMs = source.lastMs, + averageMs = source.count > 0 and source.totalMs / source.count or 0, + callsPerSecond = elapsed > 0 and source.count / elapsed or 0, + msPerSecond = elapsed > 0 and source.totalMs / elapsed or 0, + } + end + return snapshot end function ClassyMapMechanic:GetPerformanceSubMetrics() - return { - { name = "Create Border", ms = perfMetrics.CreateBorder or 0, description = "Border texture setup" }, - { name = "Hide Clutter", ms = perfMetrics.HideClutter or 0, description = "Hide minimap buttons" }, - { name = "Apply Fonts", ms = perfMetrics.ApplyFontStyles or 0, description = "Font styling" }, - { name = "Fix Layout", ms = perfMetrics.FixLayout or 0, description = "Layout adjustments" }, - { name = "Total Apply", ms = perfMetrics.ApplyMinimapChanges or 0, description = "Full minimap apply" }, - } + local snapshot = self:GetPerformanceStats() + local result = {} + for _, definition in ipairs(metricDefinitions) do + local metric = snapshot.metrics[definition.id] + result[#result + 1] = { + name = definition.name, + -- Mechanic's breakdown and total are labeled ms/s. + ms = metric.msPerSecond, + count = metric.count, + totalMs = metric.totalMs, + averageMs = metric.averageMs, + maxMs = metric.maxMs, + lastMs = metric.lastMs, + description = L["%d calls; %.3f ms total; %.3f ms average; %.3f ms max; %.3f ms last"]:format( + metric.count, + metric.totalMs, + metric.averageMs, + metric.maxMs, + metric.lastMs + ), + } + end + return result end -- ============================================================================= @@ -283,6 +354,7 @@ end -- ============================================================================= local function RegisterWithMechanic() + MechanicLib = LibStub("MechanicLib-1.0", true) if not MechanicLib then return end @@ -296,6 +368,7 @@ local function RegisterWithMechanic() end, clearDebugBuffer = function() wipe(ClassyMapMechanic.debugBuffer) + wipe(logThrottle) end, -- Testing Integration @@ -332,7 +405,7 @@ local function RegisterWithMechanic() settings = { debugMode = { type = "toggle", - name = "Debug Mode", + name = L["Debug Mode"], get = function() local profile = GetProfile() return profile and profile.debugMode @@ -346,14 +419,16 @@ local function RegisterWithMechanic() }, }, }) + return true end -- Hook into addon load local loader = CreateFrame("Frame") loader:RegisterEvent("ADDON_LOADED") loader:SetScript("OnEvent", function(_, _, addon) - if addon == addonName then - RegisterWithMechanic() - loader:UnregisterEvent("ADDON_LOADED") + if addon == addonName or addon == "!Mechanic" or addon == "Mechanic" then + if RegisterWithMechanic() then + loader:UnregisterEvent("ADDON_LOADED") + end end end) diff --git a/README.md b/README.md index fa4e03a..d1e5795 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,7 @@ A minimalist square minimap addon for World of Warcraft. Transforms the default circular minimap into a clean, modern square shape. -![WoW Version](https://img.shields.io/badge/WoW-11.0%2B-blue) -![Interface](https://img.shields.io/badge/Interface-120001-green) +![Interface](https://img.shields.io/badge/Interface-120100-green) [![GitHub](https://img.shields.io/badge/GitHub-Falkicon%2FClassyMap-181717?logo=github)](https://github.com/Falkicon/ClassyMap) [![Sponsor](https://img.shields.io/badge/Sponsor-pink?logo=githubsponsors)](https://github.com/sponsors/Falkicon) @@ -13,61 +12,73 @@ A minimalist square minimap addon for World of Warcraft. Transforms the default - **◼️ Square Minimap** – Clean square shape instead of the default circle - **🖼️ Simple Border** – Thin, customizable border -- **📦 Button Drawer** – Collects addon minimap buttons into a tidy row -- **🧹 Clutter Free** – Hides compass, zoom buttons, and blob rings -- **🔌 Addon Compartment** – Integrates with Blizzard's native addon compartment frame +- **📦 Addon Compartment** – Repositions Blizzard's native addon compartment near the minimap +- **🧹 Clutter Controls** – Hides the compass and blob rings, with optional controls for other minimap elements +- **🗺️ Expansion Shortcut** – Replaces the native expansion button with a compact button that opens the Adventure Guide ## Installation -1. Download or clone this repository +1. Download from [CurseForge](https://www.curseforge.com/wow/addons/classymap) or clone this repository 2. Place the `ClassyMap` folder in your WoW addons directory: ``` - World of Warcraft\_retail_\Interface\AddOns\ + World of Warcraft\_retail_\Interface\AddOns\ClassyMap\ ``` -3. Restart WoW or type `/reload` if already running +3. Check that `ClassyMap.toc` is directly inside that folder, then restart WoW for a first installation. Use `/reload` after updating an already loaded installation. ## Usage The addon applies automatically on login. Use the settings panel to customize. +Settings changes made during combat apply after combat ends. Changes made together are combined into one refresh. + ### Slash Commands | Command | Description | |---------|-------------| | `/classymap` or `/cm` | Open settings | -| `/classymap toggle` | Enable/disable the addon | ## Configuration -Open settings via `/cm` or `Esc` → `Options` → `AddOns` → `ClassyMap`. +Open settings via `/cm`, the ClassyMap entry in the addon compartment, or the in-game AddOns settings category. ### Settings | Setting | Description | |---------|-------------| -| Border Size | Thickness of the minimap border | +| Border Size | Thickness from 0–8; 0 hides the border | | Border Color | Color of the minimap border | -| Hide Compass | Remove the compass ring | -| Hide Zoom Buttons | Remove the +/- zoom buttons | -| Button Drawer Position | Position of collected addon buttons (bottom, left, right) | +| Font Face | Font used by the zone text and clock | +| Zone Text Size / Color | Size from 6–24 and optional override color for the zone text | +| Clock Text Size / Color | Size from 6–24 and color for the clock | +| Hide Tracking | Hide the tracking button | +| Hide Zone Text / Clock | Hide either text element | +| Hide Zoom Buttons | Hide the +/- zoom buttons | +| Hide Expansion Button | Hide the replacement expansion shortcut | +| Hide Calendar / Addon Drawer / Instance Difficulty | Hide individual minimap cluster elements | +| Profiles | Create, copy, reset, and switch AceDB profiles | ## Compatibility -- Works with LibDBIcon minimap buttons from other addons -- Properly reports `"SQUARE"` via `GetMinimapShape()` for addon compatibility +- Repositions Blizzard's native addon compartment. The **Hide Addon Drawer** setting hides this compartment; ClassyMap does not collect third-party minimap buttons. +- Reports `"SQUARE"` through `GetMinimapShape()` while managing the minimap shape. +- Leaves detected external changes to tracked frame properties alone. Other addons that also reshape or reposition the minimap still need in-game compatibility testing. ## Requirements -- World of Warcraft Retail 11.0+ or Midnight Beta +- World of Warcraft Retail. The declared client target is Interface 120100 in [ClassyMap.toc](ClassyMap.toc). +- Required libraries are bundled; Mechanic is optional developer tooling. ## Localization -ClassyMap supports 11 languages: +ClassyMap includes 11 locales: + - English (enUS) - baseline - German (deDE), French (frFR), Spanish (esES/esMX), Italian (itIT) - Portuguese (ptBR), Russian (ruRU), Korean (koKR) - Chinese Simplified (zhCN), Chinese Traditional (zhTW) +New diagnostic strings fall back to English until translated. + ## Files | File | Purpose | @@ -78,12 +89,19 @@ ClassyMap supports 11 languages: | `Settings.lua` | AceConfig settings UI | | `Mechanic.lua` | Mechanic integration for debugging | | `Locales/` | 11 locale files | +| `tests/` | Offline regression, integration, and manifest checks | +| `docs/runtime-design.md` | Runtime contracts and diagnostic reference | ## Technical Notes -- **Ace3 Framework** – Uses AceAddon, AceConfig for settings -- **Shape Override** – Globally overrides `GetMinimapShape` to return `"SQUARE"` for other addon compatibility +- **Ace3 Framework** – Uses AceAddon, AceConfig, AceDB, AceEvent, AceLocale, and AceGUI for settings and lifecycle management +- **Refresh Scheduling** – Applies changes after enable/world readiness and outside combat, combining pending work into scoped refreshes. +- **Border** – Uses four textures on the minimap's ARTWORK layer. - **Mask Texture** – Uses `Minimap:SetMaskTexture("Interface\\BUTTONS\\WHITE8X8")` +- **Cooperative Layout** – Tracks observable frame changes and leaves externally changed properties alone. Full removal of square mask effects requires disabling the addon and reloading. +- **Development Reference** – See [runtime-design.md](docs/runtime-design.md) for refresh scheduling, ownership, diagnostics, and integration-test boundaries. + +See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup and offline checks. ## Support diff --git a/Settings.lua b/Settings.lua index 09d5e48..85aefe8 100644 --- a/Settings.lua +++ b/Settings.lua @@ -3,8 +3,11 @@ local L = LibStub("AceLocale-3.0"):GetLocale("ClassyMap") local Settings = {} ns.Settings = Settings +local Core = ClassyMapCore local AceConfig = LibStub("AceConfig-3.0") local AceConfigDialog = LibStub("AceConfigDialog-3.0") +local AceConfigRegistry = LibStub("AceConfigRegistry-3.0") +local AceDBOptions = LibStub("AceDBOptions-3.0") -- ============================================================================= -- Options Table @@ -12,7 +15,7 @@ local AceConfigDialog = LibStub("AceConfigDialog-3.0") local function GetOptions() local ClassyMap = ns.ClassyMap - return { + local options = { name = L["ClassyMap"], type = "group", args = { @@ -38,11 +41,11 @@ local function GetOptions() step = 1, order = 11, get = function() - return ClassyMap.db.profile.borderSize + return Core:ValidateBorderSize(ClassyMap.db.profile.borderSize) end, set = function(_, val) - ClassyMap.db.profile.borderSize = val - ClassyMap:UpdateBorderStyle() + ClassyMap.db.profile.borderSize = Core:ValidateBorderSize(val) + ClassyMap:RequestRefresh("border") end, }, borderColor = { @@ -52,12 +55,12 @@ local function GetOptions() hasAlpha = true, order = 12, get = function() - local c = ClassyMap.db.profile.borderColor + local c = Core:ValidateColor(ClassyMap.db.profile.borderColor) return c.r, c.g, c.b, c.a end, set = function(_, r, g, b, a) - ClassyMap.db.profile.borderColor = { r = r, g = g, b = b, a = a } - ClassyMap:UpdateBorderStyle() + ClassyMap.db.profile.borderColor = Core:ValidateColor({ r = r, g = g, b = b, a = a }) + ClassyMap:RequestRefresh("border") end, }, @@ -78,22 +81,22 @@ local function GetOptions() end, set = function(_, val) ClassyMap.db.profile.font = val - ClassyMap:ApplyMinimapChanges() + ClassyMap:RequestRefresh("fonts") end, }, zoneFontSize = { type = "range", name = L["Zone Text Size"], min = 6, - max = 16, + max = 24, step = 1, order = 18, get = function() - return ClassyMap.db.profile.zoneFontSize + return Core:ValidateFontSize(ClassyMap.db.profile.zoneFontSize) end, set = function(_, val) - ClassyMap.db.profile.zoneFontSize = val - ClassyMap:ApplyMinimapChanges() + ClassyMap.db.profile.zoneFontSize = Core:ValidateFontSize(val) + ClassyMap:RequestRefresh("fonts") end, }, overrideZoneColor = { @@ -107,7 +110,7 @@ local function GetOptions() end, set = function(_, val) ClassyMap.db.profile.overrideZoneColor = val - ClassyMap:ApplyMinimapChanges() + ClassyMap:RequestRefresh("fonts") end, }, zoneTextColor = { @@ -116,12 +119,12 @@ local function GetOptions() hasAlpha = true, order = 19, get = function() - local c = ClassyMap.db.profile.zoneTextColor + local c = Core:ValidateColor(ClassyMap.db.profile.zoneTextColor) return c.r, c.g, c.b, c.a end, set = function(_, r, g, b, a) - ClassyMap.db.profile.zoneTextColor = { r = r, g = g, b = b, a = a } - ClassyMap:ApplyMinimapChanges() + ClassyMap.db.profile.zoneTextColor = Core:ValidateColor({ r = r, g = g, b = b, a = a }) + ClassyMap:RequestRefresh("fonts") end, disabled = function() return not ClassyMap.db.profile.overrideZoneColor @@ -131,15 +134,15 @@ local function GetOptions() type = "range", name = L["Clock Text Size"], min = 6, - max = 16, + max = 24, step = 1, order = 20, get = function() - return ClassyMap.db.profile.clockFontSize + return Core:ValidateFontSize(ClassyMap.db.profile.clockFontSize) end, set = function(_, val) - ClassyMap.db.profile.clockFontSize = val - ClassyMap:ApplyMinimapChanges() + ClassyMap.db.profile.clockFontSize = Core:ValidateFontSize(val) + ClassyMap:RequestRefresh("fonts") end, }, clockTextColor = { @@ -148,16 +151,15 @@ local function GetOptions() hasAlpha = true, order = 21, get = function() - local c = ClassyMap.db.profile.clockTextColor + local c = Core:ValidateColor(ClassyMap.db.profile.clockTextColor) return c.r, c.g, c.b, c.a end, set = function(_, r, g, b, a) - ClassyMap.db.profile.clockTextColor = { r = r, g = g, b = b, a = a } - ClassyMap:ApplyMinimapChanges() + ClassyMap.db.profile.clockTextColor = Core:ValidateColor({ r = r, g = g, b = b, a = a }) + ClassyMap:RequestRefresh("fonts") end, }, - -- Hide Elements -- Hide Elements hideHeader = { type = "header", @@ -175,7 +177,7 @@ local function GetOptions() end, set = function(_, val) ClassyMap.db.profile.hideTracking = val - ClassyMap:ApplyMinimapChanges() + ClassyMap:RequestRefresh("visibility") end, }, @@ -189,7 +191,7 @@ local function GetOptions() end, set = function(_, val) ClassyMap.db.profile.hideZoneText = val - ClassyMap:ApplyMinimapChanges() + ClassyMap:RequestRefresh("visibility") end, }, hideClock = { @@ -202,7 +204,7 @@ local function GetOptions() end, set = function(_, val) ClassyMap.db.profile.hideClock = val - ClassyMap:ApplyMinimapChanges() + ClassyMap:RequestRefresh("visibility") end, }, @@ -217,7 +219,7 @@ local function GetOptions() end, set = function(_, val) ClassyMap.db.profile.hideZoomButtons = val - ClassyMap:ApplyMinimapChanges() + ClassyMap:RequestRefresh("visibility") end, }, hideExpansionButton = { @@ -230,7 +232,7 @@ local function GetOptions() end, set = function(_, val) ClassyMap.db.profile.hideExpansionButton = val - ClassyMap:ApplyMinimapChanges() + ClassyMap:RequestRefresh("visibility") end, }, -- Custom Icon Input removed as per request (Hardcoded) @@ -245,7 +247,7 @@ local function GetOptions() end, set = function(_, val) ClassyMap.db.profile.hideCalendar = val - ClassyMap:ApplyMinimapChanges() + ClassyMap:RequestRefresh("visibility") end, }, hideAddonBtn = { @@ -257,7 +259,7 @@ local function GetOptions() end, set = function(_, val) ClassyMap.db.profile.hideAddonBtn = val - ClassyMap:ApplyMinimapChanges() + ClassyMap:RequestRefresh("visibility") end, }, hideInstance = { @@ -269,25 +271,56 @@ local function GetOptions() end, set = function(_, val) ClassyMap.db.profile.hideInstance = val - ClassyMap:ApplyMinimapChanges() + ClassyMap:RequestRefresh("visibility") end, }, }, } + + options.args.profiles = AceDBOptions:GetOptionsTable(ClassyMap.db) + options.args.profiles.order = 100 + return options end -- ============================================================================= -- Registration -- ============================================================================= +function Settings:OnProfileUpdated() + local ClassyMap = ns.ClassyMap + ClassyMap:RequestRefresh("all") + AceConfigRegistry:NotifyChange("ClassyMap") +end + +function Settings:RegisterProfileCallbacks() + if self.profileCallbacksRegistered then + return + end + + local db = ns.ClassyMap.db + db.RegisterCallback(self, "OnProfileChanged", "OnProfileUpdated") + db.RegisterCallback(self, "OnProfileCopied", "OnProfileUpdated") + db.RegisterCallback(self, "OnProfileReset", "OnProfileUpdated") + self.profileCallbacksRegistered = true +end + function Settings:Initialize() + if self.optionsFrame then + return true + end + if not ns.ClassyMap or not ns.ClassyMap.db then + return false + end + AceConfig:RegisterOptionsTable("ClassyMap", GetOptions) self.optionsFrame = AceConfigDialog:AddToBlizOptions("ClassyMap", "ClassyMap") + self:RegisterProfileCallbacks() + return true end function Settings:OpenOptions() -- Ensure registered - if not self.optionsFrame then - self:Initialize() + if not self.optionsFrame and not self:Initialize() then + return end -- Open standalone dialog @@ -297,9 +330,14 @@ end -- Auto-init on addon load local loader = CreateFrame("Frame") loader:RegisterEvent("ADDON_LOADED") -loader:SetScript("OnEvent", function(self, event, addon) +loader:SetScript("OnEvent", function(self, _, addon) if addon == addonName then - Settings:Initialize() self:UnregisterEvent("ADDON_LOADED") + if not Settings:Initialize() then + -- AceAddon normally initializes first; defer once if event ordering differs. + C_Timer.After(0, function() + Settings:Initialize() + end) + end end end) diff --git a/docs/quality-review.md b/docs/quality-review.md new file mode 100644 index 0000000..3d20590 --- /dev/null +++ b/docs/quality-review.md @@ -0,0 +1,42 @@ +# Repository quality review — 2026-09-06 + +Follow-up implementation: [runtime-design.md](runtime-design.md) documents the unified refresh scheduler, frame ownership and partial restoration, cumulative diagnostics, and strict tests against bundled Ace libraries. The findings below describe the original review; its lack of a restoration foundation has since been addressed within the limits described there. + +Scope: all first-party runtime code, Core tests, locales, documentation, packaging, dependency declarations, and the TOC/XML load graph. Bundled libraries were checked for load integrity and relevant API contracts; they were not rewritten or upgraded. No release or game installation was performed. + +## Findings addressed + +| Priority | Finding and impact | Resolution | +| --- | --- | --- | +| P1 | `RunSafe` registered `PLAYER_REGEN_ENABLED` without naming its handler. AceEvent then looked for a nonexistent method, so combat-deferred changes could fail. Settings could also call protected layout changes directly during combat. | Explicit handler registration; full refreshes and layout requests defer and coalesce during combat. | +| P1 | The Core and runtime queue implementations disagreed. Errors interrupted Core drains, nested work could disappear, and trailing nil arguments were lost. | One detached-batch Core drain with error isolation, preserved argument counts, and subsequent runtime drains for nested actions. | +| P2 | `FixLayout` called a hooked `SetWidth`; the hook could repeat layout synchronously. Height changes were not covered, and error paths could leave guards stuck. | Coalesced next-frame width/height invalidation, guarded layout execution, and guard cleanup after failure. | +| P2 | Clock styling assumed the first region was a FontString. It can be a texture. Late-loaded Blizzard components also missed styling. | Target `TimeManagerClockTicker` and refresh on relevant Blizzard addon load events. | +| P2 | Disabling custom zone color left the old color applied; Blizzard could overwrite an enabled override. A hidden zone heading also left the clock anchored beneath it. | Restore color through Blizzard's `Minimap_Update`, apply custom color after native updates, and anchor the clock to the map when the heading is hidden. | +| P2 | A minimap addon replaced a global covenant-renown mixin method to work around an old beta issue, altering unrelated Blizzard UI behavior. | Removed that replacement. The current shortcut opens the Adventure Guide. | +| P2 | Non-finite saved sizes and colors passed through validation. Color getters could index malformed values. | Reject non-finite values and normalize settings at display/write boundaries. | +| P2 | Mechanic debug logging inspected `ClassyMapDB.profile`, which is not the active AceDB profile. The throttle table grew with every unique message. | Read `ns.ClassyMap.db.profile`, bound throttle entries to retained history, and clear both together. | +| P2 | Mechanic's toggle changed an unused `enabled` field. Border diagnostics ignored missing edges/visibility, and the mask check passed based on that field alone. | Replace toggle with Reapply, inspect all four borders, and leave the visual mask check pending for manual verification. | +| P2 | Profiling reported seconds as milliseconds and included a total alongside its components, causing the consumer to count work twice. | Report milliseconds and a non-overlapping remainder bucket. | +| P3 | Font/color edits rebuilt the full minimap; profile changes did not refresh the UI. | Apply font styles alone for those edits; register AceDB change/copy/reset callbacks. | +| P3 | README advertised unsupported commands/settings and third-party button collection. Lint relied on a sibling checkout; packages included development material and dependency metadata listed unused libraries. | Align docs with implementation, provide a standalone lint configuration, and clean package exclusions and dependency declarations. | + +## Architecture assessment and remaining work + +The existing split between pure Core logic, WoW frame integration, settings, and optional diagnostics is appropriate for this addon's size. Centralizing queue processing and refresh scheduling addresses the most consequential coupling without a large module rewrite. + +The follow-up now captures observable frame state, makes hooks conditional, cancels pending refreshes on disable, and restores eligible properties without overwriting observed external changes. Complete removal still requires reload because original mask/blob state is not observable. Square mask behavior and matching shape reporting remain consistent until then. No control claims complete runtime disable. See [runtime-design.md](runtime-design.md) for the precise contract. + +Edit Mode and other minimap addons can also modify the same frames. Offline mocks cannot prove freedom from taint, protected-frame failures, visual overlap, or conflicts with competing layout owners. Validate in the intended client with the user's actual addon set before release. Existing client assumptions are documented by the TOC interface target; this review does not certify future-client compatibility. + +New diagnostic strings have English locale defaults; the ten other locales use AceLocale fallback for those strings. Existing translations are preserved. Human translations remain a follow-up. + +## Validation + +Reproducible offline commands are in [CONTRIBUTING.md](../CONTRIBUTING.md). The regression suites cover Core validation/queues, runtime combat/layout/font behavior, settings callbacks, and Mechanic diagnostics. `tests/check_repo.py` checks the complete TOC/XML graph, compiles every loaded Lua source, and verifies English defaults for all used locale keys. These checks do not execute the game client. + +Final results: 26 Core tests pass both with the fallback clamp and with the bundled FenCore domain; runtime, settings, and Mechanic regression suites pass. Luacheck reports zero warnings/errors across 15 runtime files. All 87 load-graph files exist, all 70 loaded Lua files compile, and all 72 used locale keys have English defaults. Formatting and `git diff --check` pass. Forty diagnostic keys fall back to English in each non-English locale. + +Mechanic MCP was unavailable in this session, so no `addon.output`, live sandbox command, installed-client inspection, or game-state assertion was made. Complete offline checks first, install/sync this checkout, then `/reload` and confirm completion before collecting diagnostic output through an available Mechanic connection. + +In-game checks: square normal/hybrid maps; border size zero and nonzero; every hide toggle; font/color changes and restoration; changes during two consecutive combats; zone changes; clock load; and Edit Mode resizing/positioning. diff --git a/docs/runtime-design.md b/docs/runtime-design.md new file mode 100644 index 0000000..a6527af --- /dev/null +++ b/docs/runtime-design.md @@ -0,0 +1,47 @@ +# Refresh scheduling, frame ownership, and diagnostics + +## Refresh requests + +Call `ClassyMap:RequestRefresh(scope)` after changing settings. Requests combine until the next timer turn and use the latest profile values when executed. + +| Scope | Work | +| --- | --- | +| `border` | Create/update ClassyMap's border textures | +| `fonts` | Zone/clock fonts and text colors | +| `visibility` | Minimap clutter/visibility, followed by layout | +| `layout` | Frame positioning and layout | +| `all` | Map setup plus every category above, once | + +A full request subsumes narrower requests. Work waits until the addon is enabled, the world is ready, and combat lockdown ends. Settings callbacks and Mechanic tools use this same entry point. `ApplyMinimapChanges`, `ApplyFontStyles`, and `FixLayout` retain compatibility entry points that enqueue work when called outside a scheduled refresh. + +Disable invalidates scheduled callbacks, clears pending requests and combat actions, and makes permanent hooks inactive. Re-enable starts a new scheduling generation. Requests raised during a refresh belong to a subsequent batch. Category failures are reported independently so another requested category can still run. + +## Frame ownership + +`OwnSet` captures observable properties before their first modification and records the values left by ClassyMap. If a subsequent comparison observes a different value, ClassyMap relinquishes that property for the current enable cycle. Matching properties can be restored on disable; properties changed by another participant are left alone. + +Restoration determines eligibility before changing anything, then restores properties in a defined order: parents and geometry before styling and visibility. This avoids treating a restoration's own side effects as a new external change. Combat-delayed restoration uses a private frame because AceEvent removes the addon's event registrations after `OnDisable` returns. + +Known native zone-color and expansion-button visibility updates have explicit policies that keep ClassyMap's enabled customization working. Ownership is based on observed values, not the identity of the addon making a call. It cannot distinguish another addon invoking the same native update path, or a change to an identical value. This is cooperative behavior, not a guarantee against all minimap-addon conflicts. + +The original minimap mask/blob scalar state cannot be queried reliably through matching getters. Disabling therefore stops scheduling and restores eligible geometry/styles, but retains square mask behavior and matching square shape reporting until reload. Hybrid mask behavior follows the same policy. No settings control advertises complete runtime disable; remove/disable the addon and reload for full removal. Another addon replacing the shape function is respected by subsequent setup work. + +## Performance measurements + +Executed work records six fixed metric names: `CreateBorder`, `HideClutter`, `ApplyFontStyles`, `FixLayout`, `Setup`, and `Refresh`. Independent font/layout refreshes are included. Queued requests that combine into one execution do not inflate invocation counts. + +Counts represent executions, including failed attempts; failures are reported through the game's error handler. Measurements describe ClassyMap's instrumented work and do not measure the complete CPU cost of other addons or Blizzard UI. + +`ClassyMapMechanic:GetPerformanceStats()` returns a detached snapshot with elapsed seconds and per-metric count, cumulative milliseconds, last duration, maximum duration, mean duration, calls/second, and milliseconds/second. Invalid samples and unknown names are rejected; the number of stored metrics is fixed. + +Mechanic's performance table is labeled milliseconds/second, so the exported `ms` value is cumulative measured time divided by elapsed time since collection began or was reset. Descriptions include count/total/mean/maximum/last duration. These are averages over the observation window, not instantaneous rates. No per-frame polling is added. + +`Refresh` is the inclusive batch duration. It is available in the snapshot but excluded from the category table, so the consumer cannot count the same work twice. Scheduler/instrumentation overhead can make the inclusive duration larger than the sum of its categories. The **Reset Metrics** tool starts a fresh observation window. + +## Offline and live verification + +The strict mock exposes explicit methods, records state, and rejects protected mutations during simulated combat. Runtime regressions exercise coalescing, ownership, cancellation, and late loads. The Ace integration suite loads the bundled AceAddon, AceEvent, CallbackHandler, and AceDB implementations to exercise real lifecycle ordering and profile callbacks; UI and client APIs remain mocked. + +Run the commands in [CONTRIBUTING.md](../CONTRIBUTING.md). These tests cannot establish client taint safety, rendering correctness, or compatibility with the user's complete addon set. After syncing the checkout, a confirmed `/reload` plus combat, Edit Mode, zone-change, and hide/show checks remains the live release gate. + +Follow-up validation (2026-09-06): 26 Core tests pass in both fallback and FenCore modes; runtime, settings, bundled Ace integration, and Mechanic regressions pass. Luacheck reports zero warnings/errors for 15 runtime files, including a separate check without the shared workspace lint configuration. All 87 manifest references exist and all 70 loaded Lua sources compile. Formatting, package exclusions, English locale defaults, and diff whitespace checks pass. The five new diagnostic strings use English fallback in non-English locales. The user subsequently reported successful manual in-game testing; individual scenarios and client build were not recorded. Remote CI results are tracked on the release PR. diff --git a/tests/ace_integration.lua b/tests/ace_integration.lua new file mode 100644 index 0000000..e36f2c7 --- /dev/null +++ b/tests/ace_integration.lua @@ -0,0 +1,180 @@ +-- Bundled Ace lifecycle integration: lua tests/ace_integration.lua + +local Mock = dofile("tests/support/wow_mock.lua") +local Assert = dofile("tests/support/assertions.lua") +local nativeXpcall = xpcall + +local function installAceLibraries(env) + -- WoW's xpcall accepts arguments; Lua 5.1's stock implementation does not. + _G.xpcall = function(callback, errorHandler, ...) + local args = Mock.pack(...) + return nativeXpcall(function() + return callback(unpack(args, 1, args.n)) + end, errorHandler) + end + _G.LibStub = nil + _G.ClassyMapDB = nil + _G.ClassyMapCore = nil + _G.ClassyMapMechanic = nil + _G.SLASH_ACECONSOLE_CLASSYMAP1 = nil + _G.SLASH_ACECONSOLE_CM1 = nil + + dofile("Libs/LibStub/LibStub.lua") + dofile("Libs/CallbackHandler-1.0/CallbackHandler-1.0.lua") + dofile("Libs/AceAddon-3.0/AceAddon-3.0.lua") + dofile("Libs/AceDB-3.0/AceDB-3.0.lua") + dofile("Libs/AceConsole-3.0/AceConsole-3.0.lua") + dofile("Libs/AceEvent-3.0/AceEvent-3.0.lua") + dofile("Libs/AceLocale-3.0/AceLocale-3.0.lua") + + local sharedMedia = assert(LibStub:NewLibrary("LibSharedMedia-3.0", 1)) + function sharedMedia:Fetch() + return "font.ttf" + end + function sharedMedia:HashTable() + return { Default = "font.ttf" } + end + + local registrations = { notify = 0, options = 0 } + local aceConfig = assert(LibStub:NewLibrary("AceConfig-3.0", 1)) + function aceConfig:RegisterOptionsTable(_, options) + registrations.options = registrations.options + 1 + registrations.optionsFactory = options + end + local dialog = assert(LibStub:NewLibrary("AceConfigDialog-3.0", 1)) + function dialog:AddToBlizOptions() + return {} + end + function dialog:Open() + registrations.opened = true + end + local registry = assert(LibStub:NewLibrary("AceConfigRegistry-3.0", 1)) + function registry:NotifyChange(name) + Assert.equal(name, "ClassyMap", "wrong AceConfig notification") + registrations.notify = registrations.notify + 1 + end + local dbOptions = assert(LibStub:NewLibrary("AceDBOptions-3.0", 1)) + function dbOptions:GetOptionsTable() + return { type = "group", name = "Profiles" } + end + + dofile("Locales/enUS.lua") + dofile("Core/init.lua") + local namespace = {} + assert(loadfile("ClassyMap.lua"))("ClassyMap", namespace) + assert(loadfile("Settings.lua"))("ClassyMap", namespace) + return namespace, LibStub("AceAddon-3.0"), registrations +end + +local function instrumentRefreshes(addon) + local requests = {} + local original = addon.RequestRefresh + function addon:RequestRefresh(category) + requests[#requests + 1] = category + return original(self, category) + end + return requests +end + +local function runBeforeLoginScenario() + local env = Mock.new({ loggedIn = false }) + local namespace, aceAddon, registrations = installAceLibraries(env) + local addon = namespace.ClassyMap + local requests = instrumentRefreshes(addon) + + Assert.equal(addon.db, nil, "addon initialized before ADDON_LOADED") + env:FireEvent("ADDON_LOADED", "ClassyMap") + Assert.truthy(addon.db, "AceAddon did not initialize ClassyMap") + Assert.equal(not aceAddon.statuses.ClassyMap, true, "addon enabled before login") + Assert.equal(registrations.options, 1, "Settings did not initialize after the database") + Assert.equal(#requests, 0, "disabled startup requested a refresh") + Assert.equal(Minimap.maskTexture, "native-mask", "disabled startup mutated the minimap") + + env:SetLoggedIn(true) + env:FireEvent("PLAYER_LOGIN") + Assert.equal(aceAddon.statuses.ClassyMap, true, "PLAYER_LOGIN did not enable ClassyMap") + Assert.equal(requests[#requests], "all", "enable did not request a complete refresh") + Assert.equal(Minimap.maskTexture, "native-mask", "enable refreshed synchronously") + env:FlushTimers() + Assert.equal(Minimap.maskTexture, "Interface\\BUTTONS\\WHITE8X8", "scheduled startup refresh did not run") + Assert.equal(#env.errors, 0, "Ace lifecycle reported an error: " .. tostring(env.errors[1])) + + -- These are real AceDB callbacks registered by Settings. + local db = addon.db + db.profile.borderSize = 3 + db:SetProfile("Alternate") + Assert.equal(requests[#requests], "all", "OnProfileChanged did not request all work") + env:FlushTimers() + db.profile.borderSize = 5 + db:SetProfile("Source") + env:FlushTimers() + db.profile.borderSize = 7 + db:SetProfile("Alternate") + env:FlushTimers() + db:CopyProfile("Source") + Assert.equal(db.profile.borderSize, 7, "AceDB did not copy the profile") + Assert.equal(requests[#requests], "all", "OnProfileCopied did not request all work") + env:FlushTimers() + db:ResetProfile() + Assert.equal(db.profile.borderSize, 1, "AceDB did not restore profile defaults") + Assert.equal(requests[#requests], "all", "OnProfileReset did not request all work") + env:FlushTimers() + Assert.equal(registrations.notify, 5, "profile callbacks did not notify AceConfig") + + -- AceAddon disables AceEvent after OnDisable returns. Combat restoration must + -- therefore survive on the addon's private one-shot event frame. + env:SetCombat(true) + addon:RequestRefresh("border") + addon:Disable() + Assert.equal(aceAddon.statuses.ClassyMap, false, "AceAddon did not disable ClassyMap") + Assert.truthy(addon.restoreFrame, "combat disable did not create a restoration frame") + Assert.equal( + addon.restoreFrame:IsEventRegistered("PLAYER_REGEN_ENABLED"), + true, + "AceEvent cleanup removed the private restoration event" + ) + Assert.point(Minimap, 1, { "CENTER", MinimapCluster, "CENTER", 0, 0 }, "combat disable mutated protected anchors") + env:SetCombat(false) + env:FireEvent("PLAYER_REGEN_ENABLED") + env:FlushTimers() + Assert.point(Minimap, 1, { "CENTER", MinimapCluster, "CENTER", 3, 4 }, "regen did not restore owned anchors") + Assert.equal(addon.restorePending, nil, "combat restoration remained pending") + Assert.equal(#env.errors, 0, "profile callbacks reported an error") +end + +local function runLoadOnDemandScenario() + local env = Mock.new({ loggedIn = true }) + local namespace, aceAddon = installAceLibraries(env) + local addon = namespace.ClassyMap + local requests = instrumentRefreshes(addon) + + env:FireEvent("ADDON_LOADED", "ClassyMap") + Assert.equal(aceAddon.statuses.ClassyMap, true, "logged-in ADDON_LOADED did not enable ClassyMap") + Assert.equal(requests[#requests], "all", "load-on-demand enable did not request all work") + Assert.equal(Minimap.maskTexture, "native-mask", "load-on-demand refresh ran synchronously") + env:FlushTimers() + + TimeManagerClockButton = env:NewFrame("TimeManagerClockButton", { + parent = MinimapCluster, + protected = true, + }) + TimeManagerClockTicker = env:NewFrame("TimeManagerClockTicker", { + objectType = "FontString", + parent = TimeManagerClockButton, + protected = true, + }) + local before = #requests + env:FireEvent("ADDON_LOADED", "Blizzard_TimeManager") + Assert.equal(#requests, before + 1, "late Blizzard load did not request a refresh") + Assert.equal(requests[#requests], "all", "late Blizzard load requested partial work") + Assert.equal(TimeManagerClockTicker:GetFont(), "native.ttf", "late-load refresh ran synchronously") + env:FlushTimers() + local _, size = TimeManagerClockTicker:GetFont() + Assert.equal(size, addon.db.profile.clockFontSize, "late clock did not receive font styling") + Assert.equal(#env.errors, 0, "load-on-demand lifecycle reported an error") +end + +runBeforeLoginScenario() +runLoadOnDemandScenario() +_G.xpcall = nativeXpcall +print("Ace integration regressions passed") diff --git a/tests/check_repo.py b/tests/check_repo.py new file mode 100644 index 0000000..0341c19 --- /dev/null +++ b/tests/check_repo.py @@ -0,0 +1,71 @@ +"""Offline TOC/XML, Lua syntax, and locale checks; no game or installed state access.""" + +import argparse +from pathlib import Path +import re +import subprocess +import xml.etree.ElementTree as ET + + +ROOT = Path(__file__).resolve().parents[1] +KEY = re.compile(r'L\["((?:\\.|[^"\\])*)"\]') + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--lua", required=True, help="Path to a Lua 5.1 executable") + args = parser.parse_args() + visited = set() + + def visit(path): + path = path.resolve() + assert path.is_relative_to(ROOT), f"Manifest escapes repository: {path}" + assert path.is_file(), f"Missing packaged dependency: {path}" + if path in visited: + return + visited.add(path) + if path.suffix == ".xml": + for element in ET.parse(path).iter(): + if "file" in element.attrib: + visit(path.parent / element.attrib["file"].replace("\\", "/")) + + for line in (ROOT / "ClassyMap.toc").read_text().splitlines(): + line = line.strip() + if line and not line.startswith("#"): + visit(ROOT / line.replace("\\", "/")) + # The package uses an unquoted, literal-path ignore list (no glob patterns). + package = (ROOT / ".pkgmeta").read_text() + ignore_block = package.split("ignore:\n", 1)[1].split("\nmanual-changelog:", 1)[0] + ignored = re.findall(r"^ - ([^\r\n]+)$", ignore_block, re.MULTILINE) + for path in visited: + relative = path.relative_to(ROOT).as_posix() + assert not any(relative == item or relative.startswith(item + "/") for item in ignored), ( + f"Required dependency excluded from package: {relative}" + ) + scripts = sorted(path for path in visited if path.suffix == ".lua") + syntax = subprocess.run( + [args.lua, "-e", 'for path in io.lines() do assert(loadfile(path)) end'], + input="\n".join(path.as_posix() for path in scripts) + "\n", + text=True, + capture_output=True, + check=False, + ) + assert syntax.returncode == 0, syntax.stderr + print(f"Manifest: {len(visited)} referenced files exist; {len(scripts)} Lua files compile") + + baseline = set(KEY.findall((ROOT / "Locales/enUS.lua").read_text(encoding="utf-8"))) + used = set() + for path in [ROOT / "ClassyMap.lua", ROOT / "Settings.lua", ROOT / "Mechanic.lua"]: + used.update(KEY.findall(path.read_text(encoding="utf-8"))) + assert not used - baseline, f"Missing English locale keys: {sorted(used - baseline)}" + for path in sorted((ROOT / "Locales").glob("*.lua")): + source = path.read_text(encoding="utf-8") + keys = set(KEY.findall(source)) + assert not keys - baseline, f"Unknown locale keys in {path.name}: {keys - baseline}" + assert 'if not L then' in source and source.index('if not L then') < source.index('L['), path + print(f"Locale {path.stem}: {len(baseline - keys)} keys use English fallback") + print(f"Localization: all {len(used)} used keys have English defaults") + + +if __name__ == "__main__": + main() diff --git a/tests/mechanic_regressions.lua b/tests/mechanic_regressions.lua new file mode 100644 index 0000000..6d678c2 --- /dev/null +++ b/tests/mechanic_regressions.lua @@ -0,0 +1,211 @@ +-- Run from the repository root with Lua 5.1. +dofile("Core/init.lua") +local frames, messages = {}, {} +local now, registrationCount = 1, 0 +local library, registration +local locale = setmetatable({}, { + __index = function(_, key) + return key + end, +}) +function LibStub(name) + if name == "AceLocale-3.0" then + return { + GetLocale = function() + return locale + end, + } + end + return library +end +function CreateFrame() + local frame = { scripts = {}, events = {} } + function frame:RegisterEvent(event) + self.events[event] = true + end + function frame:UnregisterEvent(event) + self.events[event] = nil + end + function frame:SetScript(event, callback) + self.scripts[event] = callback + end + function frame:SetPoint() end + function frame:SetSize() end + function frame:SetText(value) + self.text = value + end + function frame:CreateFontString() + return CreateFrame() + end + frames[#frames + 1] = frame + return frame +end +function GetTime() + return now +end +function debugprofilestop() + return now * 1000 +end +function wipe(tbl) + for key in pairs(tbl) do + tbl[key] = nil + end +end +C_AddOns = { + GetAddOnMetadata = function() + return "test" + end, +} +ClassyMapDB = { profiles = { Default = { debugMode = false } } } +local requested = {} +local addon = { db = { profile = { debugMode = true, borderSize = 1 } } } +function addon:RequestRefresh(scope) + requested[#requested + 1] = scope +end +local ns = { ClassyMap = addon } +assert(loadfile("Mechanic.lua"))("ClassyMap", ns) +local diagnostics, loader = ClassyMapMechanic, frames[1] +loader.scripts.OnEvent(loader, "ADDON_LOADED", "ClassyMap") +assert(loader.events.ADDON_LOADED, "Missing optional Mechanic must allow later registration") +library = { + Categories = { CORE = "core" }, + Register = function(_, _, config) + registrationCount = registrationCount + 1 + registration = config + end, + Log = function(_, _, msg) + messages[#messages + 1] = msg + end, +} +loader.scripts.OnEvent(loader, "ADDON_LOADED", "!Mechanic") +assert(registrationCount == 1 and not loader.events.ADDON_LOADED) + +diagnostics:Log("first") +diagnostics:Log("first") +assert(#diagnostics.debugBuffer == 1 and #messages == 1, "Use active AceDB profile and throttle duplicates") +addon.db.profile = { debugMode = false, borderSize = 1 } +diagnostics:Log("disabled") +assert(#diagnostics.debugBuffer == 1, "Follow active profile changes") +addon.db.profile.debugMode = true +for i = 1, 600 do + now = now + 1 + diagnostics:Log(tostring(i)) +end +assert(#diagnostics.debugBuffer == 500, "Debug history stays bounded") +for index = 1, 20 do + local name, value = debug.getupvalue(diagnostics.Log, index) + if not name then + break + end + if name == "logThrottle" then + local count = 0 + for _ in pairs(value) do + count = count + 1 + end + assert(count <= 500, "Throttle keys must not grow beyond retained history") + end +end +registration.clearDebugBuffer() +diagnostics:Log("600") +assert(#diagnostics.debugBuffer == 1, "Clear resets history and throttle together") + +local function texture(shown) + return { + IsShown = function() + return shown + end, + } +end +addon.borders = { top = texture(true), bottom = texture(true), left = texture(true), right = texture(true) } +assert(diagnostics:GetTestResult("border_textures").passed) +addon.borders.right = nil +assert(diagnostics:GetTestResult("border_textures").passed == false, "Missing right border must fail") +addon.borders.right = texture(false) +assert(diagnostics:GetTestResult("border_textures").passed == false, "Unexpected hidden border must fail") +addon.db.profile.borderSize = 0 +for key in pairs(addon.borders) do + addon.borders[key] = texture(false) +end +assert(diagnostics:GetTestResult("border_textures").passed, "Zero-size hidden borders are valid") +assert(diagnostics:GetTestResult("mask_texture").passed == nil, "Visual mask checks cannot claim an automatic pass") +function GetMinimapShape() + return "SQUARE" +end +addon.db.profile.enabled = false -- Obsolete saved flag has no runtime meaning. +assert(diagnostics:GetTestResult("minimap_shape").passed) +-- Empty/reset windows are finite, and snapshots cannot change internal counters. +diagnostics:ResetPerformanceMetrics() +local empty = diagnostics:GetPerformanceStats() +assert(empty.elapsedSeconds == 0 and empty.metrics.Refresh.count == 0) +assert(empty.metrics.CreateBorder.msPerSecond == 0) +assert(#diagnostics:GetPerformanceSubMetrics() == 5) +assert(diagnostics:RecordPerfMetric("CreateBorder", 2.5)) +assert(diagnostics:RecordPerfMetric("CreateBorder", 0.5)) +assert(diagnostics:RecordPerfMetric("FixLayout", 4)) +assert(diagnostics:RecordPerfMetric("Setup", 3)) +assert(diagnostics:RecordPerfMetric("Refresh", 12)) +now = now + 2 +local stats = diagnostics:GetPerformanceStats() +assert(stats.elapsedSeconds == 2) +local border = stats.metrics.CreateBorder +assert(border.count == 2 and border.totalMs == 3 and border.maxMs == 2.5) +assert(border.lastMs == 0.5 and border.averageMs == 1.5) +assert(border.callsPerSecond == 1 and border.msPerSecond == 1.5) +border.totalMs = 999 +assert(diagnostics:GetPerformanceStats().metrics.CreateBorder.totalMs == 3) +local total = 0 +for _, metric in ipairs(diagnostics:GetPerformanceSubMetrics()) do + total = total + metric.ms +end +assert(total == 5, "Breakdown rates include categories only, never their inclusive Refresh total") +assert(diagnostics:GetPerformanceSubMetrics()[1].description:find("2 calls", 1, true)) +assert(not diagnostics:RecordPerfMetric("CreateBorder", -1)) +assert(not diagnostics:RecordPerfMetric("CreateBorder", 0 / 0)) +assert(not diagnostics:RecordPerfMetric("CreateBorder", math.huge)) +assert(not diagnostics:RecordPerfMetric("CreateBorder", "3")) +for i = 1, 1000 do + assert(not diagnostics:RecordPerfMetric("unknown" .. i, 1)) +end +local entries = 0 +for _ in pairs(diagnostics:GetPerformanceStats().metrics) do + entries = entries + 1 +end +assert(entries == 6, "Metric cardinality is fixed") +assert(diagnostics:GetPerformanceStats().metrics.CreateBorder.count == 2) + +-- Many inexpensive invocations accumulate measurable work. +for _ = 1, 100 do + diagnostics:RecordPerfMetric("ApplyFontStyles", 0.125) +end +local fonts = diagnostics:GetPerformanceStats().metrics.ApplyFontStyles +assert(fonts.count == 100 and fonts.totalMs == 12.5 and fonts.maxMs == 0.125) + +diagnostics:CreateToolsPanel(CreateFrame()) +local found +for _, frame in ipairs(frames) do + if frame.text == "Reapply" then + frame.scripts.OnClick() + found = true + end +end +assert( + found and #requested == 1 and requested[1] == "all" and addon.db.profile.enabled == false, + "Reapply must not pretend to toggle the addon" +) +for _, frame in ipairs(frames) do + if frame.text == "2" then + frame.scripts.OnClick() + end + if frame.text == "Reset Metrics" then + frame.scripts.OnClick() + end +end +assert(requested[2] == "border", "Border tools must use the same refresh scheduler") +assert(diagnostics:GetPerformanceStats().metrics.ApplyFontStyles.count == 0) +assert(diagnostics:GetPerformanceStats().elapsedSeconds == 0) +assert(diagnostics:RecordPerfMetric("FixLayout", 0)) +assert(diagnostics:GetPerformanceStats().metrics.FixLayout.count == 1) +assert(diagnostics:RecordPerfMetric("Setup", 1e308)) +assert(not diagnostics:RecordPerfMetric("Setup", 1e308), "Cumulative duration must remain finite") +assert(diagnostics:GetPerformanceStats().metrics.Setup.count == 1) +print("Mechanic regressions passed") diff --git a/tests/run_core.lua b/tests/run_core.lua new file mode 100644 index 0000000..a1fa178 --- /dev/null +++ b/tests/run_core.lua @@ -0,0 +1,85 @@ +-- Minimal standalone runner for Core/core_spec.lua. +-- This keeps the pure Core suite runnable with Lua 5.1 when Busted is unavailable. + +local nativeAssert = assert +local contexts = {} +local failures = 0 +local tests = 0 + +local assertions = {} +setmetatable(assertions, { + __call = function(_, ...) + return nativeAssert(...) + end, +}) + +function assertions.equals(expected, actual) + nativeAssert(actual == expected, ("expected %s, got %s"):format(tostring(expected), tostring(actual))) +end + +function assertions.is_false(value) + nativeAssert(value == false, "expected false") +end + +function assertions.is_true(value) + nativeAssert(value == true, "expected true") +end + +function assertions.is_nil(value) + nativeAssert(value == nil, ("expected nil, got %s"):format(tostring(value))) +end + +function assertions.is_truthy(value) + nativeAssert(value, "expected a truthy value") +end + +function assertions.has_error(func, expected) + local success, err = pcall(func) + nativeAssert(not success, "expected an error") + err = tostring(err) + nativeAssert(err:sub(-#expected) == expected, ("expected error %q, got %q"):format(expected, err)) +end + +_G.assert = assertions + +function _G.describe(_, body) + local context = { beforeEach = {} } + table.insert(contexts, context) + body() + table.remove(contexts) +end + +function _G.before_each(callback) + table.insert(contexts[#contexts].beforeEach, callback) +end + +function _G.it(name, body) + tests = tests + 1 + local success, err = pcall(function() + for _, context in ipairs(contexts) do + for _, callback in ipairs(context.beforeEach) do + callback() + end + end + body() + end) + if not success then + failures = failures + 1 + io.stderr:write(("FAIL: %s\n%s\n"):format(name, tostring(err))) + end +end + +if arg[1] == "--fencore" then + -- Load the bundled pure domain and its real registry without WoW bootstrap code. + _G.FenCore = { Log = function() end } + dofile("Libs/FenCore/Core/Catalog.lua") + dofile("Libs/FenCore/Domains/Math.lua") +end +dofile("Core/init.lua") +dofile("Core/core_spec.lua") + +if failures > 0 then + error(("%d of %d core tests failed"):format(failures, tests), 0) +end + +print(("Core: %d tests passed"):format(tests)) diff --git a/tests/runtime_regressions.lua b/tests/runtime_regressions.lua new file mode 100644 index 0000000..278f477 --- /dev/null +++ b/tests/runtime_regressions.lua @@ -0,0 +1,403 @@ +-- Offline runtime regression checks: lua tests/runtime_regressions.lua + +local Mock = dofile("tests/support/wow_mock.lua") +local Assert = dofile("tests/support/assertions.lua") +local env = Mock.new({ loggedIn = true }) + +local addon = { events = {} } +function addon:RegisterEvent(event, method) + method = method or event + assert(type(method) == "function" or type(self[method]) == "function", "missing event handler") + self.events[event] = method +end +function addon:UnregisterEvent(event) + self.events[event] = nil +end +function addon:UnregisterAllEvents() + self.events = {} +end +function addon:RegisterChatCommand() end +function addon:Print() end + +local function fireAddonEvent(event, ...) + local method = addon.events[event] + if type(method) == "string" then + addon[method](addon, event, ...) + elseif method then + method(event, ...) + end +end + +local locale = setmetatable({}, { + __index = function(_, key) + return key + end, +}) +local libraries = { + ["AceAddon-3.0"] = { + NewAddon = function() + return addon + end, + }, + ["AceLocale-3.0"] = { + GetLocale = function() + return locale + end, + }, + ["LibSharedMedia-3.0"] = { + Fetch = function() + return "font.ttf" + end, + }, + ["AceDB-3.0"] = { + New = function(_, _, defaults) + return { profile = defaults.profile } + end, + }, +} +function _G.LibStub(name) + return assert(libraries[name], "unexpected library: " .. tostring(name)) +end + +dofile("Core/init.lua") +local namespace = {} +assert(loadfile("ClassyMap.lua"))("ClassyMap", namespace) +addon:OnInitialize() + +-- RunSafe preserves trailing nil arguments and re-registers its combat event +-- after each completed combat cycle. +for _ = 1, 2 do + env:SetCombat(true) + addon:RunSafe(function(_, ...) + Assert.equal(select("#", ...), 3, "RunSafe lost trailing nil arguments") + end, "a", nil, nil) + Assert.equal(addon.events.PLAYER_REGEN_ENABLED, "ProcessCombatQueue", "RunSafe registered the wrong handler") + env:SetCombat(false) + fireAddonEvent("PLAYER_REGEN_ENABLED") + Assert.equal(addon.events.PLAYER_REGEN_ENABLED, nil, "completed combat cycle left its event registered") +end + +-- One failing queued action cannot discard later work or work queued by a callback. +local nestedRuns = 0 +env:SetCombat(true) +addon:RunSafe(function() + error("expected queued failure") +end) +addon:RunSafe(function() + nestedRuns = nestedRuns + 1 + ClassyMapCore:QueueAction(function() + nestedRuns = nestedRuns + 1 + end) +end) +env:SetCombat(false) +fireAddonEvent("PLAYER_REGEN_ENABLED") +env:FlushTimers() +Assert.equal(nestedRuns, 2, "error or nested queue work discarded a later action") +Assert.equal(#env.errors, 1, "queued error was not isolated") +Assert.equal(addon.events.PLAYER_REGEN_ENABLED, nil, "nested queue drain left its event registered") +env.errors = {} + +local calls = {} +for _, method in ipairs({ "ApplyMinimapChanges", "CreateBorder", "HideMinimapClutter", "ApplyFontStyles", "FixLayout" }) do + local original = addon[method] + addon[method] = function(self, ...) + calls[method] = (calls[method] or 0) + 1 + return original(self, ...) + end +end +local function resetCalls() + for key in pairs(calls) do + calls[key] = nil + end + env:ResetCounts() +end + +-- Enabling is a queued lifecycle boundary and a full refresh performs each category once. +addon:OnEnable() +Assert.equal(Minimap.maskTexture, "native-mask", "OnEnable refreshed synchronously") +Assert.equal(#env.timers, 1, "OnEnable did not schedule one refresh") +env:FlushTimers() +Assert.equal(calls.ApplyMinimapChanges, 1, "startup did not perform one full refresh") +Assert.equal(calls.CreateBorder, 1, "startup did not create the border once") +Assert.equal(calls.HideMinimapClutter, 1, "startup did not apply visibility once") +Assert.equal(calls.ApplyFontStyles, 1, "startup did not apply fonts once") +Assert.equal(calls.FixLayout, 1, "startup did not apply layout once") +Assert.equal(#env.errors, 0, "startup reported an error") + +-- Both Blizzard dimension hooks coalesce, and a layout error cannot strand the guard. +resetCalls() +MinimapCluster:SetWidth(200) +MinimapCluster:SetHeight(210) +Assert.equal(#env.timers, 1, "width/height hooks did not coalesce") +env:FlushTimers() +Assert.equal(calls.FixLayout, 1, "dimension hooks did not request one layout pass") +Assert.equal(#env.timers, 0, "layout's own dimensions recursively scheduled work") + +resetCalls() +local setPoint = Minimap.SetPoint +Minimap.SetPoint = function() + error("expected layout failure") +end +addon:RequestRefresh("layout") +env:FlushTimers() +Assert.equal(addon.resizing, nil, "layout failure left the recursion guard set") +Assert.equal(#env.errors, 1, "layout failure was not reported once") +Minimap.SetPoint = setPoint +env.errors = {} +addon:RequestRefresh("layout") +env:FlushTimers() +Assert.equal(calls.FixLayout, 2, "layout did not recover after an exception") +Assert.equal(#env.errors, 0, "recovered layout still reported an error") + +-- Partial categories coalesce into one timer and visibility includes one layout pass. +resetCalls() +addon:RequestRefresh("border") +addon:RequestRefresh("fonts") +addon:RequestRefresh("visibility") +addon:RequestRefresh("layout") +addon:RequestRefresh("fonts") +Assert.equal(#env.timers, 1, "partial refresh requests did not coalesce") +env:FlushTimers() +Assert.equal(calls.ApplyMinimapChanges, nil, "partial work ran the full refresh") +Assert.equal(calls.CreateBorder, 1, "border category did not run exactly once") +Assert.equal(calls.HideMinimapClutter, 1, "visibility category did not run exactly once") +Assert.equal(calls.ApplyFontStyles, 1, "font category did not run exactly once") +Assert.equal(calls.FixLayout, 1, "layout category did not run exactly once") + +-- Independently requested work records its category and one aggregate refresh. +local metrics = {} +ClassyMapMechanic = { + RecordPerfMetric = function(_, name, duration) + assert( + type(duration) == "number" and duration == duration and math.abs(duration) < math.huge, + "non-finite metric" + ) + metrics[#metrics + 1] = name + end, +} +local function assertMetricNames(first, second) + Assert.equal(#metrics, 2, "partial refresh recorded the wrong number of metrics") + Assert.equal(metrics[1], first, "partial refresh recorded the wrong category metric") + Assert.equal(metrics[2], second, "partial refresh recorded the wrong aggregate metric") + metrics = {} +end +addon:RequestRefresh("fonts") +env:FlushTimers() +assertMetricNames("ApplyFontStyles", "Refresh") +addon:RequestRefresh("layout") +env:FlushTimers() +assertMetricNames("FixLayout", "Refresh") +ClassyMapMechanic = nil + +-- A full refresh supersedes pending category work instead of duplicating it. +resetCalls() +addon:RequestRefresh("border") +addon:RequestRefresh("all") +addon:RequestRefresh("fonts") +env:FlushTimers() +Assert.equal(calls.ApplyMinimapChanges, 1, "all scope did not run one full refresh") +Assert.equal(calls.CreateBorder, 1, "pending border work ran twice") +Assert.equal(calls.ApplyFontStyles, 1, "pending font work ran twice") +Assert.raises("Unknown refresh scope", function() + addon:RequestRefresh("typo") +end) + +-- Protected writes are rejected by the mock, while scheduler work waits for regen. +resetCalls() +env:SetCombat(true) +Assert.raises("protected mutation", function() + Minimap:SetPoint("CENTER") +end) +for _ = 1, 10 do + addon:RequestRefresh("all") +end +Assert.equal(#env.timers, 0, "combat refresh scheduled a mutating timer") +Assert.equal(calls.ApplyMinimapChanges, nil, "combat refresh touched protected frames") +Assert.equal(addon.events.PLAYER_REGEN_ENABLED, "ProcessCombatQueue", "regen handler was not registered") +env:SetCombat(false) +fireAddonEvent("PLAYER_REGEN_ENABLED") +Assert.equal(#env.timers, 1, "regen did not schedule pending work") +env:FlushTimers() +Assert.equal(calls.ApplyMinimapChanges, 1, "combat refresh did not drain once") + +-- A failing category cannot prevent independent pending work. +resetCalls() +local createBorder = addon.CreateBorder +addon.CreateBorder = function() + error("expected border failure") +end +addon:RequestRefresh("border") +addon:RequestRefresh("fonts") +env:FlushTimers() +addon.CreateBorder = createBorder +Assert.equal(calls.ApplyFontStyles, 1, "a border error discarded font work") +Assert.equal(#env.errors, 1, "category error was not isolated and reported") +env.errors = {} + +-- The clock FontString is targeted even if the button's first region is a Texture. +local firstRegion = env:NewFrame("ClockTexture", { objectType = "Texture" }) +Assert.raises("attempt to call", function() + firstRegion:SetFont("bad.ttf", 10) +end) +TimeManagerClockButton = env:NewFrame("TimeManagerClockButton", { + parent = MinimapCluster, + protected = true, + regions = { n = 1, firstRegion }, +}) +TimeManagerClockTicker = env:NewFrame("TimeManagerClockTicker", { + objectType = "FontString", + parent = TimeManagerClockButton, + protected = true, +}) +resetCalls() +fireAddonEvent("ADDON_LOADED", "Blizzard_TimeManager") +Assert.equal(#env.timers, 1, "late clock load was not queued") +env:FlushTimers() +local _, clockSize = TimeManagerClockTicker:GetFont() +Assert.equal(clockSize, addon.db.profile.clockFontSize, "named clock FontString was not styled") + +addon.db.profile.hideZoneText = true +addon:RequestRefresh("visibility") +env:FlushTimers() +Assert.point( + TimeManagerClockButton, + 1, + { "TOP", Minimap, "TOP", 0, -4 }, + "hidden zone heading left the clock anchored beneath it" +) +addon.db.profile.hideZoneText = false +addon:RequestRefresh("visibility") +env:FlushTimers() + +-- Hybrid mask ownership stays consistent with the retained square base mask. +HybridMinimap = { + MapCanvas = env:NewFrame("HybridMapCanvas", { useMaskTexture = false }), + CircleMask = env:NewFrame("HybridCircleMask", { + objectType = "Texture", + texture = "native-hybrid-mask", + }), +} +fireAddonEvent("ADDON_LOADED", "Blizzard_HybridMinimap") +env:FlushTimers() +Assert.equal(HybridMinimap.MapCanvas:GetUseMaskTexture(), true, "hybrid masking was not enabled") +Assert.equal( + HybridMinimap.CircleMask:GetTexture(), + "Interface\\BUTTONS\\WHITE8X8", + "hybrid map did not receive the square mask" +) + +-- Native zone changes update the restoration baseline, then reapply an enabled override. +addon.db.profile.overrideZoneColor = true +addon.db.profile.zoneTextColor = { r = 1, g = 0, b = 0, a = 1 } +addon:RequestRefresh("fonts") +env:FlushTimers() +local red = { MinimapZoneText:GetTextColor() } +Assert.equal(red[1], 1, "zone override was not applied") +env.nativeZoneColor = Mock.pack(0.2, 0.4, 0.8, 1) +Minimap_Update() +env:FlushTimers() +red = { MinimapZoneText:GetTextColor() } +Assert.equal(red[1], 1, "native zone update displaced an enabled override") + +addon:OnDisable() +local restoredNative = { MinimapZoneText:GetTextColor() } +Assert.equal(restoredNative[1], 0.2, "disable restored a stale pre-zone-change color") +Assert.equal(restoredNative[2], 0.4, "disable lost the latest native zone color") +Assert.equal(GetMinimapShape(), "SQUARE", "disable made shape reporting disagree with the retained mask") +Assert.equal(HybridMinimap.MapCanvas:GetUseMaskTexture(), true, "disable broke hybrid mask usage") +Assert.equal( + HybridMinimap.CircleMask:GetTexture(), + "Interface\\BUTTONS\\WHITE8X8", + "disable made the hybrid mask disagree with the retained square shape" +) +addon:OnEnable() +env:FlushTimers() + +-- A stale timer and combat queue from an earlier generation cannot run after +-- disable/re-enable; the new enable still performs its own refresh. +resetCalls() +addon:RequestRefresh("border") +addon:OnDisable() +addon:OnEnable() +env:FlushTimers() +Assert.equal(calls.ApplyMinimapChanges, 1, "re-enable did not perform one fresh full refresh") +Assert.equal(calls.CreateBorder, 1, "a stale pre-disable timer performed extra border work") + +local cancelledRun = 0 +env:SetCombat(true) +addon:RunSafe(function() + cancelledRun = cancelledRun + 1 +end) +addon:OnDisable() +addon:OnEnable() +env:SetCombat(false) +fireAddonEvent("PLAYER_REGEN_ENABLED") +env:FireEvent("PLAYER_REGEN_ENABLED") +env:FlushTimers() +Assert.equal(cancelledRun, 0, "a stale pre-disable combat action ran after re-enable") + +-- Another shape owner also owns the base mask once it takes over. +local foreignShape = function() + return "HEXAGON" +end +GetMinimapShape = foreignShape +Minimap:SetMaskTexture("foreign-mask") +addon:RequestRefresh("all") +env:FlushTimers() +Assert.equal(GetMinimapShape, foreignShape, "full refresh overwrote a foreign shape owner") +Assert.equal(Minimap.maskTexture, "foreign-mask", "full refresh overwrote a foreign base mask") + +-- Restore the ClassyMap policy for the remaining restoration checks. +GetMinimapShape = addon.shapeOverride +Minimap:SetMaskTexture("Interface\\BUTTONS\\WHITE8X8") + +-- An external color takeover is preserved when the override is turned off. +MinimapZoneText:SetTextColor(0.7, 0.2, 0.9, 1) +addon.db.profile.overrideZoneColor = false +addon:RequestRefresh("fonts") +env:FlushTimers() +local externalColor = { MinimapZoneText:GetTextColor() } +Assert.equal(externalColor[1], 0.7, "disabling the override replaced an external color") + +-- Pending callbacks are invalidated on disable and externally-owned state survives restoration. +local externalParent = env:NewFrame("ExternalOwner") +GameTimeFrame:SetParent(externalParent) +GameTimeFrame:ClearAllPoints() +GameTimeFrame:SetPoint("BOTTOM", externalParent, "BOTTOM", 9, 10) +GameTimeFrame:Hide() +local borderCalls = calls.CreateBorder or 0 +addon:RequestRefresh("border") +addon:OnDisable() +env:FlushTimers() +Assert.equal(calls.CreateBorder or 0, borderCalls, "disabled timer performed pending border work") +Assert.equal(GameTimeFrame:GetParent(), externalParent, "disable overwrote an external parent") +Assert.point(GameTimeFrame, 1, { "BOTTOM", externalParent, "BOTTOM", 9, 10 }, "disable overwrote external anchors") +Assert.equal(GameTimeFrame:IsShown(), false, "disable overwrote external visibility") +Assert.point(Minimap, 1, { "CENTER", MinimapCluster, "CENTER", 3, 4 }, "owned minimap anchor was not restored") +Assert.equal(MinimapCompassTexture:IsShown(), true, "owned compass visibility was not restored") +Assert.equal(MinimapCompassTexture:GetAlpha(), 1, "owned compass alpha was not restored") + +-- Permanent hooks are gated while disabled. +resetCalls() +ExpansionLandingPageMinimapButton:Hide() +ExpansionLandingPageMinimapButton:Show() +Minimap_Update() +MinimapCluster:SetWidth(177) +Assert.equal(ExpansionLandingPageMinimapButton:IsShown(), true, "disabled expansion hook hid native UI") +Assert.equal(#env.timers, 0, "disabled hooks scheduled refresh work") + +-- Re-enable captures current external state as the new restoration baseline. +addon:OnEnable() +env:FlushTimers() +Assert.equal(GameTimeFrame:GetParent(), Minimap, "re-enable did not reacquire layout ownership") +addon:OnDisable() +Assert.equal(GameTimeFrame:GetParent(), externalParent, "second disable did not restore the new baseline") +Assert.point( + GameTimeFrame, + 1, + { "BOTTOM", externalParent, "BOTTOM", 9, 10 }, + "second disable lost the new anchor baseline" +) +Assert.equal(#env.errors, 0, "runtime regressions reported unexpected errors") + +print("runtime regressions passed") diff --git a/tests/settings_regressions.lua b/tests/settings_regressions.lua new file mode 100644 index 0000000..8c74aae --- /dev/null +++ b/tests/settings_regressions.lua @@ -0,0 +1,149 @@ +-- Standalone settings checks: lua tests/settings_regressions.lua + +local Mock = dofile("tests/support/wow_mock.lua") +local Assert = dofile("tests/support/assertions.lua") +local env = Mock.new() + +local registeredOptions +local addToOptionsCalls, openCalls, notifyCalls = 0, 0, 0 +local locale = setmetatable({}, { + __index = function(_, key) + return key + end, +}) +local libraries = { + ["AceLocale-3.0"] = { + GetLocale = function() + return locale + end, + }, + ["AceConfig-3.0"] = { + RegisterOptionsTable = function(_, name, options) + Assert.equal(name, "ClassyMap", "wrong options-table name") + registeredOptions = options + end, + }, + ["AceConfigDialog-3.0"] = { + AddToBlizOptions = function() + addToOptionsCalls = addToOptionsCalls + 1 + return {} + end, + Open = function() + openCalls = openCalls + 1 + end, + }, + ["AceConfigRegistry-3.0"] = { + NotifyChange = function(_, name) + Assert.equal(name, "ClassyMap", "wrong notification target") + notifyCalls = notifyCalls + 1 + end, + }, + ["AceDBOptions-3.0"] = { + GetOptionsTable = function() + return { type = "group", name = "Profiles" } + end, + }, + ["LibSharedMedia-3.0"] = { + HashTable = function() + return { Default = "font.ttf" } + end, + }, +} + +function _G.LibStub(name) + return assert(libraries[name], "unexpected library: " .. tostring(name)) +end + +local callbacks, refreshes = {}, {} +local database = { + profile = { + borderSize = 0 / 0, + borderColor = "invalid", + zoneFontSize = math.huge, + zoneTextColor = "invalid", + clockFontSize = -math.huge, + clockTextColor = "invalid", + }, + RegisterCallback = function(receiver, event, method) + callbacks[event] = { receiver = receiver, method = method } + end, +} +local namespace = { + ClassyMap = { + db = database, + RequestRefresh = function(_, category) + refreshes[#refreshes + 1] = category + end, + }, +} + +dofile("Core/init.lua") +assert(loadfile("Settings.lua"))("ClassyMap", namespace) +env:FireEvent("ADDON_LOADED", "ClassyMap") + +Assert.equal(addToOptionsCalls, 1, "settings were not registered exactly once") +Assert.truthy(callbacks.OnProfileChanged, "profile-change callback was not registered") +Assert.truthy(callbacks.OnProfileCopied, "profile-copy callback was not registered") +Assert.truthy(callbacks.OnProfileReset, "profile-reset callback was not registered") + +local options = registeredOptions() +Assert.truthy(options.args.profiles, "profile options were not exposed") +Assert.equal(options.args.profiles.order, 100, "profile options order is incorrect") +Assert.equal(options.args.borderSize.get(), 1, "invalid border size was not normalized") +Assert.equal(options.args.zoneFontSize.get(), 11, "invalid zone font size was not normalized") +Assert.equal(options.args.clockFontSize.get(), 11, "invalid clock font size was not normalized") +Assert.equal(options.args.zoneFontSize.max, 24, "zone font range does not match core validation") +Assert.equal(options.args.clockFontSize.max, 24, "clock font range does not match core validation") +local r, g, b, a = options.args.borderColor.get() +assert(r == 1 and g == 1 and b == 1 and a == 1, "invalid color was not normalized") + +local expectedCategories = { + borderSize = "border", + borderColor = "border", + font = "fonts", + zoneFontSize = "fonts", + overrideZoneColor = "fonts", + zoneTextColor = "fonts", + clockFontSize = "fonts", + clockTextColor = "fonts", + hideTracking = "visibility", + hideZoneText = "visibility", + hideClock = "visibility", + hideZoomButtons = "visibility", + hideExpansionButton = "visibility", + hideCalendar = "visibility", + hideAddonBtn = "visibility", + hideInstance = "visibility", +} +for optionName, category in pairs(expectedCategories) do + local option = options.args[optionName] + local before = #refreshes + if option.type == "color" then + option.set(nil, 0.2, 0.3, 0.4, 0.5) + elseif option.type == "toggle" then + option.set(nil, true) + elseif option.type == "select" then + option.set(nil, "Default") + else + option.set(nil, option.min) + end + Assert.equal(#refreshes, before + 1, optionName .. " did not request one refresh") + Assert.equal(refreshes[#refreshes], category, optionName .. " requested the wrong category") +end + +namespace.Settings:Initialize() +Assert.equal(addToOptionsCalls, 1, "settings initialization is not idempotent") + +namespace.Settings:OnProfileUpdated() +Assert.equal(refreshes[#refreshes], "all", "profile refresh did not request all work") +Assert.equal(notifyCalls, 1, "profile refresh did not notify AceConfig") + +namespace.Settings:OpenOptions() +Assert.equal(openCalls, 1, "settings dialog did not open") + +-- Strict mocks fail at the access site instead of accepting misspelled APIs. +Assert.raises("attempt to call", function() + return Minimap:DefinitelyNotAFrameMethod() +end) + +print("settings regressions passed") diff --git a/tests/support/assertions.lua b/tests/support/assertions.lua new file mode 100644 index 0000000..cd0eff7 --- /dev/null +++ b/tests/support/assertions.lua @@ -0,0 +1,44 @@ +local Assertions = {} + +function Assertions.equal(actual, expected, message) + if actual ~= expected then + error(("%s (expected %s, got %s)"):format(message or "values differ", tostring(expected), tostring(actual)), 2) + end +end + +function Assertions.truthy(value, message) + if not value then + error(message or "expected a truthy value", 2) + end + return value +end + +function Assertions.raises(pattern, callback) + local ok, err = pcall(callback) + if ok then + error("expected callback to raise", 2) + end + if pattern and not tostring(err):match(pattern) then + error(("error %q did not match %q"):format(tostring(err), pattern), 2) + end + return err +end + +function Assertions.point(frame, index, expected, message) + local values = { frame:GetPoint(index) } + for i = 1, #expected do + if values[i] ~= expected[i] then + error( + ("%s at value %d (expected %s, got %s)"):format( + message or "point differs", + i, + tostring(expected[i]), + tostring(values[i]) + ), + 2 + ) + end + end +end + +return Assertions diff --git a/tests/support/wow_mock.lua b/tests/support/wow_mock.lua new file mode 100644 index 0000000..1dac4de --- /dev/null +++ b/tests/support/wow_mock.lua @@ -0,0 +1,662 @@ +local Mock = {} + +local unpackValues = unpack + +local function pack(...) + return { n = select("#", ...), ... } +end + +local function copyPacked(values) + local result = { n = values.n } + for i = 1, values.n do + result[i] = values[i] + end + return result +end + +local function describe(frame) + return frame.name or frame.objectType or "anonymous frame" +end + +local FrameMethods = {} + +local function record(self, method, ...) + self.calls[method] = (self.calls[method] or 0) + 1 + self.lastCall[method] = pack(...) +end + +local function mutate(self, method, ...) + if self.protected and self.env.combat then + error(("protected mutation %s:%s during combat"):format(describe(self), method), 3) + end + record(self, method, ...) +end + +function FrameMethods:GetObjectType() + return self.objectType +end + +function FrameMethods:IsObjectType(kind) + return self.objectType == kind or (kind == "Region" and self.objectType == "Texture") +end + +function FrameMethods:RegisterEvent(event) + record(self, "RegisterEvent", event) + self.events[event] = true + return true +end + +function FrameMethods:UnregisterEvent(event) + record(self, "UnregisterEvent", event) + self.events[event] = nil +end + +function FrameMethods:UnregisterAllEvents() + record(self, "UnregisterAllEvents") + self.events = {} +end + +function FrameMethods:IsEventRegistered(event) + return not not self.events[event] +end + +function FrameMethods:SetScript(script, callback) + record(self, "SetScript", script, callback) + self.scripts[script] = callback +end + +function FrameMethods:GetScript(script) + return self.scripts[script] +end + +function FrameMethods:HookScript(script, callback) + local previous = self.scripts[script] + self.scripts[script] = function(...) + if previous then + previous(...) + end + callback(...) + end +end + +function FrameMethods:SetParent(parent) + mutate(self, "SetParent", parent) + self.parent = parent +end + +function FrameMethods:GetParent() + return self.parent +end + +function FrameMethods:SetWidth(width) + mutate(self, "SetWidth", width) + self.width = width +end + +function FrameMethods:SetHeight(height) + mutate(self, "SetHeight", height) + self.height = height +end + +function FrameMethods:SetSize(width, height) + mutate(self, "SetSize", width, height) + self.width, self.height = width, height +end + +function FrameMethods:GetWidth() + return self.width +end + +function FrameMethods:GetHeight() + return self.height +end + +function FrameMethods:ClearAllPoints() + mutate(self, "ClearAllPoints") + self.points = {} +end + +function FrameMethods:SetPoint(...) + mutate(self, "SetPoint", ...) + self.points[#self.points + 1] = pack(...) +end + +function FrameMethods:SetAllPoints(relative) + mutate(self, "SetAllPoints", relative) + self.points = { pack("ALL", relative or self.parent) } +end + +function FrameMethods:GetNumPoints() + return #self.points +end + +function FrameMethods:GetPoint(index) + local point = self.points[index or 1] + if point then + return unpackValues(point, 1, point.n) + end +end + +function FrameMethods:Show() + mutate(self, "Show") + self.shown = true + local script = self.scripts.OnShow + if script then + script(self) + end +end + +function FrameMethods:Hide() + mutate(self, "Hide") + self.shown = false + local script = self.scripts.OnHide + if script then + script(self) + end +end + +function FrameMethods:IsShown() + return self.shown +end + +function FrameMethods:IsVisible() + return self.shown +end + +function FrameMethods:SetAlpha(alpha) + mutate(self, "SetAlpha", alpha) + self.alpha = alpha +end + +function FrameMethods:GetAlpha() + return self.alpha +end + +function FrameMethods:SetScale(scale) + mutate(self, "SetScale", scale) + self.scale = scale +end + +function FrameMethods:GetScale() + return self.scale +end + +function FrameMethods:SetFrameStrata(strata) + mutate(self, "SetFrameStrata", strata) + self.frameStrata = strata +end + +function FrameMethods:GetFrameStrata() + return self.frameStrata +end + +function FrameMethods:SetFrameLevel(level) + mutate(self, "SetFrameLevel", level) + self.frameLevel = level +end + +function FrameMethods:GetFrameLevel() + return self.frameLevel +end + +function FrameMethods:SetClampedToScreen(value) + mutate(self, "SetClampedToScreen", value) + self.clampedToScreen = not not value +end + +function FrameMethods:IsClampedToScreen() + return self.clampedToScreen +end + +function FrameMethods:SetClampRectInsets(...) + mutate(self, "SetClampRectInsets", ...) + self.clampRectInsets = pack(...) +end + +function FrameMethods:GetClampRectInsets() + return unpackValues(self.clampRectInsets, 1, self.clampRectInsets.n) +end + +function FrameMethods:SetFont(...) + mutate(self, "SetFont", ...) + self.font = pack(...) + return true +end + +function FrameMethods:GetFont() + return unpackValues(self.font, 1, self.font.n) +end + +function FrameMethods:SetTextColor(...) + mutate(self, "SetTextColor", ...) + self.textColor = pack(...) +end + +function FrameMethods:GetTextColor() + return unpackValues(self.textColor, 1, self.textColor.n) +end + +function FrameMethods:SetVertexColor(...) + mutate(self, "SetVertexColor", ...) + self.vertexColor = pack(...) +end + +function FrameMethods:GetVertexColor() + return unpackValues(self.vertexColor, 1, self.vertexColor.n) +end + +function FrameMethods:SetTexture(texture) + mutate(self, "SetTexture", texture) + self.texture = texture +end + +function FrameMethods:GetTexture() + return self.texture +end + +function FrameMethods:SetMaskTexture(texture) + mutate(self, "SetMaskTexture", texture) + self.maskTexture = texture +end + +function FrameMethods:SetAtlas(atlas, useAtlasSize) + mutate(self, "SetAtlas", atlas, useAtlasSize) + self.atlas, self.useAtlasSize = atlas, useAtlasSize +end + +function FrameMethods:GetAtlas() + return self.atlas +end + +function FrameMethods:SetTexCoord(...) + mutate(self, "SetTexCoord", ...) + self.texCoord = pack(...) +end + +function FrameMethods:GetTexCoord() + return unpackValues(self.texCoord, 1, self.texCoord.n) +end + +function FrameMethods:SetHighlightTexture(texture) + mutate(self, "SetHighlightTexture", texture) + self.highlightTexture = texture +end + +function FrameMethods:GetHighlightTexture() + return self.highlightTexture +end + +function FrameMethods:SetJustifyH(value) + mutate(self, "SetJustifyH", value) + self.justifyH = value +end + +function FrameMethods:GetJustifyH() + return self.justifyH +end + +function FrameMethods:SetJustifyV(value) + mutate(self, "SetJustifyV", value) + self.justifyV = value +end + +function FrameMethods:GetJustifyV() + return self.justifyV +end + +function FrameMethods:SetWordWrap(value) + mutate(self, "SetWordWrap", value) + self.wordWrap = not not value +end + +function FrameMethods:CanWordWrap() + return self.wordWrap +end + +function FrameMethods:SetUseMaskTexture(value) + mutate(self, "SetUseMaskTexture", value) + self.useMaskTexture = not not value +end + +function FrameMethods:GetUseMaskTexture() + return self.useMaskTexture +end + +for _, method in ipairs({ + "SetArchBlobRingScalar", + "SetArchBlobRingAlpha", + "SetQuestBlobRingScalar", + "SetQuestBlobRingAlpha", + "SetTaskBlobRingScalar", + "SetTaskBlobRingAlpha", +}) do + FrameMethods[method] = function(self, value) + mutate(self, method, value) + self.values[method] = value + end +end + +function FrameMethods:CreateTexture(name, layer) + record(self, "CreateTexture", name, layer) + return self.env:NewFrame(name, { + objectType = "Texture", + parent = self, + protected = false, + layer = layer, + }) +end + +function FrameMethods:GetRegions() + return unpackValues(self.regions, 1, self.regions.n) +end + +function FrameMethods:RegisterAddon(definition) + record(self, "RegisterAddon", definition) + self.registeredAddon = definition +end + +local frameMetatable = { + __index = function(self, key) + local method = FrameMethods[key] + if method then + return method + end + return nil + end, +} + +function Mock:NewFrame(name, options) + options = options or {} + local frame = setmetatable({ + n = false, + env = self, + name = name, + objectType = options.objectType or "Frame", + parent = options.parent, + protected = options.protected or false, + width = options.width or 140, + height = options.height or 140, + shown = options.shown ~= false, + alpha = options.alpha or 1, + scale = options.scale or 1, + frameStrata = options.frameStrata or "MEDIUM", + frameLevel = options.frameLevel or 1, + clampedToScreen = options.clampedToScreen or false, + clampRectInsets = options.clampRectInsets or pack(0, 0, 0, 0), + font = options.font or pack("native.ttf", 12, ""), + textColor = options.textColor or pack(0.1, 1, 0.1, 1), + vertexColor = options.vertexColor or pack(1, 1, 1, 1), + texture = options.texture, + maskTexture = options.maskTexture or "native-mask", + texCoord = options.texCoord or pack(0, 1, 0, 1), + justifyH = options.justifyH or "LEFT", + justifyV = options.justifyV or "TOP", + wordWrap = options.wordWrap ~= false, + useMaskTexture = options.useMaskTexture ~= false, + points = options.points or {}, + regions = options.regions or { n = 0 }, + events = {}, + scripts = {}, + calls = {}, + lastCall = {}, + values = {}, + }, frameMetatable) + if frame.objectType == "Texture" then + frame.SetFont = false + frame.GetFont = false + frame.SetTextColor = false + frame.GetTextColor = false + frame.SetFrameStrata = false + frame.GetFrameStrata = false + frame.SetFrameLevel = false + frame.GetFrameLevel = false + frame.RegisterEvent = false + frame.UnregisterEvent = false + frame.UnregisterAllEvents = false + frame.CreateTexture = false + elseif frame.objectType == "FontString" then + frame.SetFrameStrata = false + frame.GetFrameStrata = false + frame.SetFrameLevel = false + frame.GetFrameLevel = false + frame.RegisterEvent = false + frame.UnregisterEvent = false + frame.UnregisterAllEvents = false + frame.CreateTexture = false + frame.SetParent = false + end + self.frames[#self.frames + 1] = frame + if name then + _G[name] = frame + end + return frame +end + +function Mock:SetCombat(value) + self.combat = not not value +end + +function Mock:SetLoggedIn(value) + self.loggedIn = not not value +end + +function Mock:FlushTimers(maxRounds) + maxRounds = maxRounds or 50 + local rounds = 0 + while #self.timers > 0 do + rounds = rounds + 1 + assert(rounds <= maxRounds, "timer queue did not settle") + local pending = self.timers + self.timers = {} + for _, timer in ipairs(pending) do + if not timer.cancelled then + timer.callback() + end + end + end + return rounds +end + +function Mock:FireEvent(event, ...) + local frames = {} + for _, frame in ipairs(self.frames) do + if frame.events[event] and frame.scripts.OnEvent then + frames[#frames + 1] = frame + end + end + for _, frame in ipairs(frames) do + if frame.events[event] and frame.scripts.OnEvent then + frame.scripts.OnEvent(frame, event, ...) + end + end +end + +function Mock:ResetCounts() + for _, frame in ipairs(self.frames) do + frame.calls = {} + frame.lastCall = {} + end +end + +function Mock:Install(options) + options = options or {} + self.frames = {} + self.timers = {} + self.errors = {} + self.combat = options.combat or false + self.loggedIn = options.loggedIn ~= false + self.profileClock = 0 + self.nativeZoneColor = pack(0.1, 1, 0.1, 1) + + _G.strmatch = string.match + _G.strsub = string.sub + _G.strlower = string.lower + _G.strtrim = function(value) + return (value:gsub("^%s+", ""):gsub("%s+$", "")) + end + _G.format = string.format + _G.tinsert = table.insert + _G.tremove = table.remove + _G.wipe = function(tbl) + for key in pairs(tbl) do + tbl[key] = nil + end + return tbl + end + _G.securecallfunction = function(callback, ...) + return callback(...) + end + _G.geterrorhandler = function() + return function(err) + self.errors[#self.errors + 1] = tostring(err) + end + end + _G.debugprofilestop = function() + self.profileClock = self.profileClock + 1 + return self.profileClock + end + _G.InCombatLockdown = function() + return self.combat + end + _G.IsLoggedIn = function() + return self.loggedIn + end + _G.GetRealmName = function() + return "Test Realm" + end + _G.UnitName = function() + return "Tester" + end + _G.UnitClass = function() + return "Mage", "MAGE" + end + _G.UnitRace = function() + return "Human", "Human" + end + _G.UnitFactionGroup = function() + return "Alliance" + end + _G.GetLocale = function() + return "enUS" + end + _G.GetCurrentRegion = function() + return 1 + end + _G.GetCurrentRegionName = function() + return "US" + end + _G.CreateFrame = function(_, name, parent) + return self:NewFrame(name, { parent = parent }) + end + _G.C_Timer = { + After = function(_, callback) + local timer = { callback = callback, cancelled = false } + self.timers[#self.timers + 1] = timer + return timer + end, + } + _G.hooksecurefunc = function(target, method, callback) + if type(target) == "string" then + callback, method, target = method, target, _G + end + local original = assert(target[method], "cannot hook missing method " .. tostring(method)) + target[method] = function(...) + local results = pack(original(...)) + callback(...) + return unpackValues(results, 1, results.n) + end + end + + local nativeParent = self:NewFrame("NativeMinimapParent") + _G.MinimapCluster = self:NewFrame("MinimapCluster", { + parent = nativeParent, + protected = true, + points = { pack("TOPRIGHT", nativeParent, "TOPRIGHT", -20, -20) }, + }) + _G.Minimap = self:NewFrame("Minimap", { + parent = MinimapCluster, + protected = true, + points = { pack("CENTER", MinimapCluster, "CENTER", 3, 4) }, + }) + Minimap.ZoomIn = self:NewFrame("MinimapZoomIn", { parent = Minimap, protected = true }) + Minimap.ZoomOut = self:NewFrame("MinimapZoomOut", { parent = Minimap, protected = true }) + MinimapCluster.ZoneTextButton = self:NewFrame("MinimapClusterZoneTextButton", { + parent = MinimapCluster, + protected = true, + points = { pack("TOP", MinimapCluster, "TOP", 5, -6) }, + }) + MinimapCluster.Tracking = self:NewFrame("MinimapClusterTracking", { + parent = MinimapCluster, + protected = true, + }) + MinimapCluster.InstanceDifficulty = self:NewFrame("MinimapClusterInstanceDifficulty", { + parent = MinimapCluster, + protected = true, + }) + MinimapCluster.BorderTop = self:NewFrame("MinimapClusterBorderTop", { + parent = MinimapCluster, + protected = true, + }) + _G.MinimapZoneText = self:NewFrame("MinimapZoneText", { + objectType = "FontString", + parent = MinimapCluster.ZoneTextButton, + protected = true, + }) + _G.MinimapCompassTexture = self:NewFrame("MinimapCompassTexture", { + objectType = "Texture", + parent = Minimap, + protected = true, + }) + _G.GameTimeFrame = self:NewFrame("GameTimeFrame", { parent = MinimapCluster, protected = true }) + _G.AddonCompartmentFrame = self:NewFrame("AddonCompartmentFrame", { + parent = MinimapCluster, + protected = true, + }) + _G.ExpansionLandingPageMinimapButton = self:NewFrame("ExpansionLandingPageMinimapButton", { + parent = MinimapCluster, + protected = true, + }) + _G.TimeManagerClockButton = nil + _G.TimeManagerClockTicker = nil + _G.HybridMinimap = nil + _G.ExpansionLandingPage = nil + _G.C_Texture = { + GetAtlasInfo = function() + return true + end, + } + _G.GameTooltip = { + SetOwner = function() end, + AddLine = function() end, + Show = function() end, + Hide = function() end, + } + _G.ToggleEncounterJournal = function() end + _G.GetMinimapShape = function() + return "ROUND" + end + _G.Minimap_Update = function() + MinimapZoneText:SetTextColor(unpackValues(self.nativeZoneColor, 1, self.nativeZoneColor.n)) + end + + _G.DEFAULT_CHAT_FRAME = { + messages = {}, + AddMessage = function(frame, message) + frame.messages[#frame.messages + 1] = message + end, + } + _G.SlashCmdList = {} + _G.hash_SlashCmdList = {} + + return self +end + +function Mock.new(options) + local instance = setmetatable({}, { __index = Mock }) + return instance:Install(options) +end + +Mock.pack = pack +Mock.copyPacked = copyPacked + +return Mock