From 23a14a4a35d3a94f4bbb6e930e0af1066bb0ce75 Mon Sep 17 00:00:00 2001 From: SeanShaffer88 <252387677+SeanShaffer88@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:12:12 +0000 Subject: [PATCH] Refactor BuffRadar modules and improve Forever buffing Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- AGENTS.md | 44 +- BuffRadar/BuffRadar.lua | 3202 ++++++----------------------- BuffRadar/BuffRadar.toc | 4 +- BuffRadar/Config.lua | 60 +- BuffRadar/Coordination.lua | 38 +- BuffRadar/Data.lua | 14 +- BuffRadar/Extras.lua | 61 +- BuffRadar/Locales/deDE.lua | 28 + BuffRadar/Minimap.lua | 120 ++ BuffRadar/Profiles.lua | 51 +- BuffRadar/Recaps.lua | 4 +- BuffRadar/SavedVariables.lua | 476 +++++ BuffRadar/Slash.lua | 120 +- BuffRadar/Window.lua | 2047 +++++++++++++++--- BuffRadar/Wizard.lua | 154 +- QUALITY.md | 12 +- README.md | 26 +- docs/DECISIONS.md | 15 + docs/FOREVER_RELEASE_CHECKLIST.md | 39 + docs/PARITY.md | 10 +- editions/forever/BuffRadar.toc | 6 +- editions/forever/CHANGELOG.md | 20 + editions/forever/FEATURES.md | 20 +- editions/forever/README.md | 52 +- tools/README.md | 10 +- tools/check.ps1 | 5 +- tools/checkpackage.py | 2 +- tools/coordination51.py | 7 +- tools/gate.sh | 11 +- tools/lualimits.py | 26 +- tools/smoke51.py | 1042 +++++++--- tools/wowstub.lua | 40 +- 32 files changed, 4358 insertions(+), 3408 deletions(-) create mode 100644 BuffRadar/Minimap.lua create mode 100644 BuffRadar/SavedVariables.lua diff --git a/AGENTS.md b/AGENTS.md index 7f14103..602d16d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,31 +8,29 @@ Purpose in one line: a click-to-buff list addon for World of Warcraft — it sho every nearby player who is missing one of your buffs; click a name (or press one key) to buff them. -Frozen foundation: one shared Lua source (`BuffRadar/Data.lua` + `BuffRadar/BuffRadar.lua` + `BuffRadar/Coordination.lua` + `BuffRadar/Wizard.lua` + `BuffRadar/Window.lua` + `BuffRadar/Config.lua` + `BuffRadar/Slash.lua` + `BuffRadar/Extras.lua` + `BuffRadar/Recaps.lua` + `BuffRadar/Profiles.lua`) builds both -editions; editions differ only in their `.toc` and bundled docs -(`BuffRadar/` = Retail docs, `editions/forever/` = Forever docs). Every feature -is reachable as a `/br` slash command — the slash surface is the operation -registry — as well as through its settings control where it has one. -SavedVariables are versioned (`dbVersion`, currently 20) with a tested migration -chain; adding or changing a setting is a format change and updates the migration -smoke fixtures in the same change. +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` +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. +Every feature is reachable through `/br` as well as through its settings control +where it has one. SavedVariables are versioned (`dbVersion`, currently 21) with +migration smoke fixtures; keep those fixtures in sync with format changes. Build: none (interpreted Lua 5.1). -Full gate (all of it, every time, output read): -`python3 tools/luacheck51.py BuffRadar/BuffRadar.lua BuffRadar/Extras.lua BuffRadar/Locales/*.lua` · (or just `sh tools/gate.sh`; `sh tools/install-hooks.sh` runs it before every push) · -`python3 tools/lualimits.py BuffRadar/BuffRadar.lua` · -`python3 tools/localecheck.py BuffRadar/BuffRadar.lua BuffRadar/Locales` · -real luacheck 1.2.0 over both Lua files (0 warnings / 0 errors) · -`python3 tools/smoke51.py tools/wowstub.lua BuffRadar/BuffRadar.lua` -(six fake-client setups, 0 errors required). -Test corpus: the trial run in `tools/smoke51.py` — it only grows; every feature -lands with steps in every setup it applies to. - -Budgets: the host's per-frame budget governs — scanning is event-driven plus a -throttled ticker; no per-frame polling. Lua 5.1 hard limits enforced by -`tools/lualimits.py`: ≤200 top-level locals (currently 165 in `BuffRadar.lua`), ≤60 upvalues per -function (currently 58 peak, `HandleSlash`). New state goes in the `X` table or methods, never -new file-scope locals, unless the budget is re-checked in the same change. +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. +`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. + +Budgets: scanning is event-driven plus a throttled ticker; no per-frame +polling. The Lua 5.1 compiler enforces 200 active locals per function or chunk +and 60 upvalues per function. Check headroom with `tools/lualimits.py` when +adding file-scope state; keep state in its owning module rather than moving it +into the shared `X` table to work around the limits. Coverage floors: every user-visible capability has smoke evidence before it is called done; in-game behaviour is labelled **Unverified** until SEAN's field test diff --git a/BuffRadar/BuffRadar.lua b/BuffRadar/BuffRadar.lua index ec9f7f3..2b3aad9 100644 --- a/BuffRadar/BuffRadar.lua +++ b/BuffRadar/BuffRadar.lua @@ -1,6 +1,6 @@ -- BuffRadar - click-to-buff list for World of Warcraft (Retail and Forever) -- One source for both editions: the buff set and class tables are picked at --- load from the client's interface version (see CLASSIC_FEATURES below). +-- load from the client's interface version by Data.lua. -- Copyright (C) 2026 Malikor -- -- This program is free software: you can redistribute it and/or modify @@ -28,9 +28,10 @@ -- target and mouseover). Turn friendly nameplates on (Shift+V, or /br plates) -- to see strangers. There is no API that lists nearby players directly. -local ADDON = ... +local ADDON, namespace = ... +local X = namespace.X --- Cached globals: hot paths (refresh, aura reads, row rendering) use these locals +-- Cached globals: hot paths (scans and aura reads) use these locals -- instead of a global-table lookup on every call. local _G = _G local pairs, ipairs, next, type, select, pcall = pairs, ipairs, next, type, select, pcall @@ -56,505 +57,30 @@ BINDING_NAME_BUFFRADAR_MUTE = "Mute / unmute sound" local NEXT_BINDING = "CLICK BuffRadarNextButton:LeftButton" local MACRO_NAME = "BuffRadar" ---------------------------------------------------------------------------- --- Layout ---------------------------------------------------------------------------- -local MAX_ROWS = 15 -local ROW_H = 24 -local WIDTH = 210 -- default window width; drag the corner grip to change it -local MIN_WIDTH, MAX_WIDTH = 180, 400 -local SCALE_PRESETS = { 0.5, 0.75, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2 } -- scale dropdowns -local HEADER_H = 24 -local MAX_ICONS = 5 local UPDATE_INTERVAL = 0.4 -local FOOTER_H = 16 local SOUND_FILE = "Interface\\AddOns\\BuffRadar\\Media\\droplet.ogg" --- Enhancement state (1.4.0), declared up here so every later section -- and --- Extras.lua -- can reach it. One table on purpose: the main chunk is at --- Lua 5.1's 200-local limit, so new state lives here, not in new locals. -local X = (select(2, ...) and select(2, ...).X) or {} +-- Runtime state used across the feature modules, not SavedVariables. do - local _defs = { session = {}, dead = {}, rezAt = {}, tally = {}, tallyUnits = 0, - listA = {}, listB = {}, recentlyGone = {}, sessionCasts = 0, - missPrev = {}, missNow = {}, expiredAt = {}, rowH = 24, - handled = {}, asked = {}, applyFilter = true, - failedTargets = {}, - prevHolder = {}, queueAt = 0, consTally = {}, - assign = {}, blessPlan = {}, peers = {}, cover = {}, myCover = false, - expiryTally = {}, upTotal = 0, upFull = 0, - search = "", offNow = {}, drinkSet = {}, focusMiss = {}, cfgReg = {} } - for k, v in pairs(_defs) do if X[k] == nil then X[k] = v end end -end -X.hid = 0 -- last time an aura read came back unreadable (secret) (1.12.0) -if select(2, ...) then select(2, ...).X = X end -- shared with Data.lua / Extras.lua - --- Buff data lives in Data.lua (loaded first through the .toc); these --- locals alias the shared tables so the rest of this file reads as it --- always has. + local shared = { + session = {}, dead = {}, rezAt = {}, tally = {}, tallyUnits = 0, + sessionCasts = 0, missPrev = {}, missNow = {}, expiredAt = {}, + handled = {}, asked = {}, applyFilter = true, failedTargets = {}, + prevHolder = {}, queueAt = 0, consTally = {}, assign = {}, blessPlan = {}, + peers = {}, cover = {}, myCover = false, expiryTally = {}, upTotal = 0, upFull = 0, + search = "", offNow = {}, drinkSet = {}, + hid = 0, -- last unreadable aura data + } + for key, value in pairs(shared) do X[key] = value end +end + local CLASSIC_FEATURES = X.classic local ALL, BUFF_DEFS = X.ALL, X.BUFF_DEFS local BLESSINGS = X.BLESSINGS -- (X.MANA / X.MELEE / X.TANKS / X.AURA_DEFS / X.BLESSING_PRIORITY are read -- through X at their few use sites, to keep main-chunk locals freed.) ---------------------------------------------------------------------------- --- Saved settings ---------------------------------------------------------------------------- -local DEFAULTS = { - locked = false, - hidden = false, - includeSelf = true, -- your own character gets every buff that suits your class (top of the list) - avoidPvP = true, -- don't list PvP-flagged players unless you're flagged too - autoHide = false, -- hide the window when nobody needs anything - rebuff = 30, -- re-list a player when your buff has less than this many seconds left - scale = 1, - width = 210, -- list window width (corner grip); height always follows the list - cfgScale = 1, -- settings window scale - enabled = {}, - point = nil, - castMethod = "target", -- "target" (target player, cast, restore target), "id", "macro", "rank" - clickDebug = false, - clickReg = "both", -- which mouse half triggers the cast: "both", "down" or "up" - bgColor = { 0.04, 0.05, 0.09 }, - bgAlpha = 0.92, - showTitle = true, - showBorder = true, - playSound = true, -- water droplet when a new name shows up - showCounter = true, -- cast counter at the bottom of the window - castsTotal = 0, -- all-time casts made through BuffRadar - groupOnly = false, -- only show the window while in a party or raid - pauseInCities = true, -- stop scanning in major cities - groupCast = false, -- offer the group version (Prayer of Fortitude etc.) when enough group members need a buff - groupCastMin = 3, -- how many group members must need the buff first - showOutOfRange = false, -- the list only includes targets in cast range - sortMode = "name", -- list order: "name" or "role" (tanks and leaders first) - ignored = {}, -- player names BuffRadar never lists (right-click a row) - rebuffPer = {}, -- per-buff rebuff thresholds in seconds: buff key -> seconds - alertSound = "droplet", -- alert sound: "droplet", "system" or "none" - alertSounds = {}, -- per-alert-kind sound: new/drop/ask/fall -> a sound name (empty = use alertSound) - buffPrio = {}, -- your buff order: buff keys, first offered first (empty = normal order) - blessingPreferences = {}, -- class token -> preferred blessing key - assignmentEnabled = false, - thornsAnyClassOutdoors = false, - buffAssignments = {}, - clickThrough = false, -- while locked, let clicks pass through the window to the game - muteInInstance = false, -- no alert sound while in a dungeon, raid or battleground - showMinimap = true, -- minimap button (the addon compartment works regardless) - minimapAngle = 215, -- minimap button position, degrees - pauseInBG = false, -- pause listing in battlegrounds and arenas - pauseTaxi = false, -- pause listing while on a flight path (1.5.0) - watchDrop = true, -- alert when your single-target buff drops off its holder (1.5.0) - fallSound = false, -- alert when a watched group buff falls off mid-fight (1.15.0, #33) - lowMana = 0, -- pause offering buffs below this mana % (0 = off) (1.4.0) - specProfiles = {}, -- per-spec overrides: spec key -> { enabled=, rebuffPer= } (1.4.0) - 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) - 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) - requests = true, -- tag players who ask for a buff in chat (1.5.0) - joinDigest = true, -- one-line summary when joining a group (1.5.0) - roleFilter = "ALL", -- window list filter: "ALL", "TANK", "HEALER" or "DAMAGER" (1.5.0) - showStrip = true, -- buff toggle strip + filter chips under the title (1.5.0) - scalePerSpec = false, -- remember a window scale per specialization (1.12.0) - specScales = {}, -- spec key -> scale (1.12.0) - gripSnap = true, -- Shift while dragging a scale grip snaps to 75/100/125/150% (1.12.0) - tagSymbols = false, -- add a symbol to row tags so meaning never rests on color (1.12.0) - reduceMotion = false, -- no idle fade, no border flash (1.12.0) - rangeWatch = false, -- say when a player who needs a buff walks into range (1.12.0) - assumeRange = false, -- list players the client refuses to place, flagged as estimated - idleFade = 0, -- fade the window by this % while the mouse is away (0 = off) (1.5.0) - pill = false, -- collapse to a small pill while everyone is buffed (1.6.0) - queueTag = true, -- tag the top row "up next" right after a cast lands (1.6.0) - consumables = false, -- coverage line also tracks flasks, food and runes (1.6.0) - buddySplit = false, -- share the list with other BuffRadar users present (1.6.0) - readyPost = false, -- post the ready-check summary to group chat (leader/assistant) (1.7.0) - deathRecap = true, -- print who was missing buffs when you died (1.9.0) - wipeReport = false, -- print a rebuff report after a wipe (1.9.0) - wizardSeen = false, -- the setup wizard has been run or dismissed (1.9.0) - customThemes = {}, -- your saved themes: { name, bg, border } (1.10.0) - rowGap = 0, -- extra space between rows, 0-8 (1.10.0) - iconSize = 0, -- buff icon size 10-24; 0 = automatic (1.10.0) - strata = "MEDIUM", -- legacy saved value; frames keep the client's default layer - coverParts = {}, -- coverage-line parts switched OFF (absent = on) (1.10.0) - tooltipLevel = "standard", -- row tooltips: minimal | standard | full (1.10.0) - viewMode = "people", -- list view: "people" (one row per player) or "buffs" (one row per buff still needed) - classColors = true, -- row names in class colors (1.10.0) - showRealm = false, -- show -Realm after row names (1.10.0) - nameTrim = 0, -- shorten row names past this many letters, 0 = off (1.10.0) - rowColors = {}, -- colored edge marks on rows: mine|tank|expiring|buddy (1.10.0) - pinned = "", -- full or short name of the player pinned to the top (1.7.0) - weaponWatch = false, -- remind me when my weapon has no temporary enchant (1.7.0) - fastAura = false, -- skip refreshes for aura changes that touch no watched buff (1.14.0, Brief 2) - modClick = false, -- Shift-click a row casts the group version of its buff (1.14.0, Brief 3) - pullFlash = false, -- flash + countdown line when a pull timer starts (1.14.0, Brief 4) - enterFlash = true, -- print a reminder when entering an instance unbuffed (1.7.0) - scanThrottle = false, -- halve the steady rescan rate in groups over 20 (1.7.0) - history = {}, -- last 50 casts through BuffRadar: { t, spell, who } (1.7.0) - growUp = false, -- the list grows upward from a fixed bottom edge (1.8.0) - hideInCombat = true, -- no buff targets are available while you are in combat - twoCol = false, -- two columns when the list is long (1.9.0) - theme = "midnight", -- window color theme (1.8.0) - autoThemePriority = "", -- an empty setting uses the built-in addon priority - findBox = false, -- name finder box on the window (1.8.0) - durationBars = false, -- thin bar per row: time left on the expiring buff (1.8.0) - raidMarkers = false, -- show raid target markers on rows (1.8.0) - rangeText = false, -- word band ("near") on out-of-range rows (1.8.0) - focusWatch = false, -- a line about your focus target's buffs (1.8.0) - pets = false, -- list group pets that need buffs (1.8.0) - auraWatch = false, -- watch your own aura / aspect (Forever) (1.8.0) - worldWatch = false, -- show your active world buffs on the coverage line (Forever) (1.8.0) - drinkWatch = false, -- mark healers who are drinking (Forever) (1.8.0) - buffContext = {}, -- per-buff context: buff key -> "raid" | "instance" (1.8.0) - offenders = {}, -- group sessions where a player was seen unbuffed: name -> count (1.8.0) - autoProfile = {}, -- load a named profile per context: raid/dungeon/pvp/world/solo -> name (1.6.0) - customSpells = {}, -- extra spell IDs to watch, added with /br custom (1.6.0) - customGroup = {}, -- your own group-cast pairs: spell name -> group spell name, /br grouppair (1.15.0) - stats = {}, -- all-time casts per spell name: name -> count -} local db -local PROFILE_MAX_BYTES = 4000 - -local function IsProfileName(name) - return type(name) == "string" and #name <= 40 and name:match("^[%w_%-]+$") ~= nil -end - --- SavedVariables sanity check: anything missing, mistyped, out of range or left over --- from an older layout is repaired or dropped, so a damaged WTF file can't break the addon. --- (Its helpers live in a do-block to stay within Lua 5.1's 200-local limit for --- the file; see the config window section.) -local SanitizeDB -do -local KNOWN_KEYS = { point = true, dbVersion = true } -for k in pairs(DEFAULTS) do KNOWN_KEYS[k] = true end -local ENUMS = { - castMethod = { target = true, id = true, macro = true, rank = true }, - clickReg = { both = true, down = true, up = true }, - sortMode = { name = true, role = true, distance = true, need = true }, - roleFilter = { ALL = true, TANK = true, HEALER = true, DAMAGER = true }, - alertSound = { droplet = true, system = true, none = true }, - strata = { LOW = true, MEDIUM = true, HIGH = true, DIALOG = true }, - tooltipLevel = { minimal = true, standard = true, full = true }, - viewMode = { people = true, buffs = true }, -} -local RANGES = { bgAlpha = { 0, 1 }, scale = { 0.5, 2 }, cfgScale = { 0.5, 2 }, - width = { MIN_WIDTH, MAX_WIDTH }, rebuff = { 0, 3600 }, castsTotal = { 0, 1e9 }, - groupCastMin = { 2, 40 }, minimapAngle = { 0, 360 }, - lowMana = { 0, 100 }, textScale = { 0.8, 1.5 }, idleFade = { 0, 90 }, - rowGap = { 0, 8 }, iconSize = { 0, 24 }, nameTrim = { 0, 24 } } - -local function IsNumber(v) - return type(v) == "number" and v == v and v ~= math_huge and v ~= -math_huge -end -local function Clamp(v, lo, hi) return math_max(lo, math_min(hi, v)) end - -local MAX_AUTO_PRIORITY_BYTES = 512 - -local function OrderedAutoThemeAddons(value) - local order, seen = {}, {} - if type(value) == "string" and value ~= "" and #value <= MAX_AUTO_PRIORITY_BYTES then - local byID = {} - for _, entry in ipairs(X.AUTO_THEME_ADDONS) do byID[entry[2]] = entry end - for token in value:gmatch("[^,]+") do - local id = token:match("^%s*(.-)%s*$"):lower() - if byID[id] and not seen[id] then - order[#order + 1], seen[id] = byID[id], true - end - end - end - for _, entry in ipairs(X.AUTO_THEME_ADDONS) do - if not seen[entry[2]] then order[#order + 1] = entry end - end - return order -end - -local function EncodeAutoThemePriority(order) - local ids, isDefault = {}, true - for i, entry in ipairs(order) do - ids[i] = entry[2] - if entry ~= X.AUTO_THEME_ADDONS[i] then isDefault = false end - end - return isDefault and "" or table.concat(ids, ",") -end - -function X.AutoThemePriority() - return OrderedAutoThemeAddons(db and db.autoThemePriority) -end - -function X.MoveAutoThemePriority(palette, offset) - if not db or (offset ~= -1 and offset ~= 1) then return false end - local order = X.AutoThemePriority() - for i, entry in ipairs(order) do - if entry[2] == palette then - local nextIndex = i + offset - if not order[nextIndex] then return false end - order[i], order[nextIndex] = order[nextIndex], entry - db.autoThemePriority = EncodeAutoThemePriority(order) - X.ResolveAutoTheme() - return true - end - end - return false -end - -function X.ResetAutoThemePriority() - if not db then return false end - local changed = db.autoThemePriority ~= "" - db.autoThemePriority = "" - X.ResolveAutoTheme() - return changed -end - -function X.ProfileScalarValid(key, value) - if key == "theme" then return #value >= 1 and #value <= 24 end - if key == "autoThemePriority" then return #value <= MAX_AUTO_PRIORITY_BYTES end - local choices = ENUMS[key] - return not choices or choices[value] == true -end - -function SanitizeDB(saved) - if type(saved) ~= "table" then saved = {} end - for k in pairs(saved) do - if type(k) ~= "string" or not KNOWN_KEYS[k] then saved[k] = nil end - end - for k, def in pairs(DEFAULTS) do - local v, dt = saved[k], type(def) - if dt == "table" then - if type(v) ~= "table" then v = nil end - if k == "bgColor" then - if v and IsNumber(v[1]) and IsNumber(v[2]) and IsNumber(v[3]) then - v = { Clamp(v[1], 0, 1), Clamp(v[2], 0, 1), Clamp(v[3], 0, 1) } - else - v = { def[1], def[2], def[3] } - end - elseif k == "alertSounds" then - local clean = {} - if v then - for kind, choice in pairs(v) do - if (kind == "new" or kind == "drop" or kind == "ask" or kind == "fall") - and (choice == "droplet" or choice == "system" or choice == "none") then - clean[kind] = choice - end - end - end - v = clean - elseif k == "buffPrio" then - local clean, seenKeys = {}, {} - if v then - for _, key in ipairs(v) do - if type(key) == "string" and #key <= 40 and not seenKeys[key] then - seenKeys[key] = true - clean[#clean + 1] = key - if #clean >= 24 then break end - end - end - end - v = clean - elseif k == "buffAssignments" then - v = X.CopyAssignments(v) - elseif k == "blessingPreferences" then - local clean = {} - if v then - for class, key in pairs(v) do - if type(class) == "string" and type(key) == "string" - and X.BLESSING_CLASSES[class] and BLESSINGS[key] then clean[class] = key end - end - end - v = clean - elseif k == "enabled" or k == "ignored" or k == "coverParts" then - local clean = {} - if v then - for key, on in pairs(v) do - if type(key) == "string" and type(on) == "boolean" then clean[key] = on end - end - end - v = clean - elseif k == "specScales" then - local clean = {} - if v then - for sk, n in pairs(v) do - if type(sk) == "string" and IsNumber(n) then clean[sk] = Clamp(n, 0.5, 2) end - end - end - v = clean - elseif k == "specProfiles" then - local clean = {} - if v then - for sk, prof in pairs(v) do - if type(sk) == "string" and type(prof) == "table" then - local p = { enabled = {}, rebuffPer = {} } - if type(prof.enabled) == "table" then - for key, on in pairs(prof.enabled) do - if type(key) == "string" and type(on) == "boolean" then p.enabled[key] = on end - end - end - if type(prof.rebuffPer) == "table" then - for key, n in pairs(prof.rebuffPer) do - if type(key) == "string" and IsNumber(n) and n >= 0 then p.rebuffPer[key] = n end - end - end - clean[sk] = p - end - end - end - v = clean - elseif k == "pointByChar" then - local clean = {} - if v then - for name, p in pairs(v) do - if type(name) == "string" and type(p) == "table" and type(p[1]) == "string" - and type(p[2]) == "string" and IsNumber(p[3]) and IsNumber(p[4]) then - clean[name] = { p[1], p[2], p[3], p[4] } - end - end - end - v = clean - elseif k == "profiles" then - local clean = {} - if v then - for name, s in pairs(v) do - if IsProfileName(name) and type(s) == "string" and #s <= PROFILE_MAX_BYTES then - clean[name] = s - end - end - end - v = clean - elseif k == "autoProfile" then - local clean = {} - if v then - for ctx, name in pairs(v) do - if type(ctx) == "string" and type(name) == "string" and #name <= 40 then - clean[ctx] = name - end - end - end - v = clean - elseif k == "history" then - local clean = {} - if v then - for _, e in ipairs(v) do - if type(e) == "table" and type(e.spell) == "string" and type(e.who) == "string" then - clean[#clean + 1] = { t = IsNumber(e.t) and math_floor(e.t) or 0, - spell = e.spell, who = e.who } - end - end - end - while #clean > 50 do table.remove(clean, 1) end - v = clean - elseif k == "customSpells" then - local clean, seenIds = {}, {} - if v then - for _, id in ipairs(v) do - if IsNumber(id) and id >= 1 and id <= 2000000 and not seenIds[id] then - seenIds[id] = true - clean[#clean + 1] = math_floor(id) - if #clean >= 20 then break end - end - end - end - v = clean - elseif k == "customGroup" then - local clean, n = {}, 0 - if v then - for single, group in pairs(v) 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 - n = n + 1 - if n >= 20 then break end - end - end - end - v = clean - elseif k == "customThemes" then - local clean, seenNames = {}, {} - if v then - for _, t in ipairs(v) do - if type(t) == "table" and type(t.name) == "string" and #t.name >= 1 and #t.name <= 24 - and type(t.bg) == "table" and type(t.border) == "table" - and IsNumber(t.bg[1]) and IsNumber(t.bg[2]) and IsNumber(t.bg[3]) - and IsNumber(t.border[1]) and IsNumber(t.border[2]) and IsNumber(t.border[3]) - and not seenNames[t.name:lower()] then - seenNames[t.name:lower()] = true - clean[#clean + 1] = { - name = t.name, - bg = { Clamp(t.bg[1], 0, 1), Clamp(t.bg[2], 0, 1), Clamp(t.bg[3], 0, 1) }, - border = { Clamp(t.border[1], 0, 1), Clamp(t.border[2], 0, 1), Clamp(t.border[3], 0, 1) }, - } - if #clean >= 4 then break end - end - end - end - v = clean - elseif k == "rowColors" then - local clean = {} - if v then - for rule, c in pairs(v) do - if (rule == "mine" or rule == "tank" or rule == "expiring" or rule == "buddy") - and type(c) == "table" and IsNumber(c[1]) and IsNumber(c[2]) and IsNumber(c[3]) then - clean[rule] = { Clamp(c[1], 0, 1), Clamp(c[2], 0, 1), Clamp(c[3], 0, 1) } - end - end - end - v = clean - elseif k == "buffContext" then - local clean = {} - if v then - for key, ctx in pairs(v) do - if type(key) == "string" and (ctx == "raid" or ctx == "instance") then - clean[key] = ctx - end - end - end - v = clean - elseif k == "rebuffPer" or k == "stats" or k == "offenders" then - local clean = {} - if v then - for key, n in pairs(v) do - if type(key) == "string" and IsNumber(n) and n >= 0 then clean[key] = n end - end - end - v = clean - elseif not v then - v = {} - for i, x in pairs(def) do v[i] = x end - end - elseif dt == "number" then - if not IsNumber(v) then v = def end - local r = RANGES[k] - if r then v = Clamp(v, r[1], r[2]) end - if k == "castsTotal" then v = math_floor(v) end - elseif dt == "boolean" then - if type(v) ~= "boolean" then v = def end - elseif dt == "string" then - if type(v) ~= "string" or (ENUMS[k] and not ENUMS[k][v]) then v = def end - if k == "theme" and type(v) == "string" and #v > 24 then v = def end - if k == "autoThemePriority" and v ~= "" then - v = EncodeAutoThemePriority(OrderedAutoThemeAddons(v)) - end - end - saved[k] = v - end - local themeID = saved.theme:lower() - if X.THEMES[themeID] or themeID == "custom" then - saved.theme = themeID - else - local found = false - for _, t in ipairs(saved.customThemes or {}) do - if t.name == saved.theme then found = true; break end - end - if not found then saved.theme = "custom" end - end - local p = saved.point - if p ~= nil and not (type(p) == "table" and type(p[1]) == "string" and type(p[2]) == "string" - and IsNumber(p[3]) and IsNumber(p[4])) then - saved.point = nil - end - if saved.dbVersion ~= nil and not IsNumber(saved.dbVersion) then saved.dbVersion = nil end - return saved -end -end -- SanitizeDB block +X.OnDBLoaded(function(value) db = value end) local function Print(msg) DEFAULT_CHAT_FRAME:AddMessage("|cff33ccffBuffRadar|r: " .. tostring(msg)) @@ -563,7 +89,6 @@ end --------------------------------------------------------------------------- -- Localization scaffolding: enUS strings are the keys. A translation file -- can set the addon's private Locales["deDE"] before this file loads. --- before this file loads; only the window's status lines are wired so far. --------------------------------------------------------------------------- -- Every string the main window, its row tooltips and the minimap / addon-menu -- tooltips show is listed here (the list doubles as the translator's checklist). @@ -660,6 +185,34 @@ local L = { ["Friendly nameplates turned on, so nearby non-group players can be listed."] = "Friendly nameplates turned on, so nearby non-group players can be listed.", ["Nameplate settings are unavailable while dead."] = "Nameplate settings are unavailable while dead.", ["Next buff: %s — %s"] = "Next buff: %s — %s", + ["Complement Nearby Blessings"] = "Complement Nearby Blessings", + ["Offer a different known blessing outside your group if another Paladin already provides your preferred blessing. Explicit rules still take precedence."] = "Offer a different known blessing outside your group if another Paladin already provides your preferred blessing. Explicit rules still take precedence.", + ["Blessing: complement another Paladin"] = "Blessing: complement another Paladin", + ["Usage: /br bless complement on|off"] = "Usage: /br bless complement on|off", + ["Learn a blessing before changing this setting."] = "Learn a blessing before changing this setting.", + ["Complement Nearby Blessings: %s"] = "Complement Nearby Blessings: %s", + ["Disable Friendly Nameplates"] = "Disable Friendly Nameplates", + ["Show Friendly Health Bars"] = "Show Friendly Health Bars", + ["Show Friendly Names Only"] = "Show Friendly Names Only", + ["Restore Nameplates"] = "Restore Nameplates", + ["No nameplate changes to restore."] = "No nameplate changes to restore.", + ["Some nameplate settings could not be restored. Try again or check the game's options."] = "Some nameplate settings could not be restored. Try again or check the game's options.", + ["Restored your previous nameplate settings."] = "Restored your previous nameplate settings.", + ["Couldn't change friendly nameplate style. Check the game's nameplate settings."] = "Couldn't change friendly nameplate style. Check the game's nameplate settings.", + ["Friendly nameplates now show names only."] = "Friendly nameplates now show names only.", + ["Friendly nameplates can show health bars again."] = "Friendly nameplates can show health bars again.", + ["Couldn't turn off friendly nameplates. Check the game's nameplate settings."] = "Couldn't turn off friendly nameplates. Check the game's nameplate settings.", + ["Friendly nameplates turned off. Your group, target, and mouseover are still checked."] = "Friendly nameplates turned off. Your group, target, and mouseover are still checked.", + ["Usage: /br plates on|off|names|bars|restore"] = "Usage: /br plates on|off|names|bars|restore", + ["Macro controls are unavailable. Bind Cast next buff with /br key instead."] = "Macro controls are unavailable. Bind Cast next buff with /br key instead.", + ["Rename your custom BuffRadar macro first, or bind Cast next buff with /br key."] = "Rename your custom BuffRadar macro first, or bind Cast next buff with /br key.", + ["Your general macro slots are full. Make room or bind Cast next buff with /br key."] = "Your general macro slots are full. Make room or bind Cast next buff with /br key.", + ["Close the macro editor before creating the BuffRadar macro."] = "Close the macro editor before creating the BuffRadar macro.", + ["Couldn't save the BuffRadar macro. Bind Cast next buff with /br key instead."] = "Couldn't save the BuffRadar macro. Bind Cast next buff with /br key instead.", + ["Place the BuffRadar macro on an action bar. It follows the next buff automatically."] = "Place the BuffRadar macro on an action bar. It follows the next buff automatically.", + ["Bind a controller button to BuffRadar's Cast next buff, or put /br macro on an action bar."] = "Bind a controller button to BuffRadar's Cast next buff, or put /br macro on an action bar.", + ["/br gamepad - set up controller buffing"] = "/br gamepad - set up controller buffing", + ["Cast next buff works with a keyboard or controller and does not fire in combat."] = "Cast next buff works with a keyboard or controller and does not fire in combat.", ["Group buff key: %s"] = "Group buff key: %s", ["Group blessing would conflict with a player exception."] = "Group blessing would conflict with a player exception.", ["Could not check reagent: %s."] = "Could not check reagent: %s.", @@ -1004,8 +557,7 @@ local L = { setmetatable(L, { __index = function(_, k) return k end }) do local loc = (GetLocale and GetLocale()) or "enUS" - local ns = select(2, ...) - local pack = ns and ns.Locales and ns.Locales[loc] + local pack = namespace.Locales and namespace.Locales[loc] if type(pack) == "table" then for k, v in pairs(pack) do if type(v) == "string" then L[k] = v end end end @@ -1117,7 +669,6 @@ function X.FriendlyPlatesOn() end end end -X.friendlyPlateCVars = { "nameplateShowFriendlyPlayers", "nameplateShowFriends" } -- Major cities. Matched by map ID (both the classic-era and modern ID sets, since the -- Forever client could use either) and by zone name as a fallback. @@ -1274,7 +825,6 @@ local function SafeString(v) local ok, s = pcall(tostring, v) return ok and s or nil end -X.Readable = Readable -- A unit flag the client may refuse to answer: true or false when it answers, -- nil when the value is restricted. Callers decide what an unknown means, @@ -1371,9 +921,26 @@ do end end - function X.ReadBuff(unit, i) - -- done, name, expirationTime, complete (only when done) - local name, expiry + local function SourceOwner(source) + if not Readable(source) or type(source) ~= "string" or source == "" then return "unknown" end + if source == "player" or source == "pet" then return "mine" end + -- Use readable identities rather than assuming UnitIsUnit's false + -- means a different caster on a restricted unit. + local caster, player = X.UnitGUIDOf(source), X.UnitGUIDOf("player") + if caster and player then return caster == player and "mine" or "other" end + return "unknown" + end + + local function AuraOwner(aura) + local ok, mine = pcall(GetField, aura, "isFromPlayerOrPlayerPet") + if ok and Readable(mine) and type(mine) == "boolean" then return mine and "mine" or "other" end + local sourceOK, source = pcall(GetField, aura, "sourceUnit") + 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) if not definitive then return true, nil, nil, false end @@ -1381,11 +948,14 @@ do local nameOK, value = pcall(GetField, aura, "name") if nameOK then name = value end expiry = AuraExpiration(aura) + if withOwner then owner = AuraOwner(aura) end elseif UnitBuff then - local ok, value, _, _, _, _, expiration = pcall(UnitBuff, unit, i) + -- 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 if type(value) == "nil" then return true, nil, nil, true end name, expiry = value, expiration + if withOwner then owner = SourceOwner(source) end else return true, nil, nil, false end @@ -1394,7 +964,7 @@ do return false 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 + return false, name, expiry, nil, owner end local function SecondsLeft(expiry, now) @@ -1442,6 +1012,57 @@ do end return nil, complete and "absent" or "unknown" end + + -- Only used when the nearby complement option is on. The index fallback + -- shares one walk across all the blessing families for this recipient. + local owners, ownersComplete = {}, false + local function MergeOwner(a, b) + if a == "mine" or b == "mine" then return "mine" end + if a == "unknown" or b == "unknown" then return "unknown" end + if a == "other" or b == "other" then return "other" end + return "absent" + end + + local function IndexedOwner(unit, name) + if X.blessingScanUnit ~= unit then + wipe(owners) + X.blessingScanUnit, ownersComplete = unit, false + local now, readableNames = GetTime(), true + for i = 1, 40 do + local done, auraName, expiry, ended, owner = X.ReadBuff(unit, i, true) + if done then ownersComplete = ended and readableNames; break end + if not auraName then + readableNames = false + elseif not expiry or expiry == 0 or expiry > now then + owners[auraName] = MergeOwner(owners[auraName], owner) + end + end + end + if owners[name] == "mine" then return "mine" end + if not ownersComplete then return "unknown" end + return owners[name] or "absent" + end + + local function NamedOwner(unit, name) + local lookup = C_UnitAuras and C_UnitAuras.GetAuraDataBySpellName + if lookup then + local aura, definitive = X.QueryNamedAura(lookup, unit, name, "HELPFUL") + if definitive then + if not aura then return "absent" end + local expiry = AuraExpiration(aura) + if expiry and expiry ~= 0 and expiry <= GetTime() then return "absent" end + local owner = AuraOwner(aura) + if owner ~= "unknown" then return owner end + local indexed = IndexedOwner(unit, name) + return indexed ~= "absent" and indexed or "unknown" + end + end + return IndexedOwner(unit, name) + end + + function X.BlessingOwner(unit, names) + return MergeOwner(NamedOwner(unit, names[1]), NamedOwner(unit, names[2])) + end end --------------------------------------------------------------------------- @@ -1796,6 +1417,35 @@ function X.SetBlessingPreference(class, key) return true end +function X.SetBlessingComplement(enabled) + if not X.HasKnownBlessings() or X.PlayerSuspended() then return false end + db.blessingComplement = enabled == true + X.Refresh() + if X.RefreshConfig then X.RefreshConfig() end + return true +end + +function X.ComplementWorldBlessing(unit, class, preferred) + local owner = X.BlessingOwner(unit, preferred.names) + if owner ~= "other" then + -- With an unreadable caster, don't switch blessing or top up one that + -- could belong to a different Paladin. Regular missing-aura checks stay in force. + return preferred, owner == "unknown" and HasAny(unit, preferred.names, 0) == true + end + local alternate, uncertain + for _, key in ipairs(X.BLESSING_PRIORITY[class] or {}) do + local blessing = blessKnown[key] + if blessing and blessing.name ~= preferred.name then + local source = X.BlessingOwner(unit, blessing.names) + if source == "mine" then return blessing end -- keep our own alternate, even if an earlier one is now free + if source == "absent" and not alternate then alternate = blessing end + if source == "unknown" then uncertain = true end + end + end + if alternate and not uncertain then return alternate end + return preferred, true -- already covered; do not refresh another Paladin's copy +end + function X.AssignmentEnabled() return CLASSIC_FEATURES and db and db.assignmentEnabled == true or false end @@ -2128,16 +1778,6 @@ end -- keep/drop are scratch lists reused by CollectEntries. local Single = { holder = {}, spell = {}, keep = {}, drop = {} } ---------------------------------------------------------------------------- --- Enhancement state (1.4.0). One table on purpose: the main chunk is near --- Lua 5.1's 200-local limit, so new state lives here, not in new locals. --- session: session-only ignore set, Ignore.Key(name) -> true (never saved) --- dead / rezAt: group members seen dead, and when each was seen alive --- again -- a rezzed player has lost every buff and jumps the queue --- tally: per-buff coverage over group members from the latest scan, --- buff key -> { total = n, miss = n }; tallyUnits = members scanned ---------------------------------------------------------------------------- - -- 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). @@ -2201,7 +1841,6 @@ function X.ConsHas(unit, def) else complete = false end end end -X.listedBefore = X.listA -- guid -> true for names on the board last refresh function X.Track(unit) if not X.UnitPresent(unit) then return end @@ -2243,7 +1882,7 @@ local function Missing(unit, out, isGroup, isSelf, report, detail) if has == false then t.miss = t.miss + 1 end end end - if not reviewing then X.scanUnit = nil end -- fresh index scan for aura readers + if not reviewing then X.scanUnit, X.blessingScanUnit = nil, nil end -- fresh index scans for aura readers local n = 0 local unknown, checked local proposal, member @@ -2363,7 +2002,13 @@ local function Missing(unit, out, isGroup, isSelf, report, detail) elseif reviewing and blessingEligible then out[#out + 1] = bl.name elseif blessingEligible then - local has = HasAny(unit, bl.names) + local covered + if db.blessingComplement and not isGroup and isSelf == false and assignment == nil and not blessingSource then + local preferred = bl + bl, covered = X.ComplementWorldBlessing(unit, class, preferred) + if report == "why" and bl ~= preferred then detail.blessing = L["Blessing: complement another Paladin"] end + end + local has = covered or HasAny(unit, bl.names) if report then checked = true if has == nil then unknown = true end @@ -2521,8 +2166,6 @@ end -- Ignore.Key(): lowercase, spaces removed. "Name-Realm" ignores one player; -- a bare "Name" (every entry saved before 1.3.2) ignores that name on any realm. --------------------------------------------------------------------------- --- One table rather than separate locals: the file's main chunk is close to --- Lua 5.1's 200-local limit (see the config window section). -- index: Ignore.Key(name) -> name as stored in db.ignored -- realm: your own realm, filled in on first use local Ignore = { index = {} } @@ -2607,6 +2250,12 @@ function Ignore.UnitNames(unit) return realm and realm ~= "" and (name .. "-" .. realm) or name, name end +-- Your own "Name-Realm", for per-character settings. +function X.CharKey() + local full = Ignore.UnitNames("player") + return full +end + function Ignore.Has(full, short) if full and Ignore.index[Ignore.Key(full)] then return true end return short ~= nil and Ignore.index[Ignore.Key(short)] ~= nil @@ -3044,7 +2693,7 @@ function X.SpecSwap() local sc = db.specScales[key] if sc and sc ~= db.scale then db.scale = sc - if X.ApplyScaleNow then X.ApplyScaleNow() end + if X.ApplyGeometry then X.ApplyGeometry() end end end X.spec = key @@ -3351,31 +3000,8 @@ function X.ReadyReport(report) end end --- Settings export / import: one copyable string. Covers the window look, --- behavior toggles, buff toggles, rebuff timings and both ignore sets -- --- not positions, cast counts or stats (those belong to one machine / char). -X.EXPORT_KEYS = { "locked", "includeSelf", "avoidPvP", "autoHide", "rebuff", "scale", - "width", "cfgScale", "castMethod", "clickReg", "bgAlpha", "showTitle", "showBorder", - "playSound", "showCounter", "groupOnly", "pauseInCities", "groupCast", "groupCastMin", - "sortMode", "alertSound", "alertSounds", "buffPrio", "clickThrough", "muteInInstance", "showMinimap", "lowMana", - "sync", "requests", "joinDigest", "roleFilter", "showStrip", "idleFade", - "pill", "queueTag", "consumables", "buddySplit", "readyPost", "weaponWatch", "enterFlash", - "scanThrottle", "growUp", "theme", "autoThemePriority", "findBox", "durationBars", "raidMarkers", - "focusWatch", "pets", "auraWatch", "worldWatch", "drinkWatch", "twoCol", - "deathRecap", "wipeReport", "rowGap", "iconSize", - "tooltipLevel", "viewMode", "classColors", "showRealm", "nameTrim", - "scalePerSpec", "gripSnap", "tagSymbols", "reduceMotion", "rangeWatch", "assumeRange", - "fastAura", "modClick", "pullFlash", "fallSound" } - -local function Esc(v) return (tostring(v):gsub("%%", "%%25"):gsub(";", "%%3B"):gsub("=", "%%3D")) end -local function Unesc(v) return (v:gsub("%%3D", "="):gsub("%%3B", ";"):gsub("%%25", "%%")) end - --- X.Export, X.Import, plan strings, profiles and presets live in Profiles.lua --- since Slice E (Esc/Unesc stay here: the settings window takes Esc by value). - -- /br announce: post the group's missing buffs to party/raid chat (or --- print them locally when solo). Lives here, not in HandleSlash, to keep --- that function's upvalue count down. +-- print them locally when solo). function X.Announce() local report = X.GroupBuffReport() local note = X.GroupCoverageNote(report) @@ -4241,7 +3867,56 @@ function X.ReagentSummary(report) return string_format(L["Estimated group reagents (carried/needed): %s"], table.concat(parts, ", ")) end -function Bind(btn, unit, spell, isSelf, pick, gspell, gpick) +local function MacroArgument(value) + return type(value) == "string" and Readable(value) and value:find("%S") and not value:find("[%c;%[%]|]") +end + +local function ExactCastName(unit) + if CLASSIC_FEATURES then + -- On Forever the second return is a surname, not a realm. Use the + -- unmodified name for targeting, not a shortened name from the list. + local ok, first, surname = pcall(_G.UnitNameUnmodified or UnitName, unit) + if not ok or not MacroArgument(first) then return nil end + if type(surname) == "nil" then return first end + if not Readable(surname) then return nil end + if surname == "" then return first end + local constants = _G.Constants and _G.Constants.CharacterNameSeparatorConsts + local separator = constants and constants.CHARACTERNAME_SURNAME_SEPARATOR or " " + if MacroArgument(surname) then return first .. separator .. surname end + return nil + end + local ok, full = pcall(GetUnitName or UnitName, unit, true) + if ok and MacroArgument(full) then return full end +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+$") +end + +local function ExactCastMacro(name, text, hadTarget) + if not MacroArgument(text) then return nil end + -- A failed /targetexact must not leave a friendly previous target (or + -- auto-self-cast) eligible. Restore the target, or the lack of one. + local macro = "/cleartarget\n/targetexact " .. name .. "\n/cast [help,nodead] " .. text + .. (hadTarget and "\n/targetlasttarget" or "\n/cleartarget") + if #macro <= 255 then return macro end +end + +function X.ExactCastBody(unit, text, shifted, hadTarget) + local name = ExactCastName(unit) + if name then + return ExactCastMacro(name, text, hadTarget), shifted and ExactCastMacro(name, shifted, hadTarget) + end +end + +local function UnitCastMacro(unit, text) + if MacroArgument(text) then + local macro = "/cast [@" .. unit .. ",help,nodead] " .. text + if #macro <= 255 then return macro end + end +end + +function Bind(btn, unit, spell, isSelf, pick, gspell, gpick, hadTarget) btn:SetAttribute("shift-type1", nil) btn:SetAttribute("shift-spell1", nil) btn:SetAttribute("shift-unit1", nil) @@ -4283,14 +3958,13 @@ function Bind(btn, unit, spell, isSelf, pick, gspell, gpick) end return end - local ok, name = pcall(GetUnitName or UnitName, unit, true) - name = ok and SafeString(name) or nil -- a protected name can't build a macro: no cast - if name and name ~= "" then + local macro, shifted = X.ExactCastBody(unit, CastText(spell, pick), gspell and CastText(gspell, gpick), hadTarget) + if macro then btn:SetAttribute("type", "macro") - btn:SetAttribute("macrotext", "/targetexact " .. name .. "\n/cast " .. CastText(spell, pick) .. "\n/targetlasttarget") - if gspell then + btn:SetAttribute("macrotext", macro) + if shifted then btn:SetAttribute("shift-type1", "macro") - btn:SetAttribute("shift-macrotext1", "/targetexact " .. name .. "\n/cast " .. CastText(gspell, gpick) .. "\n/targetlasttarget") + btn:SetAttribute("shift-macrotext1", shifted) end end elseif method == "id" and pick and pick.id then @@ -4304,32 +3978,24 @@ function Bind(btn, unit, spell, isSelf, pick, gspell, gpick) btn:SetAttribute("shift-spell1", (gpick and gpick.id) or gspell) end else - local text = (method == "rank") and CastText(spell, pick) or spell - btn:SetAttribute("type", "macro") + local text = UnitCastMacro(unit, method == "rank" and CastText(spell, pick) or spell) + btn:SetAttribute("type", text and "macro" or nil) btn:SetAttribute("unit", nil) btn:SetAttribute("spell", nil) - btn:SetAttribute("macrotext", "/cast [@" .. unit .. ",help,nodead] " .. text) - if gspell then - local gtext = (method == "rank") and CastText(gspell, gpick) or gspell + btn:SetAttribute("macrotext", text) + local shifted = gspell and UnitCastMacro(unit, method == "rank" and CastText(gspell, gpick) or gspell) + if text and shifted then btn:SetAttribute("shift-type1", "macro") - btn:SetAttribute("shift-macrotext1", "/cast [@" .. unit .. ",help,nodead] " .. gtext) + btn:SetAttribute("shift-macrotext1", shifted) end end end X.PickRank, X.CastText = PickRank, CastText end -- Bind block ---------------------------------------------------------------------------- --- UI ---------------------------------------------------------------------------- -local frame, title, countText, emptyText, overflowText, combatText, nextBtn, coverText -local OpenConfig, RefreshConfig, MakeMacro -- defined further down -local QueueRefresh -- assigned to the event coalescer further down -local BuildMinimapButton, RefreshMinimapButton -- assigned in the minimap section further down -local footerText --- (X.sessionCasts, the cast tracking, the double-buffered listed sets and --- X.recentlyGone live on X since 1.4.0 -- see the enhancement state block.) -X.lastSoundAt = 0 -- shared with Coordination.lua (Slice E) +local MakeMacro -- defined with the macro helpers below +local QueueRefresh -- assigned to the event coalescer below +X.lastSoundAt = 0 -- shared with Coordination.lua local function InInstanceNow() if IsInInstance then @@ -4352,27 +4018,6 @@ local function PlayAlert(kind) if PlaySoundFile then pcall(PlaySoundFile, SOUND_FILE, "Master") end end -local function UpdateCounter() - if not footerText then return end - local show = db.showCounter and true or false - if (footerText:IsShown() and true or false) ~= show then footerText:SetShown(show) end - local total = db.castsTotal or 0 - -- The counter shares its row with the settings gear and stops short of the - -- resize grip, so a narrow window used to cut it to "39 all-t...". Width is - -- part of the cache key so a resize re-fits the line, not just a new cast. - local room = footerText:GetWidth() or 0 - if X.sessionCasts ~= X.lastCounterSession or total ~= X.lastCounterTotal - or room ~= X.lastCounterRoom then - X.lastCounterSession, X.lastCounterTotal, X.lastCounterRoom = X.sessionCasts, total, room - footerText:SetText(string_format(L["Casts: |cffffffff%d|r this session · |cffffffff%d|r all-time"], - X.sessionCasts, total)) - if room > 0 and footerText:GetStringWidth() > room then - footerText:SetText(string_format(L["Casts: |cffffffff%d|r / |cffffffff%d|r"], - X.sessionCasts, total)) - end - end -end - do local castTargetFailureGlobals = { "SPELL_FAILED_LINE_OF_SIGHT", "ERR_SPELL_FAILED_LINE_OF_SIGHT", @@ -4417,7 +4062,7 @@ local function SpellID(value) end local function CastTargetNames(unit, macro) - local exact = macro and macro:match("^/targetexact ([^\r\n]+)") + local exact = macro and (macro:match("^/targetexact ([^\r\n]+)") or macro:match("\n/targetexact ([^\r\n]+)")) if exact then return exact, exact:lower() end -- Forever's NameUtil combines the two character-name fields using the -- client's surname separator. Treat the resulting name as an exact alias. @@ -4455,7 +4100,7 @@ local function CastTargetNames(unit, macro) localTarget and name:lower() or nil, preferred and preferred:lower() or nil end -function X.BeginCastClick(btn, button, down, label) +function X.BeginCastClick(btn, button, down, label, barBody) local entry = btn.entry Trace(label .. " pre", button, down and "down" or "up", entry and entry.missing and entry.missing[1]) recentFailure = nil @@ -4477,7 +4122,7 @@ function X.BeginCastClick(btn, button, down, label) local guid = entry.castGuid or entry.guid -- folded rows borrow a real recipient local ok, currentGUID = pcall(UnitGUID, entry.unit) if not guid or not ok or StringField(currentGUID) ~= guid then return end - local macro = action == "macro" and StringField(btn:GetAttribute(shift and "shift-macrotext1" or "macrotext")) + local macro = action == "macro" and (barBody or StringField(btn:GetAttribute(shift and "shift-macrotext1" or "macrotext"))) if action == "macro" and not macro then return end local nameOfTarget, full, short, preferred = CastTargetNames(entry.unit, macro) if not nameOfTarget then return end @@ -4505,7 +4150,7 @@ function X.BeginCastClick(btn, button, down, label) local keyDown = not isRow and GetCVarBool and GetCVarBool("ActionButtonUseKeyDown") dispatch = { button = btn, spell = name, expectedID = id, guid = guid, who = nameOfTarget, full = full, short = short, preferred = preferred, terminals = {}, ambiguous = ambiguous, - press = press, deferred = (isRow or (not not down) == (not not keyDown)) and not entry.pet } + press = press, deferred = (isRow or label == "bar macro" or (not not down) == (not not keyDown)) and not entry.pet } Trace("expected", name, id, nameOfTarget, guid) end @@ -4525,7 +4170,7 @@ local function ApplyCast(cast, terminal, targetError) 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 - UpdateCounter() + X.UpdateCounter() local key = X.KeyOfName(name) if key then X.SyncSend(key, cast.guid) end X.queueAt = GetTime() @@ -4693,253 +4338,6 @@ function X.ClearCastIntent() end end -- cast tracking ---------------------------------------------------------------------------- --- Coordination (cast sync, caster coordination, chat requests, context --- checks, join digest) lives in Coordination.lua since 1.15.34 (file split --- Slice E); it reaches this file's locals through X.coordAPI (bottom). ---------------------------------------------------------------------------- - -local rows = {} -local built = false - -local function ClassColor(class) - local c = (CUSTOM_CLASS_COLORS and CUSTOM_CLASS_COLORS[class]) - or (RAID_CLASS_COLORS and RAID_CLASS_COLORS[class]) - if c then return c.r, c.g, c.b end - return 1, 1, 1 -end - --- The window is ALWAYS anchored by its top-left corner, and only by that --- corner. Refresh() changes the frame's height as names are added and --- removed; with any other anchor (the old default was LEFT, and a drag --- could leave CENTER or BOTTOM) SetHeight grows/shrinks the frame around --- that point, so the top edge -- and the whole window -- jumps up and down --- as the list changes. Anchored at TOPLEFT, the top edge stays exactly --- where the user put it and the list grows/shrinks downward only. --- Saved positions are therefore stored as a TOPLEFT anchor: --- { "TOPLEFT", , x, y } --- (Same fix as Forever edition 1.2.4; the two editions share the --- BuffRadarDB saved variable format, so positions saved by either --- edition's fixed version load unchanged in the other.) -local function SavePosition() - if db.growUp then - -- Grow-up form: the bottom-left corner is the anchor (see X.ApplyAnchor). - local left, bottom = frame:GetLeft(), frame:GetBottom() - if left and bottom then - frame:ClearAllPoints() - frame:SetPoint("BOTTOMLEFT", UIParent, "BOTTOMLEFT", left, bottom) - db.point = { "BOTTOMLEFT", "BOTTOMLEFT", left, bottom } - if db.charPoint then - local k = X.CharKey() - if k then db.pointByChar[k] = db.point end - end - return - end - end - local left, top = frame:GetLeft(), frame:GetTop() - if left and top then - -- Store the top-left corner in screen coordinates (origin bottom-left; - -- GetLeft/GetTop and SetPoint offsets use the same coordinate system - -- for this frame). Re-anchor in that form right away, too: - -- StopMovingOrSizing can leave the frame anchored by whatever point - -- the drag used, which would bring the jumping back until next reload. - frame:ClearAllPoints() - frame:SetPoint("TOPLEFT", UIParent, "BOTTOMLEFT", left, top) - db.point = { "TOPLEFT", "BOTTOMLEFT", left, top } - else - -- Position not measurable yet (frame never laid out): keep whatever - -- anchor the drag left rather than saving nothing. RestorePosition - -- converts a non-TOPLEFT anchor like this one on the next load. - local p, _, rp, x, y = frame:GetPoint() - if p then db.point = { p, rp, x, y } end - end - if db.charPoint then - local k = X.CharKey() - if k and db.point then db.pointByChar[k] = db.point end - end -end - --- Where a named anchor point sits inside a frame, as fractions of its --- width (from the left edge) and height (from the bottom edge). -local POINT_FRACTION = { - TOPLEFT = { 0, 1 }, TOP = { 0.5, 1 }, TOPRIGHT = { 1, 1 }, - LEFT = { 0, 0.5 }, CENTER = { 0.5, 0.5 }, RIGHT = { 1, 0.5 }, - BOTTOMLEFT = { 0, 0 }, BOTTOM = { 0.5, 0 }, BOTTOMRIGHT = { 1, 0 }, -} - --- Forget the saved window spot (shared and per-character), so the next --- RestorePosition lands on the default anchor. -function X.ClearSavedPoint() - db.point = nil - if db.charPoint then - local k = X.CharKey() - if k then db.pointByChar[k] = nil end - end -end - -local function RestorePosition() - 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 - X.ClearSavedPoint() - end - 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]) - return - end - if not db.point then - -- Default spot, in top-left form: the pre-1.3.1 default anchored the - -- frame's LEFT point at (40, 80) from the screen's left edge; at the - -- height the frame is built with, that puts the top-left corner half - -- a build-height above it. - frame:SetPoint("TOPLEFT", UIParent, "LEFT", 40, 80 + (HEADER_H + 30) / 2) - return - end - local p, rp, x, y = db.point[1], db.point[2], db.point[3], db.point[4] - local f = POINT_FRACTION[p] - if p == "TOPLEFT" or not f then - frame:SetPoint(p, UIParent, rp, x, y) - return - end - -- Legacy save (1.3.0 and earlier stored the drag anchor verbatim, e.g. - -- LEFT or CENTER): convert it to a TOPLEFT anchor against the same - -- point of UIParent. The top-left corner sits (-fx * W, (1 - fy) * H) - -- from the old anchor point, so with the frame's current size the - -- window does not move at all in this conversion -- it just stops - -- moving afterwards, when its height starts changing. The height at - -- drag time was never saved, so this preserves the position as - -- restored now, not necessarily the exact top edge seen while dragging. - local w, h = frame:GetWidth(), frame:GetHeight() - db.point = { "TOPLEFT", rp, x - f[1] * w, y + (1 - f[2]) * h } - frame:SetPoint("TOPLEFT", UIParent, rp, db.point[3], db.point[4]) -end - -local function Row_OnEnter(self) - if not self.entry then return end - local e = self.entry - GameTooltip:SetOwner(self, "ANCHOR_RIGHT") - if X.UnitPresent(e.unit) and X.UnitGUIDOf(e.unit) == e.guid then - GameTooltip:SetUnit(e.unit) - else - 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 - end - end - if e.groupCast then - GameTooltip:AddLine(L["Group version — one cast buffs the whole party."], 0.4, 0.8, 1) - end - -- Tooltip detail (1.10.0): minimal stops at the cast line. - if db.tooltipLevel == "minimal" then GameTooltip:Show() return end - GameTooltip:AddLine(L["Right-click to ignore this player."], 0.6, 0.6, 0.6) - GameTooltip:AddLine(L["Shift-right-click to ignore for this session only."], 0.6, 0.6, 0.6) - if #e.missing > 1 then - local rest = {} - for i = 2, #e.missing do rest[#rest + 1] = e.missing[i] end - GameTooltip:AddLine(string_format(L["Still needs: %s"], table.concat(rest, ", ")), 0.8, 0.8, 0.8, true) - end - -- The full picture (1.7.0): buffs this player HAS from your set, with - -- the time left on each, soonest first — so a hover answers "what do - -- they still need, and what's about to run out?" in one look. - if X.UnitPresent(e.unit) then - local missSet = {} - for _, m in ipairs(e.missing) do missSet[m] = true end - local have, seenHave = {}, {} - for _, def in ipairs(myBuffs) do - local nm = def.name - if nm and not seenHave[nm] and not missSet[nm] then - seenHave[nm] = true - local left = X.Remaining(e.unit, nm) - if left and left < math_huge and left > 0 then - have[#have + 1] = { name = nm, left = left } - end - end - end - table_sort(have, function(x, y) return x.left < y.left end) - for i = 1, math_min(6, #have) do - local h = have[i] - local t = h.left >= 90 and string_format(L["~%dm left"], math_floor(h.left / 60)) - or string_format(L["~%ds left"], math_floor(h.left)) - GameTooltip:AddLine(h.name .. " — " .. t, 0.55, 0.85, 0.55) - end - end - -- Full tooltips (1.10.0) add the context lines: class and group, the - -- range in words, and which other classes could cast the first buff. - if db.tooltipLevel == "full" then - 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 - 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). - local _, myClass = UnitClass("player") - local names, seenCls = {}, {} - for _, d in ipairs(BUFF_DEFS) do - local dn - if d.choices then dn = SpellName(d.choices[1][1], d.choices[1][2]) - else dn = SpellName(d.id, d.name) end - if dn == e.missing[1] then - for c in pairs(d.classes or ALL) do - if c ~= myClass and not seenCls[c] then - seenCls[c] = true - names[#names + 1] = c:sub(1, 1) .. c:sub(2):lower() - end - end - end - end - table_sort(names) - if #names > 0 then - GameTooltip:AddLine("Also castable by: " .. table.concat(names, ", "), 0.7, 0.7, 0.7, true) - end - end - GameTooltip:Show() -end - --- The name field stops this far short of the row's right edge to leave --- room for the buff icons; it follows the icon size (1.10.0). -local function IconInset() - local isz = (db.iconSize or 0) > 0 and db.iconSize or (db.compact and 12 or 16) - return MAX_ICONS * (isz + 2) + 4 -end - -function X.InstallCombatDriver(button, snippet) - if not RegisterStateDriver then return false end - local ok, accepted = pcall(button.SetAttribute, button, "_onstate-combat", snippet) - if not ok or accepted == false then return false end - ok, accepted = pcall(RegisterStateDriver, button, "combat", "[@player,dead][combat] combat; nocombat") - return ok and accepted ~= false -end - function X.RowTargetMatches(e) local guid = e and (e.castGuid or e.guid) if not guid or not e.unit then return false end @@ -4947,1241 +4345,88 @@ function X.RowTargetMatches(e) return ok and SafeString(current) == guid end -function X.RowMouseHeld() - for button, expires in pairs(X.rowMouseButtons) do - local down = X.ReadUnitBool(_G.IsMouseButtonDown, button) - if down == false or (down == nil and GetTime() >= expires) then - X.rowMouseButtons[button] = nil - end - end - return next(X.rowMouseButtons) ~= nil -end -X.rowMouseButtons = {} +--------------------------------------------------------------------------- +-- Queue refresh +--------------------------------------------------------------------------- +X.farNow, X.farPrev = {}, {} -- range-watch sets shared with Wizard.lua + +-- While scanning is idle the ticker waits for a spell, zone or roster event. +local refreshIdle = false -function X.RowWheel(_, delta) - if delta ~= 0 then X.ScrollRows(delta < 0 and 1 or -1) end +local function ClearCastQueue() + X.ClearKeybindCasts() + X.SyncCastMacro(true) end --- Row hover highlight (1.15.34): a faint wash in the theme's border colour --- instead of the bright quest-title glow. The engine shows a button's --- highlight texture only while the mouse is over it, so no script is --- needed; ApplyAppearance re-tints every row when the theme changes. -X.ROW_HOVER_ALPHA = 0.15 -function X.TintRowHover(b) - local hl = b and b.GetHighlightTexture and b:GetHighlightTexture() - if not hl or not hl.SetVertexColor then return end - local bc = X.ThemeBorder() - hl:SetVertexColor(bc[1], bc[2], bc[3], X.ROW_HOVER_ALPHA) +local function SuspendBuffing() + refreshIdle = true + X.ResetCastTracking() + X.SuspendWindow() + X.SyncCastMacro(true) end -local function CreateRow(i) - local b = CreateFrame("Button", "BuffRadarRow" .. i, frame, - "SecureActionButtonTemplate,SecureHandlerStateTemplate") - -- Anchored on both sides, so rows follow the window's width when it's resized. - b:SetHeight(ROW_H) - b:SetPoint("TOPLEFT", frame, "TOPLEFT", 6, -HEADER_H - (i - 1) * ROW_H) - b:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -6, -HEADER_H - (i - 1) * ROW_H) - if db.clickReg == "down" then - b:RegisterForClicks("AnyDown") - elseif db.clickReg == "up" then - b:RegisterForClicks("AnyUp") +function X.UpdatePlayerLife(event) + local wasDead = X.playerDead + if event == "PLAYER_DEAD" then + X.playerDead = true + X.lifeCheckPending = nil else - b:RegisterForClicks("AnyUp", "AnyDown") - end - b:SetHighlightTexture("Interface\\Buttons\\WHITE8X8", "ADD") - X.TintRowHover(b) - -- Right-click only ignores (see the OnClick hook below). Bind() sets the plain - -- "type" attribute, which the secure template uses for EVERY mouse button - -- unless a button-specific one exists; this "type2" override is a made-up - -- action the template doesn't know, so a right-click casts nothing. - -- Bind() never touches "type2", so this holds for the row's lifetime. - b:SetAttribute("type2", "buffradarignore") - b.combatDriver = X.InstallCombatDriver(b, [[ - if newstate == "combat" then - self:SetAttribute("type", nil) - self:SetAttribute("spell", nil) - self:SetAttribute("unit", nil) - self:SetAttribute("macrotext", nil) - self:SetAttribute("shift-type1", nil) - self:SetAttribute("shift-spell1", nil) - self:SetAttribute("shift-unit1", nil) - self:SetAttribute("shift-macrotext1", nil) - end - ]]) - - b.portrait = b:CreateTexture(nil, "ARTWORK") - b.portrait:SetSize(ROW_H - 2, ROW_H - 2) - b.portrait:SetPoint("LEFT", 1, 0) - if b.CreateMaskTexture and b.portrait.AddMaskTexture then - local m = b:CreateMaskTexture() - m:SetTexture("Interface\\CharacterFrame\\TempPortraitAlphaMask", - "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE") - m:SetAllPoints(b.portrait) - b.portrait:AddMaskTexture(m) - end - - b.cMissing = {} -- render cache: icons currently drawn - b.icons = {} - for j = 1, MAX_ICONS do - local t = b:CreateTexture(nil, "ARTWORK") - t:SetSize(16, 16) - t:SetTexCoord(0.08, 0.92, 0.08, 0.92) - if j == 1 then - t:SetPoint("RIGHT", b, "RIGHT", -2, 0) - else - t:SetPoint("RIGHT", b.icons[j - 1], "LEFT", -2, 0) - end - b.icons[j] = t - end - - b.name = b:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall") - b.name:SetPoint("LEFT", b.portrait, "RIGHT", 6, 0) - b.name:SetPoint("RIGHT", b, "RIGHT", -(IconInset()), 0) - b.name:SetJustifyH("LEFT") - 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") - b.tint:SetTexture("Interface\\Buttons\\WHITE8X8") - b.tint:SetPoint("TOPLEFT", b, "TOPLEFT", 0, -1) - b.tint:SetPoint("BOTTOMLEFT", b, "BOTTOMLEFT", 0, 1) - b.tint:SetWidth(3) - b.tint:Hide() - b.bar = b:CreateTexture(nil, "ARTWORK") - b.bar:SetTexture("Interface\\Buttons\\WHITE8X8") - b.bar:SetPoint("BOTTOMLEFT", b, "BOTTOMLEFT", 2, 1) - b.bar:SetHeight(3) - b.bar:SetWidth(10) - b.bar:Hide() - -- Raid marker badge (1.8.0): the player's raid target icon, drawn over - -- the portrait's top-left corner. - b.marker = b:CreateTexture(nil, "OVERLAY") - b.marker:SetSize(12, 12) - b.marker:SetPoint("TOPLEFT", b, "TOPLEFT", 1, -1) - b.marker:Hide() - - -- Short status tag under the name ("recently rezzed"); shares the slot - -- with the out-of-range label, which wins when both would apply. - b.tag = b:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall") - b.tag:SetPoint("TOPLEFT", b.name, "BOTTOMLEFT", 0, -1) - b.tag:SetTextColor(1, 0.85, 0.4) - b.tag:Hide() - - -- HookScript, never SetScript: SetScript would REPLACE the - -- SecureActionButtonTemplate's own OnClick (SecureActionButton_OnClick), - -- which is what actually performs the cast -- with it replaced, clicks run - -- only this handler and nothing is ever cast (the 1.2.0/1.2.1 bug). - b:HookScript("OnClick", function(self, button, down) - if button ~= "RightButton" or InCombatLockdown() then return end - -- With AnyUp+AnyDown registered, OnClick fires twice per physical click; - -- toggle on exactly one phase (release, unless casts trigger on press). - if down ~= (db.clickReg == "down") then return end - local e = self.entry - if not e or not db or e.spell then return end - local short = e.pet and SafeString(e.name) or e.sortName - if short == "" then short = nil end - local who = e.fullName or short -- Name-Realm: ignores this one player only - if not who then return end - if _G.IsShiftKeyDown and _G.IsShiftKeyDown() then - local k = Ignore.Key(who) - if X.session[k] then - X.session[k] = nil - Print("No longer ignoring " .. who .. " for this session.") - else - X.session[k] = true - Print("Ignoring " .. who .. " for this session only (not saved).") - end - if QueueRefresh then QueueRefresh() end - return - end - if Ignore.Has(e.fullName, short) then - -- (a row still showing an ignored player: it drops off on the next refresh) - local removed = Ignore.Remove(who) - 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 dead = X.ReadUnitBool(_G.UnitIsDeadOrGhost, "player") + if dead ~= nil then X.playerDead = dead end + if event == "PLAYER_UNGHOST" and dead == nil then X.playerDead = false end + if event == "PLAYER_UNGHOST" or event == "PLAYER_ALIVE" then + -- The synchronous event can precede the unit flag update. Recheck on + -- the existing tick until the client confirms that casting can resume. + X.lifeCheckPending = X.playerDead or nil + elseif not X.playerDead then + X.lifeCheckPending = nil end + end + if X.playerDead then + SuspendBuffing() + elseif wasDead then + X.RefreshMinimapButton() if QueueRefresh then QueueRefresh() end - end) - b:HookScript("PreClick", function(self, button, down) - if button == "LeftButton" and not InCombatLockdown() and self.bGuid then - local press = not down and X.rowLeftPress - local changed = press and (press.row ~= self or press.guid ~= self.bGuid - or press.unit ~= self.bUnit or press.spell ~= self.bSpell) - if changed or not X.RowTargetMatches(self.entry) then - X.ClearRowCast(self) - self.entry, self.guid = nil, nil - if QueueRefresh then QueueRefresh() end - return - end - end - X.BeginCastClick(self, button, down, "click") - end) - b:HookScript("PostClick", function(self, button, down) - X.EndCastClick(self, button, down, "click") - if button == "LeftButton" and not down then X.rowLeftPress = nil end - end) - b:SetScript("OnEnter", Row_OnEnter) - b:SetScript("OnLeave", function() GameTooltip:Hide() end) - b:HookScript("OnMouseDown", function(self, button) - if button == "LeftButton" or button == "RightButton" then X.rowMouseButtons[button] = GetTime() + 1 end - if button == "LeftButton" then - -- The mouse-up notification may precede the up-phase secure click. - -- Keep the presented binding through dispatch, independently of that notification. - X.rowLeftPress = { row = self, guid = self.bGuid, unit = self.bUnit, spell = self.bSpell } - end - end) - b:HookScript("OnMouseUp", function(_, button) - X.rowMouseButtons[button] = nil - end) - b:SetScript("OnMouseWheel", X.RowWheel) - b:EnableMouseWheel(false) - b:Hide() - rows[i] = b -end - -local grip -- width resize grip, bottom-right corner (built in BuildUI) - --- Color themes (1.8.0): a theme is a background color + border color pair. --- Picking one sets both; picking a custom background color afterwards --- switches the theme back to "custom" (border returns to the default). - --- Saved themes (1.10.0): your own background + border pairs, kept in --- db.customThemes, usable anywhere a built-in theme is. -function X.SavedTheme(name) - if not db or not name then return nil end - local id = name:lower() - if X.THEMES[id] or id == "custom" then return nil end - for _, t in ipairs(db.customThemes or {}) do - if t.name:lower() == id then - return { label = t.name, bg = t.bg, border = t.border } - end end - return nil + if wasDead ~= X.playerDead and event ~= "PLAYER_LOGIN" then X.SendCover() end end -function X.ThemeDef(name) - if not name then return nil end - return X.THEMES[name:lower()] or X.SavedTheme(name) +local function ScanConfirmsGroupBuffed() + if X.scanHasUnknownBuffs or X.scanHasMissingBuffs or X.scanNameFiltered then return false end + local size = X.ReadUnitNumber(_G.GetNumGroupMembers) + return size ~= nil and size > 1 and X.tallyUnits == size end --- The cycle order: built-in themes followed by your saved themes. -function X.ThemeOrder() - local order = {} - for _, k in ipairs(X.THEME_ORDER) do order[#order + 1] = k end - if db then - for _, t in ipairs(db.customThemes or {}) do - local id = t.name:lower() - if not X.THEMES[id] and id ~= "custom" then order[#order + 1] = t.name end - end +-- Focus is outside the group tallies. Pass display text, not aura reads, +-- back to the window. +local focusMissing = {} +local function FocusLine() + local valid, isSelf = Valid("focus") + if not valid then return end + local name = X.UnitNameOf("focus") + if not name then return end + local count = Missing("focus", focusMissing, false, isSelf) + if count > 0 then + return "Focus " .. name .. ": needs " .. table.concat(focusMissing, ", ", 1, math_min(count, 3)) + .. (count > 3 and (" +" .. (count - 3)) or "") end - return order + if not X.auraUnknown then return "Focus " .. name .. ": buffed" end end -function X.EffectiveTheme() - if db and db.theme == X.AUTO_THEME_ID then - return X.THEMES[X.autoThemeResolved or "midnight"] +local function PauseReason() + if db.pauseInCities and InMajorCity() then return L["Paused in a major city."], true end + if db.pauseInBG then + local instance = InInstanceNow() + if instance == "pvp" or instance == "arena" then return L["Paused in a battleground."], true end end - return db and X.ThemeDef(db.theme) -end - -function X.ThemeBorder() - local t = X.EffectiveTheme() - if t then return t.border end - return { 0.35, 0.55, 0.8 } + if db.pauseTaxi and _G.UnitOnTaxi then + local ok, onTaxi = pcall(_G.UnitOnTaxi, "player") + if ok and onTaxi then return L["Paused on a flight path."], true end + end + if db.lowMana and db.lowMana > 0 and X.LowMana() then return L["Low mana -- buffing paused."] end end -function X.ThemeBackground() - if db and db.theme == X.AUTO_THEME_ID then - return X.EffectiveTheme().bg - end - return db and db.bgColor or DEFAULTS.bgColor -end - -function X.ThemeLabel(detail) - if db and db.theme == X.AUTO_THEME_ID then - if detail then - return string_format(L["Auto (%s)"], X.EffectiveTheme().label) - end - return L["Auto"] - end - local t = db and X.ThemeDef(db.theme) - return t and t.label or "Custom" -end - -function X.AutoThemeStatus() - if not db or db.theme ~= X.AUTO_THEME_ID then - return string_format(L["Auto is off. Current theme: %s."], X.ThemeLabel()) - end - if not X.autoThemeAddon then return L["No supported UI addon is loaded. Using Midnight."] end - return string_format(L["Selected: %s (%s)"], X.EffectiveTheme().label, X.autoThemeAddon) -end - --- Grow-up (1.8.0): normally the window hangs from its top-left corner and --- the list grows downward. With grow-up on, the window stands on its --- bottom-left corner instead, so the list grows upward and the bottom --- edge never moves. The saved point records which form it holds. -function X.ApplyAnchor() - if not frame then return end - local left = frame:GetLeft() - if not left then return end - if db.growUp then - local bottom = frame:GetBottom() - if not bottom then return end - frame:ClearAllPoints() - frame:SetPoint("BOTTOMLEFT", UIParent, "BOTTOMLEFT", left, bottom) - db.point = { "BOTTOMLEFT", "BOTTOMLEFT", left, bottom } - else - local top = frame:GetTop() - if not top then return end - frame:ClearAllPoints() - frame:SetPoint("TOPLEFT", UIParent, "BOTTOMLEFT", left, top) - db.point = { "TOPLEFT", "BOTTOMLEFT", left, top } - end - if db.charPoint then - local k = X.CharKey() - if k then db.pointByChar[k] = db.point end - end -end - --- Title suffix (1.12.0): "(update pending)" while a size/scale change waits --- for combat to end; "(data hidden)" while the game is withholding aura --- data from addons (secret values), so a stale-looking list has a reason. -function X.UpdateTitleMarks() - if not title then return end - local hid = X.hid > 0 and (GetTime() - X.hid) < 10 - local key = (X.geoPending and "p" or "") .. (hid and "h" or "") - if X.titleKey == key then return end - X.titleKey = key - local txt = "|cff33ccffBuff|rRadar" - if X.geoPending then txt = txt .. " |cffffa040(update pending)|r" end - if hid then txt = txt .. " |cffffa040(data hidden)|r" end - title:SetText(txt) -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). -local function ApplyGeometry() - if not frame then return end - if InCombatLockdown() then - X.geoPending = true -- lands at PLAYER_REGEN_ENABLED; the title says so meanwhile (1.12.0) - X.UpdateTitleMarks() - return - end - X.geoPending = nil - -- Two-column layout (1.9.0): each column keeps the chosen width, with - -- a small gap between the columns. - local cols = X.cols or 1 - frame:SetWidth((db.width or WIDTH) * cols + (cols - 1) * 6) - frame:SetScale(db.scale or 1) - X.UpdateTitleMarks() -end - -function X.ApplyScaleNow() ApplyGeometry() end - -local function ApplyAppearance() - if not frame then return end - if InCombatLockdown() then - X.appearancePending = true - return - end - X.appearancePending = nil - X.flashPending = nil - local c = X.ThemeBackground() - local bc = X.ThemeBorder() - if frame.SetBackdropColor then - frame:SetBackdropColor(c[1], c[2], c[3], db.bgAlpha or 0.92) - frame:SetBackdropBorderColor(bc[1], bc[2], bc[3], db.showBorder and 1 or 0) - end - for i = 1, #rows do X.TintRowHover(rows[i]) end - if X.pill and X.pill.SetBackdropColor then - X.pill:SetBackdropColor(c[1], c[2], c[3], db.bgAlpha or 0.92) - X.pill:SetBackdropBorderColor(bc[1], bc[2], bc[3], db.showBorder and 1 or 0) - end - if grip then grip:SetShown(not db.locked) end - if X.gripL then X.gripL:SetShown(not db.locked) end - if X.edge then X.edge:SetShown(not db.locked) end - title:SetShown(db.showTitle and true or false) - if X.titleLayoutState ~= db.showTitle then X.ApplyRowLayout() end - combatText:ClearAllPoints() - if db.showTitle then - combatText:SetPoint("LEFT", title, "RIGHT", 6, 0) - else - combatText:SetPoint("TOPLEFT", frame, "TOPLEFT", 9, -8) - end -end - -do - local function LoadFinished(ok, loaded, ...) - if not ok or not Readable(loaded) then return false end - -- The two-result API can report loaded while the addon's load is - -- still in progress. A legacy one-result API has no separate flag. - if select("#", ...) == 0 then return loaded == true or loaded == 1 end - local finished = ... - return loaded == true and Readable(finished) and finished == true - end - - function X.ResolveAutoTheme() - local resolved, selectedAddon - if db and db.theme == X.AUTO_THEME_ID then - resolved = "midnight" - local isLoaded = _G.C_AddOns and _G.C_AddOns.IsAddOnLoaded - if type(isLoaded) ~= "function" then isLoaded = _G.IsAddOnLoaded end - if type(isLoaded) == "function" then - for _, entry in ipairs(X.AutoThemePriority()) do - if LoadFinished(pcall(isLoaded, entry[1])) then - resolved, selectedAddon = entry[2], entry[1] - break - end - end - end - end - if X.autoThemeResolved == resolved and X.autoThemeAddon == selectedAddon then - if X.RefreshAutoThemePriority then X.RefreshAutoThemePriority() end - return false - end - X.autoThemeResolved, X.autoThemeAddon = resolved, selectedAddon - ApplyAppearance() - if RefreshConfig then RefreshConfig() end - local wizard = X.wizardFrame - if wizard and wizard:IsShown() and wizard.page == 2 then - wizard.choice[1]:SetText("Theme: " .. X.ThemeLabel(true)) - end - return true - end -end - ---------------------------------------------------------------------------- --- The setup wizard, saved themes, alert flash, range and fall checks, --- /br why and the Nearby Player explanations, history / stats text and --- the export dialog live in Wizard.lua since 1.15.34 (file split --- Slice F); it reaches this file's locals through X.wizAPI (bottom). ---------------------------------------------------------------------------- -X.farNow, X.farPrev = {}, {} -- range-watch sets; the scan writes X.farNow - --- Compact rows + list text scale (1.4.0). Re-anchors every row; height --- changes are not combat-safe on secure buttons, so this no-ops in combat --- and lands on the post-combat refresh instead. --- Click-through (1.10.0): while the window is locked AND the player --- asked for it, the window and its rows stop eating mouse clicks, so --- clicks land on the game world behind them. Never changed in combat --- (secure buttons refuse it there); re-applied when combat ends and --- whenever the lock or the setting changes. -function X.ApplyClickThrough() - if not frame or not db then return end - if InCombatLockdown and InCombatLockdown() then return end - local mouse = not (db.clickThrough and db.locked) - if frame.EnableMouse then frame:EnableMouse(mouse) end - for i = 1, MAX_ROWS do - local row = rows[i] - if row and row.EnableMouse then row:EnableMouse(mouse) end - end - if nextBtn and nextBtn.EnableMouse then nextBtn:EnableMouse(mouse) end - if X.nextPreview then X.nextPreview:EnableMouse(mouse) end - if X.nearbyButton then X.nearbyButton:SetShown(mouse) end - X.ApplyRowWheel() - if X.UpdateFade then X.UpdateFade() end -end - -function X.ApplyRowLayout() - if not frame or InCombatLockdown() then return end - X.titleLayoutState = db.showTitle - local h = db.compact and 16 or ROW_H - local header = db.showTitle and HEADER_H or 0 - local barHeight = X.BarHeight() - X.rowH = h - if X.findBar then - X.findBar:SetShown(db.findBox and true or false) - X.findBar:ClearAllPoints() - X.findBar:SetPoint("TOPLEFT", frame, "TOPLEFT", 4, -header - barHeight) - X.findBar:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -4, -header - barHeight) - end - local top = header + barHeight + (db.findBox and 16 or 0) - X.topH = top - if X.bar then - X.bar:SetShown(barHeight > 0) - X.bar:ClearAllPoints() - X.bar:SetPoint("TOPLEFT", frame, "TOPLEFT", 4, -header) - X.bar:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -4, -header) - end - if X.edge then - X.edge:ClearAllPoints() - X.edge:SetPoint("TOPRIGHT", frame, "TOPRIGHT", 0, -header) - X.edge:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", 0, 18) - end - emptyText:ClearAllPoints() - emptyText:SetPoint("TOPLEFT", frame, "TOPLEFT", 10, -top - 3) - countText:ClearAllPoints() - if db.showTitle then - countText:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -24, -6) - else - countText:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -16, 6) - end - if X.footerText then - X.footerText:ClearAllPoints() - X.footerText:SetPoint("LEFT", X.nearbyButton or X.gear, "RIGHT", 5, 0) - X.footerText:SetPoint("RIGHT", frame, "BOTTOMRIGHT", db.showTitle and -16 or -48, 13) - end - -- Two-column layout (1.9.0): rows fill the first column top to - -- bottom, then the second. X.cols / X.rowsPerCol are kept current by - -- Refresh; with one column this is exactly the old anchoring. - local per = X.rowsPerCol or MAX_ROWS - local cols = X.cols or 1 - local cellW = (db.width or WIDTH) + 6 -- column width + the gap - for i = 1, #rows do - local row = rows[i] - local col = math_floor((i - 1) / per) - local idx = (i - 1) % per - row:SetHeight(h) - row:ClearAllPoints() - row:SetPoint("TOPLEFT", frame, "TOPLEFT", 6 + col * cellW, -top - idx * (h + (db.rowGap or 0))) - row:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -(6 + (cols - 1 - col) * cellW), -top - idx * (h + (db.rowGap or 0))) - if row.portrait then row.portrait:SetShown(not db.compact) end - local isz = (db.iconSize or 0) > 0 and db.iconSize or (db.compact and 12 or 16) - for j = 1, MAX_ICONS do if row.icons[j] then row.icons[j]:SetSize(isz, isz) end end - local ts = db.textScale or 1 - 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 - if emptyText then - emptyText:ClearAllPoints() - emptyText:SetPoint("TOPLEFT", frame, "TOPLEFT", 10, -top - 3) - end -end - ---------------------------------------------------------------------------- --- The window builder (BuildUI), toggle strip, filter chips, idle fade, --- Cast Next / group buttons and the scale / edge drag helpers live in --- Window.lua since 1.15.34 (file split Slice G). It reaches this file's --- locals through X.winAPI (bottom) and hands the window handles back --- through X.winAPI.setUI. ---------------------------------------------------------------------------- - ---------------------------------------------------------------------------- --- Minimap button + addon compartment (block-scoped: 200-local limit) ---------------------------------------------------------------------------- -do -local minimapBtn - -local function MinimapRadii() - local w = Minimap.GetWidth and Minimap:GetWidth() - local h = Minimap.GetHeight and Minimap:GetHeight() - return w and w > 0 and w / 2 + 5 or 80, h and h > 0 and h / 2 + 5 or 80 -end - -local function PositionMinimapButton() - if not minimapBtn then return end - local angle = math.rad((db and db.minimapAngle) or 215) - local rx, ry = MinimapRadii() - minimapBtn:ClearAllPoints() - minimapBtn:SetPoint("CENTER", Minimap, "CENTER", math.cos(angle) * rx, math.sin(angle) * ry) -end - -function RefreshMinimapButton() - if not minimapBtn then return end - if db and db.showMinimap and not X.PlayerSuspended() then - minimapBtn:Show() - PositionMinimapButton() - else - minimapBtn.dragging = false - minimapBtn:Hide() - end -end - -BuildMinimapButton = function() - if minimapBtn or not Minimap then return end - local b = CreateFrame("Button", "BuffRadarMinimapButton", Minimap) - b:SetSize(31, 31) - b:SetFrameStrata("MEDIUM") - b:SetFrameLevel(8) - b:RegisterForDrag("LeftButton") - b:SetHighlightTexture("Interface\\Minimap\\UI-Minimap-ZoomButton-Highlight", "ADD") - local icon = b:CreateTexture(nil, "BACKGROUND") - icon:SetSize(20, 20) - icon:SetPoint("CENTER", 0, 1) - icon:SetTexture("Interface\\AddOns\\BuffRadar\\Media\\icon.png") - local border = b:CreateTexture(nil, "ARTWORK") - border:SetSize(52, 52) - border:SetPoint("TOPLEFT") - border:SetTexture("Interface\\Minimap\\MiniMap-TrackingBorder") - b:SetScript("OnEnter", function(self) - GameTooltip:SetOwner(self, "ANCHOR_LEFT") - GameTooltip:AddLine("|cff33ccffBuff|rRadar") - GameTooltip:AddLine(L["Left-click: show / hide the window"], 0.8, 0.8, 0.8) - GameTooltip:AddLine(L["Right-click: settings"], 0.8, 0.8, 0.8) - GameTooltip:AddLine(L["Drag: move around the minimap"], 0.8, 0.8, 0.8) - GameTooltip:Show() - end) - b:SetScript("OnLeave", function() GameTooltip:Hide() end) - -- A Button only receives left clicks unless told otherwise; without this the - -- right-click-for-settings in the tooltip never fired. - b:RegisterForClicks("LeftButtonUp", "RightButtonUp") - b:SetScript("OnClick", function(_, button) - if button == "RightButton" then OpenConfig() - elseif BuffRadar_ToggleWindow then BuffRadar_ToggleWindow() end - end) - 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 mx, my = Minimap:GetCenter() - if not mx or not my then return end - local cx, cy = GetCursorPosition() - local scale = (Minimap.GetEffectiveScale and Minimap:GetEffectiveScale()) or 1 - cx, cy = cx / scale, cy / scale - local rx, ry = MinimapRadii() - local atan2 = math.atan2 or math.atan - db.minimapAngle = math.deg(atan2((cy - my) / ry, (cx - mx) / rx)) % 360 - PositionMinimapButton() - end) - minimapBtn = b - if Minimap.HookScript then Minimap:HookScript("OnSizeChanged", PositionMinimapButton) end - RefreshMinimapButton() - - -- Addon compartment (the minimap's addon menu): same clicks as the minimap - -- button. The click callback's arguments differ between client versions: - -- newer menus pass a table with .buttonName, older dropdowns pass the mouse - -- button as the 5th argument; anything else counts as a left click. - if AddonCompartmentFrame and AddonCompartmentFrame.RegisterAddon then - pcall(AddonCompartmentFrame.RegisterAddon, AddonCompartmentFrame, { - text = "BuffRadar", - icon = "Interface\\AddOns\\BuffRadar\\Media\\icon.png", - notCheckable = true, - registerForAnyClick = true, - func = function(...) - local a2, a5 = select(2, ...), select(5, ...) - local mouse = (type(a2) == "table" and a2.buttonName) or a5 - if mouse == "RightButton" then OpenConfig() - elseif BuffRadar_ToggleWindow then BuffRadar_ToggleWindow() end - end, - funcOnEnter = function(button) - if type(button) ~= "table" or X.PlayerSuspended() then return end - GameTooltip:SetOwner(button, "ANCHOR_LEFT") - GameTooltip:AddLine("|cff33ccffBuff|rRadar") - GameTooltip:AddLine(L["Left-click: show / hide the window"], 0.8, 0.8, 0.8) - GameTooltip:AddLine(L["Right-click: settings"], 0.8, 0.8, 0.8) - GameTooltip:Show() - end, - funcOnLeave = function() GameTooltip:Hide() end, - }) - end -end -end -- minimap block - ---------------------------------------------------------------------------- --- Refresh ---------------------------------------------------------------------------- --- Widget writes only when the value actually changes (no redundant redraws). -local function SetTextIfChanged(fs, text) - if fs.cText ~= text then fs.cText = text; fs:SetText(text) end -end -local function SetShownIfChanged(w, show) - if (w:IsShown() and true or false) ~= show then - if show then w:Show() else w:Hide() end - end -end --- Height changes are safe to make freely: the frame is anchored by its --- TOPLEFT corner only (see SavePosition/RestorePosition), so growing or --- shrinking the height moves only the bottom edge -- the list grows --- downward and the top of the window never moves. -local function SetHeightIfChanged(f, h) - if f.cHeight ~= h then f.cHeight = h; f:SetHeight(h) end -end - -local refreshIdle = false -local function ClearRow(row) - row.entry, row.guid = nil, nil - if row.bGuid ~= nil then X.ClearRowCast(row) end - if row:IsShown() then row:Hide() end -end - -function X.HideOwnedTooltip() - if not GameTooltip or not GameTooltip.GetOwner then return end - local owner = GameTooltip:GetOwner() - if not owner then return end - local config = _G.BuffRadarConfig - while owner do - if owner == frame or owner == config or owner == _G.BuffRadarMinimapButton - or owner == X.pill or owner == X.wizardFrame or owner == X.exportFrame then - GameTooltip:Hide() - return - end - if not owner.GetParent then return end - owner = owner:GetParent() - end -end - -function X.SuspendBuffUI() - refreshIdle = true - X.ClearRowViewport() - wipe(X.rowMouseButtons) - X.rowLeftPress = nil - X.ResetCastTracking() - X.pillPeek = nil - X.HideOwnedTooltip() - if X.HideConfig then X.HideConfig() end - if X.CloseRaidPreparation then X.CloseRaidPreparation() end - if X.CloseNearbyDiagnostics then X.CloseNearbyDiagnostics() end - if X.wizardFrame and X.wizardFrame:IsShown() then X.wizardFrame:Hide() end - if X.exportFrame and X.exportFrame:IsShown() then X.exportFrame:Hide() end - if X.EndEditMode then X.EndEditMode(true) end - if RefreshMinimapButton then RefreshMinimapButton() end - - -- The state drivers hide and disarm protected frames during lockdown. - -- Clear the Lua-side click bookkeeping immediately in either case. - local locked = InCombatLockdown() - if nextBtn then nextBtn.entry = nil end - if X.groupBtn then X.groupBtn.entry = nil end - for i = 1, #rows do - rows[i].entry, rows[i].guid = nil, nil - if not locked then - X.ClearRowCast(rows[i]) - ClearRow(rows[i]) - end - end - if locked then return end - X.EndWindowDrags() - X.ClearNext() - X.ClearGroup() - if frame then SetShownIfChanged(frame, false) end - if X.pill then SetShownIfChanged(X.pill, false) end -end - -function X.UpdatePlayerLife(event) - local wasDead = X.playerDead - if event == "PLAYER_DEAD" then - X.playerDead = true - X.lifeCheckPending = nil - else - local dead = X.ReadUnitBool(_G.UnitIsDeadOrGhost, "player") - if dead ~= nil then X.playerDead = dead end - if event == "PLAYER_UNGHOST" and dead == nil then X.playerDead = false end - if event == "PLAYER_UNGHOST" or event == "PLAYER_ALIVE" then - -- The synchronous event can precede the unit flag update. Recheck on - -- the existing tick until the client confirms that casting can resume. - X.lifeCheckPending = X.playerDead or nil - elseif not X.playerDead then - X.lifeCheckPending = nil - end - end - if X.playerDead then - X.SuspendBuffUI() - elseif wasDead then - if RefreshMinimapButton then RefreshMinimapButton() end - if QueueRefresh then QueueRefresh() end - end - if wasDead ~= X.playerDead and event ~= "PLAYER_LOGIN" then X.SendCover() end -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.cTint = nil - wipe(row.cMissing) - end - if nextBtn then nextBtn.bGuid, nextBtn.isClear = nil, false end -end - --- The name shown on a row (1.10.0): optionally with the realm, and --- optionally shortened. -local function DispName(e) - local nm = (db.showRealm and e.fullName) or e.name or "" - local trim = db.nameTrim or 0 - if trim > 0 and Readable(nm) and type(nm) == "string" and #nm > trim then - local count = 0 - -- Skip UTF-8 continuation bytes when looking for the first character - -- beyond the display limit. Keep the engine's original text if unreadable. - for offset in nm:gmatch("()[^\128-\191]") do - if count == trim then return nm:sub(1, offset - 1) .. "…" end - count = count + 1 - end - end - return nm -end - --- Tag symbols (1.12.0): with tagSymbols on, a status tag also carries a --- symbol, so its meaning never rests on color alone. -function X.InvalidateTags() - for i = 1, #rows do rows[i].cTag = false end - if QueueRefresh then QueueRefresh() end -end - -X.TAGSYM = setmetatable({}, { __index = function() return "*" end }) -do - local T = X.TAGSYM - T[L["a buff just expired"]] = "!"; T[L["recently rezzed"]] = "+"; T[L["up next"]] = ">" - T[L["being buffed"]] = "~"; T[L["your assignment"]] = "#"; T[L["assigned elsewhere"]] = "x" - T[L["buddy's watch"]] = "&"; T[L["pinned"]] = "^"; T[L["weapon enchant missing"]] = "/" - T[L["drinking"]] = "o"; T[L["asked for a buff"]] = "?"; T[L["pet"]] = "p" -end - -local function RenderRow(row, e, cached) - row.entry, row.guid = e, e.guid - local m = e.missing - 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.) - local far = e.outOfRange and true or false - if row.cFar ~= far then - row.cFar = far - row.name:ClearAllPoints() - row.name:SetPoint("LEFT", row.portrait, "RIGHT", 6, far and 5 or 0) - row.name:SetPoint("RIGHT", row, "RIGHT", -(IconInset()), 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 - -- Status tag: a rezzed player (lost every buff) is marked under the name; - -- the name shifts up for it just like the out-of-range layout, minus grey. - local tag - if not far then - if e.expired then tag = L["a buff just expired"] - elseif e.rezzed then tag = L["recently rezzed"] - elseif e.queued then tag = L["up next"] - elseif e.handled then tag = L["being buffed"] - elseif e.mine then tag = L["your assignment"] - elseif e.theirs then tag = L["assigned elsewhere"] - elseif e.buddy then tag = L["buddy's watch"] - elseif e.pinned then tag = L["pinned"] - elseif e.weapon then tag = L["weapon enchant missing"] - elseif e.drinking then tag = L["drinking"] - elseif e.asked then tag = L["asked for a buff"] - elseif e.pet then tag = L["pet"] end - end - if tag and db.tagSymbols then - tag = (X.TAGSYM[tag] or "*") .. " " .. tag - end - if not tag and e.remain1 then - tag = e.remain1 >= 90 and string_format(L["~%dm left"], math_floor(e.remain1 / 60)) - or string_format(L["~%ds left"], math_floor(e.remain1)) - end - if row.cTag ~= tag then - row.cTag = tag - if tag then - row.tag:SetText(tag) - row.name:ClearAllPoints() - row.name:SetPoint("LEFT", row.portrait, "RIGHT", 6, 5) - row.name:SetPoint("RIGHT", row, "RIGHT", -(IconInset()), 5) - row.tag:Show() - else - row.tag:Hide() - if not far then - row.name:ClearAllPoints() - row.name:SetPoint("LEFT", row.portrait, "RIGHT", 6, 0) - row.name:SetPoint("RIGHT", row, "RIGHT", -(IconInset()), 0) - end - end - end - -- 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 - end - -- Duration bar (1.8.0): the expiring buff's remaining time as a share - -- of 30 minutes; the color band shifts green -> yellow -> red. - local barKey - if db.durationBars and e.remain1 and e.remain1 < math_huge then - local frac = math_min(1, e.remain1 / 1800) - local band = e.remain1 < 300 and 1 or (e.remain1 < 900 and 2 or 3) - barKey = math_floor(frac * 40) .. ":" .. band - if row.cBar ~= barKey then - row.cBar = barKey - row.bar:SetWidth(math_max(2, (row:GetWidth() - 4) * frac)) - if band == 1 then row.bar:SetVertexColor(1, 0.3, 0.3) - elseif band == 2 then row.bar:SetVertexColor(1, 0.85, 0.4) - else row.bar:SetVertexColor(0.4, 0.9, 0.4) end - row.bar:Show() - end - end - if not barKey then - -- Unconditional: InvalidateRows clears the cache without touching - -- the texture, so the hide can't ride on the cache alone. - row.cBar = nil - row.bar:Hide() - end - -- Raid marker badge (1.8.0). - local mk = (db.raidMarkers and e.marker) or nil - if row.cMarker ~= mk then - row.cMarker = mk - if mk then - row.marker:SetTexture("Interface\\TargetingFrame\\UI-RaidTargetingIcon_" .. mk) - row.marker:Show() - else - row.marker:Hide() - end - end - if not mk then row.marker:Hide() end - -- Row color mark (1.10.0): a colored strip on the row's left edge for - -- the first matching rule you switched on — yours, tanks, expiring - -- soon, your split partner's half. - local tint - local rc = db.rowColors - if rc then - if rc.mine and e.mine then tint = rc.mine - elseif rc.tank and e.role == 1 then tint = rc.tank - elseif rc.expiring and (e.expired or (e.remain1 and e.remain1 < 300)) then tint = rc.expiring - elseif rc.buddy and e.buddy then tint = rc.buddy end - end - if row.cTint ~= tint then - row.cTint = tint - if tint then - row.tint:SetVertexColor(tint[1], tint[2], tint[3]) - row.tint:Show() - else - row.tint:Hide() - end - end - if not tint then row.tint:Hide() end - local cm, changed = row.cMissing, false - for j = 1, MAX_ICONS do - if cm[j] ~= m[j] then changed = true; break end - end - if changed then - for j = 1, MAX_ICONS do - local t, spell = row.icons[j], m[j] - if spell then - t:SetTexture(SpellIcon(spell)) - t:SetAlpha(j == 1 and 1 or 0.5) - t:Show() - else - t:Hide() - end - cm[j] = spell - end - end - 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. - row:SetAlpha(0.6) - if row.bGuid ~= nil then X.ClearRowCast(row) end - else - row:SetAlpha(1) - X.BindCached(row, e.unit, m[1], e.castGuid or e.guid) - end - if not row:IsShown() then row:Show() end -end - --- Row color marks (1.10.0): named colors for the row edge strip. -X.ROW_PALETTE = { - gold = { 1, 0.8, 0.2 }, sky = { 0.4, 0.7, 1 }, red = { 1, 0.35, 0.35 }, - green = { 0.45, 0.95, 0.45 }, violet = { 0.75, 0.5, 1 }, -} -X.ROW_PALETTE_ORDER = { "gold", "sky", "red", "green", "violet" } - -function X.RowColorName(rule) - local c = db.rowColors and db.rowColors[rule] - if not c then return "off" end - for name, rgb in pairs(X.ROW_PALETTE) do - if rgb[1] == c[1] and rgb[2] == c[2] and rgb[3] == c[3] then return name end - end - return "custom" -end - -function X.SetRowColor(rule, c) - db.rowColors = db.rowColors or {} - db.rowColors[rule] = c and { c[1], c[2], c[3] } or nil - InvalidateRows() - if QueueRefresh then QueueRefresh() end -end - --- Shared look for the "nothing to list" states (no buffs known / paused in a city). -local function ShowStatus(text) - if X.pill then SetShownIfChanged(X.pill, false) end - if X.focusText then SetShownIfChanged(X.focusText, false) end - SetShownIfChanged(coverText, false) - SetTextIfChanged(countText, "") - SetShownIfChanged(overflowText, false) - SetTextIfChanged(emptyText, text) - SetShownIfChanged(emptyText, true) - UpdateCounter() - SetHeightIfChanged(frame, (X.topH or HEADER_H) + 26 + FOOTER_H) - SetShownIfChanged(frame, true) -end - --- Pick an honest explanation for an empty list when the client cannot verify range. -function X.EmptyStatus() - if X.scanHasUnknownBuffs or (X.tallyUnknownUnits or 0) > 0 then - return L["Some buff information is unavailable."] - end - if X.FriendlyPlatesOn() == false then - return L["Friendly nameplates are off."] - end - if X.rangeSilent then - return L["Range could not be confirmed; the list may be incomplete."] - end - if X.scanNameFiltered then return L["The name finder hides all buff targets."] end - if (X.lastTargetCastProblem and GetTime() < X.lastTargetCastProblem.expires) - or (X.NoCastReason and X.NoCastReason()) then return L["No cast target is available."] end - return L["No targets in the buff queue."] -end - -function X.EmptyStatusHint() - if X.FriendlyPlatesOn() == false then return L["Use /br plates to see nearby players."] end - if X.rangeSilent then return L["Move closer or use /br why ."] end - if X.lastTargetCastProblem and GetTime() < X.lastTargetCastProblem.expires then - return X.lastTargetCastProblem.message - end - if X.NoCastReason then return X.NoCastReason() end -end - -function X.ScanConfirmsGroupBuffed() - if X.scanHasUnknownBuffs or X.scanHasMissingBuffs or X.scanNameFiltered then return false end - local size = X.ReadUnitNumber(_G.GetNumGroupMembers) - return size ~= nil and size > 1 and X.tallyUnits == size -end - --- True while the last refresh found nothing that time alone can change: no --- supported buffs known, or scanning paused (city / battleground). The steady --- timer skips its refreshes then; events (zone changes, learning a spell, --- settings changes) still refresh right away and clear it. - --- Coverage-line parts (1.10.0): the line is assembled from parts, each --- with its own switch in db.coverParts; absent means on. -local function CoverOn(part) - local cp = db and db.coverParts - return not cp or cp[part] ~= false -end - --- Group-by-buff view (1.10.0): fold the people entries into one row --- per buff still needed. Each folded row stands for the buff itself: --- its name carries the count, and it borrows an in-range holder (if --- any) as its cast target, so clicking the row buffs that player with --- exactly that spell. Only the render stage uses the folded list -- --- coverage, sounds and reports keep working on people. -function X.BuildBuffView(list, n) - local bySpell, order = {}, {} - for i = 1, n do - local e = list[i] - if not e.header then - for j = 1, #(e.missing or {}) do - local spell = e.missing[j] - local g = bySpell[spell] - if not g then - g = { spell = spell, count = 0, missing = { spell }, group = true } - bySpell[spell] = g - 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 - 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 - end - end - end - end - table_sort(order, function(a, b) - if a.count ~= b.count then return a.count > b.count end - return a.spell < b.spell - end) - for i = 1, #order do - local g = order[i] - g.name = g.count > 1 and (g.spell .. " x" .. g.count) or g.spell - g.sortName = g.spell - g.guid = "buff:" .. g.spell .. "#" .. g.count - end - return order, #order -end - -X.IsMajorCity, X.CurrentInstance = InMajorCity, InInstanceNow - -function X.ApplyRowWheel() - if not frame or InCombatLockdown() then return end - local enabled = (X.rowViewCount or 0) > MAX_ROWS and not (db.clickThrough and db.locked) - if X.rowWheelEnabled == enabled then return end - X.rowWheelEnabled = enabled - frame:EnableMouseWheel(enabled) - for _, row in ipairs(rows) do row:EnableMouseWheel(enabled) end -end - -function X.ClearRowViewport() - X.rowView, X.rowOffset, X.rowViewCount = nil, nil, nil - if frame and not InCombatLockdown() then - X.ApplyRowWheel() - SetShownIfChanged(overflowText, false) - end -end - -function X.PaintRowViewport(cached) - local view, n = X.rowView, X.rowViewCount - X.rowOffset = math_min(X.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 rowsTall = wantCols == 2 and math_floor((shown + 1) / 2) or shown - if wantCols ~= (X.cols or 1) or rowsTall ~= (X.rowsTall or shown) then - X.cols, X.rowsTall = wantCols, rowsTall - X.rowsPerCol = wantCols == 2 and rowsTall or MAX_ROWS - X.ApplyRowLayout() - ApplyGeometry() - end - for i = 1, MAX_ROWS do - if i <= shown then RenderRow(rows[i], view[X.rowOffset + i], cached) else ClearRow(rows[i]) end - end - local overflow = n > MAX_ROWS - if overflow then - local y = -(X.topH or HEADER_H) - rowsTall * (X.rowH or ROW_H) - - math_max(0, rowsTall - 1) * (db.rowGap or 0) - 2 - if overflowText.cY ~= y then - overflowText.cY = y - overflowText:ClearAllPoints() - overflowText:SetPoint("TOPLEFT", frame, "TOPLEFT", 10, y) - end - SetTextIfChanged(overflowText, string_format(L["Rows %d–%d of %d"], X.rowOffset + 1, X.rowOffset + shown, n)) - end - SetShownIfChanged(overflowText, overflow) - X.ApplyRowWheel() - return shown, rowsTall -end - -function X.ScrollRows(step) - if not X.rowView or X.rowViewCount <= MAX_ROWS or db.hidden - or not frame:IsShown() or InCombatLockdown() or X.PlayerSuspended() - or (db.clickThrough and db.locked) or X.RowMouseHeld() - or X.ReadUnitBool(_G.IsMouseButtonDown, "LeftButton") == true - or X.ReadUnitBool(_G.IsMouseButtonDown, "RightButton") == true then return false end - if X.rowViewMode ~= db.viewMode or X.rowViewSearch ~= X.search - or X.rowViewRole ~= db.roleFilter or X.rowViewTwoCol ~= db.twoCol then return false end - local offset = math_max(0, math_min(X.rowOffset + step, X.rowViewCount - MAX_ROWS)) - if offset == X.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 - X.rowOffset = offset - X.PaintRowViewport(true) - return true -end - -local function Refresh() - if not built then return end - if X.PlayerSuspended() then - if not refreshIdle or not X.playerDead then X.UpdatePlayerLife() end - return - end - if InCombatLockdown() then return end - if (X.rowViewCount or 0) > MAX_ROWS and X.RowMouseHeld() then return end - X.assignmentGroupConflicts = X.AssignmentEnabled() and next(db.buffAssignments) and {} or nil - refreshIdle = false - X.applyFilter = true -- the window honors the role filter; reports turn it off - local wasAfterCombat = X.afterCombat - X.afterCombat = nil - X.afterCombatScan = wasAfterCombat or nil - if X.flashPending then ApplyAppearance() end - - if not hasAnyBuff then - X.ClearRowViewport() - refreshIdle = true - X.ClearNext() - X.ClearGroup() - for i = 1, MAX_ROWS do ClearRow(rows[i]) end - if sessionShow and not db.hidden then - ShowStatus(L["No supported buffs in your spellbook."]) - else - SetShownIfChanged(frame, false) - if X.pill then SetShownIfChanged(X.pill, false) end - end - return - end - - local groupHidden = db.groupOnly and not InGroup() - - -- No scanning in major cities - if db.pauseInCities and X.IsMajorCity() then - X.ClearRowViewport() - refreshIdle = true - X.ClearNext() - X.ClearGroup() - wipe(X.listedBefore) - for i = 1, MAX_ROWS do ClearRow(rows[i]) end - if db.hidden or groupHidden or db.autoHide then - SetShownIfChanged(frame, false) - else - ShowStatus(L["Paused in a major city."]) - end - return - end - - -- No scanning in battlegrounds / arenas (optional; flag rules make lists noisy) - local instType = X.CurrentInstance() - if db.pauseInBG and (instType == "pvp" or instType == "arena") then - X.ClearRowViewport() - refreshIdle = true - X.ClearNext() - X.ClearGroup() - wipe(X.listedBefore) - for i = 1, MAX_ROWS do ClearRow(rows[i]) end - if db.hidden or groupHidden or db.autoHide then - SetShownIfChanged(frame, false) - else - ShowStatus(L["Paused in a battleground."]) - end - return - end - - -- No scanning on a flight path (optional): you can't cast mid-flight. - if db.pauseTaxi and _G.UnitOnTaxi then - local ok, onTaxi = pcall(_G.UnitOnTaxi, "player") - if ok and onTaxi then - X.ClearRowViewport() - refreshIdle = true - X.ClearNext() - X.ClearGroup() - wipe(X.listedBefore) - for i = 1, MAX_ROWS do ClearRow(rows[i]) end - if db.hidden or groupHidden or db.autoHide then - SetShownIfChanged(frame, false) - else - ShowStatus(L["Paused on a flight path."]) - end - return - end - end - - -- Low-mana pause (optional): don't offer buffs you can't afford to cast. - if db.lowMana and db.lowMana > 0 and X.LowMana() then - X.ClearRowViewport() - X.ClearNext() - X.ClearGroup() - wipe(X.listedBefore) - for i = 1, MAX_ROWS do ClearRow(rows[i]) end - if db.hidden or groupHidden or db.autoHide then - SetShownIfChanged(frame, false) - else - ShowStatus(L["Low mana -- buffing paused."]) - end - return - end - - X.rowView, X.groupFallback, X.groupFallbackEntry, X.groupFallbackSummary = nil, nil, nil, nil - local n = CollectEntries() - X.CheckDrops() - X.CheckRange() - X.CheckFalls() - X.UpdateTitleMarks() - X.RefreshStrip() - X.RefreshChips() - +local function OfferGroupCast(n) -- Group-cast mode: if enough group members need the same group-castable -- buff, the first such row offers the group version instead (one cast -- covers the party). Only the first matching row is converted. @@ -6224,268 +4469,91 @@ local function Refresh() if converted then break end end end +end - -- Keybind / macro target: first player in the list, their next missing buff. - if n > 0 and nextBtn and not entries[1].outOfRange then - local first = entries[1] - nextBtn.entry = X.BindCached(nextBtn, first.unit, first.missing[1], first.guid) and first or nil - X.ArmGroupBtn(first) - else - X.ClearNext() - X.ClearGroup() - end - - if db.hidden or groupHidden then - X.ClearRowViewport() - for i = 1, MAX_ROWS do ClearRow(rows[i]) end - SetShownIfChanged(frame, false) - if X.pill then SetShownIfChanged(X.pill, false) end - wipe(X.listedBefore) - if X.UpdateNearbyTargetAfterScan then X.UpdateNearbyTargetAfterScan() end - return - end +-- Reuse the two listing sets instead of allocating one on every scan. +local listA, listB, recentlyGone = {}, {}, {} +local listedBefore = listA +local function AlertOnNewEntries(n) -- Droplet sound when someone new appears on the board local now, newName = GetTime(), false - local listedNow = (X.listedBefore == X.listA) and X.listB or X.listA + local listedNow = (listedBefore == listA) and listB or listA wipe(listedNow) for i = 1, n do 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 X.listedBefore[guid] then - local gone = X.recentlyGone[guid] + if not entries[i].outOfRange and not listedBefore[guid] then + local gone = recentlyGone[guid] if not gone or now - gone > 10 then newName = true end end end - for guid in pairs(X.listedBefore) do - if not listedNow[guid] then X.recentlyGone[guid] = now end + for guid in pairs(listedBefore) do + if not listedNow[guid] then recentlyGone[guid] = now end end - for guid, t in pairs(X.recentlyGone) do - if now - t > 60 then X.recentlyGone[guid] = nil end + for guid, t in pairs(recentlyGone) do + if now - t > 60 then recentlyGone[guid] = nil end end - X.listedBefore = listedNow + listedBefore = listedNow if newName and db.playSound and now - X.lastSoundAt > 1 then X.lastSoundAt = now PlayAlert("new") end +end - -- group-by-buff view folds the render list; everything above this - -- point (coverage, sounds, counts) still works on people - local viewEntries, viewN = entries, n - if db.viewMode == "buffs" then viewEntries, viewN = X.BuildBuffView(entries, n) end - if X.rowViewMode ~= db.viewMode or X.rowViewSearch ~= X.search or X.rowViewRole ~= db.roleFilter then - X.rowOffset = nil - end - X.rowViewMode, X.rowViewSearch, X.rowViewRole = db.viewMode, X.search, db.roleFilter - X.rowViewTwoCol = db.twoCol - X.rowView, X.rowViewCount = viewEntries, viewN - local shown, rowsTall = X.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 - - SetTextIfChanged(countText, n > 0 and n or "") - if n == 0 then - local hint = X.EmptyStatusHint() - SetTextIfChanged(emptyText, X.EmptyStatus() .. (hint and "\n" .. hint or "")) - end - SetShownIfChanged(emptyText, n == 0) - - -- Coverage / progress line: shown while grouped (even when the list is - -- empty -- "15/15 fully buffed" is the good-news form of the same line). - local coverShown = false - if X.tallyUnits > 1 or (X.tallyUnits > 0 and X.tallyUnknownUnits > 0) then - local parts = {} - if CoverOn("progress") then - parts[#parts + 1] = string_format("%d/%d fully buffed", X.tallyUnits - X.tallyMissingUnits, X.tallyUnits) - end - if CoverOn("buffs") then - for _, b in ipairs(myBuffs) do - local t = not b.self and X.tally[b.key] or nil - if t and t.total > 0 then - local nm = b.key:lower():gsub("_", " ") - local seg = string_format("%s %d/%d", nm:sub(1, 1):upper() .. nm:sub(2), - t.total - t.miss, t.total) - -- A buff on a real cooldown is never counted as missing (you can't - -- cast it anyway), so its count can look complete while people - -- still need it -- flag the cooldown so the number isn't trusted - -- blindly. - local left = CooldownLeft(b.name) - if left > 5 then - seg = seg .. (left >= 60 and string_format(" (~%dm cd)", math_floor(left / 60 + 0.5)) - or string_format(" (~%ds cd)", math_floor(left + 0.5))) - end - parts[#parts + 1] = seg - end - end - local tb = X.tally.BLESSINGS - if tb and tb.total > 0 then - parts[#parts + 1] = string_format("Blessings %d/%d", tb.total - tb.miss, tb.total) - end - end - 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) - end - end - end - -- Coverage uptime (1.6.0): the share of grouped scans this run that - -- found nobody missing anything. A scan-based score, reset when a - -- Mythic+ run starts and when the group ends. - if X.tallyUnknownUnits == 0 then - X.upTotal = X.upTotal + 1 - if X.tallyMissingUnits == 0 then X.upFull = X.upFull + 1 end - end - if X.upTotal >= 10 and CoverOn("uptime") then - parts[#parts + 1] = string_format("Uptime %d%%", - math_floor(100 * X.upFull / X.upTotal + 0.5)) - end - -- Coverage roster (1.7.0): which BuffRadar users are on duty, how - -- many assignments each holds, and who is covered (dead/AFK) — - -- so a group can see the buffing is staffed at a glance. - if db.sync then - local nowC = GetTime() - -- Assignment counts keyed by short name: holders are recorded as - -- typed (often short), users are known by full name. - local held = {} - for _, who in pairs(X.assign) do - local wk = Ignore.Key(who:match("^[^%-]+") or who) - held[wk] = (held[wk] or 0) + 1 - end - local duty = {} - local meF = Ignore.UnitNames("player") - if meF then - local mk = Ignore.Key(meF:match("^[^%-]+") or meF) - duty[#duty + 1] = (meF:match("^[^%-]+") or meF) - .. (held[mk] and (" (" .. held[mk] .. ")") or "") - end - local peerNames = {} - for k, p in pairs(X.peers) do - if nowC - p.t < 90 then peerNames[#peerNames + 1] = k end - end - table_sort(peerNames) - for _, k in ipairs(peerNames) do - local p = X.peers[k] - local short = (p.name:match("^[^%-]+") or p.name) - for cname, exp in pairs(X.cover) do - if exp > nowC and X.SameUser(p.name, cname) then - short = short .. " (away)" break - end - end - local hk = Ignore.Key(p.name:match("^[^%-]+") or p.name) - if held[hk] then short = short .. " (" .. held[hk] .. ")" end - duty[#duty + 1] = short - end - if #duty > 1 and CoverOn("roster") then - parts[#parts + 1] = "Radar: " .. table.concat(duty, ", ") - end - end - -- Group expiry warning (1.7.0): a group buff inside its last five - -- minutes on at least half its holders is about to become the - -- whole list — say so while there's time to refresh it calmly. - local worstKey, worstSoon, worstTotal = nil, 0, 0 - for key, soon in pairs(X.expiryTally) do - local t = X.tally[key] - if t and soon >= 3 and soon * 2 >= t.total and soon > worstSoon then - worstKey, worstSoon, worstTotal = key, soon, t.total - end - end - if worstKey and CoverOn("expiry") then - local nm = worstKey == "BLESSINGS" and "Blessings" or worstKey - if worstKey ~= "BLESSINGS" then - for _, def in ipairs(myBuffs) do - if def.key == worstKey then nm = def.name break end - end - end - parts[#parts + 1] = string_format("%s <5m on %d/%d", nm, worstSoon, worstTotal) - end - -- Weapon watch (1.7.0): when your own row isn't on the list to - -- carry the tag, the coverage line carries the reminder instead. - if db.weaponWatch and X.WeaponEnchantMissing() then - local selfListed = false - for i = 1, nEntries do - if entries[i].isSelf then selfListed = true break end - end - if not selfListed then - parts[#parts + 1] = "your weapon has no enchant" - end - end - -- World-buff watch (1.8.0): your active world buffs, with time left. - if db.worldWatch and CoverOn("world") then - local wb = X.WorldBuffsText() - if wb then parts[#parts + 1] = wb end - end - -- Healer drinking (1.8.0): healers sitting down to drink between - -- pulls — the group waits for them, not the other way round. - if db.drinkWatch and CoverOn("drink") and (X.drinkHealers or 0) > 0 then - parts[#parts + 1] = X.drinkHealers == 1 and "Healer drinking" - or string_format("%d healers drinking", X.drinkHealers) - end - -- Pull countdown (1.15.0): while a pull timer runs (Extras tracks it - -- in X.pull), the coverage line itself counts down -- the part of the - -- pull-timer feature 1.14.0 trimmed. The steady ticker rebuilds this - -- line every 0.4s while the list is live, and Extras refreshes again - -- the moment the timer ends, so the number never goes stale. - if X.pull and X.pull.endsAt then - local left = math_ceil(X.pull.endsAt - GetTime()) - if left > 0 then parts[#parts + 1] = string_format("Pull in %ds", left) end - end - SetTextIfChanged(coverText, table.concat(parts, " · ")) - X.coverFrac = string_format("%d/%d", X.tallyUnits - X.tallyMissingUnits, X.tallyUnits) - coverShown = #parts > 0 - end - SetShownIfChanged(coverText, coverShown) - - -- Focus watch (1.8.0): what your focus target still needs, on its own - -- line above the coverage line. Missing() runs with isGroup=false, so - -- the focus never touches the coverage tallies. - local focusShown = false - local focusValid, focusSelf - if db.focusWatch and X.focusText then focusValid, focusSelf = Valid("focus") end - if focusValid then - local fname = X.UnitNameOf("focus") - if fname then - local fn = Missing("focus", X.focusMiss, false, focusSelf) - if fn > 0 then - local fparts = {} - for i = 1, math_min(fn, 3) do fparts[#fparts + 1] = X.focusMiss[i] end - SetTextIfChanged(X.focusText, "Focus " .. fname .. ": needs " - .. table.concat(fparts, ", ") .. (fn > 3 and (" +" .. (fn - 3)) or "")) - elseif not X.auraUnknown then - SetTextIfChanged(X.focusText, "Focus " .. fname .. ": buffed") - end - focusShown = fn > 0 or not X.auraUnknown - end - end - if X.focusText then SetShownIfChanged(X.focusText, focusShown) end - - local h = (X.topH or HEADER_H) + (shown > 0 and rowsTall * (X.rowH or ROW_H) + math_max(0, rowsTall - 1) * (db.rowGap or 0) or 18) + 8 - if n == 0 and X.EmptyStatusHint() then h = h + 13 end - if coverShown then h = h + 13 end - if focusShown then h = h + 13 end - if viewN > MAX_ROWS then h = h + 14 end - h = h + FOOTER_H -- bottom row: settings gear + cast counter - UpdateCounter() - SetHeightIfChanged(frame, h) - - -- All-buffed pill (1.6.0): in a group with nobody missing anything, the - -- window can collapse to the pill until someone needs a buff again (or - -- the pill is clicked for a peek). - local pillMode = db.pill and n == 0 and InGroup() and not db.hidden - and not groupHidden and X.ScanConfirmsGroupBuffed() and GetTime() > (X.pillPeek or 0) - if pillMode and X.pill then - SetTextIfChanged(X.pill.text, "|cff33ccffBuff|rRadar · " - .. (X.coverFrac and (X.coverFrac .. " ") or "") .. L["All buffed"]) - SetShownIfChanged(frame, false) - SetShownIfChanged(X.pill, true) - else - if X.pill then SetShownIfChanged(X.pill, false) end - SetShownIfChanged(frame, not (db.autoHide and n == 0 and not sessionShow)) +local function Refresh() + if not X.WindowReady() or X.macroParked then return end + if X.PlayerSuspended() then + if not refreshIdle or not X.playerDead then X.UpdatePlayerLife() end + return + end + if InCombatLockdown() or X.HasHeldRow() then return end + X.assignmentGroupConflicts = X.AssignmentEnabled() and next(db.buffAssignments) and {} or nil + refreshIdle = false + X.applyFilter = true -- the window honors the role filter; reports turn it off + local wasAfterCombat = X.afterCombat + X.afterCombat = nil + X.afterCombatScan = wasAfterCombat or nil + X.PrepareWindowScan() + + if not hasAnyBuff then + refreshIdle = true + ClearCastQueue() + X.ShowWindowStatus(sessionShow and not db.hidden and L["No supported buffs in your spellbook."]) + return end + + local groupHidden = db.groupOnly and not InGroup() + local reason, idle = PauseReason() + if reason then + refreshIdle = idle or false + ClearCastQueue() + wipe(listedBefore) + local showStatus = not (db.hidden or groupHidden or db.autoHide) + X.ShowWindowStatus(showStatus and reason, not showStatus) + return + end + + X.groupFallback, X.groupFallbackEntry, X.groupFallbackSummary = nil, nil, nil + local n = CollectEntries() + X.CheckDrops() + X.CheckRange() + X.CheckFalls() + X.RefreshWindowHeader() + OfferGroupCast(n) + + -- The native keys and bar macro follow the scan even when the list is hidden. + X.SetNextCast(n > 0 and entries[1] or nil) + X.SyncCastMacro() + if db.hidden or groupHidden then + X.ShowWindowStatus() + wipe(listedBefore) + if X.UpdateNearbyTargetAfterScan then X.UpdateNearbyTargetAfterScan() end + return + end + AlertOnNewEntries(n) + X.RenderQueue(entries, n, sessionShow, wasAfterCombat) end --------------------------------------------------------------------------- @@ -6612,9 +4680,11 @@ local function RebuildNow() local ok, err = pcall(BuildBuffList) if not ok then Print("|cffff4040error reading spellbook:|r " .. tostring(err)) end X.prioDirty = true - if built then InvalidateRows() end - if built then X.ApplyRowLayout() end - if RefreshConfig then RefreshConfig() end + if X.WindowReady() then + X.InvalidateRows() + X.ApplyRowLayout() + end + if X.RefreshConfig then X.RefreshConfig() end Soon() end local function ScheduleRebuild() @@ -6661,7 +4731,8 @@ for _, ev in ipairs({ "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", + "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", @@ -6684,7 +4755,19 @@ driver:SetScript("OnEvent", function(_, event, arg1, ...) wipe(X.auraIds) end end - -- The busiest events, filtered first. They only ever lead to a list refresh: + -- The flattened action-bar macro has no pre-cast GUID check. Park it + -- immediately if a tracked token changes, without rebuilding the list. + if event == "NAME_PLATE_UNIT_REMOVED" or event == "NAME_PLATE_UNIT_ADDED" then + if type(arg1) == "string" and Readable(arg1) then X.DisarmStaleCastMacro(arg1, event == "NAME_PLATE_UNIT_REMOVED") end + elseif event == "PLAYER_TARGET_CHANGED" then + X.DisarmStaleCastMacro("target") + 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 + X.DisarmStaleCastMacro() + end + -- The busiest events, filtered first. They queue a list refresh: -- * in combat the list is frozen and PLAYER_REGEN_ENABLED refreshes it -- afterwards, so they're dropped outright; -- * UNIT_AURA also fires for units BuffRadar never lists (enemy and NPC @@ -6715,18 +4798,20 @@ driver:SetScript("OnEvent", function(_, event, arg1, ...) return end if event == "CVAR_UPDATE" then - if arg1 == "ActionButtonUseKeyDown" or arg1 == "ACTION_BUTTON_USE_KEY_DOWN" then + local name = type(arg1) == "string" and Readable(arg1) and arg1:lower() + if name == "actionbuttonusekeydown" or name == "action_button_use_key_down" then X.ApplyNextRegistration() - if db then pcall(MakeMacro, true) end -- keep an existing BuffRadar macro in sync - elseif type(arg1) == "string" then - local name = arg1:lower() - if name == "nameplateshowfriendlyplayers" or name == "nameplateshowfriends" or name == "nameplateshowall" then - Soon() - end + if db then X.SyncCastMacro() end + elseif name == "nameplateshowfriendlyplayers" or name == "nameplateshowfriends" + or name == "nameplateshowall" or name == "nameplateshowonlynameforfriendlyplayerunits" then + Soon() end return + elseif event == "UPDATE_MACROS" then + if X.InvalidateCastMacro() and db then Soon() end + return elseif event == "UPDATE_BINDINGS" then - if RefreshConfig then RefreshConfig() end + if X.RefreshConfig then X.RefreshConfig() end return elseif event == "PARTY_LEADER_CHANGED" then X.OnCoordinationRoster(true) @@ -6779,9 +4864,7 @@ driver:SetScript("OnEvent", function(_, event, arg1, ...) if db then X.SpecSwap(); Soon() end return elseif event == "UNIT_PORTRAIT_UPDATE" then - for i = 1, #rows do - if rows[i].cUnit == arg1 then rows[i].cGuid = nil end -- redraw that portrait - end + X.InvalidatePortrait(arg1) Soon() return end @@ -6805,7 +4888,14 @@ driver:SetScript("OnEvent", function(_, event, arg1, ...) if db then X.SendCover() end return end + if event == "PLAYER_LEAVING_WORLD" or event == "PLAYER_LOGOUT" then + X.macroParked = true + ClearCastQueue() + return + end if event == "PLAYER_ENTERING_WORLD" then + X.macroParked = nil + ClearCastQueue() X.OnCoordinationRoster() X.ResetCastTracking() X.ClearReadyCheck() @@ -6840,88 +4930,15 @@ driver:SetScript("OnEvent", function(_, event, arg1, ...) end return end - BuffRadarDB = SanitizeDB(BuffRadarDB) - db = BuffRadarDB - X.ShareDB() - db.showOutOfRange, db.hideInCombat = false, true - local preVersion = db.dbVersion or 0 -- the version the save came from (1.9.0 wizard gate) + X.Settings.Load(true) Ignore.Rebuild() - -- Settings shared with the Forever edition: Classic-only choices fall back - -- to the defaults here (their controls are hidden on this edition). - if not CLASSIC_FEATURES then - if db.castMethod == "id" or db.castMethod == "rank" then db.castMethod = "target" end - db.groupCast = false - end - if (db.dbVersion or 0) < 3 then - db.castMethod = "target" - db.clickReg = "both" - end - if (db.dbVersion or 0) < 4 then - db.includeSelf = true -- yourself is always checked first now - db.dbVersion = 4 - end - if (db.dbVersion or 0) < 5 then - db.dbVersion = 5 -- 1.2.0: new settings take their defaults; nothing to migrate - end - if (db.dbVersion or 0) < 6 then - db.dbVersion = 6 -- 1.4.0: specProfiles / lowMana added; nothing to migrate - end - if (db.dbVersion or 0) < 7 then - db.dbVersion = 7 -- 1.5.0: profiles / sync / role filter added; nothing to migrate - end - if (db.dbVersion or 0) < 9 then - db.dbVersion = 9 -- 1.7.0: readyPost / pinned / weaponWatch / enterFlash / scanThrottle / history added; nothing to migrate - end - if (db.dbVersion or 0) < 10 then - db.dbVersion = 10 -- 1.8.0: new watch/search settings take their defaults - -- Resistance context (#32): on Forever, shadow protection is a - -- pre-pull buff for instances by default, not an always-on need. - -- The player can change it any time with /br context SHADOW_PROT. - if CLASSIC_FEATURES and db.buffContext.SHADOW_PROT == nil then - db.buffContext.SHADOW_PROT = "instance" - end - end - if (db.dbVersion or 0) < 11 then - db.dbVersion = 11 -- 1.9.0: twoCol / deathRecap / wipeReport / wizardSeen added - -- Anyone with a real save history (1.2.0 or later) is not a new - -- user: don't nag them with the first-run wizard hint. - if preVersion >= 5 then db.wizardSeen = true end - end - if (db.dbVersion or 0) < 12 then - db.dbVersion = 12 -- 1.10.0: customization settings take their defaults - end - if (db.dbVersion or 0) < 13 then - db.dbVersion = 13 -- 1.12.0: scalePerSpec / specScales / gripSnap / tagSymbols / reduceMotion / rangeWatch take their defaults - end - if (db.dbVersion or 0) < 14 then - db.dbVersion = 14 -- 1.14.0: fastAura / modClick / pullFlash take their defaults (all off) - end - if (db.dbVersion or 0) < 15 then - db.dbVersion = 15 -- 1.15.0: fallSound / customGroup take their defaults (fallSound off) - end - if (db.dbVersion or 0) < 16 then - db.dbVersion = 16 -- Per-class blessing preferences start with the default priority. - end - if (db.dbVersion or 0) < 17 then - db.dbVersion = 17 -- assumeRange takes its default (off) - end - if db.dbVersion < 18 then - db.dbVersion = 18 -- Class and role assignments start disabled. - end - if db.dbVersion < 19 then - db.dbVersion = 19 -- Outdoor Thorns takes its default (off). - end - if db.dbVersion < 20 then - db.dbVersion = 20 -- Auto theme priority takes the built-in order by default. - end X.SpecSwap() X.ResolveAutoTheme() elseif event == "PLAYER_LOGIN" then driver:UnregisterEvent("PLAYER_LOGIN") -- one-off if not db then - BuffRadarDB = SanitizeDB(BuffRadarDB) - db = BuffRadarDB - X.ShareDB() + -- Defensive fallback: normally ADDON_LOADED has already migrated the save. + X.Settings.Load(false) Ignore.Rebuild() end X.ResolveAutoTheme() @@ -6936,6 +4953,7 @@ driver:SetScript("OnEvent", function(_, event, arg1, ...) ok, err = pcall(X.BuildUI) if not ok then Print("|cffff4040error building window:|r " .. tostring(err)) end X.ApplyClickThrough() + X.SyncCastMacro(true) -- migrate the built-in macro, but never arm a prior session's queue Print("loaded. Type /br to show the window.") if not db.wizardSeen then Print("New to BuffRadar? /br wizard runs a one-minute setup.") @@ -6951,39 +4969,19 @@ driver:SetScript("OnEvent", function(_, event, arg1, ...) elseif event == "PLAYER_REGEN_DISABLED" then if X.CloseNearbyDiagnostics then X.CloseNearbyDiagnostics() end if X.CloseRaidPreparation then X.CloseRaidPreparation() end - wipe(X.rowMouseButtons) - if X.ReadUnitBool(_G.IsMouseButtonDown, "LeftButton") == false then X.rowLeftPress = nil end X.auraIds = nil X.ClearCastIntent() X.combatStart = GetTime() -- the wipe report times the fight from here (1.9.0) - if combatText then combatText:Show() end - -- Drivers clear cast attributes in combat; protected drag and visibility - -- work can run here only if the client has not started lockdown. - if not InCombatLockdown() then - X.EndWindowDrags() - if frame and not frame.visibilityDriver then frame:Hide() end - if X.pill and not X.pill.visibilityDriver then X.pill:Hide() end - end + X.BeginWindowCombat() elseif event == "PLAYER_REGEN_ENABLED" then X.afterCombat = true -- Refresh() pulses the border if work is waiting if InCombatLockdown() then return end - X.EndWindowDrags() - if combatText then combatText:Hide() end - X.BuildUI() - if X.PlayerSuspended() then - X.SuspendBuffUI() + X.SyncCastMacro(true) + if not X.EndWindowCombat() then + SuspendBuffing() if db and X.WipeCheck then X.WipeCheck() end return end - -- Secure snippets cleared the attributes behind the display cache. - for i = 1, #rows do rows[i].bGuid = nil end - if nextBtn then nextBtn.bGuid, nextBtn.isClear = nil, false end - if X.groupBtn then X.groupBtn.bGuid, X.groupBtn.isClear = nil, false end - ApplyGeometry() -- a scale/width change made during combat lands now - if X.appearancePending or X.flashPending then ApplyAppearance() end - X.ApplyRowLayout() - X.ApplyClickThrough() - X.ApplyNextRegistration() if db and X.WipeCheck then X.WipeCheck() end -- post-wipe report (1.9.0) Soon() elseif event == "SPELLS_CHANGED" or event == "LEARNED_SPELL_IN_TAB" or event == "LEARNED_SPELL_IN_SKILL_LINE" then @@ -7006,25 +5004,11 @@ end) --------------------------------------------------------------------------- -- Keybind actions (Bindings.xml calls these) --------------------------------------------------------------------------- -function BuffRadar_ToggleWindow() - if not db or X.PlayerSuspended() then return end - db.hidden = not db.hidden - sessionShow = not db.hidden - if InCombatLockdown() then - Print(db.hidden and "Window will hide when combat ends." or "Window will show when combat ends.") - return - end - if not db.hidden and db.groupOnly and not InGroup() then - Print("Window is set to show only in a party or raid.") - end - Refresh() -end - function BuffRadar_ToggleSound() if not db or X.PlayerSuspended() then return end db.playSound = not db.playSound Print(db.playSound and "Sound |cff00ff00on|r" or "Sound |cffff4040muted|r") - if RefreshConfig then RefreshConfig() end + if X.RefreshConfig then X.RefreshConfig() end end --------------------------------------------------------------------------- @@ -7032,11 +5016,147 @@ end --------------------------------------------------------------------------- local KeybindText, OpenKeybinds do -local function MacroBody() - if GetCVarBool and GetCVarBool("ActionButtonUseKeyDown") then - return "/click BuffRadarNextButton LeftButton 1" +local MACRO_HEADER = "# BuffRadar\n/stopmacro [combat][@player,dead]" +local MACRO_NOTE = "/click BuffRadarMacroButton" +local LEGACY_CLICK = "/click BuffRadarNextButton" +local macro = {} + +local function IsLegacyClick(body) + return body == LEGACY_CLICK or body == LEGACY_CLICK .. " LeftButton 1" +end + +local function IsManagedMacro(body) + if IsLegacyClick(body) or body == MACRO_HEADER then return true end + if #body > 255 or body:sub(1, #MACRO_HEADER + 1) ~= MACRO_HEADER .. "\n" then return false end + local text = body:sub(#MACRO_HEADER + 2) + if IsLegacyClick(text) then return true end + if text:sub(1, #MACRO_NOTE + 1) ~= MACRO_NOTE .. "\n" then return false end + text = text:sub(#MACRO_NOTE + 2) + -- The marker alone does not claim a user's edited macro at the next login. + if text:match("^/cast %[[^\r\n]+$") then return true end + local handBack = text:match("^/cleartarget\n/targetexact [^\r\n]+\n/cast %[[^\r\n]+\n(/[^\r\n]+)$") + return handBack == "/targetlasttarget" or handBack == "/cleartarget" +end + +local function ReadMacro() + if not (GetMacroIndexByName and GetMacroBody) then return end + local ok, id = pcall(GetMacroIndexByName, MACRO_NAME) + if ok and type(id) == "number" and Readable(id) and id > 0 then + local read, body = pcall(GetMacroBody, id) + return id, read and type(body) == "string" and Readable(body) and body or nil + end +end + +local function MacroBody(disarmed) + local nextBtn = X.GetNextButton() + local entry = nextBtn and nextBtn.entry + if disarmed or X.macroParked or X.PlayerSuspended() or not X.RowTargetMatches(entry) then return MACRO_HEADER end + local action = nextBtn:GetAttribute("type") + if action == "spell" then + local down = GetCVarBool and GetCVarBool("ActionButtonUseKeyDown") + return MACRO_HEADER .. "\n" .. LEGACY_CLICK .. (down and " LeftButton 1" or "") + end + if action ~= "macro" then return MACRO_HEADER end + -- WoW cannot /click a button that runs macrotext from an action-bar macro. + -- 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 + -- 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")) + if nextBtn:GetAttribute("shift-type1") and not shifted then return MACRO_HEADER end + end + if not text then return MACRO_HEADER end + if shifted and shifted ~= text then + local a, condition, spell, b = text:match("^(.-)/cast (%b[]) ([^\r\n]+)(.*)$") + local sa, sc, ss, sb = shifted:match("^(.-)/cast (%b[]) ([^\r\n]+)(.*)$") + if not condition or not sc or sa ~= a or sb ~= b then return MACRO_HEADER end + text = a .. "/cast [mod:shift,nomod:ctrl,nomod:alt," .. sc:sub(2) .. " " .. ss + .. "; " .. condition .. " " .. spell .. b + end + local body = MACRO_HEADER .. "\n" .. MACRO_NOTE .. "\n" .. text + return #body <= 255 and body or MACRO_HEADER +end + +function X.InvalidateCastMacro() + if macro.writing then return false end + macro.checked = false + return true +end + +local function TrackMacro(index, body) + -- A macro can be renumbered. A changed body, not a new slot number, + -- is what makes us stop managing it for this session. + if macro.body and body then + macro.owned = macro.owned and macro.body == body + else + macro.owned = body and IsManagedMacro(body) end - return "/click BuffRadarNextButton" + macro.index, macro.body, macro.checked = index, body, true +end + +local function RunningMacro() + if not GetRunningMacro then return end + local ok, index = pcall(GetRunningMacro) + if ok and type(index) == "number" and Readable(index) and index > 0 then return index end +end + +local function MacroEditorOpen() + local editor = _G.MacroFrame + if not (editor and editor:IsShown()) then return false end + -- UPDATE_MACROS makes the game reload the edit box from disk. Do not + -- discard unsaved text in the macro editor while following the queue. + if macro.editor ~= editor then + macro.editor = editor + editor:HookScript("OnHide", function() + if not X.InvalidateCastMacro() then return end + if 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 macro.checked then + local index, body = ReadMacro() + if index and not body then return end + TrackMacro(index, body) + end + if not macro.owned then return end + local body = MacroBody(disarmed) + if body == macro.body or MacroEditorOpen() or RunningMacro() then return end + -- Recheck immediately before a write. Never write to an old index or + -- over a body edited since the last UPDATE_MACROS notification. + local index, current = ReadMacro() + if index and not current then return end + TrackMacro(index, current) + if not macro.owned or body == current then return end + macro.writing = true + pcall(EditMacro, index, nil, nil, body) + macro.writing = false + local id, saved = ReadMacro() + if id == index and saved == body then macro.body = body end +end + +function X.DisarmStaleCastMacro(unit, removed) + local nextBtn = X.GetNextButton() + local entry = macro.owned and nextBtn and nextBtn.entry + if entry and (not unit or unit == entry.unit) and (removed or not X.RowTargetMatches(entry)) then + X.SyncCastMacro(true) + end +end + +function X.RecordBarMacroClick() + local nextBtn = X.GetNextButton() + -- Observation only: this button cannot cancel the following /cast line. + if not (macro.checked and macro.owned and macro.body:find(MACRO_NOTE, 1, true) + and RunningMacro() == macro.index and macro.body == MacroBody()) then return end + local id, body = ReadMacro() + if id ~= macro.index or body ~= macro.body then return end + X.BeginCastClick(nextBtn, "LeftButton", false, "bar macro", body) + X.EndCastClick(nextBtn, "LeftButton", false, "bar macro") end function KeybindText(binding) @@ -7067,163 +5187,85 @@ local function MacroIcon() return 134400 -- question mark end --- Creates (or updates) an account-wide macro named "BuffRadar" and puts it on the cursor. -MakeMacro = function(quiet) +-- Create or update the owned macro and put it on the cursor. Background +-- refreshes never create one or touch a custom macro of the same name. +MakeMacro = function() if InCombatLockdown() then Print("Can't edit macros during combat."); return end - if not (GetMacroIndexByName and CreateMacro and EditMacro) then - Print("Macro API unavailable. Make a macro yourself containing: " .. MacroBody()) + if not (GetMacroIndexByName and GetMacroBody and CreateMacro and EditMacro) then + Print(L["Macro controls are unavailable. Bind Cast next buff with /br key instead."]) return end + if MacroEditorOpen() then + Print(L["Close the macro editor before creating the BuffRadar macro."]) + return + end + local idx, current = ReadMacro() + if not idx or current then TrackMacro(idx, current) end local body = MacroBody() - local idx = GetMacroIndexByName(MACRO_NAME) - if idx and idx > 0 then - EditMacro(idx, MACRO_NAME, MacroIcon(), body) - else - if quiet then return end - local numGlobal = GetNumMacros and GetNumMacros() or 0 - if numGlobal >= (MAX_ACCOUNT_MACROS or 120) then - Print("Your general macro slots are full. Make room, or add this line to any macro: " .. body) + if idx and (not current or not macro.owned) then + Print(L["Rename your custom BuffRadar macro first, or bind Cast next buff with /br key."]) + return + end + if not idx and GetNumMacros then + local constants = _G.Constants and _G.Constants.MacroConsts + local cap = (constants and constants.MAX_ACCOUNT_MACROS) or MAX_ACCOUNT_MACROS or 120 + if GetNumMacros() >= cap then + Print(L["Your general macro slots are full. Make room or bind Cast next buff with /br key."]) return end - idx = CreateMacro(MACRO_NAME, MacroIcon(), body, nil) end - if quiet then return end - if idx and PickupMacro then pcall(PickupMacro, idx) end - Print("Macro |cffffd100BuffRadar|r is on your cursor; drop it on an action bar. It runs: " .. body) + macro.writing = true + if not idx then + pcall(CreateMacro, MACRO_NAME, MacroIcon(), body, nil) + elseif current ~= body then + pcall(EditMacro, idx, nil, nil, body) + end + macro.writing = false + local id, saved = ReadMacro() + if not id or saved ~= body then + Print(L["Couldn't save the BuffRadar macro. Bind Cast next buff with /br key instead."]) + return + end + macro.index, macro.body, macro.owned, macro.checked = id, body, true, true + if PickupMacro then pcall(PickupMacro, id) end + Print(L["Place the BuffRadar macro on an action bar. It follows the next buff automatically."]) end end -- keybind + macro block ---------------------------------------------------------------------------- --- Config window (tabbed: Window / Alerts / Buffs / Behavior / Ignore & Stats) --- --- The whole settings window lives in Config.lua since 1.15.0 (file split --- Slice B): the builders, the tabs, BuildConfig, RefreshConfig and --- OpenConfig moved there verbatim from the do-block that used to sit --- here, and reach this file's locals through X.cfgAPI (filled in at the --- bottom of this file). These forward locals delegate to it. ---------------------------------------------------------------------------- -RefreshConfig = function() if X.RefreshConfig then X.RefreshConfig() end end -OpenConfig = function(forceShow) if X.OpenConfig then X.OpenConfig(forceShow) end end - - ---------------------------------------------------------------------------- --- Slash commands: HandleSlash and its helpers (OnOff, ListBuffs, --- X.Context, X.AutoProfileCheck, X.SelfTest) live in Slash.lua since --- 1.15.0 (file split Slice C), reaching this file's locals through --- X.slashAPI (filled in at the bottom of this file). Main keeps only --- the hand-off and the SlashCmdList registration below. ---------------------------------------------------------------------------- --- Handed to Extras.lua (the optional second file): the few locals it needs. --- (X.OnOff is published by Slash.lua, where OnOff lives since Slice C.) -X.Print, X.L, X.Refresh, X.BUFF_DEFS = Print, L, Refresh, BUFF_DEFS - --- Handed to Config.lua (the settings window, file split Slice B): the --- locals it needs, through one table so the bridge costs this file a --- single main-chunk local. Every value has a stable identity (functions, --- and tables that are mutated in place, never replaced). -X.cfgAPI = { - L = L, Print = Print, Refresh = Refresh, PlayAlert = PlayAlert, - ApplyAppearance = ApplyAppearance, ApplyGeometry = ApplyGeometry, - BuildBuffList = BuildBuffList, InvalidateRows = InvalidateRows, - UpdateCounter = UpdateCounter, IsOn = IsOn, Esc = Esc, - KeybindText = KeybindText, OpenKeybinds = OpenKeybinds, MakeMacro = MakeMacro, - Missing = Missing, RefreshMinimapButton = RefreshMinimapButton, - myBuffs = myBuffs, myBlessing = myBlessing, Single = Single, Ignore = Ignore, - BLESSINGS = BLESSINGS, DEFAULTS = DEFAULTS, SCALE_PRESETS = SCALE_PRESETS, - CLASSIC_FEATURES = CLASSIC_FEATURES, NEXT_BINDING = NEXT_BINDING, -} - --- Handed to Slash.lua (every /br command, file split Slice C): functions --- and stable tables by value; state this file reassigns or fills after --- load (window, grip, build/session flags) through the two accessors. -X.slashAPI = { - Print = Print, Refresh = Refresh, RefreshConfig = RefreshConfig, OpenConfig = OpenConfig, - PlayAlert = PlayAlert, ApplyAppearance = ApplyAppearance, ApplyGeometry = ApplyGeometry, - BuildBuffList = BuildBuffList, BuildUI = function() return X.BuildUI() end, InvalidateRows = InvalidateRows, - IsOn = IsOn, FriendlyPlatesOn = X.FriendlyPlatesOn, InGroup = InGroup, - InInstanceNow = InInstanceNow, InMajorCity = InMajorCity, MakeMacro = MakeMacro, - OpenKeybinds = OpenKeybinds, RefreshMinimapButton = RefreshMinimapButton, - RestorePosition = RestorePosition, SpellName = SpellName, UpdateCounter = UpdateCounter, +-- 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.InGroup, X.InRaid = InGroup, InRaid +X.Core = { + BuildBuffList = BuildBuffList, + PlayAlert = PlayAlert, QueueRefresh = QueueRefresh, - ALL = ALL, BLESSINGS = BLESSINGS, BUFF_DEFS = BUFF_DEFS, Ignore = Ignore, Single = Single, - myBuffs = myBuffs, myBlessing = myBlessing, entries = entries, seen = seen, - known = known, ranks = ranks, rows = rows, - CLASSIC_FEATURES = CLASSIC_FEATURES, MAX_WIDTH = MAX_WIDTH, MIN_WIDTH = MIN_WIDTH, - getState = function() - return { frame = frame, grip = grip, built = built, hasAnyBuff = hasAnyBuff, - sessionShow = sessionShow, lastError = lastError, bookCount = bookCount, - nextWrapped = (select(1, X.NextBindState())), - nextCombatDriver = (select(2, X.NextBindState())) } - end, - setSessionShow = function(v) sessionShow = v end, -} -X.GetDB = function() return db end --- Split files that keep their own `db` local (Coordination.lua, Wizard.lua) --- register a setter in X.dbSinks; the settings table is handed to them --- here the moment it exists. -X.ShareDB = function() - for _, sink in ipairs(X.dbSinks or {}) do sink(db) end -end - --- Handed to Coordination.lua (file split Slice E): stable values by --- value; the two counters this file reassigns through accessors. -X.coordAPI = { - L = L, Print = Print, PlayAlert = PlayAlert, QueueRefresh = QueueRefresh, - Ignore = Ignore, Readable = Readable, IsOn = IsOn, - InRaid = InRaid, InGroup = InGroup, InInstanceNow = InInstanceNow, - BLESSINGS = BLESSINGS, BUFF_DEFS = BUFF_DEFS, CLASSIC_FEATURES = CLASSIC_FEATURES, - RAID = RAID, PARTY = PARTY, myBuffs = myBuffs, entries = entries, - nEntries = function() return nEntries end, - hasAnyBuff = function() return hasAnyBuff end, -} - --- Handed to Wizard.lua (file split Slice F): stable values by value; --- the list length through an accessor, the window through X.GetFrame. -X.wizAPI = { - L = L, Print = Print, PlayAlert = PlayAlert, QueueRefresh = QueueRefresh, - RefreshConfig = RefreshConfig, OpenConfig = OpenConfig, - ApplyAppearance = ApplyAppearance, ApplyGeometry = ApplyGeometry, - Ignore = Ignore, Readable = Readable, SafeString = SafeString, - Single = Single, Missing = Missing, Valid = Valid, - InGroup = InGroup, InRaid = InRaid, RAID = RAID, PARTY = PARTY, PLATES = PLATES, - myBuffs = myBuffs, entries = entries, rows = rows, - CLASSIC_FEATURES = CLASSIC_FEATURES, MAX_ROWS = MAX_ROWS, - nEntries = function() return nEntries end, + IsOn = IsOn, + InInstance = InInstanceNow, + InMajorCity = InMajorCity, + KeybindText = KeybindText, + OpenKeybinds = OpenKeybinds, + MakeMacro = MakeMacro, + NextBinding = NEXT_BINDING, + Bind = Bind, + SafeString = SafeString, + SpellName = SpellName, + SpellIcon = SpellIcon, + CooldownLeft = CooldownLeft, + FocusLine = FocusLine, + ScanConfirmsGroupBuffed = ScanConfirmsGroupBuffed, + Missing = Missing, + Valid = Valid, + Single = Single, + Buffs = myBuffs, + BlessingsByClass = myBlessing, + Entries = entries, + Ranks = ranks, + RAID = RAID, PARTY = PARTY, PLATES = PLATES, + EntryCount = function() return nEntries end, + HasAnyBuff = function() return hasAnyBuff end, + BookCount = function() return bookCount end, + LastError = function() return lastError end, + SessionShow = function() return sessionShow end, + SetSessionShow = function(shown) sessionShow = shown end, } - --- Handed to Window.lua (file split Slice G): stable values by value; the --- two counters this file reassigns through accessors; setUI takes the --- window handles BuildUI creates there, setSessionShow the close button. -X.winAPI = { - L = L, Print = Print, IsOn = IsOn, QueueRefresh = QueueRefresh, - OpenConfig = OpenConfig, RefreshConfig = RefreshConfig, - ApplyAppearance = ApplyAppearance, ApplyGeometry = ApplyGeometry, - RestorePosition = RestorePosition, SavePosition = SavePosition, UpdateCounter = UpdateCounter, - Bind = Bind, CreateRow = CreateRow, BuildMinimapButton = BuildMinimapButton, - SafeString = SafeString, SpellIcon = SpellIcon, myBuffs = myBuffs, myBlessing = myBlessing, - CLASSIC_FEATURES = CLASSIC_FEATURES, MAX_ROWS = MAX_ROWS, WIDTH = WIDTH, - HEADER_H = HEADER_H, FOOTER_H = FOOTER_H, MIN_WIDTH = MIN_WIDTH, MAX_WIDTH = MAX_WIDTH, - hasAnyBuff = function() return hasAnyBuff end, - bookCount = function() return bookCount end, - setSessionShow = function(v) sessionShow = v end, - setUI = function(f, t, ct, et, ot, cbt, nb, cv, ft, g, b) - frame, title, countText, emptyText, overflowText, combatText = f, t, ct, et, ot, cbt - nextBtn, coverText, footerText, grip, built = nb, cv, ft, g, b - end, -} -X.SanitizeDB, X.IsProfileName, X.PROFILE_MAX_BYTES = SanitizeDB, IsProfileName, PROFILE_MAX_BYTES -X.Esc, X.Unesc, X.DEFAULTS = Esc, Unesc, DEFAULTS -- for Profiles.lua -X.InGroup, X.InRaid = InGroup, InRaid -- for Recaps.lua -X.CLASSIC = CLASSIC_FEATURES -X.GetFrame = function() return frame end -X.PositionSave = SavePosition -X.ApplyAppearance = ApplyAppearance - -SlashCmdList.BUFFRADAR = function(msg) - if not X.HandleSlash then - Print("BuffRadar commands are unavailable (Slash.lua did not load).") - return - end - local ok, err = pcall(X.HandleSlash, msg) - if not ok then Print("|cffff4040error:|r " .. tostring(err)) end -end diff --git a/BuffRadar/BuffRadar.toc b/BuffRadar/BuffRadar.toc index 3a4a04f..3b0eda0 100644 --- a/BuffRadar/BuffRadar.toc +++ b/BuffRadar/BuffRadar.toc @@ -10,10 +10,12 @@ Locales\deDE.lua Data.lua +SavedVariables.lua BuffRadar.lua +Minimap.lua Coordination.lua -Wizard.lua Window.lua +Wizard.lua Config.lua Slash.lua Recaps.lua diff --git a/BuffRadar/Config.lua b/BuffRadar/Config.lua index f726eba..adc9be5 100644 --- a/BuffRadar/Config.lua +++ b/BuffRadar/Config.lua @@ -1,32 +1,25 @@ --- BuffRadar - Config: the settings window (widget builders, the five --- tabs, BuildConfig, RefreshConfig, OpenConfig). --- Loaded after BuffRadar.lua through the .toc. This is file-split --- Slice B (1.15.0): the code below is the settings do-block that used to --- sit at the bottom of BuffRadar.lua, moved verbatim; it reaches the --- main file's locals through X.cfgAPI, which BuffRadar.lua fills in --- before this file loads. Settings state (the cfg table and every --- widget) is local to this file, exactly as it was local to the block. +-- BuffRadar - settings window, controls and keyboard navigation. -- Copyright (C) 2026 Malikor. GPLv3 or later. -local _, NS = ... -NS = NS or {} -local X = NS.X or {} -NS.X = X -local A = X.cfgAPI or {} +local _, ns = ... +local X = ns.X +local core = X.Core +X.cfgReg = {} local db -- the live settings table; read fresh at each entry point (X.GetDB) -local L = A.L -local Print, Refresh, PlayAlert = A.Print, A.Refresh, A.PlayAlert -local ApplyAppearance, ApplyGeometry = A.ApplyAppearance, A.ApplyGeometry -local BuildBuffList, InvalidateRows, UpdateCounter = A.BuildBuffList, A.InvalidateRows, A.UpdateCounter -local IsOn = A.IsOn -local KeybindText, OpenKeybinds, MakeMacro = A.KeybindText, A.OpenKeybinds, A.MakeMacro -local RefreshMinimapButton = A.RefreshMinimapButton -local myBuffs = A.myBuffs -local Ignore = A.Ignore -local DEFAULTS, SCALE_PRESETS = A.DEFAULTS, A.SCALE_PRESETS -local CLASSIC_FEATURES = A.CLASSIC_FEATURES -local NEXT_BINDING = A.NEXT_BINDING +local L = X.L +local Print, Refresh, PlayAlert = X.Print, X.Refresh, core.PlayAlert +local ApplyAppearance, ApplyGeometry = X.ApplyAppearance, X.ApplyGeometry +local BuildBuffList, InvalidateRows, UpdateCounter = core.BuildBuffList, X.InvalidateRows, X.UpdateCounter +local IsOn = core.IsOn +local KeybindText, OpenKeybinds, MakeMacro = core.KeybindText, core.OpenKeybinds, core.MakeMacro +local RefreshMinimapButton = X.RefreshMinimapButton +local myBuffs = core.Buffs +local Ignore = X.Ignore +local DEFAULTS = X.Settings.Defaults +local SCALE_PRESETS = { 0.5, 0.75, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2 } +local CLASSIC_FEATURES = X.classic +local NEXT_BINDING = core.NextBinding local pairs, ipairs, type, tonumber, tostring, pcall = pairs, ipairs, type, tonumber, tostring, pcall local math_floor, math_min = math.floor, math.min local table_sort = table.sort @@ -700,7 +693,7 @@ local function OpenBlessingPanel() BackdropTemplateMixin and "BackdropTemplate" or nil) cfg.blessingPanel, cfg.blessingSelectors = panel, {} panel:SetPoint("CENTER", cfg, "CENTER") - panel:SetSize(490, 372) + panel:SetSize(490, 392) panel:SetFrameStrata("DIALOG") panel:SetFrameLevel((cfg:GetFrameLevel() or 0) + 10) panel:EnableMouse(true) @@ -730,8 +723,13 @@ local function OpenBlessingPanel() selector:SetPoint("TOPLEFT", 158, y) cfg.blessingSelectors[i] = selector end + panel.complement = MakeCheck(panel, L["Complement Nearby Blessings"], + function() return db.blessingComplement end, X.SetBlessingComplement) + panel.complement:SetPoint("TOPLEFT", 18, -321) + Tip(panel.complement, L["Complement Nearby Blessings"], + L["Offer a different known blessing outside your group if another Paladin already provides your preferred blessing. Explicit rules still take precedence."]) local hint = panel:CreateFontString(nil, "OVERLAY", "GameFontDisableSmall") - hint:SetPoint("TOPLEFT", 22, -330) + hint:SetPoint("TOPLEFT", 22, -355) hint:SetWidth(442) hint:SetJustifyH("LEFT") hint:SetText(L["An active group blessing plan takes precedence."]) @@ -2897,7 +2895,6 @@ local function BuildConfig() v = math.floor(v + 0.5) db.idleFade = v fadeValue:SetText(v .. "%") - X.curAlpha = nil end, L["Idle fade (mouse away)"], function() return cfg.fadeValue:GetText() end) local scaleLabel = look:CreateFontString(nil, "OVERLAY", "GameFontHighlight") @@ -2944,7 +2941,7 @@ local function BuildConfig() cfg.twoColCheck = MakeCheck(look, L["Two columns when the list is long"], function() return db.twoCol end, - function(v) db.twoCol = v; X.cols = nil; Refresh() end) + function(v) db.twoCol = v; Refresh() end) cfg.twoColCheck:SetPoint("TOPLEFT", 10, -396) cfg.wizardBtn = MakeButton(look, "Run the setup wizard", 150, function() @@ -3119,14 +3116,14 @@ local function BuildConfig() OpenKeybinds() end) setKey:SetPoint("TOPLEFT", 14, -288) - local makeMacro = MakeButton(alerts, "Create macro", 120, function() MakeMacro(false) end) + local makeMacro = MakeButton(alerts, "Create macro", 120, function() MakeMacro() end) makeMacro:SetPoint("LEFT", setKey, "RIGHT", 10, 0) local hint = alerts:CreateFontString(nil, "OVERLAY", "GameFontDisableSmall") hint:SetPoint("TOPLEFT", 14, -316) hint:SetWidth(420) hint:SetJustifyH("LEFT") - hint:SetText("Cast next buff targets the first player in the list. Doesn't fire in combat.") + hint:SetText(L["Cast next buff works with a keyboard or controller and does not fire in combat."]) ------------------------------------------------------------------ -- Tab: Buffs @@ -3995,6 +3992,7 @@ RefreshConfig = function() if cfg.blessingPanel and cfg.blessingPanel:IsShown() then if X.HasKnownBlessings() then for _, selector in ipairs(cfg.blessingSelectors) do selector:Update() end + cfg.blessingPanel.complement:Update() else cfg.blessingPanel:Hide() end diff --git a/BuffRadar/Coordination.lua b/BuffRadar/Coordination.lua index 9b460a7..e70528f 100644 --- a/BuffRadar/Coordination.lua +++ b/BuffRadar/Coordination.lua @@ -1,28 +1,18 @@ --- BuffRadar - Coordination: cast sync between BuffRadar users (1.5.0), --- caster coordination (1.15.26), chat buff requests, per-buff context --- checks and the join digest. --- Loaded after BuffRadar.lua through the .toc. This is file-split Slice E --- (1.15.34): the code below moved verbatim from BuffRadar.lua and reaches --- that file's locals through X.coordAPI, which BuffRadar.lua fills in --- before this file loads. The settings table arrives through X.dbSinks --- once it exists; the two counters the main file reassigns (list length, --- whether any buff is known) are read through accessors. +-- BuffRadar - cast sync, assignments, chat requests and group context. -- Copyright (C) 2026 Malikor. GPLv3 or later. -local _, NS = ... -local X = NS and NS.X -if not X or not X.coordAPI then return end -local A = X.coordAPI +local _, ns = ... +local X = ns.X +local core = X.Core -local db = X.GetDB and X.GetDB() -- nil until ADDON_LOADED; X.dbSinks updates it -X.dbSinks = X.dbSinks or {} -X.dbSinks[#X.dbSinks + 1] = function(value) db = value end +local db +X.OnDBLoaded(function(value) db = value end) -local L, Print, PlayAlert, QueueRefresh = A.L, A.Print, A.PlayAlert, A.QueueRefresh -local Ignore, Readable, IsOn = A.Ignore, A.Readable, A.IsOn -local InRaid, InGroup, InInstanceNow = A.InRaid, A.InGroup, A.InInstanceNow -local BLESSINGS, BUFF_DEFS, CLASSIC_FEATURES = A.BLESSINGS, A.BUFF_DEFS, A.CLASSIC_FEATURES -local RAID, PARTY, myBuffs, entries = A.RAID, A.PARTY, A.myBuffs, A.entries +local L, Print, PlayAlert, QueueRefresh = X.L, X.Print, core.PlayAlert, core.QueueRefresh +local Ignore, Readable, IsOn = X.Ignore, X.Readable, core.IsOn +local InRaid, InGroup, InInstanceNow = X.InRaid, X.InGroup, core.InInstance +local BLESSINGS, BUFF_DEFS, CLASSIC_FEATURES = X.BLESSINGS, X.BUFF_DEFS, X.classic +local RAID, PARTY, myBuffs, entries = core.RAID, core.PARTY, core.Buffs, core.Entries local pairs, ipairs, next, type, pcall = pairs, ipairs, next, type, pcall local tonumber = tonumber local math_floor, math_max = math.floor, math.max @@ -1042,7 +1032,7 @@ function X.OnChatAsk(text, author) if not text:lower():find("buff", 1, true) then return end local short = author:match("^[^%-]+") or author local ka, ks = Ignore.Key(author), Ignore.Key(short) - for i = 1, A.nEntries() do + for i = 1, core.EntryCount() do local e = entries[i] if e and (Ignore.Key(e.fullName or "") == ka or Ignore.Key(e.sortName or "") == ks) then if (not X.asked[e.guid] or GetTime() - X.asked[e.guid] > 30) @@ -1096,7 +1086,7 @@ function X.InstanceCheck() if not db then return end local ctx = X.Context() local inside = ctx == "dungeon" or ctx == "raid" or ctx == "pvp" - if inside and not X.wasInside and db.enterFlash and InGroup() and A.hasAnyBuff() + if inside and not X.wasInside and db.enterFlash and InGroup() and core.HasAnyBuff() and not X.PlayerSuspended() then local report = X.GroupBuffReport() local people = #report.people @@ -1131,7 +1121,7 @@ function X.OnRoster() X.PruneAssignmentRoleOverrides() X.PruneBlockerUndo() 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 A.hasAnyBuff() then + 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 diff --git a/BuffRadar/Data.lua b/BuffRadar/Data.lua index 871414e..7c74093 100644 --- a/BuffRadar/Data.lua +++ b/BuffRadar/Data.lua @@ -1,13 +1,10 @@ -- BuffRadar - Data: buff tables, class sets, blessings, presets and themes. --- Loaded FIRST through the .toc; everything lives on the shared namespace --- table X so BuffRadar.lua (loaded next) can alias what it needs without --- spending its own main-chunk locals (Lua 5.1 caps them at 200). +-- Initializes the private namespace before settings and core load. -- Copyright (C) 2026 Malikor. GPLv3 or later. -local _, NS = ... -NS = NS or {} -local X = NS.X or {} -NS.X = X +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 @@ -23,6 +20,9 @@ do end X.classic = CLASSIC_FEATURES +X.friendlyPlateCVars = { "nameplateShowFriendlyPlayers", "nameplateShowFriends" } +X.friendlyPlateNamesCVar = "nameplateShowOnlyNameForFriendlyPlayerUnits" + -- Forever group spells consume one reagent per cast. The spellbook rank ID -- selects the item, because the first ranks of two spells use cheaper items. X.groupReagents = { diff --git a/BuffRadar/Extras.lua b/BuffRadar/Extras.lua index 2afc3d4..1615e41 100644 --- a/BuffRadar/Extras.lua +++ b/BuffRadar/Extras.lua @@ -21,7 +21,16 @@ local function UpdateNearbyNameplates() nearby.lastNameplates = enabled local status = enabled == true and L["On"] or enabled == false and L["Off"] or L["Unknown"] nearby.nameplates:SetText(string.format(L["Friendly nameplates: %s"], status)) - nearby.enablePlates:SetShown(enabled == false) + nearby.togglePlates:SetText(L[enabled and "Disable Friendly Nameplates" or "Enable Friendly Nameplates"]) + nearby.togglePlates:SetShown(enabled ~= nil) + local namesOnly = X.ReadBooleanCVar(X.friendlyPlateNamesCVar) + nearby.plateStyle:SetText(L[namesOnly and "Show Friendly Health Bars" or "Show Friendly Names Only"]) + nearby.plateStyle:SetShown(namesOnly ~= nil) + nearby.restorePlates:SetShown(next(X.GetDB().plateRestore) ~= nil) +end + +function X.UpdateNearbyPlateControls() + if nearby and nearby:IsShown() then UpdateNearbyNameplates() end end function X.UpdateNearbyScanCount() @@ -55,7 +64,7 @@ end local function BuildNearby() local f = CreateFrame("Frame", "BuffRadarNearbyDiagnostics", UIParent) - f:SetSize(450, 252) + f:SetSize(480, 298) f:SetPoint("CENTER") f:SetFrameStrata("DIALOG") f:SetClampedToScreen(true) @@ -88,9 +97,9 @@ local function BuildNearby() local scroll = CreateFrame("ScrollFrame", "BuffRadarNearbyScroll", f, "UIPanelScrollFrameTemplate") scroll:SetPoint("TOPLEFT", 14, -112) - scroll:SetPoint("BOTTOMRIGHT", -30, 76) + scroll:SetPoint("BOTTOMRIGHT", -30, 108) local child = CreateFrame("Frame", nil, scroll) - child:SetSize(406, 1) + child:SetSize(436, 1) scroll:SetScrollChild(child) f.scroll, f.scrollChild = scroll, child f.details = child:CreateFontString(nil, "OVERLAY", "GameFontHighlight") @@ -99,20 +108,34 @@ local function BuildNearby() f.details:SetJustifyH("LEFT") f.details:SetJustifyV("TOP") f.details:SetWordWrap(true) - f.message = Label("GameFontHighlightSmall", -182) - - local enable = CreateFrame("Button", nil, f, "UIPanelButtonTemplate") - enable:SetSize(280, 22) - enable:SetPoint("BOTTOMLEFT", 14, 12) - enable:SetText(L["Enable Friendly Nameplates"]) - enable:SetScript("OnClick", function() - if not f:IsShown() or X.PlayerSuspended() or InCombatLockdown() or X.FriendlyPlatesOn() ~= false then return end - local message - X.EnableFriendlyNameplates(function(line) message = line end) - UpdateNearbyNameplates() - f.message:SetText(message or "") + f.message = Label("GameFontHighlightSmall", -196) + f.message:SetWordWrap(true) + f.message:SetJustifyV("TOP") + + local function PlateButton(width, point, x, y, chooseMode) + local btn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate") + btn:SetSize(width, 22) + btn:SetPoint(point, x, y) + btn:SetScript("OnClick", function() + if not f:IsShown() or not btn:IsShown() or X.PlayerSuspended() or InCombatLockdown() then return end + local mode = chooseMode() + if not mode then return end + local message + X.ChangeFriendlyNameplates(mode, function(line) message = line end) + f.message:SetText(message or "") + end) + return btn + end + f.togglePlates = PlateButton(266, "BOTTOMLEFT", 14, 42, function() + local enabled = X.FriendlyPlatesOn() + if enabled ~= nil then return enabled and "off" or "on" end + end) + f.plateStyle = PlateButton(266, "BOTTOMLEFT", 14, 12, function() + local namesOnly = X.ReadBooleanCVar(X.friendlyPlateNamesCVar) + if namesOnly ~= nil then return namesOnly and "bars" or "names" end end) - f.enablePlates = enable + f.restorePlates = PlateButton(176, "BOTTOMRIGHT", -14, 42, function() return "restore" end) + f.restorePlates:SetText(L["Restore Nameplates"]) local refresh = CreateFrame("Button", nil, f, "UIPanelButtonTemplate") refresh:SetSize(110, 22) @@ -268,7 +291,7 @@ function X.ApiCheck(export) -- Readability tier: the presence table above cannot see a restricted -- result, which is the failure that actually hides players from the list. local unit, unitWhy = ProbeUnit() - local buffs = X.slashAPI and X.slashAPI.myBuffs + local buffs = X.Core.Buffs local spell = (buffs and buffs[1] and buffs[1].name) or "Arcane Intellect" out(string.format(" readability on %s (%s), spell %s:", unit, unitWhy, spell)) local PROBES = { @@ -603,7 +626,7 @@ do end --------------------------------------------------------------------------- --- Slash registration (dispatched from BuffRadar.lua's HandleSlash) +-- Slash registration (dispatched by Slash.lua) --------------------------------------------------------------------------- X.ext.apicheck = function(rest) X.ApiCheck(rest == "export") end X.ext.ignorelist = function(rest) diff --git a/BuffRadar/Locales/deDE.lua b/BuffRadar/Locales/deDE.lua index 132f4f7..7ab7e89 100644 --- a/BuffRadar/Locales/deDE.lua +++ b/BuffRadar/Locales/deDE.lua @@ -50,6 +50,34 @@ NS.Locales.deDE = { ["Friendly nameplates turned on, so nearby non-group players can be listed."] = "Freundliche Namensplaketten sind an. Spieler in der Nähe können auch außerhalb deiner Gruppe angezeigt werden.", ["Nameplate settings are unavailable while dead."] = "Namensplaketten können im Tod nicht umgestellt werden.", ["Next buff: %s — %s"] = "Nächster Stärkungszauber: %s — %s", + ["Complement Nearby Blessings"] = "Segnungen bei Spielern in der Nähe ergänzen", + ["Offer a different known blessing outside your group if another Paladin already provides your preferred blessing. Explicit rules still take precedence."] = "Bietet außerhalb deiner Gruppe eine andere bekannte Segnung an, wenn ein anderer Paladin bereits deine bevorzugte Segnung gewirkt hat. Ausdrückliche Regeln haben Vorrang.", + ["Blessing: complement another Paladin"] = "Segnung: anderen Paladin ergänzen", + ["Usage: /br bless complement on|off"] = "Verwendung: /br bless complement on|off", + ["Learn a blessing before changing this setting."] = "Lerne zuerst eine Segnung, um diese Einstellung zu ändern.", + ["Complement Nearby Blessings: %s"] = "Segnungen bei Spielern in der Nähe ergänzen: %s", + ["Disable Friendly Nameplates"] = "Freundliche Namensplaketten ausblenden", + ["Show Friendly Health Bars"] = "Freundliche Lebensbalken anzeigen", + ["Show Friendly Names Only"] = "Nur freundliche Namen anzeigen", + ["Restore Nameplates"] = "Plaketten zurücksetzen", + ["No nameplate changes to restore."] = "Es gibt keine gespeicherten Namensplaketten-Änderungen.", + ["Some nameplate settings could not be restored. Try again or check the game's options."] = "Einige Einstellungen für Namensplaketten konnten nicht wiederhergestellt werden. Versuche es erneut oder prüfe die Spieloptionen.", + ["Restored your previous nameplate settings."] = "Deine bisherigen Einstellungen für Namensplaketten wurden wiederhergestellt.", + ["Couldn't change friendly nameplate style. Check the game's nameplate settings."] = "Der Stil freundlicher Namensplaketten konnte nicht geändert werden. Prüfe die Namensplaketten-Einstellungen im Spiel.", + ["Friendly nameplates now show names only."] = "Freundliche Namensplaketten zeigen jetzt nur Namen an.", + ["Friendly nameplates can show health bars again."] = "Freundliche Namensplaketten können wieder Lebensbalken anzeigen.", + ["Couldn't turn off friendly nameplates. Check the game's nameplate settings."] = "Freundliche Namensplaketten konnten nicht ausgeblendet werden. Prüfe die Namensplaketten-Einstellungen im Spiel.", + ["Friendly nameplates turned off. Your group, target, and mouseover are still checked."] = "Freundliche Namensplaketten sind aus. Gruppe, Ziel und Einheit unter dem Mauszeiger werden weiterhin geprüft.", + ["Usage: /br plates on|off|names|bars|restore"] = "Verwendung: /br plates on|off|names|bars|restore", + ["Macro controls are unavailable. Bind Cast next buff with /br key instead."] = "Makros sind nicht verfügbar. Weise „Cast next buff“ stattdessen mit /br key zu.", + ["Rename your custom BuffRadar macro first, or bind Cast next buff with /br key."] = "Benenne zuerst dein eigenes BuffRadar-Makro um oder weise „Cast next buff“ mit /br key zu.", + ["Your general macro slots are full. Make room or bind Cast next buff with /br key."] = "Deine allgemeinen Makroplätze sind voll. Schaffe Platz oder weise „Cast next buff“ mit /br key zu.", + ["Close the macro editor before creating the BuffRadar macro."] = "Schließe das Makrofenster, bevor du das BuffRadar-Makro erstellst.", + ["Couldn't save the BuffRadar macro. Bind Cast next buff with /br key instead."] = "Das BuffRadar-Makro konnte nicht gespeichert werden. Weise „Cast next buff“ stattdessen mit /br key zu.", + ["Place the BuffRadar macro on an action bar. It follows the next buff automatically."] = "Lege das BuffRadar-Makro in eine Aktionsleiste. Es folgt automatisch dem nächsten Stärkungszauber.", + ["Bind a controller button to BuffRadar's Cast next buff, or put /br macro on an action bar."] = "Weise einer Controller-Taste „Cast next buff“ unter BuffRadar zu oder lege das Makro aus /br macro in eine Aktionsleiste.", + ["/br gamepad - set up controller buffing"] = "/br gamepad – Stärkungszauber per Controller einrichten", + ["Cast next buff works with a keyboard or controller and does not fire in combat."] = "„Cast next buff“ funktioniert mit Tastatur und Controller, aber nicht im Kampf.", ["Group buff key: %s"] = "Taste für Gruppenstärkung: %s", ["Group blessing would conflict with a player exception."] = "Der Gruppensegen würde einer Spielerausnahme widersprechen.", ["Could not check reagent: %s."] = "Reagenz konnte nicht geprüft werden: %s.", diff --git a/BuffRadar/Minimap.lua b/BuffRadar/Minimap.lua new file mode 100644 index 0000000..bf21e51 --- /dev/null +++ b/BuffRadar/Minimap.lua @@ -0,0 +1,120 @@ +-- BuffRadar - minimap button and addon compartment. +-- Copyright (C) 2026 Malikor. GPLv3 or later. + +local _, ns = ... +local X = ns.X +local L = X.L +local db +X.OnDBLoaded(function(value) db = value end) + +local minimapBtn + +local function MinimapRadii() + local w = Minimap.GetWidth and Minimap:GetWidth() + local h = Minimap.GetHeight and Minimap:GetHeight() + return w and w > 0 and w / 2 + 5 or 80, h and h > 0 and h / 2 + 5 or 80 +end + +local function PositionMinimapButton() + if not minimapBtn then return end + local angle = math.rad((db and db.minimapAngle) or 215) + local rx, ry = MinimapRadii() + minimapBtn:ClearAllPoints() + minimapBtn:SetPoint("CENTER", Minimap, "CENTER", math.cos(angle) * rx, math.sin(angle) * ry) +end + +local function RefreshMinimapButton() + if not minimapBtn then return end + if db and db.showMinimap and not X.PlayerSuspended() then + minimapBtn:Show() + PositionMinimapButton() + else + minimapBtn.dragging = false + minimapBtn:Hide() + end +end + +local function OnClick(_, button) + if button == "RightButton" then + if X.OpenConfig then X.OpenConfig() end + else + X.ToggleWindow() + end +end + +local function BuildMinimapButton() + if minimapBtn or not Minimap then return end + local b = CreateFrame("Button", "BuffRadarMinimapButton", Minimap) + b:SetSize(31, 31) + b:SetFrameStrata("MEDIUM") + b:SetFrameLevel(8) + b:RegisterForDrag("LeftButton") + b:SetHighlightTexture("Interface\\Minimap\\UI-Minimap-ZoomButton-Highlight", "ADD") + local icon = b:CreateTexture(nil, "BACKGROUND") + icon:SetSize(20, 20) + icon:SetPoint("CENTER", 0, 1) + icon:SetTexture("Interface\\AddOns\\BuffRadar\\Media\\icon.png") + local border = b:CreateTexture(nil, "ARTWORK") + border:SetSize(52, 52) + border:SetPoint("TOPLEFT") + border:SetTexture("Interface\\Minimap\\MiniMap-TrackingBorder") + b:SetScript("OnEnter", function(self) + GameTooltip:SetOwner(self, "ANCHOR_LEFT") + GameTooltip:AddLine("|cff33ccffBuff|rRadar") + GameTooltip:AddLine(L["Left-click: show / hide the window"], 0.8, 0.8, 0.8) + GameTooltip:AddLine(L["Right-click: settings"], 0.8, 0.8, 0.8) + GameTooltip:AddLine(L["Drag: move around the minimap"], 0.8, 0.8, 0.8) + GameTooltip:Show() + end) + b:SetScript("OnLeave", function() GameTooltip:Hide() end) + -- A Button only receives left clicks unless told otherwise; without this the + -- 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 mx, my = Minimap:GetCenter() + if not mx or not my then return end + local cx, cy = GetCursorPosition() + local scale = (Minimap.GetEffectiveScale and Minimap:GetEffectiveScale()) or 1 + cx, cy = cx / scale, cy / scale + local rx, ry = MinimapRadii() + local atan2 = math.atan2 or math.atan + db.minimapAngle = math.deg(atan2((cy - my) / ry, (cx - mx) / rx)) % 360 + PositionMinimapButton() + end) + minimapBtn = b + if Minimap.HookScript then Minimap:HookScript("OnSizeChanged", PositionMinimapButton) end + RefreshMinimapButton() + + -- Addon compartment (the minimap's addon menu): same clicks as the minimap + -- button. The click callback's arguments differ between client versions: + -- newer menus pass a table with .buttonName, older dropdowns pass the mouse + -- button as the 5th argument; anything else counts as a left click. + if AddonCompartmentFrame and AddonCompartmentFrame.RegisterAddon then + pcall(AddonCompartmentFrame.RegisterAddon, AddonCompartmentFrame, { + text = "BuffRadar", + icon = "Interface\\AddOns\\BuffRadar\\Media\\icon.png", + notCheckable = true, + registerForAnyClick = true, + func = function(...) + local a2, a5 = select(2, ...), select(5, ...) + OnClick(nil, (type(a2) == "table" and a2.buttonName) or a5) + end, + funcOnEnter = function(button) + if type(button) ~= "table" or X.PlayerSuspended() then return end + GameTooltip:SetOwner(button, "ANCHOR_LEFT") + GameTooltip:AddLine("|cff33ccffBuff|rRadar") + GameTooltip:AddLine(L["Left-click: show / hide the window"], 0.8, 0.8, 0.8) + GameTooltip:AddLine(L["Right-click: settings"], 0.8, 0.8, 0.8) + GameTooltip:Show() + end, + funcOnLeave = function() GameTooltip:Hide() end, + }) + end +end + +X.BuildMinimapButton = BuildMinimapButton +X.RefreshMinimapButton = RefreshMinimapButton diff --git a/BuffRadar/Profiles.lua b/BuffRadar/Profiles.lua index c541605..26af3f0 100644 --- a/BuffRadar/Profiles.lua +++ b/BuffRadar/Profiles.lua @@ -1,20 +1,35 @@ --- BuffRadar - Profiles: export/import strings, buff plans, saved profiles and --- presets (/br export, import, plan, profile, preset). Split out of --- BuffRadar.lua (file split Slice E). Loaded after BuffRadar.lua; talks to it --- only through the shared X table. +-- BuffRadar - settings and plan strings, saved profiles and presets. -- Copyright (C) 2026 Malikor. GPLv3 or later. -local _, NS = ... -local X = NS and NS.X -if not X then return end +local _, ns = ... +local X = ns.X -local BLESSINGS, DEFAULTS, Ignore = X.BLESSINGS, X.DEFAULTS, X.Ignore -local Esc, Unesc, SanitizeDB = X.Esc, X.Unesc, X.SanitizeDB -local IsProfileName, PROFILE_MAX_BYTES = X.IsProfileName, X.PROFILE_MAX_BYTES +local settings = X.Settings +local BLESSINGS, DEFAULTS, Ignore = X.BLESSINGS, settings.Defaults, X.Ignore +local IsProfileName, PROFILE_MAX_BYTES = settings.IsProfileName, settings.ProfileMaxBytes local math_floor, math_huge, math_max = math.floor, math.huge, math.max local string_format, table_sort = string.format, table.sort local CLIPBOARD_MAX_BYTES = 16384 +-- Settings export / import: one copyable string. Covers the window look, +-- behavior toggles, buff toggles, rebuff timings and both ignore sets -- +-- not positions, cast counts or stats (those belong to one machine / char). +local EXPORT_KEYS = { "locked", "includeSelf", "avoidPvP", "autoHide", "rebuff", "scale", + "width", "cfgScale", "castMethod", "clickReg", "bgAlpha", "showTitle", "showBorder", + "playSound", "showCounter", "groupOnly", "pauseInCities", "groupCast", "groupCastMin", + "sortMode", "alertSound", "alertSounds", "buffPrio", "clickThrough", "muteInInstance", "showMinimap", "lowMana", + "sync", "requests", "joinDigest", "roleFilter", "showStrip", "idleFade", + "pill", "queueTag", "consumables", "buddySplit", "readyPost", "weaponWatch", "enterFlash", + "scanThrottle", "growUp", "theme", "autoThemePriority", "findBox", "durationBars", "raidMarkers", + "focusWatch", "pets", "auraWatch", "worldWatch", "drinkWatch", "twoCol", + "deathRecap", "wipeReport", "rowGap", "iconSize", + "tooltipLevel", "viewMode", "classColors", "showRealm", "nameTrim", + "scalePerSpec", "gripSnap", "tagSymbols", "reduceMotion", "rangeWatch", "assumeRange", + "fastAura", "modClick", "pullFlash", "fallSound" } + +local function Esc(v) return (tostring(v):gsub("%%", "%%25"):gsub(";", "%%3B"):gsub("=", "%%3D")) end +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 @@ -37,7 +52,7 @@ end function X.Export() local db = X.GetDB() local parts = { "BR1", "complete=1" } - for _, k in ipairs(X.EXPORT_KEYS) do + for _, k in ipairs(EXPORT_KEYS) do local v = db[k] if type(v) == "boolean" then parts[#parts + 1] = k .. "=" .. (v and "1" or "0") elseif type(v) == "number" or type(v) == "string" then parts[#parts + 1] = k .. "=" .. Esc(v) end @@ -85,7 +100,7 @@ do local retiredScalars = { strata = "string", showOutOfRange = "boolean", hideInCombat = "boolean", rangeText = "boolean" } local retiredLayers = { LOW = true, MEDIUM = true, HIGH = true, DIALOG = true } - for _, key in ipairs(X.EXPORT_KEYS) do + for _, key in ipairs(EXPORT_KEYS) do if type(DEFAULTS[key]) ~= "table" then scalarKeys[key], legacyScalars[key] = true, true scalarList[#scalarList + 1] = key @@ -93,12 +108,14 @@ do end for _, key in ipairs({ "compact", "textScale", "charPoint", "pauseInBG", "pauseTaxi", "watchDrop", - "minimapAngle", "rangeText", "pinned", "thornsAnyClassOutdoors", + "minimapAngle", "rangeText", "pinned", "thornsAnyClassOutdoors", "blessingComplement", }) do scalarKeys[key] = true scalarList[#scalarList + 1] = key end + local optionalFalse = { thornsAnyClassOutdoors = true, blessingComplement = true } + local function Encode(value) if type(value) == "boolean" then return value and "1" or "0" end if type(value) == "table" then return table.concat(value, ",", 1, 3) end @@ -109,7 +126,7 @@ do local db = X.GetDB() local parts = { "bgColor=" .. Encode(db.bgColor), "blessingPreferences=1" } for _, key in ipairs(scalarList) do - if key ~= "thornsAnyClassOutdoors" or db[key] then + if not optionalFalse[key] or db[key] then parts[#parts + 1] = key .. "=" .. Encode(db[key]) end end @@ -223,7 +240,7 @@ do scalarFields[key] = true elseif key == "bgColor" or (modern and scalarKeys[key]) or legacyScalars[key] then local value = Decode(key == "bgColor" and "color" or type(DEFAULTS[key]), key, raw) - if value == nil or scalarFields[key] or not X.ProfileScalarValid(key, value) then return nil end + if value == nil or scalarFields[key] or not settings.ProfileScalarValid(key, value) then return nil end patch[key], scalarFields[key] = value, true count = count + 1 elseif (modern and key == "strata") or (not modern and retiredScalars[key]) then @@ -252,7 +269,7 @@ do if not patch.bgColor then return nil end for _, key in ipairs(scalarList) do if not scalarFields[key] and key ~= "autoThemePriority" then - if key == "thornsAnyClassOutdoors" or (key == "assumeRange" and scalarFields.strata) then + if optionalFalse[key] or (key == "assumeRange" and scalarFields.strata) then patch[key] = false else return nil @@ -300,7 +317,7 @@ do local candidate = {} for key, value in pairs(db) do candidate[key] = value end for key, value in pairs(patch) do candidate[key] = value end - SanitizeDB(candidate) + settings.Sanitize(candidate) for key in pairs(patch) do db[key] = candidate[key] end if syncWasEnabled and not db.sync then X.StopCoordination() end X.blockerProfileRevision = (X.blockerProfileRevision or 0) + 1 diff --git a/BuffRadar/Recaps.lua b/BuffRadar/Recaps.lua index 1004188..67b6867 100644 --- a/BuffRadar/Recaps.lua +++ b/BuffRadar/Recaps.lua @@ -145,7 +145,7 @@ local function BuildReadyView() end function X.RaidPreparationSnapshot(personal) - if not X.CLASSIC or not X.InGroup() or InCombatLockdown() or X.PlayerSuspended() then return end + if not X.classic or not X.InGroup() or InCombatLockdown() or X.PlayerSuspended() then return end local report = X.GroupBuffReport(false, true, true) local reagents, incomplete = X.ReagentEstimate(report) local snapshot = { members = {}, reagents = reagents, incomplete = incomplete } @@ -189,7 +189,7 @@ function X.RaidPreparationSnapshot(personal) end function X.RaidPreparationCommand(mode) - if not X.CLASSIC then return end + if not X.classic then return end if mode == "hide" then X.CloseRaidPreparation(); return end if InCombatLockdown() or X.PlayerSuspended() then return end if mode == "next" or mode == "prev" then X.MoveRaidPreparation(mode == "next" and 1 or -1); return end diff --git a/BuffRadar/SavedVariables.lua b/BuffRadar/SavedVariables.lua new file mode 100644 index 0000000..d876f0e --- /dev/null +++ b/BuffRadar/SavedVariables.lua @@ -0,0 +1,476 @@ +-- BuffRadar - SavedVariables schema, validation and load lifecycle. +-- WoW supplies BuffRadarDB before ADDON_LOADED; never read it at file load. +-- Copyright (C) 2026 Malikor. GPLv3 or later. + +local _, ns = ... +local X = ns.X +local DB_VERSION = 21 +local PROFILE_MAX_BYTES = 4000 +local MIN_WIDTH, MAX_WIDTH = 180, 400 + +local DEFAULTS = { + locked = false, + hidden = false, + includeSelf = true, -- your own character gets every buff that suits your class (top of the list) + avoidPvP = true, -- don't list PvP-flagged players unless you're flagged too + autoHide = false, -- hide the window when nobody needs anything + rebuff = 30, -- re-list a player when your buff has less than this many seconds left + scale = 1, + width = 210, -- list window width (corner grip); height always follows the list + cfgScale = 1, -- settings window scale + enabled = {}, + point = nil, + castMethod = "target", -- "target" (target player, cast, restore target), "id", "macro", "rank" + clickDebug = false, + clickReg = "both", -- which mouse half triggers the cast: "both", "down" or "up" + bgColor = { 0.04, 0.05, 0.09 }, + bgAlpha = 0.92, + showTitle = true, + showBorder = true, + playSound = true, -- water droplet when a new name shows up + showCounter = true, -- cast counter at the bottom of the window + castsTotal = 0, -- all-time casts made through BuffRadar + groupOnly = false, -- only show the window while in a party or raid + pauseInCities = true, -- stop scanning in major cities + groupCast = false, -- offer the group version (Prayer of Fortitude etc.) when enough group members need a buff + groupCastMin = 3, -- how many group members must need the buff first + showOutOfRange = false, -- the list only includes targets in cast range + sortMode = "name", -- list order: "name" or "role" (tanks and leaders first) + ignored = {}, -- player names BuffRadar never lists (right-click a row) + rebuffPer = {}, -- per-buff rebuff thresholds in seconds: buff key -> seconds + alertSound = "droplet", -- alert sound: "droplet", "system" or "none" + alertSounds = {}, -- per-alert-kind sound: new/drop/ask/fall -> a sound name (empty = use alertSound) + buffPrio = {}, -- your buff order: buff keys, first offered first (empty = normal order) + blessingPreferences = {}, -- class token -> preferred blessing key + blessingComplement = false, -- offer a different blessing to ungrouped players with another Paladin's copy + plateRestore = {}, -- original values of supported game CVars changed by /br plates + assignmentEnabled = false, + thornsAnyClassOutdoors = false, + buffAssignments = {}, + clickThrough = false, -- while locked, let clicks pass through the window to the game + muteInInstance = false, -- no alert sound while in a dungeon, raid or battleground + showMinimap = true, -- minimap button (the addon compartment works regardless) + minimapAngle = 215, -- minimap button position, degrees + pauseInBG = false, -- pause listing in battlegrounds and arenas + pauseTaxi = false, -- pause listing while on a flight path (1.5.0) + watchDrop = true, -- alert when your single-target buff drops off its holder (1.5.0) + fallSound = false, -- alert when a watched group buff falls off mid-fight (1.15.0, #33) + lowMana = 0, -- pause offering buffs below this mana % (0 = off) (1.4.0) + specProfiles = {}, -- per-spec overrides: spec key -> { enabled=, rebuffPer= } (1.4.0) + 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) + 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) + requests = true, -- tag players who ask for a buff in chat (1.5.0) + joinDigest = true, -- one-line summary when joining a group (1.5.0) + roleFilter = "ALL", -- window list filter: "ALL", "TANK", "HEALER" or "DAMAGER" (1.5.0) + showStrip = true, -- buff toggle strip + filter chips under the title (1.5.0) + scalePerSpec = false, -- remember a window scale per specialization (1.12.0) + specScales = {}, -- spec key -> scale (1.12.0) + gripSnap = true, -- Shift while dragging a scale grip snaps to 75/100/125/150% (1.12.0) + tagSymbols = false, -- add a symbol to row tags so meaning never rests on color (1.12.0) + reduceMotion = false, -- no idle fade, no border flash (1.12.0) + rangeWatch = false, -- say when a player who needs a buff walks into range (1.12.0) + assumeRange = false, -- list players the client refuses to place, flagged as estimated + idleFade = 0, -- fade the window by this % while the mouse is away (0 = off) (1.5.0) + pill = false, -- collapse to a small pill while everyone is buffed (1.6.0) + queueTag = true, -- tag the top row "up next" right after a cast lands (1.6.0) + consumables = false, -- coverage line also tracks flasks, food and runes (1.6.0) + buddySplit = false, -- share the list with other BuffRadar users present (1.6.0) + readyPost = false, -- post the ready-check summary to group chat (leader/assistant) (1.7.0) + deathRecap = true, -- print who was missing buffs when you died (1.9.0) + wipeReport = false, -- print a rebuff report after a wipe (1.9.0) + wizardSeen = false, -- the setup wizard has been run or dismissed (1.9.0) + customThemes = {}, -- your saved themes: { name, bg, border } (1.10.0) + rowGap = 0, -- extra space between rows, 0-8 (1.10.0) + iconSize = 0, -- buff icon size 10-24; 0 = automatic (1.10.0) + strata = "MEDIUM", -- legacy saved value; frames keep the client's default layer + coverParts = {}, -- coverage-line parts switched OFF (absent = on) (1.10.0) + tooltipLevel = "standard", -- row tooltips: minimal | standard | full (1.10.0) + viewMode = "people", -- list view: "people" (one row per player) or "buffs" (one row per buff still needed) + classColors = true, -- row names in class colors (1.10.0) + showRealm = false, -- show -Realm after row names (1.10.0) + nameTrim = 0, -- shorten row names past this many letters, 0 = off (1.10.0) + rowColors = {}, -- colored edge marks on rows: mine|tank|expiring|buddy (1.10.0) + pinned = "", -- full or short name of the player pinned to the top (1.7.0) + weaponWatch = false, -- remind me when my weapon has no temporary enchant (1.7.0) + fastAura = false, -- skip refreshes for aura changes that touch no watched buff (1.14.0, Brief 2) + modClick = false, -- Shift-click a row casts the group version of its buff (1.14.0, Brief 3) + pullFlash = false, -- flash + countdown line when a pull timer starts (1.14.0, Brief 4) + enterFlash = true, -- print a reminder when entering an instance unbuffed (1.7.0) + scanThrottle = false, -- halve the steady rescan rate in groups over 20 (1.7.0) + history = {}, -- last 50 casts through BuffRadar: { t, spell, who } (1.7.0) + growUp = false, -- the list grows upward from a fixed bottom edge (1.8.0) + hideInCombat = true, -- no buff targets are available while you are in combat + twoCol = false, -- two columns when the list is long (1.9.0) + theme = "midnight", -- window color theme (1.8.0) + autoThemePriority = "", -- an empty setting uses the built-in addon priority + findBox = false, -- name finder box on the window (1.8.0) + durationBars = false, -- thin bar per row: time left on the expiring buff (1.8.0) + raidMarkers = false, -- show raid target markers on rows (1.8.0) + rangeText = false, -- word band ("near") on out-of-range rows (1.8.0) + focusWatch = false, -- a line about your focus target's buffs (1.8.0) + pets = false, -- list group pets that need buffs (1.8.0) + auraWatch = false, -- watch your own aura / aspect (Forever) (1.8.0) + worldWatch = false, -- show your active world buffs on the coverage line (Forever) (1.8.0) + drinkWatch = false, -- mark healers who are drinking (Forever) (1.8.0) + buffContext = {}, -- per-buff context: buff key -> "raid" | "instance" (1.8.0) + offenders = {}, -- group sessions where a player was seen unbuffed: name -> count (1.8.0) + autoProfile = {}, -- load a named profile per context: raid/dungeon/pvp/world/solo -> name (1.6.0) + customSpells = {}, -- extra spell IDs to watch, added with /br custom (1.6.0) + customGroup = {}, -- your own group-cast pairs: spell name -> group spell name, /br grouppair (1.15.0) + stats = {}, -- all-time casts per spell name: name -> count +} + +local KNOWN_KEYS = { point = true, dbVersion = true } +for k in pairs(DEFAULTS) do KNOWN_KEYS[k] = true end +local ENUMS = { + castMethod = { target = true, id = true, macro = true, rank = true }, + clickReg = { both = true, down = true, up = true }, + sortMode = { name = true, role = true, distance = true, need = true }, + roleFilter = { ALL = true, TANK = true, HEALER = true, DAMAGER = true }, + alertSound = { droplet = true, system = true, none = true }, + strata = { LOW = true, MEDIUM = true, HIGH = true, DIALOG = true }, + tooltipLevel = { minimal = true, standard = true, full = true }, + viewMode = { people = true, buffs = true }, +} +local RANGES = { bgAlpha = { 0, 1 }, scale = { 0.5, 2 }, cfgScale = { 0.5, 2 }, + width = { MIN_WIDTH, MAX_WIDTH }, rebuff = { 0, 3600 }, castsTotal = { 0, 1e9 }, + groupCastMin = { 2, 40 }, minimapAngle = { 0, 360 }, + lowMana = { 0, 100 }, textScale = { 0.8, 1.5 }, idleFade = { 0, 90 }, + rowGap = { 0, 8 }, iconSize = { 0, 24 }, nameTrim = { 0, 24 } } + +local function IsNumber(v) + return type(v) == "number" and v == v and v ~= math.huge and v ~= -math.huge +end + +local function Clamp(v, lo, hi) + return math.max(lo, math.min(hi, v)) +end + +local function IsProfileName(name) + return type(name) == "string" and #name <= 40 and name:match("^[%w_%-]+$") ~= nil +end + +local MAX_AUTO_PRIORITY_BYTES = 512 + +local function OrderedAutoThemeAddons(value) + local order, seen = {}, {} + if type(value) == "string" and value ~= "" and #value <= MAX_AUTO_PRIORITY_BYTES then + local byID = {} + for _, entry in ipairs(X.AUTO_THEME_ADDONS) do byID[entry[2]] = entry end + for token in value:gmatch("[^,]+") do + local id = token:match("^%s*(.-)%s*$"):lower() + if byID[id] and not seen[id] then + order[#order + 1], seen[id] = byID[id], true + end + end + end + for _, entry in ipairs(X.AUTO_THEME_ADDONS) do + if not seen[entry[2]] then order[#order + 1] = entry end + end + return order +end + +local function EncodeAutoThemePriority(order) + local ids, isDefault = {}, true + for i, entry in ipairs(order) do + ids[i] = entry[2] + if entry ~= X.AUTO_THEME_ADDONS[i] then isDefault = false end + end + return isDefault and "" or table.concat(ids, ",") +end + +local function ProfileScalarValid(key, value) + if key == "theme" then return #value >= 1 and #value <= 24 end + if key == "autoThemePriority" then return #value <= MAX_AUTO_PRIORITY_BYTES end + local choices = ENUMS[key] + return not choices or choices[value] == true +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 clean = {} + for key, item in pairs(value) do + if type(key) == "string" and valid(item) then clean[key] = item end + 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 CopyBooleanMap(value) return CopyStringMap(value, IsBoolean) end +local function CopyNumberMap(value) return CopyStringMap(value, IsNonnegative) end + +local function IsPoint(value) + return type(value) == "table" and type(value[1]) == "string" and type(value[2]) == "string" + and IsNumber(value[3]) and IsNumber(value[4]) +end + +local function CopyColor(value) + if type(value) == "table" and IsNumber(value[1]) and IsNumber(value[2]) and IsNumber(value[3]) then + return { Clamp(value[1], 0, 1), Clamp(value[2], 0, 1), Clamp(value[3], 0, 1) } + end +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 + end + return clean +end + +local function CopyPlateRestore(value) + local clean = {} + for _, name in ipairs(X.friendlyPlateCVars) do + if IsBoolean(value[name]) then clean[name] = value[name] end + end + for _, name in ipairs({ "nameplateShowAll", X.friendlyPlateNamesCVar }) do + if IsBoolean(value[name]) then clean[name] = value[name] end + end + return clean +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 } + end + end + while #clean > 50 do table.remove(clean, 1) end + return clean +end + +local function CopyCustomThemes(value) + local clean, seen = {}, {} + for _, theme in ipairs(value) do + if type(theme) == "table" and type(theme.name) == "string" and #theme.name >= 1 and #theme.name <= 24 then + local key = theme.name:lower() + if not seen[key] then + local bg, border = CopyColor(theme.bg), CopyColor(theme.border) + if bg and border then + seen[key] = true + clean[#clean + 1] = { name = theme.name, bg = bg, border = border } + if #clean >= 4 then break end + end + end + end + end + return clean +end + +local function CopyCustomSpells(value) + local clean, seen = {}, {} + for _, id in ipairs(value) do + if IsNumber(id) and id >= 1 and id <= 2000000 and not seen[id] then + seen[id] = true + clean[#clean + 1] = math.floor(id) + if #clean >= 20 then break end + end + end + 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 + end + return clean +end + +local function CopyBuffPriority(value) + local clean, seen = {}, {} + for _, key in ipairs(value) do + if type(key) == "string" and #key <= 40 and not seen[key] then + seen[key] = true + clean[#clean + 1] = key + if #clean >= 24 then break end + end + end + return clean +end + +local TABLE_FIELDS = { + bgColor = function(value) + local fallback = DEFAULTS.bgColor + return CopyColor(value) or { fallback[1], fallback[2], fallback[3] } + end, + alertSounds = function(value) + local clean = {} + for kind, choice in pairs(value) do + if (kind == "new" or kind == "drop" or kind == "ask" or kind == "fall") and ENUMS.alertSound[choice] then + clean[kind] = choice + end + end + return clean + end, + buffPrio = CopyBuffPriority, + buffAssignments = X.CopyAssignments, + plateRestore = CopyPlateRestore, + blessingPreferences = function(value) + local clean = {} + for class, key in pairs(value) do + if type(key) == "string" and X.BLESSING_CLASSES[class] and X.BLESSINGS[key] then clean[class] = key end + end + return clean + end, + enabled = CopyBooleanMap, + ignored = CopyBooleanMap, + coverParts = CopyBooleanMap, + 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 + 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 + end + return clean + end, + profiles = 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 + 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, + customThemes = CopyCustomThemes, + rowColors = function(value) + local clean = {} + for rule, color in pairs(value) do + if rule == "mine" or rule == "tank" or rule == "expiring" or rule == "buddy" then + clean[rule] = CopyColor(color) + end + end + return clean + end, + buffContext = function(value) + return CopyStringMap(value, function(context) return context == "raid" or context == "instance" end) + end, + rebuffPer = CopyNumberMap, + stats = CopyNumberMap, + offenders = CopyNumberMap, +} + +local function CleanSetting(key, value, default) + local kind = type(default) + if kind == "table" then + return TABLE_FIELDS[key](type(value) == "table" and value or {}) + elseif kind == "number" then + if not IsNumber(value) then value = default end + local range = RANGES[key] + if range then value = Clamp(value, range[1], range[2]) end + if key == "castsTotal" then value = math.floor(value) end + elseif type(value) ~= kind then + return 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 == "autoThemePriority" and value ~= "" then + return EncodeAutoThemePriority(OrderedAutoThemeAddons(value)) + end + end + return value +end + +local function CleanTheme(name, themes) + local id = name:lower() + if X.THEMES[id] or id == "custom" then return id end + for _, theme in ipairs(themes) do + if theme.name == name then return name end + end + return "custom" +end + +-- Also used for detached profile candidates, without publishing a new DB. +local function Sanitize(saved) + if type(saved) ~= "table" then saved = {} end + for key in pairs(saved) do + if not KNOWN_KEYS[key] then saved[key] = nil end + end + for key, default in pairs(DEFAULTS) do + 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 + if not IsNumber(saved.dbVersion) then saved.dbVersion = nil end + return saved +end + +local function Migrate(saved) + local previous = saved.dbVersion or 0 + saved.showOutOfRange, saved.hideInCombat = false, true + if not X.classic then + if saved.castMethod == "id" or saved.castMethod == "rank" then saved.castMethod = "target" end + saved.groupCast = false + end + if previous < 3 then saved.castMethod, saved.clickReg = "target", "both" end + if previous < 4 then saved.includeSelf = true end + -- Forever shadow protection became an instance-only default in v10. + if previous < 10 and X.classic and saved.buffContext.SHADOW_PROT == nil then + saved.buffContext.SHADOW_PROT = "instance" + end + -- v11 added the wizard; genuine existing users should not see the hint. + if previous >= 5 and previous < 11 then saved.wizardSeen = true end + -- Versions with no transformation take the defaults supplied by Sanitize. + if previous < DB_VERSION then saved.dbVersion = DB_VERSION end +end + +local db +local listeners = {} + +local function Load(migrate) + local saved = Sanitize(BuffRadarDB) + if migrate then Migrate(saved) end + BuffRadarDB, db = saved, saved + for _, listener in ipairs(listeners) do listener(db) end +end + +local function OnDBLoaded(listener) + listeners[#listeners + 1] = listener + if db then listener(db) end +end + +X.GetDB = function() return db end +X.OnDBLoaded = OnDBLoaded +X.Settings = { + Load = Load, + Sanitize = Sanitize, + Defaults = DEFAULTS, + MinWidth = MIN_WIDTH, + MaxWidth = MAX_WIDTH, + ProfileMaxBytes = PROFILE_MAX_BYTES, + IsProfileName = IsProfileName, + ProfileScalarValid = ProfileScalarValid, + AutoThemeOrder = OrderedAutoThemeAddons, + EncodeAutoThemeOrder = EncodeAutoThemePriority, +} diff --git a/BuffRadar/Slash.lua b/BuffRadar/Slash.lua index 0ab99d4..baae036 100644 --- a/BuffRadar/Slash.lua +++ b/BuffRadar/Slash.lua @@ -1,51 +1,42 @@ --- BuffRadar - Slash: every /br command (HandleSlash and its helpers: --- OnOff, ListBuffs, X.Context, X.AutoProfileCheck, X.SelfTest). --- Loaded after BuffRadar.lua and Config.lua through the .toc. This is --- file-split Slice C (1.15.0): the code below is the slash do-block that --- used to sit at the bottom of BuffRadar.lua, moved verbatim; it reaches --- the main file's locals through X.slashAPI, which BuffRadar.lua fills --- in before this file loads. State the main file owns and reassigns --- (the window and build/session flags) is re-read through --- syncState() at each command, so nothing here can go stale. +-- BuffRadar - /br command parsing and dispatch. -- Copyright (C) 2026 Malikor. GPLv3 or later. -local _, NS = ... -NS = NS or {} -local X = NS.X or {} -NS.X = X -local A = X.slashAPI or {} -local L = X.cfgAPI.L +local _, ns = ... +local X = ns.X +local core = X.Core +local L = X.L local db -- the live settings table; read fresh by syncState (X.GetDB) -local Print, Refresh, PlayAlert = A.Print, A.Refresh, A.PlayAlert -local RefreshConfig, OpenConfig = A.RefreshConfig, A.OpenConfig -local ApplyAppearance, ApplyGeometry = A.ApplyAppearance, A.ApplyGeometry -local BuildBuffList, BuildUI, InvalidateRows = A.BuildBuffList, A.BuildUI, A.InvalidateRows -local IsOn, FriendlyPlatesOn = A.IsOn, A.FriendlyPlatesOn -local InGroup, InInstanceNow, InMajorCity = A.InGroup, A.InInstanceNow, A.InMajorCity -local MakeMacro, OpenKeybinds = A.MakeMacro, A.OpenKeybinds -local RefreshMinimapButton, RestorePosition = A.RefreshMinimapButton, A.RestorePosition -local SpellName, UpdateCounter, QueueRefresh = A.SpellName, A.UpdateCounter, A.QueueRefresh -local myBuffs, myBlessing = A.myBuffs, A.myBlessing -local Ignore = A.Ignore -local BLESSINGS, BUFF_DEFS = A.BLESSINGS, A.BUFF_DEFS -local ranks, rows = A.ranks, A.rows -local CLASSIC_FEATURES = A.CLASSIC_FEATURES -local MAX_WIDTH, MIN_WIDTH = A.MAX_WIDTH, A.MIN_WIDTH +local Print, Refresh, PlayAlert = X.Print, X.Refresh, core.PlayAlert +local RefreshConfig, OpenConfig = X.RefreshConfig, X.OpenConfig +local ApplyAppearance, ApplyGeometry = X.ApplyAppearance, X.ApplyGeometry +local BuildBuffList, BuildUI, InvalidateRows = core.BuildBuffList, X.BuildUI, X.InvalidateRows +local IsOn, FriendlyPlatesOn = core.IsOn, X.FriendlyPlatesOn +local InGroup, InInstanceNow, InMajorCity = X.InGroup, core.InInstance, core.InMajorCity +local MakeMacro, OpenKeybinds = core.MakeMacro, core.OpenKeybinds +local RefreshMinimapButton = X.RefreshMinimapButton +local SpellName, UpdateCounter, QueueRefresh = core.SpellName, X.UpdateCounter, core.QueueRefresh +local myBuffs, myBlessing = core.Buffs, core.BlessingsByClass +local Ignore = X.Ignore +local BLESSINGS, BUFF_DEFS = X.BLESSINGS, X.BUFF_DEFS +local ranks = core.Ranks +local CLASSIC_FEATURES = X.classic +local MIN_WIDTH, MAX_WIDTH = X.Settings.MinWidth, X.Settings.MaxWidth local pairs, ipairs, next, type, tonumber, tostring, pcall = pairs, ipairs, next, type, tonumber, tostring, pcall local math_floor, math_min = math.floor, math.min local string_format = string.format local table_sort = table.sort local wipe = wipe or function(t) for k in pairs(t) do t[k] = nil end return t end --- State owned by BuffRadar.lua; refreshed at every command entry. +-- Read the current settings, scan and window state at command entry. local frame, built, hasAnyBuff, sessionShow local lastError, bookCount, nextWrapped, nextCombatDriver local function syncState() db = X.GetDB() - local s = A.getState() - frame, built, hasAnyBuff, sessionShow = s.frame, s.built, s.hasAnyBuff, s.sessionShow - lastError, bookCount, nextWrapped, nextCombatDriver = s.lastError, s.bookCount, s.nextWrapped, s.nextCombatDriver + frame, built = X.GetFrame(), X.WindowReady() + hasAnyBuff, sessionShow = core.HasAnyBuff(), core.SessionShow() + lastError, bookCount = core.LastError(), core.BookCount() + nextWrapped, nextCombatDriver = X.NextBindState() end local function OnOff(v) return v and "|cff00ff00on|r" or "|cffff4040off|r" end @@ -264,14 +255,12 @@ local function HandleSlash(msg) if cmd == "" then if frame and frame:IsShown() then db.hidden, sessionShow = true, false - A.setSessionShow(sessionShow) - A.setSessionShow(sessionShow) + core.SetSessionShow(sessionShow) frame:Hide() Print("Hidden.") else db.hidden, sessionShow = false, true - A.setSessionShow(sessionShow) - A.setSessionShow(sessionShow) + core.SetSessionShow(sessionShow) Print("Shown." .. (hasAnyBuff and "" or " (No supported buffs found; try /br debug)")) end elseif cmd == "show" then @@ -408,9 +397,12 @@ local function HandleSlash(msg) UpdateCounter() Print("Cast counts reset.") elseif cmd == "macro" then - MakeMacro(false) - elseif cmd == "key" or cmd == "keybind" then + MakeMacro() + elseif cmd == "key" or cmd == "keybind" or cmd == "gamepad" then OpenKeybinds() + if cmd == "gamepad" and not InCombatLockdown() and not X.PlayerSuspended() then + Print(L["Bind a controller button to BuffRadar's Cast next buff, or put /br macro on an action bar."]) + end elseif cmd == "clicks" then db.clickDebug = not db.clickDebug Print("Click diagnostics " .. OnOff(db.clickDebug)) @@ -437,11 +429,7 @@ local function HandleSlash(msg) if m == "both" or m == "down" or m == "up" then if InCombatLockdown() then Print("Can't change this during combat."); return end db.clickReg = m - for _, row in ipairs(rows) do - if m == "down" then row:RegisterForClicks("AnyDown") - elseif m == "up" then row:RegisterForClicks("AnyUp") - else row:RegisterForClicks("AnyUp", "AnyDown") end - end + X.ApplyRowClickRegistration() Print("Clicks trigger on: " .. m) else Print("Usage: /br clickreg both|down|up (currently " .. tostring(db.clickReg) .. ")") @@ -572,7 +560,6 @@ local function HandleSlash(msg) local n = tonumber(rest) if n and n >= 0 and n <= 90 then db.idleFade = math_floor(n) - X.curAlpha = nil Print(string.format("Idle fade: %d%% while the mouse is away (0 = off).", db.idleFade)) else Print("Usage: /br fade <0-90> (currently " .. tostring(db.idleFade or 0) .. ")") @@ -962,18 +949,15 @@ local function HandleSlash(msg) end elseif cmd == "twocol" then db.twoCol = not db.twoCol - X.cols = nil -- force the column split to re-decide on the next refresh Print("Two columns when the list is long " .. OnOff(db.twoCol) .. " — on: past 8 rows the list splits into two columns.") Refresh() elseif cmd == "find" then if rest == "" or rest:lower() == "off" then - X.search = "" - if X.findEdit then X.findEdit:SetText("") end + X.SetFinderText("") Print("Name finder cleared — everyone is listed again.") else - X.search = rest:lower() - if X.findEdit then X.findEdit:SetText(rest) end + X.SetFinderText(rest) Print("Name finder: only names matching '" .. rest .. "' are listed. /br find off clears it.") end Refresh() @@ -1157,7 +1141,16 @@ local function HandleSlash(msg) local cls, bkey, bname = rest:match("^(%S*)%s*(%S*)%s*(.-)%s*$") cls = (cls or ""):upper() bkey = (bkey or ""):upper() - if cls == "PLAYER" then + if cls == "COMPLEMENT" then + if bname ~= "" or (bkey ~= "" and bkey ~= "ON" and bkey ~= "OFF") then + Print(L["Usage: /br bless complement on|off"]) + elseif bkey ~= "" and not X.SetBlessingComplement(bkey == "ON") then + Print(L["Learn a blessing before changing this setting."]) + else + Print(string.format(L["Complement Nearby Blessings: %s"], db.blessingComplement and L["On"] or L["Off"])) + end + return + elseif cls == "PLAYER" then local name, key = rest:match("^%S+%s+(.+)%s+(%S+)%s*$") if not name then Print("Usage: /br bless player .") @@ -1367,14 +1360,9 @@ local function HandleSlash(msg) else Print(string.format("Usage: /br width <%d - %d>", MIN_WIDTH, MAX_WIDTH)) end - elseif cmd == "reset" then - X.ClearSavedPoint() - if frame then RestorePosition() end - Print("Position reset.") - elseif cmd == "resetpos" then - X.ClearSavedPoint() - if frame then RestorePosition() end - Print("Window position reset to the default spot.") + elseif cmd == "reset" or cmd == "resetpos" then + X.ResetWindowPosition() + Print(cmd == "reset" and "Position reset." or "Window position reset to the default spot.") elseif cmd == "buffs" then ListBuffs() elseif cmd == "toggle" then @@ -1411,7 +1399,8 @@ local function HandleSlash(msg) Print(rest .. " isn't ignored for this session.") end elseif cmd == "plates" then - X.EnableFriendlyNameplates(Print) + X.ChangeFriendlyNameplates(rest == "" and "on" or rest:lower(), Print) + return elseif X.ext[cmd] then X.ext[cmd](rest) else @@ -1421,6 +1410,7 @@ local function HandleSlash(msg) Print(L[" /br config navigate - keyboard navigation /br config narrate - keyboard navigation with speech"]) Print(" /br macro - create a 'BuffRadar' macro that casts the next buff") Print(" /br key - open Key Bindings to bind 'Cast next buff'") + Print(L["/br gamepad - set up controller buffing"]) Print(" /br sound - toggle the water droplet alert") Print(" /br group - only show the window in a party or raid") Print(" /br cities - pause scanning in major cities") @@ -1432,7 +1422,7 @@ local function HandleSlash(msg) Print(" /br mode " .. (CLASSIC_FEATURES and "target|id|macro|rank" or "target|macro") .. " - how clicks cast (default target)") Print(" /br clickreg both|down|up - which half of the click casts") - Print(" /br plates - turn on friendly nameplates (needed for non-group players)") + Print(L["Usage: /br plates on|off|names|bars|restore"]) if CLASSIC_FEATURES then Print(" /br nearby - diagnose nearby players and your current target") end if CLASSIC_FEATURES then Print(" /br groupcast [on|off|] - offer group buffs when n+ players need one") @@ -1494,6 +1484,7 @@ local function HandleSlash(msg) Print(" /br autoprofile - load a profile by context") if CLASSIC_FEATURES then Print(" /br bless [name] - blessing planner") + Print(L["Usage: /br bless complement on|off"]) Print(" /br buffassign [on|off|preview] - class and role buff assignments") Print(" /br practice · /br undo - practice blocker edits or undo the last one") Print(" /br coverage - read-only buff coverage by raid subgroup") @@ -1508,5 +1499,8 @@ local function HandleSlash(msg) Refresh() end -X.HandleSlash = HandleSlash X.OnOff = OnOff +SlashCmdList.BUFFRADAR = function(msg) + local ok, err = pcall(HandleSlash, msg) + if not ok then Print("|cffff4040error:|r " .. tostring(err)) end +end diff --git a/BuffRadar/Window.lua b/BuffRadar/Window.lua index 2fbf30b..e534094 100644 --- a/BuffRadar/Window.lua +++ b/BuffRadar/Window.lua @@ -1,47 +1,60 @@ --- BuffRadar - Window: the main window's builder (BuildUI), the toggle --- strip, filter chips and idle fade (1.5.0), the Cast Next / group cast --- buttons and their secure bindings, and the scale / edge drag helpers. --- Loaded after BuffRadar.lua through the .toc. This is file-split Slice G --- (1.15.34): the code below moved verbatim from BuffRadar.lua and reaches --- that file's locals through X.winAPI, which BuffRadar.lua fills in --- before this file loads. BuildUI creates the window handles here and --- hands them back with PublishUI() before any main-file code reads them; --- the settings table arrives through X.dbSinks. +-- BuffRadar - main window, rows, layout and secure click surfaces. +-- Consumes the core's scan results; this file owns the frames and their caches. -- Copyright (C) 2026 Malikor. GPLv3 or later. -local _, NS = ... -local X = NS and NS.X -if not X or not X.winAPI then return end -local A = X.winAPI - -local db = X.GetDB and X.GetDB() -- nil until ADDON_LOADED; X.dbSinks updates it -X.dbSinks = X.dbSinks or {} -X.dbSinks[#X.dbSinks + 1] = function(value) db = value end - -local L, Print, IsOn, QueueRefresh = A.L, A.Print, A.IsOn, A.QueueRefresh -local OpenConfig, RefreshConfig = A.OpenConfig, A.RefreshConfig -local ApplyAppearance, ApplyGeometry = A.ApplyAppearance, A.ApplyGeometry -local RestorePosition, SavePosition, UpdateCounter = A.RestorePosition, A.SavePosition, A.UpdateCounter -local Bind, CreateRow, BuildMinimapButton = A.Bind, A.CreateRow, A.BuildMinimapButton -local SafeString, SpellIcon = A.SafeString, A.SpellIcon -local myBuffs, myBlessing = A.myBuffs, A.myBlessing -local CLASSIC_FEATURES, MAX_ROWS, WIDTH = A.CLASSIC_FEATURES, A.MAX_ROWS, A.WIDTH -local HEADER_H, FOOTER_H, MIN_WIDTH, MAX_WIDTH = A.HEADER_H, A.FOOTER_H, A.MIN_WIDTH, A.MAX_WIDTH -local pairs, ipairs, pcall = pairs, ipairs, pcall -local math_floor = math.floor -local string_format = string.format +local _, addon = ... +local X = addon.X +local core = X.Core +local db +X.OnDBLoaded(function(value) db = value end) + +local L, Print, IsOn, QueueRefresh = X.L, X.Print, core.IsOn, core.QueueRefresh +local Bind, SpellIcon, SpellName = core.Bind, core.SpellIcon, core.SpellName +local Readable, SafeString, Ignore = X.Readable, core.SafeString, X.Ignore +local myBuffs, myBlessing = core.Buffs, core.BlessingsByClass +local ALL, BUFF_DEFS, CLASSIC_FEATURES = X.ALL, X.BUFF_DEFS, X.classic +local math_floor, math_min, math_max, math_ceil, math_huge = math.floor, math.min, math.max, math.ceil, math.huge +local string_format, table_sort = string.format, table.sort local wipe = wipe or function(t) for k in pairs(t) do t[k] = nil end return t end -local GetTime, InCombatLockdown = GetTime, InCombatLockdown -local UnitName, UnitLevel = UnitName, UnitLevel +local GetTime, InCombatLockdown, UnitLevel = GetTime, InCombatLockdown, UnitLevel + +local MAX_ROWS = 15 +local ROW_H = 24 +local WIDTH = X.Settings.Defaults.width +local MIN_WIDTH, MAX_WIDTH = X.Settings.MinWidth, X.Settings.MaxWidth +local HEADER_H = 24 +local MAX_ICONS = 5 +local FOOTER_H = 16 --- Window handles BuildUI creates. BuffRadar.lua keeps its own copies for --- the scan and refresh; PublishUI() hands these over as soon as they exist. local frame, title, countText, emptyText, overflowText, combatText, nextBtn, coverText -local footerText, grip -local built = false -local function PublishUI() - A.setUI(frame, title, countText, emptyText, overflowText, combatText, - nextBtn, coverText, footerText, grip, built) +local footerText, focusText, gear, closeButton, nextPreview, nearbyButton +local bar, stripButtons, chipButtons, stripState, findBar, findEdit +local grip, leftGrip, widthHandle, groupBtn, pill +local rows, built = {}, false +local rowMouseButtons, rowLeftPress = {}, nil +local viewport, viewportCount, rowOffset +local viewportMode, viewportSearch, viewportRole, viewportTwoCol, rowWheelEnabled +local columns, rowsPerColumn, previousRowsTall = 1, MAX_ROWS, nil +local rowHeight, topHeight = ROW_H, HEADER_H +local titleLayoutState, titleKey, geometryPending, appearancePending, flashPending +local currentAlpha, pillPeek, groupWrapped +local lastCounterSession, lastCounterTotal, lastCounterRoom + +-- Widget writes only when the value actually changes (no redundant redraws). +local function SetTextIfChanged(fs, text) + if fs.cText ~= text then fs.cText = text; fs:SetText(text) end +end +local function SetShownIfChanged(w, show) + if (w:IsShown() and true or false) ~= show then + if show then w:Show() else w:Hide() end + end +end +-- Height changes are safe to make freely: the frame is anchored by its +-- TOPLEFT corner only (see SavePosition/RestorePosition), so growing or +-- shrinking the height moves only the bottom edge -- the list grows +-- downward and the top of the window never moves. +local function SetHeightIfChanged(f, h) + if f.cHeight ~= h then f.cHeight = h; f:SetHeight(h) end end --------------------------------------------------------------------------- @@ -49,22 +62,22 @@ end -- title carries one icon button per buff you can cast (click toggles it, -- like the Buffs tab) and the role filter chips on the right. --------------------------------------------------------------------------- -function X.BarHeight() - return (db and db.showStrip and A.hasAnyBuff()) and 18 or 0 +local function BarHeight() + return (db and db.showStrip and core.HasAnyBuff()) and 18 or 0 end -function X.RefreshStrip() - if not X.stripBtns or not db then return end +local function RefreshStrip() + if not stripButtons or not db then return end local parts = {} for _, b in ipairs(myBuffs) do parts[#parts + 1] = b.key .. (IsOn(b.key, b.default) and "1" or "0") end if next(myBlessing) then parts[#parts + 1] = "BLESSINGS" .. (IsOn("BLESSINGS", true) and "1" or "0") end - local sig = table.concat(parts, ",") .. "|" .. A.bookCount() - if sig == X.stripSig then return end - X.stripSig = sig + local sig = table.concat(parts, ",") .. "|" .. core.BookCount() + if sig == stripState then return end + stripState = sig local i = 0 local function place(key, name, default) i = i + 1 - local b = X.stripBtns[i] + local b = stripButtons[i] if not b then return end b.buffKey, b.buffName, b.buffDefault = key, name, default local on = IsOn(key, default) @@ -78,12 +91,12 @@ function X.RefreshStrip() local _, anyB = next(myBlessing) if anyB then place("BLESSINGS", anyB.name, true) end end - for j = i + 1, #X.stripBtns do X.stripBtns[j]:Hide() end + for j = i + 1, #stripButtons do stripButtons[j]:Hide() end end function X.RefreshChips() - if not X.chipBtns or not db then return end - for _, b in ipairs(X.chipBtns) do + if not chipButtons or not db then return end + for _, b in ipairs(chipButtons) do if b.roleKey == db.roleFilter then b.fs:SetTextColor(1, 0.85, 0.3) else b.fs:SetTextColor(0.55, 0.55, 0.55) end end @@ -94,7 +107,7 @@ end -- refresh ticker (no per-frame work). function X.UpdateFade() if not frame or not db then return end - local close = X.closeButton + local close = closeButton local over = (frame.IsMouseOver and frame:IsMouseOver()) or (close and close:IsShown() and close.IsMouseOver and close:IsMouseOver()) if close and not InCombatLockdown() then @@ -121,15 +134,139 @@ function X.UpdateFade() end local target = 1 if db.idleFade and db.idleFade > 0 and not db.reduceMotion and not frame.isMoving and not (grip and grip.isSizing) - and not (X.gripL and X.gripL.isSizing) and not (X.edge and X.edge.isSizing) then + and not (leftGrip and leftGrip.isSizing) and not (widthHandle and widthHandle.isSizing) then if not over then target = 1 - db.idleFade / 100 end end - if X.curAlpha ~= target then - X.curAlpha = target + if currentAlpha ~= target then + currentAlpha = target frame:SetAlpha(target) end end +-- Anchor at the growing edge's opposite corner so row count changes never +-- move the saved position. Legacy anchors are converted when restored. +local function SavePosition() + if db.growUp then + -- Grow-up form: the bottom-left corner is the anchor (see X.ApplyAnchor). + local left, bottom = frame:GetLeft(), frame:GetBottom() + if left and bottom then + frame:ClearAllPoints() + frame:SetPoint("BOTTOMLEFT", UIParent, "BOTTOMLEFT", left, bottom) + db.point = { "BOTTOMLEFT", "BOTTOMLEFT", left, bottom } + if db.charPoint then + local k = X.CharKey() + if k then db.pointByChar[k] = db.point end + end + return + end + end + local left, top = frame:GetLeft(), frame:GetTop() + if left and top then + -- Store the top-left corner in screen coordinates (origin bottom-left; + -- GetLeft/GetTop and SetPoint offsets use the same coordinate system + -- for this frame). Re-anchor in that form right away, too: + -- StopMovingOrSizing can leave the frame anchored by whatever point + -- the drag used, which would bring the jumping back until next reload. + frame:ClearAllPoints() + frame:SetPoint("TOPLEFT", UIParent, "BOTTOMLEFT", left, top) + db.point = { "TOPLEFT", "BOTTOMLEFT", left, top } + else + -- Position not measurable yet (frame never laid out): keep whatever + -- anchor the drag left rather than saving nothing. RestorePosition + -- converts a non-TOPLEFT anchor like this one on the next load. + local p, _, rp, x, y = frame:GetPoint() + if p then db.point = { p, rp, x, y } end + end + if db.charPoint then + local k = X.CharKey() + if k and db.point then db.pointByChar[k] = db.point end + end +end + +-- Where a named anchor point sits inside a frame, as fractions of its +-- width (from the left edge) and height (from the bottom edge). +local POINT_FRACTION = { + TOPLEFT = { 0, 1 }, TOP = { 0.5, 1 }, TOPRIGHT = { 1, 1 }, + LEFT = { 0, 0.5 }, CENTER = { 0.5, 0.5 }, RIGHT = { 1, 0.5 }, + BOTTOMLEFT = { 0, 0 }, BOTTOM = { 0.5, 0 }, BOTTOMRIGHT = { 1, 0 }, +} + +-- Forget the saved window spot (shared and per-character), so the next +-- RestorePosition lands on the default anchor. +local function ClearSavedPoint() + db.point = nil + if db.charPoint then + local k = X.CharKey() + if k then db.pointByChar[k] = nil end + end +end + +local function RestorePosition() + 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.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]) + return + end + if not db.point then + -- Default spot, in top-left form: the pre-1.3.1 default anchored the + -- frame's LEFT point at (40, 80) from the screen's left edge; at the + -- height the frame is built with, that puts the top-left corner half + -- a build-height above it. + frame:SetPoint("TOPLEFT", UIParent, "LEFT", 40, 80 + (HEADER_H + 30) / 2) + return + end + local p, rp, x, y = db.point[1], db.point[2], db.point[3], db.point[4] + local f = POINT_FRACTION[p] + if p == "TOPLEFT" or not f then + frame:SetPoint(p, UIParent, rp, x, y) + return + end + -- Legacy save (1.3.0 and earlier stored the drag anchor verbatim, e.g. + -- LEFT or CENTER): convert it to a TOPLEFT anchor against the same + -- point of UIParent. The top-left corner sits (-fx * W, (1 - fy) * H) + -- from the old anchor point, so with the frame's current size the + -- window does not move at all in this conversion -- it just stops + -- moving afterwards, when its height starts changing. The height at + -- drag time was never saved, so this preserves the position as + -- restored now, not necessarily the exact top edge seen while dragging. + local w, h = frame:GetWidth(), frame:GetHeight() + db.point = { "TOPLEFT", rp, x - f[1] * w, y + (1 - f[2]) * h } + frame:SetPoint("TOPLEFT", UIParent, rp, db.point[3], db.point[4]) +end + +function X.ResetWindowPosition() + ClearSavedPoint() + if frame then RestorePosition() end +end + +local function InstallCombatDriver(button, snippet) + if not RegisterStateDriver then return false end + local ok, accepted = pcall(button.SetAttribute, button, "_onstate-combat", snippet) + if not ok or accepted == false then return false end + ok, accepted = pcall(RegisterStateDriver, button, "combat", "[@player,dead][combat] combat; nocombat") + return ok and accepted ~= false +end + -- The keybind / macro button. Like the rows, it's set up between clicks (never during one). -- It casts on press when "ActionButtonUseKeyDown" is on and on release otherwise, so one -- key press = one cast. It clears itself after each use and whenever combat starts. @@ -140,11 +277,11 @@ local function ApplyNextRegistration() else nextBtn:RegisterForClicks("LeftButtonUp") end - if X.groupBtn then + if groupBtn then if GetCVarBool and GetCVarBool("ActionButtonUseKeyDown") then - X.groupBtn:RegisterForClicks("LeftButtonDown") + groupBtn:RegisterForClicks("LeftButtonDown") else - X.groupBtn:RegisterForClicks("LeftButtonUp") + groupBtn:RegisterForClicks("LeftButtonUp") end end end @@ -154,7 +291,7 @@ local nextWrapped, nextCombatDriver = false, false local function ClearNext() if not nextBtn or InCombatLockdown() then return end nextBtn.entry = nil - if nextBtn.isClear then return end -- already disarmed: skip four protected writes + if nextBtn.isClear then return end -- already disarmed: skip protected writes nextBtn:SetAttribute("type", nil) nextBtn:SetAttribute("spell", nil) nextBtn:SetAttribute("unit", nil) @@ -168,19 +305,18 @@ local function ClearNext() end local function ClearGroup() - if not X.groupBtn or InCombatLockdown() then return end - X.groupBtn.entry = nil - if X.groupBtn.isClear then return end -- already disarmed: skip the protected writes - X.groupBtn:SetAttribute("type", nil) - X.groupBtn:SetAttribute("spell", nil) - X.groupBtn:SetAttribute("unit", nil) - X.groupBtn:SetAttribute("macrotext", nil) - X.groupBtn.isClear = true - X.groupBtn.bGuid = nil -end -X.ClearGroup = ClearGroup - -function X.DisarmStaleKeybind(button, mouseButton, clear) + if not groupBtn or InCombatLockdown() then return end + groupBtn.entry = nil + if groupBtn.isClear then return end -- already disarmed: skip the protected writes + groupBtn:SetAttribute("type", nil) + groupBtn:SetAttribute("spell", nil) + groupBtn:SetAttribute("unit", nil) + groupBtn:SetAttribute("macrotext", nil) + groupBtn.isClear = true + groupBtn.bGuid = nil +end + +local function DisarmStaleKeybind(button, mouseButton, clear) if mouseButton == "LeftButton" and not InCombatLockdown() and button:GetAttribute("type") and not X.RowTargetMatches(button.entry) then clear() @@ -188,53 +324,10 @@ function X.DisarmStaleKeybind(button, mouseButton, clear) end end - -- Group-cast keybind (1.15.0): the group button's plain attribute family -- carries the GROUP version of the head row's buff, so one key press -- casts it. When the buff has no group version the button falls back to -- the plain cast -- the key is never dead, same as the next-buff key. --- Mirrors Bind's cast-method branches for the single spell it writes; --- Bind itself is untouched (rows and the next-buff button keep their --- proven path). -local function BindGroup(btn, unit, gspell, isSelf, pick) - local method = db.castMethod - if method == "target" then - btn:SetAttribute("type", nil) - btn:SetAttribute("unit", nil) - btn:SetAttribute("spell", nil) - btn:SetAttribute("macrotext", nil) - if isSelf then - btn:SetAttribute("type", "spell") - btn:SetAttribute("spell", (pick and pick.id) or gspell) - btn:SetAttribute("unit", "player") - return - end - if unit:match("^party%d+$") or unit:match("^raid%d+$") then - btn:SetAttribute("type", "spell") - btn:SetAttribute("spell", (pick and pick.id) or gspell) - btn:SetAttribute("unit", unit) - return - end - local ok, name = pcall(GetUnitName or UnitName, unit, true) - name = ok and SafeString(name) or nil -- a protected name can't build a macro: no cast - if name and name ~= "" then - btn:SetAttribute("type", "macro") - btn:SetAttribute("macrotext", "/targetexact " .. name .. "\n/cast " .. X.CastText(gspell, pick) .. "\n/targetlasttarget") - end - elseif method == "id" and pick and pick.id then - btn:SetAttribute("type", "spell") - btn:SetAttribute("unit", unit) - btn:SetAttribute("spell", pick.id) - btn:SetAttribute("macrotext", nil) - else - local text = (method == "rank") and X.CastText(gspell, pick) or gspell - btn:SetAttribute("type", "macro") - btn:SetAttribute("unit", nil) - btn:SetAttribute("spell", nil) - btn:SetAttribute("macrotext", "/cast [@" .. unit .. ",help,nodead] " .. text) - end -end - local function BindGroupCached(btn, unit, spell, guid) if not btn.combatDriver then return false end local isSelf = X.IsSelf(unit) @@ -246,22 +339,24 @@ local function BindGroupCached(btn, unit, spell, guid) local pick = X.BindingRank(gspell, unit, lvl, method) if pick == false then ClearGroup(); return false end local id = pick and pick.id + local hadTarget = X.NeedsExactTarget(unit, isSelf, method) and X.UnitPresent("target") btn.bOfferReason = X.GroupOfferReason(item, count, reason, blocker) btn.bOfferSummary = blocker and X.GroupOfferReason(item, count, reason, blocker, true) or btn.bOfferReason if btn.bGuid == guid and btn.bUnit == unit and btn.bSpell == gspell - and btn.bMethod == method and btn.bLevel == lvl and btn.bSelf == isSelf and btn.bRankID == id then + and btn.bMethod == method and btn.bLevel == lvl and btn.bSelf == isSelf and btn.bRankID == id + and btn.bHadTarget == hadTarget then return btn:GetAttribute("type") ~= nil end - BindGroup(btn, unit, gspell, isSelf, pick) + Bind(btn, unit, gspell, isSelf, pick, nil, nil, hadTarget) btn.bGuid, btn.bUnit, btn.bSpell, btn.bMethod, btn.bLevel = guid, unit, gspell, method, lvl - btn.bSelf = isSelf + btn.bSelf, btn.bHadTarget = isSelf, hadTarget btn.bRankID, btn.bActionID, btn.bSpellText = id, id, X.CastText(gspell, pick) if method == "macro" then btn.bActionID, btn.bSpellText = nil, gspell end btn.isClear = false return btn:GetAttribute("type") ~= nil end -function X.ClearRowCast(btn) +local function ClearRowCast(btn) if InCombatLockdown() then return end btn:SetAttribute("type", nil) btn:SetAttribute("spell", nil) @@ -279,13 +374,13 @@ local function BindCached(btn, unit, spell, guid) if not btn.combatDriver then return false end local isSelf = X.IsSelf(unit) if isSelf == nil then - if btn.bGuid ~= nil then X.ClearRowCast(btn) end + if btn.bGuid ~= nil then ClearRowCast(btn) end return false end local method = db.castMethod local lvl = X.ReadUnitNumber(UnitLevel, unit) or 0 local pick = X.BindingRank(spell, unit, lvl, method) - if pick == false then X.ClearRowCast(btn); return false end + if pick == false then ClearRowCast(btn); return false end local gspell, item, count, reason, blocker if db.modClick then local _ @@ -294,15 +389,17 @@ local function BindCached(btn, unit, spell, guid) if reason then gspell = spell end -- explicit Shift fallback mirrors the primary binding local gpick = gspell and X.BindingRank(gspell, unit, lvl, method) local id, gid = pick and pick.id, gpick and gpick.id + local hadTarget = X.NeedsExactTarget(unit, isSelf, method) and X.UnitPresent("target") btn.bOfferReason = X.GroupOfferReason(item, count, reason, blocker) if btn.bGuid == guid and btn.bUnit == unit and btn.bSpell == spell and btn.bMethod == method and btn.bLevel == lvl and btn.bSelf == isSelf - and btn.bRankID == id and btn.bGroupSpell == gspell and btn.bGroupRankID == gid then + and btn.bRankID == id and btn.bGroupSpell == gspell and btn.bGroupRankID == gid + and btn.bHadTarget == hadTarget then return btn:GetAttribute("type") ~= nil end - Bind(btn, unit, spell, isSelf, pick, gspell, gpick) + Bind(btn, unit, spell, isSelf, pick, gspell, gpick, hadTarget) btn.bGuid, btn.bUnit, btn.bSpell, btn.bMethod, btn.bLevel = guid, unit, spell, method, lvl - btn.bSelf = isSelf + btn.bSelf, btn.bHadTarget = isSelf, hadTarget btn.bRankID, btn.bGroupRankID, btn.bGroupSpell = id, gid, gspell btn.bActionID, btn.bGroupID, btn.bSpellText = id, gid, X.CastText(spell, pick) btn.bGroupText = gspell and X.CastText(gspell, gpick) @@ -313,15 +410,14 @@ local function BindCached(btn, unit, spell, guid) return btn:GetAttribute("type") ~= nil end --- Arm the group button with the head row (called from Refresh, which is --- at its upvalue ceiling and reaches the button only through X). -function X.ArmGroupBtn(first) - if not X.groupBtn then return end - X.groupBtn.entry = BindGroupCached(X.groupBtn, first.unit, first.missing[1], first.guid) and first or nil +-- The group key uses the same head as the next-buff key. +local function ArmGroupButton(first) + if not groupBtn then return end + groupBtn.entry = BindGroupCached(groupBtn, first.unit, first.missing[1], first.guid) and first or nil end -function X.NoCastReason(entry) - local group = X.groupBtn +local function NoCastReason(entry) + local group = groupBtn if not entry then return X.groupFallback or (group and group.entry and group.bOfferReason) end if group and group.entry == entry and group.bOfferReason then return group.bOfferSummary @@ -329,18 +425,18 @@ function X.NoCastReason(entry) if X.groupFallbackEntry == entry then return X.groupFallbackSummary end end -function X.ShowNextPreview(owner) +local function ShowNextPreview(owner) if InCombatLockdown() or X.PlayerSuspended() or (db.locked and db.clickThrough) then return end local entry = nextBtn and nextBtn.entry if not entry or not nextBtn:GetAttribute("type") then return end GameTooltip:SetOwner(owner, "ANCHOR_RIGHT") GameTooltip:AddLine(string_format(L["Next buff: %s — %s"], entry.fullName or entry.name, nextBtn.bSpellText or entry.missing[1]), 1, 1, 1, true) - local group = X.groupBtn + local group = groupBtn if group and group.entry == entry and group.bSpellText then GameTooltip:AddLine(string_format(L["Group buff key: %s"], group.bSpellText), 0.8, 0.9, 1, true) end - local reason = X.NoCastReason(entry) + local reason = NoCastReason(entry) if reason then GameTooltip:AddLine(reason, 1, 0.7, 0.3, true) end GameTooltip:Show() end @@ -356,7 +452,7 @@ local function BuildNextButton() ApplyNextRegistration() -- Secure snippets clear the button the instant combat starts and right after each use. -- Leave casting disarmed if the client cannot install combat clearing. - nextCombatDriver = X.InstallCombatDriver(nextBtn, [[ + nextCombatDriver = InstallCombatDriver(nextBtn, [[ if newstate == "combat" then self:SetAttribute("type", nil) self:SetAttribute("spell", nil) @@ -382,7 +478,7 @@ local function BuildNextButton() ]]) end nextBtn:HookScript("PreClick", function(self, button, down) - X.DisarmStaleKeybind(self, button, ClearNext) + DisarmStaleKeybind(self, button, ClearNext) X.BeginCastClick(self, button, down, "next-buff key") end) nextBtn:HookScript("PostClick", function(self, button, down) @@ -399,14 +495,14 @@ end local function BuildGroupButton() local btn = CreateFrame("Button", "BuffRadarGroupButton", UIParent, "SecureActionButtonTemplate,SecureHandlerStateTemplate") - X.groupBtn = btn + groupBtn = btn btn:SetSize(1, 1) btn:SetPoint("BOTTOMLEFT", UIParent, "BOTTOMLEFT", 0, 0) btn:SetAlpha(0) btn:EnableMouse(false) btn:Show() ApplyNextRegistration() - X.groupCombatDriver = X.InstallCombatDriver(btn, [[ + btn.combatDriver = InstallCombatDriver(btn, [[ if newstate == "combat" then self:SetAttribute("type", nil) self:SetAttribute("spell", nil) @@ -414,9 +510,8 @@ local function BuildGroupButton() self:SetAttribute("macrotext", nil) end ]]) - btn.combatDriver = X.groupCombatDriver if SecureHandlerWrapScript then - X.groupWrapped = pcall(SecureHandlerWrapScript, btn, "OnClick", btn, [[ return nil, true ]], [[ + groupWrapped = pcall(SecureHandlerWrapScript, btn, "OnClick", btn, [[ return nil, true ]], [[ self:SetAttribute("type", nil) self:SetAttribute("spell", nil) self:SetAttribute("unit", nil) @@ -424,29 +519,1340 @@ local function BuildGroupButton() ]]) end btn:HookScript("PreClick", function(self, button, down) - X.DisarmStaleKeybind(self, button, ClearGroup) + DisarmStaleKeybind(self, button, ClearGroup) X.BeginCastClick(self, button, down, "group-buff key") end) btn:HookScript("PostClick", function(self, button, down) X.EndCastClick(self, button, down, "group-buff key") self.bGuid, self.isClear = nil, false -- attributes changed outside our cache - if not X.groupWrapped then ClearGroup() end -- one press = one cast + if not groupWrapped then ClearGroup() end -- one press = one cast + end) +end + +function X.SetNextCast(entry) + if nextBtn and entry and not entry.outOfRange then + nextBtn.entry = BindCached(nextBtn, entry.unit, entry.missing[1], entry.guid) and entry or nil + ArmGroupButton(entry) + else + ClearNext() + ClearGroup() + end +end + +function X.ClearKeybindCasts() + ClearNext() + ClearGroup() +end + +local function ClassColor(class) + local c = (CUSTOM_CLASS_COLORS and CUSTOM_CLASS_COLORS[class]) + or (RAID_CLASS_COLORS and RAID_CLASS_COLORS[class]) + if c then return c.r, c.g, c.b end + return 1, 1, 1 +end + +local function Row_OnEnter(self) + if not self.entry then return end + local e = self.entry + GameTooltip:SetOwner(self, "ANCHOR_RIGHT") + if X.UnitPresent(e.unit) and X.UnitGUIDOf(e.unit) == e.guid then + GameTooltip:SetUnit(e.unit) + else + 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 + end + end + if e.groupCast then + GameTooltip:AddLine(L["Group version — one cast buffs the whole party."], 0.4, 0.8, 1) + end + -- Tooltip detail (1.10.0): minimal stops at the cast line. + if db.tooltipLevel == "minimal" then GameTooltip:Show() return end + GameTooltip:AddLine(L["Right-click to ignore this player."], 0.6, 0.6, 0.6) + GameTooltip:AddLine(L["Shift-right-click to ignore for this session only."], 0.6, 0.6, 0.6) + if #e.missing > 1 then + local rest = {} + for i = 2, #e.missing do rest[#rest + 1] = e.missing[i] end + GameTooltip:AddLine(string_format(L["Still needs: %s"], table.concat(rest, ", ")), 0.8, 0.8, 0.8, true) + end + -- The full picture (1.7.0): buffs this player HAS from your set, with + -- the time left on each, soonest first — so a hover answers "what do + -- they still need, and what's about to run out?" in one look. + if X.UnitPresent(e.unit) then + local missSet = {} + for _, m in ipairs(e.missing) do missSet[m] = true end + local have, seenHave = {}, {} + for _, def in ipairs(myBuffs) do + local nm = def.name + if nm and not seenHave[nm] and not missSet[nm] then + seenHave[nm] = true + local left = X.Remaining(e.unit, nm) + if left and left < math_huge and left > 0 then + have[#have + 1] = { name = nm, left = left } + end + end + end + table_sort(have, function(x, y) return x.left < y.left end) + for i = 1, math_min(6, #have) do + local h = have[i] + local t = h.left >= 90 and string_format(L["~%dm left"], math_floor(h.left / 60)) + or string_format(L["~%ds left"], math_floor(h.left)) + GameTooltip:AddLine(h.name .. " — " .. t, 0.55, 0.85, 0.55) + end + end + -- Full tooltips (1.10.0) add the context lines: class and group, the + -- range in words, and which other classes could cast the first buff. + if db.tooltipLevel == "full" then + 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 + 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). + local _, myClass = UnitClass("player") + local names, seenCls = {}, {} + for _, d in ipairs(BUFF_DEFS) do + local dn + if d.choices then dn = SpellName(d.choices[1][1], d.choices[1][2]) + else dn = SpellName(d.id, d.name) end + if dn == e.missing[1] then + for c in pairs(d.classes or ALL) do + if c ~= myClass and not seenCls[c] then + seenCls[c] = true + names[#names + 1] = c:sub(1, 1) .. c:sub(2):lower() + end + end + end + end + table_sort(names) + if #names > 0 then + GameTooltip:AddLine("Also castable by: " .. table.concat(names, ", "), 0.7, 0.7, 0.7, true) + end + end + GameTooltip:Show() +end + +-- The name field stops this far short of the row's right edge to leave +-- room for the buff icons; it follows the icon size (1.10.0). +local function IconInset() + local isz = (db.iconSize or 0) > 0 and db.iconSize or (db.compact and 12 or 16) + return MAX_ICONS * (isz + 2) + 4 +end + +local function RowMouseHeld() + for button, expires in pairs(rowMouseButtons) do + local down = X.ReadUnitBool(_G.IsMouseButtonDown, button) + if down == false or (down == nil and GetTime() >= expires) then + rowMouseButtons[button] = nil + end + end + return next(rowMouseButtons) ~= nil +end +local function RowWheel(_, delta) + if delta ~= 0 then X.ScrollRows(delta < 0 and 1 or -1) end +end + +-- Row hover highlight (1.15.34): a faint wash in the theme's border colour +-- instead of the bright quest-title glow. The engine shows a button's +-- highlight texture only while the mouse is over it, so no script is +-- needed; ApplyAppearance re-tints every row when the theme changes. +local ROW_HOVER_ALPHA = 0.15 +local function TintRowHover(b) + local hl = b and b.GetHighlightTexture and b:GetHighlightTexture() + if not hl or not hl.SetVertexColor then return end + local bc = X.ThemeBorder() + hl:SetVertexColor(bc[1], bc[2], bc[3], ROW_HOVER_ALPHA) +end + +local function RegisterRowClicks(b) + if db.clickReg == "down" then + b:RegisterForClicks("AnyDown") + elseif db.clickReg == "up" then + b:RegisterForClicks("AnyUp") + else + b:RegisterForClicks("AnyUp", "AnyDown") + end +end + +local function IgnoreRowPlayer(self, button, down) + if button ~= "RightButton" or InCombatLockdown() then return end + -- With AnyUp+AnyDown registered, OnClick fires twice per physical click; + -- toggle on exactly one phase (release, unless casts trigger on press). + if down ~= (db.clickReg == "down") then return end + local e = self.entry + if not e or not db or e.spell then return end + local short = e.pet and SafeString(e.name) or e.sortName + if short == "" then short = nil end + local who = e.fullName or short -- Name-Realm: ignores this one player only + if not who then return end + if _G.IsShiftKeyDown and _G.IsShiftKeyDown() then + local k = Ignore.Key(who) + if X.session[k] then + X.session[k] = nil + Print("No longer ignoring " .. who .. " for this session.") + else + X.session[k] = true + Print("Ignoring " .. who .. " for this session only (not saved).") + end + if QueueRefresh then QueueRefresh() end + return + end + if Ignore.Has(e.fullName, short) then + -- (a row still showing an ignored player: it drops off on the next refresh) + local removed = Ignore.Remove(who) + 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.") + end + if QueueRefresh then QueueRefresh() end +end + +local function ValidateRowClick(self, button, down) + if button == "LeftButton" and not InCombatLockdown() and self.bGuid 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) + if changed or not X.RowTargetMatches(self.entry) then + ClearRowCast(self) + self.entry, self.guid = nil, nil + if QueueRefresh then QueueRefresh() end + return + end + end + X.BeginCastClick(self, button, down, "click") +end + +local function TrackRowCast(self, button, down) + X.EndCastClick(self, button, down, "click") + if button == "LeftButton" and not down then rowLeftPress = nil end +end + +local function RememberRowPress(self, button) + if button == "LeftButton" or button == "RightButton" then rowMouseButtons[button] = GetTime() + 1 end + if button == "LeftButton" then + -- The mouse-up notification may precede the up-phase secure click. + -- Keep the presented binding through dispatch, independently of that notification. + rowLeftPress = { row = self, guid = self.bGuid, unit = self.bUnit, spell = self.bSpell } + end +end + +local function EndRowMouseHold(_, button) + rowMouseButtons[button] = nil +end + +local function BuildRowVisuals(b) + b.portrait = b:CreateTexture(nil, "ARTWORK") + b.portrait:SetSize(ROW_H - 2, ROW_H - 2) + b.portrait:SetPoint("LEFT", 1, 0) + if b.CreateMaskTexture and b.portrait.AddMaskTexture then + local m = b:CreateMaskTexture() + m:SetTexture("Interface\\CharacterFrame\\TempPortraitAlphaMask", + "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE") + m:SetAllPoints(b.portrait) + b.portrait:AddMaskTexture(m) + end + + b.cMissing = {} -- render cache: icons currently drawn + b.icons = {} + for j = 1, MAX_ICONS do + local t = b:CreateTexture(nil, "ARTWORK") + t:SetSize(16, 16) + t:SetTexCoord(0.08, 0.92, 0.08, 0.92) + if j == 1 then + t:SetPoint("RIGHT", b, "RIGHT", -2, 0) + else + t:SetPoint("RIGHT", b.icons[j - 1], "LEFT", -2, 0) + end + b.icons[j] = t + end + + b.name = b:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall") + b.name:SetPoint("LEFT", b.portrait, "RIGHT", 6, 0) + b.name:SetPoint("RIGHT", b, "RIGHT", -(IconInset()), 0) + b.name:SetJustifyH("LEFT") + 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") + b.tint:SetTexture("Interface\\Buttons\\WHITE8X8") + b.tint:SetPoint("TOPLEFT", b, "TOPLEFT", 0, -1) + b.tint:SetPoint("BOTTOMLEFT", b, "BOTTOMLEFT", 0, 1) + b.tint:SetWidth(3) + b.tint:Hide() + b.bar = b:CreateTexture(nil, "ARTWORK") + b.bar:SetTexture("Interface\\Buttons\\WHITE8X8") + b.bar:SetPoint("BOTTOMLEFT", b, "BOTTOMLEFT", 2, 1) + b.bar:SetHeight(3) + b.bar:SetWidth(10) + b.bar:Hide() + -- Raid marker badge (1.8.0): the player's raid target icon, drawn over + -- the portrait's top-left corner. + b.marker = b:CreateTexture(nil, "OVERLAY") + b.marker:SetSize(12, 12) + b.marker:SetPoint("TOPLEFT", b, "TOPLEFT", 1, -1) + b.marker:Hide() + + -- Short status tag under the name ("recently rezzed"); shares the slot + -- with the out-of-range label, which wins when both would apply. + b.tag = b:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall") + b.tag:SetPoint("TOPLEFT", b.name, "BOTTOMLEFT", 0, -1) + b.tag:SetTextColor(1, 0.85, 0.4) + b.tag:Hide() +end + +local function CreateRow(i) + local b = CreateFrame("Button", "BuffRadarRow" .. i, frame, + "SecureActionButtonTemplate,SecureHandlerStateTemplate") + -- Anchored on both sides, so rows follow the window's width when it's resized. + b:SetHeight(ROW_H) + b:SetPoint("TOPLEFT", frame, "TOPLEFT", 6, -HEADER_H - (i - 1) * ROW_H) + b:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -6, -HEADER_H - (i - 1) * ROW_H) + RegisterRowClicks(b) + b:SetHighlightTexture("Interface\\Buttons\\WHITE8X8", "ADD") + TintRowHover(b) + -- Right-click only ignores (see the OnClick hook below). Bind() sets the plain + -- "type" attribute, which the secure template uses for EVERY mouse button + -- unless a button-specific one exists; this "type2" override is a made-up + -- action the template doesn't know, so a right-click casts nothing. + -- Bind() never touches "type2", so this holds for the row's lifetime. + b:SetAttribute("type2", "buffradarignore") + b.combatDriver = InstallCombatDriver(b, [[ + if newstate == "combat" then + self:SetAttribute("type", nil) + self:SetAttribute("spell", nil) + self:SetAttribute("unit", nil) + self:SetAttribute("macrotext", nil) + self:SetAttribute("shift-type1", nil) + self:SetAttribute("shift-spell1", nil) + self:SetAttribute("shift-unit1", nil) + self:SetAttribute("shift-macrotext1", nil) + end + ]]) + + BuildRowVisuals(b) + + -- HookScript, never SetScript: SetScript would REPLACE the + -- SecureActionButtonTemplate's own OnClick (SecureActionButton_OnClick), + -- which is what actually performs the cast -- with it replaced, clicks run + -- only this handler and nothing is ever cast (the 1.2.0/1.2.1 bug). + b:HookScript("OnClick", IgnoreRowPlayer) + b:HookScript("PreClick", ValidateRowClick) + b:HookScript("PostClick", TrackRowCast) + b:SetScript("OnEnter", Row_OnEnter) + b:SetScript("OnLeave", function() GameTooltip:Hide() end) + b:HookScript("OnMouseDown", RememberRowPress) + b:HookScript("OnMouseUp", EndRowMouseHold) + b:SetScript("OnMouseWheel", RowWheel) + b:EnableMouseWheel(false) + b:Hide() + rows[i] = b +end + +-- Color themes (1.8.0): a theme is a background color + border color pair. +-- Picking one sets both; picking a custom background color afterwards +-- switches the theme back to "custom" (border returns to the default). + +-- Saved themes (1.10.0): your own background + border pairs, kept in +-- db.customThemes, usable anywhere a built-in theme is. +function X.SavedTheme(name) + if not db or not name then return nil end + local id = name:lower() + if X.THEMES[id] or id == "custom" then return nil end + for _, t in ipairs(db.customThemes or {}) do + if t.name:lower() == id then + return { label = t.name, bg = t.bg, border = t.border } + end + end + return nil +end + +function X.ThemeDef(name) + if not name then return nil end + return X.THEMES[name:lower()] or X.SavedTheme(name) +end + +-- The cycle order: built-in themes followed by your saved themes. +function X.ThemeOrder() + local order = {} + for _, k in ipairs(X.THEME_ORDER) do order[#order + 1] = k end + if db then + for _, t in ipairs(db.customThemes or {}) do + local id = t.name:lower() + if not X.THEMES[id] and id ~= "custom" then order[#order + 1] = t.name end + end + end + return order +end + +function X.EffectiveTheme() + if db and db.theme == X.AUTO_THEME_ID then + return X.THEMES[X.autoThemeResolved or "midnight"] + end + return db and X.ThemeDef(db.theme) +end + +function X.ThemeBorder() + local t = X.EffectiveTheme() + if t then return t.border end + return { 0.35, 0.55, 0.8 } +end + +function X.ThemeBackground() + if db and db.theme == X.AUTO_THEME_ID then + return X.EffectiveTheme().bg + end + return db and db.bgColor or X.Settings.Defaults.bgColor +end + +function X.ThemeLabel(detail) + if db and db.theme == X.AUTO_THEME_ID then + if detail then + return string_format(L["Auto (%s)"], X.EffectiveTheme().label) + end + return L["Auto"] + end + local t = db and X.ThemeDef(db.theme) + return t and t.label or "Custom" +end + +function X.AutoThemePriority() + return X.Settings.AutoThemeOrder(db and db.autoThemePriority) +end + +function X.MoveAutoThemePriority(palette, offset) + if not db or (offset ~= -1 and offset ~= 1) then return false end + local order = X.AutoThemePriority() + for i, entry in ipairs(order) do + if entry[2] == palette then + local nextIndex = i + offset + if not order[nextIndex] then return false end + order[i], order[nextIndex] = order[nextIndex], entry + db.autoThemePriority = X.Settings.EncodeAutoThemeOrder(order) + X.ResolveAutoTheme() + return true + end + end + return false +end + +function X.ResetAutoThemePriority() + if not db then return false end + local changed = db.autoThemePriority ~= "" + db.autoThemePriority = "" + X.ResolveAutoTheme() + return changed +end + +function X.AutoThemeStatus() + if not db or db.theme ~= X.AUTO_THEME_ID then + return string_format(L["Auto is off. Current theme: %s."], X.ThemeLabel()) + end + if not X.autoThemeAddon then return L["No supported UI addon is loaded. Using Midnight."] end + return string_format(L["Selected: %s (%s)"], X.EffectiveTheme().label, X.autoThemeAddon) +end + +-- Grow-up (1.8.0): normally the window hangs from its top-left corner and +-- the list grows downward. With grow-up on, the window stands on its +-- bottom-left corner instead, so the list grows upward and the bottom +-- edge never moves. The saved point records which form it holds. +function X.ApplyAnchor() + if not frame then return end + local left = frame:GetLeft() + if not left then return end + if db.growUp then + local bottom = frame:GetBottom() + if not bottom then return end + frame:ClearAllPoints() + frame:SetPoint("BOTTOMLEFT", UIParent, "BOTTOMLEFT", left, bottom) + db.point = { "BOTTOMLEFT", "BOTTOMLEFT", left, bottom } + else + local top = frame:GetTop() + if not top then return end + frame:ClearAllPoints() + frame:SetPoint("TOPLEFT", UIParent, "BOTTOMLEFT", left, top) + db.point = { "TOPLEFT", "BOTTOMLEFT", left, top } + end + if db.charPoint then + local k = X.CharKey() + if k then db.pointByChar[k] = db.point end + end +end + +-- Title suffix (1.12.0): "(update pending)" while a size/scale change waits +-- for combat to end; "(data hidden)" while the game is withholding aura +-- data from addons (secret values), so a stale-looking list has a reason. +local function UpdateTitleMarks() + if not title then return end + local hid = X.hid > 0 and (GetTime() - X.hid) < 10 + local key = (geometryPending and "p" or "") .. (hid and "h" or "") + if titleKey == key then return end + titleKey = key + local txt = "|cff33ccffBuff|rRadar" + if geometryPending then txt = txt .. " |cffffa040(update pending)|r" end + if hid then txt = txt .. " |cffffa040(data hidden)|r" end + title:SetText(txt) +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). +local function ApplyGeometry() + if not frame then return end + if InCombatLockdown() then + geometryPending = true -- lands at PLAYER_REGEN_ENABLED; the title says so meanwhile (1.12.0) + UpdateTitleMarks() + return + end + geometryPending = nil + -- Two-column layout (1.9.0): each column keeps the chosen width, with + -- a small gap between the columns. + local cols = columns + frame:SetWidth((db.width or WIDTH) * cols + (cols - 1) * 6) + frame:SetScale(db.scale or 1) + UpdateTitleMarks() +end + +local function ApplyAppearance() + if not frame then return end + if InCombatLockdown() then + appearancePending = true + return + end + appearancePending = nil + flashPending = nil + local c = X.ThemeBackground() + local bc = X.ThemeBorder() + if frame.SetBackdropColor then + frame:SetBackdropColor(c[1], c[2], c[3], db.bgAlpha or 0.92) + frame:SetBackdropBorderColor(bc[1], bc[2], bc[3], db.showBorder and 1 or 0) + end + for i = 1, #rows do TintRowHover(rows[i]) end + if pill and pill.SetBackdropColor then + pill:SetBackdropColor(c[1], c[2], c[3], db.bgAlpha or 0.92) + pill:SetBackdropBorderColor(bc[1], bc[2], bc[3], db.showBorder and 1 or 0) + end + if grip then grip:SetShown(not db.locked) end + if leftGrip then leftGrip:SetShown(not db.locked) end + if widthHandle then widthHandle:SetShown(not db.locked) end + title:SetShown(db.showTitle and true or false) + if titleLayoutState ~= db.showTitle then X.ApplyRowLayout() end + combatText:ClearAllPoints() + if db.showTitle then + combatText:SetPoint("LEFT", title, "RIGHT", 6, 0) + else + combatText:SetPoint("TOPLEFT", frame, "TOPLEFT", 9, -8) + end +end + +-- Briefly highlight the window when a pull ends or a countdown starts. +function X.Flash() + if not frame or not frame.SetBackdropBorderColor or InCombatLockdown() or db.reduceMotion then return end + frame:SetBackdropBorderColor(1, 0.35, 0.35, 1) + if C_Timer and C_Timer.After then + C_Timer.After(0.7, ApplyAppearance) + else + flashPending = true -- no timer API: Refresh() restores it next pass + end +end + +do + local function LoadFinished(ok, loaded, ...) + if not ok or not Readable(loaded) then return false end + -- The two-result API can report loaded while the addon's load is + -- still in progress. A legacy one-result API has no separate flag. + if select("#", ...) == 0 then return loaded == true or loaded == 1 end + local finished = ... + return loaded == true and Readable(finished) and finished == true + end + + function X.ResolveAutoTheme() + local resolved, selectedAddon + if db and db.theme == X.AUTO_THEME_ID then + resolved = "midnight" + local isLoaded = _G.C_AddOns and _G.C_AddOns.IsAddOnLoaded + if type(isLoaded) ~= "function" then isLoaded = _G.IsAddOnLoaded end + if type(isLoaded) == "function" then + for _, entry in ipairs(X.AutoThemePriority()) do + if LoadFinished(pcall(isLoaded, entry[1])) then + resolved, selectedAddon = entry[2], entry[1] + break + end + end + end + end + if X.autoThemeResolved == resolved and X.autoThemeAddon == selectedAddon then + if X.RefreshAutoThemePriority then X.RefreshAutoThemePriority() end + return false + end + X.autoThemeResolved, X.autoThemeAddon = resolved, selectedAddon + ApplyAppearance() + if X.RefreshConfig then X.RefreshConfig() end + local wizard = X.wizardFrame + if wizard and wizard:IsShown() and wizard.page == 2 then + wizard.choice[1]:SetText("Theme: " .. X.ThemeLabel(true)) + end + return true + end +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) + if rowWheelEnabled == enabled then return end + rowWheelEnabled = enabled + frame:EnableMouseWheel(enabled) + for _, row in ipairs(rows) do row:EnableMouseWheel(enabled) end +end + +local function ClearRowViewport() + viewport, rowOffset, viewportCount = nil, nil, nil + if frame and not InCombatLockdown() then + ApplyRowWheel() + SetShownIfChanged(overflowText, false) + end +end + +-- Click-through (1.10.0): while the window is locked AND the player +-- asked for it, the window and its rows stop eating mouse clicks, so +-- clicks land on the game world behind them. Never changed in combat +-- (secure buttons refuse it there); re-applied when combat ends and +-- whenever the lock or the setting changes. +function X.ApplyClickThrough() + if not frame or not db then return end + if InCombatLockdown and InCombatLockdown() then return end + local mouse = not (db.clickThrough and db.locked) + if frame.EnableMouse then frame:EnableMouse(mouse) end + for i = 1, MAX_ROWS do + local row = rows[i] + if row and row.EnableMouse then row:EnableMouse(mouse) end + end + if nextBtn and nextBtn.EnableMouse then nextBtn:EnableMouse(mouse) end + if nextPreview then nextPreview:EnableMouse(mouse) end + if nearbyButton then nearbyButton:SetShown(mouse) end + ApplyRowWheel() + if X.UpdateFade then X.UpdateFade() end +end + +-- Compact rows, text scale and column layout. Re-anchoring secure rows +-- must wait until combat ends. +function X.ApplyRowLayout() + if not frame or InCombatLockdown() then return end + titleLayoutState = db.showTitle + local h = db.compact and 16 or ROW_H + local header = db.showTitle and HEADER_H or 0 + local barHeight = BarHeight() + rowHeight = h + if findBar then + findBar:SetShown(db.findBox and true or false) + findBar:ClearAllPoints() + findBar:SetPoint("TOPLEFT", frame, "TOPLEFT", 4, -header - barHeight) + findBar:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -4, -header - barHeight) + end + local top = header + barHeight + (db.findBox and 16 or 0) + topHeight = top + if bar then + bar:SetShown(barHeight > 0) + bar:ClearAllPoints() + bar:SetPoint("TOPLEFT", frame, "TOPLEFT", 4, -header) + bar:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -4, -header) + end + if widthHandle then + widthHandle:ClearAllPoints() + widthHandle:SetPoint("TOPRIGHT", frame, "TOPRIGHT", 0, -header) + widthHandle:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", 0, 18) + end + emptyText:ClearAllPoints() + emptyText:SetPoint("TOPLEFT", frame, "TOPLEFT", 10, -top - 3) + countText:ClearAllPoints() + if db.showTitle then + countText:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -24, -6) + else + countText:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -16, 6) + end + if footerText then + footerText:ClearAllPoints() + footerText:SetPoint("LEFT", nearbyButton or gear, "RIGHT", 5, 0) + footerText:SetPoint("RIGHT", frame, "BOTTOMRIGHT", db.showTitle and -16 or -48, 13) + end + -- Two-column layout (1.9.0): rows fill the first column top to + -- bottom, then the second. PaintRowViewport selects the column count. + local per = rowsPerColumn + local cols = columns + local cellW = (db.width or WIDTH) + 6 -- column width + the gap + local isz = (db.iconSize or 0) > 0 and db.iconSize or (db.compact and 12 or 16) + local ts = db.textScale or 1 + for i, row in ipairs(rows) do + local col = math_floor((i - 1) / per) + local idx = (i - 1) % per + row:SetHeight(h) + row:ClearAllPoints() + row:SetPoint("TOPLEFT", frame, "TOPLEFT", 6 + col * cellW, -top - idx * (h + (db.rowGap or 0))) + row:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -(6 + (cols - 1 - col) * cellW), -top - idx * (h + (db.rowGap or 0))) + 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 + +local function UpdateCounter() + if not footerText then return end + SetShownIfChanged(footerText, db.showCounter == true) + local total = db.castsTotal or 0 + -- The counter shares its row with the settings gear and stops short of the + -- resize grip, so a narrow window used to cut it to "39 all-t...". Width is + -- part of the cache key so a resize re-fits the line, not just a new cast. + local room = footerText:GetWidth() or 0 + if X.sessionCasts ~= lastCounterSession or total ~= lastCounterTotal + or room ~= lastCounterRoom then + lastCounterSession, lastCounterTotal, lastCounterRoom = X.sessionCasts, total, room + footerText:SetText(string_format(L["Casts: |cffffffff%d|r this session · |cffffffff%d|r all-time"], + X.sessionCasts, total)) + if room > 0 and footerText:GetStringWidth() > room then + footerText:SetText(string_format(L["Casts: |cffffffff%d|r / |cffffffff%d|r"], + X.sessionCasts, total)) + end + end +end + +local function ClearRow(row) + row.entry, row.guid = nil, nil + if row.bGuid ~= nil then ClearRowCast(row) end + if row:IsShown() then row:Hide() end +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.cTint = nil + wipe(row.cMissing) + end + if nextBtn then nextBtn.bGuid, nextBtn.isClear = nil, false end +end + +-- The name shown on a row (1.10.0): optionally with the realm, and +-- optionally shortened. +local function DispName(e) + local nm = (db.showRealm and e.fullName) or e.name or "" + local trim = db.nameTrim or 0 + if trim > 0 and Readable(nm) and type(nm) == "string" and #nm > trim then + local count = 0 + -- Skip UTF-8 continuation bytes when looking for the first character + -- beyond the display limit. Keep the engine's original text if unreadable. + for offset in nm:gmatch("()[^\128-\191]") do + if count == trim then return nm:sub(1, offset - 1) .. "…" end + count = count + 1 + end + end + return nm +end + +-- Tag symbols (1.12.0): with tagSymbols on, a status tag also carries a +-- symbol, so its meaning never rests on color alone. +function X.InvalidateTags() + for i = 1, #rows do rows[i].cTag = false end + QueueRefresh() +end + +-- Label and symbol are keyed by the same status, not translated text. +-- Earlier entries win when more than one status applies. +local ROW_TAGS = { + { "expired", "a buff just expired", "!" }, + { "rezzed", "recently rezzed", "+" }, + { "queued", "up next", ">" }, + { "handled", "being buffed", "~" }, + { "mine", "your assignment", "#" }, + { "theirs", "assigned elsewhere", "x" }, + { "buddy", "buddy's watch", "&" }, + { "pinned", "pinned", "^" }, + { "weapon", "weapon enchant missing", "/" }, + { "drinking", "drinking", "o" }, + { "asked", "asked for a buff", "?" }, + { "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 + end + local left = entry.remain1 + if left then + return left >= 90 and string_format(L["~%dm left"], math_floor(left / 60)) + or string_format(L["~%ds left"], math_floor(left)) + end +end + +local function SetNameOffset(row, y) + row.name:ClearAllPoints() + row.name:SetPoint("LEFT", row.portrait, "RIGHT", 6, 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 +end + +local function RenderRowTag(row, entry, far) + local tag = RowTag(entry, far, db.tagSymbols) + if row.cTag == tag then return end + row.cTag = tag + if tag then + row.tag:SetText(tag) + SetNameOffset(row, 5) + 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 + end +end + +local function RenderDurationBar(row, e) + -- Duration bar (1.8.0): the expiring buff's remaining time as a share + -- of 30 minutes; the color band shifts green -> yellow -> red. + local barKey + if db.durationBars and e.remain1 and e.remain1 < math_huge then + local frac = math_min(1, e.remain1 / 1800) + local band = e.remain1 < 300 and 1 or (e.remain1 < 900 and 2 or 3) + barKey = math_floor(frac * 40) .. ":" .. band + if row.cBar ~= barKey then + row.cBar = barKey + row.bar:SetWidth(math_max(2, (row:GetWidth() - 4) * frac)) + if band == 1 then row.bar:SetVertexColor(1, 0.3, 0.3) + elseif band == 2 then row.bar:SetVertexColor(1, 0.85, 0.4) + else row.bar:SetVertexColor(0.4, 0.9, 0.4) end + row.bar:Show() + end + end + if not barKey then + -- Unconditional: InvalidateRows clears the cache without touching + -- the texture, so the hide can't ride on the cache alone. + row.cBar = nil + row.bar:Hide() + end +end + +local function RenderRaidMarker(row, e) + -- Raid marker badge (1.8.0). + local mk = (db.raidMarkers and e.marker) or nil + if row.cMarker ~= mk then + row.cMarker = mk + if mk then + row.marker:SetTexture("Interface\\TargetingFrame\\UI-RaidTargetingIcon_" .. mk) + row.marker:Show() + else + row.marker:Hide() + end + end + if not mk then row.marker:Hide() end +end + +local function RenderRowTint(row, e) + -- Row color mark (1.10.0): a colored strip on the row's left edge for + -- the first matching rule you switched on — yours, tanks, expiring + -- soon, your split partner's half. + local tint + local rc = db.rowColors + if rc then + if rc.mine and e.mine then tint = rc.mine + elseif rc.tank and e.role == 1 then tint = rc.tank + elseif rc.expiring and (e.expired or (e.remain1 and e.remain1 < 300)) then tint = rc.expiring + elseif rc.buddy and e.buddy then tint = rc.buddy end + end + if row.cTint ~= tint then + row.cTint = tint + if tint then + row.tint:SetVertexColor(tint[1], tint[2], tint[3]) + row.tint:Show() + else + row.tint:Hide() + end + end + if not tint then row.tint:Hide() end +end + +local function RenderRowIcons(row, m) + local cm, changed = row.cMissing, false + for j = 1, MAX_ICONS do + if cm[j] ~= m[j] then changed = true; break end + end + if changed then + for j = 1, MAX_ICONS do + local t, spell = row.icons[j], m[j] + if spell then + t:SetTexture(SpellIcon(spell)) + t:SetAlpha(j == 1 and 1 or 0.5) + t:Show() + else + t:Hide() + end + cm[j] = spell + end + end +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) + 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. + row:SetAlpha(0.6) + if row.bGuid ~= nil then ClearRowCast(row) end + else + row:SetAlpha(1) + BindCached(row, e.unit, m[1], e.castGuid or e.guid) + end + if not row:IsShown() then row:Show() end +end + +-- Row color marks (1.10.0): named colors for the row edge strip. +X.ROW_PALETTE = { + gold = { 1, 0.8, 0.2 }, sky = { 0.4, 0.7, 1 }, red = { 1, 0.35, 0.35 }, + green = { 0.45, 0.95, 0.45 }, violet = { 0.75, 0.5, 1 }, +} +X.ROW_PALETTE_ORDER = { "gold", "sky", "red", "green", "violet" } + +function X.RowColorName(rule) + local c = db.rowColors and db.rowColors[rule] + if not c then return "off" end + for name, rgb in pairs(X.ROW_PALETTE) do + if rgb[1] == c[1] and rgb[2] == c[2] and rgb[3] == c[3] then return name end + end + return "custom" +end + +function X.SetRowColor(rule, c) + db.rowColors = db.rowColors or {} + db.rowColors[rule] = c and { c[1], c[2], c[3] } or nil + InvalidateRows() + QueueRefresh() +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) + ClearRowViewport() + for _, row in ipairs(rows) do ClearRow(row) end + if pill and not keepPill then SetShownIfChanged(pill, false) end + if not text then + SetShownIfChanged(frame, false) + return + end + if focusText then SetShownIfChanged(focusText, false) end + SetShownIfChanged(coverText, false) + SetTextIfChanged(countText, "") + SetShownIfChanged(overflowText, false) + SetTextIfChanged(emptyText, text) + SetShownIfChanged(emptyText, true) + UpdateCounter() + SetHeightIfChanged(frame, topHeight + 26 + FOOTER_H) + SetShownIfChanged(frame, true) +end + +-- Pick an honest explanation for an empty list when the client cannot verify range. +function X.EmptyStatus() + if X.scanHasUnknownBuffs or (X.tallyUnknownUnits or 0) > 0 then + return L["Some buff information is unavailable."] + end + if X.FriendlyPlatesOn() == false then + return L["Friendly nameplates are off."] + end + if X.rangeSilent then + return L["Range could not be confirmed; the list may be incomplete."] + end + if X.scanNameFiltered then return L["The name finder hides all buff targets."] end + if (X.lastTargetCastProblem and GetTime() < X.lastTargetCastProblem.expires) + or NoCastReason() then return L["No cast target is available."] end + return L["No targets in the buff queue."] +end + +local function EmptyStatusHint() + if X.FriendlyPlatesOn() == false then return L["Use /br plates to see nearby players."] end + if X.rangeSilent then return L["Move closer or use /br why ."] end + if X.lastTargetCastProblem and GetTime() < X.lastTargetCastProblem.expires then + return X.lastTargetCastProblem.message + end + return NoCastReason() +end + +-- Coverage-line parts (1.10.0): the line is assembled from parts, each +-- with its own switch in db.coverParts; absent means on. +local function CoverOn(part) + local cp = db and db.coverParts + return not cp or cp[part] ~= false +end + +-- Group-by-buff view (1.10.0): fold the people entries into one row +-- per buff still needed. Each folded row stands for the buff itself: +-- its name carries the count, and it borrows an in-range holder (if +-- any) as its cast target, so clicking the row buffs that player with +-- exactly that spell. Only the render stage uses the folded list -- +-- coverage, sounds and reports keep working on people. +local function BuildBuffView(list, n) + local bySpell, order = {}, {} + for i = 1, n do + local e = list[i] + if not e.header then + for j = 1, #(e.missing or {}) do + local spell = e.missing[j] + local g = bySpell[spell] + if not g then + g = { spell = spell, count = 0, missing = { spell }, group = true } + bySpell[spell] = g + 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 + 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 + end + end + end + end + table_sort(order, function(a, b) + if a.count ~= b.count then return a.count > b.count end + return a.spell < b.spell end) + for i = 1, #order do + local g = order[i] + g.name = g.count > 1 and (g.spell .. " x" .. g.count) or g.spell + g.sortName = g.spell + g.guid = "buff:" .. g.spell .. "#" .. g.count + end + return order, #order +end + +local function PaintRowViewport(cached) + 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 rowsTall = wantCols == 2 and math_floor((shown + 1) / 2) or shown + if wantCols ~= columns or rowsTall ~= (previousRowsTall or shown) then + columns, previousRowsTall = wantCols, rowsTall + rowsPerColumn = wantCols == 2 and rowsTall or MAX_ROWS + X.ApplyRowLayout() + ApplyGeometry() + end + 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 + if overflow then + local y = -topHeight - rowsTall * rowHeight + - math_max(0, rowsTall - 1) * (db.rowGap or 0) - 2 + if overflowText.cY ~= y then + overflowText.cY = y + overflowText:ClearAllPoints() + overflowText:SetPoint("TOPLEFT", frame, "TOPLEFT", 10, y) + end + SetTextIfChanged(overflowText, string_format(L["Rows %d–%d of %d"], rowOffset + 1, rowOffset + shown, n)) + end + SetShownIfChanged(overflowText, overflow) + ApplyRowWheel() + return shown, rowsTall +end + +function X.ScrollRows(step) + if not viewport or viewportCount <= MAX_ROWS 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)) + 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 +end + +local function AppendBuffCoverage(parts) + for _, b in ipairs(myBuffs) do + local t = not b.self and X.tally[b.key] or nil + if t and t.total > 0 then + local nm = b.key:lower():gsub("_", " ") + local seg = string_format("%s %d/%d", nm:sub(1, 1):upper() .. nm:sub(2), + t.total - t.miss, t.total) + -- A buff on a real cooldown is never counted as missing (you can't + -- cast it anyway), so its count can look complete while people + -- still need it -- flag the cooldown so the number isn't trusted + -- blindly. + local left = core.CooldownLeft(b.name) + if left > 5 then + seg = seg .. (left >= 60 and string_format(" (~%dm cd)", math_floor(left / 60 + 0.5)) + or string_format(" (~%ds cd)", math_floor(left + 0.5))) + end + parts[#parts + 1] = seg + end + end + local tb = X.tally.BLESSINGS + if tb and tb.total > 0 then + parts[#parts + 1] = string_format("Blessings %d/%d", tb.total - tb.miss, tb.total) + end +end + +local function CoverageRoster() + local nowC = GetTime() + -- Assignment counts keyed by short name: holders are recorded as + -- typed (often short), users are known by full name. + local held = {} + for _, who in pairs(X.assign) do + local wk = Ignore.Key(who:match("^[^%-]+") or who) + held[wk] = (held[wk] or 0) + 1 + end + local duty = {} + local meF = Ignore.UnitNames("player") + if meF then + local mk = Ignore.Key(meF:match("^[^%-]+") or meF) + duty[#duty + 1] = (meF:match("^[^%-]+") or meF) + .. (held[mk] and (" (" .. held[mk] .. ")") or "") + end + local peerNames = {} + for k, p in pairs(X.peers) do + if nowC - p.t < 90 then peerNames[#peerNames + 1] = k end + end + table_sort(peerNames) + for _, k in ipairs(peerNames) do + local p = X.peers[k] + local short = (p.name:match("^[^%-]+") or p.name) + for cname, exp in pairs(X.cover) do + if exp > nowC and X.SameUser(p.name, cname) then + short = short .. " (away)" break + end + end + local hk = Ignore.Key(p.name:match("^[^%-]+") or p.name) + if held[hk] then short = short .. " (" .. held[hk] .. ")" end + duty[#duty + 1] = short + end + if #duty > 1 then return "Radar: " .. table.concat(duty, ", ") end +end + +local function ExpiringGroupBuffs() + local worstKey, worstSoon, worstTotal = nil, 0, 0 + for key, soon in pairs(X.expiryTally) do + local t = X.tally[key] + if t and soon >= 3 and soon * 2 >= t.total and soon > worstSoon then + worstKey, worstSoon, worstTotal = key, soon, t.total + end + end + if worstKey then + local nm = worstKey == "BLESSINGS" and "Blessings" or worstKey + if worstKey ~= "BLESSINGS" then + for _, def in ipairs(myBuffs) do + if def.key == worstKey then nm = def.name break end + end + end + return string_format("%s <5m on %d/%d", nm, worstSoon, worstTotal) + end +end + +local function RenderCoverage(entries, n) + if X.tallyUnits <= 1 and (X.tallyUnits == 0 or X.tallyUnknownUnits == 0) then + SetShownIfChanged(coverText, false) + return false + end + local parts = {} + if CoverOn("progress") then + parts[#parts + 1] = string_format("%d/%d fully buffed", X.tallyUnits - X.tallyMissingUnits, X.tallyUnits) + end + if CoverOn("buffs") then AppendBuffCoverage(parts) end + 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) + end + end + end + -- Coverage uptime (1.6.0): the share of grouped scans this run that + -- found nobody missing anything. A scan-based score, reset when a + -- Mythic+ run starts and when the group ends. + if X.tallyUnknownUnits == 0 then + X.upTotal = X.upTotal + 1 + if X.tallyMissingUnits == 0 then X.upFull = X.upFull + 1 end + end + if X.upTotal >= 10 and CoverOn("uptime") then + parts[#parts + 1] = string_format("Uptime %d%%", + math_floor(100 * X.upFull / X.upTotal + 0.5)) + end + if db.sync and CoverOn("roster") then parts[#parts + 1] = CoverageRoster() end + if CoverOn("expiry") then parts[#parts + 1] = ExpiringGroupBuffs() end + -- Weapon watch (1.7.0): when your own row isn't on the list to + -- carry the tag, the coverage line carries the reminder instead. + if db.weaponWatch and X.WeaponEnchantMissing() then + local selfListed = false + for i = 1, n do + if entries[i].isSelf then selfListed = true break end + end + if not selfListed then + parts[#parts + 1] = "your weapon has no enchant" + end + end + -- World-buff watch (1.8.0): your active world buffs, with time left. + if db.worldWatch and CoverOn("world") then + local wb = X.WorldBuffsText() + if wb then parts[#parts + 1] = wb end + end + -- Healer drinking (1.8.0): healers sitting down to drink between + -- pulls — the group waits for them, not the other way round. + if db.drinkWatch and CoverOn("drink") and (X.drinkHealers or 0) > 0 then + parts[#parts + 1] = X.drinkHealers == 1 and "Healer drinking" + or string_format("%d healers drinking", X.drinkHealers) + end + -- Pull countdown (1.15.0): while a pull timer runs (Extras tracks it + -- in X.pull), the coverage line itself counts down -- the part of the + -- pull-timer feature 1.14.0 trimmed. The steady ticker rebuilds this + -- line every 0.4s while the list is live, and Extras refreshes again + -- the moment the timer ends, so the number never goes stale. + if X.pull and X.pull.endsAt then + local left = math_ceil(X.pull.endsAt - GetTime()) + if left > 0 then parts[#parts + 1] = string_format("Pull in %ds", left) end + end + SetTextIfChanged(coverText, table.concat(parts, " · ")) + SetShownIfChanged(coverText, #parts > 0) + return #parts > 0 +end + +function X.RenderQueue(entries, n, sessionShow, wasAfterCombat) + -- group-by-buff view folds the render list; everything above this + -- point (coverage, sounds, counts) still works on people + local viewEntries, viewN = entries, n + if db.viewMode == "buffs" then viewEntries, viewN = BuildBuffView(entries, n) end + if viewportMode ~= db.viewMode or viewportSearch ~= X.search or viewportRole ~= db.roleFilter then + rowOffset = nil + end + 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 + + SetTextIfChanged(countText, n > 0 and n or "") + local hint + if n == 0 then + hint = EmptyStatusHint() + SetTextIfChanged(emptyText, X.EmptyStatus() .. (hint and "\n" .. hint or "")) + end + SetShownIfChanged(emptyText, n == 0) + + local coverShown = RenderCoverage(entries, n) + local focusLine = db.focusWatch and focusText and core.FocusLine() + if focusText then + if focusLine then SetTextIfChanged(focusText, focusLine) end + SetShownIfChanged(focusText, focusLine and true or false) + 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 + h = h + FOOTER_H -- bottom row: settings gear + cast counter + UpdateCounter() + SetHeightIfChanged(frame, h) + + -- All-buffed pill (1.6.0): in a group with nobody missing anything, the + -- window can collapse to the pill until someone needs a buff again (or + -- the pill is clicked for a peek). + local pillMode = db.pill and n == 0 and X.InGroup() and not db.hidden + and core.ScanConfirmsGroupBuffed() and GetTime() > (pillPeek or 0) + if pillMode and pill then + SetTextIfChanged(pill.text, "|cff33ccffBuff|rRadar · " + .. string_format("%d/%d ", X.tallyUnits - X.tallyMissingUnits, X.tallyUnits) .. L["All buffed"]) + SetShownIfChanged(frame, false) + SetShownIfChanged(pill, true) + else + if pill then SetShownIfChanged(pill, false) end + SetShownIfChanged(frame, not (db.autoHide and n == 0 and not sessionShow)) + end end -- Scale drag (1.11.0). Cursor-driven; the OnUpdate runs only while a grip is -- held. Scale = the cursor's horizontal distance from the fixed bottom -- corner divided by the window's unscaled width. -X.SNAPS = { 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2 } +local SNAPS = { 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2 } -function X.ScaleFromCursor(g) +local function ScaleFromCursor(g) local cx = GetCursorPosition() / UIParent:GetEffectiveScale() local w = g.baseW if not w or w <= 0 then return db.scale or 1 end local ns = (g.side == "RIGHT") and (cx - g.fixedX) / w or (g.fixedX - cx) / w if db.gripSnap ~= false and IsShiftKeyDown and IsShiftKeyDown() then local best, bd = ns, 0.06 -- Shift: snap to a preset within 6% - for _, p in ipairs(X.SNAPS) do + for _, p in ipairs(SNAPS) do local d = math.abs(ns - p) if d < bd then best, bd = p, d end end @@ -456,7 +1862,7 @@ function X.ScaleFromCursor(g) return ns end -function X.PlaceScaled(g, ns) +local function PlaceScaled(g, ns) local left = (g.side == "RIGHT") and g.fixedX or (g.fixedX - g.baseW * ns) frame:SetScale(ns) frame:ClearAllPoints() @@ -467,18 +1873,19 @@ function X.PlaceScaled(g, ns) end end -function X.EndEdgeDrag(e) +local function EndEdgeDrag(e) if not e or not e.isSizing or InCombatLockdown() then return end e.isSizing = false frame:StopMovingOrSizing() - local cols = X.cols or 1 + local cols = columns local w = (frame:GetWidth() - (cols - 1) * 6) / cols db.width = math.max(MIN_WIDTH, math.min(MAX_WIDTH, math_floor(w + 0.5))) ApplyGeometry() SavePosition() end -function X.BeginScaleDrag(g) +local EndScaleDrag +local function BeginScaleDrag(g) local s = frame:GetScale() or 1 local l, r = frame:GetLeft(), frame:GetRight() local y = db.growUp and frame:GetBottom() or frame:GetTop() @@ -488,40 +1895,88 @@ function X.BeginScaleDrag(g) g.fixedY = y * s g.isSizing = true g:SetScript("OnUpdate", function(self) - if InCombatLockdown() then X.EndScaleDrag(self); return end - local ns = X.ScaleFromCursor(self) + if InCombatLockdown() then EndScaleDrag(self); return end + local ns = ScaleFromCursor(self) db.scale = ns - X.PlaceScaled(self, ns) + PlaceScaled(self, ns) end) end -function X.EndScaleDrag(g) +EndScaleDrag = function(g) if not g or not g.isSizing then return end g:SetScript("OnUpdate", nil) if InCombatLockdown() then return end g.isSizing = false local ns = math_floor((db.scale or 1) * 100 + 0.5) / 100 db.scale = ns - X.PlaceScaled(g, ns) + PlaceScaled(g, ns) SavePosition() - if RefreshConfig then RefreshConfig() end + if X.RefreshConfig then X.RefreshConfig() end end -function X.EndWindowDrags() +local function EndWindowDrags() if InCombatLockdown() then return end if frame and frame.isMoving then frame:StopMovingOrSizing() frame.isMoving = false SavePosition() end - X.EndScaleDrag(grip) - X.EndScaleDrag(X.gripL) - X.EndEdgeDrag(X.edge) + EndScaleDrag(grip) + EndScaleDrag(leftGrip) + EndEdgeDrag(widthHandle) end -local function BuildUI() - if built or InCombatLockdown() then return end +local function HideOwnedTooltip() + if not GameTooltip or not GameTooltip.GetOwner then return end + local owner = GameTooltip:GetOwner() + if not owner then return end + local config = _G.BuffRadarConfig + while owner do + if owner == frame or owner == config or owner == _G.BuffRadarMinimapButton + or owner == pill or owner == X.wizardFrame or owner == X.exportFrame then + GameTooltip:Hide() + return + end + if not owner.GetParent then return end + owner = owner:GetParent() + end +end + +function X.SuspendWindow() + ClearRowViewport() + wipe(rowMouseButtons) + rowLeftPress = nil + pillPeek = nil + HideOwnedTooltip() + if X.HideConfig then X.HideConfig() end + if X.CloseRaidPreparation then X.CloseRaidPreparation() end + if X.CloseNearbyDiagnostics then X.CloseNearbyDiagnostics() end + if X.wizardFrame and X.wizardFrame:IsShown() then X.wizardFrame:Hide() end + if X.exportFrame and X.exportFrame:IsShown() then X.exportFrame:Hide() end + if X.EndEditMode then X.EndEditMode(true) end + X.RefreshMinimapButton() + -- The state drivers hide and disarm protected frames during lockdown. + -- Clear the Lua-side click bookkeeping immediately in either case. + local locked = InCombatLockdown() + if nextBtn then nextBtn.entry = nil end + if groupBtn then groupBtn.entry = nil end + for i = 1, #rows do + rows[i].entry, rows[i].guid = nil, nil + if not locked then + ClearRowCast(rows[i]) + ClearRow(rows[i]) + end + end + if locked then return end + EndWindowDrags() + ClearNext() + ClearGroup() + if frame then SetShownIfChanged(frame, false) end + if pill then SetShownIfChanged(pill, false) end +end + +local function BuildWindowFrame() frame = CreateFrame("Frame", "BuffRadarFrame", UIParent, BackdropTemplateMixin and "BackdropTemplate" or nil) if X.PlayerSuspended() then frame:Hide() end @@ -540,7 +1995,7 @@ local function BuildUI() frame:SetMaxResize(MAX_WIDTH, 4000) end frame:EnableMouse(true) - frame:SetScript("OnMouseWheel", X.RowWheel) + frame:SetScript("OnMouseWheel", RowWheel) frame:EnableMouseWheel(false) frame:RegisterForDrag("LeftButton") frame:SetScript("OnDragStart", function(self) @@ -565,13 +2020,15 @@ local function BuildUI() frame:SetBackdropColor(0.04, 0.05, 0.09, 0.92) frame:SetBackdropBorderColor(0.35, 0.55, 0.8, 1) end +end +local function BuildCloseControl() title = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal") title:SetPoint("TOPLEFT", 9, -7) title:SetText("|cff33ccffBuff|rRadar") local close = CreateFrame("Button", nil, frame, "UIPanelCloseButton") - X.closeButton = close + closeButton = close close:SetSize(22, 22) close:SetPoint("TOPRIGHT", 0, 0) close.hoverAnchor = "TOPRIGHT" @@ -579,7 +2036,7 @@ local function BuildUI() close:Hide() close:SetScript("OnClick", function() if X.PlayerSuspended() or InCombatLockdown() or (db.clickThrough and db.locked) then return end - db.hidden = true; A.setSessionShow(false) + db.hidden = true; core.SetSessionShow(false) frame:Hide() Print("Hidden. Type /br to show it again.") end) @@ -590,21 +2047,56 @@ local function BuildUI() if not InCombatLockdown() then close:Hide() if db.hidden then - wipe(X.rowMouseButtons) - X.rowLeftPress = nil - X.ClearRowViewport() + wipe(rowMouseButtons) + rowLeftPress = nil + ClearRowViewport() end end end) close:HookScript("OnLeave", X.UpdateFade) +end + +local function BuildStatusLabels() + countText = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall") + + combatText = frame:CreateFontString(nil, "OVERLAY", "GameFontRedSmall") + combatText:SetPoint("LEFT", title, "RIGHT", 6, 0) + combatText:SetText(L["combat"]) + combatText:Hide() + + emptyText = frame:CreateFontString(nil, "OVERLAY", "GameFontDisableSmall") + emptyText:SetPoint("TOPLEFT", 10, -HEADER_H - 3) + emptyText:SetText(L["No targets in the buff queue."]) + + overflowText = frame:CreateFontString(nil, "OVERLAY", "GameFontDisableSmall") + overflowText:SetPoint("TOPLEFT", frame, "TOPLEFT", 10, -HEADER_H) + + -- Coverage line (1.4.0): "12/15 fully buffed · Fortitude 13/15 · ...", + -- directly above the footer; Refresh() grows the window when it's shown. + coverText = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall") + coverText:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 9, FOOTER_H + 3) + coverText:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -16, FOOTER_H + 3) + coverText:SetJustifyH("LEFT") + if coverText.SetWordWrap then coverText:SetWordWrap(false) end + coverText:Hide() + + -- Focus watch line (1.8.0): one line about your focus target's buffs, + -- directly above the coverage line. Refresh fills and shows it. + focusText = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall") + focusText:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 9, FOOTER_H + 17) + focusText:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -16, FOOTER_H + 17) + focusText:SetJustifyH("LEFT") + if focusText.SetWordWrap then focusText:SetWordWrap(false) end + focusText:Hide() +end - local gear = CreateFrame("Button", nil, frame) - X.gear = gear +local function BuildFooter() + gear = CreateFrame("Button", nil, frame) gear:SetSize(14, 14) gear:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 20, 6) gear:SetNormalTexture("Interface\\Buttons\\UI-OptionsButton") gear:SetHighlightTexture("Interface\\Buttons\\UI-OptionsButton", "ADD") - gear:SetScript("OnClick", function() OpenConfig() end) + gear:SetScript("OnClick", function() if X.OpenConfig then X.OpenConfig() end end) gear:SetScript("OnEnter", function(self) GameTooltip:SetOwner(self, "ANCHOR_RIGHT") GameTooltip:AddLine(L["BuffRadar settings"]) @@ -614,7 +2106,7 @@ local function BuildUI() if CLASSIC_FEATURES then local help = CreateFrame("Button", nil, frame) - X.nearbyButton = help + nearbyButton = help help:SetSize(14, 14) help:SetPoint("LEFT", gear, "RIGHT", 4, 0) help:SetNormalFontObject("GameFontNormal") @@ -632,49 +2124,27 @@ local function BuildUI() help:SetScript("OnLeave", function() GameTooltip:Hide() end) end - countText = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall") - - combatText = frame:CreateFontString(nil, "OVERLAY", "GameFontRedSmall") - combatText:SetPoint("LEFT", title, "RIGHT", 6, 0) - combatText:SetText(L["combat"]) - combatText:Hide() - - emptyText = frame:CreateFontString(nil, "OVERLAY", "GameFontDisableSmall") - emptyText:SetPoint("TOPLEFT", 10, -HEADER_H - 3) - emptyText:SetText(L["No targets in the buff queue."]) - - overflowText = frame:CreateFontString(nil, "OVERLAY", "GameFontDisableSmall") - overflowText:SetPoint("TOPLEFT", frame, "TOPLEFT", 10, -HEADER_H) - footerText = frame:CreateFontString(nil, "OVERLAY", "GameFontDisableSmall") - footerText:SetPoint("LEFT", X.nearbyButton or gear, "RIGHT", 5, 0) + footerText:SetPoint("LEFT", nearbyButton or gear, "RIGHT", 5, 0) footerText:SetPoint("RIGHT", frame, "BOTTOMRIGHT", -16, 13) -- clear of the resize grip footerText:SetJustifyH("LEFT") if footerText.SetWordWrap then footerText:SetWordWrap(false) end - X.footerText = footerText if CLASSIC_FEATURES then local preview = CreateFrame("Frame", nil, frame) preview:SetPoint("TOPLEFT", footerText, "TOPLEFT", 0, 0) preview:SetPoint("BOTTOMRIGHT", footerText, "BOTTOMRIGHT", 0, 0) preview:EnableMouse(true) - preview:SetScript("OnEnter", X.ShowNextPreview) + preview:SetScript("OnEnter", ShowNextPreview) preview:SetScript("OnLeave", function() GameTooltip:Hide() end) - X.nextPreview = preview + nextPreview = preview end +end - -- Coverage line (1.4.0): "12/15 fully buffed · Fortitude 13/15 · ...", - -- directly above the footer; Refresh() grows the window when it's shown. - coverText = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall") - coverText:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 9, FOOTER_H + 3) - coverText:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -16, FOOTER_H + 3) - coverText:SetJustifyH("LEFT") - if coverText.SetWordWrap then coverText:SetWordWrap(false) end - coverText:Hide() - +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. - local pill = CreateFrame("Button", "BuffRadarPill", UIParent, + pill = CreateFrame("Button", "BuffRadarPill", UIParent, BackdropTemplateMixin and "BackdropTemplate" or nil) if X.PlayerSuspended() then pill:Hide() end pill:SetSize(150, 22) @@ -693,23 +2163,23 @@ local function BuildUI() pill.text:SetPoint("CENTER", 0, 0) pill.text:SetText(L["All buffed"]) pill:SetScript("OnClick", function(self) - X.pillPeek = GetTime() + 5 + pillPeek = GetTime() + 5 self:Hide() if frame then frame:Show() end end) pill:Hide() - X.pill = pill +end +local function BuildToggleBar() -- Toggle strip + role filter bar (1.5.0), directly under the title: -- your buff icons on the left (click one to toggle that buff), the role -- filter chips on the right. ApplyRowLayout shows/hides the bar and -- moves the rows below it. - local bar = CreateFrame("Frame", nil, frame) + bar = CreateFrame("Frame", nil, frame) bar:SetPoint("TOPLEFT", frame, "TOPLEFT", 4, -HEADER_H) bar:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -4, -HEADER_H) bar:SetHeight(18) - X.bar = bar - X.stripBtns = {} + stripButtons = {} for i = 1, 10 do local b = CreateFrame("Button", "BuffRadarStrip" .. i, bar) b:SetSize(16, 16) @@ -719,7 +2189,7 @@ local function BuildUI() b:SetScript("OnClick", function(self) if InCombatLockdown() or not self.buffKey then return end db.enabled[self.buffKey] = not IsOn(self.buffKey, self.buffDefault) - X.stripSig = nil + stripState = nil if QueueRefresh then QueueRefresh() end end) b:SetScript("OnEnter", function(self) @@ -732,9 +2202,9 @@ local function BuildUI() end) b:SetScript("OnLeave", function() GameTooltip:Hide() end) b:Hide() - X.stripBtns[i] = b + stripButtons[i] = b end - X.chipBtns = {} + chipButtons = {} local chipDefs = { { "ALL", "All", 26, -98 }, { "TANK", "Tank", 32, -64 }, { "HEALER", "Heal", 32, -30 }, { "DAMAGER", "DPS", 28, 0 }, @@ -753,10 +2223,12 @@ local function BuildUI() X.RefreshChips() if QueueRefresh then QueueRefresh() end end) - X.chipBtns[#X.chipBtns + 1] = b + chipButtons[#chipButtons + 1] = b end X.RefreshChips() +end +local function BuildResizeControls() -- Scale grips (1.11.0): drag either bottom corner to rescale the whole -- window (frame, rows, icons and text) together. The opposite bottom -- corner stays put on screen; the top edge (or bottom edge when the list @@ -779,9 +2251,9 @@ local function BuildUI() end g:SetScript("OnMouseDown", function(self, button) if button ~= "LeftButton" or db.locked or InCombatLockdown() then return end - X.BeginScaleDrag(self) + BeginScaleDrag(self) end) - g:SetScript("OnMouseUp", function(self) X.EndScaleDrag(self) end) + g:SetScript("OnMouseUp", function(self) EndScaleDrag(self) end) g:SetScript("OnEnter", function(self) GameTooltip:SetOwner(self, right and "ANCHOR_RIGHT" or "ANCHOR_LEFT") GameTooltip:AddLine(L["Drag to resize the window"]) @@ -795,7 +2267,7 @@ local function BuildUI() return g end grip = MakeScaleGrip("RIGHT") - X.gripL = MakeScaleGrip("LEFT") + leftGrip = MakeScaleGrip("LEFT") -- Width handle (1.12.0): drag the right edge to change the list width, -- the job the old corner grip did. Kept clear of the corner grip. @@ -808,24 +2280,26 @@ local function BuildUI() frame:StartSizing("RIGHT") self.isSizing = true end) - edge:SetScript("OnMouseUp", function(self) X.EndEdgeDrag(self) end) + edge:SetScript("OnMouseUp", function(self) EndEdgeDrag(self) end) edge:SetScript("OnEnter", function(self) GameTooltip:SetOwner(self, "ANCHOR_CURSOR") GameTooltip:AddLine("Drag to change the width") GameTooltip:Show() end) edge:SetScript("OnLeave", function() GameTooltip:Hide() end) - X.edge = edge + widthHandle = edge +end +local function BuildFinder() -- Name finder (1.8.0): a slim bar under the toggle strip holding one -- edit box; while it has text, the list shows only matching names. -- ApplyRowLayout positions and shows/hides it. - local findBar = CreateFrame("Frame", nil, frame) + findBar = CreateFrame("Frame", nil, frame) findBar:SetHeight(16) local findLabel = findBar:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall") findLabel:SetPoint("LEFT", 2, 0) findLabel:SetText("Find:") - local findEdit = CreateFrame("EditBox", nil, findBar, "InputBoxTemplate") + findEdit = CreateFrame("EditBox", nil, findBar, "InputBoxTemplate") findEdit:SetSize(130, 16) findEdit:SetPoint("LEFT", findLabel, "RIGHT", 6, 0) findEdit:SetAutoFocus(false) @@ -840,21 +2314,9 @@ local function BuildUI() self:ClearFocus() end) findBar:Hide() - X.findBar, X.findEdit = findBar, findEdit - - -- Focus watch line (1.8.0): one line about your focus target's buffs, - -- directly above the coverage line. Refresh fills and shows it. - local focusText = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall") - focusText:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 9, FOOTER_H + 17) - focusText:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -16, FOOTER_H + 17) - focusText:SetJustifyH("LEFT") - if focusText.SetWordWrap then focusText:SetWordWrap(false) end - focusText:Hide() - X.focusText = focusText - - PublishUI() -- CreateRow and the calls below read the main file's copies - for i = 1, MAX_ROWS do CreateRow(i) end +end +local function BuildCastControls() -- Hide securely during death or combat. Refresh owns the visible state. if RegisterStateDriver then local ok, accepted = pcall(RegisterStateDriver, frame, "visibility", "[@player,dead][combat] hide") @@ -863,22 +2325,139 @@ local function BuildUI() pill.visibilityDriver = ok and accepted ~= false end + -- Plain button: the action-bar macro uses this only to observe the press. + local macroNote = CreateFrame("Button", "BuffRadarMacroButton", UIParent) + macroNote:SetSize(1, 1) + macroNote:SetPoint("BOTTOMLEFT") + macroNote:SetAlpha(0) + macroNote:EnableMouse(false) + macroNote:RegisterForClicks("LeftButtonUp") + macroNote:SetScript("OnClick", X.RecordBarMacroClick) local okNext, errNext = pcall(BuildNextButton) pcall(BuildGroupButton) - PublishUI() -- nextBtn now exists if not okNext then Print("|cffff4040keybind button unavailable:|r " .. tostring(errNext)) end +end + +local function BuildUI() + if built or InCombatLockdown() then return end + BuildWindowFrame() + BuildCloseControl() + BuildStatusLabels() + BuildFooter() + BuildPill() + BuildToggleBar() + BuildResizeControls() + BuildFinder() + for i = 1, MAX_ROWS do CreateRow(i) end + BuildCastControls() ApplyGeometry() RestorePosition() ApplyAppearance() X.ApplyRowLayout() UpdateCounter() - BuildMinimapButton() + X.BuildMinimapButton() built = true - PublishUI() end --- Entry points BuffRadar.lua and Slash.lua call. -X.BuildUI, X.ApplyNextRegistration, X.ClearNext, X.BindCached = - BuildUI, ApplyNextRegistration, ClearNext, BindCached +function X.BeginWindowCombat() + wipe(rowMouseButtons) + if X.ReadUnitBool(_G.IsMouseButtonDown, "LeftButton") == false then rowLeftPress = nil end + if combatText then combatText:Show() end + -- Drivers clear cast attributes in combat; protected drag and visibility + -- work can run here only if the client has not started lockdown. + if not InCombatLockdown() then + EndWindowDrags() + if frame and not frame.visibilityDriver then frame:Hide() end + if pill and not pill.visibilityDriver then pill:Hide() end + end +end + +function X.EndWindowCombat() + EndWindowDrags() + if combatText then combatText:Hide() end + BuildUI() + if X.PlayerSuspended() then return false end + -- Secure snippets cleared the attributes behind the display cache. + for i = 1, #rows do rows[i].bGuid = nil end + if nextBtn then nextBtn.bGuid, nextBtn.isClear = nil, false end + if groupBtn then groupBtn.bGuid, groupBtn.isClear = nil, false end + ApplyGeometry() -- a scale/width change made during combat lands now + if appearancePending or flashPending then ApplyAppearance() end + X.ApplyRowLayout() + X.ApplyClickThrough() + ApplyNextRegistration() + return true +end + +function X.PrepareWindowScan() + -- The next scan reuses entry tables. Do not scroll the previous view while it runs. + viewport = nil + if flashPending then ApplyAppearance() end +end + +function X.RefreshWindowHeader() + UpdateTitleMarks() + RefreshStrip() + X.RefreshChips() +end + +function X.SetFinderText(text) + X.search = text:lower() + if findEdit then findEdit:SetText(text) end +end + +function X.HasHeldRow() + return (viewportCount or 0) > MAX_ROWS and RowMouseHeld() +end + +function X.QueueVisibility(entries, index) + for _, row in ipairs(rows) do + 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 + return "overflow" + end +end + +function X.ApplyRowClickRegistration() + if InCombatLockdown() then return end + for _, row in ipairs(rows) do RegisterRowClicks(row) end +end + +function X.InvalidatePortrait(unit) + for _, row in ipairs(rows) do + if row.cUnit == unit then row.cGuid = nil end + end +end + +local function ToggleWindow() + if not db or X.PlayerSuspended() then return end + db.hidden = not db.hidden + core.SetSessionShow(not db.hidden) + if InCombatLockdown() then + Print(db.hidden and "Window will hide when combat ends." or "Window will show when combat ends.") + return + end + if not db.hidden and db.groupOnly and not X.InGroup() then + Print("Window is set to show only in a party or raid.") + end + X.Refresh() +end + +X.ToggleWindow = ToggleWindow +BuffRadar_ToggleWindow = ToggleWindow -- Bindings.xml + +-- Private entry points used by the core and other UI modules. +X.BuildUI = BuildUI +X.WindowReady = function() return built end +X.GetFrame = function() return frame end +X.GetNextButton = function() return nextBtn end X.NextBindState = function() return nextWrapped, nextCombatDriver end +X.ApplyNextRegistration = ApplyNextRegistration +X.InvalidateRows = InvalidateRows +X.ApplyGeometry = ApplyGeometry +X.ApplyAppearance = ApplyAppearance +X.UpdateCounter = UpdateCounter +X.PositionSave = SavePosition diff --git a/BuffRadar/Wizard.lua b/BuffRadar/Wizard.lua index bedb0e7..563918c 100644 --- a/BuffRadar/Wizard.lua +++ b/BuffRadar/Wizard.lua @@ -1,34 +1,21 @@ --- BuffRadar - Wizard: the first-run setup wizard (1.9.0) and the --- tools around it that only the slash commands, settings and timers call: --- saved themes, the alert flash, range and fall checks, /br why and the --- Nearby Player explanations, history / stats / Discord text and the --- export dialog. --- Loaded after BuffRadar.lua through the .toc. This is file-split Slice F --- (1.15.34): the code below moved verbatim from BuffRadar.lua and reaches --- that file's locals through X.wizAPI, which BuffRadar.lua fills in --- before this file loads. The settings table arrives through X.dbSinks; --- the window comes from X.GetFrame() and the list length from an accessor. +-- BuffRadar - setup wizard, themes, and nearby / cast diagnostics. -- Copyright (C) 2026 Malikor. GPLv3 or later. -local _, NS = ... -local X = NS and NS.X -if not X or not X.wizAPI then return end -local A = X.wizAPI +local _, ns = ... +local X = ns.X +local core = X.Core -local db = X.GetDB and X.GetDB() -- nil until ADDON_LOADED; X.dbSinks updates it -X.dbSinks = X.dbSinks or {} -X.dbSinks[#X.dbSinks + 1] = function(value) db = value end +local db +X.OnDBLoaded(function(value) db = value end) -local L, Print, PlayAlert, QueueRefresh = A.L, A.Print, A.PlayAlert, A.QueueRefresh -local RefreshConfig, OpenConfig = A.RefreshConfig, A.OpenConfig -local ApplyAppearance, ApplyGeometry = A.ApplyAppearance, A.ApplyGeometry -local Ignore, Readable, SafeString = A.Ignore, A.Readable, A.SafeString -local Single, Missing, Valid = A.Single, A.Missing, A.Valid -local InGroup, InRaid = A.InGroup, A.InRaid -local RAID, PARTY, PLATES = A.RAID, A.PARTY, A.PLATES -local myBuffs, entries, rows = A.myBuffs, A.entries, A.rows -local CLASSIC_FEATURES = A.CLASSIC_FEATURES -local MAX_ROWS = A.MAX_ROWS +local L, Print, PlayAlert, QueueRefresh = X.L, X.Print, core.PlayAlert, core.QueueRefresh +local ApplyAppearance, ApplyGeometry = X.ApplyAppearance, X.ApplyGeometry +local Ignore, Readable, SafeString = X.Ignore, X.Readable, core.SafeString +local Single, Missing, Valid = core.Single, core.Missing, core.Valid +local InGroup, InRaid = X.InGroup, X.InRaid +local RAID, PARTY, PLATES = core.RAID, core.PARTY, core.PLATES +local myBuffs, entries = core.Buffs, core.Entries +local CLASSIC_FEATURES = X.classic local pairs, ipairs, type, pcall = pairs, ipairs, type, pcall local math_min, math_max, math_floor = math.min, math.max, math.floor local string_format = string.format @@ -65,7 +52,7 @@ function X.WizardPage(n) ApplyGeometry() ApplyAppearance() X.ApplyRowLayout() - if RefreshConfig then RefreshConfig() end + if X.RefreshConfig then X.RefreshConfig() end if QueueRefresh then QueueRefresh() end Print("Setup wizard: the " .. s[2] .. " preset is applied.") end @@ -87,7 +74,7 @@ function X.WizardPage(n) local cur = 1 for i, k in ipairs(order) do if k:lower() == (db.theme or ""):lower() then cur = i end end X.ApplyTheme(order[cur % #order + 1]) - if RefreshConfig then RefreshConfig() end + if X.RefreshConfig then X.RefreshConfig() end b:SetText(themeLabel()) end) b:Show() @@ -104,7 +91,7 @@ function X.WizardPage(n) or "You don't know any buffs BuffRadar handles yet; the list appears once you learn one. Press Finish to close.") local b = w.choice[1] b:SetText("Open settings") - b:SetScript("OnClick", function() OpenConfig() end) + b:SetScript("OnClick", function() X.OpenConfig() end) b:Show() w.next:SetText("Finish") w.next:Show() @@ -189,7 +176,7 @@ function X.ApplyTheme(name) if id ~= X.AUTO_THEME_ID then db.bgColor = { t.bg[1], t.bg[2], t.bg[3] } end if not X.ResolveAutoTheme() then ApplyAppearance() - if RefreshConfig then RefreshConfig() end + if X.RefreshConfig then X.RefreshConfig() end end return true end @@ -224,7 +211,7 @@ function X.DeleteTheme(name) if not X.THEMES[name:lower()] and (db.theme or ""):lower() == name:lower() then db.theme = "custom" ApplyAppearance() - if RefreshConfig then RefreshConfig() end + if X.RefreshConfig then X.RefreshConfig() end end return true end @@ -232,19 +219,6 @@ function X.DeleteTheme(name) return false end --- One border pulse; restores the normal border shortly after. Assigned --- here because frame / ApplyAppearance only exist from this point on. -function X.Flash() - local frame = X.GetFrame() - if not frame or not frame.SetBackdropBorderColor or InCombatLockdown() or db.reduceMotion then return end - frame:SetBackdropBorderColor(1, 0.35, 0.35, 1) - if C_Timer and C_Timer.After then - C_Timer.After(0.7, function() if frame then ApplyAppearance() end end) - else - X.flashPending = true -- no timer API: Refresh() restores it next pass - end -end - -- Watched-buff drop alert (1.5.0): your single-target buff (Earth Shield) -- was on someone at the last scan and is gone now, while that player is -- still around -- say so instead of silently re-offering it. The alert @@ -259,7 +233,7 @@ function X.CheckRange() if not db.rangeWatch then wipe(X.farPrev); wipe(X.farNow); return end - for i = 1, A.nEntries() do + 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 @@ -395,16 +369,12 @@ function X.ExplainPlayer(selected, emit, showUnknown) .. (failure and failure.guid == guid and " " .. failure.message or "") .. " Try again in a few seconds.") return end - for i = 1, A.nEntries() do + for i = 1, core.EntryCount() do if guid and entries[i].guid == guid then - local shown = false - for r = 1, MAX_ROWS do - if rows[r] and rows[r].entry == entries[i] then shown = true break end - end - if shown then + local visibility = X.QueueVisibility(entries, i) + if visibility == "visible" then emit(disp .. " is on the list (row " .. i .. "), missing: " .. table.concat(miss, ", ") .. ".") - elseif db.viewMode == "people" and X.rowView == entries - and (i <= (X.rowOffset or 0) or i > (X.rowOffset or 0) + MAX_ROWS) then + elseif visibility == "overflow" then emit(disp .. " is outside the visible rows. " .. L["Use the mouse wheel to see more rows."]) else emit(disp .. " needs " .. table.concat(miss, ", ") .. " and is collected, but the row is not shown -- the role filter under the title is the usual reason.") @@ -458,28 +428,62 @@ function X.ExplainCurrentTarget(emit) X.ExplainPlayer({ unit = unit, full = full, short = short, group = unit ~= "target", guid = guid }, emit, true) end -function X.EnableFriendlyNameplates(emit) +-- These are game settings, not frame overrides. Remember only values we +-- changed and verified, and never save them in a shareable profile. +local function WritePlateSetting(name, value, remember) + local before = X.ReadBooleanCVar(name) + if before == nil then return false end + if before ~= value then + local setter = (C_CVar and C_CVar.SetCVar) or SetCVar + if not setter then return false end + pcall(setter, name, value and "1" or "0") + if X.ReadBooleanCVar(name) ~= value then return false end + if remember and db.plateRestore[name] == nil then db.plateRestore[name] = before end + end + if db.plateRestore[name] == value then db.plateRestore[name] = nil end + return true +end + +function X.ChangeFriendlyNameplates(mode, emit) if InCombatLockdown() then emit(L["Can't change nameplate settings during combat."]); return end if X.PlayerSuspended() then emit(L["Nameplate settings are unavailable while dead."]); return end - local enabled, name = X.FriendlyPlatesOn() - local setter = (C_CVar and C_CVar.SetCVar) or SetCVar - if not name or not setter then - emit(L["Couldn't find a supported friendly nameplate setting on this client."]) - return - end - if not enabled then pcall(setter, name, "1") end - if X.FriendlyPlatesOn() ~= true then - emit(L["Couldn't turn on friendly nameplates. Check the game's nameplate settings."]) - return - end - if X.ReadBooleanCVar("nameplateShowAll") == false then - pcall(setter, "nameplateShowAll", "1") - if X.ReadBooleanCVar("nameplateShowAll") ~= true then - emit(L["Friendly nameplates are enabled. The game may still hide them outside combat."]) + if mode == "restore" then + if not next(db.plateRestore) then emit(L["No nameplate changes to restore."]); return end + for name, value in pairs(db.plateRestore) do WritePlateSetting(name, value, false) end + emit(L[next(db.plateRestore) and "Some nameplate settings could not be restored. Try again or check the game's options." + or "Restored your previous nameplate settings."]) + elseif mode == "names" or mode == "bars" then + local namesOnly = mode == "names" + if not WritePlateSetting(X.friendlyPlateNamesCVar, namesOnly, true) then + emit(L["Couldn't change friendly nameplate style. Check the game's nameplate settings."]) + return + end + emit(L[namesOnly and "Friendly nameplates now show names only." or "Friendly nameplates can show health bars again."]) + elseif mode == "on" or mode == "off" then + local _, name = X.FriendlyPlatesOn() + if not name then + emit(L["Couldn't find a supported friendly nameplate setting on this client."]) return end + local enable = mode == "on" + if not WritePlateSetting(name, enable, true) then + emit(L[enable and "Couldn't turn on friendly nameplates. Check the game's nameplate settings." + or "Couldn't turn off friendly nameplates. Check the game's nameplate settings."]) + return + end + if not enable then + emit(L["Friendly nameplates turned off. Your group, target, and mouseover are still checked."]) + elseif X.ReadBooleanCVar("nameplateShowAll") == false and not WritePlateSetting("nameplateShowAll", true, true) then + emit(L["Friendly nameplates are enabled. The game may still hide them outside combat."]) + else + emit(L["Friendly nameplates turned on, so nearby non-group players can be listed."]) + end + else + emit(L["Usage: /br plates on|off|names|bars|restore"]) + return end - emit(L["Friendly nameplates turned on, so nearby non-group players can be listed."]) + if X.UpdateNearbyPlateControls then X.UpdateNearbyPlateControls() end + QueueRefresh() end function X.CheckDrops() @@ -646,7 +650,7 @@ function X.ShowExport(text, forImport, titleText, mode) f:Hide() ApplyGeometry() ApplyAppearance() - if RefreshConfig then RefreshConfig() end + if X.RefreshConfig then X.RefreshConfig() end if QueueRefresh then QueueRefresh() end end end) @@ -663,9 +667,3 @@ function X.ShowExport(text, forImport, titleText, mode) if f.editBox.SetFocus then f.editBox:SetFocus() end if f.editBox.HighlightText then f.editBox:HighlightText() end end - --- Your own "Name-Realm", for per-character settings. -function X.CharKey() - local full = Ignore.UnitNames("player") - return full -end diff --git a/QUALITY.md b/QUALITY.md index 0cf93b5..6cf0f58 100644 --- a/QUALITY.md +++ b/QUALITY.md @@ -66,13 +66,13 @@ are named below as waivers with owners and follow-ups, not hidden. | Dimension (weight) | Score | Verdict | Evidence | |---|---|---|---| -| Correctness (14) | 5 | Pass | Full gate green (Lua 5.1 compile, luacheck 0/0, locale, trial run × 6 fake-client setups, 0 errors) and every release through 1.15.31 passed in game (SEAN, 2026-11-16). | +| 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→v20 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 migration chain v2→v21 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. | | 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 source is split across ten files (Data, BuffRadar, Coordination, Wizard, Window, Config, Slash, Extras, Recaps, Profiles; 17.4k lines). Slices E, F and G (2026-11-16) moved coordination, the wizard/diagnostics tools and the window builder with its cast buttons out, so `BuffRadar.lua` dropped from ~9,700 to ~7,200 lines, but it is still above the prompt's file-length target and Config.lua is ~4,100. Lua 5.1 limits are tool-enforced on every file: main chunk 165/200 locals, `HandleSlash` 58/60 upvalues, `Refresh` 49/60. The score stays 3 until the split passes a field test and the scan core (who is around, rank selection, Refresh) is the only large block left. Slice G touches the secure cast path, so it needs its own field test. | -| Modularity (6) | 3 | Pass | Seven load-ordered files; sections stay one-way (data → scan → render → UI → commands), shared state lives in one `X` registry table, and the split files reach main state only through bridge tables (`X.cfgAPI`, `X.slashAPI`). Every capability is a named slash operation before it is a settings control. Not 4: the bridge tables are a wide coupling surface, checked by review only. | +| 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. | +| Modularity (6) | 3 | Pass | Both TOCs load the same addon-private modules. SavedVariables owns DB load and migration, the core owns scan and cast decisions, and Window and Minimap own their frames. One private core interface replaces consumer-specific bridges. Some scan tables are still shared read-only by convention. | | 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. | @@ -87,7 +87,7 @@ waivers SEAN approved on 2026-10-25 are now closed: the UX field test gate-enforced, 2026-11-16). One minor waiver remains (Maintainability: the main file's length). The ≥85 release bar is not met; releases continue under SEAN's standing approval. The honest path upward is real work: -shrinking `BuffRadar.lua` (maintainability 3→4, ≈+1.4), narrowing the -bridge tables (modularity 3→4, ≈+1.2), in-game `/br perf` numbers from a +further shrinking `BuffRadar.lua` (maintainability 3→4, ≈+1.4), narrowing +the shared scan state (modularity 3→4, ≈+1.2), in-game `/br perf` numbers from a 40-player raid (performance 4→5, ≈+1.6), and the remaining 3-scored dimensions (scalability, self-documentation) each earning a 4. diff --git a/README.md b/README.md index cb87ac1..5472c0f 100644 --- a/README.md +++ b/README.md @@ -19,9 +19,13 @@ macro to work through the list. Your character goes first by default. ## Quick Start - Run `/br plates` to enable friendly nameplates for nearby players outside - your group. BuffRadar also checks your group, target, and mouseover. + your group. BuffRadar also checks your group, target, and mouseover. Use + `/br plates names` to keep detection without friendly health bars, or + `/br plates restore` to undo recorded nameplate changes. - Click a row to buff its player. Use `/br key` to set keybinds or run `/br macro` outside combat to create a cast-next macro for your action bar. + On a controller, use `/br gamepad` to bind **Cast next buff** directly or + activate the macro from your action bar. - Open settings with `/br config`. Run `/br wizard` for guided setup or `/br why ` for a player's eligibility and assignment. - Click **?** on the buff window or run `/br nearby` to check friendly @@ -97,6 +101,9 @@ aura and Hunter aspect reminders with `/br aura`. precedence over personal class preferences. Use `/br bless player ` for a normal blessing exception in your current group, subject to the plan's caster ownership. + Enable **Complement Nearby Blessings** with `/br bless complement on` to + offer a different known blessing outside your group when another Paladin + already provides your preferred one. Explicit rules take precedence. - **Class & Role Assignments.** Enable the table in **Settings → Buffs** or with `/br buffassign on`. It uses the class and known group role, or the class's **World** cell when the role is unavailable or the player is @@ -220,10 +227,19 @@ BuffRadar has targeted Forever since 1.8.0. The last Retail release was ## Source and Contributions -- [Runtime](BuffRadar/BuffRadar.lua), [coordination](BuffRadar/Coordination.lua), - [setup wizard and diagnostics](BuffRadar/Wizard.lua), [window](BuffRadar/Window.lua), [settings](BuffRadar/Config.lua), - [slash commands](BuffRadar/Slash.lua), [profiles](BuffRadar/Profiles.lua), and - [translations](BuffRadar/Locales). +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) + handles settings and plan imports and exports. +- [Core](BuffRadar/BuffRadar.lua) scans and builds the cast queue. + [Coordination](BuffRadar/Coordination.lua) handles group messages and plans. +- [Window](BuffRadar/Window.lua) owns the main window and secure buttons. + [Minimap](BuffRadar/Minimap.lua) owns the minimap and addon menu. + [Config](BuffRadar/Config.lua), [Wizard](BuffRadar/Wizard.lua), and + [Slash](BuffRadar/Slash.lua) handle settings, setup, and commands. + - [Report a bug or request a feature](https://github.com/SeanShaffer88/BuffRadar/issues/new/choose). Use the [security policy](SECURITY.md) for private reports. - [Contributing](CONTRIBUTING.md) and [local checks](tools/README.md). diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index bda96a4..db0fa87 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -402,3 +402,18 @@ split, then Briefs 2, 3, 4 — nothing else built; file-split Slices B - Added `tools/patterncheck.py` to the gate. gate.sh now probes that the interpreter runs, so the Windows Store python3 stub no longer stops it. - Unverified in game. + +## 2026-11-17 — Separate queue, UI, and SavedVariables ownership + +- Both TOCs load data before settings, then the core and feature modules. WoW's + addon table carries the private interfaces; there is no runtime module loader. +- `SavedVariables.lua` validates and migrates `BuffRadarDB` to v21 before sharing + it with the modules. The defensive login fallback still sanitizes without + migrating. Import validation does not replace the live table. +- The core chooses what to cast. `Window.lua` owns frames, the viewport, secure + attributes and their cache, and post-combat appearance. A scan invalidates the + viewport before reusing queue entries. `Minimap.lua` owns both minimap and + compartment click dispatch. Existing frame and binding names are retained. +- The smoke harness follows both manifests and checks load order, replaced saves, + secure driver refusal, and position-only resets. The Forever field test is + still required on the candidate ZIP. diff --git a/docs/FOREVER_RELEASE_CHECKLIST.md b/docs/FOREVER_RELEASE_CHECKLIST.md index a30a747..97f69a0 100644 --- a/docs/FOREVER_RELEASE_CHECKLIST.md +++ b/docs/FOREVER_RELEASE_CHECKLIST.md @@ -2,6 +2,45 @@ 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.35 Nearby casting, controller input, blessings, and nameplates + +Result: **Unverified in game**. Run against the candidate ZIP, not a loose copy. + +- **Save and window compatibility:** Upgrade with an existing `BuffRadarDB`, a + saved profile, and per-character positions. Reload and check that the profile, + window position, minimap button, and settings persist. `/br reset` and + `/br resetpos` should reset only the current window position. On leaving + combat, check that deferred scale and theme changes apply, the border flash + returns to the normal colour, and the rows and both cast bindings rearm. +- **Existing and new macros:** Upgrade with the old BuffRadar-generated macro + already on a bar; it should update in place. Try both key-down and key-up + settings. With your own buff missing and an ungrouped player on the list, + the macro should buff you once and then the other player, including a + player with a surname. Test `/br macro` on a fresh install too. +- **Target safety:** Test with a friendly target selected, and again with no + target. After buffing a nearby player your previous target state should + return. If the exact player has left, the cast must not land on the old + target or yourself. Try a party member, combat, death, and a loading + screen. The macro must never cast during combat. Inspect `/br history` and + the counter after successful and failed attempts. +- **Controller:** On the standard gamepad, bind **Cast next buff** via + `/br gamepad` and press it without pointing to a row. Repeat using the + managed action-bar macro. Check one cast per press and that toggling the + game's key-down setting doesn't break the native binding. +- **Blessings:** On a Paladin who knows Kings and a class-appropriate + alternate, test on a nearby player outside your group who has another + Paladin's Kings (then Greater Kings). With the option off, no alternate + should appear. With it on, cast the alternate and check that the queue + does not cycle to a third blessing. Repeat using your own Kings, then with + a group plan or explicit World assignment; the opt-in must not override them. +- **Nameplates:** Note your game settings before using `/br plates` and + `/br plates names`. Make sure the friendly health bar disappears but the + nearby player remains discoverable. Turn plates off, then target or mouse + over the same player; these sources should still work. Change settings + again, reload, and use **Restore Nameplates** or `/br plates restore` to + confirm the recorded values (including Always Show, if changed) return. + Check that enemy and personal nameplate preferences stay untouched. + ## 1.15.34 File split (Slices E, F and G) and row hover highlight Code moved into `Coordination.lua`, `Wizard.lua` and `Window.lua`; nothing should look or diff --git a/docs/PARITY.md b/docs/PARITY.md index 231bd38..fb0efcc 100644 --- a/docs/PARITY.md +++ b/docs/PARITY.md @@ -13,21 +13,23 @@ evidence. In-game status: **1.12.0 verified by SEAN on Forever 1.60.1.70862** (2026-11-08), and SEAN reported on 2026-11-16 that every release through **1.15.31** passed in game; 1.15.32 (Shadowguard watch) and 1.15.33 (input hardening) passed the same day. 1.15.34 (file split, -row hover highlight) is Unverified. +row hover highlight) is Unverified, as is 1.15.35 (macro, controller, nearby blessings, nameplate controls, +and the TOC module refactor). | Area | Target | State | Evidence (test / corpus) | Gap | |---|---|---|---|---| -| Core list & casting | Missing-buff list for group + nearby players; click / keybind / macro casting; you first | Complete | Trial run: list building, click-cast paths (target/id/macro/rank), BuffRadarNextButton + macro sync, in all 6 setups | In-game click-cast verified on Forever at 1.12.0; Retail edition ended at 1.7.0 and stays Unverified | +| Core list & casting | Missing-buff list for group + nearby players; click / keybind / macro casting; you first | Complete | Trial run: list building, click-cast paths (target/id/macro/rank), macro sync and exact-name failure handling in the applicable TOC-driven setups | In-game click-cast verified on Forever at 1.12.0; revised bar macro and hardware controller are Unverified | | Retail buff set | All 13 classes, patch 12.1.5 set | Complete | Edition + per-class steps in the Retail setups | Unverified in a live retail client | +| 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 — 6 setups | All multi-user behaviour Unverified in game (needs a second BuffRadar user) | +| 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 | | 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, wizard step (preset pick applies + advances, theme cycles, Finish marks seen) | — | -| Settings data safety | Versioned SavedVariables, migrations, corrupt-data repair | Complete | Migration fixture: legacy v2 save → v12, corrupt save replaced, corrupt customSpells/autoProfile repaired; v9 save marks the setup wizard as seen (existing users are not nagged) | — | +| Settings data safety | Versioned SavedVariables, migrations, corrupt-data repair | Complete | Migration fixture: legacy v2 save → v21, including defaults for v20 saves; invalid plate-restore keys and malformed settings are dropped | — | | Localisation | deDE, frFR, esES, ruRU, zhCN complete for every user-facing string | Complete | `tools/localecheck.py`: 81/81 strings in each of the five locales; German setup runs the full trial run | New locales are machine-assisted translations; native-speaker review welcome | ## The 50-item program (SEAN approved 2026-10-25: add all 50) diff --git a/editions/forever/BuffRadar.toc b/editions/forever/BuffRadar.toc index 8f1fe52..b605357 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.34 +## Version: 1.15.35 ## SavedVariables: BuffRadarDB ## IconTexture: Interface\AddOns\BuffRadar\Media\icon.png ## Category: Combat @@ -14,10 +14,12 @@ Locales\esES.lua Locales\ruRU.lua Locales\zhCN.lua Data.lua +SavedVariables.lua BuffRadar.lua +Minimap.lua Coordination.lua -Wizard.lua Window.lua +Wizard.lua Config.lua Slash.lua Extras.lua diff --git a/editions/forever/CHANGELOG.md b/editions/forever/CHANGELOG.md index f0aa2d3..4ebe36c 100644 --- a/editions/forever/CHANGELOG.md +++ b/editions/forever/CHANGELOG.md @@ -2,6 +2,26 @@ All notable changes to BuffRadar are listed here. Newest first. +## 1.15.35 — WoW: Forever + +- Fix the action-bar macro for nearby players. It carries the prepared cast + directly when WoW would otherwise have to run a macro from inside another + macro. Existing BuffRadar-generated macros update in place. If an exact + name can no longer be targeted, BuffRadar won't cast on you or your old target. +- Use `/br gamepad` to find the native **Cast next buff** controller binding, + or put the macro from `/br macro` on your controller's action bar. +- Add **Complement Nearby Blessings** under **Buffs → Blessings by class**. + It offers a different known blessing outside your group when another Paladin + already provides your preferred one. It starts off and respects explicit rules. +- In Nearby Player Diagnostics, show names instead of friendly health bars + without losing nearby-player discovery, disable friendly nameplates, or + restore the game settings BuffRadar changed. Use `/br nearby` or `/br plates`. +- Internally, the buff queue, window, minimap, and saved settings now live in + separate addon files. The split retains existing saves and bindings. + +Automated checks passed; live casting, controller input, and nameplate +appearance still need the Forever field test. + ## 1.15.34 — WoW: Forever - Hovering a name now lights its row with a faint wash in your theme's diff --git a/editions/forever/FEATURES.md b/editions/forever/FEATURES.md index 3ac68b0..02c8370 100644 --- a/editions/forever/FEATURES.md +++ b/editions/forever/FEATURES.md @@ -262,9 +262,10 @@ each needs in-game evidence or a sharper definition, recorded in Since 1.3.2, buffing a group member no longer changes your target; for anyone else, BuffRadar targets them by name, casts, then switches back to your previous target. -- **One-key buffing.** Bind *Cast next buff*, or use the BuffRadar - macro (`/br macro`, or `/click BuffRadarNextButton LeftButton 1` - in any macro), to work through the list without clicking. +- **One-key buffing.** Bind *Cast next buff* to a keyboard or controller + button (`/br key` or `/br gamepad`), or put the managed BuffRadar macro + (`/br macro`) on an action bar. A hand-written `/click` macro can't + chain another macro to reach an ungrouped target. - **Highest rank.** Buffs are cast by name, so your highest known rank is always used. - **Class-aware.** Arcane Intellect only goes to mana users, Thorns @@ -272,7 +273,9 @@ each needs in-game evidence or a sharper definition, recorded in each class one fitting blessing: **Blessing of Kings leads every class list since 1.2.3** (it is learned after Might/Wisdom, so it was previously unreachable); Might (warriors, rogues) and Wisdom - (everyone else) are the fallbacks. + (everyone else) are the fallbacks. **Complement Nearby Blessings** + (`/br bless complement on`) can choose an alternative when a player + outside your group has someone else's copy of your preferred blessing. - **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, Greater Blessings…) instead — one @@ -307,7 +310,10 @@ stays hidden on those characters. instead of claiming everyone is buffed, BuffRadar warns once in chat at login, and `/br debug` reports the nameplate setting plus how many nameplate units/players the game is currently showing. - `/br plates` turns friendly nameplates on. + `/br plates` turns friendly nameplates on. Use `/br plates off` to turn + them off, `/br plates names` to keep discovery without health bars on + supported clients, or `/br plates restore` to undo recorded changes. + These controls are also in Nearby Player Diagnostics (`/br nearby`). - **Range can be unanswerable.** This client may accept a range query and return a value no addon is allowed to read. `C_Spell.IsSpellInRange` behaves that way, `UnitInRange` reports nothing usable for anyone outside your group, @@ -374,6 +380,10 @@ stays hidden on those characters. ## Verification status +**1.15.35 candidate:** 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**. + **Field test through 1.15.33:** on 2026-11-16 the maintainer reported that every release up to and including 1.15.31 passed in-game testing in WoW: Forever, and later that day that 1.15.32 (Shadowguard watch) and 1.15.33 diff --git a/editions/forever/README.md b/editions/forever/README.md index 2afe80f..88b1186 100644 --- a/editions/forever/README.md +++ b/editions/forever/README.md @@ -83,7 +83,12 @@ targets the Forever client, and BuffRadar picks the Forever buff set when it loa the Buffs tab, or use `/br bless prefer `. An active group blessing plan takes precedence. Use `/br bless player ` to set or clear a - normal blessing exception for a member of your current group. + normal blessing exception for a member of your current group. Enable + **Complement Nearby Blessings** in the same panel or with + `/br bless complement on` to pick a different known class-appropriate + blessing when an ungrouped player already has your preferred blessing + from another Paladin, including its Greater version. It starts off and + does not override group plans or explicit class/role assignments. - **Class & Role Assignments** (optional): from Settings → Buffs, open **Class & Role Assignments** or type `/br buffassign`. A known group role uses its class and role cell. Strangers and players whose role is @@ -272,17 +277,25 @@ Hover over a name to see exactly what will be cast and what they still need. ### Keybind and macro -- **Keybinds:** Settings > *Set keybind* opens Key Bindings at the BuffRadar section, - which has three: **Cast next buff**, **Show / hide window** and **Mute / unmute sound**. -- **Macro:** Settings > *Create macro* (or `/br macro`) puts a ready-made macro on your - cursor. Drop it on an action bar. You can also add this line to any macro: - - ``` - /click BuffRadarNextButton LeftButton 1 - ``` - - Use `/click BuffRadarNextButton` instead if you've turned off *Cast action keybinds on - key down* in the game options. The BuffRadar macro updates itself if you change that. +- **Keybinds:** `/br key` opens the game's **Key Bindings → BuffRadar**. Bind + **Cast next buff** to a key or controller button. There are also bindings for + **Cast next group buff**, **Show / hide window**, and **Mute / unmute sound**. +- **Macro:** Settings > *Create macro* (or `/br macro`) puts the managed + **BuffRadar** macro on your cursor. Drop it on an action bar and activate + the slot with your keyboard, controller, or mouse. The macro follows the + queue; don't copy its body into a custom macro. Existing auto-generated + macros update in place. A hand-written `/click BuffRadarNextButton` macro + cannot execute another macro, so replace it with the managed one. Use the + direct binding if a cast won't fit within the game's 255-byte macro limit, + and remove the bar macro if you disable or uninstall BuffRadar. +- **Controllers:** `/br gamepad` opens the same binding menu and shows the two + ways to set up controller buffing. To put the macro on a gamepad action bar + without a mouse, select **BuffRadar** in the game's Macros window and use + the prompt to bind it to a gamepad action bar. Neither method needs the + cursor over a player row when casting. + +If only your own character appears, run `/br nearby` to check discovery. Test +outside a capital, or turn off the default city pause with `/br cities`. ## Commands @@ -292,7 +305,7 @@ Hover over a name to see exactly what will be cast and what they still need. | `/br config` | Open the settings window | | `/br config navigate` | Open settings in keyboard navigation mode | | `/br config narrate` | Open keyboard navigation with the game's text-to-speech voice | -| `/br key` | Open Key Bindings at the BuffRadar section | +| `/br key` · `/br gamepad` | Open the BuffRadar key bindings for a keyboard or controller | | `/br macro` | Create the BuffRadar macro | | `/br buffs` | List the buffs you can cast and whether each is on | | `/br toggle KEY` | Turn one buff on or off (keys come from `/br buffs`) | @@ -313,6 +326,7 @@ Hover over a name to see exactly what will be cast and what they still need. | `/br profile save\|load\|delete\|list ` | Named settings profiles | | `/br watch` · `/br taxi` | Alert when your single-target buff drops · pause on flight paths | | `/br bless [name]` | Plan which blessing each class gets | +| `/br bless complement on\|off` | Offer a different blessing to ungrouped players who have your preferred one from another Paladin | | `/br bless player ` | Set or clear a normal blessing exception for a member of your current group | | `/br ready show\|hide\|next\|prev` | Show, hide, or scroll the local ready-check detail | | `/br assign ` | Leader assigns a buff to one player (rows float/sink by owner) | @@ -333,8 +347,10 @@ Hover over a name to see exactly what will be cast and what they still need. | `/br pvp` | Include or skip PvP-flagged players when you aren't flagged (skipped by default) | | `/br lock` · `/br scale ` · `/br reset` | Lock (moving and resizing), set any scale from 0.5 to 2, or reset the window's position | | `/br autohide` | Hide the window when nobody needs anything | -| `/br plates` | Turn on friendly nameplates | -| `/br nearby` | Open Nearby Player Diagnostics to check friendly nameplates, the last scan count, and your current target | +| `/br plates` · `/br plates on\|off` | Enable or disable the game's friendly nameplates | +| `/br plates names\|bars` | Hide or show friendly health bars without changing discovery (on supported clients) | +| `/br plates restore` | Restore nameplate settings last changed through BuffRadar | +| `/br nearby` | Open Nearby Player Diagnostics to change friendly nameplates and check the scan and your current target | | `/br clicks` · `/br debug` | Troubleshooting output | ## Good to know @@ -353,6 +369,12 @@ Hover over a name to see exactly what will be cast and what they still need. players can appear. When nameplates are off the window says so instead of claiming everyone is buffed, and BuffRadar warns once at login. `/br debug` shows whether nameplates are on and how many the game is currently showing. + BuffRadar doesn't tint world nameplates. To hide their health bars while + still finding nearby players, use `/br plates names` or **Show Friendly + Names Only** in Nearby Player Diagnostics. Use `/br plates restore` to + undo recorded changes, including **Always Show Nameplates** if BuffRadar + turned it on. Changes made by older versions weren't recorded; if needed, + use `/br plates off` and adjust **Always Show Nameplates** in game options. - **Major cities:** Stormwind, Ironforge, Darnassus, Orgrimmar, Thunder Bluff, Undercity, The Exodar, Silvermoon and Shattrath. If a city isn't detected, `/br debug` shows the zone and map ID BuffRadar sees. diff --git a/tools/README.md b/tools/README.md index 14c36b8..db893e1 100644 --- a/tools/README.md +++ b/tools/README.md @@ -48,9 +48,9 @@ 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 every Lua file listed in the Forever TOC. A nonzero compiler exit stops the checker before the trial run. | +| **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 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`) | Errors while running: loads the addon into a fake game client, logs in, fires game events, runs every `/br` command, clicks every settings control, and checks the behavior added in 1.3.2, 1.4.0, 1.5.0, 1.6.0 and 1.7.0 (coverage, rezzed priority, session ignore, announce, ready check, expiry flag, low-mana pause, distance sort, spec profiles, export/import, compact rows, per-character position, post-combat flash, SavedVariables migration, cast sync, chat requests, join digest, role filter, toggle strip, need sort, phase skip, idle fade, named profiles, drop alert, coverage cooldown note, flight-path pause, resetpos, all-buffed pill, cast queue tag, shipped presets, consumables watch, custom watched spells, buff assignments, buddy split, blessing planner, coverage uptime, auto profiles, cover-me handoff, ready-check auto-post, coverage roster line, pin a player, tooltip remaining times, weapon enchant watch, instance-entry reminder, group expiry warning, cast history, scan throttle). Runs six setups: retail (modern client, older timer, no UI templates, German client) and Forever (two). | +| **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. | | **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. | @@ -59,9 +59,9 @@ then — just run `-Setup` again. ## Limits of the fake game client `wowstub.lua` imitates only the parts of the game BuffRadar uses, closely -enough to run every code path. It doesn't model layout, secure-button rules, -real casting, group play or combat restrictions, so a clean run still needs a -test in the game. When you add a feature, add a step for it in `smoke51.py`. +enough to exercise the addon's logic and record widget writes. It is not a +renderer or a secure execution environment. A clean run still needs an in-game +test of real casting, controller input, combat lockdown, and visual layout. When you add a feature, add a step for it in `smoke51.py`. The two-client harness controls message order and duplicates in memory. Its assertions cover the addon’s handling of those messages. The harness diff --git a/tools/check.ps1 b/tools/check.ps1 index c8b1001..38c9fdc 100644 --- a/tools/check.ps1 +++ b/tools/check.ps1 @@ -60,7 +60,10 @@ function Section($name) { Write-Host "`n== $name" } # 1. luacheck: accidental globals, unused or shadowed variables, unreachable code Section 'luacheck' Push-Location $project -try { & $luacheck 'BuffRadar\Data.lua' 'BuffRadar\BuffRadar.lua' 'BuffRadar\Coordination.lua' 'BuffRadar\Wizard.lua' 'BuffRadar\Window.lua' 'BuffRadar\Config.lua' 'BuffRadar\Slash.lua' 'BuffRadar\Extras.lua' 'BuffRadar\Recaps.lua' 'BuffRadar\Profiles.lua' 'BuffRadar\Locales' --no-color --codes; if ($LASTEXITCODE -ne 0) { $failed += 'luacheck' } } +try { + & $luacheck 'BuffRadar' --no-color --codes + if ($LASTEXITCODE -ne 0) { $failed += 'luacheck' } +} finally { Pop-Location } # 2. Compile with real Lua 5.1 (the language WoW runs) diff --git a/tools/checkpackage.py b/tools/checkpackage.py index 635491e..7b8ce78 100644 --- a/tools/checkpackage.py +++ b/tools/checkpackage.py @@ -79,7 +79,7 @@ def check_package(archive, project=None): setfenv(chunk, env) chunk("BuffRadar", ns) end, function() - assert(ns.X and ns.X.OpenConfig and ns.X.HandleSlash and ns.X.Export + assert(ns.X and ns.X.OpenConfig and env.SlashCmdList.BUFFRADAR and ns.X.Export and ns.X.DeathRecap, "packaged modules did not initialize") for _, event in ipairs({"ADDON_LOADED", "PLAYER_LOGIN"}) do for _, frame in ipairs(env.__frames) do diff --git a/tools/coordination51.py b/tools/coordination51.py index daff9c6..e496e1b 100644 --- a/tools/coordination51.py +++ b/tools/coordination51.py @@ -90,8 +90,11 @@ error("due timers did not settle") end local function rowFor(unit) - for _, row in ipairs(ns.X.slashAPI.rows) do + local index = 1 + while env["BuffRadarRow" .. index] do + local row = env["BuffRadarRow" .. index] if row:IsShown() and row.entry and row.entry.unit == unit then return row end + index = index + 1 end end return { @@ -116,7 +119,7 @@ buffers = function(fortitude, spirit) local db = env.BuffRadarDB db.enabled.FORTITUDE, db.enabled.DIVINE_SPIRIT = fortitude, spirit - ns.X.slashAPI.BuildBuffList() + ns.X.Core.BuildBuffList() end, slash = function(command) env.SlashCmdList.BUFFRADAR("coordinate " .. command) end, toggleSync = function() env.SlashCmdList.BUFFRADAR("sync") end, diff --git a/tools/gate.sh b/tools/gate.sh index 2a2eab5..e09f9cd 100644 --- a/tools/gate.sh +++ b/tools/gate.sh @@ -1,5 +1,5 @@ #!/bin/sh -# Static checks and the six-setup smoke run used by GitHub CI. +# Static checks and the TOC-driven smoke run used by GitHub CI. # Usage: sh tools/gate.sh (needs python3 or python, plus the lupa package) set -e cd "$(dirname "$0")/.." @@ -12,12 +12,11 @@ for candidate in python3 python; do if "$candidate" -c "import sys" >/dev/null 2>&1; then PY=$candidate; break; fi done [ -n "$PY" ] || { echo "No working python3 or python found."; exit 1; } -LUA="BuffRadar/Data.lua BuffRadar/BuffRadar.lua BuffRadar/Coordination.lua BuffRadar/Wizard.lua BuffRadar/Window.lua BuffRadar/Config.lua BuffRadar/Slash.lua BuffRadar/Extras.lua BuffRadar/Recaps.lua BuffRadar/Profiles.lua" -LOC="$(ls BuffRadar/Locales/*.lua)" -echo "== luacheck51"; "$PY" -I tools/luacheck51.py $LUA $LOC -echo "== lualimits"; for f in $LUA; do "$PY" -I tools/lualimits.py "$f"; done +# 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 echo "== localecheck"; "$PY" -I tools/localecheck.py BuffRadar/BuffRadar.lua BuffRadar/Locales -echo "== patterncheck"; "$PY" -I tools/patterncheck.py $LUA $LOC +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 "Gate passed. Real luacheck 1.2.0: run tools/check.ps1 on Windows." diff --git a/tools/lualimits.py b/tools/lualimits.py index 8f937e6..c6b4194 100644 --- a/tools/lualimits.py +++ b/tools/lualimits.py @@ -1,6 +1,6 @@ -"""Rough Lua 5.1 limit checker for BuffRadar.lua (WoW's Lua is 5.1). +"""Rough limit checker for BuffRadar's Lua 5.1 modules. -Checks the two compile-time limits most likely to break a big single-file addon: +Checks the two compile-time limits most likely to break a large module: * at most 200 active local variables in the main chunk (LUAI_MAXVARS) * at most 60 upvalues per function (LUAI_MAXUPVALUES) Approximate: top-level code is assumed to start at column 0 (the file's style), @@ -17,14 +17,22 @@ KEYWORDS = set("and break do else elseif end false for function if in local nil not or repeat return then true until while".split()) +# Match comments and strings together so a comment marker inside a quoted +# message (e.g. "Low mana -- buffing paused.") never swallows the closing quote. +NON_CODE = re.compile( + r"--\[(?P=*)\[.*?\](?P=comment)\]|--[^\n]*" + r"|\[(?P=*)\[.*?\](?P=brackets)\]" + r"|\"(?:\\.|[^\"\\\n])*\"|'(?:\\.|[^'\\\n])*'", + re.S, +) + + def strip(src): - # remove long comments/strings, comments, then short strings (keep line count) - src = re.sub(r"--\[(=*)\[.*?\]\1\]", lambda m: "\n" * m.group(0).count("\n"), src, flags=re.S) - src = re.sub(r"\[(=*)\[.*?\]\1\]", lambda m: '""' + "\n" * m.group(0).count("\n"), src, flags=re.S) - src = re.sub(r"--[^\n]*", "", src) - src = re.sub(r'"(?:\\.|[^"\\\n])*"', '""', src) - src = re.sub(r"'(?:\\.|[^'\\\n])*'", "''", src) - return src + def blank(token): + text = token.group() + return (" " if text.startswith("--") else '""') + "\n" * text.count("\n") + + return NON_CODE.sub(blank, src) def top_level_locals(lines): diff --git a/tools/smoke51.py b/tools/smoke51.py index 02eb6ba..7b070a1 100644 --- a/tools/smoke51.py +++ b/tools/smoke51.py @@ -1,18 +1,19 @@ """Smoke-run BuffRadar.lua under real Lua 5.1 against a fake WoW API (wowstub.lua). -Loads the file, fires ADDON_LOADED and PLAYER_LOGIN, runs a refresh and a set +Loads the TOC entries in order, fires ADDON_LOADED and PLAYER_LOGIN, runs a refresh and a set of slash commands, opens every settings tab and fires the controls' handlers. Reports the first Lua error of each step plus anything the addon printed as an error. Usage: python -I smoke51.py STUB.lua ADDON.lua """ import sys +from pathlib import Path from lupa import lua51 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()) -harness = lua.eval(r"""function(addonSrc, withTimer, noTemplates, forever, german, localeSrc, extrasSrc, dataSrc, configSrc, slashSrc, recapsSrc, profilesSrc, coordSrc, wizardSrc, windowSrc) +harness = lua.eval(r"""function(sources, withTimer, noTemplates, forever, german) local chat = {} local env = WOWSTUB(chat, withTimer, noTemplates, forever, german) local unitIsUnit = env.UnitIsUnit @@ -71,92 +72,55 @@ end local NS = {} -local chunk, cerr = loadstring(addonSrc, "=BuffRadar.lua") -if not chunk then return { { "compile", "FAIL: " .. cerr } }, chat end -setfenv(chunk, env) -if localeSrc then -- Locales\*.lua load before BuffRadar.lua (.toc order) - step("load translation file", function() - local lchunk = assert(loadstring(localeSrc, "=Locales/deDE.lua")) - setfenv(lchunk, env) - lchunk("BuffRadar", NS) - assert(NS.Locales and NS.Locales.deDE and not env.BuffRadarLocales, "locale pack did not stay in the addon namespace") - end) -end -if dataSrc then - step("load Data.lua", function() - local dch = assert(loadstring(dataSrc, "=Data.lua")) - setfenv(dch, env) - dch("BuffRadar", NS) - assert(NS.X and NS.X.BUFF_DEFS and NS.X.BLESSINGS, "Data.lua did not publish its tables") - end) -end -step("load file (main chunk)", function() chunk("BuffRadar", NS) end) --- File split Slices E, F and G (1.15.34) load straight after the main file (.toc order). -if coordSrc then - step("load Coordination.lua", function() - local och = assert(loadstring(coordSrc, "=Coordination.lua")) - setfenv(och, env) - och("BuffRadar", NS) - assert(NS.X.InitSync and NS.X.OnAddonMsg and NS.X.OnRoster, "Coordination.lua did not publish its entry points") - end) -end -if wizardSrc then - step("load Wizard.lua", function() - local wch = assert(loadstring(wizardSrc, "=Wizard.lua")) - setfenv(wch, env) - wch("BuffRadar", NS) - assert(NS.X.WizardPage, "Wizard.lua did not publish its entry points") - end) -end -if windowSrc then - step("load Window.lua", function() - local gch = assert(loadstring(windowSrc, "=Window.lua")) - setfenv(gch, env) - gch("BuffRadar", NS) - assert(NS.X.BuildUI and NS.X.ClearNext and NS.X.BindCached and NS.X.NextBindState, - "Window.lua did not publish its entry points") - end) -end -if configSrc then - step("load Config.lua", function() - local cch = assert(loadstring(configSrc, "=Config.lua")) - setfenv(cch, env) - cch("BuffRadar", NS) - assert(NS.X.RefreshConfig and NS.X.OpenConfig, "Config.lua did not publish its entry points") - end) -end -if slashSrc then - step("load Slash.lua", function() - local sch = assert(loadstring(slashSrc, "=Slash.lua")) - setfenv(sch, env) - sch("BuffRadar", NS) - assert(NS.X.HandleSlash and NS.X.OnOff, "Slash.lua did not publish its entry points") - end) -end -if extrasSrc then - step("load Extras.lua", function() - local ech = assert(loadstring(extrasSrc, "=Extras.lua")) - setfenv(ech, env) - ech("BuffRadar", NS) - end) +local initialGlobals = {} +for key in pairs(env) do initialGlobals[key] = true end +local addonGlobals = { + BuffRadarDB = true, + BuffRadar_ToggleWindow = true, BuffRadar_ToggleSound = true, + SLASH_BUFFRADAR1 = true, SLASH_BUFFRADAR2 = true, + BINDING_HEADER_BUFFRADAR = true, BINDING_CATEGORY_BUFFRADAR = true, + BINDING_NAME_BUFFRADAR_TOGGLE = true, BINDING_NAME_BUFFRADAR_MUTE = true, + ["BINDING_NAME_CLICK BuffRadarNextButton:LeftButton"] = true, + ["BINDING_NAME_CLICK BuffRadarGroupButton:LeftButton"] = true, +} +local function CheckGlobals() + local frames = {} + for _, f in ipairs(env.__frames) do + local name = f:GetName() + if name then frames[name] = f end + end + for key, value in pairs(env) do + assert(initialGlobals[key] or addonGlobals[key] or frames[key] == value, "unexpected global: " .. tostring(key)) + end end -if recapsSrc then - step("load Recaps.lua", function() - local rch = assert(loadstring(recapsSrc, "=Recaps.lua")) - setfenv(rch, env) - rch("BuffRadar", NS) - assert(NS.X.DeathRecap and NS.X.WipeCheck, "Recaps.lua did not publish its entry points") - end) +local function LoadFile(file, client, ns) + local chunk = assert(loadstring(file[2], "@" .. file[1])) + setfenv(chunk, client) + chunk("BuffRadar", ns) end -if profilesSrc then - step("load Profiles.lua", function() - local pch = assert(loadstring(profilesSrc, "=Profiles.lua")) - setfenv(pch, env) - pch("BuffRadar", NS) - assert(NS.X.Export and NS.X.Import and NS.X.ApplyPreset, "Profiles.lua did not publish its entry points") - end) +for _, file in ipairs(sources) do + step("load " .. file[1], function() LoadFile(file, env, NS) end) end +step("TOC modules initialize in the private namespace", function() + CheckGlobals() + local X = NS.X + assert(X and X.BUFF_DEFS and X.BLESSINGS and X.Settings and X.BuildUI and X.BuildMinimapButton, + "data, settings, window or minimap module missing") + assert(X.InitSync and X.OnAddonMsg and X.OnRoster and X.WizardPage and X.RefreshConfig + and X.OpenConfig and env.SlashCmdList.BUFFRADAR and X.OnOff and X.DeathRecap and X.WipeCheck + and X.Export and X.Import and X.ApplyPreset, "feature module did not publish its entry points") + assert(NS.Locales and NS.Locales.deDE, "locale pack did not stay in the addon namespace") +end) +step("SavedVariables are not opened by module loading or profile validation", function() + local X = NS.X + assert(X.GetDB() == nil and env.BuffRadarDB == nil, "settings loaded before ADDON_LOADED") + local first, second = X.Settings.Sanitize({}), X.Settings.Sanitize({}) + first.enabled.TEST = true + first.bgColor[1] = 1 + assert(not second.enabled.TEST and second.bgColor[1] == 0.04, "clean settings share defaults by reference") + assert(X.GetDB() == nil and env.BuffRadarDB == nil, "sanitizing a candidate published it") +end) local driver for _, f in ipairs(env.__frames) do @@ -166,6 +130,48 @@ end step("find event frame", function() assert(driver, "no frame registered ADDON_LOADED") end) if not driver then return results, chat end +local function TestClient() + local messages = {} + local client = WOWSTUB(messages, withTimer, noTemplates, forever, german) + client._G = client + return setmetatable(client, { __index = std }), messages +end +local function LoadClient(client) + local ns = {} + for _, file in ipairs(sources) do LoadFile(file, client, ns) end + for _, f in ipairs(client.__frames) do + if f.events and f.events.PLAYER_LOGIN and f.events.ADDON_LOADED then return ns.X, f end + end + error("login driver did not register both events") +end +step("login fallback sanitizes without migrating and later loads replace the live save", function() + local client = TestClient() + local saved = { dbVersion = 9, scale = 9, castMethod = "rank", showOutOfRange = true, + showMinimap = false, ignored = { BeforeLogin = true }, obsolete = true } + client.BuffRadarDB = saved + local X, startup = LoadClient(client) + local onEvent = startup.scripts.OnEvent + onEvent(startup, "ADDON_LOADED", "OtherAddon") + 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(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") + local minimap = client.BuffRadarMinimapButton + assert(minimap and not minimap:IsShown(), "minimap did not receive fallback settings") + + local replacement = { dbVersion = 9, scale = 1.5, showMinimap = true } + client.BuffRadarDB = replacement + onEvent(startup, "ADDON_LOADED", "BuffRadar") + assert(X.GetDB() == replacement and replacement.dbVersion == 21 and replacement.wizardSeen, + "normal load did not migrate and publish the replacement") + assert(not X.Ignore.Has("BeforeLogin", "BeforeLogin"), "ignore index retained a replaced save") + X.ApplyGeometry() + X.RefreshMinimapButton() + assert(client.BuffRadarFrame:GetScale() == 1.5 and minimap:IsShown(), "UI modules held onto replaced settings") +end) local fire = function(ev, ...) driver.scripts.OnEvent(driver, ev, ...) if ev == "PLAYER_REGEN_DISABLED" or (ev == "PLAYER_DEAD" and env.__combat) then @@ -180,7 +186,9 @@ end step("ADDON_LOADED", function() fire("ADDON_LOADED", "BuffRadar") + assert(NS.X.GetDB() == env.BuffRadarDB and env.BuffRadarDB.dbVersion == 21, "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") local before, registered = env.C_ChatInfo, {} env.C_ChatInfo = { RegisterAddonMessagePrefix = function(prefix) registered[#registered + 1] = prefix end } @@ -197,7 +205,7 @@ local oldMinimap = db.showMinimap db.showMinimap = true fire("PLAYER_LOGIN") - assert(not env.BuffRadarFrame:IsShown() and not NS.X.pill:IsShown(), "dead login showed a buff surface") + assert(not env.BuffRadarFrame:IsShown() and not env.BuffRadarPill:IsShown(), "dead login showed a buff surface") assert(not env.BuffRadarMinimapButton:IsShown() and db.showMinimap, "dead login changed minimap preference") assert(not env.BuffRadarNextButton:GetAttribute("type") and not env.BuffRadarGroupButton:GetAttribute("type"), "dead login armed a cast binding") @@ -205,8 +213,9 @@ fire("PLAYER_ALIVE") assert(env.BuffRadarMinimapButton:IsShown(), "living player did not regain configured minimap button") db.showMinimap = oldMinimap - NS.X.cfgAPI.RefreshMinimapButton() + NS.X.RefreshMinimapButton() end) +step("startup creates only game entry points and named frames", CheckGlobals) step("window exists", function() assert(env.BuffRadarFrame, "BuffRadarFrame not created") end) step("minimap button exists", function() assert(env.BuffRadarMinimapButton, "no minimap button") end) step("minimap button follows both axes after the map is resized", function() @@ -214,7 +223,7 @@ local oldWidth, oldHeight, oldAngle, oldCursor = map.GetWidth, map.GetHeight, db.minimapAngle, env.GetCursorPosition map.GetWidth, map.GetHeight = function() return 240 end, function() return 160 end db.minimapAngle = 0 - NS.X.cfgAPI.RefreshMinimapButton() + NS.X.RefreshMinimapButton() local p = button.points[#button.points] local horizontal = #button.points == 1 and math.abs(p[4] - 125) < 0.01 map.GetWidth, map.GetHeight = function() return 300 end, function() return 200 end @@ -228,34 +237,76 @@ button:GetScript("OnDragStop")(button) local angle = db.minimapAngle map.GetWidth, map.GetHeight, db.minimapAngle, env.GetCursorPosition = oldWidth, oldHeight, oldAngle, oldCursor - NS.X.cfgAPI.RefreshMinimapButton() + NS.X.RefreshMinimapButton() assert(horizontal and followsSize and math.abs(angle - 45) < 0.01, "minimap geometry ignored an axis or resize") end) -step("friendly nameplates select the supported CVar and verify changes", function() - local vars = { nameplateShowFriendlyPlayers = "0", nameplateShowAll = "0" } +step("friendly plate styles and restore only change verified, supported CVars", function() + local X, db = NS.X, env.BuffRadarDB + local style = X.friendlyPlateNamesCVar + local vars = { nameplateShowFriendlyPlayers = "0", nameplateShowAll = "0", [style] = "0", + nameplateShowEnemies = "1", nameplateShowSelf = "1" } local oldCVar, oldGet, oldBool, oldSet = env.C_CVar, env.GetCVar, env.GetCVarBool, env.SetCVar + local oldRestore = db.plateRestore env.GetCVar, env.GetCVarBool, env.SetCVar = nil, function() return false end, nil - env.C_CVar = { - GetCVar = function(key) return vars[key] end, - SetCVar = function(key, value) if vars[key] then vars[key] = value end end, - } - local friendly = NS.X.FriendlyPlatesOn - local initiallyOff = friendly and friendly() == false - env.SlashCmdList.BUFFRADAR("plates") - local modernSet = vars.nameplateShowFriendlyPlayers == "1" and vars.nameplateShowAll == "1" - vars.nameplateShowFriendlyPlayers, vars.nameplateShowFriends = nil, "1" - local legacy, name - if friendly then legacy, name = friendly() end - vars.nameplateShowFriends = nil - local unknown = friendly and friendly() == nil - vars.nameplateShowFriendlyPlayers = "0" - env.C_CVar.SetCVar = function() return true end - local n = #chat - env.SlashCmdList.BUFFRADAR("plates") - local reportsFailure = #chat > n and not chat[#chat]:find("Friendly nameplates turned on", 1, true) + db.plateRestore = {} + local ok, err = pcall(function() + local writes, refused = 0, "nameplateShowFriendlyPlayers" + env.C_CVar = { + GetCVar = function(key) return vars[key] end, + SetCVar = function(key, value) + writes = writes + 1 + if vars[key] and key ~= refused then vars[key] = value end + end, + } + local slash = env.SlashCmdList.BUFFRADAR + assert(X.FriendlyPlatesOn() == false and writes == 0, "reading nameplates changed settings") + slash("plates") + assert(writes == 1 and vars.nameplateShowAll == "0" and not next(db.plateRestore), + "a refused write changed or recorded other settings") + refused = nil + slash("plates") + assert(vars.nameplateShowFriendlyPlayers == "1" and vars.nameplateShowAll == "1", "enable skipped a setting") + assert(db.plateRestore.nameplateShowFriendlyPlayers == false and db.plateRestore.nameplateShowAll == false, + "the original off values were not saved") + slash("plates names") + assert(vars[style] == "1" and vars.nameplateShowFriendlyPlayers == "1", "names-only lost friendly plate discovery") + assert(not assert(X.ProfileSnapshot()):find("plateRestore", 1, true) + and not assert(X.Export()):find("plateRestore", 1, true), "local nameplate settings leaked into a shareable export") + slash("plates bars") + assert(vars[style] == "0" and db.plateRestore[style] == nil, "bars did not clear its pending change") + slash("plates names") + env.__combat = true + local before = writes + slash("plates restore") + slash("plates off") + assert(writes == before, "plate settings changed during combat") + env.__combat = false + refused = style + slash("plates restore") + assert(vars.nameplateShowAll == "0" and vars.nameplateShowFriendlyPlayers == "0" and vars[style] == "1" + and db.plateRestore[style] == false, "partial restore did not preserve the refused setting for retry") + refused = nil + slash("plates restore") + assert(vars[style] == "0" and not next(db.plateRestore), "restore retry did not finish") + assert(vars.nameplateShowEnemies == "1" and vars.nameplateShowSelf == "1", "unrelated plates were changed") + + vars.nameplateShowFriendlyPlayers, vars.nameplateShowFriends, vars[style] = nil, "1", nil + local legacy, name = X.FriendlyPlatesOn() + assert(legacy and name == "nameplateShowFriends", "legacy nameplate CVar was not found") + slash("plates off") + assert(vars.nameplateShowFriends == "0" and db.plateRestore.nameplateShowFriends == true, + "explicit off did not save the previously enabled state") + slash("plates restore") + assert(vars.nameplateShowFriends == "1", "restore did not reenable previously enabled nameplates") + before = writes + slash("plates names") + vars.nameplateShowFriends = nil + slash("plates off") + assert(writes == before and X.FriendlyPlatesOn() == nil, "unsupported plate setting was written") + end) env.C_CVar, env.GetCVar, env.GetCVarBool, env.SetCVar = oldCVar, oldGet, oldBool, oldSet - assert(initiallyOff and modernSet and legacy and name == "nameplateShowFriends" and unknown and reportsFailure, - "friendly nameplate CVar selection or readback failed") + db.plateRestore, env.__combat = oldRestore, false + assert(ok, err) end) step("slash command registered", function() assert(env.SLASH_BUFFRADAR1 == "/br" and env.SlashCmdList.BUFFRADAR, "no /br") @@ -475,6 +526,7 @@ runQueued() end) step("pull timer: probe counts sightings; flash fires with casts outstanding (1.14.0)", function() + if not NS.X.ApiCheck then return end -- optional Extras.lua local pf for _, f in ipairs(env.__frames) do if f.events and f.events.START_TIMER then pf = f end end assert(pf, "no frame registered START_TIMER") @@ -504,6 +556,7 @@ env.SlashCmdList.BUFFRADAR("pullflash off") end) step("changing a pull timer keeps its replacement until the replacement expires", function() + if not NS.X.ApiCheck then return end -- optional Extras.lua if not env.__timers then return end runQueued() local X, db = NS.X, env.BuffRadarDB @@ -884,6 +937,268 @@ env.IsSpellInRange = nil end end +step("action-bar macro follows self and nearby targets without chaining macros", function() + local cleanup = twoTanks() + local X, O, db = NS.X, env.__over, env.BuffRadarDB + local index = env.GetMacroIndexByName("BuffRadar") + local savedMacro = env.__macros[index] + local oldCVar, oldOpen, oldSpell, oldZone = env.GetCVarBool, env.Settings.OpenToCategory, env.C_Spell, env.__zone + local oldSelf, oldMode, oldMod, oldSort, oldCity = db.includeSelf, db.castMethod, db.modClick, db.sortMode, db.pauseInCities + local oldEdit, oldFrame, oldOffer, oldShift = env.EditMacro, env.MacroFrame, X.GroupOffer, env.IsShiftKeyDown + local function idle(body) return body and not body:find("\n/click", 1, true) and not body:find("\n/cast", 1, true) end + local ok, err = pcall(function() + env.__macros[index] = nil + fire("UPDATE_MACROS") + X.SyncCastMacro(true) + assert(env.GetMacroIndexByName("BuffRadar") == 0, "background sync created a macro without permission") + env.SlashCmdList.BUFFRADAR("macro") + index = env.GetMacroIndexByName("BuffRadar") + assert(index > 0 and env.__pickedMacro == index, "/br macro did not create and pick up a new macro") + env.__macros[index] = nil + fire("UPDATE_MACROS") + X.SyncCastMacro(true) + -- A macro already in a user's action bar should be upgraded in its own slot. + index = env.CreateMacro("BuffRadar", 134400, "/click BuffRadarNextButton LeftButton 1") + fire("UPDATE_MACROS") + env.EditMacro = function(...) + local slot = oldEdit(...) + fire("UPDATE_MACROS") -- this event is synchronous on the real client + return slot + end + X.SyncCastMacro(true) + assert(idle(env.GetMacroBody(index)), "old addon macro was not migrated to a harmless idle body") + local keyDown, selfCovered, hasTarget = false, false, true + local exists, name, guid = O.UnitExists, O.UnitName, O.UnitGUID + local renamed, replacement + O.UnitExists = function(unit) return unit == "target" and hasTarget or exists(unit) end + O.UnitGUID = function(unit) if unit == "nameplate1" and replacement then return replacement end; return guid(unit) end + O.UnitName = function(unit) + if unit == "nameplate1" then return renamed or "Alden", env.__forever and "Ashford" or nil end + return name(unit) + end + O.Aura = function(unit) + if unit == "player" and selfCovered then return { expirationTime = env.GetTime() + 3600 } end + return nil + end + env.IsSpellInRange = function() return 1 end + env.GetCVarBool = function(key) + if key == "ActionButtonUseKeyDown" then return keyDown end + return oldCVar(key) + end + db.includeSelf, db.castMethod, db.modClick, db.sortMode = true, "target", false, "name" + X.Refresh() + local button = env.BuffRadarNextButton + local selfBody = env.GetMacroBody(index) + assert(button.entry and button.entry.isSelf and selfBody:find("\n/click BuffRadarNextButton$"), + "self-priority or native spell action changed") + keyDown = true + fire("CVAR_UPDATE", "ACTION_BUTTON_USE_KEY_DOWN") + assert(button.clickRegistration[1] == "LeftButtonDown" + and env.GetMacroBody(index):find("BuffRadarNextButton LeftButton 1$"), "key-down phase not synced for spell casts") + env.SlashCmdList.BUFFRADAR("macro") + assert(env.__pickedMacro == index, "create macro did not preserve the existing action bar slot") + + selfCovered = true + X.Refresh() + local target = env.__forever and "Alden Ashford" or "Alden" + local body = env.GetMacroBody(index) + assert(button.entry and button.entry.unit == "nameplate1" and button:GetAttribute("type") == "macro", + "next secure button did not move from self to the nearby player") + assert(body:find("/stopmacro [combat][@player,dead]", 1, true) + and not body:find("/click BuffRadarNextButton", 1, true) + and body:find("\n/cleartarget\n/targetexact " .. target .. "\n/cast [help,nodead] ", 1, true) + and body:find("\n/targetlasttarget$"), "managed macro does not execute a guarded exact-name cast at top level") + assert(body:find(shownRows().nameplate1.row:GetAttribute("macrotext"), 1, true), + "row and bar macro disagreed on how to reach the player") + local writes = env.__macroWrites + X.Refresh(); X.Refresh() + assert(env.__macroWrites == writes, "a steady queue rewrote its macro") + keyDown = false + fire("CVAR_UPDATE", "ActionButtonUseKeyDown") + assert(button.clickRegistration[1] == "LeftButtonUp" and env.GetMacroBody(index) == body, + "changing key phase rewrote a direct bar cast or lost the up binding") + + -- Model only the relevant slash commands, including a /targetexact miss + -- leaving its input target alone. The real secure execution needs WoW. + local function simulate(text, previous, available, stopped) + local current, last, cast = previous, "Old target" + for line in text:gmatch("[^\n]+") do + if line == "/stopmacro [combat][@player,dead]" and stopped then break end + if line == "/cleartarget" then + if current then last = current end + current = nil + elseif line:find("^/targetexact ") then + if available then current = line:sub(14) end + elseif line:find("/cast [help,nodead] ", 1, true) then + cast = current + elseif line == "/targetlasttarget" then + current = last + end + end + return cast, current + end + local recipient, restored = simulate(body, "Previous friend", false) + assert(not recipient and restored == "Previous friend", "a missed exact name cast on the old target or self") + recipient, restored = simulate(body, "Previous friend", true) + assert(recipient == target and restored == "Previous friend", "exact cast did not hand back the prior target") + hasTarget = false + X.Refresh() + body = env.GetMacroBody(index) + recipient, restored = simulate(body, nil, true) + assert(recipient == target and not restored, "cast with no original target reselected a stale previous one") + + -- The action marker does not cast. Only the spell event with the intended + -- target and ID can advance the counter, whether the input was key or bar. + local spellID = env.__forever and 1244 or 462854 + env.C_Spell = { GetSpellIDForSpellIdentifier = function() return spellID end } + local before = db.castsTotal + X.ResetCastTracking() + env.__runningMacro = index + 1 + env.BuffRadarMacroButton:Click() + fire("UNIT_SPELLCAST_SENT", "player", target, "macro-unowned", spellID) + fire("UNIT_SPELLCAST_SUCCEEDED", "player", "macro-unowned", spellID) + assert(db.castsTotal == before, "a different macro claimed the managed cast") + env.__runningMacro = index + env.BuffRadarMacroButton:Click() + env.__runningMacro = nil + fire("UNIT_SPELLCAST_SENT", "player", target, "managed-macro", spellID) + fire("UNIT_SPELLCAST_SUCCEEDED", "player", "managed-macro", spellID) + assert(db.castsTotal == before + 1 and db.history[#db.history].who == target, + "the direct bar cast lost confirmed recipient attribution") + local opened + env.Settings.OpenToCategory = function(category, section) opened = category == env.Settings.KEYBINDINGS_CATEGORY_ID and section end + env.SlashCmdList.BUFFRADAR("gamepad") + assert(opened == "BuffRadar" and button.entry.unit == "nameplate1", "controller setup did not open the native buff binding") + + env.__runningMacro = index + X.SyncCastMacro(true) + assert(env.GetMacroBody(index) == body, "an in-progress macro was rewritten") + env.__runningMacro = nil + fire("NAME_PLATE_UNIT_REMOVED", "nameplate2") + assert(env.GetMacroBody(index) == body, "an unrelated nameplate disarmed the macro") + fire("NAME_PLATE_UNIT_REMOVED", "nameplate1") + assert(idle(env.GetMacroBody(index)), "nameplate removal left the macro armed until the next scan") + renamed, replacement = "Cedric", "Player-1-T99" + X.Refresh() + assert(env.GetMacroBody(index):find("/targetexact Cedric", 1, true), "recycled nameplate kept its old target") + db.castMethod = "macro" + X.Refresh() + assert(button:GetAttribute("macrotext"):find("[@nameplate1,help,nodead]", 1, true) + and env.GetMacroBody(index):find("/targetexact Cedric", 1, true), "bar macro embedded a recycled unit token") + renamed, replacement, db.castMethod = nil, nil, "target" + X.Refresh() + + -- The editor may have unsaved text. Background writes must not fire + -- UPDATE_MACROS until it closes, and a hand-edit loses ownership. + env.MacroFrame = env.CreateFrame("Frame") + env.MacroFrame:Show() + renamed, replacement = "Cedric", "Player-1-T99" + X.Refresh() + assert(env.GetMacroBody(index) == body, "macro editor did not defer automatic writes") + env.MacroFrame:Hide() + timerTick() + assert(env.GetMacroBody(index):find("/targetexact Cedric", 1, true), "macro did not catch up after editing finished") + env.MacroFrame = oldFrame + + -- Refuse a body the game would truncate, without disabling the native + -- action (its shorter script still fits). Then verify a Shift variant. + renamed, replacement = "A" .. string.rep("é", 77), "Player-1-T100" + X.Refresh() + assert(button.entry and #button:GetAttribute("macrotext") <= 255 and idle(env.GetMacroBody(index)), + "an oversized bar macro was stored or disabled the native cast") + renamed, replacement = "Alden\n/cast Another Spell", "Player-1-T101" + X.Refresh() + assert(not button:GetAttribute("macrotext") and idle(env.GetMacroBody(index)), + "an unusable exact name became macro commands") + renamed, replacement = nil, nil + X.Refresh() + if env.__forever then + local base = button.bSpell + db.modClick = true + X.GroupOffer = function(spell, unit) + if spell == base and unit == "nameplate1" then return "Group buff" end + return oldOffer(spell, unit) + end + X.Refresh() + local shifted = env.GetMacroBody(index) + assert(shifted:find("/cast [mod:shift,nomod:ctrl,nomod:alt,help,nodead] Group buff; [help,nodead] ", 1, true) + and not shifted:find("/click BuffRadarNextButton", 1, true), "bar cast lost or nested the Shift variant") + X.ResetCastTracking() + env.IsShiftKeyDown = function() return true end + env.__runningMacro = index + env.BuffRadarMacroButton:Click() + env.__runningMacro = nil + fire("UNIT_SPELLCAST_SENT", "player", target, "shifted-macro", spellID) + fire("UNIT_SPELLCAST_SUCCEEDED", "player", "shifted-macro", spellID) + assert(db.history[#db.history].spell == "Group buff", "bar macro attributed Shift to the unmodified spell") + env.IsShiftKeyDown, db.modClick, X.GroupOffer = oldShift, false, oldOffer + X.Refresh() + end + assert(env.GetMacroBody(index) == body, "restoring the original queue did not restore the original macro") + db.pauseInCities, env.__zone = true, "Stormwind City" + fire("ZONE_CHANGED_NEW_AREA") + timerTick() + assert(idle(env.GetMacroBody(index)) and not button.entry, "city pause left the macro armed") + db.pauseInCities, env.__zone = false, oldZone + X.Refresh() + assert(not idle(env.GetMacroBody(index)), "turning off city pause did not rearm the macro") + + env.__combat = true + fire("PLAYER_REGEN_DISABLED") + local combatWrites = env.__macroWrites + X.SyncCastMacro(true) + assert(env.__macroWrites == combatWrites and not simulate(body, "Previous friend", true, true), + "combat attempted to edit the macro or left the direct cast enabled") + env.__combat = false + fire("PLAYER_REGEN_ENABLED") + assert(idle(env.GetMacroBody(index)), "pre-combat macro was still armed before a safe rescan") + X.Refresh() + assert(not idle(env.GetMacroBody(index)), "leaving combat did not rearm the macro") + fire("PLAYER_DEAD") + assert(idle(env.GetMacroBody(index)), "death left the macro armed") + fire("PLAYER_ALIVE") + X.Refresh() + assert(not idle(env.GetMacroBody(index)), "resurrection did not rearm the macro") + fire("PLAYER_LEAVING_WORLD") + X.Refresh() + assert(idle(env.GetMacroBody(index)), "loading screen left an armed macro") + fire("PLAYER_ENTERING_WORLD") + X.Refresh() + assert(not idle(env.GetMacroBody(index)), "returning to the world did not rearm the macro") + + -- A manual edit may happen before the next UPDATE_MACROS. Recheck + -- before disarming so the write cannot hit an unrelated macro slot. + local custom = env.GetMacroBody(index) .. "\n/say hello" + oldEdit(index, nil, nil, custom) + X.SyncCastMacro(true) + fire("UPDATE_MACROS") + X.Refresh() + env.SlashCmdList.BUFFRADAR("macro") + assert(env.GetMacroBody(index) == custom, "an edited BuffRadar macro was overwritten") + env.__macros[index] = nil + fire("UPDATE_MACROS") + X.SyncCastMacro(true) + index = env.CreateMacro("BuffRadar", 134400, custom) -- even before it is tracked this session + fire("UPDATE_MACROS") + X.SyncCastMacro(true) + assert(env.GetMacroBody(index) == custom, "a macro with an added line was reclaimed from the marker alone") + end) + env.__combat, env.__runningMacro, X.macroParked = false, nil, nil + env.GetCVarBool, env.Settings.OpenToCategory, env.C_Spell, env.__zone = oldCVar, oldOpen, oldSpell, oldZone + env.EditMacro, env.MacroFrame, X.GroupOffer, env.IsShiftKeyDown = oldEdit, oldFrame, oldOffer, oldShift + db.includeSelf, db.castMethod, db.modClick, db.sortMode, db.pauseInCities = oldSelf, oldMode, oldMod, oldSort, oldCity + env.__macros[index] = nil + fire("UPDATE_MACROS") + X.SyncCastMacro(true) + if savedMacro then env.CreateMacro(savedMacro.name, savedMacro.icon, savedMacro.body); fire("UPDATE_MACROS") end + cleanup() + env.IsSpellInRange = nil + X.ResetCastTracking() + fire("PLAYER_ALIVE") + X.ApplyNextRegistration() + X.Refresh() + assert(ok, err) +end) step("cast keybinds disarm when a roster token changes after the scan", function() local cleanup = partyOfTwo("KEY") local O, X, db = env.__over, NS.X, env.BuffRadarDB @@ -1350,7 +1665,7 @@ end) step("rezzed party member jumps the queue (1.4.0)", function() if env.__forever then return end - local cleanup = partyOfTwo() + local cleanup = partyOfTwo("RezSymbols") local O = env.__over env.IsSpellInRange = function() return 1 end -- in range: the tag, not the far label, applies local dead = false @@ -1368,6 +1683,15 @@ "rezzed member not second (after self): " .. tostring(row2 and row2.entry and row2.entry.unit)) assert(row2.entry.rezzed, "rezzed flag not set on the entry") assert(row2.tag and row2.tag.shown, "'recently rezzed' tag not shown") + local db = env.BuffRadarDB + local oldSymbols = db.tagSymbols + db.tagSymbols = true + NS.X.InvalidateTags() + refresh() + local withSymbol = row2.tag:GetText() + db.tagSymbols = oldSymbols + NS.X.InvalidateTags() + assert(withSymbol == "+ " .. NS.X.L["recently rezzed"], "rezzed tag lost its accessibility symbol") O.UnitIsDeadOrGhost = nil cleanup() end) @@ -1416,7 +1740,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 == 20, "dbVersion not migrated to 20: " .. tostring(d.dbVersion)) + assert(d.dbVersion == 21, "dbVersion not migrated to 21: " .. 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") @@ -1440,7 +1764,7 @@ env.BuffRadarDB = "junk" fire("ADDON_LOADED", "BuffRadar") d = env.BuffRadarDB - assert(type(d) == "table" and d.dbVersion == 20 and d.scale == 1, + assert(type(d) == "table" and d.dbVersion == 21 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 @@ -1448,18 +1772,32 @@ env.BuffRadarDB = { dbVersion = 9 } fire("ADDON_LOADED", "BuffRadar") d = env.BuffRadarDB - assert(d.dbVersion == 20 and d.wizardSeen == true, + assert(d.dbVersion == 21 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 == 20 and d.thornsAnyClassOutdoors == false and d.assignmentEnabled, + assert(d.dbVersion == 21 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 == 20 and d.theme == "ui.auto" and d.autoThemePriority == "", + assert(d.dbVersion == 21 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 == 21 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, + [NS.X.friendlyPlateNamesCVar] = "0", nameplateShowEnemies = false } + fire("ADDON_LOADED", "BuffRadar") + d = env.BuffRadarDB + assert(d.blessingComplement and d.plateRestore.nameplateShowFriends == false and d.plateRestore.nameplateShowAll == true + and d.plateRestore[NS.X.friendlyPlateNamesCVar] == nil and d.plateRestore.nameplateShowEnemies == nil, + "reloading lost valid options or accepted unsupported CVars") + d.blessingComplement, d.plateRestore = false, {} NS.X.ApplyTheme("midnight") d.assignmentEnabled = false d.wizardSeen = false -- leave the save as the rest of the suite expects @@ -1680,6 +2018,7 @@ env.GetSpecialization = nil end) step("ignore list export/import round-trip (1.13.0)", function() + if not NS.X.ApiCheck then return end -- optional Extras.lua local d = env.BuffRadarDB env.SlashCmdList.BUFFRADAR("ignore Zork") env.SlashCmdList.BUFFRADAR("ignore Bleep-Realm") @@ -1705,6 +2044,7 @@ end) step("/br summary and /br apicheck export (1.13.0)", function() env.SlashCmdList.BUFFRADAR("summary") + if not NS.X.ApiCheck then return end -- optional Extras.lua env.SlashCmdList.BUFFRADAR("apicheck export") local f = env.BuffRadarExportFrame assert(f and f.editBox:GetText():find("API check", 1, true), "apicheck export text missing") @@ -1752,7 +2092,7 @@ "BR1;" .. string.rep("A", 16384), } for i, input in ipairs(bad) do - assert(not X.Import(input) and not X.SettingsDiff(input), "invalid clipboard accepted: " .. i) + assert(not X.Import(input) and (not X.SettingsDiff or not X.SettingsDiff(input)), "invalid clipboard accepted: " .. i) assert(d.enabled.TEST and d.rebuffPer.TEST == 33 and d.ignored.Zed and d.scale == 1, "invalid clipboard changed settings: " .. i) end @@ -2989,7 +3329,7 @@ "incorrect swatch for " .. palette[1]) end assert(appliedBackground[4] == alpha, "theme changed background opacity") - local restored = X.SanitizeDB({ theme = palette[1], bgColor = db.bgColor }) + local restored = X.Settings.Sanitize({ theme = palette[1], bgColor = db.bgColor }) assert(restored.theme == palette[1], "sanitizer discarded " .. palette[1]) end slash("theme parchment") @@ -3064,7 +3404,7 @@ local queries = 0 env.IsAddOnLoaded = nil env.C_AddOns = { IsAddOnLoaded = function(name) queries = queries + 1; return loaded[name] == true, loaded[name] == true end } - assert(X.SanitizeDB({}).theme == "midnight", "Auto replaced the default") + assert(X.Settings.Sanitize({}).theme == "midnight", "Auto replaced the default") slash("theme midnight") fire("ADDON_LOADED", "ElvUI") assert(db.theme == "midnight" and queries == 0, "manual/default theme opted in or probed addons") @@ -3314,13 +3654,13 @@ local slash = env.SlashCmdList.BUFFRADAR local prevModern, prevLegacy, prevOrder = env.C_AddOns, env.IsAddOnLoaded, db.autoThemePriority local ok, err = pcall(function() - local repaired = X.SanitizeDB({ + local repaired = X.Settings.Sanitize({ autoThemePriority = " UI.WICKS ,unknown,ui.elvui,ui.wicks,ui.auto", }) assert(repaired.autoThemePriority:match("^ui%.wicks,ui%.elvui,ui%.ellesmereui,ui%.anoui,"), "partial order did not allowlist, dedupe, and append default candidates") for _, malformed in ipairs({ {}, 42, "unknown", string.rep("x", 513) }) do - assert(X.SanitizeDB({ autoThemePriority = malformed }).autoThemePriority == "", + assert(X.Settings.Sanitize({ autoThemePriority = malformed }).autoThemePriority == "", "corrupt priority order did not use defaults") end env.C_AddOns = { IsAddOnLoaded = function(name) @@ -3412,14 +3752,18 @@ end) step("close control follows hover without reserving titleless header space", function() local X, db = NS.X, env.BuffRadarDB - local frame, close = env.BuffRadarFrame, NS.X.closeButton + local frame, close = env.BuffRadarFrame + for _, widget in ipairs(env.__frames) do + if widget.parent == frame and widget.template == "UIPanelCloseButton" then close = widget; break end + end + assert(close, "main window did not create its close button") local oldTitle, oldLocked, oldClick = db.showTitle, db.locked, db.clickThrough local oldMouse, oldCloseMouse, oldTop = env.__mouseOver, close.IsMouseOver, env.UIParent.GetTop local ok, err = pcall(function() db.showTitle, db.locked, db.clickThrough = true, false, false env.__mouseOver = false X.ApplyRowLayout() - local titledTop = X.topH + local titledY = env.BuffRadarRow1.points[1][5] frame:Show() X.UpdateFade() assert(not close:IsShown(), "close control is visible without hover") @@ -3430,7 +3774,7 @@ db.showTitle = false X.ApplyRowLayout() X.UpdateFade() - assert(titledTop - X.topH == 24, "titleless rows still reserve the title header") + assert(env.BuffRadarRow1.points[1][5] - titledY == 24, "titleless rows still reserve the title header") assert(close.hoverAnchor == "BOTTOMRIGHT", "titleless close does not float above its rows") env.__mouseOver = false close.IsMouseOver = function() return true end @@ -3457,7 +3801,7 @@ assert(ok, err) end) step("combat visibility leaves locked frames to the secure driver", function() - local frame, pill = env.BuffRadarFrame, NS.X.pill + local frame, pill = env.BuffRadarFrame, env.BuffRadarPill local db = env.BuffRadarDB local oldHidden = db.hidden local hideFrame, hidePill = frame.Hide, pill.Hide @@ -3493,14 +3837,14 @@ end) step("death suspends the window, settings and casts through release and combat exit", function() local X, db = NS.X, env.BuffRadarDB - local frame, pill, button = env.BuffRadarFrame, X.pill, env.BuffRadarMinimapButton + local frame, pill, button = env.BuffRadarFrame, env.BuffRadarPill, env.BuffRadarMinimapButton local oldHidden, oldMinimap, oldDead = db.hidden, db.showMinimap, env.__over.UnitIsDeadOrGhost local oldHide = frame.Hide local tooltip, oldOwner = env.GameTooltip, env.GameTooltip.GetOwner local dead = true local ok, err = pcall(function() db.hidden, db.showMinimap = false, true - X.cfgAPI.RefreshMinimapButton() + X.RefreshMinimapButton() X.OpenConfig(true) local cfg = assert(env.BuffRadarConfig) frame:Show() @@ -3561,28 +3905,27 @@ tooltip.GetOwner = oldOwner tooltip:Hide() fire("PLAYER_ALIVE") - X.cfgAPI.RefreshMinimapButton() + X.RefreshMinimapButton() timerTick() assert(ok, err) end) step("appearance refresh never changes the frame layer and flash restore waits for combat", function() local X, db = NS.X, env.BuffRadarDB - local frame, pill = env.BuffRadarFrame, X.pill + local frame, pill = env.BuffRadarFrame, env.BuffRadarPill local oldFrame, oldPill = frame.SetFrameStrata, pill.SetFrameStrata local oldMotion, writes = db.reduceMotion, 0 frame.SetFrameStrata = function() writes = writes + 1; error("main frame layer is fixed") end pill.SetFrameStrata = function() writes = writes + 1; error("pill frame layer is fixed") end local ok, err = pcall(function() db.reduceMotion = false - X.cfgAPI.ApplyAppearance() + X.ApplyAppearance() assert(writes == 0, "appearance refresh changed a frame layer") local restoreBorder X.Flash() + assert(frame.borderColor[1] == 1 and frame.borderColor[2] == 0.35, "border pulse did not show") if env.C_Timer then restoreBorder = table.remove(env.__timers) assert(restoreBorder, "border pulse did not schedule a restore") - else - assert(X.flashPending, "border pulse did not request a fallback restore") end env.__combat = true local delayOk, delayErr = true, nil @@ -3591,8 +3934,10 @@ assert(writes == 0, "combat flash restore changed a frame layer") env.__combat = false fire("PLAYER_REGEN_ENABLED") - assert(not X.flashPending, "appearance replay left a redundant fallback border restore") - X.cfgAPI.ApplyAppearance() + local expected = X.ThemeBorder() + assert(frame.borderColor[1] == expected[1] and frame.borderColor[2] == expected[2], + "post-combat appearance did not restore the border colour") + X.ApplyAppearance() assert(writes == 0, "appearance refresh attempted a protected frame-layer change") end) env.__combat = false @@ -3617,7 +3962,7 @@ env.GetSpellTabInfo = function() return "General", nil, 0, 1 end db.hidden, db.groupOnly, db.includeSelf, db.pauseInCities = false, false, true, false db.castMethod, db.enabled.SHAMAN_SHIELD = "target", true - X.cfgAPI.BuildBuffList() + X.Core.BuildBuffList() X.Refresh() local listed = assert(shownRows().player, "Lightning Shield self row is absent") row = listed.row @@ -3660,29 +4005,48 @@ env.GetSpellBookItemName, env.GetSpellBookItemInfo, env.GetSpellTabInfo = oldNames, oldInfo, oldTab db.hidden, db.groupOnly, db.includeSelf, db.pauseInCities = oldHidden, oldGroup, oldSelf, oldCity db.castMethod, db.enabled.SHAMAN_SHIELD = oldMethod, oldShield - X.cfgAPI.BuildBuffList() + X.Core.BuildBuffList() assert(ok, err) end) -step("combat cast driver requires both secure setup operations to accept", function() - local X = NS.X - local previousRegister = env.RegisterStateDriver - local registrations, snippetResult, driverResult = 0, false, nil - local button = { SetAttribute = function() return snippetResult end } - local ok, err = pcall(function() - env.RegisterStateDriver = function() - registrations = registrations + 1 - return driverResult - end - assert(not X.InstallCombatDriver(button, ""), "explicit snippet refusal armed the control") - assert(registrations == 0, "driver installed after the snippet failed") - snippetResult, driverResult = nil, false - assert(not X.InstallCombatDriver(button, ""), "explicit driver refusal armed the control") - snippetResult, driverResult = nil, nil - assert(X.InstallCombatDriver(button, "") and registrations == 2, "successful void calls did not arm") - end) - env.RegisterStateDriver = previousRegister - assert(ok, err) +step("secure rows and keys arm only after the combat driver is installed", function() + for _, outcome in ipairs({ "snippet refused", "registration refused", "success" }) do + local client, messages = TestClient() + local create, registrations = client.CreateFrame, {} + client.CreateFrame = function(kind, name, parent, template) + local button = create(kind, name, parent, template) + if template and template:find("SecureActionButtonTemplate", 1, true) then + local setScript, setAttribute = button.SetScript, button.SetAttribute + button.SetScript = function(self, event, callback) + assert(event ~= "OnClick", name .. " replaced a secure OnClick") + return setScript(self, event, callback) + end + button.SetAttribute = function(self, key, value) + if key == "_onstate-combat" and outcome == "snippet refused" then return false end + return setAttribute(self, key, value) + end + end + return button + end + client.RegisterStateDriver = function(button, state) + if state ~= "combat" then return end + registrations[button] = (registrations[button] or 0) + 1 + if outcome == "registration refused" then return false end + end + local X, startup = LoadClient(client) + startup.scripts.OnEvent(startup, "ADDON_LOADED", "BuffRadar") + startup.scripts.OnEvent(startup, "PLAYER_LOGIN") + X.Refresh() + for _, message in ipairs(messages) do assert(not message:find("error", 1, true), message) end + local row = assert(client.BuffRadarRow1) + assert(row:IsShown() and row.entry, "no eligible row to exercise secure setup") + for _, name in ipairs({ "BuffRadarRow1", "BuffRadarNextButton", "BuffRadarGroupButton" }) do + local button = assert(client[name], name .. " was not built") + local expected = outcome == "snippet refused" and 0 or 1 + assert((registrations[button] or 0) == expected, name .. " registered unexpectedly: " .. outcome) + assert((button:GetAttribute("type") ~= nil) == (outcome == "success"), name .. " armed incorrectly: " .. outcome) + end + end end) step("name finder filters the list (1.8.0)", function() @@ -5845,14 +6209,14 @@ local function cleanup() env.IsPlayerSpell, db.blessingPreferences, X.blessPlan.MAGE = oldKnown, oldPreferences, oldPlan X.DeleteProfile("AuditBlessing") - X.cfgAPI.BuildBuffList() + X.Core.BuildBuffList() if env.BuffRadarBlessingPreferences then env.BuffRadarBlessingPreferences:Hide() end if X.RefreshConfig then X.RefreshConfig() end end local ok, err = pcall(function() env.IsPlayerSpell = function(id) return id == 19740 or id == 19742 or oldKnown(id) end db.blessingPreferences, X.blessPlan.MAGE = {}, nil - X.cfgAPI.BuildBuffList() + X.Core.BuildBuffList() assert(X.BlessingForClass("MAGE").name == "Blessing of Wisdom", "default blessing changed") local sent = #env.__addonSent env.SlashCmdList.BUFFRADAR("bless prefer MAGE MIGHT") @@ -5877,13 +6241,133 @@ assert(env.BuffRadarBlessingPreferences.shown and #cfg.blessingSelectors == 9, "blessing settings did not show one control per Forever class") env.IsPlayerSpell = function(id) return id == 19742 or oldKnown(id) end - X.cfgAPI.BuildBuffList() + X.Core.BuildBuffList() assert(X.BlessingForClass("MAGE").name == "Blessing of Wisdom" and db.blessingPreferences.MAGE == "MIGHT", "an unavailable saved preference did not fall back without clearing it") end) cleanup() assert(ok, err) end) +step("Forever nearby blessing complement respects caster ownership and explicit rules", function() + if not env.__forever then return end + local cleanup = twoTanks() + local X, O, db = NS.X, env.__over, env.BuffRadarDB + local oldKnown, oldAuras, oldSecret = env.IsPlayerSpell, env.C_UnitAuras, env.issecretvalue + local oldComplement, oldPrefs, oldRules, oldMode = db.blessingComplement, db.blessingPreferences, db.buffAssignments, db.assignmentEnabled + local oldPlan, oldEnabled, oldContext = X.blessPlan, db.enabled.BLESSINGS, db.buffContext.BLESSINGS + local ok, err = pcall(function() + local kings, greater, wisdom, might = "Blessing of Kings", "Greater Blessing of Kings", "Blessing of Wisdom", "Blessing of Might" + local unit = "nameplate2" + local expiry, auras = env.GetTime() + 600, {} + env.IsPlayerSpell = function(id) return id == 20217 or id == 19742 or id == 19740 or oldKnown(id) end + db.blessingComplement, db.blessingPreferences, db.buffAssignments, db.assignmentEnabled = false, {}, {}, false + db.enabled.BLESSINGS, db.buffContext.BLESSINGS, X.blessPlan = true, nil, {} + env.IsSpellInRange = function() return 1 end + O.Aura = function(u, name) if u == unit then return auras[name] end; return nil end + X.Core.BuildBuffList() + local function aura(owner, timer) + return { isFromPlayerOrPlayerPet = owner, expirationTime = timer or expiry } + end + local scan = 0 + local function offers(expected) + X.Refresh() + scan = scan + 1 + local row = shownRows()[unit] or {} + for _, name in ipairs({ kings, wisdom, might }) do + assert((row[name] == true) == (expected == name), "scan " .. scan .. " unexpected queue spell: " .. name .. "; wanted " .. tostring(expected)) + end + end + auras[kings] = aura(false) + offers(nil) + local slash, sent = env.SlashCmdList.BUFFRADAR, #env.__addonSent + slash("bless complement on") + assert(db.blessingComplement and #env.__addonSent == sent, "world blessing opt-in was not local") + offers(wisdom) + local before = #chat + slash("why Tank2") + assert(chatSince(before, "complement another Paladin") and chatSince(before, wisdom), + "why disagreed with the nearby blessing on offer") + auras[might] = aura(true) + offers(nil) -- Don't cycle away from your own already-active alternate. + auras[might].expirationTime = env.GetTime() + 5 + offers(might) + auras[might], auras[wisdom] = nil, aura(false) + offers(might) + auras[might], auras[kings].expirationTime = aura(false), env.GetTime() + 5 + offers(nil) -- Don't overwrite a foreign blessing when no alternative fits. + auras = { [kings] = aura(true, env.GetTime() + 5) } + offers(kings) + auras = { [wisdom] = aura(false) } + offers(kings) -- The usual preference is already complementary. + local masked = {} + env.issecretvalue = function(v) return v == masked end + auras = { [kings] = aura(masked, env.GetTime() + 5) } + offers(nil) + env.issecretvalue = oldSecret + + local list = { { name = greater, expirationTime = expiry, sourceUnit = "nameplate1" } } + env.C_UnitAuras = { GetBuffDataByIndex = oldAuras.GetBuffDataByIndex } + O.AuraList = function(u) if u == unit then return list end end + offers(wisdom) -- Greater and normal share a family, including on the index API. + env.C_UnitAuras = nil + offers(wisdom) -- Legacy UnitBuff's caster return carries the same meaning. + list[1].sourceUnit = "player" + offers(nil) + local guid = O.UnitGUID + list[1].sourceUnit = "target" + O.UnitGUID = function(u) if u == "target" then return guid("player") end; return guid(u) end + offers(nil) -- A caster token can alias the player. + O.UnitGUID = guid + offers(nil) -- A caster token with no readable GUID is not another Paladin. + list[1].sourceUnit = "nameplate1" + list[2] = { name = masked, expirationTime = expiry, sourceUnit = "player" } + env.issecretvalue = function(v) return v == masked end + offers(nil) -- An incomplete index read cannot prove the alternate is absent. + env.issecretvalue, env.C_UnitAuras = oldSecret, oldAuras + auras = { [kings] = aura(false) } + O.AuraList = nil + + X.blessPlan.PALADIN = { mine = true, key = "KINGS" } + offers(nil) + X.blessPlan.PALADIN = nil + assert(X.SetAssignmentEnabled(true) and X.SetAssignment("PALADIN", "WORLD", { BLESS_KINGS = true })) + offers(nil) + assert(X.SetAssignmentEnabled(false)) + offers(wisdom) + local details, groupMissing = { cooldown = {}, cooldowns = {} }, {} + X.Core.Missing(unit, groupMissing, true, false, "why", details) + assert(not table.concat(groupMissing):find(wisdom, 1, true) and not details.blessing, + "world option affected a grouped recipient") + + assert(X.SaveProfile("ComplementAudit"), "could not save complement setting") + local shared = assert(X.ProfileShareText("ComplementAudit")) + assert(shared:find(";blessingComplement=1;", 1, true), "BR2 did not serialize the opt-in") + 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, + "a pre-v21 BR2 did not load with complement off") + offers(nil) + assert(X.ProfileImport(shared) and X.LoadProfile("ComplementAudit") and db.blessingComplement, + "a shared profile did not restore the opt-in") + local cfg = env.BuffRadarConfig + X.OpenConfig(true) + cfg.blessingButton:Click() + local check = env.BuffRadarBlessingPreferences.complement + assert(check:GetChecked(), "blessing panel did not reflect the setting") + check:SetChecked(false); check:Click() + assert(not db.blessingComplement, "the complement checkbox did not turn the option off") + end) + env.IsPlayerSpell, env.C_UnitAuras, env.issecretvalue = oldKnown, oldAuras, oldSecret + db.blessingComplement, db.blessingPreferences, db.buffAssignments, db.assignmentEnabled = oldComplement, oldPrefs, oldRules, oldMode + X.blessPlan, db.enabled.BLESSINGS, db.buffContext.BLESSINGS = oldPlan, oldEnabled, oldContext + X.DeleteProfile("ComplementAudit") + if env.BuffRadarBlessingPreferences then env.BuffRadarBlessingPreferences:Hide() end + X.Core.BuildBuffList() + cleanup() + env.IsSpellInRange = nil + assert(ok, err) +end) step("blessing plan: set, broadcast, receive, list (1.6.0)", function() if not env.__forever then return end local cleanup = partyOfTwo("L") @@ -6056,7 +6540,8 @@ if not env.__forever then return end local cleanup = partyOfTwo("Nearby") local X, O, db = NS.X, env.__over, env.BuffRadarDB - local oldCVar, oldCount = env.C_CVar, X.playersSeen + local oldCVar, oldCount, oldRestore = env.C_CVar, X.playersSeen, db.plateRestore + db.plateRestore = {} local oldRole, oldAssignments, oldMode = env.UnitGroupRolesAssigned, db.buffAssignments, db.assignmentEnabled local oldTitle, oldLocked, oldClick = db.showTitle, db.locked, db.clickThrough local ok, err = pcall(function() @@ -6077,7 +6562,7 @@ env.UnitGroupRolesAssigned = function(unit) return unit == "party1" and "DAMAGER" or "NONE" end db.buffAssignments = {} assert(X.SetAssignmentEnabled(true) and X.SetAssignment("MAGE", "DAMAGER", false)) - local vars = { nameplateShowFriendlyPlayers = "0", nameplateShowAll = "0" } + local vars = { nameplateShowFriendlyPlayers = "0", nameplateShowAll = "0", [X.friendlyPlateNamesCVar] = "0" } local writes, allow = 0, false env.C_CVar = { GetCVar = function(key) return vars[key] end, @@ -6092,16 +6577,20 @@ X.ApplyRowLayout() db.locked, db.clickThrough = true, true X.ApplyClickThrough() - assert(X.nearbyButton and not X.nearbyButton:IsShown(), "nearby help intercepted locked click-through") + local help + for _, widget in ipairs(env.__frames) do + if widget.parent == env.BuffRadarFrame and widget:GetText() == "?" then help = widget; break end + end + assert(help and not help:IsShown(), "nearby help intercepted locked click-through") db.locked, db.clickThrough = false, false X.ApplyClickThrough() X.playersSeen = nil local tally, n = X.tally, #chat local cast = env.BuffRadarNextButton:GetAttribute("unit") - assert(X.nearbyButton:IsShown(), "nearby help missing from the titleless window with eligible players") - X.nearbyButton:Click() + assert(help:IsShown(), "nearby help missing from the titleless window with eligible players") + help:Click() local panel = env.BuffRadarNearbyDiagnostics - assert(panel:IsShown() and panel.enablePlates:IsShown() and panel.nameplates:GetText() == "Friendly nameplates: Off", + assert(panel:IsShown() and panel.togglePlates:IsShown() and panel.nameplates:GetText() == "Friendly nameplates: Off", "off nameplates did not offer an action in the diagnostics panel") assert(panel.count:GetText():find("unavailable", 1, true) and panel.details:GetText() ~= "", "missing scan data or target was not explained") @@ -6115,17 +6604,24 @@ assert(panel.targetDirty and reason:find("Aaron", 1, true) and reason:find("DPS rule", 1, true) and reason:find("None", 1, true) and X.tally == tally and #chat == n, "the read-only target diagnosis lost the matched party unit or its explicit role rule") - panel.enablePlates:Click() - assert(writes == 1 and panel.enablePlates:IsShown() and panel.message:GetText() ~= "", + panel.togglePlates:Click() + assert(writes == 1 and panel.togglePlates:IsShown() and panel.message:GetText() ~= "", "a refused nameplate write was accepted") allow = true - panel.enablePlates:Click() - assert(writes == 3 and not panel.enablePlates:IsShown() and panel.nameplates:GetText() == "Friendly nameplates: On", + panel.togglePlates:Click() + assert(writes == 3 and panel.togglePlates:GetText() == "Disable Friendly Nameplates" + and panel.restorePlates:IsShown() and panel.nameplates:GetText() == "Friendly nameplates: On", "a verified nameplate write did not update the panel") - assert(#chat == n and X.tally == tally, "the enable action posted chat or rebuilt the queue") + panel.plateStyle:Click() + assert(vars[X.friendlyPlateNamesCVar] == "1" and panel.plateStyle:GetText() == "Show Friendly Health Bars", + "names-only control did not update the native style") + panel.restorePlates:Click() + assert(not panel.restorePlates:IsShown() and vars.nameplateShowAll == "0" and vars[X.friendlyPlateNamesCVar] == "0" + and panel.togglePlates:GetText() == "Enable Friendly Nameplates", "restore did not return the panel and CVars to baseline") + assert(#chat == n and X.tally == tally, "the plate controls posted chat or rebuilt the queue synchronously") vars.nameplateShowFriendlyPlayers = nil event(panel, "CVAR_UPDATE") - assert(panel.nameplates:GetText() == "Friendly nameplates: Unknown" and not panel.enablePlates:IsShown() + assert(panel.nameplates:GetText() == "Friendly nameplates: Unknown" and not panel.togglePlates:IsShown() and panel.message:GetText() == "", "unknown nameplate setting was treated as a writable off setting") plate = true @@ -6150,7 +6646,7 @@ assert(not panel:IsShown() and not panel.events.CVAR_UPDATE, "death left nearby diagnostics open") end) X.CloseNearbyDiagnostics() - env.C_CVar, env.__combat, X.playersSeen = oldCVar, false, oldCount + env.C_CVar, env.__combat, X.playersSeen, db.plateRestore = oldCVar, false, oldCount, oldRestore env.UnitGroupRolesAssigned, db.buffAssignments, db.assignmentEnabled = oldRole, oldAssignments, oldMode db.showTitle, db.locked, db.clickThrough = oldTitle, oldLocked, oldClick cleanup() @@ -6160,6 +6656,7 @@ assert(ok, err) end) step("pull countdown shows on the coverage line (1.15.0)", function() + if not NS.X.ApiCheck then return end -- optional Extras.lua local cleanup = partyOfTwo() local pf for _, f in ipairs(env.__frames) do if f.events and f.events.START_TIMER then pf = f end end @@ -6264,7 +6761,7 @@ estimate = X.ReagentEstimate(report) assert(#estimate == 1 and estimate[1].needed == 1 and estimate[1].carried == nil and X.ReagentSummary(report):find("17028 ?/1", 1, true), "unreadable stock was treated as zero") - assert(shownRows().party1.row:GetAttribute("spell") == 1243 and X.NoCastReason():find("Could not check reagent"), + assert(shownRows().party1.row:GetAttribute("spell") == 1243 and (group.bOfferReason or ""):find("Could not check reagent", 1, true), "unreadable bags armed a reagent spell or hid the reason") targetLevel = 30 refresh() @@ -6460,6 +6957,14 @@ local oldSize = env.GetNumGroupMembers local oldCount, oldTip = env.C_Item.GetItemCount, env.GameTooltip local oldIncludeSelf, oldGroupCast, oldClickThrough = db.includeSelf, db.groupCast, db.clickThrough + local previewAnchor + for _, widget in ipairs(env.__frames) do + if widget.parent == env.BuffRadarFrame and widget.kind == "Frame" and widget:GetScript("OnEnter") then + previewAnchor = widget + break + end + end + assert(previewAnchor, "next-cast preview control not built") local ok, err = pcall(function() local role = "DAMAGER" env.GetNumGroupMembers = function() return 3 end @@ -6503,7 +7008,7 @@ local lines = {} env.GameTooltip = { SetOwner = function() end, Show = function() end, Hide = function() end, AddLine = function(_, line) lines[#lines + 1] = line end } - X.ShowNextPreview({}) + previewAnchor:GetScript("OnEnter")(previewAnchor) local tooltip = table.concat(lines, "\n") assert(tooltip:find("Prayer of Fortitude is blocked by 1 group member.", 1, true), "next-cast tooltip did not count the blocker: " .. tooltip) @@ -6563,7 +7068,7 @@ lines = {} env.GameTooltip = { SetOwner = function() end, Show = function() end, Hide = function() end, AddLine = function(_, line) lines[#lines + 1] = line end } - X.ShowNextPreview({}) + previewAnchor:GetScript("OnEnter")(previewAnchor) tooltip = table.concat(lines, "\n") assert(tooltip:find("Prayer of Fortitude is blocked by 2 group members.", 1, true) and tooltip:find("incomplete", 1, true) @@ -7139,7 +7644,7 @@ end db.assignmentEnabled, db.buffAssignments, db.enabled.THORNS, db.buffContext.THORNS = false, {}, true, nil db.thornsAnyClassOutdoors = false - X.cfgAPI.BuildBuffList() + X.Core.BuildBuffList() X.Refresh() local function offered(unit, buff) local row = shownRows()[unit] @@ -7237,7 +7742,7 @@ X.DeleteProfile("OutdoorThornsTest") cleanup() env.IsSpellInRange = oldRange - X.cfgAPI.BuildBuffList() + X.Core.BuildBuffList() refresh() assert(ok, err) end) @@ -7433,19 +7938,36 @@ assert(shownRows().party1, "party not listed after landing") cleanup() end) -step("/br resetpos clears the saved window spot (1.5.0)", function() - local db = env.BuffRadarDB - db.point = { "TOPLEFT", "BOTTOMLEFT", 5000, 4000 } - local n = #chat - env.SlashCmdList.BUFFRADAR("resetpos") - assert(db.point == nil, "resetpos did not clear the saved spot") - assert(chatSince(n, "default spot"), "no resetpos message") +step("/br reset and resetpos clear only the current window position", function() + local X, db = NS.X, env.BuffRadarDB + local character = assert(X.CharKey()) + local point, byChar, charPoint = db.point, db.pointByChar, db.charPoint + local width, casts, profiles = db.width, db.castsTotal, db.profiles + db.charPoint, db.width, db.castsTotal = true, 275, 42 + db.profiles = { Keep = "BR1;width=250" } + local expected = X.Export() + local otherPoint = { "TOPLEFT", "BOTTOMLEFT", 200, 600 } + for _, command in ipairs({ "reset", "resetpos" }) do + db.point = { "TOPLEFT", "BOTTOMLEFT", 5000, 4000 } + db.pointByChar = { [character] = db.point, ["Offline-Realm"] = otherPoint } + local n = #chat + env.SlashCmdList.BUFFRADAR(command) + assert(X.GetDB() == db and not db.point and not db.pointByChar[character], command .. " kept the saved spot") + assert(db.pointByChar["Offline-Realm"] == otherPoint, command .. " reset another character's spot") + assert(X.Export() == expected and db.castsTotal == 42 and db.profiles.Keep == "BR1;width=250", + command .. " changed unrelated settings") + local anchor = env.BuffRadarFrame.points[1] + assert(anchor[1] == "TOPLEFT" and anchor[3] == "LEFT" and anchor[4] == 40, command .. " did not reanchor the window") + assert(chatSince(n, command == "reset" and "Position reset." or "default spot"), "no " .. command .. " message") + end + db.point, db.pointByChar, db.charPoint = point, byChar, charPoint + db.width, db.castsTotal, db.profiles = width, casts, profiles end) step("/br selftest prints a paste-able block (1.4.0)", function() local n = #chat env.SlashCmdList.BUFFRADAR("selftest") assert(chatSince(n, "BuffRadar self-test"), "no self-test header") - assert(chatSince(n, "dbVersion 20"), "self-test missing dbVersion") + assert(chatSince(n, "dbVersion 21"), "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") @@ -7501,6 +8023,7 @@ env.SlashCmdList.BUFFRADAR("width 210") end) step("1.12.0 diagnostics: apicheck, buffcheck, perf, settings diff", function() + if not NS.X.ApiCheck then return end -- optional Extras.lua local X = NS.X local n = #chat env.SlashCmdList.BUFFRADAR("apicheck") @@ -7527,16 +8050,21 @@ env.SlashCmdList.BUFFRADAR("profile delete dtest") end) step("cast counter fits a narrow window instead of being cut off", function() - local X = NS.X - local f = X.footerText - assert(f, "footer text was not exposed") + local f + for _, label in ipairs(env.__fontstrings) do + local right = label.points and label.points[2] + if right and right[1] == "RIGHT" and right[2] == env.BuffRadarFrame and right[3] == "BOTTOMRIGHT" then + f = label + break + end + end + assert(f, "cast counter not anchored to the window footer") local prevW, prevSW = f.GetWidth, f.GetStringWidth -- Plenty of room: the full line stays. f.GetWidth = function() return 400 end f.GetStringWidth = function() return 120 end - X.lastCounterRoom = nil - NS.X.slashAPI.UpdateCounter() + NS.X.UpdateCounter() -- Checked on the "/" that only the compact form has, so this holds in every -- locale: the German pack translates the words but not the separator. assert(not f:GetText():find("/", 1, true), @@ -7546,16 +8074,15 @@ -- right with word wrap off, the alternative is a cut-off "39 all-t...". f.GetWidth = function() return 40 end f.GetStringWidth = function() return 120 end - X.lastCounterRoom = nil - NS.X.slashAPI.UpdateCounter() + NS.X.UpdateCounter() local narrow = f:GetText() assert(narrow:find("/", 1, true), "the long counter line survived a window too narrow for it") f.GetWidth, f.GetStringWidth = prevW, prevSW - X.lastCounterRoom = nil end) step("apicheck readability tier tells restricted apart from absent", function() + if not NS.X.ApiCheck then return end -- optional Extras.lua local n = #chat env.SlashCmdList.BUFFRADAR("apicheck") assert(chatSince(n, "readability on"), "no readability section") @@ -7597,7 +8124,6 @@ assert(db.tagSymbols == true, "tagsymbols not on") env.SlashCmdList.BUFFRADAR("tagsymbols") assert(db.tagSymbols == false, "tagsymbols not off") - assert(X.TAGSYM["recently rezzed"] == "+" or env.__german, "tag symbol table") env.SlashCmdList.BUFFRADAR("motion") assert(db.reduceMotion == true, "reduced motion not on") local a = env.BuffRadarFrame.borderColor @@ -7630,24 +8156,25 @@ end) step("1.12.0 badges: update pending (combat) and data hidden (secret)", function() local X = NS.X - local frame = env.BuffRadarFrame - env.__combat = true - env.SlashCmdList.BUFFRADAR("width 250") - env.__combat = false - X.ext = X.ext -- (slash width is refused in combat; ApplyGeometry path is what we test) + local function HasTitleMark(mark) + for _, label in ipairs(env.__fontstrings) do + local text = label:GetText() + if type(text) == "string" and text:find("|cff33ccffBuff|rRadar", 1, true) == 1 + and text:find(mark, 1, true) then return true end + end + end env.__combat = true - X.ApplyScaleNow() - assert(X.geoPending == true, "pending flag not set in combat") + X.ApplyGeometry() + local pending = HasTitleMark("(update pending)") env.__combat = false - X.ApplyScaleNow() - assert(not X.geoPending, "pending flag not cleared out of combat") + X.ApplyGeometry() + assert(pending and not HasTitleMark("(update pending)"), "combat geometry title did not mark and clear the pending change") X.hid = env.GetTime() - X.titleKey = nil - X.UpdateTitleMarks() - assert(X.titleKey == "h", "data-hidden mark not set: " .. tostring(X.titleKey)) + X.RefreshWindowHeader() + local hidden = HasTitleMark("(data hidden)") X.hid = 0 - X.UpdateTitleMarks() - assert(X.titleKey == "", "data-hidden mark not cleared") + X.RefreshWindowHeader() + assert(hidden and not HasTitleMark("(data hidden)"), "unreadable aura title did not mark and clear the data warning") end) step("1.12.0 UNIT_AURA payload: empty incremental update is dropped", function() local n0 = env.__zoneCalls @@ -7739,16 +8266,18 @@ -- IgnoreImport: valid, oversize, escape codes, control characters. local before = {} for k, v in pairs(db.ignored) do before[k] = v end - local ok = X.IgnoreImport("BRI1;Hardenone;Hardentwo") - assert(ok and db.ignored.Hardenone and db.ignored.Hardentwo, "valid ignore import failed") - local okBig, msgBig = X.IgnoreImport("BRI1;" .. string.rep("Floodname;", 2000)) - assert(not okBig and msgBig:find("16 KiB", 1, true) and not db.ignored.Floodname, - "oversize ignore import was accepted") - assert(X.IgnoreImport("BRI1;|cffff0000Red|r;Tab\tName;Hardenthree"), "mixed ignore import refused") - assert(not db.ignored["|cffff0000Red|r"] and not db.ignored["Tab\tName"] and db.ignored.Hardenthree, - "escape-code or control-character name was stored") - assert(X.IgnoreImport(("BRI1;" .. string.rep("x", 65))), "overlong name aborted the import") - assert(not db.ignored[string.rep("x", 65)], "overlong name was stored") + if X.IgnoreImport then -- optional Extras.lua + local ok = X.IgnoreImport("BRI1;Hardenone;Hardentwo") + assert(ok and db.ignored.Hardenone and db.ignored.Hardentwo, "valid ignore import failed") + local okBig, msgBig = X.IgnoreImport("BRI1;" .. string.rep("Floodname;", 2000)) + assert(not okBig and msgBig:find("16 KiB", 1, true) and not db.ignored.Floodname, + "oversize ignore import was accepted") + assert(X.IgnoreImport("BRI1;|cffff0000Red|r;Tab\tName;Hardenthree"), "mixed ignore import refused") + assert(not db.ignored["|cffff0000Red|r"] and not db.ignored["Tab\tName"] and db.ignored.Hardenthree, + "escape-code or control-character name was stored") + assert(X.IgnoreImport(("BRI1;" .. string.rep("x", 65))), "overlong name aborted the import") + assert(not db.ignored[string.rep("x", 65)], "overlong name was stored") + end env.SlashCmdList.BUFFRADAR("ignore |TInterface\\Icons\\X:0|t") env.SlashCmdList.BUFFRADAR("ignore Hardenfour") assert(not db.ignored["|TInterface\\Icons\\X:0|t"] and db.ignored.Hardenfour, @@ -8100,7 +8629,7 @@ for _, fs in ipairs(env.__fontstrings) do if fs.text == "Kampf" then found = true end end assert(found, "combat label not translated ('Kampf' not found)") end) -step("split files share the live settings (Slices E and F)", function() +step("coordination and wizard share the live settings", function() local X, db = NS.X, NS.X.GetDB() assert(db, "settings not loaded") local savedCtx, savedHistory, savedRaid = db.buffContext, db.history, env.IsInRaid @@ -8113,7 +8642,6 @@ local text = X.HistoryText() db.history = savedHistory assert(type(text) == "string" and text:find("Splitcheck", 1, true), "Wizard.lua does not read the live settings table") - assert(X.coordAPI.nEntries() == X.wizAPI.nEntries(), "list-length accessors disagree") end) step("row hover highlight is a faint theme-coloured wash", function() local X, db = NS.X, NS.X.GetDB() @@ -8124,10 +8652,9 @@ assert(hl.file == "Interface\\Buttons\\WHITE8X8" and hl.blend == "ADD", "hover highlight is not the flat wash") local function matches() local bc, c = X.ThemeBorder(), hl.vcolor - return c and c[1] == bc[1] and c[2] == bc[2] and c[3] == bc[3] and c[4] == X.ROW_HOVER_ALPHA + return c and c[1] == bc[1] and c[2] == bc[2] and c[3] == bc[3] and c[4] == 0.15 end assert(matches(), "hover highlight does not use the theme border colour") - assert(X.ROW_HOVER_ALPHA > 0 and X.ROW_HOVER_ALPHA <= 0.2, "hover highlight is not subtle") local saved = db.theme db.theme = (saved == "crimson") and "forest" or "crimson" X.ApplyAppearance() @@ -8136,15 +8663,16 @@ X.ApplyAppearance() assert(followed, "hover highlight did not follow a theme change") end) -step("Window.lua hands the window back to the main file (Slice G)", function() +step("window creation is idempotent and keeps bindings on the same frames", function() local X = NS.X + local count = #env.__frames X.BuildUI() - local st = X.slashAPI.getState() - assert(st.built == true, "main file does not see the window as built") - assert(st.frame and st.frame == env.BuffRadarFrame and X.GetFrame() == st.frame, "main file did not receive the window frame") - assert(st.grip, "main file did not receive the resize grip") - local wrapped, driver = X.NextBindState() - assert(st.nextWrapped == wrapped and st.nextCombatDriver == driver, "next-button state differs between files") + assert(X.WindowReady() and #env.__frames == count, "second window build created more frames") + assert(X.GetFrame() == env.BuffRadarFrame, "window accessor returned the wrong frame") + local nextButton = env.BuffRadarNextButton + assert(X.GetNextButton() == nextButton, "next-cast accessor returned the wrong frame") + local _, installed = X.NextBindState() + assert(installed == nextButton.combatDriver, "next-button driver state differs from diagnostics") end) step("right-click a row (ignore path)", function() local row = env.BuffRadarRow1 @@ -8155,40 +8683,36 @@ return results, chat end""") -import os -src = open(addon_path, encoding="utf-8").read() -de_path = os.path.join(os.path.dirname(os.path.abspath(addon_path)), "Locales", "deDE.lua") -de_src = open(de_path, encoding="utf-8").read() if os.path.exists(de_path) else None -ex_path = os.path.join(os.path.dirname(os.path.abspath(addon_path)), "Extras.lua") -ex_src = open(ex_path, encoding="utf-8").read() if os.path.exists(ex_path) else None -da_path = os.path.join(os.path.dirname(os.path.abspath(addon_path)), "Data.lua") -da_src = open(da_path, encoding="utf-8").read() if os.path.exists(da_path) else None -cf_path = os.path.join(os.path.dirname(os.path.abspath(addon_path)), "Config.lua") -cf_src = open(cf_path, encoding="utf-8").read() if os.path.exists(cf_path) else None -sl_path = os.path.join(os.path.dirname(os.path.abspath(addon_path)), "Slash.lua") -rc_path = os.path.join(os.path.dirname(os.path.abspath(addon_path)), "Recaps.lua") -rc_src = open(rc_path, encoding="utf-8").read() if os.path.exists(rc_path) else None -pf_path = os.path.join(os.path.dirname(os.path.abspath(addon_path)), "Profiles.lua") -pf_src = open(pf_path, encoding="utf-8").read() if os.path.exists(pf_path) else None -co_path = os.path.join(os.path.dirname(os.path.abspath(addon_path)), "Coordination.lua") -co_src = open(co_path, encoding="utf-8").read() if os.path.exists(co_path) else None -wz_path = os.path.join(os.path.dirname(os.path.abspath(addon_path)), "Wizard.lua") -wz_src = open(wz_path, encoding="utf-8").read() if os.path.exists(wz_path) else None -wn_path = os.path.join(os.path.dirname(os.path.abspath(addon_path)), "Window.lua") -wn_src = open(wn_path, encoding="utf-8").read() if os.path.exists(wn_path) else None -sl_src = open(sl_path, encoding="utf-8").read() if os.path.exists(sl_path) else None +addon = Path(addon_path).resolve() +root = addon.parent + + +def read_sources(toc): + paths = [line.strip().replace("\\", "/") for line in toc.read_text(encoding="utf-8-sig").splitlines() + if line.strip() and not line.lstrip().startswith("#") and line.strip().lower().endswith(".lua")] + if len(paths) != len(set(paths)) or addon.name not in paths: + sys.exit(f"Duplicate entries or missing core file in {toc}") + return [(path, (root / path).read_text(encoding="utf-8-sig")) for path in paths] + + +retail_sources = read_sources(root / "BuffRadar.toc") +forever_sources = read_sources(root.parent / "editions" / "forever" / "BuffRadar.toc") +# Keep the older Retail+Extras coverage for optional-API paths (especially +# diagnostics with unreadable values), in addition to the real Retail TOC. +retail_extras = retail_sources + [file for file in forever_sources if file[0] == "Extras.lua"] setups = [ - ("Retail: modern client (C_Timer, UI templates)", True, False, False, False), - ("Retail: fallback timer (OnUpdate)", False, False, False, False), - ("Retail: no UI templates (fallback settings look)", True, True, False, False), - ("Forever: modern client", True, False, True, False), - ("Forever: fallback timer, no UI templates", False, True, True, False), + ("Retail: declared TOC (no Extras)", True, False, False, False, retail_sources), + ("Retail + Extras: modern client (C_Timer, UI templates)", True, False, False, False, retail_extras), + ("Retail + Extras: fallback timer (OnUpdate)", False, False, False, False, retail_extras), + ("Retail + Extras: no UI templates", True, True, False, False, retail_extras), + ("Forever: modern client", True, False, True, False, forever_sources), + ("Forever: fallback timer, no UI templates", False, True, True, False, forever_sources), + ("Retail + Extras: German client (Locales/deDE.lua)", True, False, False, True, retail_extras), ] -if de_src: - setups.append(("Retail: German client (Locales/deDE.lua)", True, False, False, True)) failed = False -for label, with_timer, no_templates, forever, german in setups: - results, chat = harness(src, with_timer, no_templates, forever, german, de_src if german else None, ex_src, da_src, cf_src, sl_src, rc_src, pf_src, co_src, wz_src, wn_src) +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) bad = 0 for i in range(1, len(results) + 1): name, status = results[i][1], results[i][2] diff --git a/tools/wowstub.lua b/tools/wowstub.lua index 530ba1c..70928db 100644 --- a/tools/wowstub.lua +++ b/tools/wowstub.lua @@ -10,7 +10,7 @@ function WOWSTUB(chat, withTimer, noTemplates, forever, german) -- frames lack the template's members and the addon's fallback UI is used. local templateOnly = { SetTitle = true, Inset = true, CloseButton = true, SetPortraitToAsset = true } if withTimer then -- modern client: C_Timer; callbacks queue until the test runs them - env.__timers = {} + env.__timers, env.__ticker = {}, false env.C_Timer = { After = function(_, f) env.__timers[#env.__timers + 1] = f end, NewTicker = function(_, f) env.__ticker = f; return {} end, @@ -19,7 +19,7 @@ function WOWSTUB(chat, withTimer, noTemplates, forever, german) local noop = function() end local function newObject(kind, name) - local o = { kind = kind, name = name, scripts = {}, attrs = {}, shown = true, text = "" } + local o = { kind = kind, frameName = name, scripts = {}, attrs = {}, shown = true, text = "" } local methods = {} function methods.SetScript(self, ev, fn) self.scripts[ev] = fn end function methods.GetScript(self, ev) return self.scripts[ev] end @@ -36,6 +36,7 @@ function WOWSTUB(chat, withTimer, noTemplates, forever, german) function methods.IsVisible(self) return self.shown and (not self.parent or self.parent:IsVisible()) end function methods.SetAttribute(self, k, v) self.attrs[k] = v end function methods.GetAttribute(self, k) return self.attrs[k] end + function methods.RegisterForClicks(self, ...) self.clickRegistration = { ... } end function methods.SetText(self, t) self.text = t end function methods.GetText(self) return self.text end function methods.SetAlpha(self, a) self.alpha = a end @@ -76,7 +77,7 @@ function WOWSTUB(chat, withTimer, noTemplates, forever, german) env.__editFocus = self if self.scripts.OnEditFocusGained then self.scripts.OnEditFocusGained(self) end end - function methods.GetName(self) return self.name end + function methods.GetName(self) return self.frameName end function methods.SetID(self, id) self.id = id end function methods.GetID(self) return self.id or 0 end function methods.CreateTexture() return newObject("Texture") end @@ -173,7 +174,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, 0, 0, 0, a.expirationTime end + if a then return a.name, "", 0, nil, 0, a.expirationTime, a.sourceUnit end return nil end env.GetBuildInfo = function() return "12.1.5", "99999", "Oct 2026", 120105 end @@ -239,11 +240,31 @@ function WOWSTUB(chat, withTimer, noTemplates, forever, german) env.PlaySoundFile = noop env.GetBindingKey = function() return nil end env.GetBindingText = function(k) return k end - env.GetMacroIndexByName = function() return 0 end - env.GetNumMacros = function() return 3, 0 end - env.CreateMacro = function() return 4 end - env.EditMacro = noop - env.PickupMacro = noop + local macros = {} + env.__macros, env.__macroWrites = macros, 0 + env.GetMacroIndexByName = function(name) + for i, macro in pairs(macros) do if macro.name == name then return i end end + return 0 + end + env.GetMacroBody = function(i) return macros[i] and macros[i].body end + env.GetNumMacros = function() return #macros, 0 end + env.CreateMacro = function(name, icon, body) + assert(not env.__combat, "macro created during combat") + assert(#body <= 255, "macro body exceeds 255 bytes") + macros[#macros + 1] = { name = name, icon = icon, body = body } + env.__macroWrites = env.__macroWrites + 1 + return #macros + end + env.EditMacro = function(i, name, icon, body) + assert(not env.__combat, "macro edited during combat") + assert(#body <= 255, "macro body exceeds 255 bytes") + local macro = assert(macros[i], "missing macro") + macro.name, macro.icon, macro.body = name or macro.name, icon or macro.icon, body + env.__macroWrites = env.__macroWrites + 1 + return i + end + env.GetRunningMacro = function() return env.__runningMacro end + env.PickupMacro = function(i) env.__pickedMacro = i end env.GetCursorPosition = function() return 0, 0 end env.SetPortraitTexture = noop env.RegisterStateDriver = noop @@ -264,6 +285,7 @@ function WOWSTUB(chat, withTimer, noTemplates, forever, german) } env.SettingsPanel = newObject("Frame", "SettingsPanel") env.HideUIPanel = function(f) f:Hide() end + env.__compartment = false env.AddonCompartmentFrame = { RegisterAddon = function(_, info) env.__compartment = info end } -- Forever client: interface 16001, a level-60 priest with ranked spells. if forever then