From f19f13d44c098e4cd9caa2cae95c14ecbacf0486 Mon Sep 17 00:00:00 2001 From: Brues <5278969+brues-code@users.noreply.github.com> Date: Sat, 31 Oct 2026 23:16:01 -0500 Subject: [PATCH] feat(debugtools): fold pfDebug in as /profiler pfDebug was a separate addon that profiled through ClassicAPI's own APIs: GetAddOnMemoryUsage and GetAddOnCPUUsage, GetFrameCPUUsage, GetFunctionCPUUsage, GetEventCPUUsage, and the intrinsic precall and postcall script hooks. Its code now lives in ClassicAPI_DebugTools under Profiler/, with its MIT notice (Copyright (c) 2018 Shagu). The analyzer tabs (Addons, Frames, Events, Globals) and the widget are pfDebug's, with the frame and template names renamed to ClassicAPIProfiler*. /profiler and /prof load DebugTools on demand through the same stub as /dump, then toggle the analyzer. The subcommands widget, reset and profile on|off are pfDebug's. What changed in the move: - The sampler starts only when the widget or the analyzer first opens, so a load for /dump costs nothing. It first takes every counter as it is, so the first CPU/s and KB/s cover one second, not the session. - Whether profiling runs is probed, not read from the cvar: a function is called once and GetFunctionCPUUsage must count that call. The scriptProfile cvar can already hold the next session's value. - A frame record starts at the frame's current CPU time and call count, and opening the analyzer takes every frame and event counter again, because the frame totals and the deep hooks keep counting while it is closed. pfDebug started records at 0, so the first scan and each reopen showed a frame's whole session as one second. - The /fstack lines (owner, OnUpdate and OnEvent owner and CPU, all scripts, deep allocations) are added at the end of FrameStackTooltip_OnTooltipSetFrameStack, not by hooking OnTooltipSetFrameStack. - No pfUI skin and no SavedVariables. The plain backdrop is pfDebug's own fallback. The widget no longer opens at login, because that would load DebugTools at login. README's Debug tools table gains /profiler and the new /fstack lines. --- README.md | 3 +- .../Util/SlashCommandsRegistry.lua | 8 + .../ClassicAPI_DebugTools.toc | 10 + .../ClassicAPI_DebugTools/DebugTools.lua | 7 +- .../Profiler/AddonsTab.lua | 105 +++++ .../ClassicAPI_DebugTools/Profiler/Core.lua | 283 +++++++++++++ .../Profiler/EventsTab.lua | 124 ++++++ .../Profiler/FrameStack.lua | 39 ++ .../Profiler/FramesTab.lua | 166 ++++++++ .../Profiler/GlobalsTab.lua | 177 ++++++++ .../Profiler/Profiler.xml | 58 +++ .../ClassicAPI_DebugTools/Profiler/Track.lua | 212 ++++++++++ .../ClassicAPI_DebugTools/Profiler/Widget.lua | 180 ++++++++ .../ClassicAPI_DebugTools/Profiler/Window.lua | 392 ++++++++++++++++++ 14 files changed, 1762 insertions(+), 2 deletions(-) create mode 100644 src/embed/AddOns/ClassicAPI_DebugTools/Profiler/AddonsTab.lua create mode 100644 src/embed/AddOns/ClassicAPI_DebugTools/Profiler/Core.lua create mode 100644 src/embed/AddOns/ClassicAPI_DebugTools/Profiler/EventsTab.lua create mode 100644 src/embed/AddOns/ClassicAPI_DebugTools/Profiler/FrameStack.lua create mode 100644 src/embed/AddOns/ClassicAPI_DebugTools/Profiler/FramesTab.lua create mode 100644 src/embed/AddOns/ClassicAPI_DebugTools/Profiler/GlobalsTab.lua create mode 100644 src/embed/AddOns/ClassicAPI_DebugTools/Profiler/Profiler.xml create mode 100644 src/embed/AddOns/ClassicAPI_DebugTools/Profiler/Track.lua create mode 100644 src/embed/AddOns/ClassicAPI_DebugTools/Profiler/Widget.lua create mode 100644 src/embed/AddOns/ClassicAPI_DebugTools/Profiler/Window.lua diff --git a/README.md b/README.md index f3ed4203..a50ad2a7 100644 --- a/README.md +++ b/README.md @@ -498,9 +498,10 @@ that you use one of these commands: |---------|---------| | `/dump ` | Shows a Lua value in the chat frame. It shows tables and all return values. Use it to examine the return values of `GetSpellInfo`, `C_Item.GetItemInfoInstant`, and other functions. | | `/etrace` | Opens the event trace window. Other forms: `/etrace start`, `/etrace stop`, `/etrace add EVENT`, and more. | -| `/framestack [showHidden [showRegions]]` (or `/fstack`) | Shows a tooltip with a list of the frames under the cursor. A `-->` mark shows one frame, with its anchors and the file and line that made it. Left Alt and Right Alt move the mark. Ctrl opens the marked frame in the table inspector. Shift shows its texture files. | +| `/framestack [showHidden [showRegions]]` (or `/fstack`) | Shows a tooltip with a list of the frames under the cursor. A `-->` mark shows one frame, with its anchors and the file and line that made it. Left Alt and Right Alt move the mark. Ctrl opens the marked frame in the table inspector. Shift shows its texture files. The tooltip also shows the addon that made the marked frame. When `scriptProfile` is `1`, it shows the CPU time of the frame scripts. | | `/tinspect [expr]` (or `/tins`) | Opens a table inspector on the result of `expr`. With no table, it opens on the frame under the cursor. The window shows the anchors and the fields of the table, grouped by type. You can edit numbers, strings and booleans, filter the lines, and open a child table or frame. | | `/luaerrors` (or `/scripterrors`) | Opens the Lua error window. | +| `/profiler` (or `/prof`) | Opens the profiler. The profiler shows the Lua memory, the allocations and the CPU time of each addon, frame, event and global function. `/profiler widget` shows a small window with the Lua memory, the frame rate and the addons that use the most. `/profiler reset` sets the counters to zero. CPU times need `scriptProfile` `1`. `/profiler profile on` sets it and reloads the UI. | ## Building diff --git a/src/embed/AddOns/!!!ClassicAPI/Util/SlashCommandsRegistry.lua b/src/embed/AddOns/!!!ClassicAPI/Util/SlashCommandsRegistry.lua index 5da13af2..541573a8 100644 --- a/src/embed/AddOns/!!!ClassicAPI/Util/SlashCommandsRegistry.lua +++ b/src/embed/AddOns/!!!ClassicAPI/Util/SlashCommandsRegistry.lua @@ -1064,6 +1064,14 @@ end SLASH_LUAERRORS1 = "/luaerrors"; SLASH_LUAERRORS2 = "/scripterrors"; +SlashCmdList["PROFILER"] = function(msg) + if ( LoadDebugTools() ) then + ClassicAPIProfiler_HandleSlashCmd(msg); + end +end +SLASH_PROFILER1 = "/profiler"; +SLASH_PROFILER2 = "/prof"; + -- --------------------------------------------------------------------- -- Give a contested command back to whoever already owned it -- diff --git a/src/embed/AddOns/ClassicAPI_DebugTools/ClassicAPI_DebugTools.toc b/src/embed/AddOns/ClassicAPI_DebugTools/ClassicAPI_DebugTools.toc index 091bfb3b..77bb4cbc 100644 --- a/src/embed/AddOns/ClassicAPI_DebugTools/ClassicAPI_DebugTools.toc +++ b/src/embed/AddOns/ClassicAPI_DebugTools/ClassicAPI_DebugTools.toc @@ -13,3 +13,13 @@ TableInspectorDataProvider.lua TableInspectorAnchorDataProvider.xml TableInspectorAttributeDataProvider.xml TableInspector.xml +Profiler\Profiler.xml +Profiler\Core.lua +Profiler\Track.lua +Profiler\Widget.lua +Profiler\Window.lua +Profiler\AddonsTab.lua +Profiler\FramesTab.lua +Profiler\EventsTab.lua +Profiler\GlobalsTab.lua +Profiler\FrameStack.lua diff --git a/src/embed/AddOns/ClassicAPI_DebugTools/DebugTools.lua b/src/embed/AddOns/ClassicAPI_DebugTools/DebugTools.lua index aaf520d0..6577e7f3 100644 --- a/src/embed/AddOns/ClassicAPI_DebugTools/DebugTools.lua +++ b/src/embed/AddOns/ClassicAPI_DebugTools/DebugTools.lua @@ -26,9 +26,12 @@ -- the time column without re-anchoring frames. -- -- The table inspector (/tinspect, Ctrl in /fstack) is retail's --- Blizzard_TableInspector; see TableInspector.lua. +-- Blizzard_TableInspector; see TableInspector.lua. The profiler (/profiler) +-- is in Profiler/, and adds its owner and CPU lines to /fstack. ------------------------------------------------------------------------------ +local _, ns = ...; + EVENT_TRACE_EVENT_HEIGHT = 16; EVENT_TRACE_MAX_ENTRIES = 1000; -- Toolbar above the event list (Pause + Args/Time toggles + Search) eats @@ -1184,6 +1187,8 @@ function FrameStackTooltip_OnTooltipSetFrameStack(self, highlightFrame) if (fsobj) then self:AddLine(string.format("\nfsobj = %s", fsobj:GetDebugName())); end + + ns.AddFrameStackLines(self, self.highlightFrame); end function FrameStackTooltip_Show(self, showHidden, showRegions) diff --git a/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/AddonsTab.lua b/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/AddonsTab.lua new file mode 100644 index 00000000..44a3323d --- /dev/null +++ b/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/AddonsTab.lua @@ -0,0 +1,105 @@ +-- Addons tab: the memory, allocation rate and CPU time of each addon. +local _, ns = ... + +local stats = ns.stats + +local function Profiled(fn) + return function(addon) + if ns.profiling then return fn(addon) end + end +end + +local tab = ns.AddTab("Addons") + +tab.list = ns.CreateList(tab.frame, { + sort = 3, + columns = { + { + title = "Addon", + text = function(addon) return addon.title end, + value = function(addon) return strlower(addon.name) end, + }, + { + title = "Memory", width = 70, + tip = "The Lua memory that the addon's objects use now.", + text = function(addon) return ns.KB(addon.mem) end, + value = function(addon) return addon.mem end, + }, + { + title = "Alloc/s", width = 76, + tip = "The Lua memory the addon allocated in the last second. Allocations become garbage that the collector must free. A second with a garbage collection keeps the previous value.", + text = function(addon) return ns.KBRate(addon.memRate) end, + value = function(addon) return addon.memRate end, + }, + { + title = "Peak/s", width = 76, + tip = "The highest Alloc/s since the last reset.", + text = function(addon) return ns.KBRate(addon.peakRate) end, + value = function(addon) return addon.peakRate end, + }, + { + title = "CPU/s", width = 64, + tip = "The CPU time of the addon's own functions in the last second. Needs CPU profiling.", + text = Profiled(function(addon) return ns.MS(addon.cpuRate) end), + value = Profiled(function(addon) return addon.cpuRate end), + }, + { + title = "CPU %", width = 50, + tip = "The addon's share of the CPU time of all addons in the last second.", + text = Profiled(function(addon) return addon.cpuShare and format("%.1f%%", addon.cpuShare) end), + value = Profiled(function(addon) return addon.cpuShare end), + }, + { + title = "CPU Total", width = 70, + tip = "The CPU time of the addon's own functions since the last reset.", + text = Profiled(function(addon) return ns.MS(addon.cpu) end), + value = Profiled(function(addon) return addon.cpu end), + }, + }, + + tooltip = function(addon) + GameTooltip:AddLine(addon.title) + GameTooltip:AddLine(addon.name, .6, .6, .6) + GameTooltip:AddLine(" ") + GameTooltip:AddDoubleLine("Memory", ns.KB(addon.mem), 1, 1, 1, 1, 1, 1) + GameTooltip:AddDoubleLine("Allocated per second", ns.KBRate(addon.memRate), 1, 1, 1, 1, 1, 1) + GameTooltip:AddDoubleLine("Peak per second", ns.KBRate(addon.peakRate), 1, 1, 1, 1, 1, 1) + if ns.profiling then + GameTooltip:AddDoubleLine("CPU per second", ns.MS(addon.cpuRate), 1, 1, 1, 1, 1, 1) + GameTooltip:AddDoubleLine("CPU since reset", ns.MS(addon.cpu), 1, 1, 1, 1, 1, 1) + else + GameTooltip:AddLine("Turn on CPU profiling to see CPU times.", .6, .6, .6) + end + GameTooltip:AddLine(" ") + GameTooltip:AddLine("Click: show its frames. Right-click: more.", .6, .6, .6) + end, + + click = function(addon) + ns.ShowIn("Frames", addon.name) + end, + + menu = function(addon, root) + root:CreateTitle(addon.name) + root:CreateButton("Show frames", function() ns.ShowIn("Frames", addon.name) end) + root:CreateButton("Show globals", function() ns.ShowIn("Globals", addon.name) end) + root:CreateButton("Copy name", function() ns.Copy(addon.name) end) + end, +}) +tab.list:SetAllPoints() + +function tab:OnSelect() + self.list:SetEntries(stats.list) +end + +function tab:OnSample() + self.list:SetEntries(stats.list) +end + +function tab:Status() + local text = format("%d addons Lua %s / %s", #stats.list, ns.KB(stats.mem or 0), ns.KB(stats.threshold or 0)) + if ns.profiling and stats.scriptRate then + text = text .. format(" scripts %s/s events %s/s (%.0f fired/s)", + ns.MS(stats.scriptRate), ns.MS(stats.eventRate), stats.eventCountRate) + end + return text +end diff --git a/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/Core.lua b/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/Core.lua new file mode 100644 index 00000000..13bd75e9 --- /dev/null +++ b/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/Core.lua @@ -0,0 +1,283 @@ +-- Profiler core: shared helpers, the once-a-second sampler and the per-addon +-- memory and CPU statistics every other profiler file reads. +-- +-- Based on pfDebug (https://github.com/shagu/pfDebug): +-- +-- MIT License +-- +-- Copyright (c) 2018 Shagu +-- +-- Permission is hereby granted, free of charge, to any person obtaining a copy +-- of this software and associated documentation files (the "Software"), to deal +-- in the Software without restriction, including without limitation the rights +-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +-- copies of the Software, and to permit persons to whom the Software is +-- furnished to do so, subject to the following conditions: +-- +-- The above copyright notice and this permission notice shall be included in all +-- copies or substantial portions of the Software. +-- +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +-- SOFTWARE. +local _, ns = ... + +ns.INTERVAL = 1 -- seconds between samples + +-- whether CPU profiling runs in this session. scriptProfile takes effect at +-- a reload and these tools load on demand, so the cvar can already hold the +-- next session's value: ask the profiler whether it counted a call instead. +local function Probe() end +Probe() +ns.profiling = select(2, GetFunctionCPUUsage(Probe)) > 0 + +-- [[ styling ]] +function ns.CreateBackdrop(frame) + frame:SetBackdrop({ + bgFile = "Interface\\BUTTONS\\WHITE8X8", tile = false, tileSize = 0, + edgeFile = "Interface\\BUTTONS\\WHITE8X8", edgeSize = 1, + insets = {left = -1, right = -1, top = -1, bottom = -1}, + }) + frame:SetBackdropColor(0, 0, 0, .75) + frame:SetBackdropBorderColor(.1, .1, .1, 1) +end + +-- [[ formatting ]] +ns.ACCENT = "|cff33ffcc" +ns.GOLD = "|cffffcc00" +ns.GREY = "|cffaaaaaa" +ns.WHITE = "|cffffffff" +ns.RED = "|cffff5555" + +function ns.Print(msg) + DEFAULT_CHAT_FRAME:AddMessage(ns.ACCENT .. "Profiler|r: " .. msg) +end + +function ns.KB(kb) + if math.abs(kb) >= 1024 then return format("%.1f MB", kb / 1024) end + return format("%.0f KB", kb) +end + +function ns.KBRate(kbps) + if not kbps then return "-" end + if math.abs(kbps) >= 1024 then return format("%.2f MB/s", kbps / 1024) end + return format("%.1f KB/s", kbps) +end + +function ns.MS(ms) + if not ms then return "-" end + if ms >= 10000 then return format("%.1f s", ms / 1000) end + if ms >= 100 then return format("%.0f ms", ms) end + if ms >= 1 then return format("%.1f ms", ms) end + return format("%.3f ms", ms) +end + +function ns.Count(n) + if not n then return "-" end + return BreakUpLargeNumbers(floor(n + .5)) +end + +-- [[ ownership: which addon made a table, function or frame ]] +-- nil for objects the game's own code made (FrameXML or the engine), "script" +-- for objects a macro or /run made. +function ns.Owner(value) + local tag = _classicapi_GcTagOf(value) + if tag and strsub(tag, 1, 2) == "0x" then return "script" end + return tag +end + +function ns.OwnerLabel(owner) + return owner or "FrameXML" +end + +-- a frame's name as the debug tools show it +function ns.FrameName(frame) + local name = frame:GetDebugName() + if name == "" then return "<" .. frame:GetObjectType() .. ">" end + return name +end + +-- [[ events of this module: sample and reset listeners ]] +local sampleListeners, resetListeners = {}, {} + +function ns.OnSample(fn) tinsert(sampleListeners, fn) end +function ns.OnReset(fn) tinsert(resetListeners, fn) end + +-- [[ per-addon statistics ]] +-- addon rates are deltas between two samples. A garbage collection between +-- the samples frees memory of every addon, so a window with a collection +-- holds the previous allocation rate. +local stats = { + addons = {}, -- [name] = record + list = {}, -- loaded addon records, in load order +} +ns.stats = stats + +local gc = { count = 0 } +ns.gc = gc + +local collected = false +local lastMem, lastThreshold = gcinfo() + +local function NewAddon(index, name, title) + local addon = { index = index, name = name, title = title, mem = 0, cpu = 0, peakRate = 0 } + addon.search = strlower(name .. " " .. title) + stats.addons[name] = addon + tinsert(stats.list, addon) + return addon +end + +-- a cumulative counter's growth since `last`, where a drop means a reset +local function Delta(now, last) + if not last or now < last then return now end + return now - last +end +ns.Delta = Delta + +local lastScript, lastEventTime, lastEventCount + +local function Sample(dt) + local mem, threshold = gcinfo() + stats.collected = collected + stats.memRate = not collected and stats.mem and (mem - stats.mem) / dt or nil + stats.mem, stats.threshold = mem, threshold + collected = false + + UpdateAddOnMemoryUsage() + if ns.profiling then UpdateAddOnCPUUsage() end + + local cpuSum, topMem, topCpu = 0, nil, nil + for i = 1, GetNumAddOns() do + if IsAddOnLoaded(i) then + local name, title = GetAddOnInfo(i) + local addon = stats.addons[name] or NewAddon(i, name, title) + + local addonMem = GetAddOnMemoryUsage(i) + if not stats.collected and addon.sampled then + addon.memRate = (addonMem - addon.mem) / dt + addon.peakRate = max(addon.peakRate, addon.memRate) + end + addon.mem, addon.sampled = addonMem, true + + if ns.profiling then + local cpu = GetAddOnCPUUsage(i) + addon.cpuRate = Delta(cpu, addon.cpu) / dt + addon.cpu = cpu + cpuSum = cpuSum + addon.cpuRate + if not topCpu or addon.cpuRate > topCpu.cpuRate then topCpu = addon end + end + + if addon.memRate and (not topMem or addon.memRate > topMem.memRate) then topMem = addon end + end + end + + for _, addon in ipairs(stats.list) do + addon.cpuShare = cpuSum > 0 and addon.cpuRate and addon.cpuRate / cpuSum * 100 or nil + end + stats.cpuSum, stats.topMem, stats.topCpu = cpuSum, topMem, topCpu + + if ns.profiling then + local script = GetScriptCPUUsage() + local eventTime, eventCount = GetEventCPUUsage() + stats.scriptRate = Delta(script, lastScript) / dt + stats.eventRate = Delta(eventTime, lastEventTime) / dt + stats.eventCountRate = Delta(eventCount, lastEventCount) / dt + lastScript, lastEventTime, lastEventCount = script, eventTime, eventCount + end + + for _, fn in ipairs(sampleListeners) do fn(dt) end +end + +-- the counters as they are now, so the first sample's rates cover only its +-- own second, not the time since the UI loaded +local function Baseline() + stats.mem, stats.threshold = gcinfo() + lastMem, lastThreshold = stats.mem, stats.threshold + + UpdateAddOnMemoryUsage() + if ns.profiling then UpdateAddOnCPUUsage() end + for i = 1, GetNumAddOns() do + if IsAddOnLoaded(i) then + local name, title = GetAddOnInfo(i) + local addon = stats.addons[name] or NewAddon(i, name, title) + addon.mem, addon.sampled = GetAddOnMemoryUsage(i), true + if ns.profiling then addon.cpu = GetAddOnCPUUsage(i) end + end + end + + if ns.profiling then + lastScript = GetScriptCPUUsage() + lastEventTime, lastEventCount = GetEventCPUUsage() + end +end + +function ns.Reset() + ResetCPUUsage() + lastScript, lastEventTime, lastEventCount = nil, nil, nil + for _, addon in ipairs(stats.list) do + addon.cpu, addon.peakRate = 0, 0 + end + for _, fn in ipairs(resetListeners) do fn() end +end + +-- [[ the sampler: every frame, from the first open of the widget or the +-- analyzer until /reload ]] +-- The debug tools also load for /dump and the rest, so the profiler costs +-- nothing until it is opened. +local sampler = CreateFrame("Frame") +sampler:Hide() +local elapsedSinceSample = 0 + +-- spot garbage collections: Lua 5.0 sets a new threshold after each +-- collection, so a changed threshold means a collection ran +sampler:SetScript("OnUpdate", function(self, elapsed) + local mem, threshold = gcinfo() + if threshold ~= lastThreshold then + collected = true + gc.count = gc.count + 1 + gc.time, gc.clock, gc.freed = GetTime(), date("%H:%M:%S"), lastMem - mem + end + lastMem, lastThreshold = mem, threshold + + elapsedSinceSample = elapsedSinceSample + elapsed + if elapsedSinceSample >= ns.INTERVAL then + Sample(elapsedSinceSample) + elapsedSinceSample = 0 + end +end) + +function ns.StartSampling() + if sampler:IsShown() then return end + Baseline() + sampler:Show() +end + +-- [[ CPU profiling switch: the cvar takes effect after a reload ]] +function ns.SetProfiling(enable) + SetCVar("scriptProfile", enable and "1" or "0") + ReloadUI() +end + +-- [[ /profiler ]] +function ClassicAPIProfiler_HandleSlashCmd(msg) + local cmd, arg = strmatch(strlower(msg or ""), "^(%S*)%s*(.-)$") + if cmd == "" then + ns.window:SetShown(not ns.window:IsShown()) + elseif cmd == "widget" then + ns.widget:SetShown(not ns.widget:IsShown()) + elseif cmd == "reset" then + ns.Reset() + ns.Print("CPU and allocation counters reset.") + elseif cmd == "profile" and (arg == "on" or arg == "off") then + ns.SetProfiling(arg == "on") + else + ns.Print("/profiler - toggle the analyzer") + ns.Print("/profiler widget - toggle the memory widget") + ns.Print("/profiler reset - reset CPU and allocation counters") + ns.Print("/profiler profile on|off - CPU profiling (reloads the UI)") + end +end diff --git a/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/EventsTab.lua b/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/EventsTab.lua new file mode 100644 index 00000000..166c621e --- /dev/null +++ b/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/EventsTab.lua @@ -0,0 +1,124 @@ +-- Events tab: how often each event fires while the analyzer is open, how +-- many frames listen to it, and (deep tracking) what its handlers cost. +local _, ns = ... + +local track = ns.track + +local function Tracked(fn) + return function(ev) + if track.deep then return fn(ev) end + end +end + +local function Line(left, right) + GameTooltip:AddDoubleLine(left, right, 1, 1, 1, 1, 1, 1) +end + +local function Tooltip(ev) + GameTooltip:AddLine(ev.name) + Line("Fired", ns.Count(ev.fires) .. ns.GREY .. " (" .. format("%.1f", ev.fireRate or 0) .. "/s)") + if track.deep then + Line("Handlers ran", ns.Count(ev.dispatches)) + if ns.profiling then Line("Handler CPU", ns.MS(ev.cpu)) end + Line("Allocated", ns.KB(ev.alloc)) + end + + local listeners = {} + for _, frame in ipairs({ GetFramesRegisteredForEvent(ev.name) }) do + if frame ~= track.capture then + local rec = track.frames[frame] + tinsert(listeners, { frame = frame, stat = rec and rec.events[ev.name] }) + end + end + if #listeners == 0 then return end + + table.sort(listeners, function(a, b) + local ca, cb = a.stat and a.stat.cpu or -1, b.stat and b.stat.cpu or -1 + return ca > cb + end) + + GameTooltip:AddLine(" ") + GameTooltip:AddLine("Listeners", 1, .8, 0) + for i = 1, min(#listeners, 15) do + local frame, stat = listeners[i].frame, listeners[i].stat + local text = ns.GREY .. ns.OwnerLabel(ns.Owner(frame:GetScript("OnEvent") or frame)) + if stat then + if ns.profiling then text = text .. " " .. ns.WHITE .. ns.MS(stat.cpu) end + text = text .. " " .. ns.WHITE .. ns.KB(stat.alloc) + end + Line(ns.FrameName(frame), text) + end + if #listeners > 15 then + GameTooltip:AddLine("and " .. (#listeners - 15) .. " more", .6, .6, .6) + end +end + +local tab = ns.AddTab("Events") + +tab.list = ns.CreateList(tab.frame, { + sort = 2, + columns = { + { + title = "Event", + text = function(ev) return ev.name end, + value = function(ev) return ev.search end, + }, + { + title = "Fires/s", width = 60, + tip = "How often the event fired in the last second.", + text = function(ev) return ev.fireRate and format("%.1f", ev.fireRate) end, + value = function(ev) return ev.fireRate end, + }, + { + title = "Listeners", width = 60, + tip = "The frames registered for the event.", + text = function(ev) return ev.listeners end, + value = function(ev) return ev.listeners end, + }, + { + title = "CPU/s", width = 64, + tip = "The CPU time of the event's OnEvent handlers in the last second. Needs deep tracking and CPU profiling.", + text = Tracked(function(ev) return ns.profiling and ns.MS(ev.cpuRate) end), + value = Tracked(function(ev) return ns.profiling and ev.cpuRate or nil end), + }, + { + title = "Alloc/s", width = 72, + tip = "The Lua memory the event's OnEvent handlers allocated in the last second. Needs deep tracking.", + text = Tracked(function(ev) return ns.KBRate(ev.allocRate) end), + value = Tracked(function(ev) return ev.allocRate end), + }, + { + title = "Fired", width = 64, + tip = "How often the event fired since the analyzer opened or the last reset.", + text = function(ev) return ns.Count(ev.fires) end, + value = function(ev) return ev.fires end, + }, + }, + + tooltip = Tooltip, + + menu = function(ev, root) + root:CreateTitle(ev.name) + root:CreateButton("Copy name", function() ns.Copy(ev.name) end) + end, +}) +tab.list:SetAllPoints() + +local function Update(self) + local entries = {} + for _, ev in pairs(track.events) do tinsert(entries, ev) end + self.list:SetEntries(entries) +end + +tab.OnSelect = Update +tab.OnSample = Update + +function tab:Status() + local fires = 0 + for _, ev in pairs(track.events) do fires = fires + (ev.fireRate or 0) end + local text = format("%d events seen %.0f fired/s", #self.list.entries, fires) + if not track.deep then + return text .. " " .. ns.GOLD .. "Turn on deep tracking for the CPU time and memory of each event." + end + return text +end diff --git a/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/FrameStack.lua b/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/FrameStack.lua new file mode 100644 index 00000000..bf087c73 --- /dev/null +++ b/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/FrameStack.lua @@ -0,0 +1,39 @@ +-- /fstack: the owner, script CPU time and allocations of the highlighted +-- frame, which FrameStackTooltip_OnTooltipSetFrameStack adds to the tooltip. +local _, ns = ... + +local function Line(tooltip, left, right) + tooltip:AddDoubleLine(left, right, .2, 1, .8, 1, 1, 1) +end + +function ns.AddFrameStackLines(tooltip, region) + if not region then return end + -- a texture or font string runs no scripts: report its frame's + local frame = region.GetScript and region or region:GetParent() + + tooltip:AddLine(" ") + Line(tooltip, "Owner", ns.OwnerLabel(ns.Owner(region))) + if not frame then return end + + for _, script in ipairs({ "OnUpdate", "OnEvent" }) do + local fn = frame:GetScript(script) + if fn then + local text = ns.OwnerLabel(ns.Owner(fn)) + if ns.profiling then + local ms, calls = GetFunctionCPUUsage(fn) + text = text .. ns.GREY .. " " .. ns.MS(ms) .. " in " .. ns.Count(calls) .. " calls" + end + Line(tooltip, script, text) + end + end + + if ns.profiling then + local ms, calls = GetFrameCPUUsage(frame, false) + Line(tooltip, "All scripts", ns.MS(ms) .. ns.GREY .. " in " .. ns.Count(calls) .. " calls") + end + + local rec = ns.track.frames[frame] + if rec and (rec.hookedUpdate or rec.hookedEvent) then + Line(tooltip, "Allocated", ns.KB(rec.alloc) .. ns.GREY .. " (" .. ns.KBRate(rec.allocRate) .. ")") + end +end diff --git a/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/FramesTab.lua b/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/FramesTab.lua new file mode 100644 index 00000000..76150c2a --- /dev/null +++ b/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/FramesTab.lua @@ -0,0 +1,166 @@ +-- Frames tab: the frames that run scripts, with the CPU time of all their +-- scripts (CPU profiling) and the memory they allocate (deep tracking). +local _, ns = ... + +local track = ns.track + +local function Profiled(fn) + return function(rec) + if ns.profiling then return fn(rec) end + end +end + +local function Tracked(fn) + return function(rec) + if rec.hookedUpdate or rec.hookedEvent then return fn(rec) end + end +end + +local function Line(left, right) + GameTooltip:AddDoubleLine(left, right, 1, 1, 1, 1, 1, 1) +end + +-- the events of a frame, most expensive first +local function SortedEvents(rec) + local list = {} + for name, stat in pairs(rec.events) do + tinsert(list, { name = name, stat = stat }) + end + local key = ns.profiling and "cpu" or "alloc" + table.sort(list, function(a, b) return a.stat[key] > b.stat[key] end) + return list +end + +local function Tooltip(rec) + local frame = rec.frame + GameTooltip:AddLine(rec.name) + Line("Type", frame:GetObjectType()) + Line("Owner", ns.OwnerLabel(rec.owner)) + Line("State", frame:IsVisible() and "visible" or frame:IsShown() and "shown, parent hidden" or "hidden") + + local source = frame:GetSourceLocation() + if source then + GameTooltip:AddLine(source, .6, .6, .6, true) + end + + GameTooltip:AddLine(" ") + for _, script in ipairs({ "OnUpdate", "OnEvent" }) do + local fn = frame:GetScript(script) + if fn then + local text = ns.OwnerLabel(ns.Owner(fn)) + if ns.profiling then + local ms, calls = GetFunctionCPUUsage(fn) + text = text .. ns.GREY .. " " .. ns.MS(ms) .. " in " .. ns.Count(calls) .. " calls" + end + Line(script, text) + end + end + + if ns.profiling then + Line("All scripts", ns.MS(rec.cpu) .. " in " .. ns.Count(rec.calls) .. " calls") + end + if rec.hookedUpdate or rec.hookedEvent then + Line("Allocated", ns.KB(rec.alloc)) + end + + local events = SortedEvents(rec) + if #events > 0 then + GameTooltip:AddLine(" ") + GameTooltip:AddLine("Events", 1, .8, 0) + for i = 1, min(#events, 12) do + local stat = events[i].stat + local text = ns.Count(stat.count) .. "x" + if ns.profiling then text = text .. " " .. ns.MS(stat.cpu) end + Line(events[i].name, text .. " " .. ns.KB(stat.alloc)) + end + end + + GameTooltip:AddLine(" ") + GameTooltip:AddLine("Right-click: highlight, inspect or copy.", .6, .6, .6) +end + +local tab = ns.AddTab("Frames") + +tab.list = ns.CreateList(tab.frame, { + sort = 3, + columns = { + { + title = "Frame", + text = function(rec) return rec.name end, + value = function(rec) return strlower(rec.name) end, + }, + { + title = "Owner", width = 100, justify = "LEFT", + tip = "The addon that made the frame's OnUpdate or OnEvent handler, or the frame itself.", + text = function(rec) return ns.OwnerLabel(rec.owner) end, + value = function(rec) return strlower(ns.OwnerLabel(rec.owner)) end, + }, + { + title = "CPU/s", width = 64, + tip = "The CPU time of all the frame's scripts in the last second. Needs CPU profiling.", + text = Profiled(function(rec) return ns.MS(rec.cpuRate) end), + value = Profiled(function(rec) return rec.cpuRate end), + }, + { + title = "Calls/s", width = 60, + tip = "How often the frame's scripts ran in the last second. Needs CPU profiling.", + text = Profiled(function(rec) return ns.Count(rec.callRate) end), + value = Profiled(function(rec) return rec.callRate end), + }, + { + title = "Per Call", width = 64, + tip = "The average CPU time of one script call since the last reset.", + text = Profiled(function(rec) return rec.calls > 0 and ns.MS(rec.cpu / rec.calls) end), + value = Profiled(function(rec) return rec.calls > 0 and rec.cpu / rec.calls or nil end), + }, + { + title = "Alloc/s", width = 72, + tip = "The Lua memory the frame's OnUpdate and OnEvent scripts allocated in the last second. Needs deep tracking.", + text = Tracked(function(rec) return ns.KBRate(rec.allocRate) end), + value = Tracked(function(rec) return rec.allocRate end), + }, + { + title = "CPU Total", width = 64, + tip = "The CPU time of all the frame's scripts since the last reset.", + text = Profiled(function(rec) return ns.MS(rec.cpu) end), + value = Profiled(function(rec) return rec.cpu end), + }, + }, + + tooltip = Tooltip, + + menu = function(rec, root) + root:CreateTitle(rec.name) + root:CreateButton("Highlight", function() ns.Highlight(rec.frame) end) + root:CreateButton("Inspect", function() ns.Inspect(rec.frame) end) + root:CreateButton("Copy name", function() ns.Copy(rec.name) end) + local source = rec.frame:GetSourceLocation() + if source then + root:CreateButton("Copy source location", function() ns.Copy(source) end) + end + root:CreateButton("Show " .. ns.OwnerLabel(rec.owner) .. " frames", function() + ns.ShowIn("Frames", ns.OwnerLabel(rec.owner)) + end) + end, +}) +tab.list:SetAllPoints() + +local function Update(self) + local entries = {} + for _, rec in pairs(track.frames) do + if rec.calls > 0 or rec.alloc > 0 then tinsert(entries, rec) end + end + self.list:SetEntries(entries) +end + +tab.OnSelect = Update +tab.OnSample = Update + +function tab:Status() + local text = format("%d frames %d listed", track.frameCount, #self.list.shown) + if not ns.profiling and not track.deep then + return text .. " " .. ns.GOLD .. "Turn on CPU profiling or deep tracking to measure frames." + end + if track.deep then text = text .. " deep tracking on" end + return text +end diff --git a/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/GlobalsTab.lua b/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/GlobalsTab.lua new file mode 100644 index 00000000..f2f14776 --- /dev/null +++ b/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/GlobalsTab.lua @@ -0,0 +1,177 @@ +-- Globals tab: the global tables, functions and frames each addon made, the +-- ClassicAPI functions that something replaced or hooked, and (CPU +-- profiling) the time of every global function, game API included. +local _, ns = ... + +-- namespaces whose functions are listed as Name.key +local LIBRARIES = { string = true, table = true, math = true, coroutine = true } + +local function Kind(value) + local t = type(value) + if t == "table" and type(rawget(value, 0)) == "userdata" and value.GetObjectType then + return value:GetObjectType() + end + return t +end + +local function Line(left, right) + GameTooltip:AddDoubleLine(left, right, 1, 1, 1, 1, 1, 1) +end + +local function Tooltip(entry) + local value = entry.value + GameTooltip:AddLine(entry.name) + Line("Type", entry.kind) + Line("Owner", ns.OwnerLabel(entry.owner)) + if entry.override then + GameTooltip:AddLine("Not ClassicAPI's function: something replaced or hooked it.", 1, .3, .3, true) + end + + if entry.kind == "function" and ns.profiling then + Line("CPU", ns.MS(entry.cpu)) + Line("Calls", ns.Count(entry.calls)) + if entry.calls > 0 then Line("Per call", ns.MS(entry.cpu / entry.calls)) end + elseif entry.kind == "table" then + Line("Entries", ns.Count(table.count(value))) + elseif type(value) == "table" then + Line("Debug name", ns.FrameName(value)) + local source = value:GetSourceLocation() + if source then GameTooltip:AddLine(source, .6, .6, .6, true) end + elseif type(value) ~= "function" and value ~= nil then + Line("Value", strsub(tostring(value), 1, 60)) + end +end + +local tab = ns.AddTab("Globals") +tab.untagged = false + +tab.list = ns.CreateList(tab.frame, { + sort = 3, + columns = { + { + title = "Name", + text = function(entry) + if entry.override then return ns.RED .. entry.name .. ns.GREY .. " (replaced)" end + return entry.name + end, + value = function(entry) return strlower(entry.name) end, + }, + { + title = "Type", width = 80, justify = "LEFT", + text = function(entry) return entry.kind end, + value = function(entry) return entry.kind end, + }, + { + title = "Owner", width = 100, justify = "LEFT", + tip = "The addon that made the value. Strings, numbers and booleans have no owner.", + text = function(entry) return ns.OwnerLabel(entry.owner) end, + value = function(entry) return strlower(ns.OwnerLabel(entry.owner)) end, + }, + { + title = "CPU", width = 64, + tip = "The CPU time of the function since the last reset. Needs CPU profiling.", + text = function(entry) return entry.cpu and ns.MS(entry.cpu) end, + value = function(entry) return entry.cpu end, + }, + { + title = "Calls", width = 70, + tip = "How often the function ran since the last reset. Needs CPU profiling.", + text = function(entry) return entry.calls and ns.Count(entry.calls) end, + value = function(entry) return entry.calls end, + }, + }, + + tooltip = Tooltip, + + menu = function(entry, root) + local value = entry.value + root:CreateTitle(entry.name) + if type(value) == "table" then + root:CreateButton("Inspect", function() ns.Inspect(value) end) + if entry.kind ~= "table" then + root:CreateButton("Highlight", function() ns.Highlight(value) end) + end + end + root:CreateButton("Copy name", function() ns.Copy(entry.name) end) + end, +}) +tab.list:SetPoint("TOPLEFT", 0, -26) +tab.list:SetPoint("BOTTOMRIGHT") + +-- [[ scan ]] +local function Scan() + -- the ClassicAPI functions whose global is no longer ClassicAPI's + local overrides = {} + for name, fn in pairs(ClassicAPI) do + if type(fn) == "function" then + if _G[name] ~= fn then overrides[name] = true end + elseif type(fn) == "table" and type(_G[name]) == "table" then + for key, sub in pairs(fn) do + if type(sub) == "function" and _G[name][key] ~= sub then overrides[name .. "." .. key] = true end + end + end + end + + local entries = {} + local function Add(name, value) + local kind = Kind(value) + local owner = (kind ~= "string" and kind ~= "number" and kind ~= "boolean" and kind ~= "nil") and ns.Owner(value) or nil + local override = overrides[name] + if not owner and not override and not tab.untagged then return end + + local entry = { name = name, value = value, kind = kind, owner = owner, override = override } + entry.search = strlower(name .. " " .. ns.OwnerLabel(owner)) + if kind == "function" and ns.profiling then + entry.cpu, entry.calls = GetFunctionCPUUsage(value) + end + tinsert(entries, entry) + overrides[name] = nil + end + + for name, value in pairs(_G) do + if type(name) == "string" then + Add(name, value) + if type(value) == "table" and (LIBRARIES[name] or strfind(name, "^C_")) then + for key, fn in pairs(value) do + if type(key) == "string" and type(fn) == "function" then Add(name .. "." .. key, fn) end + end + end + end + end + + -- overridden names that are gone or live outside the scanned namespaces + for name in pairs(overrides) do + local space, key = strmatch(name, "^([^.]+)%.(.+)$") + Add(name, space and _G[space][key] or _G[name]) + end + + tab.count = #entries + tab.overrides = 0 + for _, entry in ipairs(entries) do + if entry.override then tab.overrides = tab.overrides + 1 end + end + tab.list:SetEntries(entries) +end + +local rescan = ns.CreateButton("ClassicAPIProfilerWindowRescan", tab.frame, 80, "Rescan", Scan) +rescan:SetPoint("TOPRIGHT", -4, -2) +ns.Tooltip(rescan, "Read the global namespace again. Also updates the CPU times.") + +local untagged = CreateFrame("CheckButton", "ClassicAPIProfilerWindowUntagged", tab.frame, "UICheckButtonTemplate") +untagged:SetSize(20, 20) +untagged:SetPoint("RIGHT", rescan, "LEFT", -110, 0) +ClassicAPIProfilerWindowUntaggedText:SetText("Show FrameXML") +untagged:SetScript("OnClick", function(self) + tab.untagged = self:GetChecked() and true or false + Scan() +end) +ns.Tooltip(untagged, "Also list the values the game's own code made, and plain strings, numbers and booleans. With CPU profiling this shows the cost of every game API function.") + +function tab:OnSelect() + if not self.count then Scan() end +end + +function tab:Status() + if not self.count then return "" end + return format("%d globals listed %d ClassicAPI functions replaced or hooked", #self.list.shown, self.overrides) +end diff --git a/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/Profiler.xml b/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/Profiler.xml new file mode 100644 index 00000000..3eb32086 --- /dev/null +++ b/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/Profiler.xml @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/Track.lua b/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/Track.lua new file mode 100644 index 00000000..8028be37 --- /dev/null +++ b/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/Track.lua @@ -0,0 +1,212 @@ +-- Profiler track: per-frame and per-event statistics for the Frames and +-- Events tabs. The analyzer runs Scan once a sample while it is open. +-- +-- Deep tracking hooks the intrinsic precall and postcall of every OnUpdate +-- and OnEvent script. The hooks never replace a handler, so GetScript and +-- SetScript behave as before, and they stay until /reload. Around each +-- script they measure the Lua memory it allocated and, with CPU profiling, +-- the time of each OnEvent handler per event. +local addonName, ns = ... + +local PRECALL = LE_SCRIPT_BINDING_TYPE_INTRINSIC_PRECALL +local POSTCALL = LE_SCRIPT_BINDING_TYPE_INTRINSIC_POSTCALL +local Delta = ns.Delta + +local track = { + frames = {}, -- [frame] = record: frames that ran scripts, or are hooked + events = {}, -- [event] = record: events fired while the analyzer is open + frameCount = 0, -- frames in the last scan + deep = false, +} +ns.track = track + +-- the frame that counts every event while the analyzer is open +local capture = CreateFrame("Frame") +track.capture = capture + +-- the addon that runs a frame's scripts: the owner of its handlers, or the +-- frame's creator when the game's own code made the handlers +local function OwnerOf(frame) + local fn = frame:GetScript("OnUpdate") or frame:GetScript("OnEvent") + return fn and ns.Owner(fn) or ns.Owner(frame) +end + +-- cpu and calls are the frame's totals now, so its first rate covers only +-- the time after the record exists, not the whole session +local function FrameRecord(frame, cpu, calls) + local rec = { + frame = frame, name = ns.FrameName(frame), owner = OwnerOf(frame), + cpu = cpu or 0, calls = calls or 0, alloc = 0, events = {}, + } + rec.search = strlower(rec.name .. " " .. ns.OwnerLabel(rec.owner)) + track.frames[frame] = rec + return rec +end + +local function EventRecord(name) + local rec = { name = name, search = strlower(name), fires = 0, dispatches = 0, cpu = 0, alloc = 0 } + track.events[name] = rec + return rec +end + +capture:SetScript("OnEvent", function(self, event) + local rec = track.events[event] or EventRecord(event) + rec.fires = rec.fires + 1 +end) + +-- [[ deep tracking ]] +-- a stack, because a script can run inside another script +local depth = 0 +local memAt, gcAt, fnAt, cpuAt, eventAt = {}, {}, {}, {}, {} + +local function Enter(fn, event) + depth = depth + 1 + memAt[depth], gcAt[depth] = gcinfo() + fnAt[depth], eventAt[depth] = fn, event + if fn and ns.profiling then cpuAt[depth] = GetFunctionCPUUsage(fn) end +end + +-- the KB allocated since the matching Enter (nil when a garbage collection +-- ran in between), the handler's CPU time in ms, and the event +local function Leave() + local d = depth + if d == 0 then return end + depth = d - 1 + + local mem, threshold = gcinfo() + local alloc = threshold == gcAt[d] and max(mem - memAt[d], 0) or nil + local fn, cpu = fnAt[d], nil + if fn and ns.profiling then cpu = max(GetFunctionCPUUsage(fn) - cpuAt[d], 0) end + fnAt[d] = nil + return alloc, cpu, eventAt[d] +end + +local function EnterUpdate() Enter() end + +local function LeaveEvent(rec) + local alloc, cpu, name = Leave() + if not name then return end + + local ev = track.events[name] or EventRecord(name) + local fe = rec.events[name] + if not fe then + fe = { count = 0, cpu = 0, alloc = 0 } + rec.events[name] = fe + end + + fe.count = fe.count + 1 + ev.dispatches = ev.dispatches + 1 + if alloc then + rec.alloc, fe.alloc, ev.alloc = rec.alloc + alloc, fe.alloc + alloc, ev.alloc + alloc + end + if cpu then + fe.cpu, ev.cpu = fe.cpu + cpu, ev.cpu + cpu + end +end + +local function Hook(frame, rec) + if not rec.hookedUpdate and frame:GetScript("OnUpdate") then + rec.hookedUpdate = true + frame:HookScript("OnUpdate", EnterUpdate, PRECALL) + frame:HookScript("OnUpdate", function() + local alloc = Leave() + if alloc then rec.alloc = rec.alloc + alloc end + end, POSTCALL) + end + + if not rec.hookedEvent and frame:GetScript("OnEvent") then + rec.hookedEvent = true + -- the engine sets the `event` global before it runs the script + frame:HookScript("OnEvent", function() Enter(frame:GetScript("OnEvent"), event) end, PRECALL) + frame:HookScript("OnEvent", function() LeaveEvent(rec) end, POSTCALL) + end +end + +function track.EnableDeep() + track.deep = true +end + +-- [[ sampling ]] +-- the frames registered for an event, without the capture frame +local function CountListeners(...) + local n = select("#", ...) + for i = 1, n do + if select(i, ...) == capture then return n - 1 end + end + return n +end +track.CountListeners = CountListeners + +function track.Scan(dt) + local profiling, deep = ns.profiling, track.deep + local count = 0 + + local frame = EnumerateFrames() + while frame do + count = count + 1 + local rec = track.frames[frame] + + if profiling then + local cpu, calls = GetFrameCPUUsage(frame, false) + if calls > 0 and not rec then rec = FrameRecord(frame, cpu, calls) end + if rec then + rec.cpuRate = Delta(cpu, rec.cpu) / dt + rec.callRate = Delta(calls, rec.calls) / dt + rec.cpu, rec.calls = cpu, calls + end + end + + if deep and not (rec and rec.hookedUpdate and rec.hookedEvent) then + if frame:GetScript("OnUpdate") or frame:GetScript("OnEvent") then + rec = rec or FrameRecord(frame) + -- the profiler does not measure its own addon + if rec.owner ~= addonName then Hook(frame, rec) end + end + end + + frame = EnumerateFrames(frame) + end + track.frameCount = count + + for _, rec in pairs(track.frames) do + rec.allocRate = Delta(rec.alloc, rec.lastAlloc) / dt + rec.lastAlloc = rec.alloc + end + + for name, ev in pairs(track.events) do + ev.fireRate = Delta(ev.fires, ev.lastFires) / dt + ev.cpuRate = Delta(ev.cpu, ev.lastCpu) / dt + ev.allocRate = Delta(ev.alloc, ev.lastAlloc) / dt + ev.lastFires, ev.lastCpu, ev.lastAlloc = ev.fires, ev.cpu, ev.alloc + ev.listeners = CountListeners(GetFramesRegisteredForEvent(name)) + end +end + +-- the frame totals and the deep hooks keep counting while the analyzer is +-- closed, so an open takes the counters as they are now, and the first scan +-- covers only its own second +function track.Start() + for frame, rec in pairs(track.frames) do + if ns.profiling then rec.cpu, rec.calls = GetFrameCPUUsage(frame, false) end + rec.lastAlloc = rec.alloc + end + for _, ev in pairs(track.events) do + ev.lastCpu, ev.lastAlloc = ev.cpu, ev.alloc + end + capture:RegisterAllEvents() +end + +function track.Stop() + capture:UnregisterAllEvents() +end + +ns.OnReset(function() + for _, rec in pairs(track.frames) do + rec.cpu, rec.calls, rec.alloc, rec.lastAlloc = 0, 0, 0, 0 + table.wipe(rec.events) + end + for _, ev in pairs(track.events) do + ev.fires, ev.dispatches, ev.cpu, ev.alloc = 0, 0, 0, 0 + ev.lastFires, ev.lastCpu, ev.lastAlloc = 0, 0, 0 + end +end) diff --git a/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/Widget.lua b/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/Widget.lua new file mode 100644 index 00000000..6c0d9ef7 --- /dev/null +++ b/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/Widget.lua @@ -0,0 +1,180 @@ +-- Profiler widget: Lua memory, garbage collection, frame rate and the addons +-- that make the most garbage and use the most CPU. +local _, ns = ... + +local LINE_HEIGHT = 14 +local stats, gc = ns.stats, ns.gc + +local widget = CreateFrame("Button", "ClassicAPIProfilerWidget", UIParent) +ns.widget = widget +widget:Hide() +widget:SetPoint("CENTER", 0, 0) +widget:SetWidth(240) +widget:SetMovable(true) +widget:SetClampedToScreen(true) +widget:EnableMouse(true) +widget:RegisterForDrag("LeftButton") +widget:RegisterForClicks("LeftButtonUp", "RightButtonUp") +ns.CreateBackdrop(widget) + +local lines = {} +local function AddLine(label) + local y = -4 - #lines * LINE_HEIGHT + + local left = widget:CreateFontString(nil, "LOW", "GameFontWhite") + left:SetPoint("TOPLEFT", 5, y) + left:SetText(ns.ACCENT .. label) + + local right = widget:CreateFontString(nil, "LOW", "GameFontWhite") + right:SetPoint("TOPRIGHT", -5, y) + right:SetJustifyH("RIGHT") + + tinsert(lines, right) + return right +end + +local memory = AddLine("Memory") +local rate = AddLine("Rate") +local cleanup = AddLine("Last Cleanup") +local framerate = AddLine("Framerate") +local cpu = AddLine("Lua CPU") +local topMem = AddLine("Top Alloc") +local topCpu = AddLine("Top CPU") + +-- the largest allocation in a tenth of a second, draining over 5 seconds +local DRAIN = .1 / 5 +local bar = CreateFrame("StatusBar", nil, widget) +bar:SetColorFill(1, .3, .3) +bar:SetPoint("BOTTOMLEFT", 1, 1) +bar:SetPoint("BOTTOMRIGHT", -1, 1) +bar:SetHeight(18) +bar:SetMinMaxValues(0, 1) +bar:SetValue(0) + +local barText = bar:CreateFontString(nil, "OVERLAY", "GameFontWhite") +barText:SetPoint("LEFT", 4, 0) + +widget:SetHeight(#lines * LINE_HEIGHT + 8 + 20) + +-- lastMem is taken on the first tick while shown, so the growth while hidden +-- or while the other addons load never counts as a peak +local lastMem, peakElapsed = nil, 0 +widget:SetScript("OnShow", function() ns.StartSampling() end) +widget:SetScript("OnHide", function() lastMem = nil end) +widget:SetScript("OnUpdate", function(self, elapsed) + peakElapsed = peakElapsed + elapsed + if peakElapsed < .1 then return end + peakElapsed = 0 + + local mem = gcinfo() + local grown = lastMem and mem - lastMem or 0 + lastMem = mem + + local value, peak = bar:GetValue(), select(2, bar:GetMinMaxValues()) + if grown > value then + bar:SetMinMaxValues(0, grown) + bar:SetValue(grown) + barText:SetText(ns.ACCENT .. "Last Peak (100ms):|r " .. grown .. ns.GREY .. " KB") + else + bar:SetValue(max(value - peak * DRAIN, 0)) + end + bar:SetColorFill(1, .3, .3, min(bar:GetValue() / 10, 1)) +end) + +local function Unit(value, unit) + return ns.WHITE .. value .. " " .. ns.GREY .. unit +end + +ns.OnSample(function() + if not widget:IsShown() then return end + + memory:SetText(ns.WHITE .. ns.KB(stats.mem) .. ns.GREY .. " / " .. ns.WHITE .. ns.KB(stats.threshold)) + + if stats.collected then + rate:SetText(ns.ACCENT .. "collected " .. ns.KB(gc.freed or 0)) + elseif stats.memRate then + rate:SetText(ns.WHITE .. ns.KBRate(stats.memRate)) + end + + if gc.time then + cleanup:SetText(ns.WHITE .. gc.clock .. ns.GREY .. " (" .. SecondsToTime(GetTime() - gc.time) .. " ago)") + else + cleanup:SetText(ns.GREY .. "none yet") + end + + local fps = GetFramerate() + framerate:SetText(Unit(format("%.0f", fps), "fps") .. ns.GREY .. " (" .. ns.WHITE .. format("%.1f", 1000 / fps) .. ns.GREY .. " ms)") + + if ns.profiling then + cpu:SetText(ns.WHITE .. ns.MS(stats.scriptRate) .. ns.GREY .. "/s (" .. ns.WHITE .. format("%.1f%%", stats.scriptRate / 10) .. ns.GREY .. ")") + topCpu:SetText(stats.topCpu and ns.WHITE .. stats.topCpu.name .. " " .. ns.GREY .. ns.MS(stats.topCpu.cpuRate) .. "/s" or "") + else + cpu:SetText(ns.GREY .. "profiling off") + topCpu:SetText(ns.GREY .. "-") + end + + local top = stats.topMem + if top and top.memRate > 0 then + topMem:SetText(ns.WHITE .. top.name .. " " .. ns.GREY .. ns.KBRate(top.memRate)) + else + topMem:SetText(ns.GREY .. "-") + end + + if GameTooltip:IsOwned(widget) then widget:GetScript("OnEnter")(widget) end +end) + +ns.OnReset(function() + bar:SetValue(0) +end) + +-- the top `count` loaded addons by `key`, largest first +local function Top(key, count) + local sorted = {} + for _, addon in ipairs(stats.list) do + if (addon[key] or 0) > 0 then tinsert(sorted, addon) end + end + table.sort(sorted, function(a, b) return a[key] > b[key] end) + for i = count + 1, #sorted do sorted[i] = nil end + return sorted +end + +widget:SetScript("OnEnter", function(self) + GameTooltip:SetOwner(self, "ANCHOR_BOTTOMLEFT") + GameTooltip:ClearLines() + GameTooltip:AddLine(ns.ACCENT .. "Profiler") + + GameTooltip:AddLine(" ") + GameTooltip:AddLine("Allocated per second", 1, .8, 0) + for _, addon in ipairs(Top("memRate", 8)) do + GameTooltip:AddDoubleLine(addon.name, ns.KBRate(addon.memRate), 1, 1, 1, 1, 1, 1) + end + + if ns.profiling then + GameTooltip:AddLine(" ") + GameTooltip:AddLine("CPU per second", 1, .8, 0) + for _, addon in ipairs(Top("cpuRate", 8)) do + GameTooltip:AddDoubleLine(addon.name, ns.MS(addon.cpuRate), 1, 1, 1, 1, 1, 1) + end + end + + GameTooltip:AddLine(" ") + GameTooltip:AddLine("Left-click: reset the peak", .6, .6, .6) + GameTooltip:AddLine("Right-click: open the analyzer", .6, .6, .6) + GameTooltip:AddLine("Drag: move", .6, .6, .6) + GameTooltip:Show() +end) + +widget:SetScript("OnLeave", function() + GameTooltip:Hide() +end) + +widget:SetScript("OnClick", function(self, button) + if button == "RightButton" then + ns.window:SetShown(not ns.window:IsShown()) + else + bar:SetValue(0) + end +end) + +widget:SetScript("OnDragStart", function(self) self:StartMoving() end) +widget:SetScript("OnDragStop", function(self) self:StopMovingOrSizing() end) diff --git a/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/Window.lua b/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/Window.lua new file mode 100644 index 00000000..66057234 --- /dev/null +++ b/src/embed/AddOns/ClassicAPI_DebugTools/Profiler/Window.lua @@ -0,0 +1,392 @@ +-- Profiler window: the analyzer. Its tabs share a toolbar (search, deep +-- tracking, reset, copy) and the sortable list below. +local _, ns = ... + +local ROW_HEIGHT = 18 +local WHITE8X8 = "Interface\\BUTTONS\\WHITE8X8" + +ns.search = "" + +local window = CreateFrame("Frame", "ClassicAPIProfilerWindow", UIParent) +ns.window = window +window:Hide() +window:SetSize(760, 480) +window:SetPoint("CENTER") +window:SetFrameStrata("DIALOG") +window:SetMovable(true) +window:EnableMouse(true) +window:SetClampedToScreen(true) +window:RegisterForDrag("LeftButton") +window:SetScript("OnDragStart", window.StartMoving) +window:SetScript("OnDragStop", window.StopMovingOrSizing) +ns.CreateBackdrop(window) +tinsert(UISpecialFrames, "ClassicAPIProfilerWindow") + +local title = window:CreateFontString(nil, "OVERLAY", "GameFontWhite") +title:SetFont(STANDARD_TEXT_FONT, 14) +title:SetPoint("TOPLEFT", 10, -10) +title:SetText(ns.ACCENT .. "Profiler|r: " .. ns.GOLD .. "Analyzer") + +local close = CreateFrame("Button", "ClassicAPIProfilerWindowClose", window, "UIPanelCloseButton") +close:SetSize(20, 20) +close:SetPoint("TOPRIGHT", 0, 0) +close:SetScript("OnClick", function() window:Hide() end) + +local status = window:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall") +status:SetPoint("BOTTOMLEFT", 10, 8) +status:SetPoint("BOTTOMRIGHT", -10, 8) +status:SetJustifyH("LEFT") + +-- [[ widgets ]] +local function Tooltip(frame, text) + frame:SetScript("OnEnter", function(self) + GameTooltip:SetOwner(self, "ANCHOR_BOTTOMLEFT") + GameTooltip:SetText(type(text) == "function" and text() or text, 1, 1, 1, 1, true) + GameTooltip:Show() + end) + frame:SetScript("OnLeave", function() GameTooltip:Hide() end) +end +ns.Tooltip = Tooltip + +function ns.CreateButton(name, parent, width, text, onClick) + local button = CreateFrame("Button", name, parent, "UIPanelButtonTemplate") + button:SetSize(width, 20) + button:SetText(text) + button:SetScript("OnClick", onClick) + return button +end + +-- [[ actions the tabs offer in their context menus ]] +function ns.Copy(text) + local bytes = CopyToClipboard(text, true) + ns.Print("Copied " .. bytes .. " bytes to the clipboard.") +end + +function ns.Inspect(value) + DisplayTableInspectorWindow(value) +end + +local highlight = CreateFrame("Frame", nil, UIParent) +highlight:SetFrameStrata("TOOLTIP") +highlight:SetBackdrop({ bgFile = WHITE8X8, edgeFile = WHITE8X8, edgeSize = 2 }) +highlight:SetBackdropColor(.2, 1, .8, .15) +highlight:SetBackdropBorderColor(.2, 1, .8, 1) +highlight:Hide() + +function ns.Highlight(frame) + if not frame:IsVisible() then + ns.Print(ns.FrameName(frame) .. " is hidden.") + return + end + highlight:ClearAllPoints() + highlight:SetAllPoints(frame) + highlight:Show() + if highlight.timer then highlight.timer:Cancel() end + highlight.timer = C_Timer.NewTimer(3, function() highlight:Hide() end) +end + +-- [[ list: a sortable, searchable ScrollBox ]] +-- columns = { { title, width, justify, tip, text = fn(entry), value = fn(entry) } } +-- The first column takes the space the others leave. `value` sorts the +-- column and sizes the row bars; it is a number, a lowercase string or nil. +local function LayoutColumns(parent, cells, columns) + local right = -4 + for i = #columns, 2, -1 do + cells[i]:SetPoint("RIGHT", parent, "RIGHT", right, 0) + cells[i]:SetWidth(columns[i].width) + right = right - columns[i].width - 8 + end + cells[1]:SetPoint("LEFT", parent, "LEFT", 4, 0) + cells[1]:SetPoint("RIGHT", parent, "RIGHT", right, 0) +end + +-- green to yellow to red, as `perc` goes from 0 to 1 +local function Gradient(perc) + if perc <= .5 then return perc * 2, 1, 0 end + return 1, 2 - perc * 2, 0 +end + +local function RowOnEnter(row) + local tooltip = row.list.def.tooltip + if not tooltip then return end + GameTooltip:SetOwner(row, "ANCHOR_RIGHT") + GameTooltip:ClearLines() + tooltip(row.entry) + GameTooltip:Show() +end + +local function RowOnLeave() + GameTooltip:Hide() +end + +local function RowOnClick(row, button) + local def = row.list.def + if button == "RightButton" and def.menu then + MenuUtil.CreateContextMenu(row, function(owner, root) + def.menu(row.entry, root) + end) + elseif button == "LeftButton" and def.click then + def.click(row.entry) + end +end + +local function InitRow(list, row, entry) + local columns = list.def.columns + + if not row.cells then + row:EnableMouse(true) + row:RegisterForClicks("LeftButtonUp", "RightButtonUp") + row:SetHighlightTexture(WHITE8X8) + row:GetHighlightTexture():SetVertexColor(1, 1, 1, .1) + row:SetScript("OnEnter", RowOnEnter) + row:SetScript("OnLeave", RowOnLeave) + row:SetScript("OnClick", RowOnClick) + + row.bar = CreateFrame("StatusBar", nil, row) + row.bar:SetAllPoints() + row.bar:SetMinMaxValues(0, 1) + + row.cells = {} + for i, column in ipairs(columns) do + local cell = row.bar:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall") + cell:SetHeight(ROW_HEIGHT) + cell:SetWordWrap(false) + cell:SetJustifyH(column.justify or (i == 1 and "LEFT" or "RIGHT")) + row.cells[i] = cell + end + LayoutColumns(row, row.cells, columns) + end + + row.list, row.entry = list, entry + for i, column in ipairs(columns) do + row.cells[i]:SetText(column.text(entry) or "") + end + + local value = columns[list.sortColumn].value + local v = value and value(entry) + local perc = type(v) == "number" and list.maxValue > 0 and max(v, 0) / list.maxValue or 0 + local r, g, b = Gradient(perc) + row.bar:SetColorFill(r, g, b, .2) + row.bar:SetValue(perc) + + if GameTooltip:IsOwned(row) then RowOnEnter(row) end +end + +local ListMixin = {} + +function ListMixin:UpdateHeader() + for i, column in ipairs(self.def.columns) do + local text = column.title + if i == self.sortColumn then + text = ns.ACCENT .. text .. (self.sortDesc and " v" or " ^") + end + self.headers[i].text:SetText(text) + end +end + +function ListMixin:SortBy(index) + if self.sortColumn == index then + self.sortDesc = not self.sortDesc + else + self.sortColumn, self.sortDesc = index, true + end + self:UpdateHeader() + self:Refresh() +end + +function ListMixin:SetEntries(entries) + self.entries = entries + self:Refresh() +end + +-- filter by the search text, sort, and show +function ListMixin:Refresh() + local value = self.def.columns[self.sortColumn].value + local needle, desc = ns.search, self.sortDesc + local shown, keys, maxValue = {}, {}, 0 + + for _, entry in ipairs(self.entries) do + if needle == "" or strfind(entry.search, needle, 1, true) then + tinsert(shown, entry) + local v = value and value(entry) + keys[entry] = v + if type(v) == "number" and v > maxValue then maxValue = v end + end + end + + table.sort(shown, function(a, b) + local va, vb = keys[a], keys[b] + if va == vb then return a.search < b.search end + if va == nil then return false end + if vb == nil then return true end + if desc then return va > vb end + return va < vb + end) + + self.shown, self.maxValue = shown, maxValue + self.ScrollBox:SetDataProvider(CreateDataProvider(shown), ScrollBoxConstants.RetainScrollPosition) +end + +-- the shown rows as plain text +function ListMixin:Export() + local columns = self.def.columns + local function Line(texts) + local parts = {} + for i, text in ipairs(texts) do + text = gsub(gsub(text, "|c%x%x%x%x%x%x%x%x", ""), "|r", "") + parts[i] = format(i == 1 and "%-48s" or "%14s", text) + end + return table.concat(parts, " ") + end + + local titles = {} + for i, column in ipairs(columns) do titles[i] = column.title end + local lines = { Line(titles) } + + for _, entry in ipairs(self.shown) do + local texts = {} + for i, column in ipairs(columns) do texts[i] = column.text(entry) or "" end + tinsert(lines, Line(texts)) + end + return table.concat(lines, "\n") +end + +function ns.CreateList(parent, def) + local list = CreateFrame("Frame", nil, parent, "ClassicAPIProfilerListTemplate") + Mixin(list, ListMixin) + list.def = def + list.entries, list.shown, list.maxValue = {}, {}, 0 + list.sortColumn, list.sortDesc = def.sort or 1, true + ns.CreateBackdrop(list) + + list.headers = {} + for i, column in ipairs(def.columns) do + local header = CreateFrame("Button", nil, list.Header) + header:SetHeight(18) + header:EnableMouse(true) + header.text = header:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall") + header.text:SetAllPoints() + header.text:SetJustifyH(column.justify or (i == 1 and "LEFT" or "RIGHT")) + header:SetScript("OnClick", function() list:SortBy(i) end) + if column.tip then Tooltip(header, column.tip) end + list.headers[i] = header + end + LayoutColumns(list.Header, list.headers, def.columns) + list:UpdateHeader() + + local view = CreateScrollBoxListLinearView(0, 0, 0, 0, 1) + view:SetElementExtent(ROW_HEIGHT) + view:SetElementInitializer("Button", function(row, entry) InitRow(list, row, entry) end) + ScrollUtil.InitScrollBoxListWithScrollBar(list.ScrollBox, list.ScrollBar, view) + return list +end + +-- [[ tabs ]] +-- a tab has `frame`, `list`, and optionally OnSelect(), OnSample(dt) and +-- Status() for the line at the bottom +local tabs = {} + +local function UpdateStatus() + local tab = window.active + status:SetText(tab and tab.Status and tab:Status() or "") +end + +function ns.SelectTab(tab) + for _, other in ipairs(tabs) do + other.frame:SetShown(other == tab) + if other == tab then other.button:LockHighlight() else other.button:UnlockHighlight() end + end + window.active = tab + if tab.OnSelect then tab:OnSelect() end + UpdateStatus() +end + +function ns.AddTab(name) + local tab = { name = name } + local index = #tabs + 1 + + tab.frame = CreateFrame("Frame", nil, window) + tab.frame:SetPoint("TOPLEFT", 6, -84) + tab.frame:SetPoint("BOTTOMRIGHT", -6, 24) + tab.frame:Hide() + + tab.button = ns.CreateButton("ClassicAPIProfilerWindowTab" .. index, window, 90, name, function() ns.SelectTab(tab) end) + tab.button:SetPoint("TOPLEFT", 8 + (index - 1) * 94, -32) + + tabs[index] = tab + tabs[name] = tab + return tab +end + +-- show `text` in the search box and switch to tab `name` +function ns.ShowIn(name, text) + window.search:SetText(text) + ns.SelectTab(tabs[name]) +end + +-- [[ toolbar ]] +local search = CreateFrame("EditBox", "ClassicAPIProfilerWindowSearch", window, "InputBoxTemplate") +window.search = search +search:SetSize(200, 20) +search:SetPoint("TOPLEFT", 14, -58) +search:SetAutoFocus(false) +search:SetScript("OnTextChanged", function(self) + ns.search = strlower(self:GetText()) + self.placeholder:SetShown(self:GetText() == "") + if window.active then window.active.list:Refresh() end +end) + +search.placeholder = search:CreateFontString(nil, "OVERLAY", "GameFontDisableSmall") +search.placeholder:SetPoint("LEFT", 2, 0) +search.placeholder:SetText("Search name, owner or source") + +local copy = ns.CreateButton("ClassicAPIProfilerWindowCopy", window, 70, "Copy", function() + ns.Copy(window.active.list:Export()) +end) +copy:SetPoint("TOPRIGHT", -8, -58) +Tooltip(copy, "Copy the shown rows to the clipboard as plain text.") + +local reset = ns.CreateButton("ClassicAPIProfilerWindowReset", window, 70, "Reset", function() + ns.Reset() + UpdateStatus() +end) +reset:SetPoint("RIGHT", copy, "LEFT", -4, 0) +Tooltip(reset, "Set every CPU time, call count, allocation and event count to zero.") + +local deep = ns.CreateButton("ClassicAPIProfilerWindowDeep", window, 150, "", function(self) + ns.track.EnableDeep() + self:SetText("Deep Tracking: " .. ns.ACCENT .. "ON") + self:Disable() +end) +deep:SetPoint("RIGHT", reset, "LEFT", -4, 0) +deep:SetText("Deep Tracking: " .. ns.GREY .. "OFF") +Tooltip(deep, "Hooks the OnUpdate and OnEvent scripts of every frame to measure the Lua memory each frame allocates, and the CPU time and memory of each event. The hooks never replace a handler, but they add a little time to every script call. They stay until /reload.") + +local profiling = ns.CreateButton("ClassicAPIProfilerWindowProfiling", window, 150, "", function() + ns.SetProfiling(not ns.profiling) +end) +profiling:SetPoint("TOPRIGHT", -24, -32) +profiling:SetText("CPU Profiling: " .. (ns.profiling and ns.ACCENT .. "ON" or ns.GREY .. "OFF")) +Tooltip(profiling, function() + return (ns.profiling and "Turn CPU profiling off" or "Turn CPU profiling on") .. + " and reload the UI.\n\nProfiling measures the CPU time of every addon, frame, function and event. It makes each Lua call slower, so turn it off when you are done." +end) + +-- [[ sampling while open ]] +ns.OnSample(function(dt) + if not window:IsShown() then return end + ns.track.Scan(dt) + local tab = window.active + if tab.OnSample then tab:OnSample(dt) end + UpdateStatus() +end) + +window:SetScript("OnShow", function() + ns.StartSampling() + ns.track.Start() + ns.SelectTab(window.active or tabs[1]) +end) + +window:SetScript("OnHide", function() + ns.track.Stop() +end)