Quantcast
--[[
##############################################################################
_____/\\\\\\\\\\\____/\\\________/\\\__/\\\________/\\\__/\\\\\\\\\\\_       #
 ___/\\\/////////\\\_\/\\\_______\/\\\_\/\\\_______\/\\\_\/////\\\///__      #
  __\//\\\______\///__\//\\\______/\\\__\/\\\_______\/\\\_____\/\\\_____     #
   ___\////\\\__________\//\\\____/\\\___\/\\\_______\/\\\_____\/\\\_____    #
    ______\////\\\________\//\\\__/\\\____\/\\\_______\/\\\_____\/\\\_____   #
     _________\////\\\______\//\\\/\\\_____\/\\\_______\/\\\_____\/\\\_____  #
      __/\\\______\//\\\______\//\\\\\______\//\\\______/\\\______\/\\\_____ #
       _\///\\\\\\\\\\\/________\//\\\________\///\\\\\\\\\/____/\\\\\\\\\\\_#
        ___\///////////___________\///___________\/////////_____\///////////_#
##############################################################################
S U P E R - V I L L A I N - U I   By: Munglunch                              #
############################################################################## ]]--
--[[ GLOBALS ]]--
local _G = _G;
local unpack        = _G.unpack;
local select        = _G.select;
local pairs         = _G.pairs;
local type          = _G.type;
local rawset        = _G.rawset;
local rawget        = _G.rawget;
local tinsert       = _G.tinsert;
local tremove       = _G.tremove;
local tostring      = _G.tostring;
local error         = _G.error;
local getmetatable  = _G.getmetatable;
local setmetatable  = _G.setmetatable;
local string    = _G.string;
local math      = _G.math;
local table     = _G.table;
--[[ STRING METHODS ]]--
local upper = string.upper;
local format, find, match, gsub = string.format, string.find, string.match, string.gsub;
--[[ MATH METHODS ]]--
local floor = math.floor
--[[ TABLE METHODS ]]--
local twipe, tsort, tconcat = table.wipe, table.sort, table.concat;
--[[
##############################################################################
  /$$$$$$  /$$        /$$$$$$  /$$$$$$$   /$$$$$$  /$$
 /$$__  $$| $$       /$$__  $$| $$__  $$ /$$__  $$| $$
| $$  \__/| $$      | $$  \ $$| $$  \ $$| $$  \ $$| $$
| $$ /$$$$| $$      | $$  | $$| $$$$$$$ | $$$$$$$$| $$
| $$|_  $$| $$      | $$  | $$| $$__  $$| $$__  $$| $$
| $$  \ $$| $$      | $$  | $$| $$  \ $$| $$  | $$| $$
|  $$$$$$/| $$$$$$$$|  $$$$$$/| $$$$$$$/| $$  | $$| $$$$$$$$
 \______/ |________/ \______/ |_______/ |__/  |__/|________/
##############################################################################
]]--

--[[ LOCALS ]]--

local SVUINameSpace, SVUICore = ...;
local SVUIVersion = GetAddOnMetadata(..., "Version");
local clientVersion, internalVersion, releaseDate, uiVersion = GetBuildInfo();
local callbacks = {};
local numCallbacks = 0;

local messagePattern = "|cffFF2F00%s:|r"
local debugPattern = "|cffFF2F00%s|r [|cff992FFF%s|r]|cffFF2F00:|r"

--[[  CONSTANTS ]]--

BINDING_HEADER_SVUI = "Supervillain UI";
SLASH_RELOADUI1 = "/rl"
SLASH_RELOADUI2 = "/reloadui"
SlashCmdList.RELOADUI = ReloadUI

--[[ MUNGLUNCH's FASTER ASSERT FUNCTION ]]--

function enforce(condition, ...)
   if not condition then
      if next({...}) then
         local fn = function (...) return(string.format(...)) end
         local s,r = pcall(fn, ...)
         if s then
            error("Error!: " .. r, 2)
         end
      end
      error("Error!", 2)
   end
end
local assert = enforce;

--[[ META METHODS ]]--

local rootstring = function(self) return self.___addonName end

--[[ LOCALIZATION HELPERS ]]--

local failsafe = function() assert(false) end

local metaread = {
    __index = function(self, key)
        rawset(self, key, key)
        return key
    end
}

local activeLocale

local defaultwrite = setmetatable({}, {
    __newindex = function(self, key, value)
        if not rawget(activeLocale, key) then
            rawset(activeLocale, key, value == true and key or value)
        end
    end,
    __index = failsafe
})

local metawrite = setmetatable({}, {
    __newindex = function(self, key, value)
        rawset(activeLocale, key, value == true and key or value)
    end,
    __index = failsafe
})

--[[ CLASS COLOR LOCALS ]]--

local function formatValueString(text)
    if "string" == type(text) then
        text = gsub(text,"\n","\\n")
        if match(gsub(text,"[^'\"]",""),'^"+$') then
            return "'"..text.."'";
        else
            return '"'..gsub(text,'"','\\"')..'"';
        end
    else
        return tostring(text);
    end
end

local function formatKeyString(text)
    if "string"==type(text) and match(text,"^[_%a][_%a%d]*$") then
        return text;
    else
        return "["..formatValueString(text).."]";
    end
end

local function RegisterCallback(self, m, h)
    assert(type(m) == "string" or type(m) == "function", "Bad argument #1 to :RegisterCallback (string or function expected)")
    if type(m) == "string" then
        assert(type(h) == "table", "Bad argument #2 to :RegisterCallback (table expected)")
        assert(type(h[m]) == "function", "Bad argument #1 to :RegisterCallback (m \"" .. m .. "\" not found)")
        m = h[m]
    end
    callbacks[m] = h or true
    numCallbacks = numCallbacks + 1
end

local function UnregisterCallback(self, m, h)
    assert(type(m) == "string" or type(m) == "function", "Bad argument #1 to :UnregisterCallback (string or function expected)")
    if type(m) == "string" then
        assert(type(h) == "table", "Bad argument #2 to :UnregisterCallback (table expected)")
        assert(type(h[m]) == "function", "Bad argument #1 to :UnregisterCallback (m \"" .. m .. "\" not found)")
        m = h[m]
    end
    callbacks[m] = nil
    numCallbacks = numCallbacks + 1
end

local function DispatchCallbacks()
    if (numCallbacks < 1) then return end
    for m, h in pairs(callbacks) do
        local ok, err = pcall(m, h ~= true and h or nil)
        if not ok then
            print("ERROR:", err)
        end
    end
end

--[[ BUILD CLASS COLOR GLOBAL ]]--

SVUI_CLASS_COLORS = {};
do
    local classes = {};
    local supercolors = {
        ["HUNTER"]        = { r = 0.454, g = 0.698, b = 0 },
        ["WARLOCK"]       = { r = 0.286, g = 0,     b = 0.788 },
        ["PRIEST"]        = { r = 0.976, g = 1,     b = 0.839 },
        ["PALADIN"]       = { r = 0.956, g = 0.207, b = 0.733 },
        ["MAGE"]          = { r = 0,     g = 0.796, b = 1 },
        ["ROGUE"]         = { r = 1,     g = 0.894, b = 0.117 },
        ["DRUID"]         = { r = 1,     g = 0.513, b = 0 },
        ["SHAMAN"]        = { r = 0,     g = 0.38,  b = 1 },
        ["WARRIOR"]       = { r = 0.698, g = 0.36,  b = 0.152 },
        ["DEATHKNIGHT"]   = { r = 0.847, g = 0.117, b = 0.074 },
        ["MONK"]          = { r = 0.015, g = 0.886, b = 0.38 },
    };
    for class in pairs(RAID_CLASS_COLORS) do
        tinsert(classes, class)
    end
    tsort(classes)
    setmetatable(SVUI_CLASS_COLORS,{
        __index = function(t, k)
            if k == "RegisterCallback" then return RegisterCallback end
            if k == "UnregisterCallback" then return UnregisterCallback end
            if k == "DispatchCallbacks" then return DispatchCallbacks end
        end
    });
    for i, class in ipairs(classes) do
        local color = supercolors[class]
        local r, g, b = color.r, color.g, color.b
        local hex = ("ff%02x%02x%02x"):format(r * 255, g * 255, b * 255)
        if not SVUI_CLASS_COLORS[class] or not SVUI_CLASS_COLORS[class].r or not SVUI_CLASS_COLORS[class].g or not SVUI_CLASS_COLORS[class].b then
            SVUI_CLASS_COLORS[class] = {
                r = r,
                g = g,
                b = b,
                colorStr = hex,
            }
        end
    end
    classes = nil
end

--[[ APPENDED LUA METHODS ]]--

function math.parsefloat(value,decimal)
    if decimal and decimal > 0 then
        local calc1 = 10 ^ decimal;
        local calc2 = (value * calc1) + 0.5;
        return floor(calc2) / calc1
    end
    return floor(value + 0.5)
end

function table.dump(targetTable)
    local dumpTable = {};
    local dumpCheck = {};
    for key,value in ipairs(targetTable) do
        tinsert(dumpTable, formatValueString(value));
        dumpCheck[key] = true;
    end
    for key,value in pairs(targetTable) do
        if not dumpCheck[key] then
            tinsert(dumpTable, "\n    "..formatKeyString(key).." = "..formatValueString(value));
        end
    end
    local output = tconcat(dumpTable, ", ");
    return "{ "..output.." }";
end

function table.copy(targetTable,deepCopy,mergeTable)
    mergeTable = mergeTable or {};
    if targetTable==nil then return nil end
    if mergeTable[targetTable] then return mergeTable[targetTable] end
    local replacementTable = {}
    for key,value in pairs(targetTable)do
        if deepCopy and type(value) == "table" then
            replacementTable[key] = table.copy(value, deepCopy, mergeTable)
        else
            replacementTable[key] = value
        end
    end
    setmetatable(replacementTable, table.copy(getmetatable(targetTable), deepCopy, mergeTable))
    mergeTable[targetTable] = replacementTable;
    return replacementTable
end

function string.trim(this)
    return this:find('^%s*$') and '' or this:match('^%s*(.*%S)')
end

function string.color(this, color)
    return ("|cff%s%s|r"):format(color, this)
end

function string.link(this, prefix, text, color)
    text = tostring(text)
    local colorstring = tostring(this):color(color or "ffffff")
    return ("|H%s:%s|h%s|h"):format(prefix, text, colorstring)
end

function string.explode(str, delim)
   local res = { }
   local pattern = string.format("([^%s]+)%s()", delim, delim)
   while (true) do
      line, pos = str:match(pattern, pos)
      if line == nil then break end
      table.insert(res, line)
   end
   return res
end

--[[ CORE ENGINE CONSTRUCT ]]--

local Core_StaticPopup_Show = function(self, arg)
    if arg == "ADDON_ACTION_FORBIDDEN" then
        StaticPopup_Hide(arg)
    end
end

local Core_ResetAllUI = function(self, confirmed)
    if InCombatLockdown()then
        SendAddonMessage(ERR_NOT_IN_COMBAT)
        return
    end
    if(not confirmed) then
        self:StaticPopup_Show('RESET_UI_CHECK')
        return
    end
    self:ResetInstallation()
end

local Core_ResetUI = function(self, confirmed)
    if InCombatLockdown()then
        SendAddonMessage(ERR_NOT_IN_COMBAT)
        return
    end
    if(not confirmed) then
        self:StaticPopup_Show('RESETMOVERS_CHECK')
        return
    end
    self:ResetMovables()
end

local Core_ToggleConfig = function(self)
    if InCombatLockdown() then
        SendAddonMessage(ERR_NOT_IN_COMBAT)
        self.UIParent:RegisterEvent('PLAYER_REGEN_ENABLED')
        return
    end
    if not IsAddOnLoaded("SVUI_ConfigOMatic") then
        local _,_,_,_,_,state = GetAddOnInfo("SVUI_ConfigOMatic")
        if state ~= "MISSING" and state ~= "DISABLED" then
            LoadAddOn("SVUI_ConfigOMatic")
            local config_version = GetAddOnMetadata("SVUI_ConfigOMatic", "Version")
            if(tonumber(config_version) < 4) then
                self:StaticPopup_Show("CLIENT_UPDATE_REQUEST")
            end
        else
            self:AddonMessage("|cffff0000Error -- Addon 'SVUI_ConfigOMatic' not found or is disabled.|r")
            return
        end
    end
    local aceConfig = LibStub("AceConfigDialog-3.0")
    local switch = not aceConfig.OpenFrames["SVUI"] and "Open" or "Close"
    aceConfig[switch](aceConfig, "SVUI")
    GameTooltip:Hide()
end

--/script SVUI[1]:TaintHandler("SVUI", "Script", "Function")
local Core_TaintHandler = function(self, taint, sourceName, sourceFunc)
    if GetCVarBool('scriptErrors') ~= 1 then return end
    local errorString = ("Error Captured: %s->%s->{%s}"):format(taint, sourceName or "Unknown", sourceFunc or "Unknown")
    self:AddonMessage(errorString)
    self:StaticPopup_Show("TAINT_RL")
end

local function _sendmessage(msg, prefix)
    if(type(msg) == "table") then
        msg = tostring(msg)
    end

    if(not msg) then return end

    if(prefix) then
        local outbound = ("%s %s"):format(prefix, msg);
        print(outbound)
    else
        print(msg)
    end
end

local Core_Debugger = function(self, msg)
    if(not self.DebuggingMode) then return end
    local outbound = (debugPattern):format("SVUI", "DEBUG")
    _sendmessage(msg, outbound)
end

local Core_AddonMessage = function(self, msg)
    local outbound = (messagePattern):format("SVUI")
    _sendmessage(msg, outbound)
end

local Core_SetLocaleStrings = function(self, locale, isDefault)
    local gameLocale = GetLocale()
    if gameLocale == "enGB" then gameLocale = "enUS" end

    activeLocale = self.Localization

    if isDefault then
        return defaultwrite
    elseif(locale == GAME_LOCALE or locale == gameLocale) then
        return metawrite
    end
end

local Core_Prototype = function(self, name)
    local version = GetAddOnMetadata(name, "Version")
    local schema = GetAddOnMetadata(name, "X-SVUI-Schema")

    self.Configs[schema] = {["enable"] = false}

    local obj = {
        ___addonName = name,
        ___version = version,
        ___schema = schema
    }

    local mt = {}
    local old = getmetatable(obj)
    if old then
        for k, v in pairs(old) do mt[k] = v end
    end
    mt.__tostring = rootstring
    setmetatable(obj, mt)
    return obj
end

local SVUI = {
    ___addonName = SVUINameSpace,
    ___version = GetAddOnMetadata(SVUINameSpace, "Version"),
    ___interface = tonumber(uiVersion),
    db = {},
    Global = {
        Accountant = {},
        profiles = {},
        profileKeys = {},
    },
    Configs = {},
    Media = {},
    DisplayAudit = {},
    DynamicOptions = {},
    Dispellable = {},
    Snap = {},
    SetLocaleStrings = Core_SetLocaleStrings,
    Prototype = Core_Prototype,
    AddonMessage = Core_AddonMessage,
    Debugger = Core_Debugger,
    StaticPopup_Show,
    ResetAllUI = Core_ResetAllUI,
    ResetUI = Core_ResetUI,
    ToggleConfig = Core_ToggleConfig,
    TaintHandler = Core_TaintHandler
}

SVUI.Localization = setmetatable({}, metaread)
SVUI.Options = { type = "group", name = "|cff339fffConfig-O-Matic|r", args = {}}

--[[ MISC ]]--

SVUI.fubar = function() return end
SVUI.class = select(2,UnitClass("player"));
SVUI.ClassRole = "";
SVUI.UnitRole = "NONE";
SVUI.ConfigurationMode = false;
SVUI.DebuggingMode = false

--[[ UTILITY FRAMES ]]--

SVUI.UIParent = CreateFrame("Frame", "SVUIParent", UIParent);
SVUI.UIParent:SetFrameLevel(UIParent:GetFrameLevel());
SVUI.UIParent:SetPoint("CENTER", UIParent, "CENTER");
SVUI.UIParent:SetSize(UIParent:GetSize());
SVUI.Snap[1] = SVUI.UIParent;

SVUI.Cloaked = CreateFrame("Frame", nil, UIParent);
SVUI.Cloaked:Hide();

--[[ ENSURE META METHODS ]]--

local mt = {}
local old = getmetatable(SVUI)
if old then
    for k, v in pairs(old) do mt[k] = v end
end
mt.__tostring = rootstring
setmetatable(SVUI, mt)

--[[ COMMON FUNCTIONS ]]--

SVUICore[1] = SVUI
SVUICore[2] = SVUI.Localization

--[[ SET MASTER GLOBAL ]]--

_G[SVUINameSpace] = SVUICore;