diff --git a/.gitattributes b/.gitattributes index 7fccbdb..6365342 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,6 +1,11 @@ # Store text files with LF line endings; check them out as the platform prefers. * text=auto +# Artifact source text is identical on Windows and POSIX checkouts. +BuffRadar/** text=auto eol=lf +editions/forever/** text=auto eol=lf # Media files are binary: never touch their bytes. *.png binary +*.jpg binary +*.jpeg binary *.ogg binary *.zip binary diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a47e8ce..25b17d2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,9 +13,42 @@ jobs: python-version: "3.12" - run: | python -m pip install --only-binary=:all: lupa==2.8 - - name: Gate (static checks + smoke on six fake-client setups) + - name: Gate (static checks and Lua 5.1 fake-client suites) run: sh tools/gate.sh - name: Package (dry run) run: sh tools/package.sh - name: Verify packaged Forever load order and bindings run: python -I tools/checkpackage.py dist/BuffRadar-*-Forever.zip . + - name: Save POSIX digest for comparison + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: forever-posix-digest + path: dist/SHA256SUMS.txt + if-no-files-found: error + windows-package: + needs: gate + runs-on: windows-latest + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-python@v6 + with: + python-version: "3.12" + - name: Install Lua 5.1 test dependency + run: | + python -m pip install --only-binary=:all: lupa==2.8 + - run: ./build.ps1 + - name: Verify packaged Forever load order and bindings + shell: pwsh + run: | + $zip = Get-ChildItem dist/BuffRadar-*-Forever.zip + python -I tools/checkpackage.py $zip.FullName . + - uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0 # v5.0.0 + with: + name: forever-posix-digest + path: posix + - name: Compare the Windows and POSIX package digests + shell: pwsh + run: | + if ((Get-Content dist/SHA256SUMS.txt -Raw) -cne (Get-Content posix/SHA256SUMS.txt -Raw)) { + throw 'Package bytes differ across platforms.' + } diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6980409..95ad806 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -15,11 +15,8 @@ jobs: - run: | python -m pip install --only-binary=:all: lupa==2.8 - run: sh tools/gate.sh - - name: Tag must match the TOC version - run: | - VER="$(sed -n 's/^## Version:[[:space:]]*//p' editions/forever/BuffRadar.toc | head -1 | tr -d '\r')" - [ "v$VER" = "${GITHUB_REF_NAME}" ] || { echo "tag ${GITHUB_REF_NAME} != TOC version v$VER"; exit 1; } - - run: sh tools/package.sh + - name: Verify tag and build package + run: sh tools/package.sh --tag "$GITHUB_REF_NAME" - name: Verify packaged Forever load order and bindings run: python -I tools/checkpackage.py dist/BuffRadar-*-Forever.zip . - name: Collect release notes @@ -52,7 +49,7 @@ jobs: export GH_REPO="$GITHUB_REPOSITORY" (cd dist && sha256sum -c SHA256SUMS.txt) if gh release view "${GITHUB_REF_NAME}" >/dev/null 2>&1; then - gh release upload "${GITHUB_REF_NAME}" dist/BuffRadar-*-Forever.zip dist/SHA256SUMS.txt --clobber + echo "Release already exists; verify the hosted bytes without replacing assets." else gh release create "${GITHUB_REF_NAME}" dist/BuffRadar-*-Forever.zip dist/SHA256SUMS.txt \ --title "BuffRadar ${GITHUB_REF_NAME#v}" --notes-file dist/notes.md --verify-tag diff --git a/.gitignore b/.gitignore index 10780b0..f85e311 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ # Release zips made by build.ps1 (attach them to a GitHub release instead) dist dist/ + +# Local handoff artifacts for field testing (do not commit ZIPs). +/release-candidates/ diff --git a/AGENTS.md b/AGENTS.md index 4f5e30e..c878ee6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,19 +10,24 @@ key) to buff them. Frozen foundation: both editions share the Lua source under `BuffRadar/`. Their `.toc` files declare load order; do not use `require` or add globals for -module communication. `Data.lua` initializes the addon namespace, `SavedVariables.lua` +module communication. `Forever.lua` identifies the shipping edition, `Data.lua` checks the client +and initializes the addon namespace, and `SavedVariables.lua` owns the schema and publishes the live DB, `BuffRadar.lua` owns scanning and cast decisions, and `Window.lua` and `Minimap.lua` own their frames and caches. Keep implementation state local and share entry points through the addon table. `BuffRadarAPI` is a versioned, read-only external interface, not a module bridge. Every feature is reachable through `/br` as well as through its settings control -where it has one. SavedVariables are versioned (`dbVersion`, currently 22) with +where it has one. SavedVariables are versioned (`dbVersion`, currently 23) with migration smoke fixtures; keep those fixtures in sync with format changes. +Never overwrite a newer schema with an older addon. Bound saved collections +at their writers as well as at load, and preserve over-limit user profiles +and permanent ignores for explicit recovery. Build: none (interpreted Lua 5.1). Full gate (all of it, every time, output read): `sh tools/gate.sh` runs the Lua 5.1 compiler, advisory limit estimates, locale and pattern checks, seven -fake-client smoke setups using the two TOCs, and two-client coordination. +fake-client smoke setups using the two TOCs, two-client coordination, and +packaging regressions. `sh tools/install-hooks.sh` installs the pre-push gate. Also run real luacheck 1.2.0 on all addon Lua files (0 warnings / 0 errors); `tools/check.ps1` runs the checks on Windows. Add trial steps for every feature in the setups it applies to. @@ -38,16 +43,20 @@ called done; in-game behaviour is labelled **Unverified** until SEAN's field tes proves it (evidence labels: Verified / Partially Verified / Unverified). Special rules for this project: -- Manual Forever release validation: run docs/FOREVER_RELEASE_CHECKLIST.md on the exact candidate build before marking in-game behavior verified. +- Manual Forever release validation: use `docs/FOREVER_RELEASE_CHECKLIST.md` + and record the exact candidate ZIP digest, Windows parity result and game + build. An offline pass is not a Forever field pass. - Secure action buttons: `HookScript` / `WrapScript` only — **never** `SetScript("OnClick")` on a secure button. -- **CI runs the gate** (`.github/workflows/ci.yml`, added in 1.13.0): static checks + trial run + a packaging dry run on every push/PR. Real luacheck 1.2.0 stays a local Windows step (`tools/check.ps1`) — SEAN skipped it in CI on 2026-11-08. `release.yml` publishes on a `v*` tag that must equal the Forever .toc version. -- Publishing: one `push_files` snapshot via the GitHub connector (the Contents - API's per-call size cap cannot carry `BuffRadar.lua`), then blob-verify every - published file against the local tree. **Forever-only from 1.8.0** (SEAN - dropped Retail support 2026-10-25; Retail docs stay frozen at 1.7.0): - releases attach the Forever zip plus `SHA256SUMS.txt`, and are not shipped - until the assets are re-downloaded and hash-verified. +- **CI runs the gate** (`.github/workflows/ci.yml`) on main pushes and PRs. + The Windows and POSIX wrappers call `tools/package.py`; CI compares their + digests. Real luacheck 1.2.0 remains a separate local check (included in + `tools/check.ps1` on Windows), not a CI dependency. +- **Publishing:** keep the Retail docs frozen at 1.7.0; only the Forever ZIP + ships. Verify the release source against the tested tree. `release.yml` runs + on a `v*` tag matching the Forever TOC, publishes the ZIP and `SHA256SUMS.txt`, + and checks the downloaded assets against the packaged bytes. Do not treat a + successful upload as a verified release. - The German locale stays complete — `tools/localecheck.py` enforces it; new user-facing list tags need an `L[...]` entry and a deDE translation. - Licence is GPLv3 (upstream author Malikor). The SEAN-annex MIT default does diff --git a/BuffRadar/BuffRadar.lua b/BuffRadar/BuffRadar.lua index 1105d9f..271f004 100644 --- a/BuffRadar/BuffRadar.lua +++ b/BuffRadar/BuffRadar.lua @@ -50,10 +50,6 @@ local SOON_DELAY = 0.1 -- event-driven refreshes are coalesced into one per 0.1 -- Key Bindings menu labels (Bindings.xml defines the binding itself) BINDING_HEADER_BUFFRADAR = "BuffRadar" BINDING_CATEGORY_BUFFRADAR = "BuffRadar" -_G["BINDING_NAME_CLICK BuffRadarNextButton:LeftButton"] = "Cast next buff" -_G["BINDING_NAME_CLICK BuffRadarGroupButton:LeftButton"] = "Cast next group buff" -BINDING_NAME_BUFFRADAR_TOGGLE = "Show / hide window" -BINDING_NAME_BUFFRADAR_MUTE = "Mute / unmute sound" local NEXT_BINDING = "CLICK BuffRadarNextButton:LeftButton" local MACRO_NAME = "BuffRadar" @@ -95,6 +91,96 @@ end -- Strings with %d / %s are string.format patterns: keep the placeholders. -- Any key a translation leaves out falls back to English. local L = { + ["Group chat send requested; delivery is not confirmed."] = "Group chat send requested; delivery is not confirmed.", + ["the party"] = "the party", + ["the raid"] = "the raid", + ["Apply and share sends changed assignments and blessings to %s."] = "Apply and share sends changed assignments and blessings to %s.", + ["Compared with your current settings (not applied):"] = "Compared with your current settings (not applied):", + ["Group spell range could not be confirmed."] = "Group spell range could not be confirmed.", + ["No eligible group target."] = "No eligible group target.", + ["Can't open that during combat."] = "Can't open that during combat.", + ["Delete"] = "Delete", + ["Load"] = "Load", + ["Save"] = "Save", + ["Save window, alert and buff preferences to load here or with /br profile."] = "Save window, alert and buff preferences to load here or with /br profile.", + ["Settings profiles"] = "Settings profiles", + ["Share BR2"] = "Share BR2", + ["Import"] = "Import", + ["Open the BuffRadar section of the game's key bindings."] = "Open the BuffRadar section of the game's key bindings.", + ["Create macro"] = "Create macro", + ["Set keybind"] = "Set keybind", + ["Keybinds"] = "Keybinds", + ["Open Game Menu > Options > Keybindings and look for the BuffRadar section."] = "Open Game Menu > Options > Keybindings and look for the BuffRadar section.", + ["Can't open key bindings during combat."] = "Can't open key bindings during combat.", + ["not bound"] = "not bound", + ["Mute / unmute sound"] = "Mute / unmute sound", + ["Show / hide window"] = "Show / hide window", + ["Cast next group buff"] = "Cast next group buff", + ["Cast next buff"] = "Cast next buff", + ["Remember panel positions: %s"] = "Remember panel positions: %s", + ["Use /br positions on|off|reset."] = "Use /br positions on|off|reset.", + ["Reset panel positions"] = "Reset panel positions", + ["Remember Settings and Ready Check positions"] = "Remember Settings and Ready Check positions", + ["Profile storage is full. Delete a profile first."] = "Profile storage is full. Delete a profile first.", + ["Ignore list is full. Remove entries first."] = "Ignore list is full. Remove entries first.", + ["Profiles: %d/%d · Ignores: %d/%d"] = "Profiles: %d/%d · Ignores: %d/%d", + ["No matching entry in an oversized save."] = "No matching entry in an oversized save.", + ["Removed from the preserved save. Reload to try normal saving again."] = "Removed from the preserved save. Reload to try normal saving again.", + ["Use /br storage delete profile or /br storage delete ignore , then reload."] = "Use /br storage delete profile or /br storage delete ignore , then reload.", + ["Too many profiles or ignores. The original save was preserved; changes are temporary."] = "Too many profiles or ignores. The original save was preserved; changes are temporary.", + ["Local only — not sent: %s"] = "Local only — not sent: %s", + ["Game accepted the group chat send; delivery is not confirmed."] = "Game accepted the group chat send; delivery is not confirmed.", + ["The game did not accept the send."] = "The game did not accept the send.", + ["The message exceeds the chat limit."] = "The message exceeds the chat limit.", + ["Group chat is unavailable."] = "Group chat is unavailable.", + ["No group channel."] = "No group channel.", + ["Group-cast pair limit reached. Remove a pair first."] = "Group-cast pair limit reached. Remove a pair first.", + ["Invalid group-cast pair; nothing changed."] = "Invalid group-cast pair; nothing changed.", + ["Applicability unknown"] = "Applicability unknown", + ["Not applicable"] = "Not applicable", + ["%d unknown"] = "%d unknown", + ["Some world buff information is unavailable."] = "Some world buff information is unavailable.", + ["Use a named BR2 profile to share newer preferences."] = "Use a named BR2 profile to share newer preferences.", + ["Group sharing is unavailable for this review."] = "Group sharing is unavailable for this review.", + ["Auto-profile mappings stay local, even when sharing."] = "Auto-profile mappings stay local, even when sharing.", + ["Group plan copy (select all, copy)"] = "Group plan copy (select all, copy)", + ["Paste a group plan, then review."] = "Paste a group plan, then review.", + ["Paste a shared profile, then review."] = "Paste a shared profile, then review.", + ["Legacy BR1 settings copy (select all, copy)"] = "Legacy BR1 settings copy (select all, copy)", + ["Paste a legacy BR1 settings copy, then review."] = "Paste a legacy BR1 settings copy, then review.", + ["Store as %s without loading its settings."] = "Store as %s without loading its settings.", + ["Auto-profile mappings using this name: %s"] = "Auto-profile mappings using this name: %s", + ["Existing profile: %s. Enter a different name to keep it."] = "Existing profile: %s. Enter a different name to keep it.", + ["The current values changed. Review again before applying."] = "The current values changed. Review again before applying.", + ["No settings or plan values would change."] = "No settings or plan values would change.", + ["Review before applying"] = "Review before applying", + ["Import canceled."] = "Import canceled.", + ["Save profile"] = "Save profile", + ["Replace profile"] = "Replace profile", + ["Apply and share"] = "Apply and share", + ["Apply locally"] = "Apply locally", + ["Review import"] = "Review import", + ["Edit paste"] = "Edit paste", + ["These settings are too large to save as a profile."] = "These settings are too large to save as a profile.", + ["Profile stored: %s (not loaded)."] = "Profile stored: %s (not loaded).", + ["That profile already exists or changed. Review it, rename, or explicitly replace it."] = "That profile already exists or changed. Review it, rename, or explicitly replace it.", + ["Profile names use letters, numbers, - and _ (max 40)."] = "Profile names use letters, numbers, - and _ (max 40).", + ["The profile's settings string is damaged."] = "The profile's settings string is damaged.", + ["That doesn't look like a shared BuffRadar profile."] = "That doesn't look like a shared BuffRadar profile.", + ["That shared profile is too large."] = "That shared profile is too large.", + ["Game accepted %d of %d sends; delivery is not confirmed."] = "Game accepted %d of %d sends; delivery is not confirmed.", + ["Plan applied locally: %d assignments, %d blessings, %d auto profiles."] = "Plan applied locally: %d assignments, %d blessings, %d auto profiles.", + ["Group or sharing permission changed. Review the plan again."] = "Group or sharing permission changed. Review the plan again.", + ["Missing profile for %s: %s"] = "Missing profile for %s: %s", + ["Settings applied locally."] = "Settings applied locally.", + ["Paste a complete, valid BuffRadar plan export."] = "Paste a complete, valid BuffRadar plan export.", + ["Paste a complete, valid BuffRadar settings export."] = "Paste a complete, valid BuffRadar settings export.", + ["That import exceeds 16 KiB."] = "That import exceeds 16 KiB.", + ["Nothing to import."] = "Nothing to import.", + ["Can't move the buff window during combat."] = "Can't move the buff window during combat.", + ["Buff scan interrupted. Waiting for a fresh scan."] = "Buff scan interrupted. Waiting for a fresh scan.", + ["A newer BuffRadar save was preserved. Changes are for this session only."] = "A newer BuffRadar save was preserved. Changes are for this session only.", + ["BuffRadar requires the Forever package on Interface 16001. Casting is disabled."] = "BuffRadar requires the Forever package on Interface 16001. Casting is disabled.", ["Find"] = "Find", ["Find in this tab (Esc to close)"] = "Find in this tab (Esc to close)", ["Matches: %d"] = "Matches: %d", @@ -682,6 +768,10 @@ do for k, v in pairs(pack) do if type(v) == "string" then L[k] = v end end end end +_G["BINDING_NAME_CLICK BuffRadarNextButton:LeftButton"] = L["Cast next buff"] +_G["BINDING_NAME_CLICK BuffRadarGroupButton:LeftButton"] = L["Cast next group buff"] +BINDING_NAME_BUFFRADAR_TOGGLE = L["Show / hide window"] +BINDING_NAME_BUFFRADAR_MUTE = L["Mute / unmute sound"] --------------------------------------------------------------------------- -- API helpers (tolerant of old and new client APIs) @@ -894,15 +984,21 @@ do return false, nil, true end + function X.GroupSpellInRange(spell, unit, isSelf) + if isSelf then return true end + local inRange, _, unknown = InRange(spell, unit, true) + return inRange and not unknown + end + function X.FilterInRange(unit, source, out, isSelf, diagnostic) wipe(out) if isSelf == nil then isSelf = X.IsSelf(unit) end if isSelf == nil then return 0 end local n, approximate, unknown, rankLimited = 0, false, false, false - local level = CLASSIC_FEATURES and db.castMethod == "target" and X.ReadUnitNumber(UnitLevel, unit) + local level = CLASSIC_FEATURES and X.ReadUnitNumber(UnitLevel, unit) for i = 1, #source do local inRange, estimated, unreadable - if level and X.DefaultRank(source[i], level) == false then + if X.RankTooLow(source[i], level, db.castMethod) then rankLimited = true elseif isSelf then inRange = true @@ -1048,33 +1144,42 @@ do return sourceOK and SourceOwner(source) or "unknown" end - function X.ReadBuff(unit, i, withOwner) - -- done, name, expirationTime, complete (only when done), optional owner - local name, expiry, owner - if C_UnitAuras and C_UnitAuras.GetBuffDataByIndex then - local aura, definitive = X.QueryAura(C_UnitAuras.GetBuffDataByIndex, unit, i) + local function BuffTuple(...) return select("#", ...), ... end + local function ReadLegacyBuff(unit, i) return BuffTuple(UnitBuff(unit, i)) end + + function X.ReadBuff(unit, i, withOwner, withID) + -- done, name, expirationTime, complete (when done), optional owner/ID + local name, expiry, owner, id + local lookup = C_UnitAuras and (C_UnitAuras.GetBuffDataByIndex or C_UnitAuras.GetAuraDataByIndex) + if lookup then + local aura, definitive = X.QueryAura(lookup, unit, i, "HELPFUL") if not definitive then return true, nil, nil, false end if not aura then return true, nil, nil, true end local nameOK, value = pcall(GetField, aura, "name") if nameOK then name = value end expiry = AuraExpiration(aura) if withOwner then owner = AuraOwner(aura) end + if withID then + local read, spell = pcall(GetField, aura, "spellId") + if read then id = spell end + end elseif UnitBuff then -- UnitBuff's rank-less return list: expirationTime, then source. - local ok, value, _, _, _, _, expiration, source = pcall(UnitBuff, unit, i) - if not ok then return true, nil, nil, false end + local ok, count, value, _, _, _, _, expiration, source, _, _, spell = pcall(ReadLegacyBuff, unit, i) + if not ok or count == 0 then return true, nil, nil, false end if type(value) == "nil" then return true, nil, nil, true end - name, expiry = value, expiration + name, expiry, id = value, expiration, spell if withOwner then owner = SourceOwner(source) end else return true, nil, nil, false end - if not Readable(name) or type(name) ~= "string" then + if not Readable(name) or type(name) ~= "string" or name == "" then X.hid = GetTime() - return false + name = nil end + if withID and not (Readable(id) and X.Settings.PositiveID(id)) then id = nil end if not Readable(expiry) or type(expiry) ~= "number" or not (expiry >= 0 and expiry < math_huge) then expiry = nil end - return false, name, expiry, nil, owner + return false, name, expiry, nil, owner, id end local function SecondsLeft(expiry, now) @@ -1269,7 +1374,9 @@ do if added then probe.added = (probe.added or 0) + 1 end if removed then probe.removed = (probe.removed or 0) + 1 end if updated then probe.updated = (probe.updated or 0) + 1 end - if db and db.fastAura and not full then + local optional = db and not db.liteMode and ((unit == "player" and db.worldWatch) + or ((db.consumables or db.drinkWatch) and (unit == "player" or unit:match("^party%d+$") or unit:match("^raid%d+$")))) + if db and db.fastAura and not full and not optional then if not X.AuraRelevant(unit, added, updated, removed) then probe.skipped = (probe.skipped or 0) + 1 return false @@ -1316,6 +1423,30 @@ local function HasAny(unit, names, minLeft, measure) return has, longest end +do + local function ObserveFamily(unit, names, cutoff) + local longest, partial, untimed = 0, false, false + for _, name in ipairs(names) do + local left, presence, uncertain = X.Remaining(unit, name) + if left and left > cutoff then return "present", nil, nil, true end + if left and left > longest then longest = left end + if presence == "present" and not left then untimed = true end + if presence == "unknown" or (presence == "present" and (not left or uncertain)) then partial = true end + end + if longest > 0 or untimed then return "present", longest, partial, untimed end + return partial and "unknown" or "absent", longest, partial + end + + function X.FortitudeCoverage(unit, names, threshold, measure) + local state, longest, uncertain, untimed = ObserveFamily(unit, names, math_max(threshold, measure or 0)) + if state == "present" and not longest then return true end + if state == "unknown" then return nil end + local covered = state == "present" and (longest > threshold or (threshold == 0 and untimed)) + if uncertain then return covered and true or nil end + return covered, longest + end +end + --------------------------------------------------------------------------- -- What can I cast? --------------------------------------------------------------------------- @@ -1368,6 +1499,7 @@ end local function ByRank(a, b) return a.rank < b.rank end function BuildBuffList() + X.nameKeyStamp = nil -- custom buffs can change without changing the spellbook size wipe(known) local total = SpellbookSize() local probing = total == 0 -- size unknown: walk until the book clearly ends @@ -1396,7 +1528,6 @@ function BuildBuffList() end wipe(myBuffs) - X.nameKeyStamp = nil for _, d in ipairs(BUFF_DEFS) do local castName, names = nil, {} if d.choices then @@ -1488,15 +1619,10 @@ function BuildBuffList() do -- watched aura names for the fast-aura relevance check (1.14.0) local watch = {} - if CLASSIC_FEATURES then watch.Drink = true end for _, b in ipairs(myBuffs) do if b.name then watch[b.name] = true end for _, n in ipairs(b.names or {}) do watch[n] = true end end - for _, cd in ipairs(X.CONS_DEFS or {}) do - for _, n in ipairs(cd.names or {}) do watch[n] = true end - if cd.sub then watch[cd.sub] = true end - end for _, b in pairs(blessKnown) do if type(b) == "table" then if b.name then watch[b.name] = true end @@ -1900,85 +2026,232 @@ end -- keep/drop are scratch lists reused by CollectEntries. local Single = { holder = {}, spell = {}, keep = {}, drop = {} } --- Consumables watch (1.6.0): not castable, so these never make rows -- --- they only feed the coverage line. Matched by aura name: exact names, or --- a substring ("Flask of ..." covers every flask on both clients). -X.CONS_DEFS = { - { key = "FLASK", label = "Flask", sub = "Flask of" }, - { key = "FOOD", label = "Food", names = { "Well Fed" } }, -} -if not CLASSIC_FEATURES then - X.CONS_DEFS[#X.CONS_DEFS + 1] = { key = "RUNE", label = "Rune", sub = "Augment Rune" } -end - --- World-buff watch (1.8.0, Forever): the famous world buffs on YOU, --- matched by aura name like the consumables above. Feeds one segment of --- the coverage line, so a raid can see whose Dragonslayer is ticking. -X.WORLD_BUFFS = { - { name = "Rallying Cry of the Dragonslayer" }, { name = "Warchief's Blessing" }, - { name = "Songflower Serenade" }, { name = "Spirit of Zandalar" }, - { sub = "Sayge's Dark Fortune" }, { name = "Fengus' Ferocity" }, - { name = "Mol'dar's Moxie" }, { name = "Slip'kik's Savvy" }, - { name = "Traces of Silithid" }, -} +do -- one bounded helpful-aura observation, no aura state kept across units + local english = not GetLocale or GetLocale() == "enUS" or GetLocale() == "enGB" + local function Family(key, label, ids, name, fragment) + local def = { key = key, label = label, ids = {}, names = {}, unresolved = ids, retryAt = 0, + legacyName = not CLASSIC_FEATURES and english and name or nil, + legacyFragment = not CLASSIC_FEATURES and english and fragment or nil } + for _, id in ipairs(ids) do def.ids[id] = true end + return def + end + X.CONS_DEFS = { + Family("FLASK", "Flask", { 17626, 17627, 17628, 17629 }, nil, "Flask of"), + Family("FOOD", "Food", { 19705, 19706, 19708, 19709, 19710 }, "Well Fed"), + } + if not CLASSIC_FEATURES then X.CONS_DEFS[3] = Family("RUNE", "Rune", {}, nil, "Augment Rune") end + local drink = Family("DRINK", "Drink", { 430, 431, 432, 1133, 1135, 1137, 10250, 22734 }) + local world = Family("WORLD", "World", { 22888, 16609, 15366, 24425, 22817, 22818, 22820, 29534, + 23735, 23736, 23737, 23738, 23766, 23767, 23768, 23769 }) + + local function Resolve(def, now) + if #def.unresolved == 0 or now < def.retryAt then return end + def.retryAt = now + 10 + for i = #def.unresolved, 1, -1 do + local ok, name = pcall(SpellName, def.unresolved[i]) + if ok and SafeString(name) and name ~= "" then + def.names[name] = true + table.remove(def.unresolved, i) + end + end + end -function X.WorldBuffsText() - if not CLASSIC_FEATURES then return nil end - local found = {} - for i = 1, 40 do - local done, name = X.ReadBuff("player", i) - if done then break end - if name then - for _, w in ipairs(X.WORLD_BUFFS) do - if (w.name and name == w.name) or (w.sub and name:find(w.sub, 1, true)) then - local left = X.Remaining("player", name) - local when = "" - if left and left < math_huge then + local function OptionalAura(unit, id, now) + local api = C_UnitAuras + if not api then return end + local aura + if unit == "player" and api.GetPlayerAuraBySpellID then + aura = X.QueryAura(api.GetPlayerAuraBySpellID, id) + elseif api.GetUnitAuraBySpellID then + aura = X.QueryAura(api.GetUnitAuraBySpellID, unit, id) + end + -- An exact match can prove presence. Nil cannot prove absence: the unit + -- may be out of sight or restricted. Let the bounded helpful scan decide. + if not aura then return end + local ok, spell, expiration, helpful, harmful = pcall(function() + return aura.spellId, aura.expirationTime, aura.isHelpful, aura.isHarmful + end) + if not ok or not Readable(spell) or spell ~= id or not Readable(expiration) + or type(expiration) ~= "number" or not (expiration == 0 or (expiration > now and expiration < math_huge)) then return end + if type(helpful) ~= "nil" and (not Readable(helpful) or helpful ~= true) then return end + if type(harmful) ~= "nil" and (not Readable(harmful) or harmful ~= false) then return end + return helpful == true or harmful == false -- absence of both flags is not proof + end + + local function Matches(def, id, name) + if id and def.ids[id] then return true end + if name and (def.names[name] or name == def.legacyName + or (def.legacyFragment and name:find(def.legacyFragment, 1, true))) then return true end + -- A known aura ID suffices for a defined ID catalogue, but neither an + -- unreadable ID nor an untranslated name can prove absence on its own. + if (id and next(def.ids)) or (name and (def.legacyName or def.legacyFragment + or (next(def.names) and #def.unresolved == 0))) then return false end + end + + function X.ObserveConsumables(unit, output, checkFood, checkDrink, optional) + wipe(output) + local now = GetTime() + local remaining, unavailable = checkFood and #X.CONS_DEFS or 0, {} + if checkFood then for _, def in ipairs(X.CONS_DEFS) do Resolve(def, now) end end + if checkDrink then Resolve(drink, now); remaining = remaining + 1 end + if optional then remaining = remaining + 1 end + if optional and OptionalAura(unit, optional, now) then output.OPTIONAL, remaining = true, remaining - 1 end + if remaining == 0 then return output end + local drinkUnknown, optionalUnknown + for i = 1, 40 do + local done, name, expiry, complete, _, id = X.ReadBuff(unit, i, false, true) + if done then + if complete then + if checkFood then + for _, def in ipairs(X.CONS_DEFS) do + if output[def.key] == nil and not unavailable[def.key] + and (next(def.ids) or def.legacyName or def.legacyFragment) then output[def.key] = false end + end + end + if checkDrink and not output.DRINK and not drinkUnknown then output.DRINK = false end + if optional and not output.OPTIONAL and not optionalUnknown then output.OPTIONAL = false end + end + return output + end + if not expiry or expiry == 0 or expiry > now then + if checkFood then + for _, def in ipairs(X.CONS_DEFS) do + local key = def.key + if not output[key] then + local match = Matches(def, id, name) + if match then output[key] = true; remaining = remaining - 1 + elseif match == nil then unavailable[key] = true end + end + end + end + if checkDrink and not output.DRINK then + local match = Matches(drink, id, name) + if match then output.DRINK = true; remaining = remaining - 1 + elseif match == nil then drinkUnknown = true end + end + if optional and not output.OPTIONAL then + if id == optional then output.OPTIONAL = true; remaining = remaining - 1 + elseif not id then optionalUnknown = true end + end + end + if remaining == 0 then break end -- every requested category hit + end + return output + end + + local observation = {} + function X.ScanConsumables(unit) + local checkFood = db.consumables + local checkDrink = CLASSIC_FEATURES and db.drinkWatch + if db.liteMode or not (checkFood or checkDrink) then return end + X.ObserveConsumables(unit, observation, checkFood, checkDrink) + if checkFood then + for _, def in ipairs(X.CONS_DEFS) do + local has, t = observation[def.key], X.consTally[def.key] + if not t then t = { total = 0, miss = 0, unknown = 0 }; X.consTally[def.key] = t end + if has == nil then t.unknown = t.unknown + 1 + else + t.total = t.total + 1 + if not has then t.miss = t.miss + 1 end + end + end + end + return observation.DRINK + end + + function X.WorldBuffsText() + if not CLASSIC_FEATURES then return nil end + local found, complete, now = {}, false, GetTime() + Resolve(world, now) + local unreadable = false + for i = 1, 40 do + local done, name, expiry, ended, _, id = X.ReadBuff("player", i, false, true) + if done then complete = ended and not unreadable; break end + if not expiry or expiry == 0 or expiry > now then + local match = Matches(world, id, name) + if match and name then + local when, left = "", expiry and expiry > 0 and expiry - now + if left then when = left >= 3600 and string_format(" ~%dh", math_floor(left / 3600)) or string_format(" ~%dm", math_floor(left / 60)) end found[#found + 1] = name .. when - break - end + elseif match ~= false then unreadable = true end end end + if not complete then found[#found + 1] = L["Some world buff information is unavailable."] end + if #found > 0 then return L["World"] .. ": " .. table.concat(found, ", ") end end - if #found == 0 then return nil end - return "World: " .. table.concat(found, ", ") end -function X.ConsHas(unit, def) - local complete = true - for i = 1, 40 do - local done, name, _, ended = X.ReadBuff(unit, i) - if done then - if ended and complete then return false end - return nil +do + local current, spare = {}, {} + local function Track(unit, now) + if X.ReadUnitBool(UnitExists, unit) ~= true then return end + local guid = X.UnitGUIDOf(unit) + if not guid or current[guid] then return end + current[guid] = true + local dead = X.ReadUnitBool(UnitIsDeadOrGhost, unit) + if dead == true then + X.dead[guid], X.rezAt[guid] = now, nil + elseif dead == false and X.dead[guid] then + X.dead[guid], X.rezAt[guid] = nil, now end - if name then - if def.sub and name:find(def.sub, 1, true) then return true end - if def.names then - for _, nm in ipairs(def.names) do if name == nm then return true end end + end + + function X.TrackDeaths(list) + local now = GetTime() + wipe(current) + for i = 1, #list do Track(list[i], now) end + Track("player", now) + for guid, last in pairs(X.dead) do if not current[guid] or now - last >= 600 then X.dead[guid] = nil end end + for guid, last in pairs(X.rezAt) do if not current[guid] or now - last >= 60 then X.rezAt[guid] = nil end end + for guid, last in pairs(X.expiredAt) do if not current[guid] or now - last >= 10 then X.expiredAt[guid] = nil end end + for guid, keys in pairs(X.missPrev) do + if not current[guid] then + X.missPrev[guid] = nil + wipe(keys) + spare[#spare + 1] = keys end - else complete = false end + end end -end -function X.Track(unit) - if not X.UnitPresent(unit) then return end - local guid = X.UnitGUIDOf(unit) - if not guid then return end - if X.ReadUnitBool(UnitIsDeadOrGhost, unit) == true then - X.dead[guid] = true - elseif X.dead[guid] then - X.dead[guid] = nil - X.rezAt[guid] = GetTime() + function X.ResetMissingScan() + for guid, keys in pairs(X.missNow) do + wipe(keys) + spare[#spare + 1] = keys + X.missNow[guid] = nil + end end -end -function X.TrackDeaths(list, extra) - for i = 1, #list do X.Track(list[i]) end - if extra then X.Track(extra) end + function X.RecordMissing(guid, unit, spells, unknown) + local previous = X.missPrev[guid] + if unknown and not previous then return end + local slot = #spare + local keys = spare[slot] or {} + spare[slot] = nil + X.missNow[guid] = keys + if unknown then + for k in pairs(previous) do keys[k] = true end + return + end + local expired, fall + for _, spell in ipairs(spells) do + local key = X.KeyOfName(spell) + if key then + keys[key] = true + if previous and not previous[key] then + local names + for _, b in ipairs(myBuffs) do if b.name == spell then names = b.names; break end end + local blessing = blessKeys[spell] and blessKnown[blessKeys[spell]:sub(7)] + if HasAny(unit, names or (blessing and blessing.names) or { spell }, 0) == false then + expired, fall = true, fall or not Single.spell[key] + end + end + end + end + return expired, fall + end end local function MeasureExpiry(unit, key, name, has, left, observe, blessing) @@ -2004,15 +2277,6 @@ local function Missing(unit, out, isGroup, isSelf, report, detail) if report == "why" then detail.rule = L["Rule unavailable"] end return 0, true, false end - if not report and isGroup and db.consumables and not db.liteMode then - for _, cd in ipairs(X.CONS_DEFS) do - local t = X.consTally[cd.key] - if not t then t = { total = 0, miss = 0 }; X.consTally[cd.key] = t end - local has = X.ConsHas(unit, cd) - if has ~= nil then t.total = t.total + 1 end - if has == false then t.miss = t.miss + 1 end - end - end if not reviewing then X.scanUnit, X.blessingScanUnit = nil, nil end -- fresh index scans for aura readers local n = 0 local unknown, checked @@ -2055,10 +2319,11 @@ local function Missing(unit, out, isGroup, isSelf, report, detail) if report == "why" and eligible and outdoorThorns then detail.rule = detail.rule .. " · " .. L["Thorns: Any Class Outdoors"] end + local coverage = b.key == "FORTITUDE" and X.FortitudeCoverage or HasAny if report == "raidCoverage" then if eligible and not b.self then local has - if detail.observable then has = HasAny(unit, b.names, 0) end + if detail.observable then has = coverage(unit, b.names, 0) end detail.record(b.name, has) end elseif reviewing and eligible then @@ -2066,7 +2331,7 @@ local function Missing(unit, out, isGroup, isSelf, report, detail) elseif eligible then local thr = report and report ~= "why" and 0 or (db.rebuffPer and db.rebuffPer[b.key]) or db.rebuff - local has, left = HasAny(unit, b.names, thr, not report and isGroup and scanHorizon) + local has, left = coverage(unit, b.names, thr, not report and isGroup and scanHorizon) if report then checked = true if has == nil then unknown = true end @@ -2248,7 +2513,6 @@ local function EntryOrder(a, b) if db.sortMode == "role" and (a.role or 3) ~= (b.role or 3) then return (a.role or 3) < (b.role or 3) end - if (a.outOfRange or false) ~= (b.outOfRange or false) then return not a.outOfRange end if a.group ~= b.group then return a.group end return a.sortName < b.sortName -- readable name, or "" (a shown name may be protected) end @@ -2293,7 +2557,7 @@ X.Ignore = Ignore -- for Extras.lua (1.13.0) function Ignore.Rebuild() wipe(Ignore.index) local dupes - for name in pairs(db.ignored) do + for _, name in ipairs(Ignore.Sorted()) do local k = Ignore.Key(name) if Ignore.index[k] then dupes = dupes or {} @@ -2311,17 +2575,28 @@ end -- What a stored ignore entry may be: a plausible name or name-realm. Game -- escape codes ("|"), control characters and the list separator never occur -- in player names, and a stored one would render as markup in the list. -function Ignore.Valid(name) - return type(name) == "string" and name ~= "" and #name <= 64 - and name:find("%S") ~= nil and not name:find("[%c;|]") +Ignore.Valid = X.Settings.ValidIgnore + +function Ignore.AddMany(names) + local add, pending = {}, {} + local available = X.Settings.Limits.ignored - X.Settings.Count(db.ignored) + for _, name in ipairs(names) do + if Ignore.Valid(name) then + local key = Ignore.Key(name) + if not Ignore.index[key] and not pending[key] then + if #add >= available then return nil, L["Ignore list is full. Remove entries first."] end + pending[key] = true + add[#add + 1] = name + end + end + end + for _, name in ipairs(add) do db.ignored[name], Ignore.index[Ignore.Key(name)] = true, name end + return #add end function Ignore.Add(name) - local k = Ignore.Key(name) - if Ignore.index[k] then return false end - db.ignored[name] = true - Ignore.index[k] = name - return true + local n, err = Ignore.AddMany({ name }) + return n == 1, err end -- Removes the matching entry. Unless exact, a bare name also removes that @@ -2414,8 +2689,7 @@ local function Consider(unit, isGroup) -- Healer drinking (1.8.0, Forever): anyone in the group with a Drink -- aura is marked; healing classes also feed the coverage line count. X.scanUnit = nil - if isGroup and db.drinkWatch and not db.liteMode and CLASSIC_FEATURES - and select(2, X.Remaining(unit, "Drink")) == "present" then + if isGroup and X.ScanConsumables(unit) then X.drinkSet[guid] = true local dclass = X.UnitClassToken(unit) if dclass == "PRIEST" or dclass == "PALADIN" or dclass == "SHAMAN" @@ -2436,7 +2710,10 @@ local function Consider(unit, isGroup) if auraUnknown then X.scanHasUnknownBuffs = true end if allN > 0 or X.auraNeedsBuff then X.scanHasMissingBuffs = true end e.remain1, e.expiringSpell = X.remainTmp, e.allMissing[1] - if isGroup and not auraUnknown and allN == 0 then X.missNow[guid] = {} end + local expired, fallExpired + if isGroup then expired, fallExpired = X.RecordMissing(guid, unit, e.allMissing, auraUnknown) end + if expired then X.expiredAt[guid] = GetTime() end + if fallExpired and db.fallSound and X.afterCombatScan then X.fallPending = true end local queue = e.allMissing if X.subgroupDuties and next(X.subgroupDuties) and InRaid() then e.subgroupMissing = e.subgroupMissing or {} @@ -2444,7 +2721,7 @@ local function Consider(unit, isGroup) end local n, approximate = X.FilterInRange(unit, queue, e.missing, isSelf) if #queue > 0 and n == 0 and db.rangeWatch then X.farNow[guid] = nm or true end - if n == 0 and (#queue > 0 or allN == 0) then return end + if n == 0 then return end local class = X.UnitClassToken(unit) e.unit, e.guid, e.name, e.class, e.group = unit, guid, nm or unit, class, isGroup e.fullName, e.sortName = full, nm or "" @@ -2452,41 +2729,11 @@ local function Consider(unit, isGroup) e.rangeBucket = 0 e.approximateRange = approximate e.marker = X.ReadRaidMarker(unit) - if isGroup and not auraUnknown then - -- Expiry tracking: a buff that was not missing last scan, is missing - -- now, and is truly gone (not just inside its rebuff window) expired, - -- was dispelled, or went away with a death. - local keys, expired, fallExpired = {}, nil, nil - for j = 1, #e.allMissing do - local key = X.KeyOfName(e.allMissing[j]) - if key then - keys[key] = true - local prev = X.missPrev[guid] - if prev and not prev[key] and HasAny(unit, { e.allMissing[j] }, 0) == false then - expired = true - if not Single.spell[key] then fallExpired = true end - end - end - end - X.missNow[guid] = keys - -- Sticky for a few seconds: the next scan already sees the buff as - -- "missing last time too", so without this the flag would flap off. - if expired then X.expiredAt[guid] = GetTime() end - -- #33 (1.15.0): a group buff that was up before the fight and is gone - -- at the first scan after it fell off here -- CheckFalls plays the - -- distinct "fall" alert for it (single-target buffs excluded: they - -- have their own drop alert in CheckDrops). - if fallExpired and db.fallSound and X.afterCombatScan then X.fallPending = true end - local ea = X.expiredAt[guid] - e.expired = (expired or (ea and GetTime() - ea < 10)) or nil - else - e.expired = nil - end - if n == 0 then return end + local ea = X.expiredAt[guid] + e.expired = isGroup and not auraUnknown and (expired or (ea and GetTime() - ea < 10)) or nil nEntries = slot local rz = X.rezAt[guid] e.rezzed = (rz and GetTime() - rz < 60) or nil - e.outOfRange = false e.groupCast = false e.role, e.groupRole = RoleOf(unit, isSelf) e.pet = nil @@ -2557,7 +2804,6 @@ function X.ConsiderPet(petUnit, ownerUnit) e.marker = X.ReadRaidMarker(petUnit) e.remain1, e.expiringSpell, e.groupRole = nil, nil, nil e.expired, e.rezzed = nil, nil - e.outOfRange = false e.groupCast = false e.role = 3 end @@ -2607,13 +2853,12 @@ local function CollectEntries() X.tallyUnits, X.tallyMissingUnits, X.tallyUnknownUnits = 0, 0, 0 X.scanHasUnknownBuffs, X.scanHasMissingBuffs, X.scanNameFiltered = false, false, false X.rangeSilent = false - X.missPrev, X.missNow = X.missNow, {} - wipe(X.missNow) + X.ResetMissingScan() X.fallPending = nil nEntries = 0 X.platesSeen, X.playersSeen = 0, 0 local list = InRaid() and RAID or PARTY - X.TrackDeaths(list, "player") + X.TrackDeaths(list) for i = 1, #list do Consider(list[i], true) end Consider("player", true) -- Group pets (1.8.0): your pet and your group members' pets, as rows. @@ -2698,9 +2943,7 @@ local function CollectEntries() e.drinking = X.drinkSet[e.guid] or nil -- Repeat-offender history (1.8.0): remember who was seen unbuffed -- this group session; the count lands when the group ends. - if e.group and not e.pet and e.sortName and e.sortName ~= "" then - X.offNow[e.sortName] = true - end + if e.group and not e.isSelf and not e.pet and e.fullName then X.TrackOffender(e.guid, e.fullName) end e.queued = nil -- set after the sort, on the new top row only e.weapon = nil -- set below, on your own row only (pooled entries) end @@ -2799,7 +3042,7 @@ X.ext = {} -- extra slash commands, registered by Extras.lua: name -> function function X.SpecKey() if not _G.GetSpecialization then return nil end local ok, idx = pcall(_G.GetSpecialization) - if ok and type(idx) == "number" and idx > 0 then return "s" .. idx end + if ok and Readable(idx) and type(idx) == "number" and idx >= 1 and idx <= 4 and idx == math_floor(idx) then return "s" .. idx end return nil end @@ -3090,9 +3333,13 @@ end function X.SendGroupReport(text) local channel = InRaid() and "RAID" or (InGroup() and "PARTY" or nil) local send = (_G.C_ChatInfo and _G.C_ChatInfo.SendChatMessage) or _G.SendChatMessage - if not channel or not send or #text > 255 then return end + if not channel then return nil, L["No group channel."] end + if type(send) ~= "function" then return nil, L["Group chat is unavailable."] end + if #text > 255 then return nil, L["The message exceeds the chat limit."] end local ok, accepted = pcall(send, text, channel) - if ok and accepted ~= false then return channel end + if ok and type(accepted) == "nil" then return channel, nil, false end -- no delivery result from the client + if ok and Readable(accepted) and accepted == true then return channel, nil, true end + return nil, L["The game did not accept the send."] end function X.SnapshotMissing(report) @@ -3117,9 +3364,10 @@ function X.ReadyReport(report) -- Auto-post (1.7.0): the leader or an assistant can have the summary -- posted to group chat too, so the group sees it without asking. if db.readyPost and X.AmLead() then - X.SendGroupReport(string_format("BuffRadar ready check: %d %s missing buffs (%d buffs needed).%s", + local sent, failure = X.SendGroupReport(string_format("BuffRadar ready check: %d %s missing buffs (%d buffs needed).%s", people, people == 1 and "person is" or "people are", report.buffs, note and (" " .. note) or "")) + if not sent then Print(string_format(L["Local only — not sent: %s"], failure)) end end end end @@ -3151,7 +3399,12 @@ function X.Announce() end local text = "BuffRadar -- missing buffs: " .. table.concat(segs, " · ") .. (note and (" · " .. note) or "") - if not X.SendGroupReport(text) then + local channel, failure, accepted = X.SendGroupReport(text) + if channel then + Print(L[accepted and "Game accepted the group chat send; delivery is not confirmed." + or "Group chat send requested; delivery is not confirmed."]) + else + Print(string_format(L["Local only — not sent: %s"], failure)) Print(text) end end @@ -3212,7 +3465,12 @@ function X.DefaultRank(spell, level) return false end +function X.RankTooLow(spell, level, method) + return CLASSIC_FEATURES and method ~= "macro" and X.DefaultRank(spell, level) == false +end + function X.BindingRank(spell, unit, level, method) + if X.RankTooLow(spell, level, method) then return false end if method == "target" then return X.DefaultRank(spell, level) end return PickRank(spell, unit, level) end @@ -3379,24 +3637,12 @@ function X.SubgroupDutyCommand(input) if #keys > 0 then Print(string_format(L["Available Buff Keys: %s"], table.concat(keys, ", "))) end return end - if not X.KnownSubgroupKey(key) or not selection or not InRaid() or - (selection ~= "ALL" and selection ~= "NONE" and not selection:match("^[1-8][,1-8]*$")) then + if not X.KnownSubgroupKey(key) or not selection or not InRaid() then Print(L["In a raid, use /br subgroup BUFF 1,2,3 or ALL or NONE."]) return end - local groups - if selection ~= "ALL" then - groups = {} - if selection ~= "NONE" then - for group in selection:gmatch("[^,]+") do - if #group ~= 1 then Print(L["Use subgroup numbers 1 to 8, separated by commas."]); return end - groups[tonumber(group)] = true - end - if selection:find(",,", 1, true) or selection:sub(-1) == "," then - Print(L["Use subgroup numbers 1 to 8, separated by commas."]); return - end - end - end + local groups, valid = X.Settings.ParseSubgroups(selection) + if not valid then Print(L["Use subgroup numbers 1 to 8, separated by commas."]); return end if X.SetSubgroupDuty(key, groups) then Print(string_format(L["Subgroup responsibility updated for %s."], key)) end end @@ -3544,11 +3790,20 @@ function X.GroupOffer(spell, unit, preview) if not CLASSIC_FEATURES then return nil end local name, baseID, greater = GroupSpellFor(spell) if not name then return nil end + local raid = InRaid() + local valid, isSelf = Valid(unit) + if not valid or not X.UnitGUIDOf(unit) or (not isSelf and not (InGroup() + and (raid and unit:match("^raid%d+$") or not raid and unit:match("^party[1-4]$")))) then + return nil, nil, nil, "target" + end local list = ranks[name] local pick = X.BindingRank(name, unit, X.ReadUnitNumber(UnitLevel, unit), db.castMethod) - if pick == false or (baseID and not known[name] and not X.ReadUnitBool(_G.IsPlayerSpell, baseID) - and not X.ReadUnitBool(_G.IsSpellKnown, baseID)) then return nil end + if pick == false or (not known[name] and not (baseID and (X.ReadUnitBool(_G.IsPlayerSpell, baseID) + or X.ReadUnitBool(_G.IsSpellKnown, baseID)))) then return nil end if not preview and OnCooldown(name) then return nil end + if not preview and not X.GroupSpellInRange(name, unit, isSelf) then + return nil, nil, nil, "range" + end local blocker, reason = X.GroupBlockersFor(spell, name, unit, greater, baseID, preview) if blocker then return nil, nil, nil, reason, nil, blocker end local exact = db.castMethod ~= "macro" and pick @@ -3590,6 +3845,8 @@ local function GroupBlockerText(blocker) end function X.GroupOfferReason(item, count, reason, blockers, compact) + if reason == "target" then return L["No eligible group target."] end + if reason == "range" then return L["Group spell range could not be confirmed."] end if blockers then local first, total = blockers.first, #blockers.members local text @@ -4015,7 +4272,8 @@ local function ExactCastName(unit) end function X.NeedsExactTarget(unit, isSelf, method) - return method == "target" and not isSelf and not unit:match("^party%d+$") and not unit:match("^raid%d+$") + return method == "target" and not isSelf and unit ~= "pet" and not unit:match("^party[1-4]$") + and not unit:match("^raid%d+$") and not unit:match("^partypet[1-4]$") and not unit:match("^raidpet%d+$") end local function ExactCastMacro(name, text, hadTarget) @@ -4048,15 +4306,13 @@ function Bind(btn, unit, spell, isSelf, pick, gspell, gpick, hadTarget) btn:SetAttribute("shift-macrotext1", nil) local method = db.castMethod if method == "target" then - -- Self-casts go straight to "player", and party/raid members are cast on - -- by their group unit (party2, raid14, ...), so your target never changes. + -- Self, party/raid and pet casts use their unit tokens directly, so + -- your target never changes and a pet does not need a unique name. -- Anyone else -- nameplate, target or mouseover units, which can point at -- a different player by the time you click -- uses BuffYou's approach -- (MIT, by datdata): target them by exact name, cast the buff, -- then restore your previous target. - -- Group units are rebound on every roster change (GROUP_ROSTER_UPDATE - -- refreshes the list); only a roster change during combat, while the - -- list is frozen, can leave a row pointing at whoever took that slot. + -- PreClick checks the live GUID before acting on a reused unit token. btn:SetAttribute("type", nil) btn:SetAttribute("unit", nil) btn:SetAttribute("spell", nil) @@ -4072,7 +4328,7 @@ function Bind(btn, unit, spell, isSelf, pick, gspell, gpick, hadTarget) end return end - if unit:match("^party%d+$") or unit:match("^raid%d+$") then + if not X.NeedsExactTarget(unit, isSelf, method) then btn:SetAttribute("type", "spell") btn:SetAttribute("spell", (pick and pick.id) or spell) btn:SetAttribute("unit", unit) @@ -4291,10 +4547,13 @@ local function ApplyCast(cast, terminal, targetError) X.sessionCasts = X.sessionCasts + 1 db.castsTotal = (db.castsTotal or 0) + 1 db.stats = db.stats or {} - db.stats[name] = (db.stats[name] or 0) + 1 - db.history = db.history or {} - db.history[#db.history + 1] = { t = (time and time()) or 0, spell = name, who = cast.who } - while #db.history > 50 do table.remove(db.history, 1) end + if X.Settings.PlainString(name, 128) then + if X.Settings.CanAdd(db.stats, "stats", name) then db.stats[name] = (db.stats[name] or 0) + 1 end + if X.Settings.PlainString(cast.who, 128) then + if #db.history >= 50 then table.remove(db.history, 1) end + db.history[#db.history + 1] = { t = (time and time()) or 0, spell = name, who = cast.who } + end + end X.UpdateCounter() local key = X.KeyOfName(name) if key then X.SyncSend(key, cast.guid) end @@ -4560,7 +4819,7 @@ local function OfferGroupCast(n) local tally = {} for i = 1, n do local e = entries[i] - if e.group and not e.isSelf and not e.outOfRange then + if e.group and not e.isSelf and not e.pet and X.RowTargetMatches(e) then for _, spell in ipairs(e.missing) do for _, b in ipairs(myBuffs) do if b.name == spell and b.groupName then @@ -4572,9 +4831,8 @@ local function OfferGroupCast(n) end for i = 1, n do local e = entries[i] - if e.outOfRange then break end local converted = false - if e.group then + if e.group and not e.pet then for _, b in ipairs(myBuffs) do if b.name == e.missing[1] and b.groupName and (tally[b.key] or 0) >= (db.groupCastMin or 3) then @@ -4610,7 +4868,7 @@ local function AlertOnNewEntries(n) local guid = entries[i].guid listedNow[guid] = true -- (greyed out-of-range rows don't ding: they're not castable yet) - if not entries[i].outOfRange and not listedBefore[guid] then + if not listedBefore[guid] then local gone = recentlyGone[guid] if not gone or now - gone > 10 then newName = true end end @@ -4687,6 +4945,7 @@ local function Refresh() AlertOnNewEntries(n) end X.Status.Publish(entries, n) + X.missPrev, X.missNow = X.missNow, X.missPrev end --------------------------------------------------------------------------- @@ -4696,26 +4955,51 @@ local driver = CreateFrame("Frame") local refreshQueued = false local ticker -X.perf = { n = 0, total = 0, max = 0, last = 0 } -local function SafeRefresh() - local t0 = debugprofilestop and debugprofilestop() - local ok, err = pcall(Refresh) - if t0 then - local dt = debugprofilestop() - t0 - local pf = X.perf - pf.n, pf.total, pf.last = pf.n + 1, pf.total + dt, dt - if dt > pf.max then pf.max = dt end - end - if not ok then - scanHorizon = nil - X.Status.Unavailable("updating") - if err ~= lastError then - lastError = err - Print("|cffff4040error:|r " .. tostring(err)) +do + local function RecordTiming(kind, start, ...) + local stop = X.ReadUnitNumber(debugprofilestop) + if stop and stop >= start then + local dt, stat = stop - start, X.timings[kind] + stat.n, stat.total, stat.last = stat.n + 1, stat.total + dt, dt + if dt > stat.max then stat.max = dt end end + return ... + end + + function X.Measure(kind, work, ...) + local start = X.ReadUnitNumber(debugprofilestop) + if not start then return work(...) end + return RecordTiming(kind, start, work(...)) end end +X.timings = {} +for _, kind in ipairs({ "scan", "prepare", "import", "debuff", "combatDebuff" }) do + X.timings[kind] = { n = 0, total = 0, max = 0, last = 0 } +end + +function X.RefreshFault(err) + scanHorizon, nEntries, X.afterCombatScan, X.fallPending = nil, 0, nil, nil + X.groupFallback, X.groupFallbackEntry, X.groupFallbackSummary = nil, nil, nil + X.scanUnit, X.blessingScanUnit = nil, nil + X.scanHasUnknownBuffs, X.scanHasMissingBuffs, X.scanNameFiltered = true, false, false + X.tallyUnits, X.tallyMissingUnits, X.tallyUnknownUnits = 0, 0, 0 + wipe(X.tally); wipe(X.consTally); wipe(X.expiryTally) + X.ClearCastIntent() + pcall(X.AbortWindowScan) + pcall(X.SyncCastMacro, true) + pcall(X.Status.Unavailable, InCombatLockdown() and "combat" or "updating") + if err ~= lastError then + lastError = err + Print("|cffff4040error:|r " .. tostring(err)) + end +end + +local function SafeRefresh() + local ok, err = X.Measure("scan", pcall, Refresh) + if not ok then X.RefreshFault(err) end +end + -- Steady refresh every UPDATE_INTERVAL via C_Timer; bursts of events (UNIT_AURA storms in -- raids, nameplates popping in) collapse into a single refresh SOON_DELAY later. -- How many players are in my group, me included (0 when solo)? @@ -4794,6 +5078,7 @@ else end if X.playerDead then return end if X.ExpireReadyCheck then X.ExpireReadyCheck() end + if X.TickPull then X.TickPull() end X.UpdateFade() X.TickMinimapPulse() if not InCombatLockdown() and (eventPending or not refreshIdle) then SafeRefresh() end @@ -4856,31 +5141,49 @@ local function RequestSpellData() end end --- Register events one at a time and ignore any this client doesn't have --- (newer clients throw an error for unknown event names, which would stop the whole file). -for _, ev in ipairs({ - "ADDON_LOADED", "PLAYER_LOGIN", "PLAYER_ENTERING_WORLD", "PLAYER_REGEN_DISABLED", "PLAYER_REGEN_ENABLED", - "SPELLS_CHANGED", "LEARNED_SPELL_IN_TAB", "LEARNED_SPELL_IN_SKILL_LINE", - "GROUP_ROSTER_UPDATE", "PARTY_MEMBERS_CHANGED", "RAID_ROSTER_UPDATE", "PARTY_LEADER_CHANGED", - "PLAYER_ROLES_ASSIGNED", "GROUP_LEFT", - "PLAYER_TARGET_CHANGED", "UPDATE_MOUSEOVER_UNIT", "UNIT_AURA", "NAME_PLATE_UNIT_ADDED", "NAME_PLATE_UNIT_REMOVED", - "UNIT_SPELLCAST_SENT", "UNIT_SPELLCAST_SUCCEEDED", "UNIT_SPELLCAST_FAILED", - "UNIT_SPELLCAST_FAILED_QUIET", "UNIT_SPELLCAST_INTERRUPTED", "UI_ERROR_MESSAGE", - "ADDON_ACTION_BLOCKED", "ADDON_ACTION_FORBIDDEN", "CVAR_UPDATE", "UPDATE_BINDINGS", "UPDATE_MACROS", - "PLAYER_LEAVING_WORLD", "PLAYER_LOGOUT", - "ZONE_CHANGED_NEW_AREA", "ZONE_CHANGED", "ZONE_CHANGED_INDOORS", - "SPELL_DATA_LOAD_RESULT", "UNIT_PORTRAIT_UPDATE", "BAG_UPDATE_DELAYED", - "READY_CHECK", "READY_CHECK_CONFIRM", "READY_CHECK_FINISHED", - "PLAYER_TALENT_UPDATE", "ACTIVE_TALENT_GROUP_CHANGED", - "CHAT_MSG_ADDON", "CHAT_MSG_WHISPER", "CHAT_MSG_SAY", "CHALLENGE_MODE_START", - "PLAYER_DEAD", "PLAYER_ALIVE", "PLAYER_UNGHOST", "PLAYER_FLAGS_CHANGED", - "PLAYER_FOCUS_CHANGED", "PLAYER_STARTED_MOVING", "PLAYER_STOPPED_MOVING", - "ENCOUNTER_START", "ENCOUNTER_END", "UPDATE_INVENTORY_DURABILITY", "PLAYER_EQUIPMENT_CHANGED", "UNIT_PET", -}) do - pcall(driver.RegisterEvent, driver, ev) -end - -driver:SetScript("OnEvent", function(_, event, arg1, ...) +-- An incompatible install needs only the startup warning and, if locked +-- down, one combat-exit callback to park an owned action-bar macro. +if not X.supported then + driver:RegisterEvent("ADDON_LOADED") + driver:RegisterEvent("PLAYER_LOGIN") +else + -- Register events one at a time and ignore any this client doesn't have + -- (newer clients throw an error for unknown event names, which would stop the whole file). + for _, ev in ipairs({ + "ADDON_LOADED", "PLAYER_LOGIN", "PLAYER_ENTERING_WORLD", "PLAYER_REGEN_DISABLED", "PLAYER_REGEN_ENABLED", + "SPELLS_CHANGED", "LEARNED_SPELL_IN_TAB", "LEARNED_SPELL_IN_SKILL_LINE", + "GROUP_ROSTER_UPDATE", "PARTY_MEMBERS_CHANGED", "RAID_ROSTER_UPDATE", "PARTY_LEADER_CHANGED", + "PLAYER_ROLES_ASSIGNED", "GROUP_LEFT", "DISPLAY_SIZE_CHANGED", "UI_SCALE_CHANGED", + "PLAYER_TARGET_CHANGED", "UPDATE_MOUSEOVER_UNIT", "UNIT_AURA", "NAME_PLATE_UNIT_ADDED", "NAME_PLATE_UNIT_REMOVED", + "UNIT_SPELLCAST_SENT", "UNIT_SPELLCAST_SUCCEEDED", "UNIT_SPELLCAST_FAILED", + "UNIT_SPELLCAST_FAILED_QUIET", "UNIT_SPELLCAST_INTERRUPTED", "UI_ERROR_MESSAGE", + "ADDON_ACTION_BLOCKED", "ADDON_ACTION_FORBIDDEN", "CVAR_UPDATE", "UPDATE_BINDINGS", "UPDATE_MACROS", + "PLAYER_LEAVING_WORLD", "PLAYER_LOGOUT", + "ZONE_CHANGED_NEW_AREA", "ZONE_CHANGED", "ZONE_CHANGED_INDOORS", + "SPELL_DATA_LOAD_RESULT", "UNIT_PORTRAIT_UPDATE", "BAG_UPDATE_DELAYED", + "READY_CHECK", "READY_CHECK_CONFIRM", "READY_CHECK_FINISHED", + "PLAYER_TALENT_UPDATE", "ACTIVE_TALENT_GROUP_CHANGED", + "CHAT_MSG_ADDON", "CHAT_MSG_WHISPER", "CHAT_MSG_SAY", "CHALLENGE_MODE_START", + "PLAYER_DEAD", "PLAYER_ALIVE", "PLAYER_UNGHOST", "PLAYER_FLAGS_CHANGED", + "PLAYER_FOCUS_CHANGED", "PLAYER_STARTED_MOVING", "PLAYER_STOPPED_MOVING", + "ENCOUNTER_START", "ENCOUNTER_END", "UPDATE_INVENTORY_DURABILITY", "PLAYER_EQUIPMENT_CHANGED", "UNIT_PET", + }) do + pcall(driver.RegisterEvent, driver, ev) + end +end + +driver:SetScript("OnEvent", function(self, event, arg1, ...) + if not X.supported then + if event == "PLAYER_LOGIN" or (event == "ADDON_LOADED" and arg1 == ADDON) then + self:UnregisterAllEvents() + if InCombatLockdown() then self:RegisterEvent("PLAYER_REGEN_ENABLED") else X.SyncCastMacro(true) end + Print(L["BuffRadar requires the Forever package on Interface 16001. Casting is disabled."]) + elseif event == "PLAYER_REGEN_ENABLED" and not InCombatLockdown() then + self:UnregisterAllEvents() + X.SyncCastMacro(true) + end + return + end if X.auraIds then if event == "PLAYER_TARGET_CHANGED" then X.auraIds.target = nil elseif event == "UPDATE_MOUSEOVER_UNIT" then X.auraIds.mouseover = nil @@ -4900,7 +5203,7 @@ driver:SetScript("OnEvent", function(_, event, arg1, ...) elseif event == "UPDATE_MOUSEOVER_UNIT" then X.DisarmStaleCastMacro("mouseover") elseif event == "GROUP_ROSTER_UPDATE" or event == "PARTY_MEMBERS_CHANGED" or event == "RAID_ROSTER_UPDATE" - or event == "GROUP_LEFT" then + or event == "GROUP_LEFT" or event == "UNIT_PET" then X.DisarmStaleCastMacro() end -- The busiest events, filtered first. They queue a list refresh: @@ -4936,7 +5239,10 @@ driver:SetScript("OnEvent", function(_, event, arg1, ...) if db and X.CastEvent(event, arg1, ...) then Soon() end return end - if event == "PLAYER_STARTED_MOVING" or event == "PLAYER_STOPPED_MOVING" then + if event == "DISPLAY_SIZE_CHANGED" or event == "UI_SCALE_CHANGED" then + Soon() -- the secure viewport is resized only by an unlocked refresh + return + elseif event == "PLAYER_STARTED_MOVING" or event == "PLAYER_STOPPED_MOVING" then scanTicksRemaining = 0 if db and db.scanThrottle and not refreshIdle and not InCombatLockdown() then Soon() end return @@ -4957,6 +5263,7 @@ driver:SetScript("OnEvent", function(_, event, arg1, ...) if X.QueuePersonalReadiness and (event ~= "UNIT_PET" or Readable(arg1) and arg1 == "player") then X.QueuePersonalReadiness() end + if event == "UNIT_PET" and db and db.pets and not InCombatLockdown() then Soon() end return elseif event == "CVAR_UPDATE" then local name = type(arg1) == "string" and Readable(arg1) and arg1:lower() @@ -4975,6 +5282,8 @@ driver:SetScript("OnEvent", function(_, event, arg1, ...) if X.RefreshConfig then X.RefreshConfig() end return elseif event == "PARTY_LEADER_CHANGED" then + X.CheckLegacyAuthority() + if X.CheckPullRoster then X.CheckPullRoster() end X.OnCoordinationRoster(true) Soon() return @@ -4986,6 +5295,9 @@ driver:SetScript("OnEvent", function(_, event, arg1, ...) if X.QueueAssignmentPreviewRefresh then X.QueueAssignmentPreviewRefresh() end return elseif event == "GROUP_LEFT" then + X.CheckLegacyAuthority(not InGroup()) + X.joinGeneration = (X.joinGeneration or 0) + 1 + X.OnRoster() X.OnCoordinationRoster(true) if not InGroup() then X.Intel.ResetContext() @@ -5106,7 +5418,7 @@ driver:SetScript("OnEvent", function(_, event, arg1, ...) end return end - X.Settings.Load(true) + X.ShowSaveState(X.Settings.Load(true)) X.Status.Unavailable("updating") Ignore.Rebuild() X.SpecSwap() @@ -5115,7 +5427,7 @@ driver:SetScript("OnEvent", function(_, event, arg1, ...) driver:UnregisterEvent("PLAYER_LOGIN") -- one-off if not db then -- Defensive fallback: normally ADDON_LOADED has already migrated the save. - X.Settings.Load(false) + X.ShowSaveState(X.Settings.Load(false)) Ignore.Rebuild() end X.ResolveAutoTheme() @@ -5253,7 +5565,7 @@ local function MacroBody(disarmed) -- Write the already prepared action as top-level commands instead. The -- only /click in this path is an ordinary button for cast bookkeeping. local text, shifted = nextBtn:GetAttribute("macrotext"), nextBtn:GetAttribute("shift-macrotext1") - if db.castMethod ~= "target" and not entry.pet and X.NeedsExactTarget(entry.unit, entry.isSelf, "target") then + if db.castMethod ~= "target" and X.NeedsExactTarget(entry.unit, entry.isSelf, "target") then -- In other cast modes the button may carry a mutable nameplate or -- mouseover token. Never embed that token in a stored macro. text, shifted = X.ExactCastBody(entry.unit, nextBtn.bSpellText, shifted and nextBtn.bGroupText, X.UnitPresent("target")) @@ -5303,14 +5615,14 @@ local function MacroEditorOpen() macro.editor = editor editor:HookScript("OnHide", function() if not X.InvalidateCastMacro() then return end - if X.PlayerSuspended() then X.SyncCastMacro(true) else Soon() end + if not X.supported or X.PlayerSuspended() then X.SyncCastMacro(true) else Soon() end end) end return true end function X.SyncCastMacro(disarmed) - if not db or InCombatLockdown() or macro.writing or not EditMacro then return end + if (not db and not disarmed) or InCombatLockdown() or macro.writing or not EditMacro then return end if not macro.checked then local index, body = ReadMacro() if index and not body then return end @@ -5354,20 +5666,20 @@ end function KeybindText(binding) local k1, k2 = nil, nil if GetBindingKey then k1, k2 = GetBindingKey(binding or NEXT_BINDING) end - if not k1 then return "|cff888888not bound|r" end + if not k1 then return "|cff888888" .. L["not bound"] .. "|r" end local function nice(k) return (GetBindingText and GetBindingText(k)) or k end return "|cffffd100" .. nice(k1) .. (k2 and (", " .. nice(k2)) or "") .. "|r" end function OpenKeybinds() if X.PlayerSuspended() then return end - if InCombatLockdown() then Print("Can't open key bindings during combat."); return end + if InCombatLockdown() then Print(L["Can't open key bindings during combat."]); return end local ok = false if Settings and Settings.OpenToCategory and Settings.KEYBINDINGS_CATEGORY_ID then ok = pcall(Settings.OpenToCategory, Settings.KEYBINDINGS_CATEGORY_ID, BINDING_HEADER_BUFFRADAR) end if not ok then - Print("Open Game Menu > Options > Keybindings and look for the BuffRadar section.") + Print(L["Open Game Menu > Options > Keybindings and look for the BuffRadar section."]) end end @@ -5426,7 +5738,7 @@ end -- keybind + macro block -- Addon-private entry points. Consumers read the current queue counts and -- session flags through accessors; the spell and entry tables are reused. -X.Print, X.L, X.Refresh = Print, L, Refresh +X.Print, X.L, X.Refresh = Print, L, SafeRefresh X.InGroup, X.InRaid = InGroup, InRaid X.Core = { BuildBuffList = BuildBuffList, diff --git a/BuffRadar/Config.lua b/BuffRadar/Config.lua index 85015f2..10e25f9 100644 --- a/BuffRadar/Config.lua +++ b/BuffRadar/Config.lua @@ -278,7 +278,7 @@ function K.Start(narrate) end function K.Build() - local button = CreateFrame("Button", nil, cfg, "UIPanelButtonTemplate") + local button = X.PanelWidget("Button", nil, cfg, "UIPanelButtonTemplate") button:SetSize(166, 22) button:SetPoint("BOTTOMRIGHT", cfg, "BOTTOMRIGHT", -16, 9) button:SetText(L["Keyboard Navigation"]) @@ -293,7 +293,7 @@ function K.Build() status:SetWordWrap(false) status:Hide() cfg.navStatus = status - local border = CreateFrame("Frame", nil, cfg, BackdropTemplateMixin and "BackdropTemplate" or nil) + local border = X.PanelWidget("Frame", nil, cfg, BackdropTemplateMixin and "BackdropTemplate" or nil) if border.SetBackdrop then border:SetBackdrop({ edgeFile = "Interface\\Buttons\\WHITE8X8", edgeSize = 2 }) border:SetBackdropBorderColor(1, 0.82, 0.24, 1) @@ -460,7 +460,7 @@ end -- Seconds entry box (0-3600). Enter or clicking away saves, Esc cancels; -- onCommit gets the number, or nil for an empty box. Shows getText() otherwise. local function MakeSecondsBox(parent, getText, onCommit) - local eb = CreateFrame("EditBox", nil, parent, "InputBoxTemplate") + local eb = X.PanelWidget("EditBox", nil, parent, "InputBoxTemplate") eb:SetSize(40, 20) eb:SetAutoFocus(false) eb:SetNumeric(true) @@ -485,7 +485,7 @@ local function MakeSecondsBox(parent, getText, onCommit) end local function MakeButton(parent, text, width, onClick) - local b = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate") + local b = X.PanelWidget("Button", nil, parent, "UIPanelButtonTemplate") b:SetSize(width, 22) b:SetText(text) b:SetScript("OnClick", onClick) @@ -497,7 +497,7 @@ local function MakeButton(parent, text, width, onClick) end local function MakeSlider(parent, x, y, width, minV, maxV, step, onChange, label, valueText) - local slider = CreateFrame("Slider", nil, parent, BackdropTemplateMixin and "BackdropTemplate" or nil) + local slider = X.PanelWidget("Slider", nil, parent, BackdropTemplateMixin and "BackdropTemplate" or nil) slider:SetOrientation("HORIZONTAL") slider:SetSize(width, 17) slider:SetPoint("TOPLEFT", x, y) @@ -689,7 +689,7 @@ end local function OpenBlessingPanel() if not cfg.blessingPanel then - local panel = CreateFrame("Frame", "BuffRadarBlessingPreferences", cfg, + local panel = X.PanelWidget("Frame", "BuffRadarBlessingPreferences", cfg, BackdropTemplateMixin and "BackdropTemplate" or nil) cfg.blessingPanel, cfg.blessingSelectors = panel, {} panel:SetPoint("CENTER", cfg, "CENTER") @@ -709,7 +709,7 @@ local function OpenBlessingPanel() local title = panel:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge") title:SetPoint("TOPLEFT", 20, -18) title:SetText(L["Blessings by class"]) - local close = CreateFrame("Button", nil, panel, "UIPanelCloseButton") + local close = X.PanelWidget("Button", nil, panel, "UIPanelCloseButton") close:SetPoint("TOPRIGHT", -5, -5) close:SetScript("OnClick", function() panel:Hide() end) K.Register(close, panel, L["Close"], "button") @@ -849,7 +849,7 @@ function AssignmentUI.CreatePanel(parent, name, width, height, level) end function AssignmentUI.CloseButton(panel, onClose) - local close = CreateFrame("Button", nil, panel, "UIPanelCloseButton") + local close = X.PanelWidget("Button", nil, panel, "UIPanelCloseButton") close:SetPoint("TOPRIGHT", -4, -4) close:SetScript("OnClick", onClose) K.Register(close, panel, L["Close"], "button") @@ -1910,7 +1910,7 @@ function AssignmentUI.RefreshPreparation(view, rosterRefresh) if not view:IsVisible() then return end view.pendingRefresh = nil if not AssignmentUI.PreparationAvailable(view.tab) then view:Hide(); return end - view.report = X.RaidPreparationSnapshot(view.tab == "personal") + view.report = X.Measure("prepare", X.RaidPreparationSnapshot, view.tab == "personal") if not view.report then view:Hide(); return end AssignmentUI.DrawPreparation(view, rosterRefresh) end @@ -2453,7 +2453,7 @@ function AssignmentUI.BuildCoordination(panel) view.needLabel = view:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall") view.needLabel:SetPoint("BOTTOMLEFT", 260, 65) view.needLabel:SetText(L["Buff Key"]) - view.need = CreateFrame("EditBox", nil, view, "InputBoxTemplate") + view.need = X.PanelWidget("EditBox", nil, view, "InputBoxTemplate") view.need:SetSize(122, 20) view.need:SetPoint("BOTTOMLEFT", 265, 42) view.need:SetAutoFocus(false) @@ -2711,7 +2711,7 @@ function AssignmentUI.BuildReadinessSettings(panel) end local function section(text, x, y) return label(L[text], x, y, "GameFontNormal") end local function field(text, x, y, width, length, numeric, commit) - local box = CreateFrame("EditBox", nil, panel, "InputBoxTemplate") + local box = X.PanelWidget("EditBox", nil, panel, "InputBoxTemplate") box:SetSize(width, 20) box:SetPoint("TOPLEFT", x, y) box:SetAutoFocus(false) @@ -2730,8 +2730,7 @@ function AssignmentUI.BuildReadinessSettings(panel) end local function check(key, text, x, y, tip) local cb = MakeCheck(panel, L[text], function() return db[key] end, function(value) - db[key] = value - I.SettingsChanged() + X.SetPreference(key, value) RefreshConfig() end) cb:SetPoint("TOPLEFT", x, y) @@ -2846,11 +2845,13 @@ local function BuildConfig() -- Blizzard's standard window (title bar, BuffRadar icon in the portrait -- corner, close button, inset content area) so it matches the retail UI. -- A client without that template gets the original hand-drawn window. - cfg = CreateFrame("Frame", "BuffRadarConfig", UIParent, "ButtonFrameTemplate") - local native = cfg.SetTitle and cfg.Inset and cfg.CloseButton and true or false - if not native then - cfg:Hide() - cfg = CreateFrame("Frame", "BuffRadarConfig", UIParent, BackdropTemplateMixin and "BackdropTemplate" or nil) + local templateOK, built = pcall(CreateFrame, "Frame", "BuffRadarConfig", UIParent, "ButtonFrameTemplate") + local native = templateOK and built and built.SetTitle and built.Inset and built.CloseButton + if native then + cfg = built + else + if templateOK and built then built:Hide() end + cfg = X.PanelWidget("Frame", "BuffRadarConfig", UIParent, BackdropTemplateMixin and "BackdropTemplate" or nil) end cfg:SetSize(CONFIG_WIDTH, CONFIG_HEIGHT) cfg.navControls = {} @@ -2865,7 +2866,6 @@ local function BuildConfig() K.Stop() self:StartMoving() end) - cfg:SetScript("OnDragStop", cfg.StopMovingOrSizing) if UISpecialFrames then table.insert(UISpecialFrames, "BuffRadarConfig") end -- Esc closes it if native then @@ -2891,7 +2891,7 @@ local function BuildConfig() local head = cfg:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge") head:SetPoint("TOP", 0, -12) head:SetText("|cff33ccffBuff|rRadar Settings") - local close = CreateFrame("Button", nil, cfg, "UIPanelCloseButton") + local close = X.PanelWidget("Button", nil, cfg, "UIPanelCloseButton") close:SetPoint("TOPRIGHT", -2, -2) close:SetScript("OnClick", function() cfg:Hide() end) cfg.closeButton = close @@ -2908,12 +2908,23 @@ local function BuildConfig() { "behavior", L["Behavior"], 98 }, { "data", L["Ignore & Stats"], 126 }, { "readiness", L["Readiness"], 106 }, } local tabList, prevTab, fallbackX = {}, nil, 14 + if cfg.nativeTabs then + for i = 1, #tabDefs do + local ok, tab = pcall(CreateFrame, "Button", "BuffRadarConfigTab" .. i, cfg, "PanelTabButtonTemplate") + if not ok or not tab then + cfg.nativeTabs = false + for _, item in ipairs(tabList) do item:Hide() end + break + end + tabList[i] = tab + end + end for i, td in ipairs(tabDefs) do local key, label = td[1], td[2] local function onClick() SelectTab(key); RefreshConfig() end local btn if cfg.nativeTabs then - btn = CreateFrame("Button", "BuffRadarConfigTab" .. i, cfg, "PanelTabButtonTemplate") + btn = tabList[i] btn:SetID(i) btn:SetText(label) btn:SetScript("OnClick", onClick) @@ -2924,7 +2935,6 @@ local function BuildConfig() btn:SetPoint("TOPLEFT", cfg, "BOTTOMLEFT", 11, 2) end prevTab = btn - tabList[i] = btn else btn = MakeButton(cfg, "", td[3], onClick) btn:SetText(label) @@ -2934,7 +2944,7 @@ local function BuildConfig() K.Register(btn, cfg, label, "tab").key = key cfg.tabBtns[key] = btn local panel = CreateFrame("Frame", nil, cfg) - if native then -- inside the template's inset area, below the title bar + if cfg.nativeTabs then -- inside the template's inset area, below the title bar panel:SetPoint("TOPLEFT", cfg.Inset, "TOPLEFT", 4, -4) else panel:SetPoint("TOPLEFT", 8, -70) @@ -2967,7 +2977,7 @@ local function BuildConfig() local colorLabel = look:CreateFontString(nil, "OVERLAY", "GameFontHighlight") colorLabel:SetPoint("TOPLEFT", 14, -34) colorLabel:SetText("Background color") - local swatch = CreateFrame("Button", nil, look, BackdropTemplateMixin and "BackdropTemplate" or nil) + local swatch = X.PanelWidget("Button", nil, look, BackdropTemplateMixin and "BackdropTemplate" or nil) swatch:SetSize(40, 18) swatch:SetPoint("LEFT", colorLabel, "RIGHT", 10, 0) if swatch.SetBackdrop then @@ -3013,7 +3023,7 @@ local function BuildConfig() db.charPoint = v if v then local k = X.CharKey() - if k and db.point then db.pointByChar[k] = db.point end + if db.point then X.SaveCharacterPoint(k) end end end) cfg.charPointCheck:SetPoint("TOPLEFT", 250, -150) @@ -3176,6 +3186,14 @@ local function BuildConfig() end) cfg.displayBtn:SetPoint("TOPLEFT", 300, -428) + cfg.panelPointCheck = MakeCheck(look, L["Remember Settings and Ready Check positions"], + function() return db.rememberPanelPositions end, + function(v) X.PanelPositions(v and "on" or "off") end) + cfg.panelPointCheck:SetPoint("TOPLEFT", 10, -428) + WrapCheckLabel(cfg.panelPointCheck) + local resetPanels = MakeButton(look, L["Reset panel positions"], 170, function() X.PanelPositions("reset") end) + resetPanels:SetPoint("TOPLEFT", 14, -465) + cfg.minimapCheck = MakeCheck(look, L["Minimap button (drag it around the minimap)"], function() return db.showMinimap end, function(v) db.showMinimap = v; if RefreshMinimapButton then RefreshMinimapButton() end end) @@ -3271,19 +3289,19 @@ local function BuildConfig() end) resetCount:SetPoint("TOPLEFT", 34, -190) - section(alerts, "Keybinds", 10, -230) + section(alerts, L["Keybinds"], 10, -230) local keyText = alerts:CreateFontString(nil, "OVERLAY", "GameFontHighlight") keyText:SetPoint("TOPLEFT", 14, -254) local keyText2 = alerts:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall") keyText2:SetPoint("TOPLEFT", 14, -270) cfg.keyText, cfg.keyText2 = keyText, keyText2 - local setKey = MakeButton(alerts, "Set keybind", 120, function() + local setKey = MakeButton(alerts, L["Set keybind"], 120, function() K.Stop() OpenKeybinds() end) setKey:SetPoint("TOPLEFT", 14, -288) - local makeMacro = MakeButton(alerts, "Create macro", 120, function() MakeMacro() end) + local makeMacro = MakeButton(alerts, L["Create macro"], 120, function() MakeMacro() end) makeMacro:SetPoint("LEFT", setKey, "RIGHT", 10, 0) local hint = alerts:CreateFontString(nil, "OVERLAY", "GameFontDisableSmall") @@ -3486,10 +3504,7 @@ local function BuildConfig() cfg.syncCheck = MakeCheck(beh, L["Sync casts with other BuffRadar users"], function() return db.sync end, - function(v) - db.sync = v - if not v then X.StopCoordination() end - end) + function(v) X.SetPreference("sync", v) end) cfg.syncCheck:SetPoint("TOPLEFT", 296, -200 + castY) WrapCheckLabel(cfg.syncCheck) @@ -3548,7 +3563,7 @@ local function BuildConfig() cfg.throttleCheck = MakeCheck(beh, L["Adaptive scan throttle"], function() return db.scanThrottle end, - function(v) db.scanThrottle = v; X.Intel.SettingsChanged(); RefreshConfig() end) + function(v) X.SetPreference("scanThrottle", v); RefreshConfig() end) cfg.throttleCheck:SetPoint("TOPLEFT", 10, -215) cfg.fastAuraCheck = MakeCheck(beh, L["Skip rescans for aura changes that touch no watched buff"], function() return db.fastAura end, @@ -3557,7 +3572,7 @@ local function BuildConfig() WrapCheckLabel(cfg.fastAuraCheck) cfg.pullFlashCheck = MakeCheck(beh, L["Flash when a pull timer starts"], function() return db.pullFlash end, - function(v) db.pullFlash = v end) + function(v) X.SetPreference("pullFlash", v) end) cfg.pullFlashCheck:SetPoint("TOPLEFT", 10, -270) section(beh, "More watches", 10, -298) @@ -3675,11 +3690,11 @@ local function BuildConfig() end) resetStats:SetPoint("TOPLEFT", 14, -290) - section(data, "Settings profiles", 10, -330) + section(data, L["Settings profiles"], 10, -330) local profHint = data:CreateFontString(nil, "OVERLAY", "GameFontDisableSmall") profHint:SetPoint("TOPLEFT", 14, -352) - profHint:SetText("Save window, alert and buff preferences to load here or with /br profile.") - cfg.profileBox = CreateFrame("EditBox", nil, data, "InputBoxTemplate") + profHint:SetText(L["Save window, alert and buff preferences to load here or with /br profile."]) + cfg.profileBox = X.PanelWidget("EditBox", nil, data, "InputBoxTemplate") cfg.profileBox:SetSize(170, 20) cfg.profileBox:SetPoint("TOPLEFT", 18, -374) cfg.profileBox:SetAutoFocus(false) @@ -3690,14 +3705,12 @@ local function BuildConfig() local function profName() return (cfg.profileBox:GetText() or ""):match("^%s*(.-)%s*$") end - local profSave = MakeButton(data, "Save", 62, function() - local name = profName() - local ok, err = X.SaveProfile(name) - if ok then Print("Profile saved: " .. name) else Print(err) end - RefreshConfig() + local profSave = MakeButton(data, L["Save"], 62, function() + K.Stop() + X.RequestProfileSave(profName()) end) profSave:SetPoint("LEFT", cfg.profileBox, "RIGHT", 10, 0) - local profLoad = MakeButton(data, "Load", 62, function() + local profLoad = MakeButton(data, L["Load"], 62, function() local name = profName() local ok, err = X.LoadProfile(name) if ok then @@ -3710,14 +3723,14 @@ local function BuildConfig() else Print(err or "No profile named '" .. name .. "'.") end end) profLoad:SetPoint("LEFT", profSave, "RIGHT", 6, 0) - local profDel = MakeButton(data, "Delete", 62, function() + local profDel = MakeButton(data, L["Delete"], 62, function() local name = profName() if X.DeleteProfile(name) then Print("Profile deleted: " .. name) else Print("No profile named '" .. name .. "'.") end RefreshConfig() end) profDel:SetPoint("LEFT", profLoad, "RIGHT", 6, 0) - local profShare = MakeButton(data, "Share", 62, function() + local profShare = MakeButton(data, L["Share BR2"], 86, function() local name = profName() local text = X.ProfileShareText(name) if text then @@ -3728,7 +3741,12 @@ local function BuildConfig() end end) profShare:SetPoint("LEFT", profDel, "RIGHT", 6, 0) - Tip(profShare, "Share this profile", "Shows the named profile as one copyable text you can send to another player; they bring it in with /br profile import. Only that one profile is shared, not your other settings.") + Tip(profShare, L["Share BR2"], L["Use a named BR2 profile to share newer preferences."]) + local profImport = MakeButton(data, L["Import"], 112, function() + K.Stop() + X.ShowExport("", true, L["Paste a shared profile, then review."], "profile") + end) + profImport:SetPoint("TOPRIGHT", -14, -422) cfg.profileText = data:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall") cfg.profileText:SetPoint("TOPLEFT", 14, -402) cfg.profileText:SetWidth(540) @@ -3786,7 +3804,7 @@ local function BuildConfig() Tip(cfg.watchCheck, "Buff drop alert", "When a single-target buff of yours (like Earth Shield) disappears from the player who had it -- expired, dispelled or used up -- you get a message, the alert sound and a border flash, so you know to recast it. Moving it to another player doesn't trigger this. Same as /br watch.") Tip(cfg.counterCheck, "Cast counter", "Shows casts made through BuffRadar this session and all-time at the bottom of the window.") Tip(resetCount, "Reset counts", "Sets this session's and the all-time cast counts to zero. Per-spell stats (Ignore & Stats tab) are kept.") - Tip(setKey, "Set keybind", "Opens Key Bindings at the BuffRadar section: Cast next buff, Show / hide window, Mute / unmute sound.") + Tip(setKey, L["Set keybind"], L["Open the BuffRadar section of the game's key bindings."]) Tip(makeMacro, "Create macro", "Puts a BuffRadar macro on your cursor. Drop it on an action bar; pressing it casts the next buff.") -- Behavior Tip(cfg.groupCheck, "Only show in a party or raid", "Hide the window while you're solo. The Cast next buff key still works.") @@ -3818,7 +3836,7 @@ local function BuildConfig() -- More display options (1.10.0): a small panel of its own — the tabs -- are full. Coverage-line parts, row color marks, tooltip detail and -- the row-name options live here. - local dpanel = CreateFrame("Frame", nil, cfg, BackdropTemplateMixin and "BackdropTemplate" or nil) + local dpanel = X.PanelWidget("Frame", nil, cfg, BackdropTemplateMixin and "BackdropTemplate" or nil) dpanel:SetSize(470, 484) dpanel:SetPoint("CENTER", cfg, "CENTER", 0, 0) if dpanel.SetBackdrop then @@ -3950,7 +3968,7 @@ local function BuildConfig() footer:SetSize(360, 20) footer:SetPoint("BOTTOMLEFT", cfg, "BOTTOMLEFT", 16, 10) cfg.searchFooter = footer - local searchBox = CreateFrame("EditBox", nil, footer, "InputBoxTemplate") + local searchBox = X.PanelWidget("EditBox", nil, footer, "InputBoxTemplate") searchBox:SetSize(180, 20) searchBox:SetPoint("LEFT") searchBox:SetAutoFocus(false) @@ -3965,7 +3983,7 @@ local function BuildConfig() return cfg.searchHint:GetText() end) cfg.searchBox = searchBox - local searchToggle = CreateFrame("Button", nil, cfg, "UIPanelButtonTemplate") + local searchToggle = X.PanelWidget("Button", nil, cfg, "UIPanelButtonTemplate") searchToggle:SetSize(70, 22) searchToggle:SetText(L["Find"]) searchToggle:SetScript("OnClick", function() @@ -3989,6 +4007,7 @@ local function BuildConfig() if cfg.searchToggle then cfg.searchToggle:Show() end RefreshConfig() end) + X.BindPanelPosition(cfg, "settings", 0) K.Build() Tip(cfg.navButton, L["Keyboard Navigation"], navigationHelp) cfg:HookScript("OnHide", function() @@ -4025,6 +4044,7 @@ RefreshConfig = function() cfg.borderCheck:Update() if cfg.compactCheck then cfg.compactCheck:Update() end if cfg.charPointCheck then cfg.charPointCheck:Update() end + cfg.panelPointCheck:Update() if cfg.stripCheck then cfg.stripCheck:Update() end if cfg.clickThroughCheck then cfg.clickThroughCheck:Update() end for _, chk in pairs(cfg.coverChecks or {}) do chk:Update() end @@ -4057,10 +4077,10 @@ RefreshConfig = function() cfg.muteInstCheck:Update() if cfg.watchCheck then cfg.watchCheck:Update() end cfg.counterCheck:Update() - cfg.keyText:SetText("Cast next buff: " .. KeybindText(NEXT_BINDING) .. - " Cast next group buff: " .. KeybindText("CLICK BuffRadarGroupButton:LeftButton")) - cfg.keyText2:SetText("Show / hide: " .. KeybindText("BUFFRADAR_TOGGLE") .. - " Mute: " .. KeybindText("BUFFRADAR_MUTE")) + cfg.keyText:SetText(L["Cast next buff"] .. ": " .. KeybindText(NEXT_BINDING) .. + " " .. L["Cast next group buff"] .. ": " .. KeybindText("CLICK BuffRadarGroupButton:LeftButton")) + cfg.keyText2:SetText(L["Show / hide window"] .. ": " .. KeybindText("BUFFRADAR_TOGGLE") .. + " " .. L["Mute / unmute sound"] .. ": " .. KeybindText("BUFFRADAR_MUTE")) cfg.groupCheck:Update() cfg.cityCheck:Update() cfg.bgCheck:Update() @@ -4233,7 +4253,7 @@ end -- Esc > Options > AddOns > BuffRadar: a short page with a button that opens -- the full settings window (which has more room than the options page). -if Settings and Settings.RegisterCanvasLayoutCategory and Settings.RegisterAddOnCategory then +if X.supported and Settings and Settings.RegisterCanvasLayoutCategory and Settings.RegisterAddOnCategory then local page = CreateFrame("Frame") local head = page:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge") head:SetPoint("TOPLEFT", 16, -16) diff --git a/BuffRadar/Coordination.lua b/BuffRadar/Coordination.lua index f817d79..a3c5e36 100644 --- a/BuffRadar/Coordination.lua +++ b/BuffRadar/Coordination.lua @@ -55,7 +55,7 @@ function X.Broadcast(msg) local success = _G.Enum and _G.Enum.SendAddonMessageResult and _G.Enum.SendAddonMessageResult.Success return result == (success or 0) end - return result ~= false + return result == true end -- Tell the other BuffRadar users in the group "I just cast KEY on GUID", @@ -194,6 +194,104 @@ do return false end + local function Authority() + local channel = SyncChannel() + if not channel then return end + local raid, leader = InRaid(), nil + local roster = raid and RAID or PARTY + for i = raid and 1 or 0, #roster do + local unit = roster[i] or "player" + local present = X.ReadUnitBool(UnitExists, unit) + if present == true and PlanRank(unit) == 2 then + local guid = X.UnitGUIDOf(unit) + if not guid or leader then return end + leader = guid + end + end + if leader then return channel .. ":" .. leader end + end + + local function MemberGUID(unit) + local guid = X.UnitGUIDOf(unit) + if guid and #guid <= 85 and guid:match("^[%w%-]+$") then return guid end + end + + function X.GroupIdentity() + local channel = SyncChannel() + local size = X.ReadUnitNumber(GetNumGroupMembers) + if not channel or not size or size < 2 or size > 40 then return end + local members, seen, incomplete = {}, {}, false + X.ForReportRoster(function(unit, present) + local guid = present and MemberGUID(unit) + if not guid or seen[guid] then incomplete = true; return end + seen[guid] = true + members[#members + 1] = guid + end) + if incomplete or #members ~= size then return end + table_sort(members) + return channel .. ":" .. table.concat(members, ";") + end + + local rosterEpoch, lastMembership = 0, nil + function X.GroupRosterEpoch() return rosterEpoch end + + function X.GroupShareScope(messages) + local authority, membership = Authority(), X.GroupIdentity() + if not authority or not membership then return end + local lead = X.AmLead() + for _, message in ipairs(messages) do + if not lead and (message:sub(1, 6) ~= "BLESS;" or X.UnitClassToken("player") ~= "PALADIN") then return end + end + return table.concat({ authority, X.joinGeneration or 0, X.authorityEpoch or 0, rosterEpoch, membership }, ":") + end + + local remote = { ASSIGN = {}, BLESS = {} } + local function PlanMap(kind) return kind == "ASSIGN" and X.assign or X.blessPlan end + + function X.SetLocalPlan(kind, key, value) + remote[kind][key] = nil + PlanMap(kind)[key] = value + end + + function X.ClearLocalPlans(kind) + wipe(remote[kind]) + wipe(PlanMap(kind)) + end + + function X.CheckLegacyAuthority(left) + local membership = not left and X.GroupIdentity() or nil + if membership ~= lastMembership then + lastMembership, rosterEpoch = membership, rosterEpoch + 1 + end + local scope = not left and db and db.sync and Authority() or nil + if scope ~= X.lastLegacyAuthority then + X.lastLegacyAuthority, X.authorityEpoch = scope, (X.authorityEpoch or 0) + 1 + end + if not next(remote.ASSIGN) and not next(remote.BLESS) then return end + for kind, owners in pairs(remote) do + local map = PlanMap(kind) + for k, owner in pairs(owners) do + local unit = membership and scope and owner.scope == scope and owner.epoch == rosterEpoch and X.SenderUnit(owner.sender) + if not unit or MemberGUID(unit) ~= owner.guid or not HasPlanRole(unit, kind == "BLESS") then + if map[k] == owner.value then map[k] = owner.prior end + owners[k] = nil + end + end + end + end + + local function SetRemotePlan(kind, key, value, unit, sender) + X.CheckLegacyAuthority() + local scope, guid = X.lastLegacyAuthority, MemberGUID(unit) + if not scope or not guid or not lastMembership then return end + local map, owners = PlanMap(kind), remote[kind] + local prior = map[key] + if owners[key] then prior = owners[key].prior end + owners[key] = { scope = scope, epoch = rosterEpoch, sender = sender, guid = guid, prior = prior, value = value } + map[key] = value + return true + end + function X.PruneSyncRoster() if not next(X.peers) and not next(X.cover) then return end local roster = InRaid() and RAID or PARTY @@ -994,16 +1092,14 @@ do elseif kind == "ASSIGN" then local holder = rest:match("^;([^;]+)$") if not ValidBuffKey(first) or not ValidName(holder) or not HasPlanRole(unit) then return end - if holder:lower() == "none" then X.assign[first] = nil else X.assign[first] = holder end + if not SetRemotePlan(kind, first, holder:lower() ~= "none" and holder or nil, unit, name) then return end elseif kind == "BLESS" then local key, holder = rest:match("^;([%w_]+);([^;]+)$") if not key or not X.BLESSING_CLASSES[first] or not ValidName(holder) or (key ~= "NONE" and not BLESSINGS[key]) or not HasPlanRole(unit, true) then return end - if key == "NONE" or holder == "none" then - X.blessPlan[first] = nil - else - X.blessPlan[first] = { key = key, name = holder, mine = me ~= nil and X.SameUser(holder, me) } - end + local value = key ~= "NONE" and holder:lower() ~= "none" + and { key = key, name = holder, mine = me ~= nil and X.SameUser(holder, me) } or nil + if not SetRemotePlan(kind, first, value, unit, name) then return end elseif kind == "COVER" or kind == "BACK" or kind == "HELLO" or kind == "HERE" then if rest ~= "" or not ValidName(first) or not X.SameUser(first, name) then return end if kind == "COVER" then X.cover[name] = now + 300 end @@ -1064,24 +1160,44 @@ function X.ContextOK(key) return true end -function X.WeaponEnchantMissing(strict) - local fn = _G.GetWeaponEnchantInfo - if not fn then return nil end - local ok, hasMH, _, _, _, hasOH = pcall(fn) - if not ok then return nil end - local function missing(has, slot) - if not Readable(has) then return nil end - if has == true or has == 1 then return false end - if has ~= false and has ~= 0 then return nil end - if not _G.GetInventoryItemID then return not strict or nil end - local okI, id = pcall(_G.GetInventoryItemID, "player", slot) - if not okI then return nil end - if type(id) == "nil" then return false end - if Readable(id) and type(id) == "number" then return id > 0 end +local meleeTypes = { INVTYPE_WEAPON = true, INVTYPE_2HWEAPON = true, + INVTYPE_WEAPONMAINHAND = true, INVTYPE_WEAPONOFFHAND = true } + +function X.WeaponCoatingState() + local enchants = _G.GetWeaponEnchantInfo + if type(enchants) ~= "function" then return "unknown" end + local ok, main, _, _, _, off = pcall(enchants) + if not ok then return "unknown" end + local inventory = _G.GetInventoryItemID + local itemInfo = (_G.C_Item and _G.C_Item.GetItemInfoInstant) or _G.GetItemInfoInstant + local function Hand(has, slot) + if type(inventory) ~= "function" then return "unknown" end + local read, id = pcall(inventory, "player", slot) + if not read then return "unknown" end + if type(id) == "nil" then return "na" end -- successful read of an empty slot + if not Readable(id) then return "unknown" end + if id == 0 then return "na" end + if not X.Settings.PositiveID(id) or type(itemInfo) ~= "function" then return "unknown" end + local info, _, _, _, equipLoc, _, classID = pcall(itemInfo, id) + if not info or not Readable(classID) or type(classID) ~= "number" then return "unknown" end + if classID ~= 2 then return "na" end -- Enum.ItemClass.Weapon (also on legacy clients) + if not Readable(equipLoc) or type(equipLoc) ~= "string" or equipLoc == "" then return "unknown" end + if not meleeTypes[equipLoc] then return "na" end + if Readable(has) then + if has == true or has == 1 then return "present" end + if has == false or has == 0 then return "missing" end + end + return "unknown" end - local mh, oh = missing(hasMH, 16), missing(hasOH, 17) - if mh or oh then return true end - if mh == false and oh == false then return false end + local mh, oh = Hand(main, 16), Hand(off, 17) + if mh == "missing" or oh == "missing" then return "missing" end + if mh == "unknown" or oh == "unknown" then return "unknown" end + if mh == "present" or oh == "present" then return "present" end + return "na" +end + +function X.WeaponEnchantMissing() + return X.WeaponCoatingState() == "missing" end -- Instance-entry reminder (1.7.0): stepping into a dungeon, raid or @@ -1118,9 +1234,24 @@ end -- Roster events: only the step from solo to grouped triggers the join -- summary, not every roster shuffle afterwards. +local offCount = 0 +function X.TrackOffender(guid, name) + if not X.Settings.PlainString(guid, 85) or not X.Settings.PlainString(name, 128) then return end + if X.offNow[guid] then + X.offNow[guid] = name + elseif offCount < 128 then + X.offNow[guid], offCount = name, offCount + 1 + end +end + function X.OnRoster() local g = InGroup() - if not g and X.CloseRaidPreparation then X.CloseRaidPreparation() end + if not g and X.CloseRaidPreparation then X.CloseRaidPreparation(true) end + if X.CheckPullRoster then X.CheckPullRoster() end + X.CheckLegacyAuthority(not g) + X.TrackDeaths(InRaid() and RAID or PARTY) + if not g and X.QueuePersonalReadiness then X.QueuePersonalReadiness() end + if g ~= X.inGroupPrev then X.joinGeneration = (X.joinGeneration or 0) + 1 end if not InRaid() then X.subgroupDuties = nil end X.PruneBlessingExceptions() X.PruneAssignmentRoleOverrides() @@ -1128,8 +1259,14 @@ function X.OnRoster() if db then X.SendCover() end -- roster changes refresh a live cover (1.7.0) if X.inGroupPrev == false and g and db and db.joinDigest and core.HasAnyBuff() then if C_Timer and C_Timer.After then - C_Timer.After(1.5, function() X.JoinDigest("join") end) - else + local generation, membership, epoch = X.joinGeneration, X.GroupIdentity(), X.GroupRosterEpoch() + if membership then + C_Timer.After(1.5, function() + if generation == X.joinGeneration and epoch == X.GroupRosterEpoch() and membership == X.GroupIdentity() and db.joinDigest + and not InCombatLockdown() then X.JoinDigest("join") end + end) + end + elseif X.GroupIdentity() and not InCombatLockdown() then X.JoinDigest("join") end end @@ -1143,25 +1280,18 @@ function X.OnRoster() if g then X.PruneSyncRoster() else - wipe(X.assign) - wipe(X.blessPlan) + if X.inGroupPrev then + X.ClearLocalPlans("ASSIGN") + X.ClearLocalPlans("BLESS") + end wipe(X.peers) wipe(X.cover) wipe(X.handled) X.upTotal, X.upFull = 0, 0 -- the run is over (1.6.0) -- Repeat-offender history (1.8.0): the session that just ended -- counts once for everyone who was seen unbuffed during it. - if db then - for name in pairs(X.offNow) do - db.offenders[name] = (db.offenders[name] or 0) + 1 - end - local orows = {} - for nm, c in pairs(db.offenders) do orows[#orows + 1] = { nm = nm, c = c } end - if #orows > 50 then -- keep the worst 50 only - table_sort(orows, function(a, b) return a.c > b.c end) - for i = 51, #orows do db.offenders[orows[i].nm] = nil end - end - end + if db and next(X.offNow) then X.Settings.RecordOffenders(X.offNow) end + offCount = 0 wipe(X.offNow) end X.inGroupPrev = g diff --git a/BuffRadar/Data.lua b/BuffRadar/Data.lua index 7c74093..5b19ae0 100644 --- a/BuffRadar/Data.lua +++ b/BuffRadar/Data.lua @@ -6,19 +6,15 @@ local _, ns = ... local X = {} ns.X = X --- Edition, picked at load from the client's interface version: the --- Forever client reports 16001, retail 120105 and up. One source serves --- both; each edition's zip differs only in its .toc and docs. CLASSIC_FEATURES (true --- on Forever) turns on spell ranks, group versions of buffs (Prayer of --- Fortitude, ...) and paladin blessings; on retail their settings, commands --- and cast modes ("id", "rank") are hidden and that code stays inert. -local CLASSIC_FEATURES -do - local ok, _, _, _, iface = pcall(GetBuildInfo) - iface = ok and tonumber(iface) or 0 - CLASSIC_FEATURES = iface > 0 and iface < 100000 -end +-- The packaged loader supplies the declared client; API feature detection +-- remains separate. The non-shipping Retail TOC is only a regression fixture. +local ok, iface = pcall(function() + local _, _, _, interface = GetBuildInfo() + return tonumber(interface) +end) +local CLASSIC_FEATURES = ok and ns.ForeverInterface == iface and iface ~= nil X.classic = CLASSIC_FEATURES +X.supported = CLASSIC_FEATURES or (ok and not ns.ForeverInterface and iface == 120105) X.friendlyPlateCVars = { "nameplateShowFriendlyPlayers", "nameplateShowFriends" } X.friendlyPlateNamesCVar = "nameplateShowOnlyNameForFriendlyPlayerUnits" diff --git a/BuffRadar/Debuffs.lua b/BuffRadar/Debuffs.lua index 7e3a4e7..1775a50 100644 --- a/BuffRadar/Debuffs.lua +++ b/BuffRadar/Debuffs.lua @@ -17,17 +17,16 @@ local function Tuple(...) return select("#", ...), ... end local function Legacy(lookup, unit, index) return Tuple(lookup(unit, index)) end -- An explicit nil at the end of a list is different from a refused read. --- The same guarded exact-ID reader is used for the personal consumable check. -function D.ReadAura(unit, index, harmful) - local modern = C_UnitAuras and (harmful and C_UnitAuras.GetDebuffDataByIndex or not harmful and C_UnitAuras.GetBuffDataByIndex) +local function ReadDebuff(unit, index) + local modern = C_UnitAuras and C_UnitAuras.GetDebuffDataByIndex local indexed = C_UnitAuras and C_UnitAuras.GetAuraDataByIndex local ok, id, name, icon, stacks if modern or indexed then - local aura, answered = X.QueryAura(modern or indexed, unit, index, harmful and "HARMFUL" or "HELPFUL") + local aura, answered = X.QueryAura(modern or indexed, unit, index, "HARMFUL") if not aura then return true, answered end ok, id, name, icon, stacks = pcall(Fields, aura) else - local legacyLookup = harmful and UnitDebuff or not harmful and UnitBuff + local legacyLookup = UnitDebuff if type(legacyLookup) ~= "function" then return true, false end local read, count, label, image, applications, _, _, _, _, _, _, spell = pcall(Legacy, legacyLookup, unit, index) if not read or count == 0 then return true, false end @@ -104,7 +103,7 @@ local function Scan(unit) Wipe(result) if X.PlayerSuspended() or not Watches(unit) or not X.UnitPresent(unit) then return end for i = 1, 40 do - local done, _, spell, name, icon, stacks = D.ReadAura(unit, i, true) + local done, _, spell, name, icon, stacks = ReadDebuff(unit, i) if done then break end if spell then for j, rule in ipairs(db.debuffRules) do @@ -127,20 +126,27 @@ function D.Clear() end end -function D.Refresh() - if not listening then return end +local function RefreshAll() Wipe(pending) Scan("player") Scan("focus") Draw() end -local function RefreshUnit(unit) +function D.Refresh() + if listening then X.Measure(InCombatLockdown() and "combatDebuff" or "debuff", RefreshAll) end +end + +local function RefreshOne(unit) pending[unit] = nil Scan(unit) Draw() end +local function RefreshUnit(unit) + X.Measure(InCombatLockdown() and "combatDebuff" or "debuff", RefreshOne, unit) +end + local function OnEvent(_, event, unit) if not listening then return end if event == "PLAYER_FOCUS_CHANGED" then @@ -233,10 +239,9 @@ X.ext.debuff = function(rest) local id, unit, boss = args:match("^(%d+)%s*(%a*)%s*(%d*)$") unit = unit == "" and "player" or unit if (action == "on" or action == "off") and args == "" then - db.debuffWatch = action == "on" + X.SetPreference("debuffWatch", action == "on") Print(string.format(L["Debuff watch: %s"], L[db.debuffWatch and "On" or "Off"])) if db.debuffWatch and db.liteMode then Print(L["Debuff watch is paused in Lite mode."]) end - D.Apply() elseif action == "add" and id then if D.SetRule(tonumber(id), unit, boss == "" and 0 or tonumber(boss)) then Print(L["Debuff rule saved."]) end elseif action == "remove" and id and boss == "" then diff --git a/BuffRadar/Extras.lua b/BuffRadar/Extras.lua index 50154d2..89e46e7 100644 --- a/BuffRadar/Extras.lua +++ b/BuffRadar/Extras.lua @@ -87,7 +87,7 @@ local function BuildNearby() local title = Label("GameFontNormalLarge", -12) title:SetPoint("TOPRIGHT", -32, -12) title:SetText(L["Nearby Player Diagnostics"]) - local close = CreateFrame("Button", nil, f, "UIPanelCloseButton") + local close = X.PanelWidget("Button", nil, f, "UIPanelCloseButton") close:SetPoint("TOPRIGHT", -3, -3) close:SetScript("OnClick", function() f:Hide() end) f.nameplates = Label("GameFontHighlight", -45) @@ -95,7 +95,7 @@ local function BuildNearby() local targetTitle = Label("GameFontNormal", -92) targetTitle:SetText(L["Current Target"]) - local scroll = CreateFrame("ScrollFrame", "BuffRadarNearbyScroll", f, "UIPanelScrollFrameTemplate") + local scroll = X.PanelWidget("ScrollFrame", "BuffRadarNearbyScroll", f, "UIPanelScrollFrameTemplate") scroll:SetPoint("TOPLEFT", 14, -112) scroll:SetPoint("BOTTOMRIGHT", -30, 108) local child = CreateFrame("Frame", nil, scroll) @@ -113,7 +113,7 @@ local function BuildNearby() f.message:SetJustifyV("TOP") local function PlateButton(width, point, x, y, chooseMode) - local btn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate") + local btn = X.PanelWidget("Button", nil, f, "UIPanelButtonTemplate") btn:SetSize(width, 22) btn:SetPoint(point, x, y) btn:SetScript("OnClick", function() @@ -137,7 +137,7 @@ local function BuildNearby() f.restorePlates = PlateButton(176, "BOTTOMRIGHT", -14, 42, function() return "restore" end) f.restorePlates:SetText(L["Restore Nameplates"]) - local refresh = CreateFrame("Button", nil, f, "UIPanelButtonTemplate") + local refresh = X.PanelWidget("Button", nil, f, "UIPanelButtonTemplate") refresh:SetSize(110, 22) refresh:SetPoint("BOTTOMRIGHT", -14, 12) refresh:SetText(L["Refresh"]) @@ -381,10 +381,8 @@ function X.IgnoreImport(text) name = name:gsub("^%s+", ""):gsub("%s+$", "") if X.Ignore.Valid(name) then names[#names + 1] = name end end - local added = 0 - for _, name in ipairs(names) do - if X.Ignore.Add(name) then added = added + 1 end - end + local added, err = X.Ignore.AddMany(names) + if not added then return false, err end local seen = #names if X.Refresh then X.Refresh() end return true, string.format("Ignore list: %d added, %d already there.", added, seen - added) @@ -432,10 +430,14 @@ end -- /br perf: scan cost and memory, so the budgets have in-game evidence. --------------------------------------------------------------------------- function X.PerfReport() - local pf = X.perf - if not pf or pf.n == 0 then Print("Perf: no scans timed yet (needs debugprofilestop)."); return end - Print(string.format("Perf: %d scans · average %.2f ms · last %.2f ms · worst %.2f ms", - pf.n, pf.total / pf.n, pf.last, pf.max)) + for _, key in ipairs({ "scan", "prepare", "import", "debuff", "combatDebuff" }) do + local t = X.timings[key] + if t.n > 0 then + Print(string.format("Perf: %s · %d samples · CPU average %.2f ms · last %.2f ms · worst %.2f ms", + key, t.n, t.total / t.n, t.last, t.max)) + end + end + if not debugprofilestop then Print("Perf: CPU timing unavailable (needs debugprofilestop).") end local probe = X.auraProbe if probe and probe.seen then Print(string.format("Perf: UNIT_AURA payloads %d · skipped by fast aura %d", @@ -449,53 +451,12 @@ end --------------------------------------------------------------------------- -- Settings diff: what applying a settings string would change. --------------------------------------------------------------------------- -local function Parse(text) - local out = {} - if type(text) ~= "string" then return out end - for part in (text .. ";"):gmatch("(.-);") do - local k, v = part:match("^(.-)=(.*)$") - if k then out[k] = v end - end - return out -end - function X.SettingsDiff(text, named) - if type(text) ~= "string" then return nil, "Not a BuffRadar settings string." end - local profile = text:match("^BR2;") ~= nil - local patch, body - if profile or named then - patch, body = X.ParseProfile(text), text - else - patch, body = X.ParseSettingsImport(text) - end - if not patch then return nil, "Not a complete, valid BuffRadar settings string." end - local current, err - if profile then - current = X.ProfileSnapshot() - if not current then return nil, "Current settings exceed the profile size limit." end - else - current, err = X.Export() - if not current then return nil, err end - end - local want, have = Parse(body), Parse(current) - if patch.assumeRange == false and want.assumeRange == nil then want.assumeRange = "0" end - local lines = {} - local keys = {} - for k in pairs(want) do keys[k] = true end - for k in pairs(have) do keys[k] = true end - local names = {} - for k in pairs(keys) do names[#names + 1] = k end - table.sort(names) - for _, k in ipairs(names) do - local map = k:match("^(%a+)%.") - if (map and patch[map] ~= nil) or patch[k] ~= nil then - local a, b = have[k], want[k] - if a ~= b then - lines[#lines + 1] = string.format("%s: %s -> %s", k, tostring(a), tostring(b)) - end - end - end - return lines + if type(text) ~= "string" then return nil, L["Paste a complete, valid BuffRadar settings export."] end + local patch + if named or text:match("^BR2;") then patch = X.ParseProfile(text) else patch = X.ParseSettingsImport(text) end + if not patch then return nil, L["Paste a complete, valid BuffRadar settings export."] end + return X.ReviewSettings(patch) end function X.PrintDiff(text, label, named) @@ -554,25 +515,88 @@ end X.pullProbe = { stSeen = 0, stTypes = {}, d5 = 0 } X.pull = nil -function X.PullStart(secs, source) - if not X.Readable(secs) or type(secs) ~= "number" or not (secs >= 0 and secs <= 600) then return end - if secs == 0 then - if X.pull and X.pull.source == source then - X.pull = nil - X.Core.QueueRefresh() - end - return +local function PullScope() + return X.InRaid() and "RAID" or X.InGroup() and "PARTY" or "solo" +end + +local function PullOwnerPresent(owner) + if not owner or X.UnitGUIDOf("player") == owner then return true end + local present = false + X.ForReportRoster(function(unit, exists) + if exists and X.UnitGUIDOf(unit) == owner then present = true end + end) + return present +end + +local function StopPull(source, owner, timerID) + local active = X.pull + if active and active.source == source and active.owner == owner and active.scope == PullScope() + and not active.ambiguousStop and active.timerID == timerID and PullOwnerPresent(owner) + and (source ~= "boss mod" or timerID ~= nil) + and (owner or active.scope == "solo" or active.membership == X.GroupIdentity()) then + X.pull = nil + X.Core.QueueRefresh() + end +end + +local function FinishPull(pull) + if X.pull ~= pull then return end + X.pull = nil + if not pull.forecastOnly and X.GetDB().pullFlash and X.Flash then X.Flash() end + X.Core.QueueRefresh() +end + +-- The existing throttled ticker owns expiry on clients without C_Timer. +function X.TickPull() + local pull = X.pull + if not pull or (C_Timer and C_Timer.After) then return end + local left = pull.endsAt - GetTime() + if left <= 0 then FinishPull(pull) + elseif left <= 3 and not pull.warned and not pull.forecastOnly then + pull.warned = true + if X.GetDB().pullFlash and X.Flash then X.Flash() end end +end + +function X.CheckPullRoster() + local pull = X.pull + if not pull then return end + local trusted = not pull.sender or X.SenderTrusted(pull.sender) + local membership = not pull.owner and X.GroupIdentity() or nil + if pull.scope ~= PullScope() or not trusted or not PullOwnerPresent(pull.owner) + or (not pull.owner and pull.membership ~= membership) then + X.pull = nil + X.Core.QueueRefresh() + end +end + +function X.PullStart(secs, source, owner, timerID, sender) + if not X.Readable(secs) or type(secs) ~= "number" or not (secs >= 0 and secs <= 600) then return end + if secs == 0 then StopPull(source, owner, timerID); return end local db = X.GetDB() if not db or (not db.pullFlash and not X.Intel.ForecastEnabled()) then return end - if InCombatLockdown() or X.PlayerSuspended() then return end + if InCombatLockdown() or X.PlayerSuspended() or not PullOwnerPresent(owner) then return end local casts = 0 if db.pullFlash then for _, tt in pairs(X.tally or {}) do casts = casts + (tt.miss or 0) end end local flash = casts > 0 if not flash and not X.Intel.ForecastEnabled() then return end - local pull = { endsAt = GetTime() + secs, source = source, forecastOnly = not flash } + local now, scope, previous = GetTime(), PullScope(), X.pull + local membership = not owner and X.GroupIdentity() or nil + if not owner and scope ~= "solo" and not membership then return end + local ends = now + secs + local sameSource = previous and previous.source == source and previous.scope == scope and previous.endsAt > now + if sameSource and math.abs(previous.endsAt - ends) < 0.75 and (not previous.owner or not owner or previous.owner == owner) + and previous.timerID == timerID then + if owner then previous.owner, previous.sender = owner, sender end + return -- paired native notifications or repeat of an already running timer + end + local ambiguous = sameSource and previous.owner == owner + and (not previous.timerID or not timerID or previous.timerID == timerID) + local pull = { endsAt = ends, source = source, forecastOnly = not flash, owner = owner, + timerID = timerID, sender = sender, scope = scope, ambiguousStop = ambiguous, + membership = membership } X.pull = pull if flash then Print(string.format("Pull in %ds (%s) -- %d casts still needed.", secs, source, casts)) @@ -585,17 +609,11 @@ function X.PullStart(secs, source) if X.pull == pull and db.pullFlash and X.Flash then X.Flash() end end) end - C_Timer.After(secs, function() - if X.pull == pull then - X.pull = nil - if flash and db.pullFlash and X.Flash then X.Flash() end - X.Core.QueueRefresh() - end - end) + C_Timer.After(secs, function() FinishPull(pull) end) end end -do +if X.supported then local pf = CreateFrame("Frame") X.pullFrame = pf pf:RegisterEvent("ADDON_LOADED") @@ -604,7 +622,7 @@ do pcall(pf.RegisterEvent, pf, event) end pf:RegisterEvent("CHAT_MSG_ADDON") - pf:SetScript("OnEvent", function(_, ev, a1, a2, _, a4) + pf:SetScript("OnEvent", function(_, ev, a1, a2, a3, a4) local probe = X.pullProbe if ev == "ADDON_LOADED" then if a1 == "BuffRadar" then @@ -620,19 +638,26 @@ do if X.Readable(a1) and type(a1) == "number" and a1 >= 0 and a1 <= 10 then probe.stTypes[a1] = true end if X.Readable(a1) and a1 == playerCountdown then X.PullStart(a2, "countdown") end elseif ev == "START_PLAYER_COUNTDOWN" then - -- Unlike START_TIMER, the first argument is the initiator's GUID. - X.PullStart(a2, "countdown") - elseif ev == "CANCEL_PLAYER_COUNTDOWN" or (ev == "STOP_TIMER_OF_TYPE" and X.Readable(a1) and a1 == playerCountdown) then - X.PullStart(0, "countdown") + -- Native IDful stops carry the initiator's GUID, not a timer number. + local guid = X.Core.SafeString(a1) + if guid and guid ~= "" and #guid <= 85 then X.PullStart(a2, "countdown", guid) end + elseif ev == "CANCEL_PLAYER_COUNTDOWN" then + local guid = X.Core.SafeString(a1) + if guid and guid ~= "" then StopPull("countdown", guid) end + elseif ev == "STOP_TIMER_OF_TYPE" and X.Readable(a1) and a1 == playerCountdown then + StopPull("countdown") elseif ev == "CHAT_MSG_ADDON" and X.Readable(a1) and a1 == "D5" - and type(a2) == "string" and X.Readable(a2) then + and type(a2) == "string" and X.Readable(a2) and #a2 <= 255 then local sub, rest = a2:match("^(%u+)%s+(.+)$") if sub == "PT" then probe.d5 = probe.d5 + 1 - local secs = tonumber(rest:match("^(%d+)%f[%s%z]")) - if secs and X.SenderTrusted and X.SenderTrusted(a4) then - X.PullStart(secs, "boss mod") - end + if not X.Readable(a3) or a3 == "solo" or a3 ~= PullScope() then return end + local secs, map = rest:match("^(%d+)\t(%d+)$") + secs = secs or rest:match("^(%d+)$") + if not secs then return end + local unit, sender = X.SenderUnit(a4) + local owner = unit and X.SenderTrusted(a4) and X.UnitGUIDOf(unit) + if owner then X.PullStart(tonumber(secs), "boss mod", owner, map ~= "" and map or nil, sender) end end return end @@ -654,4 +679,4 @@ X.ext.diff = function(rest) X.PrintDiff(rest, "That string") end -X.InitEditMode() +if X.supported then X.InitEditMode() end diff --git a/BuffRadar/Forever.lua b/BuffRadar/Forever.lua new file mode 100644 index 0000000..6981027 --- /dev/null +++ b/BuffRadar/Forever.lua @@ -0,0 +1,3 @@ +-- Loaded only by the shipped Forever TOC, before the shared data and settings. +local _, ns = ... +ns.ForeverInterface = 16001 diff --git a/BuffRadar/Intelligence.lua b/BuffRadar/Intelligence.lua index 1b0faa7..3259ed9 100644 --- a/BuffRadar/Intelligence.lua +++ b/BuffRadar/Intelligence.lua @@ -176,16 +176,34 @@ function I.MemoryReport() Print(I.PaceText()) end -function I.SettingsChanged() - if not I.ForecastEnabled() then - manualDeadline, noticedSpell, noticedEnd, notifyAfter = nil, nil, nil, 0 - if X.pull and X.pull.forecastOnly then X.pull = nil end +function X.SettingsChanged(changed) + local lite = changed.liteMode + if changed.forecastSeconds or lite then + I.ForgetAlerts() + if not I.ForecastEnabled() then + manualDeadline, noticedSpell, noticedEnd, notifyAfter = nil, nil, nil, 0 + end end - if db.liteMode and X.CloseRaidPreparation then X.CloseRaidPreparation() end - if X.Debuffs then X.Debuffs.Apply() end - if X.UpdateMinimapStatus then X.UpdateMinimapStatus() end - if X.TickMinimapPulse then X.TickMinimapPulse() end - X.Core.QueueRefresh() + if X.pull and (changed.pullFlash or changed.forecastSeconds or lite) and not I.ForecastEnabled() + and (not db.pullFlash or X.pull.forecastOnly) then X.pull = nil end + if changed.smartPriority and not db.smartPriority then wipeUntil = 0 end + if lite and db.liteMode and X.CloseRaidPreparation then X.CloseRaidPreparation() end + if lite or changed.debuffWatch or changed.debuffRules then X.Debuffs.Apply() end + if (lite or changed.statusMinimap) and X.UpdateMinimapStatus then X.UpdateMinimapStatus() end + if (lite or changed.visualAlerts) and X.TickMinimapPulse then X.TickMinimapPulse() end + if changed.readinessAura and X.QueuePersonalReadiness then X.QueuePersonalReadiness() end + if changed.sync then + X.CheckLegacyAuthority(not db.sync) + if not db.sync then X.StopCoordination() end + end + if changed.forecastSeconds or changed.pullFlash or lite or changed.smartPriority or changed.scanThrottle + or changed.profile then X.Core.QueueRefresh() end +end + +function X.SetPreference(key, value) + if db[key] == value then return end + db[key] = value + X.SettingsChanged({ [key] = true }) end function I.SetForecast(seconds) @@ -193,9 +211,7 @@ function I.SetForecast(seconds) Print(L["Enter a forecast time from 0 to 300 seconds (0 turns it off)."]) return false end - I.ForgetAlerts() - db.forecastSeconds = seconds - I.SettingsChanged() + X.SetPreference("forecastSeconds", seconds) return true end @@ -255,10 +271,8 @@ X.ext.smartprio = function(rest) local here = input:match("^here%s+(%S+)$") local id, key = input:match("^instance%s+(%d+)%s+(%S+)$") if input == "" or input == "on" or input == "off" then - db.smartPriority = input == "on" or (input == "" and not db.smartPriority) - if not db.smartPriority then wipeUntil = 0 end + X.SetPreference("smartPriority", input == "on" or (input == "" and not db.smartPriority)) Print(string.format(L["Smart priority: %s"], L[db.smartPriority and "On" or "Off"])) - X.Core.QueueRefresh() elseif here or id then local instance = here and I.InstanceID() or tonumber(id) if I.SetInstancePriority(instance, here or key) then @@ -281,9 +295,8 @@ local function Toggle(setting, label, usage) return function(rest) local value = rest:lower() if value ~= "" and value ~= "on" and value ~= "off" then Print(usage); return true end - db[setting] = value == "on" or (value == "" and not db[setting]) + X.SetPreference(setting, value == "on" or (value == "" and not db[setting])) Print(string.format(label, L[db[setting] and "On" or "Off"])) - I.SettingsChanged() if X.RefreshConfig then X.RefreshConfig() end return true end diff --git a/BuffRadar/Locales/deDE.lua b/BuffRadar/Locales/deDE.lua index c0f6e80..8ce5ef6 100644 --- a/BuffRadar/Locales/deDE.lua +++ b/BuffRadar/Locales/deDE.lua @@ -14,6 +14,96 @@ local _, NS = ... NS.Locales = NS.Locales or {} NS.Locales.deDE = { + ["Group chat send requested; delivery is not confirmed."] = "Senden an den Gruppenchat angefordert; Zustellung nicht bestätigt.", + ["the party"] = "die Gruppe", + ["the raid"] = "den Schlachtzug", + ["Apply and share sends changed assignments and blessings to %s."] = "Anwenden und teilen sendet geänderte Aufgaben und Segen an %s.", + ["Compared with your current settings (not applied):"] = "Vergleich mit den aktuellen Einstellungen (nicht angewendet):", + ["Group spell range could not be confirmed."] = "Die Reichweite des Gruppenzaubers ließ sich nicht bestätigen.", + ["No eligible group target."] = "Kein geeignetes Gruppenziel.", + ["Can't open that during combat."] = "Das lässt sich im Kampf nicht öffnen.", + ["Delete"] = "Löschen", + ["Load"] = "Laden", + ["Save"] = "Speichern", + ["Save window, alert and buff preferences to load here or with /br profile."] = "Fenster-, Alarm- und Buff-Einstellungen hier oder mit /br profile speichern und laden.", + ["Settings profiles"] = "Einstellungsprofile", + ["Share BR2"] = "BR2 teilen", + ["Import"] = "Importieren", + ["Open the BuffRadar section of the game's key bindings."] = "Öffne den BuffRadar-Abschnitt der Tastenbelegung.", + ["Create macro"] = "Makro erstellen", + ["Set keybind"] = "Taste belegen", + ["Keybinds"] = "Tastenbelegung", + ["Open Game Menu > Options > Keybindings and look for the BuffRadar section."] = "Öffne Spielmenü > Optionen > Tastenbelegung und suche den Abschnitt BuffRadar.", + ["Can't open key bindings during combat."] = "Tastenbelegung ist im Kampf nicht verfügbar.", + ["not bound"] = "nicht belegt", + ["Mute / unmute sound"] = "Ton ein-/ausschalten", + ["Show / hide window"] = "Fenster ein-/ausblenden", + ["Cast next group buff"] = "Nächsten Gruppenbuff wirken", + ["Cast next buff"] = "Nächsten Buff wirken", + ["Remember panel positions: %s"] = "Fensterpositionen merken: %s", + ["Use /br positions on|off|reset."] = "Nutze /br positions on|off|reset.", + ["Reset panel positions"] = "Fensterpositionen zurücksetzen", + ["Remember Settings and Ready Check positions"] = "Position von Einstellungen und Bereitschaftscheck merken", + ["Profile storage is full. Delete a profile first."] = "Der Profilspeicher ist voll. Lösche zuerst ein Profil.", + ["Ignore list is full. Remove entries first."] = "Die Ignorierliste ist voll. Entferne zuerst Einträge.", + ["Profiles: %d/%d · Ignores: %d/%d"] = "Profile: %d/%d · Ignoriert: %d/%d", + ["No matching entry in an oversized save."] = "Kein passender Eintrag in einem zu großen Speicherstand.", + ["Removed from the preserved save. Reload to try normal saving again."] = "Aus den bewahrten Daten entfernt. Lade neu, um wieder normal zu speichern.", + ["Use /br storage delete profile or /br storage delete ignore , then reload."] = "Nutze /br storage delete profile oder /br storage delete ignore und lade dann neu.", + ["Too many profiles or ignores. The original save was preserved; changes are temporary."] = "Zu viele Profile oder ignorierte Namen. Die Originaldaten bleiben erhalten; Änderungen sind vorläufig.", + ["Local only — not sent: %s"] = "Nur lokal – nicht gesendet: %s", + ["Game accepted the group chat send; delivery is not confirmed."] = "Das Spiel hat die Gruppennachricht angenommen. Zustellung nicht bestätigt.", + ["The game did not accept the send."] = "Das Spiel hat die Sendung nicht angenommen.", + ["The message exceeds the chat limit."] = "Die Nachricht überschreitet das Chat-Limit.", + ["Group chat is unavailable."] = "Gruppenchat ist nicht verfügbar.", + ["No group channel."] = "Kein Gruppenkanal.", + ["Group-cast pair limit reached. Remove a pair first."] = "Limit für Gruppenzauberpaare erreicht. Entferne zuerst ein Paar.", + ["Invalid group-cast pair; nothing changed."] = "Ungültiges Gruppenzauberpaar. Nichts geändert.", + ["Applicability unknown"] = "Anwendbarkeit unbekannt", + ["Not applicable"] = "Nicht anwendbar", + ["%d unknown"] = "%d unbekannt", + ["Some world buff information is unavailable."] = "Einige Informationen zu Weltbuffs fehlen.", + ["Use a named BR2 profile to share newer preferences."] = "Verwende ein benanntes BR2-Profil, um neuere Einstellungen zu teilen.", + ["Group sharing is unavailable for this review."] = "Das Teilen mit der Gruppe ist für diese Prüfung nicht verfügbar.", + ["Auto-profile mappings stay local, even when sharing."] = "Auto-Profil-Zuordnungen bleiben auch beim Teilen lokal.", + ["Group plan copy (select all, copy)"] = "Gruppenplankopie (alles auswählen und kopieren)", + ["Paste a group plan, then review."] = "Füge einen Gruppenplan ein und prüfe ihn.", + ["Paste a shared profile, then review."] = "Füge ein geteiltes Profil ein und prüfe es.", + ["Legacy BR1 settings copy (select all, copy)"] = "Alte BR1-Einstellungskopie (alles auswählen und kopieren)", + ["Paste a legacy BR1 settings copy, then review."] = "Füge eine alte BR1-Einstellungskopie ein und prüfe sie.", + ["Store as %s without loading its settings."] = "Unter %s speichern, ohne die Einstellungen zu laden.", + ["Auto-profile mappings using this name: %s"] = "Auto-Profil-Zuordnungen für diesen Namen: %s", + ["Existing profile: %s. Enter a different name to keep it."] = "Vorhandenes Profil: %s. Gib einen anderen Namen ein, um es zu behalten.", + ["The current values changed. Review again before applying."] = "Die aktuellen Werte haben sich geändert. Prüfe sie vor dem Anwenden erneut.", + ["No settings or plan values would change."] = "Keine Einstellungen oder Planwerte würden sich ändern.", + ["Review before applying"] = "Vor dem Anwenden prüfen", + ["Import canceled."] = "Import abgebrochen.", + ["Save profile"] = "Profil speichern", + ["Replace profile"] = "Profil ersetzen", + ["Apply and share"] = "Anwenden und teilen", + ["Apply locally"] = "Lokal anwenden", + ["Review import"] = "Import prüfen", + ["Edit paste"] = "Text bearbeiten", + ["These settings are too large to save as a profile."] = "Diese Einstellungen sind zu groß für ein Profil.", + ["Profile stored: %s (not loaded)."] = "Profil gespeichert: %s (nicht geladen).", + ["That profile already exists or changed. Review it, rename, or explicitly replace it."] = "Das Profil existiert bereits oder wurde geändert. Prüfe es, benenne es um oder ersetze es ausdrücklich.", + ["Profile names use letters, numbers, - and _ (max 40)."] = "Profilnamen nutzen Buchstaben, Zahlen, - und _ (max. 40).", + ["The profile's settings string is damaged."] = "Die Einstellungszeichenfolge des Profils ist beschädigt.", + ["That doesn't look like a shared BuffRadar profile."] = "Das ist kein geteiltes BuffRadar-Profil.", + ["That shared profile is too large."] = "Dieses geteilte Profil ist zu groß.", + ["Game accepted %d of %d sends; delivery is not confirmed."] = "Das Spiel hat %d von %d Sendungen angenommen. Zustellung nicht bestätigt.", + ["Plan applied locally: %d assignments, %d blessings, %d auto profiles."] = "Plan lokal angewendet: %d Zuweisungen, %d Segen, %d Autoprofile.", + ["Group or sharing permission changed. Review the plan again."] = "Gruppe oder Freigaberecht hat sich geändert. Prüfe den Plan erneut.", + ["Missing profile for %s: %s"] = "Fehlendes Profil für %s: %s", + ["Settings applied locally."] = "Einstellungen lokal angewendet.", + ["Paste a complete, valid BuffRadar plan export."] = "Füge einen vollständigen, gültigen BuffRadar-Plan ein.", + ["Paste a complete, valid BuffRadar settings export."] = "Füge einen vollständigen, gültigen BuffRadar-Einstellungsexport ein.", + ["That import exceeds 16 KiB."] = "Der Import überschreitet 16 KiB.", + ["Nothing to import."] = "Nichts zu importieren.", + ["Can't move the buff window during combat."] = "Das Buff-Fenster lässt sich im Kampf nicht verschieben.", + ["Buff scan interrupted. Waiting for a fresh scan."] = "Buff-Prüfung unterbrochen. Warte auf eine neue Prüfung.", + ["A newer BuffRadar save was preserved. Changes are for this session only."] = "Neuere BuffRadar-Einstellungen wurden bewahrt. Änderungen gelten nur für diese Sitzung.", + ["BuffRadar requires the Forever package on Interface 16001. Casting is disabled."] = "BuffRadar benötigt das Forever-Paket mit Interface 16001. Zauber sind deaktiviert.", ["Find"] = "Suchen", ["Find in this tab (Esc to close)"] = "In diesem Tab suchen (Esc schließt)", ["Matches: %d"] = "Treffer: %d", diff --git a/BuffRadar/Minimap.lua b/BuffRadar/Minimap.lua index 0ae780c..75bd736 100644 --- a/BuffRadar/Minimap.lua +++ b/BuffRadar/Minimap.lua @@ -74,6 +74,10 @@ local function PositionMinimapButton() minimapBtn:SetPoint("CENTER", Minimap, "CENTER", math.cos(angle) * rx, math.sin(angle) * ry) end +local function StopMinimapDrag(self) + self:SetScript("OnUpdate", nil) +end + local function RefreshMinimapButton() if not minimapBtn then return end if db and db.showMinimap and not X.PlayerSuspended() then @@ -83,7 +87,7 @@ local function RefreshMinimapButton() else pulseEnd = nil minimapBtn.pulse:Hide() - minimapBtn.dragging = false + StopMinimapDrag(minimapBtn) minimapBtn:Hide() end end @@ -135,10 +139,8 @@ local function BuildMinimapButton() -- right-click-for-settings in the tooltip never fired. b:RegisterForClicks("LeftButtonUp", "RightButtonUp") b:SetScript("OnClick", OnClick) - b:SetScript("OnDragStart", function(self) self.dragging = true end) - b:SetScript("OnDragStop", function(self) self.dragging = false end) - b:SetScript("OnUpdate", function(self) - if not self.dragging or not db then return end + local function DragUpdate(self) + if X.PlayerSuspended() or not db then StopMinimapDrag(self); return end local mx, my = Minimap:GetCenter() if not mx or not my then return end local cx, cy = GetCursorPosition() @@ -148,7 +150,12 @@ local function BuildMinimapButton() local atan2 = math.atan2 or math.atan db.minimapAngle = math.deg(atan2((cy - my) / ry, (cx - mx) / rx)) % 360 PositionMinimapButton() + end + b:SetScript("OnDragStart", function(self) + if db and not X.PlayerSuspended() and self:IsVisible() then self:SetScript("OnUpdate", DragUpdate) end end) + b:SetScript("OnDragStop", StopMinimapDrag) + b:SetScript("OnHide", StopMinimapDrag) minimapBtn = b if Minimap.HookScript then Minimap:HookScript("OnSizeChanged", PositionMinimapButton) end RefreshMinimapButton() diff --git a/BuffRadar/Profiles.lua b/BuffRadar/Profiles.lua index 410ac63..a86933b 100644 --- a/BuffRadar/Profiles.lua +++ b/BuffRadar/Profiles.lua @@ -3,6 +3,8 @@ local _, ns = ... local X = ns.X +local L = X.L +local wipe = wipe or function(t) for k in pairs(t) do t[k] = nil end end local settings = X.Settings local BLESSINGS, DEFAULTS, Ignore = X.BLESSINGS, settings.Defaults, X.Ignore @@ -31,10 +33,10 @@ local function Esc(v) return (tostring(v):gsub("%%", "%%25"):gsub(";", "%%3B"):g local function Unesc(v) return (v:gsub("%%3D", "="):gsub("%%3B", ";"):gsub("%%25", "%%")) end local function ClipboardText(text) - if type(text) ~= "string" then return nil, "Nothing to import." end - if #text > CLIPBOARD_MAX_BYTES then return nil, "That import exceeds 16 KiB." end + if type(text) ~= "string" then return nil, L["Nothing to import."] end + if #text > CLIPBOARD_MAX_BYTES then return nil, L["That import exceeds 16 KiB."] end text = text:match("^%s*(.-)%s*$") - if text == "" then return nil, "Nothing to import." end + if text == "" then return nil, L["Nothing to import."] end return text end @@ -108,7 +110,7 @@ do end for _, key in ipairs({ "compact", "textScale", "charPoint", "pauseInBG", "pauseTaxi", "watchDrop", - "minimapAngle", "rangeText", "pinned", "thornsAnyClassOutdoors", "blessingComplement", + "minimapAngle", "pinned", "thornsAnyClassOutdoors", "blessingComplement", }) do scalarKeys[key] = true scalarList[#scalarList + 1] = key @@ -194,13 +196,23 @@ do end end + local function BoundedMapMember(map, member) + if map == "ignored" then return settings.ValidIgnore(member) end + if map == "enabled" or map == "rebuffPer" or map == "buffContext" then + return #member <= 40 and member:match("^[A-Z0-9_]+$") + end + if map == "specScales" then return member:match("^s[1-4]$") end + if map == "coverParts" then return settings.PlainString(member, 24) end + return true + end + local function ParseProfile(body, directImport) if type(body) ~= "string" or #body > (directImport and CLIPBOARD_MAX_BYTES or PROFILE_MAX_BYTES) then return nil end local version, payload = body:match("^(BR[12]);(.+)$") if not version or (directImport and version ~= "BR1") then return nil end local modern = version == "BR2" local patch, count, scalarFields, priorityKeys = {}, 0, {}, {} - local assignments = {} + local assignments, sizes = {}, {} if modern then for map in pairs(profileMaps) do patch[map] = {} end end @@ -225,7 +237,12 @@ do patch.assignmentEnabled, scalarFields[key] = raw == "1", true elseif kind and (modern or legacyMaps[map]) then member = DecodeString(member) - if not member or member == "" then return nil end + if not member or member == "" or not BoundedMapMember(map, member) then return nil end + local limit = settings.Limits[map] + if limit then + sizes[map] = (sizes[map] or 0) + 1 + if sizes[map] > limit then return nil end + end patch[map] = patch[map] or {} if map == "buffPrio" then member = Number(member) @@ -305,6 +322,9 @@ do for map in pairs(legacyMaps) do patch[map] = patch[map] or {} end end end + for _, key in ipairs({ "enabled", "rebuffPer", "ignored", "specScales", "buffContext", "coverParts" }) do + if patch[key] and settings.Count(patch[key]) > settings.Limits[key] then return nil end + end return patch end @@ -314,28 +334,47 @@ do local body, err = ClipboardText(text) if not body then return nil, err end local patch = ParseProfile(body, true) - if not patch then return nil, "Paste a complete, valid BuffRadar settings export." end + if not patch then return nil, L["Paste a complete, valid BuffRadar settings export."] end return patch, body end + local function Changes(dst, path, before, after) + if before == after then return end + if type(before) == "table" or type(after) == "table" then + before = type(before) == "table" and before or {} + after = type(after) == "table" and after or {} + for k, v in pairs(before) do Changes(dst, path .. "." .. k, v, after[k]) end + for k, v in pairs(after) do if before[k] == nil then Changes(dst, path .. "." .. k, nil, v) end end + else + dst[#dst + 1] = string_format("%s: %s → %s", path, tostring(before), tostring(after)) + end + end + + function X.ReviewSettings(patch) + local db, lines = X.GetDB(), {} + local candidate = settings.PreparePatch(db, patch) + for key in pairs(patch) do Changes(lines, key, db[key], candidate[key]) end + table_sort(lines) + return lines + end + function X.ApplyProfile(patch) local db = X.GetDB() - local syncWasEnabled, featuresChanged = db.sync, false - -- Normalize the complete proposed state before changing the live settings. - local candidate = {} - for key, value in pairs(db) do candidate[key] = value end - for key, value in pairs(patch) do candidate[key] = value end - settings.Sanitize(candidate) + local candidate = settings.PreparePatch(db, patch) + local changed, delta = {}, {} for key in pairs(patch) do - if featureScalars[key] and db[key] ~= candidate[key] then featuresChanged = true end - db[key] = candidate[key] + Changes(delta, key, db[key], candidate[key]) + if #delta > 0 then changed[key] = true end + wipe(delta) end - if featuresChanged then X.Intel.SettingsChanged() end - if syncWasEnabled and not db.sync then X.StopCoordination() end X.blockerProfileRevision = (X.blockerProfileRevision or 0) + 1 X.assignmentGroupConflicts = nil - X.prioDirty = true - Ignore.Rebuild() + if not next(changed) then return end + for key in pairs(changed) do db[key] = candidate[key] end + changed.profile = true + if changed.buffPrio then X.prioDirty = true end + if changed.ignored then Ignore.Rebuild() end + X.SettingsChanged(changed) X.ResolveAutoTheme() end end @@ -344,7 +383,7 @@ function X.Import(text) local patch, result = X.ParseSettingsImport(text) if not patch then return false, result end X.ApplyProfile(patch) - return true, "Settings imported." + return true, L["Settings applied locally."] end -- Buff plan strings (1.8.0): the group's plan — assignments, the @@ -400,7 +439,8 @@ local function ParsePlan(text) i = i + 3 elseif tag == "B" then local holder = fields[i + 3] and DecodeString(fields[i + 3]) - if not X.BLESSING_CLASSES[key] or not BLESSINGS[value] or not PlanHolder(holder) or blessings[key] then return nil end + if not X.BLESSING_CLASSES[key] or not BLESSINGS[value] or not PlanHolder(holder) + or holder:lower() == "none" or blessings[key] then return nil end blessings[key] = { key = value, name = holder } i = i + 4 elseif tag == "P" then @@ -414,47 +454,80 @@ local function ParsePlan(text) return assignments, blessings, auto end -function X.PlanImport(text) +function X.ParsePlanImport(text) local body, err = ClipboardText(text) - if not body then return false, err end + if not body then return nil, err end local assignments, blessings, auto = ParsePlan(body) - if not assignments then return false, "Paste a complete, valid BuffRadar plan export." end - if not (next(assignments) or next(blessings) or next(auto)) then - return true, "The imported plan has no entries. Nothing changed." - end + if not assignments then return nil, L["Paste a complete, valid BuffRadar plan export."] end + return { assignments = assignments, blessings = blessings, auto = auto } +end +function X.ReviewPlan(draft) + local lines, outbound = {}, {} local db = X.GetDB() - local myName = Ignore.UnitNames("player") - local nA, nB, nP = 0, 0, 0 - local outbound = {} - local inGroup = X.InGroup() - local share = inGroup and X.AmLead() - local _, myClass = UnitClass("player") - local shareBlessing = share or (inGroup and myClass == "PALADIN") - for key, value in pairs(assignments) do - if X.assign[key] ~= value and share then + for key, value in pairs(draft.assignments) do + local nextHolder = value:lower() ~= "none" and value or nil + if X.assign[key] ~= nextHolder then + lines[#lines + 1] = string_format("%s: %s → %s", key, X.assign[key] or "—", nextHolder or "—") outbound[#outbound + 1] = "ASSIGN;" .. key .. ";" .. value end - X.assign[key] = value - nA = nA + 1 end - for class, plan in pairs(blessings) do - local previous = X.blessPlan[class] - if shareBlessing and (not previous or previous.key ~= plan.key or previous.name ~= plan.name) then + for class, plan in pairs(draft.blessings) do + local before = X.blessPlan[class] + if not before or before.key ~= plan.key or before.name ~= plan.name then + lines[#lines + 1] = string_format("%s: %s → %s (%s)", class, + before and (before.key .. " (" .. before.name .. ")") or "—", plan.key, plan.name) outbound[#outbound + 1] = "BLESS;" .. class .. ";" .. plan.key .. ";" .. plan.name end - plan.mine = myName ~= nil and X.SameUser(plan.name, myName) - X.blessPlan[class] = plan + end + for context, name in pairs(draft.auto) do + if db.autoProfile[context] ~= name then + lines[#lines + 1] = string_format("%s: %s → %s", context, db.autoProfile[context] or "—", name) + end + if not db.profiles[name] then + lines[#lines + 1] = string_format(L["Missing profile for %s: %s"], context, name) + end + end + table_sort(lines) + table_sort(outbound) + local scope = db.sync and #outbound > 0 and X.GroupShareScope(outbound) or nil + return lines, outbound, scope +end + +function X.ApplyPlan(draft, shareScope) + local _, outbound, scope = X.ReviewPlan(draft) + if shareScope and shareScope ~= scope then return false, L["Group or sharing permission changed. Review the plan again."] end + local db = X.GetDB() + local myName = Ignore.UnitNames("player") + local nA, nB, nP = 0, 0, 0 + for key, value in pairs(draft.assignments) do + X.SetLocalPlan("ASSIGN", key, value:lower() ~= "none" and value or nil) + nA = nA + 1 + end + for class, plan in pairs(draft.blessings) do + X.SetLocalPlan("BLESS", class, { key = plan.key, name = plan.name, + mine = myName ~= nil and X.SameUser(plan.name, myName) }) nB = nB + 1 end - for context, name in pairs(auto) do + for context, name in pairs(draft.auto) do db.autoProfile[context] = name nP = nP + 1 end - for _, message in ipairs(outbound) do X.Broadcast(message) end - -- The import window repaints after successful commits. - return true, string_format("Plan imported: %d assignments, %d blessings, %d auto profiles.", - nA, nB, nP) + local sent = 0 + if shareScope then + for _, message in ipairs(outbound) do if X.Broadcast(message) then sent = sent + 1 end end + end + local outcome = string_format(L["Plan applied locally: %d assignments, %d blessings, %d auto profiles."], nA, nB, nP) + if shareScope then + outcome = outcome .. " " .. string_format(L["Game accepted %d of %d sends; delivery is not confirmed."], sent, #outbound) + end + return true, outcome +end + +function X.PlanImport(text) + local draft, err = X.ParsePlanImport(text) + if not draft then return false, err end + return X.ApplyPlan(draft) end -- Share a single profile (1.8.0): one named profile (not all your @@ -467,35 +540,56 @@ function X.ProfileShareText(name) return "BuffRadar profile: " .. name .. "\n" .. s end -function X.ProfileImport(text) - local db = X.GetDB() - if type(text) ~= "string" then return false, "Nothing to import." end +function X.ParseSharedProfile(text) + if type(text) ~= "string" then return nil, L["Nothing to import."] end if #text > PROFILE_MAX_BYTES + #"BuffRadar profile: " + 42 then - return false, "That shared profile is too large." + return nil, L["That shared profile is too large."] end local name, body = text:match("^BuffRadar profile: ([%w_%-]+)\r?\n(.+)$") if not IsProfileName(name) then - return false, "That doesn't look like a shared BuffRadar profile." + return nil, L["That doesn't look like a shared BuffRadar profile."] end body = body:match("^%s*(.-)%s*$") - if not X.ParseProfile(body) then - return false, "The profile's settings string is damaged." + local patch = X.ParseProfile(body) + if not patch then return nil, L["The profile's settings string is damaged."] end + return { name = name, body = body, patch = patch } +end + +function X.ProfileMappings(name) + local used = {} + for context, mapped in pairs(X.GetDB().autoProfile) do + if mapped == name then used[#used + 1] = context end end - db.profiles[name] = body - return true, "Profile imported: " .. name - .. " — /br profile load " .. name .. " applies it." + table_sort(used) + return used end -function X.SaveProfile(name) +function X.StoreProfile(name, body, reviewedBody) local db = X.GetDB() if not IsProfileName(name) then - return false, "Profile names use letters, numbers, - and _ (max 40)." + return false, L["Profile names use letters, numbers, - and _ (max 40)."] + end + if not X.ParseProfile(body) then return false, L["The profile's settings string is damaged."] end + if db.profiles[name] ~= reviewedBody then + return false, L["That profile already exists or changed. Review it, rename, or explicitly replace it."] + end + if not settings.CanAdd(db.profiles, "profiles", name) then + return false, L["Profile storage is full. Delete a profile first."] end - local body = X.ProfileSnapshot() - if not body then return false, "These settings are too large to save as a profile." end - if not X.ParseProfile(body) then return false, "The current settings cannot be saved as a profile." end db.profiles[name] = body - return true + return true, string_format(L["Profile stored: %s (not loaded)."], name) +end + +function X.ProfileImport(text, reviewedBody) + local draft, err = X.ParseSharedProfile(text) + if not draft then return false, err end + return X.StoreProfile(draft.name, draft.body, reviewedBody) +end + +function X.SaveProfile(name, reviewedBody) + local body = X.ProfileSnapshot() + if not body then return false, L["These settings are too large to save as a profile."] end + return X.StoreProfile(name, body, reviewedBody) end function X.LoadProfile(name) @@ -529,11 +623,8 @@ end -- so they compose with spec profiles and named profiles. function X.ApplyPreset(name) - local db = X.GetDB() local p = X.PRESETS[name] if not p then return false end - for k, v in pairs(p) do - if DEFAULTS[k] ~= nil and type(v) == type(DEFAULTS[k]) then db[k] = v end - end + X.ApplyProfile(p) return true end diff --git a/BuffRadar/Readiness.lua b/BuffRadar/Readiness.lua index b7e2f4b..4c2bd8d 100644 --- a/BuffRadar/Readiness.lua +++ b/BuffRadar/Readiness.lua @@ -53,19 +53,6 @@ local function Repairs() return incomplete and (reading .. " · " .. L["Some slots unknown"]) or reading end -local function HasAuraID(id) - local complete = true - for i = 1, 40 do - local done, answered, spell = X.Debuffs.ReadAura("player", i, false) - if done then - if answered and complete then return false end - return nil - end - if spell == id then return true end - if not spell then complete = false end - end -end - local function Presence(value) if value == nil then return L["Unknown"] end return L[value and "Present" or "Missing"] @@ -75,21 +62,22 @@ function R.Personal() local db = X.GetDB() if not X.classic or not db or db.liteMode or X.PlayerSuspended() or InCombatLockdown() then return end local lines = {} + local results = X.ObserveConsumables("player", {}, true, false, db.readinessAura > 0 and db.readinessAura or nil) for _, def in ipairs(X.CONS_DEFS) do - lines[#lines + 1] = { text = L[def.label], hint = Presence(X.ConsHas("player", def)) } + lines[#lines + 1] = { text = L[def.label], hint = Presence(results[def.key]) } end if db.readinessAura > 0 then local ok, name = pcall(X.Core.SpellName, db.readinessAura) local label = ok and X.Readable(name) and type(name) == "string" and name or "#" .. db.readinessAura - lines[#lines + 1] = { text = L["Optional consumable"] .. " · " .. label, hint = Presence(HasAuraID(db.readinessAura)) } + lines[#lines + 1] = { text = L["Optional consumable"] .. " · " .. label, hint = Presence(results.OPTIONAL) } else lines[#lines + 1] = { text = L["Optional consumable"], hint = L["No aura configured"] } end lines[#lines + 1] = { text = L["Healthstone in bags"], hint = Presence(Healthstone()) } lines[#lines + 1] = { text = L["Equipment durability"], hint = Repairs() } - local missing = X.WeaponEnchantMissing(true) - lines[#lines + 1] = { text = L["Temporary weapon coating"], hint = missing == nil and L["Unknown"] - or L[missing and "Missing" or "No missing coating"] } + local coating = X.WeaponCoatingState() + lines[#lines + 1] = { text = L["Temporary weapon coating"], hint = L[coating == "present" and "Present" + or coating == "missing" and "Missing" or coating == "na" and "Not applicable" or "Applicability unknown"] } local class = X.UnitClassToken("player") if class == "HUNTER" or class == "WARLOCK" then lines[#lines + 1] = { text = L["Active pet"], hint = Presence(X.ReadUnitBool(UnitExists, "pet")) } @@ -102,8 +90,7 @@ function R.SetAura(id) Print(L["Enter a consumable aura spell ID, or 0 to clear it."]) return false end - X.GetDB().readinessAura = id - if X.QueuePersonalReadiness then X.QueuePersonalReadiness() end + X.SetPreference("readinessAura", id) return true end diff --git a/BuffRadar/Recaps.lua b/BuffRadar/Recaps.lua index ff8a14c..e0dd166 100644 --- a/BuffRadar/Recaps.lua +++ b/BuffRadar/Recaps.lua @@ -68,7 +68,7 @@ local function BuildReadyView() f:SetMovable(true) f:RegisterForDrag("LeftButton") f:SetScript("OnDragStart", function(self) self:StartMoving() end) - f:SetScript("OnDragStop", function(self) self:StopMovingOrSizing() end) + X.BindPanelPosition(f, "ready", 85) f:EnableMouseWheel(true) f:SetScript("OnMouseWheel", function(_, delta) ScrollReady(delta > 0 and -1 or 1) end) local bg = f:CreateTexture(nil, "BACKGROUND") @@ -79,7 +79,7 @@ local function BuildReadyView() title:SetPoint("TOPRIGHT", -34, -12) title:SetJustifyH("LEFT") title:SetText(L["BuffRadar Ready Check"]) - local close = CreateFrame("Button", nil, f, "UIPanelCloseButton") + local close = X.PanelWidget("Button", nil, f, "UIPanelCloseButton") close:SetPoint("TOPRIGHT", -2, -2) close:SetScript("OnClick", function() X.ReadyViewCommand("hide") end) f.summary = f:CreateFontString(nil, "OVERLAY", "GameFontHighlight") @@ -152,6 +152,7 @@ function X.RaidPreparationSnapshot(personal) local report = X.GroupBuffReport(false, true, true) local reagents, incomplete = X.ReagentEstimate(report) local snapshot = { members = {}, reagents = reagents, incomplete = incomplete } + local observed = {} local size = X.ReadUnitNumber(GetNumGroupMembers) if not size or #report.members ~= size then snapshot.incomplete = true end for _, member in ipairs(report.members) do @@ -162,9 +163,10 @@ function X.RaidPreparationSnapshot(personal) local parts = BuffDetails(member) local attention = #member.missing > 0 or #member.expiring > 0 local unknown = member.unknown or #member.unavailable > 0 + if member.observable then X.ObserveConsumables(member.unit, observed, true) end for _, def in ipairs(X.CONS_DEFS) do local has - if member.observable then has = X.ConsHas(member.unit, def) end + if member.observable then has = observed[def.key] end if has == false then parts[#parts + 1] = string.format(L["%s missing"], L[def.label]) attention = true @@ -356,9 +358,10 @@ function X.WipeCheck() for i = first, math_min(#lines, 12) do Print(lines[i]) end if #lines > 12 then Print(string.format(" +%d more", #lines - 12)) end if people > 0 and X.AmLead() then - X.SendGroupReport(string.format( + local sent, failure = X.SendGroupReport(string.format( "BuffRadar wipe report: %d of %d died. %d %s missing buffs (%d buffs needed).%s", dead, total, people, people == 1 and "person is" or "people are", report.buffs, note and (" " .. note) or "")) + if not sent then Print(string.format(L["Local only — not sent: %s"], failure)) end end end diff --git a/BuffRadar/SavedVariables.lua b/BuffRadar/SavedVariables.lua index 45ec306..c788aeb 100644 --- a/BuffRadar/SavedVariables.lua +++ b/BuffRadar/SavedVariables.lua @@ -4,10 +4,35 @@ local _, ns = ... local X = ns.X -local DB_VERSION = 22 +local DB_VERSION = 23 local PROFILE_MAX_BYTES = 4000 local MIN_WIDTH, MAX_WIDTH = 180, 400 +local LIMITS = { profiles = 32, ignored = 192, pointByChar = 64, stats = 192, specProfiles = 4, + specScales = 4, enabled = 256, rebuffPer = 256, coverParts = 16, buffContext = 256, offenders = 50 } + +local function Count(map) + local n = 0 + for _ in pairs(map) do n = n + 1 end + return n +end + +local function KeepKeys(source, limit, valid, compare) + local keys = {} + local function Trim() + table.sort(keys, compare) + for i = #keys, limit + 1, -1 do keys[i] = nil end + end + for key, value in pairs(source) do + if valid(key, value) then + keys[#keys + 1] = key + if #keys >= limit * 2 then Trim() end + end + end + Trim() + return keys +end + local DEFAULTS = { locked = false, hidden = false, @@ -60,6 +85,8 @@ local DEFAULTS = { compact = false, -- half-height rows without portraits (1.4.0) textScale = 1, -- list text scale, separate from the window scale (1.4.0) charPoint = false, -- remember the window position per character (1.4.0) + rememberPanelPositions = false, + panelPoints = {}, pointByChar = {}, -- charPoint positions: "Name-Realm" -> point table (1.4.0) profiles = {}, -- named settings profiles: name -> settings string (1.5.0) sync = true, -- trade "I just buffed them" notes with other BuffRadar users (1.5.0) @@ -178,12 +205,9 @@ local function PriorityKey(key) end local function CopyInstancePriority(value) - local clean, count = {}, 0 - for id, key in pairs(value) do - if PositiveID(id) and PriorityKey(key) then - clean[id], count = key, count + 1 - if count >= MAX_INSTANCE_RULES then break end - end + local clean = {} + for _, id in ipairs(KeepKeys(value, MAX_INSTANCE_RULES, function(id, key) return PositiveID(id) and PriorityKey(key) end)) do + clean[id] = value[id] end return clean end @@ -248,23 +272,44 @@ end -- Each table field is rebuilt from validated values. Never hand a defaults -- subtable to the writable DB, or touch live settings while checking an import. -local function CopyStringMap(value, valid) +local function PlainString(value, limit) + return type(value) == "string" and #value > 0 and #value <= limit and not value:find("[%c|]") +end + +local function ValidIgnore(name) + return PlainString(name, 64) and name:find("%S") ~= nil and not name:find(";", 1, true) +end + +local function CopyMap(value, limit, valid) local clean = {} - for key, item in pairs(value) do - if type(key) == "string" and valid(item) then clean[key] = item end - end + for _, key in ipairs(KeepKeys(value, limit, valid)) do clean[key] = value[key] end return clean end local function IsBoolean(v) return type(v) == "boolean" end local function IsNonnegative(v) return IsNumber(v) and v >= 0 end +local function ValidBuffToken(key) return PlainString(key, 40) and key:match("^[A-Z0-9_]+$") end + +local function CopyBooleanMap(value) + return CopyMap(value, LIMITS.enabled, function(k, v) return ValidBuffToken(k) and IsBoolean(v) end) +end -local function CopyBooleanMap(value) return CopyStringMap(value, IsBoolean) end -local function CopyNumberMap(value) return CopyStringMap(value, IsNonnegative) end +local function CopyRebuffMap(value) + local clean = CopyMap(value, LIMITS.rebuffPer, function(k, v) return ValidBuffToken(k) and IsNonnegative(v) end) + for key, v in pairs(clean) do clean[key] = Clamp(v, 0, 600) end + return clean +end -local function IsPoint(value) - return type(value) == "table" and type(value[1]) == "string" and type(value[2]) == "string" +local anchors = { TOPLEFT = true, TOP = true, TOPRIGHT = true, LEFT = true, CENTER = true, + RIGHT = true, BOTTOMLEFT = true, BOTTOM = true, BOTTOMRIGHT = true } +local function ValidPoint(value) + return type(value) == "table" and anchors[value[1]] and anchors[value[2]] and IsNumber(value[3]) and IsNumber(value[4]) + and math.abs(value[3]) <= 100000 and math.abs(value[4]) <= 100000 +end + +local function CopyPoint(value) + if ValidPoint(value) then return { value[1], value[2], value[3], value[4] } end end local function CopyColor(value) @@ -273,15 +318,18 @@ local function CopyColor(value) end end +local function SpecKey(key) + return type(key) == "string" and key:match("^s[1-4]$") ~= nil +end + local function CopySpecProfiles(value) local clean = {} - for key, profile in pairs(value) do - if type(key) == "string" and type(profile) == "table" then - clean[key] = { - enabled = type(profile.enabled) == "table" and CopyBooleanMap(profile.enabled) or {}, - rebuffPer = type(profile.rebuffPer) == "table" and CopyNumberMap(profile.rebuffPer) or {}, - } - end + for _, key in ipairs(KeepKeys(value, LIMITS.specProfiles, function(k, v) return SpecKey(k) and type(v) == "table" end)) do + local p = value[key] + clean[key] = { + enabled = type(p.enabled) == "table" and CopyBooleanMap(p.enabled) or {}, + rebuffPer = type(p.rebuffPer) == "table" and CopyRebuffMap(p.rebuffPer) or {}, + } end return clean end @@ -298,14 +346,16 @@ local function CopyPlateRestore(value) end local function CopyHistory(value) - local clean = {} - for _, entry in ipairs(value) do - if type(entry) == "table" and type(entry.spell) == "string" and type(entry.who) == "string" then - clean[#clean + 1] = { t = IsNumber(entry.t) and math.floor(entry.t) or 0, - spell = entry.spell, who = entry.who } + local recent, clean = {}, {} + -- Look back through at most 200 slots even for an oversized/corrupt save. + for i = #value, math.max(1, #value - 199), -1 do + local entry = value[i] + if type(entry) == "table" and PlainString(entry.spell, 128) and PlainString(entry.who, 128) then + recent[#recent + 1] = { t = IsNumber(entry.t) and math.floor(entry.t) or 0, spell = entry.spell, who = entry.who } + if #recent >= 50 then break end end end - while #clean > 50 do table.remove(clean, 1) end + for i = #recent, 1, -1 do clean[#clean + 1] = recent[i] end return clean end @@ -339,17 +389,17 @@ local function CopyCustomSpells(value) return clean end -local function CopyCustomGroup(value) - local clean, count = {}, 0 - for single, group in pairs(value) do - if type(single) == "string" and type(group) == "string" - and #single >= 1 and #single <= 60 and #group >= 1 and #group <= 60 then - clean[single] = group - count = count + 1 - if count >= 20 then break end - end +local MAX_GROUP_PAIRS = 20 +local function ValidGroupPair(single, group) + local function ValidSpell(name) + return type(name) == "string" and #name >= 1 and #name <= 60 + and name:match("^%S") and name:match("%S$") and not name:find("[%c;%[%]|]") end - return clean + return ValidSpell(single) and ValidSpell(group) +end + +local function CopyCustomGroup(value) + return CopyMap(value, MAX_GROUP_PAIRS, ValidGroupPair) end local function CopyBuffPriority(value) @@ -391,33 +441,38 @@ local TABLE_FIELDS = { return clean end, enabled = CopyBooleanMap, - ignored = CopyBooleanMap, - coverParts = CopyBooleanMap, + ignored = function(value) + return CopyMap(value, LIMITS.ignored, function(name, enabled) return enabled == true and ValidIgnore(name) end) + end, + coverParts = function(value) + return CopyMap(value, LIMITS.coverParts, function(k, v) return PlainString(k, 24) and IsBoolean(v) end) + end, specScales = function(value) - local clean = {} - for key, scale in pairs(value) do - if type(key) == "string" and IsNumber(scale) then clean[key] = Clamp(scale, 0.5, 2) end - end + local clean = CopyMap(value, LIMITS.specScales, function(k, v) return SpecKey(k) and IsNumber(v) end) + for key, scale in pairs(clean) do clean[key] = Clamp(scale, 0.5, 2) end return clean end, specProfiles = CopySpecProfiles, pointByChar = function(value) local clean = {} - for name, point in pairs(value) do - if type(name) == "string" and IsPoint(point) then clean[name] = { point[1], point[2], point[3], point[4] } end + for _, name in ipairs(KeepKeys(value, LIMITS.pointByChar, function(k, v) return PlainString(k, 128) and ValidPoint(v) end)) do + clean[name] = CopyPoint(value[name]) end return clean end, + panelPoints = function(value) + return { settings = CopyPoint(value.settings), ready = CopyPoint(value.ready) } + end, profiles = function(value) + return CopyMap(value, LIMITS.profiles, function(k, v) return IsProfileName(k) and type(v) == "string" and #v <= PROFILE_MAX_BYTES end) + end, + autoProfile = function(value) local clean = {} - for name, body in pairs(value) do - if IsProfileName(name) and type(body) == "string" and #body <= PROFILE_MAX_BYTES then clean[name] = body end + for _, key in ipairs({ "raid", "dungeon", "pvp", "world", "solo" }) do + if IsProfileName(value[key]) then clean[key] = value[key] end end return clean end, - autoProfile = function(value) - return CopyStringMap(value, function(name) return type(name) == "string" and #name <= 40 end) - end, history = CopyHistory, customSpells = CopyCustomSpells, customGroup = CopyCustomGroup, @@ -432,11 +487,27 @@ local TABLE_FIELDS = { return clean end, buffContext = function(value) - return CopyStringMap(value, function(context) return context == "raid" or context == "instance" end) + return CopyMap(value, LIMITS.buffContext, function(k, v) return ValidBuffToken(k) and (v == "raid" or v == "instance") end) + end, + rebuffPer = CopyRebuffMap, + stats = function(value) return CopyMap(value, LIMITS.stats, function(k, v) return PlainString(k, 128) and IsNonnegative(v) end) end, + offenders = function(value) + local function Valid(k, v) + if not PlainString(k, 128) then return false end + if IsNonnegative(v) then return true end -- legacy display-name key + return type(v) == "table" and PlainString(v.name, 128) and IsNonnegative(v.count) + end + local function Counts(k) local v = value[k]; return type(v) == "number" and v or v.count end + local clean = {} + for _, key in ipairs(KeepKeys(value, LIMITS.offenders, Valid, function(a, b) + return Counts(a) > Counts(b) or (Counts(a) == Counts(b) and a < b) + end)) do + local v = value[key] + if type(v) == "number" then clean["legacy:" .. key] = { name = key, count = v } + else clean[key] = { name = v.name, count = v.count } end + end + return clean end, - rebuffPer = CopyNumberMap, - stats = CopyNumberMap, - offenders = CopyNumberMap, } local function CleanSetting(key, value, default) @@ -453,6 +524,7 @@ local function CleanSetting(key, value, default) elseif kind == "string" then if ENUMS[key] and not ENUMS[key][value] then return default end if key == "theme" and #value > 24 then return default end + if key == "pinned" and (#value > 128 or value:find("[%c|]")) then return default end if key == "autoThemePriority" and value ~= "" then return EncodeAutoThemePriority(OrderedAutoThemeAddons(value)) end @@ -470,6 +542,15 @@ local function CleanTheme(name, themes) end -- Also used for detached profile candidates, without publishing a new DB. +local function PreparePatch(saved, patch) + local prepared = {} + for key, value in pairs(patch) do + if DEFAULTS[key] ~= nil then prepared[key] = CleanSetting(key, value, DEFAULTS[key]) end + end + if prepared.theme then prepared.theme = CleanTheme(prepared.theme, saved.customThemes) end + return prepared +end + local function Sanitize(saved) if type(saved) ~= "table" then saved = {} end for key in pairs(saved) do @@ -479,7 +560,7 @@ local function Sanitize(saved) saved[key] = CleanSetting(key, saved[key], default) end saved.theme = CleanTheme(saved.theme, saved.customThemes) - if not IsPoint(saved.point) then saved.point = nil end + saved.point = CopyPoint(saved.point) if not IsNumber(saved.dbVersion) then saved.dbVersion = nil end return saved end @@ -503,14 +584,58 @@ local function Migrate(saved) if previous < DB_VERSION then saved.dbVersion = DB_VERSION end end -local db +local function ParseSubgroups(value) + if value == "ALL" then return nil, true end + if value == "NONE" then return {}, true end + if type(value) ~= "string" or #value > 15 or #value == 0 then return nil, false end + local groups = {} + for token in (value .. ","):gmatch("(.-),") do + if not token:match("^[1-8]$") then return nil, false end + local n = tonumber(token) + if groups[n] then return nil, false end + groups[n] = true + end + return groups, true +end + +local db, preserved, saveState local listeners = {} +local function DeliberateOverflow(saved) + local profiles, ignored = 0, 0 + if type(saved.profiles) == "table" then + for name, body in pairs(saved.profiles) do + if IsProfileName(name) and type(body) == "string" then + profiles = profiles + 1 + if #body > PROFILE_MAX_BYTES or profiles > LIMITS.profiles then return true end + end + end + end + if type(saved.ignored) == "table" then + for name, value in pairs(saved.ignored) do + if value == true and ValidIgnore(name) then + ignored = ignored + 1 + if ignored > LIMITS.ignored then return true end + end + end + end +end + local function Load(migrate) - local saved = Sanitize(BuffRadarDB) - if migrate then Migrate(saved) end - BuffRadarDB, db = saved, saved + local original, candidate = BuffRadarDB, {} + if type(original) == "table" then + for key in pairs(KNOWN_KEYS) do candidate[key] = original[key] end + end + local future = IsNumber(candidate.dbVersion) and candidate.dbVersion > DB_VERSION + saveState = future and "future" or (DeliberateOverflow(candidate) and "overflow") or nil + preserved = saveState == "overflow" and original or nil + local saved = Sanitize(candidate) + if future then saved.dbVersion = DB_VERSION end + if migrate or future then Migrate(saved) end + if not saveState then BuffRadarDB = saved end + db = saved for _, listener in ipairs(listeners) do listener(db) end + return saveState end local function OnDBLoaded(listener) @@ -523,6 +648,30 @@ X.OnDBLoaded = OnDBLoaded X.Settings = { Load = Load, Sanitize = Sanitize, + PreparePatch = PreparePatch, + CopyPoint = CopyPoint, + ValidGroupPair = ValidGroupPair, + ParseSubgroups = ParseSubgroups, + MaxGroupPairs = MAX_GROUP_PAIRS, + Limits = LIMITS, + Count = Count, + PlainString = PlainString, + ValidIgnore = ValidIgnore, + CanAdd = function(map, kind, key) return map[key] ~= nil or Count(map) < LIMITS[kind] end, + SaveState = function() return saveState end, + RemovePreservedEntry = function(kind, key) + local collection = preserved and saveState == "overflow" and preserved[kind] + if type(collection) ~= "table" or collection[key] == nil then return false end + collection[key] = nil + return true + end, + RecordOffenders = function(observed) + for guid, name in pairs(observed) do + local old = db.offenders[guid] + db.offenders[guid] = { name = name, count = (old and old.count or 0) + 1 } + end + db.offenders = TABLE_FIELDS.offenders(db.offenders) + end, Defaults = DEFAULTS, MinWidth = MIN_WIDTH, MaxWidth = MAX_WIDTH, diff --git a/BuffRadar/Slash.lua b/BuffRadar/Slash.lua index fd6ffec..19e0996 100644 --- a/BuffRadar/Slash.lua +++ b/BuffRadar/Slash.lua @@ -99,9 +99,12 @@ end function X.SelfTest() local ver, build, _, iface = GetBuildInfo() + local metadata = (_G.C_AddOns and _G.C_AddOns.GetAddOnMetadata) or _G.GetAddOnMetadata + local ok, version = pcall(metadata, "BuffRadar", "Version") + version = ok and X.Readable(version) and type(version) == "string" and version or "unknown" Print("BuffRadar self-test -- paste this whole block into a bug report:") Print(string.format(" version %s · %s edition · interface %s · client %s build %s", - "1.13.0", CLASSIC_FEATURES and "Forever" or "Retail", tostring(iface), tostring(ver), tostring(build))) + version, CLASSIC_FEATURES and "Forever" or "Retail", tostring(iface), tostring(ver), tostring(build))) Print(string.format(" settings dbVersion %s · sort %s · cast mode %s · scale %s", tostring(db.dbVersion), tostring(db.sortMode), tostring(db.castMethod), tostring(db.scale))) Print(string.format(" sync %s · requests %s · role filter %s · profiles %d · idle fade %s", @@ -181,6 +184,7 @@ local function HandleSlash(msg) syncState() local cmd, rest = (msg or ""):match("^%s*(%S*)%s*(.-)%s*$") cmd = (cmd or ""):lower() + if not X.supported then Print(L["BuffRadar requires the Forever package on Interface 16001. Casting is disabled."]); return end if not db then Print("Settings not loaded yet."); return end if (cmd == "" or cmd == "show" or cmd == "hide" or cmd == "announce" or cmd == "summary" or cmd == "discord" or cmd == "why") and X.PlayerSuspended() then @@ -297,8 +301,7 @@ local function HandleSlash(msg) db.pauseInCities = not db.pauseInCities Print("Pause in major cities " .. OnOff(db.pauseInCities)) elseif cmd == "sync" then - db.sync = not db.sync - if not db.sync then X.StopCoordination() end + X.SetPreference("sync", not db.sync) Print("BuffRadar cast sync " .. OnOff(db.sync)) elseif cmd == "requests" then db.requests = not db.requests @@ -600,23 +603,21 @@ local function HandleSlash(msg) db.charPoint = not db.charPoint if db.charPoint then local k = X.CharKey() - if k and db.point then db.pointByChar[k] = db.point end + if db.point then X.SaveCharacterPoint(k) end end Print("Per-character window position " .. OnOff(db.charPoint)) elseif cmd == "export" then local text, err = X.Export() if not text then Print(err); return end X.ShowExport(text, false) - Print("Settings string shown -- copy it, then use /br import on the other character.") + Print(L["Use a named BR2 profile to share newer preferences."]) elseif cmd == "import" then X.ShowExport("", true) elseif cmd == "profile" then local sub, pname = rest:match("^(%S*)%s*(.-)%s*$") sub = (sub or ""):lower() if sub == "save" then - local ok, err = X.SaveProfile(pname) - if ok then Print("Profile saved: " .. pname) else Print(err) end - if RefreshConfig then RefreshConfig() end + X.RequestProfileSave(pname) elseif sub == "load" then local ok, err = X.LoadProfile(pname) if ok then @@ -640,7 +641,7 @@ local function HandleSlash(msg) Print("No profile named '" .. pname .. "'. /br profile list shows them.") end elseif sub == "import" then - X.ShowExport("", true, "BuffRadar — paste a shared profile, then Import", "profile") + X.ShowExport("", true, L["Paste a shared profile, then review."], "profile") elseif sub == "diff" then local str = db.profiles[pname] if type(str) ~= "string" then Print("No profile named '" .. pname .. "'. /br profile list shows them.") @@ -658,10 +659,10 @@ local function HandleSlash(msg) if sub == "export" then local text, err = X.PlanExport() if not text then Print(err); return end - X.ShowExport(text, false, "BuffRadar — your group buff plan (copy it)") + X.ShowExport(text, false, L["Group plan copy (select all, copy)"]) Print("Plan string shown — it carries assignments, the blessing plan and auto profiles, not your settings.") elseif sub == "import" then - X.ShowExport("", true, "BuffRadar — paste a plan string, then Import", "plan") + X.ShowExport("", true, L["Paste a group plan, then review."], "plan") else local acount, bcount = 0, 0 for _ in pairs(X.assign) do acount = acount + 1 end @@ -679,14 +680,25 @@ local function HandleSlash(msg) elseif cmd == "discord" then X.ShowExport(X.DiscordText(), false, "BuffRadar — copy into Discord") Print("Discord summary shown — copy it into your Discord message.") + elseif cmd == "storage" then + local kind, name = rest:match("^delete%s+(%a+)%s+(.+)$") + if kind == "profile" or kind == "ignore" then + if X.Settings.RemovePreservedEntry(kind == "profile" and "profiles" or "ignored", name) then + Print(L["Removed from the preserved save. Reload to try normal saving again."]) + else Print(L["No matching entry in an oversized save."]) end + else + X.ShowSaveState(X.Settings.SaveState()) + Print(string.format(L["Profiles: %d/%d · Ignores: %d/%d"], X.Settings.Count(db.profiles), X.Settings.Limits.profiles, + X.Settings.Count(db.ignored), X.Settings.Limits.ignored)) + end elseif cmd == "offenders" then if rest:lower() == "clear" then wipe(db.offenders) Print("Repeat-offender history cleared.") else local orows = {} - for nm, c in pairs(db.offenders) do orows[#orows + 1] = { nm = nm, c = c } end - table_sort(orows, function(a, b) return a.c > b.c end) + for guid, item in pairs(db.offenders) do orows[#orows + 1] = { nm = item.name, c = item.count, guid = guid } end + table_sort(orows, function(a, b) return a.c > b.c or (a.c == b.c and a.guid < b.guid) end) if #orows == 0 then Print("No repeat offenders yet — a player lands here after a group session where they were seen unbuffed.") else @@ -732,8 +744,15 @@ local function HandleSlash(msg) Refresh() elseif cmd == "grouppair" then local cg = db.customGroup - local single, group = rest:match('^"([^"]+)"%s*"([^"]+)"$') + local single, group = rest:match('^"([^"]+)"%s+"([^"]+)"$') if single then + if not X.Settings.ValidGroupPair(single, group) then Print(L["Invalid group-cast pair; nothing changed."]); return end + local count = 0 + for _ in pairs(cg) do count = count + 1 end + if not cg[single] and count >= X.Settings.MaxGroupPairs then + Print(L["Group-cast pair limit reached. Remove a pair first."]) + return + end cg[single] = group Print("Group-cast pair set: Shift-click " .. single .. " casts " .. group .. " (needs /br modclick on).") elseif rest:lower():sub(1, 6) == "clear " then @@ -750,9 +769,7 @@ local function HandleSlash(msg) Refresh() elseif cmd == "pullflash" then local m = rest:lower() - if m == "on" then db.pullFlash = true - elseif m == "off" then db.pullFlash = false - else db.pullFlash = not db.pullFlash end + X.SetPreference("pullFlash", m == "on" or (m ~= "off" and not db.pullFlash)) Print("Pull-timer flash " .. OnOff(db.pullFlash) .. " -- border flash and a countdown line when a group pull timer starts (the game's /countdown or a boss-mod pull).") elseif cmd == "ready" then @@ -781,8 +798,7 @@ local function HandleSlash(msg) local sub, arg = rest:match("^(%S*)%s*(.-)%s*$") sub = (sub or ""):lower() local id = tonumber(arg) - if sub == "add" and id then - id = math.floor(id) + if sub == "add" and X.Settings.PositiveID(id) then local have = false for _, x in ipairs(db.customSpells) do if x == id then have = true break end end if have then Print("That spell is already on the custom list.") @@ -800,6 +816,8 @@ local function HandleSlash(msg) if db.customSpells[i] == id then table.remove(db.customSpells, i); gone = true end end if gone then + local key = "CUSTOM" .. id + db.enabled[key], db.rebuffPer[key] = nil, nil pcall(BuildBuffList) Print("Custom spell removed.") Refresh() @@ -827,7 +845,7 @@ local function HandleSlash(msg) Print(#parts > 0 and ("Assignments: " .. table.concat(parts, ", ")) or "No buff assignments. /br assign sets one (leader or assistant).") elseif akey == "CLEAR" then - wipe(X.assign) + X.ClearLocalPlans("ASSIGN") Print("Assignments cleared.") Refresh() elseif not InGroup() then @@ -837,7 +855,7 @@ local function HandleSlash(msg) elseif aname == "" then Print("Usage: /br assign , or /br assign none to clear one.") else - if aname:lower() == "none" then X.assign[akey] = nil else X.assign[akey] = aname end + X.SetLocalPlan("ASSIGN", akey, aname:lower() ~= "none" and aname or nil) X.Broadcast("ASSIGN;" .. akey .. ";" .. aname) Print("Assignment: " .. akey .. " -> " .. aname) Refresh() @@ -864,9 +882,8 @@ local function HandleSlash(msg) elseif cmd == "throttle" then local mode = rest:lower() if mode ~= "" and mode ~= "on" and mode ~= "off" then Print("/br throttle [on|off]"); return end - db.scanThrottle = mode == "on" or (mode == "" and not db.scanThrottle) + X.SetPreference("scanThrottle", mode == "on" or (mode == "" and not db.scanThrottle)) Print(string.format(L["Adaptive scan throttle: %s"], L[db.scanThrottle and "On" or "Off"])) - X.Intel.SettingsChanged() if RefreshConfig then RefreshConfig() end return elseif cmd == "growup" then @@ -1199,7 +1216,7 @@ local function HandleSlash(msg) if not X.AmLead() and myClass ~= "PALADIN" then Print("Only the group leader, an assistant or a paladin can set the blessing plan.") elseif bkey == "NONE" then - X.blessPlan[cls] = nil + X.SetLocalPlan("BLESS", cls, nil) X.Broadcast("BLESS;" .. cls .. ";NONE;none") Print("Blessing plan cleared for " .. cls .. ".") Refresh() @@ -1211,8 +1228,8 @@ local function HandleSlash(msg) else local holder = (bname ~= "") and bname or (Ignore.UnitNames("player") or "me") local me = Ignore.UnitNames("player") - X.blessPlan[cls] = { key = bkey, name = holder, - mine = me ~= nil and Ignore.Key(holder) == Ignore.Key(me) } + X.SetLocalPlan("BLESS", cls, { key = bkey, name = holder, + mine = me ~= nil and Ignore.Key(holder) == Ignore.Key(me) }) X.Broadcast("BLESS;" .. cls .. ";" .. bkey .. ";" .. holder) Print("Blessing plan: " .. cls .. " gets " .. bkey .. " from " .. holder .. ".") Refresh() @@ -1262,7 +1279,9 @@ local function HandleSlash(msg) elseif cmd == "ignore" then if rest == "" then Print("Usage: /br ignore or (or right-click a row)"); return end if not Ignore.Valid(rest) then Print("That is not a player name (64 characters at most, no | or ;)."); return end - if Ignore.Add(rest) then + local added, err = Ignore.Add(rest) + if err then Print(err); return end + if added then Print("Ignoring " .. rest .. (rest:find("-", 1, true) and "." or " on every realm.")) else Print(rest .. " is already ignored.") @@ -1371,9 +1390,17 @@ local function HandleSlash(msg) else Print(string.format("Usage: /br width <%d - %d>", MIN_WIDTH, MAX_WIDTH)) end + elseif cmd == "positions" then + if not X.PanelPositions(rest:lower()) then Print(L["Use /br positions on|off|reset."]); return end + Print(string.format(L["Remember panel positions: %s"], L[db.rememberPanelPositions and "On" or "Off"])) + if RefreshConfig then RefreshConfig() end + return elseif cmd == "reset" or cmd == "resetpos" then - X.ResetWindowPosition() - Print(cmd == "reset" and "Position reset." or "Window position reset to the default spot.") + if X.ResetWindowPosition() then + Print(cmd == "reset" and "Position reset." or "Window position reset to the default spot.") + else + Print(L["Can't move the buff window during combat."]) + end elseif cmd == "buffs" then ListBuffs() elseif cmd == "toggle" then diff --git a/BuffRadar/Window.lua b/BuffRadar/Window.lua index f802306..a5b81ae 100644 --- a/BuffRadar/Window.lua +++ b/BuffRadar/Window.lua @@ -33,6 +33,7 @@ local grip, leftGrip, widthHandle, groupBtn, pill local rows, built = {}, false local rowMouseButtons, rowLeftPress = {}, nil local viewport, viewportCount, rowOffset +local visibleLimit = MAX_ROWS local viewportMode, viewportSearch, viewportRole, viewportTwoCol, rowWheelEnabled local columns, rowsPerColumn, previousRowsTall = 1, MAX_ROWS, nil local rowHeight, topHeight = ROW_H, HEADER_H @@ -155,7 +156,7 @@ local function SavePosition() db.point = { "BOTTOMLEFT", "BOTTOMLEFT", left, bottom } if db.charPoint then local k = X.CharKey() - if k then db.pointByChar[k] = db.point end + X.SaveCharacterPoint(k) end return end @@ -179,7 +180,7 @@ local function SavePosition() end if db.charPoint then local k = X.CharKey() - if k and db.point then db.pointByChar[k] = db.point end + if db.point then X.SaveCharacterPoint(k) end end end @@ -191,6 +192,20 @@ local POINT_FRACTION = { BOTTOMLEFT = { 0, 0 }, BOTTOM = { 0.5, 0 }, BOTTOMRIGHT = { 1, 0 }, } +local function UsablePoint(point, widget) + if not X.Settings.CopyPoint(point) then return false end + local to, from = POINT_FRACTION[point[1]], POINT_FRACTION[point[2]] + local width = X.ReadUnitNumber(UIParent.GetWidth, UIParent) + local height = X.ReadUnitNumber(UIParent.GetHeight, UIParent) + if not width or width <= 0 or not height or height <= 0 then return true end + local scale = X.ReadUnitNumber(widget.GetScale, widget) or 1 + local w, h = X.ReadUnitNumber(widget.GetWidth, widget), X.ReadUnitNumber(widget.GetHeight, widget) + if not w or not h or w <= 0 or h <= 0 then return true end + local left = from[1] * width + (point[3] - to[1] * w) * scale + local bottom = from[2] * height + (point[4] - to[2] * h) * scale + return left < width and bottom < height and left + w * scale > 0 and bottom + h * scale > 0 +end + -- Forget the saved window spot (shared and per-character), so the next -- RestorePosition lands on the default anchor. local function ClearSavedPoint() @@ -201,27 +216,13 @@ local function ClearSavedPoint() end end -local function RestorePosition() +local function PlaceSavedPosition() if db.charPoint then local k = X.CharKey() if k and db.pointByChar[k] then db.point = db.pointByChar[k] end end frame:ClearAllPoints() - -- Rescue (1.5.0): a saved spot can end up off-screen after a monitor or - -- resolution change. Saved points anchor TOPLEFT to the screen's - -- BOTTOMLEFT, so x is the left edge and y the top edge from the bottom; - -- if the window would be (mostly) unreachable, forget the spot instead - -- of restoring it blind. - if db.point and db.point[1] == "TOPLEFT" and db.point[2] == "BOTTOMLEFT" - and _G.GetScreenWidth and _G.GetScreenHeight then - local okW, sw = pcall(_G.GetScreenWidth) - local okH, sh = pcall(_G.GetScreenHeight) - local x, y = db.point[3], db.point[4] - if okW and okH and type(sw) == "number" and type(sh) == "number" - and (x < 30 - frame:GetWidth() or x > sw - 50 or y < 50 or y > sh) then - ClearSavedPoint() - end - end + if db.point and not UsablePoint(db.point, frame) then ClearSavedPoint() end if db.growUp and db.point and db.point[1] == "BOTTOMLEFT" then -- Grow-up form (1.8.0): restore the bottom anchor as saved. frame:SetPoint("BOTTOMLEFT", UIParent, db.point[2], db.point[3], db.point[4]) @@ -254,9 +255,25 @@ local function RestorePosition() frame:SetPoint("TOPLEFT", UIParent, rp, db.point[3], db.point[4]) end +local function RestorePosition() + if InCombatLockdown() then return end + if not pcall(PlaceSavedPosition) then + ClearSavedPoint() + PlaceSavedPosition() + end +end + +function X.SaveCharacterPoint(key) + if key and X.Settings.PlainString(key, 128) and X.Settings.CanAdd(db.pointByChar, "pointByChar", key) then + db.pointByChar[key] = X.Settings.CopyPoint(db.point) + end +end + function X.ResetWindowPosition() + if InCombatLockdown() then return false end ClearSavedPoint() if frame then RestorePosition() end + return true end local function InstallCombatDriver(button, snippet) @@ -530,7 +547,7 @@ local function BuildGroupButton() end function X.SetNextCast(entry) - if nextBtn and entry and not entry.outOfRange then + if nextBtn and entry then nextBtn.entry = BindCached(nextBtn, entry.unit, entry.missing[1], entry.guid) and entry or nil ArmGroupButton(entry) else @@ -561,18 +578,13 @@ local function Row_OnEnter(self) GameTooltip:AddLine(e.name) end GameTooltip:AddLine(" ") - if e.outOfRange then - GameTooltip:AddLine(L["Out of range — move closer to cast:"], 1, 0.5, 0.3) - GameTooltip:AddLine("|cff00ff00" .. e.missing[1] .. "|r") - else - GameTooltip:AddLine(string_format(L["Click to cast: %s"], "|cff00ff00" .. (self.bSpellText or e.missing[1]) .. "|r")) - if db.modClick and CLASSIC_FEATURES then - local gs = self.bGroupText or self.bGroupSpell - if gs then - GameTooltip:AddLine(string_format(L["Shift-click to cast: %s"], "|cff00ff00" .. gs .. "|r")) - end - if self.bOfferReason then GameTooltip:AddLine(self.bOfferReason, 1, 0.7, 0.3, true) end + GameTooltip:AddLine(string_format(L["Click to cast: %s"], "|cff00ff00" .. (self.bSpellText or e.missing[1]) .. "|r")) + if db.modClick and CLASSIC_FEATURES then + local gs = self.bGroupText or self.bGroupSpell + if gs then + GameTooltip:AddLine(string_format(L["Shift-click to cast: %s"], "|cff00ff00" .. gs .. "|r")) end + if self.bOfferReason then GameTooltip:AddLine(self.bOfferReason, 1, 0.7, 0.3, true) end end if e.groupCast then GameTooltip:AddLine(L["Group version — one cast buffs the whole party."], 0.4, 0.8, 1) @@ -617,9 +629,7 @@ local function Row_OnEnter(self) local bits = {} if e.class then bits[#bits + 1] = e.class:sub(1, 1) .. e.class:sub(2):lower() end bits[#bits + 1] = e.group and "In your group" or "Nearby, not in your group" - if not e.outOfRange then bits[#bits + 1] = "in cast range" - elseif e.approximateRange then bits[#bits + 1] = L["Estimated range"] - elseif e.rangeBucket == 1 then bits[#bits + 1] = "near — just out of range" end + bits[#bits + 1] = e.approximateRange and L["Estimated range"] or "in cast range" GameTooltip:AddLine(table.concat(bits, " · "), 0.7, 0.7, 0.7) -- Which other classes could cast the first missing buff: scanned -- from the definitions on the spot (a hover is rare; no state kept). @@ -717,14 +727,15 @@ local function IgnoreRowPlayer(self, button, down) if #removed == 0 and short then removed = Ignore.Remove(short) end Print("No longer ignoring " .. table.concat(removed, ", ") .. ".") else - Ignore.Add(who) - Print("Ignoring " .. who .. ". Undo with /br unignore " .. who .. " or on the Ignore & Stats tab.") + local ok, err = Ignore.Add(who) + if ok then Print("Ignoring " .. who .. ". Undo with /br unignore " .. who .. " or on the Ignore & Stats tab.") + elseif err then Print(err) end end if QueueRefresh then QueueRefresh() end end local function ValidateRowClick(self, button, down) - if button == "LeftButton" and not InCombatLockdown() and self.bGuid then + if button == "LeftButton" and not InCombatLockdown() and self:GetAttribute("type") then local press = not down and rowLeftPress local changed = press and (press.row ~= self or press.guid ~= self.bGuid or press.unit ~= self.bUnit or press.spell ~= self.bSpell) @@ -789,11 +800,6 @@ local function BuildRowVisuals(b) if b.name.SetWordWrap then b.name:SetWordWrap(false) end -- "out of range" under the name of a greyed row, so the state doesn't rest -- on color alone (RenderRow moves the name up to make room). - b.far = b:CreateFontString(nil, "OVERLAY", "GameFontDisableSmall") - b.far:SetPoint("TOPLEFT", b.name, "BOTTOMLEFT", 0, -1) - b.far:SetText(L["out of range"]) - b.far:Hide() - -- Duration bar (1.8.0): a thin bar along the row's bottom edge showing -- how much of a 30-minute span the expiring buff has left. b.tint = b:CreateTexture(nil, "OVERLAY") @@ -997,7 +1003,7 @@ function X.ApplyAnchor() end if db.charPoint then local k = X.CharKey() - if k then db.pointByChar[k] = db.point end + X.SaveCharacterPoint(k) end end @@ -1018,6 +1024,61 @@ end -- Width and scale. The window holds secure row buttons, so its size can't -- change in combat; callers retry after combat (PLAYER_REGEN_ENABLED). +function X.PanelWidget(kind, name, parent, template) + local ok, widget = pcall(CreateFrame, kind, name, parent, template) + if ok and widget then return widget end + widget = CreateFrame(kind, name, parent) + if kind == "Button" then + widget:SetNormalFontObject(GameFontNormal) + widget:SetHighlightFontObject(GameFontHighlight) + local texture = widget:CreateTexture(nil, "BACKGROUND") + texture:SetAllPoints() + texture:SetColorTexture(0.12, 0.16, 0.21, 0.95) + if template == "UIPanelCloseButton" then widget:SetSize(22, 22); widget:SetText("×") end + elseif kind == "EditBox" then + widget:SetFontObject(GameFontHighlight) + elseif template == "BackdropTemplate" and kind == "Frame" and not widget.SetBackdrop then + local texture = widget:CreateTexture(nil, "BACKGROUND") + texture:SetAllPoints() + texture:SetColorTexture(0.04, 0.06, 0.10, 0.95) + end + return widget +end + +do + local panels = {} + local function RestorePanel(widget, key, offset) + local point = db.rememberPanelPositions and db.panelPoints[key] + widget:ClearAllPoints() + if point and UsablePoint(point, widget) and pcall(widget.SetPoint, widget, point[1], UIParent, point[2], point[3], point[4]) then return end + db.panelPoints[key] = nil + widget:SetPoint("CENTER", UIParent, "CENTER", 0, offset) + end + + function X.BindPanelPosition(widget, key, offset) + panels[key] = { frame = widget, offset = offset } + RestorePanel(widget, key, offset) + widget:HookScript("OnShow", function(self) RestorePanel(self, key, offset) end) + widget:SetScript("OnDragStop", function(self) + self:StopMovingOrSizing() + if db.rememberPanelPositions then + local p, relative, rp, x, y = self:GetPoint(1) + if relative == UIParent then db.panelPoints[key] = X.Settings.CopyPoint({ p, rp, x, y }) end + end + end) + end + + function X.PanelPositions(mode) + if mode == "on" then db.rememberPanelPositions = true + elseif mode == "off" or mode == "reset" then + if mode == "off" then db.rememberPanelPositions = false end + wipe(db.panelPoints) + for key, info in pairs(panels) do RestorePanel(info.frame, key, info.offset) end + else return false end + return true + end +end + local function ApplyGeometry() if not frame then return end if InCombatLockdown() then @@ -1118,7 +1179,7 @@ end local function ApplyRowWheel() if not frame or InCombatLockdown() then return end - local enabled = (viewportCount or 0) > MAX_ROWS and not (db.clickThrough and db.locked) + local enabled = (viewportCount or 0) > visibleLimit and not (db.clickThrough and db.locked) if rowWheelEnabled == enabled then return end rowWheelEnabled = enabled frame:EnableMouseWheel(enabled) @@ -1212,7 +1273,6 @@ function X.ApplyRowLayout() if row.portrait then row.portrait:SetShown(not db.compact) end for j = 1, MAX_ICONS do if row.icons[j] then row.icons[j]:SetSize(isz, isz) end end if row.name then row.name:SetScale(ts) end - if row.far then row.far:SetScale(ts) end if row.tag then row.tag:SetScale(ts) end end end @@ -1246,8 +1306,10 @@ end local function InvalidateRows() for i = 1, #rows do local row = rows[i] - row.cGuid, row.cUnit, row.bGuid, row.cFar, row.cTag = nil, nil, nil, nil, nil - row.cBar, row.cMarker, row.cFarTxt = nil, nil, nil + row.cGuid, row.cUnit, row.cTag = nil, nil, nil + -- false means rebuild (or clear if this row is retired), not disarmed. + if row.bGuid ~= nil then row.bGuid = false end + row.cBar, row.cMarker = nil, nil row.cTint = nil wipe(row.cMissing) end @@ -1295,13 +1357,9 @@ local ROW_TAGS = { { "pet", "pet", "p" }, } -local function RowTag(entry, far, symbols) - if not far then - for _, tag in ipairs(ROW_TAGS) do - if entry[tag[1]] then - return symbols and (tag[3] .. " " .. L[tag[2]]) or L[tag[2]] - end - end +local function RowTag(entry, symbols) + for _, tag in ipairs(ROW_TAGS) do + if entry[tag[1]] then return symbols and (tag[3] .. " " .. L[tag[2]]) or L[tag[2]] end end local left = entry.remain1 if left then @@ -1316,30 +1374,17 @@ local function SetNameOffset(row, y) row.name:SetPoint("RIGHT", row, "RIGHT", -IconInset(), y) end -local function RenderRowName(row, e, far) - if row.cGuid ~= e.guid or row.cUnit ~= e.unit then - -- 3D portrait render: only for a new player/token. Guarded like the rest of - -- this file: if a build renames or restricts it, the row still renders. - if SetPortraitTexture then pcall(SetPortraitTexture, row.portrait, e.unit) end - row.name:SetText(DispName(e)) - row.cGuid, row.cUnit = e.guid, e.unit - row.cFar = nil -- new player on this row: set color and layout below - end - -- In range: class-colored name centered on the row. Out of range: grey name - -- moved up, with "out of range" under it. (Before 1.3.2 the grey stayed - -- after the player came back into range.) - if row.cFar ~= far then - row.cFar = far - SetNameOffset(row, far and 5 or 0) - row.far:SetShown(far) - if far then row.name:SetTextColor(0.55, 0.55, 0.55) - elseif db.classColors then row.name:SetTextColor(ClassColor(e.class)) - else row.name:SetTextColor(0.92, 0.92, 0.92) end - end +local function RenderRowName(row, e) + if row.cGuid == e.guid and row.cUnit == e.unit then return end + if SetPortraitTexture then pcall(SetPortraitTexture, row.portrait, e.unit) end + row.name:SetText(DispName(e)) + row.cGuid, row.cUnit = e.guid, e.unit + if db.classColors then row.name:SetTextColor(ClassColor(e.class)) + else row.name:SetTextColor(0.92, 0.92, 0.92) end end -local function RenderRowTag(row, entry, far) - local tag = RowTag(entry, far, db.tagSymbols) +local function RenderRowTag(row, entry) + local tag = RowTag(entry, db.tagSymbols) if row.cTag == tag then return end row.cTag = tag if tag then @@ -1348,17 +1393,7 @@ local function RenderRowTag(row, entry, far) row.tag:Show() else row.tag:Hide() - if not far then SetNameOffset(row, 0) end - end -end - -local function RenderRowRange(row, e, far) - -- Range band in words (1.8.0): a greyed row in group range reads - -- "near" instead of "out of range" when the setting is on. - local farTxt = far and (db.rangeText and e.rangeBucket == 1 and L["near"] or L["out of range"]) or nil - if row.cFarTxt ~= farTxt then - row.cFarTxt = farTxt - if farTxt then row.far:SetText(farTxt) end + SetNameOffset(row, 0) end end @@ -1448,18 +1483,15 @@ end local function RenderRow(row, e, cached) row.entry, row.guid = e, e.guid - local far = e.outOfRange and true or false - RenderRowName(row, e, far) - RenderRowTag(row, e, far) - RenderRowRange(row, e, far) + RenderRowName(row, e) + RenderRowTag(row, e) RenderDurationBar(row, e) RenderRaidMarker(row, e) RenderRowTint(row, e) local m = e.missing RenderRowIcons(row, m) - if e.outOfRange or (cached and not X.RowTargetMatches(e)) then - -- Greyed placeholder row: no live binding behind the click, and the - -- cached binding is cleared so a reused row can't cast a stale target. + if cached and not X.RowTargetMatches(e) then + -- A cached entry whose unit token was recycled is display-only. row:SetAlpha(0.6) if row.bGuid ~= nil then ClearRowCast(row) end else @@ -1492,6 +1524,23 @@ function X.SetRowColor(rule, c) QueueRefresh() end +function X.AbortWindowScan() + viewport, viewportCount, rowOffset = nil, nil, nil + if nextBtn then nextBtn.entry, nextBtn.isClear = nil, false end + if groupBtn then groupBtn.entry, groupBtn.isClear = nil, false end + for _, row in ipairs(rows) do row.entry, row.guid = nil, nil end + rowLeftPress = nil + wipe(rowMouseButtons) + if InCombatLockdown() then return end -- secure combat drivers own clearing here + pcall(ClearNext) + pcall(ClearGroup) + for _, row in ipairs(rows) do + pcall(ClearRowCast, row) + pcall(row.Hide, row) + end + pcall(X.ShowWindowStatus, not db.hidden and L["Buff scan interrupted. Waiting for a fresh scan."]) +end + -- Drop paused or hidden rows without changing the independent keybind queue. -- A pause whose status is suppressed leaves an already-collapsed pill alone. function X.ShowWindowStatus(text, keepPill) @@ -1566,10 +1615,9 @@ local function BuildBuffView(list, n) order[#order + 1] = g end g.count = g.count + 1 - if (not e.outOfRange and (g.unit == nil or g.outOfRange)) or g.unit == nil then + if g.unit == nil then g.unit, g.class, g.castGuid, g.pet = e.unit, e.class, e.guid, e.pet - g.outOfRange = e.outOfRange and true or false - g.rangeBucket, g.approximateRange = e.rangeBucket, e.approximateRange + g.approximateRange = e.approximateRange end end end @@ -1587,11 +1635,29 @@ local function BuildBuffView(list, n) return order, #order end -local function PaintRowViewport(cached) +local function FitRows(n, extraHeight) + local height = X.ReadUnitNumber(UIParent.GetHeight, UIParent) + local width = X.ReadUnitNumber(UIParent.GetWidth, UIParent) + local scale = db.scale or 1 -- frame is a direct child of UIParent + height = height and height > 0 and height / scale - 12 or math.huge + width = width and width > 0 and width / scale - 12 or math.huge + local gap = db.rowGap or 0 + local budget = height - topHeight - FOOTER_H - 8 - extraHeight + gap + local pitch = rowHeight + gap + local single = math_max(1, math_floor(budget / pitch)) + local cols = db.twoCol and width >= (db.width or WIDTH) * 2 + 6 and (n > 8 or n > single) and 2 or 1 + if n > math_min(MAX_ROWS, single * cols) then + single = math_max(1, math_floor((budget - 14) / pitch)) + end + return math_min(MAX_ROWS, single * cols), cols +end + +local function PaintRowViewport(cached, extraHeight) local view, n = viewport, viewportCount - rowOffset = math_min(rowOffset or 0, math_max(0, n - MAX_ROWS)) - local shown = math_min(n, MAX_ROWS) - local wantCols = (db.twoCol and shown > 8) and 2 or 1 + local wantCols = columns + if not cached then visibleLimit, wantCols = FitRows(n, extraHeight) end + rowOffset = math_min(rowOffset or 0, math_max(0, n - visibleLimit)) + local shown = math_min(n, visibleLimit) local rowsTall = wantCols == 2 and math_floor((shown + 1) / 2) or shown if wantCols ~= columns or rowsTall ~= (previousRowsTall or shown) then columns, previousRowsTall = wantCols, rowsTall @@ -1602,7 +1668,7 @@ local function PaintRowViewport(cached) for i = 1, MAX_ROWS do if i <= shown then RenderRow(rows[i], view[rowOffset + i], cached) else ClearRow(rows[i]) end end - local overflow = n > MAX_ROWS + local overflow = n > visibleLimit if overflow then local y = -topHeight - rowsTall * rowHeight - math_max(0, rowsTall - 1) * (db.rowGap or 0) - 2 @@ -1619,20 +1685,21 @@ local function PaintRowViewport(cached) end function X.ScrollRows(step) - if not viewport or viewportCount <= MAX_ROWS or db.hidden + if not viewport or viewportCount <= visibleLimit or db.hidden or not frame:IsShown() or InCombatLockdown() or X.PlayerSuspended() or (db.clickThrough and db.locked) or RowMouseHeld() or X.ReadUnitBool(_G.IsMouseButtonDown, "LeftButton") == true or X.ReadUnitBool(_G.IsMouseButtonDown, "RightButton") == true then return false end if viewportMode ~= db.viewMode or viewportSearch ~= X.search or viewportRole ~= db.roleFilter or viewportTwoCol ~= db.twoCol then return false end - local offset = math_max(0, math_min(rowOffset + step, viewportCount - MAX_ROWS)) + local offset = math_max(0, math_min(rowOffset + step, viewportCount - visibleLimit)) if offset == rowOffset then return false end local owner = GameTooltip and GameTooltip.GetOwner and GameTooltip:GetOwner() if owner == frame or (owner and owner.GetParent and owner:GetParent() == frame) then GameTooltip:Hide() end rowOffset = offset - PaintRowViewport(true) - return true + local ok, err = pcall(PaintRowViewport, true) + if not ok then X.RefreshFault(err) end + return ok end local function AppendBuffCoverage(parts) @@ -1728,8 +1795,9 @@ local function RenderCoverage(entries, n) if db.consumables then for _, cd in ipairs(X.CONS_DEFS) do local t = X.consTally[cd.key] - if t and t.total > 0 then - parts[#parts + 1] = string_format("%s %d/%d", cd.label, t.total - t.miss, t.total) + if t then + local text = t.total > 0 and string_format("%s %d/%d", L[cd.label], t.total - t.miss, t.total) or L[cd.label] + parts[#parts + 1] = text .. (t.unknown > 0 and (" · " .. string_format(L["%d unknown"], t.unknown)) or "") end end end @@ -1793,8 +1861,6 @@ function X.RenderQueue(entries, n, sessionShow, wasAfterCombat) viewportMode, viewportSearch, viewportRole = db.viewMode, X.search, db.roleFilter viewportTwoCol = db.twoCol viewport, viewportCount = viewEntries, viewN - local shown, rowsTall = PaintRowViewport() - if X.UpdateNearbyTargetAfterScan then X.UpdateNearbyTargetAfterScan() end -- Post-combat catch-up: one border pulse when the frozen list thaws with -- work waiting, so a pull's-end rebuff round doesn't go unnoticed. if wasAfterCombat and n > 0 and X.Flash then X.Flash() end @@ -1814,11 +1880,14 @@ function X.RenderQueue(entries, n, sessionShow, wasAfterCombat) SetShownIfChanged(focusText, focusLine and true or false) end + local extras = (coverShown and 13 or 0) + (focusLine and 13 or 0) + local shown, rowsTall = PaintRowViewport(false, extras) + if X.UpdateNearbyTargetAfterScan then X.UpdateNearbyTargetAfterScan() end local h = topHeight + (shown > 0 and rowsTall * rowHeight + math_max(0, rowsTall - 1) * (db.rowGap or 0) or 18) + 8 if hint then h = h + 13 end if coverShown then h = h + 13 end if focusLine then h = h + 13 end - if viewN > MAX_ROWS then h = h + 14 end + if viewN > visibleLimit then h = h + 14 end h = h + FOOTER_H -- bottom row: settings gear + cast counter UpdateCounter() SetHeightIfChanged(frame, h) @@ -1976,7 +2045,7 @@ function X.SuspendWindow() end local function BuildWindowFrame() - frame = CreateFrame("Frame", "BuffRadarFrame", UIParent, + frame = X.PanelWidget("Frame", "BuffRadarFrame", UIParent, BackdropTemplateMixin and "BackdropTemplate" or nil) if X.PlayerSuspended() then frame:Hide() end frame:SetSize(db.width or WIDTH, HEADER_H + 30) @@ -2026,7 +2095,7 @@ local function BuildCloseControl() title:SetPoint("TOPLEFT", 9, -7) title:SetText("|cff33ccffBuff|rRadar") - local close = CreateFrame("Button", nil, frame, "UIPanelCloseButton") + local close = X.PanelWidget("Button", nil, frame, "UIPanelCloseButton") closeButton = close close:SetSize(22, 22) close:SetPoint("TOPRIGHT", 0, 0) @@ -2143,7 +2212,7 @@ local function BuildPill() -- All-buffed pill (1.6.0): with /br pill on, the full window collapses to -- this small button while the group is fully buffed. It sits where the -- window's top-left corner is; clicking it peeks at the full window. - pill = CreateFrame("Button", "BuffRadarPill", UIParent, + pill = X.PanelWidget("Button", "BuffRadarPill", UIParent, BackdropTemplateMixin and "BackdropTemplate" or nil) if X.PlayerSuspended() then pill:Hide() end pill:SetSize(150, 22) @@ -2298,7 +2367,7 @@ local function BuildFinder() local findLabel = findBar:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall") findLabel:SetPoint("LEFT", 2, 0) findLabel:SetText("Find:") - findEdit = CreateFrame("EditBox", nil, findBar, "InputBoxTemplate") + findEdit = X.PanelWidget("EditBox", nil, findBar, "InputBoxTemplate") findEdit:SetSize(130, 16) findEdit:SetPoint("LEFT", findLabel, "RIGHT", 6, 0) findEdit:SetAutoFocus(false) @@ -2407,7 +2476,7 @@ function X.SetFinderText(text) end function X.HasHeldRow() - return (viewportCount or 0) > MAX_ROWS and RowMouseHeld() + return (viewportCount or 0) > visibleLimit and RowMouseHeld() end function X.QueueVisibility(entries, index) @@ -2415,7 +2484,7 @@ function X.QueueVisibility(entries, index) if row.entry == entries[index] then return "visible" end end if db.viewMode == "people" and viewport == entries - and (index <= (rowOffset or 0) or index > (rowOffset or 0) + MAX_ROWS) then + and (index <= (rowOffset or 0) or index > (rowOffset or 0) + visibleLimit) then return "overflow" end end diff --git a/BuffRadar/Wizard.lua b/BuffRadar/Wizard.lua index d8edd4e..89428a3 100644 --- a/BuffRadar/Wizard.lua +++ b/BuffRadar/Wizard.lua @@ -92,8 +92,8 @@ local function FinishSetup(w) ApplyGeometry() ApplyAppearance() X.ApplyRowLayout() - X.Intel.ForgetAlerts() - X.Intel.SettingsChanged() + X.SettingsChanged({ forecastSeconds = true, smartPriority = true, visualAlerts = true, + statusMinimap = true, profile = true }) if X.RefreshConfig then X.RefreshConfig() end Print(L["Quick Setup complete. Run /br wizard to make new choices."]) end @@ -106,7 +106,7 @@ function X.OpenWizard() end local w = X.wizardFrame if not w then - w = CreateFrame("Frame", "BuffRadarWizard", UIParent, BackdropTemplateMixin and "BackdropTemplate" or nil) + w = X.PanelWidget("Frame", "BuffRadarWizard", UIParent, BackdropTemplateMixin and "BackdropTemplate" or nil) X.wizardFrame = w w:SetSize(422, 334) w:SetPoint("CENTER") @@ -129,27 +129,24 @@ function X.OpenWizard() w.body:SetWordWrap(true) w.choice = {} for i = 1, 3 do - local b = CreateFrame("Button", nil, w, "UIPanelButtonTemplate") + local b = X.PanelWidget("Button", nil, w, "UIPanelButtonTemplate") b:SetSize(252, 28) b:SetPoint("TOP", w, "TOP", 0, -100 - (i - 1) * 38) w.choice[i] = b end - w.back = CreateFrame("Button", nil, w, "UIPanelButtonTemplate") + w.back = X.PanelWidget("Button", nil, w, "UIPanelButtonTemplate") w.back:SetSize(94, 24) w.back:SetPoint("BOTTOMLEFT", 16, 14) w.back:SetText(L["Back"]) w.back:SetScript("OnClick", function() X.WizardPage(w.page - 1) end) - w.next = CreateFrame("Button", nil, w, "UIPanelButtonTemplate") + w.next = X.PanelWidget("Button", nil, w, "UIPanelButtonTemplate") w.next:SetSize(112, 24) w.next:SetPoint("BOTTOMRIGHT", -16, 14) w.next:SetText(L["Apply"]) w.next:SetScript("OnClick", function() FinishSetup(w) end) - local close = CreateFrame("Button", nil, w, "UIPanelCloseButton") + local close = X.PanelWidget("Button", nil, w, "UIPanelCloseButton") close:SetPoint("TOPRIGHT", -5, -5) - close:SetScript("OnClick", function() - db.wizardSeen = true - w:Hide() - end) + close:SetScript("OnClick", function() w:Hide() end) w.close = close w:SetScript("OnHide", function() w.draft = nil end) if UISpecialFrames then table.insert(UISpecialFrames, "BuffRadarWizard") end @@ -230,7 +227,7 @@ function X.CheckRange() for i = 1, core.EntryCount() do local e = entries[i] local g = e.guid - if g and X.farPrev[g] and not e.outOfRange and not e.pet then + if g and X.farPrev[g] and not e.pet then local name = X.farPrev[g] == true and e.name or X.farPrev[g] Print(string_format("%s is in range now and still needs a buff.", name)) PlayAlert("new") @@ -582,82 +579,240 @@ function X.DiscordText() return table.concat(lines, "\n") end +local function ReviewText(f, lines) + f.reviewText:SetText(table.concat(lines, "\n")) + f.reviewChild:SetHeight(math.max(1, f.reviewText:GetStringHeight() or 1)) + f.review:SetVerticalScroll(0) +end + +local function ReviewNamedProfile(f) + local name = f.nameBox:GetText():match("^%s*(.-)%s*$") + local valid = X.Settings.IsProfileName(name) + local prior = valid and db.profiles[name] or nil + local used = valid and table.concat(X.ProfileMappings(name), ", ") or "" + local lines = { valid and string_format(L["Store as %s without loading its settings."], name) + or L["Profile names use letters, numbers, - and _ (max 40)."] } + if prior then lines[#lines + 1] = string_format(L["Existing profile: %s. Enter a different name to keep it."], name) end + if used ~= "" then lines[#lines + 1] = string_format(L["Auto-profile mappings using this name: %s"], used) end + f.reviewName, f.reviewPrior, f.reviewMappings = name, prior, used + f.apply:SetText(L[prior and "Replace profile" or "Save profile"]) + f.apply:SetEnabled(valid and true or false) + lines[#lines + 1] = L["Compared with your current settings (not applied):"] + for _, line in ipairs(f.profileLines) do lines[#lines + 1] = line end + if #f.profileLines == 0 then lines[#lines + 1] = L["No settings or plan values would change."] end + ReviewText(f, lines) +end + +local function ReviewImport(f) + return X.Measure("import", function() + local parse = f.importMode == "plan" and X.ParsePlanImport + or f.importMode == "profile" and X.ParseSharedProfile or X.ParseSettingsImport + local draft, err = parse(f.editBox:GetText()) + if not draft then Print(err); return end + f.draft, f.reviewDB, f.reviewSignature, f.shareScope = draft, db, nil, nil + f.title:SetText(L["Review before applying"]) + f.editBox:ClearFocus() + f.editBox:Hide() + f.accept:Hide() + f.back:Show() + f.review:Show() + f.apply:SetEnabled(true) + f.apply:Show() + if f.importMode == "profile" then + f.profileLines = X.ReviewSettings(draft.patch) + f.nameBox:Show() + f.nameBox:SetText(draft.name) + ReviewNamedProfile(f) + return + end + f.apply:SetText(L["Apply locally"]) + local lines, _, scope + if f.importMode == "plan" then lines, _, scope = X.ReviewPlan(draft) + else lines = X.ReviewSettings(draft) end + f.reviewSignature, f.shareScope = table.concat(lines, "\n"), scope or nil + f.share:SetShown(f.shareScope ~= nil) + if #lines == 0 then lines[1] = L["No settings or plan values would change."] end + if f.importMode == "plan" then + lines[#lines + 1] = L["Auto-profile mappings stay local, even when sharing."] + if scope then + local channel = scope:match("^(%u+):") + lines[#lines + 1] = string_format(L["Apply and share sends changed assignments and blessings to %s."], + L[channel == "RAID" and "the raid" or "the party"]) + else lines[#lines + 1] = L["Group sharing is unavailable for this review."] end + end + ReviewText(f, lines) + end) +end + +local function ApplyImport(f, share) + if not f.draft or f.reviewDB ~= db or InCombatLockdown() or X.PlayerSuspended() then return end + local ok, msg = X.Measure("import", function() + if f.importMode == "profile" then + local name = f.nameBox:GetText():match("^%s*(.-)%s*$") + local lines = X.ReviewSettings(f.draft.patch) + if name ~= f.reviewName or db.profiles[name] ~= f.reviewPrior + or table.concat(X.ProfileMappings(name), ", ") ~= f.reviewMappings + or table.concat(lines, "\n") ~= table.concat(f.profileLines, "\n") then + f.profileLines = lines + ReviewNamedProfile(f) + return false, L["The current values changed. Review again before applying."] + end + return X.StoreProfile(name, f.draft.body, f.reviewPrior) + end + local plan = f.importMode == "plan" + local lines = plan and X.ReviewPlan(f.draft) or X.ReviewSettings(f.draft) + if f.reviewSignature ~= table.concat(lines, "\n") then + ReviewImport(f) + return false, L["The current values changed. Review again before applying."] + end + if plan then + if share and not f.shareScope then return false, L["Group sharing is unavailable for this review."] end + return X.ApplyPlan(f.draft, share and f.shareScope or nil) + end + X.ApplyProfile(f.draft) + return true, L["Settings applied locally."] + end) + Print(msg) + if not ok then return end + f.completed = true + f:Hide() + ApplyGeometry() + ApplyAppearance() + X.ApplyRowLayout() + if X.RefreshConfig then X.RefreshConfig() end + QueueRefresh() +end + +local function ShowPaste(f, importing) + f.draft, f.reviewDB, f.reviewPrior, f.profileLines = nil, nil, nil, nil + f.title:SetText(f.pasteTitle) + f.review:Hide() + f.nameBox:Hide() + f.apply:Hide() + f.share:Hide() + f.back:Hide() + f.accept:SetShown(importing) + f.editBox:Show() + f.editBox:SetFocus() + f.editBox:HighlightText() +end + function X.ShowExport(text, forImport, titleText, mode) if X.PlayerSuspended() then return end - if InCombatLockdown() then Print("Can't open that during combat."); return end + if InCombatLockdown() then Print(L["Can't open that during combat."]); return end local f = X.exportFrame if not f then - f = CreateFrame("Frame", "BuffRadarExportFrame", UIParent, + f = X.PanelWidget("Frame", "BuffRadarExportFrame", UIParent, BackdropTemplateMixin and "BackdropTemplate" or nil) X.exportFrame = f - f:SetSize(440, 150) + f:SetSize(550, 275) f:SetPoint("CENTER") + f:SetClampedToScreen(true) f:SetFrameStrata("DIALOG") + f:EnableMouse(true) if f.SetBackdrop then - f:SetBackdrop({ - bgFile = "Interface\\Tooltips\\UI-Tooltip-Background", - edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", - tile = true, tileSize = 16, edgeSize = 12, - insets = { left = 3, right = 3, top = 3, bottom = 3 }, - }) + f:SetBackdrop({ bgFile = "Interface\\Tooltips\\UI-Tooltip-Background", + edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", tile = true, tileSize = 16, edgeSize = 12, + insets = { left = 3, right = 3, top = 3, bottom = 3 } }) f:SetBackdropColor(0.04, 0.05, 0.09, 0.97) f:SetBackdropBorderColor(0.35, 0.55, 0.8, 1) end - f:EnableMouse(true) - f:SetMovable(true) - f:RegisterForDrag("LeftButton") - f:SetScript("OnDragStart", function(self) self:StartMoving() end) - f:SetScript("OnDragStop", function(self) self:StopMovingOrSizing() end) f.title = f:CreateFontString(nil, "OVERLAY", "GameFontNormal") f.title:SetPoint("TOPLEFT", 12, -10) - local close = CreateFrame("Button", nil, f, "UIPanelCloseButton") + local close = X.PanelWidget("Button", nil, f, "UIPanelCloseButton") close:SetSize(22, 22) close:SetPoint("TOPRIGHT", 0, 0) close:SetScript("OnClick", function() f:Hide() end) local eb = CreateFrame("EditBox", nil, f) - eb:SetPoint("TOPLEFT", 12, -34) - eb:SetPoint("BOTTOMRIGHT", -12, 36) + eb:SetPoint("TOPLEFT", 12, -38) + eb:SetPoint("BOTTOMRIGHT", -12, 38) eb:SetMultiLine(true) - if eb.SetAutoFocus then eb:SetAutoFocus(false) end + eb:SetAutoFocus(false) if eb.SetFontObject and ChatFontNormal then eb:SetFontObject(ChatFontNormal) end - eb:SetScript("OnEscapePressed", function(self) if self.ClearFocus then self:ClearFocus() end end) + eb:SetScript("OnEscapePressed", function() f:Hide() end) f.editBox = eb - local acc = CreateFrame("Button", nil, f, "UIPanelButtonTemplate") - acc:SetSize(110, 22) - acc:SetPoint("BOTTOMRIGHT", -12, 8) - acc:SetText("Import") - acc:SetScript("OnClick", function() - local ok, msg - if f.importMode == "plan" then - ok, msg = X.PlanImport(f.editBox:GetText()) - elseif f.importMode == "profile" then - ok, msg = X.ProfileImport(f.editBox:GetText()) - elseif f.importMode == "ignore" then - ok, msg = X.IgnoreImport(f.editBox:GetText()) - else - local txt = f.editBox:GetText() - if X.PrintDiff then X.PrintDiff(txt, "This import") end -- what it changes, before it does (1.12.0) - ok, msg = X.Import(txt) - end + f.review = CreateFrame("ScrollFrame", nil, f) + f.review:SetPoint("TOPLEFT", 12, -36) + f.review:SetPoint("BOTTOMRIGHT", -12, 65) + f.review:EnableMouseWheel(true) + f.review:SetScript("OnMouseWheel", function(self, delta) + local scroll = math.max(0, math.min(self:GetVerticalScrollRange(), self:GetVerticalScroll() - delta * 48)) + self:SetVerticalScroll(scroll) + end) + f.reviewChild = CreateFrame("Frame", nil, f.review) + f.reviewChild:SetSize(520, 1) + f.review:SetScrollChild(f.reviewChild) + f.reviewText = f.reviewChild:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall") + f.reviewText:SetPoint("TOPLEFT") + f.reviewText:SetWidth(520) + f.reviewText:SetJustifyH("LEFT") + f.nameBox = X.PanelWidget("EditBox", nil, f, "InputBoxTemplate") + f.nameBox:SetSize(208, 22) + f.nameBox:SetPoint("BOTTOMLEFT", 17, 38) + f.nameBox:SetAutoFocus(false) + f.nameBox:SetMaxLetters(40) + f.nameBox:SetScript("OnTextChanged", function() if f.profileLines then ReviewNamedProfile(f) end end) + f.nameBox:SetScript("OnEscapePressed", function() f:Hide() end) + local function button(label, w, anchor, offset, action, y) + local b = X.PanelWidget("Button", nil, f, "UIPanelButtonTemplate") + b:SetSize(w, 22) + b:SetPoint(anchor, offset, y or 8) + b:SetText(L[label]) + b:SetScript("OnClick", function() + if f:IsShown() and b:IsShown() and not InCombatLockdown() and not X.PlayerSuspended() then action() end + end) + return b + end + f.back = button("Edit paste", 135, "BOTTOMLEFT", 12, function() ShowPaste(f, true) end) + f.share = button("Apply and share", 170, "BOTTOMRIGHT", -98, function() ApplyImport(f, true) end, 37) + f.apply = button("Apply locally", 170, "BOTTOMRIGHT", -98, function() ApplyImport(f) end) + f.cancel = button("Cancel", 80, "BOTTOMRIGHT", -12, function() f:Hide() end) + f.accept = button("Review import", 145, "BOTTOMRIGHT", -98, function() + if f.importMode ~= "ignore" then ReviewImport(f); return end + local ok, msg = X.IgnoreImport(f.editBox:GetText()) Print(msg) - if ok then - f:Hide() - ApplyGeometry() - ApplyAppearance() - if X.RefreshConfig then X.RefreshConfig() end - if QueueRefresh then QueueRefresh() end - end + if ok then f.completed = true; f:Hide() end + end) + f:SetScript("OnHide", function() + if f.importing and not f.completed then Print(L["Import canceled."]) end + f.draft, f.reviewDB, f.reviewPrior, f.importing, f.profileLines = nil, nil, nil, nil, nil + f.editBox:ClearFocus() + f.nameBox:ClearFocus() end) - f.accept = acc if UISpecialFrames then UISpecialFrames[#UISpecialFrames + 1] = "BuffRadarExportFrame" end f:Hide() end - f.title:SetText(titleText or (forImport and "BuffRadar -- paste a settings string, then Import" - or "BuffRadar -- your settings string (select all, copy)")) - f.importMode = mode or "settings" -- what the Import button applies (1.8.0) + f.importMode, f.importing, f.completed = mode or "settings", forImport, nil + f.pasteTitle = titleText or L[forImport and "Paste a legacy BR1 settings copy, then review." + or "Legacy BR1 settings copy (select all, copy)"] f.editBox:SetText(text or "") - f.accept:SetShown(forImport and true or false) + f.accept:SetText(L[f.importMode == "ignore" and "Import" or "Review import"]) f:Show() - if f.editBox.SetFocus then f.editBox:SetFocus() end - if f.editBox.HighlightText then f.editBox:HighlightText() end + ShowPaste(f, forImport and true or false) +end + +function X.ShowSaveState(state) + if state == "future" then Print(L["A newer BuffRadar save was preserved. Changes are for this session only."]) + elseif state == "overflow" then + Print(L["Too many profiles or ignores. The original save was preserved; changes are temporary."]) + Print(L["Use /br storage delete profile or /br storage delete ignore , then reload."]) + end +end + +function X.RequestProfileSave(name) + if not X.Settings.IsProfileName(name) then + Print(L["Profile names use letters, numbers, - and _ (max 40)."]) + return + end + local prior = db.profiles[name] + if not prior then + local _, msg = X.SaveProfile(name) + Print(msg) + if X.RefreshConfig then X.RefreshConfig() end + return + end + local body = X.ProfileSnapshot() + if not body then Print(L["These settings are too large to save as a profile."]); return end + X.ShowExport("BuffRadar profile: " .. name .. "\n" .. body, true, L["Review before applying"], "profile") + if X.exportFrame and X.exportFrame:IsShown() and not InCombatLockdown() then ReviewImport(X.exportFrame) end end diff --git a/QUALITY.md b/QUALITY.md index 8bc8599..f43a0d1 100644 --- a/QUALITY.md +++ b/QUALITY.md @@ -68,7 +68,7 @@ are named below as waivers with owners and follow-ups, not hidden. |---|---|---|---| | Correctness (14) | 5 | Pass | Full gate green (Lua 5.1 compile, luacheck 0/0, locale, trial run × 7 fake-client setups, 0 errors) and every release through 1.15.31 passed in game (SEAN, 2026-11-16). | | Security & privacy (12) | 4 | Pass | Risk Tier 0: no network, no credentials, no data leaves the client; SavedVariables are local settings/stats only. Addon comms ride the game's group channel on one prefix; assignment/blessing-plan messages are trust-gated (leader/assistant; paladin for blessings). `SECURITY.md` present. | -| Robustness (11) | 4 | Pass | SavedVariables migration chain v2→v22 smoke-tested, including corrupt-save replacement and repair of corrupt custom-spell / auto-profile entries; a strict sanitizer rebuilds settings on load; handlers are pcall-wrapped so one bad event can't kill the addon. | +| Robustness (11) | 4 | Pass | SavedVariables v2→v23 migration and detached nested validation are smoke-tested, including future/over-limit preservation and explicit recovery; handlers are pcall-wrapped so one bad event can't kill the addon. | | Feature completeness (9) | 4 | Pass | Core purpose complete. The approved 50-item program is **complete** with **nothing parked**: 44 shipped by 1.9.0, three duplicates replaced in-batch (#23, #10, #15), and the three parked items built later (#8 and #19 in 1.14.0, #33 in 1.15.0). Three further suggestion lists are done except one platform limit recorded in `docs/SUGGESTIONS.md` (#13: the game does not let addons auto-cast, so out-of-range players get a notice instead). Not 5: that limit. | | Performance (8) | 4 | Pass (waiver closed 2026-11-16) | Budget defined 2026-11-16 (`docs/DECISIONS.md`) and enforced by the trial run on every push: a worst-case scan (every player missing every buff) reads ≤8 auras per player, grows linearly from 20 to 40 players, and averages <5 ms in the fake client (measured: ~5.75 reads per player, ~0.7 ms for 40 players). Scans are event-driven, coalesced to one per 0.1 s and ticked every 0.4 s; rows are pooled. Not 5: the in-game target (`/br perf` average ≤2 ms, worst ≤8 ms in a 40-player raid) has no field numbers yet. | | Maintainability (7) | 3 | **Waiver** (minor) | The TOC refactor moves window refresh, secure widgets, minimap, and the save schema out of the core. `BuffRadar.lua` is now ~5,300 lines, down from ~7,600 before the refactor; `Config.lua` is still ~4,100. All files compile with Lua 5.1's local and upvalue limits enforced. A Forever field test of the secure cast path is still required. | @@ -76,10 +76,10 @@ are named below as waivers with owners and follow-ups, not hidden. | UX & accessibility (6) | 4 | Pass (waiver closed 2026-11-16) | The UI is complete in code and smoke, and SEAN's in-game field test passed for every release through 1.15.31 on Forever (reported 2026-11-16). Not 5: no accessibility audit beyond the tag-symbol, reduced-motion and text-scale options. | | Scalability (5) | 3 | Pass | Host caps group size (40); scan cost is linear in roster size and throttled; the row pool is capped at 15 with overflow counted on the coverage line. 10x/100x testing is not applicable to a host-capped addon; the cap behaviour is smoke-tested. | | Idiomatic quality (5) | 4 | Pass | luacheck 1.2.0 at strict settings: 0 warnings / 0 errors; project checkers (compile, limits, locale) green; consistent style across the file. | -| Test & corpus evidence (5) | 4 | Pass | Corpus = the trial run: 350/350 steps in five setups, 351/351 in the German setup at 1.15.32, plus the two-client coordination run, the package check, migration fixtures from real legacy save shapes, corrupt-data fixtures, a randomized roster/combat step and the performance-budget step. The corpus only grows. Line-coverage percentage is not measurable for this stack, so the corpus fraction is the recorded evidence. | +| Test & corpus evidence (5) | 4 | Pass | 1.15.38: 2,802 smoke steps across seven fake-client setups, 22 two-client coordination scenarios, and seven packaging regressions. See the [audit ledger](docs/AUDIT_1.15.38.md) and [candidate matrix](docs/FOREVER_1.15.38_VALIDATION.md); Windows package parity passed in CI; the full local Windows gate and live Forever checks remain pending. The corpus only grows. Line-coverage percentage is not measurable for this stack, so the corpus fraction is the recorded evidence. | | Self-documentation (4) | 3 | Pass | Section banners and why-comments throughout; architecture and rules in `AGENTS.md`; module map in the root README's Layout table. Versioned [status API](docs/STATUS_API.md) and [roadmap](docs/ROADMAP.md). | | Documentation (4) | 4 | Pass | Four-doc set per edition (README / FEATURES / DESCRIPTION / CHANGELOG) plus `tools/README.md`, in-game help covering every command, `SECURITY.md`, and `## TL;DR` openings on all three READMEs (added at adoption). Checked against the code at every release. | -| Diagnostics & supportability (4) | 4 | Pass | `/br selftest` (versioned paste-able block), `/br debug`, `/br apicheck [export]` (client API probe), `/br buffcheck` (spell table vs live client), `/br perf` (scan ms, memory), `/br why ` (the deciding listing check) and the Nearby Player Diagnostics panel. Local only; nothing is sent anywhere. Not 5: no stable error IDs — the game's error frame carries those. | +| Diagnostics & supportability (4) | 4 | Pass | `/br selftest` (versioned paste-able block), `/br debug`, `/br apicheck [export]` (client API probe), `/br buffcheck` (spell table vs live client), `/br perf` (separate CPU timing buckets and total addon memory), `/br why ` (the deciding listing check) and the Nearby Player Diagnostics panel. Local only; nothing is sent anywhere. Not 5: no stable error IDs — the game's error frame carries those. | **Total: 78 / 100.** No dimension is Fail and none is below 3. Both major waivers SEAN approved on 2026-10-25 are now closed: the UX field test diff --git a/README.md b/README.md index 538cf4c..e1dc62d 100644 --- a/README.md +++ b/README.md @@ -8,13 +8,19 @@ BuffRadar shows which players need a buff you can cast in **WoW: Forever** (Interface 16001). Click a name, press your **Cast next buff** key, or use a macro to work through the list. Your character goes first by default. +**1.15.38 candidate:** safer imports and saves, stricter cast checks, and a +list that fits shorter viewports. See the [changes](editions/forever/CHANGELOG.md) +and [verification status](docs/FOREVER_1.15.38_VALIDATION.md). + ## Download and Install 1. Download the Forever ZIP from the [latest GitHub release](https://github.com/SeanShaffer88/BuffRadar/releases/latest) or the [CurseForge project](https://www.curseforge.com/wow/addons/buffradar). 2. Extract the `BuffRadar` folder into your Forever client's `Interface/AddOns` folder. The installed TOC should be at `Interface/AddOns/BuffRadar/BuffRadar.toc`. -3. Enable BuffRadar in the game's AddOns list. +3. Enable BuffRadar in the game's AddOns list. `/br selftest` reports the + installed version and client interface. This package needs Interface 16001; + loading it as out of date on another interface does not enable casting. ## Quick Start @@ -48,8 +54,8 @@ macro to work through the list. Your character goes first by default. | Discovery and eligibility | Checks group members, target, mouseover, and readable friendly nameplates for buffs you know that fit the recipient. Uses spell range where available and proximity where needed. `/br assumerange` lets you opt into listing players with unknown range. `/br rangewatch` can alert when someone who needs a buff enters range. | | Safety and pauses | Combat hides and disarms cast rows and excludes targets in combat. Death and ghost state suspend the addon UI. Choose group-only visibility, major-city pauses, battleground and arena pauses, flight-path pauses, PvP skips, and a low-mana threshold with `/br group`, `/br cities`, `/br bg`, `/br taxi`, `/br pvp`, and `/br mana`. | | Queue order | Check yourself first, prioritize recently resurrected players, and pin one player. Sort by name, tanks and leaders, distance, or most buffs needed. Filter by name or by group role when the client supplies roles. Use `/br self`, `/br pin`, `/br sort`, `/br find`, and `/br filter`. | -| List views | Use `/br view people\|buffs` for a row per player or per needed buff. The buff view shows how many players need each buff. Scroll long lists with the wheel or `/br scroll up\|down`. The cast-next key still uses the head of the full queue. | -| Ignore lists | Right-click a row to save an ignore or Shift-right-click to ignore for this session. Manage entries under **Ignore & Stats** or with `/br ignore`, `/br unignore`, `/br signore`, and `/br unsignore`. Export or import the list with `/br ignorelist export` or `/br ignorelist import`. | +| List views | Use `/br view people\|buffs` for a row per player or per needed buff. The list fits up to 15 rows to the usable screen size. Scroll with the wheel or `/br scroll up\|down`; Cast Next Buff still uses the head of the full queue. | +| Ignore lists | Right-click a row to save an ignore or Shift-right-click to ignore for this session. Manage entries under **Ignore & Stats** or with `/br ignore`, `/br unignore`, `/br signore`, and `/br unsignore`. Export or import with `/br ignorelist export` or `/br ignorelist import`. The permanent list holds up to 192 names; imports past that limit do not partially apply. | | Scan options | `/br throttle on` adjusts periodic scans to movement, group size, and latency without delaying event refreshes. `/br fastaura` skips rescans when a readable aura change can be identified as unrelated to watched buffs. | ### Casting @@ -68,8 +74,9 @@ macro to work through the list. Your character goes first by default. - **Group versions.** Set the minimum need for automatic group-cast offers with `/br groupcast`. Enable Shift-click with `/br modclick` and register your own spells with `/br grouppair "Single" "Group"`. BuffRadar falls - back to a single-target cast when group eligibility or known reagent - availability blocks the group cast. + back to a single-target cast when the roster, assignment, spell range, + cooldown, or a required reagent blocks the group cast. Supported group pets + get single-target buffs; they do not count toward the group-cast threshold. - **Cast controls.** `/br mode` selects target, spell ID, macro, or ranked macro mode. `/br clickreg` chooses when clicks fire. If BuffRadar can tie a line-of-sight failure to its cast, it skips that target temporarily so @@ -133,10 +140,10 @@ aura and Hunter aspect reminders with `/br aura`. | Raid Preparation | Open the read-only checklist from **Raid Coverage** or use `/br prep`. Expand a player for missing and expiring buffs, consumable checks, and unknown readings. **Reagents** compares carried quantities with estimated needs and flags shortfalls. Roster changes refresh the open checklist and preserve expansion for a player still present. Open **Personal** with `/br readiness`, even solo, for food, flask, an optional consumable aura, carried Healthstones, durability, and applicable weapon and pet checks. | | Subgroup Responsibilities | Open from **Raid Coverage** or `/br subgroup panel`. Restrict a buff to selected raid groups, preview the affected roster, and see why a group cast may fall back to a single-target cast. For example, `/br subgroup FORTITUDE 1,2` assigns groups 1 and 2. Set **All** or **None** as needed. Rules clear when you leave the raid or reload. | | Ready Checks | `/br ready show` lists player responses, missing and expiring buffs, unknowns, and estimated group reagents. `/br readypost` lets leaders and assistants enable automatic group-chat summaries. | -| Recaps and sharing | Get a death recap or post-wipe rebuff report and reprint them with `/br death show` and `/br wipe show`. Use `/br summary` for needs by buff, `/br announce` for party or raid chat, and `/br discord` for copyable Markdown. | +| Recaps and sharing | Get a death recap or post-wipe rebuff report and reprint them with `/br death show` and `/br wipe show`. Use `/br summary` for needs by buff, `/br announce` requests a party or raid send and falls back to a local report on refusal; it cannot confirm delivery. `/br discord` copies Markdown. | | Coverage line | Pick visible parts with `/br cover` including progress, buffs and cooldowns, the active or away BuffRadar roster, group expiry, world buffs, drinking healers, and session uptime. `/br uptime` reports the share of grouped scans that found every checked player buffed. | | Encounter debuffs | In Settings → **Readiness**, or with `/br debuff add [player\|focus] [encounter ID]` and `/br debuff on`, show readable auras and their stacks in a separate strip. An encounter ID restricts a rule to that fight. | -| Extras to watch | Read flask and food counts for Forever, see your temporary weapon enchant, and track your focus target's buff needs, world buff timers, or drinking healers. Watch group pets for Fortitude, Mark of the Wild, and Arcane Intellect. Use `/br consumables`, `/br weapon`, `/br focus`, `/br worldbuff`, `/br drink`, or `/br pets`. | +| Extras to watch | Read recognised flask and food auras and see your temporary melee-weapon coating, and track your focus target's buff needs, world buff timers, or drinking healers. Watch group pets for Fortitude, Mark of the Wild, and Arcane Intellect. Use `/br consumables`, `/br weapon`, `/br focus`, `/br worldbuff`, `/br drink`, or `/br pets`. | ### Group Coordination @@ -176,7 +183,9 @@ aura and Hunter aspect reminders with `/br aura`. - **Window layout.** Drag, lock, resize from the bottom corners, reset position or appearance, and set width, list scale, or settings scale independently. Save position per character and scale per specialization. - Move the window through the game's Edit Mode when the client exposes it. + Use `/br positions on` to remember the Settings and Ready Check panels' + positions separately (off by default); use `reset` to recenter them. + Move the main window through the game's Edit Mode when available. Hold Shift to snap while resizing when enabled. Click-through while locked, idle fade, an all-buffed pill with click-to-peek, and empty-list hiding are optional. Hover to show the close button. Hiding the title @@ -213,9 +222,9 @@ aura and Hunter aspect reminders with `/br aura`. |---|---| | Presets and specialization | Quick Setup drafts a preset and alert preferences based on your activity and role. It applies them only on confirmation. Standalone presets are available through `/br preset`. Buff toggles and rebuff overrides can follow the active specialization when the client identifies it. | | Named profiles | Save, load, list, delete, and share profiles from **Ignore & Stats** or `/br profile`. Preview a saved profile's differences with `/br profile diff `. `/br autoprofile` can switch profiles for raids, dungeons, battlegrounds, grouped world play, or solo play. | -| Import and export | Use `/br export` and `/br import` for settings strings and `/br diff ` to preview them. Share the Class & Role Assignments table with `/br profile share` and `/br profile import`. A shared profile can replace a saved profile of the same name and is applied when loaded. Use `/br plan export` and `/br plan import` to transfer and merge group buff assignments, the blessing plan, and auto-profile mappings. | -| Casts and history | Show session and all-time totals, reset counters, see per-spell stats or export them, and review the last 50 tracked casts. See `/br count`, `/br resetcount`, `/br stats`, and `/br history`. `/br offenders` tracks players seen unbuffed across group sessions. | -| Troubleshooting | `/br why ` explains how a player is handled. `/br debug` reports client and window state, `/br clicks` logs cast attempts, `/br selftest` prints a report for bug reports, `/br apicheck export` produces a copyable API report, `/br buffcheck` checks spell IDs, and `/br perf` reports scan timings when available. `/br stats memory` reports the game's addon total, not per-feature estimates. `/br lite on` pauses forecasts, readiness, debuffs, and optional watches without changing their saved settings. | +| Import and export | `/br import` reviews a legacy BR1 settings copy before applying it locally. `/br profile import` previews a named profile; rename it or confirm replacement, then load it separately. `/br plan import` reviews a plan and defaults to applying locally. **Apply and share** requires current group authority and sync, and sends only changed assignments and blessings, never auto-profile mappings. | +| Casts and history | Show session and all-time totals, reset counters, see per-spell stats or export them, and review the last 50 tracked casts. See `/br count`, `/br resetcount`, `/br stats`, and `/br history`. `/br offenders` tracks up to 50 records by player identity, counted once per group session. | +| Troubleshooting | `/br why ` explains how a player is handled. `/br debug` reports client and window state, `/br clicks` logs cast attempts, `/br selftest` prints a report for bug reports, `/br apicheck export` produces a copyable API report, `/br buffcheck` checks spell IDs, and `/br perf` reports separate scan, preparation, import and debuff CPU timings when available. `/br stats memory` reports the game's addon total, not per-feature estimates. `/br lite on` pauses forecasts, readiness, debuffs, and optional watches without changing their saved settings. | | UI integration and feedback | Use the [read-only status API](docs/STATUS_API.md) or `/br status export`. Get a copyable feature-request link with `/br feedback` or see the [roadmap](docs/ROADMAP.md). | ## Player Guides @@ -243,8 +252,9 @@ BuffRadar has targeted Forever since 1.8.0. The last Retail release was The [Forever TOC](editions/forever/BuffRadar.toc) and the historical [Retail TOC](BuffRadar/BuffRadar.toc) load a shared Lua 5.1 implementation: -- [Data](BuffRadar/Data.lua) initializes the addon namespace. [SavedVariables](BuffRadar/SavedVariables.lua) - validates and migrates `BuffRadarDB` on load; [Profiles](BuffRadar/Profiles.lua) +- [Data](BuffRadar/Data.lua) checks the client using the shipping TOC marker. + [SavedVariables](BuffRadar/SavedVariables.lua) validates and migrates + `BuffRadarDB` on a detached copy; [Profiles](BuffRadar/Profiles.lua) handles settings and plan imports and exports. - [Core](BuffRadar/BuffRadar.lua) scans and builds the cast queue. [Intelligence](BuffRadar/Intelligence.lua) owns scan cadence, forecasts and @@ -267,7 +277,7 @@ The [Forever TOC](editions/forever/BuffRadar.toc) and the historical |---|---| | `BuffRadar/` | Shared addon source, translations, art, bindings, and historical Retail files | | `editions/forever/` | The Forever edition's `.toc`, README and changelog | -| `build.ps1` | Packages the supported Forever edition and SHA-256 checksum with PowerShell 7 | +| `build.ps1`, `tools/package.sh` | PowerShell 7 and POSIX entry points to the same deterministic Forever packager | | `tools/` | Automated checks — see [tools/README.md](tools/README.md) | | `.luacheckrc` | luacheck settings used by the checks | | `AGENTS.md` | Project rule sheet (prompt in force, frozen foundation, gate) | @@ -277,14 +287,22 @@ The [Forever TOC](editions/forever/BuffRadar.toc) and the historical ## Making a Release -```powershell -.\tools\check.ps1 -Setup # first time only -.\tools\check.ps1 # luacheck, Lua 5.1 compile and limits, translations, trial run -.\build.ps1 # Forever ZIP and SHA256SUMS.txt in dist\ +Run `sh tools/gate.sh` on POSIX (Python 3.10+ with Lupa) and Luacheck 1.2.0 +on `BuffRadar/`, or use `tools/check.ps1` in PowerShell 7 (`-Setup` once). +Build with `sh tools/package.sh` or `./build.ps1`. Both write the Forever ZIP +and `SHA256SUMS.txt` to `dist/`. With the gate's Python environment active, run: + +```sh +python -I tools/checkpackage.py dist/BuffRadar-X.Y.Z-Forever.zip . ``` -Then test the Forever zip in the game. The zip holds a `BuffRadar` folder that goes in -`Interface\AddOns`. +Replace `X.Y.Z` with the TOC version. In CI the Windows and POSIX digests +must match. Test the exact ZIP in Forever with the +[release checklist](docs/FOREVER_RELEASE_CHECKLIST.md), not a loose source +copy. Record the digest, game build and results. See the +[1.15.38 audit ledger](docs/AUDIT_1.15.38.md) for offline coverage and limits. +After a tagged release, verify the hosted ZIP against its published checksum +and the tested artifact. ## License diff --git a/build.ps1 b/build.ps1 index 1e17f0e..b44dd91 100644 --- a/build.ps1 +++ b/build.ps1 @@ -1,40 +1,11 @@ #Requires -Version 7.0 -# Packages the supported Forever edition into dist\BuffRadar--Forever.zip. - +# Windows wrapper for the shared deterministic Forever packager. $ErrorActionPreference = 'Stop' -$source = Join-Path $PSScriptRoot 'BuffRadar' -$forever = Join-Path $PSScriptRoot 'editions\forever' -$dist = Join-Path $PSScriptRoot 'dist' -$editionFiles = 'BuffRadar.toc', 'README.md', 'CHANGELOG.md', 'DESCRIPTION.md', 'FEATURES.md' -$versionLine = Select-String -LiteralPath (Join-Path $forever 'BuffRadar.toc') -Pattern '^## Version:\s*(\d+\.\d+\.\d+)\s*$' -if (@($versionLine).Count -ne 1) { throw 'Expected one numeric Version in the Forever TOC.' } -$version = $versionLine.Matches.Groups[1].Value -$zipName = "BuffRadar-$version-Forever.zip" -$zipPath = Join-Path $dist $zipName -$temporary = Join-Path $dist ([guid]::NewGuid().ToString() + '.tmp') - -New-Item -ItemType Directory -Force $dist | Out-Null -Add-Type -AssemblyName System.IO.Compression.FileSystem -try { - $archive = [IO.Compression.ZipFile]::Open($temporary, [IO.Compression.ZipArchiveMode]::Create) - try { - $payload = Get-ChildItem -LiteralPath $source -Recurse -File | Where-Object { - $_.DirectoryName -ne $source -or $_.Name -notin $editionFiles - } - foreach ($file in $payload) { - $relative = [IO.Path]::GetRelativePath($source, $file.FullName).Replace('\', '/') - [IO.Compression.ZipFileExtensions]::CreateEntryFromFile($archive, $file.FullName, "BuffRadar/$relative") | Out-Null - } - foreach ($file in $editionFiles) { - [IO.Compression.ZipFileExtensions]::CreateEntryFromFile($archive, (Join-Path $forever $file), "BuffRadar/$file") | Out-Null - } - } finally { - $archive.Dispose() - } - Move-Item -LiteralPath $temporary -Destination $zipPath -Force - $digest = (Get-FileHash -LiteralPath $zipPath -Algorithm SHA256).Hash.ToLowerInvariant() - "$digest $zipName" | Set-Content -LiteralPath (Join-Path $dist 'SHA256SUMS.txt') -Encoding ascii - Write-Host "Forever $zipPath" -} finally { - if (Test-Path -LiteralPath $temporary) { Remove-Item -LiteralPath $temporary } +$PSNativeCommandUseErrorActionPreference = $false +$script = Join-Path $PSScriptRoot 'tools/package.py' +if (Get-Command py -ErrorAction SilentlyContinue) { + & py -3 -I $script @args +} else { + & python -I $script @args } +if ($LASTEXITCODE -ne 0) { throw "Forever package failed (exit $LASTEXITCODE)." } diff --git a/docs/AUDIT_1.15.38.md b/docs/AUDIT_1.15.38.md new file mode 100644 index 0000000..b27061d --- /dev/null +++ b/docs/AUDIT_1.15.38.md @@ -0,0 +1,66 @@ +# BuffRadar 1.15.38 — audit follow-up + +This ledger groups the 32 follow-up items by subsystem. It compares the +candidate with v1.15.37 (`a02f3ebcafb663352d1e6038cb95e8e3c3eaf41e`). +Unless marked otherwise, the evidence is from Lua 5.1 fake clients, static +checks or local packaging. Passing those checks does not verify secure +execution, rendering, chat delivery or native timing in WoW: Forever. See +[the candidate matrix](FOREVER_1.15.38_VALIDATION.md) for the exact ZIP and +pending Windows and live checks. + +In the tables, **audit smoke** means an isolated case in +[`tools/audit51.lua`](../tools/audit51.lua), driven by +[`tools/smoke51.py`](../tools/smoke51.py) in all applicable setups. The Retail +TOC is a regression fixture, not a supported release. + +## Startup, persistence and reviews + +| # | Recommendation and change | Evidence and remaining limits | +|---|---|---| +| 01 | **Verify the edition at startup.** The shipping TOC loads `Forever.lua` before `Data.lua`. The declared interface and `GetBuildInfo` must both identify Interface 16001. An unsupported install leaves SavedVariables untouched and does not initialize the cast UI, pull listeners or the Options category. | Unsupported-build and wrong-edition audit smoke; supported TOC startup in both Forever setups; packaged `/br selftest`. WoW itself may stop an out-of-date TOC before addon code runs. | +| 02 | **Park only an owned macro.** Recognize BuffRadar-generated bodies, keep the combat/death guard, and recheck the body before editing. Park ineligible actions without overwriting a same-name user macro. Defer incompatible-client parking until combat ends if needed. | Macro migration, edit, length and stale-target smoke; unsupported startup and refresh fault audit cases. Game lockdown and macro editor deferral still require live testing. | +| 03 | **Validate on a detached save.** `SavedVariables.lua` rebuilds known nested maps and validates finite numbers, enums, keys, booleans, strings and anchors before publishing schema 23. Buff masks, custom pairs and spell IDs use shared validators. | Legacy v2 and v22 fixtures, corrupt-save fuzz, and tests for nested aliasing and malformed points. Named profile text is bounded on load and validated again when parsed for use. | +| 04 | **Preserve future saves.** Use a sanitized working copy when `dbVersion > 23`; leave the original global and unknown fields untouched. Changes only last for the session. | Future schema fixture changes the working copy, including nested values, without modifying the original object. Real logout/reload persistence is a live check. | +| 05 | **Cap deliberate storage without dropping the user's data.** Limit to 32 profiles (4,000 bytes each) and 192 permanent ignores. Reject a save, add or paste that would exceed a limit without partially applying it. Preserve pre-existing overflow and allow only explicit `/br storage delete …` recovery. | Audit smoke: full profile store, atomic ignore batch and BR1 cap rejection, overflow recovery followed by reload. An intentionally preserved save may still exceed the caps on disk. | +| 06 | **Bound retained state and telemetry.** Keep 64 character anchors, 192 stat keys, 50 history entries, 50 persisted offenders, 128 current-session offenders and 20 group-spell pairs. Record each offender GUID once per group, even when two players have the same display name. | Cap fixtures and deterministic load/prune paths, offender fold/rename/same-name cases. Older name-keyed offender totals remain labeled legacy rather than being guessed onto a GUID. | +| 07 | **Rescue bad window placement.** Reject malformed anchors and non-finite offsets; recover from an off-screen point or a failed `SetPoint` with a safe default. | Audit startup tests force an impossible point and a genuine frame placement refusal. Native drag, display-scale and UIParent coordinates still need a field pass. | +| 08 | **Share preference side effects.** Quick Setup, UI controls, slash commands and profile application use common readiness invalidation. Enabling Lite or disabling forecasts, pull flash, sync or optional watches retires the relevant state without unrelated edits. | Setup, profile, Lite and combat-debuff smoke; pull audit checks that turning off flash preserves a still-enabled forecast and turning both off clears it. | +| 09 | **Review BR1 settings pastes before applying.** Parse a bounded, complete string; show normalized changes, allow Edit paste or Cancel, and require another review if compared values change. Apply locally; keep unrelated geometry and history. | Settings round-trip, fuzz, paste length/cap/cancel and review drift audit cases. Historical BR1 formats that meet the completeness checks remain readable. | +| 10 | **Make profile replacement explicit.** `/br profile import` reviews a BR2 draft, reports the same-name collision and affected auto-profile contexts, supports renaming and rechecks before storing. Saving does not load the profile. | Audit cases change a profile during review, rename to a new name, then explicitly replace the original and retain its mapping. Profiles remain limited snapshots, not character backups. | +| 11 | **Make plan imports local by default.** Review assignment, blessing and auto-profile changes and warn about missing named profiles. Apply locally without sending; export remains copyable. | Plan parser/round-trip, review cancel and audit send-count assertions. Only assignments and blessings can be shared; mappings always stay local. | +| 12 | **Recheck plan-sharing authority and scope.** Explicit **Apply and share** needs sync, current role and a unique, complete roster. Capture leader and membership epochs; refuse stale confirmation after replacement, leave/rejoin or handoff. Reordering alone is not a change. | Audit cases exercise churn back to the same roster, leader handoff, pure reorder and duplicate GUID refusal. Submission counts are not acknowledgements. | +| 13 | **Retire legacy remote plan overlays.** Track sender GUID, scope and prior local value for legacy `ASSIGN`/`BLESS` updates. Restore prior values on membership/authority loss or sync-off without clobbering a subsequent local edit. | Legacy ownership audit, trust checks, and 22 two-client coordination scenarios for SYNC v3. Legacy messages do **not** have the v3 generation proof; a late message from a currently authorised sender may be accepted. | + +## Observations and cast eligibility + +| # | Recommendation and change | Evidence and remaining limits | +|---|---|---| +| 14 | **Distinguish absent, restricted, and incomplete aura data.** Protect modern reads and legacy tuples. Separate explicit list termination, zero returned values, unreadable fields and API errors; bound index scans to 40 slots. | Aura read/refusal/tuple cases and API-chaos smoke. A cap or refusal is not proof of missing auras; live secret-value behavior is pending. | +| 15 | **Avoid English matching on Forever.** Recognise a finite catalogue of food, flasks, drinking and world buffs by spell ID or client-resolved names. Report unknown counts separately and avoid claiming expiry without a readable timer. | Localized aura and legacy tuple audit fixture, world buff and drinking smoke. This is not a complete Forever spell catalogue; IDs and live coverage need field samples. | +| 16 | **Guard optional consumable and harmful-aura watches.** For the requested optional ID, accept an exact helpful result or fall back to the helpful index scan. Debuffs on player/focus stay read-only and separately bounded, including in combat. | Helpful vs harmful and unclassified ID cases, bounded scan, gated debuff/event smoke and combat timing counters. Restrictions may hide real auras; no Soulwell or encounter prediction claims. | +| 17 | **Check temporary coating applicability.** Inspect main/off-hand item class and equip location. An empty slot, shield or non-coatable weapon is not missing a coating; unreadable item information is unknown. | Audit smoke covers a nil slot, shield, coatable off-hand and unreadable details; Personal and row watch cases. No permanent-enchant check. | +| 18 | **Separate Fortitude family observations from policy.** Use presence/expiry observations for Fortitude and Prayer, then apply rebuff and forecast thresholds; conserve known coverage when alternate timing is incomplete. | Forecast/family alternate, expiry and unknown smoke cases; retained observation audit. This is an incremental Fortitude separation, not a rewrite of every buff's policy. | +| 19 | **Apply recipient-rank rules consistently.** Explicit rank and ID, secure spell and target paths reject a known too-low recipient and can choose a lower eligible rank. | Rank audit exercises rejection and lower-rank selection in target, ID and rank modes. Plain name macro mode intentionally leaves final rank choice to WoW. | +| 20 | **Use a shared group-cast gate.** Automatic, Shift-click and group key paths require a suitable current target, known spell, group spell range, group rules and applicable reagent counts; otherwise use an eligible single cast. Subgroup input accepts distinct groups 1–8 or All/None. | Group fallback audit covers unconfirmed range, cooldown, reagents, stale target and invalid subgroup lists; existing blessing/blocker/assignment steps. Real range, mana and reagent behavior still need testing. | +| 21 | **Keep pets and reused tokens safe.** Treat supported player/party/raid pet tokens as single-target recipients, do not include pets in group-cast need counts, and check live GUIDs before acting. Park an owned macro on pet-token reuse and refresh the queue. | Audit assertions inspect secure unit attributes, replace a pet, reject the stale row and check macro parking/re-arm; pet reports remain excluded. Actual protected pet casts are unverified. | +| 22 | **Prune GUID observations and avoid false drop alerts.** Reuse bounded scan maps, retain last confirmed state through unreadable reads for that member, and remove expired markers or departed GUIDs. | Unknown → confirmed loss, death → resurrect, expiry TTL and member-replacement audit steps. Offline observation does not prove live detection frequency. | + +## Group events and UI + +| # | Recommendation and change | Evidence and remaining limits | +|---|---|---| +| 23 | **Scope pull countdowns.** Require the native owner where supplied; boss-mod messages need a matching party/raid route and current trusted sender. Avoid cancelling a replacement based on an unrelated or ambiguous stop. Tie callbacks to the active object and expire on the fallback ticker too. | Native dedup, unrelated stops, same-owner replacement, malformed/wrong-route traffic and fallback expiry audit. A map field is context, not a unique timer generation. Ambiguous stops may be ignored until expiry. | +| 24 | **Report chat outcomes accurately.** Check the route and 255-byte cap before sending, distinguish refusal from submission/acceptance, and leave a local report on refusal. | Both mock chat APIs, PARTY/RAID selection, nil/true/false/throw, oversize and solo refusal cases. Actual delivery and instance routing remain live checks. | +| 25 | **Scope delayed join digests.** Use the join generation and roster membership epoch so a queued reminder cannot run in a later group or after a roster round trip. | Join → leave → rejoin and changed → restored membership audit. If the roster cannot be identified, skip the ambiguous reminder. | +| 26 | **Retire old far-row handling; keep Nearby diagnostic work local.** Exclude known out-of-range units, keep Range Watch and opt-in estimated range, and distinguish unavailable readings from complete coverage. Nearby updates relevant fields only while visible, with a post-paint target check when needed. | Range Watch/estimated range smoke; audit checks target changes, hidden list, unsubscribe on Hide, and refresh on reopen. Opening the panel does not scan or change CVars by itself. | +| 27 | **Fit the existing secure pool to the viewport.** Reduce visible rows for shorter UIParent height, scale and chrome; use two columns only when they fit. Cached scrolling must not change the full-queue head. | Short viewport/overflow/range/queue identity audit; ordinary, scaled, two-column and combat scrolling smoke. The stub does not render or model fullscreen/DPI changes. | +| 28 | **Fail closed on scan and paint errors.** Clear row, modifier, next/group and macro actions out of combat, invalidate the API snapshot, and rebuild on a later successful scan. Do not write protected attributes during lockdown. | Errors injected before arming and after a partial paint; cached wheel paint failure, stale cache eviction and recovery in audit smoke. Actual secure driver/taint behavior is unverified. | +| 29 | **Make panels usable without optional templates and preserve positions only by choice.** Optional widgets have plain visuals; required secure buttons never fall back to ordinary buttons. Remember Settings and Ready Check anchors only when opted in, with reset and rejection recovery. | Real template-refusal fixtures on the mock, no-template runs, positions on/off/reset, placement rescue; native panel compatibility and geometry pending. | +| 30 | **Measure the right work and stop idle updates.** The minimap drag script detaches on release or hide, the scan cadence stays throttled/coalesced, and `/br perf` separates scan, prep, import, debuff and combat-debuff samples. | Minimap script lifecycle, scan budgets, separate timing counters and refused clock cases. Offline counts don't measure live CPU, latency or memory growth. | + +## Release evidence + +| # | Recommendation and change | Evidence and remaining limits | +|---|---|---| +| 31 | **Keep language checks and local gates aligned.** German keys and format placeholders are checked; both local gates compile all addon/locale files and run TOC smoke, coordination and package tests. Luacheck 1.2.0 remains a separate local gate on POSIX. | The seven setups include a German fixture and run audit cases where applicable. No full native German layout review or Windows `check.ps1` run has been recorded. | +| 32 | **Build and verify the same Forever ZIP across platforms.** Use one manifest, fixed ZIP metadata, a version/tag check, runtime-byte and binding validation, CI digest comparison and hosted asset readback. | Two identical local builds, seven package regression tests, SHA-256, packaged Forever startup and four bindings. [Windows and POSIX digests matched in CI](https://github.com/SeanShaffer88/BuffRadar/actions/runs/44429425381). Published readback for **1.15.38** has not run. | diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 7a71c6b..dbfa33e 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -428,3 +428,23 @@ copies of the last completed scan, with no targets while the scan is paused. Readiness checks use only exposed local data; a carried Healthstone is not evidence about a placed Soulwell. These policies and the new UI still need Forever field verification. + +## 2026-11-18 — Review before applying or sharing; preserve incompatible saves + +The 1.15.38 audit follow-up separates parsing, local review, and application. +Legacy clipboard settings and named profiles don't send messages. Plan +sharing is a separate action scoped to a readable group and current authority; +never assume that a successful send means a recipient received it. The +newer-schema and deliberate-overflow save paths keep the original rather than +rewriting it from an older or trimmed copy. Only explicit overflow recovery +can remove preserved entries. See [the audit ledger](AUDIT_1.15.38.md). + +## 2026-11-18 — One deterministic Forever release package + +The PowerShell and POSIX launchers use the same Python manifest, with fixed +ordering and ZIP metadata. CI compares their checksums; offline repeatability +alone is not proof of Windows parity. The release workflow requires the +Forever TOC version to match the tag, verifies the packaged addon and stable +binding names, and re-downloads the published files without overwriting an +existing release. Track field results by ZIP SHA-256 so changed bytes don't +inherit earlier verification. diff --git a/docs/FOREVER_1.15.38_VALIDATION.md b/docs/FOREVER_1.15.38_VALIDATION.md new file mode 100644 index 0000000..dfdb5f8 --- /dev/null +++ b/docs/FOREVER_1.15.38_VALIDATION.md @@ -0,0 +1,72 @@ +# BuffRadar 1.15.38 — candidate verification + +- **Artifact:** `BuffRadar-1.15.38-Forever.zip` · 1,280,404 bytes +- **SHA-256:** `73c0c7389e5cfa96401c4e641e886263afdf8dcd5175d44927981af1949e8112` +- **Target:** WoW: Forever, Interface 16001 · SavedVariables schema 23 + +This is an **unpublished candidate** built from the audit follow-up worktree, +not the published 1.15.37 package. The local handoff copies of the ZIP and +`SHA256SUMS.txt` are in `release-candidates/1.15.38/` outside Git. Rebuild with +`sh tools/package.sh` or PowerShell 7 `./build.ps1` from the same source. +If the ZIP hash changes, use a new matrix for the changed artifact. + +## Offline gate and release bytes + +| Check | Result | Evidence | +|---|---|---| +| Lua 5.1 compile, advisory limits, locales and patterns | **Pass** | `sh tools/gate.sh` compiled all 22 Lua files. Compiler self-tests reject 201 locals and 61 upvalues. German key and format checks and the literal-pattern check passed. | +| Declared Retail TOC (regression fixture) | **Pass** | 398 steps, zero errors. | +| Retail + Extras: modern, timer fallback, no UI templates, German | **Pass** | 399 steps each, zero errors. | +| Forever: modern, and fallback timer without UI templates | **Pass** | 404 steps each, zero errors. | +| Scoped two-client coordination | **Pass** | 22 cases, including roster and leader changes, replay floors, and proof retry/fallback. | +| Real Luacheck 1.2.0 on POSIX | **Pass** | Lua 5.1.5, 22 addon and locale files, zero warnings/errors. Separate from the compile check. | +| Package regressions | **Pass** | Seven tests including repeatability with changed source mtimes, invalid metadata and tags, links, path aliases, source drift, checksums and binding verification. | +| Candidate repeat build and checksum | **Pass** | Two clean POSIX output runs (one with `--tag v1.15.38`), byte-identical ZIPs and checksum files, then `sha256sum -c SHA256SUMS.txt`. No tag was created. | +| Package contents and startup | **Pass** | Source-aware `tools/checkpackage.py` verified all 32 files, loaded 22 Forever TOC entries in Lua 5.1, checked all four stable bindings, and read version 1.15.38 and Interface 16001 via `/br selftest`. | +| Patch whitespace and release notes | **Pass** | `git diff --check`; the first Forever changelog section matches the candidate TOC. | +| Windows `build.ps1` and package parity | **Pass in CI** | [PR #57 CI run](https://github.com/SeanShaffer88/BuffRadar/actions/runs/44429425381) built and verified the Windows ZIP with PowerShell and compared its SHA-256 with the POSIX build. The candidate was also reproduced byte-for-byte from the tested commit. | +| Full native Windows `tools/check.ps1` gate | **Not run** | The Windows CI job checks packaging; it does not run the full local Windows checker. | +| Hosted ZIP and checksum readback | **Not run** | No 1.15.38 GitHub release or other publication. After approved publication verify both downloaded files against the candidate bytes. | + +Detailed scope: [32-item audit ledger](AUDIT_1.15.38.md). + +## Windows parity handoff + +On a clean checkout of the candidate source, use PowerShell 7 and Python +3.10 or newer. Set up the local tooling with `./tools/check.ps1 -Setup` if +needed. Build and run the full checker (including the ZIP): + +```powershell +./build.ps1 --tag v1.15.38 +./tools/check.ps1 +Get-FileHash -Algorithm SHA256 dist/BuffRadar-1.15.38-Forever.zip +Get-Content dist/SHA256SUMS.txt +``` + +Record the Windows/PowerShell/Python versions, gate exit status, and digest. +The file hash and checksum line must match the header above. The CI parity +result is recorded separately from the full local Windows check. + +## Forever field pass — pending + +Install the **exact ZIP above** into a clean `Interface/AddOns/BuffRadar` +folder; do not test loose source files. Back up `WTF` before migration or +recovery checks. Record tester/date, client build/interface and language, +party or raid size, UI scale/resolution, and the ZIP digest. Attach relevant +screenshots, client error/taint excerpts, or copied diagnostic output. + +| ID | Scenario | What to verify and record | Result | +|---|---|---|---| +| F1 | Install, upgrade, reload | `/br selftest` reports 1.15.38, Forever, Interface 16001 and schema 23. Upgrade a copied v22 save; keep profiles, saved class and role rules, keybinds and applicable preferences. With disposable future or over-limit saves, verify the warning and original save preservation; test explicit overflow recovery only after backing up. | Pending | +| F2 | Review and share | Try cancel/edit/apply with BR1; rename and replace a BR2 collision with an auto-profile mapping without loading it. Review a plan locally with no sends, then share with a second user; change membership or leadership during review and check that sharing refuses. Record what the receiver actually sees. | Pending | +| F3 | Protected casting and macro safety | Use a row, Cast Next Buff, Cast Next Group Buff, Shift-click and the action-bar macro. Include nearby exact-name, party, raid, self, group pet, and controller if available. Verify correct recipients and rank; check no stale or blocked actions on combat entry/exit, death/release/resurrection, token reuse, or after closing a macro editor. A user-owned same-name macro stays unchanged. | Pending | +| F4 | Group fallbacks and observations | Use a Fortitude/Prayer tier against low-level and eligible recipients. Change range, reagents, cooldown and subgroup rules; verify fallback and that pets don't count toward group need. Distinguish present/missing/unknown food, flask, drinking, world buffs and custom aura IDs, and test shield, empty hand, and coatable weapons in Personal readiness. Include restricted auras and combat debuff stacks. | Pending | +| F5 | Viewport, focus and panel positions | Test a short viewport, large UI scale, two columns and a long roster. Scroll in people/buff views; check the visible row casts on its own player, Cast Next Buff stays on the first eligible player, and the footer/buttons stay reachable. Test drag/save/reopen/reload/reset for Settings and Ready Check, combat/death closure, and review focus/scrolling without overlapping controls. | Pending | +| F6 | Nearby and locales | In English and German, compare nameplates on/off, estimated vs explicitly failed range, target changes, close/reopen and confirmed vs unknown texts. Opening Nearby or toggling its visibility does not itself change CVars. Check translated dialog buttons, markers and actual ID-based observations on a German client. | Pending | +| F7 | Countdown and roster transitions | Test native and available boss-mod countdowns in a party/raid. Cancel with the original sender, replace an active countdown, try an unrelated stop, and leave/rejoin. Confirm forecasts remain scoped; an ambiguous stop can wait for expiry. Record the `/br apicheck` timer observations and check no old join digest fires. | Pending | +| F8 | Reports and chat routes | Try `/br announce` and opt-in ready-check chat in normal party and raid and, if available, instanced group contexts. Test refusal or throttling and retain the local report. Compare the caster's send result with another player's received messages; API acceptance or no return value is not delivery. | Pending | +| F9 | Timings and memory | Collect `/br perf` in solo, 5-player, 25-player and up-to-40-player groups, including raids and combat debuff updates. Record scan average/worst against the 2 ms/8 ms targets, preparation/import/debuff samples when present, and addon total memory before/after roster churn and Lite mode. Record client latency and panel visibility; fake-client or CPU timings aren't end-to-end latency. | Pending | + +Also run the applicable [general and readiness checks](FOREVER_RELEASE_CHECKLIST.md). +A skipped game scenario remains unverified; don't carry a result forward from +another build, language or changed artifact. diff --git a/docs/FOREVER_RELEASE_CHECKLIST.md b/docs/FOREVER_RELEASE_CHECKLIST.md index 1770ddc..e9ef146 100644 --- a/docs/FOREVER_RELEASE_CHECKLIST.md +++ b/docs/FOREVER_RELEASE_CHECKLIST.md @@ -2,6 +2,14 @@ Run this against the exact candidate ZIP after CI passes. Record the version, client build, tester, and pass/fail for each check. Do not mark a build field-tested until the applicable checks pass. +## 1.15.38 Audit Follow-up + +Use the [candidate verification matrix](FOREVER_1.15.38_VALIDATION.md) to +identify the ZIP and record Windows and Forever results. Run the 1.15.38 rows +there plus the applicable readiness and general checks below. Use a backed-up +SavedVariables file and disposable test settings for downgrade and cap checks. +An offline pass does not verify rendering, protected actions, or delivery. + ## 1.15.37 Readiness Result: **Unverified in game**. Use the 1.15.37 Forever ZIP. @@ -316,7 +324,9 @@ Result: **passed** — SEAN, reported 2026-11-16 (all releases through ## General Release Checks -- **Empty list:** with no missing buffs, confirm the fully-buffed message. Disable friendly nameplates and confirm the explicit warning. On a client that does not answer range checks, confirm the list warns that range cannot be verified instead of claiming everyone is buffed. +- **Empty list:** verify that confirmed coverage, no eligible cast target, + disabled friendly nameplates and unreadable range or auras are distinct + states. Unknown coverage must not be reported as fully buffed. - **Eligibility:** confirm a player appears only when a known buff benefits them and they are in spell range, alive, and out of combat. Toggle include-self and verify the character can buff itself. - **Cast attribution:** outside combat, use `/br clicks` to turn on diagnostics. Start with a buff that appears in the list and note the cast counter. Click its @@ -338,8 +348,9 @@ Result: **passed** — SEAN, reported 2026-11-16 (all releases through - **Combat:** enter combat with buffs missing. Confirm no protected cast starts; after combat, verify the list resumes and catches up. - **Death and resurrection:** die in and out of combat. Check that BuffRadar's window, pill, minimap button, and open settings close, and that its cast bindings stay disarmed. Reload while dead and test release to ghost form, combat ending while dead, resurrection after releasing, and resurrection without releasing. Confirm the normal window and minimap preferences resume after resurrection and combat, including a window you hid manually before death. The game's AddOns and minimap-compartment entries can stay listed, but their BuffRadar controls should not open the addon while dead. - **Hover close:** with the title on and off, hover the list, then move onto and off the close button. Confirm it stays under the cursor, remains reachable near the screen edge, and leaves no header gap with the title off. Confirm locked click-through and the existing show/hide binding still work. -- **Scrollable rows:** with more than 15 entries, scroll over the list to the - bottom and back. Confirm the row range updates and a click buffs the player +- **Scrollable rows:** test with more than 15 entries, then with a short + viewport or higher UI scale so fewer rows fit. Scroll to the bottom and + back. Confirm the footer's row span updates and a click buffs the player shown on that row. Verify the Cast Next Buff key still uses the first eligible player in the full list. Test wheel input while holding a mouse button over a row and after combat begins. Confirm the secure rows disarm in combat and @@ -360,10 +371,14 @@ Result: **passed** — SEAN, reported 2026-11-16 (all releases through and remove a watched buff, then change target or leave the group. Verify the list reflects the new unit and its buffs. Run `/br perf` out of combat and record scan counts and timings while solo and in a raid, if available. + Record preparation, import and combat-debuff samples separately. Compare + the raid scan average and worst case with the 2 ms / 8 ms field targets; + don't infer these from fake-client timings. - **Pull timers:** with buffs missing and pull flash enabled, start a group - countdown, cancel or replace it, and verify the replacement stays active - until its own deadline. Use `/br apicheck` to check the native and supported - boss-mod countdown diagnostics. + countdown and cancel it. Replace a countdown while it is still active: + unrelated or ambiguous cancellations must not remove the replacement, which + still has its own expiry. Use `/br apicheck` to record which payloads the + client emits. Do not assume a boss-mod map field is a unique timer ID. - **Ready check and wipe:** confirm missing buffs are reported for a group member beyond cast range. Check that unreadable aura data is marked unverified and a ready check leaves the visible cast target unchanged. In a raid, confirm diff --git a/docs/PARITY.md b/docs/PARITY.md index e673448..003da42 100644 --- a/docs/PARITY.md +++ b/docs/PARITY.md @@ -23,14 +23,15 @@ and the TOC module refactor). | Nearby player options | Complement another Paladin's blessing outside the group; names-only and reversible nameplates | Complete | Trial run: cast-source ownership and explicit-rule precedence, verified CVar writes, refusal, persistence and restore | Aura ownership and plate appearance still need a Forever field test | | Forever buff set | Classic set incl. blessings, ranks, group variants | Complete | Forever setups incl. rank-table and Kings-first steps | Verified in game at 1.12.0 on 1.60.1.70862 | | Coordination (1.5.0–1.8.0) | Cast sync, chat requests, assignments, buddy split, blessing plan, peer hello, cover-me handoff, coverage roster, plan strings | Complete (batches 1–3) | Trial steps: sync handled-marks, request tags, leader-trust assignment sink/float, buddy hash split, blessing plan set/broadcast/receive, cover handoff + return, roster line, plan export/import round-trip; two-client coordination harness | All multi-user behaviour Unverified in game (needs a second BuffRadar user) | -| List & window | Sorts (name/role/distance/need), filters, strip, chips, pill, idle fade, rescue, pin, name finder, grow-up anchor, combat hide, color themes, two-column layout, saved custom themes, row spacing + icon size, window strata, click-through while locked, group-by-buff view | Complete (batches 1–4 + 1.10.0) | Trial steps per feature, incl. pill show/hide/peek, off-screen rescue via `/br resetpos`, pin order under name sort, find filter, grow-up anchor, combat hide/show, theme cycle, two-column split + widen/narrow (harness records anchors + width); 1.10.0 steps: theme save/apply/delete + sanitizer round-trip, row-pitch + icon-size deltas, frame strata, click-through mouse flags locked/unlocked, buff-view fold + cast target | Window load-rescue branch itself is not smoke-covered (harness limit) | -| Rows & interaction | Tags (expired/rezzed/asked/handled/queued/assigned/buddy/pinned/weapon/drinking/pet), portraits, compact rows, text scale, tooltips (3 detail levels), duration bars, raid markers, range text, focus line, coverage-line part toggles, row color marks, name formats (class colors / realm / trim), buff priority order | Complete (batches 1–3 + 1.10.0) | Tag-priority steps incl. queue + pinned + weapon + drinking tags; tooltip step (recorder GameTooltip: missing + remaining-time lines); bars/markers/range/focus steps; 1.10.0 display step (coverage part off/on, tooltip minimal/full lines, tank color mark, realm + trimmed names, plain name color); priority step (offer order flips + resets) | The aura/aspect note in the row below applies as before | +| List & window | Sorts (name/role/distance/need), filters, strip, chips, pill, idle fade, rescue, pin, name finder, grow-up anchor, combat hide, color themes, two-column layout, saved custom themes, row spacing + icon size, window strata, click-through while locked, group-by-buff view | Complete (batches 1–4 + 1.10.0) | Trial steps per feature, incl. pill show/hide/peek, off-screen rescue via `/br resetpos`, pin order under name sort, find filter, grow-up anchor, combat hide/show, theme cycle, two-column split + widen/narrow (harness records anchors + width); 1.10.0 steps: theme save/apply/delete + sanitizer round-trip, row-pitch + icon-size deltas, frame strata, click-through mouse flags locked/unlocked, buff-view fold + cast target | 1.15.38 covers rejected and off-screen anchors, pooled short viewports, and failed row paints offline. Live layout still needs testing | +| Rows & interaction | Tags (expired/rezzed/asked/handled/queued/assigned/buddy/pinned/weapon/drinking/pet), portraits, compact rows, text scale, tooltips (3 detail levels), duration bars, raid markers, estimated-range text, focus line, coverage-line part toggles, row color marks, name formats (class colors / realm / trim), buff priority order | Complete (batches 1–3 + 1.10.0) | Tag-priority steps incl. queue + pinned + weapon + drinking tags; tooltip step (recorder GameTooltip: missing + remaining-time lines); bars/markers/range/focus steps; 1.10.0 display step (coverage part off/on, tooltip minimal/full lines, tank color mark, realm + trimmed names, plain name color); priority step (offer order flips + resets) | Explicitly out-of-range rows no longer display. Range Watch and opt-in estimated range remain | | Coverage expansion | Built-in buffs + consumables + custom spells + uptime + weapon watch + pets + aura/aspect watch + per-buff context + world-buff watch + healer drinking | Complete (batches 1–3) | Consumable tally, custom add/remove/list, uptime scoring, weapon flag on/off steps; pet rows + report exclusion, context gating (incl. the SHADOW_PROT instance default), world-buff line, drinking tag + coverage count steps | Weapon watch reads temporary weapon enchants only (GetWeaponEnchantInfo); solo with no other row, the reminder waits for a row or a group. The aura/aspect watch's positive path (a hunter/paladin who knows an aspect/aura spell) is not smoke-covered — the harness spellbook is a priest's/shaman's; toggle + edition gating are covered | | Alerts | New-name alert, drop alert, post-combat flash, instance-entry reminder, group expiry warning, a sound per alert kind | Complete | Alert + flash steps; entry reminder fires-once step; expiry tally step (3 holders < 5 min); 1.10.0 per-kind sound step (save/change/master via `/br soundfor`) | #33 shipped in 1.15.0 as the fall alert (off by default, Unverified in game) | | Stats & reporting | Cast stats + export, cast history, announce, ready-check report + auto-post, join digest, selftest, repeat offenders, Discord summary, death recap, post-wipe report | Complete (batches 1–4) | Announce/ready/digest/selftest steps; auto-post step (leader posts to PARTY); history record + resetcount-clear step; offenders fold-on-group-end step; stats export + Discord render steps; death-recap step (PLAYER_DEAD print + reprint); wipe step (controllable clock: single death = no report, 2-of-3 dead after 20 s = report) | — | | Settings & QoL | Tabs UI, export/import, named profiles + share-one-profile, per-spec profiles, presets, auto profiles, scan throttle, settings search, setup wizard | Complete (batches 1–4) | Settings-fire-every-control step, export/import round-trip, profile + preset + auto-profile steps, throttle toggle + 25-player tick step, profile share/import round-trip, settings-search dim step, Quick Setup step (draft, Back, cancel, then apply) | — | -| Settings data safety | Versioned SavedVariables, migrations, corrupt-data repair | Complete | Migration fixture: legacy v2 save → v22, including v21 readiness-setting validation; invalid plate-restore keys and malformed settings are dropped | — | +| Settings data safety | Versioned SavedVariables, migrations, corrupt-data repair | Complete | Migration fixture: legacy v2 save → v23; detached validation, valid nested values and position rescue, and preservation of newer or over-limit saves | Back up before testing downgrade/overflow recovery | | Localisation | English and German keys, partial frFR, esES, ruRU, zhCN | Offline checked | `tools/localecheck.py` enforces German coverage; German setup runs the full trial run | Native-speaker review welcome | +| 1.15.38 audit follow-up | Incompatible-client guard, reviewed imports, more conservative cast eligibility, roster cleanup, bounded storage, viewport, and deterministic package | Offline checked | [32-item audit ledger](AUDIT_1.15.38.md) | [Windows package parity passed; Forever field pass pending](FOREVER_1.15.38_VALIDATION.md) | | Readiness and forecasts | Confirmed expiry alerts, role/instance/wipe priority, player/focus debuffs, Personal checklist, status API, Quick Setup, minimap badges, and Lite mode | 1.15.37 (offline checked) | Lua 5.1 trial steps cover alternate aura expiry, pull cancellation, role/instance order, restricted aura data, solo checklist, API copies, and combat/Lite invalidation | Unverified in game; Soulwell and prospective boss-mechanic availability are not inferred | ## The 50-item program (SEAN approved 2026-10-25: add all 50) diff --git a/docs/RISK_MATRIX.md b/docs/RISK_MATRIX.md index 43d290d..c625662 100644 --- a/docs/RISK_MATRIX.md +++ b/docs/RISK_MATRIX.md @@ -1,7 +1,8 @@ # BuffRadar — Use-Case, Risk and Test Matrix -Written 2026-11-16 against 1.15.33, the release that added this file. Each row ties a scenario to its mitigation and to the evidence that -checks it. Evidence names are trial-run steps in `tools/smoke51.py` unless +Started with 1.15.33 and updated for the 1.15.38 audit follow-up. Each row +ties a scenario to its mitigation and evidence. See the [audit ledger](AUDIT_1.15.38.md) +and [candidate matrix](FOREVER_1.15.38_VALIDATION.md) for new cases. Evidence names are trial-run steps in `tools/smoke51.py` unless marked `coord:` (`tools/coordination51.py`) or `gate` (`tools/gate.sh` / `tools/check.ps1`). @@ -26,7 +27,8 @@ passes, and the last one covered releases through 1.15.33. 3. **Trust levels:** - The local player's own typing is trusted for intent, but not for format. - Group members are partially trusted. Plan authority comes from the - game-reported leader or assistant role, never from the message itself. + game-reported leader/assistant role (or Paladin for legacy blessings), + never from the message itself. - Strangers nearby, whisper senders, and pasted or shared strings are untrusted. - Game API results are untrusted for type and readability: secret values, @@ -49,14 +51,14 @@ passes, and the last one covered releases through 1.15.33. | U1 | Solo leveller (priest, mage, druid…) | Buff self and passers-by in the open world | Lists people it can't buff; clutter | Lists only players in range who can benefit from a known buff; nearby players need friendly nameplates | out-of-range players are never listed, then appear in range; empty list explains range, nameplate, and buff states | Covered | | U2 | Dungeon healer or support | Keep 5 players buffed between pulls | Missed rebuffs; casting on the wrong target | Cast-next keybind bound to the displayed row; rows rebind after roster changes | scrolling virtualizes secure rows without moving the cast queue; 1.15.31 checklist | Covered (field-verified at 1.15.31) | | U3 | Raid buffer (20–40 players) | Group buffs, blessings by class, assignments | Frame drops; duplicate casts between buffers | Throttled, coalesced scans; performance budget; caster coordination | performance budget: worst-case 40-player scan; scan throttle halves the big-group rescan; coord: request, report, reviewed publish… | Covered offline; in-game `/br perf` numbers not collected | -| U4 | Raid leader or assistant | Publish who buffs what | A non-leader hijacks the plan | Assignment and blessing messages accepted only from leader or assistant units | buff assignments from the leader tag and sink rows; group sync accepts current raid traffic and rejects unreadable authority | Covered | +| U4 | Raid leader or assistant | Publish who buffs what | A non-leader hijacks the plan | Legacy plans require a readable current roster and leader; assignments require leader/assistant and blessings also permit Paladins | buff assignments from the leader tag and sink rows; group sync accepts current raid traffic and rejects unreadable authority | Covered | | U5 | Paladin | Blessings per class, greater blessings | Wrong blessing per class | Kings-first priority, per-class choices, the group plan wins | per-class blessing choices persist and defer to the group plan; blessing plan: set, broadcast, receive, list | Covered | | U6 | Priest who knows Shadowguard | Self-buff watch | Not shown, or shown when the spell is unknown | Shown only when the spell is known | edition buff set | Covered; in game Unverified | | U7 | New user | First install | Overwhelming setup | Setup wizard; presets; a v9+ save counts as an existing user | saved settings: legacy saves migrate…; wizard steps | Covered | | U8 | Non-English client | German, French, Spanish, Russian or Chinese UI | Untranslated or broken format strings | Locale completeness for German; placeholder parity checked for every locale | gate localecheck; German client uses the translation | Partial: non-German translations are machine-assisted | | U9 | Player with low vision, colour-vision deficiency or motion sensitivity | Read the list comfortably | Colour-only meaning; flashing; small text | Tag symbols, reduced motion, text and icon scale, row spacing | 1.12.0 toggles: tag symbols, reduced motion…; saved themes, row spacing, icon size… | Covered | | U10 | Keyboard-first or screen-reader-assisted player | Use settings without a mouse | Controls unreachable | Keyboard settings navigation; narration through the game's TTS voice | keyboard settings navigation changes tabs…; settings narration uses the standard game voice… | Partial: no audit with assistive-tech users | -| U11 | Multi-character or multi-account player | Move settings between characters | Lost or corrupted settings on import | Named profiles; atomic imports; export round-trip | named settings profiles save, load…; clipboard settings imports require complete input and apply atomically | Covered | +| U11 | Multi-character or multi-account player | Move settings between characters | Lost or corrupted settings on import | Reviewed, local-by-default imports; caps and collision recheck; export round-trip | named settings profiles save, load…; clipboard settings imports require complete input and apply atomically | Covered | | U12 | Support helper or addon author | Diagnose a bug report | Can't reproduce | `/br selftest`, `apicheck`, `buffcheck`, `perf`, `why`, nearby diagnostics | /br selftest prints a paste-able block; 1.12.0 diagnostics… | Covered | ## 2. Environments and contexts @@ -69,10 +71,10 @@ passes, and the last one covered releases through 1.15.33. | E4 | 40-player raid | Frame time | Budget ≤8 aura reads per player, linear growth, <5 ms per scan in the fake client | performance budget: worst-case 40-player scan | Covered offline; in-game target Unverified | | E5 | Client hides data (secret or restricted values) | Errors; or silently empty lists | Every unit and aura read goes through readability checks; "data hidden" badge | protected (secret) GUID / name from the game: no error; 1.12.0 badges…; apicheck readability tier… | Covered | | E6 | Client API raises, returns nil or returns the wrong type | Scan aborts and the whole list disappears | Unit identity reads guarded (`X.UnitPresent`, `X.UnitGUIDOf`, `X.UnitClassToken`, `X.UnitNameOf`); one bad unit is skipped | hardening regressions: … one bad unit; robustness fuzz (API chaos, per-API raise) | Covered (fixed in this change) | -| E7 | Clients without `C_Timer` or UI templates | Feature breaks on older or alternative clients | Fallback `OnUpdate` timer; fallback settings look | six setups in the trial run | Covered | +| E7 | Clients without `C_Timer` or UI templates | Feature breaks on older or alternative clients | Fallback `OnUpdate` timer; fallback settings look | seven trial-run setups; optional template refusal on Settings and review | Covered | | E8 | Spell-range API silent (other realms, nameplate limits) | Lists unreachable players, or no one | Fails closed; opt-in `assumerange`; checked-distance fallback | range uses checked distance only when both spell range answers are unavailable; assumeRange lists players… | Covered | -| E9 | Other addons: UI suites, boss mods, Edit Mode | Clashing visuals; spoofed pull timers | Auto theme reads exact addon folders; pull comms accepted only from trusted senders | Auto theme opts in…; pull timer: probe counts…; changing a pull timer keeps its replacement… | Covered | -| E10 | Reload or relog mid-session | Lost state; stale casts | Saved settings versioned; session state reset on entering the world | migration chain steps | Covered | +| E9 | Other addons: UI suites, boss mods, Edit Mode | Clashing visuals; spoofed pull timers | Auto theme checks exact folders; boss-mod pulls require matching group channel and trusted sender; ambiguous stops do not cancel a replacement | Auto theme opts in…; pull timer: probe counts…; changing a pull timer keeps its replacement… | Covered | +| E10 | Reload or relog mid-session | Lost state; stale casts | Schema 23 keeps an untouched future or over-limit user save and resets session state on entering the world | migration chain steps | Covered | | E11 | Game patch changes spell IDs or APIs | Buffs silently missing | `/br buffcheck`, `/br apicheck`; `IsPlayerSpell` gating | 1.12.0 diagnostics… | Partial: detects but can't self-repair | ## 3. Inputs and trust boundaries @@ -81,13 +83,13 @@ passes, and the last one covered releases through 1.15.33. |---|---|---|---|---|---| | I1 | Settings import `BR1` (untrusted paste) | Crash; partial apply; injected values | 16 KiB cap; full required-field set; per-field type and range decode; atomic apply | clipboard settings imports require complete input…; robustness fuzz (1,000+ inputs, field mutations, round trip) | Covered | | I2 | Profile string `BR2` / shared profile (untrusted) | Same as I1; oversized saved profiles | Size limits; enum checks; invalid profile preserves the existing save | profile limits and validation preserve an existing save; robustness fuzz | Covered | -| I3 | Plan string `BRPLAN1` (untrusted) | Hijacked assignments; markup in holder names | Key pattern, holder ≤128 characters with no `;`, `\|` or control characters; atomic | plan import validates atomically…; hardening regressions | Covered (control characters fixed in this change) | -| I4 | Ignore-list string `BRI1` (untrusted) | Flooding SavedVariables; markup names | 16 KiB cap checked before anything is added; `Ignore.Valid` (≤64 characters, no `\|`, `;` or control characters) | hardening regressions; ignore list export/import round-trip | Covered (fixed in this change) | +| I3 | Plan string `BRPLAN1` (untrusted) | Hijacked assignments; markup in holder names | Bounded key/holder syntax; reviewed local apply; explicit share scoped to current roster and roles | plan import validates atomically…; audit plan review and authority drift | Covered offline | +| I4 | Ignore-list string `BRI1` (untrusted) | Flooding SavedVariables; markup names | 16 KiB string and 192-name saved caps checked before any additions; ≤64 bytes per name, no `\|`, `;` or control characters | hardening regressions; audit storage limits | Covered offline | | I5 | Assignment mask (from profiles) | Crash on wrong type | String-only, canonical digits, range-checked | hardening regressions; robustness fuzz | Covered (fixed in this change) | -| I6 | Addon messages (group members) | Forged plans; replay; oversized messages; spoofed sender | Prefix, channel and 255-byte checks; sender must resolve to a current group unit; leader or assistant gate; scoped sync with epochs, challenges and replay floors | coord: (all 20+ PASS lines); group sync validates current party members…; robustness fuzz (3,000 messages) | Covered | +| I6 | Addon messages (group members) | Forged plans; replay; oversized messages; spoofed sender | Prefix, channel, sender and 255-byte checks; scoped SYNC v3 for caster coordination, roster/authority cleanup for legacy ASSIGN/BLESS | coord: (22 cases); audit remote-plan ownership; fuzz | Partial: legacy ASSIGN/BLESS has no wire generation | | I7 | Whispers and `/say` containing "buff" (anyone nearby) | Sound spam; tagging strangers | Matches listed players only; sound ≤1 per second overall and ≤1 per 30 s per player; `/br requests off` | chat request tags the asker; robustness fuzz | Covered | | I8 | Slash command arguments (local player) | Error output; bad stored values | Every handler runs in `pcall`; per-command validation; `/br ignore` validates names | robustness fuzz (1,500 random commands, no "error:" output) | Covered | -| I9 | SavedVariables (hand-edited or corrupt) | Crash at load; NaN or infinity propagating; wrong types | Sanitizer rebuilds every key to its default type; migration chain v2→v20 | saved settings: legacy saves migrate…; robustness fuzz (250 corrupt saves per setup) | Covered | +| I9 | SavedVariables (hand-edited or corrupt) | Crash at load; NaN or infinity propagating; wrong types | Detached finite typed validation; future/overflow preservation; migration chain v2→v23 | legacy migration, fuzz and detached-save audit fixtures | Covered | | I10 | Game event payloads (`UNIT_AURA`, roster, nameplates) | Refresh storms | Untracked units ignored; coalesced to 0.1 s; ticker every 0.4 s | UNIT_AURA on an NPC nameplate / boss / pet: no refresh; fallback event refresh coalesces… | Covered | | I11 | Any user or peer text reaching `find`/`match`/`gmatch`/`gsub` | Pattern injection ("malformed pattern" errors, wrong matches) | Every pattern argument is a literal or the call is a plain find; enforced by `tools/patterncheck.py`; edit boxes have max lengths | gate patterncheck (fails on a non-literal pattern) | Covered (added in this change) | @@ -101,17 +103,17 @@ passes, and the last one covered releases through 1.15.33. | F4 | Lua 5.1 local or upvalue ceilings | Addon fails to load after an edit | `tools/lualimits.py` in the gate | gate | Covered (main chunk 165/200, `HandleSlash` 58/60 upvalues) | | F5 | Locale string with a mismatched placeholder | `string.format` error | `localecheck` checks placeholder parity | gate | Covered | | F6 | Package missing a file or in the wrong load order | Addon broken on install | `checkpackage.py` loads the ZIP in TOC order; release assets hash-verified after upload | gate; release workflow | Covered | -| F7 | Chat send refused (throttle or channel) | Silent report failure | Send result checked; 255-byte cap | group reports respect ignored players and chat refusal | Covered | +| F7 | Chat send refused (throttle or channel) | Silent report failure | Refusal leaves a local report; nil or true describes submission/acceptance, not delivery; 255-byte cap | audit chat report outcomes in PARTY and RAID mocks | Partial: live chat routes and delivery pending | ## 5. Security, privacy and abuse | ID | Abuse or exposure | Mitigation | Evidence | Status | |---|---|---|---|---| | S1 | A group member forges leader plans | Authority taken from the game's unit role, never from the payload | buff assignments from the leader…; coord: | Covered | -| S2 | Replay or delayed messages after a roster or leader change | Epoch proofs, replay floors, bounded pending queues (≤2 epochs, ≤8 packets) | coord: roster/leader boundary PASS lines | Covered | +| S2 | Replay or delayed messages after a roster or leader change | SYNC v3 epoch proofs, replay floors and bounded pending queues (≤2 epochs, ≤8 packets each); legacy overlays retire on authority or membership loss | coord: roster/leader boundary cases; audit legacy overlays | Partial: legacy plan replay after a valid scope returns is not proven preventable | | S3 | Malicious shared import string | Size caps, strict decode, atomic apply, round trip | I1–I5 | Covered | | S4 | Markup injection (`\|c`, `\|T`, `\|H`) through names | `\|` rejected in addon-message names, plan holders and ignore entries | hardening regressions; code review of `ValidName` | Partial: free-text names from the game itself are trusted as game-sanitized | -| S5 | Unbounded saved growth | Ignore import capped; profiles size-limited; peer and cover tables keyed by current group | robustness fuzz state bounds | Partial: repeated `/br ignore` by the player is unbounded (self-inflicted) | +| S5 | Unbounded saved growth | 32 profiles, 192 permanent ignores, 64 per-character anchors, 192 stat keys, 50 history slots, 50 stored offenders, 20 custom group pairs. Session offender collection limited to 128 GUIDs | bounded writer/load and overflow recovery fixtures | Covered for saved collections; a preserved legacy save is intentionally not truncated | | S6 | Privacy: other players' names stored locally (ignore list, stats, history) | Local SavedVariables only; no network; exports are user-initiated | SECURITY.md (risk tier 0) | Covered by design | | S7 | Privacy: names shared through Discord or stats exports | Shown in a copy box for the user to paste; nothing is sent automatically | stats export and Discord summary render | Covered by design | | S8 | Botting or automation | Casting requires a hardware event; no auto-cast (`/br rangewatch` only notifies) | platform | Platform | @@ -138,11 +140,8 @@ passes, and the last one covered releases through 1.15.33. - A depth floor fails the fuzz if mutated inputs stop reaching the accepting import paths. -**Coverage summary:** -- 51 rows in total: 43 Covered (some need in-game confirmation), 5 Partial, - 2 Covered by design, and 1 Platform. -- No row is an unmitigated Gap. The Partial rows above name what is still - uncertain. +**Coverage summary:** offline mitigations do not remove the residual risks +below. Keep the current Windows and in-game results with the tested ZIP hash. ## 7. Residual risks and limitations @@ -150,7 +149,8 @@ passes, and the last one covered releases through 1.15.33. throttling and real secret-value behaviour can't be reproduced offline. A passing gate is evidence, not proof. - **In-game verification:** releases through 1.15.33 are field-verified; - 1.15.34 is Unverified in game. + 1.15.34–1.15.38 are Unverified in game. Windows package parity passed in + CI; see the [candidate matrix](FOREVER_1.15.38_VALIDATION.md). - **Fuzzing is sampled:** about 1,000 inputs per parser, 3,000 messages, 1,500 commands, 250 corrupt saves and 200 API-chaos rounds per setup. It finds shallow-to-medium defects; it can't prove their absence. The @@ -163,7 +163,10 @@ passes, and the last one covered releases through 1.15.33. alias such as `local find = string.find`, is not inspected. - **Unauthenticated protocol:** coordination relies on game-reported roles and the protocol is not cryptographically authenticated. A group leader - can always publish a bad plan. + can always publish a bad plan. Legacy assignment/blessing and boss-mod + traffic do not carry a unique generation. Cleanup and matching avoid + retaining stale local state; they do not prove that all late packets are + fresh. - **Accessibility:** there's no external audit with screen-reader or switch-access users, and the in-game narration depends on the client's TTS voice. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 3893e33..ed36b58 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -7,7 +7,8 @@ or copy its link in **Settings → Readiness → Feedback** (`/br feedback`). | Status | Work | | --- | --- | -| **1.15.37 — awaiting field verification** | Confirmed buff expiry forecasts, contextual priority, personal readiness, player/focus debuff watches, a read-only status API, Quick Setup, minimap status, quiet visuals, adaptive scans, and Lite mode. | -| **Next: verify in Forever** | Walk the [release checklist](FOREVER_RELEASE_CHECKLIST.md) on the candidate build. Check a raid-sized roster, live countdown cancellation, combat aura visibility, and scan/memory diagnostics. | +| **1.15.38 candidate — offline checks complete** | Safer saves, reviews, cast eligibility and roster cleanup; deterministic Forever candidate. See the [audit ledger](AUDIT_1.15.38.md) and [verification matrix](FOREVER_1.15.38_VALIDATION.md). | +| **1.15.37 — released; live verification pending** | Confirmed buff expiry forecasts, contextual priority, personal readiness, player/focus debuff watches, a read-only status API, Quick Setup, minimap status, quiet visuals, adaptive scans, and Lite mode. | +| **Next: field test in Forever** | Ship only after the applicable checks; Windows package bytes matched in CI. Walk the [release checklist](FOREVER_RELEASE_CHECKLIST.md) on the exact candidate. Check real casts, short viewports, a raid-sized roster, countdowns, chat delivery, combat aura visibility, and scan/memory diagnostics. | | **Under consideration** | Shareable encounter presets after spell IDs and aura availability are confirmed, more options for placing the debuff strip, and community examples using the [status API](STATUS_API.md). | | **Waiting on client data** | Confirming that a placed Soulwell is reachable and usable, and automatically predicting upcoming encounter mechanics. BuffRadar does not guess at data the client does not expose. | diff --git a/docs/STATUS_API.md b/docs/STATUS_API.md index 4b25abc..ce23d31 100644 --- a/docs/STATUS_API.md +++ b/docs/STATUS_API.md @@ -32,7 +32,9 @@ confirmed missing or has at most 15 seconds left. `partial` can be true even when one need is known. `covered` applies only to the buffs BuffRadar was able to check, not every buff in the game. `unavailable` has a `reason` of `inactive`, `updating`, `paused`, `combat`, or `dead`. In these states the API does not -return old targets as current. +return old targets as current. In 1.15.38 an incompatible install stays +`inactive`; a failed refresh or cached row paint invalidates the snapshot +instead of republishing an old queue. This does not change the API version. ## React to changes diff --git a/editions/forever/BuffRadar.toc b/editions/forever/BuffRadar.toc index 4bc6c02..2169084 100644 --- a/editions/forever/BuffRadar.toc +++ b/editions/forever/BuffRadar.toc @@ -2,7 +2,7 @@ ## Title: |cff33ccffBuff|rRadar ## Notes: Clickable list of in-range players who can benefit from your buffs. Click a name, press a key or use a macro to buff them. ## Author: Malikor -## Version: 1.15.37 +## Version: 1.15.38 ## SavedVariables: BuffRadarDB ## IconTexture: Interface\AddOns\BuffRadar\Media\icon.png ## Category: Combat @@ -13,6 +13,7 @@ Locales\frFR.lua Locales\esES.lua Locales\ruRU.lua Locales\zhCN.lua +Forever.lua Data.lua SavedVariables.lua BuffRadar.lua diff --git a/editions/forever/CHANGELOG.md b/editions/forever/CHANGELOG.md index e488615..06f4292 100644 --- a/editions/forever/CHANGELOG.md +++ b/editions/forever/CHANGELOG.md @@ -2,6 +2,38 @@ All notable changes to BuffRadar are listed here. Newest first. +## 1.15.38 — WoW: Forever + +- Require the Forever package on Interface 16001. On another interface, + BuffRadar leaves the save alone, disables casting, and parks only its own + Cast Next Buff macro when the client allows edits. +- Upgrade saves to schema 23 with validated nested settings and window + positions. A newer save or one over the profile or ignore limit is + preserved, with a temporary working copy instead of silent data loss. +- Review settings, named profiles, and plans before applying them. Named + profile collisions show affected auto-profile mappings; saving a profile + doesn't load it. Plans apply locally unless you choose **Apply and share** + with current group permission. Chat and plan sends don't promise delivery. +- Check ranks, group spell range and reagents before offering the group + version. A pet row uses its pet unit and stays out of the group threshold. + A scan or row paint error clears stale cast actions before recovery. +- Use recognised spell IDs for food, flasks, drinking and world buffs. Mark + unreadable data unknown and distinguish a missing temporary weapon coating + from an inapplicable or unreadable slot. +- Fit the scrollable list to available screen height without changing the + next cast. `/br positions on` remembers Settings and Ready Check panel + positions; `/br positions reset` recenters them. Nearby diagnostics update + on target and nameplate setting changes while open. +- Keep stale roster data and delayed join notices from crossing group + transitions. Pull countdowns ignore unrelated cancellations and expire + on either timer backend. `/br perf` separates scan, preparation, import + and debuff timings. +- Use one deterministic Forever ZIP builder from Windows and POSIX. Verify + the TOC, SHA-256, packaged Lua startup, and all four existing bindings. + +**Verification:** automated Lua 5.1 and package checks passed. Windows +build parity and live behavior on this candidate are **Unverified**. + ## 1.15.37 — WoW: Forever - Open **Settings → Readiness** for buff expiry forecasts and smart priority. diff --git a/editions/forever/DESCRIPTION.md b/editions/forever/DESCRIPTION.md index ef819dc..55b0455 100644 --- a/editions/forever/DESCRIPTION.md +++ b/editions/forever/DESCRIPTION.md @@ -2,8 +2,7 @@ **A click-to-buff list for World of Warcraft: Forever.** -Store-listing copy prepared 2026-10-24 from the shipped 1.3.2 -Forever README. +Forever package · Interface 16001 --- @@ -18,16 +17,15 @@ come first. - **One list, no hunting.** Players stay listed until every buff you can cast that suits their class is on them, then drop off. The - window is anchored by its top-left corner, so it grows downward - without ever jumping around your screen. + list scrolls when more targets are available than fit on your screen. - **It knows your class.** Arcane Intellect only goes to mana users, Thorns to melee, Fear Ward to warriors. Paladins lead with Blessing of Kings when they know it, with Might and Wisdom as fallbacks. Group versions count as buffed, expiring buffs are re-offered, and spells on cooldown are skipped. - **Group casts, offered.** When enough of your party or raid needs - the same buff, BuffRadar offers the group version instead — one - cast for everyone. + the same buff and the group spell is eligible, BuffRadar offers the + group version. Otherwise it offers the eligible single-target spell. - **Honest about what it can see.** Addons get no list of nearby players, so BuffRadar finds people through your group, your target, your mouseover and friendly nameplates. If nameplates are off, it @@ -46,7 +44,15 @@ come first. of the main window on German clients (settings are English for now). -## Readiness in 1.15.37 +## What's new in 1.15.38 + +Review a paste before applying settings or plans. Plans stay local unless +an authorised player chooses to share them, and importing a named profile +no longer risks replacing a save without showing the collision. The list +fits shorter viewports; Settings and Ready Check positions can be remembered +separately with `/br positions on`. + +## Readiness Choose your role and activity in Quick Setup, see what needs attention on the minimap, and review consumables, Healthstones in bags, and gear durability in @@ -73,5 +79,6 @@ were informed by BuffYou by datdata (MIT). Since 1.3.2 the Forever and Retail editions are built from the same source; **from 1.8.0 BuffRadar is Forever-only** — Retail support ended at 1.7.0. -**Verification:** Field-tested through 1.15.33. The 1.15.37 readiness update -passes automated checks but is **Unverified in game**. +**Verification:** Field-tested through 1.15.33. The 1.15.38 candidate passes +automated checks; live casting, layout and chat behavior are **Unverified** +on this build. diff --git a/editions/forever/FEATURES.md b/editions/forever/FEATURES.md index 484a7c0..4c7810f 100644 --- a/editions/forever/FEATURES.md +++ b/editions/forever/FEATURES.md @@ -4,12 +4,27 @@ The feature list for BuffRadar (Forever edition) for WoW: Forever (Interface 16001). For the short version see `README.md`; for store-listing copy see `DESCRIPTION.md`. -Prepared 2026-10-24 from the shipped 1.3.2 Forever README and -CHANGELOG; updated 2026-11-14 for 1.15.16. Since 1.3.2 both editions are built from one source — -the addon picks the Forever buff set when it loads on the Forever -client — and the Forever buff set itself is unchanged from 1.2.4. -**From 1.8.0 BuffRadar is Forever-only**: Retail support was dropped -2026-10-25, and 1.7.0 is the last Retail release. +The shipping Forever TOC requires Interface 16001. The historical Retail +TOC remains a test fixture; 1.7.0 was the last Retail release. + +## 1.15.38: safer casts, saves and sharing + +- A scan or viewport paint failure clears cast actions until a successful + refresh. The viewport scrolls when fewer rows fit your screen. +- Group casts use the same eligibility checks for automatic offers, + Shift-click, and the group key. Missing prerequisites fall back to the + single cast. Pet rows bind their pet unit, not a player's name. +- Food, flask, drinking and world-buff checks use recognised aura IDs and + client spell names. An unreadable observation is not a confirmed absence. + Personal readiness checks temporary coatings only on eligible weapons. +- Schema 23 preserves newer saves and deliberate profile/ignore overflow. + Review pasted settings before applying. Named profiles show collisions + and may be stored under another name without loading them. +- Plan imports are local by default. Sharing requires an explicit choice, + current group membership and permission to send. Auto-profile mappings + stay local. A send result doesn't confirm that another player received it. +- `/br positions on` remembers Settings and Ready Check positions (off by + default). `/br perf` reports available CPU timing samples by type. ## 1.15.37: Readiness @@ -99,7 +114,9 @@ each needs in-game evidence or a sharper definition, recorded in - **Buff plan strings** (`/br plan export|import`): assignments, the blessing plan and the auto-profile map as one copyable - string; importing applies it and shares it onward. + string. Import opens a review; **Apply locally** is the default. If + authorised, **Apply and share** sends changed assignments and blessings, + not auto-profile mappings. - **Name finder** (`/br find`, `/br findbox`): a search box on the window filters the list by name; reports stay unfiltered. - **Duration bars** (`/br bars`): a thin bar under each row shows @@ -161,8 +178,9 @@ each needs in-game evidence or a sharper definition, recorded in - **Row tooltips, completed:** hover a row to see the buffs the player has from your set, with the time left on each. - **Weapon enchant watch** (`/br weapon`): your row (or the - coverage line) flags an equipped weapon with no temporary - enchant — imbue, poison, oil or stone. + coverage line) flags an applicable melee weapon with no temporary + coating (such as an imbue, poison, oil or stone). Empty slots, shields, and + ranged weapons don't count as missing. - **Instance-entry reminder** (`/br enterflash`, on by default): one line on entering a dungeon, raid or battleground unbuffed. - **Group expiry warning:** the coverage line names a group buff @@ -346,13 +364,12 @@ stays hidden on those characters. - **Water droplet alert** when someone new appears (optional, with a mute keybind; a system sound or silence can be chosen instead, and alerts can stay quiet in instances). -- **Out-of-range players** can stay listed, greyed **and marked - *out of range* in text** (since 1.3.2 — the state doesn't rely on - color alone), so you see who's coming into range. **Right-click a - row** to ignore a player who doesn't want buffs - (`/br ignore` / `/br unignore` / `/br ignorelist`); since 1.3.2 - the ignore list is realm-aware, ignores capitalization, and names - can be removed one by one on the Ignore & Stats tab. +- **Explicitly out-of-range players are not cast rows.** Range Watch + (`/br rangewatch`) can alert when a player enters range. Assumed range is + an opt-in for unanswered checks and is marked estimated. **Right-click a + row** or use `/br ignore` to add to the realm-aware permanent ignore list + (up to 192 names); remove names on the Ignore & Stats tab or with + `/br unignore`. - **Role ordering** option: you, tanks (by the group role they picked) and leaders first (`/br sort name|role`). - Pauses in major cities (and, optionally, in battlegrounds), can @@ -385,8 +402,8 @@ stays hidden on those characters. statistics (`/br count`, `/br resetcount`, `/br stats`). The session count resets on login or `/reload`; the all-time count is shared by all your characters. -- Three keybinds: **Cast next buff**, **Show / hide window** and - **Mute / unmute sound** (`/br key`). +- Four keybinds: **Cast next buff**, **Cast next group buff**, + **Show / hide window**, and **Mute / unmute sound** (`/br key`). ## Not in this version @@ -399,6 +416,12 @@ stays hidden on those characters. ## Verification status +**1.15.38:** Lua 5.1 fake-client, coordination, lint, and package checks pass. +Windows package parity and live Forever results are **Unverified**. Fake +clients do not reproduce taint, chat delivery, real viewport rendering, or +restricted aura/range behavior on a live build. Known spell IDs are not a +complete catalogue of all Forever consumables or world buffs. + **1.15.35:** Macro migration, nearby cast targeting, blessing selection, and reversible nameplate controls pass the Lua smoke tests. Live casting, controller bindings, and nameplate appearance are **Unverified**. diff --git a/editions/forever/README.md b/editions/forever/README.md index d6578f0..3b06dc6 100644 --- a/editions/forever/README.md +++ b/editions/forever/README.md @@ -52,8 +52,8 @@ as the situation calls for. When everyone is buffed, the list empties and gets out of your way. It costs nothing, asks for nothing, and never talks to anything outside the game. -Version 1.15.37 · Interface 16001 · GPLv3. -Field-tested through v1.15.33; v1.15.34–v1.15.37 remain Unverified in game. +Version 1.15.38 · Interface 16001 · GPLv3. +Field-tested through v1.15.33; v1.15.34–v1.15.38 remain Unverified in game. **Forever-only from 1.8.0:** the Retail edition ended at 1.7.0 (dropped 2026-10-25). Both editions were built from the same source; this zip's `.toc` @@ -63,7 +63,21 @@ targets the Forever client, and BuffRadar picks the Forever buff set when it loa **Docs:** [Features](FEATURES.md) · [Description](DESCRIPTION.md) · [Changelog](CHANGELOG.md) -## Readiness in 1.15.37 +## Upgrading to 1.15.38 + +Back up `BuffRadarDB`'s SavedVariables file before upgrading. Existing valid +settings upgrade to schema 23. A newer schema is left untouched; your +changes in this session don't save. The same temporary mode applies if an +older save has more than 32 profiles or 192 permanent ignores (or a profile +body over 4,000 bytes). After backing up or exporting what you want to keep, +use `/br storage delete profile ` or `/br storage delete ignore ` +to remove an entry from an over-limit save, then reload. Those commands +can't edit a newer-schema save. + +`/br selftest` should report **1.15.38 · Forever edition · interface 16001**. +An incompatible client won't start the cast UI or change your saved settings. + +## Readiness (introduced in 1.15.37) Open **Settings → Readiness** for the new controls. Combat restrictions on click-to-buff casts still apply. @@ -94,10 +108,10 @@ and [roadmap](https://github.com/SeanShaffer88/BuffRadar/blob/main/docs/ROADMAP. - **The list grows downward.** The window is anchored by its top-left corner, so its top edge stays exactly where you put it as names come and go — only the bottom edge moves. -- **Scroll long lists.** When more than 15 rows are available, use the mouse - wheel over the list or `/br scroll up|down`. The range under the list shows - which rows are visible. Cast Next Buff still starts at the head of the - full queue. +- **Scroll long lists.** The list shows up to 15 rows, fewer when your screen + or UI scale leaves less room. Use the wheel or `/br scroll up|down`. The + footer shows the visible row span. Cast Next Buff still uses the head of + the full queue. - **You first.** Your own character is always checked first and sits at the top of the list whenever you're missing something. - **Class-aware.** Arcane Intellect only goes to mana users, Thorns to melee classes, @@ -119,11 +133,15 @@ and [roadmap](https://github.com/SeanShaffer88/BuffRadar/blob/main/docs/ROADMAP. instances). - **Group-cast offers:** when enough of your party or raid needs the same buff, BuffRadar offers the group version (Prayer of Fortitude, Gift of the Wild…) - instead. If the group spell's reagent is missing, it offers the - single-target spell. The ready-check view shows estimated reagent needs. + instead. It falls back to the single-target spell when group range, + recipient eligibility, cooldown or required reagents block the group + version. Supported pets get single-target buffs only. Ready Check estimates + reagent needs. - **Only eligible players appear:** your character must know a useful buff, and - both characters must be out of combat. When Forever cannot report spell-specific - range, BuffRadar uses the client's proximity estimate. **Right-click a row** + both characters must be out of combat. An explicitly out-of-range player + stays off the cast list. When spell range cannot be checked, BuffRadar may + use readable proximity information. `/br assumerange` opts into estimated + range for otherwise eligible single-target offers. **Right-click a row** to ignore a player who doesn't want buffs. - **Paladin blessings by class:** choose a known blessing for each class from the Buffs tab, or use `/br bless prefer `. An active @@ -201,16 +219,22 @@ and [roadmap](https://github.com/SeanShaffer88/BuffRadar/blob/main/docs/ROADMAP. per-buff coverage — also your progress while buffing a fresh group. - **Session-only ignore:** Shift-right-click a row to ignore someone until you log out (nothing saved). -- **`/br announce`** posts the group's missing buffs to party/raid chat, and - a ready check prints you a local summary. Use `/br ready show` to see - individual responses and buff status locally. +- **`/br announce`** requests a party/raid post and prints a local report on + refusal. A submitted send is not proof of delivery. Ready checks give a + local summary; `/br ready show` displays individual responses and buff status. - **Low-mana pause** (optional): listing pauses while your mana is under a percentage you set. - **Distance ordering** option: nearest first. -- **Settings export/import:** copy nearly all settings between characters - as one string (`/br export`, `/br import`). +- **Settings and profile imports:** `/br import` reviews a BR1 copy before + applying settings locally. `/br profile import` lets you rename or replace + a saved profile without loading it. `/br plan import` reviews assignments, + blessings and auto-profile mappings before merging. Choose **Apply locally** + to send nothing, or **Apply and share** when offered to send only assignment + and blessing changes to the current group. - **Compact rows** without portraits, a separate list text size, and a - per-character window position option. + per-character window position option. `/br positions on` remembers where + you drag Settings and Ready Check; `/br positions off` or `reset` clears + those panel positions. - **Post-combat flash:** the border pulses once when combat ends with buffs still missing. - **Cast sync between BuffRadar users:** when anyone running BuffRadar in @@ -247,14 +271,14 @@ and [roadmap](https://github.com/SeanShaffer88/BuffRadar/blob/main/docs/ROADMAP. - **Cover-me handoff:** when a BuffRadar user dies or goes AFK, their duties pass to the others automatically (sync channel, no setting). - **Pin, weapon watch, cast history:** keep one player on top - (`/br pin`), get flagged when your weapon has no enchant, and review - your last 50 casts (`/br history`). + (`/br pin`), check applicable melee weapons for temporary coatings, and + review your last 50 casts (`/br history`). - **All-buffed pill:** when everyone is fully buffed the window collapses to a small pill with the coverage count; click to peek. - **Cast queue tag:** the next row is tagged *up next* for a few seconds after one of your casts lands. -- **Consumables watch:** the coverage line also counts flasks and food - across the group (read-only — no rows). +- **Consumables watch:** the coverage line counts recognised flask and food + auras (read-only — no rows). An unreadable aura check is unknown, not missing. - **Custom watched spells:** watch any buff spell you know (`/br custom add `), offered to everyone it suits. - **Coverage uptime:** the share of grouped scans this session that @@ -386,7 +410,9 @@ outside a capital, or turn off the default city pause with `/br cities`. | `/br resetpos` | Reset the window position (also clears the per-character spot) | | `/br signore ` · `/br unsignore ` | Ignore a player for this session only (or Shift-right-click a row) | | `/br mana <0-100>` | Pause listing below this mana % (0 = off) | -| `/br export` · `/br import` | Copy settings between characters as one string | +| `/br export` · `/br import` | Copy settings between characters; review before applying locally | +| `/br profile import` · `/br plan import` | Review a named profile or plan before saving or applying it | +| `/br positions on\|off\|reset` | Remember or recenter Settings and Ready Check panel positions | | `/br compact` · `/br text <0.8-1.5>` · `/br charpoint` | Half-height rows · list text size · per-character window position | | `/br selftest` | Print a paste-able block for bug reports | | `/br bg` · `/br minimap` · `/br stats` | Pause in battlegrounds · toggle minimap button · casts by spell | @@ -426,8 +452,9 @@ outside a capital, or turn off the default city pause with `/br cities`. zone and map ID BuffRadar sees. - **Cast counter:** the session count resets on login or `/reload`. The all-time count is shared by all your characters. -- **Languages:** the main window, its tooltips and the minimap tooltips are in German - on German clients (`Locales\deDE.lua`); the settings window is English for now. +- **Languages:** the main list, tooltips, minimap, and new review and safety + messages are translated in `Locales\deDE.lua`. Some Settings controls and + diagnostics remain English. To add a language, copy that file — it explains how at the top. ## Credits diff --git a/tools/README.md b/tools/README.md index db893e1..b909b7d 100644 --- a/tools/README.md +++ b/tools/README.md @@ -8,7 +8,7 @@ including the one where WoW silently refuses to load the whole addon. On Windows, open **PowerShell 7** in the project folder (the one holding `BuffRadar\` and `build.ps1`). In File Explorer, open that folder and type -`pwsh` into the address bar. Install Python 3 first if `py -3 --version` +`pwsh` into the address bar. Install Python 3.10 or newer first if `py -3 --version` doesn't find it. Follow the one-time setup below, then run: ```powershell @@ -19,8 +19,25 @@ If you already have a BuffRadar tools folder, pass it with `-ToolsDir 'C:\path\to\brlua'`. From a Unix shell with Python 3 and Lupa available, use `sh tools/gate.sh` to run the same gate used by GitHub CI. -The checker prints each result and ends with **All checks passed.** or -**FAILED:** followed by what failed (exit code 1). Then build with `.\build.ps1`. +The checker exits nonzero on failure. A compiler failure stops the run before +smoke. Run Luacheck 1.2.0 separately from the POSIX gate. + +## Build and verify the ZIP + +Use `.\build.ps1` from PowerShell or `sh tools/package.sh` from POSIX. Both +call `tools/package.py`, write a deterministic ZIP and checksum to `dist/`, +and accept `--tag vX.Y.Z` to require an exact TOC match. Build before running +`check.ps1` again to include the current ZIP in its checks, or verify directly +with the Python environment that has Lupa installed: + +```sh +python -I tools/checkpackage.py dist/BuffRadar-X.Y.Z-Forever.zip . +``` + +Replace `X.Y.Z` with the TOC version. The final `.` checks ZIP inventory and +bytes against the current source, including the adjacent `SHA256SUMS.txt`. +CI builds on Windows and POSIX and compares SHA-256 digests. Build twice +before freezing a candidate, and use that exact ZIP for the field checklist. To run only the two-client Caster Coordination harness with the checker’s Python environment, use: @@ -48,12 +65,13 @@ then — just run `-Setup` again. | Check | Catches | |---|---| | **luacheck** | Accidental globals, unused or shadowed variables, unreachable code. Settings in `..\.luacheckrc`: reading the game's API is allowed, creating globals is reported unless listed there. | -| **Lua 5.1 compile** (`luacheck51.py`) | Compiles the addon and translations (the Forever TOC in PowerShell, all shared Lua files in CI). A compiler failure stops the gate before the trial run. | +| **Lua 5.1 compile** (`luacheck51.py`) | Compiles all shared Lua and locale files in PowerShell and POSIX. A compiler failure stops the gate before the trial run. | | **Lua 5.1 limits** (`lualimits.py`) | Estimates headroom against Lua 5.1's limits of 200 active locals and 60 upvalues per function. The checker warns from 195 locals or 55 upvalues. The estimates are advisory. | -| **Trial run** (`smoke51.py` + `wowstub.lua`) | Loads each edition in its TOC order. Checks startup and save migrations, cast attributes and event bookkeeping, window layout and controls, profile round trips, slash commands, and scan performance. Runs seven setups: both declared TOCs, plus variations for Extras on Retail, timers, UI templates, and German. | -| **Translations** (`localecheck.py`) | Each `Locales\*.lua` against BuffRadar's English text: keys BuffRadar doesn't use (typos, outdated text) and `%d` / `%s` / color codes that differ — both fail the check. Untranslated lines are only listed. | +| **Trial run** (`smoke51.py` + `wowstub.lua`) | Loads each edition in its TOC order. Checks startup and save migrations, cast attributes and event bookkeeping, window layout and controls, profile round trips, slash commands, and scan performance. `audit51.lua` contains isolated hardening regressions. Runs seven setups: both declared TOCs, plus variations for Extras on Retail, timers, UI templates, and German. | +| **Translations** (`localecheck.py`) | Each `Locales\*.lua` against BuffRadar's English text: keys BuffRadar doesn't use (typos, outdated text) and `%d` / `%s` / color codes that differ — both fail the check. Missing German keys fail; untranslated keys in partial locales are reported. | | **Lua pattern arguments** (`patterncheck.py`) | Every `find` / `match` / `gmatch` / `gsub` pattern must be a string literal, or the call must be a plain find (`:find(x, 1, true)`), so player names, chat and imports can never be read as patterns. One line at a time; a non-literal pattern fails the check. | -| **Forever package** | If a ZIP for the current version exists in `dist\`, checks its bytes against the current source, TOC metadata, declared Lua load order, and XML bindings in a Forever mock. CI builds and checks the archive on every PR. | +| **Packaging regressions** (`test_package.py`) | Rebuilds from independent source trees and checks repeat bytes, version/tag rejection, link and path refusal, source drift, archive metadata, checksums and exact bindings. | +| **Forever package** | If a ZIP for the current version exists in `dist\`, checks its bytes against the current source, TOC metadata, declared Lua load order, and XML bindings in a Forever mock, including `/br selftest` version readback. CI builds and checks the archive on every PR. | | **Two-client coordination** (`coordination51.py`) | Loads two independent Forever mock clients. Relays their real plan, cast, and session-proof packets. Checks plan acceptance, bidirectional cast sync, and replay rejection across roster and leadership changes. | ## Limits of the fake game client diff --git a/tools/audit51.lua b/tools/audit51.lua new file mode 100644 index 0000000..cba3c2c --- /dev/null +++ b/tools/audit51.lua @@ -0,0 +1,685 @@ +-- Focused release-candidate regressions using the same isolated clients as the smoke gate. +return function(step, fresh, testClient, loadClient, forever) + local function mentions(messages, text, first) + local count = 0 + for i = (first or 0) + 1, #messages do + if messages[i]:find(text, 1, true) then count = count + 1 end + end + return count + end + + local function rowFor(client, unit) + for i = 1, 15 do + local row = client["BuffRadarRow" .. i] + if row.entry and row.entry.unit == unit then return row end + end + end + + local function profile(f, rebuff) + local body, count = assert(f.X.ProfileSnapshot()):gsub(";rebuff=%d+;", ";rebuff=" .. rebuff .. ";") + assert(count == 1) + return body + end + + local function review(f, command, text) + f.slash(command) + local dialog = assert(f.client.BuffRadarExportFrame) + dialog.editBox:SetText(text) + dialog.accept:Click() + return dialog + end + + step("audit: unsupported clients leave saves untouched and park only an owned macro", function() + local parked = "# BuffRadar\n/stopmacro [combat][@player,dead]" + local cases = { + { 16000, "/click BuffRadarNextButton", parked }, + { forever and 120105 or 16001, "/say My own macro", "/say My own macro" }, + { 16002, parked .. "\n/click BuffRadarMacroButton\n/cast [@party1,help,nodead] Fortitude", parked, true }, + } + for _, case in ipairs(cases) do + local c, messages = testClient() + c.GetBuildInfo = function() return "bad", "0", "", case[1] end + local original = { scale = 9, opaque = {} } + c.BuffRadarDB = original + local i = c.CreateMacro("BuffRadar", 134400, case[2]) + local X, driver = loadClient(c) + c.__combat = case[4] or false + driver.scripts.OnEvent(driver, "ADDON_LOADED", "BuffRadar") + assert(not X.GetDB() and c.BuffRadarDB == original and original.scale == 9) + assert(not X.supported and not X.pullFrame and not c.__settings.registered) + assert(not c.BuffRadarNextButton and not c.BuffRadarFrame and c.BuffRadarAPI.GetSummary().actionable == 0) + assert(mentions(messages, X.L["BuffRadar requires the Forever package on Interface 16001. Casting is disabled."]) == 1) + if c.__combat then + assert(driver.events.PLAYER_REGEN_ENABLED and c.GetMacroBody(i) == case[2]) + c.__combat = false + driver.scripts.OnEvent(driver, "PLAYER_REGEN_ENABLED") + end + assert(not next(driver.events) and c.GetMacroBody(i) == case[3]) + end + end) + + step("audit: detached nested saves, future-version preservation and rejected placement", function() + local original = { dbVersion = 900, futureOnly = { "keep" }, scale = math.huge, + enabled = { FORTITUDE = false, INNER_FIRE = false, SHADOWGUARD = false, garbage = true }, + specProfiles = { s1 = { enabled = { FORTITUDE = true, FAKE = {} }, rebuffPer = { FORTITUDE = 2000 } }, + junk = { enabled = {} } }, + point = { "WAT", "CENTER", 2, 3 }, pointByChar = { ok = { "CENTER", "CENTER", 5, 6 }, bad = { "CENTER", "CENTER", 0/0, 1 } }, + customGroup = { Fortitude = "Prayer", Broken = "X;Y" }, stats = { Bright = 2, Bad = -1 }, offenders = { Alia = 3 } } + local f = fresh(original) + local db = f.db + assert(f.client.BuffRadarDB == original and db ~= original and db.dbVersion == 23) + assert(db.scale == 1 and not db.futureOnly and not db.point and not db.pointByChar.bad) + assert(db.specProfiles.s1.rebuffPer.FORTITUDE == 600 and not db.specProfiles.s1.enabled.FAKE and not db.specProfiles.junk) + assert(db.customGroup.Fortitude == "Prayer" and not db.customGroup.Broken and not db.stats.Bad) + assert(db.offenders["legacy:Alia"].count == 3) + db.pointByChar.ok[3], db.specProfiles.s1.enabled.FORTITUDE = 55, false + assert(original.pointByChar.ok[3] == 5 and original.specProfiles.s1.enabled.FORTITUDE and original.futureOnly[1] == "keep") + f.slash("scale 1.5") + assert(original.scale == math.huge and original.dbVersion == 900) + local rejected = false + local g = fresh({ point = { "TOPLEFT", "CENTER", 177, 4 } }, false, function(c) + local create = c.CreateFrame + c.CreateFrame = function(kind, name, parent, template) + local frame = create(kind, name, parent, template) + if name == "BuffRadarFrame" then + local place = frame.SetPoint + frame.SetPoint = function(self, p, rel, rp, x, y) + if x == 177 then rejected = true; error("refused saved anchor") end + place(self, p, rel, rp, x, y) + end + end + return frame + end + end) + assert(rejected and g.X.WindowReady() and not g.db.point and g.client.BuffRadarFrame.points[1][3] == "LEFT") + local h = fresh({ point = { "TOPRIGHT", "TOPRIGHT", 88888, 88888 } }) + assert(h.X.WindowReady() and not h.db.point, "plausible but off-screen point was restored") + end) + + step("audit: storage limits reject additions atomically and preserve oversized legacy saves", function() + local f = fresh({}) + local X, db = f.X, f.db + for i = 1, X.Settings.Limits.profiles do assert(X.SaveProfile("P" .. i)) end + assert(not X.SaveProfile("Overflow") and X.Settings.Count(db.profiles) == X.Settings.Limits.profiles) + local names = {} + for i = 1, X.Settings.Limits.ignored - 1 do names[i] = "Name" .. i end + assert(X.Ignore.AddMany(names) == #names) + assert(not X.Ignore.AddMany({ "Extra", "Second" }) and not db.ignored.Extra and not db.ignored.Second) + for i = 1, X.Settings.MaxGroupPairs do f.slash('grouppair "Single ' .. i .. '" "Group ' .. i .. '"') end + f.slash('grouppair "Overflow" "Group"') + f.slash('grouppair "Single 1" "[harm]Action"') + assert(not db.customGroup.Overflow and db.customGroup["Single 1"] == "Group 1") + local original = { dbVersion = 22, profiles = db.profiles, ignored = db.ignored } + original.profiles.Overflow = original.profiles.P1 + local g = fresh(original) + assert(g.client.BuffRadarDB == original and g.X.Settings.SaveState() == "overflow" and original.profiles.Overflow) + g.slash("storage delete profile Overflow") + assert(not original.profiles.Overflow and original.profiles.P1 and original.dbVersion == 22) + assert(g.X.Settings.Load(true) == nil and g.client.BuffRadarDB ~= original and g.client.BuffRadarDB.dbVersion == 23) + end) + + step("audit: settings review supports cancel, edit paste and re-review after drift", function() + local f = fresh({ rebuff = 27, hidden = false }, true) + local text, change = assert(f.X.Export()):gsub(";rebuff=27;", ";rebuff=79;") + assert(change == 1) + local d = review(f, "import", text) + assert(d.review:IsShown() and d.draft and not d.share:IsShown() and f.db.rebuff == 27) + assert(d.reviewText:GetText():find("rebuff: 27 → 79", 1, true)) + d.back:Click() + assert(d.editBox:IsShown() and d.editBox:GetText() == text and not d.draft) + d.accept:Click(); d.cancel:Click() + assert(not d:IsShown() and not d.draft and f.db.rebuff == 27 and not f.client.__editFocus) + d = review(f, "import", text) + local oldHistory, oldPositions = f.db.history, f.db.panelPoints + f.slash("rebuff 40") + d.apply:Click() + assert(d:IsShown() and f.db.rebuff == 40 and d.reviewText:GetText():find("rebuff: 40 → 79", 1, true)) + d.apply:Click() + assert(not d:IsShown() and f.db.rebuff == 79 and f.db.history == oldHistory and f.db.panelPoints == oldPositions) + local over = review(f, "import", "BR1;" .. string.rep("x", 16384)) + assert(over.editBox:IsShown() and not over.draft and f.db.rebuff == 79) + local many = {} + for i = 1, f.X.Settings.Limits.ignored + 1 do many[i] = ";ignored.More" .. i .. "=1" end + local oversized = text:gsub(";endExport=1$", table.concat(many) .. ";endExport=1") + assert(#oversized < 16384 and not f.X.ParseSettingsImport(oversized)) + assert(not f.X.Import(oversized) and not next(f.db.ignored)) + end) + + step("audit: profile import exposes collisions, rechecks replacement and can rename without loading", function() + local f = fresh({ rebuff = 27 }) + local db = f.db + local prior, changed, body = profile(f, 15), profile(f, 16), profile(f, 79) + db.profiles.Alpha, db.autoProfile.raid = prior, "Alpha" + local d = review(f, "profile import", "BuffRadar profile: Alpha\n" .. body) + assert(d.apply:GetText() == f.X.L["Replace profile"] and d.reviewText:GetText():find("raid", 1, true)) + assert(d.reviewText:GetText():find("rebuff: 27 → 79", 1, true) and db.profiles.Alpha == prior) + db.profiles.Alpha = changed + d.apply:Click() + assert(d:IsShown() and db.profiles.Alpha == changed and db.rebuff == 27) + d.nameBox:SetText("Beta"); d.nameBox.scripts.OnTextChanged(d.nameBox) + assert(d.apply:GetText() == f.X.L["Save profile"]) + d.apply:Click() + assert(not d:IsShown() and db.profiles.Beta == body and db.profiles.Alpha == changed and db.rebuff == 27) + d = review(f, "profile import", "BuffRadar profile: Alpha\n" .. body) + d.apply:Click() + assert(db.profiles.Alpha == body and db.autoProfile.raid == "Alpha" and db.rebuff == 27) + end) + + step("audit: plan review is local by default and sharing rejects membership and authority drift", function() + local f = fresh({ sync = true }, true) + local X, c = f.X, f.client + local leader = "Me" + c.UnitIsGroupLeader = function(unit) return c.UnitName(unit) == leader end + f.event("GROUP_ROSTER_UPDATE") + local function sent() + local total = 0 + for _, message in ipairs(c.__addonSent) do if message.msg:sub(1, 7) == "ASSIGN;" then total = total + 1 end end + return total + end + local text = "BRPLAN1;A;FORTITUDE;Alia;P;raid;Future" + local d = review(f, "plan import", text) + assert(d.share:IsShown() and d.reviewText:GetText():find("Future", 1, true)) + assert(d.back.points[1][3] ~= d.share.points[1][3] and d.share.points[1][3] ~= d.apply.points[1][3]) + d.apply:Click() + assert(X.assign.FORTITUDE == "Alia" and f.db.autoProfile.raid == "Future" and sent() == 0) + text = "BRPLAN1;A;FORTITUDE;Bren" + d = review(f, "plan import", text) + local before = f.units.party1 + f.units.party1 = { "Substitute", "MAGE" }; f.event("GROUP_ROSTER_UPDATE") + f.units.party1 = before; f.event("GROUP_ROSTER_UPDATE") + d.share:Click() + assert(d:IsShown() and X.assign.FORTITUDE == "Alia" and sent() == 0, "same members returned after churn") + d = review(f, "plan import", text) + leader = "Bren"; f.event("PARTY_LEADER_CHANGED") + d.share:Click() + assert(d:IsShown() and X.assign.FORTITUDE == "Alia" and sent() == 0) + leader = "Me"; f.event("PARTY_LEADER_CHANGED") + d = review(f, "plan import", text) + f.units.party1, f.units.party2 = f.units.party2, f.units.party1 + f.event("GROUP_ROSTER_UPDATE") + d.share:Click() + assert(not d:IsShown() and X.assign.FORTITUDE == "Bren" and sent() == 1, "reorder retired an otherwise current review") + local guid = f.O.UnitGUID + f.O.UnitGUID = function(unit) return guid(unit == "party1" and "party2" or unit) end + f.event("GROUP_ROSTER_UPDATE") + d = review(f, "plan import", "BRPLAN1;A;FORTITUDE;Alia") + assert(not X.GroupIdentity() and not d.share:IsShown() and sent() == 1, "duplicate GUID allowed sharing") + end) + + step("audit: remote legacy plan ownership restores local values after authority loss", function() + local f = fresh({ sync = true }, true) + local X, c = f.X, f.client + local leader = "Alia" + c.UnitIsGroupLeader = function(unit) return c.UnitName(unit) == leader end + X.SetLocalPlan("ASSIGN", "FORTITUDE", "Local-Realm") + local prior = { key = "KINGS", name = "Local-Realm" } + X.SetLocalPlan("BLESS", "WARRIOR", prior) + f.event("CHAT_MSG_ADDON", "BuffRadar", "ASSIGN;FORTITUDE;Alia-Realm", "PARTY", "Alia-Realm") + f.event("CHAT_MSG_ADDON", "BuffRadar", "BLESS;WARRIOR;MIGHT;Alia-Realm", "PARTY", "Alia-Realm") + assert(X.assign.FORTITUDE == "Alia-Realm" and X.blessPlan.WARRIOR.key == "MIGHT") + leader = "Bren"; f.event("PARTY_LEADER_CHANGED") + assert(X.assign.FORTITUDE == "Local-Realm" and X.blessPlan.WARRIOR == prior) + f.event("CHAT_MSG_ADDON", "BuffRadar", "ASSIGN;FORTITUDE;Bren-Realm", "PARTY", "Bren-Realm") + assert(X.assign.FORTITUDE == "Bren-Realm") + f.units.party1 = { "Substitute", "PRIEST" }; f.event("GROUP_ROSTER_UPDATE") + assert(X.assign.FORTITUDE == "Local-Realm", "previous membership kept its overlay") + f.event("CHAT_MSG_ADDON", "BuffRadar", "ASSIGN;FORTITUDE;Bren-Realm", "PARTY", "Bren-Realm") + assert(X.assign.FORTITUDE == "Bren-Realm") + f.slash("sync") + assert(X.assign.FORTITUDE == "Local-Realm" and not f.db.sync) + end) + + step("audit: refresh faults before arm and after partial paint disarm all actions and recover", function() + local f = fresh({ includeSelf = false }, true) + local X, c = f.X, f.client + local nextButton, group = c.BuffRadarNextButton, c.BuffRadarGroupButton + X.Refresh(); f.slash("macro") + local index = assert(c.GetMacroIndexByName("BuffRadar")) + local parked = "# BuffRadar\n/stopmacro [combat][@player,dead]" + local function unavailable(why) + local status = f.api.GetStatus() + assert(status.state == "unavailable" and status.reason == why and #status.targets == 0) + assert(not nextButton.entry and not group.entry and not nextButton.attrs.type and not group.attrs.type) + assert(not next(X.tally) and not X.ScrollRows(1)) + for i = 1, 15 do + local row = c["BuffRadarRow" .. i] + assert(not row.entry and not row.attrs.type and not row.attrs["shift-type1"]) + end + end + local function armed() + assert(f.api.GetSummary().actionable >= 2 and nextButton.attrs.type and group.attrs.type) + assert(c.GetMacroBody(index) ~= parked) + end + armed() + local prepare = X.PrepareWindowScan + X.PrepareWindowScan = function() error("fault before arm") end + X.Refresh(); unavailable("updating") + assert(c.GetMacroBody(index) == parked) + X.PrepareWindowScan = prepare + X.Refresh(); armed() + local row = c.BuffRadarRow2 + local paint = row.SetAlpha + row.SetAlpha = function() error("fault during second row paint") end + X.Refresh(); unavailable("updating") + assert(c.GetMacroBody(index) == parked) + row.SetAlpha = paint + X.Refresh(); armed() + + -- Simulate the secure driver's clearing before dispatching the combat event. + -- Counts record attempted protected writes even if pcall swallowed an error. + local attempts = 0 + for _, button in ipairs({ nextButton, group, c.BuffRadarRow1, c.BuffRadarRow2, c.BuffRadarFrame }) do + for _, method in ipairs({ "SetAttribute", "Hide", "Show", "SetPoint" }) do + local original = button[method] + button[method] = function(self, ...) + if c.__combat then attempts = attempts + 1; error("protected write in combat") end + return original(self, ...) + end + end + for attribute in pairs(button.attrs) do if attribute ~= "_onstate-combat" then button.attrs[attribute] = nil end end + end + local edit = c.EditMacro + c.EditMacro = function(...) + if c.__combat then attempts = attempts + 1; error("macro write in combat") end + return edit(...) + end + c.__combat = true; f.event("PLAYER_REGEN_DISABLED") + X.RefreshFault("fault while locked") + unavailable("combat") + assert(attempts == 0 and c.GetMacroBody(index):find("/stopmacro [combat][@player,dead]", 1, true)) + c.__combat = false; f.event("PLAYER_REGEN_ENABLED"); f.advance(0.11) + armed() + end) + + step("audit: short viewport reuses secure rows and cached paint shares fault cleanup", function() + local f = fresh({ scale = 1.5, includeSelf = true, showStrip = false }, true) + local X, c = f.X, f.client + f.units.party3, f.units.party4 = { "Dara", "PRIEST" }, { "Elio", "MAGE" } + c.GetNumGroupMembers = function() return 5 end + X.Refresh() + local row, frames = c.BuffRadarRow1, #c.__frames + c.UIParent.GetHeight = function() return 160 end + f.event("DISPLAY_SIZE_CHANGED"); f.advance(0.11) + assert(c.BuffRadarFrame.height * f.db.scale <= 160 and #c.__frames == frames, + "height=" .. tostring(c.BuffRadarFrame.height * f.db.scale) .. " frames=" .. #c.__frames .. "/" .. frames) + local first, nextEntry = assert(row.entry).guid, c.BuffRadarNextButton.entry + assert(X.ScrollRows(1), "the short viewport did not scroll") + assert(row.entry.guid ~= first and c.BuffRadarNextButton.entry == nextEntry, "scroll changed the cast-next entry") + local paint = row.SetAlpha + row.SetAlpha = function() error("cached paint fault") end + assert(not X.ScrollRows(-1)) + assert(not row.entry and not row.attrs.type and not c.BuffRadarNextButton.attrs.type and f.api.GetSummary().reason == "updating") + row.SetAlpha = paint + X.Refresh() + assert(row.entry and row.attrs.type and c.BuffRadarNextButton.attrs.type and #c.__frames == frames) + X.InvalidateRows() -- invalidate the presentation cache just before retiring an armed row + f.db.hidden = true; X.Refresh() + assert(not row.entry and not row.attrs.type and not row.attrs["shift-type1"] and c.BuffRadarNextButton.attrs.type) + end) + + step("audit: group actions fall back for target, range, reagents and stale identity", function() + if not forever then return end + local f = fresh({ includeSelf = false, modClick = true, groupCast = true, groupCastMin = 2, pets = true }, true) + local X, c, db = f.X, f.client, f.db + local single, prayer = "Power Word: Fortitude", "Prayer of Fortitude" + db.enabled[f.manaKey] = false + local group = c.BuffRadarGroupButton + X.Refresh() + assert(group.bSpell == prayer and c.BuffRadarNextButton.bSpell == prayer) + c.GetSpellCooldown = function(spell) if spell == prayer then return 95, 20 end return 0, 0 end + X.Refresh() + assert(group.bSpell == single and c.BuffRadarNextButton.bSpell == single) + c.GetSpellCooldown = nil + c.IsSpellInRange = function(spell) return spell ~= prayer and 1 or 0 end + X.Refresh() + local row = assert(rowFor(c, "party1")) + assert(row.bSpell == single and row.bGroupSpell == single and group.bSpell == single) + c.IsSpellInRange = function(spell) if spell ~= prayer then return 1 end end + c.UnitInRange = function() return nil end + db.assumeRange = true; X.Refresh() + assert(group.bSpell == single, "assumed range armed the group version") + c.IsSpellInRange = function() return 1 end + c.C_Item.GetItemCount = function() return nil end + X.InvalidateReagents(); X.Refresh() + assert(group.bSpell == single and row.bGroupSpell == single) + c.C_Item.GetItemCount = function() return 10 end + X.InvalidateReagents(); X.Refresh() + assert(group.bSpell == prayer) + f.units[group.entry.unit] = { "New", "PRIEST" } + group.scripts.PreClick(group, "LeftButton", false) + assert(not group.attrs.type and not group.entry) + f.units.partypet1 = { "Wolf", "WARRIOR" } + f.O.UnitIsPlayer = function(unit) return f.units[unit] ~= nil and unit ~= "partypet1" end + f.O.Aura = function(unit, spell) + if unit ~= "partypet1" and spell == single then return { expirationTime = 0 } end + end + X.Refresh() + row = assert(rowFor(c, "partypet1")) + assert(row.bSpell == single and row.bGroupSpell == single and group.bSpell == single) + assert(not X.GroupOffer(single, "partypet1")) + assert(row.attrs.type == "spell" and row.attrs.unit == "partypet1" and not row.attrs.macrotext) + assert(c.BuffRadarNextButton.attrs.unit == "partypet1" and group.attrs.unit == "partypet1") + f.slash("macro") + local macro = c.GetMacroIndexByName("BuffRadar") + assert(c.GetMacroBody(macro):find("/click BuffRadarNextButton", 1, true)) + f.units.partypet1 = { "AnotherWolf", "WARRIOR" } + f.event("UNIT_PET", "party1") + assert(not c.GetMacroBody(macro):find("/click", 1, true), "stale pet token left the macro armed") + row.scripts.PreClick(row, "LeftButton", false) + assert(not row.attrs.type and not row.entry) + f.advance(0.11) + assert(c.GetMacroBody(macro):find("/click BuffRadarNextButton", 1, true), "pet-change refresh did not re-arm") + f.slash("subgroup FORTITUDE 1") + assert(not X.GetSubgroupDuty("FORTITUDE"), "party accepted raid-only subgroup duty") + for _, value in ipairs({ "1,1", "1,,2", "1,", "0", "9", "1.0", "ALL,1" }) do + local _, ok = X.Settings.ParseSubgroups(value) + assert(not ok, "invalid subgroup set: " .. value) + end + end) + + step("audit: ineligible rank is not armed except in explicit plain macro mode", function() + if not forever then return end + local f = fresh({ includeSelf = false, castMethod = "target" }, true, function(c) + c.UnitLevel = function(unit) return unit == "party1" and 15 or 25 end + c.GetSpellLevelLearned = function(id) return id == 1243 and 30 or (id == 1244 and 40 or nil) end + end) + f.db.enabled[f.manaKey] = false + for _, method in ipairs({ "target", "id", "rank" }) do + f.db.castMethod = method + f.X.Refresh() + local low, allowed = rowFor(f.client, "party1"), rowFor(f.client, "party2") + assert(not low and allowed and allowed.bRankID == 1243 and allowed.attrs.type, method .. " chose the wrong rank") + end + f.db.castMethod = "macro" + f.X.Refresh() + assert(rowFor(f.client, "party1"), "explicit plain macro mode changed") + end) + + step("audit: aura IDs are locale-independent and unavailable helpful reads never prove absence", function() + if not forever then return end + local f = fresh({ readinessAura = 801, worldWatch = true }, false, function(c) c.GetLocale = function() return "deDE" end end) + local c, X = f.client, f.X + local list = { + { name = "Stärkungszauber", spellId = 17626, expirationTime = 500 }, + { name = "Satt", spellId = 19705, expirationTime = 500 }, + { name = "Trinken", spellId = 430, expirationTime = 500 }, + { name = "Drachentöter", spellId = 22888, expirationTime = 500 }, + } + f.O.AuraList = function() return list end + local reads = 0 + c.C_UnitAuras.GetPlayerAuraBySpellID = function(id) + reads = reads + 1 + assert(id == 801) + return { spellId = 801, expirationTime = 0, isHarmful = false } + end + local got = X.ObserveConsumables("player", {}, true, true, 801) + assert(got.FOOD and got.FLASK and got.DRINK and got.OPTIONAL and reads == 1) + assert(X.WorldBuffsText():find("Drachentöter", 1, true)) + c.C_UnitAuras.GetPlayerAuraBySpellID = function() return { spellId = 801, expirationTime = 0 } end + assert(X.ObserveConsumables("player", {}, false, false, 801).OPTIONAL == false, "unclassified aura proved helpful") + c.C_UnitAuras.GetPlayerAuraBySpellID = function() return { spellId = 801, expirationTime = 0, isHarmful = true } end + assert(X.ObserveConsumables("player", {}, false, false, 801).OPTIONAL == false, "harmful aura proved helpful") + c.C_UnitAuras.GetPlayerAuraBySpellID = function() return nil end + c.C_UnitAuras.GetBuffDataByIndex = function() error("restricted auras") end + got = X.ObserveConsumables("player", {}, true, true, 801) + assert(not next(got) and X.WorldBuffsText():find(X.L["Some world buff information is unavailable."], 1, true)) + c.C_UnitAuras.GetBuffDataByIndex = function() + reads = reads + 1 + return { name = "Anderer Zauber", spellId = 332, expirationTime = 0 } + end + reads = 0 + assert(not next(X.ObserveConsumables("player", {}, true, true, 801)) and reads == 40) + c.C_UnitAuras = nil + got = X.ObserveConsumables("player", {}, true, true, 801) + assert(got.FOOD and got.FLASK and got.DRINK and got.OPTIONAL == false, "legacy tuple lost spell identity") + c.GetInventoryItemID = function(_, slot) return slot == 17 and 112 or nil end + c.GetWeaponEnchantInfo = function() return false, 0, 0, 0, false end + c.GetItemInfoInstant = function() return 112, nil, nil, "INVTYPE_SHIELD", nil, 4 end + assert(X.WeaponCoatingState() == "na") + c.GetItemInfoInstant = function() return 112, nil, nil, "INVTYPE_WEAPONOFFHAND", nil, 2 end + assert(X.WeaponCoatingState() == "missing") + c.GetItemInfoInstant = function() return nil end + assert(X.WeaponCoatingState() == "unknown") + end) + + step("audit: roster observations survive an unknown read but retire after departure and expiry", function() + local f = fresh({ includeSelf = false }, true) + local X, c = f.X, f.client + f.db.enabled[f.manaKey] = false + local guid = c.UnitGUID("party1") + local previous = c.C_UnitAuras.GetBuffDataByIndex + local covered = true + f.O.Aura = function(unit, spell) + if unit == "party1" and spell == "Power Word: Fortitude" and covered then return { expirationTime = 0 } end + end + X.Refresh() + assert(X.missPrev[guid] and not X.missPrev[guid].FORTITUDE) + covered = false + f.O.Aura = function() error("no named aura read") end + c.C_UnitAuras.GetBuffDataByIndex = function(unit, ...) if unit ~= "party1" then return previous(unit, ...) end end + X.Refresh() + assert(X.missPrev[guid] and not X.missPrev[guid].FORTITUDE and not X.expiredAt[guid]) + f.O.Aura, c.C_UnitAuras.GetBuffDataByIndex = nil, previous + X.Refresh() + assert(X.expiredAt[guid] and X.missPrev[guid].FORTITUDE) + local dead = true + f.O.UnitIsDeadOrGhost = function(unit) return unit == "party1" and dead end + X.Refresh(); assert(X.dead[guid]) + dead = false + X.Refresh(); assert(X.rezAt[guid] and not X.dead[guid]) + f.advance(11); X.Refresh(); assert(not X.expiredAt[guid] and X.rezAt[guid]) + f.units.party1 = { "Replacement", "PRIEST" } + f.event("GROUP_ROSTER_UPDATE") + assert(not X.missPrev[guid] and not X.rezAt[guid] and not X.dead[guid] and not X.expiredAt[guid]) + end) + + step("audit: pull ownership ignores unrelated and ambiguous stops and boss-mod traffic outside group scope", function() + local f = fresh({ forecastSeconds = 30 }, true) + local X, c = f.X, f.client + if not X.pullFrame then return end + c.UnitIsGroupLeader = function(unit) return unit == "party1" end + f.event("START_TIMER", 2, 15, 15) + local timer = assert(X.pull) + f.event("START_PLAYER_COUNTDOWN", "Player-1-Alia", 15, 15) + assert(X.pull == timer and timer.owner == "Player-1-Alia") + f.event("STOP_TIMER_OF_TYPE", 2) + f.event("CANCEL_PLAYER_COUNTDOWN", "Player-1-Bren") + assert(X.pull == timer) + f.event("CANCEL_PLAYER_COUNTDOWN", "Player-1-Alia") + assert(not X.pull) + f.event("START_PLAYER_COUNTDOWN", "Player-1-Stranger", 20) + assert(not X.pull) + f.event("START_PLAYER_COUNTDOWN", "Player-1-Alia", 20) + f.event("START_PLAYER_COUNTDOWN", "Player-1-Alia", 11) + f.event("CANCEL_PLAYER_COUNTDOWN", "Player-1-Alia") + assert(X.pull and X.pull.ambiguousStop) + f.advance(12, true) + assert(not X.pull, "replacement never expired") + f.event("CHAT_MSG_ADDON", "D5", "PT\t10\t33", "RAID", "Alia-Realm") + f.event("CHAT_MSG_ADDON", "D5", "PT\t10\tbroken", "PARTY", "Alia-Realm") + f.event("CHAT_MSG_ADDON", "D5", "PT\t10\t33", "PARTY", "Alia-WrongRealm") + assert(not X.pull) + f.event("CHAT_MSG_ADDON", "D5", "PT\t10\t33", "PARTY", "Alia-Realm") + assert(X.pull and X.pull.owner == "Player-1-Alia") + f.event("CHAT_MSG_ADDON", "D5", "PT\t0", "PARTY", "Alia-Realm") + assert(X.pull, "mapless stop canceled a scoped timer") + f.event("CHAT_MSG_ADDON", "D5", "PT\t0\t34", "PARTY", "Alia-Realm") + assert(X.pull, "different timer ID canceled a scoped timer") + f.event("CHAT_MSG_ADDON", "D5", "PT\t0\t33", "PARTY", "Alia-Realm") + assert(not X.pull) + f.event("CHAT_MSG_ADDON", "D5", "PT\t10", "PARTY", "Alia-Realm") + f.event("CHAT_MSG_ADDON", "D5", "PT\t0", "PARTY", "Alia-Realm") + assert(X.pull, "mapless stop canceled an unidentified timer") + c.UnitIsGroupLeader = function(unit) return unit == "party2" end + f.event("PARTY_LEADER_CHANGED") + assert(not X.pull, "timer retained without a trusted sender") + X.tally = { FORTITUDE = { miss = 1 } } + f.slash("pullflash on") + f.event("START_PLAYER_COUNTDOWN", "Player-1-Bren", 20) + local active = assert(X.pull) + f.slash("pullflash off") + assert(X.pull == active, "disabling flash discarded an active forecast") + f.slash("forecast off") + assert(not X.pull, "disabling both consumers retained a pull") + end) + + step("audit: delayed join digest cannot cross a leave and rejoin", function() + local f = fresh({ joinDigest = true, includeSelf = false }) + if not f.client.C_Timer then return end + local joined = false + f.client.IsInGroup = function() return joined end + f.client.GetNumGroupMembers = function() return joined and 2 or 0 end + local function enter(name) + joined, f.units.party1 = true, { name, "PRIEST" } + f.event("GROUP_ROSTER_UPDATE") + end + enter("First"); f.advance(0.40) + joined, f.units.party1 = false, nil; f.event("GROUP_LEFT") + enter("Second"); f.advance(1.11) + assert(mentions(f.messages, "Joined a group:") == 0) + f.advance(0.50) + assert(mentions(f.messages, "Joined a group:") == 1) + joined, f.units.party1 = false, nil; f.event("GROUP_LEFT") + enter("Third") + enter("Changed"); enter("Third") + f.advance(2) + assert(mentions(f.messages, "Joined a group:") == 1, "a retired membership printed a delayed digest") + end) + + step("audit: chat reports distinguish refusal, submission and delivery uncertainty", function() + local f = fresh({ includeSelf = false }, true) + local X, c, L = f.X, f.client, f.X.L + local requested = L["Group chat send requested; delivery is not confirmed."] + local accepted = L["Game accepted the group chat send; delivery is not confirmed."] + local n = #f.messages + f.slash("announce") + assert(#c.__sent == 1 and c.__sent[1].chattype == "PARTY" and mentions(f.messages, requested, n) == 1) + c.SendChatMessage = function() return true end + n = #f.messages; f.slash("announce") + assert(mentions(f.messages, accepted, n) == 1) + c.SendChatMessage = function() return false end + n = #f.messages; f.slash("announce") + assert(mentions(f.messages, L["The game did not accept the send."], n) == 1 + and mentions(f.messages, "missing buffs:", n) == 1 and mentions(f.messages, accepted, n) == 0) + c.SendChatMessage = function() error("chat refused") end + assert(not X.SendGroupReport("Local")) + local calls = 0 + c.C_ChatInfo = { SendChatMessage = function(text, channel) + assert(text == "Local" and channel == "RAID"); calls = calls + 1 + end } + c.IsInRaid = function() return true end + assert(X.SendGroupReport("Local") == "RAID" and calls == 1) + calls, c.C_ChatInfo, c.IsInRaid = 0, nil, nil + c.SendChatMessage = function() calls = calls + 1 end + assert(not X.SendGroupReport(string.rep("x", 256)) and calls == 0) + c.IsInGroup, c.GetNumGroupMembers = function() return false end, function() return 0 end + assert(not X.SendGroupReport("Local") and calls == 0) + end) + + step("audit: settings and import fall back when optional templates refuse; panel positions are opt-in", function() + local refused = 0 + local f = fresh({}, true, function(c) + c.BackdropTemplateMixin = {} + c.__rejectTemplate = function(_, _, template) + local reject = template and not template:find("Secure", 1, true) + if reject then refused = refused + 1 end + return reject + end + end) + local c, db, L = f.client, f.db, f.X.L + assert(f.X.WindowReady() and c.BuffRadarRow1) + f.slash("config") + local cfg = assert(c.BuffRadarConfig) + assert(cfg:IsShown() and not cfg.nativeTabs and cfg.scaleDrop:GetText() ~= "" and refused > 0) + local dialog = review(f, "profile import", "BuffRadar profile: Usable\n" .. profile(f, 40)) + assert(dialog.draft and dialog.review:IsShown()) + dialog.apply:Click(); assert(db.profiles.Usable) + cfg.GetPoint = function() return "CENTER", c.UIParent, "CENTER", 51, 26 end + cfg.scripts.OnDragStop(cfg) + assert(not db.panelPoints.settings) + f.slash("positions on") + cfg.scripts.OnDragStop(cfg) + cfg:Hide(); cfg:Show() + assert(db.panelPoints.settings[3] == 51 and cfg.points[1][4] == 51) + f.slash("ready show"); f.event("READY_CHECK") + local ready = assert(c.BuffRadarReadyCheck) + ready.GetPoint = function() return "CENTER", c.UIParent, "CENTER", 31, 11 end + ready.scripts.OnDragStop(ready) + assert(db.panelPoints.ready[3] == 31) + f.slash("positions reset") + assert(db.rememberPanelPositions and not next(db.panelPoints) and ready.points[1][5] == 85 and cfg.points[1][4] == 0) + f.slash("positions off") + assert(not db.rememberPanelPositions) + assert(c["BINDING_NAME_CLICK BuffRadarNextButton:LeftButton"] == L["Cast next buff"]) + local button = c.BuffRadarMinimapButton + assert(not button.scripts.OnUpdate) + button.scripts.OnDragStart(button); assert(button.scripts.OnUpdate) + button.scripts.OnDragStop(button); assert(not button.scripts.OnUpdate) + end) + + step("audit: CPU counters measure scan, import, preparation and combat debuff work independently", function() + local tick = 0 + local f = fresh({ debuffWatch = true, debuffRules = { { spellID = 710, unit = "player", encounterID = 0 } } }, true, + function(c) c.debugprofilestop = function() tick = tick + 0.1; return tick end end) + local t = f.X.timings + f.X.Refresh() + assert(t.scan.n >= 1 and t.scan.max > 0 and t.import.n == 0) + review(f, "profile import", "BuffRadar profile: Timing\n" .. profile(f, 42)).apply:Click() + assert(t.import.n == 2 and t.import.total > 0) + if forever then f.slash("readiness"); assert(t.prepare.n >= 1 and t.prepare.last > 0) end + local before = t.scan.n + f.client.__combat = true; f.event("PLAYER_REGEN_DISABLED") + assert(t.scan.n == before and t.combatDebuff.n >= 1 and t.combatDebuff.total > 0) + f.client.debugprofilestop = function() error("profiling clock not available") end + f.client.__combat = false; f.event("PLAYER_REGEN_ENABLED"); f.advance(0.11) + assert(t.scan.n == before and f.api.GetSummary().actionable > 0, "optional timing prevented recovery") + end) + + step("audit: Nearby resolves against the painted viewport and does no target work while closed", function() + if not forever then return end + local f = fresh({ includeSelf = false }, true) + local X, c = f.X, f.client + local reads, explain = 0, X.ExplainCurrentTarget + X.ExplainCurrentTarget = function(...) + reads = reads + 1 + return explain(...) + end + f.slash("nearby") + local panel = assert(c.BuffRadarNearbyDiagnostics) + assert(panel:IsShown() and reads == 1) + f.units.target = { "Drifter", "PRIEST" } + f.event("PLAYER_TARGET_CHANGED") + assert(panel.targetDirty and reads == 2) + f.advance(0.11) + assert(not panel.targetDirty and reads == 3 and panel.details:GetText():find("Drifter is on the list", 1, true)) + f.db.hidden = true + f.units.target = { "Traveler", "MAGE" } + f.event("PLAYER_TARGET_CHANGED"); f.advance(0.11) + assert(not panel.targetDirty and reads == 5 and not c.BuffRadarFrame:IsShown()) + assert(panel.details:GetText():find("Traveler", 1, true) and not panel.details:GetText():find("on the list", 1, true)) + panel:Hide() + f.units.target = { "Third", "MAGE" } + f.event("PLAYER_TARGET_CHANGED"); f.advance(0.11, true) + assert(reads == 5 and not panel.targetDirty and not panel.events.PLAYER_TARGET_CHANGED and not panel.events.CVAR_UPDATE) + f.slash("nearby") + assert(panel:IsShown() and panel.events.PLAYER_TARGET_CHANGED and panel.events.CVAR_UPDATE + and panel.details:GetText():find("Third", 1, true) and reads == 6) + end) + + step("audit: offender histories stay bounded, use GUIDs and count once per group", function() + local f = fresh({}, true) + local X, c = f.X, f.client + local first = "Player-1-001" + for i = 1, 160 do X.TrackOffender(string.format("Player-1-%03d", i), "SameName") end + X.TrackOffender(first, "UpdatedName") + assert(X.Settings.Count(X.offNow) == 128 and X.offNow[first] == "UpdatedName") + c.IsInGroup, c.GetNumGroupMembers = function() return false end, function() return 0 end + f.units.party1, f.units.party2 = nil, nil + f.event("GROUP_LEFT") + local off = f.db.offenders + assert(X.Settings.Count(off) == 50 and off[first].name == "UpdatedName" and off[first].count == 1) + assert(off["Player-1-002"].name == "SameName" and off["Player-1-002"].count == 1) + f.event("GROUP_ROSTER_UPDATE") + assert(not next(X.offNow) and f.db.offenders[first].count == 1) + end) +end diff --git a/tools/check.ps1 b/tools/check.ps1 index 38c9fdc..c5983f3 100644 --- a/tools/check.ps1 +++ b/tools/check.ps1 @@ -1,3 +1,4 @@ +#Requires -Version 7.0 # Runs every BuffRadar check in one go. See tools\README.md. # # .\tools\check.ps1 run all checks (nonzero exit if any fails) @@ -66,17 +67,11 @@ try { } finally { Pop-Location } -# 2. Compile with real Lua 5.1 (the language WoW runs) +# 2. Compile and check all shared modules, like the POSIX gate. Section 'Lua 5.1 compile' -# The Forever TOC is copied over the shared addon directory during packaging. -$luaFiles = @(foreach ($line in Get-Content -LiteralPath $toc) { - $entry = $line.Trim() - if (-not $entry.StartsWith('#') -and $entry -like '*.lua') { - Join-Path $addon $entry - } -}) -if (-not $luaFiles.Count) { throw "No Lua entries in the Forever TOC: $toc" } -& $py -I (Join-Path $here 'luacheck51.py') @luaFiles +$luaFiles = @((Get-ChildItem -LiteralPath $addon -Filter '*.lua' -File).FullName) +$localeFiles = @((Get-ChildItem -LiteralPath $locales -Filter '*.lua' -File).FullName) +& $py -I (Join-Path $here 'luacheck51.py') @luaFiles @localeFiles $compileExit = $LASTEXITCODE if ($compileExit -ne 0) { Write-Host "FAILED: Lua 5.1 compile (exit $compileExit)" @@ -89,7 +84,7 @@ Section 'Translations' if ($LASTEXITCODE -ne 0) { $failed += 'translations' } Section 'Lua pattern arguments' -& $py -I (Join-Path $here 'patterncheck.py') @($luaFiles | ForEach-Object { "$_" }) +& $py -I (Join-Path $here 'patterncheck.py') @luaFiles @localeFiles if ($LASTEXITCODE -ne 0) { $failed += 'patterns' } # 3. Advisory Lua 5.1 limits. Only the compiler decides whether Lua can load. @@ -114,9 +109,15 @@ Section 'Caster Coordination (two fake game clients)' & $py -I (Join-Path $here 'coordination51.py') (Join-Path $here 'wowstub.lua') $lua if ($LASTEXITCODE -ne 0) { $failed += 'two-client coordination' } +Section 'Packaging regression tests' +& $py -I (Join-Path $here 'test_package.py') +if ($LASTEXITCODE -ne 0) { $failed += 'packaging regression tests' } + # 5. Validate the current Forever ZIP if it has been built. $dist = Join-Path $project 'dist' -$version = (Select-String -LiteralPath $toc -Pattern '^## Version:\s*(\d+\.\d+\.\d+)\s*$').Matches.Groups[1].Value +$versions = @(Select-String -LiteralPath $toc -Pattern '^## Version:\s*(\d+\.\d+\.\d+)\s*$') +if ($versions.Count -ne 1) { throw "Expected one valid Version in $toc" } +$version = $versions[0].Matches[0].Groups[1].Value $zip = Join-Path $dist "BuffRadar-$version-Forever.zip" if (Test-Path -LiteralPath $zip) { Section 'Forever package' diff --git a/tools/checkpackage.py b/tools/checkpackage.py index 7b8ce78..5974e96 100644 --- a/tools/checkpackage.py +++ b/tools/checkpackage.py @@ -1,60 +1,71 @@ """Validate the Forever ZIP and load its Lua files in TOC order under Lua 5.1.""" import re +import runpy +import stat import sys -from pathlib import Path, PurePosixPath +from pathlib import Path from xml.etree import ElementTree -from zipfile import BadZipFile, ZipFile +from zipfile import BadZipFile, ZIP_STORED, ZipFile from lupa import lua51 +manifest = runpy.run_path(str(Path(__file__).with_name("package.py"))) +BINDINGS = { + "CLICK BuffRadarNextButton:LeftButton": "", + "CLICK BuffRadarGroupButton:LeftButton": "", + "BUFFRADAR_TOGGLE": "BuffRadar_ToggleWindow()", + "BUFFRADAR_MUTE": "BuffRadar_ToggleSound()", +} -def load_archive(archive): + +def load_archive(archive, require_deterministic=False): with ZipFile(archive) as package: broken = package.testzip() if broken: raise ValueError(f"CRC check failed for {broken}") - members = {} + members, spellings = {}, {} used_names = set() + if require_deterministic and (package.comment or package.namelist() != sorted(package.namelist())): + raise ValueError("Expected deterministic archive metadata and member order") for entry in package.infolist(): - name = entry.filename.rstrip("/") - path = PurePosixPath(name) + name = entry.filename[:-1] if entry.is_dir() else entry.filename + path = manifest["register_path"](name, spellings) if ( - path.as_posix() != name + entry.orig_filename != entry.filename or path.parts[:1] != ("BuffRadar",) - or ".." in path.parts - or "\\" in name - or ":" in name or (len(path.parts) == 1 and not entry.is_dir()) - or name.casefold() in used_names + or stat.S_ISLNK(entry.external_attr >> 16) + or name in used_names ): raise ValueError(f"Invalid or duplicate package path: {entry.filename}") - used_names.add(name.casefold()) + if require_deterministic and (entry.is_dir() or entry.compress_type != ZIP_STORED + or entry.date_time != manifest["FIXED_DATE"] or entry.create_system != 3 + or entry.external_attr != manifest["FIXED_MODE"] or entry.extra or entry.comment): + raise ValueError(f"Unexpected package metadata: {entry.filename}") + used_names.add(name) if not entry.is_dir(): members[path.relative_to("BuffRadar").as_posix()] = package.read(entry) return members def check_package(archive, project=None): - members = load_archive(archive) + members = load_archive(archive, require_deterministic=project is not None) if project is not None: - edition = {"BuffRadar.toc", "README.md", "CHANGELOG.md", "DESCRIPTION.md", "FEATURES.md"} - shared = project / "BuffRadar" - expected = {path.relative_to(shared).as_posix(): path - for path in shared.rglob("*") if path.is_file()} - expected.update({name: project / "editions" / "forever" / name for name in edition}) + _, expected = manifest["source_manifest"](project) if set(members) != set(expected): raise ValueError(f"Package inventory differs from source: {sorted(set(members) ^ set(expected))}") for name, path in expected.items(): if members[name] != path.read_bytes(): raise ValueError(f"Stale package entry {name}. Rebuild the ZIP.") toc = members["BuffRadar.toc"].decode("utf-8-sig").replace("\r\n", "\n") - interface = re.findall(r"^## Interface:[ \t]*(.+)$", toc, re.MULTILINE) - if len(interface) != 1 or interface[0].strip() != "16001": - raise ValueError("The Forever TOC must declare Interface 16001") - version = re.findall(r"^## Version:[ \t]*(\d+\.\d+\.\d+)[ \t]*$", toc, re.MULTILINE) - if len(version) != 1 or archive.name != f"BuffRadar-{version[0]}-Forever.zip": + manifest["metadata"](toc, "Interface", manifest["INTERFACE"]) + version = manifest["metadata"](toc, "Version", r"[0-9]+\.[0-9]+\.[0-9]+") + if archive.name != f"BuffRadar-{version}-Forever.zip": raise ValueError("The ZIP filename must match the Forever TOC version") + sums = archive.with_name("SHA256SUMS.txt") + if (project is not None or sums.exists()) and sums.read_bytes() != manifest["checksum"](archive).encode("ascii"): + raise ValueError("SHA256SUMS.txt does not match the archive bytes") paths = [line.strip().replace("\\", "/") for line in toc.splitlines() if line.strip() and not line.lstrip().startswith("#")] if len(paths) != len(set(paths)): @@ -62,16 +73,22 @@ def check_package(archive, project=None): lua_files = {name for name in members if name.endswith(".lua")} if set(paths) != lua_files or not lua_files: raise ValueError(f"TOC and packaged Lua files differ: {sorted(set(paths) ^ lua_files)}") + expected_names = lua_files | manifest["EDITION"] | manifest["SHARED_ASSETS"] + if set(members) != expected_names: + raise ValueError(f"Unexpected package inventory: {sorted(set(members) ^ expected_names)}") for icon in re.findall(r"^## IconTexture:[ \t]*Interface\\AddOns\\BuffRadar\\(.+)$", toc, re.MULTILINE): if icon.strip().replace("\\", "/") not in members: raise ValueError(f"Missing TOC icon asset: {icon}") lua = lua51.LuaRuntime(unpack_returned_tuples=True) lua.execute(Path(__file__).with_name("wowstub.lua").read_text(encoding="utf-8")) - start = lua.eval(r"""function() + start = lua.eval(r"""function(version) local chat = {} - local env = WOWSTUB(chat, true, false, true, true) + local env = WOWSTUB(chat, true, false, true, false) env._G, env.strlower, env.format = env, string.lower, string.format + env.C_AddOns = { GetAddOnMetadata = function(addon, key) + if addon == "BuffRadar" and key == "Version" then return version end + end } setmetatable(env, {__index = _G}) local ns = {} return env, function(source, name) @@ -88,24 +105,32 @@ def check_package(archive, project=None): end end end - for _, line in ipairs(chat) do - assert(not line:find("error", 1, true), line) + assert(ns.X.classic and env.BuffRadarFrame and env.SlashCmdList.BUFFRADAR, "packaged addon did not start") + local nextLine, versionFound = #chat + 1, false + env.SlashCmdList.BUFFRADAR("selftest") + for i, line in ipairs(chat) do + assert(not line:find("|cffff4040error:|r", 1, true), line) + if i >= nextLine and line:find("version " .. version .. " · Forever edition · interface 16001", 1, true) then + versionFound = true + end end - assert(env.BuffRadarFrame and env.SlashCmdList.BUFFRADAR, "packaged addon did not start") + assert(versionFound, "Self-test did not report the installed version and edition") end end""") - env, load, login = start() + env, load, login = start(version) for path in paths: load(members[path].decode("utf-8-sig"), path) login() bindings = ElementTree.fromstring(members["Bindings.xml"]) - if bindings.tag != "Bindings" or not len(bindings): + if bindings.tag != "Bindings" or len(bindings) != len(BINDINGS): raise ValueError("Missing binding definitions") seen = set() for binding in bindings: name = binding.get("name") - if binding.tag != "Binding" or not name or name in seen or not binding.get("category") or len(binding): + code = (binding.text or "").strip() + if (binding.tag != "Binding" or name not in BINDINGS or name in seen + or binding.get("category") != "BUFFRADAR" or len(binding) or code != BINDINGS[name]): raise ValueError(f"Invalid binding definition: {name}") seen.add(name) click = re.fullmatch(r"CLICK (\w+):\w+", name) @@ -113,7 +138,6 @@ def check_package(archive, project=None): if env[click.group(1)] is None: raise ValueError(f"Missing binding target: {name}") else: - code = (binding.text or "").strip() handler = re.fullmatch(r"(\w+)\(\)", code) if not handler or lua.eval("type")(env[handler.group(1)]) != "function": raise ValueError(f"Missing binding handler: {name}") diff --git a/tools/gate.sh b/tools/gate.sh index e09f9cd..2d41842 100644 --- a/tools/gate.sh +++ b/tools/gate.sh @@ -9,9 +9,9 @@ cd "$(dirname "$0")/.." # so probe each candidate by running it rather than by finding it. PY= for candidate in python3 python; do - if "$candidate" -c "import sys" >/dev/null 2>&1; then PY=$candidate; break; fi + if "$candidate" -c 'import sys; sys.exit(sys.version_info < (3, 10))' >/dev/null 2>&1; then PY=$candidate; break; fi done -[ -n "$PY" ] || { echo "No working python3 or python found."; exit 1; } +[ -n "$PY" ] || { echo "Python 3.10 or newer is required."; exit 1; } # Check all shared modules, including files added to either edition. echo "== luacheck51"; "$PY" -I tools/luacheck51.py BuffRadar/*.lua BuffRadar/Locales/*.lua echo "== lualimits"; for f in BuffRadar/*.lua; do "$PY" -I tools/lualimits.py "$f"; done @@ -19,4 +19,5 @@ echo "== localecheck"; "$PY" -I tools/localecheck.py BuffRadar/BuffRadar.lua Bu echo "== patterncheck"; "$PY" -I tools/patterncheck.py BuffRadar/*.lua BuffRadar/Locales/*.lua echo "== smoke"; "$PY" -I tools/smoke51.py tools/wowstub.lua BuffRadar/BuffRadar.lua echo "== coordination"; "$PY" -I tools/coordination51.py tools/wowstub.lua BuffRadar/BuffRadar.lua +echo "== packaging regression tests"; "$PY" -I tools/test_package.py echo "Gate passed. Real luacheck 1.2.0: run tools/check.ps1 on Windows." diff --git a/tools/localecheck.py b/tools/localecheck.py index 4d282e2..885bff3 100644 --- a/tools/localecheck.py +++ b/tools/localecheck.py @@ -25,7 +25,8 @@ def codes(s): - return sorted(re.findall(r"%[ds]|\|c[0-9a-fA-F]{8}|\|r", s)) + placeholders = re.findall(r"%%|%[-+#0]*[0-9]*(?:\.[0-9]+)?[cdiouxXeEfgGqs]", s) + return [item[-1] for item in placeholders], sorted(re.findall(r"\|c[0-9a-fA-F]{8}|\|r", s)) required = {"deDE", "esES", "frFR", "ruRU", "zhCN"} diff --git a/tools/package.py b/tools/package.py new file mode 100644 index 0000000..0e4549f --- /dev/null +++ b/tools/package.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""Build the supported Forever ZIP from a shared, confined source manifest.""" + +import argparse +import hashlib +import os +import re +import stat +import tempfile +from pathlib import Path, PurePosixPath +from zipfile import ZIP_STORED, ZipFile, ZipInfo + +EDITION = {"BuffRadar.toc", "README.md", "CHANGELOG.md", "DESCRIPTION.md", "FEATURES.md"} +SHARED_ASSETS = {"Bindings.xml", "LICENSE", "Media/icon.png", "Media/logo.png", "Media/droplet.ogg"} +INTERFACE = "16001" +FIXED_DATE = (1980, 1, 1, 0, 0, 0) +FIXED_MODE = 0o100644 << 16 +WINDOWS_DEVICE = re.compile(r"^(?:CON|PRN|AUX|NUL|COM[1-9¹²³]|LPT[1-9¹²³])(?:\.|$)", re.IGNORECASE) + + +def metadata(toc, field, pattern): + values = re.findall(rf"^## {field}:[ \t]*(.*)$", toc, re.MULTILINE) + if len(values) != 1 or re.fullmatch(pattern, values[0].strip()) is None: + raise ValueError(f"Expected exactly one valid {field} in the Forever TOC") + return values[0].strip() + + +def canonical(name): + path = PurePosixPath(name) + if not path.parts or path.as_posix() != name or path.is_absolute() or ".." in path.parts: + raise ValueError(f"Invalid package path: {name!r}") + for part in path.parts: + if part.endswith((" ", ".")) or WINDOWS_DEVICE.match(part) or re.search(r'[\\<>:"|?*\x00-\x1f]', part): + raise ValueError(f"Non-portable package path: {name!r}") + return path + + +def register_path(name, seen): + """Reject spelling aliases for both members and their directory components.""" + path = canonical(name) + for part in (path, *path.parents): + spelling = part.as_posix() + previous = seen.setdefault(spelling.casefold(), spelling) + if previous != spelling: + raise ValueError(f"Case-folded duplicate: {previous}, {spelling}") + return path + + +def checked(path, directory=False): + info = path.lstat() + linked = stat.S_ISLNK(info.st_mode) or getattr(info, "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT + valid = stat.S_ISDIR(info.st_mode) if directory else stat.S_ISREG(info.st_mode) + if linked or not valid: + raise ValueError(f"Not a regular, non-linked {'directory' if directory else 'file'}: {path}") + return path + + +def source_files(base): + """Walk only real directories; never follow symlinks, junctions or special files.""" + for path in base.iterdir(): + if path.is_dir(): + yield from source_files(checked(path, directory=True)) + else: + yield checked(path) + + +def source_manifest(project): + shared = checked(project / "BuffRadar", directory=True) + edition = checked(checked(project / "editions", directory=True) / "forever", directory=True) + toc_path = checked(edition / "BuffRadar.toc") + toc = toc_path.read_text(encoding="utf-8-sig") + metadata(toc, "Interface", INTERFACE) + version = metadata(toc, "Version", r"[0-9]+\.[0-9]+\.[0-9]+") + manifest = {} + for path in source_files(shared): + name = path.relative_to(shared).as_posix() + if name not in EDITION: + manifest[name] = path + manifest.update({name: checked(edition / name) for name in EDITION}) + seen = {} + for name in sorted(manifest): + register_path(name, seen) + load_order = [line.strip().replace("\\", "/") for line in toc.splitlines() + if line.strip() and not line.lstrip().startswith("#")] + lua = {name for name in manifest if name.endswith(".lua")} + if not lua or len(load_order) != len(lua) or set(load_order) != lua: + raise ValueError("Packaged Lua must match the Forever TOC exactly") + expected = lua | SHARED_ASSETS | EDITION + if set(manifest) != expected: + raise ValueError(f"Package inventory differs from the declared assets: {sorted(set(manifest) ^ expected)}") + return version, dict(sorted(manifest.items())) + + +def checksum(archive, filename=None): + with archive.open("rb") as source: + digest = hashlib.sha256() + for chunk in iter(lambda: source.read(64 * 1024), b""): + digest.update(chunk) + return f"{digest.hexdigest()} {filename or archive.name}\n" + + +def pack(project, expected_tag=None): + version, files = source_manifest(project) + if expected_tag is not None and expected_tag != f"v{version}": + raise ValueError(f"Tag {expected_tag!r} does not match the Forever TOC version v{version}") + dist = project / "dist" + dist.mkdir(exist_ok=True) + checked(dist, directory=True) + filename = f"BuffRadar-{version}-Forever.zip" + with tempfile.TemporaryDirectory(prefix=".package-", dir=dist) as directory: + staging = Path(directory) + archive = staging / filename + with ZipFile(archive, "w", compression=ZIP_STORED) as package: + # Stored ZIPs avoid different zlib versions changing compressed bytes. + # Explicit metadata (date, permission bits, OS) ignores source mtimes. + for name, source in files.items(): + entry = ZipInfo(f"BuffRadar/{name}", FIXED_DATE) + entry.create_system, entry.external_attr = 3, FIXED_MODE + package.writestr(entry, source.read_bytes()) + sums = checksum(archive) + (staging / "SHA256SUMS.txt").write_bytes(sums.encode("ascii")) + os.replace(archive, dist / filename) + os.replace(staging / "SHA256SUMS.txt", dist / "SHA256SUMS.txt") + print(sums, end="") + + +if __name__ == "__main__": + cli = argparse.ArgumentParser(description=__doc__) + cli.add_argument("--tag", help="require the exact version tag (vX.Y.Z) before writing files") + options = cli.parse_args() + try: + pack(Path(__file__).resolve().parent.parent, options.tag) + except (OSError, ValueError) as exc: + cli.exit(1, f"Forever package failed: {exc}\n") diff --git a/tools/package.sh b/tools/package.sh index 7b9b11a..1edec40 100644 --- a/tools/package.sh +++ b/tools/package.sh @@ -1,28 +1,11 @@ #!/bin/sh -# Builds dist/BuffRadar--Forever.zip and dist/SHA256SUMS.txt (Linux/CI twin of build.ps1). -# Usage: sh tools/package.sh -set -e +# POSIX wrapper for the shared deterministic Forever packager. +set -eu cd "$(dirname "$0")/.." -VER="$(sed -n 's/^## Version:[[:space:]]*//p' editions/forever/BuffRadar.toc | head -1 | tr -d '\r')" -[ -n "$VER" ] || { echo "No '## Version:' in editions/forever/BuffRadar.toc" >&2; exit 1; } -STAGE="$(mktemp -d)" -trap 'rm -rf "$STAGE"' EXIT -mkdir -p "$STAGE/BuffRadar" dist -for f in BuffRadar/*; do - case "$(basename "$f")" in BuffRadar.toc|README.md|CHANGELOG.md|DESCRIPTION.md|FEATURES.md) ;; *) cp -r "$f" "$STAGE/BuffRadar/" ;; esac +for py in python3 python; do + if "$py" -c 'import sys; sys.exit(sys.version_info < (3, 10))' >/dev/null 2>&1; then + exec "$py" -I tools/package.py "$@" + fi done -for f in BuffRadar.toc README.md CHANGELOG.md DESCRIPTION.md FEATURES.md; do cp "editions/forever/$f" "$STAGE/BuffRadar/"; done -ZIP="dist/BuffRadar-$VER-Forever.zip" -rm -f "$ZIP" -( cd "$STAGE" && python3 -I - "$OLDPWD/$ZIP" <<'PY' -import os, sys, zipfile -out = sys.argv[1] -with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z: - for root, dirs, files in os.walk("BuffRadar"): - dirs.sort() - z.write(root) - for f in sorted(files): - z.write(os.path.join(root, f)) -PY -) -( cd dist && sha256sum "BuffRadar-$VER-Forever.zip" > SHA256SUMS.txt && cat SHA256SUMS.txt ) +echo 'Python 3.10 or newer is required.' >&2 +exit 1 diff --git a/tools/smoke51.py b/tools/smoke51.py index b3e80c2..d5b6304 100644 --- a/tools/smoke51.py +++ b/tools/smoke51.py @@ -12,8 +12,9 @@ stub_path, addon_path = sys.argv[1], sys.argv[2] lua = lua51.LuaRuntime(unpack_returned_tuples=True) lua.execute(open(stub_path, encoding="utf-8").read()) +audit_tests = lua.execute(Path(__file__).with_name("audit51.lua").read_text(encoding="utf-8")) -harness = lua.eval(r"""function(sources, withTimer, noTemplates, forever, german) +harness = lua.eval(r"""function(sources, withTimer, noTemplates, forever, german, auditTests) local chat = {} local env = WOWSTUB(chat, withTimer, noTemplates, forever, german) local unitIsUnit = env.UnitIsUnit @@ -155,7 +156,9 @@ assert(not X.GetDB() and saved.obsolete and saved.scale == 9, "settings changed before BuffRadar loaded") onEvent(startup, "PLAYER_LOGIN") assert(not startup.events.PLAYER_LOGIN and client.BuffRadarFrame, "login fallback did not build the window once") - assert(X.GetDB() == saved and saved.scale == 2 and not saved.obsolete, "fallback did not sanitize and publish the save") + assert(X.GetDB() ~= saved and saved.obsolete and saved.scale == 9, "fallback modified the input save") + saved = X.GetDB() + assert(saved == client.BuffRadarDB and saved.scale == 2 and not saved.obsolete, "fallback did not publish sanitized state") assert(saved.dbVersion == 9 and not saved.wizardSeen and saved.showOutOfRange and saved.castMethod == "rank", "login fallback applied normal-load migrations") assert(X.Ignore.Has("BeforeLogin", "BeforeLogin"), "fallback did not rebuild the ignore index") @@ -165,8 +168,9 @@ local replacement = { dbVersion = 9, scale = 1.5, showMinimap = true } client.BuffRadarDB = replacement onEvent(startup, "ADDON_LOADED", "BuffRadar") - assert(X.GetDB() == replacement and replacement.dbVersion == 22 and replacement.wizardSeen, - "normal load did not migrate and publish the replacement") + assert(replacement.dbVersion == 9 and not replacement.wizardSeen, "migration edited the input table") + assert(X.GetDB() == client.BuffRadarDB and X.GetDB().dbVersion == 23 and X.GetDB().wizardSeen, + "normal load did not migrate and publish detached settings") assert(not X.Ignore.Has("BeforeLogin", "BeforeLogin"), "ignore index retained a replaced save") X.ApplyGeometry() X.RefreshMinimapButton() @@ -186,7 +190,7 @@ end step("ADDON_LOADED", function() fire("ADDON_LOADED", "BuffRadar") - assert(NS.X.GetDB() == env.BuffRadarDB and env.BuffRadarDB.dbVersion == 22, "live settings were not published") + assert(NS.X.GetDB() == env.BuffRadarDB and env.BuffRadarDB.dbVersion == 23, "live settings were not published") local pullFrame = NS.X.pullFrame if not NS.X.ApiCheck then return end -- not in the Retail TOC assert(pullFrame and pullFrame.events.ADDON_LOADED, "pull listener missing at startup") @@ -232,9 +236,14 @@ p = button.points[#button.points] local followsSize = math.abs(p[4] - 155) < 0.01 env.GetCursorPosition = function() return 655, 505 end + assert(not button:GetScript("OnUpdate"), "idle minimap has a frame update") button:GetScript("OnDragStart")(button) button:GetScript("OnUpdate")(button) button:GetScript("OnDragStop")(button) + assert(not button:GetScript("OnUpdate"), "minimap update survived drag release") + button:GetScript("OnDragStart")(button) + button:Hide() + assert(not button:GetScript("OnUpdate"), "minimap update survived hide") local angle = db.minimapAngle map.GetWidth, map.GetHeight, db.minimapAngle, env.GetCursorPosition = oldWidth, oldHeight, oldAngle, oldCursor NS.X.RefreshMinimapButton() @@ -561,6 +570,8 @@ runQueued() local X, db = NS.X, env.BuffRadarDB local oldTally, oldPull, oldFlash, oldTrusted = X.tally, X.pull, X.Flash, X.SenderTrusted + local oldSender, oldRaid = X.SenderUnit, env.IsInRaid + X.SenderUnit = function() return "player", "Leader-TestRealm" end local oldSetting = db.pullFlash local flashes = 0 X.Flash = function() flashes = flashes + 1 end @@ -569,6 +580,7 @@ local pf = X.pullFrame pf.scripts.OnEvent(pf, "START_TIMER", 2, 8, 8) local timerA = X.pull + env.IsInRaid = function() return true end -- change scope before the new provider starts pf.scripts.OnEvent(pf, "CHAT_MSG_ADDON", "D5", "PT\t12", "RAID", "Leader-TestRealm") local timerB = X.pull pf.scripts.OnEvent(pf, "CANCEL_PLAYER_COUNTDOWN", "Player-Leader") @@ -587,6 +599,7 @@ correct = correct and X.pull == nil and flashes == 4 end X.tally, X.pull, X.Flash, X.SenderTrusted, db.pullFlash = oldTally, oldPull, oldFlash, oldTrusted, oldSetting + X.SenderUnit, env.IsInRaid = oldSender, oldRaid assert(scheduled and correct, "an outdated pull timer flashed or cleared the replacement") end) step("modifier clicks: group spell mapping + shift-click bookkeeping (1.14.0)", function() @@ -670,9 +683,12 @@ fire("UNIT_AURA", "player", { addedAuras = { { name = watchedName, auraInstanceID = 9003 } } }) assert(#env.__timers == 1, "watched payload did not queue a refresh") runQueued() - fire("UNIT_AURA", "player", { addedAuras = { { name = "Well Fed", auraInstanceID = 9001 } } }) + local cons = env.BuffRadarDB.consumables + env.BuffRadarDB.consumables = true + fire("UNIT_AURA", "player", { addedAuras = { { name = "Well Fed", spellId = 19705, auraInstanceID = 9001 } } }) assert(#env.__timers == 1, "consumable aura change (Well Fed) did not queue a refresh") runQueued() + env.BuffRadarDB.consumables = cons fire("UNIT_AURA", "player", { removedAuraInstanceIDs = { 9002 } }) assert(#env.__timers == 1, "unknown removed ID must refresh conservatively") runQueued() @@ -901,7 +917,7 @@ env.IsSpellInRange = function() return 1 end refresh() local row = assert(shownRows().nameplate1, "tank 1 not listed in range").row - assert(not row.far.shown, "'out of range' marker still shown in range") + assert(row:GetAttribute("type"), "a returned in-range target did not rearm the row") env.IsSpellInRange = nil cleanup() end) @@ -925,6 +941,8 @@ if u == "player" then return env.__forever and "PRIEST" or "SHAMAN", env.__forever and "PRIEST" or "SHAMAN" end end env.IsInGroup = function() return true end + local originalSize = env.GetNumGroupMembers + env.GetNumGroupMembers = function() return env.IsInGroup() and 3 or 0 end O.Aura = nil -- clear any aura hook a previous step left behind env.SlashCmdList.BUFFRADAR("unsignore Aaron") env.SlashCmdList.BUFFRADAR("unsignore Zed") @@ -936,6 +954,7 @@ return function() for k in pairs(O) do O[k] = nil end env.IsInGroup = function() return false end + env.GetNumGroupMembers = originalSize env.IsSpellInRange = nil end end @@ -1742,7 +1761,7 @@ assert(d.castMethod == "target", "pre-v3 castMethod not reset: " .. tostring(d.castMethod)) assert(d.clickReg == "both", "pre-v3 clickReg not reset: " .. tostring(d.clickReg)) assert(d.includeSelf == true, "pre-v4 includeSelf not forced on") - assert(d.dbVersion == 22, "dbVersion not migrated to 21: " .. tostring(d.dbVersion)) + assert(d.dbVersion == 23, "dbVersion not migrated to 23: " .. tostring(d.dbVersion)) assert(d.assignmentEnabled == false and next(d.buffAssignments) == nil, "migration activated assignments") assert(next(d.blessingPreferences) == nil, "existing character got a blessing override") assert(d.wizardSeen == false, "ancient save should still count as a new user for the wizard") @@ -1766,7 +1785,7 @@ env.BuffRadarDB = "junk" fire("ADDON_LOADED", "BuffRadar") d = env.BuffRadarDB - assert(type(d) == "table" and d.dbVersion == 22 and d.scale == 1, + assert(type(d) == "table" and d.dbVersion == 23 and d.scale == 1, "corrupt save not replaced with defaults") d.scale = 1 -- a 1.7.0-era save (dbVersion 9): an existing user — the wizard @@ -1774,22 +1793,22 @@ env.BuffRadarDB = { dbVersion = 9 } fire("ADDON_LOADED", "BuffRadar") d = env.BuffRadarDB - assert(d.dbVersion == 22 and d.wizardSeen == true, + assert(d.dbVersion == 23 and d.wizardSeen == true, "existing user not marked wizard-seen: " .. tostring(d.wizardSeen)) d.dbVersion, d.assignmentEnabled, d.thornsAnyClassOutdoors = 18, true, nil fire("ADDON_LOADED", "BuffRadar") d = env.BuffRadarDB - assert(d.dbVersion == 22 and d.thornsAnyClassOutdoors == false and d.assignmentEnabled, + assert(d.dbVersion == 23 and d.thornsAnyClassOutdoors == false and d.assignmentEnabled, "v18 settings did not gain an opt-in Thorns default while preserving assignments") d.dbVersion, d.autoThemePriority, d.theme = 19, nil, "ui.auto" fire("ADDON_LOADED", "BuffRadar") d = env.BuffRadarDB - assert(d.dbVersion == 22 and d.theme == "ui.auto" and d.autoThemePriority == "", + assert(d.dbVersion == 23 and d.theme == "ui.auto" and d.autoThemePriority == "", "v19 migration changed Auto opt-in or failed to default the priority order") d.dbVersion, d.blessingComplement, d.plateRestore = 20, nil, nil fire("ADDON_LOADED", "BuffRadar") d = env.BuffRadarDB - assert(d.dbVersion == 22 and d.blessingComplement == false and not next(d.plateRestore) and d.assignmentEnabled, + assert(d.dbVersion == 23 and d.blessingComplement == false and not next(d.plateRestore) and d.assignmentEnabled, "v20 migration turned on a new feature or lost an existing preference") d.blessingComplement = true d.plateRestore = { nameplateShowFriends = false, nameplateShowAll = true, @@ -2068,6 +2087,8 @@ env.SlashCmdList.BUFFRADAR("import") f.editBox.text = text f.accept.scripts.OnClick(f.accept, "LeftButton") + assert(d.scale == 1 and d.sortMode == "name" and f.apply:IsShown(), "preview applied settings") + f.apply:Click() assert(d.scale == 1.5 and d.sortMode == "role", "import did not restore scalars") assert(d.enabled.CUSTOM_TEST == false and d.rebuffPer.CUSTOM_TEST == 77, "import did not restore per-buff tables") @@ -2103,9 +2124,10 @@ "older complete clipboard did not clear intentionally empty tables") assert(X.Import(withData) and d.enabled.TEST and d.ignored.Zed, "framed clipboard round-trip failed") local current, currentRebuff, currentIgnore = d.enabled, d.rebuffPer, d.ignored - current[string.rep("A", 4100)] = true + -- Large but within schema limits: exercise the size cap independently of key validation. + for i = 1, 180 do current["TEST_" .. i .. "_" .. string.rep("A", 24)] = true end local large = assert(X.Export(), "valid clipboard larger than named profile cap was refused") - assert(X.Import(large), "valid large clipboard did not round-trip") + assert(#large > 4000 and X.Import(large), "valid large clipboard did not round-trip") current[string.rep("A", 16500)] = true d.enabled, d.rebuffPer, d.ignored = current, currentRebuff, currentIgnore assert(not X.Export(), "oversized settings produced an unreadable export") @@ -2171,7 +2193,8 @@ local key for k in pairs(d.pointByChar) do key = k end assert(key and key:find("TestRealm", 1, true), "no per-character position stored: " .. tostring(key)) - assert(d.pointByChar[key] == d.point, "stored position is not the current point") + assert(d.pointByChar[key] and table.concat(d.pointByChar[key], ",") == table.concat(d.point, ","), + "stored position differs from the current point") env.SlashCmdList.BUFFRADAR("charpoint") assert(d.charPoint == false, "charpoint not disabled") end) @@ -2200,6 +2223,8 @@ local cleanup = partyOfTwo("V") local X, db, O = NS.X, env.BuffRadarDB, env.__over local sync, canAccess, assistant = db.sync, env.canaccessvalue, env.UnitIsGroupAssistant + local leader = env.UnitIsGroupLeader + env.UnitIsGroupLeader = function(u) return u == "party1" end local fullName, exists = O.UnitFullName, O.UnitExists db.sync = true O.UnitFullName = function(u) @@ -2233,18 +2258,20 @@ O.UnitExists = function(u) return u ~= "party2" and exists(u) end fire("GROUP_ROSTER_UPDATE") assert(not X.peers["tera-realmtwo"] and not X.cover["Tera-RealmTwo"], "departed peer was retained") - db.sync, env.UnitIsGroupAssistant = sync, assistant + db.sync, env.UnitIsGroupAssistant, env.UnitIsGroupLeader = sync, assistant, leader cleanup() fire("GROUP_ROSTER_UPDATE") end) step("group sync accepts current raid traffic and rejects unreadable authority", function() local X, db, O = NS.X, env.BuffRadarDB, env.__over local sync, raid, leader, assistant = db.sync, env.IsInRaid, env.UnitIsGroupLeader, env.UnitIsGroupAssistant - local canAccess, roster = env.canaccessvalue, env.GetRaidRosterInfo - local exists, fullName, isUnit = O.UnitExists, O.UnitFullName, O.UnitIsUnit + local canAccess, roster, size = env.canaccessvalue, env.GetRaidRosterInfo, env.GetNumGroupMembers + local exists, fullName, isUnit, guid = O.UnitExists, O.UnitFullName, O.UnitIsUnit, O.UnitGUID + O.UnitGUID = function(u) return u == "raid1" and "Player-Me" or u == "raid2" and "Player-Lian" end local protected = {} db.sync = true env.IsInRaid = function() return true end + env.GetNumGroupMembers = function() return 2 end O.UnitExists = function(u) return u == "player" or u == "raid1" or u == "raid2" end O.UnitFullName = function(u) if u == "player" or u == "raid1" then return "Me", "TestRealm" end @@ -2257,14 +2284,15 @@ local key = env.__forever and "FORTITUDE" or "SKYFURY" fire("CHAT_MSG_ADDON", "BuffRadar", "ASSIGN;" .. key .. ";Lian", "RAID", "Lian-OtherRealm") assert(not X.assign[key] and not X.peers["lian-otherrealm"], "unreadable rank changed state") - env.GetRaidRosterInfo = function(i) if i == 2 then return "Lian-OtherRealm", 1 end end + env.GetRaidRosterInfo = function(i) return i == 2 and "Lian-OtherRealm" or "Me-TestRealm", i == 1 and 2 or 1 end fire("CHAT_MSG_ADDON", "BuffRadar", "ASSIGN;" .. key .. ";Lian", "RAID", "Lian-OtherRealm") assert(X.assign[key] == "Lian" and X.peers["lian-otherrealm"], "readable raid assistant was ignored") - X.assign[key], X.peers["lian-otherrealm"] = nil, nil + X.SetLocalPlan("ASSIGN", key, nil) + X.peers["lian-otherrealm"] = nil db.sync, env.IsInRaid = sync, raid env.UnitIsGroupLeader, env.UnitIsGroupAssistant = leader, assistant - env.canaccessvalue, env.GetRaidRosterInfo = canAccess, roster - O.UnitExists, O.UnitFullName, O.UnitIsUnit = exists, fullName, isUnit + env.canaccessvalue, env.GetRaidRosterInfo, env.GetNumGroupMembers = canAccess, roster, size + O.UnitExists, O.UnitFullName, O.UnitIsUnit, O.UnitGUID = exists, fullName, isUnit, guid end) step("caster coordination checks roster authority, drafts, acceptance and acknowledgement", function() if not env.__forever then return end @@ -2853,21 +2881,22 @@ assert(env.BuffRadarDB.consumables == true, "consumables setting not stored") env.__over.AuraList = function(u) if u == "party2" then - return { { name = "Flask of the Titans", expirationTime = env.GetTime() + 600 }, - { name = "Well Fed", expirationTime = env.GetTime() + 600 } } + return { { name = "Flask of the Titans", spellId = 17626, expirationTime = env.GetTime() + 600 }, + { name = "Well Fed", spellId = 19705, expirationTime = env.GetTime() + 600 } } end return {} end refresh() local cover + local labels = NS.X.L for _, fs in ipairs(env.__fontstrings) do - if type(fs.text) == "string" and fs.text:find("Flask ", 1, true) then cover = fs.text end + if type(fs.text) == "string" and fs.text:find(labels["Flask"] .. " ", 1, true) then cover = fs.text end end assert(cover, "no consumables on the coverage line") - assert(cover:find("Flask 1/3", 1, true), "flask count wrong: " .. cover) - assert(cover:find("Food 1/3", 1, true), "food count wrong: " .. cover) + assert(cover:find(labels["Flask"] .. " 1/3", 1, true), "flask count wrong: " .. cover) + assert(cover:find(labels["Food"] .. " 1/3", 1, true), "food count wrong: " .. cover) if not env.__forever then - assert(cover:find("Rune 0/3", 1, true), "rune count wrong: " .. cover) + assert(cover:find(env.__german and (labels["Rune"] .. " · " .. string.format(labels["%d unknown"], 3)) or "Rune 0/3", 1, true), "rune count wrong: " .. cover) end env.__over.AuraList = nil env.SlashCmdList.BUFFRADAR("consumables") @@ -3133,7 +3162,8 @@ db.weaponWatch = true env.IsSpellInRange = function() return 1 end env.GetWeaponEnchantInfo = function() return false, 0, 0, 0, false, 0, 0, 0 end - env.GetInventoryItemID = function() return 12345 end + env.GetInventoryItemID = function(_, slot) return slot == 16 and 12345 or 42 end + env.GetItemInfoInstant = function(id) return id, nil, nil, id == 12345 and "INVTYPE_WEAPON" or "INVTYPE_SHIELD", nil, id == 12345 and 2 or 4 end refresh() local function selfEntry() for i = 1, 15 do @@ -3149,7 +3179,7 @@ local e2 = selfEntry() assert(e2 and not e2.weapon, "weapon flag stuck after enchanting") env.GetWeaponEnchantInfo = nil - env.GetInventoryItemID = nil + env.GetInventoryItemID, env.GetItemInfoInstant = nil, nil cleanup() end) @@ -3361,6 +3391,7 @@ } slash("theme ui.elvui") fire("ADDON_LOADED", "BuffRadar") + db = env.BuffRadarDB assert(env.BuffRadarDB.theme == "ui.elvui" and X.ThemeBorder()[1] == 96 / 255, "reload gave a reserved name to a saved theme") local order = X.ThemeOrder() @@ -3385,7 +3416,7 @@ and math.abs(db.bgColor[1] - 24 / 255) < 1e-12, "BR1 lost the palette or its color") slash("theme midnight") X.DeleteProfile("PaletteRegression") - assert(X.ProfileImport(shared) and X.LoadProfile("PaletteRegression") + assert(X.ProfileImport(shared, db.profiles.PaletteRegression) and X.LoadProfile("PaletteRegression") and db.theme == "ui.foreverforge" and math.abs(db.bgColor[1] - 24 / 255) < 1e-12, "BR2 lost the palette or its color") X.DeleteProfile("PaletteRegression") @@ -3545,7 +3576,7 @@ loaded = "DaylightUI" slash("theme midnight") X.DeleteProfile("AutoPaletteRegression") - assert(X.ProfileImport(br2) and X.LoadProfile("AutoPaletteRegression") and db.theme == "ui.auto" + assert(X.ProfileImport(br2, db.profiles.AutoPaletteRegression) and X.LoadProfile("AutoPaletteRegression") and db.theme == "ui.auto" and db.bgColor[1] == 0.3 and X.autoThemeResolved == "ui.daylightui" and X.ThemeBorder()[1] == 55 / 255, "BR2 restored the sender's displayed palette instead of local Auto") end) @@ -3694,7 +3725,7 @@ assert(X.Import(export) and db.autoThemePriority == order and X.autoThemeAddon == "EllesmereUI", "new BR1 did not restore the order and recalculate Auto") slash("theme priority reset") - assert(X.ProfileImport(shared) and X.LoadProfile("ThemeOrderRegression") + assert(X.ProfileImport(shared, db.profiles.ThemeOrderRegression) and X.LoadProfile("ThemeOrderRegression") and db.autoThemePriority == order and X.autoThemeAddon == "EllesmereUI", "new BR2 did not restore the order and recalculate Auto") end) @@ -4567,7 +4598,7 @@ local O = env.__over O.AuraList = function(u) if u == "player" then - return { { name = "Rallying Cry of the Dragonslayer", expirationTime = env.GetTime() + 7500 } } + return { { name = "Rallying Cry of the Dragonslayer", spellId = 22888, expirationTime = env.GetTime() + 7500 } } end return {} end @@ -4578,12 +4609,12 @@ end local n = #chat env.SlashCmdList.BUFFRADAR("worldbuff") - assert(chatSince(n, "World: Rallying Cry of the Dragonslayer ~2h"), + assert(chatSince(n, NS.X.L["World"] .. ": Rallying Cry of the Dragonslayer ~2h"), "world buff not reported by the toggle") refresh() local line for _, fs in ipairs(env.__fontstrings) do - if type(fs.text) == "string" and fs.text:find("World: Rallying Cry", 1, true) then line = fs.text end + if type(fs.text) == "string" and fs.text:find(NS.X.L["World"] .. ": Rallying Cry", 1, true) then line = fs.text end end assert(line, "coverage line carries no world-buff segment") env.SlashCmdList.BUFFRADAR("worldbuff") @@ -4601,8 +4632,8 @@ if u == "party1" then return "Priest", "PRIEST" end return prevClass(u) end - O.Aura = function(u, name) - if u == "party1" and name == "Drink" then return { expirationTime = env.GetTime() + 60 } end + O.AuraList = function(u) + if u == "party1" then return { { spellId = 430, name = "Drink", expirationTime = env.GetTime() + 60 } } end end env.IsSpellInRange = function() return 1 end env.SlashCmdList.BUFFRADAR("drink") @@ -4617,7 +4648,7 @@ end assert(line, "coverage line does not count the drinking healer") env.SlashCmdList.BUFFRADAR("drink") - O.Aura = nil + O.UnitClass, O.AuraList = prevClass, nil cleanup() end) @@ -4662,8 +4693,11 @@ env.SlashCmdList.BUFFRADAR("plan import") env.BuffRadarExportFrame.editBox:SetText(text) local n = #chat - env.BuffRadarExportFrame.accept.scripts.OnClick(env.BuffRadarExportFrame.accept) - assert(chatSince(n, "Plan imported: 1 assignments, 0 blessings, 1 auto profiles"), + local dialog = env.BuffRadarExportFrame + dialog.accept:Click() + assert(db.autoProfile.dungeon == nil, "review changed a saved mapping") + dialog.apply:Click() + assert(chatSince(n, string.format(NS.X.L["Plan applied locally: %d assignments, %d blessings, %d auto profiles."], 1, 0, 1)), "plan import did not report the parts") assert(db.autoProfile.dungeon == "pset", "auto profile not restored by the plan") local n2 = #chat @@ -4683,19 +4717,25 @@ X.assign, X.blessPlan, db.autoProfile = { FORTITUDE = "Aaron" }, {}, { dungeon = "Original" } env.UnitIsGroupLeader = function(u) return u == "player" end local messages = {} - X.Broadcast = function(msg) messages[#messages + 1] = msg end + X.Broadcast = function(msg) messages[#messages + 1] = msg; return true end assert(not X.PlanImport("BRPLAN1;A;FORTITUDE;Other;P;dungeon"), "incomplete plan was accepted") assert(not X.PlanImport("BRPLAN1;A;FORTITUDE;Other;A;FORTITUDE;Aaron"), "duplicate plan was accepted") assert(not X.PlanImport("BRPLAN1;P;unknown;Original"), "unknown plan context accepted") assert(X.PlanImport("BRPLAN1"), "empty plan was not accepted as no-op") assert(X.assign.FORTITUDE == "Aaron" and db.autoProfile.dungeon == "Original" and #messages == 0, "invalid or empty plan changed state") - assert(X.PlanImport("BRPLAN1;A;FORTITUDE;Aaron;A;THORNS;Bela;P;raid;Future")) + local draft = assert(X.ParsePlanImport("BRPLAN1;A;FORTITUDE;Aaron;A;THORNS;Bela;P;raid;Future")) + local lines, _, scope = X.ReviewPlan(draft) + assert(scope and #lines == 3 and lines[1]:find("Future", 1, true), "review omitted missing profile or sharing") + env.UnitIsGroupLeader = nil + assert(not X.ApplyPlan(draft, scope) and not X.assign.THORNS and #messages == 0, + "confirmation ignored the changed group authority") + env.UnitIsGroupLeader = function(u) return u == "player" end + assert(X.ApplyPlan(draft, scope)) assert(db.autoProfile.dungeon == "Original" and db.autoProfile.raid == "Future", "plan mapping did not merge") assert(#messages == 1 and messages[1] == "ASSIGN;THORNS;Bela", "plan did not send only the changed record") - env.UnitIsGroupLeader = nil assert(X.PlanImport("BRPLAN1;A;THORNS;Aaron")) - assert(#messages == 1, "plan published assignments without leadership") + assert(#messages == 1, "local-only plan imported with an unrequested send") X.assign, X.blessPlan, db.autoProfile, env.UnitIsGroupLeader, X.Broadcast = assign, bless, mapping, leader, sent cleanup() end) @@ -4712,8 +4752,11 @@ env.SlashCmdList.BUFFRADAR("profile import") env.BuffRadarExportFrame.editBox:SetText(text) local n = #chat - env.BuffRadarExportFrame.accept.scripts.OnClick(env.BuffRadarExportFrame.accept) - assert(chatSince(n, "Profile imported: shareme"), "profile import not reported") + local dialog = env.BuffRadarExportFrame + dialog.accept:Click() + assert(not db.profiles.shareme and dialog.apply:IsShown(), "profile review changed storage") + dialog.apply:Click() + assert(chatSince(n, string.format(NS.X.L["Profile stored: %s (not loaded)."], "shareme")), "profile import not reported") assert(type(db.profiles.shareme) == "string", "profile not stored by the import") env.SlashCmdList.BUFFRADAR("profile delete shareme") end) @@ -4743,19 +4786,20 @@ local cleanup = partyOfTwo("G") local db = env.BuffRadarDB env.IsSpellInRange = function() return 1 end - -- Earlier sessions in this setup may already have counted these two; - -- this step asserts exactly one more fold for its own session. - local beforeA = db.offenders["Aaron"] or 0 - local beforeZ = db.offenders["Zed"] or 0 + env.SlashCmdList.BUFFRADAR("offenders clear") + NS.X.OnRoster() + -- Isolate the saved history so the two named rows are in the top ten. + local guidA, guidZ = env.UnitGUID("party1"), env.UnitGUID("party2") + local function count(guid) return db.offenders[guid] and db.offenders[guid].count or 0 end + local beforeA, beforeZ = count(guidA), count(guidZ) refresh() -- Aaron and Zed are both seen unbuffed this session env.IsInGroup = function() return false end fire("GROUP_ROSTER_UPDATE") -- the group ends: the session folds - assert(db.offenders["Aaron"] == beforeA + 1, - "Aaron not counted once more: " .. tostring(db.offenders["Aaron"])) - assert(db.offenders["Zed"] == beforeZ + 1, "Zed not counted once more") + assert(count(guidA) == beforeA + 1 and db.offenders[guidA].name == "Aaron-TestRealm", "Aaron not counted once more") + assert(count(guidZ) == beforeZ + 1, "Zed not counted once more") local n = #chat env.SlashCmdList.BUFFRADAR("offenders") - assert(chatSince(n, "Aaron: " .. (beforeA + 1)), "offender list does not name Aaron") + assert(chatSince(n, "Aaron-TestRealm: " .. (beforeA + 1)), "offender list does not name Aaron") env.SlashCmdList.BUFFRADAR("offenders clear") assert(next(db.offenders) == nil, "offender history not cleared") cleanup() @@ -5892,7 +5936,7 @@ "Tank + Raid did not apply the reviewed setup") assert(db.theme == theme and db.enabled == enabled, "Quick Setup changed the theme or selected buffs") for key, value in pairs(old) do db[key] = value end - NS.X.Intel.SettingsChanged() + NS.X.SettingsChanged({ liteMode = true, forecastSeconds = true, statusMinimap = true, visualAlerts = true }) end) step("two-column layout splits a long list (1.9.0)", function() @@ -6358,10 +6402,10 @@ assert(not X.ProfileImport(shared:gsub("blessingComplement=1", "blessingComplement=maybe")), "BR2 accepted a malformed complement setting") local older = shared:gsub(";blessingComplement=1;", ";") - assert(X.ProfileImport(older) and X.LoadProfile("ComplementAudit") and not db.blessingComplement, + assert(X.ProfileImport(older, db.profiles.ComplementAudit) and X.LoadProfile("ComplementAudit") and not db.blessingComplement, "a pre-v21 BR2 did not load with complement off") offers(nil) - assert(X.ProfileImport(shared) and X.LoadProfile("ComplementAudit") and db.blessingComplement, + assert(X.ProfileImport(shared, db.profiles.ComplementAudit) and X.LoadProfile("ComplementAudit") and db.blessingComplement, "a shared profile did not restore the opt-in") local cfg = env.BuffRadarConfig X.OpenConfig(true) @@ -6411,7 +6455,7 @@ local n0 = #chat env.SlashCmdList.BUFFRADAR("profile save RaidNight") assert(db.profiles and db.profiles.RaidNight, "profile not saved") - assert(chatSince(n0, "Profile saved: RaidNight"), "no save message") + assert(chatSince(n0, string.format(NS.X.L["Profile stored: %s (not loaded)."], "RaidNight")), "no save message") env.SlashCmdList.BUFFRADAR("scale 0.75") assert(db.scale == 0.75, "scale not changed after saving") env.SlashCmdList.BUFFRADAR("profile load RaidNight") @@ -7505,7 +7549,7 @@ "includeSelf", "hidden", "groupOnly", "autoHide", "pauseInCities", "sortMode", "viewMode", "roleFilter", "pinned", "buddy", "fastAura" } local api = { "IsInRaid", "IsInGroup", "GetNumGroupMembers", "UnitGroupRolesAssigned", - "GetSpellBookItemName", "GetSpellBookItemInfo", "GetSpellTabInfo", "IsPlayerSpell", "__combat", "__addonSent" } + "GetSpellBookItemName", "GetSpellBookItemInfo", "GetSpellTabInfo", "IsPlayerSpell", "__combat", "__addonSent", "UnitIsGroupLeader" } local saved, savedApi, savedUnits = {}, {}, {} for _, key in ipairs(fields) do saved[key] = db[key] end for _, key in ipairs(api) do savedApi[key] = env[key] end @@ -7537,6 +7581,7 @@ end env.IsInRaid, env.IsInGroup = function() return true end, function() return true end env.GetNumGroupMembers = function() return 5 end + env.UnitIsGroupLeader = function(unit) return unit == "player" or unit == "raid1" end env.UnitGroupRolesAssigned = function(unit) local u = member(unit); return u and u[3] end env.C_Item.GetItemCount = function() return 10 end local book = { @@ -7981,7 +8026,7 @@ local n = #chat env.SlashCmdList.BUFFRADAR("selftest") assert(chatSince(n, "BuffRadar self-test"), "no self-test header") - assert(chatSince(n, "dbVersion 22"), "self-test missing dbVersion") + assert(chatSince(n, "dbVersion 23"), "self-test missing dbVersion") assert(chatSince(n, "role filter"), "self-test missing the 1.5.0 state line") assert(chatSince(n, "custom spells"), "self-test missing the 1.6.0 state line") assert(chatSince(n, "weapon watch"), "self-test missing the 1.7.0 state line") @@ -8532,7 +8577,7 @@ local ok, err = pcall(fire, "ADDON_LOADED", "BuffRadar") if not ok then note("savedvars load", round, err) else - local db2 = env.BuffRadarDB + local db2 = X.GetDB() if type(db2) ~= "table" then note("savedvars load", round, "save is no longer a table") else for k, ty in pairs(expected) do @@ -8639,7 +8684,7 @@ end) -- Fresh, clock-controlled clients for the intelligence and readiness features. do - local function FeatureClient(saved, roster) + local function FeatureClient(saved, roster, setup) local client, messages = TestClient() local O = client.__over local now, due = 100, {} @@ -8666,8 +8711,9 @@ client.IsPlayerSpell = function(id) return id == 1243 or id == (forever and 14752 or 1459) end if not forever then client.GetSpellBookItemName = function() end end saved.dbVersion, saved.wizardSeen, saved.playSound = saved.dbVersion or 22, true, false - saved.enabled = { INNER_FIRE = false, SHADOWGUARD = false } + saved.enabled = saved.enabled or { INNER_FIRE = false, SHADOWGUARD = false } client.BuffRadarDB = saved + if setup then setup(client, units) end local X, startup = LoadClient(client) local function event(name, ...) for i = 1, #client.__frames do @@ -8700,6 +8746,8 @@ O = O, units = units, mana = mana, manaKey = manaKey, slash = client.SlashCmdList.BUFFRADAR, messages = messages } end + auditTests(step, FeatureClient, TestClient, LoadClient, forever) + step("v21 upgrades to validated bounded readiness settings; named profiles leave local rules alone", function() local f = FeatureClient({ dbVersion = 21, forecastSeconds = 900, smartPriority = "true", readinessAura = -12, instancePriority = { [12] = "FORTITUDE", [11] = "NOT_A_BUFF", [0] = "FORTITUDE" }, @@ -8707,7 +8755,7 @@ { spellID = 700, unit = "focus", encounterID = 99 }, { spellID = 701, unit = "target", encounterID = 0 }, { spellID = math.huge, unit = "player", encounterID = 0 } } }) local db, X = f.db, f.X - assert(db.dbVersion == 22 and db.forecastSeconds == 300 and not db.smartPriority + assert(db.dbVersion == 23 and db.forecastSeconds == 300 and not db.smartPriority and db.readinessAura == 0 and db.statusMinimap, "new scalar defaults or validation were wrong") assert(db.instancePriority[12] == "FORTITUDE" and not db.instancePriority[0] and not db.instancePriority[11] and #db.debuffRules == 1 and db.debuffRules[1].encounterID == 21, "invalid or duplicate rule survived sanitation") @@ -9143,7 +9191,7 @@ def read_sources(toc): failed = False for label, with_timer, no_templates, forever, german, sources in setups: results, chat = harness(lua.table_from([lua.table_from(file) for file in sources]), - with_timer, no_templates, forever, german) + with_timer, no_templates, forever, german, audit_tests) bad = 0 for i in range(1, len(results) + 1): name, status = results[i][1], results[i][2] diff --git a/tools/test_package.py b/tools/test_package.py new file mode 100644 index 0000000..6d96aba --- /dev/null +++ b/tools/test_package.py @@ -0,0 +1,119 @@ +"""Exercise the real packager on isolated source trees, without release credentials.""" + +import os +import runpy +import shutil +from pathlib import Path +from tempfile import TemporaryDirectory +from unittest import TestCase, main +from zipfile import ZipFile, ZipInfo + + +PACK = runpy.run_path(str(Path(__file__).with_name("package.py"))) +VERIFY = runpy.run_path(str(Path(__file__).with_name("checkpackage.py"))) +PROJECT = Path(__file__).resolve().parent.parent + + +class PackageTest(TestCase): + def setUp(self): + self.temp = TemporaryDirectory(prefix="br-package-test-") + self.addCleanup(self.temp.cleanup) + self.project = Path(self.temp.name) + self.version, self.sources = PACK["source_manifest"](PROJECT) + # Recreate a canonical independent checkout in reverse entry order. + for name, source in reversed(list(self.sources.items())): + base = "editions/forever" if name in PACK["EDITION"] else "BuffRadar" + path = self.project / base / name + path.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, path) + self.toc = self.project / "editions/forever/BuffRadar.toc" + self.archive = self.project / f"dist/BuffRadar-{self.version}-Forever.zip" + self.sums = self.archive.with_name("SHA256SUMS.txt") + + def test_repeat_is_byte_identical_after_mtime_changes_and_verifies(self): + PACK["pack"](self.project, f"v{self.version}") + first, digest = self.archive.read_bytes(), self.sums.read_bytes() + for path in self.project.rglob("*.lua"): + os.utime(path, (1_600_000_000, 1_600_000_000)) + PACK["pack"](self.project) + self.assertEqual(first, self.archive.read_bytes()) + self.assertEqual(digest, self.sums.read_bytes()) + VERIFY["check_package"](self.archive, self.project) + self.sums.write_bytes(b"not the computed digest\n") + with self.assertRaisesRegex(ValueError, "does not match"): + VERIFY["check_package"](self.archive, self.project) + + def test_mismatched_tag_and_wrong_or_duplicate_metadata_fail_before_build(self): + with self.assertRaisesRegex(ValueError, "does not match"): + PACK["pack"](self.project, "v0.0.0") + self.assertFalse(self.archive.exists()) + toc = self.toc.read_text(encoding="utf-8") + self.toc.write_text(toc.replace("## Interface: 16001", "## Interface: 120105"), encoding="utf-8") + with self.assertRaisesRegex(ValueError, "valid Interface"): + PACK["pack"](self.project) + self.toc.write_text(toc + "\n## Version: 0.0.0\n", encoding="utf-8") + with self.assertRaisesRegex(ValueError, "valid Version"): + PACK["pack"](self.project) + self.assertFalse(self.archive.exists()) + + def test_undeclared_source_and_escaped_toc_path_fail(self): + extra = self.project / "BuffRadar" / "extra.txt" + extra.write_text("not part of the addon", encoding="utf-8") + with self.assertRaisesRegex(ValueError, "inventory"): + PACK["source_manifest"](self.project) + extra.unlink() + with self.toc.open("a", encoding="utf-8") as stream: + stream.write("\n../outside.lua\n") + with self.assertRaisesRegex(ValueError, "must match"): + PACK["source_manifest"](self.project) + + def test_cross_platform_path_aliases_fail(self): + for name in ("../x.lua", "/x.lua", "x//z.lua", "dir/./foo.lua", "dir\\foo.lua", "C:/foo.lua", "x/COM1.lua", "x /foo.lua"): + with self.subTest(name=name), self.assertRaises(ValueError): + PACK["canonical"](name) + image = self.project / "BuffRadar/Media/ICON.PNG" + if image.exists(): # Case-insensitive volume already prevents the duplicate. + return + image.write_bytes(b"different icon") + with self.assertRaisesRegex(ValueError, "Case-folded duplicate"): + PACK["source_manifest"](self.project) + + def test_source_and_binding_drift_are_rejected(self): + source = self.project / "BuffRadar/Bindings.xml" + PACK["pack"](self.project) + source.write_bytes(source.read_bytes().replace(b"BUFFRADAR_MUTE", b"BUFFRADAR_OTHER")) + with self.assertRaisesRegex(ValueError, "Stale package entry Bindings.xml"): + VERIFY["check_package"](self.archive, self.project) + PACK["pack"](self.project) + with self.assertRaisesRegex(ValueError, "Invalid binding definition"): + VERIFY["check_package"](self.archive, self.project) + + def test_verifier_refuses_archive_metadata_and_directory_aliases(self): + PACK["pack"](self.project) + with ZipFile(self.archive, "a") as edited: + edited.comment = b"unverified metadata" + with self.assertRaisesRegex(ValueError, "deterministic archive"): + VERIFY["load_archive"](self.archive, require_deterministic=True) + with ZipFile(self.archive, "w") as edited: + edited.writestr(ZipInfo("BuffRadar/Media/icon.png"), b"icon") + edited.writestr(ZipInfo("BuffRadar/MEDIA/logo.png"), b"logo") + with self.assertRaisesRegex(ValueError, "Case-folded duplicate"): + VERIFY["load_archive"](self.archive) + + def test_symlink_is_never_packaged(self): + path = self.project / "BuffRadar" / "linked.lua" + try: + path.symlink_to(self.toc) + except (NotImplementedError, OSError) as exc: + self.skipTest(f"Symbolic links unavailable: {exc}") + with self.assertRaisesRegex(ValueError, "non-linked"): + PACK["source_manifest"](self.project) + path.unlink() + directory = self.project / "BuffRadar" / "linked-dir" + directory.symlink_to(self.toc.parent, target_is_directory=True) + with self.assertRaisesRegex(ValueError, "non-linked"): + PACK["source_manifest"](self.project) + + +if __name__ == "__main__": + main(verbosity=2) diff --git a/tools/wowstub.lua b/tools/wowstub.lua index 8f48217..341578e 100644 --- a/tools/wowstub.lua +++ b/tools/wowstub.lua @@ -94,6 +94,7 @@ function WOWSTUB(chat, withTimer, noTemplates, forever, german) function methods.ClearAllPoints(self) self.points = {} end function methods.SetWidth(self, w) self.width = w end function methods.SetSize(self, w, h) self.size = { w, h } end + function methods.SetHeight(self, h) self.height = h end function methods.SetFrameStrata(self, s) self.strata = s end function methods.SetVertexColor(self, r, g, b, a) self.vcolor = { r, g, b, a } end function methods.SetHighlightTexture(self, file, blend) @@ -108,6 +109,7 @@ function WOWSTUB(chat, withTimer, noTemplates, forever, german) function methods.SetBackdropBorderColor(self, r, g, b, a) self.borderColor = { r, g, b, a } end function methods.RegisterEvent(self, ev) self.events[ev] = true end function methods.UnregisterEvent(self, ev) self.events[ev] = nil end + function methods.UnregisterAllEvents(self) self.events = {} end function methods.RegisterUnitEvent(self, ev, ...) self.events[ev] = { ... } end -- DropdownButton (modern menu) API function methods.SetupMenu(self, gen) self.menuGen = gen end @@ -130,6 +132,7 @@ function WOWSTUB(chat, withTimer, noTemplates, forever, german) local frames = {} function env.CreateFrame(kind, name, parent, template) + if env.__rejectTemplate and env.__rejectTemplate(kind, name, template) then error("template refused: " .. tostring(template)) end local f = newObject(kind, name) f.template = template f.parent = parent @@ -144,6 +147,8 @@ function WOWSTUB(chat, withTimer, noTemplates, forever, german) end env.__frames = frames env.UIParent = newObject("Frame", "UIParent") + env.UIParent.GetWidth = function() return 1280 end + env.UIParent.GetHeight = function() return 720 end env.Minimap = newObject("Frame", "Minimap") env.GameTooltip = newObject("GameTooltip", "GameTooltip") env.ColorPickerFrame = newObject("Frame", "ColorPickerFrame") @@ -175,7 +180,7 @@ function WOWSTUB(chat, withTimer, noTemplates, forever, german) local f = env.__over.AuraList local list = f and f(unit) local a = list and list[i] - if a then return a.name, "", 0, nil, 0, a.expirationTime, a.sourceUnit end + if a then return a.name, "", 0, nil, 0, a.expirationTime, a.sourceUnit, nil, nil, a.spellId end return nil end env.GetBuildInfo = function() return "12.1.5", "99999", "Oct 2026", 120105 end