mirror of
https://github.com/Bluewhale1337/ElvUIModernized.git
synced 2026-07-27 08:24:44 +00:00
remove temp folder structure
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
<Bindings>
|
||||
<Binding name="Raid Marker" runOnUp="true" header="ELVUI">
|
||||
RaidMark_HotkeyPressed(keystate);
|
||||
</Binding>
|
||||
<Binding name="Farm Mode" runOnUp="false">
|
||||
FarmMode();
|
||||
</Binding>
|
||||
<Binding name="Toggle Chat (Left)" runOnUp="false">
|
||||
HideLeftChat();
|
||||
</Binding>
|
||||
<Binding name="Toggle Chat (Right)" runOnUp="false">
|
||||
HideRightChat();
|
||||
</Binding>
|
||||
<Binding name="Toggle Chat (Both)" runOnUp="false">
|
||||
HideBothChat();
|
||||
</Binding>
|
||||
</Bindings>
|
||||
@@ -0,0 +1,463 @@
|
||||
local E, L, V, P, G = unpack(ElvUI); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
|
||||
local CC = E:NewModule("ClassCache", "AceEvent-3.0");
|
||||
local LW = LibStub:GetLibrary("LibWho-2.0");
|
||||
|
||||
--Cache global variables
|
||||
--Lua functions
|
||||
local split, upper = string.split, string.upper
|
||||
local wipe = table.wipe
|
||||
local pairs = pairs
|
||||
local select = select
|
||||
--WoW API / Variables
|
||||
local GetBattlefieldScore = GetBattlefieldScore
|
||||
local GetFriendInfo = GetFriendInfo
|
||||
local GetGuildRosterInfo = GetGuildRosterInfo
|
||||
local GetNumBattlefieldScores = GetNumBattlefieldScores
|
||||
local GetNumFriends = GetNumFriends
|
||||
local GetNumGuildMembers = GetNumGuildMembers
|
||||
local GetNumPartyMembers = GetNumPartyMembers
|
||||
local GetNumRaidMembers = GetNumRaidMembers
|
||||
local GetTime = GetTime
|
||||
local IsInGuild = IsInGuild
|
||||
local UnitClass = UnitClass
|
||||
local UnitExists = UnitExists
|
||||
local UnitIsPlayer = UnitIsPlayer
|
||||
local UnitName = UnitName
|
||||
|
||||
local UNKNOWN = UNKNOWN
|
||||
|
||||
local GAME_LOCALE = GetLocale()
|
||||
local ENGLISH_CLASS_NAMES
|
||||
|
||||
local function GetEnglishClassName(class)
|
||||
if class == UNKNOWN then
|
||||
return class
|
||||
elseif GAME_LOCALE == "enUS" then
|
||||
return upper(class)
|
||||
end
|
||||
|
||||
if not ENGLISH_CLASS_NAMES then
|
||||
ENGLISH_CLASS_NAMES = {}
|
||||
|
||||
for english, localized in pairs(LOCALIZED_CLASS_NAMES_MALE) do
|
||||
ENGLISH_CLASS_NAMES[localized] = english
|
||||
end
|
||||
for english, localized in pairs(LOCALIZED_CLASS_NAMES_FEMALE) do
|
||||
ENGLISH_CLASS_NAMES[localized] = english
|
||||
end
|
||||
end
|
||||
|
||||
return ENGLISH_CLASS_NAMES[class]
|
||||
end
|
||||
|
||||
local function WhoCallback(result)
|
||||
if result then
|
||||
if result.NoLocaleClass then
|
||||
CC:CachePlayer(result.Name, result.NoLocaleClass)
|
||||
CC:SendMessage("ClassCacheQueryResult", result.Name, result.NoLocaleClass)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function CC:GetClassByName(name, realm)
|
||||
if not name or name == "" then return end
|
||||
if realm and realm == "" then return end
|
||||
|
||||
if E.db.general.classCacheStoreInDB then
|
||||
if realm then
|
||||
if self.cache[realm] and self.cache[realm][name] then
|
||||
return self.cache[realm][name]
|
||||
else
|
||||
return
|
||||
end
|
||||
else
|
||||
if self.cache[E.myrealm][name] then
|
||||
return self.cache[E.myrealm][name]
|
||||
end
|
||||
end
|
||||
else
|
||||
if realm then
|
||||
if self.tempCache[realm] and self.tempCache[realm][name] then
|
||||
return self.tempCache[realm][name]
|
||||
else
|
||||
return
|
||||
end
|
||||
else
|
||||
if self.tempCache[E.myrealm][name] then
|
||||
return self.tempCache[E.myrealm][name]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if E.db.general.classCacheRequestInfo then
|
||||
local result = LW:UserInfo(name, {
|
||||
queue = LW.WHOLIB_QUEUE_QUIET,
|
||||
timeout = 0,
|
||||
callback = function(result)
|
||||
WhoCallback(result)
|
||||
end
|
||||
})
|
||||
|
||||
if result and result.NoLocaleClass then
|
||||
self:CachePlayer(result.Name, result.NoLocaleClass)
|
||||
return result.NoLocaleClass
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function CC:CachePlayer(name, class, realm)
|
||||
if not (name and class and class ~= UNKNOWN) then return end
|
||||
|
||||
if realm and realm == "" then return end
|
||||
|
||||
if E.db.general.classCacheStoreInDB then
|
||||
if realm and not self.cache[realm] then
|
||||
self.cache[realm] = {}
|
||||
end
|
||||
|
||||
if realm then
|
||||
self.cache[realm][name] = class
|
||||
else
|
||||
self.cache[E.myrealm][name] = class
|
||||
end
|
||||
else
|
||||
if realm and not self.tempCache[realm] then
|
||||
self.tempCache[realm] = {}
|
||||
end
|
||||
|
||||
if realm then
|
||||
self.tempCache[realm][name] = class
|
||||
else
|
||||
self.tempCache[E.myrealm][name] = class
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function CC:SwitchCacheType(init)
|
||||
if E.db.general.classCacheStoreInDB then
|
||||
if not self.cache[E.myrealm] then
|
||||
self.cache[E.myrealm] = {}
|
||||
end
|
||||
|
||||
if not self.cache[E.myrealm][E.myname] then
|
||||
self.cache[E.myrealm][E.myname] = E.myclass
|
||||
end
|
||||
|
||||
if not init then
|
||||
for realm in pairs(self.tempCache) do
|
||||
if not self.cache[realm] then
|
||||
self.cache[realm] = {}
|
||||
end
|
||||
|
||||
for name, class in pairs(self.tempCache[realm]) do
|
||||
self.cache[realm][name] = class
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
if not self.tempCache[E.myrealm] then
|
||||
self.tempCache[E.myrealm] = {}
|
||||
end
|
||||
|
||||
if not self.tempCache[E.myrealm][E.myname] then
|
||||
self.tempCache[E.myrealm][E.myname] = E.myclass
|
||||
end
|
||||
|
||||
if not init then
|
||||
for realm in pairs(self.cache) do
|
||||
if not self.cache[realm] then
|
||||
self.tempCache[realm] = {}
|
||||
end
|
||||
|
||||
for name, class in pairs(self.cache[realm]) do
|
||||
self.tempCache[realm][name] = class
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function CC:GetCacheTable()
|
||||
if E.db.general.classCacheStoreInDB then
|
||||
return self.cache
|
||||
else
|
||||
return self.tempCache
|
||||
end
|
||||
end
|
||||
|
||||
function CC:GetCacheSize(global)
|
||||
if global and not (self.cacheDBCalculationTime + 30 < GetTime()) then
|
||||
return self.cacheDBSize > 1, self.cacheDBSize
|
||||
elseif not global and not (self.cacheLocalCalculationTime + 30 < GetTime()) then
|
||||
return self.cacheLocalSize > 1, self.cacheLocalSize
|
||||
end
|
||||
|
||||
local size = 0
|
||||
|
||||
if global then
|
||||
for realm in pairs(self.cache) do
|
||||
for name in pairs(self.cache[realm]) do
|
||||
size = size + 1
|
||||
end
|
||||
end
|
||||
|
||||
self.cacheDBSize = size
|
||||
self.cacheDBCalculationTime = GetTime()
|
||||
else
|
||||
for realm in pairs(self.tempCache) do
|
||||
for name in pairs(self.tempCache[realm]) do
|
||||
size = size + 1
|
||||
end
|
||||
end
|
||||
|
||||
self.cacheLocalSize = size
|
||||
self.cacheLocalCalculationTime = GetTime()
|
||||
end
|
||||
|
||||
return size > 1, size
|
||||
end
|
||||
|
||||
function CC:WipeCache(global)
|
||||
if global then
|
||||
for realm in pairs(self.cache) do
|
||||
wipe(realm)
|
||||
end
|
||||
|
||||
wipe(self.cache)
|
||||
self:SwitchCacheType(true)
|
||||
self.cacheDBCalculationTime = 0
|
||||
|
||||
E:Print(L["Class DB cache wiped."])
|
||||
else
|
||||
for realm in pairs(self.tempCache) do
|
||||
wipe(realm)
|
||||
end
|
||||
|
||||
wipe(self.tempCache)
|
||||
self:SwitchCacheType(true)
|
||||
self.cacheLocalCalculationTime = 0
|
||||
|
||||
E:Print(L["Class session cache wiped."])
|
||||
end
|
||||
end
|
||||
|
||||
function CC:PLAYER_ENTERING_WORLD()
|
||||
local inInstance, instanceType = IsInInstance()
|
||||
self.inInstance = inInstance
|
||||
|
||||
if instanceType == "arena" or instanceType == "pvp" then
|
||||
self.inBattleground = true
|
||||
else
|
||||
self.inBattleground = false
|
||||
end
|
||||
|
||||
if self.inInstance or self.inBattleground then
|
||||
self.lastNumPlayers = 0
|
||||
|
||||
self:UnregisterEvent("PLAYER_TARGET_CHANGED")
|
||||
self:UnregisterEvent("UPDATE_MOUSEOVER_UNIT")
|
||||
|
||||
self:UnregisterEvent("PARTY_MEMBERS_CHANGED")
|
||||
self:UnregisterEvent("RAID_ROSTER_UPDATE")
|
||||
|
||||
|
||||
self:RegisterEvent("UPDATE_BATTLEFIELD_SCORE")
|
||||
|
||||
if self.inBattleground then
|
||||
self:UPDATE_BATTLEFIELD_SCORE()
|
||||
end
|
||||
else
|
||||
self.lastNumPlayers = 0
|
||||
|
||||
self:RegisterEvent("PLAYER_TARGET_CHANGED")
|
||||
self:RegisterEvent("UPDATE_MOUSEOVER_UNIT")
|
||||
|
||||
self:RegisterEvent("PARTY_MEMBERS_CHANGED")
|
||||
self:RegisterEvent("RAID_ROSTER_UPDATE")
|
||||
|
||||
self:UnregisterEvent("UPDATE_BATTLEFIELD_SCORE")
|
||||
end
|
||||
|
||||
self:PLAYER_GUILD_UPDATE()
|
||||
|
||||
if not self.initUpdate then
|
||||
if GetNumRaidMembers() > 0 then
|
||||
self:RAID_ROSTER_UPDATE()
|
||||
elseif GetNumPartyMembers() > 0 then
|
||||
self:PARTY_MEMBERS_CHANGED()
|
||||
end
|
||||
|
||||
self:GUILD_ROSTER_UPDATE(nil, true)
|
||||
|
||||
self.initUpdate = true
|
||||
end
|
||||
end
|
||||
|
||||
function CC:PLAYER_GUILD_UPDATE()
|
||||
if IsInGuild() then
|
||||
self:RegisterEvent("GUILD_ROSTER_UPDATE")
|
||||
else
|
||||
self:UnregisterEvent("RAID_ROSTER_UPDATE")
|
||||
end
|
||||
end
|
||||
|
||||
function CC:FRIENDLIST_UPDATE()
|
||||
local name, class, _
|
||||
|
||||
for i = 1, GetNumFriends() do
|
||||
name, _, class = GetFriendInfo(i)
|
||||
|
||||
if class then
|
||||
self:CachePlayer(name, GetEnglishClassName(class))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function CC:GUILD_ROSTER_UPDATE(_, update)
|
||||
if not update then return end
|
||||
|
||||
local name, class, _
|
||||
|
||||
for i = 1, GetNumGuildMembers() do
|
||||
name, _, _, _, _, _, _, _, _, _, class = GetGuildRosterInfo(i)
|
||||
|
||||
if class then
|
||||
self:CachePlayer(name, class)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function CC:PARTY_MEMBERS_CHANGED()
|
||||
local name, realm, class, _
|
||||
|
||||
for i = 1, GetNumPartyMembers() do
|
||||
name, realm = UnitName("party"..i)
|
||||
_, class = UnitClass("party"..i)
|
||||
|
||||
if not class then return end
|
||||
|
||||
if self.inBattleground then
|
||||
self:CachePlayer(name, class, realm)
|
||||
else
|
||||
self:CachePlayer(name, class)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function CC:RAID_ROSTER_UPDATE()
|
||||
local name, realm, class, _
|
||||
|
||||
for i = 1, GetNumRaidMembers() do
|
||||
name, realm = UnitName("raid"..i)
|
||||
_, class = UnitClass("raid"..i)
|
||||
|
||||
if not class then return end
|
||||
|
||||
if self.inBattleground then
|
||||
self:CachePlayer(name, class, realm)
|
||||
else
|
||||
self:CachePlayer(name, class)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function CC:PLAYER_TARGET_CHANGED()
|
||||
if not UnitExists("target") or not UnitIsPlayer("target") then return end
|
||||
|
||||
local _, class = UnitClass("target")
|
||||
if not class then return end
|
||||
|
||||
local name, realm = UnitName("target")
|
||||
|
||||
if self.inBattleground then
|
||||
self:CachePlayer(name, class, realm)
|
||||
else
|
||||
self:CachePlayer(name, class)
|
||||
end
|
||||
end
|
||||
|
||||
function CC:UPDATE_MOUSEOVER_UNIT()
|
||||
if not UnitExists("mouseover") or not UnitIsPlayer("mouseover") then return end
|
||||
|
||||
local _, class = UnitClass("mouseover")
|
||||
if not class then return end
|
||||
|
||||
local name, realm = UnitName("mouseover")
|
||||
|
||||
if self.inBattleground then
|
||||
self:CachePlayer(name, class, realm)
|
||||
else
|
||||
self:CachePlayer(name, class)
|
||||
end
|
||||
end
|
||||
|
||||
function CC:UPDATE_BATTLEFIELD_SCORE()
|
||||
local numPlayers = GetNumBattlefieldScores() or 0
|
||||
|
||||
if self.lastNumPlayers == numPlayers then
|
||||
return
|
||||
elseif self.lastNumPlayers > numPlayers then
|
||||
self.lastNumPlayers = numPlayers
|
||||
return
|
||||
end
|
||||
|
||||
local name, realm, class, _
|
||||
|
||||
for i = 1, numPlayers do
|
||||
name, _, _, _, _, _, _, _, _, class = GetBattlefieldScore(i)
|
||||
|
||||
if name and class then
|
||||
name, realm = split("-", name)
|
||||
self:CachePlayer(name, class, realm)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function CC:WHOLIB_QUERY_RESULT(_, query, results, complete)
|
||||
for _, result in pairs(results) do
|
||||
if result and result.NoLocaleClass then
|
||||
self:CachePlayer(result.Name, result.NoLocaleClass)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function CC:ToggleModule()
|
||||
if E.private.general.classCache then
|
||||
if not self.initialized then
|
||||
self:SwitchCacheType(true)
|
||||
self.initialized = true
|
||||
end
|
||||
|
||||
self:RegisterEvent("PLAYER_ENTERING_WORLD")
|
||||
self:RegisterEvent("PLAYER_GUILD_UPDATE")
|
||||
|
||||
self:RegisterEvent("FRIENDLIST_UPDATE")
|
||||
self:RegisterEvent("PARTY_MEMBERS_CHANGED")
|
||||
self:RegisterEvent("RAID_ROSTER_UPDATE")
|
||||
|
||||
LW.RegisterCallback(self, "WHOLIB_QUERY_RESULT", "WHOLIB_QUERY_RESULT")
|
||||
else
|
||||
self:UnregisterAllEvents()
|
||||
LW.UnregisterAllCallbacks(self)
|
||||
end
|
||||
end
|
||||
|
||||
function CC:Initialize()
|
||||
self.cache = E.global.classCache
|
||||
self.tempCache = {}
|
||||
|
||||
self.cacheLocalCalculationTime = 0
|
||||
self.cacheDBCalculationTime = 0
|
||||
|
||||
LW:SetWhoLibDebug(false)
|
||||
|
||||
if E.private.general.classCache then
|
||||
self:ToggleModule()
|
||||
end
|
||||
end
|
||||
|
||||
local function InitializeCallback()
|
||||
CC:Initialize()
|
||||
end
|
||||
|
||||
E:RegisterModule(CC:GetName(), InitializeCallback)
|
||||
@@ -0,0 +1,130 @@
|
||||
local E, L, V, P, G = unpack(ElvUI); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
|
||||
|
||||
--Cache global variables
|
||||
--Lua functions
|
||||
local _G = _G
|
||||
local tonumber, type = tonumber, type
|
||||
local format, lower, match = string.format, string.lower, string.match
|
||||
--WoW API / Variables
|
||||
local UIFrameFadeOut, UIFrameFadeIn = UIFrameFadeOut, UIFrameFadeIn
|
||||
local EnableAddOn, DisableAddOn, DisableAllAddOns = EnableAddOn, DisableAddOn, DisableAllAddOns
|
||||
local SetCVar = SetCVar
|
||||
local ReloadUI = ReloadUI
|
||||
local GetAddOnInfo = GetAddOnInfo
|
||||
|
||||
function E:EnableAddon(addon)
|
||||
local _, _, _, _, _, reason, _ = GetAddOnInfo(addon)
|
||||
if reason ~= "MISSING" then
|
||||
EnableAddOn(addon)
|
||||
ReloadUI()
|
||||
else
|
||||
E:Print(format("Addon '%s' not found.", addon))
|
||||
end
|
||||
end
|
||||
|
||||
function E:DisableAddon(addon)
|
||||
local _, _, _, _, _, reason, _ = GetAddOnInfo(addon)
|
||||
if reason ~= "MISSING" then
|
||||
DisableAddOn(addon)
|
||||
ReloadUI()
|
||||
else
|
||||
E:Print(format("Addon '%s' not found.", addon))
|
||||
end
|
||||
end
|
||||
|
||||
function FarmMode()
|
||||
if E.private.general.minimap.enable ~= true then return end
|
||||
|
||||
if Minimap:IsShown() then
|
||||
UIFrameFadeOut(Minimap, 0.3)
|
||||
UIFrameFadeIn(FarmModeMap, 0.3)
|
||||
Minimap.fadeInfo.finishedFunc = function() Minimap:Hide() _G.MinimapZoomIn:Click() _G.MinimapZoomOut:Click() Minimap:SetAlpha(1) end
|
||||
FarmModeMap.enabled = true
|
||||
else
|
||||
UIFrameFadeOut(FarmModeMap, 0.3)
|
||||
UIFrameFadeIn(Minimap, 0.3)
|
||||
FarmModeMap.fadeInfo.finishedFunc = function() FarmModeMap:Hide() _G.MinimapZoomIn:Click() _G.MinimapZoomOut:Click() Minimap:SetAlpha(1) end
|
||||
FarmModeMap.enabled = false
|
||||
end
|
||||
end
|
||||
|
||||
function E:FarmMode(msg)
|
||||
if E.private.general.minimap.enable ~= true then return end
|
||||
if msg and type(tonumber(msg)) == "number" and tonumber(msg) <= 500 and tonumber(msg) >= 20 then
|
||||
E.db.farmSize = tonumber(msg)
|
||||
FarmModeMap:SetWidth(tonumber(msg))
|
||||
FarmModeMap:SetHeight(tonumber(msg))
|
||||
end
|
||||
|
||||
FarmMode()
|
||||
end
|
||||
|
||||
function E:Grid(msg)
|
||||
if msg and type(tonumber(msg)) == "number" and tonumber(msg) <= 256 and tonumber(msg) >= 4 then
|
||||
E.db.gridSize = msg
|
||||
E:Grid_Show()
|
||||
else
|
||||
if EGrid then
|
||||
E:Grid_Hide()
|
||||
else
|
||||
E:Grid_Show()
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function E:LuaError(msg)
|
||||
msg = lower(msg)
|
||||
if msg == "on" then
|
||||
DisableAllAddOns()
|
||||
EnableAddOn("ElvUI")
|
||||
EnableAddOn("ElvUI_Config")
|
||||
SetCVar("ShowErrors", "1")
|
||||
ReloadUI()
|
||||
elseif msg == "off" then
|
||||
SetCVar("ShowErrors", "0")
|
||||
E:Print("Lua errors off.")
|
||||
else
|
||||
E:Print("/luaerror on - /luaerror off")
|
||||
end
|
||||
end
|
||||
|
||||
function E:BGStats()
|
||||
local DT = E:GetModule("DataTexts")
|
||||
DT.ForceHideBGStats = nil
|
||||
DT:LoadDataTexts()
|
||||
|
||||
E:Print(L["Battleground datatexts will now show again if you are inside a battleground."])
|
||||
end
|
||||
|
||||
local function OnCallback(command)
|
||||
MacroEditBox:GetScript("OnEvent")(MacroEditBox, "EXECUTE_CHAT_LINE", command)
|
||||
end
|
||||
|
||||
function E:DelayScriptCall(msg)
|
||||
local secs, command = match(msg, "^([^%s]+)%s+(.*)$")
|
||||
secs = tonumber(secs)
|
||||
if (not secs) or (getn(command) == 0) then
|
||||
self:Print("usage: /in <seconds> <command>")
|
||||
self:Print("example: /in 1.5 /say hi")
|
||||
else
|
||||
E:ScheduleTimer(OnCallback, secs, command)
|
||||
end
|
||||
end
|
||||
|
||||
function E:LoadCommands()
|
||||
self:RegisterChatCommand("in", "DelayScriptCall")
|
||||
self:RegisterChatCommand("ec", "ToggleConfig")
|
||||
self:RegisterChatCommand("elvui", "ToggleConfig")
|
||||
self:RegisterChatCommand("bgstats", "BGStats")
|
||||
self:RegisterChatCommand("luaerror", "LuaError")
|
||||
self:RegisterChatCommand("egrid", "Grid")
|
||||
self:RegisterChatCommand("moveui", "ToggleConfigMode")
|
||||
self:RegisterChatCommand("resetui", "ResetUI")
|
||||
self:RegisterChatCommand("enable", "EnableAddon")
|
||||
self:RegisterChatCommand("disable", "DisableAddon")
|
||||
self:RegisterChatCommand("farmmode", "FarmMode")
|
||||
|
||||
-- if E:GetModule("ActionBars") and E.private.actionbar.enable then
|
||||
-- self:RegisterChatCommand("kb", E:GetModule("ActionBars").ActivateBindMode)
|
||||
-- end
|
||||
end
|
||||
@@ -0,0 +1,497 @@
|
||||
local E, L, V, P, G = unpack(ElvUI); -- Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
|
||||
|
||||
--Cache global variables
|
||||
--Lua functions
|
||||
local _G = _G
|
||||
local type, ipairs, tonumber = type, ipairs, tonumber
|
||||
local floor = math.floor
|
||||
--WoW API / Variables
|
||||
local CreateFrame = CreateFrame
|
||||
local IsAddOnLoaded = IsAddOnLoaded
|
||||
local GetScreenWidth = GetScreenWidth
|
||||
local GetScreenHeight = GetScreenHeight
|
||||
local RESET = RESET
|
||||
|
||||
local grid
|
||||
local selectedValue = "ALL"
|
||||
|
||||
E.ConfigModeLayouts = {
|
||||
"ALL",
|
||||
"GENERAL",
|
||||
"SOLO",
|
||||
"PARTY",
|
||||
"RAID",
|
||||
"ACTIONBARS"
|
||||
}
|
||||
|
||||
E.ConfigModeLocalizedStrings = {
|
||||
ALL = ALL,
|
||||
GENERAL = GENERAL,
|
||||
SOLO = SOLO,
|
||||
PARTY = PARTY,
|
||||
RAID = RAID,
|
||||
ACTIONBARS = ACTIONBAR_LABEL
|
||||
}
|
||||
|
||||
function E:Grid_Show()
|
||||
if not grid then
|
||||
E:Grid_Create()
|
||||
elseif grid.boxSize ~= E.db.gridSize then
|
||||
grid:Hide()
|
||||
E:Grid_Create()
|
||||
else
|
||||
grid:Show()
|
||||
end
|
||||
end
|
||||
|
||||
function E:Grid_Hide()
|
||||
if grid then
|
||||
grid:Hide()
|
||||
end
|
||||
end
|
||||
|
||||
function E:ToggleConfigMode(override, configType)
|
||||
if override ~= nil and override ~= "" then E.ConfigurationMode = override end
|
||||
|
||||
if E.ConfigurationMode ~= true then
|
||||
if not grid then
|
||||
E:Grid_Create()
|
||||
elseif grid.boxSize ~= E.db.gridSize then
|
||||
grid:Hide()
|
||||
E:Grid_Create()
|
||||
else
|
||||
grid:Show()
|
||||
end
|
||||
|
||||
if not ElvUIMoverPopupWindow then
|
||||
E:CreateMoverPopup()
|
||||
end
|
||||
|
||||
ElvUIMoverPopupWindow:Show()
|
||||
if(IsAddOnLoaded("ElvUI_Config")) then
|
||||
LibStub("AceConfigDialog-3.0"):Close("ElvUI")
|
||||
GameTooltip:Hide()
|
||||
end
|
||||
|
||||
E.ConfigurationMode = true
|
||||
else
|
||||
if ElvUIMoverPopupWindow then
|
||||
ElvUIMoverPopupWindow:Hide()
|
||||
end
|
||||
|
||||
if grid then
|
||||
grid:Hide()
|
||||
end
|
||||
|
||||
E.ConfigurationMode = false
|
||||
end
|
||||
|
||||
if type(configType) ~= "string" then
|
||||
configType = nil
|
||||
end
|
||||
|
||||
self:ToggleMovers(E.ConfigurationMode, configType or "ALL")
|
||||
end
|
||||
|
||||
function E:Grid_Create()
|
||||
grid = CreateFrame("Frame", "EGrid", UIParent)
|
||||
grid.boxSize = E.db.gridSize
|
||||
grid:SetAllPoints(E.UIParent)
|
||||
grid:Show()
|
||||
|
||||
local size = 1
|
||||
local width = E.eyefinity or GetScreenWidth()
|
||||
local ratio = width / GetScreenHeight()
|
||||
local height = GetScreenHeight() * ratio
|
||||
|
||||
local wStep = width / E.db.gridSize
|
||||
local hStep = height / E.db.gridSize
|
||||
|
||||
for i = 0, E.db.gridSize do
|
||||
local tx = grid:CreateTexture(nil, "BACKGROUND")
|
||||
if i == E.db.gridSize / 2 then
|
||||
tx:SetTexture(1, 0, 0)
|
||||
else
|
||||
tx:SetTexture(0, 0, 0)
|
||||
end
|
||||
tx:SetPoint("TOPLEFT", grid, "TOPLEFT", i*wStep - (size/2), 0)
|
||||
tx:SetPoint("BOTTOMRIGHT", grid, "BOTTOMLEFT", i*wStep + (size/2), 0)
|
||||
end
|
||||
height = GetScreenHeight()
|
||||
|
||||
do
|
||||
local tx = grid:CreateTexture(nil, "BACKGROUND")
|
||||
tx:SetTexture(1, 0, 0)
|
||||
tx:SetPoint("TOPLEFT", grid, "TOPLEFT", 0, -(height/2) + (size/2))
|
||||
tx:SetPoint("BOTTOMRIGHT", grid, "TOPRIGHT", 0, -(height/2 + size/2))
|
||||
end
|
||||
|
||||
for i = 1, floor((height/2)/hStep) do
|
||||
local tx = grid:CreateTexture(nil, "BACKGROUND")
|
||||
tx:SetTexture(0, 0, 0)
|
||||
|
||||
tx:SetPoint("TOPLEFT", grid, "TOPLEFT", 0, -(height/2+i*hStep) + (size/2))
|
||||
tx:SetPoint("BOTTOMRIGHT", grid, "TOPRIGHT", 0, -(height/2+i*hStep + size/2))
|
||||
|
||||
tx = grid:CreateTexture(nil, "BACKGROUND")
|
||||
tx:SetTexture(0, 0, 0)
|
||||
|
||||
tx:SetPoint("TOPLEFT", grid, "TOPLEFT", 0, -(height/2-i*hStep) + (size/2))
|
||||
tx:SetPoint("BOTTOMRIGHT", grid, "TOPRIGHT", 0, -(height/2-i*hStep + size/2))
|
||||
end
|
||||
end
|
||||
|
||||
local function ConfigMode_OnClick()
|
||||
selectedValue = this.value
|
||||
E:ToggleConfigMode(false, this.value)
|
||||
UIDropDownMenu_SetSelectedValue(ElvUIMoverPopupWindowDropDown, this.value)
|
||||
end
|
||||
|
||||
local function ConfigMode_Initialize()
|
||||
local info = {}
|
||||
info.func = ConfigMode_OnClick
|
||||
|
||||
for _, configMode in ipairs(E.ConfigModeLayouts) do
|
||||
info.text = E.ConfigModeLocalizedStrings[configMode]
|
||||
info.value = configMode
|
||||
UIDropDownMenu_AddButton(info)
|
||||
end
|
||||
|
||||
UIDropDownMenu_SetSelectedValue(ElvUIMoverPopupWindowDropDown, selectedValue)
|
||||
end
|
||||
|
||||
function E:NudgeMover(nudgeX, nudgeY)
|
||||
local mover = ElvUIMoverNudgeWindow.child
|
||||
|
||||
local x, y, point = E:CalculateMoverPoints(mover, nudgeX, nudgeY)
|
||||
|
||||
mover:ClearAllPoints()
|
||||
mover:SetPoint(mover.positionOverride or point, E.UIParent, mover.positionOverride and "BOTTOMLEFT" or point, x, y)
|
||||
E:SaveMoverPosition(mover.name)
|
||||
|
||||
E:UpdateNudgeFrame(mover, x, y)
|
||||
end
|
||||
|
||||
function E:UpdateNudgeFrame(mover, x, y)
|
||||
if not(x and y) then
|
||||
x, y = E:CalculateMoverPoints(mover)
|
||||
end
|
||||
|
||||
x = E:Round(x, 0)
|
||||
y = E:Round(y, 0)
|
||||
|
||||
ElvUIMoverNudgeWindow.xOffset:SetText(x)
|
||||
ElvUIMoverNudgeWindow.yOffset:SetText(y)
|
||||
ElvUIMoverNudgeWindow.xOffset.currentValue = x
|
||||
ElvUIMoverNudgeWindow.yOffset.currentValue = y
|
||||
ElvUIMoverNudgeWindowHeader.title:SetText(mover.textString)
|
||||
end
|
||||
|
||||
function E:AssignFrameToNudge()
|
||||
ElvUIMoverNudgeWindow.child = self
|
||||
E:UpdateNudgeFrame(self)
|
||||
end
|
||||
|
||||
function E:CreateMoverPopup()
|
||||
local f = CreateFrame("Frame", "ElvUIMoverPopupWindow", UIParent)
|
||||
f:SetFrameStrata("DIALOG")
|
||||
f:SetToplevel(true)
|
||||
f:EnableMouse(true)
|
||||
f:SetMovable(true)
|
||||
f:SetFrameLevel(99)
|
||||
f:SetClampedToScreen(true)
|
||||
f:SetWidth(360)
|
||||
f:SetHeight(170)
|
||||
E:SetTemplate(f, "Transparent")
|
||||
f:SetPoint("BOTTOM", UIParent, "CENTER", 0, 100)
|
||||
f:SetScript("OnHide", function()
|
||||
if ElvUIMoverPopupWindowDropDown then
|
||||
UIDropDownMenu_SetSelectedValue(ElvUIMoverPopupWindowDropDown, "ALL")
|
||||
end
|
||||
end)
|
||||
f:Hide()
|
||||
|
||||
local S = E:GetModule("Skins")
|
||||
|
||||
local header = CreateFrame("Button", nil, f)
|
||||
E:SetTemplate(header, "Default", true)
|
||||
header:SetWidth(100) header:SetHeight(25)
|
||||
header:SetPoint("CENTER", f, "TOP")
|
||||
header:SetFrameLevel(header:GetFrameLevel() + 2)
|
||||
header:EnableMouse(true)
|
||||
header:RegisterForClicks("AnyUp", "AnyDown")
|
||||
header:SetScript("OnMouseDown", function() f:StartMoving() end)
|
||||
header:SetScript("OnMouseUp", function() f:StopMovingOrSizing() end)
|
||||
|
||||
local title = header:CreateFontString("OVERLAY")
|
||||
E:FontTemplate(title)
|
||||
title:SetPoint("CENTER", header, "CENTER")
|
||||
title:SetText("ElvUI")
|
||||
|
||||
local desc = f:CreateFontString("ARTWORK")
|
||||
desc:SetFontObject("GameFontHighlight")
|
||||
desc:SetJustifyV("TOP")
|
||||
desc:SetJustifyH("LEFT")
|
||||
desc:SetPoint("TOPLEFT", 18, -32)
|
||||
desc:SetPoint("BOTTOMRIGHT", -18, 48)
|
||||
desc:SetText(L["DESC_MOVERCONFIG"])
|
||||
|
||||
local snapping = CreateFrame("CheckButton", f:GetName().."CheckButton", f, "OptionsCheckButtonTemplate")
|
||||
_G[snapping:GetName().."Text"]:SetText(L["Sticky Frames"])
|
||||
|
||||
snapping:SetScript("OnShow", function()
|
||||
this:SetChecked(E.db.general.stickyFrames)
|
||||
end)
|
||||
|
||||
snapping:SetScript("OnClick", function()
|
||||
E.db.general.stickyFrames = this:GetChecked()
|
||||
end)
|
||||
|
||||
local lock = CreateFrame("Button", f:GetName().."CloseButton", f, "OptionsButtonTemplate")
|
||||
_G[lock:GetName().."Text"]:SetText(L["Lock"])
|
||||
|
||||
lock:SetScript("OnClick", function()
|
||||
E:ToggleConfigMode(true)
|
||||
|
||||
if(IsAddOnLoaded("ElvUI_Config")) then
|
||||
LibStub("AceConfigDialog-3.0"):Open("ElvUI")
|
||||
end
|
||||
|
||||
selectedValue = "ALL"
|
||||
UIDropDownMenu_SetSelectedValue(ElvUIMoverPopupWindowDropDown, selectedValue)
|
||||
end)
|
||||
|
||||
local align = CreateFrame("EditBox", f:GetName().."EditBox", f, "InputBoxTemplate")
|
||||
align:SetWidth(32)
|
||||
align:SetHeight(17)
|
||||
align:SetAutoFocus(false)
|
||||
align:SetScript("OnEscapePressed", function()
|
||||
this:SetText(E.db.gridSize)
|
||||
this:ClearFocus()
|
||||
end)
|
||||
align:SetScript("OnEnterPressed", function()
|
||||
local text = this:GetText()
|
||||
if tonumber(text) then
|
||||
if tonumber(text) <= 256 and tonumber(text) >= 4 then
|
||||
E.db.gridSize = tonumber(text)
|
||||
else
|
||||
this:SetText(E.db.gridSize)
|
||||
end
|
||||
else
|
||||
this:SetText(E.db.gridSize)
|
||||
end
|
||||
E:Grid_Show()
|
||||
this:ClearFocus()
|
||||
end)
|
||||
align:SetScript("OnEditFocusLost", function()
|
||||
this:SetText(E.db.gridSize)
|
||||
end)
|
||||
align:SetScript("OnShow", function()
|
||||
this:ClearFocus()
|
||||
this:SetText(E.db.gridSize)
|
||||
end)
|
||||
|
||||
align.text = align:CreateFontString(nil, "OVERLAY", "GameFontNormal")
|
||||
align.text:SetPoint("RIGHT", align, "LEFT", -4, 0)
|
||||
align.text:SetText(L["Grid Size:"])
|
||||
|
||||
--position buttons
|
||||
snapping:SetPoint("BOTTOMLEFT", 14, 10)
|
||||
lock:SetPoint("BOTTOMRIGHT", -14, 14)
|
||||
align:SetPoint("TOPRIGHT", lock, "TOPLEFT", -4, -2)
|
||||
|
||||
S:HandleCheckBox(snapping)
|
||||
S:HandleButton(lock)
|
||||
S:HandleEditBox(align)
|
||||
|
||||
f:RegisterEvent("PLAYER_REGEN_DISABLED")
|
||||
f:SetScript("OnEvent", function()
|
||||
if this:IsShown() then
|
||||
this:Hide()
|
||||
E:Grid_Hide()
|
||||
E:ToggleConfigMode(true)
|
||||
end
|
||||
end)
|
||||
|
||||
local configMode = CreateFrame("Frame", f:GetName().."DropDown", f, "UIDropDownMenuTemplate")
|
||||
configMode:SetPoint("BOTTOMRIGHT", lock, "TOPRIGHT", 8, -5)
|
||||
S:HandleDropDownBox(configMode, 148)
|
||||
configMode.text = configMode:CreateFontString(nil, "OVERLAY", "GameFontNormal")
|
||||
configMode.text:SetPoint("RIGHT", configMode.backdrop, "LEFT", -2, 0)
|
||||
configMode.text:SetText(L["Config Mode:"])
|
||||
|
||||
UIDropDownMenu_Initialize(configMode, ConfigMode_Initialize)
|
||||
|
||||
local nudgeFrame = CreateFrame("Frame", "ElvUIMoverNudgeWindow", E.UIParent)
|
||||
nudgeFrame:SetFrameStrata("DIALOG")
|
||||
nudgeFrame:SetWidth(200)
|
||||
nudgeFrame:SetHeight(110)
|
||||
E:SetTemplate(nudgeFrame, "Transparent")
|
||||
nudgeFrame:SetPoint("TOP", ElvUIMoverPopupWindow, "BOTTOM", 0, -15)
|
||||
nudgeFrame:SetFrameLevel(100)
|
||||
nudgeFrame:Hide()
|
||||
nudgeFrame:EnableMouse(true)
|
||||
nudgeFrame:SetClampedToScreen(true)
|
||||
HookScript(ElvUIMoverPopupWindow, "OnHide", function() ElvUIMoverNudgeWindow:Hide() end)
|
||||
|
||||
header = CreateFrame("Button", "ElvUIMoverNudgeWindowHeader", nudgeFrame)
|
||||
E:SetTemplate(header, "Default", true)
|
||||
header:SetWidth(100) header:SetHeight(25)
|
||||
header:SetPoint("CENTER", nudgeFrame, "TOP")
|
||||
header:SetFrameLevel(header:GetFrameLevel() + 2)
|
||||
|
||||
title = header:CreateFontString("OVERLAY")
|
||||
E:FontTemplate(title)
|
||||
title:SetPoint("CENTER", header, "CENTER")
|
||||
title:SetText(L["Nudge"])
|
||||
header.title = title
|
||||
|
||||
local xOffset = CreateFrame("EditBox", nudgeFrame:GetName().."XEditBox", nudgeFrame, "InputBoxTemplate")
|
||||
xOffset:SetWidth(50)
|
||||
xOffset:SetHeight(17)
|
||||
xOffset:SetAutoFocus(false)
|
||||
xOffset.currentValue = 0
|
||||
xOffset:SetScript("OnEscapePressed", function()
|
||||
this:SetText(E:Round(xOffset.currentValue))
|
||||
this:ClearFocus()
|
||||
end)
|
||||
xOffset:SetScript("OnEnterPressed", function()
|
||||
local num = this:GetText()
|
||||
if(tonumber(num)) then
|
||||
local diff = num - xOffset.currentValue
|
||||
xOffset.currentValue = num
|
||||
E:NudgeMover(diff)
|
||||
end
|
||||
this:SetText(E:Round(xOffset.currentValue))
|
||||
this:ClearFocus()
|
||||
end)
|
||||
xOffset:SetScript("OnEditFocusLost", function()
|
||||
this:SetText(E:Round(xOffset.currentValue))
|
||||
end)
|
||||
xOffset:SetScript("OnShow", function()
|
||||
this:ClearFocus()
|
||||
this:SetText(E:Round(xOffset.currentValue))
|
||||
end)
|
||||
|
||||
xOffset.text = xOffset:CreateFontString(nil, "OVERLAY", "GameFontNormal")
|
||||
xOffset.text:SetPoint("RIGHT", xOffset, "LEFT", -4, 0)
|
||||
xOffset.text:SetText("X:")
|
||||
xOffset:SetPoint("BOTTOMRIGHT", nudgeFrame, "CENTER", -6, 8)
|
||||
nudgeFrame.xOffset = xOffset
|
||||
S:HandleEditBox(xOffset)
|
||||
|
||||
local yOffset = CreateFrame("EditBox", nudgeFrame:GetName().."YEditBox", nudgeFrame, "InputBoxTemplate")
|
||||
yOffset:SetWidth(50)
|
||||
yOffset:SetHeight(17)
|
||||
yOffset:SetAutoFocus(false)
|
||||
yOffset.currentValue = 0
|
||||
yOffset:SetScript("OnEscapePressed", function()
|
||||
this:SetText(E:Round(yOffset.currentValue))
|
||||
this:ClearFocus()
|
||||
end)
|
||||
yOffset:SetScript("OnEnterPressed", function()
|
||||
local num = this:GetText()
|
||||
if(tonumber(num)) then
|
||||
local diff = num - yOffset.currentValue
|
||||
yOffset.currentValue = num
|
||||
E:NudgeMover(nil, diff)
|
||||
end
|
||||
this:SetText(E:Round(yOffset.currentValue))
|
||||
this:ClearFocus()
|
||||
end)
|
||||
yOffset:SetScript("OnEditFocusLost", function()
|
||||
this:SetText(E:Round(yOffset.currentValue))
|
||||
end)
|
||||
yOffset:SetScript("OnShow", function()
|
||||
this:ClearFocus()
|
||||
this:SetText(E:Round(yOffset.currentValue))
|
||||
end)
|
||||
|
||||
yOffset.text = yOffset:CreateFontString(nil, "OVERLAY", "GameFontNormal")
|
||||
yOffset.text:SetPoint("RIGHT", yOffset, "LEFT", -4, 0)
|
||||
yOffset.text:SetText("Y:")
|
||||
yOffset:SetPoint("BOTTOMLEFT", nudgeFrame, "CENTER", 16, 8)
|
||||
nudgeFrame.yOffset = yOffset
|
||||
S:HandleEditBox(yOffset)
|
||||
|
||||
local resetButton = CreateFrame("Button", nudgeFrame:GetName().."ResetButton", nudgeFrame, "UIPanelButtonTemplate")
|
||||
resetButton:SetText(RESET)
|
||||
resetButton:SetPoint("TOP", nudgeFrame, "CENTER", 0, 2)
|
||||
resetButton:SetWidth(100)
|
||||
resetButton:SetHeight(25)
|
||||
resetButton:SetScript("OnClick", function()
|
||||
if(ElvUIMoverNudgeWindow.child.textString) then
|
||||
E:ResetMovers(ElvUIMoverNudgeWindow.child.textString)
|
||||
E:UpdateNudgeFrame(ElvUIMoverNudgeWindow.child)
|
||||
end
|
||||
end)
|
||||
S:HandleButton(resetButton)
|
||||
-- Up Button
|
||||
local upButton = CreateFrame("Button", nudgeFrame:GetName().."PrevButton", nudgeFrame)
|
||||
upButton:SetWidth(26)
|
||||
upButton:SetHeight(26)
|
||||
upButton:SetPoint("BOTTOMRIGHT", nudgeFrame, "BOTTOM", -6, 4)
|
||||
upButton:SetScript("OnClick", function()
|
||||
E:NudgeMover(nil, 1)
|
||||
end)
|
||||
upButton.icon = upButton:CreateTexture(nil, "ARTWORK")
|
||||
upButton.icon:SetWidth(13)
|
||||
upButton.icon:SetHeight(13)
|
||||
upButton.icon:SetPoint("CENTER", 0, 0)
|
||||
upButton.icon:SetTexture([[Interface\AddOns\ElvUI\Media\Textures\SquareButtonTextures.blp]])
|
||||
upButton.icon:SetTexCoord(0.01562500, 0.20312500, 0.01562500, 0.20312500)
|
||||
|
||||
S:SquareButton_SetIcon(upButton, "UP")
|
||||
S:HandleButton(upButton)
|
||||
-- Down Button
|
||||
local downButton = CreateFrame("Button", nudgeFrame:GetName().."DownButton", nudgeFrame)
|
||||
downButton:SetWidth(26)
|
||||
downButton:SetHeight(26)
|
||||
downButton:SetPoint("BOTTOMLEFT", nudgeFrame, "BOTTOM", 6, 4)
|
||||
downButton:SetScript("OnClick", function()
|
||||
E:NudgeMover(nil, -1)
|
||||
end)
|
||||
downButton.icon = downButton:CreateTexture(nil, "ARTWORK")
|
||||
downButton.icon:SetWidth(13)
|
||||
downButton.icon:SetHeight(13)
|
||||
downButton.icon:SetPoint("CENTER", 0, 0)
|
||||
downButton.icon:SetTexture([[Interface\AddOns\ElvUI\Media\Textures\SquareButtonTextures.blp]])
|
||||
downButton.icon:SetTexCoord(0.01562500, 0.20312500, 0.01562500, 0.20312500)
|
||||
|
||||
S:SquareButton_SetIcon(downButton, "DOWN")
|
||||
S:HandleButton(downButton)
|
||||
-- Left Button
|
||||
local leftButton = CreateFrame("Button", nudgeFrame:GetName().."LeftButton", nudgeFrame)
|
||||
leftButton:SetWidth(26)
|
||||
leftButton:SetHeight(26)
|
||||
leftButton:SetPoint("RIGHT", upButton, "LEFT", -6, 0)
|
||||
leftButton:SetScript("OnClick", function()
|
||||
E:NudgeMover(-1)
|
||||
end)
|
||||
leftButton.icon = leftButton:CreateTexture(nil, "ARTWORK")
|
||||
leftButton.icon:SetWidth(13)
|
||||
leftButton.icon:SetHeight(13)
|
||||
leftButton.icon:SetPoint("CENTER", 0, 0)
|
||||
leftButton.icon:SetTexture([[Interface\AddOns\ElvUI\Media\Textures\SquareButtonTextures.blp]])
|
||||
leftButton.icon:SetTexCoord(0.01562500, 0.20312500, 0.01562500, 0.20312500)
|
||||
|
||||
S:SquareButton_SetIcon(leftButton, "LEFT")
|
||||
S:HandleButton(leftButton)
|
||||
-- Right Button
|
||||
local rightButton = CreateFrame("Button", nudgeFrame:GetName().."RightButton", nudgeFrame)
|
||||
rightButton:SetWidth(26)
|
||||
rightButton:SetHeight(26)
|
||||
rightButton:SetPoint("LEFT", downButton, "RIGHT", 6, 0)
|
||||
rightButton:SetScript("OnClick", function()
|
||||
E:NudgeMover(1)
|
||||
end)
|
||||
rightButton.icon = rightButton:CreateTexture(nil, "ARTWORK")
|
||||
rightButton.icon:SetWidth(13)
|
||||
rightButton.icon:SetHeight(13)
|
||||
rightButton.icon:SetPoint("CENTER", 0, 0)
|
||||
rightButton.icon:SetTexture([[Interface\AddOns\ElvUI\Media\Textures\SquareButtonTextures.blp]])
|
||||
rightButton.icon:SetTexCoord(0.01562500, 0.20312500, 0.01562500, 0.20312500)
|
||||
|
||||
S:SquareButton_SetIcon(rightButton, "RIGHT")
|
||||
S:HandleButton(rightButton)
|
||||
end
|
||||
@@ -0,0 +1,140 @@
|
||||
local E, L, V, P, G = unpack(ElvUI); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
|
||||
|
||||
--Cache global variables
|
||||
--Lua functions
|
||||
local floor = math.floor
|
||||
local format = string.format
|
||||
local GetTime = GetTime
|
||||
--WoW API / Variables
|
||||
local CreateFrame = CreateFrame
|
||||
local hooksecurefunc = hooksecurefunc
|
||||
|
||||
local ICON_SIZE = 36 --the normal size for an icon (don't change this)
|
||||
local FONT_SIZE = 20 --the base font size to use at a scale of 1
|
||||
local MIN_SCALE = 0.5 --the minimum scale we want to show cooldown counts at, anything below this will be hidden
|
||||
local MIN_DURATION = 1.5 --the minimum duration to show cooldown text for
|
||||
|
||||
local TimeColors = {
|
||||
[0] = "|cfffefefe",
|
||||
[1] = "|cfffefefe",
|
||||
[2] = "|cfffefefe",
|
||||
[3] = "|cfffefefe",
|
||||
[4] = "|cfffe0000"
|
||||
}
|
||||
|
||||
local function Cooldown_OnUpdate(cd, elapsed)
|
||||
if cd.nextUpdate > 0 then
|
||||
cd.nextUpdate = cd.nextUpdate - elapsed
|
||||
return
|
||||
end
|
||||
|
||||
local remain = cd.duration - (GetTime() - cd.start)
|
||||
if remain > 0.05 then
|
||||
if (cd.fontScale * cd:GetEffectiveScale() / UIParent:GetScale()) < MIN_SCALE then
|
||||
cd.text:SetText("")
|
||||
cd.nextUpdate = 500
|
||||
else
|
||||
local timervalue, formatid
|
||||
timervalue, formatid, cd.nextUpdate = E:GetTimeInfo(remain, E.db.cooldown.threshold)
|
||||
cd.text:SetText(format("%s%s|r", TimeColors[formatid], format(E.TimeFormats[formatid][2], timervalue)))
|
||||
end
|
||||
else
|
||||
E:Cooldown_StopTimer(cd)
|
||||
end
|
||||
end
|
||||
|
||||
function E:Cooldown_OnSizeChanged(cd, width)
|
||||
local fontScale = floor(width +.5) / ICON_SIZE
|
||||
local override = cd:GetParent():GetParent().SizeOverride
|
||||
if override then
|
||||
fontScale = override / FONT_SIZE
|
||||
end
|
||||
|
||||
if fontScale == cd.fontScale then
|
||||
return
|
||||
end
|
||||
|
||||
cd.fontScale = fontScale
|
||||
if fontScale < MIN_SCALE and not override then
|
||||
cd:Hide()
|
||||
else
|
||||
cd:Show()
|
||||
E:FontTemplate(cd.text, nil, fontScale * FONT_SIZE, "OUTLINE")
|
||||
if cd.enabled then
|
||||
self:Cooldown_ForceUpdate(cd)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function E:Cooldown_ForceUpdate(cd)
|
||||
cd.nextUpdate = 0
|
||||
cd:Show()
|
||||
end
|
||||
|
||||
function E:Cooldown_StopTimer(cd)
|
||||
cd.enabled = nil
|
||||
cd:Hide()
|
||||
end
|
||||
|
||||
function E:CreateCooldownTimer(parent)
|
||||
local scaler = CreateFrame("Frame", nil, parent)
|
||||
scaler:SetAllPoints()
|
||||
|
||||
local timer = CreateFrame("Frame", nil, scaler)
|
||||
timer:Hide()
|
||||
timer:SetAllPoints()
|
||||
timer:SetScript("OnUpdate", function() Cooldown_OnUpdate(this, arg1) end)
|
||||
|
||||
local text = timer:CreateFontString(nil, "OVERLAY")
|
||||
text:SetPoint("CENTER", 1, 1)
|
||||
text:SetJustifyH("CENTER")
|
||||
timer.text = text
|
||||
|
||||
self:Cooldown_OnSizeChanged(timer, parent:GetWidth(), parent:GetHeight())
|
||||
parent:SetScript("OnSizeChanged", function() self:Cooldown_OnSizeChanged(timer, parent:GetWidth(), parent:GetHeight()) end)
|
||||
|
||||
parent.timer = timer
|
||||
return timer
|
||||
end
|
||||
|
||||
function E:OnSetCooldown(start, duration, enable)
|
||||
if self.noOCC then return end
|
||||
|
||||
if start > 0 and duration > MIN_DURATION and enable > 0 then
|
||||
local timer = self.timer or E:CreateCooldownTimer(self)
|
||||
timer.start = start
|
||||
timer.duration = duration
|
||||
timer.enabled = true
|
||||
timer.nextUpdate = 0
|
||||
if timer.fontScale >= MIN_SCALE then timer:Show() end
|
||||
else
|
||||
local timer = self.timer
|
||||
if timer then
|
||||
E:Cooldown_StopTimer(timer)
|
||||
return
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function E:RegisterCooldown(cooldown)
|
||||
if not E.private.cooldown.enable or cooldown.isHooked then return end
|
||||
hooksecurefunc("CooldownFrame_SetTimer", E.OnSetCooldown)
|
||||
cooldown.isHooked = true
|
||||
end
|
||||
|
||||
function E:UpdateCooldownSettings()
|
||||
local color = self.db.cooldown.expiringColor
|
||||
TimeColors[4] = E:RGBToHex(color.r, color.g, color.b) -- color for timers that are soon to expire
|
||||
|
||||
color = self.db.cooldown.secondsColor
|
||||
TimeColors[3] = E:RGBToHex(color.r, color.g, color.b) -- color for timers that have seconds remaining
|
||||
|
||||
color = self.db.cooldown.minutesColor
|
||||
TimeColors[2] = E:RGBToHex(color.r, color.g, color.b) -- color for timers that have minutes remaining
|
||||
|
||||
color = self.db.cooldown.hoursColor
|
||||
TimeColors[1] = E:RGBToHex(color.r, color.g, color.b) -- color for timers that have hours remaining
|
||||
|
||||
color = self.db.cooldown.daysColor
|
||||
TimeColors[0] = E:RGBToHex(color.r, color.g, color.b) -- color for timers that have days remaining
|
||||
end
|
||||
@@ -0,0 +1,18 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="Math.lua"/>
|
||||
<Script file="core.lua"/>
|
||||
<Script file="fonts.lua"/>
|
||||
<Script file="install.lua"/>
|
||||
<Script file="pixelperfect.lua"/>
|
||||
<Script file="toolkit.lua"/>
|
||||
<Script file="Commands.lua"/>
|
||||
<Script file="StaticPopups.lua"/>
|
||||
<Script file="Movers.lua"/>
|
||||
<Script file="Config.lua"/>
|
||||
<Script file="tutorials.lua"/>
|
||||
<Script file="distributor.lua"/>
|
||||
<Script file="dropdown.lua"/>
|
||||
<Script file="Cooldowns.lua"/>
|
||||
<Script file="pluginInstaller.lua"/>
|
||||
<Script file="ClassCache.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,421 @@
|
||||
local E, L, V, P, G = unpack(ElvUI); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
|
||||
|
||||
--Cache global variables
|
||||
--Lua functions
|
||||
local select, unpack, assert, tonumber, type, pairs = select, unpack, assert, tonumber, type, pairs
|
||||
local getn, tinsert, tremove = table.getn, tinsert, tremove
|
||||
local abs, ceil, floor, modf, mod = math.abs, math.ceil, math.floor, math.modf, math.mod
|
||||
local find, format, byte, len, sub, gsub, upper, split, utf8sub = string.find, string.format, string.byte, string.len, string.sub, string.gsub, string.upper, string.split, string.utf8sub
|
||||
--WoW API / Variables
|
||||
local GetScreenWidth, GetScreenHeight = GetScreenWidth, GetScreenHeight
|
||||
local CreateFrame = CreateFrame
|
||||
|
||||
--Return short value of a number
|
||||
local shortValueDec
|
||||
function E:ShortValue(v)
|
||||
shortValueDec = format("%%.%df", E.db.general.decimalLength or 1)
|
||||
if E.db.general.numberPrefixStyle == "METRIC" then
|
||||
if abs(v) >= 1e9 then
|
||||
return format(shortValueDec.."G", v / 1e9)
|
||||
elseif abs(v) >= 1e6 then
|
||||
return format(shortValueDec.."M", v / 1e6)
|
||||
elseif abs(v) >= 1e3 then
|
||||
return format(shortValueDec.."k", v / 1e3)
|
||||
else
|
||||
return format("%s", v)
|
||||
end
|
||||
elseif E.db.general.numberPrefixStyle == "CHINESE" then
|
||||
if abs(v) >= 1e8 then
|
||||
return format(shortValueDec.."Y", v / 1e8)
|
||||
elseif abs(v) >= 1e4 then
|
||||
return format(shortValueDec.."W", v / 1e4)
|
||||
else
|
||||
return format("%s", v)
|
||||
end
|
||||
elseif E.db.general.numberPrefixStyle == "KOREAN" then
|
||||
if abs(v) >= 1e8 then
|
||||
return format(shortValueDec.."억", v / 1e8)
|
||||
elseif abs(v) >= 1e4 then
|
||||
return format(shortValueDec.."만", v / 1e4)
|
||||
elseif abs(v) >= 1e3 then
|
||||
return format(shortValueDec.."천", v / 1e3)
|
||||
else
|
||||
return format("%s", v)
|
||||
end
|
||||
elseif E.db.general.numberPrefixStyle == "GERMAN" then
|
||||
if abs(v) >= 1e9 then
|
||||
return format(shortValueDec.."Mrd", v / 1e9)
|
||||
elseif abs(v) >= 1e6 then
|
||||
return format(shortValueDec.."Mio", v / 1e6)
|
||||
elseif abs(v) >= 1e3 then
|
||||
return format(shortValueDec.."Tsd", v / 1e3)
|
||||
else
|
||||
return format("%s", v)
|
||||
end
|
||||
else
|
||||
if abs(v) >= 1e9 then
|
||||
return format(shortValueDec.."B", v / 1e9)
|
||||
elseif abs(v) >= 1e6 then
|
||||
return format(shortValueDec.."M", v / 1e6)
|
||||
elseif abs(v) >= 1e3 then
|
||||
return format(shortValueDec.."K", v / 1e3)
|
||||
else
|
||||
return format("%s", v)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function E:IsEvenNumber(num)
|
||||
return mod(num, 2) == 0
|
||||
end
|
||||
|
||||
function E:ColorGradient(perc, r1, g1, b1, r2, g2, b2, r3, g3, b3)
|
||||
if perc >= 1 then
|
||||
return r3, g3, b3
|
||||
elseif perc <= 0 then
|
||||
return r1, g1, b1
|
||||
end
|
||||
|
||||
local segment, relperc = modf(perc)
|
||||
if segment > 0 then
|
||||
r1, g1, b1, r2, g2, b2 = r2, g2, b2, r3, g3, b3
|
||||
end
|
||||
|
||||
return r1 + (r2-r1)*relperc, g1 + (g2-g1)*relperc, b1 + (b2-b1)*relperc
|
||||
end
|
||||
|
||||
function E:Round(num, idp)
|
||||
if idp and idp > 0 then
|
||||
local mult = 10 ^ idp
|
||||
return floor(num * mult + 0.5) / mult
|
||||
end
|
||||
return floor(num + 0.5)
|
||||
end
|
||||
|
||||
function E:Truncate(v, decimals)
|
||||
return v - (mod(v, 0.1 ^ (decimals or 0)))
|
||||
end
|
||||
|
||||
function E:RGBToHex(r, g, b)
|
||||
r = r <= 1 and r >= 0 and r or 0
|
||||
g = g <= 1 and g >= 0 and g or 0
|
||||
b = b <= 1 and b >= 0 and b or 0
|
||||
return format("|cff%02x%02x%02x", r*255, g*255, b*255)
|
||||
end
|
||||
|
||||
function E:HexToRGB(hex)
|
||||
local rhex, ghex, bhex = sub(hex, 1, 2), sub(hex, 3, 4), sub(hex, 5, 6)
|
||||
return tonumber(rhex, 16), tonumber(ghex, 16), tonumber(bhex, 16)
|
||||
end
|
||||
|
||||
function E:FramesOverlap(frameA, frameB)
|
||||
if not frameA or not frameB then return end
|
||||
|
||||
local sA, sB = frameA:GetEffectiveScale(), frameB:GetEffectiveScale()
|
||||
if not sA or not sB then return end
|
||||
|
||||
local frameALeft = frameA:GetLeft()
|
||||
local frameARight = frameA:GetRight()
|
||||
local frameABottom = frameA:GetBottom()
|
||||
local frameATop = frameA:GetTop()
|
||||
|
||||
local frameBLeft = frameB:GetLeft()
|
||||
local frameBRight = frameB:GetRight()
|
||||
local frameBBottom = frameB:GetBottom()
|
||||
local frameBTop = frameB:GetTop()
|
||||
|
||||
if not frameALeft or not frameARight or not frameABottom or not frameATop then return end
|
||||
if not frameBLeft or not frameBRight or not frameBBottom or not frameBTop then return end
|
||||
|
||||
return ((frameALeft*sA) < (frameBRight*sB))
|
||||
and ((frameBLeft*sB) < (frameARight*sA))
|
||||
and ((frameABottom*sA) < (frameBTop*sB))
|
||||
and ((frameBBottom*sB) < (frameATop*sA))
|
||||
end
|
||||
|
||||
function E:GetScreenQuadrant(frame)
|
||||
local x, y = frame:GetCenter()
|
||||
local screenWidth = GetScreenWidth()
|
||||
local screenHeight = GetScreenHeight()
|
||||
local point
|
||||
|
||||
if not frame:GetCenter() then
|
||||
return "UNKNOWN", frame:GetName()
|
||||
end
|
||||
|
||||
if (x > (screenWidth / 3) and x < (screenWidth / 3)*2) and y > (screenHeight / 3)*2 then
|
||||
point = "TOP"
|
||||
elseif x < (screenWidth / 3) and y > (screenHeight / 3)*2 then
|
||||
point = "TOPLEFT"
|
||||
elseif x > (screenWidth / 3)*2 and y > (screenHeight / 3)*2 then
|
||||
point = "TOPRIGHT"
|
||||
elseif (x > (screenWidth / 3) and x < (screenWidth / 3)*2) and y < (screenHeight / 3) then
|
||||
point = "BOTTOM"
|
||||
elseif x < (screenWidth / 3) and y < (screenHeight / 3) then
|
||||
point = "BOTTOMLEFT"
|
||||
elseif x > (screenWidth / 3)*2 and y < (screenHeight / 3) then
|
||||
point = "BOTTOMRIGHT"
|
||||
elseif x < (screenWidth / 3) and (y > (screenHeight / 3) and y < (screenHeight / 3)*2) then
|
||||
point = "LEFT"
|
||||
elseif x > (screenWidth / 3)*2 and y < (screenHeight / 3)*2 and y > (screenHeight / 3) then
|
||||
point = "RIGHT"
|
||||
else
|
||||
point = "CENTER"
|
||||
end
|
||||
return point
|
||||
end
|
||||
|
||||
function E:GetXYOffset(position, override)
|
||||
local default = E.Spacing
|
||||
local x, y = override or default, override or default
|
||||
|
||||
if position == "TOP" then
|
||||
return 0, y
|
||||
elseif position == "TOPLEFT" then
|
||||
return x, y
|
||||
elseif position == "TOPRIGHT" then
|
||||
return -x, y
|
||||
elseif position == "BOTTOM" then
|
||||
return 0, -y
|
||||
elseif(position == "BOTTOMLEFT") then
|
||||
return x, -y
|
||||
elseif position == "BOTTOMRIGHT" then
|
||||
return -x, -y
|
||||
elseif position == "LEFT" then
|
||||
return -x, 0
|
||||
elseif position == "RIGHT" then
|
||||
return x, 0
|
||||
elseif position == "CENTER" then
|
||||
return 0, 0
|
||||
end
|
||||
end
|
||||
|
||||
local styles = {
|
||||
-- keep percents in this table with `PERCENT` in the key, and `%.1f%%` in the value somewhere.
|
||||
-- we use these two things to follow our setting for decimal length. they need to be EXACT.
|
||||
["CURRENT"] = "%s",
|
||||
["CURRENT_MAX"] = "%s - %s",
|
||||
["CURRENT_PERCENT"] = "%s - %.1f%%",
|
||||
["CURRENT_MAX_PERCENT"] = "%s - %s | %.1f%%",
|
||||
["PERCENT"] = "%.1f%%",
|
||||
["DEFICIT"] = "-%s"
|
||||
}
|
||||
|
||||
function E:GetFormattedText(style, min, max)
|
||||
assert(styles[style], "Invalid format style: "..style)
|
||||
assert(min, "You need to provide a current value. Usage: E:GetFormattedText(style, min, max)")
|
||||
assert(max, "You need to provide a maximum value. Usage: E:GetFormattedText(style, min, max)")
|
||||
|
||||
if max == 0 then max = 1 end
|
||||
|
||||
gftDec = E.db.general.decimalLength or 1
|
||||
if gftDec ~= 1 and find(style, "PERCENT") then
|
||||
gftUseStyle = gsub(styles[style], "%%%.1f%%%%", "%%."..gftDec.."f%%%%")
|
||||
else
|
||||
gftUseStyle = styles[style]
|
||||
end
|
||||
|
||||
if style == "DEFICIT" then
|
||||
gftDeficit = max - min
|
||||
return ((gftDeficit > 0) and format(gftUseStyle, E:ShortValue(gftDeficit))) or ""
|
||||
elseif style == "PERCENT" then
|
||||
return format(gftUseStyle, min / max * 100)
|
||||
elseif style == "CURRENT" or ((style == "CURRENT_MAX" or style == "CURRENT_MAX_PERCENT" or style == "CURRENT_PERCENT") and min == max) then
|
||||
return format(styles["CURRENT"], E:ShortValue(min))
|
||||
elseif style == "CURRENT_MAX" then
|
||||
return format(gftUseStyle, E:ShortValue(min), E:ShortValue(max))
|
||||
elseif style == "CURRENT_PERCENT" then
|
||||
return format(gftUseStyle, E:ShortValue(min), min / max * 100)
|
||||
elseif style == "CURRENT_MAX_PERCENT" then
|
||||
return format(gftUseStyle, E:ShortValue(min), E:ShortValue(max), min / max * 100)
|
||||
end
|
||||
end
|
||||
|
||||
function E:AbbreviateString(string, allUpper)
|
||||
local newString = ""
|
||||
local words = {split(" ", string)}
|
||||
for _, word in pairs(words) do
|
||||
word = utf8sub(word, 1, 1)
|
||||
if(allUpper) then
|
||||
word = upper(word)
|
||||
end
|
||||
newString = newString..word
|
||||
end
|
||||
|
||||
return newString
|
||||
end
|
||||
|
||||
function E:ShortenString(string, numChars, dots)
|
||||
local bytes = len(string)
|
||||
if bytes <= numChars then
|
||||
return string
|
||||
else
|
||||
local len, pos = 0, 1
|
||||
while pos <= bytes do
|
||||
len = len + 1
|
||||
local c = byte(string, pos)
|
||||
if c > 0 and c <= 127 then
|
||||
pos = pos + 1
|
||||
elseif c >= 192 and c <= 223 then
|
||||
pos = pos + 2
|
||||
elseif c >= 224 and c <= 239 then
|
||||
pos = pos + 3
|
||||
elseif c >= 240 and c <= 247 then
|
||||
pos = pos + 4
|
||||
end
|
||||
if len == numChars then break end
|
||||
end
|
||||
|
||||
if len == numChars and pos <= bytes then
|
||||
return sub(string, 1, pos - 1)..(dots and "..." or "")
|
||||
else
|
||||
return string
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local waitTable = {}
|
||||
local waitFrame
|
||||
function E:Delay(delay, func, ...)
|
||||
if (type(delay) ~= "number") or (type(func) ~= "function") then
|
||||
return false
|
||||
end
|
||||
if waitFrame == nil then
|
||||
waitFrame = CreateFrame("Frame", "WaitFrame", E.UIParent)
|
||||
waitFrame:SetScript("OnUpdate", function()
|
||||
local waitRecord, waitDelay, waitFunc, waitParams
|
||||
local i, count = 1, getn(waitTable)
|
||||
while i <= count do
|
||||
waitRecord = tremove(waitTable, i)
|
||||
waitDelay = tremove(waitRecord, 1)
|
||||
waitFunc = tremove(waitRecord, 1)
|
||||
waitParams = tremove(waitRecord, 1)
|
||||
if waitDelay > arg1 then
|
||||
tinsert(waitTable, i, {waitDelay - arg1, waitFunc, waitParams})
|
||||
i = i + 1
|
||||
else
|
||||
count = count - 1
|
||||
waitFunc(unpack(waitParams))
|
||||
end
|
||||
end
|
||||
end)
|
||||
end
|
||||
tinsert(waitTable, {delay, func, arg})
|
||||
return true
|
||||
end
|
||||
|
||||
function E:StringTitle(str)
|
||||
return gsub(str, "(.)", upper, 1)
|
||||
end
|
||||
|
||||
E.TimeColors = {
|
||||
[0] = "|cffeeeeee",
|
||||
[1] = "|cffeeeeee",
|
||||
[2] = "|cffeeeeee",
|
||||
[3] = "|cffeeeeee",
|
||||
[4] = "|cfffe0000"
|
||||
}
|
||||
|
||||
E.TimeFormats = {
|
||||
[0] = {"%dd", "%dd"},
|
||||
[1] = {"%dh", "%dh"},
|
||||
[2] = {"%dm", "%dm"},
|
||||
[3] = {"%ds", "%d"},
|
||||
[4] = {"%.1fs", "%.1f"}
|
||||
}
|
||||
|
||||
local DAY, HOUR, MINUTE = 86400, 3600, 60
|
||||
local DAYISH, HOURISH, MINUTEISH = HOUR * 23.5, MINUTE * 59.5, 59.5
|
||||
local HALFDAYISH, HALFHOURISH, HALFMINUTEISH = DAY/2 + 0.5, HOUR/2 + 0.5, MINUTE/2 + 0.5
|
||||
|
||||
function E:GetTimeInfo(s, threshhold)
|
||||
if s < MINUTE then
|
||||
if s >= threshhold then
|
||||
return floor(s), 3, 0.51
|
||||
else
|
||||
return s, 4, 0.051
|
||||
end
|
||||
elseif s < HOUR then
|
||||
local minutes = floor((s/MINUTE)+.5)
|
||||
return ceil(s / MINUTE), 2, minutes > 1 and (s - (minutes*MINUTE - HALFMINUTEISH)) or (s - MINUTEISH)
|
||||
elseif s < DAY then
|
||||
local hours = floor((s/HOUR)+.5)
|
||||
return ceil(s / HOUR), 1, hours > 1 and (s - (hours*HOUR - HALFHOURISH)) or (s - HOURISH)
|
||||
else
|
||||
local days = floor((s/DAY)+.5)
|
||||
return ceil(s / DAY), 0, days > 1 and (s - (days*DAY - HALFDAYISH)) or (s - DAYISH)
|
||||
end
|
||||
end
|
||||
|
||||
local COLOR_COPPER = "|cffeda55f"
|
||||
local COLOR_SILVER = "|cffc7c7cf"
|
||||
local COLOR_GOLD = "|cffffd700"
|
||||
|
||||
function E:FormatMoney(amount, style)
|
||||
local coppername = L.copperabbrev
|
||||
local silvername = L.silverabbrev
|
||||
local goldname = L.goldabbrev
|
||||
|
||||
local value = abs(amount)
|
||||
local gold = floor(value / 10000)
|
||||
local silver = floor(mod(value / 100, 100))
|
||||
local copper = floor(mod(value, 100))
|
||||
|
||||
if not style or style == "SMART" then
|
||||
local str = ""
|
||||
if gold > 0 then
|
||||
str = format("%d%s%s", gold, goldname, (silver > 0 or copper > 0) and " " or "")
|
||||
end
|
||||
if silver > 0 then
|
||||
str = format("%s%d%s%s", str, silver, silvername, copper > 0 and " " or "")
|
||||
end
|
||||
if copper > 0 or value == 0 then
|
||||
str = format("%s%d%s", str, copper, coppername)
|
||||
end
|
||||
return str
|
||||
end
|
||||
|
||||
if style == "FULL" then
|
||||
if gold > 0 then
|
||||
return format("%d%s %d%s %d%s", gold, goldname, silver, silvername, copper, coppername)
|
||||
elseif silver > 0 then
|
||||
return format("%d%s %d%s", silver, silvername, copper, coppername)
|
||||
else
|
||||
return format("%d%s", copper, coppername)
|
||||
end
|
||||
elseif style == "SHORT" then
|
||||
if gold > 0 then
|
||||
return format("%.1f%s", amount / 10000, goldname)
|
||||
elseif silver > 0 then
|
||||
return format("%.1f%s", amount / 100, silvername)
|
||||
else
|
||||
return format("%d%s", amount, coppername)
|
||||
end
|
||||
elseif style == "SHORTINT" then
|
||||
if gold > 0 then
|
||||
return format("%d%s", gold, goldname)
|
||||
elseif silver > 0 then
|
||||
return format("%d%s", silver, silvername)
|
||||
else
|
||||
return format("%d%s", copper, coppername)
|
||||
end
|
||||
elseif style == "CONDENSED" then
|
||||
if gold > 0 then
|
||||
return format("%s%d|r.%s%02d|r.%s%02d|r", COLOR_GOLD, gold, COLOR_SILVER, silver, COLOR_COPPER, copper)
|
||||
elseif silver > 0 then
|
||||
return format("%s%d|r.%s%02d|r", COLOR_SILVER, silver, COLOR_COPPER, copper)
|
||||
else
|
||||
return format("%s%d|r", COLOR_COPPER, copper)
|
||||
end
|
||||
elseif style == "BLIZZARD" then
|
||||
if gold > 0 then
|
||||
return format("%s%s %d%s %d%s", gold, goldname, silver, silvername, copper, coppername)
|
||||
elseif silver > 0 then
|
||||
return format("%d%s %d%s", silver, silvername, copper, coppername)
|
||||
else
|
||||
return format("%d%s", copper, coppername)
|
||||
end
|
||||
end
|
||||
|
||||
return self:FormatMoney(amount, "SMART")
|
||||
end
|
||||
@@ -0,0 +1,499 @@
|
||||
local E, L, V, P, G = unpack(ElvUI); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
|
||||
local Sticky = LibStub("LibSimpleSticky-1.0");
|
||||
|
||||
--Cache global variables
|
||||
--Lua functions
|
||||
local _G = _G
|
||||
local type, unpack, pairs = type, unpack, pairs
|
||||
local format, split, find = string.format, string.split, string.find
|
||||
--WoW API / Variables
|
||||
local CreateFrame = CreateFrame
|
||||
|
||||
E.CreatedMovers = {}
|
||||
E.DisabledMovers = {}
|
||||
|
||||
local function SizeChanged(self)
|
||||
self.mover:SetWidth(self.dirtyWidth and self.dirtyWidth or self:GetWidth())
|
||||
self.mover:SetHeight(self.dirtyHeight and self.dirtyHeight or self:GetHeight())
|
||||
end
|
||||
|
||||
local function GetPoint(obj)
|
||||
local point, anchor, secondaryPoint, x, y = obj:GetPoint()
|
||||
if not anchor then anchor = ElvUIParent end
|
||||
|
||||
return format("%s,%s,%s,%d,%d", point, anchor:GetName(), secondaryPoint, E:Round(x), E:Round(y))
|
||||
end
|
||||
|
||||
local function UpdateCoords(self)
|
||||
local mover = self.child;
|
||||
local x, y, _, nudgePoint, nudgeInversePoint = E:CalculateMoverPoints(mover);
|
||||
|
||||
local coordX, coordY = E:GetXYOffset(nudgeInversePoint, 1);
|
||||
ElvUIMoverNudgeWindow:ClearAllPoints();
|
||||
ElvUIMoverNudgeWindow:SetPoint(nudgePoint, mover, nudgeInversePoint, coordX, coordY);
|
||||
E:UpdateNudgeFrame(mover, x, y);
|
||||
end
|
||||
|
||||
local isDragging = false
|
||||
local coordFrame = CreateFrame("Frame")
|
||||
coordFrame:SetScript("OnUpdate", function() UpdateCoords(this) end)
|
||||
coordFrame:Hide()
|
||||
|
||||
local function CreateMover(parent, name, text, overlay, snapOffset, postdrag, shouldDisable)
|
||||
if not parent then return end --If for some reason the parent isnt loaded yet
|
||||
if E.CreatedMovers[name].Created then return end
|
||||
|
||||
if overlay == nil then overlay = true end
|
||||
local point, anchor, secondaryPoint, x, y = split(",", GetPoint(parent))
|
||||
|
||||
local width = parent.dirtyWidth or parent:GetWidth()
|
||||
local height = parent.dirtyHeight or parent:GetHeight()
|
||||
|
||||
local f = CreateFrame("Button", name, E.UIParent)
|
||||
f:SetClampedToScreen(true)
|
||||
f:RegisterForDrag("LeftButton", "RightButton")
|
||||
f:EnableMouseWheel(true)
|
||||
f:SetMovable(true)
|
||||
f:SetWidth(width)
|
||||
f:SetHeight(height)
|
||||
E:SetTemplate(f, "Transparent", nil, nil, true)
|
||||
f:Hide()
|
||||
f.parent = parent
|
||||
f.name = name
|
||||
f.textString = text
|
||||
f.postdrag = postdrag
|
||||
f.overlay = overlay
|
||||
f.snapOffset = snapOffset or -2
|
||||
f.shouldDisable = shouldDisable
|
||||
|
||||
f:SetFrameLevel(parent:GetFrameLevel() + 1)
|
||||
if(overlay == true) then
|
||||
f:SetFrameStrata("DIALOG")
|
||||
else
|
||||
f:SetFrameStrata("BACKGROUND")
|
||||
end
|
||||
|
||||
E.CreatedMovers[name].mover = f
|
||||
E["snapBars"][getn(E["snapBars"]) + 1] = f
|
||||
|
||||
local fs = f:CreateFontString(nil, "OVERLAY")
|
||||
E:FontTemplate(fs)
|
||||
fs:SetJustifyH("CENTER")
|
||||
fs:SetPoint("CENTER", f)
|
||||
fs:SetText(text or name)
|
||||
fs:SetTextColor(unpack(E["media"].rgbvaluecolor))
|
||||
f:SetFontString(fs)
|
||||
f.text = fs
|
||||
|
||||
if E.db["movers"] and E.db["movers"][name] then
|
||||
if type(E.db["movers"][name]) == "table" then
|
||||
f:SetPoint(E.db["movers"][name]["p"], E.UIParent, E.db["movers"][name]["p2"], E.db["movers"][name]["p3"], E.db["movers"][name]["p4"])
|
||||
E.db["movers"][name] = GetPoint(f)
|
||||
f:ClearAllPoints()
|
||||
end
|
||||
|
||||
local delim
|
||||
local anchorString = E.db["movers"][name]
|
||||
if find(anchorString, "\031") then
|
||||
delim = "\031"
|
||||
elseif find(anchorString, ",") then
|
||||
delim = ","
|
||||
end
|
||||
local point, anchor, secondaryPoint, x, y = split(delim, anchorString)
|
||||
f:SetPoint(point, anchor, secondaryPoint, x, y)
|
||||
else
|
||||
|
||||
f:SetPoint(point, anchor, secondaryPoint, x, y)
|
||||
end
|
||||
|
||||
local function OnDragStart(self)
|
||||
if E.db["general"].stickyFrames then
|
||||
Sticky:StartMoving(self, E["snapBars"], f.snapOffset, f.snapOffset, f.snapOffset, f.snapOffset)
|
||||
else
|
||||
self:StartMoving()
|
||||
end
|
||||
coordFrame.child = self
|
||||
coordFrame:Show()
|
||||
isDragging = true
|
||||
end
|
||||
|
||||
local function OnDragStop(self)
|
||||
isDragging = false
|
||||
if E.db["general"].stickyFrames then
|
||||
Sticky:StopMoving(self)
|
||||
else
|
||||
self:StopMovingOrSizing()
|
||||
end
|
||||
|
||||
local x, y, point = E:CalculateMoverPoints(self)
|
||||
self:ClearAllPoints()
|
||||
local overridePoint
|
||||
if(self.positionOverride) then
|
||||
if(self.positionOverride == "BOTTOM" or self.positionOverride == "TOP") then
|
||||
overridePoint = "BOTTOM"
|
||||
else
|
||||
overridePoint = "BOTTOMLEFT"
|
||||
end
|
||||
end
|
||||
|
||||
self:SetPoint(self.positionOverride or point, E.UIParent, overridePoint and overridePoint or point, x, y)
|
||||
if(self.positionOverride) then
|
||||
self.parent:ClearAllPoints()
|
||||
self.parent:SetPoint(self.positionOverride, self, self.positionOverride)
|
||||
end
|
||||
|
||||
E:SaveMoverPosition(name)
|
||||
|
||||
if ElvUIMoverNudgeWindow then
|
||||
E:UpdateNudgeFrame(self, x, y)
|
||||
end
|
||||
|
||||
coordFrame.child = nil
|
||||
coordFrame:Hide()
|
||||
|
||||
if postdrag ~= nil and type(postdrag) == "function" then
|
||||
postdrag(self, E:GetScreenQuadrant(self))
|
||||
end
|
||||
|
||||
self:SetUserPlaced(false)
|
||||
end
|
||||
|
||||
local function OnEnter()
|
||||
if isDragging then return end
|
||||
this.text:SetTextColor(1, 1, 1)
|
||||
ElvUIMoverNudgeWindow:Show()
|
||||
E.AssignFrameToNudge(this)
|
||||
coordFrame.child = this
|
||||
UpdateCoords(coordFrame)
|
||||
--coordFrame:GetScript("OnUpdate")(coordFrame)
|
||||
end
|
||||
|
||||
local function OnMouseDown(button)
|
||||
if button == "RightButton" then
|
||||
isDragging = false
|
||||
if E.db["general"].stickyFrames then
|
||||
Sticky:StopMoving(this)
|
||||
else
|
||||
this:StopMovingOrSizing()
|
||||
end
|
||||
if IsControlKeyDown() and this.textString then
|
||||
E:ResetMovers(this.textString)
|
||||
elseif IsShiftKeyDown() then
|
||||
this:Hide()
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function OnLeave(self)
|
||||
if isDragging then return end
|
||||
this.text:SetTextColor(unpack(E["media"].rgbvaluecolor))
|
||||
end
|
||||
|
||||
local function OnShow(self)
|
||||
this:SetBackdropBorderColor(unpack(E["media"].rgbvaluecolor))
|
||||
end
|
||||
|
||||
local function OnMouseWheel(_, delta)
|
||||
if(IsShiftKeyDown()) then
|
||||
E:NudgeMover(delta)
|
||||
else
|
||||
E:NudgeMover(nil, delta)
|
||||
end
|
||||
end
|
||||
|
||||
f:SetScript("OnDragStart", function() OnDragStart(f) end)
|
||||
f:SetScript("OnMouseUp", E.AssignFrameToNudge)
|
||||
f:SetScript("OnDragStop", function() OnDragStop(f) end)
|
||||
f:SetScript("OnEnter", OnEnter)
|
||||
f:SetScript("OnMouseDown", OnMouseDown)
|
||||
f:SetScript("OnLeave", OnLeave)
|
||||
f:SetScript("OnShow", OnShow)
|
||||
f:SetScript("OnMouseWheel", OnMouseWheel)
|
||||
|
||||
parent:SetScript("OnSizeChanged", function() SizeChanged(parent) end)
|
||||
parent.mover = f
|
||||
|
||||
parent:ClearAllPoints()
|
||||
parent:SetPoint(point, f, 0, 0)
|
||||
|
||||
if postdrag ~= nil and type(postdrag) == "function" then
|
||||
f:RegisterEvent("PLAYER_ENTERING_WORLD")
|
||||
f:SetScript("OnEvent", function()
|
||||
postdrag(f, E:GetScreenQuadrant(f))
|
||||
this:UnregisterAllEvents()
|
||||
end)
|
||||
end
|
||||
|
||||
E.CreatedMovers[name].Created = true
|
||||
end
|
||||
|
||||
function E:CalculateMoverPoints(mover, nudgeX, nudgeY)
|
||||
local screenWidth, screenHeight, screenCenter = E.UIParent:GetRight(), E.UIParent:GetTop(), E.UIParent:GetCenter()
|
||||
local x, y = mover:GetCenter()
|
||||
|
||||
local LEFT = screenWidth / 3
|
||||
local RIGHT = screenWidth * 2 / 3
|
||||
local TOP = screenHeight / 2
|
||||
local point, nudgePoint, nudgeInversePoint
|
||||
|
||||
if(y >= TOP) then
|
||||
point = "TOP"
|
||||
nudgePoint = "TOP"
|
||||
nudgeInversePoint = "BOTTOM"
|
||||
y = -(screenHeight - mover:GetTop())
|
||||
else
|
||||
point = "BOTTOM"
|
||||
nudgePoint = "BOTTOM"
|
||||
nudgeInversePoint = "TOP"
|
||||
y = mover:GetBottom()
|
||||
end
|
||||
|
||||
if(x >= RIGHT) then
|
||||
point = point .. "RIGHT"
|
||||
nudgePoint = "RIGHT"
|
||||
nudgeInversePoint = "LEFT"
|
||||
x = mover:GetRight() - screenWidth
|
||||
elseif(x <= LEFT) then
|
||||
point = point .. "LEFT"
|
||||
nudgePoint = "LEFT"
|
||||
nudgeInversePoint = "RIGHT"
|
||||
x = mover:GetLeft()
|
||||
else
|
||||
x = x - screenCenter
|
||||
end
|
||||
|
||||
if(mover.positionOverride) then
|
||||
if(mover.positionOverride == "TOPLEFT") then
|
||||
x = mover:GetLeft() - E.diffGetLeft
|
||||
y = mover:GetTop() - E.diffGetTop
|
||||
elseif(mover.positionOverride == "TOPRIGHT") then
|
||||
x = mover:GetRight() - E.diffGetRight
|
||||
y = mover:GetTop() - E.diffGetTop
|
||||
elseif(mover.positionOverride == "BOTTOMLEFT") then
|
||||
x = mover:GetLeft() - E.diffGetLeft
|
||||
y = mover:GetBottom() - E.diffGetBottom
|
||||
elseif(mover.positionOverride == "BOTTOMRIGHT") then
|
||||
x = mover:GetRight() - E.diffGetRight
|
||||
y = mover:GetBottom() - E.diffGetBottom
|
||||
elseif(mover.positionOverride == "BOTTOM") then
|
||||
x = mover:GetCenter() - screenCenter
|
||||
y = mover:GetBottom() - E.diffGetBottom
|
||||
elseif(mover.positionOverride == "TOP") then
|
||||
x = mover:GetCenter() - screenCenter
|
||||
y = mover:GetTop() - E.diffGetTop
|
||||
end
|
||||
end
|
||||
|
||||
x = x + (nudgeX or 0)
|
||||
y = y + (nudgeY or 0)
|
||||
|
||||
return x, y, point, nudgePoint, nudgeInversePoint
|
||||
end
|
||||
|
||||
function E:UpdatePositionOverride(name)
|
||||
if _G[name] and _G[name]:GetScript("OnDragStop") then
|
||||
_G[name]:GetScript("OnDragStop")(_G[name])
|
||||
end
|
||||
end
|
||||
|
||||
function E:HasMoverBeenMoved(name)
|
||||
if E.db["movers"] and E.db["movers"][name] then
|
||||
return true
|
||||
else
|
||||
return false
|
||||
end
|
||||
end
|
||||
|
||||
function E:SaveMoverPosition(name)
|
||||
if not _G[name] then return end
|
||||
if not E.db.movers then E.db.movers = {} end
|
||||
|
||||
E.db.movers[name] = GetPoint(_G[name])
|
||||
end
|
||||
|
||||
function E:SetMoverSnapOffset(name, offset)
|
||||
if not _G[name] or not E.CreatedMovers[name] then return end
|
||||
E.CreatedMovers[name].mover.snapOffset = offset or -2
|
||||
E.CreatedMovers[name]["snapoffset"] = offset or -2
|
||||
end
|
||||
|
||||
function E:SaveMoverDefaultPosition(name)
|
||||
if not _G[name] then return end
|
||||
|
||||
E.CreatedMovers[name]["point"] = GetPoint(_G[name])
|
||||
E.CreatedMovers[name]["postdrag"](_G[name], E:GetScreenQuadrant(_G[name]))
|
||||
end
|
||||
|
||||
function E:CreateMover(parent, name, text, overlay, snapoffset, postdrag, moverTypes, shouldDisable)
|
||||
if not moverTypes then moverTypes = "ALL,GENERAL" end
|
||||
|
||||
if E.CreatedMovers[name] == nil then
|
||||
E.CreatedMovers[name] = {}
|
||||
E.CreatedMovers[name]["parent"] = parent
|
||||
E.CreatedMovers[name]["text"] = text
|
||||
E.CreatedMovers[name]["overlay"] = overlay
|
||||
E.CreatedMovers[name]["postdrag"] = postdrag
|
||||
E.CreatedMovers[name]["snapoffset"] = snapoffset
|
||||
E.CreatedMovers[name]["point"] = GetPoint(parent)
|
||||
E.CreatedMovers[name]["shouldDisable"] = shouldDisable
|
||||
|
||||
E.CreatedMovers[name]["type"] = {}
|
||||
local types = {split(",", moverTypes)}
|
||||
for i = 1, getn(types) do
|
||||
local moverType = types[i]
|
||||
E.CreatedMovers[name]["type"][moverType] = true
|
||||
end
|
||||
end
|
||||
|
||||
CreateMover(parent, name, text, overlay, snapoffset, postdrag, shouldDisable)
|
||||
end
|
||||
|
||||
function E:ToggleMovers(show, moverType)
|
||||
self.configMode = show
|
||||
|
||||
for name, _ in pairs(E.CreatedMovers) do
|
||||
if not show then
|
||||
_G[name]:Hide()
|
||||
else
|
||||
if E.CreatedMovers[name]["type"][moverType] then
|
||||
_G[name]:Show()
|
||||
else
|
||||
_G[name]:Hide()
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function E:DisableMover(name)
|
||||
if(self.DisabledMovers[name]) then return end
|
||||
if(not self.CreatedMovers[name]) then
|
||||
error("mover doesn't exist")
|
||||
end
|
||||
|
||||
self.DisabledMovers[name] = {}
|
||||
for x, y in pairs(self.CreatedMovers[name]) do
|
||||
self.DisabledMovers[name][x] = y
|
||||
end
|
||||
|
||||
if(self.configMode) then
|
||||
_G[name]:Hide()
|
||||
end
|
||||
|
||||
self.CreatedMovers[name] = nil
|
||||
end
|
||||
|
||||
function E:EnableMover(name)
|
||||
if(self.CreatedMovers[name]) then return end
|
||||
if(not self.DisabledMovers[name]) then
|
||||
error("mover doesn't exist")
|
||||
end
|
||||
|
||||
self.CreatedMovers[name] = {}
|
||||
for x, y in pairs(self.DisabledMovers[name]) do
|
||||
self.CreatedMovers[name][x] = y
|
||||
end
|
||||
|
||||
--Commented out, as it created an issue with trying to reset a mover after having used EnableMover on it. Not sure if this code is even needed anymore.
|
||||
--[[
|
||||
if(E.db["movers"] and E.db["movers"][name] and type(E.db["movers"][name]) == "string") then
|
||||
self.CreatedMovers[name]["point"] = E.db["movers"][name]
|
||||
end
|
||||
]]
|
||||
|
||||
if(self.configMode) then
|
||||
_G[name]:Show()
|
||||
end
|
||||
|
||||
self.DisabledMovers[name] = nil
|
||||
end
|
||||
|
||||
function E:ResetMovers(arg)
|
||||
if arg == "" or arg == nil then
|
||||
for name, _ in pairs(E.CreatedMovers) do
|
||||
local f = _G[name]
|
||||
local point, anchor, secondaryPoint, x, y = split(",", E.CreatedMovers[name]["point"])
|
||||
f:ClearAllPoints()
|
||||
f:SetPoint(point, anchor, secondaryPoint, x, y)
|
||||
|
||||
for key, value in pairs(E.CreatedMovers[name]) do
|
||||
if key == "postdrag" and type(value) == "function" then
|
||||
value(f, E:GetScreenQuadrant(f))
|
||||
end
|
||||
end
|
||||
end
|
||||
self.db.movers = nil
|
||||
else
|
||||
for name, _ in pairs(E.CreatedMovers) do
|
||||
for key, value in pairs(E.CreatedMovers[name]) do
|
||||
if key == "text" then
|
||||
if arg == value then
|
||||
local f = _G[name]
|
||||
local point, anchor, secondaryPoint, x, y = split(",", E.CreatedMovers[name]["point"])
|
||||
f:ClearAllPoints()
|
||||
f:SetPoint(point, anchor, secondaryPoint, x, y)
|
||||
|
||||
if self.db.movers then
|
||||
self.db.movers[name] = nil
|
||||
end
|
||||
|
||||
if E.CreatedMovers[name]["postdrag"] ~= nil and type(E.CreatedMovers[name]["postdrag"]) == "function" then
|
||||
E.CreatedMovers[name]["postdrag"](f, E:GetScreenQuadrant(f))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--Profile Change
|
||||
function E:SetMoversPositions()
|
||||
for name in pairs(E.DisabledMovers) do
|
||||
local shouldDisable = ((E.DisabledMovers[name].shouldDisable and E.DisabledMovers[name]["shouldDisable"]()) or false)
|
||||
if not shouldDisable then
|
||||
E:EnableMover(name)
|
||||
end
|
||||
end
|
||||
|
||||
for name, _ in pairs(E.CreatedMovers) do
|
||||
local f = _G[name]
|
||||
local point, anchor, secondaryPoint, x, y
|
||||
if E.db["movers"] and E.db["movers"][name] and type(E.db["movers"][name]) == "string" then
|
||||
local delim
|
||||
local anchorString = E.db["movers"][name]
|
||||
if(find(anchorString, "\031")) then
|
||||
delim = "\031"
|
||||
elseif(find(anchorString, ",")) then
|
||||
delim = ","
|
||||
end
|
||||
point, anchor, secondaryPoint, x, y = split(delim, anchorString)
|
||||
f:ClearAllPoints()
|
||||
f:SetPoint(point, anchor, secondaryPoint, x, y)
|
||||
elseif f then
|
||||
point, anchor, secondaryPoint, x, y = split(",", E.CreatedMovers[name]["point"])
|
||||
f:ClearAllPoints()
|
||||
f:SetPoint(point, anchor, secondaryPoint, x, y)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--Called from core.lua
|
||||
function E:LoadMovers()
|
||||
for n, _ in pairs(E.CreatedMovers) do
|
||||
local p, t, o, so, pd
|
||||
for key, value in pairs(E.CreatedMovers[n]) do
|
||||
if key == "parent" then
|
||||
p = value
|
||||
elseif key == "text" then
|
||||
t = value
|
||||
elseif key == "overlay" then
|
||||
o = value
|
||||
elseif key == "snapoffset" then
|
||||
so = value
|
||||
elseif key == "postdrag" then
|
||||
pd = value
|
||||
end
|
||||
end
|
||||
CreateMover(p, n, t, o, so, pd)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,932 @@
|
||||
local E, L, V, P, G = unpack(ElvUI); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
|
||||
|
||||
--Cache global variables
|
||||
--Lua functions
|
||||
local _G = _G
|
||||
local pairs, type, unpack, assert = pairs, type, unpack, assert
|
||||
local getn, tremove, tContains, tinsert, wipe = table.getn, tremove, tContains, tinsert, table.wipe
|
||||
local lower = string.lower
|
||||
--WoW API / Variables
|
||||
local CreateFrame = CreateFrame
|
||||
local UnitIsDeadOrGhost, InCinematic = UnitIsDeadOrGhost, InCinematic
|
||||
local GetBindingFromClick, RunBinding = GetBindingFromClick, RunBinding
|
||||
local PurchaseSlot, GetBankSlotCost = PurchaseSlot, GetBankSlotCost
|
||||
local MoneyFrame_Update = MoneyFrame_Update
|
||||
local SetCVar, DisableAddOn = SetCVar, DisableAddOn
|
||||
local ReloadUI, PlaySound, StopMusic = ReloadUI, PlaySound, StopMusic
|
||||
local StaticPopup_Resize = StaticPopup_Resize
|
||||
|
||||
E.PopupDialogs = {}
|
||||
E.StaticPopup_DisplayedFrames = {}
|
||||
|
||||
E.PopupDialogs["ELVUI_UPDATE_AVAILABLE"] = {
|
||||
text = L["ElvUI is five or more revisions out of date. You can download the newest version from https://github.com/ElvUI-Vanilla/ElvUI/"],
|
||||
hasEditBox = 1,
|
||||
OnShow = function()
|
||||
this.editBox:SetAutoFocus(false)
|
||||
this.editBox.width = this.editBox:GetWidth()
|
||||
this.editBox:SetWidth(220)
|
||||
this.editBox:SetText("https://github.com/ElvUI-Vanilla/ElvUI")
|
||||
this.editBox:HighlightText()
|
||||
-- ChatEdit_FocusActiveWindow()
|
||||
end,
|
||||
OnHide = function()
|
||||
this.editBox:SetWidth(this.editBox.width or 50)
|
||||
this.editBox.width = nil
|
||||
end,
|
||||
hideOnEscape = 1,
|
||||
button1 = OKAY,
|
||||
button2 = CLOSE, -- Temporary until further fix
|
||||
OnAccept = E.noop,
|
||||
EditBoxOnEnterPressed = function()
|
||||
-- ChatEdit_FocusActiveWindow()
|
||||
this:GetParent():Hide()
|
||||
end,
|
||||
EditBoxOnEscapePressed = function()
|
||||
-- ChatEdit_FocusActiveWindow()
|
||||
this:GetParent():Hide()
|
||||
end,
|
||||
EditBoxOnTextChanged = function()
|
||||
if this:GetText() ~= "https://github.com/ElvUI-Vanilla/ElvUI" then
|
||||
this:SetText("https://github.com/ElvUI-Vanilla/ElvUI")
|
||||
end
|
||||
this:HighlightText()
|
||||
this:ClearFocus()
|
||||
-- ChatEdit_FocusActiveWindow()
|
||||
end,
|
||||
OnEditFocusGained = function()
|
||||
this:HighlightText()
|
||||
end,
|
||||
showAlert = 1
|
||||
}
|
||||
|
||||
E.PopupDialogs["CLIQUE_ADVERT"] = {
|
||||
text = L["Using the healer layout it is highly recommended you download the addon Clique if you wish to have the click-to-heal function."],
|
||||
button1 = YES,
|
||||
button2 = CLOSE, -- Temporary until further fix
|
||||
OnAccept = E.noop,
|
||||
showAlert = 1
|
||||
}
|
||||
|
||||
E.PopupDialogs["CONFIRM_LOSE_BINDING_CHANGES"] = {
|
||||
text = CONFIRM_LOSE_BINDING_CHANGES,
|
||||
button1 = OKAY,
|
||||
button2 = CANCEL,
|
||||
OnAccept = function()
|
||||
E:GetModule("ActionBars"):ChangeBindingProfile()
|
||||
E:GetModule("ActionBars").bindingsChanged = nil
|
||||
end,
|
||||
OnCancel = function()
|
||||
if ElvUIBindPopupWindowCheckButton:GetChecked() then
|
||||
ElvUIBindPopupWindowCheckButton:SetChecked()
|
||||
else
|
||||
ElvUIBindPopupWindowCheckButton:SetChecked(1)
|
||||
end
|
||||
end,
|
||||
timeout = 0,
|
||||
whileDead = 1,
|
||||
showAlert = 1
|
||||
}
|
||||
|
||||
E.PopupDialogs["TUKUI_ELVUI_INCOMPATIBLE"] = {
|
||||
text = L["Oh lord, you have got ElvUI and Tukui both enabled at the same time. Select an addon to disable."],
|
||||
OnAccept = function() DisableAddOn("ElvUI") ReloadUI() end,
|
||||
OnCancel = function() DisableAddOn("Tukui") ReloadUI() end,
|
||||
button1 = "ElvUI",
|
||||
button2 = "Tukui",
|
||||
timeout = 0,
|
||||
whileDead = 1,
|
||||
hideOnEscape = false
|
||||
}
|
||||
|
||||
E.PopupDialogs["DISABLE_INCOMPATIBLE_ADDON"] = {
|
||||
text = L["Do you swear not to post in technical support about something not working without first disabling the addon/module combination first?"],
|
||||
OnAccept = function() E.global.ignoreIncompatible = true end,
|
||||
OnCancel = function() E:StaticPopup_Hide("DISABLE_INCOMPATIBLE_ADDON") E:StaticPopup_Show("INCOMPATIBLE_ADDON", E.PopupDialogs["INCOMPATIBLE_ADDON"].addon, E.PopupDialogs["INCOMPATIBLE_ADDON"].module) end,
|
||||
button1 = L["I Swear"],
|
||||
button2 = DECLINE,
|
||||
timeout = 0,
|
||||
whileDead = 1,
|
||||
hideOnEscape = false
|
||||
}
|
||||
|
||||
E.PopupDialogs["INCOMPATIBLE_ADDON"] = {
|
||||
text = L["INCOMPATIBLE_ADDON"],
|
||||
OnAccept = function() DisableAddOn(E.PopupDialogs["INCOMPATIBLE_ADDON"].addon) ReloadUI() end,
|
||||
OnCancel = function() E.private[lower(E.PopupDialogs["INCOMPATIBLE_ADDON"].module)].enable = false ReloadUI() end,
|
||||
button3 = L["Disable Warning"],
|
||||
OnAlt = function ()
|
||||
E:StaticPopup_Hide("INCOMPATIBLE_ADDON")
|
||||
E:StaticPopup_Show("DISABLE_INCOMPATIBLE_ADDON")
|
||||
end,
|
||||
timeout = 0,
|
||||
whileDead = 1,
|
||||
hideOnEscape = false
|
||||
}
|
||||
|
||||
E.PopupDialogs["PIXELPERFECT_CHANGED"] = {
|
||||
text = L["You have changed the Thin Border Theme option. You will have to complete the installation process to remove any graphical bugs."],
|
||||
button1 = ACCEPT,
|
||||
button2 = CLOSE, -- Temporary until further fix
|
||||
OnAccept = E.noop,
|
||||
timeout = 0,
|
||||
whileDead = 1,
|
||||
hideOnEscape = false
|
||||
}
|
||||
|
||||
E.PopupDialogs["CONFIGAURA_SET"] = {
|
||||
text = L["Because of the mass confusion caused by the new aura system I've implemented a new step to the installation process. This is optional. If you like how your auras are setup go to the last step and click finished to not be prompted again. If for some reason you are prompted repeatedly please restart your game."],
|
||||
button1 = ACCEPT,
|
||||
button2 = CLOSE, -- Temporary until further fix
|
||||
OnAccept = E.noop,
|
||||
timeout = 0,
|
||||
whileDead = 1,
|
||||
hideOnEscape = false
|
||||
}
|
||||
|
||||
E.PopupDialogs["QUEUE_TAINT"] = {
|
||||
text = L["You have changed your UIScale, however you still have the AutoScale option enabled in ElvUI. Press accept if you would like to disable the Auto Scale option."],
|
||||
button1 = ACCEPT,
|
||||
button2 = CANCEL,
|
||||
OnAccept = ReloadUI,
|
||||
timeout = 0,
|
||||
whileDead = 1,
|
||||
hideOnEscape = false
|
||||
}
|
||||
|
||||
E.PopupDialogs["FAILED_UISCALE"] = {
|
||||
text = L["You have changed your UIScale, however you still have the AutoScale option enabled in ElvUI. Press accept if you would like to disable the Auto Scale option."],
|
||||
button1 = ACCEPT,
|
||||
button2 = CANCEL,
|
||||
OnAccept = function() E.global.general.autoScale = false ReloadUI() end,
|
||||
timeout = 0,
|
||||
whileDead = 1,
|
||||
hideOnEscape = false
|
||||
}
|
||||
|
||||
E.PopupDialogs["CONFIG_RL"] = {
|
||||
text = L["One or more of the changes you have made require a ReloadUI."],
|
||||
button1 = ACCEPT,
|
||||
button2 = CANCEL,
|
||||
OnAccept = ReloadUI,
|
||||
timeout = 0,
|
||||
whileDead = 1,
|
||||
hideOnEscape = false
|
||||
}
|
||||
|
||||
E.PopupDialogs["GLOBAL_RL"] = {
|
||||
text = L["One or more of the changes you have made will effect all characters using this addon. You will have to reload the user interface to see the changes you have made."],
|
||||
button1 = ACCEPT,
|
||||
button2 = CANCEL,
|
||||
OnAccept = ReloadUI,
|
||||
timeout = 0,
|
||||
whileDead = 1,
|
||||
hideOnEscape = false
|
||||
}
|
||||
|
||||
E.PopupDialogs["PRIVATE_RL"] = {
|
||||
text = L["A setting you have changed will change an option for this character only. This setting that you have changed will be uneffected by changing user profiles. Changing this setting requires that you reload your User Interface."],
|
||||
button1 = ACCEPT,
|
||||
button2 = CANCEL,
|
||||
OnAccept = ReloadUI,
|
||||
timeout = 0,
|
||||
whileDead = 1,
|
||||
hideOnEscape = false
|
||||
}
|
||||
|
||||
E.PopupDialogs["KEYBIND_MODE"] = {
|
||||
text = L["Hover your mouse over any actionbutton or spellbook button to bind it. Press the escape key or right click to clear the current actionbutton's keybinding."],
|
||||
button1 = L["Save"],
|
||||
button2 = L["Discard"],
|
||||
OnAccept = function() E:GetModule("ActionBars"):DeactivateBindMode(true) end,
|
||||
OnCancel = function() E:GetModule("ActionBars"):DeactivateBindMode(false) end,
|
||||
timeout = 0,
|
||||
whileDead = 1,
|
||||
hideOnEscape = false
|
||||
}
|
||||
|
||||
E.PopupDialogs["DELETE_GRAYS"] = {
|
||||
text = L["Are you sure you want to delete all your gray items?"],
|
||||
button1 = YES,
|
||||
button2 = NO,
|
||||
OnAccept = function() E:GetModule("Bags"):VendorGrays(true) end,
|
||||
OnShow = function()
|
||||
MoneyFrame_Update(this:GetName().."MoneyFrame", E.PopupDialogs["DELETE_GRAYS"].Money)
|
||||
end,
|
||||
timeout = 0,
|
||||
whileDead = 1,
|
||||
hideOnEscape = false,
|
||||
hasMoneyFrame = 1
|
||||
}
|
||||
|
||||
E.PopupDialogs["BUY_BANK_SLOT"] = {
|
||||
text = CONFIRM_BUY_BANK_SLOT,
|
||||
button1 = YES,
|
||||
button2 = NO,
|
||||
OnAccept = PurchaseSlot,
|
||||
OnShow = function()
|
||||
MoneyFrame_Update(this:GetName().."MoneyFrame", GetBankSlotCost())
|
||||
end,
|
||||
hasMoneyFrame = 1,
|
||||
timeout = 0,
|
||||
hideOnEscape = 1
|
||||
}
|
||||
|
||||
E.PopupDialogs["CANNOT_BUY_BANK_SLOT"] = {
|
||||
text = L["Can't buy anymore slots!"],
|
||||
button1 = ACCEPT,
|
||||
button2 = CLOSE, -- Temporary until further fix
|
||||
timeout = 0,
|
||||
whileDead = 1
|
||||
}
|
||||
|
||||
E.PopupDialogs["NO_BANK_BAGS"] = {
|
||||
text = L["You must purchase a bank slot first!"],
|
||||
button1 = ACCEPT,
|
||||
button2 = CLOSE, -- Temporary until further fix
|
||||
timeout = 0,
|
||||
whileDead = 1
|
||||
}
|
||||
|
||||
E.PopupDialogs["RESETUI_CHECK"] = {
|
||||
text = L["Are you sure you want to reset every mover back to it's default position?"],
|
||||
button1 = ACCEPT,
|
||||
button2 = CANCEL,
|
||||
OnAccept = function()
|
||||
E:ResetAllUI()
|
||||
end,
|
||||
timeout = 0,
|
||||
whileDead = 1
|
||||
}
|
||||
|
||||
E.PopupDialogs["HARLEM_SHAKE"] = {
|
||||
text = L["ElvUI needs to perform database optimizations please be patient."],
|
||||
button1 = OKAY,
|
||||
button2 = CLOSE, -- Temporary until further fix
|
||||
OnAccept = function()
|
||||
if E.isMassiveShaking then
|
||||
E:StopHarlemShake()
|
||||
else
|
||||
E:BeginHarlemShake()
|
||||
return true
|
||||
end
|
||||
end,
|
||||
timeout = 0,
|
||||
whileDead = 1
|
||||
}
|
||||
|
||||
E.PopupDialogs["HELLO_KITTY"] = {
|
||||
text = L["ElvUI needs to perform database optimizations please be patient."],
|
||||
button1 = OKAY,
|
||||
button2 = CLOSE, -- Temporary until further fix
|
||||
OnAccept = function()
|
||||
E:SetupHelloKitty()
|
||||
end,
|
||||
timeout = 0,
|
||||
whileDead = 1
|
||||
}
|
||||
|
||||
E.PopupDialogs["HELLO_KITTY_END"] = {
|
||||
text = L["Do you enjoy the new ElvUI?"],
|
||||
button1 = L["Yes, Keep Changes!"],
|
||||
button2 = L["No, Revert Changes!"],
|
||||
OnAccept = function()
|
||||
E:Print(L["Type /hellokitty to revert to old settings."])
|
||||
StopMusic()
|
||||
SetCVar("Sound_EnableAllSound", E.oldEnableAllSound)
|
||||
SetCVar("Sound_EnableMusic", E.oldEnableMusic)
|
||||
end,
|
||||
OnCancel = function()
|
||||
E:RestoreHelloKitty()
|
||||
StopMusic()
|
||||
SetCVar("Sound_EnableAllSound", E.oldEnableAllSound)
|
||||
SetCVar("Sound_EnableMusic", E.oldEnableMusic)
|
||||
end,
|
||||
timeout = 0,
|
||||
whileDead = 1
|
||||
}
|
||||
|
||||
E.PopupDialogs["DISBAND_RAID"] = {
|
||||
text = L["Are you sure you want to disband the group?"],
|
||||
button1 = ACCEPT,
|
||||
button2 = CANCEL,
|
||||
OnAccept = function() E:GetModule("Misc"):DisbandRaidGroup() end,
|
||||
timeout = 0,
|
||||
whileDead = 1
|
||||
}
|
||||
|
||||
E.PopupDialogs["CONFIRM_LOOT_DISTRIBUTION"] = {
|
||||
text = CONFIRM_LOOT_DISTRIBUTION,
|
||||
button1 = YES,
|
||||
button2 = NO,
|
||||
timeout = 0,
|
||||
hideOnEscape = 1
|
||||
}
|
||||
|
||||
E.PopupDialogs["RESET_PROFILE_PROMPT"] = {
|
||||
text = L["Are you sure you want to reset all the settings on this profile?"],
|
||||
button1 = YES,
|
||||
button2 = NO,
|
||||
timeout = 0,
|
||||
hideOnEscape = 1,
|
||||
OnAccept = function() E:ResetProfile() end
|
||||
}
|
||||
|
||||
E.PopupDialogs["APPLY_FONT_WARNING"] = {
|
||||
text = L["Are you sure you want to apply this font to all ElvUI elements?"],
|
||||
OnAccept = function()
|
||||
local font = E.db.general.font
|
||||
local fontSize = E.db.general.fontSize
|
||||
|
||||
E.db.bags.itemLevelFont = font
|
||||
E.db.bags.itemLevelFontSize = fontSize
|
||||
E.db.bags.countFont = font
|
||||
E.db.bags.countFontSize = fontSize
|
||||
E.db.nameplates.font = font
|
||||
E.db.nameplates.fontSize = fontSize
|
||||
E.db.actionbar.font = font
|
||||
E.db.actionbar.fontSize = fontSize
|
||||
E.db.auras.font = font
|
||||
E.db.auras.fontSize = fontSize
|
||||
E.db.chat.font = font
|
||||
E.db.chat.fontSize = fontSize
|
||||
E.db.chat.tabFont = font
|
||||
E.db.chat.tapFontSize = fontSize
|
||||
E.db.datatexts.font = font
|
||||
E.db.datatexts.fontSize = fontSize
|
||||
E.db.tooltip.font = font
|
||||
E.db.tooltip.fontSize = fontSize
|
||||
E.db.tooltip.headerFontSize = fontSize
|
||||
E.db.tooltip.textFontSize = fontSize
|
||||
E.db.tooltip.smallTextFontSize = fontSize
|
||||
E.db.tooltip.healthBar.font = font
|
||||
E.db.tooltip.healthBar.fontSize = fontSize
|
||||
E.db.unitframe.font = font
|
||||
E.db.unitframe.fontSize = fontSize
|
||||
E.db.unitframe.units.party.rdebuffs.font = font
|
||||
E.db.unitframe.units.raid.rdebuffs.font = font
|
||||
E.db.unitframe.units.raid40.rdebuffs.font = font
|
||||
|
||||
E:UpdateAll(true)
|
||||
end,
|
||||
OnCancel = function() E:StaticPopup_Hide("APPLY_FONT_WARNING") end,
|
||||
button1 = YES,
|
||||
button2 = CANCEL,
|
||||
timeout = 0,
|
||||
whileDead = 1,
|
||||
hideOnEscape = false
|
||||
}
|
||||
|
||||
local MAX_STATIC_POPUPS = 4
|
||||
|
||||
function E:StaticPopup_OnShow()
|
||||
PlaySound("igMainMenuOpen")
|
||||
|
||||
local dialog = E.PopupDialogs[this.which]
|
||||
local OnShow = dialog.OnShow
|
||||
if OnShow then
|
||||
OnShow(this.data)
|
||||
end
|
||||
if dialog.enterClicksFirstButton then
|
||||
this:SetScript("OnKeyDown", E.StaticPopup_OnKeyDown)
|
||||
end
|
||||
end
|
||||
|
||||
function E:StaticPopup_EscapePressed()
|
||||
local closed = nil
|
||||
for _, frame in pairs(E.StaticPopup_DisplayedFrames) do
|
||||
if frame:IsShown() and frame.hideOnEscape then
|
||||
local standardDialog = E.PopupDialogs[frame.which]
|
||||
if standardDialog then
|
||||
local OnCancel = standardDialog.OnCancel
|
||||
local noCancelOnEscape = standardDialog.noCancelOnEscape
|
||||
if OnCancel and not noCancelOnEscape then
|
||||
OnCancel(frame, frame.data, "clicked")
|
||||
end
|
||||
frame:Hide()
|
||||
else
|
||||
E:StaticPopupSpecial_Hide(frame)
|
||||
end
|
||||
closed = 1
|
||||
end
|
||||
end
|
||||
return closed
|
||||
end
|
||||
|
||||
function E:StaticPopupSpecial_Hide(frame)
|
||||
frame:Hide()
|
||||
E:StaticPopup_CollapseTable()
|
||||
end
|
||||
|
||||
function E:StaticPopup_CollapseTable()
|
||||
local displayedFrames = E.StaticPopup_DisplayedFrames
|
||||
local index = getn(displayedFrames)
|
||||
while((index >= 1) and (not displayedFrames[index]:IsShown())) do
|
||||
tremove(displayedFrames, index)
|
||||
index = index - 1
|
||||
end
|
||||
end
|
||||
|
||||
function E:StaticPopup_SetUpPosition(dialog)
|
||||
if not tContains(E.StaticPopup_DisplayedFrames, dialog) then
|
||||
local lastFrame = E.StaticPopup_DisplayedFrames[getn(E.StaticPopup_DisplayedFrames)]
|
||||
if lastFrame then
|
||||
dialog:SetPoint("TOP", lastFrame, "BOTTOM", 0, -4)
|
||||
else
|
||||
dialog:SetPoint("TOP", E.UIParent, "TOP", 0, -100)
|
||||
end
|
||||
tinsert(E.StaticPopup_DisplayedFrames, dialog)
|
||||
end
|
||||
end
|
||||
|
||||
function E:StaticPopupSpecial_Show(frame)
|
||||
if frame.exclusive then
|
||||
E:StaticPopup_HideExclusive()
|
||||
end
|
||||
E:StaticPopup_SetUpPosition(frame)
|
||||
frame:Show()
|
||||
end
|
||||
|
||||
function E:StaticPopupSpecial_Hide(frame)
|
||||
frame:Hide()
|
||||
E:StaticPopup_CollapseTable()
|
||||
end
|
||||
|
||||
function E:StaticPopup_IsLastDisplayedFrame(frame)
|
||||
for i = getn(E.StaticPopup_DisplayedFrames), 1, -1 do
|
||||
local popup = E.StaticPopup_DisplayedFrames[i]
|
||||
if popup:IsShown() then
|
||||
return frame == popup
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
function E:StaticPopup_OnKeyDown(key)
|
||||
if GetBindingFromClick(key) == "TOGGLEGAMEMENU" then
|
||||
return E:StaticPopup_EscapePressed()
|
||||
elseif GetBindingFromClick(key) == "SCREENSHOT" then
|
||||
RunBinding("SCREENSHOT")
|
||||
return
|
||||
end
|
||||
|
||||
local dialog = E.PopupDialogs[this.which]
|
||||
if dialog then
|
||||
if arg1 == "ENTER" and dialog.enterClicksFirstButton then
|
||||
local frameName = this:GetName()
|
||||
local button
|
||||
local i = 1
|
||||
while true do
|
||||
button = _G[frameName.."Button"..i]
|
||||
if button then
|
||||
if button:IsShown() then
|
||||
E:StaticPopup_OnClick(this, i)
|
||||
return
|
||||
end
|
||||
i = i + 1
|
||||
else
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function E:StaticPopup_OnHide()
|
||||
PlaySound("igMainMenuClose")
|
||||
|
||||
E:StaticPopup_CollapseTable()
|
||||
|
||||
local dialog = E.PopupDialogs[this.which]
|
||||
local OnHide = dialog.OnHide
|
||||
if OnHide then
|
||||
OnHide(this.data)
|
||||
end
|
||||
if dialog.enterClicksFirstButton then
|
||||
this:SetScript("OnKeyDown", nil)
|
||||
end
|
||||
end
|
||||
|
||||
function E:StaticPopup_OnUpdate()
|
||||
if this.timeleft and this.timeleft > 0 then
|
||||
local which = this.which
|
||||
local timeleft = this.timeleft - arg1
|
||||
if timeleft <= 0 then
|
||||
if not E.PopupDialogs[which].timeoutInformationalOnly then
|
||||
this.timeleft = 0
|
||||
local OnCancel = E.PopupDialogs[which].OnCancel
|
||||
if OnCancel then
|
||||
OnCancel(this.data, "timeout")
|
||||
end
|
||||
this:Hide()
|
||||
end
|
||||
return
|
||||
end
|
||||
this.timeleft = timeleft
|
||||
end
|
||||
|
||||
if this.startDelay then
|
||||
local which = this.which
|
||||
local timeleft = this.startDelay - arg1
|
||||
if timeleft <= 0 then
|
||||
this.startDelay = nil
|
||||
local text = _G[this:GetName().."Text"]
|
||||
text:SetText(format(E.PopupDialogs[which].text, text.text_arg1, text.text_arg2))
|
||||
local button1 = _G[this:GetName().."Button1"]
|
||||
button1:Enable()
|
||||
StaticPopup_Resize(this, which)
|
||||
return
|
||||
end
|
||||
this.startDelay = timeleft
|
||||
end
|
||||
|
||||
local onUpdate = E.PopupDialogs[this.which].OnUpdate
|
||||
if onUpdate then
|
||||
onUpdate(arg1, this)
|
||||
end
|
||||
end
|
||||
|
||||
function E:StaticPopup_OnClick(index)
|
||||
if not self:IsShown() then
|
||||
return
|
||||
end
|
||||
local which = self.which
|
||||
local info = E.PopupDialogs[which]
|
||||
if not info then
|
||||
return nil
|
||||
end
|
||||
local hide = true
|
||||
if index == 1 then
|
||||
local OnAccept = info.OnAccept
|
||||
if OnAccept then
|
||||
hide = not OnAccept(self, self.data, self.data2)
|
||||
end
|
||||
elseif index == 3 then
|
||||
local OnAlt = info.OnAlt
|
||||
if OnAlt then
|
||||
OnAlt(self, self.data, "clicked")
|
||||
end
|
||||
else
|
||||
local OnCancel = info.OnCancel
|
||||
if OnCancel then
|
||||
hide = not OnCancel(self, self.data, "clicked")
|
||||
end
|
||||
end
|
||||
|
||||
if hide and (which == self.which) and (index ~= 3 or not info.noCloseOnAlt) then
|
||||
self:Hide()
|
||||
end
|
||||
end
|
||||
|
||||
function E:StaticPopup_EditBoxOnEnterPressed()
|
||||
local EditBoxOnEnterPressed, which, dialog
|
||||
local parent = this:GetParent()
|
||||
if parent.which then
|
||||
which = parent.which
|
||||
dialog = parent
|
||||
elseif parent:GetParent().which then
|
||||
which = parent:GetParent().which
|
||||
dialog = parent:GetParent()
|
||||
end
|
||||
EditBoxOnEnterPressed = E.PopupDialogs[which].EditBoxOnEnterPressed
|
||||
if EditBoxOnEnterPressed then
|
||||
EditBoxOnEnterPressed(this, dialog.data)
|
||||
end
|
||||
end
|
||||
|
||||
function E:StaticPopup_EditBoxOnEscapePressed()
|
||||
local EditBoxOnEscapePressed = E.PopupDialogs[this:GetParent().which].EditBoxOnEscapePressed
|
||||
if EditBoxOnEscapePressed then
|
||||
EditBoxOnEscapePressed(this, this:GetParent().data)
|
||||
end
|
||||
end
|
||||
|
||||
function E:StaticPopup_EditBoxOnTextChanged(userInput)
|
||||
local EditBoxOnTextChanged = E.PopupDialogs[this:GetParent().which].EditBoxOnTextChanged
|
||||
if EditBoxOnTextChanged then
|
||||
EditBoxOnTextChanged(this, this:GetParent().data)
|
||||
end
|
||||
end
|
||||
|
||||
function E:StaticPopup_FindVisible(which, data)
|
||||
local info = E.PopupDialogs[which]
|
||||
if not info then
|
||||
return nil
|
||||
end
|
||||
for index = 1, MAX_STATIC_POPUPS, 1 do
|
||||
local frame = _G["ElvUI_StaticPopup"..index]
|
||||
if (frame:IsShown() and (frame.which == which) and (not info.multiple or (frame.data == data))) then
|
||||
return frame
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function E:StaticPopup_Resize(dialog, which)
|
||||
local info = E.PopupDialogs[which]
|
||||
if not info then
|
||||
return nil
|
||||
end
|
||||
|
||||
local name = dialog:GetName()
|
||||
local text = _G[name.."Text"]
|
||||
local editBox = _G[name.."EditBox"]
|
||||
local button1 = _G[name.."Button1"]
|
||||
|
||||
local maxHeightSoFar, maxWidthSoFar = (dialog.maxHeightSoFar or 0), (dialog.maxWidthSoFar or 0)
|
||||
local width = 320
|
||||
|
||||
if dialog.numButtons == 3 then
|
||||
width = 440
|
||||
elseif info.showAlert or info.showAlertGear or info.closeButton then
|
||||
width = 420
|
||||
elseif info.editBoxWidth and info.editBoxWidth > 260 then
|
||||
width = width + (info.editBoxWidth - 260)
|
||||
end
|
||||
|
||||
if width > maxWidthSoFar then
|
||||
dialog:SetWidth(width)
|
||||
dialog.maxWidthSoFar = width
|
||||
end
|
||||
|
||||
local height = 32 + text:GetHeight() + 8 + button1:GetHeight()
|
||||
if info.hasEditBox then
|
||||
height = height + 8 + editBox:GetHeight()
|
||||
elseif info.hasMoneyFrame then
|
||||
height = height + 16
|
||||
end
|
||||
|
||||
if height > maxHeightSoFar then
|
||||
dialog:SetHeight(height)
|
||||
dialog.maxHeightSoFar = height
|
||||
end
|
||||
end
|
||||
|
||||
function E:StaticPopup_OnEvent()
|
||||
self.maxHeightSoFar = 0
|
||||
E:StaticPopup_Resize(self, self.which)
|
||||
end
|
||||
|
||||
local tempButtonLocs = {}
|
||||
function E:StaticPopup_Show(which, text_arg1, text_arg2, data)
|
||||
local info = E.PopupDialogs[which]
|
||||
if not info then
|
||||
return nil
|
||||
end
|
||||
|
||||
if UnitIsDeadOrGhost("player") and not info.whileDead then
|
||||
if info.OnCancel then
|
||||
info.OnCancel()
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
if InCinematic() and not info.interruptCinematic then
|
||||
if info.OnCancel then
|
||||
info.OnCancel()
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
if info.cancels then
|
||||
for index = 1, MAX_STATIC_POPUPS, 1 do
|
||||
local frame = _G["ElvUI_StaticPopup"..index]
|
||||
if (frame:IsShown() and (frame.which == info.cancels)) then
|
||||
frame:Hide()
|
||||
local OnCancel = E.PopupDialogs[frame.which].OnCancel
|
||||
if OnCancel then
|
||||
OnCancel(frame, frame.data, "override")
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local dialog = nil
|
||||
dialog = E:StaticPopup_FindVisible(which, data)
|
||||
if dialog then
|
||||
if not info.noCancelOnReuse then
|
||||
local OnCancel = info.OnCancel
|
||||
if OnCancel then
|
||||
OnCancel(dialog, dialog.data, "override")
|
||||
end
|
||||
end
|
||||
dialog:Hide()
|
||||
end
|
||||
if not dialog then
|
||||
local index = 1
|
||||
if info.preferredIndex then
|
||||
index = info.preferredIndex
|
||||
end
|
||||
for i = index, MAX_STATIC_POPUPS do
|
||||
local frame = _G["ElvUI_StaticPopup"..i]
|
||||
if not frame:IsShown() then
|
||||
dialog = frame
|
||||
break
|
||||
end
|
||||
end
|
||||
if not dialog and info.preferredIndex then
|
||||
for i = 1, info.preferredIndex do
|
||||
local frame = _G["ElvUI_StaticPopup"..i]
|
||||
if not frame:IsShown() then
|
||||
dialog = frame
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if not dialog then
|
||||
if info.OnCancel then
|
||||
info.OnCancel()
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
dialog.maxHeightSoFar, dialog.maxWidthSoFar = 0, 0
|
||||
|
||||
local name = dialog:GetName()
|
||||
local text = _G[name.."Text"]
|
||||
text:SetText(format(info.text, text_arg1, text_arg2))
|
||||
|
||||
if info.closeButton then
|
||||
local closeButton = _G[name.."CloseButton"]
|
||||
if info.closeButtonIsHide then
|
||||
closeButton:SetNormalTexture("Interface\\Buttons\\UI-Panel-HideButton-Up")
|
||||
closeButton:SetPushedTexture("Interface\\Buttons\\UI-Panel-HideButton-Down")
|
||||
else
|
||||
closeButton:SetNormalTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Up")
|
||||
closeButton:SetPushedTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Down")
|
||||
end
|
||||
closeButton:Show()
|
||||
else
|
||||
_G[name.."CloseButton"]:Hide()
|
||||
end
|
||||
|
||||
local editBox = _G[name.."EditBox"]
|
||||
if info.hasEditBox then
|
||||
editBox:Show()
|
||||
|
||||
if info.maxLetters then
|
||||
editBox:SetMaxLetters(info.maxLetters)
|
||||
end
|
||||
if info.maxBytes then
|
||||
editBox:SetMaxBytes(info.maxBytes)
|
||||
end
|
||||
editBox:SetText("")
|
||||
if info.editBoxWidth then
|
||||
editBox:SetWidth(info.editBoxWidth)
|
||||
else
|
||||
editBox:SetWidth(130)
|
||||
end
|
||||
else
|
||||
editBox:Hide()
|
||||
end
|
||||
|
||||
if info.hasMoneyFrame then
|
||||
_G[name.."MoneyFrame"]:Show()
|
||||
else
|
||||
_G[name.."MoneyFrame"]:Hide()
|
||||
end
|
||||
|
||||
dialog.which = which
|
||||
dialog.timeleft = info.timeout
|
||||
dialog.hideOnEscape = info.hideOnEscape
|
||||
dialog.exclusive = info.exclusive
|
||||
dialog.enterClicksFirstButton = info.enterClicksFirstButton
|
||||
dialog.data = data
|
||||
|
||||
local button1 = _G[name.."Button1"]
|
||||
local button2 = _G[name.."Button2"]
|
||||
|
||||
do
|
||||
assert(getn(tempButtonLocs) == 0)
|
||||
|
||||
tinsert(tempButtonLocs, button1)
|
||||
tinsert(tempButtonLocs, button2)
|
||||
|
||||
for i = getn(tempButtonLocs), 1, -1 do
|
||||
tempButtonLocs[i]:SetText(info["button"..i])
|
||||
tempButtonLocs[i]:Hide()
|
||||
tempButtonLocs[i]:ClearAllPoints()
|
||||
if not (info["button"..i] and (not info["DisplayButton"..i] or info["DisplayButton"..i](dialog))) then
|
||||
tremove(tempButtonLocs, i)
|
||||
end
|
||||
end
|
||||
|
||||
local numButtons = getn(tempButtonLocs)
|
||||
dialog.numButtons = numButtons
|
||||
if numButtons == 2 then
|
||||
tempButtonLocs[1]:SetPoint("BOTTOMRIGHT", dialog, "BOTTOM", -6, 16)
|
||||
elseif numButtons == 1 then
|
||||
tempButtonLocs[1]:SetPoint("BOTTOM", dialog, "BOTTOM", 0, 16)
|
||||
end
|
||||
|
||||
for i = 1, numButtons do
|
||||
if i > 1 then
|
||||
tempButtonLocs[i]:SetPoint("LEFT", tempButtonLocs[i-1], "RIGHT", 13, 0)
|
||||
end
|
||||
|
||||
local width = tempButtonLocs[i]:GetTextWidth()
|
||||
if width > 110 then
|
||||
tempButtonLocs[i]:SetWidth(width + 20)
|
||||
else
|
||||
tempButtonLocs[i]:SetWidth(120)
|
||||
end
|
||||
tempButtonLocs[i]:Enable()
|
||||
tempButtonLocs[i]:Show()
|
||||
end
|
||||
|
||||
wipe(tempButtonLocs)
|
||||
table.setn(tempButtonLocs, 0)
|
||||
end
|
||||
|
||||
local alertIcon = _G[name.."AlertIcon"]
|
||||
if info.showAlert then
|
||||
alertIcon:SetTexture("Interface\\DialogFrame\\DialogAlertIcon")
|
||||
alertIcon:SetPoint("LEFT", 24, 0)
|
||||
alertIcon:Show()
|
||||
elseif info.showAlertGear then
|
||||
alertIcon:SetTexture("Interface\\DialogFrame\\DialogAlertIcon")
|
||||
alertIcon:SetPoint("LEFT", 24, 0)
|
||||
alertIcon:Show()
|
||||
else
|
||||
alertIcon:SetTexture()
|
||||
alertIcon:Hide()
|
||||
end
|
||||
|
||||
if info.StartDelay then
|
||||
dialog.startDelay = info.StartDelay()
|
||||
button1:Disable()
|
||||
else
|
||||
dialog.startDelay = nil
|
||||
button1:Enable()
|
||||
end
|
||||
|
||||
E:StaticPopup_SetUpPosition(dialog)
|
||||
dialog:Show()
|
||||
|
||||
E:StaticPopup_Resize(dialog, which)
|
||||
|
||||
if info.sound then
|
||||
PlaySound(info.sound)
|
||||
end
|
||||
|
||||
return dialog
|
||||
end
|
||||
|
||||
function E:StaticPopup_Hide(which, data)
|
||||
for index = 1, MAX_STATIC_POPUPS, 1 do
|
||||
local dialog = _G["ElvUI_StaticPopup"..index]
|
||||
if ((dialog.which == which) and (not data or (data == dialog.data))) then
|
||||
dialog:Hide()
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function E:Contruct_StaticPopups()
|
||||
E.StaticPopupFrames = {}
|
||||
|
||||
local S = self:GetModule("Skins")
|
||||
for index = 1, MAX_STATIC_POPUPS do
|
||||
E.StaticPopupFrames[index] = CreateFrame("Frame", "ElvUI_StaticPopup"..index, E.UIParent, "StaticPopupTemplate")
|
||||
E.StaticPopupFrames[index]:SetID(index)
|
||||
|
||||
E.StaticPopupFrames[index]:SetScript("OnShow", E.StaticPopup_OnShow)
|
||||
E.StaticPopupFrames[index]:SetScript("OnHide", E.StaticPopup_OnHide)
|
||||
E.StaticPopupFrames[index]:SetScript("OnUpdate", E.StaticPopup_OnUpdate)
|
||||
E.StaticPopupFrames[index]:SetScript("OnEvent", E.StaticPopup_OnEvent)
|
||||
|
||||
local name = E.StaticPopupFrames[index]:GetName()
|
||||
for i = 1, 2 do
|
||||
local button = _G[name.."Button"..i]
|
||||
S:HandleButton(button)
|
||||
|
||||
button:SetScript("OnClick", function()
|
||||
E.StaticPopup_OnClick(this:GetParent(), this:GetID())
|
||||
end)
|
||||
|
||||
E.StaticPopupFrames[index]["button"..i] = button
|
||||
end
|
||||
|
||||
_G[name.."EditBox"]:SetScript("OnEnterPressed", E.StaticPopup_EditBoxOnEnterPressed)
|
||||
_G[name.."EditBox"]:SetScript("OnEscapePressed", E.StaticPopup_EditBoxOnEscapePressed)
|
||||
_G[name.."EditBox"]:SetScript("OnTextChanged", E.StaticPopup_EditBoxOnTextChanged)
|
||||
|
||||
E:SetTemplate(E.StaticPopupFrames[index], "Transparent")
|
||||
|
||||
E.StaticPopupFrames[index].text = _G[name.."Text"]
|
||||
E.StaticPopupFrames[index].editBox = _G[name.."EditBox"]
|
||||
|
||||
_G[name.."EditBox"]:DisableDrawLayer("BACKGROUND")
|
||||
|
||||
S:HandleEditBox(_G[name.."EditBox"])
|
||||
|
||||
S:HandleEditBox(_G[name.."MoneyInputFrameGold"])
|
||||
S:HandleEditBox(_G[name.."MoneyInputFrameSilver"])
|
||||
S:HandleEditBox(_G[name.."MoneyInputFrameCopper"])
|
||||
_G[name.."EditBox"].backdrop:SetPoint("TOPLEFT", -2, -4)
|
||||
_G[name.."EditBox"].backdrop:SetPoint("BOTTOMRIGHT", 2, 4)
|
||||
end
|
||||
|
||||
E:SecureHook("StaticPopup_Resize", "StaticPopup_SetUpPosition")
|
||||
E:SecureHook("StaticPopup_OnHide", "StaticPopup_CollapseTable")
|
||||
end
|
||||
+1146
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,549 @@
|
||||
local E, L, V, P, G = unpack(ElvUI) --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
|
||||
local D = E:NewModule("Distributor", "AceEvent-3.0","AceTimer-3.0","AceComm-3.0","AceSerializer-3.0");
|
||||
local LibCompress = LibStub:GetLibrary("LibCompress");
|
||||
local LibBase64 = LibStub("LibBase64-1.0");
|
||||
|
||||
--Cache global variables
|
||||
--Lua functions
|
||||
local tonumber, type, pcall, loadstring = tonumber, type, pcall, loadstring
|
||||
local len, format, split, find = string.len, string.format, string.split, string.find
|
||||
--WoW API / Variables
|
||||
local CreateFrame = CreateFrame
|
||||
local GetNumRaidMembers, UnitInRaid = GetNumRaidMembers, UnitInRaid
|
||||
local GetNumPartyMembers, UnitInParty = GetNumPartyMembers, UnitInParty
|
||||
local ACCEPT, CANCEL, YES, NO = ACCEPT, CANCEL, YES, NO
|
||||
|
||||
----------------------------------
|
||||
-- CONSTANTS
|
||||
----------------------------------
|
||||
|
||||
local REQUEST_PREFIX = "ELVUI_REQUEST"
|
||||
local REPLY_PREFIX = "ELVUI_REPLY"
|
||||
local TRANSFER_PREFIX = "ELVUI_TRANSFER"
|
||||
local TRANSFER_COMPLETE_PREFIX = "ELVUI_COMPLETE"
|
||||
|
||||
-- The active downloads
|
||||
local Downloads = {}
|
||||
local Uploads = {}
|
||||
|
||||
function D:Initialize()
|
||||
self:RegisterComm(REQUEST_PREFIX)
|
||||
self:RegisterEvent("CHAT_MSG_ADDON")
|
||||
|
||||
self.statusBar = CreateFrame("StatusBar", "ElvUI_Download", UIParent)
|
||||
E:RegisterStatusBar(self.statusBar)
|
||||
E:CreateBackdrop(self.statusBar, "Default")
|
||||
self.statusBar:SetStatusBarTexture(E.media.normTex)
|
||||
self.statusBar:SetStatusBarColor(0.95, 0.15, 0.15)
|
||||
self.statusBar:SetWidth(250)
|
||||
self.statusBar:SetWidth(18)
|
||||
self.statusBar.text = self.statusBar:CreateFontString(nil, "OVERLAY")
|
||||
E:FontTemplate(self.statusBar.text)
|
||||
self.statusBar.text:SetPoint("CENTER", 0, 0)
|
||||
self.statusBar:Hide()
|
||||
end
|
||||
|
||||
-- Used to start uploads
|
||||
function D:Distribute(target, otherServer, isGlobal)
|
||||
local profileKey, data
|
||||
if not isGlobal then
|
||||
if ElvDB.profileKeys then
|
||||
profileKey = ElvDB.profileKeys[E.myname.." - "..E.myrealm]
|
||||
end
|
||||
|
||||
data = ElvDB.profiles[profileKey]
|
||||
else
|
||||
profileKey = "global"
|
||||
data = ElvDB.global
|
||||
end
|
||||
|
||||
if not data or not profileKey then return end
|
||||
|
||||
local serialData = self:Serialize(data)
|
||||
local length = len(serialData)
|
||||
local message = format("%s:%d:%s", profileKey, length, target)
|
||||
|
||||
Uploads[profileKey] = {
|
||||
serialData = serialData,
|
||||
target = target,
|
||||
}
|
||||
|
||||
if otherServer then
|
||||
local numParty, numRaid = GetNumPartyMembers(), GetNumRaidMembers()
|
||||
if numRaid > 0 and UnitInRaid("target") then
|
||||
self:SendCommMessage(REQUEST_PREFIX, message, "RAID")
|
||||
elseif numParty > 0 and UnitInParty("target") then
|
||||
self:SendCommMessage(REQUEST_PREFIX, message, "PARTY")
|
||||
else
|
||||
E:Print(L["Must be in group with the player if he isn't on the same server as you."])
|
||||
return
|
||||
end
|
||||
else
|
||||
self:SendCommMessage(REQUEST_PREFIX, message, "WHISPER", target)
|
||||
end
|
||||
self:RegisterComm(REPLY_PREFIX)
|
||||
E:StaticPopup_Show("DISTRIBUTOR_WAITING")
|
||||
end
|
||||
|
||||
function D:CHAT_MSG_ADDON(_, _, message, _, sender)
|
||||
if not Downloads[sender] then return end
|
||||
local cur = len(message)
|
||||
local max = Downloads[sender].length
|
||||
Downloads[sender].current = Downloads[sender].current + cur
|
||||
|
||||
if Downloads[sender].current > max then
|
||||
Downloads[sender].current = max
|
||||
end
|
||||
|
||||
self.statusBar:SetValue(Downloads[sender].current)
|
||||
end
|
||||
|
||||
function D:OnCommReceived(prefix, msg, dist, sender)
|
||||
if prefix == REQUEST_PREFIX then
|
||||
local profile, length, sendTo = split(":", msg)
|
||||
|
||||
if dist ~= "WHISPER" and sendTo ~= E.myname then
|
||||
return
|
||||
end
|
||||
|
||||
if self.statusBar:IsShown() then
|
||||
self:SendCommMessage(REPLY_PREFIX, profile..":NO", dist, sender)
|
||||
return
|
||||
end
|
||||
|
||||
local textString = format(L["%s is attempting to share the profile %s with you. Would you like to accept the request?"], sender, profile)
|
||||
if profile == "global" then
|
||||
textString = format(L["%s is attempting to share his filters with you. Would you like to accept the request?"], sender)
|
||||
end
|
||||
|
||||
E.PopupDialogs["DISTRIBUTOR_RESPONSE"] = {
|
||||
text = textString,
|
||||
OnAccept = function()
|
||||
self.statusBar:SetMinMaxValues(0, length)
|
||||
self.statusBar:SetValue(0)
|
||||
self.statusBar.text:SetFormattedText(L["Data From: %s"], sender)
|
||||
E:StaticPopupSpecial_Show(self.statusBar)
|
||||
self:SendCommMessage(REPLY_PREFIX, profile..":YES", dist, sender)
|
||||
end,
|
||||
OnCancel = function()
|
||||
self:SendCommMessage(REPLY_PREFIX, profile..":NO", dist, sender)
|
||||
end,
|
||||
button1 = ACCEPT,
|
||||
button2 = CANCEL,
|
||||
timeout = 32,
|
||||
whileDead = 1,
|
||||
hideOnEscape = 1,
|
||||
}
|
||||
E:StaticPopup_Show("DISTRIBUTOR_RESPONSE")
|
||||
|
||||
Downloads[sender] = {
|
||||
current = 0,
|
||||
length = tonumber(length),
|
||||
profile = profile,
|
||||
}
|
||||
|
||||
self:RegisterComm(TRANSFER_PREFIX)
|
||||
elseif prefix == REPLY_PREFIX then
|
||||
self:UnregisterComm(REPLY_PREFIX)
|
||||
E:StaticPopup_Hide("DISTRIBUTOR_WAITING")
|
||||
|
||||
local profileKey, response = split(":", msg)
|
||||
if response == "YES" then
|
||||
self:RegisterComm(TRANSFER_COMPLETE_PREFIX)
|
||||
self:SendCommMessage(TRANSFER_PREFIX, Uploads[profileKey].serialData, dist, Uploads[profileKey].target)
|
||||
Uploads[profileKey] = nil
|
||||
else
|
||||
E:StaticPopup_Show("DISTRIBUTOR_REQUEST_DENIED")
|
||||
Uploads[profileKey] = nil
|
||||
end
|
||||
elseif prefix == TRANSFER_PREFIX then
|
||||
self:UnregisterComm(TRANSFER_PREFIX)
|
||||
E:StaticPopupSpecial_Hide(self.statusBar)
|
||||
|
||||
local profileKey = Downloads[sender].profile
|
||||
local success, data = self:Deserialize(msg)
|
||||
|
||||
if success then
|
||||
local textString = format(L["Profile download complete from %s, would you like to load the profile %s now?"], sender, profileKey)
|
||||
|
||||
if profileKey == "global" then
|
||||
textString = format(L["Filter download complete from %s, would you like to apply changes now?"], sender)
|
||||
else
|
||||
if not ElvDB.profiles[profileKey] then
|
||||
ElvDB.profiles[profileKey] = data
|
||||
else
|
||||
textString = format(L["Profile download complete from %s, but the profile %s already exists. Change the name or else it will overwrite the existing profile."], sender, profileKey)
|
||||
E.PopupDialogs["DISTRIBUTOR_CONFIRM"] = {
|
||||
text = textString,
|
||||
button1 = ACCEPT,
|
||||
hasEditBox = 1,
|
||||
editBoxWidth = 350,
|
||||
maxLetters = 127,
|
||||
OnAccept = function(self)
|
||||
ElvDB.profiles[self.editBox:GetText()] = data
|
||||
LibStub("AceAddon-3.0"):GetAddon("ElvUI").data:SetProfile(self.editBox:GetText())
|
||||
E:UpdateAll(true)
|
||||
Downloads[sender] = nil
|
||||
end,
|
||||
OnShow = function(self) self.editBox:SetText(profileKey) self.editBox:SetFocus() end,
|
||||
timeout = 0,
|
||||
exclusive = 1,
|
||||
whileDead = 1,
|
||||
hideOnEscape = 1,
|
||||
preferredIndex = 3
|
||||
}
|
||||
|
||||
E:StaticPopup_Show("DISTRIBUTOR_CONFIRM")
|
||||
self:SendCommMessage(TRANSFER_COMPLETE_PREFIX, "COMPLETE", dist, sender)
|
||||
return
|
||||
end
|
||||
end
|
||||
|
||||
E.PopupDialogs["DISTRIBUTOR_CONFIRM"] = {
|
||||
text = textString,
|
||||
OnAccept = function()
|
||||
if profileKey == "global" then
|
||||
E:CopyTable(ElvDB.global, data)
|
||||
E:UpdateAll(true)
|
||||
else
|
||||
LibStub("AceAddon-3.0"):GetAddon("ElvUI").data:SetProfile(profileKey)
|
||||
end
|
||||
Downloads[sender] = nil
|
||||
end,
|
||||
OnCancel = function()
|
||||
Downloads[sender] = nil
|
||||
end,
|
||||
button1 = YES,
|
||||
button2 = NO,
|
||||
whileDead = 1,
|
||||
hideOnEscape = 1,
|
||||
}
|
||||
|
||||
E:StaticPopup_Show("DISTRIBUTOR_CONFIRM")
|
||||
self:SendCommMessage(TRANSFER_COMPLETE_PREFIX, "COMPLETE", dist, sender)
|
||||
else
|
||||
E:StaticPopup_Show("DISTRIBUTOR_FAILED")
|
||||
self:SendCommMessage(TRANSFER_COMPLETE_PREFIX, "FAILED", dist, sender)
|
||||
end
|
||||
elseif prefix == TRANSFER_COMPLETE_PREFIX then
|
||||
self:UnregisterComm(TRANSFER_COMPLETE_PREFIX)
|
||||
if msg == "COMPLETE" then
|
||||
E:StaticPopup_Show("DISTRIBUTOR_SUCCESS")
|
||||
else
|
||||
E:StaticPopup_Show("DISTRIBUTOR_FAILED")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function GetProfileData(profileType)
|
||||
if not profileType or type(profileType) ~= "string" then
|
||||
E:Print("Bad argument #1 to 'GetProfileData' (string expected)")
|
||||
return
|
||||
end
|
||||
|
||||
local profileKey
|
||||
local profileData = {}
|
||||
|
||||
if profileType == "profile" then
|
||||
if ElvDB.profileKeys then
|
||||
profileKey = ElvDB.profileKeys[E.myname.." - "..E.myrealm]
|
||||
end
|
||||
|
||||
profileData = E:CopyTable(profileData , ElvDB.profiles[profileKey])
|
||||
profileData = E:RemoveTableDuplicates(profileData, P)
|
||||
elseif profileType == "private" then
|
||||
local privateProfileKey = E.myname.." - "..E.myrealm
|
||||
profileKey = "private"
|
||||
|
||||
profileData = E:CopyTable(profileData, ElvPrivateDB.profiles[privateProfileKey])
|
||||
profileData = E:RemoveTableDuplicates(profileData, V)
|
||||
elseif profileType == "global" then
|
||||
profileKey = "global"
|
||||
|
||||
profileData = E:CopyTable(profileData, ElvDB.global)
|
||||
profileData = E:RemoveTableDuplicates(profileData, G)
|
||||
elseif profileType == "filtersNP" then
|
||||
profileKey = "filtersNP"
|
||||
|
||||
profileData["nameplates"] = {}
|
||||
profileData["nameplates"]["filter"] = {}
|
||||
profileData["nameplates"]["filter"] = E:CopyTable(profileData["nameplates"]["filter"], ElvDB.global.nameplates.filter)
|
||||
profileData = E:RemoveTableDuplicates(profileData, G)
|
||||
elseif profileType == "filtersUF" then
|
||||
profileKey = "filtersUF"
|
||||
|
||||
profileData["unitframe"] = {}
|
||||
profileData["unitframe"]["aurafilters"] = {}
|
||||
profileData["unitframe"]["aurafilters"] = E:CopyTable(profileData["unitframe"]["aurafilters"], ElvDB.global.unitframe.aurafilters)
|
||||
profileData["unitframe"]["buffwatch"] = {}
|
||||
profileData["unitframe"]["buffwatch"] = E:CopyTable(profileData["unitframe"]["buffwatch"], ElvDB.global.unitframe.buffwatch)
|
||||
profileData = E:RemoveTableDuplicates(profileData, G)
|
||||
elseif profileType == "filtersAll" then
|
||||
profileKey = "filtersAll"
|
||||
|
||||
profileData["nameplates"] = {}
|
||||
profileData["nameplates"]["filter"] = {}
|
||||
profileData["nameplates"]["filter"] = E:CopyTable(profileData["nameplates"]["filter"], ElvDB.global.nameplates.filter)
|
||||
profileData["unitframe"] = {}
|
||||
profileData["unitframe"]["aurafilters"] = {}
|
||||
profileData["unitframe"]["aurafilters"] = E:CopyTable(profileData["unitframe"]["aurafilters"], ElvDB.global.unitframe.aurafilters)
|
||||
profileData["unitframe"]["buffwatch"] = {}
|
||||
profileData["unitframe"]["buffwatch"] = E:CopyTable(profileData["unitframe"]["buffwatch"], ElvDB.global.unitframe.buffwatch)
|
||||
profileData = E:RemoveTableDuplicates(profileData, G)
|
||||
end
|
||||
|
||||
return profileKey, profileData
|
||||
end
|
||||
|
||||
local function GetProfileExport(profileType, exportFormat)
|
||||
local profileExport, exportString
|
||||
local profileKey, profileData = GetProfileData(profileType)
|
||||
|
||||
if not profileKey or not profileData or (profileData and type(profileData) ~= "table") then
|
||||
E:Print("Error getting data from 'GetProfileData'")
|
||||
return
|
||||
end
|
||||
|
||||
if exportFormat == "text" then
|
||||
local serialData = D:Serialize(profileData)
|
||||
|
||||
exportString = D:CreateProfileExport(serialData, profileType, profileKey)
|
||||
|
||||
local compressedData = LibCompress:Compress(exportString)
|
||||
local encodedData = LibBase64:Encode(compressedData)
|
||||
profileExport = encodedData
|
||||
elseif exportFormat == "luaTable" then
|
||||
exportString = E:TableToLuaString(profileData)
|
||||
profileExport = D:CreateProfileExport(exportString, profileType, profileKey)
|
||||
elseif exportFormat == "luaPlugin" then
|
||||
profileExport = E:ProfileTableToPluginFormat(profileData, profileType)
|
||||
end
|
||||
|
||||
return profileKey, profileExport
|
||||
end
|
||||
|
||||
function D:CreateProfileExport(dataString, profileType, profileKey)
|
||||
local returnString
|
||||
|
||||
if profileType == "profile" then
|
||||
returnString = format("%s::%s::%s", dataString, profileType, profileKey)
|
||||
else
|
||||
returnString = format("%s::%s", dataString, profileType)
|
||||
end
|
||||
|
||||
return returnString
|
||||
end
|
||||
|
||||
function D:GetImportStringType(dataString)
|
||||
local stringType = ""
|
||||
|
||||
if LibBase64:IsBase64(dataString) then
|
||||
stringType = "Base64"
|
||||
elseif find(dataString, "{") then
|
||||
stringType = "Table"
|
||||
end
|
||||
|
||||
return stringType
|
||||
end
|
||||
|
||||
function D:Decode(dataString)
|
||||
local profileInfo, profileType, profileKey, profileData, message
|
||||
local stringType = self:GetImportStringType(dataString)
|
||||
|
||||
if stringType == "Base64" then
|
||||
local decodedData = LibBase64:Decode(dataString)
|
||||
local decompressedData, message = LibCompress:Decompress(decodedData)
|
||||
|
||||
if not decompressedData then
|
||||
E:Print("Error decompressing data:", message)
|
||||
return
|
||||
end
|
||||
|
||||
local serializedData, success
|
||||
serializedData, profileInfo = E:StringSplitMultiDelim(decompressedData, "^^::")
|
||||
|
||||
if not profileInfo then
|
||||
E:Print("Error importing profile. String is invalid or corrupted!")
|
||||
return
|
||||
end
|
||||
|
||||
serializedData = format("%s%s", serializedData, "^^")
|
||||
profileType, profileKey = E:StringSplitMultiDelim(profileInfo, "::")
|
||||
success, profileData = D:Deserialize(serializedData)
|
||||
|
||||
if not success then
|
||||
E:Print("Error deserializing:", profileData)
|
||||
return
|
||||
end
|
||||
elseif stringType == "Table" then
|
||||
local profileDataAsString
|
||||
profileDataAsString, profileInfo = E:StringSplitMultiDelim(dataString, "}::")
|
||||
|
||||
if not profileInfo then
|
||||
E:Print("Error extracting profile info. Invalid import string!")
|
||||
return
|
||||
end
|
||||
|
||||
if not profileDataAsString then
|
||||
E:Print("Error extracting profile data. Invalid import string!")
|
||||
return
|
||||
end
|
||||
|
||||
profileDataAsString = format("%s%s", profileDataAsString, "}")
|
||||
profileType, profileKey = E:StringSplitMultiDelim(profileInfo, "::")
|
||||
|
||||
local profileToTable = loadstring(format("%s %s", "return", profileDataAsString))
|
||||
if profileToTable then
|
||||
message, profileData = pcall(profileToTable)
|
||||
end
|
||||
|
||||
if not profileData or type(profileData) ~= "table" then
|
||||
E:Print("Error converting lua string to table:", message)
|
||||
return
|
||||
end
|
||||
end
|
||||
|
||||
return profileType, profileKey, profileData
|
||||
end
|
||||
|
||||
local function SetImportedProfile(profileType, profileKey, profileData, force)
|
||||
D.profileType = nil
|
||||
D.profileKey = nil
|
||||
D.profileData = nil
|
||||
|
||||
if profileType == "profile" then
|
||||
if not ElvDB.profiles[profileKey] or force then
|
||||
if force and E.data.keys.profile == profileKey then
|
||||
local tempKey = profileKey.."_Temp"
|
||||
E.data.keys.profile = tempKey
|
||||
end
|
||||
ElvDB.profiles[profileKey] = profileData
|
||||
E.data:SetProfile(profileKey)
|
||||
else
|
||||
D.profileType = profileType
|
||||
D.profileKey = profileKey
|
||||
D.profileData = profileData
|
||||
E:StaticPopup_Show("IMPORT_PROFILE_EXISTS")
|
||||
|
||||
return
|
||||
end
|
||||
elseif profileType == "private" then
|
||||
local profileKey = ElvPrivateDB.profileKeys[E.myname.." - "..E.myrealm]
|
||||
ElvPrivateDB.profiles[profileKey] = profileData
|
||||
E:StaticPopup_Show("IMPORT_RL")
|
||||
|
||||
elseif profileType == "global" then
|
||||
E:CopyTable(ElvDB.global, profileData)
|
||||
E:StaticPopup_Show("IMPORT_RL")
|
||||
elseif profileType == "filtersNP" then
|
||||
E:CopyTable(ElvDB.global.nameplates, profileData.nameplates)
|
||||
elseif profileType == "filtersUF" then
|
||||
E:CopyTable(ElvDB.global.unitframe, profileData.unitframe)
|
||||
elseif profileType == "filtersAll" then
|
||||
E:CopyTable(ElvDB.global.nameplates, profileData.nameplates)
|
||||
E:CopyTable(ElvDB.global.unitframe, profileData.unitframe)
|
||||
end
|
||||
|
||||
E:UpdateAll(true)
|
||||
end
|
||||
|
||||
function D:ExportProfile(profileType, exportFormat)
|
||||
if not profileType or not exportFormat then
|
||||
E:Print("Bad argument to 'ExportProfile' (string expected)")
|
||||
return
|
||||
end
|
||||
|
||||
local profileKey, profileExport = GetProfileExport(profileType, exportFormat)
|
||||
return profileKey, profileExport
|
||||
end
|
||||
|
||||
function D:ImportProfile(dataString)
|
||||
print(self)
|
||||
local profileType, profileKey, profileData = self:Decode(dataString)
|
||||
|
||||
if not profileData or type(profileData) ~= "table" then
|
||||
E:Print("Error: something went wrong when converting string to table!")
|
||||
return
|
||||
end
|
||||
|
||||
if profileType and ((profileType == "profile" and profileKey) or profileType ~= "profile") then
|
||||
SetImportedProfile(profileType, profileKey, profileData)
|
||||
end
|
||||
|
||||
return true
|
||||
end
|
||||
|
||||
E.PopupDialogs["DISTRIBUTOR_SUCCESS"] = {
|
||||
text = L["Your profile was successfully recieved by the player."],
|
||||
whileDead = 1,
|
||||
hideOnEscape = 1,
|
||||
button1 = OKAY,
|
||||
}
|
||||
|
||||
E.PopupDialogs["DISTRIBUTOR_WAITING"] = {
|
||||
text = L["Profile request sent. Waiting for response from player."],
|
||||
whileDead = 1,
|
||||
hideOnEscape = 1,
|
||||
timeout = 35,
|
||||
}
|
||||
|
||||
E.PopupDialogs["DISTRIBUTOR_REQUEST_DENIED"] = {
|
||||
text = L["Request was denied by user."],
|
||||
whileDead = 1,
|
||||
hideOnEscape = 1,
|
||||
button1 = OKAY,
|
||||
}
|
||||
|
||||
E.PopupDialogs["DISTRIBUTOR_FAILED"] = {
|
||||
text = L["Lord! It's a miracle! The download up and vanished like a fart in the wind! Try Again!"],
|
||||
whileDead = 1,
|
||||
hideOnEscape = 1,
|
||||
button1 = OKAY,
|
||||
}
|
||||
|
||||
E.PopupDialogs["DISTRIBUTOR_RESPONSE"] = {}
|
||||
E.PopupDialogs["DISTRIBUTOR_CONFIRM"] = {}
|
||||
|
||||
E.PopupDialogs["IMPORT_PROFILE_EXISTS"] = {
|
||||
text = L["The profile you tried to import already exists. Choose a new name or accept to overwrite the existing profile."],
|
||||
button1 = ACCEPT,
|
||||
button2 = CANCEL,
|
||||
hasEditBox = 1,
|
||||
editBoxWidth = 350,
|
||||
maxLetters = 127,
|
||||
OnAccept = function(self)
|
||||
local profileType = D.profileType
|
||||
local profileKey = self.editBox:GetText()
|
||||
local profileData = D.profileData
|
||||
SetImportedProfile(profileType, profileKey, profileData, true)
|
||||
end,
|
||||
EditBoxOnTextChanged = function(self)
|
||||
if self:GetText() == "" then
|
||||
self:GetParent().button1:Disable()
|
||||
else
|
||||
self:GetParent().button1:Enable()
|
||||
end
|
||||
end,
|
||||
OnShow = function() this.editBox:SetText(D.profileKey) this.editBox:SetFocus() end,
|
||||
timeout = 0,
|
||||
whileDead = 1,
|
||||
hideOnEscape = true,
|
||||
preferredIndex = 3
|
||||
}
|
||||
|
||||
E.PopupDialogs["IMPORT_RL"] = {
|
||||
text = L["You have imported settings which may require a UI reload to take effect. Reload now?"],
|
||||
button1 = ACCEPT,
|
||||
button2 = CANCEL,
|
||||
OnAccept = ReloadUI,
|
||||
timeout = 0,
|
||||
whileDead = 1,
|
||||
hideOnEscape = false,
|
||||
preferredIndex = 3
|
||||
}
|
||||
|
||||
local function InitializeCallback()
|
||||
D:Initialize()
|
||||
end
|
||||
|
||||
E:RegisterModule(D:GetName(), InitializeCallback)
|
||||
@@ -0,0 +1,89 @@
|
||||
local E, L, V, P, G = unpack(ElvUI); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
|
||||
|
||||
--Cache global variables
|
||||
--Lua functions
|
||||
local tinsert = tinsert
|
||||
--WoW API / Variables
|
||||
local CreateFrame = CreateFrame
|
||||
local ToggleFrame = ToggleFrame
|
||||
local GetCursorPosition = GetCursorPosition
|
||||
|
||||
local PADDING = 10
|
||||
local BUTTON_HEIGHT = 16
|
||||
local BUTTON_WIDTH = 135
|
||||
|
||||
local function OnClick(btn)
|
||||
btn.func()
|
||||
|
||||
btn:GetParent():Hide()
|
||||
end
|
||||
|
||||
local function OnEnter(btn)
|
||||
btn.hoverTex:Show()
|
||||
end
|
||||
|
||||
local function OnLeave(btn)
|
||||
btn.hoverTex:Hide()
|
||||
end
|
||||
|
||||
function E:DropDown(list, frame, xOffset, yOffset)
|
||||
if not frame.buttons then
|
||||
frame.buttons = {}
|
||||
frame:SetFrameStrata("DIALOG")
|
||||
frame:SetClampedToScreen(true)
|
||||
tinsert(UISpecialFrames, frame:GetName())
|
||||
frame:Hide()
|
||||
end
|
||||
|
||||
xOffset = xOffset or 0
|
||||
yOffset = yOffset or 0
|
||||
|
||||
for i = 1, getn(frame.buttons) do
|
||||
frame.buttons[i]:Hide()
|
||||
end
|
||||
|
||||
for i = 1, getn(list) do
|
||||
if not frame.buttons[i] then
|
||||
frame.buttons[i] = CreateFrame("Button", nil, frame)
|
||||
|
||||
frame.buttons[i].hoverTex = frame.buttons[i]:CreateTexture(nil, "OVERLAY")
|
||||
frame.buttons[i].hoverTex:SetAllPoints()
|
||||
frame.buttons[i].hoverTex:SetTexture([[Interface\QuestFrame\UI-QuestTitleHighlight]])
|
||||
frame.buttons[i].hoverTex:SetBlendMode("ADD")
|
||||
frame.buttons[i].hoverTex:Hide()
|
||||
|
||||
frame.buttons[i].text = frame.buttons[i]:CreateFontString(nil, "BORDER")
|
||||
frame.buttons[i].text:SetAllPoints()
|
||||
frame.buttons[i].text:FontTemplate()
|
||||
frame.buttons[i].text:SetJustifyH("LEFT")
|
||||
|
||||
frame.buttons[i]:SetScript("OnEnter", OnEnter)
|
||||
frame.buttons[i]:SetScript("OnLeave", OnLeave)
|
||||
end
|
||||
|
||||
frame.buttons[i]:Show()
|
||||
frame.buttons[i]:SetHeight(BUTTON_HEIGHT)
|
||||
frame.buttons[i]:SetWidth(BUTTON_WIDTH)
|
||||
frame.buttons[i].text:SetText(list[i].text)
|
||||
frame.buttons[i].func = list[i].func
|
||||
frame.buttons[i]:SetScript("OnClick", OnClick)
|
||||
|
||||
if i == 1 then
|
||||
frame.buttons[i]:SetPoint("TOPLEFT", frame, "TOPLEFT", PADDING, -PADDING)
|
||||
else
|
||||
frame.buttons[i]:SetPoint("TOPLEFT", frame.buttons[i-1], "BOTTOMLEFT")
|
||||
end
|
||||
end
|
||||
|
||||
frame:SetHeight((getn(list) * BUTTON_HEIGHT) + PADDING * 2)
|
||||
frame:SetWidth(BUTTON_WIDTH + PADDING * 2)
|
||||
|
||||
local UIScale = UIParent:GetScale()
|
||||
local x, y = GetCursorPosition()
|
||||
x = x/UIScale
|
||||
y = y/UIScale
|
||||
frame:ClearAllPoints()
|
||||
frame:SetPoint("TOPLEFT", UIParent, "BOTTOMLEFT", x + xOffset, y + yOffset)
|
||||
|
||||
ToggleFrame(frame)
|
||||
end
|
||||
@@ -0,0 +1,90 @@
|
||||
local E, L, V, P, G = unpack(ElvUI); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
|
||||
local LSM = LibStub("LibSharedMedia-3.0");
|
||||
|
||||
--Cache global variables
|
||||
--Lua functions
|
||||
|
||||
--WoW API / Variables
|
||||
local SetCVar = SetCVar
|
||||
|
||||
local function SetFont(obj, font, size, style, r, g, b, sr, sg, sb, sox, soy)
|
||||
if(not obj) then return end
|
||||
|
||||
obj:SetFont(font, size, style)
|
||||
if sr and sg and sb then obj:SetShadowColor(sr, sg, sb) end
|
||||
if sox and soy then obj:SetShadowOffset(sox, soy) end
|
||||
if r and g and b then obj:SetTextColor(r, g, b)
|
||||
elseif r then obj:SetAlpha(r) end
|
||||
end
|
||||
|
||||
function E:UpdateBlizzardFonts()
|
||||
local NORMAL = self["media"].normFont
|
||||
local COMBAT = LSM:Fetch("font", self.private.general.dmgfont)
|
||||
local NUMBER = self["media"].normFont
|
||||
local NAMEFONT = LSM:Fetch("font", self.private.general.namefont)
|
||||
local MONOCHROME = ""
|
||||
|
||||
UIDROPDOWNMENU_DEFAULT_TEXT_HEIGHT = 12
|
||||
CHAT_FONT_HEIGHTS = {10, 12, 13, 14, 15, 16, 17, 18, 19, 20}
|
||||
|
||||
UNIT_NAME_FONT = NAMEFONT
|
||||
NAMEPLATE_FONT = NAMEFONT
|
||||
DAMAGE_TEXT_FONT = COMBAT
|
||||
STANDARD_TEXT_FONT = NORMAL
|
||||
|
||||
if self.db.general.font == "Homespun" then
|
||||
MONOCHROME = "MONOCHROME"
|
||||
end
|
||||
|
||||
if self.eyefinity then
|
||||
-- damage are huge on eyefinity, so we disable it
|
||||
InterfaceOptionsCombatTextPanelTargetDamage:Hide()
|
||||
InterfaceOptionsCombatTextPanelPeriodicDamage:Hide()
|
||||
InterfaceOptionsCombatTextPanelPetDamage:Hide()
|
||||
InterfaceOptionsCombatTextPanelHealing:Hide()
|
||||
SetCVar("CombatLogPeriodicSpells",0)
|
||||
SetCVar("PetMeleeDamage",0)
|
||||
SetCVar("CombatDamage",0)
|
||||
SetCVar("CombatHealing",0)
|
||||
|
||||
-- set an invisible font for xp, honor kill, etc
|
||||
local INVISIBLE = "Interface\\Addons\\ElvUI\\Media\\Fonts\\Invisible.ttf"
|
||||
COMBAT = INVISIBLE
|
||||
end
|
||||
|
||||
if(self.private.general.replaceBlizzFonts) then
|
||||
SetFont(SystemFont, NORMAL, self.db.general.fontSize);
|
||||
SetFont(GameFontNormal, NORMAL, self.db.general.fontSize);
|
||||
SetFont(GameFontNormalSmall, NORMAL, self.db.general.fontSize);
|
||||
SetFont(GameFontNormalLarge, NORMAL, self.db.general.fontSize);
|
||||
SetFont(GameFontNormalHuge, NORMAL, 25, MONOCHROME .. "OUTLINE");
|
||||
SetFont(BossEmoteNormalHuge, NORMAL, 25, MONOCHROME .. "OUTLINE");
|
||||
SetFont(GameFontBlack, NORMAL, self.db.general.fontSize);
|
||||
SetFont(NumberFontNormal, NUMBER, self.db.general.fontSize, MONOCHROME .. "OUTLINE");
|
||||
SetFont(NumberFontNormalSmall, NUMBER, self.db.general.fontSize);
|
||||
SetFont(NumberFontNormalLarge, NUMBER, self.db.general.fontSize);
|
||||
SetFont(NumberFontNormalHuge, NUMBER, self.db.general.fontSize);
|
||||
SetFont(ChatFontNormal, NORMAL, self.db.general.fontSize);
|
||||
SetFont(ChatFontSmall, NORMAL, self.db.general.fontSize);
|
||||
SetFont(QuestTitleFont, NORMAL, self.db.general.fontSize + 8);
|
||||
SetFont(QuestFont, NORMAL, self.db.general.fontSize);
|
||||
SetFont(QuestFontHighlight, NORMAL, self.db.general.fontSize);
|
||||
SetFont(ItemTextFontNormal, NORMAL, self.db.general.fontSize);
|
||||
SetFont(ItemTextFontNormal, NORMAL, self.db.general.fontSize);
|
||||
SetFont(MailTextFontNormal, NORMAL, self.db.general.fontSize);
|
||||
SetFont(SubSpellFont, NORMAL, self.db.general.fontSize);
|
||||
SetFont(DialogButtonNormalText, NORMAL, self.db.general.fontSize);
|
||||
SetFont(ZoneTextFont, NORMAL, 32, MONOCHROME .. "OUTLINE");
|
||||
SetFont(SubZoneTextFont, NORMAL, 25, MONOCHROME .. "OUTLINE");
|
||||
SetFont(PVPInfoTextFont, NORMAL, 22, MONOCHROME .. "OUTLINE");
|
||||
SetFont(TextStatusBarText, NORMAL, self.db.general.fontSize);
|
||||
SetFont(TextStatusBarTextSmall, NORMAL, self.db.general.fontSize);
|
||||
-- SetFont(GameTooltipText, NORMAL, self.db.general.fontSize);
|
||||
-- SetFont(GameTooltipTextSmall, NORMAL, self.db.general.fontSize);
|
||||
-- SetFont(GameTooltipHeaderText, NORMAL, self.db.general.fontSize);
|
||||
SetFont(WorldMapTextFont, NORMAL, 32, MONOCHROME .. "OUTLINE");
|
||||
SetFont(InvoiceTextFontNormal, NORMAL, self.db.general.fontSize);
|
||||
SetFont(InvoiceTextFontSmall, NORMAL, self.db.general.fontSize);
|
||||
SetFont(CombatTextFont, COMBAT, 25, MONOCHROME .. "OUTLINE");
|
||||
end
|
||||
end
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,133 @@
|
||||
local E, L, V, P, G = unpack(ElvUI); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
|
||||
|
||||
--Cache global variables
|
||||
--Lua functions
|
||||
local abs, floor, min, max = math.abs, math.floor, math.min, math.max;
|
||||
local match = string.match;
|
||||
--WoW API / Variables
|
||||
local IsMacClient = IsMacClient;
|
||||
local GetCVar, SetCVar = GetCVar, SetCVar;
|
||||
local GetScreenHeight, GetScreenWidth = GetScreenHeight, GetScreenWidth;
|
||||
|
||||
local scale
|
||||
|
||||
function E:UIScale(event)
|
||||
if IsMacClient() and self.global.screenheight and self.global.screenwidth and (self.screenheight ~= self.global.screenheight or self.screenwidth ~= self.global.screenwidth) then
|
||||
self.screenheight = self.global.screenheight
|
||||
self.screenwidth = self.global.screenwidth
|
||||
end
|
||||
|
||||
if(GetCVar("UIScale")) then
|
||||
self.global.uiScale = GetCVar("UIScale");
|
||||
end
|
||||
|
||||
local minScale = self.global.general.minUiScale or 0.64;
|
||||
if(self.global.general.autoScale) then
|
||||
scale = max(minScale, min(1.00, 768/self.screenheight));
|
||||
else
|
||||
scale = max(minScale, min(1.00, self.global.uiScale or UIParent:GetScale() or 768/self.screenheight));
|
||||
end
|
||||
|
||||
if self.screenwidth < 1600 then
|
||||
self.lowversion = true;
|
||||
elseif self.screenwidth >= 3840 and self.global.general.eyefinity then
|
||||
local width = self.screenwidth;
|
||||
local height = self.screenheight;
|
||||
|
||||
-- because some user enable bezel compensation, we need to find the real width of a single monitor.
|
||||
-- I don't know how it really work, but i'm assuming they add pixel to width to compensate the bezel. :P
|
||||
|
||||
-- HQ resolution
|
||||
if width >= 9840 then width = 3280; end -- WQSXGA
|
||||
if width >= 7680 and width < 9840 then width = 2560; end -- WQXGA
|
||||
if width >= 5760 and width < 7680 then width = 1920; end -- WUXGA & HDTV
|
||||
if width >= 5040 and width < 5760 then width = 1680; end -- WSXGA+
|
||||
|
||||
-- adding height condition here to be sure it work with bezel compensation because WSXGA+ and UXGA/HD+ got approx same width
|
||||
if width >= 4800 and width < 5760 and height == 900 then width = 1600; end -- UXGA & HD+
|
||||
|
||||
-- low resolution screen
|
||||
if width >= 4320 and width < 4800 then width = 1440; end -- WSXGA
|
||||
if width >= 4080 and width < 4320 then width = 1360; end -- WXGA
|
||||
if width >= 3840 and width < 4080 then width = 1224; end -- SXGA & SXGA (UVGA) & WXGA & HDTV
|
||||
|
||||
-- yep, now set ElvUI to lower resolution if screen #1 width < 1600
|
||||
if width < 1600 then
|
||||
self.lowversion = true;
|
||||
end
|
||||
|
||||
-- register a constant, we will need it later for launch.lua
|
||||
self.eyefinity = width;
|
||||
end
|
||||
|
||||
self.mult = 768/match(GetCVar("gxResolution"), "%d+x(%d+)")/scale;
|
||||
self.Spacing = self.PixelMode and 0 or self.mult;
|
||||
self.Border = (self.PixelMode and self.mult or self.mult*2);
|
||||
--Set UIScale, NOTE: SetCVar for UIScale can cause taints so only do this when we need to..
|
||||
if E.Round and E:Round(UIParent:GetScale(), 5) ~= E:Round(scale, 5) and (event == "PLAYER_LOGIN") then
|
||||
SetCVar("UseUIScale", 1);
|
||||
SetCVar("UIScale", scale);
|
||||
WorldMapFrame.hasTaint = true;
|
||||
end
|
||||
|
||||
if (event == "PLAYER_LOGIN" or event == "UPDATE_FLOATING_CHAT_WINDOWS") then
|
||||
if IsMacClient() then
|
||||
self.global.screenheight = floor(GetScreenHeight()*100+.5)/100
|
||||
self.global.screenwidth = floor(GetScreenWidth()*100+.5)/100
|
||||
end
|
||||
|
||||
--Resize self.UIParent if Eyefinity is on.
|
||||
if self.eyefinity then
|
||||
local width = self.eyefinity;
|
||||
local height = self.screenheight;
|
||||
|
||||
-- if autoscale is off, find a new width value of self.UIParent for screen #1.
|
||||
if not self.global.general.autoScale or height > 1200 then
|
||||
local h = UIParent:GetHeight();
|
||||
local ratio = self.screenheight / h;
|
||||
local w = self.eyefinity / ratio;
|
||||
|
||||
width = w;
|
||||
height = h;
|
||||
end
|
||||
|
||||
self.UIParent:SetWidth(width);
|
||||
self.UIParent:SetHeight(height);
|
||||
else
|
||||
--[[Eyefinity Test mode
|
||||
Resize the E.UIParent to be smaller than it should be, all objects inside should relocate.
|
||||
Dragging moveable frames outside the box and reloading the UI ensures that they are saving position correctly.
|
||||
]]
|
||||
--self.UIParent:SetSize(UIParent:GetWidth() - 250, UIParent:GetHeight() - 250);
|
||||
|
||||
self.UIParent:SetWidth(GetScreenWidth());
|
||||
self.UIParent:SetHeight(GetScreenHeight());
|
||||
end
|
||||
|
||||
self.UIParent:ClearAllPoints();
|
||||
self.UIParent:SetPoint("CENTER", UIParent);
|
||||
|
||||
self.diffGetLeft = E:Round(abs(UIParent:GetLeft() - self.UIParent:GetLeft()));
|
||||
self.diffGetRight = E:Round(abs(UIParent:GetRight() - self.UIParent:GetRight()));
|
||||
self.diffGetTop = E:Round(abs(UIParent:GetTop() - self.UIParent:GetTop()));
|
||||
self.diffGetBottom = E:Round(abs(UIParent:GetBottom() - self.UIParent:GetBottom()));
|
||||
|
||||
local change
|
||||
if E.Round then
|
||||
change = abs((E:Round(UIParent:GetScale(), 5) * 100) - (E:Round(scale, 5) * 100))
|
||||
end
|
||||
|
||||
if event == "UPDATE_FLOATING_CHAT_WINDOWS" and change and change > 1 and self.global.general.autoScale then
|
||||
E:StaticPopup_Show("FAILED_UISCALE")
|
||||
elseif event == "UPDATE_FLOATING_CHAT_WINDOWS" and change and change > 1 then
|
||||
E:StaticPopup_Show("CONFIG_RL")
|
||||
end
|
||||
|
||||
self:UnregisterEvent("PLAYER_LOGIN")
|
||||
end
|
||||
end
|
||||
|
||||
-- pixel perfect script of custom ui scale.
|
||||
function E:Scale(x)
|
||||
return self.mult*floor(x/self.mult+.5);
|
||||
end
|
||||
@@ -0,0 +1,480 @@
|
||||
--Plugins pass their info using the table like:
|
||||
--[[
|
||||
addon = {
|
||||
Title = "Your Own Title",
|
||||
Name = "AddOnName",
|
||||
tutorialImage = "TexturePath",
|
||||
Pages = {
|
||||
[1] = function1,
|
||||
[2] = function2,
|
||||
[3] = function3,
|
||||
},
|
||||
StepTitles = {
|
||||
[1] = "Title 1",
|
||||
[2] = "Title 2",
|
||||
[3] = "Title 3",
|
||||
},
|
||||
StepTitlesColor = {r,g,b},
|
||||
StepTitlesColorSelected = {r,g,b},
|
||||
StepTitleWidth = 140,
|
||||
StepTitleButtonWidth = 130,
|
||||
StepTitleTextJustification = "CENTER",
|
||||
}
|
||||
E:GetModule("PluginInstaller"):Queue(addon)
|
||||
|
||||
Title is wat displayed on top of the window. By default it's ""ElvUI Plugin Installation""
|
||||
Name is how your installation will be showin in "pending list", Default is "Unknown"
|
||||
tutorialImage is a path to your own texture to use in frame. if not specified, then it will use ElvUI's one
|
||||
Pages is a table to set up pages of your install where numbers are representing actual pages' order and function is what previously was used to set layout. For example
|
||||
function function1()
|
||||
PluginInstallFrame.SubTitle:SetText("Title Text")
|
||||
PluginInstallFrame.Desc1:SetText("Desc 1 Tet")
|
||||
PluginInstallFrame.Desc2:SetText("Desc 2 Tet")
|
||||
PluginInstallFrame.Desc3:SetText("Desc 3 Tet")
|
||||
|
||||
PluginInstallFrame.Option1:Show()
|
||||
PluginInstallFrame.Option1:SetScript("OnClick", function() <Do Some Stuff> end)
|
||||
PluginInstallFrame.Option1:SetText("Text 1")
|
||||
|
||||
PluginInstallFrame.Option2:Show()
|
||||
PluginInstallFrame.Option2:SetScript("OnClick", function() <Do Some Other Stuff> end)
|
||||
PluginInstallFrame.Option2:SetText("Text 2")
|
||||
end
|
||||
StepTitles - a table to specify "titles" for your install steps. If specified and number of lines here = number of pages then you'll get an additional frame to the right of main frame
|
||||
with a list of steps (current one being highlighted), clicking on those will open respective step. BenikUI style of doing stuff.
|
||||
StepTitlesColor - a table with color values to color "titles" when they are not active
|
||||
StepTitlesColorSelected - a table with color values to color "titles" when they are active
|
||||
StepTitleWidth - Width of the steps frame on the right side
|
||||
StepTitleButtonWidth - Width of each step button in the steps frame
|
||||
StepTitleTextJustification - The justification of the text on each step button ("LEFT", "RIGHT", "CENTER"). Default: "CENTER"
|
||||
]]
|
||||
|
||||
local E, L, V, P, G, _ = unpack(ElvUI); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
|
||||
local PI = E:NewModule("PluginInstaller");
|
||||
|
||||
--Cache global variables
|
||||
--Lua functions
|
||||
local _G = _G
|
||||
local pairs, unpack = pairs, unpack
|
||||
local tinsert, tremove = tinsert, tremove
|
||||
local format = string.format
|
||||
--WoW API / Variables
|
||||
local CreateFrame = CreateFrame
|
||||
local PlaySoundFile = PlaySoundFile
|
||||
local UIFrameFadeOut = UIFrameFadeOut
|
||||
local CreateAnimationGroup = CreateAnimationGroup
|
||||
local CONTINUE, PREV, UNKNOWN = CONTINUE, PREV, UNKNOWN
|
||||
|
||||
--Global variables that we don't cache, list them here for the mikk's Find Globals script
|
||||
-- GLOBALS: PluginInstallFrame
|
||||
|
||||
--Installation Functions
|
||||
PI.Installs = {}
|
||||
local f
|
||||
local BUTTON_HEIGHT = 20
|
||||
|
||||
local function ResetAll()
|
||||
f.Next:Disable()
|
||||
f.Prev:Disable()
|
||||
f.Option1:Hide()
|
||||
f.Option1:SetScript("OnClick", nil)
|
||||
f.Option1:SetText("")
|
||||
f.Option2:Hide()
|
||||
f.Option2:SetScript("OnClick", nil)
|
||||
f.Option2:SetText("")
|
||||
f.Option3:Hide()
|
||||
f.Option3:SetScript("OnClick", nil)
|
||||
f.Option3:SetText("")
|
||||
f.Option4:Hide()
|
||||
f.Option4:SetScript("OnClick", nil)
|
||||
f.Option4:SetText("")
|
||||
f.SubTitle:SetText("")
|
||||
f.Desc1:SetText("")
|
||||
f.Desc2:SetText("")
|
||||
f.Desc3:SetText("")
|
||||
f.Desc4:SetText("")
|
||||
f:SetWidth(550)
|
||||
f:SetHeight(400)
|
||||
if f.StepTitles then
|
||||
for i = 1, getn(f.side.Lines) do f.side.Lines[i].text:SetText("") end
|
||||
end
|
||||
end
|
||||
|
||||
local function SetPage(PageNum, PrevPage)
|
||||
f.CurrentPage = PageNum
|
||||
f.PrevPage = PrevPage
|
||||
ResetAll()
|
||||
f.Status.anim.progress:SetChange(PageNum)
|
||||
f.Status.anim.progress:Play()
|
||||
|
||||
local r, g, b = E:ColorGradient(f.CurrentPage / f.MaxPage, 1, 0, 0, 1, 1, 0, 0, 1, 0)
|
||||
f.Status:SetStatusBarColor(r, g, b)
|
||||
|
||||
if PageNum == f.MaxPage then
|
||||
f.Next:Disable()
|
||||
else
|
||||
f.Next:Enable()
|
||||
end
|
||||
|
||||
if PageNum == 1 then
|
||||
f.Prev:Disable()
|
||||
else
|
||||
f.Prev:Enable()
|
||||
end
|
||||
|
||||
f.Pages[f.CurrentPage]()
|
||||
f.Status.text:SetFormattedText("%d / %d", f.CurrentPage, f.MaxPage)
|
||||
if f.StepTitles then
|
||||
for i = 1, getn(f.side.Lines) do
|
||||
local b = f.side.Lines[i]
|
||||
local color
|
||||
b.text:SetText(f.StepTitles[i])
|
||||
if i == f.CurrentPage then
|
||||
color = f.StepTitlesColorSelected or {.09,.52,.82}
|
||||
else
|
||||
color = f.StepTitlesColor or {1,1,1}
|
||||
end
|
||||
b.text:SetTextColor(color[1] or color.r, color[2] or color.g, color[3] or color.b)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function NextPage()
|
||||
if f.CurrentPage ~= f.MaxPage then
|
||||
f.CurrentPage = f.CurrentPage + 1
|
||||
SetPage(f.CurrentPage, f.CurrentPage - 1)
|
||||
end
|
||||
end
|
||||
|
||||
local function PreviousPage()
|
||||
if f.CurrentPage ~= 1 then
|
||||
f.CurrentPage = f.CurrentPage - 1
|
||||
SetPage(f.CurrentPage, f.CurrentPage + 1)
|
||||
end
|
||||
end
|
||||
|
||||
function PI:CreateStepComplete()
|
||||
local imsg = CreateFrame("Frame", "PluginInstallStepComplete", E.UIParent)
|
||||
imsg:SetWidth(418)
|
||||
imsg:SetHeight(72)
|
||||
imsg:SetPoint("TOP", 0, -190)
|
||||
imsg:Hide()
|
||||
imsg:SetScript("OnShow", function(self)
|
||||
if self.message then
|
||||
PlaySoundFile([[Sound\Interface\LevelUp.wav]])
|
||||
self.text:SetText(self.message)
|
||||
UIFrameFadeOut(self, 3.5, 1, 0)
|
||||
E:Delay(4, function() self:Hide() end)
|
||||
self.message = nil
|
||||
else
|
||||
self:Hide()
|
||||
end
|
||||
end)
|
||||
|
||||
imsg.firstShow = false
|
||||
|
||||
imsg.bg = imsg:CreateTexture(nil, "BACKGROUND")
|
||||
imsg.bg:SetTexture([[Interface\LevelUp\LevelUpTex]])
|
||||
imsg.bg:SetPoint("BOTTOM", 0, 0)
|
||||
imsg.bg:SetWidth(326)
|
||||
imsg.bg:SetHeight(103)
|
||||
imsg.bg:SetTexCoord(0.00195313, 0.63867188, 0.03710938, 0.23828125)
|
||||
imsg.bg:SetVertexColor(1, 1, 1, 0.6)
|
||||
|
||||
imsg.lineTop = imsg:CreateTexture(nil, "BACKGROUND")
|
||||
imsg.lineTop:SetDrawLayer("BACKGROUND", 2)
|
||||
imsg.lineTop:SetTexture([[Interface\LevelUp\LevelUpTex]])
|
||||
imsg.lineTop:SetPoint("TOP", 0, 0)
|
||||
imsg.lineTop:SetWidth(418)
|
||||
imsg.lineTop:SetHeight(7)
|
||||
imsg.lineTop:SetTexCoord(0.00195313, 0.81835938, 0.01953125, 0.03320313)
|
||||
|
||||
imsg.lineBottom = imsg:CreateTexture(nil, "BACKGROUND")
|
||||
imsg.lineBottom:SetDrawLayer("BACKGROUND", 2)
|
||||
imsg.lineBottom:SetTexture([[Interface\LevelUp\LevelUpTex]])
|
||||
imsg.lineBottom:SetPoint("BOTTOM", 0, 0)
|
||||
imsg.lineBottom:SetWidth(418)
|
||||
imsg.lineBottom:SetHeight(7)
|
||||
imsg.lineBottom:SetTexCoord(0.00195313, 0.81835938, 0.01953125, 0.03320313)
|
||||
|
||||
imsg.text = imsg:CreateFontString(nil, "ARTWORK")
|
||||
E:FontTemplate(imsg.text, E["media"].normFont, 32, "OUTLINE")
|
||||
imsg.text:SetPoint("BOTTOM", 0, 12)
|
||||
imsg.text:SetTextColor(1, 0.82, 0)
|
||||
imsg.text:SetJustifyH("CENTER")
|
||||
end
|
||||
|
||||
function PI:CreateFrame()
|
||||
f = CreateFrame("Button", "PluginInstallFrame", E.UIParent)
|
||||
f.SetPage = SetPage
|
||||
f:SetWidth(550)
|
||||
f:SetHeight(400)
|
||||
E:SetTemplate(f, "Transparent")
|
||||
f:SetPoint("CENTER", 0, 0)
|
||||
f:SetFrameStrata("TOOLTIP")
|
||||
|
||||
f.Title = f:CreateFontString(nil, "OVERLAY")
|
||||
E:FontTemplate(f.Title, nil, 17, nil)
|
||||
f.Title:SetPoint("TOP", 0, -5)
|
||||
|
||||
f.Next = CreateFrame("Button", "PluginInstallNextButton", f, "UIPanelButtonTemplate")
|
||||
E:StripTextures(f.Next)
|
||||
E:SetTemplate(f.Next, "Default", true)
|
||||
f.Next:SetWidth(110)
|
||||
f.Next:SetHeight(25)
|
||||
f.Next:SetPoint("BOTTOMRIGHT", -5, 5)
|
||||
f.Next:SetText(CONTINUE)
|
||||
f.Next:Disable()
|
||||
f.Next:SetScript("OnClick", NextPage)
|
||||
E.Skins:HandleButton(f.Next, true)
|
||||
|
||||
f.Prev = CreateFrame("Button", "PluginInstallPrevButton", f, "UIPanelButtonTemplate")
|
||||
E:StripTextures(f.Prev)
|
||||
E:SetTemplate(f.Prev, "Default", true)
|
||||
f.Prev:SetWidth(110)
|
||||
f.Prev:SetHeight(25)
|
||||
f.Prev:SetPoint("BOTTOMLEFT", 5, 5)
|
||||
f.Prev:SetText(PREV)
|
||||
f.Prev:Disable()
|
||||
f.Prev:SetScript("OnClick", PreviousPage)
|
||||
E.Skins:HandleButton(f.Prev, true)
|
||||
|
||||
f.Status = CreateFrame("StatusBar", "PluginInstallStatus", f)
|
||||
f.Status:SetFrameLevel(f.Status:GetFrameLevel() + 2)
|
||||
E:CreateBackdrop(f.Status, "Default", true)
|
||||
f.Status:SetStatusBarTexture(E["media"].normTex)
|
||||
f.Status:SetStatusBarColor(unpack(E["media"].rgbvaluecolor))
|
||||
f.Status:SetPoint("TOPLEFT", f.Prev, "TOPRIGHT", 6, -2)
|
||||
f.Status:SetPoint("BOTTOMRIGHT", f.Next, "BOTTOMLEFT", -6, 2)
|
||||
-- Setup StatusBar Animation
|
||||
f.Status.anim = CreateAnimationGroup(f.Status)
|
||||
f.Status.anim.progress = f.Status.anim:CreateAnimation("Progress")
|
||||
f.Status.anim.progress:SetSmoothing("Out")
|
||||
f.Status.anim.progress:SetDuration(.3)
|
||||
|
||||
f.Status.text = f.Status:CreateFontString(nil, "OVERLAY")
|
||||
E:FontTemplate(f.Status.text)
|
||||
f.Status.text:SetPoint("CENTER", 0, 0)
|
||||
|
||||
f.Option1 = CreateFrame("Button", "PluginInstallOption1Button", f, "UIPanelButtonTemplate")
|
||||
E:StripTextures(f.Option1)
|
||||
f.Option1:SetWidth(160)
|
||||
f.Option1:SetHeight(30)
|
||||
f.Option1:SetPoint("BOTTOM", 0, 45)
|
||||
f.Option1:SetText("")
|
||||
f.Option1:Hide()
|
||||
E.Skins:HandleButton(f.Option1, true)
|
||||
|
||||
f.Option2 = CreateFrame("Button", "PluginInstallOption2Button", f, "UIPanelButtonTemplate")
|
||||
E:StripTextures(f.Option2)
|
||||
f.Option2:SetWidth(160)
|
||||
f.Option2:SetHeight(30)
|
||||
f.Option2:SetPoint("BOTTOMLEFT", f, "BOTTOM", 4, 45)
|
||||
f.Option2:SetText("")
|
||||
f.Option2:Hide()
|
||||
f.Option2:SetScript("OnShow", function() f.Option1:SetWidth(110); f.Option1:ClearAllPoints(); f.Option1:SetPoint("BOTTOMRIGHT", f, "BOTTOM", -4, 45) end)
|
||||
f.Option2:SetScript("OnHide", function() f.Option1:SetWidth(160); f.Option1:ClearAllPoints(); f.Option1:SetPoint("BOTTOM", 0, 45) end)
|
||||
E.Skins:HandleButton(f.Option2, true)
|
||||
|
||||
f.Option3 = CreateFrame("Button", "PluginInstallOption3Button", f, "UIPanelButtonTemplate")
|
||||
E:StripTextures(f.Option3)
|
||||
f.Option3:SetWidth(100)
|
||||
f.Option3:SetHeight(30)
|
||||
f.Option3:SetPoint("LEFT", f.Option2, "RIGHT", 4, 0)
|
||||
f.Option3:SetText("")
|
||||
f.Option3:Hide()
|
||||
f.Option3:SetScript("OnShow", function() f.Option1:SetWidth(100); f.Option1:ClearAllPoints(); f.Option1:SetPoint("RIGHT", f.Option2, "LEFT", -4, 0); f.Option2:SetWidth(100); f.Option2:ClearAllPoints(); f.Option2:SetPoint("BOTTOM", f, "BOTTOM", 0, 45) end)
|
||||
f.Option3:SetScript("OnHide", function() f.Option1:SetWidth(160); f.Option1:ClearAllPoints(); f.Option1:SetPoint("BOTTOM", 0, 45); f.Option2:SetWidth(110); f.Option2:ClearAllPoints(); f.Option2:SetPoint("BOTTOMLEFT", f, "BOTTOM", 4, 45) end)
|
||||
E.Skins:HandleButton(f.Option3, true)
|
||||
|
||||
f.Option4 = CreateFrame("Button", "PluginInstallOption4Button", f, "UIPanelButtonTemplate")
|
||||
E:StripTextures(f.Option4)
|
||||
f.Option4:SetWidth(100)
|
||||
f.Option4:SetHeight(30)
|
||||
f.Option4:SetPoint("LEFT", f.Option3, "RIGHT", 4, 0)
|
||||
f.Option4:SetText("")
|
||||
f.Option4:Hide()
|
||||
f.Option4:SetScript("OnShow", function()
|
||||
f.Option1:SetWidth(100)
|
||||
f.Option2:SetWidth(100)
|
||||
|
||||
f.Option1:ClearAllPoints();
|
||||
f.Option1:SetPoint("RIGHT", f.Option2, "LEFT", -4, 0);
|
||||
f.Option2:ClearAllPoints();
|
||||
f.Option2:SetPoint("BOTTOMRIGHT", f, "BOTTOM", -4, 45)
|
||||
end)
|
||||
f.Option4:SetScript("OnHide", function() f.Option1:SetWidth(160); f.Option1:ClearAllPoints(); f.Option1:SetPoint("BOTTOM", 0, 45); f.Option2:SetWidth(110); f.Option2:ClearAllPoints(); f.Option2:SetPoint("BOTTOMLEFT", f, "BOTTOM", 4, 45) end)
|
||||
E.Skins:HandleButton(f.Option4, true)
|
||||
|
||||
f.SubTitle = f:CreateFontString(nil, "OVERLAY")
|
||||
E:FontTemplate(f.SubTitle, nil, 15, nil)
|
||||
f.SubTitle:SetPoint("TOP", 0, -40)
|
||||
|
||||
f.Desc1 = f:CreateFontString(nil, "OVERLAY")
|
||||
E:FontTemplate(f.Desc1)
|
||||
f.Desc1:SetPoint("TOPLEFT", 20, -75)
|
||||
f.Desc1:SetWidth(f:GetWidth() - 40)
|
||||
|
||||
f.Desc2 = f:CreateFontString(nil, "OVERLAY")
|
||||
E:FontTemplate(f.Desc2)
|
||||
f.Desc2:SetPoint("TOP", f.Desc1, "BOTTOM", 0, -20)
|
||||
f.Desc2:SetWidth(f:GetWidth() - 40)
|
||||
|
||||
f.Desc3 = f:CreateFontString(nil, "OVERLAY")
|
||||
E:FontTemplate(f.Desc3)
|
||||
f.Desc3:SetPoint("TOP", f.Desc2, "BOTTOM", 0, -20)
|
||||
f.Desc3:SetWidth(f:GetWidth() - 40)
|
||||
|
||||
f.Desc4 = f:CreateFontString(nil, "OVERLAY")
|
||||
E:FontTemplate(f.Desc4)
|
||||
f.Desc4:SetPoint("TOP", f.Desc3, "BOTTOM", 0, -20)
|
||||
f.Desc4:SetWidth(f:GetWidth() - 40)
|
||||
|
||||
local close = CreateFrame("Button", "PluginInstallCloseButton", f, "UIPanelCloseButton")
|
||||
close:SetPoint("TOPRIGHT", f, "TOPRIGHT")
|
||||
close:SetScript("OnClick", function() f:Hide() end)
|
||||
E.Skins:HandleCloseButton(close)
|
||||
|
||||
f.pending = CreateFrame("Frame", "PluginInstallPendingButton", f)
|
||||
f.pending:SetWidth(20)
|
||||
f.pending:SetHeight(20)
|
||||
f.pending:SetPoint("TOPLEFT", f, "TOPLEFT", 8, -8)
|
||||
f.pending.tex = f.pending:CreateTexture(nil, "OVERLAY")
|
||||
f.pending.tex:SetPoint("TOPLEFT", f.pending, "TOPLEFT", 2, -2)
|
||||
f.pending.tex:SetPoint("BOTTOMRIGHT", f.pending, "BOTTOMRIGHT", -2, 2)
|
||||
f.pending.tex:SetTexture([[Interface\OptionsFrame\UI-OptionsFrame-NewFeatureIcon]])
|
||||
E:CreateBackdrop(f.pending, "Transparent")
|
||||
f.pending:SetScript("OnEnter", function(self)
|
||||
_G["GameTooltip"]:SetOwner(self, "ANCHOR_BOTTOMLEFT", E.PixelMode and -7 or -9);
|
||||
_G["GameTooltip"]:AddLine(L["List of installations in queue:"], 1, 1, 1)
|
||||
_G["GameTooltip"]:AddLine(" ")
|
||||
for i = 1, getn(PI.Installs) do
|
||||
_G["GameTooltip"]:AddDoubleLine(format("%d. %s", i, (PI.Installs[i].Name or UNKNOWN)), i == 1 and format("|cff00FF00%s|r", L["In Progress"]) or format("|cffFF0000%s|r", L["Pending"]))
|
||||
end
|
||||
_G["GameTooltip"]:Show()
|
||||
end)
|
||||
f.pending:SetScript("OnLeave", function()
|
||||
_G["GameTooltip"]:Hide()
|
||||
end)
|
||||
|
||||
f.tutorialImage = f:CreateTexture("PluginInstallTutorialImage", "OVERLAY")
|
||||
f.tutorialImage:SetWidth(256)
|
||||
f.tutorialImage:SetHeight(128)
|
||||
f.tutorialImage:SetPoint("BOTTOM", 0, 70)
|
||||
|
||||
f.side = CreateFrame("Frame", "PluginInstallTitleFrame", f)
|
||||
E:SetTemplate(f.side, "Transparent")
|
||||
f.side:SetPoint("TOPLEFT", f, "TOPRIGHT", E.PixelMode and 1 or 3, 0)
|
||||
f.side:SetPoint("BOTTOMLEFT", f, "BOTTOMRIGHT", E.PixelMode and 1 or 3, 0)
|
||||
f.side:SetWidth(140)
|
||||
f.side.text = f.side:CreateFontString(nil, "OVERLAY")
|
||||
f.side.text:SetPoint("TOP", f.side, "TOP", 0, -4)
|
||||
f.side.text:SetFont(E["media"].normFont, 18, "OUTLINE")
|
||||
f.side.text:SetText(L["Steps"])
|
||||
f.side.Lines = {} --Table to keep shown lines
|
||||
f.side:Hide()
|
||||
for i = 1, 18 do
|
||||
local button = CreateFrame("Button", nil, f)
|
||||
if i == 1 then
|
||||
button:SetPoint("TOP", f.side.text, "BOTTOM", 0, -6)
|
||||
else
|
||||
button:SetPoint("TOP", f.side.Lines[i - 1], "BOTTOM")
|
||||
end
|
||||
button:SetWidth(130)
|
||||
button:SetHeight(BUTTON_HEIGHT)
|
||||
button.text = button:CreateFontString(nil, "OVERLAY")
|
||||
button.text:SetPoint("TOPLEFT", button, "TOPLEFT", 2, -2)
|
||||
button.text:SetPoint("BOTTOMRIGHT", button, "BOTTOMRIGHT", -2, 2)
|
||||
button.text:SetFont(E["media"].normFont, 14, "OUTLINE")
|
||||
button:SetScript("OnClick", function() if i <= f.MaxPage then SetPage(i, f.CurrentPage) end end)
|
||||
button.text:SetText("")
|
||||
f.side.Lines[i] = button
|
||||
button:Hide()
|
||||
end
|
||||
|
||||
f:Hide()
|
||||
|
||||
f:SetScript("OnHide", function() PI:CloseInstall() end)
|
||||
end
|
||||
|
||||
function PI:Queue(addon)
|
||||
local addonIsQueued = false
|
||||
for _, v in pairs(self.Installs) do
|
||||
if v.Name == addon.Name then
|
||||
addonIsQueued = true
|
||||
end
|
||||
end
|
||||
|
||||
if not addonIsQueued then
|
||||
tinsert(self.Installs, getn(self.Installs)+1, addon)
|
||||
self:RunInstall()
|
||||
end
|
||||
end
|
||||
|
||||
function PI:CloseInstall()
|
||||
tremove(self.Installs, 1)
|
||||
f.side:Hide()
|
||||
for i = 1, getn(f.side.Lines) do
|
||||
f.side.Lines[i].text:SetText("")
|
||||
f.side.Lines[i]:Hide()
|
||||
end
|
||||
if getn(self.Installs) > 0 then E:Delay(1, function() PI:RunInstall() end) end
|
||||
end
|
||||
|
||||
function PI:RunInstall()
|
||||
if not E.private.install_complete then return end
|
||||
if self.Installs[1] and not PluginInstallFrame:IsShown() and not (_G["ElvUIInstallFrame"] and _G["ElvUIInstallFrame"]:IsShown()) then
|
||||
f.StepTitles = nil
|
||||
f.StepTitlesColor = nil
|
||||
f.StepTitlesColorSelected = nil
|
||||
local db = self.Installs[1]
|
||||
f.CurrentPage = 0
|
||||
f.MaxPage = getn(db.Pages)
|
||||
|
||||
f.Title:SetText(db.Title or L["ElvUI Plugin Installation"])
|
||||
f.Status:SetMinMaxValues(0, f.MaxPage)
|
||||
f.Status.text:SetText(f.CurrentPage.." / "..f.MaxPage)
|
||||
f.tutorialImage:SetTexture(db.tutorialImage or [[Interface\AddOns\ElvUI\media\textures\logo.tga]])
|
||||
|
||||
f.Pages = db.Pages
|
||||
|
||||
PluginInstallFrame:Show()
|
||||
f:SetPoint("CENTER")
|
||||
if db.StepTitles and getn(db.StepTitles) == f.MaxPage then
|
||||
f:SetPoint("CENTER", E.UIParent, "CENTER", -((db.StepTitleWidth or 140)/2), 0)
|
||||
f.side:SetWidth(db.StepTitleWidth or 140)
|
||||
f.side:Show()
|
||||
|
||||
for i = 1, getn(f.side.Lines) do
|
||||
if db.StepTitles[i] then
|
||||
f.side.Lines[i]:SetWidth(db.StepTitleButtonWidth or 130)
|
||||
f.side.Lines[i].text:SetJustifyH(db.StepTitleTextJustification or "CENTER")
|
||||
f.side.Lines[i]:Show()
|
||||
end
|
||||
end
|
||||
|
||||
f.StepTitles = db.StepTitles
|
||||
f.StepTitlesColor = db.StepTitlesColor
|
||||
f.StepTitlesColorSelected = db.StepTitlesColorSelected
|
||||
end
|
||||
NextPage()
|
||||
end
|
||||
if getn(self.Installs) > 1 then
|
||||
f.pending:Show()
|
||||
-- E:Flash(f.pending, 0.53, true)
|
||||
else
|
||||
f.pending:Hide()
|
||||
-- E:StopFlash(f.pending)
|
||||
end
|
||||
end
|
||||
|
||||
function PI:Initialize()
|
||||
PI:CreateStepComplete()
|
||||
PI:CreateFrame()
|
||||
end
|
||||
|
||||
local function InitializeCallback()
|
||||
PI:Initialize()
|
||||
end
|
||||
|
||||
E:RegisterModule(PI:GetName(), InitializeCallback)
|
||||
@@ -0,0 +1,312 @@
|
||||
local E, L, V, P, G = unpack(ElvUI); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
|
||||
local LSM = LibStub("LibSharedMedia-3.0");
|
||||
|
||||
--Cache global variables
|
||||
--Lua functions
|
||||
local _G = _G
|
||||
local unpack, type = unpack, type
|
||||
--WoW API / Variables
|
||||
local CreateFrame = CreateFrame
|
||||
local RAID_CLASS_COLORS = RAID_CLASS_COLORS
|
||||
local CUSTOM_CLASS_COLORS = CUSTOM_CLASS_COLORS
|
||||
|
||||
--Preload shit..
|
||||
E.mult = 1
|
||||
local backdropr, backdropg, backdropb, backdropa, borderr, borderg, borderb = 0, 0, 0, 1, 0, 0, 0
|
||||
|
||||
local function GetTemplate(t, isUnitFrameElement)
|
||||
backdropa = 1
|
||||
if t == "ClassColor" then
|
||||
if(CUSTOM_CLASS_COLORS) then
|
||||
borderr, borderg, borderb = CUSTOM_CLASS_COLORS[E.myclass].r, CUSTOM_CLASS_COLORS[E.myclass].g, CUSTOM_CLASS_COLORS[E.myclass].b
|
||||
else
|
||||
borderr, borderg, borderb = RAID_CLASS_COLORS[E.myclass].r, RAID_CLASS_COLORS[E.myclass].g, RAID_CLASS_COLORS[E.myclass].b
|
||||
end
|
||||
|
||||
if t ~= "Transparent" then
|
||||
backdropr, backdropg, backdropb = unpack(E["media"].backdropcolor)
|
||||
else
|
||||
backdropr, backdropg, backdropb, backdropa = unpack(E["media"].backdropfadecolor)
|
||||
end
|
||||
elseif t == "Transparent" then
|
||||
if isUnitFrameElement then
|
||||
borderr, borderg, borderb = unpack(E["media"].bordercolor)
|
||||
else
|
||||
borderr, borderg, borderb = unpack(E["media"].bordercolor)
|
||||
end
|
||||
backdropr, backdropg, backdropb, backdropa = unpack(E["media"].backdropfadecolor)
|
||||
else
|
||||
if isUnitFrameElement then
|
||||
borderr, borderg, borderb = unpack(E["media"].bordercolor)
|
||||
else
|
||||
borderr, borderg, borderb = unpack(E["media"].bordercolor)
|
||||
end
|
||||
backdropr, backdropg, backdropb = unpack(E["media"].backdropcolor)
|
||||
end
|
||||
end
|
||||
|
||||
function E:Size(frame, width, height)
|
||||
assert(width)
|
||||
frame:SetSize(E:Scale(width), E:Scale(height or width))
|
||||
end
|
||||
|
||||
function E:Width(frame, width)
|
||||
frame:SetWidth(E:Scale(width))
|
||||
end
|
||||
|
||||
function E:Height(frame, height)
|
||||
assert(height)
|
||||
frame:SetHeight(E:Scale(height))
|
||||
end
|
||||
|
||||
function E:Point(obj, arg1, arg2, arg3, arg4, arg5)
|
||||
if(arg2 == nil) then
|
||||
arg2 = obj:GetParent()
|
||||
end
|
||||
|
||||
if type(arg1)=="number" then arg1 = E:Scale(arg1) end
|
||||
if type(arg2)=="number" then arg2 = E:Scale(arg2) end
|
||||
if type(arg3)=="number" then arg3 = E:Scale(arg3) end
|
||||
if type(arg4)=="number" then arg4 = E:Scale(arg4) end
|
||||
if type(arg5)=="number" then arg5 = E:Scale(arg5) end
|
||||
|
||||
obj:SetPoint(arg1, arg2, arg3, arg4, arg5)
|
||||
end
|
||||
|
||||
function E:SetOutside(obj, anchor, xOffset, yOffset, anchor2)
|
||||
xOffset = xOffset or E.Border
|
||||
yOffset = yOffset or E.Border
|
||||
anchor = anchor or obj:GetParent()
|
||||
|
||||
assert(anchor)
|
||||
if obj:GetPoint() then
|
||||
obj:ClearAllPoints()
|
||||
end
|
||||
|
||||
obj:SetPoint("TOPLEFT", anchor, "TOPLEFT", -xOffset, yOffset)
|
||||
obj:SetPoint("BOTTOMRIGHT", anchor2 or anchor, "BOTTOMRIGHT", xOffset, -yOffset)
|
||||
end
|
||||
|
||||
function E:SetInside(obj, anchor, xOffset, yOffset, anchor2)
|
||||
xOffset = xOffset or E.Border
|
||||
yOffset = yOffset or E.Border
|
||||
anchor = anchor or obj:GetParent()
|
||||
|
||||
assert(anchor)
|
||||
if obj:GetPoint() then
|
||||
obj:ClearAllPoints()
|
||||
end
|
||||
|
||||
obj:SetPoint("TOPLEFT", anchor, "TOPLEFT", xOffset, -yOffset)
|
||||
obj:SetPoint("BOTTOMRIGHT", anchor2 or anchor, "BOTTOMRIGHT", -xOffset, yOffset)
|
||||
end
|
||||
|
||||
function E:SetTemplate(f, t, glossTex, ignoreUpdates, forcePixelMode, isUnitFrameElement)
|
||||
GetTemplate(t, isUnitFrameElement)
|
||||
|
||||
if(t) then
|
||||
f.template = t
|
||||
end
|
||||
|
||||
if(glossTex) then
|
||||
f.glossTex = glossTex
|
||||
end
|
||||
|
||||
if(ignoreUpdates) then
|
||||
f.ignoreUpdates = ignoreUpdates
|
||||
end
|
||||
|
||||
if(forcePixelMode) then
|
||||
f.forcePixelMode = forcePixelMode
|
||||
end
|
||||
|
||||
local bgFile = E.media.blankTex
|
||||
if(glossTex) then
|
||||
bgFile = E.media.glossTex
|
||||
end
|
||||
|
||||
if(isUnitFrameElement) then
|
||||
f.isUnitFrameElement = isUnitFrameElement
|
||||
end
|
||||
|
||||
if(t ~= "NoBackdrop") then
|
||||
if(E.private.general.pixelPerfect or f.forcePixelMode) then
|
||||
f:SetBackdrop({
|
||||
bgFile = bgFile,
|
||||
edgeFile = E["media"].blankTex,
|
||||
tile = false, tileSize = 0, edgeSize = E.mult,
|
||||
insets = {left = 0, right = 0, top = 0, bottom = 0}
|
||||
})
|
||||
else
|
||||
f:SetBackdrop({
|
||||
bgFile = bgFile,
|
||||
edgeFile = E["media"].blankTex,
|
||||
tile = false, tileSize = 0, edgeSize = E.mult,
|
||||
insets = {left = -E.mult, right = -E.mult, top = -E.mult, bottom = -E.mult}
|
||||
})
|
||||
end
|
||||
|
||||
if not f.oborder and not f.iborder and not E.private.general.pixelPerfect and not f.forcePixelMode then
|
||||
local border = CreateFrame("Frame", nil, f)
|
||||
E:SetInside(border, f, E.mult, E.mult)
|
||||
border:SetBackdrop({
|
||||
edgeFile = E["media"].blankTex,
|
||||
edgeSize = E.mult,
|
||||
insets = {left = E.mult, right = E.mult, top = E.mult, bottom = E.mult}
|
||||
})
|
||||
border:SetBackdropBorderColor(0, 0, 0, 1)
|
||||
f.iborder = border
|
||||
|
||||
if f.oborder then return end
|
||||
border = CreateFrame("Frame", nil, f)
|
||||
E:SetOutside(border, f, E.mult, E.mult)
|
||||
border:SetFrameLevel(f:GetFrameLevel() + 1)
|
||||
border:SetBackdrop({
|
||||
edgeFile = E["media"].blankTex,
|
||||
edgeSize = E.mult,
|
||||
insets = {left = E.mult, right = E.mult, top = E.mult, bottom = E.mult}
|
||||
})
|
||||
border:SetBackdropBorderColor(0, 0, 0, 1)
|
||||
f.oborder = border
|
||||
end
|
||||
else
|
||||
f:SetBackdrop(nil)
|
||||
end
|
||||
|
||||
f:SetBackdropColor(backdropr, backdropg, backdropb, backdropa)
|
||||
f:SetBackdropBorderColor(borderr, borderg, borderb)
|
||||
|
||||
if(not f.ignoreUpdates) then
|
||||
if f.isUnitFrameElement then
|
||||
E["unitFrameElements"][f] = true
|
||||
else
|
||||
E["frames"][f] = true
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function E:CreateBackdrop(f, t, tex, ignoreUpdates, forcePixelMode, isUnitFrameElement)
|
||||
if not f then return end
|
||||
if(not t) then t = "Default" end
|
||||
|
||||
local b = CreateFrame("Frame", nil, f)
|
||||
if(f.forcePixelMode or forcePixelMode) then
|
||||
E:SetOutside(b, nil, E.mult, E.mult)
|
||||
else
|
||||
E:SetOutside(b)
|
||||
end
|
||||
E:SetTemplate(b, t, tex, ignoreUpdates, forcePixelMode, isUnitFrameElement)
|
||||
|
||||
if(f:GetFrameLevel() - 1 >= 0) then
|
||||
b:SetFrameLevel(f:GetFrameLevel() - 1)
|
||||
else
|
||||
b:SetFrameLevel(0)
|
||||
end
|
||||
|
||||
f.backdrop = b
|
||||
end
|
||||
|
||||
function E:CreateShadow(f)
|
||||
if f.shadow then return end
|
||||
|
||||
borderr, borderg, borderb = 0, 0, 0
|
||||
backdropr, backdropg, backdropb = 0, 0, 0
|
||||
|
||||
local shadow = CreateFrame("Frame", nil, f)
|
||||
shadow:SetFrameLevel(1)
|
||||
shadow:SetFrameStrata(f:GetFrameStrata())
|
||||
E:SetOutside(shadow, f, 3, 3)
|
||||
shadow:SetBackdrop({
|
||||
edgeFile = LSM:Fetch("border", "ElvUI GlowBorder"), edgeSize = E:Scale(3),
|
||||
insets = {left = E:Scale(5), right = E:Scale(5), top = E:Scale(5), bottom = E:Scale(5)}
|
||||
})
|
||||
shadow:SetBackdropColor(backdropr, backdropg, backdropb, 0)
|
||||
shadow:SetBackdropBorderColor(borderr, borderg, borderb, 0.9)
|
||||
f.shadow = shadow
|
||||
end
|
||||
|
||||
function E:Kill(object)
|
||||
if object.UnregisterAllEvents then
|
||||
object:UnregisterAllEvents()
|
||||
object:SetParent(E.HiddenFrame)
|
||||
else
|
||||
object.Show = object.Hide
|
||||
end
|
||||
|
||||
object:Hide()
|
||||
end
|
||||
|
||||
function E:StripTextures(object, kill)
|
||||
for _, region in ipairs({object:GetRegions()}) do
|
||||
if region and region:GetObjectType() == "Texture" then
|
||||
if kill and type(kill) == "boolean" then
|
||||
E:Kill(region)
|
||||
elseif region:GetDrawLayer() == kill then
|
||||
region:SetTexture(nil)
|
||||
elseif kill and type(kill) == "string" and region:GetTexture() ~= kill then
|
||||
region:SetTexture(nil)
|
||||
else
|
||||
region:SetTexture(nil)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function E:FontTemplate(fs, font, fontSize, fontStyle)
|
||||
fs.font = font
|
||||
fs.fontSize = fontSize
|
||||
fs.fontStyle = fontStyle
|
||||
|
||||
font = font or LSM:Fetch("font", E.db["general"].font)
|
||||
fontSize = fontSize or E.db.general.fontSize
|
||||
|
||||
if fontStyle == "OUTLINE" and (E.db.general.font == "Homespun") then
|
||||
if (fontSize > 10 and not fs.fontSize) then
|
||||
fontStyle = "MONOCHROMEOUTLINE"
|
||||
fontSize = 10
|
||||
end
|
||||
end
|
||||
|
||||
fs:SetFont(font, fontSize, fontStyle)
|
||||
if fontStyle and (fontStyle ~= "NONE") then
|
||||
fs:SetShadowColor(0, 0, 0, 0.2)
|
||||
else
|
||||
fs:SetShadowColor(0, 0, 0, 1)
|
||||
end
|
||||
fs:SetShadowOffset((E.mult or 1), -(E.mult or 1))
|
||||
|
||||
E["texts"][fs] = true
|
||||
end
|
||||
|
||||
function E:StyleButton(button, noHover, noPushed, noChecked)
|
||||
if button.SetHighlightTexture and not button.hover and not noHover then
|
||||
local hover = button:CreateTexture()
|
||||
hover:SetTexture(1, 1, 1, 0.3)
|
||||
E:SetInside(hover)
|
||||
button.hover = hover
|
||||
button:SetHighlightTexture(hover)
|
||||
end
|
||||
|
||||
if button.SetPushedTexture and not button.pushed and not noPushed then
|
||||
local pushed = button:CreateTexture()
|
||||
pushed:SetTexture(0.9, 0.8, 0.1, 0.3)
|
||||
E:SetInside(pushed)
|
||||
button.pushed = pushed
|
||||
button:SetPushedTexture(pushed)
|
||||
end
|
||||
|
||||
if button.SetCheckedTexture and not button.checked and not noChecked then
|
||||
local checked = button:CreateTexture()
|
||||
checked:SetTexture(1, 1, 1)
|
||||
E:SetInside(checked)
|
||||
checked:SetAlpha(0.3)
|
||||
button.checked = checked
|
||||
button:SetCheckedTexture(checked)
|
||||
end
|
||||
|
||||
local cooldown = button:GetName() and _G[button:GetName().."Cooldown"]
|
||||
if cooldown then
|
||||
cooldown:ClearAllPoints()
|
||||
E:SetInside(cooldown)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,121 @@
|
||||
local E, L, V, P, G = unpack(ElvUI); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
|
||||
|
||||
--Cache global variables
|
||||
--Lua functions
|
||||
local _G = _G
|
||||
--WoW API / Variables
|
||||
local CreateFrame = CreateFrame
|
||||
local DISABLE = DISABLE
|
||||
local HIDE = HIDE
|
||||
|
||||
E.TutorialList = {
|
||||
L["For technical support visit us at https://github.com/ElvUI-Vanilla/ElvUI"],
|
||||
L["You can toggle the microbar by using your middle mouse button on the minimap you can also accomplish this by enabling the actual microbar located in the actionbar settings."],
|
||||
L["A raid marker feature is available by pressing Escape -> Keybinds scroll to the bottom under ElvUI and setting a keybind for the raid marker."],
|
||||
L["You can set your keybinds quickly by typing /kb."],
|
||||
L["The focus unit can be set by typing /focus when you are targeting the unit you want to focus. It is recommended you make a macro to do this."],
|
||||
L["ElvUI has a dual spec feature which allows you to load different profiles based on your current spec on the fly. You can enable this from the profiles tab."],
|
||||
L["You can access copy chat and chat menu functions by mouse over the top right corner of chat panel and left/right click on the button that will appear."],
|
||||
L["If you are experiencing issues with ElvUI try disabling all your addons except ElvUI, remember ElvUI is a full UI replacement addon, you cannot run two addons that do the same thing."],
|
||||
L["If you accidently remove a chat frame you can always go the in-game configuration menu, press install, go to the chat portion and reset them."],
|
||||
L["To setup which channels appear in which chat frame, right click the chat tab and go to settings."],
|
||||
L["You can use the /resetui command to reset all of your movers. You can also use the command to reset a specific mover, /resetui <mover name>.\nExample: /resetui Player Frame"],
|
||||
L["To move abilities on the actionbars by default hold shift + drag. You can change the modifier key from the actionbar options menu."],
|
||||
L["You can see someones average item level of their gear by holding shift and mousing over them. It should appear inside the tooltip."]
|
||||
}
|
||||
|
||||
function E:SetNextTutorial()
|
||||
self.db.currentTutorial = self.db.currentTutorial or 0
|
||||
self.db.currentTutorial = self.db.currentTutorial + 1
|
||||
|
||||
if self.db.currentTutorial > getn(E.TutorialList) then
|
||||
self.db.currentTutorial = 1
|
||||
end
|
||||
|
||||
ElvUITutorialWindow.desc:SetText(E.TutorialList[self.db.currentTutorial])
|
||||
end
|
||||
|
||||
function E:SetPrevTutorial()
|
||||
self.db.currentTutorial = self.db.currentTutorial or 0
|
||||
self.db.currentTutorial = self.db.currentTutorial - 1
|
||||
|
||||
if self.db.currentTutorial <= 0 then
|
||||
self.db.currentTutorial = getn(E.TutorialList)
|
||||
end
|
||||
|
||||
ElvUITutorialWindow.desc:SetText(E.TutorialList[self.db.currentTutorial])
|
||||
end
|
||||
|
||||
function E:SpawnTutorialFrame()
|
||||
local f = CreateFrame("Frame", "ElvUITutorialWindow", UIParent)
|
||||
f:SetFrameStrata("DIALOG")
|
||||
f:SetToplevel(true)
|
||||
f:SetClampedToScreen(true)
|
||||
f:SetWidth(360)
|
||||
f:SetHeight(110)
|
||||
E:SetTemplate(f, "Transparent")
|
||||
f:Hide()
|
||||
|
||||
local S = E:GetModule("Skins")
|
||||
|
||||
local header = CreateFrame("Button", nil, f)
|
||||
E:SetTemplate(header, "Default", true)
|
||||
header:SetWidth(120); header:SetHeight(25)
|
||||
header:SetPoint("CENTER", f, "TOP")
|
||||
header:SetFrameLevel(header:GetFrameLevel() + 2)
|
||||
|
||||
local title = header:CreateFontString("OVERLAY")
|
||||
E:FontTemplate(title)
|
||||
title:SetPoint("CENTER", header, "CENTER")
|
||||
title:SetText("ElvUI")
|
||||
|
||||
local desc = f:CreateFontString("ARTWORK")
|
||||
desc:SetFontObject("GameFontHighlight")
|
||||
desc:SetJustifyV("TOP")
|
||||
desc:SetJustifyH("LEFT")
|
||||
desc:SetPoint("TOPLEFT", 18, -32)
|
||||
desc:SetPoint("BOTTOMRIGHT", -18, 30)
|
||||
f.desc = desc
|
||||
|
||||
f.disableButton = CreateFrame("CheckButton", f:GetName().."DisableButton", f, "OptionsCheckButtonTemplate")
|
||||
_G[f.disableButton:GetName() .. "Text"]:SetText(DISABLE)
|
||||
f.disableButton:SetPoint("BOTTOMLEFT", 1, 1)
|
||||
S:HandleCheckBox(f.disableButton)
|
||||
f.disableButton:SetScript("OnShow", function() this:SetChecked(E.db.hideTutorial) end)
|
||||
|
||||
f.disableButton:SetScript("OnClick", function() E.db.hideTutorial = this:GetChecked() end)
|
||||
|
||||
f.hideButton = CreateFrame("Button", f:GetName().."HideButton", f, "OptionsButtonTemplate")
|
||||
f.hideButton:SetPoint("BOTTOMRIGHT", -5, 5)
|
||||
S:HandleButton(f.hideButton)
|
||||
_G[f.hideButton:GetName() .. "Text"]:SetText(HIDE)
|
||||
f.hideButton:SetScript("OnClick", function() E:StaticPopupSpecial_Hide(this:GetParent()) end)
|
||||
|
||||
f.nextButton = CreateFrame("Button", f:GetName().."NextButton", f, "OptionsButtonTemplate")
|
||||
f.nextButton:SetPoint("RIGHT", f.hideButton, "LEFT", -4, 0)
|
||||
f.nextButton:SetWidth(20)
|
||||
S:HandleButton(f.nextButton)
|
||||
_G[f.nextButton:GetName() .. "Text"]:SetText(">")
|
||||
f.nextButton:SetScript("OnClick", function() E:SetNextTutorial() end)
|
||||
|
||||
f.prevButton = CreateFrame("Button", f:GetName().."PrevButton", f, "OptionsButtonTemplate")
|
||||
f.prevButton:SetPoint("RIGHT", f.nextButton, "LEFT", -4, 0)
|
||||
f.prevButton:SetWidth(20)
|
||||
S:HandleButton(f.prevButton)
|
||||
_G[f.prevButton:GetName() .. "Text"]:SetText("<")
|
||||
f.prevButton:SetScript("OnClick", function() E:SetPrevTutorial() end)
|
||||
|
||||
return f
|
||||
end
|
||||
|
||||
function E:Tutorials(forceShow)
|
||||
if (not forceShow and self.db.hideTutorial) or (not forceShow and not self.private.install_complete) then return end
|
||||
local f = ElvUITutorialWindow
|
||||
if not f then
|
||||
f = E:SpawnTutorialFrame()
|
||||
end
|
||||
|
||||
E:StaticPopupSpecial_Show(f)
|
||||
|
||||
self:SetNextTutorial()
|
||||
end
|
||||
@@ -0,0 +1,57 @@
|
||||
--Cache global variables
|
||||
--Lua functions
|
||||
local _G = _G
|
||||
local format = string.format
|
||||
--WoW API / Variables
|
||||
local GetMouseFocus = GetMouseFocus
|
||||
|
||||
--[[
|
||||
Command to grab frame information when mouseing over a frame
|
||||
|
||||
Frame Name
|
||||
Width
|
||||
Height
|
||||
Strata
|
||||
Level
|
||||
X Offset
|
||||
Y Offset
|
||||
Point
|
||||
]]
|
||||
|
||||
SLASH_FRAME1 = "/frame"
|
||||
SlashCmdList["FRAME"] = function(arg)
|
||||
if arg ~= "" then
|
||||
arg = _G[arg]
|
||||
else
|
||||
arg = GetMouseFocus()
|
||||
end
|
||||
if arg ~= nil then FRAME = arg end --Set the global variable FRAME to = whatever we are mousing over to simplify messing with frames that have no name.
|
||||
if arg ~= nil and arg:GetName() ~= nil then
|
||||
local point, relativeTo, relativePoint, xOfs, yOfs = arg:GetPoint()
|
||||
ChatFrame1:AddMessage("|cffCC0000----------------------------")
|
||||
ChatFrame1:AddMessage("Name: |cffFFD100"..arg:GetName())
|
||||
if arg:GetParent() and arg:GetParent():GetName() then
|
||||
ChatFrame1:AddMessage("Parent: |cffFFD100"..arg:GetParent():GetName())
|
||||
end
|
||||
|
||||
ChatFrame1:AddMessage("Width: |cffFFD100"..format("%.2f",arg:GetWidth()))
|
||||
ChatFrame1:AddMessage("Height: |cffFFD100"..format("%.2f",arg:GetHeight()))
|
||||
ChatFrame1:AddMessage("Strata: |cffFFD100"..arg:GetFrameStrata())
|
||||
ChatFrame1:AddMessage("Level: |cffFFD100"..arg:GetFrameLevel())
|
||||
|
||||
if xOfs then
|
||||
ChatFrame1:AddMessage("X: |cffFFD100"..format("%.2f",xOfs))
|
||||
end
|
||||
if yOfs then
|
||||
ChatFrame1:AddMessage("Y: |cffFFD100"..format("%.2f",yOfs))
|
||||
end
|
||||
if relativeTo and relativeTo:GetName() then
|
||||
ChatFrame1:AddMessage("Point: |cffFFD100"..point.."|r anchored to "..relativeTo:GetName().."'s |cffFFD100"..relativePoint)
|
||||
end
|
||||
ChatFrame1:AddMessage("|cffCC0000----------------------------|r")
|
||||
elseif arg == nil then
|
||||
ChatFrame1:AddMessage("Invalid frame name")
|
||||
else
|
||||
ChatFrame1:AddMessage("Could not find frame info")
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,6 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="ReloadUI.lua"/>
|
||||
<Script file="Frame.lua"/>
|
||||
<Script file="Test.lua"/>
|
||||
<Script file="Table.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,7 @@
|
||||
--[[
|
||||
Shortcut to ReloadUI
|
||||
]]
|
||||
|
||||
SLASH_RELOADUI1 = "/rl"
|
||||
SLASH_RELOADUI2 = "/reloadui"
|
||||
SlashCmdList.RELOADUI = ReloadUI
|
||||
@@ -0,0 +1,22 @@
|
||||
--Cache global variables
|
||||
local setmetatable, getmetatable = setmetatable, getmetatable
|
||||
local pairs, type = pairs, type
|
||||
local table = table
|
||||
|
||||
function table.copy(t, deep, seen)
|
||||
seen = seen or {}
|
||||
if t == nil then return nil end
|
||||
if seen[t] then return seen[t] end
|
||||
|
||||
local nt = {}
|
||||
for k, v in pairs(t) do
|
||||
if deep and type(v) == "table" then
|
||||
nt[k] = table.copy(v, deep, seen)
|
||||
else
|
||||
nt[k] = v
|
||||
end
|
||||
end
|
||||
setmetatable(nt, table.copy(getmetatable(t), deep, seen))
|
||||
seen[t] = nt
|
||||
return nt
|
||||
end
|
||||
@@ -0,0 +1,5 @@
|
||||
--[[
|
||||
Going to leave this as my bullshit lua file.
|
||||
|
||||
So I can test stuff.
|
||||
]]
|
||||
@@ -0,0 +1,19 @@
|
||||
## Interface: 11200
|
||||
## Author: Elv, Bunny
|
||||
## Version: 0.01
|
||||
## Title: |cffA11313E|r|cffC4C4C4lvUI|r
|
||||
## Notes: User Interface replacement AddOn for World of Warcraft.
|
||||
## SavedVariables: ElvDB, ElvPrivateDB
|
||||
## SavedVariablesPerCharacter: ElvCharacterDB
|
||||
## Dependencies: !Compatibility
|
||||
## OptionalDeps: !DebugTools, SharedMedia, Tukui, ButtonFacade
|
||||
|
||||
Developer\Load_Developer.xml
|
||||
Libraries\Load_Libraries.xml
|
||||
Locales\Load_Locales.xml
|
||||
Media\Load_Media.xml
|
||||
Init.lua
|
||||
Settings\Load_Config.xml
|
||||
Core\Load_Core.xml
|
||||
Layout\Load_Layout.xml
|
||||
Modules\Load_Modules.xml
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
local _G = _G
|
||||
|
||||
BINDING_HEADER_ELVUI = GetAddOnMetadata("ElvUI", "Title")
|
||||
|
||||
local AddOnName, Engine = "ElvUI", {}
|
||||
local AddOn = LibStub("AceAddon-3.0"):NewAddon(AddOnName, "AceConsole-3.0", "AceEvent-3.0", "AceTimer-3.0", "AceHook-3.0")
|
||||
AddOn.callbacks = AddOn.callbacks or
|
||||
LibStub("CallbackHandler-1.0"):New(AddOn)
|
||||
AddOn.DF = {} AddOn.DF["profile"] = {} AddOn.DF["global"] = {} AddOn.privateVars = {} AddOn.privateVars["profile"] = {} -- Defaults
|
||||
AddOn.Options = {
|
||||
type = "group",
|
||||
name = AddOnName,
|
||||
args = {},
|
||||
}
|
||||
|
||||
local Locale = LibStub("AceLocale-3.0"):GetLocale(AddOnName, false)
|
||||
Engine[1] = AddOn
|
||||
Engine[2] = Locale
|
||||
Engine[3] = AddOn.privateVars["profile"]
|
||||
Engine[4] = AddOn.DF["profile"]
|
||||
Engine[5] = AddOn.DF["global"]
|
||||
|
||||
_G[AddOnName] = Engine
|
||||
local tcopy = table.copy
|
||||
function AddOn:OnInitialize()
|
||||
if not ElvCharacterDB then
|
||||
ElvCharacterDB = {}
|
||||
end
|
||||
|
||||
self.db = tcopy(self.DF.profile, true)
|
||||
self.global = tcopy(self.DF.global, true)
|
||||
if ElvDB then
|
||||
if ElvDB.global then
|
||||
self:CopyTable(self.global, ElvDB.global)
|
||||
end
|
||||
|
||||
local profileKey
|
||||
if ElvDB.profileKeys then
|
||||
profileKey = ElvDB.profileKeys[self.myname.." - "..self.myrealm]
|
||||
end
|
||||
|
||||
if profileKey and ElvDB.profiles and ElvDB.profiles[profileKey] then
|
||||
self:CopyTable(self.db, ElvDB.profiles[profileKey])
|
||||
end
|
||||
end
|
||||
|
||||
self.private = tcopy(self.privateVars.profile, true)
|
||||
if ElvPrivateDB then
|
||||
local profileKey
|
||||
if ElvPrivateDB.profileKeys then
|
||||
profileKey = ElvPrivateDB.profileKeys[self.myname.." - "..self.myrealm]
|
||||
end
|
||||
|
||||
if profileKey and ElvPrivateDB.profiles and ElvPrivateDB.profiles[profileKey] then
|
||||
self:CopyTable(self.private, ElvPrivateDB.profiles[profileKey])
|
||||
end
|
||||
end
|
||||
|
||||
if self.private.general.pixelPerfect then
|
||||
self.Border = self.mult
|
||||
self.Spacing = 0
|
||||
self.PixelMode = true
|
||||
end
|
||||
|
||||
self:UIScale()
|
||||
self:UpdateMedia()
|
||||
|
||||
self:RegisterEvent("PLAYER_LOGIN", "Initialize")
|
||||
self:Contruct_StaticPopups()
|
||||
self:InitializeInitialModules()
|
||||
|
||||
if IsAddOnLoaded("Tukui") then
|
||||
self:StaticPopup_Show("TUKUI_ELVUI_INCOMPATIBLE")
|
||||
end
|
||||
|
||||
local GameMenuButton = CreateFrame("Button", nil, GameMenuFrame, "GameMenuButtonTemplate")
|
||||
GameMenuButton:SetWidth(GameMenuButtonLogout:GetWidth())
|
||||
GameMenuButton:SetHeight(GameMenuButtonLogout:GetHeight())
|
||||
|
||||
GameMenuButton:SetText(self:ColorizedName(AddOnName))
|
||||
GameMenuButton:SetScript("OnClick", function()
|
||||
AddOn:ToggleConfig()
|
||||
HideUIPanel(GameMenuFrame)
|
||||
end)
|
||||
GameMenuFrame[AddOnName] = GameMenuButton
|
||||
|
||||
HookScript(GameMenuFrame, "OnShow", function()
|
||||
if not GameMenuFrame.isElvUI then
|
||||
GameMenuFrame:SetHeight(GameMenuFrame:GetHeight() + GameMenuButtonLogout:GetHeight() + 1)
|
||||
GameMenuFrame.isElvUI = true
|
||||
end
|
||||
local _, relTo = GameMenuButtonLogout:GetPoint()
|
||||
if relTo ~= GameMenuFrame[AddOnName] then
|
||||
GameMenuFrame[AddOnName]:ClearAllPoints()
|
||||
GameMenuFrame[AddOnName]:SetPoint("TOPLEFT", relTo, "BOTTOMLEFT", 0, -1)
|
||||
GameMenuButtonLogout:ClearAllPoints()
|
||||
GameMenuButtonLogout:SetPoint("TOPLEFT", GameMenuFrame[AddOnName], "BOTTOMLEFT", 0, -16)
|
||||
end
|
||||
end)
|
||||
local S = AddOn:GetModule("Skins")
|
||||
S:HandleButton(GameMenuButton)
|
||||
end
|
||||
|
||||
function AddOn:ResetProfile()
|
||||
local profileKey
|
||||
if ElvPrivateDB.profileKeys then
|
||||
profileKey = ElvPrivateDB.profileKeys[self.myname.." - "..self.myrealm]
|
||||
end
|
||||
|
||||
if profileKey and ElvPrivateDB.profiles and ElvPrivateDB.profiles[profileKey] then
|
||||
ElvPrivateDB.profiles[profileKey] = nil
|
||||
end
|
||||
|
||||
ElvCharacterDB = nil
|
||||
ReloadUI()
|
||||
end
|
||||
|
||||
function AddOn:OnProfileReset()
|
||||
self:StaticPopup_Show("RESET_PROFILE_PROMPT")
|
||||
end
|
||||
|
||||
function AddOn:ToggleConfig()
|
||||
if not IsAddOnLoaded("ElvUI_Config") then
|
||||
local _, _, _, _, _, reason = GetAddOnInfo("ElvUI_Config")
|
||||
if reason ~= "MISSING" and reason ~= "DISABLED" then
|
||||
LoadAddOn("ElvUI_Config")
|
||||
if GetAddOnMetadata("ElvUI_Config", "Version") ~= "1.01" then
|
||||
self:StaticPopup_Show("CLIENT_UPDATE_REQUEST")
|
||||
end
|
||||
else
|
||||
self:Print("|cffff0000Error -- Addon 'ElvUI_Config' not found or is disabled.|r")
|
||||
return
|
||||
end
|
||||
end
|
||||
|
||||
local ACD = LibStub("AceConfigDialog-3.0")
|
||||
|
||||
local mode = "Close"
|
||||
if not ACD.OpenFrames[AddOnName] then
|
||||
mode = "Open"
|
||||
end
|
||||
|
||||
if mode == "Open" then
|
||||
PlaySound("igMainMenuOpen")
|
||||
else
|
||||
PlaySound("igMainMenuClose")
|
||||
end
|
||||
|
||||
ACD[mode](ACD, AddOnName)
|
||||
|
||||
GameTooltip:Hide() --Just in case you're mouseovered something and it closes.
|
||||
end
|
||||
@@ -0,0 +1,415 @@
|
||||
local E, L, V, P, G = unpack(ElvUI); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
|
||||
local LO = E:NewModule("Layout", "AceEvent-3.0");
|
||||
|
||||
--Cache global variables
|
||||
--Lua functions
|
||||
|
||||
--WoW API / Variables
|
||||
local CreateFrame = CreateFrame
|
||||
local UIFrameFadeIn, UIFrameFadeOut = UIFrameFadeIn, UIFrameFadeOut
|
||||
|
||||
local PANEL_HEIGHT = 22
|
||||
local SIDE_BUTTON_WIDTH = 16
|
||||
|
||||
E.Layout = LO
|
||||
|
||||
local function Panel_OnShow(self)
|
||||
self:SetFrameLevel(0)
|
||||
self:SetFrameStrata("BACKGROUND")
|
||||
end
|
||||
|
||||
function LO:Initialize()
|
||||
self:CreateChatPanels()
|
||||
self:CreateMinimapPanels()
|
||||
|
||||
self:SetDataPanelStyle()
|
||||
|
||||
self.BottomPanel = CreateFrame("Frame", "ElvUI_BottomPanel", E.UIParent)
|
||||
E:SetTemplate(self.BottomPanel, "Transparent")
|
||||
self.BottomPanel:SetPoint("BOTTOMLEFT", E.UIParent, "BOTTOMLEFT", -1, -1)
|
||||
self.BottomPanel:SetPoint("BOTTOMRIGHT", E.UIParent, "BOTTOMRIGHT", 1, -1)
|
||||
self.BottomPanel:SetHeight(PANEL_HEIGHT)
|
||||
self.BottomPanel:SetScript("OnShow", function() Panel_OnShow(this) end)
|
||||
Panel_OnShow(self.BottomPanel)
|
||||
self:BottomPanelVisibility()
|
||||
|
||||
self.TopPanel = CreateFrame("Frame", "ElvUI_TopPanel", E.UIParent)
|
||||
E:SetTemplate(self.TopPanel, "Transparent")
|
||||
self.TopPanel:SetPoint("TOPLEFT", E.UIParent, "TOPLEFT", -1, 1)
|
||||
self.TopPanel:SetPoint("TOPRIGHT", E.UIParent, "TOPRIGHT", 1, 1)
|
||||
self.TopPanel:SetHeight(PANEL_HEIGHT)
|
||||
self.TopPanel:SetScript("OnShow", function() Panel_OnShow(this) end)
|
||||
Panel_OnShow(self.TopPanel)
|
||||
self:TopPanelVisibility()
|
||||
end
|
||||
|
||||
function LO:BottomPanelVisibility()
|
||||
if(E.db.general.bottomPanel) then
|
||||
self.BottomPanel:Show()
|
||||
else
|
||||
self.BottomPanel:Hide()
|
||||
end
|
||||
end
|
||||
|
||||
function LO:TopPanelVisibility()
|
||||
if E.db.general.topPanel then
|
||||
self.TopPanel:Show()
|
||||
else
|
||||
self.TopPanel:Hide()
|
||||
end
|
||||
end
|
||||
|
||||
local function ChatPanelLeft_OnFade()
|
||||
LeftChatPanel:Hide()
|
||||
end
|
||||
|
||||
local function ChatPanelRight_OnFade()
|
||||
RightChatPanel:Hide()
|
||||
end
|
||||
|
||||
local function ChatButton_OnEnter()
|
||||
if E.db[this.parent:GetName().."Faded"] then
|
||||
this.parent:Show()
|
||||
UIFrameFadeIn(this.parent, 0.2, this.parent:GetAlpha(), 1)
|
||||
UIFrameFadeIn(this, 0.2, this:GetAlpha(), 1)
|
||||
end
|
||||
|
||||
if this == LeftChatToggleButton then
|
||||
GameTooltip:SetOwner(this, "ANCHOR_TOPLEFT", 0, (E.PixelMode and 1 or 3))
|
||||
GameTooltip:ClearLines()
|
||||
GameTooltip:AddDoubleLine(L["Left Click:"], L["Toggle Chat Frame"], 1, 1, 1)
|
||||
else
|
||||
GameTooltip:SetOwner(this, "ANCHOR_TOPRIGHT", 0, (E.PixelMode and 1 or 3))
|
||||
GameTooltip:ClearLines()
|
||||
GameTooltip:AddDoubleLine(L["Left Click:"], L["Toggle Chat Frame"], 1, 1, 1)
|
||||
end
|
||||
|
||||
GameTooltip:Show()
|
||||
end
|
||||
|
||||
local function ChatButton_OnLeave()
|
||||
if E.db[this.parent:GetName().."Faded"] then
|
||||
UIFrameFadeOut(this.parent, 0.2, this.parent:GetAlpha(), 0)
|
||||
UIFrameFadeOut(this, 0.2, this:GetAlpha(), 0)
|
||||
this.parent.fadeInfo.finishedFunc = this.parent.fadeFunc
|
||||
end
|
||||
GameTooltip:Hide()
|
||||
end
|
||||
|
||||
local function ChatButton_OnClick()
|
||||
GameTooltip:Hide()
|
||||
if E.db[this.parent:GetName().."Faded"] then
|
||||
E.db[this.parent:GetName().."Faded"] = nil
|
||||
UIFrameFadeIn(this.parent, 0.2, this.parent:GetAlpha(), 1)
|
||||
UIFrameFadeIn(this, 0.2, this:GetAlpha(), 1)
|
||||
else
|
||||
E.db[this.parent:GetName().."Faded"] = true
|
||||
UIFrameFadeOut(this.parent, 0.2, this.parent:GetAlpha(), 0)
|
||||
UIFrameFadeOut(this, 0.2, this:GetAlpha(), 0)
|
||||
this.parent.fadeInfo.finishedFunc = this.parent.fadeFunc
|
||||
end
|
||||
end
|
||||
|
||||
function HideLeftChat()
|
||||
ChatButton_OnClick(LeftChatToggleButton)
|
||||
end
|
||||
|
||||
function HideRightChat()
|
||||
ChatButton_OnClick(RightChatToggleButton)
|
||||
end
|
||||
|
||||
function HideBothChat()
|
||||
ChatButton_OnClick(LeftChatToggleButton)
|
||||
ChatButton_OnClick(RightChatToggleButton)
|
||||
end
|
||||
|
||||
function LO:ToggleChatTabPanels(rightOverride, leftOverride)
|
||||
if leftOverride or not E.db.chat.panelTabBackdrop then
|
||||
LeftChatTab:Hide()
|
||||
else
|
||||
LeftChatTab:Show()
|
||||
end
|
||||
|
||||
if rightOverride or not E.db.chat.panelTabBackdrop then
|
||||
RightChatTab:Hide()
|
||||
else
|
||||
RightChatTab:Show()
|
||||
end
|
||||
end
|
||||
|
||||
function LO:SetChatTabStyle()
|
||||
if E.db.chat.panelTabTransparency then
|
||||
E:SetTemplate(LeftChatTab, "Transparent")
|
||||
E:SetTemplate(RightChatTab, "Transparent")
|
||||
else
|
||||
E:SetTemplate(LeftChatTab, "Default", true)
|
||||
E:SetTemplate(RightChatTab, "Default", true)
|
||||
end
|
||||
end
|
||||
|
||||
function LO:SetDataPanelStyle()
|
||||
if E.db.datatexts.panelTransparency then
|
||||
if not E.db.datatexts.panelBackdrop then
|
||||
E:SetTemplate(LeftChatDataPanel, "NoBackdrop")
|
||||
E:SetTemplate(LeftChatToggleButton, "NoBackdrop")
|
||||
E:SetTemplate(RightChatDataPanel, "NoBackdrop")
|
||||
E:SetTemplate(RightChatToggleButton, "NoBackdrop")
|
||||
else
|
||||
E:SetTemplate(LeftChatDataPanel, "Transparent")
|
||||
E:SetTemplate(LeftChatToggleButton, "Transparent")
|
||||
E:SetTemplate(RightChatDataPanel, "Transparent")
|
||||
E:SetTemplate(RightChatToggleButton, "Transparent")
|
||||
end
|
||||
|
||||
E:SetTemplate(LeftMiniPanel, "Transparent")
|
||||
E:SetTemplate(RightMiniPanel, "Transparent")
|
||||
else
|
||||
if not E.db.datatexts.panelBackdrop then
|
||||
E:SetTemplate(LeftChatDataPanel, "NoBackdrop")
|
||||
E:SetTemplate(LeftChatToggleButton, "NoBackdrop")
|
||||
E:SetTemplate(RightChatDataPanel, "NoBackdrop")
|
||||
E:SetTemplate(RightChatToggleButton, "NoBackdrop")
|
||||
else
|
||||
E:SetTemplate(LeftChatDataPanel, "Default", true)
|
||||
E:SetTemplate(LeftChatToggleButton, "Default", true)
|
||||
E:SetTemplate(RightChatDataPanel, "Default", true)
|
||||
E:SetTemplate(RightChatToggleButton, "Default", true)
|
||||
end
|
||||
|
||||
E:SetTemplate(RightMiniPanel, "Default", true)
|
||||
E:SetTemplate(LeftMiniPanel, "Default", true)
|
||||
end
|
||||
end
|
||||
|
||||
function LO:ToggleChatPanels()
|
||||
LeftChatDataPanel:ClearAllPoints()
|
||||
RightChatDataPanel:ClearAllPoints()
|
||||
local SPACING = E.Border*3 - E.Spacing
|
||||
|
||||
if E.db.datatexts.leftChatPanel then
|
||||
LeftChatDataPanel:Show()
|
||||
LeftChatToggleButton:Show()
|
||||
else
|
||||
LeftChatDataPanel:Hide()
|
||||
LeftChatToggleButton:Hide()
|
||||
end
|
||||
|
||||
if E.db.datatexts.rightChatPanel then
|
||||
RightChatDataPanel:Show()
|
||||
RightChatToggleButton:Show()
|
||||
else
|
||||
RightChatDataPanel:Hide()
|
||||
RightChatToggleButton:Hide()
|
||||
end
|
||||
|
||||
local panelBackdrop = E.db.chat.panelBackdrop
|
||||
if(panelBackdrop == "SHOWBOTH") then
|
||||
LeftChatPanel.backdrop:Show()
|
||||
RightChatPanel.backdrop:Show()
|
||||
LeftChatDataPanel:SetPoint("BOTTOMLEFT", LeftChatPanel, "BOTTOMLEFT", SPACING + SIDE_BUTTON_WIDTH, SPACING)
|
||||
RightChatDataPanel:SetPoint("BOTTOMLEFT", RightChatPanel, "BOTTOMLEFT", SPACING, SPACING)
|
||||
LeftChatToggleButton:SetPoint("BOTTOMLEFT", LeftChatPanel, "BOTTOMLEFT", SPACING, SPACING)
|
||||
RightChatToggleButton:SetPoint("BOTTOMRIGHT", RightChatPanel, "BOTTOMRIGHT", -SPACING, SPACING)
|
||||
LO:ToggleChatTabPanels()
|
||||
elseif(panelBackdrop == "HIDEBOTH") then
|
||||
LeftChatPanel.backdrop:Hide()
|
||||
RightChatPanel.backdrop:Hide()
|
||||
LeftChatDataPanel:SetPoint("BOTTOMLEFT", LeftChatPanel, "BOTTOMLEFT", SIDE_BUTTON_WIDTH, 0)
|
||||
RightChatDataPanel:SetPoint("BOTTOMLEFT", RightChatPanel, "BOTTOMLEFT")
|
||||
LeftChatToggleButton:SetPoint("BOTTOMLEFT", LeftChatPanel, "BOTTOMLEFT")
|
||||
RightChatToggleButton:SetPoint("BOTTOMRIGHT", RightChatPanel, "BOTTOMRIGHT")
|
||||
LO:ToggleChatTabPanels(true, true)
|
||||
elseif(panelBackdrop == "LEFT") then
|
||||
LeftChatPanel.backdrop:Show()
|
||||
RightChatPanel.backdrop:Hide()
|
||||
LeftChatDataPanel:SetPoint("BOTTOMLEFT", LeftChatPanel, "BOTTOMLEFT", SPACING + SIDE_BUTTON_WIDTH, SPACING)
|
||||
RightChatDataPanel:SetPoint("BOTTOMLEFT", RightChatPanel, "BOTTOMLEFT")
|
||||
LeftChatToggleButton:SetPoint("BOTTOMLEFT", LeftChatPanel, "BOTTOMLEFT", SPACING, SPACING)
|
||||
RightChatToggleButton:SetPoint("BOTTOMRIGHT", RightChatPanel, "BOTTOMRIGHT")
|
||||
LO:ToggleChatTabPanels(true)
|
||||
else
|
||||
LeftChatPanel.backdrop:Hide()
|
||||
RightChatPanel.backdrop:Show()
|
||||
LeftChatDataPanel:SetPoint("BOTTOMLEFT", LeftChatPanel, "BOTTOMLEFT", SIDE_BUTTON_WIDTH, 0)
|
||||
RightChatDataPanel:SetPoint("BOTTOMLEFT", RightChatPanel, "BOTTOMLEFT", SPACING, SPACING)
|
||||
LeftChatToggleButton:SetPoint("BOTTOMLEFT", LeftChatPanel, "BOTTOMLEFT")
|
||||
RightChatToggleButton:SetPoint("BOTTOMRIGHT", RightChatPanel, "BOTTOMRIGHT", -SPACING, SPACING)
|
||||
LO:ToggleChatTabPanels(nil, true)
|
||||
end
|
||||
end
|
||||
|
||||
function LO:CreateChatPanels()
|
||||
local SPACING = E.Border*3 - E.Spacing
|
||||
--Left Chat
|
||||
local lchat = CreateFrame("Frame", "LeftChatPanel", E.UIParent)
|
||||
lchat:SetFrameStrata("BACKGROUND")
|
||||
lchat:SetWidth(E.db.chat.panelWidth)
|
||||
lchat:SetHeight(E.db.chat.panelHeight)
|
||||
lchat:SetPoint("BOTTOMLEFT", E.UIParent, 4, 4)
|
||||
lchat:SetFrameLevel(lchat:GetFrameLevel() + 2)
|
||||
E:CreateBackdrop(lchat, "Transparent")
|
||||
lchat.backdrop:SetAllPoints()
|
||||
E:CreateMover(lchat, "LeftChatMover", L["Left Chat"])
|
||||
|
||||
--Background Texture
|
||||
lchat.tex = lchat:CreateTexture(nil, "OVERLAY")
|
||||
E:SetInside(lchat.tex)
|
||||
lchat.tex:SetTexture(E.db.chat.panelBackdropNameLeft)
|
||||
lchat.tex:SetAlpha(E.db.general.backdropfadecolor.a - 0.7 > 0 and E.db.general.backdropfadecolor.a - 0.7 or 0.5)
|
||||
|
||||
--Left Chat Tab
|
||||
local lchattab = CreateFrame("Frame", "LeftChatTab", LeftChatPanel)
|
||||
lchattab:SetPoint("TOPLEFT", lchat, "TOPLEFT", SPACING, -SPACING)
|
||||
lchattab:SetPoint("BOTTOMRIGHT", lchat, "TOPRIGHT", -SPACING, -(SPACING + PANEL_HEIGHT))
|
||||
E:SetTemplate(lchattab, E.db.chat.panelTabTransparency == true and "Transparent" or "Default", true)
|
||||
|
||||
--Left Chat Data Panel
|
||||
local lchatdp = CreateFrame("Frame", "LeftChatDataPanel", LeftChatPanel)
|
||||
lchatdp:SetWidth(E.db.chat.panelWidth -((SPACING*2) + SIDE_BUTTON_WIDTH))
|
||||
lchatdp:SetHeight(PANEL_HEIGHT)
|
||||
lchatdp:SetPoint("BOTTOMLEFT", lchat, "BOTTOMLEFT", SPACING + SIDE_BUTTON_WIDTH, SPACING)
|
||||
E:SetTemplate(lchatdp, E.db.datatexts.panelTransparency and "Transparent" or "Default", true)
|
||||
E:GetModule("DataTexts"):RegisterPanel(lchatdp, 3, "ANCHOR_TOPLEFT", -16, (E.PixelMode and 1 or 3))
|
||||
|
||||
--Left Chat Toggle Button
|
||||
local lchattb = CreateFrame("Button", "LeftChatToggleButton", E.UIParent)
|
||||
lchattb.parent = LeftChatPanel
|
||||
LeftChatPanel.fadeFunc = ChatPanelLeft_OnFade
|
||||
lchattb:SetPoint("TOPRIGHT", lchatdp, "TOPLEFT", E.Border - E.Spacing*3, 0)
|
||||
lchattb:SetPoint("BOTTOMLEFT", lchat, "BOTTOMLEFT", SPACING, SPACING)
|
||||
E:SetTemplate(lchattb, E.db.datatexts.panelTransparency and "Transparent" or "Default", true)
|
||||
lchattb:SetScript("OnEnter", ChatButton_OnEnter)
|
||||
lchattb:SetScript("OnLeave", ChatButton_OnLeave)
|
||||
lchattb:SetScript("OnClick", ChatButton_OnClick)
|
||||
lchattb.text = lchattb:CreateFontString(nil, "OVERLAY")
|
||||
E:FontTemplate(lchattb.text)
|
||||
lchattb.text:SetPoint("CENTER", lchattb)
|
||||
lchattb.text:SetJustifyH("CENTER")
|
||||
lchattb.text:SetText("<")
|
||||
|
||||
--Right Chat
|
||||
local rchat = CreateFrame("Frame", "RightChatPanel", E.UIParent)
|
||||
rchat:SetFrameStrata("BACKGROUND")
|
||||
rchat:SetWidth(E.db.chat.separateSizes and E.db.chat.panelWidthRight or E.db.chat.panelWidth)
|
||||
rchat:SetHeight(E.db.chat.separateSizes and E.db.chat.panelHeightRight or E.db.chat.panelHeight)
|
||||
rchat:SetPoint("BOTTOMRIGHT", E.UIParent, -4, 4)
|
||||
rchat:SetFrameLevel(lchat:GetFrameLevel() + 2)
|
||||
E:CreateBackdrop(rchat, "Transparent")
|
||||
rchat.backdrop:SetAllPoints()
|
||||
E:CreateMover(rchat, "RightChatMover", L["Right Chat"])
|
||||
|
||||
--Background Texture
|
||||
rchat.tex = rchat:CreateTexture(nil, "OVERLAY")
|
||||
E:SetInside(rchat.tex)
|
||||
rchat.tex:SetTexture(E.db.chat.panelBackdropNameRight)
|
||||
rchat.tex:SetAlpha(E.db.general.backdropfadecolor.a - 0.7 > 0 and E.db.general.backdropfadecolor.a - 0.7 or 0.5)
|
||||
|
||||
--Right Chat Tab
|
||||
local rchattab = CreateFrame("Frame", "RightChatTab", RightChatPanel)
|
||||
rchattab:SetPoint("TOPRIGHT", rchat, "TOPRIGHT", -SPACING, -SPACING)
|
||||
rchattab:SetPoint("BOTTOMLEFT", rchat, "TOPLEFT", SPACING, -(SPACING + PANEL_HEIGHT))
|
||||
E:SetTemplate(rchattab, E.db.chat.panelTabTransparency == true and "Transparent" or "Default", true)
|
||||
|
||||
--Right Chat Data Panel
|
||||
local rchatdp = CreateFrame("Frame", "RightChatDataPanel", RightChatPanel)
|
||||
rchatdp:SetWidth((E.db.chat.separateSizes and E.db.chat.panelWidthRight or E.db.chat.panelWidth) -((SPACING*2) + SIDE_BUTTON_WIDTH))
|
||||
rchatdp:SetHeight(PANEL_HEIGHT)
|
||||
rchatdp:SetPoint("BOTTOMLEFT", rchat, "BOTTOMLEFT", SPACING, SPACING)
|
||||
E:SetTemplate(rchatdp, E.db.datatexts.panelTransparency and "Transparent" or "Default", true)
|
||||
E:GetModule("DataTexts"):RegisterPanel(rchatdp, 3, "ANCHOR_TOPRIGHT", 16, (E.PixelMode and 1 or 3))
|
||||
|
||||
--Right Chat Toggle Button
|
||||
local rchattb = CreateFrame("Button", "RightChatToggleButton", E.UIParent)
|
||||
rchattb.parent = RightChatPanel
|
||||
RightChatPanel.fadeFunc = ChatPanelRight_OnFade
|
||||
rchattb:SetPoint("TOPLEFT", rchatdp, "TOPRIGHT", -E.Border + E.Spacing*3, 0)
|
||||
rchattb:SetPoint("BOTTOMRIGHT", rchat, "BOTTOMRIGHT", -SPACING, SPACING)
|
||||
E:SetTemplate(rchattb, E.db.datatexts.panelTransparency and "Transparent" or "Default", true)
|
||||
rchattb:SetScript("OnEnter", ChatButton_OnEnter)
|
||||
rchattb:SetScript("OnLeave", ChatButton_OnLeave)
|
||||
rchattb:SetScript("OnClick", ChatButton_OnClick)
|
||||
rchattb.text = rchattb:CreateFontString(nil, "OVERLAY")
|
||||
E:FontTemplate(rchattb.text)
|
||||
rchattb.text:SetPoint("CENTER", rchattb)
|
||||
rchattb.text:SetJustifyH("CENTER")
|
||||
rchattb.text:SetText(">")
|
||||
|
||||
--Load Settings
|
||||
if E.db["LeftChatPanelFaded"] then
|
||||
LeftChatToggleButton:SetAlpha(0)
|
||||
LeftChatPanel:Hide()
|
||||
end
|
||||
|
||||
if E.db["RightChatPanelFaded"] then
|
||||
RightChatToggleButton:SetAlpha(0)
|
||||
RightChatPanel:Hide()
|
||||
end
|
||||
|
||||
self:ToggleChatPanels()
|
||||
end
|
||||
|
||||
function LO:CreateMinimapPanels()
|
||||
local lminipanel = CreateFrame("Frame", "LeftMiniPanel", Minimap.backdrop)
|
||||
lminipanel:SetWidth(E.db.general.minimap.size/2 + (E.PixelMode and 1 or 3))
|
||||
lminipanel:SetHeight(PANEL_HEIGHT)
|
||||
lminipanel:SetPoint("TOPLEFT", Minimap, "BOTTOMLEFT", -E.Border, (E.PixelMode and 0 or -3))
|
||||
E:SetTemplate(lminipanel, E.db.datatexts.panelTransparency and "Transparent" or "Default", true)
|
||||
E:GetModule("DataTexts"):RegisterPanel(lminipanel, 1, "ANCHOR_BOTTOMLEFT", lminipanel:GetWidth() * 2, -(E.PixelMode and 1 or 3))
|
||||
|
||||
local rminipanel = CreateFrame("Frame", "RightMiniPanel", Minimap.backdrop)
|
||||
rminipanel:SetWidth(E.db.general.minimap.size/2 + (E.PixelMode and 1 or 3))
|
||||
rminipanel:SetHeight(PANEL_HEIGHT)
|
||||
rminipanel:SetPoint("TOPRIGHT", Minimap, "BOTTOMRIGHT", E.Border, (E.PixelMode and 0 or -3))
|
||||
E:SetTemplate(rminipanel, E.db.datatexts.panelTransparency and "Transparent" or "Default", true)
|
||||
E:GetModule("DataTexts"):RegisterPanel(rminipanel, 1, "ANCHOR_BOTTOM", 0, -(E.PixelMode and 1 or 3))
|
||||
|
||||
if E.db.datatexts.minimapPanels then
|
||||
LeftMiniPanel:Show()
|
||||
RightMiniPanel:Show()
|
||||
else
|
||||
LeftMiniPanel:Hide()
|
||||
RightMiniPanel:Hide()
|
||||
end
|
||||
|
||||
local f = CreateFrame("Frame", "BottomMiniPanel", Minimap.backdrop)
|
||||
f:SetPoint("BOTTOM", Minimap, "BOTTOM")
|
||||
f:SetWidth(75)
|
||||
f:SetHeight(20)
|
||||
E:GetModule("DataTexts"):RegisterPanel(f, 1, "ANCHOR_BOTTOM", 0, -10)
|
||||
|
||||
f = CreateFrame("Frame", "TopMiniPanel", Minimap.backdrop)
|
||||
f:SetPoint("TOP", Minimap, "TOP")
|
||||
f:SetWidth(75)
|
||||
f:SetHeight(20)
|
||||
E:GetModule("DataTexts"):RegisterPanel(f, 1, "ANCHOR_BOTTOM", 0, -10)
|
||||
|
||||
f = CreateFrame("Frame", "TopLeftMiniPanel", Minimap.backdrop)
|
||||
f:SetPoint("TOPLEFT", Minimap, "TOPLEFT")
|
||||
f:SetWidth(75)
|
||||
f:SetHeight(20)
|
||||
E:GetModule("DataTexts"):RegisterPanel(f, 1, "ANCHOR_BOTTOMLEFT", 0, -10)
|
||||
|
||||
f = CreateFrame("Frame", "TopRightMiniPanel", Minimap.backdrop)
|
||||
f:SetPoint("TOPRIGHT", Minimap, "TOPRIGHT")
|
||||
f:SetWidth(75)
|
||||
f:SetHeight(20)
|
||||
E:GetModule("DataTexts"):RegisterPanel(f, 1, "ANCHOR_BOTTOMRIGHT", 0, -10)
|
||||
|
||||
f = CreateFrame("Frame", "BottomLeftMiniPanel", Minimap.backdrop)
|
||||
f:SetPoint("BOTTOMLEFT", Minimap, "BOTTOMLEFT")
|
||||
f:SetWidth(75)
|
||||
f:SetHeight(20)
|
||||
E:GetModule("DataTexts"):RegisterPanel(f, 1, "ANCHOR_BOTTOMLEFT", 0, -10)
|
||||
|
||||
f = CreateFrame("Frame", "BottomRightMiniPanel", Minimap.backdrop)
|
||||
f:SetPoint("BOTTOMRIGHT", Minimap, "BOTTOMRIGHT")
|
||||
f:SetWidth(75)
|
||||
f:SetHeight(20)
|
||||
E:GetModule("DataTexts"):RegisterPanel(f, 1, "ANCHOR_BOTTOMRIGHT", 0, -10)
|
||||
end
|
||||
|
||||
local function InitializeCallback()
|
||||
LO:Initialize()
|
||||
end
|
||||
|
||||
E:RegisterModule(LO:GetName(), InitializeCallback)
|
||||
@@ -0,0 +1,3 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="Layout.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,681 @@
|
||||
--- **AceAddon-3.0** provides a template for creating addon objects.
|
||||
-- It'll provide you with a set of callback functions that allow you to simplify the loading
|
||||
-- process of your addon.\\
|
||||
-- Callbacks provided are:\\
|
||||
-- * **OnInitialize**, which is called directly after the addon is fully loaded.
|
||||
-- * **OnEnable** which gets called during the PLAYER_LOGIN event, when most of the data provided by the game is already present.
|
||||
-- * **OnDisable**, which is only called when your addon is manually being disabled.
|
||||
-- @usage
|
||||
-- -- A small (but complete) addon, that doesn't do anything,
|
||||
-- -- but shows usage of the callbacks.
|
||||
-- local MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon")
|
||||
--
|
||||
-- function MyAddon:OnInitialize()
|
||||
-- -- do init tasks here, like loading the Saved Variables,
|
||||
-- -- or setting up slash commands.
|
||||
-- end
|
||||
--
|
||||
-- function MyAddon:OnEnable()
|
||||
-- -- Do more initialization here, that really enables the use of your addon.
|
||||
-- -- Register Events, Hook functions, Create Frames, Get information from
|
||||
-- -- the game that wasn't available in OnInitialize
|
||||
-- end
|
||||
--
|
||||
-- function MyAddon:OnDisable()
|
||||
-- -- Unhook, Unregister Events, Hide frames that you created.
|
||||
-- -- You would probably only use an OnDisable if you want to
|
||||
-- -- build a "standby" mode, or be able to toggle modules on/off.
|
||||
-- end
|
||||
-- @class file
|
||||
-- @name AceAddon-3.0.lua
|
||||
-- @release $Id: AceAddon-3.0.lua 1084 2013-04-27 20:14:11Z nevcairiel $
|
||||
|
||||
local MAJOR, MINOR = "AceAddon-3.0", 12
|
||||
local AceAddon, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
|
||||
|
||||
if not AceAddon then return end -- No Upgrade needed.
|
||||
|
||||
local AceCore = LibStub("AceCore-3.0")
|
||||
local new, del = AceCore.new, AceCore.del
|
||||
local wipe, truncate = AceCore.wipe, AceCore.truncate
|
||||
|
||||
AceAddon.frame = AceAddon.frame or CreateFrame("Frame", "AceAddon30Frame") -- Our very own frame
|
||||
AceAddon.addons = AceAddon.addons or {} -- addons in general
|
||||
AceAddon.statuses = AceAddon.statuses or {} -- statuses of addon.
|
||||
AceAddon.initializequeue = AceAddon.initializequeue or {} -- addons that are new and not initialized
|
||||
AceAddon.enablequeue = AceAddon.enablequeue or {} -- addons that are initialized and waiting to be enabled
|
||||
AceAddon.embeds = AceAddon.embeds or setmetatable({}, {__index = function(tbl, key) tbl[key] = {} return tbl[key] end }) -- contains a list of libraries embedded in an addon
|
||||
|
||||
-- Lua APIs
|
||||
local tinsert, tconcat, tremove, tgetn = table.insert, table.concat, table.remove, table.getn
|
||||
local strfmt, tostring = string.format, tostring
|
||||
local pairs, next, type, unpack = pairs, next, type, unpack
|
||||
local loadstring, assert, error = loadstring, assert, error
|
||||
local setmetatable, getmetatable, rawset, rawget = setmetatable, getmetatable, rawset, rawget
|
||||
|
||||
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
|
||||
-- List them here for Mikk's FindGlobals script
|
||||
-- GLOBALS: LibStub, IsLoggedIn, geterrorhandler
|
||||
|
||||
--[[
|
||||
xpcall safecall implementation
|
||||
]]
|
||||
local safecall = AceCore.safecall
|
||||
|
||||
-- local functions that will be implemented further down
|
||||
local Enable, Disable, EnableModule, DisableModule, Embed, NewModule, GetModule, GetName, SetDefaultModuleState, SetDefaultModuleLibraries, SetEnabledState, SetDefaultModulePrototype
|
||||
|
||||
-- used in the addon metatable
|
||||
local function addontostring( self ) return self.name end
|
||||
|
||||
-- Check if the addon is queued for initialization
|
||||
local function queuedForInitialization(addon)
|
||||
for i = 1, tgetn(AceAddon.initializequeue) do
|
||||
if AceAddon.initializequeue[i] == addon then
|
||||
return true
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
--- Create a new AceAddon-3.0 addon.
|
||||
-- Any libraries you specified will be embeded, and the addon will be scheduled for
|
||||
-- its OnInitialize and OnEnable callbacks.
|
||||
-- The final addon object, with all libraries embeded, will be returned.
|
||||
-- @paramsig [object ,]name[, lib, ...]
|
||||
-- @param object Table to use as a base for the addon (optional)
|
||||
-- @param name Name of the addon object to create
|
||||
-- @param lib List of libraries to embed into the addon
|
||||
-- @usage
|
||||
-- -- Create a simple addon object
|
||||
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon", "AceEvent-3.0")
|
||||
--
|
||||
-- -- Create a Addon object based on the table of a frame
|
||||
-- local MyFrame = CreateFrame("Frame")
|
||||
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon(MyFrame, "MyAddon", "AceEvent-3.0")
|
||||
function AceAddon:NewAddon(objectorname,a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10)
|
||||
|
||||
local object,name
|
||||
if type(objectorname)=="table" then
|
||||
object=objectorname
|
||||
name=a0
|
||||
else
|
||||
name=objectorname
|
||||
end
|
||||
if type(name)~="string" then
|
||||
error(strfmt("Usage: NewAddon([object,] name, [lib, lib, lib, ...]): 'name' - string expected got '%s'.", type(name)), 2)
|
||||
end
|
||||
if self.addons[name] then
|
||||
error(strfmt("Usage: NewAddon([object,] name, [lib, lib, lib, ...]): 'name' - Addon '%s' already exists.", name), 2)
|
||||
end
|
||||
|
||||
local args = new()
|
||||
args[1] = a1
|
||||
args[2] = a2
|
||||
args[3] = a3
|
||||
args[4] = a4
|
||||
args[5] = a5
|
||||
args[6] = a6
|
||||
args[7] = a7
|
||||
args[8] = a8
|
||||
args[9] = a9
|
||||
args[10] = a10
|
||||
|
||||
object = object or {}
|
||||
object.name = name
|
||||
|
||||
local addonmeta = {}
|
||||
local oldmeta = getmetatable(object)
|
||||
if oldmeta then
|
||||
for k, v in pairs(oldmeta) do addonmeta[k] = v end
|
||||
end
|
||||
addonmeta.__tostring = addontostring
|
||||
|
||||
setmetatable( object, addonmeta )
|
||||
self.addons[name] = object
|
||||
object.modules = {}
|
||||
object.orderedModules = {}
|
||||
object.defaultModuleLibraries = {}
|
||||
Embed( object ) -- embed NewModule, GetModule methods
|
||||
if type(objectorname)=="table" then
|
||||
self:EmbedLibraries(object,nil,args)
|
||||
elseif a0 then
|
||||
self:EmbedLibraries(object,a0,args)
|
||||
end
|
||||
del(args)
|
||||
|
||||
-- add to queue of addons to be initialized upon ADDON_LOADED
|
||||
tinsert(self.initializequeue, object)
|
||||
return object
|
||||
end
|
||||
|
||||
--- Get the addon object by its name from the internal AceAddon registry.
|
||||
-- Throws an error if the addon object cannot be found (except if silent is set).
|
||||
-- @param name unique name of the addon object
|
||||
-- @param silent if true, the addon is optional, silently return nil if its not found
|
||||
-- @usage
|
||||
-- -- Get the Addon
|
||||
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
|
||||
function AceAddon:GetAddon(name, silent)
|
||||
if not silent and not self.addons[name] then
|
||||
error(strfmt("Usage: GetAddon(name): 'name' - Cannot find an AceAddon '%s'.", tostring(name)), 2)
|
||||
end
|
||||
return self.addons[name]
|
||||
end
|
||||
|
||||
-- - Embed a list of libraries into the specified addon.
|
||||
-- This function will try to embed all of the listed libraries into the addon
|
||||
-- and error if a single one fails.
|
||||
--
|
||||
-- **Note:** This function is for internal use by :NewAddon/:NewModule
|
||||
-- @paramsig addon, [lib, ...]
|
||||
-- @param addon addon object to embed the libs in
|
||||
-- @param lib List of libraries to embed into the addon
|
||||
function AceAddon:EmbedLibraries(addon,a1,arg)
|
||||
if a1 then self:EmbedLibrary(addon, a1, false, 4) end
|
||||
-- 10 is the max number of variable arguments in the function NewAddon and NewModule
|
||||
for i=1,10 do
|
||||
if not arg[i] then return end
|
||||
self:EmbedLibrary(addon, arg[i], false, 4)
|
||||
end
|
||||
end
|
||||
|
||||
-- - Embed a library into the addon object.
|
||||
-- This function will check if the specified library is registered with LibStub
|
||||
-- and if it has a :Embed function to call. It'll error if any of those conditions
|
||||
-- fails.
|
||||
--
|
||||
-- **Note:** This function is for internal use by :EmbedLibraries
|
||||
-- @paramsig addon, libname[, silent[, offset]]
|
||||
-- @param addon addon object to embed the library in
|
||||
-- @param libname name of the library to embed
|
||||
-- @param silent marks an embed to fail silently if the library doesn't exist (optional)
|
||||
-- @param offset will push the error messages back to said offset, defaults to 2 (optional)
|
||||
function AceAddon:EmbedLibrary(addon, libname, silent, offset)
|
||||
local lib = LibStub:GetLibrary(libname, true)
|
||||
if not lib and not silent then
|
||||
error(strfmt("Usage: EmbedLibrary(addon, libname, silent, offset): 'libname' - Cannot find a library instance of %q.", tostring(libname)), offset or 2)
|
||||
elseif lib and type(lib.Embed) == "function" then
|
||||
lib:Embed(addon)
|
||||
tinsert(self.embeds[addon], libname)
|
||||
return true
|
||||
elseif lib then
|
||||
error(strfmt("Usage: EmbedLibrary(addon, libname, silent, offset): 'libname' - Library '%s' is not Embed capable", libname), offset or 2)
|
||||
end
|
||||
end
|
||||
|
||||
--- Return the specified module from an addon object.
|
||||
-- Throws an error if the addon object cannot be found (except if silent is set)
|
||||
-- @name //addon//:GetModule
|
||||
-- @paramsig name[, silent]
|
||||
-- @param name unique name of the module
|
||||
-- @param silent if true, the module is optional, silently return nil if its not found (optional)
|
||||
-- @usage
|
||||
-- -- Get the Addon
|
||||
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
|
||||
-- -- Get the Module
|
||||
-- MyModule = MyAddon:GetModule("MyModule")
|
||||
function GetModule(self, name, silent)
|
||||
if not self.modules[name] and not silent then
|
||||
error(strfmt("Usage: GetModule(name, silent): 'name' - Cannot find module '%s'.", tostring(name)), 2)
|
||||
end
|
||||
return self.modules[name]
|
||||
end
|
||||
|
||||
local function IsModuleTrue(self) return true end
|
||||
|
||||
--- Create a new module for the addon.
|
||||
-- The new module can have its own embeded libraries and/or use a module prototype to be mixed into the module.\\
|
||||
-- A module has the same functionality as a real addon, it can have modules of its own, and has the same API as
|
||||
-- an addon object.
|
||||
-- @name //addon//:NewModule
|
||||
-- @paramsig name[, prototype|lib[, lib, ...]]
|
||||
-- @param name unique name of the module
|
||||
-- @param prototype object to derive this module from, methods and values from this table will be mixed into the module (optional)
|
||||
-- @param lib List of libraries to embed into the addon
|
||||
-- @usage
|
||||
-- -- Create a module with some embeded libraries
|
||||
-- MyModule = MyAddon:NewModule("MyModule", "AceEvent-3.0", "AceHook-3.0")
|
||||
--
|
||||
-- -- Create a module with a prototype
|
||||
-- local prototype = { OnEnable = function(self) print("OnEnable called!") end }
|
||||
-- MyModule = MyAddon:NewModule("MyModule", prototype, "AceEvent-3.0", "AceHook-3.0")
|
||||
function NewModule(self, name, prototype, a1,a2,a3,a4,a5,a6,a7,a8,a9,a10)
|
||||
if type(name) ~= "string" then error(strfmt("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'name' - string expected got '%s'.", type(name)), 2) end
|
||||
if type(prototype) ~= "string" and type(prototype) ~= "table" and type(prototype) ~= "nil" then error(strfmt("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'prototype' - table (prototype), string (lib) or nil expected got '%s'.", type(prototype)), 2) end
|
||||
|
||||
if self.modules[name] then error(strfmt("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'name' - Module '%s' already exists.", name), 2) end
|
||||
|
||||
-- modules are basically addons. We treat them as such. They will be added to the initializequeue properly as well.
|
||||
-- NewModule can only be called after the parent addon is present thus the modules will be initialized after their parent is.
|
||||
local module = AceAddon:NewAddon(strfmt("%s_%s", self.name or tostring(self), name))
|
||||
|
||||
module.IsModule = IsModuleTrue
|
||||
module:SetEnabledState(self.defaultModuleState)
|
||||
module.moduleName = name
|
||||
|
||||
local args = new()
|
||||
args[1] = a1
|
||||
args[2] = a2
|
||||
args[3] = a3
|
||||
args[4] = a4
|
||||
args[5] = a5
|
||||
args[6] = a6
|
||||
args[7] = a7
|
||||
args[8] = a8
|
||||
args[9] = a9
|
||||
args[10] = a10
|
||||
|
||||
if type(prototype) == "string" then
|
||||
AceAddon:EmbedLibraries(module, prototype, args)
|
||||
else
|
||||
AceAddon:EmbedLibraries(module, nil, args)
|
||||
end
|
||||
del(args)
|
||||
AceAddon:EmbedLibraries(module, nil, self.defaultModuleLibraries)
|
||||
|
||||
if not prototype or type(prototype) == "string" then
|
||||
prototype = self.defaultModulePrototype or nil
|
||||
end
|
||||
|
||||
if type(prototype) == "table" then
|
||||
local mt = getmetatable(module)
|
||||
mt.__index = prototype
|
||||
setmetatable(module, mt) -- More of a Base class type feel.
|
||||
end
|
||||
|
||||
safecall(self.OnModuleCreated, 2, self, module) -- Was in Ace2 and I think it could be a cool thing to have handy.
|
||||
self.modules[name] = module
|
||||
tinsert(self.orderedModules, module)
|
||||
|
||||
return module
|
||||
end
|
||||
|
||||
--- Returns the real name of the addon or module, without any prefix.
|
||||
-- @name //addon//:GetName
|
||||
-- @paramsig
|
||||
-- @usage
|
||||
-- print(MyAddon:GetName())
|
||||
-- -- prints "MyAddon"
|
||||
function GetName(self)
|
||||
return self.moduleName or self.name
|
||||
end
|
||||
|
||||
--- Enables the Addon, if possible, return true or false depending on success.
|
||||
-- This internally calls AceAddon:EnableAddon(), thus dispatching a OnEnable callback
|
||||
-- and enabling all modules of the addon (unless explicitly disabled).\\
|
||||
-- :Enable() also sets the internal `enableState` variable to true
|
||||
-- @name //addon//:Enable
|
||||
-- @paramsig
|
||||
-- @usage
|
||||
-- -- Enable MyModule
|
||||
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
|
||||
-- MyModule = MyAddon:GetModule("MyModule")
|
||||
-- MyModule:Enable()
|
||||
function Enable(self)
|
||||
self:SetEnabledState(true)
|
||||
|
||||
-- nevcairiel 2013-04-27: don't enable an addon/module if its queued for init still
|
||||
-- it'll be enabled after the init process
|
||||
if not queuedForInitialization(self) then
|
||||
return AceAddon:EnableAddon(self)
|
||||
end
|
||||
end
|
||||
|
||||
--- Disables the Addon, if possible, return true or false depending on success.
|
||||
-- This internally calls AceAddon:DisableAddon(), thus dispatching a OnDisable callback
|
||||
-- and disabling all modules of the addon.\\
|
||||
-- :Disable() also sets the internal `enableState` variable to false
|
||||
-- @name //addon//:Disable
|
||||
-- @paramsig
|
||||
-- @usage
|
||||
-- -- Disable MyAddon
|
||||
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
|
||||
-- MyAddon:Disable()
|
||||
function Disable(self)
|
||||
self:SetEnabledState(false)
|
||||
return AceAddon:DisableAddon(self)
|
||||
end
|
||||
|
||||
--- Enables the Module, if possible, return true or false depending on success.
|
||||
-- Short-hand function that retrieves the module via `:GetModule` and calls `:Enable` on the module object.
|
||||
-- @name //addon//:EnableModule
|
||||
-- @paramsig name
|
||||
-- @usage
|
||||
-- -- Enable MyModule using :GetModule
|
||||
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
|
||||
-- MyModule = MyAddon:GetModule("MyModule")
|
||||
-- MyModule:Enable()
|
||||
--
|
||||
-- -- Enable MyModule using the short-hand
|
||||
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
|
||||
-- MyAddon:EnableModule("MyModule")
|
||||
function EnableModule(self, name)
|
||||
local module = self:GetModule( name )
|
||||
return module:Enable()
|
||||
end
|
||||
|
||||
--- Disables the Module, if possible, return true or false depending on success.
|
||||
-- Short-hand function that retrieves the module via `:GetModule` and calls `:Disable` on the module object.
|
||||
-- @name //addon//:DisableModule
|
||||
-- @paramsig name
|
||||
-- @usage
|
||||
-- -- Disable MyModule using :GetModule
|
||||
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
|
||||
-- MyModule = MyAddon:GetModule("MyModule")
|
||||
-- MyModule:Disable()
|
||||
--
|
||||
-- -- Disable MyModule using the short-hand
|
||||
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
|
||||
-- MyAddon:DisableModule("MyModule")
|
||||
function DisableModule(self, name)
|
||||
local module = self:GetModule( name )
|
||||
return module:Disable()
|
||||
end
|
||||
|
||||
--- Set the default libraries to be mixed into all modules created by this object.
|
||||
-- Note that you can only change the default module libraries before any module is created.
|
||||
-- @name //addon//:SetDefaultModuleLibraries
|
||||
-- @paramsig lib[, lib, ...]
|
||||
-- @param lib List of libraries to embed into the addon
|
||||
-- @usage
|
||||
-- -- Create the addon object
|
||||
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon")
|
||||
-- -- Configure default libraries for modules (all modules need AceEvent-3.0)
|
||||
-- MyAddon:SetDefaultModuleLibraries("AceEvent-3.0")
|
||||
-- -- Create a module
|
||||
-- MyModule = MyAddon:NewModule("MyModule")
|
||||
function SetDefaultModuleLibraries(self,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10)
|
||||
if next(self.modules) then
|
||||
error("Usage: SetDefaultModuleLibraries(...): cannot change the module defaults after a module has been registered.", 2)
|
||||
end
|
||||
local args = self.defaultModuleLibraries or {}
|
||||
args[1] = a1
|
||||
args[2] = a2
|
||||
args[3] = a3
|
||||
args[4] = a4
|
||||
args[5] = a5
|
||||
args[6] = a6
|
||||
args[7] = a7
|
||||
args[8] = a8
|
||||
args[9] = a9
|
||||
args[10] = a10
|
||||
|
||||
self.defaultModuleLibraries = args
|
||||
end
|
||||
|
||||
--- Set the default state in which new modules are being created.
|
||||
-- Note that you can only change the default state before any module is created.
|
||||
-- @name //addon//:SetDefaultModuleState
|
||||
-- @paramsig state
|
||||
-- @param state Default state for new modules, true for enabled, false for disabled
|
||||
-- @usage
|
||||
-- -- Create the addon object
|
||||
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon")
|
||||
-- -- Set the default state to "disabled"
|
||||
-- MyAddon:SetDefaultModuleState(false)
|
||||
-- -- Create a module and explicilty enable it
|
||||
-- MyModule = MyAddon:NewModule("MyModule")
|
||||
-- MyModule:Enable()
|
||||
function SetDefaultModuleState(self, state)
|
||||
if next(self.modules) then
|
||||
error("Usage: SetDefaultModuleState(state): cannot change the module defaults after a module has been registered.", 2)
|
||||
end
|
||||
self.defaultModuleState = state
|
||||
end
|
||||
|
||||
--- Set the default prototype to use for new modules on creation.
|
||||
-- Note that you can only change the default prototype before any module is created.
|
||||
-- @name //addon//:SetDefaultModulePrototype
|
||||
-- @paramsig prototype
|
||||
-- @param prototype Default prototype for the new modules (table)
|
||||
-- @usage
|
||||
-- -- Define a prototype
|
||||
-- local prototype = { OnEnable = function(self) print("OnEnable called!") end }
|
||||
-- -- Set the default prototype
|
||||
-- MyAddon:SetDefaultModulePrototype(prototype)
|
||||
-- -- Create a module and explicitly Enable it
|
||||
-- MyModule = MyAddon:NewModule("MyModule")
|
||||
-- MyModule:Enable()
|
||||
-- -- should print "OnEnable called!" now
|
||||
-- @see NewModule
|
||||
function SetDefaultModulePrototype(self, prototype)
|
||||
if next(self.modules) then
|
||||
error("Usage: SetDefaultModulePrototype(prototype): cannot change the module defaults after a module has been registered.", 2)
|
||||
end
|
||||
if type(prototype) ~= "table" then
|
||||
error(strfmt("Usage: SetDefaultModulePrototype(prototype): 'prototype' - table expected got '%s'.", type(prototype)), 2)
|
||||
end
|
||||
self.defaultModulePrototype = prototype
|
||||
end
|
||||
|
||||
--- Set the state of an addon or module
|
||||
-- This should only be called before any enabling actually happend, e.g. in/before OnInitialize.
|
||||
-- @name //addon//:SetEnabledState
|
||||
-- @paramsig state
|
||||
-- @param state the state of an addon or module (enabled=true, disabled=false)
|
||||
function SetEnabledState(self, state)
|
||||
self.enabledState = state
|
||||
end
|
||||
|
||||
|
||||
--- Return an iterator of all modules associated to the addon.
|
||||
-- @name //addon//:IterateModules
|
||||
-- @paramsig
|
||||
-- @usage
|
||||
-- -- Enable all modules
|
||||
-- for name, module in MyAddon:IterateModules() do
|
||||
-- module:Enable()
|
||||
-- end
|
||||
local function IterateModules(self) return pairs(self.modules) end
|
||||
|
||||
-- Returns an iterator of all embeds in the addon
|
||||
-- @name //addon//:IterateEmbeds
|
||||
-- @paramsig
|
||||
local function IterateEmbeds(self) return pairs(AceAddon.embeds[self]) end
|
||||
|
||||
--- Query the enabledState of an addon.
|
||||
-- @name //addon//:IsEnabled
|
||||
-- @paramsig
|
||||
-- @usage
|
||||
-- if MyAddon:IsEnabled() then
|
||||
-- MyAddon:Disable()
|
||||
-- end
|
||||
local function IsEnabled(self) return self.enabledState end
|
||||
local mixins = {
|
||||
NewModule = NewModule,
|
||||
GetModule = GetModule,
|
||||
Enable = Enable,
|
||||
Disable = Disable,
|
||||
EnableModule = EnableModule,
|
||||
DisableModule = DisableModule,
|
||||
IsEnabled = IsEnabled,
|
||||
SetDefaultModuleLibraries = SetDefaultModuleLibraries,
|
||||
SetDefaultModuleState = SetDefaultModuleState,
|
||||
SetDefaultModulePrototype = SetDefaultModulePrototype,
|
||||
SetEnabledState = SetEnabledState,
|
||||
IterateModules = IterateModules,
|
||||
IterateEmbeds = IterateEmbeds,
|
||||
GetName = GetName,
|
||||
}
|
||||
local function IsModule(self) return false end
|
||||
local pmixins = {
|
||||
defaultModuleState = true,
|
||||
enabledState = true,
|
||||
IsModule = IsModule,
|
||||
}
|
||||
-- Embed( target )
|
||||
-- target (object) - target object to embed aceaddon in
|
||||
--
|
||||
-- this is a local function specifically since it's meant to be only called internally
|
||||
function Embed(target, skipPMixins)
|
||||
for k, v in pairs(mixins) do
|
||||
target[k] = v
|
||||
end
|
||||
if not skipPMixins then
|
||||
for k, v in pairs(pmixins) do
|
||||
target[k] = target[k] or v
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
-- - Initialize the addon after creation.
|
||||
-- This function is only used internally during the ADDON_LOADED event
|
||||
-- It will call the **OnInitialize** function on the addon object (if present),
|
||||
-- and the **OnEmbedInitialize** function on all embeded libraries.
|
||||
--
|
||||
-- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing.
|
||||
-- @param addon addon object to intialize
|
||||
function AceAddon:InitializeAddon(addon)
|
||||
safecall(addon.OnInitialize, 1, addon)
|
||||
|
||||
local embeds = self.embeds[addon]
|
||||
for i = 1, tgetn(embeds) do
|
||||
local lib = LibStub:GetLibrary(embeds[i], true)
|
||||
if lib then safecall(lib.OnEmbedInitialize, 2, lib, addon) end
|
||||
end
|
||||
|
||||
-- we don't call InitializeAddon on modules specifically, this is handled
|
||||
-- from the event handler and only done _once_
|
||||
end
|
||||
|
||||
-- - Enable the addon after creation.
|
||||
-- Note: This function is only used internally during the PLAYER_LOGIN event, or during ADDON_LOADED,
|
||||
-- if IsLoggedIn() already returns true at that point, e.g. for LoD Addons.
|
||||
-- It will call the **OnEnable** function on the addon object (if present),
|
||||
-- and the **OnEmbedEnable** function on all embeded libraries.\\
|
||||
-- This function does not toggle the enable state of the addon itself, and will return early if the addon is disabled.
|
||||
--
|
||||
-- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing.
|
||||
-- Use :Enable on the addon itself instead.
|
||||
-- @param addon addon object to enable
|
||||
function AceAddon:EnableAddon(addon)
|
||||
if type(addon) == "string" then addon = AceAddon:GetAddon(addon) end
|
||||
if self.statuses[addon.name] or not addon.enabledState then return false end
|
||||
|
||||
-- set the statuses first, before calling the OnEnable. this allows for Disabling of the addon in OnEnable.
|
||||
self.statuses[addon.name] = true
|
||||
|
||||
safecall(addon.OnEnable, 1, addon)
|
||||
|
||||
-- make sure we're still enabled before continueing
|
||||
if self.statuses[addon.name] then
|
||||
local embeds = self.embeds[addon]
|
||||
for i = 1, tgetn(embeds) do
|
||||
local lib = LibStub:GetLibrary(embeds[i], true)
|
||||
if lib then safecall(lib.OnEmbedEnable, 2, lib, addon) end
|
||||
end
|
||||
|
||||
-- enable possible modules.
|
||||
local modules = addon.orderedModules
|
||||
for i = 1, tgetn(modules) do
|
||||
self:EnableAddon(modules[i])
|
||||
end
|
||||
end
|
||||
return self.statuses[addon.name] -- return true if we're disabled
|
||||
end
|
||||
|
||||
-- - Disable the addon
|
||||
-- Note: This function is only used internally.
|
||||
-- It will call the **OnDisable** function on the addon object (if present),
|
||||
-- and the **OnEmbedDisable** function on all embeded libraries.\\
|
||||
-- This function does not toggle the enable state of the addon itself, and will return early if the addon is still enabled.
|
||||
--
|
||||
-- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing.
|
||||
-- Use :Disable on the addon itself instead.
|
||||
-- @param addon addon object to enable
|
||||
function AceAddon:DisableAddon(addon)
|
||||
if type(addon) == "string" then addon = AceAddon:GetAddon(addon) end
|
||||
if not self.statuses[addon.name] then return false end
|
||||
|
||||
-- set statuses first before calling OnDisable, this allows for aborting the disable in OnDisable.
|
||||
self.statuses[addon.name] = false
|
||||
|
||||
safecall(addon.OnDisable, 1, addon)
|
||||
|
||||
-- make sure we're still disabling...
|
||||
if not self.statuses[addon.name] then
|
||||
local embeds = self.embeds[addon]
|
||||
for i = 1, tgetn(embeds) do
|
||||
local lib = LibStub:GetLibrary(embeds[i], true)
|
||||
if lib then safecall(lib.OnEmbedDisable, 2, lib, addon) end
|
||||
end
|
||||
-- disable possible modules.
|
||||
local modules = addon.orderedModules
|
||||
for i = 1, tgetn(modules) do
|
||||
self:DisableAddon(modules[i])
|
||||
end
|
||||
end
|
||||
|
||||
return not self.statuses[addon.name] -- return true if we're disabled
|
||||
end
|
||||
|
||||
--- Get an iterator over all registered addons.
|
||||
-- @usage
|
||||
-- -- Print a list of all installed AceAddon's
|
||||
-- for name, addon in AceAddon:IterateAddons() do
|
||||
-- print("Addon: " .. name)
|
||||
-- end
|
||||
function AceAddon:IterateAddons() return pairs(self.addons) end
|
||||
|
||||
--- Get an iterator over the internal status registry.
|
||||
-- @usage
|
||||
-- -- Print a list of all enabled addons
|
||||
-- for name, status in AceAddon:IterateAddonStatus() do
|
||||
-- if status then
|
||||
-- print("EnabledAddon: " .. name)
|
||||
-- end
|
||||
-- end
|
||||
function AceAddon:IterateAddonStatus() return pairs(self.statuses) end
|
||||
|
||||
-- Following Iterators are deprecated, and their addon specific versions should be used
|
||||
-- e.g. addon:IterateEmbeds() instead of :IterateEmbedsOnAddon(addon)
|
||||
function AceAddon:IterateEmbedsOnAddon(addon) return pairs(self.embeds[addon]) end
|
||||
function AceAddon:IterateModulesOfAddon(addon) return pairs(addon.modules) end
|
||||
|
||||
|
||||
local onEvent
|
||||
do
|
||||
local IsLoggedIn = false
|
||||
-- Event Handling
|
||||
function onEvent()
|
||||
-- 2011-08-17 nevcairiel - ignore the load event of Blizzard_DebugTools, so a potential startup error isn't swallowed up
|
||||
-- Ace3v: When the ADDON_LOADED event is triggerd, global arg1 is the loaded addon name
|
||||
-- so onEvent(event, arg1) won't work because it will cover the global variables
|
||||
if (event == "ADDON_LOADED" and arg1 ~= "Blizzard_DebugTools") or event == "PLAYER_LOGIN" then
|
||||
-- if a addon loads another addon, recursion could happen here, so we need to validate the table on every iteration
|
||||
-- Ace3v: When an Ace3 addons is loaded, then he initializeque should not be empty unless
|
||||
-- the addon does not use the library. If an addon that does not use Ace3 library
|
||||
-- is loaded, we will also receive the ADDON_LOADED event but in this case the
|
||||
-- queue will be empty so we have nothing to do.
|
||||
while(tgetn(AceAddon.initializequeue) > 0) do
|
||||
local addon = tremove(AceAddon.initializequeue, 1)
|
||||
-- this might be an issue with recursion - TODO: validate
|
||||
if event == "ADDON_LOADED" then addon.baseName = arg1 end
|
||||
AceAddon:InitializeAddon(addon)
|
||||
tinsert(AceAddon.enablequeue, addon)
|
||||
end
|
||||
|
||||
if event == "PLAYER_LOGIN" then
|
||||
IsLoggedIn = true
|
||||
end
|
||||
|
||||
if IsLoggedIn then
|
||||
while(tgetn(AceAddon.enablequeue) > 0) do
|
||||
local addon = tremove(AceAddon.enablequeue, 1)
|
||||
AceAddon:EnableAddon(addon)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end -- onEvent
|
||||
|
||||
AceAddon.frame:RegisterEvent("ADDON_LOADED")
|
||||
AceAddon.frame:RegisterEvent("PLAYER_LOGIN")
|
||||
AceAddon.frame:SetScript("OnEvent", onEvent)
|
||||
|
||||
-- upgrade embeded
|
||||
for name, addon in pairs(AceAddon.addons) do
|
||||
Embed(addon, true)
|
||||
end
|
||||
@@ -0,0 +1,3 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="AceAddon-3.0.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,306 @@
|
||||
--- **AceComm-3.0** allows you to send messages of unlimited length over the addon comm channels.
|
||||
-- It'll automatically split the messages into multiple parts and rebuild them on the receiving end.\\
|
||||
-- **ChatThrottleLib** is of course being used to avoid being disconnected by the server.
|
||||
--
|
||||
-- **AceComm-3.0** can be embeded into your addon, either explicitly by calling AceComm:Embed(MyAddon) or by
|
||||
-- specifying it as an embeded library in your AceAddon. All functions will be available on your addon object
|
||||
-- and can be accessed directly, without having to explicitly call AceComm itself.\\
|
||||
-- It is recommended to embed AceComm, otherwise you'll have to specify a custom `self` on all calls you
|
||||
-- make into AceComm.
|
||||
-- @class file
|
||||
-- @name AceComm-3.0
|
||||
-- @release $Id: AceComm-3.0.lua 1107 2014-02-19 16:40:32Z nevcairiel $
|
||||
|
||||
--[[ AceComm-3.0
|
||||
|
||||
TODO: Time out old data rotting around from dead senders? Not a HUGE deal since the number of possible sender names is somewhat limited.
|
||||
|
||||
]]
|
||||
|
||||
local MAJOR, MINOR = "AceComm-3.0", 9
|
||||
|
||||
local AceComm,oldminor = LibStub:NewLibrary(MAJOR, MINOR)
|
||||
|
||||
if not AceComm then return end
|
||||
|
||||
local CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0")
|
||||
local CTL = assert(ChatThrottleLib, "AceComm-3.0 requires ChatThrottleLib")
|
||||
|
||||
-- Lua APIs
|
||||
local type, next, pairs, tostring = type, next, pairs, tostring
|
||||
local strlen, strsub, strfind = string.len, string.sub, string.find
|
||||
local tinsert, tconcat, tgetn, tremove = table.insert, table.concat, table.getn, table.remove
|
||||
local error, assert = error, assert
|
||||
|
||||
|
||||
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
|
||||
-- List them here for Mikk's FindGlobals script
|
||||
-- GLOBALS: LibStub, DEFAULT_CHAT_FRAME, geterrorhandler, RegisterAddonMessagePrefix
|
||||
|
||||
AceComm.embeds = AceComm.embeds or {}
|
||||
|
||||
-- for my sanity and yours, let's give the message type bytes some names
|
||||
local MSG_MULTI_FIRST = "\001"
|
||||
local MSG_MULTI_NEXT = "\002"
|
||||
local MSG_MULTI_LAST = "\003"
|
||||
local MSG_ESCAPE = "\004"
|
||||
|
||||
-- remove old structures (pre WoW 4.0)
|
||||
AceComm.multipart_origprefixes = nil
|
||||
AceComm.multipart_reassemblers = nil
|
||||
|
||||
-- the multipart message spool: indexed by a combination of sender+distribution+
|
||||
AceComm.multipart_spool = AceComm.multipart_spool or {}
|
||||
|
||||
--- Register for Addon Traffic on a specified prefix
|
||||
-- @param prefix A printable character (\032-\255) classification of the message (typically AddonName or AddonNameEvent), max 16 characters
|
||||
-- @param method Callback to call on message reception: Function reference, or method name (string) to call on self. Defaults to "OnCommReceived"
|
||||
function AceComm:RegisterComm(prefix, method)
|
||||
if method == nil then
|
||||
method = "OnCommReceived"
|
||||
end
|
||||
|
||||
if strlen(prefix) > 16 then -- TODO: 15?
|
||||
error("AceComm:RegisterComm(prefix,method): prefix length is limited to 16 characters")
|
||||
end
|
||||
|
||||
return AceComm._RegisterComm(self, prefix, method) -- created by CallbackHandler
|
||||
end
|
||||
|
||||
local warnedPrefix=false
|
||||
|
||||
--- Send a message over the Addon Channel
|
||||
-- @param prefix A printable character (\032-\255) classification of the message (typically AddonName or AddonNameEvent)
|
||||
-- @param text Data to send, nils (\000) not allowed. Any length.
|
||||
-- @param distribution Addon channel, e.g. "RAID", "GUILD", etc; see SendAddonMessage API
|
||||
-- @param target Destination for some distributions; see SendAddonMessage API
|
||||
-- @param prio OPTIONAL: ChatThrottleLib priority, "BULK", "NORMAL" or "ALERT". Defaults to "NORMAL".
|
||||
-- @param callbackFn OPTIONAL: callback function to be called as each chunk is sent. receives 3 args: the user supplied arg (see next), the number of bytes sent so far, and the number of bytes total to send.
|
||||
-- @param callbackArg: OPTIONAL: first arg to the callback function. nil will be passed if not specified.
|
||||
function AceComm:SendCommMessage(prefix, text, distribution, target, prio, callbackFn, callbackArg)
|
||||
prio = prio or "NORMAL" -- pasta's reference implementation had different prio for singlepart and multipart, but that's a very bad idea since that can easily lead to out-of-sequence delivery!
|
||||
if not( type(prefix)=="string" and
|
||||
type(text)=="string" and
|
||||
type(distribution)=="string" and
|
||||
(target==nil or type(target)=="string") and
|
||||
(prio=="BULK" or prio=="NORMAL" or prio=="ALERT")
|
||||
) then
|
||||
error('Usage: SendCommMessage(addon, "prefix", "text", "distribution"[, "target"[, "prio"[, callbackFn, callbackarg]]])', 2)
|
||||
end
|
||||
|
||||
local textlen = strlen(text)
|
||||
-- Yes, the max is 255 even if the dev post said 256. I tested. Char 256+ get silently truncated. /Mikk, 20110327
|
||||
-- Ace3v: substract the prefix length
|
||||
local maxtextlen = 254 - strlen(prefix)
|
||||
local queueName = prefix..distribution..(target or "")
|
||||
|
||||
local ctlCallback = nil
|
||||
if callbackFn then
|
||||
ctlCallback = function(sent)
|
||||
return callbackFn(callbackArg, sent, textlen)
|
||||
end
|
||||
end
|
||||
|
||||
local forceMultipart
|
||||
if strfind(text, "^[\001-\009]") then -- 4.1+: see if the first character is a control character
|
||||
-- we need to escape the first character with a \004
|
||||
if textlen+1 > maxtextlen then -- would we go over the size limit?
|
||||
forceMultipart = true -- just make it multipart, no escape problems then
|
||||
else
|
||||
text = "\004" .. text
|
||||
end
|
||||
end
|
||||
|
||||
if not forceMultipart and textlen <= maxtextlen then
|
||||
-- fits all in one message
|
||||
CTL:SendAddonMessage(prio, prefix, text, distribution, target, queueName, ctlCallback, textlen)
|
||||
else
|
||||
maxtextlen = maxtextlen - 1 -- 1 extra byte for part indicator in prefix(4.0)/start of message(4.1)
|
||||
|
||||
-- first part
|
||||
local chunk = strsub(text, 1, maxtextlen)
|
||||
CTL:SendAddonMessage(prio, prefix, MSG_MULTI_FIRST..chunk, distribution, target, queueName, ctlCallback, maxtextlen)
|
||||
|
||||
-- continuation
|
||||
local pos = 1+maxtextlen
|
||||
|
||||
while pos+maxtextlen <= textlen do
|
||||
chunk = strsub(text, pos, pos+maxtextlen-1)
|
||||
CTL:SendAddonMessage(prio, prefix, MSG_MULTI_NEXT..chunk, distribution, target, queueName, ctlCallback, pos+maxtextlen-1)
|
||||
pos = pos + maxtextlen
|
||||
end
|
||||
|
||||
-- final part
|
||||
chunk = strsub(text, pos)
|
||||
CTL:SendAddonMessage(prio, prefix, MSG_MULTI_LAST..chunk, distribution, target, queueName, ctlCallback, textlen)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
----------------------------------------
|
||||
-- Message receiving
|
||||
----------------------------------------
|
||||
|
||||
do
|
||||
local compost = setmetatable({}, {__mode = "k"})
|
||||
local function new()
|
||||
local t = next(compost)
|
||||
if t then
|
||||
compost[t]=nil
|
||||
for i=tgetn(t),3,-1 do -- faster than pairs loop. don't even nil out 1/2 since they'll be overwritten
|
||||
tremove(t) -- Ace3v: t[i] = nil wont affect the tgetn return value
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
return {}
|
||||
end
|
||||
|
||||
local function lostdatawarning(prefix,sender,where)
|
||||
DEFAULT_CHAT_FRAME:AddMessage(MAJOR..": Warning: lost network data regarding '"..tostring(prefix).."' from '"..tostring(sender).."' (in "..where..")")
|
||||
end
|
||||
|
||||
function AceComm:OnReceiveMultipartFirst(prefix, message, distribution, sender)
|
||||
local key = prefix.."\t"..distribution.."\t"..sender -- a unique stream is defined by the prefix + distribution + sender
|
||||
local spool = AceComm.multipart_spool
|
||||
|
||||
--[[
|
||||
if spool[key] then
|
||||
lostdatawarning(prefix,sender,"First")
|
||||
-- continue and overwrite
|
||||
end
|
||||
--]]
|
||||
|
||||
spool[key] = message -- plain string for now
|
||||
end
|
||||
|
||||
function AceComm:OnReceiveMultipartNext(prefix, message, distribution, sender)
|
||||
local key = prefix.."\t"..distribution.."\t"..sender -- a unique stream is defined by the prefix + distribution + sender
|
||||
local spool = AceComm.multipart_spool
|
||||
local olddata = spool[key]
|
||||
|
||||
if not olddata then
|
||||
--lostdatawarning(prefix,sender,"Next")
|
||||
return
|
||||
end
|
||||
|
||||
if type(olddata)~="table" then
|
||||
-- ... but what we have is not a table. So make it one. (Pull a composted one if available)
|
||||
local t = new()
|
||||
t[1] = olddata -- add old data as first string
|
||||
t[2] = message -- and new message as second string
|
||||
spool[key] = t -- and put the table in the spool instead of the old string
|
||||
else
|
||||
tinsert(olddata, message)
|
||||
end
|
||||
end
|
||||
|
||||
function AceComm:OnReceiveMultipartLast(prefix, message, distribution, sender)
|
||||
local key = prefix.."\t"..distribution.."\t"..sender -- a unique stream is defined by the prefix + distribution + sender
|
||||
local spool = AceComm.multipart_spool
|
||||
local olddata = spool[key]
|
||||
|
||||
if not olddata then
|
||||
--lostdatawarning(prefix,sender,"End")
|
||||
return
|
||||
end
|
||||
|
||||
spool[key] = nil
|
||||
|
||||
if type(olddata) == "table" then
|
||||
-- if we've received a "next", the spooled data will be a table for rapid & garbage-free tconcat
|
||||
tinsert(olddata, message)
|
||||
AceComm.callbacks:Fire(prefix, 3, tconcat(olddata, ""), distribution, sender)
|
||||
compost[olddata] = true
|
||||
else
|
||||
-- if we've only received a "first", the spooled data will still only be a string
|
||||
AceComm.callbacks:Fire(prefix, 3, olddata..message, distribution, sender)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
----------------------------------------
|
||||
-- Embed CallbackHandler
|
||||
----------------------------------------
|
||||
|
||||
if not AceComm.callbacks then
|
||||
AceComm.callbacks = CallbackHandler:New(AceComm,
|
||||
"_RegisterComm",
|
||||
"UnregisterComm",
|
||||
"UnregisterAllComm")
|
||||
end
|
||||
|
||||
AceComm.callbacks.OnUsed = nil
|
||||
AceComm.callbacks.OnUnused = nil
|
||||
|
||||
-- Ace3v: in vanilla, global vars:
|
||||
-- event -> event type
|
||||
-- arg1 -> prefix
|
||||
-- arg2 -> message
|
||||
-- arg3 -> channel
|
||||
-- arg4 -> sender
|
||||
local function OnEvent()
|
||||
local prefix, message, distribution, sender = arg1, arg2, arg3, arg4
|
||||
if event == "CHAT_MSG_ADDON" then
|
||||
local _, _, control, rest = strfind(message, "^([\001-\009])(.*)")
|
||||
if control then
|
||||
if control==MSG_MULTI_FIRST then
|
||||
AceComm:OnReceiveMultipartFirst(prefix, rest, distribution, sender)
|
||||
elseif control==MSG_MULTI_NEXT then
|
||||
AceComm:OnReceiveMultipartNext(prefix, rest, distribution, sender)
|
||||
elseif control==MSG_MULTI_LAST then
|
||||
AceComm:OnReceiveMultipartLast(prefix, rest, distribution, sender)
|
||||
elseif control==MSG_ESCAPE then
|
||||
AceComm.callbacks:Fire(prefix, 3, rest, distribution, sender)
|
||||
else
|
||||
-- unknown control character, ignore SILENTLY (dont warn unnecessarily about future extensions!)
|
||||
end
|
||||
else
|
||||
-- single part: fire it off immediately and let CallbackHandler decide if it's registered or not
|
||||
AceComm.callbacks:Fire(prefix, 3, message, distribution, sender)
|
||||
end
|
||||
else
|
||||
assert(false, "Received "..tostring(event).." event?!")
|
||||
end
|
||||
end
|
||||
|
||||
AceComm.frame = AceComm.frame or CreateFrame("Frame", "AceComm30Frame")
|
||||
AceComm.frame:SetScript("OnEvent", OnEvent)
|
||||
AceComm.frame:UnregisterAllEvents()
|
||||
AceComm.frame:RegisterEvent("CHAT_MSG_ADDON")
|
||||
|
||||
|
||||
----------------------------------------
|
||||
-- Base library stuff
|
||||
----------------------------------------
|
||||
|
||||
local mixins = {
|
||||
"RegisterComm",
|
||||
"UnregisterComm",
|
||||
"UnregisterAllComm",
|
||||
"SendCommMessage",
|
||||
}
|
||||
|
||||
-- Embeds AceComm-3.0 into the target object making the functions from the mixins list available on target:..
|
||||
-- @param target target object to embed AceComm-3.0 in
|
||||
function AceComm:Embed(target)
|
||||
for k, v in pairs(mixins) do
|
||||
target[v] = self[v]
|
||||
end
|
||||
self.embeds[target] = true
|
||||
return target
|
||||
end
|
||||
|
||||
function AceComm:OnEmbedDisable(target)
|
||||
target:UnregisterAllComm()
|
||||
end
|
||||
|
||||
-- Update embeds
|
||||
for target, v in pairs(AceComm.embeds) do
|
||||
AceComm:Embed(target)
|
||||
end
|
||||
@@ -0,0 +1,4 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="ChatThrottleLib.lua"/>
|
||||
<Script file="AceComm-3.0.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,527 @@
|
||||
--
|
||||
-- ChatThrottleLib by Mikk
|
||||
--
|
||||
-- Manages AddOn chat output to keep player from getting kicked off.
|
||||
--
|
||||
-- ChatThrottleLib:SendChatMessage/:SendAddonMessage functions that accept
|
||||
-- a Priority ("BULK", "NORMAL", "ALERT") as well as prefix for SendChatMessage.
|
||||
--
|
||||
-- Priorities get an equal share of available bandwidth when fully loaded.
|
||||
-- Communication channels are separated on extension+chattype+destination and
|
||||
-- get round-robinned. (Destination only matters for whispers and channels,
|
||||
-- obviously)
|
||||
--
|
||||
-- Will install hooks for SendChatMessage and SendAddonMessage to measure
|
||||
-- bandwidth bypassing the library and use less bandwidth itself.
|
||||
--
|
||||
--
|
||||
-- Fully embeddable library. Just copy this file into your addon directory,
|
||||
-- add it to the .toc, and it's done.
|
||||
--
|
||||
-- Can run as a standalone addon also, but, really, just embed it! :-)
|
||||
--
|
||||
-- LICENSE: ChatThrottleLib is released into the Public Domain
|
||||
--
|
||||
|
||||
local CTL_VERSION = 23
|
||||
|
||||
local AceCore = LibStub("AceCore-3.0")
|
||||
local _G = AceCore._G
|
||||
local hooksecurefunc = AceCore.hooksecurefunc
|
||||
local wipe = AceCore.wipe
|
||||
|
||||
if _G.ChatThrottleLib then
|
||||
if _G.ChatThrottleLib.version >= CTL_VERSION then
|
||||
-- There's already a newer (or same) version loaded. Buh-bye.
|
||||
return
|
||||
elseif not _G.ChatThrottleLib.securelyHooked then
|
||||
print("ChatThrottleLib: Warning: There's an ANCIENT ChatThrottleLib.lua (pre-wow 2.0, <v16) in an addon somewhere. Get the addon updated or copy in a newer ChatThrottleLib.lua (>=v16) in it!")
|
||||
-- ATTEMPT to unhook; this'll behave badly if someone else has hooked...
|
||||
-- ... and if someone has securehooked, they can kiss that goodbye too... >.<
|
||||
_G.SendChatMessage = _G.ChatThrottleLib.ORIG_SendChatMessage
|
||||
if _G.ChatThrottleLib.ORIG_SendAddonMessage then
|
||||
_G.SendAddonMessage = _G.ChatThrottleLib.ORIG_SendAddonMessage
|
||||
end
|
||||
end
|
||||
_G.ChatThrottleLib.ORIG_SendChatMessage = nil
|
||||
_G.ChatThrottleLib.ORIG_SendAddonMessage = nil
|
||||
end
|
||||
|
||||
if not _G.ChatThrottleLib then
|
||||
_G.ChatThrottleLib = {}
|
||||
end
|
||||
|
||||
ChatThrottleLib = _G.ChatThrottleLib -- in case some addon does "local ChatThrottleLib" above us and we're copypasted (AceComm-2, sigh)
|
||||
local ChatThrottleLib = _G.ChatThrottleLib
|
||||
|
||||
ChatThrottleLib.version = CTL_VERSION
|
||||
|
||||
|
||||
|
||||
------------------ TWEAKABLES -----------------
|
||||
|
||||
ChatThrottleLib.MAX_CPS = 800 -- 2000 seems to be safe if NOTHING ELSE is happening. let's call it 800.
|
||||
ChatThrottleLib.MSG_OVERHEAD = 40 -- Guesstimate overhead for sending a message; source+dest+chattype+protocolstuff
|
||||
|
||||
ChatThrottleLib.BURST = 4000 -- WoW's server buffer seems to be about 32KB. 8KB should be safe, but seen disconnects on _some_ servers. Using 4KB now.
|
||||
|
||||
ChatThrottleLib.MIN_FPS = 20 -- Reduce output CPS to half (and don't burst) if FPS drops below this value
|
||||
|
||||
|
||||
local setmetatable = setmetatable
|
||||
local table_remove = table.remove
|
||||
local tinsert = table.insert
|
||||
local tostring = tostring
|
||||
local GetTime = GetTime
|
||||
local math_min = math.min
|
||||
local math_max = math.max
|
||||
local next = next
|
||||
local strlen = string.len
|
||||
local GetFramerate = GetFramerate
|
||||
local strlower = string.lower
|
||||
local unpack,type,pairs,wipe = unpack,type,pairs,wipe
|
||||
local UnitInRaid,UnitInParty = UnitInRaid,UnitInParty
|
||||
|
||||
|
||||
-----------------------------------------------------------------------
|
||||
-- Double-linked ring implementation
|
||||
|
||||
local Ring = {}
|
||||
local RingMeta = { __index = Ring }
|
||||
|
||||
function Ring:New()
|
||||
local ret = {}
|
||||
setmetatable(ret, RingMeta)
|
||||
return ret
|
||||
end
|
||||
|
||||
function Ring:Add(obj) -- Append at the "far end" of the ring (aka just before the current position)
|
||||
if self.pos then
|
||||
obj.prev = self.pos.prev
|
||||
obj.prev.next = obj
|
||||
obj.next = self.pos
|
||||
obj.next.prev = obj
|
||||
else
|
||||
obj.next = obj
|
||||
obj.prev = obj
|
||||
self.pos = obj
|
||||
end
|
||||
end
|
||||
|
||||
function Ring:Remove(obj)
|
||||
obj.next.prev = obj.prev
|
||||
obj.prev.next = obj.next
|
||||
if self.pos == obj then
|
||||
self.pos = obj.next
|
||||
if self.pos == obj then
|
||||
self.pos = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
|
||||
-----------------------------------------------------------------------
|
||||
-- Recycling bin for pipes
|
||||
-- A pipe is a plain integer-indexed queue of messages
|
||||
-- Pipes normally live in Rings of pipes (3 rings total, one per priority)
|
||||
|
||||
ChatThrottleLib.PipeBin = nil -- pre-v19, drastically different
|
||||
local PipeBin = setmetatable({}, {__mode="k"})
|
||||
|
||||
local function DelPipe(pipe)
|
||||
PipeBin[pipe] = true
|
||||
end
|
||||
|
||||
local function NewPipe()
|
||||
local pipe = next(PipeBin)
|
||||
if pipe then
|
||||
wipe(pipe)
|
||||
PipeBin[pipe] = nil
|
||||
return pipe
|
||||
end
|
||||
return {}
|
||||
end
|
||||
|
||||
|
||||
|
||||
|
||||
-----------------------------------------------------------------------
|
||||
-- Recycling bin for messages
|
||||
|
||||
ChatThrottleLib.MsgBin = nil -- pre-v19, drastically different
|
||||
local MsgBin = setmetatable({}, {__mode="k"})
|
||||
|
||||
local function DelMsg(msg)
|
||||
msg[1] = nil
|
||||
-- there's more parameters, but they're very repetetive so the string pool doesn't suffer really, and it's faster to just not delete them.
|
||||
MsgBin[msg] = true
|
||||
end
|
||||
|
||||
local function NewMsg()
|
||||
local msg = next(MsgBin)
|
||||
if msg then
|
||||
MsgBin[msg] = nil
|
||||
return msg
|
||||
end
|
||||
return {}
|
||||
end
|
||||
|
||||
|
||||
-----------------------------------------------------------------------
|
||||
-- ChatThrottleLib:Init
|
||||
-- Initialize queues, set up frame for OnUpdate, etc
|
||||
|
||||
|
||||
function ChatThrottleLib:Init()
|
||||
|
||||
-- Set up queues
|
||||
if not self.Prio then
|
||||
self.Prio = {}
|
||||
self.Prio["ALERT"] = { ByName = {}, Ring = Ring:New(), avail = 0 }
|
||||
self.Prio["NORMAL"] = { ByName = {}, Ring = Ring:New(), avail = 0 }
|
||||
self.Prio["BULK"] = { ByName = {}, Ring = Ring:New(), avail = 0 }
|
||||
end
|
||||
|
||||
-- v4: total send counters per priority
|
||||
for _, Prio in pairs(self.Prio) do
|
||||
Prio.nTotalSent = Prio.nTotalSent or 0
|
||||
end
|
||||
|
||||
if not self.avail then
|
||||
self.avail = 0 -- v5
|
||||
end
|
||||
if not self.nTotalSent then
|
||||
self.nTotalSent = 0 -- v5
|
||||
end
|
||||
|
||||
|
||||
-- Set up a frame to get OnUpdate events
|
||||
if not self.Frame then
|
||||
self.Frame = CreateFrame("Frame")
|
||||
self.Frame:Hide()
|
||||
end
|
||||
self.Frame:SetScript("OnUpdate", self.OnUpdate)
|
||||
self.Frame:SetScript("OnEvent", self.OnEvent) -- v11: Monitor P_E_W so we can throttle hard for a few seconds
|
||||
self.Frame:RegisterEvent("PLAYER_ENTERING_WORLD")
|
||||
self.OnUpdateDelay = 0
|
||||
self.LastAvailUpdate = GetTime()
|
||||
self.HardThrottlingBeginTime = GetTime() -- v11: Throttle hard for a few seconds after startup
|
||||
|
||||
-- Hook SendChatMessage and SendAddonMessage so we can measure unpiped traffic and avoid overloads (v7)
|
||||
if not self.securelyHooked then
|
||||
-- Use secure hooks as of v16. Old regular hook support yanked out in v21.
|
||||
self.securelyHooked = true
|
||||
--SendChatMessage
|
||||
hooksecurefunc("SendChatMessage", function(text, chattype, language, destination)
|
||||
return ChatThrottleLib.Hook_SendChatMessage(text, chattype, language, destination)
|
||||
end)
|
||||
--SendAddonMessage
|
||||
hooksecurefunc("SendAddonMessage", function(prefix, text, chattype, destination)
|
||||
return ChatThrottleLib.Hook_SendAddonMessage(prefix, text, chattype, destination)
|
||||
end)
|
||||
end
|
||||
self.nBypass = 0
|
||||
end
|
||||
|
||||
|
||||
-----------------------------------------------------------------------
|
||||
-- ChatThrottleLib.Hook_SendChatMessage / .Hook_SendAddonMessage
|
||||
|
||||
local bMyTraffic = false
|
||||
|
||||
function ChatThrottleLib.Hook_SendChatMessage(text, chattype, language, destination)
|
||||
if bMyTraffic then
|
||||
return
|
||||
end
|
||||
local self = ChatThrottleLib
|
||||
local size = strlen(tostring(text or "")) + strlen(tostring(destination or "")) + self.MSG_OVERHEAD
|
||||
self.avail = self.avail - size
|
||||
self.nBypass = self.nBypass + size -- just a statistic
|
||||
end
|
||||
function ChatThrottleLib.Hook_SendAddonMessage(prefix, text, chattype, destination)
|
||||
if bMyTraffic then
|
||||
return
|
||||
end
|
||||
local self = ChatThrottleLib
|
||||
local size = strlen(tostring(text or "")) + strlen(tostring(prefix or ""));
|
||||
size = size + strlen(tostring(destination or "")) + self.MSG_OVERHEAD
|
||||
self.avail = self.avail - size
|
||||
self.nBypass = self.nBypass + size -- just a statistic
|
||||
end
|
||||
|
||||
|
||||
|
||||
-----------------------------------------------------------------------
|
||||
-- ChatThrottleLib:UpdateAvail
|
||||
-- Update self.avail with how much bandwidth is currently available
|
||||
|
||||
function ChatThrottleLib:UpdateAvail()
|
||||
local now = GetTime()
|
||||
local MAX_CPS = self.MAX_CPS;
|
||||
local newavail = MAX_CPS * (now - self.LastAvailUpdate)
|
||||
local avail = self.avail
|
||||
|
||||
if now - self.HardThrottlingBeginTime < 5 then
|
||||
-- First 5 seconds after startup/zoning: VERY hard clamping to avoid irritating the server rate limiter, it seems very cranky then
|
||||
avail = math_min(avail + (newavail*0.1), MAX_CPS*0.5)
|
||||
self.bChoking = true
|
||||
elseif GetFramerate() < self.MIN_FPS then -- GetFrameRate call takes ~0.002 secs
|
||||
avail = math_min(MAX_CPS, avail + newavail*0.5)
|
||||
self.bChoking = true -- just a statistic
|
||||
else
|
||||
avail = math_min(self.BURST, avail + newavail)
|
||||
self.bChoking = false
|
||||
end
|
||||
|
||||
avail = math_max(avail, 0-(MAX_CPS*2)) -- Can go negative when someone is eating bandwidth past the lib. but we refuse to stay silent for more than 2 seconds; if they can do it, we can.
|
||||
|
||||
self.avail = avail
|
||||
self.LastAvailUpdate = now
|
||||
|
||||
return avail
|
||||
end
|
||||
|
||||
|
||||
-----------------------------------------------------------------------
|
||||
-- Despooling logic
|
||||
-- Reminder:
|
||||
-- - We have 3 Priorities, each containing a "Ring" construct ...
|
||||
-- - ... made up of N "Pipe"s (1 for each destination/pipename)
|
||||
-- - and each pipe contains messages
|
||||
|
||||
function ChatThrottleLib:Despool(Prio)
|
||||
local ring = Prio.Ring
|
||||
while ring.pos and Prio.avail > ring.pos[1].nSize do
|
||||
local msg = table_remove(ring.pos, 1)
|
||||
if not ring.pos[1] then -- did we remove last msg in this pipe?
|
||||
local pipe = Prio.Ring.pos
|
||||
Prio.Ring:Remove(pipe)
|
||||
Prio.ByName[pipe.name] = nil
|
||||
DelPipe(pipe)
|
||||
else
|
||||
Prio.Ring.pos = Prio.Ring.pos.next
|
||||
end
|
||||
local didSend=false
|
||||
local lowerDest = strlower(msg[3] or "")
|
||||
if lowerDest == "raid" and not UnitInRaid("player") then
|
||||
-- do nothing
|
||||
elseif lowerDest == "party" and not UnitInParty("player") then
|
||||
-- do nothing
|
||||
else
|
||||
Prio.avail = Prio.avail - msg.nSize
|
||||
bMyTraffic = true
|
||||
msg.f(unpack(msg, 1, msg.n))
|
||||
bMyTraffic = false
|
||||
Prio.nTotalSent = Prio.nTotalSent + msg.nSize
|
||||
DelMsg(msg)
|
||||
didSend = true
|
||||
end
|
||||
-- notify caller of delivery (even if we didn't send it)
|
||||
if msg.callbackFn then
|
||||
msg.callbackFn (msg.callbackArg, didSend)
|
||||
end
|
||||
-- USER CALLBACK MAY ERROR
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
function ChatThrottleLib.OnEvent()
|
||||
-- v11: We know that the rate limiter is touchy after login. Assume that it's touchy after zoning, too.
|
||||
local self = ChatThrottleLib
|
||||
if event == "PLAYER_ENTERING_WORLD" then
|
||||
self.HardThrottlingBeginTime = GetTime() -- Throttle hard for a few seconds after zoning
|
||||
self.avail = 0
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
function ChatThrottleLib.OnUpdate()
|
||||
local self = ChatThrottleLib
|
||||
|
||||
self.OnUpdateDelay = self.OnUpdateDelay + arg1
|
||||
if self.OnUpdateDelay < 0.08 then
|
||||
return
|
||||
end
|
||||
self.OnUpdateDelay = 0
|
||||
|
||||
self:UpdateAvail()
|
||||
|
||||
if self.avail < 0 then
|
||||
return -- argh. some bastard is spewing stuff past the lib. just bail early to save cpu.
|
||||
end
|
||||
|
||||
-- See how many of our priorities have queued messages (we only have 3, don't worry about the loop)
|
||||
local n = 0
|
||||
for prioname,Prio in pairs(self.Prio) do
|
||||
if Prio.Ring.pos or Prio.avail < 0 then
|
||||
n = n + 1
|
||||
end
|
||||
end
|
||||
|
||||
-- Anything queued still?
|
||||
if n<1 then
|
||||
-- Nope. Move spillover bandwidth to global availability gauge and clear self.bQueueing
|
||||
for prioname, Prio in pairs(self.Prio) do
|
||||
self.avail = self.avail + Prio.avail
|
||||
Prio.avail = 0
|
||||
end
|
||||
self.bQueueing = false
|
||||
self.Frame:Hide()
|
||||
return
|
||||
end
|
||||
|
||||
-- There's stuff queued. Hand out available bandwidth to priorities as needed and despool their queues
|
||||
local avail = self.avail/n
|
||||
self.avail = 0
|
||||
|
||||
for prioname, Prio in pairs(self.Prio) do
|
||||
if Prio.Ring.pos or Prio.avail < 0 then
|
||||
Prio.avail = Prio.avail + avail
|
||||
if Prio.Ring.pos and Prio.avail > Prio.Ring.pos[1].nSize then
|
||||
self:Despool(Prio)
|
||||
-- Note: We might not get here if the user-supplied callback function errors out! Take care!
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
|
||||
|
||||
|
||||
-----------------------------------------------------------------------
|
||||
-- Spooling logic
|
||||
|
||||
function ChatThrottleLib:Enqueue(prioname, pipename, msg)
|
||||
local Prio = self.Prio[prioname]
|
||||
local pipe = Prio.ByName[pipename]
|
||||
if not pipe then
|
||||
self.Frame:Show()
|
||||
pipe = NewPipe()
|
||||
pipe.name = pipename
|
||||
Prio.ByName[pipename] = pipe
|
||||
Prio.Ring:Add(pipe)
|
||||
end
|
||||
|
||||
tinsert(pipe,msg)
|
||||
|
||||
self.bQueueing = true
|
||||
end
|
||||
|
||||
function ChatThrottleLib:SendChatMessage(prio, prefix, text, chattype, language, destination, queueName, callbackFn, callbackArg)
|
||||
if not self or not prio or not prefix or not text or not self.Prio[prio] then
|
||||
error('Usage: ChatThrottleLib:SendChatMessage("{BULK||NORMAL||ALERT}", "prefix", "text"[, "chattype"[, "language"[, "destination"]]]', 2)
|
||||
end
|
||||
if callbackFn and type(callbackFn)~="function" then
|
||||
error('ChatThrottleLib:ChatMessage(): callbackFn: expected function, got '..type(callbackFn), 2)
|
||||
end
|
||||
|
||||
local nSize = strlen(text)
|
||||
|
||||
if nSize>255 then
|
||||
error("ChatThrottleLib:SendChatMessage(): message length cannot exceed 255 bytes", 2)
|
||||
end
|
||||
|
||||
nSize = nSize + self.MSG_OVERHEAD
|
||||
|
||||
-- Check if there's room in the global available bandwidth gauge to send directly
|
||||
if not self.bQueueing and nSize < self:UpdateAvail() then
|
||||
self.avail = self.avail - nSize
|
||||
bMyTraffic = true
|
||||
_G.SendChatMessage(text, chattype, language, destination)
|
||||
bMyTraffic = false
|
||||
self.Prio[prio].nTotalSent = self.Prio[prio].nTotalSent + nSize
|
||||
if callbackFn then
|
||||
callbackFn (callbackArg, true)
|
||||
end
|
||||
-- USER CALLBACK MAY ERROR
|
||||
return
|
||||
end
|
||||
|
||||
-- Message needs to be queued
|
||||
local msg = NewMsg()
|
||||
msg.f = _G.SendChatMessage
|
||||
msg[1] = text
|
||||
msg[2] = chattype or "SAY"
|
||||
msg[3] = language
|
||||
msg[4] = destination
|
||||
msg.n = 4
|
||||
msg.nSize = nSize
|
||||
msg.callbackFn = callbackFn
|
||||
msg.callbackArg = callbackArg
|
||||
|
||||
self:Enqueue(prio, queueName or (prefix..(chattype or "SAY")..(destination or "")), msg)
|
||||
end
|
||||
|
||||
|
||||
function ChatThrottleLib:SendAddonMessage(prio, prefix, text, chattype, target, queueName, callbackFn, callbackArg)
|
||||
if not self or not prio or not prefix or not text or not chattype or not self.Prio[prio] then
|
||||
error('Usage: ChatThrottleLib:SendAddonMessage("{BULK||NORMAL||ALERT}", "prefix", "text", "chattype"[, "target"])', 2)
|
||||
end
|
||||
if callbackFn and type(callbackFn)~="function" then
|
||||
error('ChatThrottleLib:SendAddonMessage(): callbackFn: expected function, got '..type(callbackFn), 2)
|
||||
end
|
||||
|
||||
local nSize = strlen(text);
|
||||
|
||||
if RegisterAddonMessagePrefix then
|
||||
if nSize>255 then
|
||||
error("ChatThrottleLib:SendAddonMessage(): message length cannot exceed 255 bytes", 2)
|
||||
end
|
||||
else
|
||||
nSize = nSize + strlen(prefix) + 1
|
||||
if nSize>255 then
|
||||
error("ChatThrottleLib:SendAddonMessage(): prefix + message length cannot exceed 254 bytes", 2)
|
||||
end
|
||||
end
|
||||
|
||||
nSize = nSize + self.MSG_OVERHEAD;
|
||||
|
||||
-- Check if there's room in the global available bandwidth gauge to send directly
|
||||
if not self.bQueueing and nSize < self:UpdateAvail() then
|
||||
self.avail = self.avail - nSize
|
||||
bMyTraffic = true
|
||||
_G.SendAddonMessage(prefix, text, chattype, target)
|
||||
bMyTraffic = false
|
||||
self.Prio[prio].nTotalSent = self.Prio[prio].nTotalSent + nSize
|
||||
if callbackFn then
|
||||
callbackFn (callbackArg, true)
|
||||
end
|
||||
-- USER CALLBACK MAY ERROR
|
||||
return
|
||||
end
|
||||
|
||||
-- Message needs to be queued
|
||||
local msg = NewMsg()
|
||||
msg.f = _G.SendAddonMessage
|
||||
msg[1] = prefix
|
||||
msg[2] = text
|
||||
msg[3] = chattype
|
||||
msg[4] = target
|
||||
msg.n = (target~=nil) and 4 or 3;
|
||||
msg.nSize = nSize
|
||||
msg.callbackFn = callbackFn
|
||||
msg.callbackArg = callbackArg
|
||||
|
||||
self:Enqueue(prio, queueName or (prefix..chattype..(target or "")), msg)
|
||||
end
|
||||
|
||||
|
||||
|
||||
|
||||
-----------------------------------------------------------------------
|
||||
-- Get the ball rolling!
|
||||
|
||||
ChatThrottleLib:Init()
|
||||
|
||||
--[[ WoWBench debugging snippet
|
||||
if(WOWB_VER) then
|
||||
local function SayTimer()
|
||||
print("SAY: "..GetTime().." "..arg1)
|
||||
end
|
||||
ChatThrottleLib.Frame:SetScript("OnEvent", SayTimer)
|
||||
ChatThrottleLib.Frame:RegisterEvent("CHAT_MSG_SAY")
|
||||
end
|
||||
]]
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
--- **AceConsole-3.0** provides registration facilities for slash commands.
|
||||
-- You can register slash commands to your custom functions and use the `GetArgs` function to parse them
|
||||
-- to your addons individual needs.
|
||||
--
|
||||
-- **AceConsole-3.0** can be embeded into your addon, either explicitly by calling AceConsole:Embed(MyAddon) or by
|
||||
-- specifying it as an embeded library in your AceAddon. All functions will be available on your addon object
|
||||
-- and can be accessed directly, without having to explicitly call AceConsole itself.\\
|
||||
-- It is recommended to embed AceConsole, otherwise you'll have to specify a custom `self` on all calls you
|
||||
-- make into AceConsole.
|
||||
-- @class file
|
||||
-- @name AceConsole-3.0
|
||||
-- @release $Id: AceConsole-3.0.lua 1143 2016-07-11 08:52:03Z nevcairiel $
|
||||
local MAJOR,MINOR = "AceConsole-3.0", 7
|
||||
|
||||
local AceConsole, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
|
||||
|
||||
if not AceConsole then return end -- No upgrade needed
|
||||
|
||||
local AceCore = LibStub("AceCore-3.0")
|
||||
|
||||
AceConsole.embeds = AceConsole.embeds or {} -- table containing objects AceConsole is embedded in.
|
||||
AceConsole.commands = AceConsole.commands or {} -- table containing commands registered
|
||||
AceConsole.weakcommands = AceConsole.weakcommands or {} -- table containing self, command => func references for weak commands that don't persist through enable/disable
|
||||
|
||||
-- Lua APIs
|
||||
local tinsert, tconcat, tgetn, tsetn = table.insert, table.concat, table.getn, table.setn
|
||||
local tostring = tostring
|
||||
local type, pairs, error = type, pairs, error
|
||||
local format, strfind, strsub = string.format, string.find, string.sub
|
||||
local max = math.max
|
||||
local strupper, strlower = string.upper, string.lower
|
||||
|
||||
-- WoW APIs
|
||||
local _G = AceCore._G
|
||||
|
||||
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
|
||||
-- List them here for Mikk's FindGlobals script
|
||||
-- GLOBALS: DEFAULT_CHAT_FRAME, SlashCmdList, hash_SlashCmdList
|
||||
local Print
|
||||
do
|
||||
local tmp = {}
|
||||
function Print(self, frame, arg)
|
||||
if self ~= AceConsole then
|
||||
tmp[1] = "|cff33ff99"..tostring(self).."|r:"
|
||||
else
|
||||
tmp[1] = ''
|
||||
end
|
||||
if type(arg) == "string" then
|
||||
frame:AddMessage(tmp[1]..arg)
|
||||
else -- arg is table and may contain frame as first element if argument frame is nil
|
||||
local b, e = frame and 1 or 2, tgetn(arg)
|
||||
if e >= b then
|
||||
frame = frame or arg[1]
|
||||
for i=0,e-b do
|
||||
tmp[2+i] = tostring(arg[b+i])
|
||||
end
|
||||
frame:AddMessage(tconcat(tmp," ",1,e-b+2)) -- explicitly, because the length is not affected by assignment
|
||||
end
|
||||
end
|
||||
end
|
||||
end -- Print
|
||||
|
||||
--- Print to DEFAULT_CHAT_FRAME or given ChatFrame (anything with an .AddMessage function)
|
||||
-- @paramsig [chatframe ,] ...
|
||||
-- @param chatframe Custom ChatFrame to print to (or any frame with an .AddMessage function)
|
||||
-- @param ... List of any values to be printed
|
||||
function AceConsole:Print(...)
|
||||
local frame = arg[1]
|
||||
if type(frame) == "table" and frame.AddMessage then -- Is first argument something with an .AddMessage member?
|
||||
return Print(self, nil, arg)
|
||||
else
|
||||
return Print(self, DEFAULT_CHAT_FRAME, arg)
|
||||
end
|
||||
end
|
||||
|
||||
--- Formatted (using format()) print to DEFAULT_CHAT_FRAME or given ChatFrame (anything with an .AddMessage function)
|
||||
-- @paramsig [chatframe ,] "format"[, ...]
|
||||
-- @param chatframe Custom ChatFrame to print to (or any frame with an .AddMessage function)
|
||||
-- @param format Format string - same syntax as standard Lua format()
|
||||
-- @param ... Arguments to the format string
|
||||
function AceConsole:Printf(a1, ...)
|
||||
local frame, succ, s
|
||||
if type(a1) == "table" and a1.AddMessage then -- Is first argument something with an .AddMessage member?
|
||||
frame, succ, s = a1, pcall(format, unpack(arg))
|
||||
else
|
||||
frame, succ, s = DEFAULT_CHAT_FRAME, pcall(format, a1, unpack(arg))
|
||||
end
|
||||
if not succ then error(s,2) end
|
||||
return Print(self, frame, s)
|
||||
end
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
--- Register a simple chat command
|
||||
-- @param command Chat command to be registered WITHOUT leading "/"
|
||||
-- @param func Function to call when the slash command is being used (funcref or methodname)
|
||||
-- @param persist if false, the command will be soft disabled/enabled when aceconsole is used as a mixin (default: true)
|
||||
function AceConsole:RegisterChatCommand( command, func, persist )
|
||||
if type(command)~="string" then error([[Usage: AceConsole:RegisterChatCommand(command, func[, persist ]): 'command' - expected a string]], 2) end
|
||||
|
||||
if persist==nil then persist=true end -- I'd rather have my addon's "/addon enable" around if the author screws up. Having some extra slash regged when it shouldnt be isn't as destructive. True is a better default. /Mikk
|
||||
|
||||
local name = "ACECONSOLE_"..strupper(command)
|
||||
|
||||
local t = type(func)
|
||||
|
||||
if t == "string" then
|
||||
-- Ace3v: prevent user from using AceConSole as self
|
||||
if self == AceConsole then
|
||||
error([[Usage: RegisterChatCommand(command, func[, persist]): 'self' - use your own 'self']], 2)
|
||||
end
|
||||
SlashCmdList[name] = function(input, editBox)
|
||||
self[func](self, input, editBox)
|
||||
end
|
||||
elseif t == "function" then
|
||||
SlashCmdList[name] = func
|
||||
else
|
||||
error([[Usage: AceConsole:RegisterChatCommand(command, func[, persist ]): 'func' - expected a string or a function]], 2)
|
||||
end
|
||||
_G["SLASH_"..name.."1"] = "/"..strlower(command)
|
||||
AceConsole.commands[command] = name
|
||||
-- non-persisting commands are registered for enabling disabling
|
||||
if not persist then
|
||||
if not AceConsole.weakcommands[self] then AceConsole.weakcommands[self] = {} end
|
||||
AceConsole.weakcommands[self][command] = func
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
--- Unregister a chatcommand
|
||||
-- @param command Chat command to be unregistered WITHOUT leading "/"
|
||||
function AceConsole:UnregisterChatCommand( command )
|
||||
local name = AceConsole.commands[command]
|
||||
if name then
|
||||
SlashCmdList[name] = nil
|
||||
_G["SLASH_" .. name .. "1"] = nil
|
||||
AceConsole.commands[command] = nil
|
||||
end
|
||||
end
|
||||
|
||||
--- Get an iterator over all Chat Commands registered with AceConsole
|
||||
-- @return Iterator (pairs) over all commands
|
||||
function AceConsole:IterateChatCommands() return pairs(AceConsole.commands) end
|
||||
|
||||
local function nils(n,argc,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10)
|
||||
if n >= 1 then
|
||||
return nil, nils(n-1,argc,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10)
|
||||
elseif not argc or argc == 0 then
|
||||
return
|
||||
else
|
||||
return a1, nils(0,argc-1,a2,a3,a4,a5,a6,a7,a8,a9,a10)
|
||||
end
|
||||
end
|
||||
|
||||
--- Retreive one or more space-separated arguments from a string.
|
||||
-- Treats quoted strings and itemlinks as non-spaced.
|
||||
-- @param str The raw argument string
|
||||
-- @param numargs How many arguments to get (default 1)
|
||||
-- @param startpos Where in the string to start scanning (default 1)
|
||||
-- @return Returns arg1, arg2, ..., nextposition\\
|
||||
-- Missing arguments will be returned as nils. 'nextposition' is returned as 1e9 at the end of the string.
|
||||
function AceConsole:GetArgs(str, numargs, startpos)
|
||||
numargs = numargs or 1
|
||||
startpos = max(startpos or 1, 1)
|
||||
|
||||
local pos=startpos
|
||||
|
||||
-- find start of new arg
|
||||
pos = strfind(str, "[^ ]", pos)
|
||||
if not pos then -- whoops, end of string
|
||||
return nils(numargs, 1, 1e9)
|
||||
end
|
||||
|
||||
if numargs<1 then
|
||||
return pos
|
||||
end
|
||||
|
||||
-- quoted or space separated? find out which pattern to use
|
||||
local delim_or_pipe
|
||||
local ch = strsub(str, pos, pos)
|
||||
if ch=='"' then
|
||||
pos = pos + 1
|
||||
delim_or_pipe='([|"])'
|
||||
elseif ch=="'" then
|
||||
pos = pos + 1
|
||||
delim_or_pipe="([|'])"
|
||||
else
|
||||
delim_or_pipe="([| ])"
|
||||
end
|
||||
|
||||
startpos = pos
|
||||
|
||||
while true do
|
||||
-- find delimiter or hyperlink
|
||||
local ch,_
|
||||
pos,_,ch = strfind(str, delim_or_pipe, pos)
|
||||
|
||||
if not pos then break end
|
||||
|
||||
if ch=="|" then
|
||||
-- some kind of escape
|
||||
|
||||
if strsub(str,pos,pos+1)=="|H" then
|
||||
-- It's a |H....|hhyper link!|h
|
||||
pos=strfind(str, "|h", pos+2) -- first |h
|
||||
if not pos then break end
|
||||
|
||||
pos=strfind(str, "|h", pos+2) -- second |h
|
||||
if not pos then break end
|
||||
elseif strsub(str,pos, pos+1) == "|T" then
|
||||
-- It's a |T....|t texture
|
||||
pos=strfind(str, "|t", pos+2)
|
||||
if not pos then break end
|
||||
end
|
||||
|
||||
pos=pos+2 -- skip past this escape (last |h if it was a hyperlink)
|
||||
|
||||
else
|
||||
-- found delimiter, done with this arg
|
||||
return strsub(str, startpos, pos-1), AceConsole:GetArgs(str, numargs-1, pos+1)
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
-- search aborted, we hit end of string. return it all as one argument. (yes, even if it's an unterminated quote or hyperlink)
|
||||
return strsub(str, startpos), nils(numargs-1, 1, 1e9)
|
||||
end
|
||||
|
||||
|
||||
--- embedding and embed handling
|
||||
|
||||
local mixins = {
|
||||
"Print",
|
||||
"Printf",
|
||||
"RegisterChatCommand",
|
||||
"UnregisterChatCommand",
|
||||
"GetArgs",
|
||||
}
|
||||
|
||||
-- Embeds AceConsole into the target object making the functions from the mixins list available on target:..
|
||||
-- @param target target object to embed AceBucket in
|
||||
function AceConsole:Embed( target )
|
||||
for k, v in pairs( mixins ) do
|
||||
target[v] = self[v]
|
||||
end
|
||||
self.embeds[target] = true
|
||||
return target
|
||||
end
|
||||
|
||||
function AceConsole:OnEmbedEnable( target )
|
||||
if AceConsole.weakcommands[target] then
|
||||
for command, func in pairs( AceConsole.weakcommands[target] ) do
|
||||
target:RegisterChatCommand( command, func, false, true ) -- nonpersisting and silent registry
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function AceConsole:OnEmbedDisable( target )
|
||||
if AceConsole.weakcommands[target] then
|
||||
for command, func in pairs( AceConsole.weakcommands[target] ) do
|
||||
target:UnregisterChatCommand( command ) -- TODO: this could potentially unregister a command from another application in case of command conflicts. Do we care?
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
for addon in pairs(AceConsole.embeds) do
|
||||
AceConsole:Embed(addon)
|
||||
end
|
||||
@@ -0,0 +1,3 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="AceConsole-3.0.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,204 @@
|
||||
local ACECORE_MAJOR, ACECORE_MINOR = "AceCore-3.0", 1
|
||||
local AceCore, oldminor = LibStub:NewLibrary(ACECORE_MAJOR, ACECORE_MINOR)
|
||||
|
||||
if not AceCore then return end -- No upgrade needed
|
||||
|
||||
AceCore._G = AceCore._G or _G
|
||||
local _G = AceCore._G
|
||||
local strsub, strgsub, strfind = string.sub, string.gsub, string.find
|
||||
local tremove, tconcat = table.remove, table.concat
|
||||
local tgetn, tsetn = table.getn, table.setn
|
||||
|
||||
local new, del
|
||||
do
|
||||
local list = setmetatable({}, {__mode = "k"})
|
||||
function new()
|
||||
local t = next(list)
|
||||
if not t then
|
||||
return {}
|
||||
end
|
||||
list[t] = nil
|
||||
return t
|
||||
end
|
||||
|
||||
function del(t)
|
||||
setmetatable(t, nil)
|
||||
for k in pairs(t) do
|
||||
t[k] = nil
|
||||
end
|
||||
tsetn(t,0)
|
||||
list[t] = true
|
||||
end
|
||||
|
||||
-- debug
|
||||
function AceCore.listcount()
|
||||
local count = 0
|
||||
for k in list do
|
||||
count = count + 1
|
||||
end
|
||||
return count
|
||||
end
|
||||
end -- AceCore.new, AceCore.del
|
||||
AceCore.new, AceCore.del = new, del
|
||||
|
||||
local function errorhandler(err)
|
||||
return geterrorhandler()(err)
|
||||
end
|
||||
AceCore.errorhandler = errorhandler
|
||||
|
||||
local function CreateSafeDispatcher(argCount)
|
||||
local code = [[
|
||||
local errorhandler = LibStub("AceCore-3.0").errorhandler
|
||||
local method, UP_ARGS
|
||||
local function call()
|
||||
local func, ARGS = method, UP_ARGS
|
||||
method, UP_ARGS = nil, NILS
|
||||
return func(ARGS)
|
||||
end
|
||||
return function(func, ARGS)
|
||||
method, UP_ARGS = func, ARGS
|
||||
return xpcall(call, errorhandler)
|
||||
end
|
||||
]]
|
||||
local c = 4*argCount-1
|
||||
local s = "b01,b02,b03,b04,b05,b06,b07,b08,b09,b10,b11,b12,b13,b14,b15,b16,b17,b18,b19,b20"
|
||||
code = strgsub(code, "UP_ARGS", string.sub(s,1,c))
|
||||
s = "a01,a02,a03,a04,a05,a06,a07,a08,a09,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20"
|
||||
code = strgsub(code, "ARGS", string.sub(s,1,c))
|
||||
s = "nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil"
|
||||
code = strgsub(code, "NILS", string.sub(s,1,c))
|
||||
return assert(loadstring(code, "safecall SafeDispatcher["..tostring(argCount).."]"))()
|
||||
end
|
||||
|
||||
local SafeDispatchers = setmetatable({}, {__index=function(self, argCount)
|
||||
local dispatcher
|
||||
if argCount > 0 then
|
||||
dispatcher = CreateSafeDispatcher(argCount)
|
||||
else
|
||||
dispatcher = function(func) return xpcall(func,errorhandler) end
|
||||
end
|
||||
rawset(self, argCount, dispatcher)
|
||||
return dispatcher
|
||||
end})
|
||||
|
||||
local function safecall(func,argc,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20)
|
||||
-- we check to see if the func is passed is actually a function here and don't error when it isn't
|
||||
-- this safecall is used for optional functions like OnInitialize OnEnable etc. When they are not
|
||||
-- present execution should continue without hinderance
|
||||
if type(func) == "function" then
|
||||
return SafeDispatchers[argc](func,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20)
|
||||
end
|
||||
end
|
||||
AceCore.safecall = safecall
|
||||
|
||||
local function CreateDispatcher(argCount)
|
||||
local code = [[
|
||||
return function(func,ARGS)
|
||||
return func(ARGS)
|
||||
end
|
||||
]]
|
||||
local s = "a01,a02,a03,a04,a05,a06,a07,a08,a09,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20"
|
||||
code = strgsub(code, "ARGS", string.sub(s,1,4*argCount-1))
|
||||
return assert(loadstring(code, "call Dispatcher["..tostring(argCount).."]"))()
|
||||
end
|
||||
|
||||
AceCore.Dispatchers = setmetatable({}, {__index=function(self, argCount)
|
||||
local dispatcher
|
||||
if argCount > 0 then
|
||||
dispatcher = CreateDispatcher(argCount)
|
||||
else
|
||||
dispatcher = function(func) return func() end
|
||||
end
|
||||
rawset(self, argCount, dispatcher)
|
||||
return dispatcher
|
||||
end})
|
||||
|
||||
-- some string functions
|
||||
-- vanilla available string operations:
|
||||
-- sub, gfind, rep, gsub, char, dump, find, upper, len, format, byte, lower
|
||||
-- we will just replace every string.match with string.find in the code
|
||||
function AceCore.strtrim(s)
|
||||
return strgsub(s, "^%s*(.-)%s*$", "%1")
|
||||
end
|
||||
|
||||
local function strsplit(delim, s, n)
|
||||
if n and n < 2 then return s end
|
||||
beg = beg or 1
|
||||
local i,j = string.find(s,delim,beg)
|
||||
if not i then
|
||||
return s, nil
|
||||
end
|
||||
return string.sub(s,1,j-1), strsplit(delim, string.sub(s,j+1), n and n-1 or nil)
|
||||
end
|
||||
AceCore.strsplit = strsplit
|
||||
|
||||
-- Ace3v: fonctions copied from AceHook-2.1
|
||||
local protFuncs = {
|
||||
CameraOrSelectOrMoveStart = true, CameraOrSelectOrMoveStop = true,
|
||||
TurnOrActionStart = true, TurnOrActionStop = true,
|
||||
PitchUpStart = true, PitchUpStop = true,
|
||||
PitchDownStart = true, PitchDownStop = true,
|
||||
MoveBackwardStart = true, MoveBackwardStop = true,
|
||||
MoveForwardStart = true, MoveForwardStop = true,
|
||||
Jump = true, StrafeLeftStart = true,
|
||||
StrafeLeftStop = true, StrafeRightStart = true,
|
||||
StrafeRightStop = true, ToggleMouseMove = true,
|
||||
ToggleRun = true, TurnLeftStart = true,
|
||||
TurnLeftStop = true, TurnRightStart = true,
|
||||
TurnRightStop = true,
|
||||
}
|
||||
|
||||
local function issecurevariable(x)
|
||||
return protFuncs[x] and 1 or nil
|
||||
end
|
||||
AceCore.issecurevariable = issecurevariable
|
||||
|
||||
local function hooksecurefunc(arg1, arg2, arg3)
|
||||
if type(arg1) == "string" then
|
||||
arg1, arg2, arg3 = _G, arg1, arg2
|
||||
end
|
||||
local orig = arg1[arg2]
|
||||
if type(orig) ~= "function" then
|
||||
error("The function "..arg2.." does not exist", 2)
|
||||
end
|
||||
arg1[arg2] = function(...)
|
||||
local tmp = {orig(unpack(arg))}
|
||||
arg3(unpack(arg))
|
||||
return unpack(tmp)
|
||||
end
|
||||
end
|
||||
AceCore.hooksecurefunc = hooksecurefunc
|
||||
|
||||
-- pickfirstset() - picks the first non-nil value and returns it
|
||||
local function pickfirstset(argc,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10)
|
||||
if (argc <= 1) or (a1 ~= nil) then
|
||||
return a1
|
||||
else
|
||||
return pickfirstset(argc-1,a2,a3,a4,a5,a6,a7,a8,a9,a10)
|
||||
end
|
||||
end
|
||||
AceCore.pickfirstset = pickfirstset
|
||||
|
||||
local function countargs(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10)
|
||||
if (a1 == nil) then return 0 end
|
||||
return 1 + countargs(a2,a3,a4,a5,a6,a7,a8,a9,a10)
|
||||
end
|
||||
AceCore.countargs = countargs
|
||||
|
||||
-- wipe preserves metatable
|
||||
function AceCore.wipe(t)
|
||||
for k,v in pairs(t) do t[k] = nil end
|
||||
tsetn(t,0)
|
||||
return t
|
||||
end
|
||||
|
||||
function AceCore.truncate(t,e)
|
||||
e = e or tgetn(t)
|
||||
for i=1,e do
|
||||
if t[i] == nil then
|
||||
tsetn(t,i-1)
|
||||
return
|
||||
end
|
||||
end
|
||||
tsetn(t,e)
|
||||
end
|
||||
@@ -0,0 +1,3 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="AceCore-3.0.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,755 @@
|
||||
--- **AceDB-3.0** manages the SavedVariables of your addon.
|
||||
-- It offers profile management, smart defaults and namespaces for modules.\\
|
||||
-- Data can be saved in different data-types, depending on its intended usage.
|
||||
-- The most common data-type is the `profile` type, which allows the user to choose
|
||||
-- the active profile, and manage the profiles of all of his characters.\\
|
||||
-- The following data types are available:
|
||||
-- * **char** Character-specific data. Every character has its own database.
|
||||
-- * **realm** Realm-specific data. All of the players characters on the same realm share this database.
|
||||
-- * **class** Class-specific data. All of the players characters of the same class share this database.
|
||||
-- * **race** Race-specific data. All of the players characters of the same race share this database.
|
||||
-- * **faction** Faction-specific data. All of the players characters of the same faction share this database.
|
||||
-- * **factionrealm** Faction and realm specific data. All of the players characters on the same realm and of the same faction share this database.
|
||||
-- * **locale** Locale specific data, based on the locale of the players game client.
|
||||
-- * **global** Global Data. All characters on the same account share this database.
|
||||
-- * **profile** Profile-specific data. All characters using the same profile share this database. The user can control which profile should be used.
|
||||
--
|
||||
-- Creating a new Database using the `:New` function will return a new DBObject. A database will inherit all functions
|
||||
-- of the DBObjectLib listed here. \\
|
||||
-- If you create a new namespaced child-database (`:RegisterNamespace`), you'll get a DBObject as well, but note
|
||||
-- that the child-databases cannot individually change their profile, and are linked to their parents profile - and because of that,
|
||||
-- the profile related APIs are not available. Only `:RegisterDefaults` and `:ResetProfile` are available on child-databases.
|
||||
--
|
||||
-- For more details on how to use AceDB-3.0, see the [[AceDB-3.0 Tutorial]].
|
||||
--
|
||||
-- You may also be interested in [[libdualspec-1-0|LibDualSpec-1.0]] to do profile switching automatically when switching specs.
|
||||
--
|
||||
-- @usage
|
||||
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("DBExample")
|
||||
--
|
||||
-- -- declare defaults to be used in the DB
|
||||
-- local defaults = {
|
||||
-- profile = {
|
||||
-- setting = true,
|
||||
-- }
|
||||
-- }
|
||||
--
|
||||
-- function MyAddon:OnInitialize()
|
||||
-- -- Assuming the .toc says ## SavedVariables: MyAddonDB
|
||||
-- self.db = LibStub("AceDB-3.0"):New("MyAddonDB", defaults, true)
|
||||
-- end
|
||||
-- @class file
|
||||
-- @name AceDB-3.0.lua
|
||||
-- @release $Id: AceDB-3.0.lua 1142 2016-07-11 08:36:19Z nevcairiel $
|
||||
local ACEDB_MAJOR, ACEDB_MINOR = "AceDB-3.0", 26
|
||||
local AceDB, oldminor = LibStub:NewLibrary(ACEDB_MAJOR, ACEDB_MINOR)
|
||||
|
||||
if not AceDB then return end -- No upgrade needed
|
||||
|
||||
local AceCore = LibStub("AceCore-3.0")
|
||||
local new, del = AceCore.new, AceCore.del
|
||||
|
||||
-- Lua APIs
|
||||
local type, pairs, next, error = type, pairs, next, error
|
||||
local setmetatable, getmetatable, rawset, rawget = setmetatable, getmetatable, rawset, rawget
|
||||
|
||||
-- WoW APIs
|
||||
local _G = AceCore._G
|
||||
|
||||
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
|
||||
-- List them here for Mikk's FindGlobals script
|
||||
-- GLOBALS: LibStub
|
||||
|
||||
AceDB.db_registry = AceDB.db_registry or {}
|
||||
AceDB.frame = AceDB.frame or CreateFrame("Frame")
|
||||
|
||||
local CallbackHandler
|
||||
local CallbackDummy = { Fire = function() end }
|
||||
|
||||
local DBObjectLib = {}
|
||||
|
||||
-- Ace3v: for all recursive functions we must declare the iterator as local again, this step is necessary in vanilla
|
||||
-- Example:
|
||||
-- for k,v in pairs(table) do
|
||||
-- local v = v
|
||||
-- ...
|
||||
|
||||
|
||||
--[[-------------------------------------------------------------------------
|
||||
AceDB Utility Functions
|
||||
---------------------------------------------------------------------------]]
|
||||
|
||||
-- Simple shallow copy for copying defaults
|
||||
local function copyTable(src, dest)
|
||||
if type(dest) ~= "table" then dest = {} end
|
||||
if type(src) == "table" then
|
||||
for k,v in pairs(src) do
|
||||
local v = v
|
||||
if type(v) == "table" then
|
||||
-- try to index the key first so that the metatable creates the defaults, if set, and use that table
|
||||
v = copyTable(v, dest[k])
|
||||
end
|
||||
dest[k] = v
|
||||
end
|
||||
end
|
||||
return dest
|
||||
end
|
||||
|
||||
-- Called to add defaults to a section of the database
|
||||
--
|
||||
-- When a ["*"] default section is indexed with a new key, a table is returned
|
||||
-- and set in the host table. These tables must be cleaned up by removeDefaults
|
||||
-- in order to ensure we don't write empty default tables.
|
||||
local function copyDefaults(dest, src)
|
||||
-- this happens if some value in the SV overwrites our default value with a non-table
|
||||
--if type(dest) ~= "table" then return end
|
||||
for k, v in pairs(src) do
|
||||
local v = v
|
||||
if k == "*" or k == "**" then
|
||||
if type(v) == "table" then
|
||||
-- This is a metatable used for table defaults
|
||||
local mt = {
|
||||
-- This handles the lookup and creation of new subtables
|
||||
__index = function(t,k)
|
||||
if k == nil then return nil end
|
||||
local tbl = {}
|
||||
copyDefaults(tbl, v)
|
||||
rawset(t, k, tbl)
|
||||
return tbl
|
||||
end,
|
||||
}
|
||||
setmetatable(dest, mt)
|
||||
-- handle already existing tables in the SV
|
||||
for dk, dv in pairs(dest) do
|
||||
if not rawget(src, dk) and type(dv) == "table" then
|
||||
copyDefaults(dv, v)
|
||||
end
|
||||
end
|
||||
else
|
||||
-- Values are not tables, so this is just a simple return
|
||||
local mt = {__index = function(t,k) return k~=nil and v or nil end}
|
||||
setmetatable(dest, mt)
|
||||
end
|
||||
elseif type(v) == "table" then
|
||||
if not rawget(dest, k) then rawset(dest, k, {}) end
|
||||
if type(dest[k]) == "table" then
|
||||
copyDefaults(dest[k], v)
|
||||
if src['**'] then
|
||||
copyDefaults(dest[k], src['**'])
|
||||
end
|
||||
end
|
||||
else
|
||||
if rawget(dest, k) == nil then
|
||||
rawset(dest, k, v)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- Called to remove all defaults in the default table from the database
|
||||
local function removeDefaults(db, defaults, blocker)
|
||||
-- remove all metatables from the db, so we don't accidentally create new sub-tables through them
|
||||
setmetatable(db, nil)
|
||||
-- loop through the defaults and remove their content
|
||||
for k,v in pairs(defaults) do
|
||||
local v = v
|
||||
if k == "*" or k == "**" then
|
||||
if type(v) == "table" then
|
||||
-- Loop through all the actual k,v pairs and remove
|
||||
for key, value in pairs(db) do
|
||||
local value = value
|
||||
if type(value) == "table" then
|
||||
-- if the key was not explicitly specified in the defaults table, just strip everything from * and ** tables
|
||||
if defaults[key] == nil and (not blocker or blocker[key] == nil) then
|
||||
removeDefaults(value, v)
|
||||
-- if the table is empty afterwards, remove it
|
||||
if next(value) == nil then
|
||||
db[key] = nil
|
||||
end
|
||||
-- if it was specified, only strip ** content, but block values which were set in the key table
|
||||
elseif k == "**" then
|
||||
removeDefaults(value, v, defaults[key])
|
||||
end
|
||||
end
|
||||
end
|
||||
elseif k == "*" then
|
||||
-- check for non-table default
|
||||
for key, value in pairs(db) do
|
||||
if defaults[key] == nil and v == value then
|
||||
db[key] = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
elseif type(v) == "table" and type(db[k]) == "table" then
|
||||
-- if a blocker was set, dive into it, to allow multi-level defaults
|
||||
removeDefaults(db[k], v, blocker and blocker[k])
|
||||
if next(db[k]) == nil then
|
||||
db[k] = nil
|
||||
end
|
||||
else
|
||||
-- check if the current value matches the default, and that its not blocked by another defaults table
|
||||
if db[k] == defaults[k] and (not blocker or blocker[k] == nil) then
|
||||
db[k] = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- This is called when a table section is first accessed, to set up the defaults
|
||||
local function initSection(db, section, svstore, key, defaults)
|
||||
local sv = rawget(db, "sv")
|
||||
|
||||
local tableCreated
|
||||
if not sv[svstore] then sv[svstore] = {} end
|
||||
if not sv[svstore][key] then
|
||||
sv[svstore][key] = {}
|
||||
tableCreated = true
|
||||
end
|
||||
|
||||
local tbl = sv[svstore][key]
|
||||
|
||||
if defaults then
|
||||
copyDefaults(tbl, defaults)
|
||||
end
|
||||
rawset(db, section, tbl)
|
||||
|
||||
return tableCreated, tbl
|
||||
end
|
||||
|
||||
-- Metatable to handle the dynamic creation of sections and copying of sections.
|
||||
local dbmt = {
|
||||
__index = function(t, section)
|
||||
local keys = rawget(t, "keys")
|
||||
local key = keys[section]
|
||||
if key then
|
||||
local defaultTbl = rawget(t, "defaults")
|
||||
local defaults = defaultTbl and defaultTbl[section]
|
||||
|
||||
if section == "profile" then
|
||||
if initSection(t, section, "profiles", key, defaults) then
|
||||
-- Callback: OnNewProfile, database, newProfileKey
|
||||
t.callbacks:Fire("OnNewProfile", 2, t, key)
|
||||
end
|
||||
elseif section == "profiles" then
|
||||
local sv = rawget(t, "sv")
|
||||
if not sv.profiles then sv.profiles = {} end
|
||||
rawset(t, "profiles", sv.profiles)
|
||||
elseif section == "global" then
|
||||
local sv = rawget(t, "sv")
|
||||
if not sv.global then sv.global = {} end
|
||||
if defaults then
|
||||
copyDefaults(sv.global, defaults)
|
||||
end
|
||||
rawset(t, section, sv.global)
|
||||
else
|
||||
initSection(t, section, section, key, defaults)
|
||||
end
|
||||
end
|
||||
|
||||
return rawget(t, section)
|
||||
end
|
||||
}
|
||||
|
||||
local function validateDefaults(defaults, keyTbl, offset)
|
||||
if not defaults then return end
|
||||
offset = offset or 0
|
||||
for k in pairs(defaults) do
|
||||
if not keyTbl[k] or k == "profiles" then
|
||||
error(("Usage: AceDBObject:RegisterDefaults(defaults): '%s' is not a valid datatype."):format(k), 3 + offset)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local preserve_keys = {
|
||||
["callbacks"] = true,
|
||||
["RegisterCallback"] = true,
|
||||
["UnregisterCallback"] = true,
|
||||
["UnregisterAllCallbacks"] = true,
|
||||
["children"] = true,
|
||||
}
|
||||
|
||||
local realmKey = GetRealmName()
|
||||
local charKey = UnitName("player") .. " - " .. realmKey
|
||||
local _, classKey = UnitClass("player")
|
||||
local _, raceKey = UnitRace("player")
|
||||
local _, factionKey = UnitFactionGroup("player")
|
||||
-- Ace3v: the faction key may error when in GM mode
|
||||
factionKey = factionKey or "Others"
|
||||
local localeKey = string.lower(GetLocale())
|
||||
|
||||
-- Actual database initialization function
|
||||
local function initdb(sv, defaults, defaultProfile, olddb, parent)
|
||||
-- Generate the database keys for each section
|
||||
|
||||
-- map "true" to our "Default" profile
|
||||
if defaultProfile == true then defaultProfile = "Default" end
|
||||
|
||||
local profileKey
|
||||
if not parent then
|
||||
-- Make a container for profile keys
|
||||
if not sv.profileKeys then sv.profileKeys = {} end
|
||||
|
||||
-- Try to get the profile selected from the char db
|
||||
profileKey = sv.profileKeys[charKey] or defaultProfile or charKey
|
||||
|
||||
-- save the selected profile for later
|
||||
sv.profileKeys[charKey] = profileKey
|
||||
else
|
||||
-- Use the profile of the parents DB
|
||||
profileKey = parent.keys.profile or defaultProfile or charKey
|
||||
|
||||
-- clear the profileKeys in the DB, namespaces don't need to store them
|
||||
sv.profileKeys = nil
|
||||
end
|
||||
|
||||
-- This table contains keys that enable the dynamic creation
|
||||
-- of each section of the table. The 'global' and 'profiles'
|
||||
-- have a key of true, since they are handled in a special case
|
||||
local keyTbl= {
|
||||
["char"] = charKey,
|
||||
["realm"] = realmKey,
|
||||
["class"] = classKey,
|
||||
["race"] = raceKey,
|
||||
["faction"] = factionKey,
|
||||
["factionrealm"] = factionKey .. " - " .. realmKey,
|
||||
["profile"] = profileKey,
|
||||
["locale"] = localeKey,
|
||||
["global"] = true,
|
||||
["profiles"] = true,
|
||||
}
|
||||
|
||||
validateDefaults(defaults, keyTbl, 1)
|
||||
|
||||
-- This allows us to use this function to reset an entire database
|
||||
-- Clear out the old database
|
||||
if olddb then
|
||||
for k,v in pairs(olddb) do if not preserve_keys[k] then olddb[k] = nil end end
|
||||
end
|
||||
|
||||
-- Give this database the metatable so it initializes dynamically
|
||||
local db = setmetatable(olddb or {}, dbmt)
|
||||
|
||||
if not rawget(db, "callbacks") then
|
||||
-- try to load CallbackHandler-1.0 if it loaded after our library
|
||||
if not CallbackHandler then CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0", true) end
|
||||
db.callbacks = CallbackHandler and CallbackHandler:New(db) or CallbackDummy
|
||||
end
|
||||
|
||||
-- Copy methods locally into the database object, to avoid hitting
|
||||
-- the metatable when calling methods
|
||||
|
||||
if not parent then
|
||||
for name, func in pairs(DBObjectLib) do
|
||||
db[name] = func
|
||||
end
|
||||
else
|
||||
-- hack this one in
|
||||
db.RegisterDefaults = DBObjectLib.RegisterDefaults
|
||||
db.ResetProfile = DBObjectLib.ResetProfile
|
||||
end
|
||||
|
||||
-- Set some properties in the database object
|
||||
db.profiles = sv.profiles
|
||||
db.keys = keyTbl
|
||||
db.sv = sv
|
||||
--db.sv_name = name
|
||||
db.defaults = defaults
|
||||
db.parent = parent
|
||||
|
||||
-- store the DB in the registry
|
||||
AceDB.db_registry[db] = true
|
||||
|
||||
return db
|
||||
end
|
||||
|
||||
-- handle PLAYER_LOGOUT
|
||||
-- strip all defaults from all databases
|
||||
-- and cleans up empty sections
|
||||
local function logoutHandler()
|
||||
if event == "PLAYER_LOGOUT" then
|
||||
for db in pairs(AceDB.db_registry) do
|
||||
db.callbacks:Fire("OnDatabaseShutdown", 1, db)
|
||||
db:RegisterDefaults(nil)
|
||||
|
||||
-- cleanup sections that are empty without defaults
|
||||
local sv = rawget(db, "sv")
|
||||
for section in pairs(db.keys) do
|
||||
if rawget(sv, section) then
|
||||
-- global is special, all other sections have sub-entrys
|
||||
-- also don't delete empty profiles on main dbs, only on namespaces
|
||||
if section ~= "global" and (section ~= "profiles" or rawget(db, "parent")) then
|
||||
for key in pairs(sv[section]) do
|
||||
if not next(sv[section][key]) then
|
||||
sv[section][key] = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
if not next(sv[section]) then
|
||||
sv[section] = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
AceDB.frame:RegisterEvent("PLAYER_LOGOUT")
|
||||
AceDB.frame:SetScript("OnEvent", logoutHandler)
|
||||
|
||||
|
||||
--[[-------------------------------------------------------------------------
|
||||
AceDB Object Method Definitions
|
||||
---------------------------------------------------------------------------]]
|
||||
|
||||
--- Sets the defaults table for the given database object by clearing any
|
||||
-- that are currently set, and then setting the new defaults.
|
||||
-- @param defaults A table of defaults for this database
|
||||
function DBObjectLib:RegisterDefaults(defaults)
|
||||
if defaults and type(defaults) ~= "table" then
|
||||
error("Usage: AceDBObject:RegisterDefaults(defaults): 'defaults' - table or nil expected.", 2)
|
||||
end
|
||||
|
||||
validateDefaults(defaults, self.keys)
|
||||
|
||||
-- Remove any currently set defaults
|
||||
if self.defaults then
|
||||
for section,key in pairs(self.keys) do
|
||||
if self.defaults[section] and rawget(self, section) then
|
||||
removeDefaults(self[section], self.defaults[section])
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- Set the DBObject.defaults table
|
||||
self.defaults = defaults
|
||||
|
||||
-- Copy in any defaults, only touching those sections already created
|
||||
if defaults then
|
||||
for section,key in pairs(self.keys) do
|
||||
if defaults[section] and rawget(self, section) then
|
||||
copyDefaults(self[section], defaults[section])
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- Changes the profile of the database and all of it's namespaces to the
|
||||
-- supplied named profile
|
||||
-- @param name The name of the profile to set as the current profile
|
||||
function DBObjectLib:SetProfile(name)
|
||||
if type(name) ~= "string" then
|
||||
error("Usage: AceDBObject:SetProfile(name): 'name' - string expected.", 2)
|
||||
end
|
||||
|
||||
-- changing to the same profile, dont do anything
|
||||
if name == self.keys.profile then return end
|
||||
|
||||
local oldProfile = self.profile
|
||||
local defaults = self.defaults and self.defaults.profile
|
||||
|
||||
-- Callback: OnProfileShutdown, database
|
||||
self.callbacks:Fire("OnProfileShutdown", 1, self)
|
||||
|
||||
if oldProfile and defaults then
|
||||
-- Remove the defaults from the old profile
|
||||
removeDefaults(oldProfile, defaults)
|
||||
end
|
||||
|
||||
self.profile = nil
|
||||
self.keys["profile"] = name
|
||||
|
||||
-- if the storage exists, save the new profile
|
||||
-- this won't exist on namespaces.
|
||||
if self.sv.profileKeys then
|
||||
self.sv.profileKeys[charKey] = name
|
||||
end
|
||||
|
||||
-- populate to child namespaces
|
||||
if self.children then
|
||||
for _, db in pairs(self.children) do
|
||||
DBObjectLib.SetProfile(db, name)
|
||||
end
|
||||
end
|
||||
|
||||
-- Callback: OnProfileChanged, database, newProfileKey
|
||||
self.callbacks:Fire("OnProfileChanged", 2, self, name)
|
||||
end
|
||||
|
||||
--- Returns a table with the names of the existing profiles in the database.
|
||||
-- You can optionally supply a table to re-use for this purpose.
|
||||
-- @param tbl A table to store the profile names in (optional)
|
||||
function DBObjectLib:GetProfiles(tbl)
|
||||
if tbl and type(tbl) ~= "table" then
|
||||
error("Usage: AceDBObject:GetProfiles(tbl): 'tbl' - table or nil expected.", 2)
|
||||
end
|
||||
|
||||
-- Clear the container table
|
||||
if tbl then
|
||||
for k,v in pairs(tbl) do tbl[k] = nil end
|
||||
else
|
||||
tbl = {}
|
||||
end
|
||||
|
||||
local curProfile = self.keys.profile
|
||||
|
||||
local i = 0
|
||||
for profileKey in pairs(self.profiles) do
|
||||
i = i + 1
|
||||
tbl[i] = profileKey
|
||||
if curProfile and profileKey == curProfile then curProfile = nil end
|
||||
end
|
||||
|
||||
-- Add the current profile, if it hasn't been created yet
|
||||
if curProfile then
|
||||
i = i + 1
|
||||
tbl[i] = curProfile
|
||||
end
|
||||
|
||||
return tbl, i
|
||||
end
|
||||
|
||||
--- Returns the current profile name used by the database
|
||||
function DBObjectLib:GetCurrentProfile()
|
||||
return self.keys.profile
|
||||
end
|
||||
|
||||
--- Deletes a named profile. This profile must not be the active profile.
|
||||
-- @param name The name of the profile to be deleted
|
||||
-- @param silent If true, do not raise an error when the profile does not exist
|
||||
function DBObjectLib:DeleteProfile(name, silent)
|
||||
if type(name) ~= "string" then
|
||||
error("Usage: AceDBObject:DeleteProfile(name): 'name' - string expected.", 2)
|
||||
end
|
||||
|
||||
if self.keys.profile == name then
|
||||
error("Cannot delete the active profile in an AceDBObject.", 2)
|
||||
end
|
||||
|
||||
if not rawget(self.profiles, name) and not silent then
|
||||
error("Cannot delete profile '" .. name .. "'. It does not exist.", 2)
|
||||
end
|
||||
|
||||
self.profiles[name] = nil
|
||||
|
||||
-- populate to child namespaces
|
||||
if self.children then
|
||||
for _, db in pairs(self.children) do
|
||||
DBObjectLib.DeleteProfile(db, name, true)
|
||||
end
|
||||
end
|
||||
|
||||
-- switch all characters that use this profile back to the default
|
||||
if self.sv.profileKeys then
|
||||
for key, profile in pairs(self.sv.profileKeys) do
|
||||
if profile == name then
|
||||
self.sv.profileKeys[key] = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- Callback: OnProfileDeleted, database, profileKey
|
||||
self.callbacks:Fire("OnProfileDeleted", 2, self, name)
|
||||
end
|
||||
|
||||
--- Copies a named profile into the current profile, overwriting any conflicting
|
||||
-- settings.
|
||||
-- @param name The name of the profile to be copied into the current profile
|
||||
-- @param silent If true, do not raise an error when the profile does not exist
|
||||
function DBObjectLib:CopyProfile(name, silent)
|
||||
if type(name) ~= "string" then
|
||||
error("Usage: AceDBObject:CopyProfile(name): 'name' - string expected.", 2)
|
||||
end
|
||||
|
||||
if name == self.keys.profile then
|
||||
error("Cannot have the same source and destination profiles.", 2)
|
||||
end
|
||||
|
||||
if not rawget(self.profiles, name) and not silent then
|
||||
error("Cannot copy profile '" .. name .. "'. It does not exist.", 2)
|
||||
end
|
||||
|
||||
-- Reset the profile before copying
|
||||
DBObjectLib.ResetProfile(self, nil, true)
|
||||
|
||||
local profile = self.profile
|
||||
local source = self.profiles[name]
|
||||
|
||||
copyTable(source, profile)
|
||||
|
||||
-- populate to child namespaces
|
||||
if self.children then
|
||||
for _, db in pairs(self.children) do
|
||||
DBObjectLib.CopyProfile(db, name, true)
|
||||
end
|
||||
end
|
||||
|
||||
-- Callback: OnProfileCopied, database, sourceProfileKey
|
||||
self.callbacks:Fire("OnProfileCopied", 2, self, name)
|
||||
end
|
||||
|
||||
--- Resets the current profile to the default values (if specified).
|
||||
-- @param noChildren if set to true, the reset will not be populated to the child namespaces of this DB object
|
||||
-- @param noCallbacks if set to true, won't fire the OnProfileReset callback
|
||||
function DBObjectLib:ResetProfile(noChildren, noCallbacks)
|
||||
local profile = self.profile
|
||||
|
||||
for k,v in pairs(profile) do
|
||||
profile[k] = nil
|
||||
end
|
||||
|
||||
local defaults = self.defaults and self.defaults.profile
|
||||
if defaults then
|
||||
copyDefaults(profile, defaults)
|
||||
end
|
||||
|
||||
-- populate to child namespaces
|
||||
if self.children and not noChildren then
|
||||
for _, db in pairs(self.children) do
|
||||
DBObjectLib.ResetProfile(db, nil, noCallbacks)
|
||||
end
|
||||
end
|
||||
|
||||
-- Callback: OnProfileReset, database
|
||||
if not noCallbacks then
|
||||
self.callbacks:Fire("OnProfileReset", 2, self, self.keys["profile"])
|
||||
end
|
||||
end
|
||||
|
||||
--- Resets the entire database, using the string defaultProfile as the new default
|
||||
-- profile.
|
||||
-- @param defaultProfile The profile name to use as the default
|
||||
function DBObjectLib:ResetDB(defaultProfile)
|
||||
if defaultProfile and type(defaultProfile) ~= "string" then
|
||||
error("Usage: AceDBObject:ResetDB(defaultProfile): 'defaultProfile' - string or nil expected.", 2)
|
||||
end
|
||||
|
||||
local sv = self.sv
|
||||
for k,v in pairs(sv) do
|
||||
sv[k] = nil
|
||||
end
|
||||
|
||||
local parent = self.parent
|
||||
|
||||
initdb(sv, self.defaults, defaultProfile, self)
|
||||
|
||||
-- fix the child namespaces
|
||||
if self.children then
|
||||
if not sv.namespaces then sv.namespaces = {} end
|
||||
for name, db in pairs(self.children) do
|
||||
if not sv.namespaces[name] then sv.namespaces[name] = {} end
|
||||
initdb(sv.namespaces[name], db.defaults, self.keys.profile, db, self)
|
||||
end
|
||||
end
|
||||
|
||||
-- Callback: OnDatabaseReset, database
|
||||
self.callbacks:Fire("OnDatabaseReset", 1, self)
|
||||
-- Callback: OnProfileChanged, database, profileKey
|
||||
self.callbacks:Fire("OnProfileChanged", 2, self, self.keys["profile"])
|
||||
|
||||
return self
|
||||
end
|
||||
|
||||
--- Creates a new database namespace, directly tied to the database. This
|
||||
-- is a full scale database in it's own rights other than the fact that
|
||||
-- it cannot control its profile individually
|
||||
-- @param name The name of the new namespace
|
||||
-- @param defaults A table of values to use as defaults
|
||||
function DBObjectLib:RegisterNamespace(name, defaults)
|
||||
if type(name) ~= "string" then
|
||||
error("Usage: AceDBObject:RegisterNamespace(name, defaults): 'name' - string expected.", 2)
|
||||
end
|
||||
if defaults and type(defaults) ~= "table" then
|
||||
error("Usage: AceDBObject:RegisterNamespace(name, defaults): 'defaults' - table or nil expected.", 2)
|
||||
end
|
||||
if self.children and self.children[name] then
|
||||
error ("Usage: AceDBObject:RegisterNamespace(name, defaults): 'name' - a namespace with that name already exists.", 2)
|
||||
end
|
||||
|
||||
local sv = self.sv
|
||||
if not sv.namespaces then sv.namespaces = {} end
|
||||
if not sv.namespaces[name] then
|
||||
sv.namespaces[name] = {}
|
||||
end
|
||||
|
||||
local newDB = initdb(sv.namespaces[name], defaults, self.keys.profile, nil, self)
|
||||
|
||||
if not self.children then self.children = {} end
|
||||
self.children[name] = newDB
|
||||
return newDB
|
||||
end
|
||||
|
||||
--- Returns an already existing namespace from the database object.
|
||||
-- @param name The name of the new namespace
|
||||
-- @param silent if true, the addon is optional, silently return nil if its not found
|
||||
-- @usage
|
||||
-- local namespace = self.db:GetNamespace('namespace')
|
||||
-- @return the namespace object if found
|
||||
function DBObjectLib:GetNamespace(name, silent)
|
||||
if type(name) ~= "string" then
|
||||
error("Usage: AceDBObject:GetNamespace(name): 'name' - string expected.", 2)
|
||||
end
|
||||
if not silent and not (self.children and self.children[name]) then
|
||||
error ("Usage: AceDBObject:GetNamespace(name): 'name' - namespace does not exist.", 2)
|
||||
end
|
||||
if not self.children then self.children = {} end
|
||||
return self.children[name]
|
||||
end
|
||||
|
||||
--[[-------------------------------------------------------------------------
|
||||
AceDB Exposed Methods
|
||||
---------------------------------------------------------------------------]]
|
||||
|
||||
--- Creates a new database object that can be used to handle database settings and profiles.
|
||||
-- By default, an empty DB is created, using a character specific profile.
|
||||
--
|
||||
-- You can override the default profile used by passing any profile name as the third argument,
|
||||
-- or by passing //true// as the third argument to use a globally shared profile called "Default".
|
||||
--
|
||||
-- Note that there is no token replacement in the default profile name, passing a defaultProfile as "char"
|
||||
-- will use a profile named "char", and not a character-specific profile.
|
||||
-- @param tbl The name of variable, or table to use for the database
|
||||
-- @param defaults A table of database defaults
|
||||
-- @param defaultProfile The name of the default profile. If not set, a character specific profile will be used as the default.
|
||||
-- You can also pass //true// to use a shared global profile called "Default".
|
||||
-- @usage
|
||||
-- -- Create an empty DB using a character-specific default profile.
|
||||
-- self.db = LibStub("AceDB-3.0"):New("MyAddonDB")
|
||||
-- @usage
|
||||
-- -- Create a DB using defaults and using a shared default profile
|
||||
-- self.db = LibStub("AceDB-3.0"):New("MyAddonDB", defaults, true)
|
||||
function AceDB:New(tbl, defaults, defaultProfile)
|
||||
if type(tbl) == "string" then
|
||||
local name = tbl
|
||||
tbl = _G[name]
|
||||
if not tbl then
|
||||
tbl = {}
|
||||
_G[name] = tbl
|
||||
end
|
||||
end
|
||||
|
||||
if type(tbl) ~= "table" then
|
||||
error("Usage: AceDB:New(tbl, defaults, defaultProfile): 'tbl' - table expected.", 2)
|
||||
end
|
||||
|
||||
if defaults and type(defaults) ~= "table" then
|
||||
error("Usage: AceDB:New(tbl, defaults, defaultProfile): 'defaults' - table expected.", 2)
|
||||
end
|
||||
|
||||
if defaultProfile and type(defaultProfile) ~= "string" and defaultProfile ~= true then
|
||||
error("Usage: AceDB:New(tbl, defaults, defaultProfile): 'defaultProfile' - string or true expected.", 2)
|
||||
end
|
||||
|
||||
return initdb(tbl, defaults, defaultProfile)
|
||||
end
|
||||
|
||||
-- upgrade existing databases
|
||||
for db in pairs(AceDB.db_registry) do
|
||||
if not db.parent then
|
||||
for name,func in pairs(DBObjectLib) do
|
||||
db[name] = func
|
||||
end
|
||||
else
|
||||
db.RegisterDefaults = DBObjectLib.RegisterDefaults
|
||||
db.ResetProfile = DBObjectLib.ResetProfile
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,3 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="AceDB-3.0.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,129 @@
|
||||
--- AceEvent-3.0 provides event registration and secure dispatching.
|
||||
-- All dispatching is done using **CallbackHandler-1.0**. AceEvent is a simple wrapper around
|
||||
-- CallbackHandler, and dispatches all game events or addon message to the registrees.
|
||||
--
|
||||
-- **AceEvent-3.0** can be embeded into your addon, either explicitly by calling AceEvent:Embed(MyAddon) or by
|
||||
-- specifying it as an embeded library in your AceAddon. All functions will be available on your addon object
|
||||
-- and can be accessed directly, without having to explicitly call AceEvent itself.\\
|
||||
-- It is recommended to embed AceEvent, otherwise you'll have to specify a custom `self` on all calls you
|
||||
-- make into AceEvent.
|
||||
-- @class file
|
||||
-- @name AceEvent-3.0
|
||||
-- @release $Id: AceEvent-3.0.lua 975 2010-10-23 11:26:18Z nevcairiel $
|
||||
local MAJOR, MINOR = "AceEvent-3.0", 3
|
||||
local AceEvent = LibStub:NewLibrary(MAJOR, MINOR)
|
||||
|
||||
if not AceEvent then return end
|
||||
|
||||
-- Lua APIs
|
||||
local pairs = pairs
|
||||
|
||||
local CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0")
|
||||
|
||||
AceEvent.frame = AceEvent.frame or CreateFrame("Frame", "AceEvent30Frame") -- our event frame
|
||||
AceEvent.embeds = AceEvent.embeds or {} -- what objects embed this lib
|
||||
|
||||
-- APIs and registry for blizzard events, using CallbackHandler lib
|
||||
if not AceEvent.events then
|
||||
AceEvent.events = CallbackHandler:New(AceEvent,
|
||||
"RegisterEvent", "UnregisterEvent", "UnregisterAllEvents")
|
||||
end
|
||||
|
||||
function AceEvent.events:OnUsed(target, eventname)
|
||||
AceEvent.frame:RegisterEvent(eventname)
|
||||
end
|
||||
|
||||
function AceEvent.events:OnUnused(target, eventname)
|
||||
AceEvent.frame:UnregisterEvent(eventname)
|
||||
end
|
||||
|
||||
|
||||
-- APIs and registry for IPC messages, using CallbackHandler lib
|
||||
if not AceEvent.messages then
|
||||
AceEvent.messages = CallbackHandler:New(AceEvent,
|
||||
"RegisterMessage", "UnregisterMessage", "UnregisterAllMessages"
|
||||
)
|
||||
AceEvent.SendMessage = AceEvent.messages.Fire
|
||||
end
|
||||
|
||||
--- embedding and embed handling
|
||||
local mixins = {
|
||||
"RegisterEvent", "UnregisterEvent",
|
||||
"RegisterMessage", "UnregisterMessage",
|
||||
"SendMessage",
|
||||
"UnregisterAllEvents", "UnregisterAllMessages",
|
||||
}
|
||||
|
||||
--- Register for a Blizzard Event.
|
||||
-- The callback will be called with the optional `arg` as the first argument (if supplied), and the event name as the second (or first, if no arg was supplied)
|
||||
-- Any arguments to the event will be passed on after that.
|
||||
-- @name AceEvent:RegisterEvent
|
||||
-- @class function
|
||||
-- @paramsig event[, callback [, arg]]
|
||||
-- @param event The event to register for
|
||||
-- @param callback The callback function to call when the event is triggered (funcref or method, defaults to a method with the event name)
|
||||
-- @param arg An optional argument to pass to the callback function
|
||||
|
||||
--- Unregister an event.
|
||||
-- @name AceEvent:UnregisterEvent
|
||||
-- @class function
|
||||
-- @paramsig event
|
||||
-- @param event The event to unregister
|
||||
|
||||
--- Register for a custom AceEvent-internal message.
|
||||
-- The callback will be called with the optional `arg` as the first argument (if supplied), and the event name as the second (or first, if no arg was supplied)
|
||||
-- Any arguments to the event will be passed on after that.
|
||||
-- @name AceEvent:RegisterMessage
|
||||
-- @class function
|
||||
-- @paramsig message[, callback [, arg]]
|
||||
-- @param message The message to register for
|
||||
-- @param callback The callback function to call when the message is triggered (funcref or method, defaults to a method with the event name)
|
||||
-- @param arg An optional argument to pass to the callback function
|
||||
|
||||
--- Unregister a message
|
||||
-- @name AceEvent:UnregisterMessage
|
||||
-- @class function
|
||||
-- @paramsig message
|
||||
-- @param message The message to unregister
|
||||
|
||||
--- Send a message over the AceEvent-3.0 internal message system to other addons registered for this message.
|
||||
-- @name AceEvent:SendMessage
|
||||
-- @class function
|
||||
-- @paramsig message, ...
|
||||
-- @param message The message to send
|
||||
-- @param ... Any arguments to the message
|
||||
|
||||
|
||||
-- Embeds AceEvent into the target object making the functions from the mixins list available on target:..
|
||||
-- @param target target object to embed AceEvent in
|
||||
function AceEvent:Embed(target)
|
||||
for k, v in pairs(mixins) do
|
||||
target[v] = self[v]
|
||||
end
|
||||
self.embeds[target] = true
|
||||
return target
|
||||
end
|
||||
|
||||
-- AceEvent:OnEmbedDisable( target )
|
||||
-- target (object) - target object that is being disabled
|
||||
--
|
||||
-- Unregister all events messages etc when the target disables.
|
||||
-- this method should be called by the target manually or by an addon framework
|
||||
function AceEvent:OnEmbedDisable(target)
|
||||
target:UnregisterAllEvents()
|
||||
target:UnregisterAllMessages()
|
||||
end
|
||||
|
||||
-- Script to fire blizzard events into the event listeners
|
||||
-- Ace3v: in vanilla the arguments are set to global:
|
||||
-- event, arg1, arg2, arg3 ...
|
||||
-- the user have always access to them, so we save the table cost here
|
||||
local events = AceEvent.events
|
||||
AceEvent.frame:SetScript("OnEvent", function()
|
||||
events:Fire(event)
|
||||
end)
|
||||
|
||||
--- Finally: upgrade our old embeds
|
||||
for target, v in pairs(AceEvent.embeds) do
|
||||
AceEvent:Embed(target)
|
||||
end
|
||||
@@ -0,0 +1,3 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="AceEvent-3.0.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,540 @@
|
||||
--- **AceHook-3.0** offers safe Hooking/Unhooking of functions, methods and frame scripts.
|
||||
-- Using AceHook-3.0 is recommended when you need to unhook your hooks again, so the hook chain isn't broken
|
||||
-- when you manually restore the original function.
|
||||
--
|
||||
-- **AceHook-3.0** can be embeded into your addon, either explicitly by calling AceHook:Embed(MyAddon) or by
|
||||
-- specifying it as an embeded library in your AceAddon. All functions will be available on your addon object
|
||||
-- and can be accessed directly, without having to explicitly call AceHook itself.\\
|
||||
-- It is recommended to embed AceHook, otherwise you'll have to specify a custom `self` on all calls you
|
||||
-- make into AceHook.
|
||||
-- @class file
|
||||
-- @name AceHook-3.0
|
||||
-- @release $Id: AceHook-3.0.lua 1118 2014-10-12 08:21:54Z nevcairiel $
|
||||
local ACEHOOK_MAJOR, ACEHOOK_MINOR = "AceHook-3.0", 8
|
||||
local AceHook, oldminor = LibStub:NewLibrary(ACEHOOK_MAJOR, ACEHOOK_MINOR)
|
||||
|
||||
if not AceHook then return end -- No upgrade needed
|
||||
|
||||
local AceCore = LibStub("AceCore-3.0")
|
||||
local new, del = AceCore.new, AceCore.del
|
||||
|
||||
AceHook.embeded = AceHook.embeded or {}
|
||||
AceHook.registry = AceHook.registry or setmetatable({}, {__index = function(tbl, key) tbl[key] = {} return tbl[key] end })
|
||||
AceHook.handlers = AceHook.handlers or {}
|
||||
AceHook.actives = AceHook.actives or {}
|
||||
AceHook.scripts = AceHook.scripts or {}
|
||||
AceHook.onceSecure = AceHook.onceSecure or {}
|
||||
AceHook.hooks = AceHook.hooks or {}
|
||||
|
||||
-- local upvalues
|
||||
local registry = AceHook.registry
|
||||
local handlers = AceHook.handlers
|
||||
local actives = AceHook.actives
|
||||
local scripts = AceHook.scripts
|
||||
local onceSecure = AceHook.onceSecure
|
||||
|
||||
-- Lua APIs
|
||||
local pairs, next, type = pairs, next, type
|
||||
local format = string.format
|
||||
local assert, error = assert, error
|
||||
|
||||
-- WoW APIs
|
||||
local hooksecurefunc, issecurevariable = AceCore.hooksecurefunc, AceCore.issecurevariable
|
||||
|
||||
local _G = AceCore._G
|
||||
|
||||
local protectedScripts = {
|
||||
OnClick = true,
|
||||
}
|
||||
|
||||
-- upgrading of embeded is done at the bottom of the file
|
||||
|
||||
local mixins = {
|
||||
"Hook", "SecureHook",
|
||||
"HookScript", "SecureHookScript",
|
||||
"Unhook", "UnhookAll",
|
||||
"IsHooked",
|
||||
"RawHook", "RawHookScript"
|
||||
}
|
||||
|
||||
-- AceHook:Embed( target )
|
||||
-- target (object) - target object to embed AceHook in
|
||||
--
|
||||
-- Embeds AceEevent into the target object making the functions from the mixins list available on target:..
|
||||
function AceHook:Embed( target )
|
||||
for k, v in pairs( mixins ) do
|
||||
target[v] = self[v]
|
||||
end
|
||||
self.embeded[target] = true
|
||||
-- inject the hooks table safely
|
||||
target.hooks = target.hooks or {}
|
||||
return target
|
||||
end
|
||||
|
||||
-- AceHook:OnEmbedDisable( target )
|
||||
-- target (object) - target object that is being disabled
|
||||
--
|
||||
-- Unhooks all hooks when the target disables.
|
||||
-- this method should be called by the target manually or by an addon framework
|
||||
function AceHook:OnEmbedDisable( target )
|
||||
target:UnhookAll()
|
||||
end
|
||||
|
||||
-- failsafe means even the hooking method fails, the original method will
|
||||
-- always be called
|
||||
local function createHook(self, handler, orig, secure, failsafe)
|
||||
local uid
|
||||
local method = type(handler) == "string"
|
||||
-- Ace3v: when this function called in the "hook" function, we have
|
||||
-- failsafe = not (raw or secure), so the first check condition
|
||||
-- is same as "if failsafe" or "if not raw and not secure"
|
||||
if failsafe and not secure then
|
||||
-- failsafe hook creation
|
||||
uid = function(...)
|
||||
if actives[uid] then
|
||||
if method then
|
||||
self[handler](self,unpack(arg))
|
||||
else
|
||||
handler(unpack(arg))
|
||||
end
|
||||
end
|
||||
return orig(unpack(arg))
|
||||
end
|
||||
-- /failsafe hook
|
||||
else
|
||||
-- all other hooks
|
||||
uid = function(...)
|
||||
if actives[uid] then
|
||||
if method then
|
||||
return self[handler](self,unpack(arg))
|
||||
else
|
||||
return handler(unpack(arg))
|
||||
end
|
||||
elseif not secure then -- backup on non secure
|
||||
return orig(unpack(arg))
|
||||
end
|
||||
end
|
||||
-- /hook
|
||||
end
|
||||
return uid
|
||||
end
|
||||
|
||||
local function donothing() end
|
||||
|
||||
-- @param self
|
||||
-- @param obj nil or a frame object, use with script = true
|
||||
-- @param method string, the name of a global function or the name of an object method
|
||||
-- @param handler function, or string when it's a method of 'self', if nil then will use the same value as method
|
||||
-- @param script boolean, must be true, if the hooked object is a frame
|
||||
-- @param secure boolean, if hooking a secure script, if true the original script will be called first, else later
|
||||
-- @param raw boolean, if raw hooking (replacing the original method)
|
||||
-- @param forceSecure boolean, if forcing to hook a secure method
|
||||
-- @param usage
|
||||
local function hook(self, obj, method, handler, script, secure, raw, forceSecure, usage)
|
||||
if not handler then handler = method end
|
||||
|
||||
-- These asserts make sure AceHooks's devs play by the rules.
|
||||
assert(not script or type(script) == "boolean")
|
||||
assert(not secure or type(secure) == "boolean")
|
||||
assert(not raw or type(raw) == "boolean")
|
||||
assert(not forceSecure or type(forceSecure) == "boolean")
|
||||
assert(usage)
|
||||
|
||||
-- Error checking Battery!
|
||||
if obj and type(obj) ~= "table" then
|
||||
error(format("%s: 'object' - nil or table expected got %s", usage, type(obj)), 3)
|
||||
end
|
||||
if type(method) ~= "string" then
|
||||
error(format("%s: 'method' - string expected got %s", usage, type(method)), 3)
|
||||
end
|
||||
if type(handler) ~= "string" and type(handler) ~= "function" then
|
||||
error(format("%s: 'handler' - nil, string, or function expected got %s", usage, type(handler)), 3)
|
||||
end
|
||||
if type(handler) == "string" and type(self[handler]) ~= "function" then
|
||||
error(format("%s: 'handler' - Handler specified does not exist at self[handler]", usage), 3)
|
||||
end
|
||||
if script then
|
||||
if not obj or not obj.GetScript or not obj:HasScript(method) then
|
||||
error(format("%s: You can only hook a script on a frame object", usage), 3)
|
||||
end
|
||||
if not secure and obj.IsProtected and obj:IsProtected() and protectedScripts[method] then
|
||||
error(format("Cannot hook secure script %q; Use SecureHookScript(obj, method, [handler]) instead.", method), 3)
|
||||
end
|
||||
else
|
||||
local issecure
|
||||
if obj then
|
||||
issecure = onceSecure[obj] and onceSecure[obj][method] or issecurevariable(obj, method)
|
||||
else
|
||||
issecure = onceSecure[method] or issecurevariable(method)
|
||||
end
|
||||
if issecure then
|
||||
if forceSecure then
|
||||
if obj then
|
||||
onceSecure[obj] = onceSecure[obj] or {}
|
||||
onceSecure[obj][method] = true
|
||||
else
|
||||
onceSecure[method] = true
|
||||
end
|
||||
elseif not secure then
|
||||
error(format("%s: Attempt to hook secure function %s. Use `SecureHook' or add `true' to the argument list to override.", usage, method), 3)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local uid
|
||||
if obj then
|
||||
uid = registry[self][obj] and registry[self][obj][method]
|
||||
else
|
||||
uid = registry[self][method]
|
||||
end
|
||||
|
||||
if uid then
|
||||
if actives[uid] then
|
||||
-- Only two sane choices exist here. We either a) error 100% of the time or b) always unhook and then hook
|
||||
-- choice b would likely lead to odd debuging conditions or other mysteries so we're going with a.
|
||||
error(format("Attempting to rehook already active hook %s.", method))
|
||||
end
|
||||
|
||||
if handlers[uid] == handler then -- turn on a decative hook, note enclosures break this ability, small memory leak
|
||||
actives[uid] = true
|
||||
return
|
||||
elseif obj then -- is there any reason not to call unhook instead of doing the following several lines?
|
||||
if self.hooks and self.hooks[obj] then
|
||||
self.hooks[obj][method] = nil
|
||||
end
|
||||
registry[self][obj][method] = nil
|
||||
else
|
||||
if self.hooks then
|
||||
self.hooks[method] = nil
|
||||
end
|
||||
registry[self][method] = nil
|
||||
end
|
||||
handlers[uid], actives[uid], scripts[uid] = nil, nil, nil
|
||||
uid = nil
|
||||
end
|
||||
|
||||
local orig
|
||||
if script then
|
||||
-- Sometimes there is not a original function for a script.
|
||||
orig = obj:GetScript(method) or donothing
|
||||
elseif obj then
|
||||
orig = obj[method]
|
||||
else
|
||||
orig = _G[method]
|
||||
end
|
||||
|
||||
if not orig then
|
||||
error(format("%s: Attempting to hook a non existing target", usage), 3)
|
||||
end
|
||||
|
||||
uid = createHook(self, handler, orig, secure, not (raw or secure))
|
||||
|
||||
if obj then
|
||||
registry[self][obj] = registry[self][obj] or new()
|
||||
registry[self][obj][method] = uid
|
||||
|
||||
if not secure then
|
||||
self.hooks[obj] = self.hooks[obj] or new()
|
||||
self.hooks[obj][method] = orig
|
||||
end
|
||||
|
||||
if script then
|
||||
if not secure then
|
||||
obj:SetScript(method, uid)
|
||||
else
|
||||
obj:SetScript(method, function(...)
|
||||
local tmp = {orig(unpack(arg))}
|
||||
uid(unpack(arg))
|
||||
return unpack(tmp)
|
||||
end)
|
||||
--obj:HookScript(method, uid) -- Ace3v: vanilla frame has no HookScript
|
||||
end
|
||||
else
|
||||
if not secure then
|
||||
obj[method] = uid
|
||||
else
|
||||
hooksecurefunc(obj, method, uid)
|
||||
end
|
||||
end
|
||||
else
|
||||
registry[self][method] = uid
|
||||
|
||||
if not secure then
|
||||
_G[method] = uid
|
||||
self.hooks[method] = orig
|
||||
else
|
||||
hooksecurefunc(method, uid)
|
||||
end
|
||||
end
|
||||
|
||||
actives[uid], handlers[uid], scripts[uid] = true, handler, script and true or nil
|
||||
end
|
||||
|
||||
--- Hook a function or a method on an object.
|
||||
-- The hook created will be a "safe hook", that means that your handler will be called
|
||||
-- before the hooked function ("Pre-Hook"), and you don't have to call the original function yourself,
|
||||
-- however you cannot stop the execution of the function, or modify any of the arguments/return values.\\
|
||||
-- This type of hook is typically used if you need to know if some function got called, and don't want to modify it.
|
||||
-- @paramsig [object], method, [handler], [hookSecure]
|
||||
-- @param object The object to hook a method from
|
||||
-- @param method If object was specified, the name of the method, or the name of the function to hook.
|
||||
-- @param handler The handler for the hook, a funcref or a method name. (Defaults to the name of the hooked function)
|
||||
-- @param hookSecure If true, AceHook will allow hooking of secure functions.
|
||||
-- @usage
|
||||
-- -- create an addon with AceHook embeded
|
||||
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("HookDemo", "AceHook-3.0")
|
||||
--
|
||||
-- function MyAddon:OnEnable()
|
||||
-- -- Hook ActionButton_UpdateHotkeys, overwriting the secure status
|
||||
-- self:Hook("ActionButton_UpdateHotkeys", true)
|
||||
-- end
|
||||
--
|
||||
-- function MyAddon:ActionButton_UpdateHotkeys(button, type)
|
||||
-- print(button:GetName() .. " is updating its HotKey")
|
||||
-- end
|
||||
function AceHook:Hook(object, method, handler, hookSecure)
|
||||
if type(object) == "string" then
|
||||
method, handler, hookSecure, object = object, method, handler, nil
|
||||
end
|
||||
|
||||
if handler == true then
|
||||
handler, hookSecure = nil, true
|
||||
end
|
||||
|
||||
hook(self, object, method, handler, false, false, false, hookSecure or false, "Usage: Hook([object], method, [handler], [hookSecure])")
|
||||
end
|
||||
|
||||
--- RawHook a function or a method on an object.
|
||||
-- The hook created will be a "raw hook", that means that your handler will completly replace
|
||||
-- the original function, and your handler has to call the original function (or not, depending on your intentions).\\
|
||||
-- The original function will be stored in `self.hooks[object][method]` or `self.hooks[functionName]` respectively.\\
|
||||
-- This type of hook can be used for all purposes, and is usually the most common case when you need to modify arguments
|
||||
-- or want to control execution of the original function.
|
||||
-- @paramsig [object], method, [handler], [hookSecure]
|
||||
-- @param object The object to hook a method from
|
||||
-- @param method If object was specified, the name of the method, or the name of the function to hook.
|
||||
-- @param handler The handler for the hook, a funcref or a method name. (Defaults to the name of the hooked function)
|
||||
-- @param hookSecure If true, AceHook will allow hooking of secure functions.
|
||||
-- @usage
|
||||
-- -- create an addon with AceHook embeded
|
||||
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("HookDemo", "AceHook-3.0")
|
||||
--
|
||||
-- function MyAddon:OnEnable()
|
||||
-- -- Hook ActionButton_UpdateHotkeys, overwriting the secure status
|
||||
-- self:RawHook("ActionButton_UpdateHotkeys", true)
|
||||
-- end
|
||||
--
|
||||
-- function MyAddon:ActionButton_UpdateHotkeys(button, type)
|
||||
-- if button:GetName() == "MyButton" then
|
||||
-- -- do stuff here
|
||||
-- else
|
||||
-- self.hooks.ActionButton_UpdateHotkeys(button, type)
|
||||
-- end
|
||||
-- end
|
||||
function AceHook:RawHook(object, method, handler, hookSecure)
|
||||
if type(object) == "string" then
|
||||
method, handler, hookSecure, object = object, method, handler, nil
|
||||
end
|
||||
|
||||
if handler == true then
|
||||
handler, hookSecure = nil, true
|
||||
end
|
||||
|
||||
hook(self, object, method, handler, false, false, true, hookSecure or false, "Usage: RawHook([object], method, [handler], [hookSecure])")
|
||||
end
|
||||
|
||||
--- SecureHook a function or a method on an object.
|
||||
-- This function is a wrapper around the `hooksecurefunc` function in the WoW API. Using AceHook
|
||||
-- extends the functionality of secure hooks, and adds the ability to unhook once the hook isn't
|
||||
-- required anymore, or the addon is being disabled.\\
|
||||
-- Secure Hooks should be used if the secure-status of the function is vital to its function,
|
||||
-- and taint would block execution. Secure Hooks are always called after the original function was called
|
||||
-- ("Post Hook"), and you cannot modify the arguments, return values or control the execution.
|
||||
-- @paramsig [object], method, [handler]
|
||||
-- @param object The object to hook a method from
|
||||
-- @param method If object was specified, the name of the method, or the name of the function to hook.
|
||||
-- @param handler The handler for the hook, a funcref or a method name. (Defaults to the name of the hooked function)
|
||||
function AceHook:SecureHook(object, method, handler)
|
||||
if type(object) == "string" then
|
||||
method, handler, object = object, method, nil
|
||||
end
|
||||
|
||||
hook(self, object, method, handler, false, true, false, false, "Usage: SecureHook([object], method, [handler])")
|
||||
end
|
||||
|
||||
--- Hook a script handler on a frame.
|
||||
-- The hook created will be a "safe hook", that means that your handler will be called
|
||||
-- before the hooked script ("Pre-Hook"), and you don't have to call the original function yourself,
|
||||
-- however you cannot stop the execution of the function, or modify any of the arguments/return values.\\
|
||||
-- This is the frame script equivalent of the :Hook safe-hook. It would typically be used to be notified
|
||||
-- when a certain event happens to a frame.
|
||||
-- @paramsig frame, script, [handler]
|
||||
-- @param frame The Frame to hook the script on
|
||||
-- @param script The script to hook
|
||||
-- @param handler The handler for the hook, a funcref or a method name. (Defaults to the name of the hooked script)
|
||||
-- @usage
|
||||
-- -- create an addon with AceHook embeded
|
||||
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("HookDemo", "AceHook-3.0")
|
||||
--
|
||||
-- function MyAddon:OnEnable()
|
||||
-- -- Hook the OnShow of FriendsFrame
|
||||
-- self:HookScript(FriendsFrame, "OnShow", "FriendsFrameOnShow")
|
||||
-- end
|
||||
--
|
||||
-- function MyAddon:FriendsFrameOnShow(frame)
|
||||
-- print("The FriendsFrame was shown!")
|
||||
-- end
|
||||
function AceHook:HookScript(frame, script, handler)
|
||||
hook(self, frame, script, handler, true, false, false, false, "Usage: HookScript(object, method, [handler])")
|
||||
end
|
||||
|
||||
--- RawHook a script handler on a frame.
|
||||
-- The hook created will be a "raw hook", that means that your handler will completly replace
|
||||
-- the original script, and your handler has to call the original script (or not, depending on your intentions).\\
|
||||
-- The original script will be stored in `self.hooks[frame][script]`.\\
|
||||
-- This type of hook can be used for all purposes, and is usually the most common case when you need to modify arguments
|
||||
-- or want to control execution of the original script.
|
||||
-- @paramsig frame, script, [handler]
|
||||
-- @param frame The Frame to hook the script on
|
||||
-- @param script The script to hook
|
||||
-- @param handler The handler for the hook, a funcref or a method name. (Defaults to the name of the hooked script)
|
||||
-- @usage
|
||||
-- -- create an addon with AceHook embeded
|
||||
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("HookDemo", "AceHook-3.0")
|
||||
--
|
||||
-- function MyAddon:OnEnable()
|
||||
-- -- Hook the OnShow of FriendsFrame
|
||||
-- self:RawHookScript(FriendsFrame, "OnShow", "FriendsFrameOnShow")
|
||||
-- end
|
||||
--
|
||||
-- function MyAddon:FriendsFrameOnShow(frame)
|
||||
-- -- Call the original function
|
||||
-- self.hooks[frame].OnShow(frame)
|
||||
-- -- Do our processing
|
||||
-- -- .. stuff
|
||||
-- end
|
||||
function AceHook:RawHookScript(frame, script, handler)
|
||||
hook(self, frame, script, handler, true, false, true, false, "Usage: RawHookScript(object, method, [handler])")
|
||||
end
|
||||
|
||||
--- SecureHook a script handler on a frame.
|
||||
-- This function is a wrapper around the `frame:HookScript` function in the WoW API. Using AceHook
|
||||
-- extends the functionality of secure hooks, and adds the ability to unhook once the hook isn't
|
||||
-- required anymore, or the addon is being disabled.\\
|
||||
-- Secure Hooks should be used if the secure-status of the function is vital to its function,
|
||||
-- and taint would block execution. Secure Hooks are always called after the original function was called
|
||||
-- ("Post Hook"), and you cannot modify the arguments, return values or control the execution.
|
||||
-- @paramsig frame, script, [handler]
|
||||
-- @param frame The Frame to hook the script on
|
||||
-- @param script The script to hook
|
||||
-- @param handler The handler for the hook, a funcref or a method name. (Defaults to the name of the hooked script)
|
||||
function AceHook:SecureHookScript(frame, script, handler)
|
||||
hook(self, frame, script, handler, true, true, false, false, "Usage: SecureHookScript(object, method, [handler])")
|
||||
end
|
||||
|
||||
--- Unhook from the specified function, method or script.
|
||||
-- @paramsig [obj], method
|
||||
-- @param obj The object or frame to unhook from
|
||||
-- @param method The name of the method, function or script to unhook from.
|
||||
function AceHook:Unhook(obj, method)
|
||||
local usage = "Usage: Unhook([obj], method)"
|
||||
if type(obj) == "string" then
|
||||
method, obj = obj, nil
|
||||
end
|
||||
|
||||
if obj and type(obj) ~= "table" then
|
||||
error(format("%s: 'obj' - expecting nil or table got %s", usage, type(obj)), 2)
|
||||
end
|
||||
if type(method) ~= "string" then
|
||||
error(format("%s: 'method' - expeting string got %s", usage, type(method)), 2)
|
||||
end
|
||||
|
||||
local uid
|
||||
if obj then
|
||||
uid = registry[self][obj] and registry[self][obj][method]
|
||||
else
|
||||
uid = registry[self][method]
|
||||
end
|
||||
|
||||
if not uid or not actives[uid] then
|
||||
-- Declining to error on an unneeded unhook since the end effect is the same and this would just be annoying.
|
||||
return false
|
||||
end
|
||||
|
||||
actives[uid], handlers[uid] = nil, nil
|
||||
|
||||
if obj then
|
||||
local tmp = registry[self][obj]
|
||||
tmp[method] = nil
|
||||
if not next(tmp) then
|
||||
del(tmp)
|
||||
registry[self][obj] = nil
|
||||
end
|
||||
|
||||
-- if the hook reference doesnt exist, then its a secure hook, just bail out and dont do any unhooking
|
||||
if not self.hooks[obj] or not self.hooks[obj][method] then return true end
|
||||
|
||||
if scripts[uid] and obj:GetScript(method) == uid then -- unhooks scripts
|
||||
obj:SetScript(method, self.hooks[obj][method] ~= donothing and self.hooks[obj][method] or nil)
|
||||
scripts[uid] = nil
|
||||
elseif obj and self.hooks[obj] and self.hooks[obj][method] and obj[method] == uid then -- unhooks methods
|
||||
obj[method] = self.hooks[obj][method]
|
||||
end
|
||||
|
||||
tmp = self.hooks[obj]
|
||||
tmp[method] = nil
|
||||
if not next(tmp) then
|
||||
del(tmp)
|
||||
self.hooks[obj] = nil
|
||||
end
|
||||
else
|
||||
registry[self][method] = nil
|
||||
|
||||
-- if self.hooks[method] doesn't exist, then this is a SecureHook, just bail out
|
||||
if not self.hooks[method] then return true end
|
||||
|
||||
if self.hooks[method] and _G[method] == uid then -- unhooks functions
|
||||
_G[method] = self.hooks[method]
|
||||
end
|
||||
|
||||
self.hooks[method] = nil
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
--- Unhook all existing hooks for this addon.
|
||||
function AceHook:UnhookAll()
|
||||
for key, value in pairs(registry[self]) do
|
||||
if type(key) == "table" then
|
||||
for method in pairs(value) do
|
||||
self:Unhook(key, method)
|
||||
end
|
||||
else
|
||||
self:Unhook(key)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- Check if the specific function, method or script is already hooked.
|
||||
-- @paramsig [obj], method
|
||||
-- @param obj The object or frame to unhook from
|
||||
-- @param method The name of the method, function or script to unhook from.
|
||||
function AceHook:IsHooked(obj, method)
|
||||
-- we don't check if registry[self] exists, this is done by evil magicks in the metatable
|
||||
if type(obj) == "string" then
|
||||
if registry[self][obj] and actives[registry[self][obj]] then
|
||||
return true, handlers[registry[self][obj]]
|
||||
end
|
||||
else
|
||||
if registry[self][obj] and registry[self][obj][method] and actives[registry[self][obj][method]] then
|
||||
return true, handlers[registry[self][obj][method]]
|
||||
end
|
||||
end
|
||||
|
||||
return false, nil
|
||||
end
|
||||
|
||||
--- Upgrade our old embeded
|
||||
for target, v in pairs( AceHook.embeded ) do
|
||||
AceHook:Embed( target )
|
||||
end
|
||||
@@ -0,0 +1,3 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="AceHook-3.0.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,137 @@
|
||||
--- **AceLocale-3.0** manages localization in addons, allowing for multiple locale to be registered with fallback to the base locale for untranslated strings.
|
||||
-- @class file
|
||||
-- @name AceLocale-3.0
|
||||
-- @release $Id: AceLocale-3.0.lua 1035 2011-07-09 03:20:13Z kaelten $
|
||||
local MAJOR,MINOR = "AceLocale-3.0", 6
|
||||
|
||||
local AceLocale, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
|
||||
|
||||
if not AceLocale then return end -- no upgrade needed
|
||||
|
||||
-- Lua APIs
|
||||
local assert, tostring, error = assert, tostring, error
|
||||
local getmetatable, setmetatable, rawset, rawget = getmetatable, setmetatable, rawset, rawget
|
||||
|
||||
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
|
||||
-- List them here for Mikk's FindGlobals script
|
||||
-- GLOBALS: GAME_LOCALE, geterrorhandler
|
||||
|
||||
local gameLocale = GetLocale()
|
||||
if gameLocale == "enGB" then
|
||||
gameLocale = "enUS"
|
||||
end
|
||||
|
||||
AceLocale.apps = AceLocale.apps or {} -- array of ["AppName"]=localetableref
|
||||
AceLocale.appnames = AceLocale.appnames or {} -- array of [localetableref]="AppName"
|
||||
|
||||
-- This metatable is used on all tables returned from GetLocale
|
||||
local readmeta = {
|
||||
__index = function(self, key) -- requesting totally unknown entries: fire off a nonbreaking error and return key
|
||||
rawset(self, key, key) -- only need to see the warning once, really
|
||||
geterrorhandler()(MAJOR..": "..tostring(AceLocale.appnames[self])..": Missing entry for '"..tostring(key).."'")
|
||||
return key
|
||||
end
|
||||
}
|
||||
|
||||
-- This metatable is used on all tables returned from GetLocale if the silent flag is true, it does not issue a warning on unknown keys
|
||||
local readmetasilent = {
|
||||
__index = function(self, key) -- requesting totally unknown entries: return key
|
||||
rawset(self, key, key) -- only need to invoke this function once
|
||||
return key
|
||||
end
|
||||
}
|
||||
|
||||
-- Remember the locale table being registered right now (it gets set by :NewLocale())
|
||||
-- NOTE: Do never try to register 2 locale tables at once and mix their definition.
|
||||
local registering
|
||||
|
||||
-- local assert false function
|
||||
local assertfalse = function() assert(false) end
|
||||
|
||||
-- This metatable proxy is used when registering nondefault locales
|
||||
local writeproxy = setmetatable({}, {
|
||||
__newindex = function(self, key, value)
|
||||
rawset(registering, key, value == true and key or value) -- assigning values: replace 'true' with key string
|
||||
end,
|
||||
__index = assertfalse
|
||||
})
|
||||
|
||||
-- This metatable proxy is used when registering the default locale.
|
||||
-- It refuses to overwrite existing values
|
||||
-- Reason 1: Allows loading locales in any order
|
||||
-- Reason 2: If 2 modules have the same string, but only the first one to be
|
||||
-- loaded has a translation for the current locale, the translation
|
||||
-- doesn't get overwritten.
|
||||
--
|
||||
local writedefaultproxy = setmetatable({}, {
|
||||
__newindex = function(self, key, value)
|
||||
if not rawget(registering, key) then
|
||||
rawset(registering, key, value == true and key or value)
|
||||
end
|
||||
end,
|
||||
__index = assertfalse
|
||||
})
|
||||
|
||||
--- Register a new locale (or extend an existing one) for the specified application.
|
||||
-- :NewLocale will return a table you can fill your locale into, or nil if the locale isn't needed for the players
|
||||
-- game locale.
|
||||
-- @paramsig application, locale[, isDefault[, silent]]
|
||||
-- @param application Unique name of addon / module
|
||||
-- @param locale Name of the locale to register, e.g. "enUS", "deDE", etc.
|
||||
-- @param isDefault If this is the default locale being registered (your addon is written in this language, generally enUS)
|
||||
-- @param silent If true, the locale will not issue warnings for missing keys. Must be set on the first locale registered. If set to "raw", nils will be returned for unknown keys (no metatable used).
|
||||
-- @usage
|
||||
-- -- enUS.lua
|
||||
-- local L = LibStub("AceLocale-3.0"):NewLocale("TestLocale", "enUS", true)
|
||||
-- L["string1"] = true
|
||||
--
|
||||
-- -- deDE.lua
|
||||
-- local L = LibStub("AceLocale-3.0"):NewLocale("TestLocale", "deDE")
|
||||
-- if not L then return end
|
||||
-- L["string1"] = "Zeichenkette1"
|
||||
-- @return Locale Table to add localizations to, or nil if the current locale is not required.
|
||||
function AceLocale:NewLocale(application, locale, isDefault, silent)
|
||||
|
||||
-- GAME_LOCALE allows translators to test translations of addons without having that wow client installed
|
||||
local gameLocale = GAME_LOCALE or gameLocale
|
||||
|
||||
local app = AceLocale.apps[application]
|
||||
|
||||
if silent and app and getmetatable(app) ~= readmetasilent then
|
||||
geterrorhandler()("Usage: NewLocale(application, locale[, isDefault[, silent]]): 'silent' must be specified for the first locale registered")
|
||||
end
|
||||
|
||||
if not app then
|
||||
if silent=="raw" then
|
||||
app = {}
|
||||
else
|
||||
app = setmetatable({}, silent and readmetasilent or readmeta)
|
||||
end
|
||||
AceLocale.apps[application] = app
|
||||
AceLocale.appnames[app] = application
|
||||
end
|
||||
|
||||
if locale ~= gameLocale and not isDefault then
|
||||
return nil -- nop, we don't need these translations
|
||||
end
|
||||
|
||||
registering = app -- remember globally for writeproxy and writedefaultproxy
|
||||
|
||||
if isDefault then
|
||||
return writedefaultproxy
|
||||
end
|
||||
|
||||
return writeproxy
|
||||
end
|
||||
|
||||
--- Returns localizations for the current locale (or default locale if translations are missing).
|
||||
-- Errors if nothing is registered (spank developer, not just a missing translation)
|
||||
-- @param application Unique name of addon / module
|
||||
-- @param silent If true, the locale is optional, silently return nil if it's not found (defaults to false, optional)
|
||||
-- @return The locale table for the current language.
|
||||
function AceLocale:GetLocale(application, silent)
|
||||
if not silent and not AceLocale.apps[application] then
|
||||
error("Usage: GetLocale(application[, silent]): 'application' - No locales registered for '"..tostring(application).."'", 2)
|
||||
end
|
||||
return AceLocale.apps[application]
|
||||
end
|
||||
@@ -0,0 +1,3 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="AceLocale-3.0.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,286 @@
|
||||
--- **AceSerializer-3.0** can serialize any variable (except functions or userdata) into a string format,
|
||||
-- that can be send over the addon comm channel. AceSerializer was designed to keep all data intact, especially
|
||||
-- very large numbers or floating point numbers, and table structures. The only caveat currently is, that multiple
|
||||
-- references to the same table will be send individually.
|
||||
--
|
||||
-- **AceSerializer-3.0** can be embeded into your addon, either explicitly by calling AceSerializer:Embed(MyAddon) or by
|
||||
-- specifying it as an embeded library in your AceAddon. All functions will be available on your addon object
|
||||
-- and can be accessed directly, without having to explicitly call AceSerializer itself.\\
|
||||
-- It is recommended to embed AceSerializer, otherwise you'll have to specify a custom `self` on all calls you
|
||||
-- make into AceSerializer.
|
||||
-- @class file
|
||||
-- @name AceSerializer-3.0
|
||||
-- @release $Id: AceSerializer-3.0.lua 1135 2015-09-19 20:39:16Z nevcairiel $
|
||||
local MAJOR,MINOR = "AceSerializer-3.0", 5
|
||||
local AceSerializer, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
|
||||
|
||||
if not AceSerializer then return end
|
||||
|
||||
-- Lua APIs
|
||||
local strbyte, strchar, gsub, gfind, format = string.byte, string.char, string.gsub, string.gfind, string.format
|
||||
local assert, error, pcall = assert, error, pcall
|
||||
local type, tostring, tonumber = type, tostring, tonumber
|
||||
local pairs, select, frexp = pairs, select, math.frexp
|
||||
local tconcat, tgetn = table.concat, table.getn
|
||||
|
||||
-- quick copies of string representations of wonky numbers
|
||||
local inf = 1/0
|
||||
|
||||
local serNaN -- can't do this in 4.3, see ace3 ticket 268
|
||||
local serInf, serInfMac = "1.#INF", "inf"
|
||||
local serNegInf, serNegInfMac = "-1.#INF", "-inf"
|
||||
|
||||
|
||||
-- Serialization functions
|
||||
|
||||
local function SerializeStringHelper(ch) -- Used by SerializeValue for strings
|
||||
-- We use \126 ("~") as an escape character for all nonprints plus a few more
|
||||
local n = strbyte(ch)
|
||||
if n==30 then -- v3 / ticket 115: catch a nonprint that ends up being "~^" when encoded... DOH
|
||||
return "\126\122"
|
||||
elseif n<=32 then -- nonprint + space
|
||||
return "\126"..strchar(n+64)
|
||||
elseif n==94 then -- value separator
|
||||
return "\126\125"
|
||||
elseif n==126 then -- our own escape character
|
||||
return "\126\124"
|
||||
elseif n==127 then -- nonprint (DEL)
|
||||
return "\126\123"
|
||||
else
|
||||
assert(false) -- can't be reached if caller uses a sane regex
|
||||
end
|
||||
end
|
||||
|
||||
local function SerializeValue(v, res, nres)
|
||||
-- We use "^" as a value separator, followed by one byte for type indicator
|
||||
local t=type(v)
|
||||
|
||||
if t=="string" then -- ^S = string (escaped to remove nonprints, "^"s, etc)
|
||||
res[nres+1] = "^S"
|
||||
res[nres+2] = gsub(v,"[%c \94\126\127]", SerializeStringHelper)
|
||||
nres=nres+2
|
||||
|
||||
elseif t=="number" then -- ^N = number (just tostring()ed) or ^F (float components)
|
||||
local str = tostring(v)
|
||||
if tonumber(str)==v --[[not in 4.3 or str==serNaN]] then
|
||||
-- translates just fine, transmit as-is
|
||||
res[nres+1] = "^N"
|
||||
res[nres+2] = str
|
||||
nres=nres+2
|
||||
elseif v == inf or v == -inf then
|
||||
res[nres+1] = "^N"
|
||||
res[nres+2] = v == inf and serInf or serNegInf
|
||||
nres=nres+2
|
||||
else
|
||||
local m,e = frexp(v)
|
||||
res[nres+1] = "^F"
|
||||
res[nres+2] = format("%.0f",m*2^53) -- force mantissa to become integer (it's originally 0.5--0.9999)
|
||||
res[nres+3] = "^f"
|
||||
res[nres+4] = tostring(e-53) -- adjust exponent to counteract mantissa manipulation
|
||||
nres=nres+4
|
||||
end
|
||||
|
||||
elseif t=="table" then -- ^T...^t = table (list of key,value pairs)
|
||||
nres=nres+1
|
||||
res[nres] = "^T"
|
||||
for k,v in pairs(v) do
|
||||
nres = SerializeValue(k, res, nres)
|
||||
nres = SerializeValue(v, res, nres)
|
||||
end
|
||||
nres=nres+1
|
||||
res[nres] = "^t"
|
||||
|
||||
elseif t=="boolean" then -- ^B = true, ^b = false
|
||||
nres=nres+1
|
||||
if v then
|
||||
res[nres] = "^B" -- true
|
||||
else
|
||||
res[nres] = "^b" -- false
|
||||
end
|
||||
|
||||
elseif t=="nil" then -- ^Z = nil (zero, "N" was taken :P)
|
||||
nres=nres+1
|
||||
res[nres] = "^Z"
|
||||
|
||||
else
|
||||
error(MAJOR..": Cannot serialize a value of type '"..t.."'") -- can't produce error on right level, this is wildly recursive
|
||||
end
|
||||
|
||||
return nres
|
||||
end
|
||||
|
||||
|
||||
|
||||
local serializeTbl = { "^1" } -- "^1" = Hi, I'm data serialized by AceSerializer protocol rev 1
|
||||
|
||||
--- Serialize the data passed into the function.
|
||||
-- Takes a list of values (strings, numbers, booleans, nils, tables)
|
||||
-- and returns it in serialized form (a string).\\
|
||||
-- May throw errors on invalid data types.
|
||||
-- @param ... List of values to serialize
|
||||
-- @return The data in its serialized form (string)
|
||||
function AceSerializer:Serialize(...)
|
||||
local nres = 1
|
||||
for i = 1,tgetn(arg) do
|
||||
local v = arg[i]
|
||||
nres = SerializeValue(v, serializeTbl, nres)
|
||||
end
|
||||
|
||||
serializeTbl[nres+1] = "^^" -- "^^" = End of serialized data
|
||||
|
||||
return tconcat(serializeTbl, "", 1, nres+1)
|
||||
end
|
||||
|
||||
-- Deserialization functions
|
||||
local function DeserializeStringHelper(escape)
|
||||
if escape<"~\122" then
|
||||
return strchar(strbyte(escape,2,2)-64)
|
||||
elseif escape=="~\122" then -- v3 / ticket 115: special case encode since 30+64=94 ("^") - OOPS.
|
||||
return "\030"
|
||||
elseif escape=="~\123" then
|
||||
return "\127"
|
||||
elseif escape=="~\124" then
|
||||
return "\126"
|
||||
elseif escape=="~\125" then
|
||||
return "\94"
|
||||
end
|
||||
error("DeserializeStringHelper got called for '"..escape.."'?!?") -- can't be reached unless regex is screwed up
|
||||
end
|
||||
|
||||
local function DeserializeNumberHelper(number)
|
||||
--[[ not in 4.3 if number == serNaN then
|
||||
return 0/0
|
||||
else]]if number == serNegInf or number == serNegInfMac then
|
||||
return -inf
|
||||
elseif number == serInf or number == serInfMac then
|
||||
return inf
|
||||
else
|
||||
return tonumber(number)
|
||||
end
|
||||
end
|
||||
|
||||
-- DeserializeValue: worker function for :Deserialize()
|
||||
-- It works in two modes:
|
||||
-- Main (top-level) mode: Deserialize a list of values and return them all
|
||||
-- Recursive (table) mode: Deserialize only a single value (_may_ of course be another table with lots of subvalues in it)
|
||||
--
|
||||
-- The function _always_ works recursively due to having to build a list of values to return
|
||||
--
|
||||
-- Callers are expected to pcall(DeserializeValue) to trap errors
|
||||
|
||||
local function DeserializeValue(iter,single,ctl,data)
|
||||
|
||||
if not single then
|
||||
ctl,data = iter()
|
||||
end
|
||||
|
||||
if not ctl then
|
||||
error("Supplied data misses AceSerializer terminator ('^^')")
|
||||
end
|
||||
|
||||
if ctl=="^^" then
|
||||
-- ignore extraneous data
|
||||
return
|
||||
end
|
||||
|
||||
local res
|
||||
|
||||
if ctl=="^S" then
|
||||
res = gsub(data, "~.", DeserializeStringHelper)
|
||||
elseif ctl=="^N" then
|
||||
res = DeserializeNumberHelper(data)
|
||||
if not res then
|
||||
error("Invalid serialized number: '"..tostring(data).."'")
|
||||
end
|
||||
elseif ctl=="^F" then -- ^F<mantissa>^f<exponent>
|
||||
local ctl2,e = iter()
|
||||
if ctl2~="^f" then
|
||||
error("Invalid serialized floating-point number, expected '^f', not '"..tostring(ctl2).."'")
|
||||
end
|
||||
local m=tonumber(data)
|
||||
e=tonumber(e)
|
||||
if not (m and e) then
|
||||
error("Invalid serialized floating-point number, expected mantissa and exponent, got '"..tostring(m).."' and '"..tostring(e).."'")
|
||||
end
|
||||
res = m*(2^e)
|
||||
elseif ctl=="^B" then -- yeah yeah ignore data portion
|
||||
res = true
|
||||
elseif ctl=="^b" then -- yeah yeah ignore data portion
|
||||
res = false
|
||||
elseif ctl=="^Z" then -- yeah yeah ignore data portion
|
||||
res = nil
|
||||
elseif ctl=="^T" then
|
||||
-- ignore ^T's data, future extensibility?
|
||||
res = {}
|
||||
local k,v
|
||||
while true do
|
||||
ctl,data = iter()
|
||||
if ctl=="^t" then break end -- ignore ^t's data
|
||||
k = DeserializeValue(iter,true,ctl,data)
|
||||
if k==nil then
|
||||
error("Invalid AceSerializer table format (no table end marker)")
|
||||
end
|
||||
ctl,data = iter()
|
||||
v = DeserializeValue(iter,true,ctl,data)
|
||||
if v==nil then
|
||||
error("Invalid AceSerializer table format (no table end marker)")
|
||||
end
|
||||
res[k]=v
|
||||
end
|
||||
else
|
||||
error("Invalid AceSerializer control code '"..ctl.."'")
|
||||
end
|
||||
|
||||
if not single then
|
||||
return res,DeserializeValue(iter)
|
||||
else
|
||||
return res
|
||||
end
|
||||
end
|
||||
|
||||
--- Deserializes the data into its original values.
|
||||
-- Accepts serialized data, ignoring all control characters and whitespace.
|
||||
-- @param str The serialized data (from :Serialize)
|
||||
-- @return true followed by a list of values, OR false followed by an error message
|
||||
function AceSerializer:Deserialize(str)
|
||||
str = gsub(str, "[%c ]", "") -- ignore all control characters; nice for embedding in email and stuff
|
||||
|
||||
local iter = gfind(str, "(^.)([^^]*)") -- Any ^x followed by string of non-^
|
||||
local ctl,data = iter()
|
||||
if not ctl or ctl~="^1" then
|
||||
-- we purposefully ignore the data portion of the start code, it can be used as an extension mechanism
|
||||
return false, "Supplied data is not AceSerializer data (rev 1)"
|
||||
end
|
||||
|
||||
return pcall(DeserializeValue, iter)
|
||||
end
|
||||
|
||||
|
||||
----------------------------------------
|
||||
-- Base library stuff
|
||||
----------------------------------------
|
||||
|
||||
AceSerializer.internals = { -- for test scripts
|
||||
SerializeValue = SerializeValue,
|
||||
SerializeStringHelper = SerializeStringHelper,
|
||||
}
|
||||
|
||||
local mixins = {
|
||||
"Serialize",
|
||||
"Deserialize",
|
||||
}
|
||||
|
||||
AceSerializer.embeds = AceSerializer.embeds or {}
|
||||
|
||||
function AceSerializer:Embed(target)
|
||||
for k, v in pairs(mixins) do
|
||||
target[v] = self[v]
|
||||
end
|
||||
self.embeds[target] = true
|
||||
return target
|
||||
end
|
||||
|
||||
-- Update embeds
|
||||
for target, v in pairs(AceSerializer.embeds) do
|
||||
AceSerializer:Embed(target)
|
||||
end
|
||||
@@ -0,0 +1,3 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="AceSerializer-3.0.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,379 @@
|
||||
--- **AceTimer-3.0** provides a central facility for registering timers.
|
||||
-- AceTimer supports one-shot timers and repeating timers. All timers are stored in an efficient
|
||||
-- data structure that allows easy dispatching and fast rescheduling. Timers can be registered
|
||||
-- or canceled at any time, even from within a running timer, without conflict or large overhead.\\
|
||||
-- AceTimer is currently limited to firing timers at a frequency of 0.01s as this is what the WoW timer API
|
||||
-- restricts us to.
|
||||
--
|
||||
-- All `:Schedule` functions will return a handle to the current timer, which you will need to store if you
|
||||
-- need to cancel the timer you just registered.
|
||||
--
|
||||
-- **AceTimer-3.0** can be embeded into your addon, either explicitly by calling AceTimer:Embed(MyAddon) or by
|
||||
-- specifying it as an embeded library in your AceAddon. All functions will be available on your addon object
|
||||
-- and can be accessed directly, without having to explicitly call AceTimer itself.\\
|
||||
-- It is recommended to embed AceTimer, otherwise you'll have to specify a custom `self` on all calls you
|
||||
-- make into AceTimer.
|
||||
-- @class file
|
||||
-- @name AceTimer-3.0
|
||||
-- @release $Id: AceTimer-3.0.lua 1119 2014-10-14 17:23:29Z nevcairiel $
|
||||
|
||||
local MAJOR, MINOR = "AceTimer-3.0", 17 -- Bump minor on changes
|
||||
local AceTimer, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
|
||||
|
||||
if not AceTimer then return end -- No upgrade needed
|
||||
|
||||
local AceCore = LibStub("AceCore-3.0")
|
||||
local safecall = AceCore.safecall
|
||||
|
||||
AceTimer.counter = AceTimer.counter or {}
|
||||
AceTimer.hash = AceTimer.hash or {} -- Array of [1..BUCKETS] = linked list of timers (using .next member)
|
||||
AceTimer.activeTimers = AceTimer.activeTimers or {} -- Active timer list
|
||||
AceTimer.frame = AceTimer.frame or CreateFrame("Frame", "AceTimer30Frame")
|
||||
|
||||
local counter = AceTimer.counter
|
||||
local activeTimers = AceTimer.activeTimers -- Upvalue our private data
|
||||
local timerFrame = AceTimer.frame
|
||||
|
||||
-- Lua APIs
|
||||
local type, unpack, next, error = type, unpack, next, error
|
||||
local floor, max, min, mod = math.floor, math.max, math.min, math.mod
|
||||
local tostring = tostring
|
||||
|
||||
-- WoW APIs
|
||||
local GetTime = GetTime
|
||||
|
||||
--[[
|
||||
Timers will not be fired more often than HZ-1 times per second.
|
||||
Keep at intended speed PLUS ONE or we get bitten by floating point rounding errors (n.5 + 0.1 can be n.599999)
|
||||
If this is ever LOWERED, all existing timers need to be enforced to have a delay >= 1/HZ on lib upgrade.
|
||||
If this number is ever changed, all entries need to be rehashed on lib upgrade.
|
||||
]]
|
||||
local HZ = 11
|
||||
local minDelay = 1/(HZ-1)
|
||||
|
||||
--[[
|
||||
Prime for good distribution
|
||||
If this number is ever changed, all entries need to be rehashed on lib upgrade.
|
||||
]]
|
||||
local BUCKETS = 131
|
||||
|
||||
local hash = AceTimer.hash
|
||||
for i=1,BUCKETS do
|
||||
hash[i] = hash[i] or false -- make it an integer-indexed array; it's faster than hashes
|
||||
end
|
||||
|
||||
local new, del
|
||||
do
|
||||
local list = setmetatable({}, {__mode = "k"})
|
||||
function new(self, loop, func, delay, argc,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10)
|
||||
local name = loop and "ScheduleRepeatingTimer" or "ScheduleTimer"
|
||||
if self == AceTimer then
|
||||
error(MAJOR..": " .. name .. "(callback, delay, argc, args...): use your own 'self'", 3)
|
||||
end
|
||||
if not func or not delay then
|
||||
error(MAJOR..": " .. name .. "(callback, delay, argc, args...): 'callback' and 'delay' must have set values.", 3)
|
||||
end
|
||||
if argc and (type(argc) ~= "number" or floor(argc) ~= argc) then
|
||||
error(MAJOR..": " .. name .. "(callback, delay, argc, args...): 'argc' must be an integer.", 3)
|
||||
end
|
||||
if type(func) == "string" then
|
||||
if type(self) ~= "table" then
|
||||
error(MAJOR..": " .. name .. "(callback, delay, argc, args...): 'self' - must be a table.", 3)
|
||||
elseif type(self[func]) ~= "function" then
|
||||
error(MAJOR..": " .. name .. "(callback, delay, argc, args...): Tried to register '"..func.."' as the callback, but it is not a method.", 3)
|
||||
end
|
||||
elseif type(func) ~= "function" then
|
||||
error(MAJOR..": " .. name .. "(callback, delay, argc, args...): Tried to register '"..tostring(func).."' as the callback, but it is not a function.", 3)
|
||||
end
|
||||
|
||||
if delay < minDelay then
|
||||
delay = minDelay
|
||||
end
|
||||
|
||||
-- Create and stuff timer in the correct hash bucket
|
||||
local now = GetTime()
|
||||
|
||||
local timer = next(list) or {}
|
||||
list[timer] = nil
|
||||
|
||||
timer.object = self
|
||||
timer.func = func
|
||||
timer.delay = delay
|
||||
timer.status = loop and "loop" or "once"
|
||||
timer.ends = now + delay
|
||||
timer.argsCount = argc or 0
|
||||
timer[1] = a1
|
||||
timer[2] = a2
|
||||
timer[3] = a3
|
||||
timer[4] = a4
|
||||
timer[5] = a5
|
||||
timer[6] = a6
|
||||
timer[7] = a7
|
||||
timer[8] = a8
|
||||
timer[9] = a9
|
||||
timer[10] = a10
|
||||
|
||||
local bucket = floor(mod((now+delay)*HZ,BUCKETS)) + 1
|
||||
timer.next = hash[bucket]
|
||||
hash[bucket] = timer
|
||||
|
||||
local id = tostring(timer) -- user has only access to the id but not the table itself
|
||||
activeTimers[id] = timer
|
||||
|
||||
counter[self] = (counter[self] or 0) + 1
|
||||
|
||||
timerFrame:Show()
|
||||
return id
|
||||
end
|
||||
|
||||
function del(t)
|
||||
local id = tostring(t)
|
||||
activeTimers[id] = nil
|
||||
if not next(activeTimers) then
|
||||
timerFrame:Hide()
|
||||
end
|
||||
local self = t.object
|
||||
for k in pairs(t) do t[k] = nil end
|
||||
list[t] = true
|
||||
if counter[self] then
|
||||
counter[self] = counter[self] - 1
|
||||
else
|
||||
counter[self] = nil
|
||||
end
|
||||
end
|
||||
end -- new, del
|
||||
|
||||
--- Schedule a new one-shot timer.
|
||||
-- The timer will fire once in `delay` seconds, unless canceled before.
|
||||
-- @param callback Callback function for the timer pulse (funcref or method name).
|
||||
-- @param delay Delay for the timer, in seconds.
|
||||
-- @param argc The numbers of arguments to be passed to the callback function
|
||||
-- @param a1,...,a10 The arguments
|
||||
-- @usage
|
||||
-- MyAddOn = LibStub("AceAddon-3.0"):NewAddon("MyAddOn", "AceTimer-3.0")
|
||||
--
|
||||
-- function MyAddOn:OnEnable()
|
||||
-- self:ScheduleTimer("TimerFeedback", 5)
|
||||
-- end
|
||||
--
|
||||
-- function MyAddOn:TimerFeedback()
|
||||
-- print("5 seconds passed")
|
||||
-- end
|
||||
function AceTimer:ScheduleTimer(func, delay, argc, ...)
|
||||
return new(self, nil, func, delay, argc, unpack(arg))
|
||||
end
|
||||
|
||||
--- Schedule a repeating timer.
|
||||
-- The timer will fire every `delay` seconds, until canceled.
|
||||
-- @param callback Callback function for the timer pulse (funcref or method name).
|
||||
-- @param delay Delay for the timer, in seconds.
|
||||
-- @param argc The numbers of arguments to be passed to the callback function
|
||||
-- @param a1,...,a10 The arguments
|
||||
-- @usage
|
||||
-- MyAddOn = LibStub("AceAddon-3.0"):NewAddon("MyAddOn", "AceTimer-3.0")
|
||||
--
|
||||
-- function MyAddOn:OnEnable()
|
||||
-- self.timerCount = 0
|
||||
-- self.testTimer = self:ScheduleRepeatingTimer("TimerFeedback", 5)
|
||||
-- end
|
||||
--
|
||||
-- function MyAddOn:TimerFeedback()
|
||||
-- self.timerCount = self.timerCount + 1
|
||||
-- print(("%d seconds passed"):format(5 * self.timerCount))
|
||||
-- -- run 30 seconds in total
|
||||
-- if self.timerCount == 6 then
|
||||
-- self:CancelTimer(self.testTimer)
|
||||
-- end
|
||||
-- end
|
||||
function AceTimer:ScheduleRepeatingTimer(func, delay, argc, ...)
|
||||
return new(self, true, func, delay, argc, unpack(arg))
|
||||
end
|
||||
|
||||
--- Cancels a timer with the given id, registered by the same addon object as used for `:ScheduleTimer`
|
||||
-- Both one-shot and repeating timers can be canceled with this function, as long as the `id` is valid
|
||||
-- and the timer has not fired yet or was canceled before.
|
||||
-- @param id The id of the timer, as returned by `:ScheduleTimer` or `:ScheduleRepeatingTimer`
|
||||
function AceTimer:CancelTimer(id)
|
||||
local timer = activeTimers[id]
|
||||
|
||||
if not timer then
|
||||
return false
|
||||
else
|
||||
-- Ace3v: the timer will always be collected in the next update but not here
|
||||
-- this is necessary for AceBucket to determinate if the bucket has been unregistered
|
||||
-- in the callback
|
||||
timer.status = nil
|
||||
activeTimers[id] = nil
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
--- Cancels all timers registered to the current addon object ('self')
|
||||
function AceTimer:CancelAllTimers()
|
||||
if type(self) ~= "table" then
|
||||
error(MAJOR..": CancelAllTimers(): 'self' - must be a table",2)
|
||||
end
|
||||
if self == AceTimer then
|
||||
error(MAJOR..": CancelAllTimers(): supply a meaningful 'self'", 2)
|
||||
end
|
||||
|
||||
for k,v in pairs(activeTimers) do
|
||||
if v.object == self then
|
||||
AceTimer.CancelTimer(self, k)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- Returns the time left for a timer with the given id, registered by the current addon object ('self').
|
||||
-- This function will return 0 when the id is invalid.
|
||||
-- @param id The id of the timer, as returned by `:ScheduleTimer` or `:ScheduleRepeatingTimer`
|
||||
-- @return The time left on the timer.
|
||||
function AceTimer:TimeLeft(id)
|
||||
local timer = activeTimers[id]
|
||||
if not timer then
|
||||
return 0
|
||||
else
|
||||
return timer.ends - GetTime()
|
||||
end
|
||||
end
|
||||
|
||||
function AceTimer:TimerStatus(id)
|
||||
local timer = activeTimers[id]
|
||||
if not timer then
|
||||
return nil
|
||||
else
|
||||
return timer.status
|
||||
end
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------
|
||||
-- Embed handling
|
||||
|
||||
AceTimer.embeds = AceTimer.embeds or {}
|
||||
|
||||
local mixins = {
|
||||
"ScheduleTimer", "ScheduleRepeatingTimer",
|
||||
"CancelTimer", "CancelAllTimers",
|
||||
"TimeLeft"
|
||||
}
|
||||
|
||||
function AceTimer:Embed(target)
|
||||
AceTimer.embeds[target] = true
|
||||
for _,v in pairs(mixins) do
|
||||
target[v] = AceTimer[v]
|
||||
end
|
||||
return target
|
||||
end
|
||||
|
||||
-- AceTimer:OnEmbedDisable(target)
|
||||
-- target (object) - target object that AceTimer is embedded in.
|
||||
--
|
||||
-- cancel all timers registered for the object
|
||||
function AceTimer:OnEmbedDisable(target)
|
||||
target:CancelAllTimers()
|
||||
end
|
||||
|
||||
for addon in pairs(AceTimer.embeds) do
|
||||
AceTimer:Embed(addon)
|
||||
end
|
||||
|
||||
-- --------------------------------------------------------------------
|
||||
-- OnUpdate handler
|
||||
--
|
||||
-- traverse buckets, always chasing "now", and fire timers that have expired
|
||||
local lastint = floor(GetTime() * HZ)
|
||||
local function OnUpdate()
|
||||
local now = GetTime()
|
||||
local nowint = floor(now * HZ)
|
||||
|
||||
-- Have we passed into a new hash bucket?
|
||||
if nowint == lastint then return end
|
||||
|
||||
local soon = now + 1 -- +1 is safe as long as 1 < HZ < BUCKETS/2
|
||||
|
||||
-- Pass through each bucket at most once
|
||||
-- Happens on e.g. instance loads, but COULD happen on high local load situations also
|
||||
for curint = (max(lastint, nowint-BUCKETS) + 1), nowint do -- loop until we catch up with "now", usually only 1 iteratio
|
||||
local curbucket = mod(curint,BUCKETS) + 1 -- Ace3v: both int so no floor here
|
||||
-- Yank the list of timers out of the bucket and empty it. This allows reinsertion in the currently-processed bucket from callbacks.
|
||||
local nexttimer = hash[curbucket]
|
||||
hash[curbucket] = false -- false rather than nil to prevent the array from becoming a hash
|
||||
|
||||
while nexttimer do
|
||||
local timer = nexttimer
|
||||
nexttimer = timer.next
|
||||
local status = timer.status
|
||||
if not status then
|
||||
del(timer)
|
||||
else
|
||||
local ends = timer.ends
|
||||
if (status == "loop" or status == "once") and ends < soon then
|
||||
local object = timer.object
|
||||
local callback = timer.func
|
||||
if type(callback) == "string" then
|
||||
callback = (type(object) == "table") and object[callback]
|
||||
if type(callback) == "function" then
|
||||
safecall(callback, timer.argsCount+1, object,
|
||||
timer[1], timer[2], timer[3], timer[4], timer[5],
|
||||
timer[6], timer[7], timer[8], timer[9], timer[10])
|
||||
else
|
||||
status = "once"
|
||||
end
|
||||
elseif type(callback) == "function" then
|
||||
safecall(callback, timer.argsCount,
|
||||
timer[1], timer[2], timer[3], timer[4], timer[5],
|
||||
timer[6], timer[7], timer[8], timer[9], timer[10])
|
||||
else
|
||||
-- probably nilled out by CancelTimer
|
||||
status = "once" -- don't reschedule it
|
||||
end
|
||||
|
||||
if status == "once" then
|
||||
del(timer)
|
||||
else
|
||||
local delay = timer.delay
|
||||
local newends = ends + delay
|
||||
if newends < now then -- Keep lag from making us firing a timer unnecessarily. (Note that this still won't catch too-short-delay timers though.)
|
||||
newends = now + delay
|
||||
end
|
||||
timer.ends = newends
|
||||
-- add next timer execution to the correct bucket
|
||||
local bucket = floor(mod(newends*HZ,BUCKETS)) + 1
|
||||
timer.next = hash[bucket]
|
||||
hash[bucket] = timer
|
||||
end
|
||||
else
|
||||
-- reinsert (yeah, somewhat expensive, but shouldn't be happening too often either due to hash distribution)
|
||||
timer.next = hash[curbucket]
|
||||
hash[curbucket] = timer
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
lastint = nowint
|
||||
end
|
||||
|
||||
local lastchecked = nil
|
||||
local function OnEvent()
|
||||
if event ~= "PLAYER_REGEN_ENABLED" then return end
|
||||
|
||||
local addon = next(counter, lastchecked)
|
||||
if not addon then
|
||||
addon = next(counter)
|
||||
end
|
||||
lastchecked = addon
|
||||
if not addon then -- should only happen if counter is empty
|
||||
return
|
||||
end
|
||||
|
||||
local n = counter[addon]
|
||||
if n > BUCKETS then
|
||||
DEFAULT_CHAT_FRAME:AddMessage(MAJOR..": Warning: The addon/module '"..tostring(addon).."' has "..tostring(n).." live timers. Surely that's not intended?")
|
||||
end
|
||||
end
|
||||
|
||||
timerFrame:SetScript("OnUpdate", OnUpdate)
|
||||
timerFrame:SetScript("OnEvent", OnEvent)
|
||||
timerFrame:RegisterEvent("PLAYER_REGEN_ENABLED")
|
||||
timerFrame:Hide()
|
||||
@@ -0,0 +1,3 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="AceTimer-3.0.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,234 @@
|
||||
--[[ $Id: CallbackHandler-1.0.lua 18 2014-10-16 02:52:20Z mikk $ ]]
|
||||
local MAJOR, MINOR = "CallbackHandler-1.0", 6
|
||||
local CallbackHandler = LibStub:NewLibrary(MAJOR, MINOR)
|
||||
|
||||
if not CallbackHandler then return end -- No upgrade needed
|
||||
|
||||
local meta = {__index = function(tbl, key) tbl[key] = {} return tbl[key] end}
|
||||
|
||||
-- Lua APIs
|
||||
local tconcat = table.concat
|
||||
local assert, error, loadstring = assert, error, loadstring
|
||||
local setmetatable, rawset, rawget = setmetatable, rawset, rawget
|
||||
local next, select, pairs, type, tostring = next, select, pairs, type, tostring
|
||||
|
||||
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
|
||||
-- List them here for Mikk's FindGlobals script
|
||||
-- GLOBALS: geterrorhandler
|
||||
|
||||
local xpcall = xpcall
|
||||
|
||||
local function errorhandler(err)
|
||||
return geterrorhandler()(err)
|
||||
end
|
||||
|
||||
local function CreateDispatcher(argCount)
|
||||
local code = [[
|
||||
local method, ARGS
|
||||
local function call() method(ARGS) end
|
||||
|
||||
local function dispatch(handlers, ...)
|
||||
local index
|
||||
index, method = next(handlers)
|
||||
if not method then return end
|
||||
local OLD_ARGS = ARGS
|
||||
ARGS = unpack(arg)
|
||||
repeat
|
||||
xpcall(call, function(err) return geterrorhandler()(err) end)
|
||||
index, method = next(handlers, index)
|
||||
until not method
|
||||
ARGS = OLD_ARGS
|
||||
end
|
||||
|
||||
return dispatch
|
||||
]]
|
||||
|
||||
local ARGS, OLD_ARGS = {}, {}
|
||||
for i = 1, argCount do ARGS[i], OLD_ARGS[i] = "arg"..i, "old_arg"..i end
|
||||
code = gsub(gsub(code, "OLD_ARGS", tconcat(OLD_ARGS, ", ")), "ARGS", tconcat(ARGS, ", "))
|
||||
return assert(loadstring(code, "safecall Dispatcher["..argCount.."]"))(next, xpcall, errorhandler)
|
||||
end
|
||||
|
||||
local Dispatchers = setmetatable({}, {__index=function(self, argCount)
|
||||
local dispatcher = CreateDispatcher(argCount)
|
||||
rawset(self, argCount, dispatcher)
|
||||
return dispatcher
|
||||
end})
|
||||
|
||||
--------------------------------------------------------------------------
|
||||
-- CallbackHandler:New
|
||||
--
|
||||
-- target - target object to embed public APIs in
|
||||
-- RegisterName - name of the callback registration API, default "RegisterCallback"
|
||||
-- UnregisterName - name of the callback unregistration API, default "UnregisterCallback"
|
||||
-- UnregisterAllName - name of the API to unregister all callbacks, default "UnregisterAllCallbacks". false == don't publish this API.
|
||||
|
||||
function CallbackHandler:New(target, RegisterName, UnregisterName, UnregisterAllName)
|
||||
|
||||
RegisterName = RegisterName or "RegisterCallback"
|
||||
UnregisterName = UnregisterName or "UnregisterCallback"
|
||||
if UnregisterAllName==nil then -- false is used to indicate "don't want this method"
|
||||
UnregisterAllName = "UnregisterAllCallbacks"
|
||||
end
|
||||
|
||||
-- we declare all objects and exported APIs inside this closure to quickly gain access
|
||||
-- to e.g. function names, the "target" parameter, etc
|
||||
|
||||
|
||||
-- Create the registry object
|
||||
local events = setmetatable({}, meta)
|
||||
local registry = { recurse=0, events=events }
|
||||
|
||||
-- registry:Fire() - fires the given event/message into the registry
|
||||
function registry:Fire(eventname, ...)
|
||||
if not rawget(events, eventname) or not next(events[eventname]) then return end
|
||||
local oldrecurse = registry.recurse
|
||||
registry.recurse = oldrecurse + 1
|
||||
|
||||
Dispatchers[getn(arg) + 1](events[eventname], eventname, unpack(arg))
|
||||
|
||||
registry.recurse = oldrecurse
|
||||
|
||||
if registry.insertQueue and oldrecurse==0 then
|
||||
-- Something in one of our callbacks wanted to register more callbacks; they got queued
|
||||
for eventname,callbacks in pairs(registry.insertQueue) do
|
||||
local first = not rawget(events, eventname) or not next(events[eventname]) -- test for empty before. not test for one member after. that one member may have been overwritten.
|
||||
for self,func in pairs(callbacks) do
|
||||
events[eventname][self] = func
|
||||
-- fire OnUsed callback?
|
||||
if first and registry.OnUsed then
|
||||
registry.OnUsed(registry, target, eventname)
|
||||
first = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
registry.insertQueue = nil
|
||||
end
|
||||
end
|
||||
|
||||
-- Registration of a callback, handles:
|
||||
-- self["method"], leads to self["method"](self, ...)
|
||||
-- self with function ref, leads to functionref(...)
|
||||
-- "addonId" (instead of self) with function ref, leads to functionref(...)
|
||||
-- all with an optional arg, which, if present, gets passed as first argument (after self if present)
|
||||
target[RegisterName] = function(self, eventname, method, ... --[[actually just a single arg]])
|
||||
if type(eventname) ~= "string" then
|
||||
error("Usage: "..RegisterName.."(eventname, method[, arg]): 'eventname' - string expected.", 2)
|
||||
end
|
||||
|
||||
method = method or eventname
|
||||
|
||||
local first = not rawget(events, eventname) or not next(events[eventname]) -- test for empty before. not test for one member after. that one member may have been overwritten.
|
||||
|
||||
if type(method) ~= "string" and type(method) ~= "function" then
|
||||
error("Usage: "..RegisterName.."(\"eventname\", \"methodname\"): 'methodname' - string or function expected.", 2)
|
||||
end
|
||||
|
||||
local regfunc
|
||||
|
||||
if type(method) == "string" then
|
||||
-- self["method"] calling style
|
||||
if type(self) ~= "table" then
|
||||
error("Usage: "..RegisterName.."(\"eventname\", \"methodname\"): self was not a table?", 2)
|
||||
elseif self==target then
|
||||
error("Usage: "..RegisterName.."(\"eventname\", \"methodname\"): do not use Library:"..RegisterName.."(), use your own 'self'", 2)
|
||||
elseif type(self[method]) ~= "function" then
|
||||
error("Usage: "..RegisterName.."(\"eventname\", \"methodname\"): 'methodname' - method '"..tostring(method).."' not found on self.", 2)
|
||||
end
|
||||
|
||||
if getn(arg)>=1 then -- this is not the same as testing for arg==nil!
|
||||
regfunc = function(...) self[method](self,arg1,unpack(arg)) end
|
||||
else
|
||||
regfunc = function(...) self[method](self,unpack(arg)) end
|
||||
end
|
||||
else
|
||||
-- function ref with self=object or self="addonId" or self=thread
|
||||
if type(self)~="table" and type(self)~="string" and type(self)~="thread" then
|
||||
error("Usage: "..RegisterName.."(self or \"addonId\", eventname, method): 'self or addonId': table or string or thread expected.", 2)
|
||||
end
|
||||
|
||||
if getn(arg)>=1 then -- this is not the same as testing for arg==nil!
|
||||
regfunc = function(...) method(arg1,unpack(arg)) end
|
||||
else
|
||||
regfunc = method
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
if events[eventname][self] or registry.recurse<1 then
|
||||
-- if registry.recurse<1 then
|
||||
-- we're overwriting an existing entry, or not currently recursing. just set it.
|
||||
events[eventname][self] = regfunc
|
||||
-- fire OnUsed callback?
|
||||
if registry.OnUsed and first then
|
||||
registry.OnUsed(registry, target, eventname)
|
||||
end
|
||||
else
|
||||
-- we're currently processing a callback in this registry, so delay the registration of this new entry!
|
||||
-- yes, we're a bit wasteful on garbage, but this is a fringe case, so we're picking low implementation overhead over garbage efficiency
|
||||
registry.insertQueue = registry.insertQueue or setmetatable({},meta)
|
||||
registry.insertQueue[eventname][self] = regfunc
|
||||
end
|
||||
end
|
||||
|
||||
-- Unregister a callback
|
||||
target[UnregisterName] = function(self, eventname)
|
||||
if not self or self==target then
|
||||
error("Usage: "..UnregisterName.."(eventname): bad 'self'", 2)
|
||||
end
|
||||
if type(eventname) ~= "string" then
|
||||
error("Usage: "..UnregisterName.."(eventname): 'eventname' - string expected.", 2)
|
||||
end
|
||||
if rawget(events, eventname) and events[eventname][self] then
|
||||
events[eventname][self] = nil
|
||||
-- Fire OnUnused callback?
|
||||
if registry.OnUnused and not next(events[eventname]) then
|
||||
registry.OnUnused(registry, target, eventname)
|
||||
end
|
||||
end
|
||||
if registry.insertQueue and rawget(registry.insertQueue, eventname) and registry.insertQueue[eventname][self] then
|
||||
registry.insertQueue[eventname][self] = nil
|
||||
end
|
||||
end
|
||||
|
||||
-- OPTIONAL: Unregister all callbacks for given selfs/addonIds
|
||||
if UnregisterAllName then
|
||||
target[UnregisterAllName] = function(...)
|
||||
if getn(arg)<1 then
|
||||
error("Usage: "..UnregisterAllName.."([whatFor]): missing 'self' or \"addonId\" to unregister events for.", 2)
|
||||
end
|
||||
if getn(arg)==1 and arg1==target then
|
||||
error("Usage: "..UnregisterAllName.."([whatFor]): supply a meaningful 'self' or \"addonId\"", 2)
|
||||
end
|
||||
|
||||
|
||||
for i=1,getn(arg) do
|
||||
local self = arg[i]
|
||||
if registry.insertQueue then
|
||||
for eventname, callbacks in pairs(registry.insertQueue) do
|
||||
if callbacks[self] then
|
||||
callbacks[self] = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
for eventname, callbacks in pairs(events) do
|
||||
if callbacks[self] then
|
||||
callbacks[self] = nil
|
||||
-- Fire OnUnused callback?
|
||||
if registry.OnUnused and not next(callbacks) then
|
||||
registry.OnUnused(registry, target, eventname)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return registry
|
||||
end
|
||||
|
||||
|
||||
-- CallbackHandler purposefully does NOT do explicit embedding. Nor does it
|
||||
-- try to upgrade old implicit embeds since the system is selfcontained and
|
||||
-- relies on closures to work.
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="CallbackHandler-1.0.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,819 @@
|
||||
-- LibAnim by Hydra
|
||||
local Version = 2.01
|
||||
|
||||
if (_LibAnim and _LibAnim >= Version) then
|
||||
return
|
||||
end
|
||||
|
||||
local _G = _G
|
||||
local cos = cos
|
||||
local sin = sin
|
||||
local pairs = pairs
|
||||
local floor = floor
|
||||
local getn = getn
|
||||
local tinsert = tinsert
|
||||
local tremove = tremove
|
||||
local strlower = strlower
|
||||
local Updater = CreateFrame("StatusBar")
|
||||
local Texture = Updater:CreateTexture()
|
||||
local Text = Updater:CreateFontString()
|
||||
local AnimTypes = {}
|
||||
local UpdateFuncs = {}
|
||||
local Callbacks = {["onplay"] = {}, ["onpause"] = {}, ["onresume"] = {}, ["onstop"] = {}, ["onreset"] = {}, ["onfinished"] = {}}
|
||||
|
||||
-- Update all current animations
|
||||
local AnimationOnUpdate = function()
|
||||
for i = 1, getn(this) do
|
||||
if this[i] then -- Double check the the index still exists, due to pauses/stops removing them on the fly
|
||||
this[i]:Update(arg1, i)
|
||||
end
|
||||
end
|
||||
|
||||
if (getn(this) == 0) then
|
||||
this:SetScript("OnUpdate", nil)
|
||||
end
|
||||
end
|
||||
|
||||
local StartUpdating = function(anim)
|
||||
tinsert(Updater, anim)
|
||||
|
||||
if (not Updater:GetScript("OnUpdate")) then
|
||||
Updater:SetScript("OnUpdate", AnimationOnUpdate)
|
||||
end
|
||||
end
|
||||
|
||||
local GetColor = function(p, r1, g1, b1, r2, g2, b2)
|
||||
return r1 + (r2 - r1) * p, g1 + (g2 - g1) * p, b1 + (b2 - b1) * p
|
||||
end
|
||||
|
||||
local Set = {
|
||||
["backdrop"] = Updater.SetBackdropColor,
|
||||
["border"] = Updater.SetBackdropBorderColor,
|
||||
["statusbar"] = Updater.SetStatusBarColor,
|
||||
["text"] = Text.SetTextColor,
|
||||
["texture"] = Texture.SetTexture,
|
||||
["vertex"] = Texture.SetVertexColor,
|
||||
}
|
||||
|
||||
local Get = {
|
||||
["backdrop"] = Updater.GetBackdropColor,
|
||||
["border"] = Updater.GetBackdropBorderColor,
|
||||
["statusbar"] = Updater.GetStatusBarColor,
|
||||
["text"] = Text.GetTextColor,
|
||||
["texture"] = Texture.GetVertexColor,
|
||||
["vertex"] = Texture.GetVertexColor,
|
||||
}
|
||||
|
||||
local Smoothing = {
|
||||
["none"] = function(t, b, c, d)
|
||||
return c * t / d + b
|
||||
end,
|
||||
|
||||
["in"] = function(t, b, c, d)
|
||||
t = t / d
|
||||
|
||||
return c * t * t + b
|
||||
end,
|
||||
|
||||
["out"] = function(t, b, c, d)
|
||||
t = t / d
|
||||
|
||||
return -c * t * (t - 2) + b
|
||||
end,
|
||||
|
||||
["inout"] = function(t, b, c, d)
|
||||
t = t / (d / 2)
|
||||
|
||||
if (t < 1) then
|
||||
return c / 2 * t * t + b
|
||||
end
|
||||
|
||||
t = t - 1
|
||||
return -c / 2 * (t * (t - 2) - 1) + b
|
||||
end,
|
||||
|
||||
["bounce"] = function(t, b, c, d)
|
||||
t = t / d
|
||||
|
||||
if (t < (1 / 2.75)) then
|
||||
return c * (7.5625 * t * t) + b
|
||||
elseif (t < (2 / 2.75)) then
|
||||
t = t - (1.5 / 2.75)
|
||||
|
||||
return c * (7.5625 * t * t + 0.75) + b
|
||||
elseif (t < (2.5 / 2.75)) then
|
||||
t = t - (2.25 / 2.75)
|
||||
|
||||
return c * (7.5625 * t * t + 0.9375) + b
|
||||
else
|
||||
t = t - (2.625 / 2.75)
|
||||
|
||||
return c * (7.5625 * (t) * t + 0.984375) + b
|
||||
end
|
||||
end,
|
||||
["elastic"] = function(t, b, c, d)
|
||||
local s, p, a = 1.70158, d * .3, c;
|
||||
if t == 0 then
|
||||
return b
|
||||
end
|
||||
t = t / d
|
||||
|
||||
if t == 1 then
|
||||
return b + c
|
||||
end
|
||||
|
||||
if a < math.abs(c) then
|
||||
a = c
|
||||
s = p / 4
|
||||
else
|
||||
s = p / (2 * math.pi) * math.asin(c / a)
|
||||
end
|
||||
|
||||
return a * math.pow(2, -10 * t) * math.sin((t * d - s) * (2 * math.pi) / p) + c + b
|
||||
end
|
||||
}
|
||||
|
||||
local AnimMethods = {
|
||||
All = {
|
||||
Play = function(self)
|
||||
if (not self.Paused) then
|
||||
AnimTypes[self.Type](self)
|
||||
self:Callback("OnPlay")
|
||||
else
|
||||
StartUpdating(self)
|
||||
self:Callback("OnResume")
|
||||
end
|
||||
|
||||
self.Playing = true
|
||||
self.Paused = false
|
||||
self.Stopped = false
|
||||
end,
|
||||
|
||||
IsPlaying = function(self)
|
||||
return self.Playing
|
||||
end,
|
||||
|
||||
Pause = function(self)
|
||||
for i = 1, getn(Updater) do
|
||||
if (Updater[i] == self) then
|
||||
tremove(Updater, i)
|
||||
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
self.Playing = false
|
||||
self.Paused = true
|
||||
self.Stopped = false
|
||||
self:Callback("OnPause")
|
||||
end,
|
||||
|
||||
IsPaused = function(self)
|
||||
return self.Paused
|
||||
end,
|
||||
|
||||
Stop = function(self, reset)
|
||||
for i = 1, getn(Updater) do
|
||||
if (Updater[i] == self) then
|
||||
tremove(Updater, i)
|
||||
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
self.Playing = false
|
||||
self.Paused = false
|
||||
self.Stopped = true
|
||||
|
||||
if reset then
|
||||
self:Reset()
|
||||
self:Callback("OnReset")
|
||||
else
|
||||
self:Callback("OnStop")
|
||||
end
|
||||
end,
|
||||
|
||||
IsStopped = function(self)
|
||||
return self.Stopped
|
||||
end,
|
||||
|
||||
SetSmoothing = function(self, smoothType)
|
||||
smoothType = strlower(smoothType)
|
||||
|
||||
self.Smoothing = Smoothing[smoothType] and smoothType or "none"
|
||||
end,
|
||||
|
||||
GetSmoothing = function(self)
|
||||
return self.Smoothing
|
||||
end,
|
||||
|
||||
SetDuration = function(self, duration)
|
||||
self.Duration = duration or 0
|
||||
end,
|
||||
|
||||
GetDuration = function(self)
|
||||
return self.Duration
|
||||
end,
|
||||
|
||||
GetProgressByTimer = function(self)
|
||||
return self.Timer
|
||||
end,
|
||||
|
||||
SetOrder = function(self, order)
|
||||
self.Order = order or 1
|
||||
|
||||
if (order > self.Group.MaxOrder) then
|
||||
self.Group.MaxOrder = order
|
||||
end
|
||||
end,
|
||||
|
||||
GetOrder = function(self)
|
||||
return self.Order
|
||||
end,
|
||||
|
||||
GetParent = function(self)
|
||||
return self.Parent
|
||||
end,
|
||||
|
||||
SetScript = function(self, handler, func)
|
||||
handler = strlower(handler)
|
||||
|
||||
if (not Callbacks[handler]) then
|
||||
return
|
||||
end
|
||||
|
||||
Callbacks[handler][self] = func
|
||||
end,
|
||||
|
||||
GetScript = function(self, handler)
|
||||
handler = strlower(handler)
|
||||
|
||||
if (Callbacks[handler] and Callbacks[handler][self]) then
|
||||
return Callbacks[handler][self]
|
||||
end
|
||||
end,
|
||||
|
||||
Callback = function(self, handler)
|
||||
handler = strlower(handler)
|
||||
|
||||
if Callbacks[handler][self] then
|
||||
Callbacks[handler][self](self)
|
||||
end
|
||||
end,
|
||||
},
|
||||
|
||||
move = {
|
||||
SetOffset = function(self, x, y)
|
||||
self.XSetting = x or 0
|
||||
self.YSetting = y or 0
|
||||
end,
|
||||
|
||||
GetOffset = function(self)
|
||||
return self.XSetting, self.YSetting
|
||||
end,
|
||||
|
||||
SetRounded = function(self, flag)
|
||||
self.IsRounded = flag
|
||||
end,
|
||||
|
||||
GetRounded = function(self)
|
||||
return self.IsRounded
|
||||
end,
|
||||
|
||||
GetProgress = function(self)
|
||||
return self.XOffset, self.YOffset
|
||||
end,
|
||||
|
||||
Reset = function(self)
|
||||
self.Parent:ClearAllPoints()
|
||||
self.Parent:SetPoint(self.A1, self.P, self.A2, self.StartX, self.StartY)
|
||||
end,
|
||||
},
|
||||
|
||||
fade = {
|
||||
SetChange = function(self, alpha)
|
||||
self.EndAlphaSetting = alpha or 0
|
||||
end,
|
||||
|
||||
GetChange = function(self)
|
||||
return self.EndAlphaSetting
|
||||
end,
|
||||
|
||||
GetProgress = function(self)
|
||||
return self.AlphaOffset
|
||||
end,
|
||||
|
||||
Reset = function(self)
|
||||
self.Parent:SetAlpha(self.StartAlpha)
|
||||
end,
|
||||
},
|
||||
|
||||
height = {
|
||||
SetChange = function(self, height)
|
||||
self.EndHeightSetting = height or 0
|
||||
end,
|
||||
|
||||
GetChange = function(self)
|
||||
return self.EndHeightSetting
|
||||
end,
|
||||
|
||||
GetProgress = function(self)
|
||||
return self.HeightOffset
|
||||
end,
|
||||
|
||||
Reset = function(self)
|
||||
self.Parent:SetHeight(self.StartHeight)
|
||||
end,
|
||||
},
|
||||
|
||||
width = {
|
||||
SetChange = function(self, width)
|
||||
self.EndWidthSetting = width or 0
|
||||
end,
|
||||
|
||||
GetChange = function(self)
|
||||
return self.EndWidthSetting
|
||||
end,
|
||||
|
||||
GetProgress = function(self)
|
||||
return self.WidthOffset
|
||||
end,
|
||||
|
||||
Reset = function(self)
|
||||
self.Parent:SetWidth(self.StartWidth)
|
||||
end,
|
||||
},
|
||||
|
||||
color = {
|
||||
SetChange = function(self, r, g, b)
|
||||
self.EndRSetting = r or 1
|
||||
self.EndGSetting = g or 1
|
||||
self.EndBSetting = b or 1
|
||||
end,
|
||||
|
||||
GetChange = function(self)
|
||||
return self.EndRSetting, self.EndGSetting, self.EndBSetting
|
||||
end,
|
||||
|
||||
SetColorType = function(self, type)
|
||||
type = strlower(type)
|
||||
|
||||
self.ColorType = Set[type] and type or "border"
|
||||
end,
|
||||
|
||||
GetColorType = function(self)
|
||||
return self.ColorType
|
||||
end,
|
||||
|
||||
GetProgress = function(self)
|
||||
return self.ColorOffset
|
||||
end,
|
||||
|
||||
Reset = function(self)
|
||||
Set[self.ColorType](self.Parent, self.StartR, self.StartG, self.StartB)
|
||||
end,
|
||||
},
|
||||
|
||||
progress = {
|
||||
SetChange = function(self, value)
|
||||
self.EndValueSetting = value or 0
|
||||
end,
|
||||
|
||||
GetChange = function(self)
|
||||
return self.EndValueSetting
|
||||
end,
|
||||
|
||||
GetProgress = function(self)
|
||||
return self.ValueOffset
|
||||
end,
|
||||
|
||||
Reset = function(self)
|
||||
self.Parent:SetValue(self.StartValue)
|
||||
end,
|
||||
},
|
||||
|
||||
number = {
|
||||
SetChange = function(self, value)
|
||||
self.EndNumberSetting = value or 0
|
||||
end,
|
||||
|
||||
GetChange = function(self)
|
||||
return self.EndNumberSetting
|
||||
end,
|
||||
|
||||
SetPrefix = function(self, text)
|
||||
self.Prefix = text or ""
|
||||
end,
|
||||
|
||||
GetPrefix = function(self)
|
||||
return self.Prefix
|
||||
end,
|
||||
|
||||
SetPostfix = function(self, text)
|
||||
self.Postfix = text or ""
|
||||
end,
|
||||
|
||||
GetPostfix = function(self)
|
||||
return self.Postfix
|
||||
end,
|
||||
|
||||
GetProgress = function(self)
|
||||
return self.NumberOffset
|
||||
end,
|
||||
|
||||
Reset = function(self)
|
||||
self.Parent:SetText(self.StartNumer)
|
||||
end,
|
||||
},
|
||||
}
|
||||
|
||||
local GroupMethods = {
|
||||
Play = function(self)
|
||||
-- Play!
|
||||
for i = 1, getn(self.Animations) do
|
||||
if (self.Animations[i].Order == self.Order) then
|
||||
self.Animations[i]:Play()
|
||||
end
|
||||
end
|
||||
|
||||
self.Playing = true
|
||||
self.Paused = false
|
||||
self.Stopped = false
|
||||
end,
|
||||
|
||||
IsPlaying = function(self)
|
||||
return self.Playing
|
||||
end,
|
||||
|
||||
Pause = function(self)
|
||||
-- Only pause current order
|
||||
for i = 1, getn(self.Animations) do
|
||||
if (self.Animations[i].Order == self.Order) then
|
||||
self.Animations[i]:Pause()
|
||||
end
|
||||
end
|
||||
|
||||
self.Playing = false
|
||||
self.Paused = true
|
||||
self.Stopped = false
|
||||
end,
|
||||
|
||||
IsPaused = function(self)
|
||||
return self.Paused
|
||||
end,
|
||||
|
||||
Stop = function(self)
|
||||
for i = 1, getn(self.Animations) do
|
||||
self.Animations[i]:Stop()
|
||||
end
|
||||
|
||||
self.Playing = false
|
||||
self.Paused = false
|
||||
self.Stopped = true
|
||||
end,
|
||||
|
||||
IsStopped = function(self)
|
||||
return self.Stopped
|
||||
end,
|
||||
|
||||
SetLooping = function(self, shouldLoop)
|
||||
self.Looping = shouldLoop
|
||||
end,
|
||||
|
||||
GetLooping = function(self)
|
||||
return self.Looping
|
||||
end,
|
||||
|
||||
GetParent = function(self)
|
||||
return self.Parent
|
||||
end,
|
||||
|
||||
CheckOrder = function(self)
|
||||
-- Check if we're done all animations at the current order, then proceed to the next order.
|
||||
local NumAtOrder = 0
|
||||
local NumDoneAtOrder = 0
|
||||
|
||||
for i = 1, getn(self.Animations) do
|
||||
if (self.Animations[i].Order == self.Order) then
|
||||
NumAtOrder = NumAtOrder + 1
|
||||
|
||||
if (not self.Animations[i].Playing) then
|
||||
NumDoneAtOrder = NumDoneAtOrder + 1
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- All the animations at x order finished, go to next order
|
||||
if (NumAtOrder == NumDoneAtOrder) then
|
||||
self.Order = self.Order + 1
|
||||
|
||||
-- We exceeded max order, reset to 1 and bail the function, or restart if we're looping
|
||||
if (self.Order > self.MaxOrder) then
|
||||
self.Order = 1
|
||||
|
||||
if (self.Stopped or not self.Looping) then
|
||||
self.Playing = false
|
||||
|
||||
return
|
||||
end
|
||||
end
|
||||
|
||||
-- Play!
|
||||
for i = 1, getn(self.Animations) do
|
||||
if (self.Animations[i].Order == self.Order) then
|
||||
self.Animations[i]:Play()
|
||||
end
|
||||
end
|
||||
end
|
||||
end,
|
||||
|
||||
CreateAnimation = function(self, type)
|
||||
type = strlower(type)
|
||||
|
||||
if (not AnimTypes[type]) then
|
||||
return
|
||||
end
|
||||
|
||||
local Animation = {}
|
||||
|
||||
-- General methods
|
||||
for key, func in pairs(AnimMethods.All) do
|
||||
Animation[key] = func
|
||||
end
|
||||
|
||||
-- Animation specific methods
|
||||
if AnimMethods[type] then
|
||||
for key, func in pairs(AnimMethods[type]) do
|
||||
Animation[key] = func
|
||||
end
|
||||
end
|
||||
|
||||
-- Set some attributes and defaults
|
||||
Animation.Paused = false
|
||||
Animation.Playing = false
|
||||
Animation.Stopped = false
|
||||
Animation.Looping = false
|
||||
Animation.Type = type
|
||||
Animation.Group = self
|
||||
Animation.Parent = self.Parent
|
||||
Animation.Order = 1
|
||||
Animation.Duration = 0.3
|
||||
Animation.Smoothing = "none"
|
||||
Animation.Update = UpdateFuncs[type]
|
||||
|
||||
tinsert(self.Animations, Animation)
|
||||
|
||||
return Animation
|
||||
end,
|
||||
}
|
||||
|
||||
CreateAnimationGroup = function(parent)
|
||||
local Group = {Animations = {}}
|
||||
|
||||
-- Add methods to the group
|
||||
for key, func in pairs(GroupMethods) do
|
||||
Group[key] = func
|
||||
end
|
||||
|
||||
Group.Parent = parent
|
||||
Group.Playing = false
|
||||
Group.Paused = false
|
||||
Group.Stopped = false
|
||||
Group.Order = 1
|
||||
Group.MaxOrder = 1
|
||||
|
||||
return Group
|
||||
end
|
||||
|
||||
-- Movement
|
||||
UpdateFuncs["move"] = function(self, elapsed, i)
|
||||
self.Timer = self.Timer + elapsed
|
||||
|
||||
if self.IsRounded then
|
||||
self.ModTimer = Smoothing[self.Smoothing](self.Timer, 0, self.Duration, self.Duration)
|
||||
self.XOffset = self.StartX - (-1) * (self.XChange * (1 - cos(90 * self.ModTimer / self.Duration)))
|
||||
self.YOffset = self.StartY + self.YChange * sin(90 * self.ModTimer / self.Duration)
|
||||
else
|
||||
self.XOffset = Smoothing[self.Smoothing](self.Timer, self.StartX, self.XChange, self.Duration)
|
||||
self.YOffset = Smoothing[self.Smoothing](self.Timer, self.StartY, self.YChange, self.Duration)
|
||||
end
|
||||
|
||||
self.Parent:SetPoint(self.A1, self.P, self.A2, (self.EndX ~= 0 and self.XOffset or self.StartX), (self.EndY ~= 0 and self.YOffset or self.StartY))
|
||||
|
||||
if (self.Timer >= self.Duration) then
|
||||
tremove(Updater, i)
|
||||
self.Parent:SetPoint(self.A1, self.P, self.A2, self.EndX, self.EndY)
|
||||
self.Playing = false
|
||||
self:Callback("OnFinished")
|
||||
self.Group:CheckOrder()
|
||||
end
|
||||
end
|
||||
|
||||
AnimTypes["move"] = function(self)
|
||||
if self:IsPlaying() then
|
||||
return
|
||||
end
|
||||
|
||||
local A1, P, A2, X, Y = self.Parent:GetPoint()
|
||||
|
||||
self.Timer = 0
|
||||
self.A1 = A1
|
||||
self.P = P
|
||||
self.A2 = A2
|
||||
self.StartX = X
|
||||
self.EndX = X + self.XSetting or 0
|
||||
self.StartY = Y
|
||||
self.EndY = Y + self.YSetting or 0
|
||||
self.XChange = self.EndX - self.StartX
|
||||
self.YChange = self.EndY - self.StartY
|
||||
|
||||
if self.IsRounded then
|
||||
if (self.XChange == 0 or self.YChange == 0) then -- Double check if we're valid to be rounded
|
||||
self.IsRounded = false
|
||||
else
|
||||
self.ModTimer = 0
|
||||
end
|
||||
end
|
||||
|
||||
StartUpdating(self)
|
||||
end
|
||||
|
||||
-- Fade
|
||||
UpdateFuncs["fade"] = function(self, elapsed, i)
|
||||
self.Timer = self.Timer + elapsed
|
||||
self.AlphaOffset = Smoothing[self.Smoothing](self.Timer, self.StartAlpha, self.Change, self.Duration)
|
||||
self.Parent:SetAlpha(self.AlphaOffset)
|
||||
|
||||
if (self.Timer >= self.Duration) then
|
||||
tremove(Updater, i)
|
||||
self.Parent:SetAlpha(self.EndAlpha)
|
||||
self.Playing = false
|
||||
self:Callback("OnFinished")
|
||||
self.Group:CheckOrder()
|
||||
end
|
||||
end
|
||||
|
||||
AnimTypes["fade"] = function(self)
|
||||
if self:IsPlaying() then
|
||||
return
|
||||
end
|
||||
|
||||
self.Timer = 0
|
||||
self.StartAlpha = self.Parent:GetAlpha() or 1
|
||||
self.EndAlpha = self.EndAlphaSetting or 0
|
||||
self.Change = self.EndAlpha - self.StartAlpha
|
||||
|
||||
StartUpdating(self)
|
||||
end
|
||||
|
||||
-- Height
|
||||
UpdateFuncs["height"] = function(self, elapsed, i)
|
||||
self.Timer = self.Timer + elapsed
|
||||
self.HeightOffset = Smoothing[self.Smoothing](self.Timer, self.StartHeight, self.HeightChange, self.Duration)
|
||||
self.Parent:SetHeight(self.HeightOffset)
|
||||
|
||||
if (self.Timer >= self.Duration) then
|
||||
tremove(Updater, i)
|
||||
self.Parent:SetHeight(self.EndHeight)
|
||||
self.Playing = false
|
||||
self:Callback("OnFinished")
|
||||
self.Group:CheckOrder()
|
||||
end
|
||||
end
|
||||
|
||||
AnimTypes["height"] = function(self)
|
||||
if self:IsPlaying() then
|
||||
return
|
||||
end
|
||||
|
||||
self.Timer = 0
|
||||
self.StartHeight = self.Parent:GetHeight() or 0
|
||||
self.EndHeight = self.EndHeightSetting or 0
|
||||
self.HeightChange = self.EndHeight - self.StartHeight
|
||||
|
||||
StartUpdating(self)
|
||||
end
|
||||
|
||||
-- Width
|
||||
UpdateFuncs["width"] = function(self, elapsed, i)
|
||||
self.Timer = self.Timer + elapsed
|
||||
self.WidthOffset = Smoothing[self.Smoothing](self.Timer, self.StartWidth, self.WidthChange, self.Duration)
|
||||
self.Parent:SetWidth(self.WidthOffset)
|
||||
|
||||
if (self.Timer >= self.Duration) then
|
||||
tremove(Updater, i)
|
||||
self.Parent:SetWidth(self.EndWidth)
|
||||
self.Playing = false
|
||||
self:Callback("OnFinished")
|
||||
self.Group:CheckOrder()
|
||||
end
|
||||
end
|
||||
|
||||
AnimTypes["width"] = function(self)
|
||||
if self:IsPlaying() then
|
||||
return
|
||||
end
|
||||
|
||||
self.Timer = 0
|
||||
self.StartWidth = self.Parent:GetWidth() or 0
|
||||
self.EndWidth = self.EndWidthSetting or 0
|
||||
self.WidthChange = self.EndWidth - self.StartWidth
|
||||
|
||||
StartUpdating(self)
|
||||
end
|
||||
|
||||
-- Color
|
||||
UpdateFuncs["color"] = function(self, elapsed, i)
|
||||
self.Timer = self.Timer + elapsed
|
||||
self.ColorOffset = Smoothing[self.Smoothing](self.Timer, 0, self.Duration, self.Duration)
|
||||
Set[self.ColorType](self.Parent, GetColor(self.Timer / self.Duration, self.StartR, self.StartG, self.StartB, self.EndR, self.EndG, self.EndB))
|
||||
|
||||
if (self.Timer >= self.Duration) then
|
||||
tremove(Updater, i)
|
||||
Set[self.ColorType](self.Parent, self.EndR, self.EndG, self.EndB)
|
||||
self.Playing = false
|
||||
self:Callback("OnFinished")
|
||||
self.Group:CheckOrder()
|
||||
end
|
||||
end
|
||||
|
||||
AnimTypes["color"] = function(self)
|
||||
self.Timer = 0
|
||||
self.ColorType = self.ColorType or "backdrop"
|
||||
self.StartR, self.StartG, self.StartB = Get[self.ColorType](self.Parent)
|
||||
self.EndR = self.EndRSetting or 1
|
||||
self.EndG = self.EndGSetting or 1
|
||||
self.EndB = self.EndBSetting or 1
|
||||
|
||||
StartUpdating(self)
|
||||
end
|
||||
|
||||
-- Progress
|
||||
UpdateFuncs["progress"] = function(self, elapsed, i)
|
||||
self.Timer = self.Timer + elapsed
|
||||
self.ValueOffset = Smoothing[self.Smoothing](self.Timer, self.StartValue, self.ProgressChange, self.Duration)
|
||||
self.Parent:SetValue(self.ValueOffset)
|
||||
|
||||
if (self.Timer >= self.Duration) then
|
||||
tremove(Updater, i)
|
||||
self.Parent:SetValue(self.EndValue)
|
||||
self.Playing = false
|
||||
self:Callback("OnFinished")
|
||||
self.Group:CheckOrder()
|
||||
end
|
||||
end
|
||||
|
||||
AnimTypes["progress"] = function(self)
|
||||
self.Timer = 0
|
||||
self.StartValue = self.Parent:GetValue() or 0
|
||||
self.EndValue = self.EndValueSetting or 0
|
||||
self.ProgressChange = self.EndValue - self.StartValue
|
||||
|
||||
StartUpdating(self)
|
||||
end
|
||||
|
||||
-- Sleep
|
||||
UpdateFuncs["sleep"] = function(self, elapsed, i)
|
||||
self.Timer = self.Timer + elapsed
|
||||
|
||||
if (self.Timer >= self.Duration) then
|
||||
tremove(Updater, i)
|
||||
self.Playing = false
|
||||
self:Callback("OnFinished")
|
||||
self.Group:CheckOrder()
|
||||
end
|
||||
end
|
||||
|
||||
AnimTypes["sleep"] = function(self)
|
||||
self.Timer = 0
|
||||
|
||||
StartUpdating(self)
|
||||
end
|
||||
|
||||
-- Number
|
||||
UpdateFuncs["number"] = function(self, elapsed, i)
|
||||
self.Timer = self.Timer + elapsed
|
||||
self.NumberOffset = Smoothing[self.Smoothing](self.Timer, self.StartNumber, self.NumberChange, self.Duration)
|
||||
self.Parent:SetText(self.Prefix..floor(self.NumberOffset)..self.Postfix)
|
||||
|
||||
if (self.Timer >= self.Duration) then
|
||||
tremove(Updater, i)
|
||||
self.Parent:SetText(self.Prefix..floor(self.EndNumber)..self.Postfix)
|
||||
self.Playing = false
|
||||
self:Callback("OnFinished")
|
||||
self.Group:CheckOrder()
|
||||
end
|
||||
end
|
||||
|
||||
AnimTypes["number"] = function(self)
|
||||
self.Timer = 0
|
||||
self.StartNumber = tonumber(self.Parent:GetText()) or 0
|
||||
self.EndNumber = self.EndNumberSetting or 0
|
||||
self.NumberChange = self.EndNumberSetting - self.StartNumber
|
||||
self.Prefix = self.Prefix or ""
|
||||
self.Postfix = self.Postfix or ""
|
||||
|
||||
StartUpdating(self)
|
||||
end
|
||||
|
||||
_G["_LibAnim"] = Version
|
||||
@@ -0,0 +1,3 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="LibAnim.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,227 @@
|
||||
--[[
|
||||
Name: LibBase64-1.0
|
||||
Author(s): ckknight (ckknight@gmail.com)
|
||||
Website: http://www.wowace.com/projects/libbase64-1-0/
|
||||
Description: A library to encode and decode Base64 strings
|
||||
License: MIT
|
||||
]]
|
||||
|
||||
local modf = math.modf
|
||||
local sub = string.sub
|
||||
local format = string.format
|
||||
local getn = table.getn
|
||||
local strlen = string.len
|
||||
local byte = string.byte
|
||||
|
||||
local LibBase64 = LibStub:NewLibrary("LibBase64-1.0", 1)
|
||||
|
||||
if not LibBase64 then
|
||||
return
|
||||
end
|
||||
|
||||
local _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
|
||||
local charTable = {}
|
||||
local byteToNum = {}
|
||||
local numToChar = {}
|
||||
|
||||
for i = 1, strlen(_chars) do
|
||||
charTable[i] = sub(_chars, i, i)
|
||||
end
|
||||
|
||||
for i = 1, getn(charTable) do
|
||||
numToChar[i - 1] = sub(_chars, i, i)
|
||||
byteToNum[byte(_chars, i)] = i - 1
|
||||
end
|
||||
|
||||
_chars = nil
|
||||
|
||||
local A_byte = byte("A")
|
||||
local Z_byte = byte("Z")
|
||||
local a_byte = byte("a")
|
||||
local z_byte = byte("z")
|
||||
local zero_byte = byte("0")
|
||||
local nine_byte = byte("9")
|
||||
local plus_byte = byte("+")
|
||||
local slash_byte = byte("/")
|
||||
local equals_byte = byte("=")
|
||||
local whitespace = {
|
||||
[byte(" ")] = true,
|
||||
[byte("\t")] = true,
|
||||
[byte("\n")] = true,
|
||||
[byte("\r")] = true,
|
||||
}
|
||||
|
||||
local t = {}
|
||||
|
||||
--- Encode a normal bytestring into a Base64-encoded string
|
||||
-- @param text a bytestring, can be binary data
|
||||
-- @param maxLineLength This should be a multiple of 4, greater than 0 or nil. If non-nil, it will break up the output into lines no longer than the given number of characters. 76 is recommended.
|
||||
-- @param lineEnding a string to end each line with. This is "\r\n" by default.
|
||||
-- @usage LibBase64.Encode("Hello, how are you doing today?") == "SGVsbG8sIGhvdyBhcmUgeW91IGRvaW5nIHRvZGF5Pw=="
|
||||
-- @return a Base64-encoded string
|
||||
function LibBase64:Encode(text, maxLineLength, lineEnding)
|
||||
if type(text) ~= "string" then
|
||||
error(format("Bad argument #1 to `Encode'. Expected %q, got %q", "string", type(text)), 2)
|
||||
end
|
||||
|
||||
if maxLineLength == nil then
|
||||
-- do nothing
|
||||
elseif type(maxLineLength) ~= "number" then
|
||||
error(format("Bad argument #2 to `Encode'. Expected %q or %q, got %q", "number", "nil", type(maxLineLength)), 2)
|
||||
elseif modf(maxLineLength, 4) ~= 0 then
|
||||
error(format("Bad argument #2 to `Encode'. Expected a multiple of 4, got %s", maxLineLength), 2)
|
||||
elseif maxLineLength <= 0 then
|
||||
error(format("Bad argument #2 to `Encode'. Expected a number > 0, got %s", maxLineLength), 2)
|
||||
end
|
||||
|
||||
if lineEnding == nil then
|
||||
lineEnding = "\r\n"
|
||||
elseif type(lineEnding) ~= "string" then
|
||||
error(format("Bad argument #3 to `Encode'. Expected %q, got %q", "string", type(lineEnding)), 2)
|
||||
end
|
||||
|
||||
local currentLength = 0
|
||||
|
||||
for i = 1, getn(text), 3 do
|
||||
local a, b, c = byte(text, i, i+2)
|
||||
local nilNum = 0
|
||||
if not b then
|
||||
nilNum = 2
|
||||
b = 0
|
||||
c = 0
|
||||
elseif not c then
|
||||
nilNum = 1
|
||||
c = 0
|
||||
end
|
||||
local num = a * 2^16 + b * 2^8 + c
|
||||
|
||||
local d = modf(num, 2^6)
|
||||
num = (num - d) / 2^6
|
||||
|
||||
local c = modf(num, 2^6)
|
||||
num = (num - c) / 2^6
|
||||
|
||||
local b = modf(num, 2^6)
|
||||
num = (num - b) / 2^6
|
||||
|
||||
local a = modf(num, 2^6)
|
||||
|
||||
t[getn(t)+1] = numToChar[a]
|
||||
|
||||
t[getn(t)+1] = numToChar[b]
|
||||
|
||||
t[getn(t)+1] = (nilNum >= 2) and "=" or numToChar[c]
|
||||
|
||||
t[getn(t)+1] = (nilNum >= 1) and "=" or numToChar[d]
|
||||
|
||||
currentLength = currentLength + 4
|
||||
if maxLineLength and modf(currentLength, maxLineLength) == 0 then
|
||||
t[getn(t)+1] = lineEnding
|
||||
end
|
||||
end
|
||||
|
||||
local s = table.concat(t)
|
||||
for i = 1, getn(t) do
|
||||
t[i] = nil
|
||||
end
|
||||
return s
|
||||
end
|
||||
|
||||
local t2 = {}
|
||||
|
||||
--- Decode a Base64-encoded string into a bytestring
|
||||
-- this will raise an error if the data passed in is not a Base64-encoded string
|
||||
-- this will ignore whitespace, but not invalid characters
|
||||
-- @param text a Base64-encoded string
|
||||
-- @usage LibBase64.Encode("SGVsbG8sIGhvdyBhcmUgeW91IGRvaW5nIHRvZGF5Pw==") == "Hello, how are you doing today?"
|
||||
-- @return a bytestring
|
||||
function LibBase64:Decode(text)
|
||||
if type(text) ~= "string" then
|
||||
error(format("Bad argument #1 to `Decode'. Expected %q, got %q", "string", type(text)), 2)
|
||||
end
|
||||
|
||||
for i = 1, getn(text) do
|
||||
local byte = byte(text, i)
|
||||
if whitespace[byte] or byte == equals_byte then
|
||||
-- do nothing
|
||||
else
|
||||
local num = byteToNum[byte]
|
||||
if not num then
|
||||
for i = 1, getn(t2) do
|
||||
t2[k] = nil
|
||||
end
|
||||
|
||||
error(format("Bad argument #1 to `Decode'. Received an invalid char: %q", sub(text, i, i)), 2)
|
||||
end
|
||||
t2[getn(t2)+1] = num
|
||||
end
|
||||
end
|
||||
|
||||
for i = 1, getn(t2), 4 do
|
||||
local a, b, c, d = t2[i], t2[i+1], t2[i+2], t2[i+3]
|
||||
|
||||
local nilNum = 0
|
||||
if not c then
|
||||
nilNum = 2
|
||||
c = 0
|
||||
d = 0
|
||||
elseif not d then
|
||||
nilNum = 1
|
||||
d = 0
|
||||
end
|
||||
|
||||
local num = a * 2^18 + b * 2^12 + c * 2^6 + d
|
||||
|
||||
local c = modf(num, 2^8)
|
||||
num = (num - c) / 2^8
|
||||
|
||||
local b = modf(num, 2^8)
|
||||
num = (num - b) / 2^8
|
||||
|
||||
local a = modf(num, 2^8)
|
||||
|
||||
t[getn(t)+1] = string.char(a)
|
||||
if nilNum < 2 then
|
||||
t[getn(t)+1] = string.char(b)
|
||||
end
|
||||
if nilNum < 1 then
|
||||
t[getn(t)+1] = string.char(c)
|
||||
end
|
||||
end
|
||||
|
||||
for i = 1, getn(t2) do
|
||||
t2[i] = nil
|
||||
end
|
||||
|
||||
local s = table.concat(t)
|
||||
|
||||
for i = 1, getn(t) do
|
||||
t[i] = nil
|
||||
end
|
||||
|
||||
return s
|
||||
end
|
||||
|
||||
function LibBase64:IsBase64(text)
|
||||
if type(text) ~= "string" then
|
||||
error(format("Bad argument #1 to `IsBase64'. Expected %q, got %q", "string", type(text)), 2)
|
||||
end
|
||||
|
||||
if modf(strlen(text), 4) ~= 0 then
|
||||
return false
|
||||
end
|
||||
|
||||
for i = 1, getn(text) do
|
||||
local byte = byte(text, i)
|
||||
if whitespace[byte] or byte == equals_byte then
|
||||
-- do nothing
|
||||
else
|
||||
local num = byteToNum[byte]
|
||||
if not num then
|
||||
return false
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return true
|
||||
end
|
||||
@@ -0,0 +1,3 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="LibBase64-1.0.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,807 @@
|
||||
----------------------------------------------------------------------------------
|
||||
--
|
||||
-- LibCompress.lua
|
||||
--
|
||||
-- Authors: jjsheets and Galmok of European Stormrage (Horde)
|
||||
-- Email : sheets.jeff@gmail.com and galmok@gmail.com
|
||||
-- Licence: GPL version 2 (General Public License)
|
||||
----------------------------------------------------------------------------------
|
||||
|
||||
|
||||
local MAJOR, MINOR = "LibCompress", 3
|
||||
|
||||
local LibCompress,oldminor = LibStub:NewLibrary(MAJOR, MINOR)
|
||||
|
||||
if not LibCompress then return end
|
||||
|
||||
-- list of codecs in this file:
|
||||
-- \000 - Never used
|
||||
-- \001 - Uncompressed
|
||||
-- \002 - LZW
|
||||
-- \003 - Huffman
|
||||
|
||||
|
||||
-- local is faster than global
|
||||
local table_insert = table.insert
|
||||
local table_remove = table.remove
|
||||
local table_concat = table.concat
|
||||
local string_char = string.char
|
||||
local string_byte = string.byte
|
||||
local string_len = string.len
|
||||
local string_sub = string.sub
|
||||
local unpack = unpack
|
||||
local pairs = pairs
|
||||
local math_modf = math.modf
|
||||
local bit_band = bit.band
|
||||
local bit_bor = bit.bor
|
||||
local bit_lshift = bit.lshift
|
||||
local bit_rshift = bit.rshift
|
||||
local tostring = tostring
|
||||
local next = next
|
||||
local strlen = strlen
|
||||
local strsplit = string.split
|
||||
local strfind = string.find
|
||||
local strgfind = string.gfind
|
||||
local tonumber = tonumber
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
-- Cleanup
|
||||
|
||||
local tables = {} -- tables that may be cleaned have to be kept here
|
||||
local tables_to_clean = {} -- list of tables by name (string) that may be reset to {} after a timeout
|
||||
local timeout = -1
|
||||
|
||||
-- tables that may be erased
|
||||
local function cleanup()
|
||||
for k,v in pairs(tables_to_clean) do
|
||||
tables[k]={}
|
||||
tables_to_clean[k]=nil
|
||||
end
|
||||
end
|
||||
|
||||
local function onUpdate(frame, elapsed)
|
||||
timeout = timeout - arg1
|
||||
if timeout < 0 then
|
||||
this:Hide()
|
||||
cleanup()
|
||||
end
|
||||
end
|
||||
|
||||
LibCompress.frame = LibCompress.frame or CreateFrame("frame", nil, UIParent) -- reuse the old frame
|
||||
LibCompress.frame:SetScript("OnUpdate", onUpdate)
|
||||
LibCompress.frame:Hide()
|
||||
|
||||
local function setCleanupTables(s1, s2)
|
||||
timeout = 15 -- empty tables after 15 seconds
|
||||
if not LibCompress.frame:IsShown() then
|
||||
LibCompress.frame:Show()
|
||||
end
|
||||
|
||||
if tables_to_clean[s1] then
|
||||
tables_to_clean[s1] = true
|
||||
end
|
||||
if tables_to_clean[s2] then
|
||||
tables_to_clean[s2] = true
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
-- LZW codec
|
||||
-- implemented by sheets.jeff@gmail.com
|
||||
|
||||
-- encode is used to uniquely encode a number into a sequence of bytes that can be decoded using decode()
|
||||
-- the bytes returned by this do not contain "\000"
|
||||
local bytes = {}
|
||||
local function encode(x)
|
||||
local math_modf = math.modf
|
||||
for k = 1, getn(bytes) do bytes[k] = nil end
|
||||
local xmod
|
||||
x, xmod = math_modf(x/255.0)
|
||||
xmod = xmod * 255
|
||||
bytes[getn(bytes) + 1] = xmod
|
||||
while x > 0 do
|
||||
x, xmod = math_modf(x/255.0)
|
||||
xmod = xmod * 255.0
|
||||
bytes[getn(bytes) + 1] = xmod
|
||||
end
|
||||
if getn(bytes) == 1 and bytes[1] > 0 and bytes[1] < 250 then
|
||||
return string_char(bytes[1])
|
||||
else
|
||||
for i = 1, getn(bytes) do bytes[i] = bytes[i] + 1 end
|
||||
return string_char(256 - getn(bytes), unpack(bytes))
|
||||
end
|
||||
end
|
||||
|
||||
--decode converts a unique character sequence into its equivalent number, from ss, beginning at the ith char.
|
||||
-- returns the decoded number and the count of characters used in the decode process.
|
||||
local function decode(ss,i)
|
||||
i = i or 1
|
||||
local a = string_byte(ss,i,i)
|
||||
if a > 249 then
|
||||
local r = 0
|
||||
a = 256 - a
|
||||
for n = i+a, i+1, -1 do
|
||||
r = r * 255 + string_byte(ss,n,n) - 1
|
||||
end
|
||||
return r, a + 1
|
||||
else
|
||||
return a, 1
|
||||
end
|
||||
end
|
||||
|
||||
--
|
||||
-- Added by Shino
|
||||
--
|
||||
function LibCompress:TableToString(t)
|
||||
if t == nil then return nil end
|
||||
if type(t)=="string" then return t end
|
||||
local cache={}
|
||||
local function sub_mod(t)
|
||||
if (type(t)=="table") then
|
||||
for pos,val in pairs(t) do
|
||||
if (type(val)=="table") then
|
||||
table_insert(cache, pos..">".."{")
|
||||
sub_mod(val)
|
||||
table_insert(cache, "}")
|
||||
elseif (type(val)=="string") then
|
||||
table_insert(cache, pos..'>"'..val..'"')
|
||||
else
|
||||
table_insert(cache, pos..">"..tostring(val))
|
||||
end
|
||||
end
|
||||
else
|
||||
table_insert(cache, tostring(t))
|
||||
end
|
||||
end
|
||||
sub_mod(t)
|
||||
return table_concat(cache, ",") -- ? maybe use a different delimiter
|
||||
end
|
||||
|
||||
-- Adding a costum string.split function cause this one has a problem with too big tables
|
||||
-- Credits: https://gist.github.com/jaredallard/ddb152179831dd23b230
|
||||
function LibCompress:StringSplit(delimiter, str)
|
||||
local result = { }
|
||||
local from = 1
|
||||
local delim_from, delim_to = strfind( str, delimiter, from )
|
||||
while delim_from do
|
||||
table_insert( result, strsub( str, from , delim_from-1 ) )
|
||||
from = delim_to + 1
|
||||
delim_from, delim_to = strfind( str, delimiter, from )
|
||||
end
|
||||
table.insert( result, strsub( str, from ) )
|
||||
return result
|
||||
end
|
||||
|
||||
function LibCompress:StringToTable(t)
|
||||
if t=="" or t==nil then return nil end
|
||||
if type(t)=="table" then return t end
|
||||
local table = self:StringSplit(",",t)
|
||||
local function fillSubTable(start)
|
||||
local subT = {}
|
||||
local cont = true
|
||||
local po = nil
|
||||
for k, v in pairs(table) do
|
||||
if k>start then
|
||||
cont = true
|
||||
po = nil
|
||||
for pos in strgfind(v, "(.+)>{") do -- opening sub table
|
||||
po = tonumber(pos)
|
||||
if po then
|
||||
subT[po], start = fillSubTable(k)
|
||||
else
|
||||
subT[pos], start = fillSubTable(k)
|
||||
end
|
||||
end
|
||||
if k>start then -- cause it could have changed if a new table was opened
|
||||
for pos, val in strgfind(v, '(.+)%>"(.+)"') do
|
||||
po = tonumber(pos)
|
||||
if po then
|
||||
subT[po] = ""..val
|
||||
else
|
||||
subT[pos] = ""..val
|
||||
end
|
||||
cont = false
|
||||
end
|
||||
if cont then
|
||||
for pos, val in strgfind(v, "(.+)%>(.+)") do -- Do floats work too?
|
||||
po = tonumber(pos)
|
||||
if val == "false" then
|
||||
if po then
|
||||
subT[po] = false
|
||||
else
|
||||
subT[pos] = false
|
||||
end
|
||||
elseif val == "true" then
|
||||
if po then
|
||||
subT[po] = true
|
||||
else
|
||||
subT[pos] = true
|
||||
end
|
||||
else
|
||||
if po then
|
||||
subT[po] = tonumber(val)
|
||||
else
|
||||
subT[pos] = tonumber(val)
|
||||
end
|
||||
end
|
||||
end
|
||||
if v=="}" then -- closing sub table
|
||||
return subT,k -- Returning the end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return subT, 0
|
||||
end
|
||||
return fillSubTable(0)
|
||||
end
|
||||
|
||||
-- Shino end --
|
||||
|
||||
-- Compresses the given uncompressed string.
|
||||
-- Unless the uncompressed string starts with "\002", this is guaranteed to return a string equal to or smaller than
|
||||
-- the passed string.
|
||||
-- the returned string will only contain "\000" characters in rare circumstances, and will contain none if the
|
||||
-- source string has none.
|
||||
local dict = {}
|
||||
function LibCompress:CompressLZW(uncompressed)
|
||||
if type(uncompressed) == "string" then
|
||||
local dict_size = 256
|
||||
for k, _ in pairs(dict) do
|
||||
dict[k] = nil
|
||||
end
|
||||
local result = {"\002"}
|
||||
local w = ''
|
||||
local ressize = 1
|
||||
for i = 0, 255 do
|
||||
dict[string_char(i)] = i
|
||||
end
|
||||
for i = 1, strlen(uncompressed) do
|
||||
local c = string_sub(uncompressed, i,i)
|
||||
local wc = w..c
|
||||
if dict[wc] then
|
||||
w = wc
|
||||
else
|
||||
dict[wc] = dict_size
|
||||
dict_size = dict_size +1
|
||||
local r = encode(dict[w])
|
||||
ressize = ressize + strlen(r)
|
||||
result[getn(result) + 1] = r
|
||||
w = c
|
||||
end
|
||||
end
|
||||
if w then
|
||||
local r = encode(dict[w])
|
||||
ressize = ressize + strlen(r)
|
||||
result[getn(result) + 1] = r
|
||||
end
|
||||
if (strlen(uncompressed)+1) > ressize then
|
||||
return table_concat(result, "")
|
||||
else
|
||||
return "\002"..uncompressed
|
||||
end
|
||||
else
|
||||
return nil, "Can only compress strings"
|
||||
end
|
||||
end
|
||||
|
||||
-- if the passed string is a compressed string, this will decompress it and return the decompressed string.
|
||||
-- Otherwise it return an error message
|
||||
-- compressed strings are marked by beginning with "\002"
|
||||
function LibCompress:DecompressLZW(compressed)
|
||||
if type(compressed) == "string" then
|
||||
if string_sub(compressed,1,1) ~= "\002" then
|
||||
return nil, "Can only decompress LZW compressed data ("..tostring(string_sub(compressed,1,1))..")"
|
||||
end
|
||||
compressed = string_sub(compressed,2)-- ?
|
||||
local dict_size = 256
|
||||
for k, _ in pairs(dict) do
|
||||
dict[k] = nil
|
||||
end
|
||||
for i = 0, 255 do
|
||||
dict[i] = string_char(i)
|
||||
end
|
||||
local result = {}
|
||||
local t = 1
|
||||
local delta, k
|
||||
k, delta = decode(compressed,t)
|
||||
t = t + delta
|
||||
result[getn(result)+1] = dict[k]
|
||||
local w = dict[k]
|
||||
local entry
|
||||
while t <= strlen(compressed) do
|
||||
k, delta = decode(compressed,t)
|
||||
t = t + delta
|
||||
entry = dict[k] or (w..string_sub(w,1,1))
|
||||
result[getn(result)+1] = entry
|
||||
dict[dict_size] = w..string_sub(entry,1,1)
|
||||
dict_size = dict_size + 1
|
||||
w = entry
|
||||
end
|
||||
return table_concat(result)
|
||||
else
|
||||
return nil, "Can only uncompress strings"
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
-- Huffman codec
|
||||
-- implemented by Galmok of European Stormrage (Horde), galmok@gmail.com
|
||||
|
||||
local function addCode(tree, bcode,len)
|
||||
if tree then
|
||||
tree.bcode = bcode;
|
||||
tree.blength = len;
|
||||
if tree.c1 then
|
||||
addCode(tree.c1, bit_bor(bcode, bit_lshift(1,len)), len+1)
|
||||
end
|
||||
if tree.c2 then
|
||||
addCode(tree.c2, bcode, len+1)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function escape_code(code, len)
|
||||
local escaped_code = 0;
|
||||
local b;
|
||||
local l = 0;
|
||||
for i = len-1, 0,- 1 do
|
||||
b = bit_band( code, bit_lshift(1,i))==0 and 0 or 1
|
||||
escaped_code = bit_lshift(escaped_code,1+b) + b
|
||||
l = l + b;
|
||||
end
|
||||
return escaped_code, len+l
|
||||
end
|
||||
|
||||
tables.Huffman_compressed = {}
|
||||
tables.Huffman_large_compressed = {}
|
||||
|
||||
local compressed_size = 0
|
||||
local remainder;
|
||||
local remainder_length;
|
||||
local function addBits(tbl, code, len)
|
||||
remainder = remainder + bit_lshift(code, remainder_length)
|
||||
remainder_length = len + remainder_length
|
||||
if remainder_length > 32 then
|
||||
return true -- Bits lost due to too long code-words.
|
||||
end
|
||||
while remainder_length>=8 do
|
||||
compressed_size = compressed_size + 1
|
||||
tbl[compressed_size] = string_char(bit_band(remainder, 255))
|
||||
remainder = bit_rshift(remainder, 8)
|
||||
remainder_length = remainder_length -8
|
||||
end
|
||||
end
|
||||
|
||||
-- word size for this huffman algorithm is 8 bits (1 byte). This means the best compression is representing 1 byte with 1 bit, i.e. compress to 0.125 of original size.
|
||||
function LibCompress:CompressHuffman(uncompressed)
|
||||
if not type(uncompressed)=="string" then
|
||||
return nil, "Can only compress strings"
|
||||
end
|
||||
|
||||
-- make histogram
|
||||
local hist = {}
|
||||
local n = 0
|
||||
-- dont have to use all datat to make the histogram
|
||||
local uncompressed_size = string_len(uncompressed)
|
||||
local c;
|
||||
for i = 1, uncompressed_size do
|
||||
c = string_byte(uncompressed, i)
|
||||
hist[c] = (hist[c] or 0) + 1
|
||||
end
|
||||
|
||||
--Start with as many leaves as there are symbols.
|
||||
local leafs = {}
|
||||
local leaf;
|
||||
local symbols = {}
|
||||
for symbol, weight in pairs(hist) do
|
||||
leaf = { symbol=string_char(symbol), weight=weight };
|
||||
symbols[symbol] = leaf;
|
||||
table_insert(leafs, leaf)
|
||||
end
|
||||
--Enqueue all leaf nodes into the first queue (by probability in increasing order so that the least likely item is in the head of the queue).
|
||||
sort(leafs, function(a,b) if a.weight<b.weight then return true elseif a.weight>b.weight then return false else return nil end end)
|
||||
|
||||
local nLeafs = getn(leafs)
|
||||
|
||||
-- create tree
|
||||
local huff = {}
|
||||
--While there is more than one node in the queues:
|
||||
local l,h, li, hi, leaf1, leaf2
|
||||
local newNode;
|
||||
while (getn(leafs)+getn(huff) > 1) do
|
||||
-- Dequeue the two nodes with the lowest weight.
|
||||
-- Dequeue first
|
||||
if not next(huff) then
|
||||
li, leaf1 = next(leafs)
|
||||
table_remove(leafs, li)
|
||||
elseif not next(leafs) then
|
||||
hi, leaf1 = next(huff)
|
||||
table_remove(huff, hi)
|
||||
else
|
||||
li, l = next(leafs);
|
||||
hi, h = next(huff);
|
||||
if l.weight<=h.weight then
|
||||
leaf1 = l;
|
||||
table_remove(leafs, li)
|
||||
else
|
||||
leaf1 = h;
|
||||
table_remove(huff, hi)
|
||||
end
|
||||
end
|
||||
-- Dequeue second
|
||||
if not next(huff) then
|
||||
li, leaf2 = next(leafs)
|
||||
table_remove(leafs, li)
|
||||
elseif not next(leafs) then
|
||||
hi, leaf2 = next(huff)
|
||||
table_remove(huff, hi)
|
||||
else
|
||||
li, l = next(leafs);
|
||||
hi, h = next(huff);
|
||||
if l.weight<=h.weight then
|
||||
leaf2 = l;
|
||||
table_remove(leafs, li)
|
||||
else
|
||||
leaf2 = h;
|
||||
table_remove(huff, hi)
|
||||
end
|
||||
end
|
||||
|
||||
--Create a new internal node, with the two just-removed nodes as children (either node can be either child) and the sum of their weights as the new weight.
|
||||
newNode = { c1 = leaf1, c2 = leaf2, weight = leaf1.weight+leaf2.weight }
|
||||
table_insert(huff,newNode)
|
||||
end
|
||||
if getn(leafs)>0 then
|
||||
li, l = next(leafs)
|
||||
table_insert(huff, l)
|
||||
table_remove(leafs, li)
|
||||
end
|
||||
huff = huff[1];
|
||||
|
||||
-- assign codes to each symbol
|
||||
-- c1 = "0", c2 = "1"
|
||||
-- As a common convention, bit '0' represents following the left child and bit '1' represents following the right child.
|
||||
-- c1 = left, c2 = right
|
||||
|
||||
addCode(huff,0,0);
|
||||
if huff then
|
||||
huff.bcode = 0
|
||||
huff.blength = 1
|
||||
end
|
||||
|
||||
-- READING
|
||||
-- bitfield = 0
|
||||
-- bitfield_len = 0
|
||||
-- read byte1
|
||||
-- bitfield = bitfield + bit_lshift(byte1, bitfield_len)
|
||||
-- bitfield_len = bitfield_len + 8
|
||||
-- read byte2
|
||||
-- bitfield = bitfield + bit_lshift(byte2, bitfield_len)
|
||||
-- bitfield_len = bitfield_len + 8
|
||||
-- (use 5 bits)
|
||||
-- word = bit_band( bitfield, bit_lshift(1,5)-1)
|
||||
-- bitfield = bit_rshift( bitfield, 5)
|
||||
-- bitfield_len = bitfield_len - 5
|
||||
-- read byte3
|
||||
-- bitfield = bitfield + bit_lshift(byte3, bitfield_len)
|
||||
-- bitfield_len = bitfield_len + 8
|
||||
|
||||
-- WRITING
|
||||
remainder = 0;
|
||||
remainder_length = 0;
|
||||
|
||||
local compressed = tables.Huffman_compressed
|
||||
--compressed_size = 0
|
||||
|
||||
-- first byte is version info. 0 = uncompressed, 1 = 8-bit word huffman compressed
|
||||
compressed[1] = "\003"
|
||||
|
||||
-- Header: byte 0=#leafs, byte 1-3=size of uncompressed data
|
||||
-- max 2^24 bytes
|
||||
local l = string_len(uncompressed)
|
||||
compressed[2] = string_char(bit_band(nLeafs-1, 255)) -- number of leafs
|
||||
compressed[3] = string_char(bit_band(l, 255)) -- bit 0-7
|
||||
compressed[4] = string_char(bit_band(bit_rshift(l, 8), 255)) -- bit 8-15
|
||||
compressed[5] = string_char(bit_band(bit_rshift(l, 16), 255)) -- bit 16-23
|
||||
compressed_size = 5
|
||||
|
||||
-- create symbol/code map
|
||||
for symbol, leaf in pairs(symbols) do
|
||||
addBits(compressed, symbol, 8);
|
||||
if addBits(compressed, escape_code(leaf.bcode, leaf.blength)) then
|
||||
-- code word too long. Needs new revision to be able to handle more than 32 bits
|
||||
return string_char(0)..uncompressed
|
||||
end
|
||||
addBits(compressed, 3, 2);
|
||||
end
|
||||
|
||||
-- create huffman code
|
||||
local large_compressed = tables.Huffman_large_compressed
|
||||
local large_compressed_size = 0
|
||||
local ulimit
|
||||
for i = 1, l, 200 do
|
||||
ulimit = l<(i+199) and l or (i+199)
|
||||
for sub_i = i, ulimit do
|
||||
c = string_byte(uncompressed, sub_i)
|
||||
addBits(compressed, symbols[c].bcode, symbols[c].blength)
|
||||
end
|
||||
large_compressed_size = large_compressed_size + 1
|
||||
large_compressed[large_compressed_size] = table_concat(compressed, "", 1, compressed_size)
|
||||
compressed_size = 0
|
||||
end
|
||||
|
||||
-- add remainding bits (if any)
|
||||
if remainder_length>0 then
|
||||
large_compressed_size = large_compressed_size + 1
|
||||
large_compressed[large_compressed_size] = string_char(remainder)
|
||||
end
|
||||
local compressed_string = table_concat(large_compressed, "", 1, large_compressed_size)
|
||||
|
||||
-- is compression worth it? If not, return uncompressed data.
|
||||
if (strlen(uncompressed)+1) <= strlen(compressed_string) then
|
||||
return "\001"..uncompressed
|
||||
end
|
||||
|
||||
setCleanupTables("Huffman_compressed", "Huffman_large_compressed")
|
||||
return compressed_string
|
||||
end
|
||||
|
||||
-- lookuptable (cached between calls)
|
||||
local lshiftMask = {}
|
||||
setmetatable(lshiftMask, {
|
||||
__index = function (t, k)
|
||||
local v = bit_lshift(1, k)
|
||||
rawset(t, k, v)
|
||||
return v
|
||||
end
|
||||
})
|
||||
|
||||
-- lookuptable (cached between calls)
|
||||
local lshiftMinusOneMask = {}
|
||||
setmetatable(lshiftMinusOneMask, {
|
||||
__index = function (t, k)
|
||||
local v = bit_lshift(1, k)-1
|
||||
rawset(t, k, v)
|
||||
return v
|
||||
end
|
||||
})
|
||||
|
||||
local function getCode(bitfield, field_len)
|
||||
if field_len>=2 then
|
||||
local b;
|
||||
local p = 0;
|
||||
for i = 0, field_len-1 do
|
||||
b = bit_band(bitfield, lshiftMask[i])
|
||||
if not (p==0) and not (b == 0) then
|
||||
-- found 2 bits set right after each other (stop bits)
|
||||
return bit_band( bitfield, lshiftMinusOneMask[i-1]), i-1,
|
||||
bit_rshift(bitfield, i+1), field_len-i-1
|
||||
end
|
||||
p = b
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function unescape_code(code, code_len)
|
||||
local unescaped_code=0;
|
||||
local b;
|
||||
local l = 0;
|
||||
local i = 0
|
||||
while i < code_len do
|
||||
b = bit_band( code, lshiftMask[i])
|
||||
if not (b==0) then
|
||||
unescaped_code = bit_bor(unescaped_code, lshiftMask[l])
|
||||
i = i + 1
|
||||
end
|
||||
i = i + 1
|
||||
l = l + 1
|
||||
end
|
||||
return unescaped_code, l
|
||||
end
|
||||
|
||||
tables.Huffman_uncompressed = {}
|
||||
tables.Huffman_large_uncompressed = {} -- will always be as big as the larges string ever decompressed. Bad, but clearing i every timetakes precious time.
|
||||
|
||||
function LibCompress:DecompressHuffman(compressed)
|
||||
if type(compressed)~="string" or compressed == nil then
|
||||
if type(compressed)=="table" then
|
||||
return compressed
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local compressed_size = strlen(compressed)
|
||||
--decode header
|
||||
local info_byte = string_byte(compressed)
|
||||
-- is data compressed
|
||||
if info_byte==1 then
|
||||
return string_sub(compressed,2) --return uncompressed data
|
||||
end
|
||||
if not (info_byte==3) then
|
||||
return nil, "Can only decompress Huffman compressed data ("..tostring(info_byte)..")"
|
||||
end
|
||||
|
||||
local num_symbols = string_byte(string_sub(compressed, 2, 2)) + 1
|
||||
local c0 = string_byte(string_sub(compressed, 3, 3))
|
||||
local c1 = string_byte(string_sub(compressed, 4, 4))
|
||||
local c2 = string_byte(string_sub(compressed, 5, 5))
|
||||
local orig_size = c2*65536 + c1*256 + c0
|
||||
if orig_size==0 then
|
||||
return "";
|
||||
end
|
||||
|
||||
-- decode code->symbal map
|
||||
local bitfield = 0;
|
||||
local bitfield_len = 0;
|
||||
local map = {} -- only table not reused in Huffman decode.
|
||||
setmetatable(map, {
|
||||
__index = function (t, k)
|
||||
local v = {}
|
||||
rawset(t, k, v)
|
||||
return v
|
||||
end
|
||||
})
|
||||
|
||||
local i = 6; -- byte 1-5 are header bytes
|
||||
local c, cl;
|
||||
local minCodeLen = 1000;
|
||||
local maxCodeLen = 0;
|
||||
local symbol, code, code_len, _bitfield, _bitfield_len;
|
||||
local n = 0;
|
||||
local state = 0; -- 0 = get symbol (8 bits), 1 = get code (varying bits, ends with 2 bits set)
|
||||
while n<num_symbols do
|
||||
if i>compressed_size then
|
||||
return nil, "Cannot decode map"
|
||||
end
|
||||
|
||||
c = string_byte(compressed, i)
|
||||
bitfield = bit_bor(bitfield, bit_lshift(c, bitfield_len))
|
||||
bitfield_len = bitfield_len + 8
|
||||
|
||||
if state == 0 then
|
||||
symbol = bit_band(bitfield, 255)
|
||||
bitfield = bit_rshift(bitfield, 8)
|
||||
bitfield_len = bitfield_len -8
|
||||
state = 1 -- search for code now
|
||||
else
|
||||
code, code_len, _bitfield, _bitfield_len = getCode(bitfield, bitfield_len)
|
||||
if code then
|
||||
bitfield, bitfield_len = _bitfield, _bitfield_len
|
||||
c, cl = unescape_code(code, code_len)
|
||||
map[cl][c]=string_char(symbol)
|
||||
minCodeLen = cl<minCodeLen and cl or minCodeLen
|
||||
maxCodeLen = cl>maxCodeLen and cl or maxCodeLen
|
||||
--print("symbol: "..string_char(symbol).." code: "..tobinary(c, cl))
|
||||
n = n + 1
|
||||
state = 0 -- search for next symbol (if any)
|
||||
end
|
||||
end
|
||||
i=i+1
|
||||
end
|
||||
|
||||
-- dont create new subtables for entries not in the map. Waste of space.
|
||||
-- But do return an empty table to prevent runtime errors. (instead of returning nil)
|
||||
local mt = {}
|
||||
setmetatable(map, {
|
||||
__index = function (t, k)
|
||||
return mt
|
||||
end
|
||||
})
|
||||
|
||||
local uncompressed = tables.Huffman_uncompressed
|
||||
local large_uncompressed = tables.Huffman_large_uncompressed
|
||||
local uncompressed_size = 0
|
||||
local large_uncompressed_size = 0
|
||||
local test_code
|
||||
local test_code_len = minCodeLen;
|
||||
local symbol;
|
||||
local dec_size = 0;
|
||||
compressed_size = compressed_size + 1
|
||||
local temp_limit = 200; -- first limit of uncompressed data. large_uncompressed will hold strings of length 200
|
||||
while true do
|
||||
if test_code_len<=bitfield_len then
|
||||
test_code=bit_band( bitfield, lshiftMinusOneMask[test_code_len])
|
||||
symbol = map[test_code_len][test_code]
|
||||
if symbol then
|
||||
uncompressed_size = uncompressed_size + 1
|
||||
uncompressed[uncompressed_size]=symbol
|
||||
dec_size = dec_size + 1
|
||||
|
||||
if dec_size>=orig_size then -- checked here for speed reasons
|
||||
break;
|
||||
end
|
||||
-- process compressed bytes in smaller chunks
|
||||
large_uncompressed_size = large_uncompressed_size + 1
|
||||
large_uncompressed[large_uncompressed_size] = table_concat(uncompressed, "", 1, uncompressed_size)
|
||||
uncompressed_size = 0
|
||||
temp_limit = temp_limit + 200 -- repeated chunk size is 200 uncompressed bytes
|
||||
temp_limit = temp_limit > orig_size and orig_size or temp_limit
|
||||
|
||||
bitfield = bit_rshift(bitfield, test_code_len)
|
||||
bitfield_len = bitfield_len - test_code_len
|
||||
test_code_len = minCodeLen
|
||||
else
|
||||
test_code_len = test_code_len + 1
|
||||
if test_code_len>maxCodeLen then
|
||||
return nil, "Decompression error at "..tostring(i).."/"..tostring(strlen(compressed))
|
||||
end
|
||||
end
|
||||
else
|
||||
c = string_byte(compressed, i)
|
||||
bitfield = bitfield + bit_lshift(c or 0, bitfield_len)
|
||||
bitfield_len = bitfield_len + 8
|
||||
i = i + 1
|
||||
if i > temp_limit then
|
||||
if i > compressed_size then
|
||||
break;
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
setCleanupTables("Huffman_uncompressed", "Huffman_large_uncompressed")
|
||||
return table_concat(large_uncompressed, "", 1, large_uncompressed_size)..table_concat(uncompressed, "", 1, uncompressed_size)
|
||||
end
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
-- Generic codec interface
|
||||
|
||||
function LibCompress:DecompressUncompressed(data)
|
||||
if type(data)~="string" then
|
||||
return nil, "Can only handle strings"
|
||||
end
|
||||
if string.byte(data) ~= 1 then
|
||||
return nil, "Can only handle uncompressed data"
|
||||
end
|
||||
return string_sub(data, 2)
|
||||
end
|
||||
|
||||
local compression_methods = {
|
||||
[2] = LibCompress.CompressLZW,
|
||||
[3] = LibCompress.CompressHuffman
|
||||
}
|
||||
|
||||
local decompression_methods = {
|
||||
[1] = LibCompress.DecompressUncompressed,
|
||||
[2] = LibCompress.DecompressLZW,
|
||||
[3] = LibCompress.DecompressHuffman
|
||||
}
|
||||
|
||||
-- try all compression codecs and return best result
|
||||
function LibCompress:Compress(data)
|
||||
local method = next(compression_methods)
|
||||
local result = compression_methods[method](self, data)
|
||||
local nTable = {}
|
||||
local rTable = {}
|
||||
local n
|
||||
method = next(compression_methods, method)
|
||||
while method do
|
||||
n = compression_methods[method](self, data)
|
||||
nTable = {}
|
||||
for i = 1, strlen(n) do
|
||||
nTable[i] = string.sub(n, i, i)
|
||||
end
|
||||
for i = 1, strlen(result) do
|
||||
rTable[i] = string.sub(result, i, i)
|
||||
end
|
||||
if getn(nTable) < getn(rTable) then
|
||||
result = nTable
|
||||
end
|
||||
method = next(compression_methods, method)
|
||||
end
|
||||
return result
|
||||
end
|
||||
|
||||
function LibCompress:Decompress(data)
|
||||
local header_info = string.byte(data)
|
||||
if decompression_methods[header_info] then
|
||||
return decompression_methods[header_info](self, data)
|
||||
else
|
||||
return nil, "Unknown compression method ("..tostring(header_info)..")"
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,3 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="LibCompress.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,90 @@
|
||||
|
||||
assert(LibStub, "LibDataBroker-1.1 requires LibStub")
|
||||
assert(LibStub:GetLibrary("CallbackHandler-1.0", true), "LibDataBroker-1.1 requires CallbackHandler-1.0")
|
||||
|
||||
local lib, oldminor = LibStub:NewLibrary("LibDataBroker-1.1", 4)
|
||||
if not lib then return end
|
||||
oldminor = oldminor or 0
|
||||
|
||||
|
||||
lib.callbacks = lib.callbacks or LibStub:GetLibrary("CallbackHandler-1.0"):New(lib)
|
||||
lib.attributestorage, lib.namestorage, lib.proxystorage = lib.attributestorage or {}, lib.namestorage or {}, lib.proxystorage or {}
|
||||
local attributestorage, namestorage, callbacks = lib.attributestorage, lib.namestorage, lib.callbacks
|
||||
|
||||
if oldminor < 2 then
|
||||
lib.domt = {
|
||||
__metatable = "access denied",
|
||||
__index = function(self, key) return attributestorage[self] and attributestorage[self][key] end,
|
||||
}
|
||||
end
|
||||
|
||||
if oldminor < 3 then
|
||||
lib.domt.__newindex = function(self, key, value)
|
||||
if not attributestorage[self] then attributestorage[self] = {} end
|
||||
if attributestorage[self][key] == value then return end
|
||||
attributestorage[self][key] = value
|
||||
local name = namestorage[self]
|
||||
if not name then return end
|
||||
callbacks:Fire("LibDataBroker_AttributeChanged", name, key, value, self)
|
||||
callbacks:Fire("LibDataBroker_AttributeChanged_"..name, name, key, value, self)
|
||||
callbacks:Fire("LibDataBroker_AttributeChanged_"..name.."_"..key, name, key, value, self)
|
||||
callbacks:Fire("LibDataBroker_AttributeChanged__"..key, name, key, value, self)
|
||||
end
|
||||
end
|
||||
|
||||
if oldminor < 2 then
|
||||
function lib:NewDataObject(name, dataobj)
|
||||
if self.proxystorage[name] then return end
|
||||
|
||||
if dataobj then
|
||||
assert(type(dataobj) == "table", "Invalid dataobj, must be nil or a table")
|
||||
self.attributestorage[dataobj] = {}
|
||||
for i,v in pairs(dataobj) do
|
||||
self.attributestorage[dataobj][i] = v
|
||||
dataobj[i] = nil
|
||||
end
|
||||
end
|
||||
dataobj = setmetatable(dataobj or {}, self.domt)
|
||||
self.proxystorage[name], self.namestorage[dataobj] = dataobj, name
|
||||
self.callbacks:Fire("LibDataBroker_DataObjectCreated", name, dataobj)
|
||||
return dataobj
|
||||
end
|
||||
end
|
||||
|
||||
if oldminor < 1 then
|
||||
function lib:DataObjectIterator()
|
||||
return pairs(self.proxystorage)
|
||||
end
|
||||
|
||||
function lib:GetDataObjectByName(dataobjectname)
|
||||
return self.proxystorage[dataobjectname]
|
||||
end
|
||||
|
||||
function lib:GetNameByDataObject(dataobject)
|
||||
return self.namestorage[dataobject]
|
||||
end
|
||||
end
|
||||
|
||||
if oldminor < 4 then
|
||||
local next = pairs(attributestorage)
|
||||
function lib:pairs(dataobject_or_name)
|
||||
local t = type(dataobject_or_name)
|
||||
assert(t == "string" or t == "table", "Usage: ldb:pairs('dataobjectname') or ldb:pairs(dataobject)")
|
||||
|
||||
local dataobj = self.proxystorage[dataobject_or_name] or dataobject_or_name
|
||||
assert(attributestorage[dataobj], "Data object not found")
|
||||
|
||||
return next, attributestorage[dataobj], nil
|
||||
end
|
||||
|
||||
local ipairs_iter = ipairs(attributestorage)
|
||||
function lib:ipairs(dataobject_or_name)
|
||||
local t = type(dataobject_or_name)
|
||||
assert(t == "string" or t == "table", "Usage: ldb:ipairs('dataobjectname') or ldb:ipairs(dataobject)")
|
||||
|
||||
local dataobj = self.proxystorage[dataobject_or_name] or dataobject_or_name
|
||||
assert(attributestorage[dataobj], "Data object not found")
|
||||
|
||||
return ipairs_iter, attributestorage[dataobj], 0
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,3 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="LibDataBroker-1.1.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,244 @@
|
||||
local MAJOR, MINOR = "LibElvUIPlugin-1.0", 18
|
||||
local lib, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
|
||||
if not lib then return end
|
||||
|
||||
--Cache global variables
|
||||
--Lua functions
|
||||
local pairs, tonumber = pairs, tonumber
|
||||
local format, gsub, strmatch, strsplit = format, gsub, strmatch, strsplit
|
||||
--WoW API / Variables
|
||||
local CreateFrame = CreateFrame
|
||||
local GetAddOnMetadata = GetAddOnMetadata
|
||||
local GetNumPartyMembers, GetNumRaidMembers = GetNumPartyMembers, GetNumRaidMembers
|
||||
local IsAddOnLoaded = IsAddOnLoaded
|
||||
local IsInInstance = IsInInstance
|
||||
local SendAddonMessage = SendAddonMessage
|
||||
|
||||
--Global variables that we don't cache, list them here for the mikk's Find Globals script
|
||||
-- GLOBALS: ElvUI
|
||||
|
||||
lib.plugins = {}
|
||||
lib.index = 0
|
||||
lib.prefix = "ElvUIPluginVC"
|
||||
|
||||
-- MULTI Language Support (Default Language: English)
|
||||
local MSG_OUTDATED = "Your version of %s %s is out of date (latest is version %s). You can download the latest version from https://github.com/ElvUI-Vanilla/ElvUI/"
|
||||
local HDR_CONFIG = "Plugins"
|
||||
local HDR_INFORMATION = "LibElvUIPlugin-1.0.%d - Plugins Loaded (Green means you have current version, Red means out of date)"
|
||||
local INFO_BY = "by"
|
||||
local INFO_VERSION = "Version:"
|
||||
local INFO_NEW = "Newest:"
|
||||
local LIBRARY = "Library"
|
||||
|
||||
if GetLocale() == "deDE" then -- German Translation
|
||||
MSG_OUTDATED = "Deine Version von %s %s ist veraltet (akutelle Version ist %s). Du kannst die aktuelle Version von https://github.com/ElvUI-Vanilla/ElvUI/ herunterrladen."
|
||||
HDR_CONFIG = "Plugins"
|
||||
HDR_INFORMATION = "LibElvUIPlugin-1.0.%d - Plugins geladen (Grün bedeutet du hast die aktuelle Version, Rot bedeutet es ist veraltet)"
|
||||
INFO_BY = "von"
|
||||
INFO_VERSION = "Version:"
|
||||
INFO_NEW = "Neuste:"
|
||||
LIBRARY = "Bibliothek"
|
||||
end
|
||||
|
||||
if GetLocale() == "ruRU" then -- Russian Translations
|
||||
MSG_OUTDATED = "Ваша версия %s %s устарела (последняя версия %s). Вы можете скачать последнюю версию на https://github.com/ElvUI-Vanilla/ElvUI/"
|
||||
HDR_CONFIG = "Плагины"
|
||||
HDR_INFORMATION = "LibElvUIPlugin-1.0.%d - загруженные плагины (зеленый означает, что у вас последняя версия, красный - устаревшая)"
|
||||
INFO_BY = "от"
|
||||
INFO_VERSION = "Версия:"
|
||||
INFO_NEW = "Последняя:"
|
||||
LIBRARY = "Библиотека"
|
||||
end
|
||||
|
||||
--
|
||||
-- Plugin table format:
|
||||
-- { name (string) - The name of the plugin,
|
||||
-- version (string) - The version of the plugin,
|
||||
-- optionCallback (string) - The callback to call when ElvUI_Config is loaded
|
||||
-- }
|
||||
--
|
||||
|
||||
--
|
||||
-- RegisterPlugin(name,callback)
|
||||
-- Registers a module with the given name and option callback, pulls version info from metadata
|
||||
--
|
||||
|
||||
function lib:RegisterPlugin(name, callback, isLib)
|
||||
local plugin = {}
|
||||
plugin.name = name
|
||||
plugin.version = name == MAJOR and MINOR or GetAddOnMetadata(name, "Version")
|
||||
if isLib then plugin.isLib = true; plugin.version = 1 end
|
||||
plugin.callback = callback
|
||||
lib.plugins[name] = plugin
|
||||
local loaded = IsAddOnLoaded("ElvUI_Config")
|
||||
|
||||
if not lib.vcframe then
|
||||
local f = CreateFrame("Frame")
|
||||
f:RegisterEvent("RAID_ROSTER_UPDATE")
|
||||
f:RegisterEvent("PARTY_MEMBERS_CHANGED")
|
||||
f:RegisterEvent("CHAT_MSG_ADDON")
|
||||
f:SetScript("OnEvent", lib.VersionCheck)
|
||||
lib.vcframe = f
|
||||
end
|
||||
|
||||
if not loaded then
|
||||
if not lib.ConfigFrame then
|
||||
local configFrame = CreateFrame("Frame")
|
||||
configFrame:RegisterEvent("ADDON_LOADED")
|
||||
configFrame:SetScript("OnEvent", function()
|
||||
if arg1 == "ElvUI_Config" then
|
||||
for _, PlugIn in pairs(lib.plugins) do
|
||||
if PlugIn.callback then
|
||||
PlugIn.callback()
|
||||
end
|
||||
end
|
||||
end
|
||||
end)
|
||||
lib.ConfigFrame = configFrame
|
||||
end
|
||||
elseif loaded then
|
||||
-- Need to update plugins list
|
||||
if name ~= MAJOR then
|
||||
ElvUI[1].Options.args.plugins.args.plugins.name = lib:GeneratePluginList()
|
||||
end
|
||||
callback()
|
||||
end
|
||||
|
||||
return plugin
|
||||
end
|
||||
|
||||
function lib:GetPluginOptions()
|
||||
ElvUI[1].Options.args.plugins = {
|
||||
order = -10,
|
||||
type = "group",
|
||||
name = HDR_CONFIG,
|
||||
guiInline = false,
|
||||
args = {
|
||||
pluginheader = {
|
||||
order = 1,
|
||||
type = "header",
|
||||
name = format(HDR_INFORMATION, MINOR),
|
||||
},
|
||||
plugins = {
|
||||
order = 2,
|
||||
type = "description",
|
||||
name = lib:GeneratePluginList(),
|
||||
},
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
function lib:GenerateVersionCheckMessage()
|
||||
local list = ""
|
||||
for _, plugin in pairs(lib.plugins) do
|
||||
if plugin.name ~= MAJOR then
|
||||
list = list..plugin.name.."="..plugin.version..";"
|
||||
end
|
||||
end
|
||||
return list
|
||||
end
|
||||
|
||||
local function SendPluginVersionCheck(self)
|
||||
lib:SendPluginVersionCheck(lib:GenerateVersionCheckMessage())
|
||||
|
||||
if self["ElvUIPluginSendMSGTimer"] then
|
||||
self:CancelTimer(self["ElvUIPluginSendMSGTimer"])
|
||||
self["ElvUIPluginSendMSGTimer"] = nil
|
||||
end
|
||||
end
|
||||
|
||||
function lib:VersionCheck()
|
||||
if not ElvUI[1].global.general.versionCheck then return end
|
||||
|
||||
local E = ElvUI[1]
|
||||
if event == "CHAT_MSG_ADDON" then
|
||||
if not (arg1 == lib.prefix and arg4 and arg1 and not strmatch(arg1, "^%s-$")) then return end
|
||||
if arg4 == E.myname then return end
|
||||
|
||||
if not E["pluginRecievedOutOfDateMessage"] then
|
||||
local name, version, plugin, Pname
|
||||
for _, p in pairs({strsplit(";", arg2)}) do
|
||||
if not strmatch(p, "^%s-$") then
|
||||
name, version = strmatch(p, "([%w_]+)=([%d%p]+)")
|
||||
if lib.plugins[name] then
|
||||
plugin = lib.plugins[name]
|
||||
if plugin.version ~= "BETA" and version and tonumber(version) and plugin.version and tonumber(plugin.version) and tonumber(version) > tonumber(plugin.version) then
|
||||
plugin.old = true
|
||||
plugin.newversion = tonumber(version)
|
||||
Pname = GetAddOnMetadata(plugin.name, "Title")
|
||||
E:Print(format(MSG_OUTDATED, Pname, plugin.version, plugin.newversion))
|
||||
E["pluginRecievedOutOfDateMessage"] = true
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
if not E.SendPluginVersionCheck then
|
||||
E.SendPluginVersionCheck = SendPluginVersionCheck
|
||||
end
|
||||
|
||||
local numRaid, numParty = GetNumRaidMembers(), GetNumPartyMembers() + 1
|
||||
local num = numRaid > 0 and numRaid or numParty
|
||||
if num ~= lib.groupSize then
|
||||
if num > 1 and ((lib.groupSize and num > lib.groupSize) or not lib.groupSize) then
|
||||
E["ElvUIPluginSendMSGTimer"] = E:ScheduleTimer("SendPluginVersionCheck", 12)
|
||||
end
|
||||
lib.groupSize = num
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function lib:GeneratePluginList()
|
||||
local list, E = "", ElvUI[1]
|
||||
local author, Pname, color
|
||||
for _, plugin in pairs(lib.plugins) do
|
||||
if plugin.name ~= MAJOR then
|
||||
author = GetAddOnMetadata(plugin.name, "Author")
|
||||
Pname = GetAddOnMetadata(plugin.name, "Title") or plugin.name
|
||||
color = plugin.old and E:RGBToHex(1, 0, 0) or E:RGBToHex(0, 1, 0)
|
||||
list = list .. Pname
|
||||
if author then
|
||||
list = list .. " ".. INFO_BY .." " .. author
|
||||
end
|
||||
list = list .. color .. (plugin.isLib and " " .. LIBRARY or " - " .. INFO_VERSION .. " " .. plugin.version)
|
||||
if plugin.old then
|
||||
list = list .. " (" .. INFO_NEW .." " .. plugin.newversion .. ")"
|
||||
end
|
||||
list = list .. "|r\n"
|
||||
end
|
||||
end
|
||||
return list
|
||||
end
|
||||
|
||||
function lib:SendPluginVersionCheck(message)
|
||||
if not message or strmatch(message, "^%s-$") then return end
|
||||
|
||||
local ChatType
|
||||
if GetNumRaidMembers() > 1 then
|
||||
local _, instanceType = IsInInstance()
|
||||
ChatType = instanceType == "pvp" and "BATTLEGROUND" or "RAID"
|
||||
elseif GetNumPartyMembers() > 0 then
|
||||
ChatType = "PARTY"
|
||||
end
|
||||
if not ChatType then return end
|
||||
|
||||
local maxChar, msgLength = 254 - strlen(lib.prefix), strlen(message)
|
||||
if msgLength > maxChar then
|
||||
local delay, splitMessage = 0
|
||||
|
||||
for _ = 1, ceil(msgLength / maxChar) do
|
||||
splitMessage = strmatch(strsub(message, 1, maxChar), ".+;")
|
||||
|
||||
if splitMessage then -- incase the string is over `maxChar` but doesnt contain `;`
|
||||
message = gsub(message, "^"..gsub(splitMessage, "([%-%.%+%[%]%(%)%$%^%%%?%*])","%%%1"), "")
|
||||
ElvUI[1]:Delay(delay, SendAddonMessage, lib.prefix, splitMessage, ChatType)
|
||||
delay = delay + 1
|
||||
end
|
||||
end
|
||||
else
|
||||
SendAddonMessage(lib.prefix, message, ChatType)
|
||||
end
|
||||
end
|
||||
|
||||
lib:RegisterPlugin(MAJOR, lib.GetPluginOptions)
|
||||
@@ -0,0 +1,3 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="LibElvUIPlugin-1.0.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,204 @@
|
||||
--[[
|
||||
Copyright 2013 João Cardoso
|
||||
CustomSearch is distributed under the terms of the GNU General Public License (Version 3).
|
||||
As a special exception, the copyright holders of this library give you permission to embed it
|
||||
with independent modules to produce an addon, regardless of the license terms of these
|
||||
independent modules, and to copy and distribute the resulting software under terms of your
|
||||
choice, provided that you also meet, for each embedded independent module, the terms and
|
||||
conditions of the license of that module. Permission is not granted to modify this library.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with the library. If not, see <http://www.gnu.org/licenses/gpl-3.0.txt>.
|
||||
|
||||
This file is part of CustomSearch.
|
||||
--]]
|
||||
|
||||
local Lib = LibStub:NewLibrary('CustomSearch-1.0', 9)
|
||||
if not Lib then
|
||||
return
|
||||
end
|
||||
|
||||
local find, gmatch, lower, match = string.find, string.gmatch, string.lower, string.match
|
||||
|
||||
--[[ Parsing ]]--
|
||||
|
||||
function Lib:Matches(object, search, filters)
|
||||
if object then
|
||||
self.filters = filters
|
||||
self.object = object
|
||||
|
||||
return self:MatchAll(search or '')
|
||||
end
|
||||
end
|
||||
|
||||
function Lib:MatchAll(search)
|
||||
for phrase in gmatch(self:Clean(search), '[^&]+') do
|
||||
if not self:MatchAny(phrase) then
|
||||
return
|
||||
end
|
||||
end
|
||||
|
||||
return true
|
||||
end
|
||||
|
||||
function Lib:MatchAny(search)
|
||||
for phrase in gmatch(search, '[^|]+') do
|
||||
if self:Match(phrase) then
|
||||
return true
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Lib:Match(search)
|
||||
local tag, rest = match(search, '^%s*(%S+):(.*)$')
|
||||
if tag then
|
||||
tag = '^' .. tag
|
||||
search = rest
|
||||
end
|
||||
|
||||
local words = gmatch(search, '%S+')
|
||||
local failed
|
||||
|
||||
for word in words do
|
||||
if word == self.OR then
|
||||
if failed then
|
||||
failed = false
|
||||
else
|
||||
break
|
||||
end
|
||||
|
||||
else
|
||||
local negate, rest = match(word, '^([!~]=*)(.*)$')
|
||||
if negate or word == self.NOT_MATCH then
|
||||
word = rest and rest ~= '' and rest or words() or ''
|
||||
negate = -1
|
||||
else
|
||||
negate = 1
|
||||
end
|
||||
|
||||
local operator, rest = match(word, '^(=*[<>]=*)(.*)$')
|
||||
if operator then
|
||||
word = rest ~= '' and rest or words()
|
||||
end
|
||||
|
||||
local result = self:Filter(tag, operator, word) and 1 or -1
|
||||
if result * negate ~= 1 then
|
||||
failed = true
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return not failed
|
||||
end
|
||||
|
||||
|
||||
--[[ Filtering ]]--
|
||||
|
||||
function Lib:Filter(tag, operator, search)
|
||||
if not search then
|
||||
return true
|
||||
end
|
||||
|
||||
if tag then
|
||||
for _, filter in pairs(self.filters) do
|
||||
for _, value in pairs(filter.tags or {}) do
|
||||
if find(value, tag) then
|
||||
return self:UseFilter(filter, operator, search)
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
for _, filter in pairs(self.filters) do
|
||||
if not filter.onlyTags and self:UseFilter(filter, operator, search) then
|
||||
return true
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Lib:UseFilter(filter, operator, search)
|
||||
local data = {filter:canSearch(operator, search, self.object)}
|
||||
if data[1] then
|
||||
return match(filter, self.object, operator, unpack(data))
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
--[[ Utilities ]]--
|
||||
|
||||
function Lib:Find(search, ...)
|
||||
for i = 1, getn(arg) do
|
||||
local text = arg[i]
|
||||
if text and find(self:Clean(text), search) then
|
||||
return true
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Lib:Clean(string)
|
||||
string = lower(string)
|
||||
string = gsub(string, '[%(%)%.%%%+%-%*%?%[%]%^%$]', function(c) return '%'..c end)
|
||||
|
||||
for accent, char in pairs(self.ACCENTS) do
|
||||
string = gsub(string, accent, char)
|
||||
end
|
||||
|
||||
return string
|
||||
end
|
||||
|
||||
function Lib:Compare(op, a, b)
|
||||
if op then
|
||||
if find(op, '<') then
|
||||
if find(op, '=') then
|
||||
return a <= b
|
||||
end
|
||||
|
||||
return a < b
|
||||
end
|
||||
|
||||
if find(op, '>')then
|
||||
if find(op, '=') then
|
||||
return a >= b
|
||||
end
|
||||
|
||||
return a > b
|
||||
end
|
||||
end
|
||||
|
||||
return a == b
|
||||
end
|
||||
|
||||
|
||||
--[[ Localization ]]--
|
||||
|
||||
do
|
||||
local no = {enUS = 'Not', frFR = 'Pas', deDE = 'Nicht', ruRU = 'Нет'}
|
||||
local just_or = {enUS = 'Or', frFR = 'Ou', deDE = 'Oder', ruRU = 'Или'}
|
||||
local accents = {
|
||||
a = {'à','â','ã','å'},
|
||||
e = {'è','é','ê','ê','ë'},
|
||||
i = {'ì', 'í', 'î', 'ï'},
|
||||
o = {'ó','ò','ô','õ'},
|
||||
u = {'ù', 'ú', 'û', 'ü'},
|
||||
c = {'ç'}, n = {'ñ'}
|
||||
}
|
||||
|
||||
Lib.ACCENTS = {}
|
||||
for char, accents in pairs(accents) do
|
||||
for _, accent in ipairs(accents) do
|
||||
Lib.ACCENTS[accent] = char
|
||||
end
|
||||
end
|
||||
|
||||
Lib.OR = Lib:Clean(just_or[GetLocale()] or "")
|
||||
Lib.NOT = no[GetLocale()] or NO
|
||||
Lib.NOT_MATCH = Lib:Clean(Lib.NOT)
|
||||
setmetatable(Lib, {__call = Lib.Matches})
|
||||
end
|
||||
|
||||
return Lib
|
||||
@@ -0,0 +1,4 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/
|
||||
..\FrameXML\UI.xsd">
|
||||
<Script file="CustomSearch-1.0.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,212 @@
|
||||
--[[
|
||||
ItemSearch
|
||||
An item text search engine of some sort
|
||||
--]]
|
||||
|
||||
local Search = LibStub("CustomSearch-1.0");
|
||||
local Unfit = LibStub("Unfit-1.0");
|
||||
local Lib = LibStub:NewLibrary("LibItemSearch-1.2", 11);
|
||||
if Lib then
|
||||
Lib.Filters = {}
|
||||
else
|
||||
return
|
||||
end
|
||||
|
||||
local tonumber = tonumber
|
||||
local find, strmatch, lower = string.find, string.match, string.lower
|
||||
|
||||
--[[ User API ]]--
|
||||
|
||||
function Lib:Matches(link, search)
|
||||
return Search(link, search, self.Filters)
|
||||
end
|
||||
|
||||
function Lib:Tooltip(link, search)
|
||||
return link and strmatch(self.Filters.tip, link, nil, search)
|
||||
end
|
||||
|
||||
function Lib:TooltipPhrase(link, search)
|
||||
return link and strmatch(self.Filters.tipPhrases, link, nil, search)
|
||||
end
|
||||
|
||||
--[[ Basics ]]--
|
||||
|
||||
Lib.Filters.name = {
|
||||
tags = {"n", "name"},
|
||||
|
||||
canSearch = function(self, operator, search)
|
||||
return not operator and search
|
||||
end,
|
||||
|
||||
match = function(self, item, _, search)
|
||||
local name = strmatch(item, "%[(.-)%]")
|
||||
return Search:Find(search, name)
|
||||
end
|
||||
}
|
||||
|
||||
Lib.Filters.type = {
|
||||
tags = {"t", "type", "s", "slot"},
|
||||
|
||||
canSearch = function(self, operator, search)
|
||||
return not operator and search
|
||||
end,
|
||||
|
||||
match = function(self, item, _, search)
|
||||
local type, subType, _, equipSlot = select(6, GetItemInfo(item))
|
||||
return Search:Find(search, type, subType, _G[equipSlot])
|
||||
end
|
||||
}
|
||||
|
||||
Lib.Filters.level = {
|
||||
tags = {"l", "level", "lvl", "ilvl"},
|
||||
|
||||
canSearch = function(self, _, search)
|
||||
return tonumber(search)
|
||||
end,
|
||||
|
||||
match = function(self, link, operator, num)
|
||||
local _, _, _, lvl = GetItemInfo(link)
|
||||
if lvl then
|
||||
return Search:Compare(operator, lvl, num)
|
||||
end
|
||||
end
|
||||
}
|
||||
|
||||
Lib.Filters.requiredlevel = {
|
||||
tags = {"r", "req", "rl", "reql", "reqlvl"},
|
||||
|
||||
canSearch = function(self, _, search)
|
||||
return tonumber(search)
|
||||
end,
|
||||
|
||||
match = function(self, link, operator, num)
|
||||
local _, _, _, _, lvl = GetItemInfo(link)
|
||||
if lvl then
|
||||
return Search:Compare(operator, lvl, num)
|
||||
end
|
||||
end
|
||||
}
|
||||
|
||||
--[[ Quality ]]--
|
||||
|
||||
local qualities = {}
|
||||
for i = 0, getn(ITEM_QUALITY_COLORS) do
|
||||
qualities[i] = lower(_G["ITEM_QUALITY"..i.."_DESC"])
|
||||
end
|
||||
|
||||
Lib.Filters.quality = {
|
||||
tags = {"q", "quality"},
|
||||
|
||||
canSearch = function(self, _, search)
|
||||
for i, name in pairs(qualities) do
|
||||
if find(namesearch) then
|
||||
return i
|
||||
end
|
||||
end
|
||||
end,
|
||||
|
||||
match = function(self, link, operator, num)
|
||||
local _, _, quality = GetItemInfo(link)
|
||||
return Search:Compare(operator, quality, num)
|
||||
end
|
||||
}
|
||||
|
||||
--[[ Usable ]]--
|
||||
|
||||
Lib.Filters.usable = {
|
||||
tags = {},
|
||||
|
||||
canSearch = function(self, operator, search)
|
||||
return not operator and search == "usable"
|
||||
end,
|
||||
|
||||
match = function(self, link)
|
||||
if(not Unfit:IsItemUnusable(link)) then
|
||||
local _, _, _, _, lvl = GetItemInfo(link)
|
||||
return lvl and (lvl ~= 0 and lvl <= UnitLevel("player"))
|
||||
end
|
||||
end
|
||||
}
|
||||
|
||||
--[[ Tooltip Searches ]]--
|
||||
|
||||
local scanner = LibItemSearchTooltipScanner or CreateFrame("GameTooltip", "LibItemSearchTooltipScanner", UIParent, "GameTooltipTemplate")
|
||||
|
||||
Lib.Filters.tip = {
|
||||
tags = {"tt", "tip", "tooltip"},
|
||||
|
||||
onlyTags = true,
|
||||
|
||||
canSearch = function(self, _, search)
|
||||
return search
|
||||
end,
|
||||
|
||||
match = function(self, link, _, search)
|
||||
if find(link, "item:") then
|
||||
scanner:SetOwner(UIParent, "ANCHOR_NONE")
|
||||
scanner:SetHyperlink(link)
|
||||
|
||||
for i = 1, scanner:NumLines() do
|
||||
if Search:Find(search, _G[scanner:GetName().."TextLeft"..i]:GetText()) then
|
||||
return true
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
}
|
||||
|
||||
local escapes = {
|
||||
["|c%x%x%x%x%x%x%x%x"] = "",
|
||||
["|r"] = ""
|
||||
}
|
||||
|
||||
local function CleanString(str)
|
||||
for k, v in pairs(escapes) do
|
||||
str = string.gsub(str, k, v)
|
||||
end
|
||||
return str
|
||||
end
|
||||
|
||||
Lib.Filters.tipPhrases = {
|
||||
canSearch = function(self, _, search)
|
||||
return self.keywords[search]
|
||||
end,
|
||||
|
||||
match = function(self, link, _, search)
|
||||
local id = strmatch(link, "item:(%d+)")
|
||||
if not id then
|
||||
return
|
||||
end
|
||||
|
||||
local cached = self.cache[search][id]
|
||||
if cached ~= nil then
|
||||
return cached
|
||||
end
|
||||
|
||||
scanner:SetOwner(UIParent, "ANCHOR_NONE")
|
||||
scanner:SetHyperlink(link)
|
||||
|
||||
local matches = false
|
||||
for i = 1, scanner:NumLines() do
|
||||
local text = _G["LibItemSearchTooltipScannerTextLeft"..i]:GetText()
|
||||
text = CleanString(text)
|
||||
if search == text then
|
||||
matches = true
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
self.cache[search][id] = matches
|
||||
return matches
|
||||
end,
|
||||
|
||||
cache = setmetatable({}, {__index = function(t, k) local v = {} t[k] = v return v end}),
|
||||
|
||||
keywords = {
|
||||
[lower(ITEM_SOULBOUND)] = ITEM_BIND_ON_PICKUP,
|
||||
["bound"] = ITEM_BIND_ON_PICKUP,
|
||||
["bop"] = ITEM_BIND_ON_PICKUP,
|
||||
["boe"] = ITEM_BIND_ON_EQUIP,
|
||||
["bou"] = ITEM_BIND_ON_USE
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/
|
||||
..\FrameXML\UI.xsd">
|
||||
<Include file="CustomSearch-1.0\CustomSearch-1.0.xml"/>
|
||||
<Include file="Unfit-1.0\Unfit-1.0.xml"/>
|
||||
<Script file="LibItemSearch-1.2.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,111 @@
|
||||
--[[
|
||||
Copyright 2011-2016 João Cardoso
|
||||
Unfit is distributed under the terms of the GNU General Public License (Version 3).
|
||||
As a special exception, the copyright holders of this library give you permission to embed it
|
||||
with independent modules to produce an addon, regardless of the license terms of these
|
||||
independent modules, and to copy and distribute the resulting software under terms of your
|
||||
choice, provided that you also meet, for each embedded independent module, the terms and
|
||||
conditions of the license of that module. Permission is not granted to modify this library.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with the library. If not, see <http://www.gnu.org/licenses/gpl-3.0.txt>.
|
||||
|
||||
This file is part of Unfit.
|
||||
--]]
|
||||
|
||||
local Lib = LibStub:NewLibrary('Unfit-1.0', 9)
|
||||
if not Lib then
|
||||
return
|
||||
end
|
||||
|
||||
|
||||
--[[ Data ]]--
|
||||
|
||||
do
|
||||
local _, Class = UnitClass('player')
|
||||
local Unusable
|
||||
|
||||
if Class == 'DRUID' then
|
||||
Unusable = {
|
||||
{1, 2, 3, 4, 8, 9, 14, 15, 16},
|
||||
{4, 5, 7},
|
||||
true
|
||||
}
|
||||
elseif Class == 'HUNTER' then
|
||||
Unusable = {
|
||||
{5, 6, 16},
|
||||
{5, 6}
|
||||
}
|
||||
elseif Class == 'MAGE' then
|
||||
Unusable = {
|
||||
{1, 2, 3, 4, 5, 6, 7, 9, 11, 14, 15},
|
||||
{3, 4, 5, 7},
|
||||
true
|
||||
}
|
||||
elseif Class == 'PALADIN' then
|
||||
Unusable = {
|
||||
{3, 4, 10, 11, 13, 14, 15, 16},
|
||||
{},
|
||||
true
|
||||
}
|
||||
elseif Class == 'PRIEST' then
|
||||
Unusable = {
|
||||
{1, 2, 3, 4, 6, 7, 8, 9, 11, 14, 15},
|
||||
{3, 4, 5, 7},
|
||||
true
|
||||
}
|
||||
elseif Class == 'ROGUE' then
|
||||
Unusable = {
|
||||
{2, 6, 7, 9, 10, 16},
|
||||
{4, 5, 6}
|
||||
}
|
||||
elseif Class == 'SHAMAN' then
|
||||
Unusable = {
|
||||
{3, 4, 7, 8, 9, 14, 15, 16},
|
||||
{5}
|
||||
}
|
||||
elseif Class == 'WARLOCK' then
|
||||
Unusable = {
|
||||
{1, 2, 3, 4, 5, 6, 7, 9, 11, 14, 15},
|
||||
{3, 4, 5, 7},
|
||||
true
|
||||
}
|
||||
elseif Class == 'WARRIOR' then
|
||||
Unusable = {{16}, {}}
|
||||
else
|
||||
Unusable = {{}, {}}
|
||||
end
|
||||
|
||||
for class = 1, 2 do
|
||||
local subs = {GetAuctionItemSubClasses(class)}
|
||||
for i, subclass in ipairs(Unusable[class]) do
|
||||
Unusable[subs[subclass]] = true
|
||||
end
|
||||
|
||||
Unusable[class] = nil
|
||||
subs = nil
|
||||
end
|
||||
|
||||
Lib.unusable = Unusable
|
||||
Lib.cannotDual = Unusable[3]
|
||||
end
|
||||
|
||||
--[[ API ]]--
|
||||
|
||||
function Lib:IsItemUnusable(arg1)
|
||||
if arg1 then
|
||||
local subclass, _, slot = select(7, GetItemInfo(arg1))
|
||||
return Lib:IsClassUnusable(subclass, slot)
|
||||
end
|
||||
end
|
||||
|
||||
function Lib:IsClassUnusable(subclass, slot)
|
||||
if subclass then
|
||||
return slot ~= '' and Unusable[subclass] or slot == 'INVTYPE_WEAPONOFFHAND' and Lib.cannotDual
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,4 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/
|
||||
..\FrameXML\UI.xsd">
|
||||
<Script file="Unfit-1.0.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,237 @@
|
||||
--[[
|
||||
Name: LibSharedMedia-3.0
|
||||
Revision: $Revision: 62 $
|
||||
Author: Elkano (elkano@gmx.de)
|
||||
Inspired By: SurfaceLib by Haste/Otravi (troeks@gmail.com)
|
||||
Website: http://www.wowace.com/projects/libsharedmedia-3-0/
|
||||
Description: Shared handling of media data (fonts, sounds, textures, ...) between addons.
|
||||
Dependencies: LibStub, CallbackHandler-1.0
|
||||
License: LGPL v2.1
|
||||
]]
|
||||
|
||||
local MAJOR, MINOR = "LibSharedMedia-3.0", 2040001 -- 2.4.3 / increase manually on changes
|
||||
local lib = LibStub:NewLibrary(MAJOR, MINOR)
|
||||
|
||||
if not lib then return end
|
||||
|
||||
local _G = _G
|
||||
|
||||
local pairs = _G.pairs
|
||||
local type = _G.type
|
||||
|
||||
local band = _G.bit.band
|
||||
|
||||
local table_insert = _G.table.insert
|
||||
local table_sort = _G.table.sort
|
||||
|
||||
local locale = GetLocale()
|
||||
local locale_is_western
|
||||
local LOCALE_MASK = 0
|
||||
lib.LOCALE_BIT_koKR = 1
|
||||
lib.LOCALE_BIT_ruRU = 2
|
||||
lib.LOCALE_BIT_zhCN = 4
|
||||
lib.LOCALE_BIT_zhTW = 8
|
||||
lib.LOCALE_BIT_western = 128
|
||||
|
||||
local CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0")
|
||||
|
||||
lib.callbacks = lib.callbacks or CallbackHandler:New(lib)
|
||||
|
||||
lib.DefaultMedia = lib.DefaultMedia or {}
|
||||
lib.MediaList = lib.MediaList or {}
|
||||
lib.MediaTable = lib.MediaTable or {}
|
||||
lib.MediaType = lib.MediaType or {}
|
||||
lib.OverrideMedia = lib.OverrideMedia or {}
|
||||
|
||||
local defaultMedia = lib.DefaultMedia
|
||||
local mediaList = lib.MediaList
|
||||
local mediaTable = lib.MediaTable
|
||||
local overrideMedia = lib.OverrideMedia
|
||||
|
||||
|
||||
-- create mediatype constants
|
||||
lib.MediaType.BACKGROUND = "background" -- background textures
|
||||
lib.MediaType.BORDER = "border" -- border textures
|
||||
lib.MediaType.FONT = "font" -- fonts
|
||||
lib.MediaType.STATUSBAR = "statusbar" -- statusbar textures
|
||||
lib.MediaType.SOUND = "sound" -- sound files
|
||||
|
||||
-- populate lib with default Blizzard data
|
||||
-- BACKGROUND
|
||||
if not lib.MediaTable.background then lib.MediaTable.background = {} end
|
||||
lib.MediaTable.background["None"] = [[]]
|
||||
lib.MediaTable.background["Blizzard Dialog Background"] = [[Interface\DialogFrame\UI-DialogBox-Background]]
|
||||
lib.MediaTable.background["Blizzard Dialog Background Gold"] = [[Interface\DialogFrame\UI-DialogBox-Gold-Background]]
|
||||
lib.MediaTable.background["Blizzard Low Health"] = [[Interface\FullScreenTextures\LowHealth]]
|
||||
lib.MediaTable.background["Blizzard Out of Control"] = [[Interface\FullScreenTextures\OutOfControl]]
|
||||
lib.MediaTable.background["Blizzard Tabard Background"] = [[Interface\TabardFrame\TabardFrameBackground]]
|
||||
lib.MediaTable.background["Blizzard Tooltip"] = [[Interface\Tooltips\UI-Tooltip-Background]]
|
||||
lib.MediaTable.background["Solid"] = [[Interface\Buttons\WHITE8X8]]
|
||||
lib.DefaultMedia.background = "None"
|
||||
|
||||
-- BORDER
|
||||
if not lib.MediaTable.border then lib.MediaTable.border = {} end
|
||||
lib.MediaTable.border["None"] = [[]]
|
||||
lib.MediaTable.border["Blizzard Chat Bubble"] = [[Interface\Tooltips\ChatBubble-Backdrop]]
|
||||
lib.MediaTable.border["Blizzard Dialog"] = [[Interface\DialogFrame\UI-DialogBox-Border]]
|
||||
lib.MediaTable.border["Blizzard Dialog Gold"] = [[Interface\DialogFrame\UI-DialogBox-Gold-Border]]
|
||||
lib.MediaTable.border["Blizzard Party"] = [[Interface\CHARACTERFRAME\UI-Party-Border]]
|
||||
lib.MediaTable.border["Blizzard Tooltip"] = [[Interface\Tooltips\UI-Tooltip-Border]]
|
||||
lib.DefaultMedia.border = "None"
|
||||
|
||||
-- FONT
|
||||
if not lib.MediaTable.font then lib.MediaTable.font = {} end
|
||||
local SML_MT_font = lib.MediaTable.font
|
||||
if locale == "koKR" then
|
||||
LOCALE_MASK = lib.LOCALE_BIT_koKR
|
||||
--
|
||||
SML_MT_font["굵은 글꼴"] = [[Fonts\2002B.TTF]]
|
||||
SML_MT_font["기본 글꼴"] = [[Fonts\2002.TTF]]
|
||||
SML_MT_font["데미지 글꼴"] = [[Fonts\K_Damage.TTF]]
|
||||
SML_MT_font["퀘스트 글꼴"] = [[Fonts\K_Pagetext.TTF]]
|
||||
--
|
||||
lib.DefaultMedia["font"] = "기본 글꼴" -- someone from koKR please adjust if needed
|
||||
--
|
||||
elseif locale == "zhCN" then
|
||||
LOCALE_MASK = lib.LOCALE_BIT_zhCN
|
||||
--
|
||||
SML_MT_font["伤害数字"] = [[Fonts\ZYKai_C.ttf]]
|
||||
SML_MT_font["默认"] = [[Fonts\ZYKai_T.ttf]]
|
||||
SML_MT_font["聊天"] = [[Fonts\ZYHei.ttf]]
|
||||
--
|
||||
lib.DefaultMedia["font"] = "默认" -- someone from zhCN please adjust if needed
|
||||
--
|
||||
elseif locale == "zhTW" then
|
||||
LOCALE_MASK = lib.LOCALE_BIT_zhTW
|
||||
--
|
||||
SML_MT_font["提示訊息"] = [[Fonts\bHEI00M.ttf]]
|
||||
SML_MT_font["聊天"] = [[Fonts\bHEI01B.ttf]]
|
||||
SML_MT_font["傷害數字"] = [[Fonts\bKAI00M.ttf]]
|
||||
SML_MT_font["預設"] = [[Fonts\bLEI00D.ttf]]
|
||||
--
|
||||
lib.DefaultMedia["font"] = "預設" -- someone from zhTW please adjust if needed
|
||||
|
||||
elseif locale == "ruRU" then
|
||||
LOCALE_MASK = lib.LOCALE_BIT_ruRU
|
||||
--
|
||||
SML_MT_font["Arial Narrow"] = [[Fonts\ARIALN.TTF]]
|
||||
SML_MT_font["Friz Quadrata TT"] = [[Fonts\FRIZQT__.TTF]]
|
||||
SML_MT_font["Morpheus"] = [[Fonts\MORPHEUS.TTF]]
|
||||
SML_MT_font["Nimrod MT"] = [[Fonts\NIM_____.ttf]]
|
||||
SML_MT_font["Skurri"] = [[Fonts\SKURRI.TTF]]
|
||||
|
||||
lib.DefaultMedia.font = "Arial Narrow"
|
||||
--
|
||||
else
|
||||
LOCALE_MASK = lib.LOCALE_BIT_western
|
||||
locale_is_western = true
|
||||
--
|
||||
SML_MT_font["Arial Narrow"] = [[Fonts\ARIALN.TTF]]
|
||||
SML_MT_font["Friz Quadrata TT"] = [[Fonts\FRIZQT__.TTF]]
|
||||
SML_MT_font["Morpheus"] = [[Fonts\MORPHEUS.TTF]]
|
||||
SML_MT_font["Skurri"] = [[Fonts\SKURRI.TTF]]
|
||||
--
|
||||
lib.DefaultMedia.font = "Friz Quadrata TT"
|
||||
--
|
||||
end
|
||||
|
||||
-- STATUSBAR
|
||||
if not lib.MediaTable.statusbar then lib.MediaTable.statusbar = {} end
|
||||
lib.MediaTable.statusbar["Blizzard"] = [[Interface\TargetingFrame\UI-StatusBar]]
|
||||
lib.DefaultMedia.statusbar = "Blizzard"
|
||||
|
||||
-- SOUND
|
||||
if not lib.MediaTable.sound then lib.MediaTable.sound = {} end
|
||||
lib.MediaTable.sound["None"] = [[Interface\Quiet.ogg]] -- Relies on the fact that PlaySound[File] doesn't error on non-existing input.
|
||||
lib.DefaultMedia.sound = "None"
|
||||
|
||||
local function rebuildMediaList(mediatype)
|
||||
local mtable = mediaTable[mediatype]
|
||||
if not mtable then return end
|
||||
if not mediaList[mediatype] then mediaList[mediatype] = {} end
|
||||
local mlist = mediaList[mediatype]
|
||||
-- list can only get larger, so simply overwrite it
|
||||
local i = 0
|
||||
for k in pairs(mtable) do
|
||||
i = i + 1
|
||||
mlist[i] = k
|
||||
end
|
||||
table_sort(mlist)
|
||||
end
|
||||
|
||||
function lib:Register(mediatype, key, data, langmask)
|
||||
if type(mediatype) ~= "string" then
|
||||
error(MAJOR..":Register(mediatype, key, data, langmask) - mediatype must be string, got "..type(mediatype))
|
||||
end
|
||||
if type(key) ~= "string" then
|
||||
error(MAJOR..":Register(mediatype, key, data, langmask) - key must be string, got "..type(key))
|
||||
end
|
||||
mediatype = string.lower(mediatype)
|
||||
if mediatype == lib.MediaType.FONT and ((langmask and band(langmask, LOCALE_MASK) == 0) or not (langmask or locale_is_western)) then return false end
|
||||
if mediatype == lib.MediaType.SOUND and type(data) == "string" then
|
||||
local path = data
|
||||
-- Only wav, ogg and mp3 are valid sounds.
|
||||
if not string.find(path, ".ogg", nil, true) and not string.find(path, ".mp3", nil, true) and not string.find(path, ".wav", nil, true) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
if not mediaTable[mediatype] then mediaTable[mediatype] = {} end
|
||||
local mtable = mediaTable[mediatype]
|
||||
if mtable[key] then return false end
|
||||
|
||||
mtable[key] = data
|
||||
rebuildMediaList(mediatype)
|
||||
self.callbacks:Fire("LibSharedMedia_Registered", mediatype, key)
|
||||
return true
|
||||
end
|
||||
|
||||
function lib:Fetch(mediatype, key, noDefault)
|
||||
local mtt = mediaTable[mediatype]
|
||||
local overridekey = overrideMedia[mediatype]
|
||||
local result = mtt and ((overridekey and mtt[overridekey] or mtt[key]) or (not noDefault and defaultMedia[mediatype] and mtt[defaultMedia[mediatype]])) or nil
|
||||
return result ~= "" and result or nil
|
||||
end
|
||||
|
||||
function lib:IsValid(mediatype, key)
|
||||
return mediaTable[mediatype] and (not key or mediaTable[mediatype][key]) and true or false
|
||||
end
|
||||
|
||||
function lib:HashTable(mediatype)
|
||||
return mediaTable[mediatype]
|
||||
end
|
||||
|
||||
function lib:List(mediatype)
|
||||
if not mediaTable[mediatype] then
|
||||
return nil
|
||||
end
|
||||
if not mediaList[mediatype] then
|
||||
rebuildMediaList(mediatype)
|
||||
end
|
||||
return mediaList[mediatype]
|
||||
end
|
||||
|
||||
function lib:GetGlobal(mediatype)
|
||||
return overrideMedia[mediatype]
|
||||
end
|
||||
|
||||
function lib:SetGlobal(mediatype, key)
|
||||
if not mediaTable[mediatype] then
|
||||
return false
|
||||
end
|
||||
overrideMedia[mediatype] = (key and mediaTable[mediatype][key]) and key or nil
|
||||
self.callbacks:Fire("LibSharedMedia_SetGlobal", mediatype, overrideMedia[mediatype])
|
||||
return true
|
||||
end
|
||||
|
||||
function lib:GetDefault(mediatype)
|
||||
return defaultMedia[mediatype]
|
||||
end
|
||||
|
||||
function lib:SetDefault(mediatype, key)
|
||||
if mediaTable[mediatype] and mediaTable[mediatype][key] and not defaultMedia[mediatype] then
|
||||
defaultMedia[mediatype] = key
|
||||
return true
|
||||
else
|
||||
return false
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,3 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="LibSharedMedia-3.0.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,280 @@
|
||||
--[[---------------------------------------------------------------------------------
|
||||
General Library providing an alternate StartMoving() that allows you to
|
||||
specify a number of frames to snap-to when moving the frame around
|
||||
|
||||
Example Usage:
|
||||
|
||||
<OnLoad>
|
||||
this:RegisterForDrag("LeftButton")
|
||||
</OnLoad>
|
||||
<OnDragStart>
|
||||
StickyFrames:StartMoving(this, {WatchDogFrame_player, WatchDogFrame_target, WatchDogFrame_party1, WatchDogFrame_party2, WatchDogFrame_party3, WatchDogFrame_party4},3,3,3,3)
|
||||
</OnDragStart>
|
||||
<OnDragStop>
|
||||
StickyFrames:StopMoving(this)
|
||||
StickyFrames:AnchorFrame(this)
|
||||
</OnDragStop>
|
||||
|
||||
------------------------------------------------------------------------------------
|
||||
This is a modified version by Elv for ElvUI
|
||||
------------------------------------------------------------------------------------]]
|
||||
|
||||
local MAJOR, MINOR = "LibSimpleSticky-1.0", 2
|
||||
local StickyFrames, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
|
||||
|
||||
if not StickyFrames then return end
|
||||
|
||||
--[[---------------------------------------------------------------------------------
|
||||
Class declaration, along with a temporary table to hold any existing OnUpdate
|
||||
scripts.
|
||||
------------------------------------------------------------------------------------]]
|
||||
|
||||
StickyFrames.scripts = StickyFrames.scripts or {}
|
||||
StickyFrames.rangeX = 15
|
||||
StickyFrames.rangeY = 15
|
||||
StickyFrames.sticky = StickyFrames.sticky or {}
|
||||
|
||||
--[[---------------------------------------------------------------------------------
|
||||
StickyFrames:StartMoving() - Sets a custom OnUpdate for the frame so it follows
|
||||
the mouse and snaps to the frames you specify
|
||||
|
||||
frame: The frame we want to move. Is typically "this"
|
||||
|
||||
frameList: A integer indexed list of frames that the given frame should try to
|
||||
stick to. These don't have to have anything special done to them,
|
||||
and they don't really even need to exist. You can inclue the
|
||||
moving frame in this list, it will be ignored. This helps you
|
||||
if you have a number of frames, just make ONE list to pass.
|
||||
|
||||
{WatchDogFrame_player, WatchDogFrame_party1, .. WatchDogFrame_party4}
|
||||
|
||||
left: If your frame has a tranparent border around the entire frame
|
||||
(think backdrops with borders). This can be used to fine tune the
|
||||
edges when you're stickying groups. Refers to any offset on the
|
||||
LEFT edge of the frame being moved.
|
||||
|
||||
top: same
|
||||
right: same
|
||||
bottom: same
|
||||
------------------------------------------------------------------------------------]]
|
||||
|
||||
function StickyFrames:StartMoving(frame, frameList, left, top, right, bottom)
|
||||
local x,y = GetCursorPosition()
|
||||
local aX,aY = frame:GetCenter()
|
||||
local aS = frame:GetEffectiveScale()
|
||||
|
||||
aX,aY = aX*aS,aY*aS
|
||||
local xoffset,yoffset = (aX - x),(aY - y)
|
||||
self.scripts[frame] = frame:GetScript("OnUpdate")
|
||||
frame:SetScript("OnUpdate", self:GetUpdateFunc(frame, frameList, xoffset, yoffset, left, top, right, bottom))
|
||||
end
|
||||
|
||||
--[[---------------------------------------------------------------------------------
|
||||
This stops the OnUpdate, leaving the frame at its last position. This will
|
||||
leave it anchored to UIParent. You can call StickyFrames:AnchorFrame() to
|
||||
anchor it back "TOPLEFT" , "TOPLEFT" to the parent.
|
||||
------------------------------------------------------------------------------------]]
|
||||
|
||||
function StickyFrames:StopMoving(frame)
|
||||
frame:SetScript("OnUpdate", self.scripts[frame])
|
||||
self.scripts[frame] = nil
|
||||
|
||||
if StickyFrames.sticky[frame] then
|
||||
local sticky = StickyFrames.sticky[frame]
|
||||
StickyFrames.sticky[frame] = nil
|
||||
return true, sticky
|
||||
else
|
||||
return false, nil
|
||||
end
|
||||
end
|
||||
|
||||
--[[---------------------------------------------------------------------------------
|
||||
This can be called in conjunction with StickyFrames:StopMoving() to anchor the
|
||||
frame right back to the parent, so you can manipulate its children as a group
|
||||
(This is useful in WatchDog)
|
||||
------------------------------------------------------------------------------------]]
|
||||
|
||||
function StickyFrames:AnchorFrame(frame)
|
||||
local xA,yA = frame:GetCenter()
|
||||
local parent = frame:GetParent() or UIParent
|
||||
local xP,yP = parent:GetCenter()
|
||||
local sA,sP = frame:GetEffectiveScale(), parent:GetEffectiveScale()
|
||||
|
||||
xP,yP = (xP*sP) / sA, (yP*sP) / sA
|
||||
|
||||
local xo,yo = (xP - xA)*-1, (yP - yA)*-1
|
||||
|
||||
frame:ClearAllPoints()
|
||||
frame:SetPoint("CENTER", parent, "CENTER", xo, yo)
|
||||
end
|
||||
|
||||
|
||||
--[[---------------------------------------------------------------------------------
|
||||
Internal Functions -- Do not call these.
|
||||
------------------------------------------------------------------------------------]]
|
||||
|
||||
|
||||
|
||||
--[[---------------------------------------------------------------------------------
|
||||
Returns an anonymous OnUpdate function for the frame in question. Need
|
||||
to provide the frame, frameList along with the x and y offset (difference between
|
||||
where the mouse picked up the frame, and the insets (left,top,right,bottom) in the
|
||||
case of borders, etc.w
|
||||
------------------------------------------------------------------------------------]]
|
||||
|
||||
function StickyFrames:GetUpdateFunc(frame, frameList, xoffset, yoffset, left, top, right, bottom)
|
||||
return function()
|
||||
local x,y = GetCursorPosition()
|
||||
local s = frame:GetEffectiveScale()
|
||||
local sticky = nil
|
||||
|
||||
x,y = x/s,y/s
|
||||
|
||||
frame:ClearAllPoints()
|
||||
frame:SetPoint("CENTER", UIParent, "BOTTOMLEFT", x+xoffset, y+yoffset)
|
||||
|
||||
StickyFrames.sticky[frame] = nil
|
||||
for i = 1, table.getn(frameList) do
|
||||
local v = frameList[i]
|
||||
if frame ~= v and frame ~= v:GetParent() and not IsShiftKeyDown() and v:IsVisible() then
|
||||
if self:SnapFrame(frame, v, left, top, right, bottom) then
|
||||
StickyFrames.sticky[frame] = v
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
--[[---------------------------------------------------------------------------------
|
||||
Internal debug function.
|
||||
------------------------------------------------------------------------------------]]
|
||||
|
||||
function StickyFrames:debug(msg)
|
||||
DEFAULT_CHAT_FRAME:AddMessage("|cffffff00StickyFrames: |r"..tostring(msg))
|
||||
end
|
||||
|
||||
--[[---------------------------------------------------------------------------------
|
||||
This is called when finding an overlap between two sticky frame. If frameA is near
|
||||
a sticky edge of frameB, then it will snap to that edge and return true. If there
|
||||
is no sticky edge collision, will return false so we can test other frames for
|
||||
stickyness.
|
||||
------------------------------------------------------------------------------------]]
|
||||
function StickyFrames:SnapFrame(frameA, frameB, left, top, right, bottom)
|
||||
local sA, sB = frameA:GetEffectiveScale(), frameB:GetEffectiveScale()
|
||||
local xA, yA = frameA:GetCenter()
|
||||
local xB, yB = frameB:GetCenter()
|
||||
local hA, hB = frameA:GetHeight() / 2, ((frameB:GetHeight() * sB) / sA) / 2
|
||||
local wA, wB = frameA:GetWidth() / 2, ((frameB:GetWidth() * sB) / sA) / 2
|
||||
|
||||
local newX, newY = xA, yA
|
||||
|
||||
if not left then left = 0 end
|
||||
if not top then top = 0 end
|
||||
if not right then right = 0 end
|
||||
if not bottom then bottom = 0 end
|
||||
|
||||
-- Lets translate B's coords into A's scale
|
||||
if not xB or not yB or not sB or not sA or not sB then return end
|
||||
xB, yB = (xB*sB) / sA, (yB*sB) / sA
|
||||
|
||||
local stickyAx, stickyAy = wA * 0.75, hA * 0.75
|
||||
local stickyBx, stickyBy = wB * 0.75, hB * 0.75
|
||||
|
||||
-- Grab the edges of each frame, for easier comparison
|
||||
|
||||
local lA, tA, rA, bA = frameA:GetLeft(), frameA:GetTop(), frameA:GetRight(), frameA:GetBottom()
|
||||
local lB, tB, rB, bB = frameB:GetLeft(), frameB:GetTop(), frameB:GetRight(), frameB:GetBottom()
|
||||
local snap = nil
|
||||
|
||||
-- Translate into A's scale
|
||||
lB, tB, rB, bB = (lB * sB) / sA, (tB * sB) / sA, (rB * sB) / sA, (bB * sB) / sA
|
||||
|
||||
if (bA <= tB and bB <= tA) then
|
||||
|
||||
-- Horizontal Centers
|
||||
if xA <= (xB + StickyFrames.rangeX) and xA >= (xB - StickyFrames.rangeX) then
|
||||
newX = xB
|
||||
snap = true
|
||||
end
|
||||
|
||||
-- Interior Left
|
||||
if lA <= (lB + StickyFrames.rangeX) and lA >= (lB - StickyFrames.rangeX) then
|
||||
newX = lB + wA
|
||||
if frameB == UIParent or frameB == WorldFrame or frameB == ElvUIParent then
|
||||
newX = newX + 4
|
||||
end
|
||||
snap = true
|
||||
end
|
||||
|
||||
-- Interior Right
|
||||
if rA <= (rB + StickyFrames.rangeX) and rA >= (rB - StickyFrames.rangeX) then
|
||||
newX = rB - wA
|
||||
if frameB == UIParent or frameB == WorldFrame or frameB == ElvUIParent then
|
||||
newX = newX - 4
|
||||
end
|
||||
snap = true
|
||||
end
|
||||
|
||||
-- Exterior Left to Right
|
||||
if lA <= (rB + StickyFrames.rangeX) and lA >= (rB - StickyFrames.rangeX) then
|
||||
newX = rB + (wA - left)
|
||||
|
||||
snap = true
|
||||
end
|
||||
|
||||
-- Exterior Right to Left
|
||||
if rA <= (lB + StickyFrames.rangeX) and rA >= (lB - StickyFrames.rangeX) then
|
||||
newX = lB - (wA - right)
|
||||
snap = true
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
if (lA <= rB and lB <= rA) then
|
||||
|
||||
-- Vertical Centers
|
||||
if yA <= (yB + StickyFrames.rangeY) and yA >= (yB - StickyFrames.rangeY) then
|
||||
newY = yB
|
||||
snap = true
|
||||
end
|
||||
|
||||
-- Interior Top
|
||||
if tA <= (tB + StickyFrames.rangeY) and tA >= (tB - StickyFrames.rangeY) then
|
||||
newY = tB - hA
|
||||
if frameB == UIParent or frameB == WorldFrame or frameB == ElvUIParent then
|
||||
newY = newY - 4
|
||||
end
|
||||
snap = true
|
||||
end
|
||||
|
||||
-- Interior Bottom
|
||||
if bA <= (bB + StickyFrames.rangeY) and bA >= (bB - StickyFrames.rangeY) then
|
||||
newY = bB + hA
|
||||
if frameB == UIParent or frameB == WorldFrame or frameB == ElvUIParent then
|
||||
newY = newY + 4
|
||||
end
|
||||
snap = true
|
||||
end
|
||||
|
||||
-- Exterior Top to Bottom
|
||||
if tA <= (bB + StickyFrames.rangeY + bottom) and tA >= (bB - StickyFrames.rangeY + bottom) then
|
||||
newY = bB - (hA - top)
|
||||
snap = true
|
||||
end
|
||||
|
||||
-- Exterior Bottom to Top
|
||||
if bA <= (tB + StickyFrames.rangeY - top) and bA >= (tB - StickyFrames.rangeY - top) then
|
||||
newY = tB + (hA - bottom)
|
||||
snap = true
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
if snap then
|
||||
frameA:ClearAllPoints()
|
||||
frameA:SetPoint("CENTER", UIParent, "BOTTOMLEFT", newX, newY)
|
||||
return true
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,3 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="LibSimpleSticky.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,33 @@
|
||||
-- LibStub is a simple versioning stub meant for use in Libraries. http://www.wowace.com/wiki/LibStub for more info
|
||||
-- LibStub is hereby placed in the Public Domain Credits: Kaelten, Cladhaire, ckknight, Mikk, Ammo, Nevcairiel, joshborke
|
||||
local LIBSTUB_MAJOR, LIBSTUB_MINOR = "LibStub", 2 -- NEVER MAKE THIS AN SVN REVISION! IT NEEDS TO BE USABLE IN ALL REPOS!
|
||||
local _G = _G
|
||||
local strfind, strfmt = string.find, string.format
|
||||
local LibStub = _G[LIBSTUB_MAJOR]
|
||||
|
||||
if not LibStub or LibStub.minor < LIBSTUB_MINOR then
|
||||
LibStub = LibStub or { libs = {}, minors = {} }
|
||||
_G[LIBSTUB_MAJOR] = LibStub
|
||||
LibStub.minor = LIBSTUB_MINOR
|
||||
|
||||
function LibStub:NewLibrary(major, minor)
|
||||
assert(type(major) == "string", "Bad argument #2 to `NewLibrary' (string expected)")
|
||||
local _,_,num = strfind(minor, "(%d+)")
|
||||
minor = assert(tonumber(num), "Minor version must either be a number or contain a number.")
|
||||
|
||||
local oldminor = self.minors[major]
|
||||
if oldminor and oldminor >= minor then return nil end
|
||||
self.minors[major], self.libs[major] = minor, self.libs[major] or {}
|
||||
return self.libs[major], oldminor
|
||||
end
|
||||
|
||||
function LibStub:GetLibrary(major, silent)
|
||||
if not self.libs[major] and not silent then
|
||||
error(strfmt("Cannot find a library instance of %q.", tostring(major)), 2)
|
||||
end
|
||||
return self.libs[major], self.minors[major]
|
||||
end
|
||||
|
||||
function LibStub:IterateLibraries() return pairs(self.libs) end
|
||||
setmetatable(LibStub, { __call = LibStub.GetLibrary })
|
||||
end
|
||||
@@ -0,0 +1,3 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="LibStub.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,47 @@
|
||||
--$Id: LibEasyMenu.lua 19 2017-07-02 13:34:55Z arith $
|
||||
-- Simplified Menu Display System
|
||||
-- This is a basic system for displaying a menu from a structure table.
|
||||
--
|
||||
-- See UIDropDownMenu.lua for the menuList details.
|
||||
--
|
||||
-- Args:
|
||||
-- menuList - menu table
|
||||
-- menuFrame - the UI frame to populate
|
||||
-- anchor - where to anchor the frame (e.g. CURSOR)
|
||||
-- x - x offset
|
||||
-- y - y offset
|
||||
-- displayMode - border type
|
||||
-- autoHideDelay - how long until the menu disappears
|
||||
--
|
||||
--
|
||||
-- ----------------------------------------------------------------------------
|
||||
-- Localized Lua globals.
|
||||
-- ----------------------------------------------------------------------------
|
||||
local _G = _G
|
||||
-- ----------------------------------------------------------------------------
|
||||
local MAJOR_VERSION = "LibEasyMenu-1.04.7030024484"
|
||||
local MINOR_VERSION = 90000 + 19
|
||||
|
||||
local LibStub = _G.LibStub
|
||||
if not LibStub then error(MAJOR_VERSION .. " requires LibStub.") end
|
||||
local Lib = LibStub:NewLibrary(MAJOR_VERSION, MINOR_VERSION)
|
||||
if not Lib then return end
|
||||
|
||||
function L_EasyMenu(menuList, menuFrame, anchor, x, y, displayMode, autoHideDelay )
|
||||
if ( displayMode == "MENU" ) then
|
||||
menuFrame.displayMode = displayMode;
|
||||
end
|
||||
L_UIDropDownMenu_Initialize(menuFrame, L_EasyMenu_Initialize, displayMode, nil, menuList);
|
||||
L_ToggleDropDownMenu(1, nil, menuFrame, anchor, x, y, menuList, nil, autoHideDelay);
|
||||
end
|
||||
|
||||
function L_EasyMenu_Initialize( frame, level, menuList )
|
||||
for index = 1, getn(menuList) do
|
||||
local value = menuList[index]
|
||||
if (value.text) then
|
||||
value.index = index;
|
||||
L_UIDropDownMenu_AddButton( value, level );
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,29 @@
|
||||
<!-- $Id: LibUIDropDownMenu.xml 13 2017-05-25 04:26:27Z arith $ -->
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/
|
||||
..\FrameXML\UI.xsd">
|
||||
<Script file="LibUIDropDownMenu.lua"/>
|
||||
<Include file="LibUIDropDownMenuTemplates.xml"/>
|
||||
<Script file="LibEasyMenu.lua"/>
|
||||
<Button name="L_DropDownList1" toplevel="true" frameStrata="FULLSCREEN_DIALOG" inherits="L_UIDropDownListTemplate" hidden="true" id="1">
|
||||
<Size>
|
||||
<AbsDimension x="180" y="10"/>
|
||||
</Size>
|
||||
<Scripts>
|
||||
<OnLoad>
|
||||
local fontName, fontHeight, fontFlags = getglobal("L_DropDownList1Button1NormalText"):GetFont();
|
||||
L_UIDROPDOWNMENU_DEFAULT_TEXT_HEIGHT = fontHeight;
|
||||
tinsert(UIMenus, "L_DropDownList1"); --Allow closing with escape
|
||||
</OnLoad>
|
||||
</Scripts>
|
||||
</Button>
|
||||
<Button name="L_DropDownList2" toplevel="true" frameStrata="FULLSCREEN_DIALOG" inherits="L_UIDropDownListTemplate" hidden="true" id="2">
|
||||
<Size>
|
||||
<AbsDimension x="180" y="10"/>
|
||||
</Size>
|
||||
<Scripts>
|
||||
<OnLoad>
|
||||
tinsert(UIMenus, "L_DropDownList2"); --Allow closing with escape
|
||||
</OnLoad>
|
||||
</Scripts>
|
||||
</Button>
|
||||
</Ui>
|
||||
@@ -0,0 +1,424 @@
|
||||
<!-- $Id: LibUIDropDownMenuTemplates.xml 19 2017-07-02 13:34:55Z arith $ -->
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/
|
||||
..\FrameXML\UI.xsd">
|
||||
<Button name="L_UIDropDownMenuButtonTemplate" virtual="true">
|
||||
<Size>
|
||||
<AbsDimension x="128" y="16"/>
|
||||
</Size>
|
||||
<Layers>
|
||||
<Layer level="BACKGROUND">
|
||||
<Texture name="$parentHighlight" file="Interface\QuestFrame\UI-QuestTitleHighlight" alphaMode="ADD" setAllPoints="true" hidden="true"/>
|
||||
</Layer>
|
||||
<Layer level="ARTWORK">
|
||||
<Texture name="$parentCheck" file="Interface\Buttons\UI-CheckBox-Check">
|
||||
<Size>
|
||||
<AbsDimension x="24" y="24"/>
|
||||
</Size>
|
||||
<Anchors>
|
||||
<Anchor point="LEFT">
|
||||
<Offset>
|
||||
<AbsDimension x="0" y="0"/>
|
||||
</Offset>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
</Texture>
|
||||
<Texture name="$parentIcon" hidden="true">
|
||||
<Size>
|
||||
<AbsDimension x="15" y="15"/>
|
||||
</Size>
|
||||
<Anchors>
|
||||
<Anchor point="RIGHT">
|
||||
<Offset>
|
||||
<AbsDimension x="-5" y="0"/>
|
||||
</Offset>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
</Texture>
|
||||
</Layer>
|
||||
</Layers>
|
||||
<Frames>
|
||||
<Button name="$parentColorSwatch" hidden="true">
|
||||
<Size>
|
||||
<AbsDimension x="16" y="16"/>
|
||||
</Size>
|
||||
<Anchors>
|
||||
<Anchor point="RIGHT">
|
||||
<Offset>
|
||||
<AbsDimension x="-6" y="0"/>
|
||||
</Offset>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Layers>
|
||||
<Layer level="BACKGROUND">
|
||||
<Texture name="$parentSwatchBg">
|
||||
<Size>
|
||||
<AbsDimension x="14" y="14"/>
|
||||
</Size>
|
||||
<Anchors>
|
||||
<Anchor point="CENTER">
|
||||
<Offset>
|
||||
<AbsDimension x="0" y="0"/>
|
||||
</Offset>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Color r="1.0" g="1.0" b="1.0"/>
|
||||
</Texture>
|
||||
</Layer>
|
||||
</Layers>
|
||||
<Scripts>
|
||||
<OnClick>
|
||||
CloseMenus()
|
||||
L_UIDropDownMenuButton_OpenColorPicker(this:GetParent())
|
||||
</OnClick>
|
||||
<OnEnter>
|
||||
L_CloseDropDownMenus(this:GetParent():GetParent():GetID() + 1)
|
||||
getglobal(this:GetName().."SwatchBg"):SetVertexColor(NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b)
|
||||
L_UIDropDownMenu_StopCounting(this:GetParent():GetParent())
|
||||
</OnEnter>
|
||||
<OnLeave>
|
||||
getglobal(this:GetName().."SwatchBg"):SetVertexColor(HIGHLIGHT_FONT_COLOR.r, HIGHLIGHT_FONT_COLOR.g, HIGHLIGHT_FONT_COLOR.b)
|
||||
L_UIDropDownMenu_StartCounting(this:GetParent():GetParent())
|
||||
</OnLeave>
|
||||
</Scripts>
|
||||
<NormalTexture name="$parentNormalTexture" file="Interface\ChatFrame\ChatFrameColorSwatch"/>
|
||||
</Button>
|
||||
<Button name="$parentExpandArrow" hidden="true">
|
||||
<Size>
|
||||
<AbsDimension x="16" y="16"/>
|
||||
</Size>
|
||||
<Anchors>
|
||||
<Anchor point="RIGHT">
|
||||
<Offset>
|
||||
<AbsDimension x="0" y="0"/>
|
||||
</Offset>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Scripts>
|
||||
<OnClick>
|
||||
L_ToggleDropDownMenu(this:GetParent():GetParent():GetID() + 1, this:GetParent().value, nil, nil, nil, nil, this:GetParent().menuList, this)
|
||||
</OnClick>
|
||||
<OnEnter>
|
||||
local level = this:GetParent():GetParent():GetID() + 1
|
||||
local listFrame = getglobal("L_DropDownList"..level)
|
||||
if not listFrame or not listFrame:IsShown() or select(2, listFrame:GetPoint()) ~= this then
|
||||
L_ToggleDropDownMenu(level, this:GetParent().value, nil, nil, nil, nil, this:GetParent().menuList, this)
|
||||
end
|
||||
L_UIDropDownMenu_StopCounting(this:GetParent():GetParent())
|
||||
</OnEnter>
|
||||
<OnLeave>
|
||||
L_UIDropDownMenu_StartCounting(this:GetParent():GetParent())
|
||||
</OnLeave>
|
||||
</Scripts>
|
||||
<NormalTexture file="Interface\ChatFrame\ChatFrameExpandArrow"/>
|
||||
</Button>
|
||||
<Button name="$parentInvisibleButton" hidden="true">
|
||||
<Anchors>
|
||||
<Anchor point="TOPLEFT"/>
|
||||
<Anchor point="BOTTOMLEFT"/>
|
||||
<Anchor point="RIGHT" relativeTo="$parentColorSwatch" relativePoint="LEFT">
|
||||
<Offset>
|
||||
<AbsDimension x="0" y="0"/>
|
||||
</Offset>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Scripts>
|
||||
<OnEnter>
|
||||
L_UIDropDownMenu_StopCounting(this:GetParent():GetParent())
|
||||
L_CloseDropDownMenus(this:GetParent():GetParent():GetID() + 1)
|
||||
local parent = this:GetParent();
|
||||
if parent.tooltipTitle and parent.tooltipWhileDisabled then
|
||||
if parent.tooltipOnButton then
|
||||
GameTooltip:SetOwner(parent, "ANCHOR_RIGHT")
|
||||
GameTooltip:AddLine(parent.tooltipTitle, 1.0, 1.0, 1.0)
|
||||
GameTooltip:AddLine(parent.tooltipText, nil, nil, nil, true)
|
||||
GameTooltip:Show()
|
||||
else
|
||||
GameTooltip_AddNewbieTip(parent, parent.tooltipTitle, 1.0, 1.0, 1.0, parent.tooltipText, 1)
|
||||
end
|
||||
end
|
||||
</OnEnter>
|
||||
<OnLeave>
|
||||
L_UIDropDownMenu_StartCounting(this:GetParent():GetParent())
|
||||
GameTooltip:Hide()
|
||||
</OnLeave>
|
||||
</Scripts>
|
||||
</Button>
|
||||
</Frames>
|
||||
<Scripts>
|
||||
<OnLoad>
|
||||
this:SetFrameLevel(this:GetParent():GetFrameLevel()+2)
|
||||
</OnLoad>
|
||||
<OnClick>
|
||||
L_UIDropDownMenuButton_OnClick(this, arg1, arg2)
|
||||
</OnClick>
|
||||
<OnEnter>
|
||||
if this.hasArrow then
|
||||
local level = this:GetParent():GetID() + 1
|
||||
local listFrame = getglobal("L_DropDownList"..level)
|
||||
if not listFrame or not listFrame:IsShown() or select(2, listFrame:GetPoint()) ~= this then
|
||||
L_ToggleDropDownMenu(this:GetParent():GetID() + 1, this.value, nil, nil, nil, nil, this.menuList, this)
|
||||
end
|
||||
else
|
||||
L_CloseDropDownMenus(this:GetParent():GetID() + 1)
|
||||
end
|
||||
getglobal(this:GetName().."Highlight"):Show()
|
||||
L_UIDropDownMenu_StopCounting(this:GetParent())
|
||||
if this.tooltipTitle then
|
||||
if this.tooltipOnButton then
|
||||
GameTooltip:SetOwner(this, "ANCHOR_RIGHT")
|
||||
GameTooltip:AddLine(this.tooltipTitle, 1.0, 1.0, 1.0)
|
||||
GameTooltip:AddLine(this.tooltipText, nil, nil, nil, true)
|
||||
GameTooltip:Show()
|
||||
else
|
||||
GameTooltip_AddNewbieTip(this, this.tooltipTitle, 1.0, 1.0, 1.0, this.tooltipText, 1)
|
||||
end
|
||||
end
|
||||
</OnEnter>
|
||||
<OnLeave>
|
||||
getglobal(this:GetName().."Highlight"):Hide()
|
||||
L_UIDropDownMenu_StartCounting(this:GetParent())
|
||||
GameTooltip:Hide()
|
||||
</OnLeave>
|
||||
</Scripts>
|
||||
<ButtonText name="$parentNormalText"/>
|
||||
<NormalFont inherits="GameFontHighlightSmall" justifyH="LEFT"/>
|
||||
<HighlightFont inherits="GameFontHighlightSmall" justifyH="LEFT"/>
|
||||
<DisabledFont inherits="GameFontDisableSmall" justifyH="LEFT"/>
|
||||
</Button>
|
||||
|
||||
<Button name="L_UIDropDownListTemplate" hidden="true" frameStrata="DIALOG" enableMouse="true" virtual="true">
|
||||
<Frames>
|
||||
<Frame name="$parentBackdrop" setAllPoints="true">
|
||||
<Backdrop bgFile="Interface\DialogFrame\UI-DialogBox-Background-Dark" edgeFile="Interface\DialogFrame\UI-DialogBox-Border" tile="true">
|
||||
<BackgroundInsets>
|
||||
<AbsInset left="11" right="12" top="12" bottom="9"/>
|
||||
</BackgroundInsets>
|
||||
<TileSize>
|
||||
<AbsValue val="32"/>
|
||||
</TileSize>
|
||||
<EdgeSize>
|
||||
<AbsValue val="32"/>
|
||||
</EdgeSize>
|
||||
</Backdrop>
|
||||
</Frame>
|
||||
<Frame name="$parentMenuBackdrop" setAllPoints="true">
|
||||
<Backdrop bgFile="Interface\Tooltips\UI-Tooltip-Background" edgeFile="Interface\Tooltips\UI-Tooltip-Border" tile="true">
|
||||
<EdgeSize>
|
||||
<AbsValue val="16"/>
|
||||
</EdgeSize>
|
||||
<TileSize>
|
||||
<AbsValue val="16"/>
|
||||
</TileSize>
|
||||
<BackgroundInsets>
|
||||
<AbsInset left="5" right="5" top="5" bottom="4"/>
|
||||
</BackgroundInsets>
|
||||
</Backdrop>
|
||||
<Scripts>
|
||||
<OnLoad>
|
||||
this:SetBackdropBorderColor(TOOLTIP_DEFAULT_COLOR.r, TOOLTIP_DEFAULT_COLOR.g, TOOLTIP_DEFAULT_COLOR.b);
|
||||
this:SetBackdropColor(TOOLTIP_DEFAULT_BACKGROUND_COLOR.r, TOOLTIP_DEFAULT_BACKGROUND_COLOR.g, TOOLTIP_DEFAULT_BACKGROUND_COLOR.b);
|
||||
</OnLoad>
|
||||
</Scripts>
|
||||
</Frame>
|
||||
<Button name="$parentButton1" inherits="L_UIDropDownMenuButtonTemplate" id="1"/>
|
||||
<Button name="$parentButton2" inherits="L_UIDropDownMenuButtonTemplate" id="2"/>
|
||||
<Button name="$parentButton3" inherits="L_UIDropDownMenuButtonTemplate" id="3"/>
|
||||
<Button name="$parentButton4" inherits="L_UIDropDownMenuButtonTemplate" id="4"/>
|
||||
<Button name="$parentButton5" inherits="L_UIDropDownMenuButtonTemplate" id="5"/>
|
||||
<Button name="$parentButton6" inherits="L_UIDropDownMenuButtonTemplate" id="6"/>
|
||||
<Button name="$parentButton7" inherits="L_UIDropDownMenuButtonTemplate" id="7"/>
|
||||
<Button name="$parentButton8" inherits="L_UIDropDownMenuButtonTemplate" id="8"/>
|
||||
<Button name="$parentButton9" inherits="L_UIDropDownMenuButtonTemplate" id="9"/>
|
||||
<Button name="$parentButton10" inherits="L_UIDropDownMenuButtonTemplate" id="10"/>
|
||||
<Button name="$parentButton11" inherits="L_UIDropDownMenuButtonTemplate" id="11"/>
|
||||
<Button name="$parentButton12" inherits="L_UIDropDownMenuButtonTemplate" id="12"/>
|
||||
<Button name="$parentButton13" inherits="L_UIDropDownMenuButtonTemplate" id="13"/>
|
||||
<Button name="$parentButton14" inherits="L_UIDropDownMenuButtonTemplate" id="14"/>
|
||||
<Button name="$parentButton15" inherits="L_UIDropDownMenuButtonTemplate" id="15"/>
|
||||
<Button name="$parentButton16" inherits="L_UIDropDownMenuButtonTemplate" id="16"/>
|
||||
<Button name="$parentButton17" inherits="L_UIDropDownMenuButtonTemplate" id="17"/>
|
||||
<Button name="$parentButton18" inherits="L_UIDropDownMenuButtonTemplate" id="18"/>
|
||||
<Button name="$parentButton19" inherits="L_UIDropDownMenuButtonTemplate" id="19"/>
|
||||
<Button name="$parentButton20" inherits="L_UIDropDownMenuButtonTemplate" id="20"/>
|
||||
<Button name="$parentButton21" inherits="L_UIDropDownMenuButtonTemplate" id="21"/>
|
||||
<Button name="$parentButton22" inherits="L_UIDropDownMenuButtonTemplate" id="22"/>
|
||||
<Button name="$parentButton23" inherits="L_UIDropDownMenuButtonTemplate" id="23"/>
|
||||
<Button name="$parentButton24" inherits="L_UIDropDownMenuButtonTemplate" id="24"/>
|
||||
<Button name="$parentButton25" inherits="L_UIDropDownMenuButtonTemplate" id="25"/>
|
||||
<Button name="$parentButton26" inherits="L_UIDropDownMenuButtonTemplate" id="26"/>
|
||||
<Button name="$parentButton27" inherits="L_UIDropDownMenuButtonTemplate" id="27"/>
|
||||
<Button name="$parentButton28" inherits="L_UIDropDownMenuButtonTemplate" id="28"/>
|
||||
<Button name="$parentButton29" inherits="L_UIDropDownMenuButtonTemplate" id="29"/>
|
||||
<Button name="$parentButton30" inherits="L_UIDropDownMenuButtonTemplate" id="30"/>
|
||||
<Button name="$parentButton31" inherits="L_UIDropDownMenuButtonTemplate" id="31"/>
|
||||
<Button name="$parentButton32" inherits="L_UIDropDownMenuButtonTemplate" id="32"/>
|
||||
</Frames>
|
||||
<Scripts>
|
||||
<OnClick>
|
||||
this:Hide();
|
||||
</OnClick>
|
||||
<OnEnter>
|
||||
L_UIDropDownMenu_StopCounting(this, arg1);
|
||||
</OnEnter>
|
||||
<OnLeave>
|
||||
L_UIDropDownMenu_StartCounting(this, arg1);
|
||||
</OnLeave>
|
||||
<OnUpdate>
|
||||
L_UIDropDownMenu_OnUpdate(this, arg1);
|
||||
</OnUpdate>
|
||||
<OnShow>
|
||||
for i=1, L_UIDROPDOWNMENU_MAXBUTTONS do
|
||||
if (not this.noResize) then
|
||||
getglobal(this:GetName().."Button"..i):SetWidth(this.maxWidth);
|
||||
end
|
||||
end
|
||||
if (not this.noResize) then
|
||||
this:SetWidth(this.maxWidth+25);
|
||||
end
|
||||
this.showTimer = nil;
|
||||
if ( this:GetID() > 1 ) then
|
||||
this.parent = getglobal("L_DropDownList"..(this:GetID() - 1));
|
||||
end
|
||||
</OnShow>
|
||||
<OnHide>
|
||||
L_UIDropDownMenu_OnHide(this);
|
||||
</OnHide>
|
||||
</Scripts>
|
||||
</Button>
|
||||
|
||||
<Frame name="L_UIDropDownMenuTemplate" virtual="true">
|
||||
<Size>
|
||||
<AbsDimension x="40" y="32"/>
|
||||
</Size>
|
||||
<Layers>
|
||||
<Layer level="ARTWORK">
|
||||
<Texture name="$parentLeft" file="Interface\Glues\CharacterCreate\CharacterCreate-LabelFrame">
|
||||
<Size>
|
||||
<AbsDimension x="25" y="64"/>
|
||||
</Size>
|
||||
<Anchors>
|
||||
<Anchor point="TOPLEFT">
|
||||
<Offset>
|
||||
<AbsDimension x="0" y="17"/>
|
||||
</Offset>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<TexCoords left="0" right="0.1953125" top="0" bottom="1"/>
|
||||
</Texture>
|
||||
<Texture name="$parentMiddle" file="Interface\Glues\CharacterCreate\CharacterCreate-LabelFrame">
|
||||
<Size>
|
||||
<AbsDimension x="115" y="64"/>
|
||||
</Size>
|
||||
<Anchors>
|
||||
<Anchor point="LEFT" relativeTo="$parentLeft" relativePoint="RIGHT"/>
|
||||
</Anchors>
|
||||
<TexCoords left="0.1953125" right="0.8046875" top="0" bottom="1"/>
|
||||
</Texture>
|
||||
<Texture name="$parentRight" file="Interface\Glues\CharacterCreate\CharacterCreate-LabelFrame">
|
||||
<Size>
|
||||
<AbsDimension x="25" y="64"/>
|
||||
</Size>
|
||||
<Anchors>
|
||||
<Anchor point="LEFT" relativeTo="$parentMiddle" relativePoint="RIGHT"/>
|
||||
</Anchors>
|
||||
<TexCoords left="0.8046875" right="1" top="0" bottom="1"/>
|
||||
</Texture>
|
||||
<FontString parentKey="Text" name="$parentText" inherits="GameFontHighlightSmall" wordwrap="false" justifyH="RIGHT">
|
||||
<Size>
|
||||
<AbsDimension x="0" y="10"/>
|
||||
</Size>
|
||||
<Anchors>
|
||||
<Anchor point="RIGHT" relativeTo="$parentRight">
|
||||
<Offset>
|
||||
<AbsDimension x="-43" y="2"/>
|
||||
</Offset>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
</FontString>
|
||||
</Layer>
|
||||
<Layer level="OVERLAY">
|
||||
<Texture parentKey="Icon" name="$parentIcon" hidden="true">
|
||||
<Size>
|
||||
<AbsDimension x="16" y="16"/>
|
||||
</Size>
|
||||
<Anchors>
|
||||
<Anchor point="LEFT">
|
||||
<Offset x="30" y="2"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
</Texture>
|
||||
</Layer>
|
||||
</Layers>
|
||||
<Frames>
|
||||
<Button parentKey="Button" name="$parentButton" motionScriptsWhileDisabled="true" >
|
||||
<Size>
|
||||
<AbsDimension x="24" y="24"/>
|
||||
</Size>
|
||||
<Anchors>
|
||||
<Anchor point="TOPRIGHT" relativeTo="$parentRight">
|
||||
<Offset>
|
||||
<AbsDimension x="-16" y="-18"/>
|
||||
</Offset>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Scripts>
|
||||
<OnEnter>
|
||||
local parent = this:GetParent();
|
||||
local myscript = parent:GetScript("OnEnter");
|
||||
if(myscript ~= nil) then
|
||||
myscript(parent);
|
||||
end
|
||||
</OnEnter>
|
||||
<OnLeave>
|
||||
local parent = this:GetParent();
|
||||
local myscript = parent:GetScript("OnLeave");
|
||||
if(myscript ~= nil) then
|
||||
myscript(parent);
|
||||
end
|
||||
</OnLeave>
|
||||
<OnClick>
|
||||
L_ToggleDropDownMenu(nil, nil, this:GetParent());
|
||||
PlaySound(PlaySoundKitID and "igMainMenuOptionCheckBoxOn" or SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON);
|
||||
</OnClick>
|
||||
</Scripts>
|
||||
<NormalTexture name="$parentNormalTexture" file="Interface\ChatFrame\UI-ChatIcon-ScrollDown-Up">
|
||||
<Size>
|
||||
<AbsDimension x="24" y="24"/>
|
||||
</Size>
|
||||
<Anchors>
|
||||
<Anchor point="RIGHT"/>
|
||||
</Anchors>
|
||||
</NormalTexture>
|
||||
<PushedTexture name="$parentPushedTexture" file="Interface\ChatFrame\UI-ChatIcon-ScrollDown-Down">
|
||||
<Size>
|
||||
<AbsDimension x="24" y="24"/>
|
||||
</Size>
|
||||
<Anchors>
|
||||
<Anchor point="RIGHT"/>
|
||||
</Anchors>
|
||||
</PushedTexture>
|
||||
<DisabledTexture name="$parentDisabledTexture" file="Interface\ChatFrame\UI-ChatIcon-ScrollDown-Disabled">
|
||||
<Size>
|
||||
<AbsDimension x="24" y="24"/>
|
||||
</Size>
|
||||
<Anchors>
|
||||
<Anchor point="RIGHT"/>
|
||||
</Anchors>
|
||||
</DisabledTexture>
|
||||
<HighlightTexture name="$parentHighlightTexture" file="Interface\Buttons\UI-Common-MouseHilight" alphaMode="ADD">
|
||||
<Size>
|
||||
<AbsDimension x="24" y="24"/>
|
||||
</Size>
|
||||
<Anchors>
|
||||
<Anchor point="RIGHT"/>
|
||||
</Anchors>
|
||||
</HighlightTexture>
|
||||
</Button>
|
||||
</Frames>
|
||||
<Scripts>
|
||||
<OnHide>
|
||||
L_CloseDropDownMenus();
|
||||
</OnHide>
|
||||
</Scripts>
|
||||
</Frame>
|
||||
</Ui>
|
||||
@@ -0,0 +1,939 @@
|
||||
---
|
||||
--- check for an already loaded old WhoLib
|
||||
---
|
||||
|
||||
if WhoLibByALeX or WhoLib then
|
||||
-- the WhoLib-1.0 (WhoLibByALeX) or WhoLib (by Malex) is loaded -> fail!
|
||||
error("an other WhoLib is already running - disable them first!\n")
|
||||
return
|
||||
end -- if
|
||||
|
||||
---
|
||||
--- check version
|
||||
---
|
||||
|
||||
assert(LibStub, "LibWho-2.0 requires LibStub")
|
||||
|
||||
|
||||
local major_version = 'LibWho-2.0'
|
||||
local minor_version = tonumber("154") or 99999
|
||||
|
||||
local lib = LibStub:NewLibrary(major_version, minor_version)
|
||||
|
||||
|
||||
if not lib then
|
||||
return -- already loaded and no upgrade necessary
|
||||
end
|
||||
|
||||
lib.callbacks = lib.callbacks or LibStub("CallbackHandler-1.0"):New(lib)
|
||||
local callbacks = lib.callbacks
|
||||
|
||||
local am = {}
|
||||
local om = getmetatable(lib)
|
||||
if om then
|
||||
for k, v in pairs(om) do am[k] = v end
|
||||
end
|
||||
am.__tostring = function() return major_version end
|
||||
setmetatable(lib, am)
|
||||
|
||||
local function dbgfunc(...) if lib.Debug then print(unpack(arg)) end end
|
||||
local function NOP() return end
|
||||
local dbg = NOP
|
||||
|
||||
---
|
||||
--- initalize base
|
||||
---
|
||||
|
||||
if type(lib['hooked']) ~= 'table' then
|
||||
lib['hooked'] = {}
|
||||
end -- if
|
||||
|
||||
if type(lib['hook']) ~= 'table' then
|
||||
lib['hook'] = {}
|
||||
end -- if
|
||||
|
||||
if type(lib['events']) ~= 'table' then
|
||||
lib['events'] = {}
|
||||
end -- if
|
||||
|
||||
if type(lib['embeds']) ~= 'table' then
|
||||
lib['embeds'] = {}
|
||||
end -- if
|
||||
|
||||
if type(lib['frame']) ~= 'table' then
|
||||
lib['frame'] = CreateFrame('Frame', major_version);
|
||||
end -- if
|
||||
lib['frame']:Hide()
|
||||
|
||||
lib.Queue = {[1]={}, [2]={}, [3]={}}
|
||||
lib.WhoInProgress = false
|
||||
lib.Result = nil
|
||||
lib.Args = nil
|
||||
lib.Total = nil
|
||||
lib.Quiet = nil
|
||||
lib.Debug = false
|
||||
lib.Cache = {}
|
||||
lib.CacheQueue = {}
|
||||
lib.SetWhoToUIState = false
|
||||
|
||||
|
||||
lib.MinInterval = 2.5
|
||||
lib.MaxInterval = 10
|
||||
|
||||
---
|
||||
--- locale
|
||||
---
|
||||
|
||||
if (GetLocale() == "ruRU") then
|
||||
lib.L = {
|
||||
['console_queued'] = 'Добавлено в очередь "/who %s"',
|
||||
['console_query'] = 'Результат "/who %s"',
|
||||
['gui_wait'] = '- Пожалуйста подождите -',
|
||||
}
|
||||
else
|
||||
-- enUS is the default
|
||||
lib.L = {
|
||||
['console_queued'] = 'Added "/who %s" to queue',
|
||||
['console_query'] = 'Result of "/who %s"',
|
||||
['gui_wait'] = '- Please Wait -',
|
||||
}
|
||||
end -- if
|
||||
|
||||
|
||||
---
|
||||
--- external functions/constants
|
||||
---
|
||||
|
||||
lib['external'] = {
|
||||
'WHOLIB_QUEUE_USER',
|
||||
'WHOLIB_QUEUE_QUIET',
|
||||
'WHOLIB_QUEUE_SCANNING',
|
||||
'WHOLIB_FLAG_ALWAYS_CALLBACK',
|
||||
'Who',
|
||||
'UserInfo',
|
||||
'CachedUserInfo',
|
||||
'GetWhoLibDebug',
|
||||
'SetWhoLibDebug',
|
||||
-- 'RegisterWhoLibEvent',
|
||||
}
|
||||
|
||||
-- queues
|
||||
lib['WHOLIB_QUEUE_USER'] = 1
|
||||
lib['WHOLIB_QUEUE_QUIET'] = 2
|
||||
lib['WHOLIB_QUEUE_SCANNING'] = 3
|
||||
|
||||
|
||||
|
||||
local queue_all = {
|
||||
[1] = 'WHOLIB_QUEUE_USER',
|
||||
[2] = 'WHOLIB_QUEUE_QUIET',
|
||||
[3] = 'WHOLIB_QUEUE_SCANNING',
|
||||
}
|
||||
|
||||
local queue_quiet = {
|
||||
[2] = 'WHOLIB_QUEUE_QUIET',
|
||||
[3] = 'WHOLIB_QUEUE_SCANNING',
|
||||
}
|
||||
|
||||
-- bit masks!
|
||||
lib['WHOLIB_FLAG_ALWAYS_CALLBACK'] = 1
|
||||
|
||||
function lib:Reset()
|
||||
self.Queue = {[1]={}, [2]={}, [3]={}}
|
||||
self.Cache = {}
|
||||
self.CacheQueue = {}
|
||||
end
|
||||
|
||||
function lib.Who(defhandler, query, opts)
|
||||
local self, args, usage = lib, {}, 'Who(query, [opts])'
|
||||
|
||||
args.query = self:CheckArgument(usage, 'query', 'string', query)
|
||||
opts = self:CheckArgument(usage, 'opts', 'table', opts, {})
|
||||
args.queue = self:CheckPreset(usage, 'opts.queue', queue_all, opts.queue, self.WHOLIB_QUEUE_SCANNING)
|
||||
args.flags = self:CheckArgument(usage, 'opts.flags', 'number', opts.flags, 0)
|
||||
args.callback, args.handler = self:CheckCallback(usage, 'opts.', opts.callback, opts.handler, defhandler)
|
||||
-- now args - copied and verified from opts
|
||||
|
||||
if args.queue == self.WHOLIB_QUEUE_USER then
|
||||
if WhoFrame:IsShown() then
|
||||
self:GuiWho(args.query)
|
||||
else
|
||||
self:ConsoleWho(args.query)
|
||||
end
|
||||
else
|
||||
self:AskWho(args)
|
||||
end
|
||||
end
|
||||
|
||||
function lib.UserInfo(defhandler, name, opts)
|
||||
local self, args, usage = lib, {}, 'UserInfo(name, [opts])'
|
||||
local now = time()
|
||||
|
||||
name = self:CheckArgument(usage, 'name', 'string', name)
|
||||
if strlen(name) == 0 then return end
|
||||
|
||||
if string.find(name, "%-") then --[[dbg("ignoring xrealm: "..name)]] return end
|
||||
|
||||
args.name = self:CapitalizeInitial(name)
|
||||
opts = self:CheckArgument(usage, 'opts', 'table', opts, {})
|
||||
args.queue = self:CheckPreset(usage, 'opts.queue', queue_quiet, opts.queue, self.WHOLIB_QUEUE_SCANNING)
|
||||
args.flags = self:CheckArgument(usage, 'opts.flags', 'number', opts.flags, 0)
|
||||
args.timeout = self:CheckArgument(usage, 'opts.timeout', 'number', opts.timeout, 5)
|
||||
args.callback, args.handler = self:CheckCallback(usage, 'opts.', opts.callback, opts.handler, defhandler)
|
||||
|
||||
-- now args - copied and verified from opts
|
||||
local cachedName = self.Cache[args.name]
|
||||
|
||||
if(cachedName ~= nil)then
|
||||
-- user is in cache
|
||||
if(cachedName.valid == true and (args.timeout < 0 or cachedName.last + args.timeout*60 > now))then
|
||||
-- cache is valid and timeout is in range
|
||||
--dbg('Info(' .. args.name ..') returned immedeatly')
|
||||
if(bit.band(args.flags, self.WHOLIB_FLAG_ALWAYS_CALLBACK) ~= 0)then
|
||||
self:RaiseCallback(args, cachedName.data)
|
||||
return false
|
||||
else
|
||||
return self:DupAll(self:ReturnUserInfo(args.name))
|
||||
end
|
||||
elseif(cachedName.valid == false)then
|
||||
-- query is already running (first try)
|
||||
if(args.callback ~= nil)then
|
||||
tinsert(cachedName.callback, args)
|
||||
end
|
||||
--dbg('Info(' .. args.name ..') returned cause it\'s already searching')
|
||||
return nil
|
||||
end
|
||||
else
|
||||
self.Cache[args.name] = {valid=false, inqueue=false, callback={}, data={Name = args.name}, last=now }
|
||||
end
|
||||
|
||||
local cachedName = self.Cache[args.name]
|
||||
|
||||
if(cachedName.inqueue)then
|
||||
-- query is running!
|
||||
if(args.callback ~= nil)then
|
||||
tinsert(cachedName.callback, args)
|
||||
end
|
||||
dbg('Info(' .. args.name ..') returned cause it\'s already searching')
|
||||
return nil
|
||||
end
|
||||
if (GetLocale() == "ruRU") then -- in ruRU with n- not show information about player in WIM addon
|
||||
if args.name and strlen(args.name) > 0 then
|
||||
local query = 'и-"' .. args.name .. '"'
|
||||
cachedName.inqueue = true
|
||||
if(args.callback ~= nil)then
|
||||
tinsert(cachedName.callback, args)
|
||||
end
|
||||
self.CacheQueue[query] = args.name
|
||||
dbg('Info(' .. args.name ..') added to queue')
|
||||
self:AskWho( { query = query, queue = args.queue, flags = 0, info = args.name } )
|
||||
end
|
||||
else
|
||||
if args.name and strlen(args.name) > 0 then
|
||||
local query = 'n-"' .. args.name .. '"'
|
||||
cachedName.inqueue = true
|
||||
if(args.callback ~= nil)then
|
||||
tinsert(cachedName.callback, args)
|
||||
end
|
||||
self.CacheQueue[query] = args.name
|
||||
dbg('Info(' .. args.name ..') added to queue')
|
||||
self:AskWho( { query = query, queue = args.queue, flags = 0, info = args.name } )
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function lib.CachedUserInfo(_, name)
|
||||
local self, usage = lib, 'CachedUserInfo(name)'
|
||||
|
||||
name = self:CapitalizeInitial(self:CheckArgument(usage, 'name', 'string', name))
|
||||
|
||||
if self.Cache[name] == nil then
|
||||
return nil
|
||||
else
|
||||
return self:DupAll(self:ReturnUserInfo(name))
|
||||
end
|
||||
end
|
||||
|
||||
function lib.GetWhoLibDebug(_, mode)
|
||||
return lib.Debug
|
||||
end
|
||||
|
||||
function lib.SetWhoLibDebug(_, mode)
|
||||
lib.Debug = mode
|
||||
dbg = mode and dbgfunc or NOP
|
||||
end
|
||||
|
||||
--function lib.RegisterWhoLibEvent(defhandler, event, callback, handler)
|
||||
-- local self, usage = lib, 'RegisterWhoLibEvent(event, callback, [handler])'
|
||||
--
|
||||
-- self:CheckPreset(usage, 'event', self.events, event)
|
||||
-- local callback, handler = self:CheckCallback(usage, '', callback, handler, defhandler, true)
|
||||
-- table.insert(self.events[event], {callback=callback, handler=handler})
|
||||
--end
|
||||
|
||||
-- non-embedded externals
|
||||
|
||||
function lib.Embed(_, handler)
|
||||
local self, usage = lib, 'Embed(handler)'
|
||||
|
||||
self:CheckArgument(usage, 'handler', 'table', handler)
|
||||
|
||||
for _,name in pairs(self.external) do
|
||||
handler[name] = self[name]
|
||||
end -- do
|
||||
self['embeds'][handler] = true
|
||||
|
||||
return handler
|
||||
end
|
||||
|
||||
function lib.Library(_)
|
||||
local self = lib
|
||||
|
||||
return self:Embed({})
|
||||
end
|
||||
|
||||
---
|
||||
--- internal functions
|
||||
---
|
||||
|
||||
function lib:AllQueuesEmpty()
|
||||
local queueCount = getn(self.Queue[1]) + getn(self.Queue[2]) + getn(self.Queue[3]) + getn(self.CacheQueue)
|
||||
|
||||
-- Be sure that we have cleared the in-progress status
|
||||
if self.WhoInProgress then
|
||||
queueCount = queueCount + 1
|
||||
end
|
||||
|
||||
return queueCount == 0
|
||||
end
|
||||
|
||||
local queryInterval = 5
|
||||
|
||||
function lib:GetQueryInterval() return queryInterval end
|
||||
|
||||
function lib:AskWhoNextIn5sec()
|
||||
if self.frame:IsShown() then return end
|
||||
|
||||
dbg("Waiting to send next who")
|
||||
self.Timeout_time = queryInterval
|
||||
self['frame']:Show()
|
||||
end
|
||||
|
||||
function lib:CancelPendingWhoNext()
|
||||
lib['frame']:Hide()
|
||||
end
|
||||
|
||||
lib['frame']:SetScript("OnUpdate", function()
|
||||
lib.Timeout_time = lib.Timeout_time - arg1
|
||||
if lib.Timeout_time <= 0 then
|
||||
lib['frame']:Hide()
|
||||
lib:AskWhoNext()
|
||||
end -- if
|
||||
end);
|
||||
|
||||
|
||||
-- queue scheduler
|
||||
local queue_weights = { [1] = 0.6, [2] = 0.2, [3] = 0.2 }
|
||||
local queue_bounds = { [1] = 0.6, [2] = 0.2, [3] = 0.2 }
|
||||
|
||||
-- allow for single queries from the user to get processed faster
|
||||
local lastInstantQuery = time()
|
||||
local INSTANT_QUERY_MIN_INTERVAL = 60 -- only once every 1 min
|
||||
|
||||
function lib:UpdateWeights()
|
||||
local weightsum, sum, count = 0, 0, 0
|
||||
for k,v in pairs(queue_weights) do
|
||||
sum = sum + v
|
||||
weightsum = weightsum + v * getn(self.Queue[k])
|
||||
end
|
||||
|
||||
if weightsum == 0 then
|
||||
for k,v in pairs(queue_weights) do queue_bounds[k] = v end
|
||||
return
|
||||
end
|
||||
|
||||
local adjust = sum / weightsum
|
||||
|
||||
for k,v in pairs(queue_bounds) do
|
||||
queue_bounds[k] = queue_weights[k] * adjust * getn(self.Queue[k])
|
||||
end
|
||||
end
|
||||
|
||||
function lib:GetNextFromScheduler()
|
||||
self:UpdateWeights()
|
||||
|
||||
-- Since an addon could just fill up the user q for instant processing
|
||||
-- we have to limit instants to 1 per INSTANT_QUERY_MIN_INTERVAL
|
||||
-- and only try instant fulfilment if it will empty the user queue
|
||||
if getn(self.Queue[1]) == 1 then
|
||||
if time() - lastInstantQuery > INSTANT_QUERY_MIN_INTERVAL then
|
||||
dbg("INSTANT")
|
||||
lastInstantQuery = time()
|
||||
return 1, self.Queue[1]
|
||||
end
|
||||
end
|
||||
|
||||
local n,i = math.random(),0
|
||||
repeat
|
||||
i=i+1
|
||||
n = n - queue_bounds[i]
|
||||
until i >= getn(self.Queue) or n <= 0
|
||||
|
||||
dbg(string.format("Q=%d, bound=%d", i, queue_bounds[i]))
|
||||
|
||||
if getn(self.Queue[i]) > 0 then
|
||||
dbg(string.format("Q=%d, bound=%d", i, queue_bounds[i]))
|
||||
return i, self.Queue[i]
|
||||
else
|
||||
dbg("Queues empty, waiting")
|
||||
end
|
||||
end
|
||||
|
||||
lib.queue_bounds = queue_bounds
|
||||
|
||||
function lib:AskWhoNext()
|
||||
if lib.frame:IsShown() then
|
||||
dbg("Already waiting")
|
||||
return
|
||||
end
|
||||
|
||||
self:CancelPendingWhoNext()
|
||||
|
||||
if self.WhoInProgress then
|
||||
-- if we had a who going, it didnt complete
|
||||
dbg("TIMEOUT: "..self.Args.query)
|
||||
local args = self.Args
|
||||
self.Args = nil
|
||||
-- if args.info and self.CacheQueue[args.query] ~= nil then
|
||||
dbg("Requeing "..args.query)
|
||||
tinsert(self.Queue[args.queue], args)
|
||||
if args.console_show ~= nil then
|
||||
DEFAULT_CHAT_FRAME:AddMessage(string.format("Timeout on result of '%s' - retrying...", args.query), 1, 1, 0)
|
||||
args.console_show = true
|
||||
end
|
||||
-- end
|
||||
|
||||
if queryInterval < lib.MaxInterval then
|
||||
queryInterval = queryInterval + 0.5
|
||||
dbg("--Throttling down to 1 who per " .. queryInterval .. "s")
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
self.WhoInProgress = false
|
||||
|
||||
local v,k,args = nil
|
||||
local kludge = 10
|
||||
repeat
|
||||
k, v = self:GetNextFromScheduler()
|
||||
if not k then break end
|
||||
if WhoFrame:IsShown() and k > self.WHOLIB_QUEUE_QUIET then
|
||||
break
|
||||
end
|
||||
if getn(v) > 0 then
|
||||
args = tremove(v, 1)
|
||||
break
|
||||
end
|
||||
kludge = kludge - 1
|
||||
until kludge <= 0
|
||||
|
||||
if args then
|
||||
self.WhoInProgress = true
|
||||
self.Result = {}
|
||||
self.Args = args
|
||||
self.Total = -1
|
||||
if(args.console_show == true)then
|
||||
DEFAULT_CHAT_FRAME:AddMessage(string.format(self.L['console_query'], args.query), 1, 1, 0)
|
||||
|
||||
end
|
||||
|
||||
if args.queue == self.WHOLIB_QUEUE_USER then
|
||||
WhoFrameEditBox:SetText(args.query)
|
||||
self.Quiet = false
|
||||
|
||||
if args.whotoui then
|
||||
-- self.hooked.SetWhoToUI(args.whotoui)
|
||||
else
|
||||
-- self.hooked.SetWhoToUI(args.gui and true or false)
|
||||
end
|
||||
else
|
||||
-- self.hooked.SetWhoToUI(true)
|
||||
self.Quiet = true
|
||||
end
|
||||
|
||||
dbg("QUERY: "..args.query)
|
||||
-- self.hooked.SendWho(args.query)
|
||||
else
|
||||
self.Args = nil
|
||||
self.WhoInProgress = false
|
||||
end
|
||||
|
||||
-- Keep processing the who queue if there is more work
|
||||
if not self:AllQueuesEmpty() then
|
||||
self:AskWhoNextIn5sec()
|
||||
else
|
||||
dbg("*** Done processing requests ***")
|
||||
end
|
||||
end
|
||||
|
||||
function lib:AskWho(args)
|
||||
tinsert(self.Queue[args.queue], args)
|
||||
dbg('[' .. args.queue .. '] added "' .. args.query .. '", queues=' .. getn(self.Queue[1]) .. '/'.. getn(self.Queue[2]) .. '/'.. getn(self.Queue[3]))
|
||||
self:TriggerEvent('WHOLIB_QUERY_ADDED')
|
||||
|
||||
self:AskWhoNext()
|
||||
end
|
||||
|
||||
function lib:ReturnWho()
|
||||
if not self.Args then
|
||||
self.Quiet = nil
|
||||
return
|
||||
end
|
||||
|
||||
if(self.Args.queue == self.WHOLIB_QUEUE_QUIET or self.Args.queue == self.WHOLIB_QUEUE_SCANNING)then
|
||||
self.Quiet = nil
|
||||
end
|
||||
|
||||
if queryInterval > self.MinInterval then
|
||||
queryInterval = queryInterval - 0.5
|
||||
dbg("--Throttling up to 1 who per " .. queryInterval .. "s")
|
||||
end
|
||||
|
||||
self.WhoInProgress = false
|
||||
dbg("RESULT: "..self.Args.query)
|
||||
dbg('[' .. self.Args.queue .. '] returned "' .. self.Args.query .. '", total=' .. self.Total ..' , queues=' .. getn(self.Queue[1]) .. '/'.. getn(self.Queue[2]) .. '/'.. getn(self.Queue[3]))
|
||||
local now = time()
|
||||
local complete = (self.Total == getn(self.Result)) and (self.Total < MAX_WHOS_FROM_SERVER)
|
||||
for _,v in pairs(self.Result)do
|
||||
if v.Name then
|
||||
if(self.Cache[v.Name] == nil)then
|
||||
self.Cache[v.Name] = { inqueue = false, callback = {} }
|
||||
end
|
||||
|
||||
local cachedName = self.Cache[v.Name]
|
||||
|
||||
cachedName.valid = true -- is now valid
|
||||
cachedName.data = v -- update data
|
||||
cachedName.data.Online = true -- player is online
|
||||
cachedName.last = now -- update timestamp
|
||||
if(cachedName.inqueue)then
|
||||
if(self.Args.info and self.CacheQueue[self.Args.query] == v.Name)then
|
||||
-- found by the query which was created to -> remove us from query
|
||||
self.CacheQueue[self.Args.query] = nil
|
||||
else
|
||||
-- found by another query
|
||||
for k2,v2 in pairs(self.CacheQueue) do
|
||||
if(v2 == v.Name)then
|
||||
for i=self.WHOLIB_QUEUE_QUIET, self.WHOLIB_QUEUE_SCANNING do
|
||||
for k3,v3 in pairs(self.Queue[i]) do
|
||||
if(v3.query == k2 and v3.info)then
|
||||
-- remove the query which was generated for this user, cause another query was faster...
|
||||
dbg("Found '"..v.Name.."' early via query '"..self.Args.query.."'")
|
||||
table.remove(self.Queue[i], k3)
|
||||
self.CacheQueue[k2] = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
dbg('Info(' .. v.Name ..') returned: on')
|
||||
for _,v2 in pairs(cachedName.callback) do
|
||||
self:RaiseCallback(v2, self:ReturnUserInfo(v.Name))
|
||||
end
|
||||
cachedName.callback = {}
|
||||
end
|
||||
cachedName.inqueue = false -- query is done
|
||||
end
|
||||
end
|
||||
if(self.Args.info and self.CacheQueue[self.Args.query])then
|
||||
-- the query did not deliver the result => not online!
|
||||
local name = self.CacheQueue[self.Args.query]
|
||||
local cachedName = self.Cache[name]
|
||||
if (cachedName.inqueue)then
|
||||
-- nothing found (yet)
|
||||
cachedName.valid = true -- is now valid
|
||||
cachedName.inqueue = false -- query is done?
|
||||
cachedName.last = now -- update timestamp
|
||||
if(complete)then
|
||||
cachedName.data.Online = false -- player is offline
|
||||
else
|
||||
cachedName.data.Online = nil -- player is unknown (more results from who than can be displayed)
|
||||
end
|
||||
end
|
||||
dbg('Info(' .. name ..') returned: ' .. (cachedName.data.Online == false and 'off' or 'unkn'))
|
||||
for _,v in pairs(cachedName.callback) do
|
||||
self:RaiseCallback(v, self:ReturnUserInfo(name))
|
||||
end
|
||||
cachedName.callback = {}
|
||||
self.CacheQueue[self.Args.query] = nil
|
||||
end
|
||||
self:RaiseCallback(self.Args, self.Args.query, self.Result, complete, self.Args.info)
|
||||
self:TriggerEvent('WHOLIB_QUERY_RESULT', self.Args.query, self.Result, complete, self.Args.info)
|
||||
|
||||
if not self:AllQueuesEmpty() then
|
||||
self:AskWhoNextIn5sec()
|
||||
end
|
||||
end
|
||||
|
||||
function lib:GuiWho(msg)
|
||||
if(msg == self.L['gui_wait'])then
|
||||
return
|
||||
end
|
||||
|
||||
for _,v in pairs(self.Queue[self.WHOLIB_QUEUE_USER]) do
|
||||
if(v.gui == true)then
|
||||
return
|
||||
end
|
||||
end
|
||||
if(self.WhoInProgress)then
|
||||
WhoFrameEditBox:SetText(self.L['gui_wait'])
|
||||
end
|
||||
self.savedText = msg
|
||||
self:AskWho({query = msg, queue = self.WHOLIB_QUEUE_USER, flags = 0, gui = true})
|
||||
WhoFrameEditBox:ClearFocus();
|
||||
end
|
||||
|
||||
function lib:ConsoleWho(msg)
|
||||
--WhoFrameEditBox:SetText(msg)
|
||||
local console_show = false
|
||||
local q1 = self.Queue[self.WHOLIB_QUEUE_USER]
|
||||
local q1count = getn(q1)
|
||||
|
||||
if(q1count > 0 and q1[q1count].query == msg)then -- last query is itdenical: drop
|
||||
return
|
||||
end
|
||||
|
||||
if(q1count > 0 and q1[q1count].console_show == false)then -- display 'queued' if console and not yet shown
|
||||
DEFAULT_CHAT_FRAME:AddMessage(string.format(self.L['console_queued'], q1[q1count].query), 1, 1, 0)
|
||||
q1[q1count].console_show = true
|
||||
end
|
||||
if(q1count > 0 or self.WhoInProgress)then
|
||||
DEFAULT_CHAT_FRAME:AddMessage(string.format(self.L['console_queued'], msg), 1, 1, 0)
|
||||
console_show = true
|
||||
end
|
||||
self:AskWho({query = msg, queue = self.WHOLIB_QUEUE_USER, flags = 0, console_show = console_show})
|
||||
end
|
||||
|
||||
function lib:ReturnUserInfo(name)
|
||||
if(name ~= nil and self ~= nil and self.Cache ~= nil and self.Cache[name] ~= nil) then
|
||||
return self.Cache[name].data, (time() - self.Cache[name].last) / 60
|
||||
end
|
||||
end
|
||||
|
||||
function lib:RaiseCallback(args, ...)
|
||||
if type(args.callback) == 'function' then
|
||||
args.callback(self:DupAll(unpack(args)))
|
||||
elseif args.callback then -- must be a string
|
||||
args.handler[args.callback](args.handler, self:DupAll(unpack(args)))
|
||||
end -- if
|
||||
end
|
||||
|
||||
-- Argument checking
|
||||
|
||||
function lib:CheckArgument(func, name, argtype, arg, defarg)
|
||||
if arg == nil and defarg ~= nil then
|
||||
return defarg
|
||||
elseif type(arg) == argtype then
|
||||
return arg
|
||||
else
|
||||
error(string.format("%s: '%s' - %s%s expected got %s", func, name, (defarg ~= nil) and 'nil or ' or '', argtype, type(arg)), 3)
|
||||
end -- if
|
||||
end
|
||||
|
||||
function lib:CheckPreset(func, name, preset, arg, defarg)
|
||||
if arg == nil and defarg ~= nil then
|
||||
return defarg
|
||||
elseif arg ~= nil and preset[arg] ~= nil then
|
||||
return arg
|
||||
else
|
||||
local p = {}
|
||||
for k,v in pairs(preset) do
|
||||
if type(v) ~= 'string' then
|
||||
table.insert(p, k)
|
||||
else
|
||||
table.insert(p, v)
|
||||
end -- if
|
||||
end -- for
|
||||
error(string.format("%s: '%s' - one of %s%s expected got %s", func, name, (defarg ~= nil) and 'nil, ' or '', table.concat(p, ', '), self:simple_dump(arg)), 3)
|
||||
end -- if
|
||||
end
|
||||
|
||||
function lib:CheckCallback(func, prefix, callback, handler, defhandler, nonil)
|
||||
if not nonil and callback == nil then
|
||||
-- no callback: ignore handler
|
||||
return nil, nil
|
||||
elseif type(callback) == 'function' then
|
||||
-- simple function
|
||||
if handler ~= nil then
|
||||
error(string.format("%s: '%shandler' - nil expected got %s", func, prefix, type(arg)), 3)
|
||||
end -- if
|
||||
elseif type(callback) == 'string' then
|
||||
-- method
|
||||
if handler == nil then
|
||||
handler = defhandler
|
||||
end -- if
|
||||
if type(handler) ~= 'table' or type(handler[callback]) ~= 'function' or handler == self then
|
||||
error(string.format("%s: '%shandler' - nil or function expected got %s", func, prefix, type(arg)), 3)
|
||||
end -- if
|
||||
else
|
||||
error(string.format("%s: '%scallback' - %sfunction or string expected got %s", func, prefix, nonil and 'nil or ' or '', type(arg)), 3)
|
||||
end -- if
|
||||
|
||||
return callback, handler
|
||||
end
|
||||
|
||||
-- helpers
|
||||
|
||||
function lib:simple_dump(x)
|
||||
if type(x) == 'string' then
|
||||
return 'string \''..x..'\''
|
||||
elseif type(x) == 'number' then
|
||||
return 'number '..x
|
||||
else
|
||||
return type(x)
|
||||
end
|
||||
end
|
||||
|
||||
function lib:Dup(from)
|
||||
local to = {}
|
||||
|
||||
for k,v in pairs(from) do
|
||||
if type(v) == 'table' then
|
||||
to[k] = self:Dup(v)
|
||||
else
|
||||
to[k] = v
|
||||
end -- if
|
||||
end -- for
|
||||
|
||||
return to
|
||||
end
|
||||
|
||||
function lib:DupAll(x, ...)
|
||||
if type(x) == 'table' then
|
||||
return self:Dup(x), self:DupAll(unpack(args))
|
||||
elseif x ~= nil then
|
||||
return x, self:DupAll(unpack(args))
|
||||
else
|
||||
return nil
|
||||
end -- if
|
||||
end
|
||||
|
||||
local MULTIBYTE_FIRST_CHAR = "^([\192-\255]?%a?[\128-\191]*)"
|
||||
|
||||
function lib:CapitalizeInitial(name)
|
||||
return string.gsub(name, MULTIBYTE_FIRST_CHAR, string.upper, 1)
|
||||
end
|
||||
|
||||
---
|
||||
--- user events (Using CallbackHandler)
|
||||
---
|
||||
|
||||
lib.PossibleEvents = {
|
||||
'WHOLIB_QUERY_RESULT',
|
||||
'WHOLIB_QUERY_ADDED',
|
||||
}
|
||||
|
||||
function lib:TriggerEvent(...)
|
||||
callbacks:Fire(event, unpack(arg))
|
||||
end
|
||||
|
||||
---
|
||||
--- slash commands
|
||||
---
|
||||
|
||||
SlashCmdList['WHO'] = function(msg)
|
||||
dbg("console /who: "..msg)
|
||||
-- new /who function
|
||||
--local self = lib
|
||||
|
||||
if(msg == '')then
|
||||
lib:GuiWho(WhoFrame_GetDefaultWhoCommand())
|
||||
elseif(WhoFrame:IsVisible())then
|
||||
lib:GuiWho(msg)
|
||||
else
|
||||
lib:ConsoleWho(msg)
|
||||
end
|
||||
end
|
||||
|
||||
SlashCmdList['WHOLIB_DEBUG'] = function()
|
||||
-- /wholibdebug: toggle debug on/off
|
||||
local self = lib
|
||||
|
||||
self:SetWhoLibDebug(not self.Debug)
|
||||
end
|
||||
|
||||
SLASH_WHOLIB_DEBUG1 = '/wholibdebug'
|
||||
|
||||
|
||||
---
|
||||
--- hook activation
|
||||
---
|
||||
|
||||
-- functions to hook
|
||||
local hooks = {
|
||||
-- 'SendWho',
|
||||
-- 'WhoFrameEditBox_OnEnterPressed',
|
||||
-- 'FriendsFrame_OnEvent',
|
||||
-- 'SetWhoToUI',
|
||||
}
|
||||
|
||||
-- hook all functions (which are not yet hooked)
|
||||
for _, name in pairs(hooks) do
|
||||
if not lib['hooked'][name] then
|
||||
lib['hooked'][name] = _G[name]
|
||||
_G[name] = function(...)
|
||||
lib.hook[name](lib, unpack(arg))
|
||||
end -- function
|
||||
end -- if
|
||||
end -- for
|
||||
|
||||
-- fake 'WhoFrame:Hide' as hooked
|
||||
table.insert(hooks, 'WhoFrame_Hide')
|
||||
|
||||
-- check for unused hooks -> remove function
|
||||
for name, _ in pairs(lib['hook']) do
|
||||
if not hooks[name] then
|
||||
lib['hook'][name] = function() end
|
||||
end -- if
|
||||
end -- for
|
||||
|
||||
-- secure hook 'WhoFrame:Hide'
|
||||
if not lib['hooked']['WhoFrame_Hide'] then
|
||||
lib['hooked']['WhoFrame_Hide'] = true
|
||||
hooksecurefunc(WhoFrame, 'Hide', function(...)
|
||||
lib['hook']['WhoFrame_Hide'](lib, unpack(arg))
|
||||
end -- function
|
||||
)
|
||||
end -- if
|
||||
|
||||
|
||||
|
||||
----- Coroutine based implementation (future)
|
||||
--function lib:sendWhoResult(val)
|
||||
-- coroutine.yield(val)
|
||||
--end
|
||||
--
|
||||
--function lib:sendWaitState(val)
|
||||
-- coroutine.yield(val)
|
||||
--end
|
||||
--
|
||||
--function lib:producer()
|
||||
-- return coroutine.create(
|
||||
-- function()
|
||||
-- lib:AskWhoNext()
|
||||
-- lib:sendWaitState(true)
|
||||
--
|
||||
-- -- Resumed look for data
|
||||
--
|
||||
-- end)
|
||||
--end
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
---
|
||||
--- hook replacements
|
||||
---
|
||||
|
||||
function lib.hook.SendWho(self, msg)
|
||||
dbg("SendWho: "..msg)
|
||||
lib.AskWho(self, {query = msg, queue = lib.WHOLIB_QUEUE_USER, whotoui = lib.SetWhoToUIState, flags = 0})
|
||||
end
|
||||
|
||||
function lib.hook.WhoFrameEditBox_OnEnterPressed(self)
|
||||
lib:GuiWho(WhoFrameEditBox:GetText())
|
||||
end
|
||||
|
||||
--[[
|
||||
function lib.hook.FriendsFrame_OnEvent(self, ...)
|
||||
if event ~= 'WHO_LIST_UPDATE' or not lib.Quiet then
|
||||
lib.hooked.FriendsFrame_OnEvent(...)
|
||||
end
|
||||
end
|
||||
]]
|
||||
|
||||
hooksecurefunc(FriendsFrame, 'RegisterEvent', function(self, event)
|
||||
if(event == "WHO_LIST_UPDATE") then
|
||||
self:UnregisterEvent("WHO_LIST_UPDATE");
|
||||
end
|
||||
end);
|
||||
|
||||
|
||||
function lib.hook.SetWhoToUI(self, state)
|
||||
lib.SetWhoToUIState = state
|
||||
end
|
||||
|
||||
function lib.hook.WhoFrame_Hide(self)
|
||||
if(not lib.WhoInProgress)then
|
||||
lib:AskWhoNextIn5sec()
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
---
|
||||
--- WoW events
|
||||
---
|
||||
|
||||
local who_pattern = string.gsub(WHO_NUM_RESULTS, '%%d', '%%d%+')
|
||||
|
||||
|
||||
function lib:CHAT_MSG_SYSTEM(arg1)
|
||||
if arg1 and string.find(arg1, who_pattern) then
|
||||
lib:ProcessWhoResults()
|
||||
end
|
||||
end
|
||||
|
||||
FriendsFrame:UnregisterEvent("WHO_LIST_UPDATE")
|
||||
|
||||
function lib:WHO_LIST_UPDATE()
|
||||
if not lib.Quiet then
|
||||
WhoList_Update()
|
||||
FriendsFrame_Update()
|
||||
end
|
||||
|
||||
lib:ProcessWhoResults()
|
||||
end
|
||||
|
||||
function lib:ProcessWhoResults()
|
||||
self.Result = self.Result and table.wipe(self.Result) or {}
|
||||
|
||||
local num
|
||||
self.Total, num = GetNumWhoResults()
|
||||
for i=1, num do
|
||||
local charname, guildname, level, race, class, zone, nonlocalclass, sex = GetWhoInfo(i)
|
||||
self.Result[i] = {Name=charname, Guild=guildname, Level=level, Race=race, Class=class, Zone=zone, NoLocaleClass=nonlocalclass, Sex=sex }
|
||||
end
|
||||
|
||||
self:ReturnWho()
|
||||
end
|
||||
|
||||
---
|
||||
--- event activation
|
||||
---
|
||||
|
||||
lib['frame']:UnregisterAllEvents();
|
||||
|
||||
lib['frame']:SetScript("OnEvent", function(...)
|
||||
lib[event](lib, unpack(arg))
|
||||
end);
|
||||
|
||||
for _,name in pairs({
|
||||
'CHAT_MSG_SYSTEM',
|
||||
'WHO_LIST_UPDATE',
|
||||
}) do
|
||||
lib['frame']:RegisterEvent(name);
|
||||
end -- for
|
||||
|
||||
|
||||
---
|
||||
--- re-embed
|
||||
---
|
||||
|
||||
for target,_ in pairs(lib['embeds']) do
|
||||
if type(target) == 'table' then
|
||||
lib:Embed(target)
|
||||
end -- if
|
||||
end -- for
|
||||
@@ -0,0 +1,4 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/
|
||||
..\FrameXML\UI.xsd">
|
||||
<Script file="LibWho-2.0.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,26 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Include file="LibStub\LibStub.xml"/>
|
||||
<Include file="CallbackHandler-1.0\CallbackHandler-1.0.xml"/>
|
||||
<Include file="AceCore-3.0\AceCore-3.0.xml"/>
|
||||
<Include file="AceAddon-3.0\AceAddon-3.0.xml"/>
|
||||
<Include file="AceEvent-3.0\AceEvent-3.0.xml"/>
|
||||
<Include file="AceConsole-3.0\AceConsole-3.0.xml"/>
|
||||
<Include file="AceDB-3.0\AceDB-3.0.xml"/>
|
||||
<Include file="AceLocale-3.0\AceLocale-3.0.xml"/>
|
||||
<Include file="AceComm-3.0\AceComm-3.0.xml"/>
|
||||
<Include file="AceSerializer-3.0\AceSerializer-3.0.xml"/>
|
||||
<Include file="AceTimer-3.0\AceTimer-3.0.xml"/>
|
||||
<Include file="AceHook-3.0\AceHook-3.0.xml"/>
|
||||
<Include file="LibSharedMedia-3.0\LibSharedMedia-3.0.xml"/>
|
||||
<Include file="LibSimpleSticky\LibSimpleSticky.xml"/>
|
||||
<Include file="LibDataBroker\LibDataBroker-1.1.xml"/>
|
||||
<Include file="LibElvUIPlugin-1.0\LibElvUIPlugin-1.0.xml"/>
|
||||
<Include file="oUF\oUF.xml"/>
|
||||
<Include file="UTF8\UTF8.xml"/>
|
||||
<Include file="LibCompress\LibCompress.xml"/>
|
||||
<Include file="LibBase64-1.0\LibBase64-1.0.xml"/>
|
||||
<Include file="LibAnim\LibAnim.xml"/>
|
||||
<Include file="LibWho-2.0\LibWho-2.0.xml"/>
|
||||
<Include file="LibUIDropDownMenu\LibUIDropDownMenu.xml"/>
|
||||
<Include file="LibItemSearch-1.2\LibItemSearch-1.2.xml"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,4 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="utf8.lua"/>
|
||||
<Script file="utf8data.lua"/>
|
||||
</Ui>
|
||||
@@ -0,0 +1,318 @@
|
||||
-- $Id: utf8.lua 179 2009-04-03 18:10:03Z pasta $
|
||||
--
|
||||
-- Provides UTF-8 aware string functions implemented in pure lua:
|
||||
-- * string.utf8len(s)
|
||||
-- * string.utf8sub(s, i, j)
|
||||
-- * string.utf8reverse(s)
|
||||
--
|
||||
-- If utf8data.lua (containing the lower<->upper case mappings) is loaded, these
|
||||
-- additional functions are available:
|
||||
-- * string.utf8upper(s)
|
||||
-- * string.utf8lower(s)
|
||||
--
|
||||
-- All functions behave as their non UTF-8 aware counterparts with the exception
|
||||
-- that UTF-8 characters are used instead of bytes for all units.
|
||||
|
||||
--[[
|
||||
Copyright (c) 2006-2007, Kyle Smith
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of the author nor the names of its contributors may be
|
||||
used to endorse or promote products derived from this software without
|
||||
specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
--]]
|
||||
|
||||
-- ABNF from RFC 3629
|
||||
--
|
||||
-- UTF8-octets = *( UTF8-char )
|
||||
-- UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
|
||||
-- UTF8-1 = %x00-7F
|
||||
-- UTF8-2 = %xC2-DF UTF8-tail
|
||||
-- UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
|
||||
-- %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
|
||||
-- UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
|
||||
-- %xF4 %x80-8F 2( UTF8-tail )
|
||||
-- UTF8-tail = %x80-BF
|
||||
--
|
||||
|
||||
local strbyte, strlen, strsub, type = string.byte, string.len, string.sub, type
|
||||
|
||||
-- returns the number of bytes used by the UTF-8 character at byte i in s
|
||||
-- also doubles as a UTF-8 character validator
|
||||
local function utf8charbytes(s, i)
|
||||
-- argument defaults
|
||||
i = i or 1
|
||||
|
||||
-- argument checking
|
||||
if type(s) ~= "string" then
|
||||
error("bad argument #1 to 'utf8charbytes' (string expected, got ".. type(s).. ")")
|
||||
end
|
||||
if type(i) ~= "number" then
|
||||
error("bad argument #2 to 'utf8charbytes' (number expected, got ".. type(i).. ")")
|
||||
end
|
||||
|
||||
local c = strbyte(s, i)
|
||||
|
||||
-- determine bytes needed for character, based on RFC 3629
|
||||
-- validate byte 1
|
||||
if c > 0 and c <= 127 then
|
||||
-- UTF8-1
|
||||
return 1
|
||||
|
||||
elseif c >= 194 and c <= 223 then
|
||||
-- UTF8-2
|
||||
local c2 = strbyte(s, i + 1)
|
||||
|
||||
if not c2 then
|
||||
error("UTF-8 string terminated early")
|
||||
end
|
||||
|
||||
-- validate byte 2
|
||||
if c2 < 128 or c2 > 191 then
|
||||
error("Invalid UTF-8 character")
|
||||
end
|
||||
|
||||
return 2
|
||||
|
||||
elseif c >= 224 and c <= 239 then
|
||||
-- UTF8-3
|
||||
local c2 = strbyte(s, i + 1)
|
||||
local c3 = strbyte(s, i + 2)
|
||||
|
||||
if not c2 or not c3 then
|
||||
error("UTF-8 string terminated early")
|
||||
end
|
||||
|
||||
-- validate byte 2
|
||||
if c == 224 and (c2 < 160 or c2 > 191) then
|
||||
error("Invalid UTF-8 character")
|
||||
elseif c == 237 and (c2 < 128 or c2 > 159) then
|
||||
error("Invalid UTF-8 character")
|
||||
elseif c2 < 128 or c2 > 191 then
|
||||
error("Invalid UTF-8 character")
|
||||
end
|
||||
|
||||
-- validate byte 3
|
||||
if c3 < 128 or c3 > 191 then
|
||||
error("Invalid UTF-8 character")
|
||||
end
|
||||
|
||||
return 3
|
||||
|
||||
elseif c >= 240 and c <= 244 then
|
||||
-- UTF8-4
|
||||
local c2 = strbyte(s, i + 1)
|
||||
local c3 = strbyte(s, i + 2)
|
||||
local c4 = strbyte(s, i + 3)
|
||||
|
||||
if not c2 or not c3 or not c4 then
|
||||
error("UTF-8 string terminated early")
|
||||
end
|
||||
|
||||
-- validate byte 2
|
||||
if c == 240 and (c2 < 144 or c2 > 191) then
|
||||
error("Invalid UTF-8 character")
|
||||
elseif c == 244 and (c2 < 128 or c2 > 143) then
|
||||
error("Invalid UTF-8 character")
|
||||
elseif c2 < 128 or c2 > 191 then
|
||||
error("Invalid UTF-8 character")
|
||||
end
|
||||
|
||||
-- validate byte 3
|
||||
if c3 < 128 or c3 > 191 then
|
||||
error("Invalid UTF-8 character")
|
||||
end
|
||||
|
||||
-- validate byte 4
|
||||
if c4 < 128 or c4 > 191 then
|
||||
error("Invalid UTF-8 character")
|
||||
end
|
||||
|
||||
return 4
|
||||
|
||||
else
|
||||
error("Invalid UTF-8 character")
|
||||
end
|
||||
end
|
||||
|
||||
-- returns the number of characters in a UTF-8 string
|
||||
local function utf8len(s)
|
||||
-- argument checking
|
||||
if type(s) ~= "string" then
|
||||
error("bad argument #1 to 'utf8len' (string expected, got ".. type(s).. ")")
|
||||
end
|
||||
|
||||
local pos = 1
|
||||
local bytes = strlen(s)
|
||||
local len = 0
|
||||
|
||||
while pos <= bytes do
|
||||
len = len + 1
|
||||
pos = pos + utf8charbytes(s, pos)
|
||||
end
|
||||
|
||||
return len
|
||||
end
|
||||
|
||||
-- install in the string library
|
||||
if not string.utf8len then
|
||||
string.utf8len = utf8len
|
||||
end
|
||||
|
||||
-- functions identically to string.sub except that i and j are UTF-8 characters
|
||||
-- instead of bytes
|
||||
local function utf8sub(s, i, j)
|
||||
-- argument defaults
|
||||
j = j or -1
|
||||
|
||||
-- argument checking
|
||||
if type(s) ~= "string" then
|
||||
error("bad argument #1 to 'utf8sub' (string expected, got ".. type(s).. ")")
|
||||
end
|
||||
if type(i) ~= "number" then
|
||||
error("bad argument #2 to 'utf8sub' (number expected, got ".. type(i).. ")")
|
||||
end
|
||||
if type(j) ~= "number" then
|
||||
error("bad argument #3 to 'utf8sub' (number expected, got ".. type(j).. ")")
|
||||
end
|
||||
|
||||
local pos = 1
|
||||
local bytes = strlen(s)
|
||||
local len = 0
|
||||
|
||||
-- only set l if i or j is negative
|
||||
local l = (i >= 0 and j >= 0) or utf8len(s)
|
||||
local startChar = (i >= 0) and i or l + i + 1
|
||||
local endChar = (j >= 0) and j or l + j + 1
|
||||
|
||||
-- can't have start before end!
|
||||
if startChar > endChar then
|
||||
return ""
|
||||
end
|
||||
|
||||
-- byte offsets to pass to string.sub
|
||||
local startByte, endByte = 1, bytes
|
||||
|
||||
while pos <= bytes do
|
||||
len = len + 1
|
||||
|
||||
if len == startChar then
|
||||
startByte = pos
|
||||
end
|
||||
|
||||
pos = pos + utf8charbytes(s, pos)
|
||||
|
||||
if len == endChar then
|
||||
endByte = pos - 1
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
return strsub(s, startByte, endByte)
|
||||
end
|
||||
|
||||
-- install in the string library
|
||||
if not string.utf8sub then
|
||||
string.utf8sub = utf8sub
|
||||
end
|
||||
|
||||
-- replace UTF-8 characters based on a mapping table
|
||||
local function utf8replace(s, mapping)
|
||||
-- argument checking
|
||||
if type(s) ~= "string" then
|
||||
error("bad argument #1 to 'utf8replace' (string expected, got ".. type(s).. ")")
|
||||
end
|
||||
if type(mapping) ~= "table" then
|
||||
error("bad argument #2 to 'utf8replace' (table expected, got ".. type(mapping).. ")")
|
||||
end
|
||||
|
||||
local pos = 1
|
||||
local bytes = strlen(s)
|
||||
local charbytes
|
||||
local newstr = ""
|
||||
|
||||
while pos <= bytes do
|
||||
charbytes = utf8charbytes(s, pos)
|
||||
local c = strsub(s, pos, pos + charbytes - 1)
|
||||
|
||||
newstr = newstr .. (mapping[c] or c)
|
||||
|
||||
pos = pos + charbytes
|
||||
end
|
||||
|
||||
return newstr
|
||||
end
|
||||
|
||||
-- identical to string.upper except it knows about unicode simple case conversions
|
||||
local function utf8upper(s)
|
||||
return utf8replace(s, utf8_lc_uc)
|
||||
end
|
||||
|
||||
-- install in the string library
|
||||
if not string.utf8upper and utf8_lc_uc then
|
||||
string.utf8upper = utf8upper
|
||||
end
|
||||
|
||||
-- identical to string.lower except it knows about unicode simple case conversions
|
||||
local function utf8lower(s)
|
||||
return utf8replace(s, utf8_uc_lc)
|
||||
end
|
||||
|
||||
-- install in the string library
|
||||
if not string.utf8lower and utf8_uc_lc then
|
||||
string.utf8lower = utf8lower
|
||||
end
|
||||
|
||||
-- identical to string.reverse except that it supports UTF-8
|
||||
local function utf8reverse(s)
|
||||
-- argument checking
|
||||
if type(s) ~= "string" then
|
||||
error("bad argument #1 to 'utf8reverse' (string expected, got ".. type(s).. ")")
|
||||
end
|
||||
|
||||
local bytes = strlen(s)
|
||||
local pos = bytes
|
||||
local charbytes
|
||||
local newstr = ""
|
||||
local c
|
||||
|
||||
while pos > 0 do
|
||||
c = strbyte(s, pos)
|
||||
while c >= 128 and c <= 191 do
|
||||
pos = pos - 1
|
||||
c = strbyte(pos)
|
||||
end
|
||||
|
||||
charbytes = utf8charbytes(s, pos)
|
||||
|
||||
newstr = newstr .. strsub(s, pos, pos + charbytes - 1)
|
||||
|
||||
pos = pos - 1
|
||||
end
|
||||
|
||||
return newstr
|
||||
end
|
||||
|
||||
-- install in the string library
|
||||
if not string.utf8reverse then
|
||||
string.utf8reverse = utf8reverse
|
||||
end
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,25 @@
|
||||
Copyright (c) 2006-2017 Trond A Ekseth <troeks@gmail.com>
|
||||
Copyright (c) 2016-2017 Val Voronov <i.lightspark@gmail.com>
|
||||
Copyright (c) 2016-2017 Adrian L Lange <contact@p3lim.net>
|
||||
Copyright (c) 2016-2017 Rainrider <rainrider.wow@gmail.com>
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,72 @@
|
||||
local ns = oUF
|
||||
local oUF = ns.oUF
|
||||
|
||||
local hiddenParent = CreateFrame("Frame")
|
||||
|
||||
-- sourced from FrameXML/PartyMemberFrame.lua
|
||||
local MAX_PARTY_MEMBERS = MAX_PARTY_MEMBERS or 4
|
||||
|
||||
local hiddenParent = CreateFrame('Frame', nil, UIParent)
|
||||
hiddenParent:SetAllPoints()
|
||||
hiddenParent:Hide()
|
||||
|
||||
local function handleFrame(baseName)
|
||||
local frame
|
||||
if(type(baseName) == 'string') then
|
||||
frame = _G[baseName]
|
||||
else
|
||||
frame = baseName
|
||||
end
|
||||
|
||||
if(frame) then
|
||||
frame:UnregisterAllEvents()
|
||||
frame:Hide()
|
||||
|
||||
-- Keep frame hidden without causing taint
|
||||
frame:SetParent(hiddenParent)
|
||||
|
||||
local health = frame.healthBar or frame.healthbar
|
||||
if(health) then
|
||||
health:UnregisterAllEvents()
|
||||
end
|
||||
|
||||
local power = frame.manabar
|
||||
if(power) then
|
||||
power:UnregisterAllEvents()
|
||||
end
|
||||
|
||||
local spell = frame.castBar or frame.spellbar
|
||||
if(spell) then
|
||||
spell:UnregisterAllEvents()
|
||||
end
|
||||
|
||||
local buffFrame = frame.BuffFrame
|
||||
if(buffFrame) then
|
||||
buffFrame:UnregisterAllEvents()
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function oUF:DisableBlizzard(unit)
|
||||
if(not unit) then return end
|
||||
|
||||
if(unit == 'player') then
|
||||
handleFrame(PlayerFrame)
|
||||
elseif(unit == 'pet') then
|
||||
handleFrame(PetFrame)
|
||||
elseif(unit == 'target') then
|
||||
handleFrame(TargetFrame)
|
||||
handleFrame(ComboFrame)
|
||||
elseif(unit == 'targettarget') then
|
||||
handleFrame(TargetofTargetFrame)
|
||||
elseif(unit:match('party%d?$')) then
|
||||
local id = unit:match('party(%d)')
|
||||
if(id) then
|
||||
handleFrame('PartyMemberFrame' .. id)
|
||||
else
|
||||
for i = 1, MAX_PARTY_MEMBERS do
|
||||
handleFrame(string.format('PartyMemberFrame%d', i))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,234 @@
|
||||
local ns = oUF
|
||||
local oUF = ns.oUF
|
||||
local Private = oUF.Private
|
||||
|
||||
local frame_metatable = Private.frame_metatable
|
||||
|
||||
local colors = {
|
||||
smooth = {
|
||||
1, 0, 0,
|
||||
1, 1, 0,
|
||||
0, 1, 0
|
||||
},
|
||||
health = {49 / 255, 207 / 255, 37 / 255},
|
||||
disconnected = {.6, .6, .6},
|
||||
tapped = {.6, .6, .6},
|
||||
class = {},
|
||||
reaction = {},
|
||||
power = {},
|
||||
}
|
||||
|
||||
-- We do this because people edit the vars directly, and changing the default
|
||||
-- globals makes SPICE FLOW!
|
||||
local function customClassColors()
|
||||
if(CUSTOM_CLASS_COLORS) then
|
||||
local function updateColors()
|
||||
for classToken, color in next, CUSTOM_CLASS_COLORS do
|
||||
colors.class[classToken] = {color.r, color.g, color.b}
|
||||
end
|
||||
|
||||
for _, obj in next, oUF.objects do
|
||||
obj:UpdateAllElements('CUSTOM_CLASS_COLORS')
|
||||
end
|
||||
end
|
||||
|
||||
updateColors()
|
||||
CUSTOM_CLASS_COLORS:RegisterCallback(updateColors)
|
||||
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
if(not customClassColors()) then
|
||||
for classToken, color in next, RAID_CLASS_COLORS do
|
||||
colors.class[classToken] = {color.r, color.g, color.b}
|
||||
end
|
||||
|
||||
local eventHandler = CreateFrame('Frame')
|
||||
eventHandler:RegisterEvent('ADDON_LOADED')
|
||||
eventHandler:SetScript('OnEvent', function(self)
|
||||
if(customClassColors()) then
|
||||
self:UnregisterEvent('ADDON_LOADED')
|
||||
self:SetScript('OnEvent', nil)
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
for eclass, color in next, FACTION_BAR_COLORS do
|
||||
colors.reaction[eclass] = {color.r, color.g, color.b}
|
||||
end
|
||||
|
||||
colors.power = {}
|
||||
colors.power[0] = {0.00, 0.00, 1.00}
|
||||
colors.power[1] = {1.00, 0.00, 0.00}
|
||||
colors.power[2] = {1.00, 0.50, 0.25}
|
||||
colors.power[3] = {1.00, 1.00, 0.00}
|
||||
colors.power[4] = {0.00, 1.00, 1.00}
|
||||
|
||||
local function colorsAndPercent(a, b, ...)
|
||||
if(a <= 0 or b == 0) then
|
||||
return nil, unpack(arg)
|
||||
elseif(a >= b) then
|
||||
return nil, select(select('#', unpack(arg)) - 2, unpack(arg))
|
||||
end
|
||||
|
||||
local num = select('#', unpack(arg)) / 3
|
||||
local segment, relperc = math.modf((a / b) * (num - 1))
|
||||
return relperc, select((segment * 3) + 1, unpack(arg))
|
||||
end
|
||||
|
||||
-- http://www.wowwiki.com/ColorGradient
|
||||
--[[ Colors: oUF:RGBColorGradient(a, b, ...)
|
||||
Used to convert a percent value (the quotient of `a` and `b`) into a gradient from 2 or more RGB colors. If more than 2
|
||||
colors are passed, the gradient will be between the two colors which perc lies in an evenly divided range. A RGB color
|
||||
is a sequence of 3 consecutive RGB percent values (in the range [0-1]). If `a` is negative or `b` is zero then the first
|
||||
RGB color (the first 3 RGB values passed to the function) is returned. If `a` is bigger than or equal to `b`, then the
|
||||
last 3 RGB values are returned.
|
||||
|
||||
* self - the global oUF object
|
||||
* a - value used as numerator to calculate the percentage (number)
|
||||
* b - value used as denominator to calculate the percentage (number)
|
||||
* ... - a list of RGB percent values. At least 6 values should be passed (number [0-1])
|
||||
--]]
|
||||
local function RGBColorGradient(...)
|
||||
local relperc, r1, g1, b1, r2, g2, b2 = colorsAndPercent(unpack(arg))
|
||||
if(relperc) then
|
||||
return r1 + (r2 - r1) * relperc, g1 + (g2 - g1) * relperc, b1 + (b2 - b1) * relperc
|
||||
else
|
||||
return r1, g1, b1
|
||||
end
|
||||
end
|
||||
|
||||
-- HCY functions are based on http://www.chilliant.com/rgb2hsv.html
|
||||
local function getY(r, g, b)
|
||||
return 0.299 * r + 0.587 * g + 0.114 * b
|
||||
end
|
||||
|
||||
--[[ Colors: oUF:RGBToHCY(r, g, b)
|
||||
Used to convert a color from RGB to HCY color space.
|
||||
|
||||
* self - the global oUF object
|
||||
* r - red color component (number [0-1])
|
||||
* g - green color component (number [0-1])
|
||||
* b - blue color component (number [0-1])
|
||||
--]]
|
||||
function oUF:RGBToHCY(r, g, b)
|
||||
local min, max = min(r, g, b), max(r, g, b)
|
||||
local chroma = max - min
|
||||
local hue
|
||||
if(chroma > 0) then
|
||||
if(r == max) then
|
||||
hue = math.mod((g - b) / chroma, 6)
|
||||
elseif(g == max) then
|
||||
hue = (b - r) / chroma + 2
|
||||
elseif(b == max) then
|
||||
hue = (r - g) / chroma + 4
|
||||
end
|
||||
hue = hue / 6
|
||||
end
|
||||
return hue, chroma, getY(r, g, b)
|
||||
end
|
||||
|
||||
local math_abs = math.abs
|
||||
--[[ Colors: oUF:HCYtoRGB(hue, chroma, luma)
|
||||
Used to convert a color from HCY to RGB color space.
|
||||
|
||||
* self - the global oUF object
|
||||
* hue - hue color component (number [0-1])
|
||||
* chroma - chroma color component (number [0-1])
|
||||
* luma - luminance color component (number [0-1])
|
||||
--]]
|
||||
function oUF:HCYtoRGB(hue, chroma, luma)
|
||||
local r, g, b = 0, 0, 0
|
||||
if(hue and luma > 0) then
|
||||
local h2 = hue * 6
|
||||
local x = chroma * (1 - math_abs(math.mod(h2, 2 - 1)))
|
||||
if(h2 < 1) then
|
||||
r, g, b = chroma, x, 0
|
||||
elseif(h2 < 2) then
|
||||
r, g, b = x, chroma, 0
|
||||
elseif(h2 < 3) then
|
||||
r, g, b = 0, chroma, x
|
||||
elseif(h2 < 4) then
|
||||
r, g, b = 0, x, chroma
|
||||
elseif(h2 < 5) then
|
||||
r, g, b = x, 0, chroma
|
||||
else
|
||||
r, g, b = chroma, 0, x
|
||||
end
|
||||
|
||||
local y = getY(r, g, b)
|
||||
if(luma < y) then
|
||||
chroma = chroma * (luma / y)
|
||||
elseif(y < 1) then
|
||||
chroma = chroma * (1 - luma) / (1 - y)
|
||||
end
|
||||
|
||||
r = (r - y) * chroma + luma
|
||||
g = (g - y) * chroma + luma
|
||||
b = (b - y) * chroma + luma
|
||||
end
|
||||
return r, g, b
|
||||
end
|
||||
|
||||
--[[ Colors: oUF:HCYColorGradient(a, b, ...)
|
||||
Used to convert a percent value (the quotient of `a` and `b`) into a gradient from 2 or more HCY colors. If more than 2
|
||||
colors are passed, the gradient will be between the two colors which perc lies in an evenly divided range. A HCY color
|
||||
is a sequence of 3 consecutive values in the range [0-1]. If `a` is negative or `b` is zero then the first
|
||||
HCY color (the first 3 HCY values passed to the function) is returned. If `a` is bigger than or equal to `b`, then the
|
||||
last 3 HCY values are returned.
|
||||
|
||||
* self - the global oUF object
|
||||
* a - value used as numerator to calculate the percentage (number)
|
||||
* b - value used as denominator to calculate the percentage (number)
|
||||
* ... - a list of HCY color values. At least 6 values should be passed (number [0-1])
|
||||
--]]
|
||||
local function HCYColorGradient(...)
|
||||
local relperc, r1, g1, b1, r2, g2, b2 = colorsAndPercent(unpack(arg))
|
||||
if(not relperc) then
|
||||
return r1, g1, b1
|
||||
end
|
||||
|
||||
local h1, c1, y1 = self:RGBToHCY(r1, g1, b1)
|
||||
local h2, c2, y2 = self:RGBToHCY(r2, g2, b2)
|
||||
local c = c1 + (c2 - c1) * relperc
|
||||
local y = y1 + (y2 - y1) * relperc
|
||||
|
||||
if(h1 and h2) then
|
||||
local dh = h2 - h1
|
||||
if(dh < -0.5) then
|
||||
dh = dh + 1
|
||||
elseif(dh > 0.5) then
|
||||
dh = dh - 1
|
||||
end
|
||||
|
||||
return self:HCYtoRGB(math.mod(h1 + dh * relperc, 1), c, y)
|
||||
else
|
||||
return self:HCYtoRGB(h1 or h2, c, y)
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
--[[ Colors: oUF:ColorGradient(a, b, ...) or frame:ColorGradient(a, b, ...)
|
||||
Used as a proxy to call the proper gradient function depending on the user's preference. If `oUF.useHCYColorGradient` is
|
||||
set to true, `:HCYColorGradient` will be called, else `:RGBColorGradient`.
|
||||
|
||||
* self - the global oUF object or a unit frame
|
||||
* a - value used as numerator to calculate the percentage (number)
|
||||
* b - value used as denominator to calculate the percentage (number)
|
||||
* ... - a list of color values. At least 6 values should be passed (number [0-1])
|
||||
--]]
|
||||
local function ColorGradient(...)
|
||||
return (oUF.useHCYColorGradient and HCYColorGradient or RGBColorGradient)(unpack(arg))
|
||||
end
|
||||
|
||||
Private.colors = colors
|
||||
|
||||
oUF.colors = colors
|
||||
oUF.ColorGradient = ColorGradient
|
||||
oUF.RGBColorGradient = RGBColorGradient
|
||||
oUF.HCYColorGradient = HCYColorGradient
|
||||
oUF.useHCYColorGradient = false
|
||||
|
||||
frame_metatable.__index.colors = colors
|
||||
frame_metatable.__index.ColorGradient = ColorGradient
|
||||
@@ -0,0 +1,103 @@
|
||||
--[[
|
||||
# Element: Assistant Indicator
|
||||
|
||||
Toggles the visibility of an indicator based on the unit's raid assistant status.
|
||||
|
||||
## Widget
|
||||
|
||||
AssistantIndicator - Any UI widget.
|
||||
|
||||
## Notes
|
||||
|
||||
A default texture will be applied if the widget is a Texture and doesn't have a texture or a color set.
|
||||
|
||||
## Examples
|
||||
|
||||
-- Position and size
|
||||
local AssistantIndicator = self:CreateTexture(nil, 'OVERLAY')
|
||||
AssistantIndicator:SetSize(16, 16)
|
||||
AssistantIndicator:SetPoint('TOP', self)
|
||||
|
||||
-- Register it with oUF
|
||||
self.AssistantIndicator = AssistantIndicator
|
||||
--]]
|
||||
|
||||
local ns = oUF
|
||||
local oUF = ns.oUF
|
||||
|
||||
local UnitInRaid = UnitInRaid
|
||||
local UnitIsPartyLeader = UnitIsPartyLeader
|
||||
local UnitIsRaidOfficer = UnitIsRaidOfficer
|
||||
|
||||
local function Update(self, event)
|
||||
local element = self.AssistantIndicator
|
||||
|
||||
--[[ Callback: AssistantIndicator:PreUpdate()
|
||||
Called before the element has been updated.
|
||||
|
||||
* self - the AssistantIndicator element
|
||||
--]]
|
||||
if(element.PreUpdate) then
|
||||
element:PreUpdate()
|
||||
end
|
||||
|
||||
local unit = self.unit
|
||||
local isAssistant = UnitInRaid(unit) and not UnitIsPartyLeader(unit)
|
||||
if(isAssistant) then
|
||||
element:Show()
|
||||
else
|
||||
element:Hide()
|
||||
end
|
||||
|
||||
--[[ Callback: AssistantIndicator:PostUpdate(isAssistant)
|
||||
Called after the element has been updated.
|
||||
|
||||
* self - the AssistantIndicator element
|
||||
* isAssistant - indicates whether the unit is a raid assistant (boolean)
|
||||
--]]
|
||||
if(element.PostUpdate) then
|
||||
return element:PostUpdate(isAssistant)
|
||||
end
|
||||
end
|
||||
|
||||
local function Path(self, ...)
|
||||
--[[ Override: AssistantIndicator.Override(self, event, ...)
|
||||
Used to completely override the element's update process.
|
||||
|
||||
* self - the parent object
|
||||
* event - the event triggering the update (string)
|
||||
* ... - the arguments accompanying the event (string)
|
||||
--]]
|
||||
return (self.AssistantIndicator.Override or Update) (self, unpack(arg))
|
||||
end
|
||||
|
||||
local function ForceUpdate(element)
|
||||
return Path(element.__owner, 'ForceUpdate')
|
||||
end
|
||||
|
||||
local function Enable(self)
|
||||
local element = self.AssistantIndicator
|
||||
if(element) then
|
||||
element.__owner = self
|
||||
element.ForceUpdate = ForceUpdate
|
||||
|
||||
self:RegisterEvent('PARTY_MEMBERS_CHANGED', Path)
|
||||
|
||||
if(element:IsObjectType('Texture') and not element:GetTexture()) then
|
||||
element:SetTexture([[Interface\GroupFrame\UI-Group-AssistantIcon]])
|
||||
end
|
||||
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
local function Disable(self)
|
||||
local element = self.AssistantIndicator
|
||||
if(element) then
|
||||
element:Hide()
|
||||
|
||||
self:UnregisterEvent('PARTY_MEMBERS_CHANGED', Path)
|
||||
end
|
||||
end
|
||||
|
||||
oUF:AddElement('AssistantIndicator', Path, Enable, Disable)
|
||||
@@ -0,0 +1,516 @@
|
||||
--[[
|
||||
# Element: Auras
|
||||
|
||||
Handles creation and updating of aura icons.
|
||||
|
||||
## Widget
|
||||
|
||||
Auras - A Frame to hold `Button`s representing both buffs and debuffs.
|
||||
Buffs - A Frame to hold `Button`s representing buffs.
|
||||
Debuffs - A Frame to hold `Button`s representing debuffs.
|
||||
|
||||
## Notes
|
||||
|
||||
At least one of the above widgets must be present for the element to work.
|
||||
|
||||
## Options
|
||||
|
||||
.disableMouse - Disables mouse events (boolean)
|
||||
.disableCooldown - Disables the cooldown spiral (boolean)
|
||||
.size - Aura icon size. Defaults to 16 (number)
|
||||
.spacing - Spacing between each icon. Defaults to 0 (number)
|
||||
.['spacing-x'] - Horizontal spacing between each icon. Takes priority over `spacing` (number)
|
||||
.['spacing-y'] - Vertical spacing between each icon. Takes priority over `spacing` (number)
|
||||
.['growth-x'] - Horizontal growth direction. Defaults to 'RIGHT' (string)
|
||||
.['growth-y'] - Vertical growth direction. Defaults to 'UP' (string)
|
||||
.initialAnchor - Anchor point for the icons. Defaults to 'BOTTOMLEFT' (string)
|
||||
.filter - Custom filter list for auras to display. Defaults to 'HELPFUL' for buffs and 'HARMFUL' for
|
||||
debuffs (string)
|
||||
|
||||
## Options Auras
|
||||
|
||||
.numBuffs - The maximum number of buffs to display. Defaults to 32 (number)
|
||||
.numDebuffs - The maximum number of debuffs to display. Defaults to 40 (number)
|
||||
.numTotal - The maximum number of auras to display. Prioritizes buffs over debuffs. Defaults to the sum of
|
||||
.numBuffs and .numDebuffs (number)
|
||||
.gap - Controls the creation of an invisible icon between buffs and debuffs. Defaults to false (boolean)
|
||||
.buffFilter - Custom filter list for buffs to display. Takes priority over `filter` (string)
|
||||
.debuffFilter - Custom filter list for debuffs to display. Takes priority over `filter` (string)
|
||||
|
||||
## Options Buffs
|
||||
|
||||
.num - Number of buffs to display. Defaults to 32 (number)
|
||||
|
||||
## Options Debuffs
|
||||
|
||||
.num - Number of debuffs to display. Defaults to 40 (number)
|
||||
|
||||
## Attributes
|
||||
|
||||
button.filter - the filter list used to determine the visibility of the aura (string)
|
||||
button.isDebuff - indicates if the button holds a debuff (boolean)
|
||||
|
||||
## Examples
|
||||
|
||||
-- Position and size
|
||||
local Buffs = CreateFrame('Frame', nil, self)
|
||||
Buffs:SetPoint('RIGHT', self, 'LEFT')
|
||||
Buffs:SetSize(16 * 2, 16 * 16)
|
||||
|
||||
-- Register with oUF
|
||||
self.Buffs = Buffs
|
||||
--]]
|
||||
|
||||
local ns = oUF
|
||||
local oUF = ns.oUF
|
||||
|
||||
local tinsert = table.insert
|
||||
local floor = math.floor
|
||||
|
||||
local CreateFrame = CreateFrame
|
||||
local GetTime = GetTime
|
||||
local UnitAura = UnitAura
|
||||
|
||||
local VISIBLE = 1
|
||||
local HIDDEN = 0
|
||||
|
||||
local function UpdateTooltip(self)
|
||||
if self.filter == 'HELPFUL' then
|
||||
GameTooltip:SetUnitBuff(self:GetParent().__owner.unit, self:GetID(), self.filter)
|
||||
else
|
||||
GameTooltip:SetUnitDebuff(self:GetParent().__owner.unit, self:GetID(), self.filter)
|
||||
end
|
||||
end
|
||||
|
||||
local function onEnter(self)
|
||||
if(not self:IsVisible()) then return end
|
||||
|
||||
GameTooltip:SetOwner(self, 'ANCHOR_BOTTOMRIGHT')
|
||||
self:UpdateTooltip()
|
||||
end
|
||||
|
||||
local function onLeave()
|
||||
GameTooltip:Hide()
|
||||
end
|
||||
|
||||
local function createAuraIcon(element, index)
|
||||
local button = CreateFrame('Button', '$parentButton' .. index, element)
|
||||
button:RegisterForClicks('RightButtonUp')
|
||||
|
||||
local cd = CreateFrame('Cooldown', '$parentCooldown', button, 'oUF_CooldownFrameTemplate')
|
||||
cd:SetAllPoints()
|
||||
|
||||
local icon = button:CreateTexture(nil, 'BORDER')
|
||||
icon:SetAllPoints()
|
||||
|
||||
local count = button:CreateFontString(nil, 'OVERLAY', 'NumberFontNormal')
|
||||
count:SetPoint('BOTTOMRIGHT', button, 'BOTTOMRIGHT', -1, 0)
|
||||
|
||||
local overlay = button:CreateTexture(nil, 'OVERLAY')
|
||||
overlay:SetTexture([[Interface\Buttons\UI-Debuff-Overlays]])
|
||||
overlay:SetAllPoints()
|
||||
overlay:SetTexCoord(.296875, .5703125, 0, .515625)
|
||||
button.overlay = overlay
|
||||
|
||||
button.UpdateTooltip = UpdateTooltip
|
||||
button:SetScript('OnEnter', onEnter)
|
||||
button:SetScript('OnLeave', onLeave)
|
||||
|
||||
button.icon = icon
|
||||
button.count = count
|
||||
button.cd = cd
|
||||
|
||||
--[[ Callback: Auras:PostCreateIcon(button)
|
||||
Called after a new aura button has been created.
|
||||
|
||||
* self - the widget holding the aura buttons
|
||||
* button - the newly created aura button (Button)
|
||||
--]]
|
||||
if(element.PostCreateIcon) then element:PostCreateIcon(button) end
|
||||
|
||||
return button
|
||||
end
|
||||
|
||||
local function customFilter(element, unit, button, name)
|
||||
if(name) then
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
local function updateIcon(element, unit, index, offset, filter, isDebuff, visible)
|
||||
local name, rank, texture, count, dispelType, duration, expiration = UnitAura(unit, index, filter)
|
||||
|
||||
if element.forceShow then
|
||||
name, rank, texture = GetSpellInfo(26993)
|
||||
count, dispelType, duration, expiration = 5, 'Magic', 0, 60
|
||||
end
|
||||
|
||||
if(name) then
|
||||
local position = visible + offset + 1
|
||||
local button = element[position]
|
||||
if(not button) then
|
||||
--[[ Override: Auras:CreateIcon(position)
|
||||
Used to create the aura button at a given position.
|
||||
|
||||
* self - the widget holding the aura buttons
|
||||
* position - the position at which the aura button is to be created (number)
|
||||
|
||||
## Returns
|
||||
|
||||
* button - the button used to represent the aura (Button)
|
||||
--]]
|
||||
button = (element.CreateIcon or createAuraIcon) (element, position)
|
||||
|
||||
tinsert(element, button)
|
||||
element.createdIcons = element.createdIcons + 1
|
||||
end
|
||||
|
||||
button.filter = filter
|
||||
button.isDebuff = isDebuff
|
||||
|
||||
--[[ Override: Auras:CustomFilter(unit, button, ...)
|
||||
Defines a custom filter that controls if the aura button should be shown.
|
||||
|
||||
* self - the widget holding the aura buttons
|
||||
* unit - the unit on which the aura is cast (string)
|
||||
* button - the button displaying the aura (Button)
|
||||
* ... - the return values from [UnitAura](http://wowprogramming.com/docs/api/UnitAura)
|
||||
|
||||
## Returns
|
||||
|
||||
* show - indicates whether the aura button should be shown (boolean)
|
||||
--]]
|
||||
local show = true
|
||||
if not element.forceShow then
|
||||
show = (element.CustomFilter or customFilter) (element, unit, button, name, rank, texture, count, dispelType, duration, expiration)
|
||||
end
|
||||
|
||||
if(show) then
|
||||
-- We might want to consider delaying the creation of an actual cooldown
|
||||
-- object to this point, but I think that will just make things needlessly
|
||||
-- complicated.
|
||||
if(button.cd and not element.disableCooldown) then
|
||||
if(duration and duration > 0) then
|
||||
button.cd:SetCooldown(GetTime() - (duration - expiration), duration)
|
||||
button.cd:Show()
|
||||
else
|
||||
button.cd:Hide()
|
||||
end
|
||||
end
|
||||
|
||||
if(button.overlay) then
|
||||
if((isDebuff and element.showDebuffType) or (not isDebuff and element.showBuffType) or element.showType) then
|
||||
local color = DebuffTypeColor[dispelType] or DebuffTypeColor.none
|
||||
|
||||
button.overlay:SetVertexColor(color.r, color.g, color.b)
|
||||
button.overlay:Show()
|
||||
else
|
||||
button.overlay:Hide()
|
||||
end
|
||||
end
|
||||
|
||||
if(button.icon) then button.icon:SetTexture(texture) end
|
||||
if(button.count) then button.count:SetText(count > 1 and count) end
|
||||
|
||||
local size = element.size or 16
|
||||
button:SetSize(size, size)
|
||||
|
||||
button:EnableMouse(not element.disableMouse)
|
||||
button:SetID(index)
|
||||
button:Show()
|
||||
|
||||
--[[ Callback: Auras:PostUpdateIcon(unit, button, index, position)
|
||||
Called after the aura button has been updated.
|
||||
|
||||
* self - the widget holding the aura buttons
|
||||
* unit - the unit on which the aura is cast (string)
|
||||
* button - the updated aura button (Button)
|
||||
* index - the index of the aura (number)
|
||||
* position - the actual position of the aura button (number)
|
||||
--]]
|
||||
if(element.PostUpdateIcon) then
|
||||
element:PostUpdateIcon(unit, button, index, position)
|
||||
end
|
||||
|
||||
return VISIBLE
|
||||
else
|
||||
return HIDDEN
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function SetPosition(element, from, to)
|
||||
local sizex = (element.size or 16) + (element['spacing-x'] or element.spacing or 0)
|
||||
local sizey = (element.size or 16) + (element['spacing-y'] or element.spacing or 0)
|
||||
local anchor = element.initialAnchor or 'BOTTOMLEFT'
|
||||
local growthx = (element['growth-x'] == 'LEFT' and -1) or 1
|
||||
local growthy = (element['growth-y'] == 'DOWN' and -1) or 1
|
||||
local cols = floor(element:GetWidth() / sizex + 0.5)
|
||||
|
||||
for i = from, to do
|
||||
local button = element[i]
|
||||
|
||||
-- Bail out if the to range is out of scope.
|
||||
if(not button) then break end
|
||||
local col = (i - 1) % cols
|
||||
local row = floor((i - 1) / cols)
|
||||
|
||||
button:ClearAllPoints()
|
||||
button:SetPoint(anchor, element, anchor, col * sizex * growthx, row * sizey * growthy)
|
||||
end
|
||||
end
|
||||
|
||||
local function filterIcons(element, unit, filter, limit, isDebuff, offset, dontHide)
|
||||
if(not offset) then offset = 0 end
|
||||
local index = 1
|
||||
local visible = 0
|
||||
local hidden = 0
|
||||
while(visible < limit) do
|
||||
local result = updateIcon(element, unit, index, offset, filter, isDebuff, visible)
|
||||
if(not result) then
|
||||
break
|
||||
elseif(result == VISIBLE) then
|
||||
visible = visible + 1
|
||||
elseif(result == HIDDEN) then
|
||||
hidden = hidden + 1
|
||||
end
|
||||
|
||||
index = index + 1
|
||||
end
|
||||
|
||||
if(not dontHide) then
|
||||
for i = visible + offset + 1, #element do
|
||||
element[i]:Hide()
|
||||
end
|
||||
end
|
||||
|
||||
return visible, hidden
|
||||
end
|
||||
|
||||
local function UpdateAuras(self, event, unit)
|
||||
if(self.unit ~= unit) then return end
|
||||
|
||||
local auras = self.Auras
|
||||
if(auras) then
|
||||
--[[ Callback: Auras:PreUpdate(unit)
|
||||
Called before the element has been updated.
|
||||
|
||||
* self - the widget holding the aura buttons
|
||||
* unit - the unit for which the update has been triggered (string)
|
||||
--]]
|
||||
if(auras.PreUpdate) then auras:PreUpdate(unit) end
|
||||
|
||||
local numBuffs = auras.numBuffs or 32
|
||||
local numDebuffs = auras.numDebuffs or 40
|
||||
local max = auras.numTotal or numBuffs + numDebuffs
|
||||
|
||||
local visibleBuffs, hiddenBuffs = filterIcons(auras, unit, auras.buffFilter or auras.filter or 'HELPFUL', math.min(numBuffs, max), nil, 0, true)
|
||||
|
||||
local hasGap
|
||||
if(visibleBuffs ~= 0 and auras.gap) then
|
||||
hasGap = true
|
||||
visibleBuffs = visibleBuffs + 1
|
||||
|
||||
local button = auras[visibleBuffs]
|
||||
if(not button) then
|
||||
button = (auras.CreateIcon or createAuraIcon) (auras, visibleBuffs)
|
||||
tinsert(auras, button)
|
||||
auras.createdIcons = auras.createdIcons + 1
|
||||
end
|
||||
|
||||
-- Prevent the button from displaying anything.
|
||||
if(button.cd) then button.cd:Hide() end
|
||||
if(button.icon) then button.icon:SetTexture() end
|
||||
if(button.overlay) then button.overlay:Hide() end
|
||||
if(button.stealable) then button.stealable:Hide() end
|
||||
if(button.count) then button.count:SetText() end
|
||||
|
||||
button:EnableMouse(false)
|
||||
button:Show()
|
||||
|
||||
--[[ Callback: Auras:PostUpdateGapIcon(unit, gapButton, visibleBuffs)
|
||||
Called after an invisible aura button has been created. Only used by Auras when the `gap` option is enabled.
|
||||
|
||||
* self - the widget holding the aura buttons
|
||||
* unit - the unit that has the invisible aura button (string)
|
||||
* gapButton - the invisible aura button (Button)
|
||||
* visibleBuffs - the number of currently visible aura buttons (number)
|
||||
--]]
|
||||
if(auras.PostUpdateGapIcon) then
|
||||
auras:PostUpdateGapIcon(unit, button, visibleBuffs)
|
||||
end
|
||||
end
|
||||
|
||||
local visibleDebuffs, hiddenDebuffs = filterIcons(auras, unit, auras.debuffFilter or auras.filter or 'HARMFUL', math.min(numDebuffs, max - visibleBuffs), true, visibleBuffs)
|
||||
auras.visibleDebuffs = visibleDebuffs
|
||||
|
||||
if(hasGap and visibleDebuffs == 0) then
|
||||
auras[visibleBuffs]:Hide()
|
||||
visibleBuffs = visibleBuffs - 1
|
||||
end
|
||||
|
||||
auras.visibleBuffs = visibleBuffs
|
||||
auras.visibleAuras = auras.visibleBuffs + auras.visibleDebuffs
|
||||
|
||||
local fromRange, toRange
|
||||
--[[ Callback: Auras:PreSetPosition(max)
|
||||
Called before the aura buttons have been (re-)anchored.
|
||||
|
||||
* self - the widget holding the aura buttons
|
||||
* max - the maximum possible number of aura buttons (number)
|
||||
|
||||
## Returns
|
||||
|
||||
* from - the offset of the first aura button to be (re-)anchored (number)
|
||||
* to - the offset of the last aura button to be (re-)anchored (number)
|
||||
--]]
|
||||
if(auras.PreSetPosition) then
|
||||
fromRange, toRange = auras:PreSetPosition(max)
|
||||
end
|
||||
|
||||
if(fromRange or auras.createdIcons > auras.anchoredIcons) then
|
||||
--[[ Override: Auras:SetPosition(from, to)
|
||||
Used to (re-)anchor the aura buttons.
|
||||
Called when new aura buttons have been created or if :PreSetPosition is defined.
|
||||
|
||||
* self - the widget that holds the aura buttons
|
||||
* from - the offset of the first aura button to be (re-)anchored (number)
|
||||
* to - the offset of the last aura button to be (re-)anchored (number)
|
||||
--]]
|
||||
(auras.SetPosition or SetPosition) (auras, fromRange or auras.anchoredIcons + 1, toRange or auras.createdIcons)
|
||||
auras.anchoredIcons = auras.createdIcons
|
||||
end
|
||||
|
||||
--[[ Callback: Auras:PostUpdate(unit)
|
||||
Called after the element has been updated.
|
||||
|
||||
* self - the widget holding the aura buttons
|
||||
* unit - the unit for which the update has been triggered (string)
|
||||
--]]
|
||||
if(auras.PostUpdate) then auras:PostUpdate(unit) end
|
||||
end
|
||||
|
||||
local buffs = self.Buffs
|
||||
if(buffs) then
|
||||
if(buffs.PreUpdate) then buffs:PreUpdate(unit) end
|
||||
|
||||
local numBuffs = buffs.num or 32
|
||||
local visibleBuffs, hiddenBuffs = filterIcons(buffs, unit, buffs.filter or 'HELPFUL', numBuffs)
|
||||
buffs.visibleBuffs = visibleBuffs
|
||||
|
||||
local fromRange, toRange
|
||||
if(buffs.PreSetPosition) then
|
||||
fromRange, toRange = buffs:PreSetPosition(numBuffs)
|
||||
end
|
||||
|
||||
if(fromRange or buffs.createdIcons > buffs.anchoredIcons) then
|
||||
(buffs.SetPosition or SetPosition) (buffs, fromRange or buffs.anchoredIcons + 1, toRange or buffs.createdIcons)
|
||||
buffs.anchoredIcons = buffs.createdIcons
|
||||
end
|
||||
|
||||
if(buffs.PostUpdate) then buffs:PostUpdate(unit) end
|
||||
end
|
||||
|
||||
local debuffs = self.Debuffs
|
||||
if(debuffs) then
|
||||
if(debuffs.PreUpdate) then debuffs:PreUpdate(unit) end
|
||||
|
||||
local numDebuffs = debuffs.num or 40
|
||||
local visibleDebuffs, hiddenDebuffs = filterIcons(debuffs, unit, debuffs.filter or 'HARMFUL', numDebuffs, true)
|
||||
debuffs.visibleDebuffs = visibleDebuffs
|
||||
|
||||
local fromRange, toRange
|
||||
if(debuffs.PreSetPosition) then
|
||||
fromRange, toRange = debuffs:PreSetPosition(numDebuffs)
|
||||
end
|
||||
|
||||
if(fromRange or debuffs.createdIcons > debuffs.anchoredIcons) then
|
||||
(debuffs.SetPosition or SetPosition) (debuffs, fromRange or debuffs.anchoredIcons + 1, toRange or debuffs.createdIcons)
|
||||
debuffs.anchoredIcons = debuffs.createdIcons
|
||||
end
|
||||
|
||||
if(debuffs.PostUpdate) then debuffs:PostUpdate(unit) end
|
||||
end
|
||||
end
|
||||
|
||||
local function Update(self, event, unit)
|
||||
if(self.unit ~= unit) then return end
|
||||
|
||||
UpdateAuras(self, event, unit)
|
||||
|
||||
-- Assume no event means someone wants to re-anchor things. This is usually
|
||||
-- done by UpdateAllElements and :ForceUpdate.
|
||||
if(event == 'ForceUpdate' or not event) then
|
||||
local buffs = self.Buffs
|
||||
if(buffs) then
|
||||
(buffs.SetPosition or SetPosition) (buffs, 1, buffs.createdIcons)
|
||||
end
|
||||
|
||||
local debuffs = self.Debuffs
|
||||
if(debuffs) then
|
||||
(debuffs.SetPosition or SetPosition) (debuffs, 1, debuffs.createdIcons)
|
||||
end
|
||||
|
||||
local auras = self.Auras
|
||||
if(auras) then
|
||||
(auras.SetPosition or SetPosition) (auras, 1, auras.createdIcons)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function ForceUpdate(element)
|
||||
return Update(element.__owner, 'ForceUpdate', element.__owner.unit)
|
||||
end
|
||||
|
||||
local function Enable(self)
|
||||
if(self.Buffs or self.Debuffs or self.Auras) then
|
||||
self:RegisterEvent('UNIT_AURA', UpdateAuras)
|
||||
|
||||
local buffs = self.Buffs
|
||||
if(buffs) then
|
||||
buffs.__owner = self
|
||||
buffs.ForceUpdate = ForceUpdate
|
||||
|
||||
buffs.createdIcons = buffs.createdIcons or 0
|
||||
buffs.anchoredIcons = 0
|
||||
|
||||
--buffs:Show()
|
||||
end
|
||||
|
||||
local debuffs = self.Debuffs
|
||||
if(debuffs) then
|
||||
debuffs.__owner = self
|
||||
debuffs.ForceUpdate = ForceUpdate
|
||||
|
||||
debuffs.createdIcons = debuffs.createdIcons or 0
|
||||
debuffs.anchoredIcons = 0
|
||||
|
||||
--debuffs:Show()
|
||||
end
|
||||
|
||||
local auras = self.Auras
|
||||
if(auras) then
|
||||
auras.__owner = self
|
||||
auras.ForceUpdate = ForceUpdate
|
||||
|
||||
auras.createdIcons = auras.createdIcons or 0
|
||||
auras.anchoredIcons = 0
|
||||
|
||||
--auras:Show()
|
||||
end
|
||||
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
local function Disable(self)
|
||||
if(self.Buffs or self.Debuffs or self.Auras) then
|
||||
self:UnregisterEvent('UNIT_AURA', UpdateAuras)
|
||||
|
||||
if(self.Buffs) then self.Buffs:Hide() end
|
||||
if(self.Debuffs) then self.Debuffs:Hide() end
|
||||
if(self.Auras) then self.Auras:Hide() end
|
||||
end
|
||||
end
|
||||
|
||||
oUF:AddElement('Auras', Update, Enable, Disable)
|
||||
@@ -0,0 +1,585 @@
|
||||
--[[
|
||||
# Element: Castbar
|
||||
|
||||
Handles the visibility and updating of spell castbars.
|
||||
Based upon oUF_Castbar by starlon.
|
||||
|
||||
## Widget
|
||||
|
||||
Castbar - A `StatusBar` to represent spell cast/channel progress.
|
||||
|
||||
## Sub-Widgets
|
||||
|
||||
.Text - A `FontString` to represent spell name.
|
||||
.Icon - A `Texture` to represent spell icon.
|
||||
.Time - A `FontString` to represent spell duration.
|
||||
.SafeZone - A `Texture` to represent latency.
|
||||
|
||||
## Notes
|
||||
|
||||
A default texture will be applied to the StatusBar and Texture widgets if they don't have a texture or a color set.
|
||||
|
||||
## Options
|
||||
|
||||
.timeToHold - indicates for how many seconds the castbar should be visible after a _FAILED or _INTERRUPTED
|
||||
event. Defaults to 0 (number)
|
||||
|
||||
## Examples
|
||||
|
||||
-- Position and size
|
||||
local Castbar = CreateFrame('StatusBar', nil, self)
|
||||
Castbar:SetSize(20, 20)
|
||||
Castbar:SetPoint('TOP')
|
||||
Castbar:SetPoint('LEFT')
|
||||
Castbar:SetPoint('RIGHT')
|
||||
|
||||
-- Add a background
|
||||
local Background = Castbar:CreateTexture(nil, 'BACKGROUND')
|
||||
Background:SetAllPoints(Castbar)
|
||||
Background:SetTexture(1, 1, 1, .5)
|
||||
|
||||
-- Add a spark
|
||||
local Spark = Castbar:CreateTexture(nil, 'OVERLAY')
|
||||
Spark:SetSize(20, 20)
|
||||
Spark:SetBlendMode('ADD')
|
||||
|
||||
-- Add a timer
|
||||
local Time = Castbar:CreateFontString(nil, 'OVERLAY', 'GameFontNormalSmall')
|
||||
Time:SetPoint('RIGHT', Castbar)
|
||||
|
||||
-- Add spell text
|
||||
local Text = Castbar:CreateFontString(nil, 'OVERLAY', 'GameFontNormalSmall')
|
||||
Text:SetPoint('LEFT', Castbar)
|
||||
|
||||
-- Add spell icon
|
||||
local Icon = Castbar:CreateTexture(nil, 'OVERLAY')
|
||||
Icon:SetSize(20, 20)
|
||||
Icon:SetPoint('TOPLEFT', Castbar, 'TOPLEFT')
|
||||
|
||||
-- Add safezone
|
||||
local SafeZone = Castbar:CreateTexture(nil, 'OVERLAY')
|
||||
|
||||
-- Register it with oUF
|
||||
Castbar.bg = Background
|
||||
Castbar.Spark = Spark
|
||||
Castbar.Time = Time
|
||||
Castbar.Text = Text
|
||||
Castbar.Icon = Icon
|
||||
Castbar.SafeZone = SafeZone
|
||||
self.Castbar = Castbar
|
||||
--]]
|
||||
local ns = oUF
|
||||
local oUF = ns.oUF
|
||||
|
||||
local GetNetStats = GetNetStats
|
||||
local GetTime = GetTime
|
||||
local UnitCastingInfo = UnitCastingInfo
|
||||
local UnitChannelInfo = UnitChannelInfo
|
||||
local UnitIsUnit = UnitIsUnit
|
||||
|
||||
local tradeskillCastTime, tradeskillCastDuration, tradeskillCurrent, tradeskillTotal, mergeTradeskill = 0, 0, 0, 0, false
|
||||
|
||||
local function updateSafeZone(self)
|
||||
local safeZone = self.SafeZone
|
||||
local width = self:GetWidth()
|
||||
local _, _, ms = GetNetStats()
|
||||
|
||||
-- Guard against GetNetStats returning latencies of 0.
|
||||
if(ms ~= 0) then
|
||||
local safeZoneRatio = (ms / 1e3) / self.max
|
||||
if(safeZoneRatio > 1) then
|
||||
safeZoneRatio = 1
|
||||
end
|
||||
safeZone:SetWidth(width * safeZoneRatio)
|
||||
safeZone:Show()
|
||||
else
|
||||
safeZone:Hide()
|
||||
end
|
||||
end
|
||||
|
||||
local function UNIT_SPELLCAST_SENT(self, event, unit, spell, rank, target)
|
||||
local element = self.Castbar
|
||||
element.curTarget = (target and target ~= '') and target or nil
|
||||
|
||||
if element.isTradeSkill then
|
||||
element.tradeSkillCastName = spell
|
||||
end
|
||||
end
|
||||
|
||||
local function UNIT_SPELLCAST_START(self, event, unit)
|
||||
if(self.unit ~= unit and self.realUnit ~= unit) then return end
|
||||
|
||||
local element = self.Castbar
|
||||
local name, _, text, texture, startTime, endTime, isTradeSkill = UnitCastingInfo(unit)
|
||||
if(not name) then
|
||||
return element:Hide()
|
||||
end
|
||||
|
||||
endTime = endTime / 1e3
|
||||
startTime = startTime / 1e3
|
||||
local max = endTime - startTime
|
||||
|
||||
element.castName = name
|
||||
element.duration = GetTime() - startTime
|
||||
element.max = max
|
||||
element.delay = 0
|
||||
element.casting = true
|
||||
element.holdTime = 0
|
||||
element.isTradeSkill = isTradeSkill
|
||||
|
||||
if(mergeTradeskill and isTradeSkill and UnitIsUnit(unit, 'player')) then
|
||||
element.duration = element.duration + (element.max * tradeskillCurrent)
|
||||
element.max = max * tradeskillTotal
|
||||
|
||||
if(unit == 'player') then
|
||||
tradeskillCurrent = tradeskillCurrent + 1
|
||||
tradeskillCastDuration = element.duration
|
||||
tradeskillCastTime = max
|
||||
end
|
||||
|
||||
element:SetValue(element.duration)
|
||||
else
|
||||
element:SetValue(0)
|
||||
end
|
||||
element:SetMinMaxValues(0, element.max)
|
||||
|
||||
if(element.Text) then element.Text:SetText(text) end
|
||||
if(element.Icon) then element.Icon:SetTexture(texture) end
|
||||
if(element.Time) then element.Time:SetText() end
|
||||
|
||||
local sf = element.SafeZone
|
||||
if(sf) then
|
||||
sf:ClearAllPoints()
|
||||
sf:SetPoint('RIGHT')
|
||||
sf:SetPoint('TOP')
|
||||
sf:SetPoint('BOTTOM')
|
||||
updateSafeZone(element)
|
||||
end
|
||||
|
||||
--[[ Callback: Castbar:PostCastStart(unit, name)
|
||||
Called after the element has been updated upon a spell cast start.
|
||||
|
||||
* self - the Castbar widget
|
||||
* unit - unit for which the update has been triggered (string)
|
||||
* name - name of the spell being cast (string)
|
||||
--]]
|
||||
if(element.PostCastStart) then
|
||||
element:PostCastStart(unit, name)
|
||||
end
|
||||
element:Show()
|
||||
end
|
||||
|
||||
local function UNIT_SPELLCAST_FAILED(self, event, unit, spellname)
|
||||
if(not self.casting) then return end
|
||||
if(self.unit ~= unit and self.realUnit ~= unit) then return end
|
||||
|
||||
local element = self.Castbar
|
||||
if(spellname and (element.castName ~= spellname and element.tradeSkillCastName ~= spellname)) then
|
||||
return
|
||||
end
|
||||
|
||||
if(mergeTradeskill and UnitIsUnit(unit, 'player')) then
|
||||
mergeTradeskill = false
|
||||
element.tradeSkillCastName = nil
|
||||
end
|
||||
|
||||
local text = element.Text
|
||||
if(text) then
|
||||
text:SetText(FAILED)
|
||||
end
|
||||
|
||||
element.casting = nil
|
||||
element.holdTime = element.timeToHold or 0
|
||||
|
||||
--[[ Callback: Castbar:PostCastFailed(unit, name)
|
||||
Called after the element has been updated upon a failed spell cast.
|
||||
|
||||
* self - the Castbar widget
|
||||
* unit - unit for which the update has been triggered (string)
|
||||
* name - name of the failed spell (string)
|
||||
--]]
|
||||
if(element.PostCastFailed) then
|
||||
return element:PostCastFailed(unit, spellname)
|
||||
end
|
||||
end
|
||||
|
||||
local function UNIT_SPELLCAST_FAILED_QUIET(self, event, unit, spellname)
|
||||
if(not self.casting) then return end
|
||||
if(self.unit ~= unit and self.realUnit ~= unit) then return end
|
||||
|
||||
local element = self.Castbar
|
||||
if(spellname and (element.castName ~= spellname and element.tradeSkillCastName ~= spellname)) then
|
||||
return
|
||||
end
|
||||
|
||||
if(mergeTradeskill and UnitIsUnit(unit, 'player')) then
|
||||
mergeTradeskill = false
|
||||
element.tradeSkillCastName = nil
|
||||
end
|
||||
|
||||
element.casting = nil
|
||||
element:SetValue(0)
|
||||
element:Hide()
|
||||
end
|
||||
|
||||
local function UNIT_SPELLCAST_INTERRUPTED(self, event, unit, spellname)
|
||||
if(self.unit ~= unit and self.realUnit ~= unit) then return end
|
||||
|
||||
local element = self.Castbar
|
||||
if(spellname and element.castName ~= spellname) then
|
||||
return
|
||||
end
|
||||
|
||||
local text = element.Text
|
||||
if(text) then
|
||||
text:SetText(INTERRUPTED)
|
||||
end
|
||||
|
||||
element.casting = nil
|
||||
element.channeling = nil
|
||||
element.holdTime = element.timeToHold or 0
|
||||
|
||||
--[[ Callback: Castbar:PostCastInterrupted(unit, name)
|
||||
Called after the element has been updated upon an interrupted spell cast.
|
||||
|
||||
* self - the Castbar widget
|
||||
* unit - unit for which the update has been triggered (string)
|
||||
* name - name of the interrupted spell (string)
|
||||
--]]
|
||||
if(element.PostCastInterrupted) then
|
||||
return element:PostCastInterrupted(unit, spellname)
|
||||
end
|
||||
end
|
||||
|
||||
local function UNIT_SPELLCAST_DELAYED(self, event, unit)
|
||||
if(self.unit ~= unit and self.realUnit ~= unit) then return end
|
||||
|
||||
local element = self.Castbar
|
||||
local name, _, _, _, startTime = UnitCastingInfo(unit)
|
||||
if(not startTime or not element:IsShown()) then return end
|
||||
|
||||
local duration = GetTime() - (startTime / 1000)
|
||||
if(duration < 0) then duration = 0 end
|
||||
|
||||
element.delay = element.delay + element.duration - duration
|
||||
element.duration = duration
|
||||
|
||||
element:SetValue(duration)
|
||||
|
||||
--[[ Callback: Castbar:PostCastDelayed(unit, name)
|
||||
Called after the element has been updated when a spell cast has been delayed.
|
||||
|
||||
* self - the Castbar widget
|
||||
* unit - unit that the update has been triggered (string)
|
||||
* name - name of the delayed spell (string)
|
||||
--]]
|
||||
if(element.PostCastDelayed) then
|
||||
return element:PostCastDelayed(unit, name)
|
||||
end
|
||||
end
|
||||
|
||||
local function UNIT_SPELLCAST_STOP(self, event, unit, spellname)
|
||||
if(self.unit ~= unit and self.realUnit ~= unit) then return end
|
||||
|
||||
local element = self.Castbar
|
||||
if(spellname and (element.castName ~= spellname)) then
|
||||
return
|
||||
end
|
||||
|
||||
if(mergeTradeskill and UnitIsUnit(unit, 'player')) then
|
||||
if(tradeskillCurrent == tradeskillTotal) then
|
||||
mergeTradeskill = false
|
||||
end
|
||||
else
|
||||
element.casting = nil
|
||||
end
|
||||
|
||||
--[[ Callback: Castbar:PostCastStop(unit, name)
|
||||
Called after the element has been updated when a spell cast has finished.
|
||||
|
||||
* self - the Castbar widget
|
||||
* unit - unit for which the update has been triggered (string)
|
||||
* name - name of the spell (string)
|
||||
--]]
|
||||
if(element.PostCastStop) then
|
||||
return element:PostCastStop(unit, spellname)
|
||||
end
|
||||
end
|
||||
|
||||
local function UNIT_SPELLCAST_CHANNEL_START(self, event, unit)
|
||||
if(self.unit ~= unit and self.realUnit ~= unit) then return end
|
||||
|
||||
local element = self.Castbar
|
||||
local name, _, _, texture, startTime, endTime = UnitChannelInfo(unit)
|
||||
if(not name) then
|
||||
return
|
||||
end
|
||||
|
||||
endTime = endTime / 1e3
|
||||
startTime = startTime / 1e3
|
||||
local max = (endTime - startTime)
|
||||
local duration = endTime - GetTime()
|
||||
|
||||
element.duration = duration
|
||||
element.max = max
|
||||
element.delay = 0
|
||||
element.startTime = startTime
|
||||
element.endTime = endTime
|
||||
element.extraTickRatio = 0
|
||||
element.channeling = true
|
||||
element.holdTime = 0
|
||||
|
||||
-- We have to do this, as it's possible for spell casts to never have _STOP
|
||||
-- executed or be fully completed by the OnUpdate handler before CHANNEL_START
|
||||
-- is called.
|
||||
element.casting = nil
|
||||
element.castName = nil
|
||||
|
||||
element:SetMinMaxValues(0, max)
|
||||
element:SetValue(duration)
|
||||
|
||||
if(element.Text) then element.Text:SetText(name) end
|
||||
if(element.Icon) then element.Icon:SetTexture(texture) end
|
||||
if(element.Time) then element.Time:SetText() end
|
||||
|
||||
local sf = element.SafeZone
|
||||
if(sf) then
|
||||
sf:ClearAllPoints()
|
||||
sf:SetPoint('LEFT')
|
||||
sf:SetPoint('TOP')
|
||||
sf:SetPoint('BOTTOM')
|
||||
updateSafeZone(element)
|
||||
end
|
||||
|
||||
--[[ Callback: Castbar:PostChannelStart(unit, name)
|
||||
Called after the element has been updated upon a spell channel start.
|
||||
|
||||
* self - the Castbar widget
|
||||
* unit - unit for which the update has been triggered (string)
|
||||
* name - name of the channeled spell (string)
|
||||
--]]
|
||||
if(element.PostChannelStart) then
|
||||
element:PostChannelStart(unit, name)
|
||||
end
|
||||
element:Show()
|
||||
end
|
||||
|
||||
local function UNIT_SPELLCAST_CHANNEL_UPDATE(self, event, unit)
|
||||
if(self.unit ~= unit and self.realUnit ~= unit) then return end
|
||||
|
||||
local element = self.Castbar
|
||||
local name, _, _, _, startTime, endTime = UnitChannelInfo(unit)
|
||||
if(not name or not element:IsShown()) then
|
||||
return
|
||||
end
|
||||
|
||||
local duration = (endTime / 1000) - GetTime()
|
||||
element.delay = element.delay + element.duration - duration
|
||||
element.duration = duration
|
||||
element.max = (endTime - startTime) / 1000
|
||||
element.startTime = startTime / 1000
|
||||
element.endTime = endTime / 1000
|
||||
|
||||
element:SetMinMaxValues(0, element.max)
|
||||
element:SetValue(duration)
|
||||
|
||||
--[[ Callback: Castbar:PostChannelUpdate(unit, name)
|
||||
Called after the element has been updated after a channeled spell has been delayed or interrupted.
|
||||
|
||||
* self - the Castbar widget
|
||||
* unit - unit for which the update has been triggered (string)
|
||||
* name - name of the channeled spell (string)
|
||||
--]]
|
||||
if(element.PostChannelUpdate) then
|
||||
return element:PostChannelUpdate(unit, name)
|
||||
end
|
||||
end
|
||||
|
||||
local function UNIT_SPELLCAST_CHANNEL_STOP(self, event, unit, spellname)
|
||||
if(self.unit ~= unit and self.realUnit ~= unit) then return end
|
||||
|
||||
local element = self.Castbar
|
||||
if(element:IsShown()) then
|
||||
element.channeling = nil
|
||||
|
||||
--[[ Callback: Castbar:PostChannelUpdate(unit, name)
|
||||
Called after the element has been updated after a channeled spell has been completed.
|
||||
|
||||
* self - the Castbar widget
|
||||
* unit - unit for which the update has been triggered (string)
|
||||
* name - name of the channeled spell (string)
|
||||
--]]
|
||||
if(element.PostChannelStop) then
|
||||
return element:PostChannelStop(unit, spellname)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function onUpdate(self, elapsed)
|
||||
if(self.casting) then
|
||||
local duration = self.duration + elapsed
|
||||
if(duration >= self.max or (tradeskillTotal > 1 and duration >= (tradeskillCastDuration + tradeskillCastTime * 1.25))) then
|
||||
self.casting = nil
|
||||
self:Hide()
|
||||
tradeskillTotal = 0
|
||||
|
||||
if(self.PostCastStop) then self:PostCastStop(self.__owner.unit) end
|
||||
return
|
||||
end
|
||||
|
||||
if(self.Time) then
|
||||
if(self.delay ~= 0) then
|
||||
if(self.CustomDelayText) then
|
||||
self:CustomDelayText(duration)
|
||||
else
|
||||
self.Time:SetText(format('%.1f|cffff0000-%.1f|r', duration, self.delay))
|
||||
end
|
||||
else
|
||||
if(self.CustomTimeText) then
|
||||
self:CustomTimeText(duration)
|
||||
else
|
||||
self.Time:SetText(format('%.1f', duration))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
self.duration = duration
|
||||
self:SetValue(duration)
|
||||
|
||||
if(self.Spark) then
|
||||
self.Spark:SetPoint('CENTER', self, 'LEFT', (duration / self.max) * self:GetWidth(), 0)
|
||||
end
|
||||
elseif(self.channeling) then
|
||||
local duration = self.duration - elapsed
|
||||
|
||||
if(duration <= 0) then
|
||||
self.channeling = nil
|
||||
self:Hide()
|
||||
|
||||
if(self.PostChannelStop) then self:PostChannelStop(self.__owner.unit) end
|
||||
return
|
||||
end
|
||||
|
||||
if(self.Time) then
|
||||
if(self.delay ~= 0) then
|
||||
if(self.CustomDelayText) then
|
||||
self:CustomDelayText(duration)
|
||||
else
|
||||
self.Time:SetText(format('%.1f|cffff0000-%.1f|r', duration, self.delay))
|
||||
end
|
||||
else
|
||||
if(self.CustomTimeText) then
|
||||
self:CustomTimeText(duration)
|
||||
else
|
||||
self.Time:SetText(format('%.1f', duration))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
self.duration = duration
|
||||
self:SetValue(duration)
|
||||
if(self.Spark) then
|
||||
self.Spark:SetPoint('CENTER', self, 'LEFT', (duration / self.max) * self:GetWidth(), 0)
|
||||
end
|
||||
elseif(self.holdTime > 0) then
|
||||
self.holdTime = self.holdTime - elapsed
|
||||
else
|
||||
self.casting = nil
|
||||
self.castName = nil
|
||||
self.channeling = nil
|
||||
tradeskillTotal = 0
|
||||
|
||||
self:Hide()
|
||||
end
|
||||
end
|
||||
|
||||
local function Update(self, ...)
|
||||
UNIT_SPELLCAST_START(self, ...)
|
||||
return UNIT_SPELLCAST_CHANNEL_START(self, ...)
|
||||
end
|
||||
|
||||
local function ForceUpdate(element)
|
||||
return Update(element.__owner, 'ForceUpdate', element.__owner.unit)
|
||||
end
|
||||
|
||||
local function Enable(self, unit)
|
||||
local element = self.Castbar
|
||||
if(element) then
|
||||
element.__owner = self
|
||||
element.ForceUpdate = ForceUpdate
|
||||
|
||||
if(not (unit and unit:match('%wtarget$'))) then
|
||||
self:RegisterEvent('UNIT_SPELLCAST_START', UNIT_SPELLCAST_START)
|
||||
self:RegisterEvent('UNIT_SPELLCAST_FAILED', UNIT_SPELLCAST_FAILED)
|
||||
self:RegisterEvent('UNIT_SPELLCAST_STOP', UNIT_SPELLCAST_STOP)
|
||||
self:RegisterEvent('UNIT_SPELLCAST_INTERRUPTED', UNIT_SPELLCAST_INTERRUPTED)
|
||||
self:RegisterEvent('UNIT_SPELLCAST_DELAYED', UNIT_SPELLCAST_DELAYED)
|
||||
self:RegisterEvent('UNIT_SPELLCAST_CHANNEL_START', UNIT_SPELLCAST_CHANNEL_START)
|
||||
self:RegisterEvent('UNIT_SPELLCAST_CHANNEL_UPDATE', UNIT_SPELLCAST_CHANNEL_UPDATE)
|
||||
self:RegisterEvent('UNIT_SPELLCAST_CHANNEL_STOP', UNIT_SPELLCAST_CHANNEL_STOP)
|
||||
self:RegisterEvent('UNIT_SPELLCAST_SENT', UNIT_SPELLCAST_SENT, true)
|
||||
self:RegisterEvent('UNIT_SPELLCAST_FAILED_QUIET', UNIT_SPELLCAST_FAILED_QUIET)
|
||||
end
|
||||
|
||||
element.holdTime = 0
|
||||
element:SetScript('OnUpdate', element.OnUpdate or onUpdate)
|
||||
|
||||
if(self.unit == 'player') then
|
||||
CastingBarFrame:UnregisterAllEvents()
|
||||
CastingBarFrame.Show = CastingBarFrame.Hide
|
||||
CastingBarFrame:Hide()
|
||||
|
||||
PetCastingBarFrame:UnregisterAllEvents()
|
||||
PetCastingBarFrame.Show = PetCastingBarFrame.Hide
|
||||
PetCastingBarFrame:Hide()
|
||||
end
|
||||
|
||||
if(element:IsObjectType('StatusBar') and not element:GetStatusBarTexture()) then
|
||||
element:SetStatusBarTexture([[Interface\TargetingFrame\UI-StatusBar]])
|
||||
end
|
||||
|
||||
local spark = element.Spark
|
||||
if(spark and spark:IsObjectType('Texture') and not spark:GetTexture()) then
|
||||
spark:SetTexture([[Interface\CastingBar\UI-CastingBar-Spark]])
|
||||
end
|
||||
|
||||
local safeZone = element.SafeZone
|
||||
if(safeZone and safeZone:IsObjectType('Texture') and not safeZone:GetTexture()) then
|
||||
safeZone:SetTexture(1, 0, 0)
|
||||
end
|
||||
|
||||
element:Hide()
|
||||
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
local function Disable(self)
|
||||
local element = self.Castbar
|
||||
if(element) then
|
||||
element:Hide()
|
||||
|
||||
self:UnregisterEvent('UNIT_SPELLCAST_START', UNIT_SPELLCAST_START)
|
||||
self:UnregisterEvent('UNIT_SPELLCAST_FAILED', UNIT_SPELLCAST_FAILED)
|
||||
self:UnregisterEvent('UNIT_SPELLCAST_STOP', UNIT_SPELLCAST_STOP)
|
||||
self:UnregisterEvent('UNIT_SPELLCAST_INTERRUPTED', UNIT_SPELLCAST_INTERRUPTED)
|
||||
self:UnregisterEvent('UNIT_SPELLCAST_DELAYED', UNIT_SPELLCAST_DELAYED)
|
||||
self:UnregisterEvent('UNIT_SPELLCAST_CHANNEL_START', UNIT_SPELLCAST_CHANNEL_START)
|
||||
self:UnregisterEvent('UNIT_SPELLCAST_CHANNEL_UPDATE', UNIT_SPELLCAST_CHANNEL_UPDATE)
|
||||
self:UnregisterEvent('UNIT_SPELLCAST_CHANNEL_STOP', UNIT_SPELLCAST_CHANNEL_STOP)
|
||||
self:UnregisterEvent('UNIT_SPELLCAST_SENT', UNIT_SPELLCAST_SENT)
|
||||
self:UnregisterEvent('UNIT_SPELLCAST_FAILED_QUIET', UNIT_SPELLCAST_FAILED_QUIET)
|
||||
|
||||
element:SetScript('OnUpdate', nil)
|
||||
end
|
||||
end
|
||||
|
||||
hooksecurefunc('DoTradeSkill', function(_, num)
|
||||
tradeskillCastTime = 0
|
||||
tradeskillCastDuration = 0
|
||||
tradeskillCurrent = 0
|
||||
tradeskillTotal = num or 1
|
||||
mergeTradeskill = true
|
||||
end)
|
||||
|
||||
oUF:AddElement('Castbar', Update, Enable, Disable)
|
||||
@@ -0,0 +1,102 @@
|
||||
--[[
|
||||
# Element: Combat Indicator
|
||||
|
||||
Toggles the visibility of an indicator based on the player's combat status.
|
||||
|
||||
## Widget
|
||||
|
||||
CombatIndicator - Any UI widget.
|
||||
|
||||
## Notes
|
||||
|
||||
A default texture will be applied if the widget is a Texture and doesn't have a texture or a color set.
|
||||
|
||||
## Examples
|
||||
|
||||
-- Position and size
|
||||
local CombatIndicator = self:CreateTexture(nil, 'OVERLAY')
|
||||
CombatIndicator:SetSize(16, 16)
|
||||
CombatIndicator:SetPoint('TOP', self)
|
||||
|
||||
-- Register it with oUF
|
||||
self.CombatIndicator = CombatIndicator
|
||||
--]]
|
||||
|
||||
local ns = oUF
|
||||
local oUF = ns.oUF
|
||||
|
||||
local UnitAffectingCombat = UnitAffectingCombat
|
||||
|
||||
local function Update(self, event)
|
||||
local element = self.CombatIndicator
|
||||
|
||||
--[[ Callback: CombatIndicator:PreUpdate()
|
||||
Called before the element has been updated.
|
||||
|
||||
* self - the CombatIndicator element
|
||||
--]]
|
||||
if(element.PreUpdate) then
|
||||
element:PreUpdate()
|
||||
end
|
||||
|
||||
local inCombat = UnitAffectingCombat('player')
|
||||
if(inCombat) then
|
||||
element:Show()
|
||||
else
|
||||
element:Hide()
|
||||
end
|
||||
|
||||
--[[ Callback: CombatIndicator:PostUpdate(inCombat)
|
||||
Called after the element has been updated.
|
||||
|
||||
* self - the CombatIndicator element
|
||||
* inCombat - indicates if the player is affecting combat (boolean)
|
||||
--]]
|
||||
if(element.PostUpdate) then
|
||||
return element:PostUpdate(inCombat)
|
||||
end
|
||||
end
|
||||
|
||||
local function Path(self, ...)
|
||||
--[[ Override: CombatIndicator.Override(self, event)
|
||||
Used to completely override the internal update function.
|
||||
|
||||
* self - the parent object
|
||||
* event - the event triggering the update (string)
|
||||
--]]
|
||||
return (self.CombatIndicator.Override or Update) (self, unpack(arg))
|
||||
end
|
||||
|
||||
local function ForceUpdate(element)
|
||||
return Path(element.__owner, 'ForceUpdate')
|
||||
end
|
||||
|
||||
local function Enable(self, unit)
|
||||
local element = self.CombatIndicator
|
||||
if(element and unit == 'player') then
|
||||
element.__owner = self
|
||||
element.ForceUpdate = ForceUpdate
|
||||
|
||||
self:RegisterEvent('PLAYER_REGEN_DISABLED', Path)
|
||||
self:RegisterEvent('PLAYER_REGEN_ENABLED', Path)
|
||||
|
||||
if(element:IsObjectType('Texture') and not element:GetTexture()) then
|
||||
element:SetTexture([[Interface\CharacterFrame\UI-StateIcon]])
|
||||
element:SetTexCoord(.5, 1, 0, .49)
|
||||
end
|
||||
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
local function Disable(self)
|
||||
local element = self.CombatIndicator
|
||||
if(element) then
|
||||
element:Hide()
|
||||
|
||||
self:UnregisterEvent('PLAYER_REGEN_DISABLED', Path)
|
||||
self:UnregisterEvent('PLAYER_REGEN_ENABLED', Path)
|
||||
end
|
||||
end
|
||||
|
||||
oUF:AddElement('CombatIndicator', Path, Enable, Disable)
|
||||
@@ -0,0 +1,118 @@
|
||||
--[[
|
||||
# Element: ComboPoints
|
||||
|
||||
Handles the visibility and updating of the player's combo points.
|
||||
|
||||
## Widget
|
||||
|
||||
ComboPoints - An `table` consisting of as many Textures as the theoretical maximum return of [GetComboPoints](http://wowprogramming.com/docs/api/GetComboPoints).
|
||||
|
||||
## Notes
|
||||
|
||||
A default texture will be applied if the widget is a Texture and doesn't have a texture or a color set.
|
||||
|
||||
## Examples
|
||||
|
||||
local ComboPoints = {}
|
||||
for index = 1, 10 do
|
||||
local Bar = CreateFrame('StatusBar', nil, self)
|
||||
|
||||
-- Position and size.
|
||||
Bar:SetSize(16, 16)
|
||||
Bar:SetPoint('TOPLEFT', self, 'BOTTOMLEFT', (index - 1) * Bar:GetWidth(), 0)
|
||||
|
||||
ComboPoints[index] = Bar
|
||||
end
|
||||
|
||||
-- Register with oUF
|
||||
self.ComboPoints = ComboPoints
|
||||
--]]
|
||||
|
||||
local ns = oUF
|
||||
local oUF = ns.oUF
|
||||
|
||||
local GetComboPoints = GetComboPoints
|
||||
local MAX_COMBO_POINTS = MAX_COMBO_POINTS
|
||||
|
||||
local function Update(self, event)
|
||||
local element = self.ComboPoints
|
||||
|
||||
--[[ Callback: ComboPoints:PreUpdate()
|
||||
Called before the element has been updated.
|
||||
|
||||
* self - the ComboPoints element
|
||||
--]]
|
||||
if(element.PreUpdate) then
|
||||
element:PreUpdate()
|
||||
end
|
||||
|
||||
local cp = GetComboPoints('player', 'target')
|
||||
|
||||
for i = 1, MAX_COMBO_POINTS do
|
||||
if(i <= cp) then
|
||||
element[i]:Show()
|
||||
else
|
||||
element[i]:Hide()
|
||||
end
|
||||
end
|
||||
|
||||
--[[ Callback: ComboPoints:PostUpdate(role)
|
||||
Called after the element has been updated.
|
||||
|
||||
* self - the ComboPoints element
|
||||
* cpoint - the current amount of combo points (number)
|
||||
--]]
|
||||
if(element.PostUpdate) then
|
||||
return element:PostUpdate(cp)
|
||||
end
|
||||
end
|
||||
|
||||
local function Path(self, ...)
|
||||
--[[ Override: ComboPoints.Override(self, event, ...)
|
||||
Used to completely override the internal update function.
|
||||
|
||||
* self - the parent object
|
||||
* event - the event triggering the update (string)
|
||||
* ... - the arguments accompanying the event
|
||||
--]]
|
||||
return (self.ComboPoints.Override or Update) (self, ...)
|
||||
end
|
||||
|
||||
local function ForceUpdate(element)
|
||||
return Path(element.__owner, 'ForceUpdate', element.__owner.unit)
|
||||
end
|
||||
|
||||
local function Enable(self)
|
||||
local element = self.ComboPoints
|
||||
if(element) then
|
||||
element.__owner = self
|
||||
element.ForceUpdate = ForceUpdate
|
||||
|
||||
self:RegisterEvent('PLAYER_COMBO_POINTS', Path, true)
|
||||
self:RegisterEvent('PLAYER_TARGET_CHANGED', Path, true)
|
||||
|
||||
for index = 1, MAX_COMBO_POINTS do
|
||||
local cp = element[index]
|
||||
if(cp:IsObjectType('Texture') and not cp:GetTexture()) then
|
||||
cp:SetTexture([[Interface\ComboFrame\ComboPoint]])
|
||||
cp:SetTexCoord(0, 0.375, 0, 1)
|
||||
end
|
||||
end
|
||||
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
local function Disable(self)
|
||||
local element = self.ComboPoints
|
||||
if(element) then
|
||||
for index = 1, MAX_COMBO_POINTS do
|
||||
element[index]:Hide()
|
||||
end
|
||||
|
||||
self:UnregisterEvent('PLAYER_COMBO_POINTS', Path)
|
||||
self:UnregisterEvent('PLAYER_TARGET_CHANGED', Path)
|
||||
end
|
||||
end
|
||||
|
||||
oUF:AddElement('ComboPoints', Path, Enable, Disable)
|
||||
@@ -0,0 +1,22 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/">
|
||||
<Script file="power.lua"/>
|
||||
<!--<Script file="auras.lua"/>-->
|
||||
<Script file="health.lua"/>
|
||||
<Script file="raidtargetindicator.lua"/>
|
||||
<Script file="leaderindicator.lua"/>
|
||||
<Script file="combatindicator.lua"/>
|
||||
<Script file="restingindicator.lua"/>
|
||||
<!--<Script file="pvpindicator.lua"/>-->
|
||||
<Script file="portrait.lua"/>
|
||||
<!--
|
||||
<Script file="range.lua"/>
|
||||
<Script file="castbar.lua"/>-->
|
||||
<Script file="tags.lua"/>
|
||||
<Script file="masterlooterindicator.lua"/>
|
||||
<Script file="assistantindicator.lua"/>
|
||||
<!--<Script file="readycheckindicator.lua"/>
|
||||
<Script file="combopoints.lua"/>
|
||||
<Script file="raidroleindicator.lua"/>
|
||||
<Script file="happinessindicator.lua"/>
|
||||
-->
|
||||
</Ui>
|
||||
@@ -0,0 +1,116 @@
|
||||
--[[
|
||||
# Element: HappinessIndicator
|
||||
|
||||
Handles the visibility and updating of player pet happiness.
|
||||
|
||||
## Widget
|
||||
|
||||
HappinessIndicator - A `Texture` used to display the current happiness level.
|
||||
The element works by changing the texture's vertex color.
|
||||
|
||||
## Notes
|
||||
|
||||
A default texture will be applied if the widget is a Texture and doesn't have a texture or a color set.
|
||||
|
||||
## Examples
|
||||
|
||||
-- Position and size
|
||||
local HappinessIndicator = self:CreateTexture(nil, 'OVERLAY')
|
||||
HappinessIndicator:SetSize(16, 16)
|
||||
HappinessIndicator:SetPoint('TOPRIGHT', self)
|
||||
|
||||
-- Register it with oUF
|
||||
self.HappinessIndicator = HappinessIndicator
|
||||
--]]
|
||||
|
||||
local ns = oUF
|
||||
local oUF = ns.oUF
|
||||
|
||||
local GetPetHappiness = GetPetHappiness
|
||||
local HasPetUI = HasPetUI
|
||||
|
||||
local function Update(self, event, unit)
|
||||
if(not unit or self.unit ~= unit) then return end
|
||||
|
||||
local element = self.HappinessIndicator
|
||||
|
||||
--[[ Callback: HappinessIndicator:PreUpdate()
|
||||
Called before the element has been updated.
|
||||
|
||||
* self - the ComboPoints element
|
||||
--]]
|
||||
if(element.PreUpdate) then
|
||||
element:PreUpdate()
|
||||
end
|
||||
|
||||
local _, hunterPet = HasPetUI()
|
||||
local happiness, damagePercentage = GetPetHappiness()
|
||||
|
||||
if(hunterPet and happiness) then
|
||||
if(happiness == 1) then
|
||||
element:SetTexCoord(0.375, 0.5625, 0, 0.359375)
|
||||
elseif(happiness == 2) then
|
||||
element:SetTexCoord(0.1875, 0.375, 0, 0.359375)
|
||||
elseif(happiness == 3) then
|
||||
element:SetTexCoord(0, 0.1875, 0, 0.359375)
|
||||
end
|
||||
|
||||
element:Show()
|
||||
else
|
||||
return element:Hide()
|
||||
end
|
||||
|
||||
--[[ Callback: HappinessIndicator:PostUpdate(role)
|
||||
Called after the element has been updated.
|
||||
|
||||
* self - the ComboPoints element
|
||||
* unit - the unit for which the update has been triggered (string)
|
||||
* happiness - the numerical happiness value of the pet (1 = unhappy, 2 = content, 3 = happy) (number)
|
||||
* damagePercentage - damage modifier, happiness affects this (unhappy = 75%, content = 100%, happy = 125%) (number)
|
||||
--]]
|
||||
if(element.PostUpdate) then
|
||||
return element:PostUpdate(unit, happiness, damagePercentage)
|
||||
end
|
||||
end
|
||||
|
||||
local function Path(self, ...)
|
||||
--[[ Override: HappinessIndicator.Override(self, event, ...)
|
||||
Used to completely override the internal update function.
|
||||
|
||||
* self - the parent object
|
||||
* event - the event triggering the update (string)
|
||||
* ... - the arguments accompanying the event
|
||||
--]]
|
||||
return (self.HappinessIndicator.Override or Update) (self, ...)
|
||||
end
|
||||
|
||||
local function ForceUpdate(element)
|
||||
return Path(element.__owner, 'ForceUpdate', element.__owner.unit)
|
||||
end
|
||||
|
||||
local function Enable(self)
|
||||
local element = self.HappinessIndicator
|
||||
if(element) then
|
||||
element.__owner = self
|
||||
element.ForceUpdate = ForceUpdate
|
||||
|
||||
self:RegisterEvent('UNIT_HAPPINESS', Path)
|
||||
|
||||
if(element:IsObjectType('Texture') and not element:GetTexture()) then
|
||||
element:SetTexture([[Interface\PetPaperDollFrame\UI-PetHappiness]])
|
||||
end
|
||||
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
local function Disable(self)
|
||||
local element = self.HappinessIndicator
|
||||
if(element) then
|
||||
element:Hide()
|
||||
|
||||
self:UnregisterEvent('UNIT_HAPPINESS', Path)
|
||||
end
|
||||
end
|
||||
|
||||
oUF:AddElement('HappinessIndicator', Path, Enable, Disable)
|
||||
@@ -0,0 +1,292 @@
|
||||
--[[
|
||||
# Element: Health Bar
|
||||
|
||||
Handles the updating of a status bar that displays the unit's health.
|
||||
|
||||
## Widget
|
||||
|
||||
Health - A `StatusBar` used to represent the unit's health.
|
||||
|
||||
## Sub-Widgets
|
||||
|
||||
.bg - A `Texture` used as a background. It will inherit the color of the main StatusBar.
|
||||
|
||||
## Notes
|
||||
|
||||
A default texture will be applied if the widget is a StatusBar and doesn't have a texture set.
|
||||
|
||||
## Options
|
||||
|
||||
.frequentUpdates - Indicates whether to use OnUpdate script instead of UNIT_HEALTH to update the bar (boolean)
|
||||
.smoothGradient - 9 color values to be used with the .colorSmooth option (table)
|
||||
|
||||
The following options are listed by priority. The first check that returns true decides the color of the bar.
|
||||
|
||||
.colorTapping - Use `self.colors.tapping` to color the bar if the unit isn't tapped by the player (boolean)
|
||||
.colorDisconnected - Use `self.colors.disconnected` to color the bar if the unit is offline (boolean)
|
||||
.colorHappiness - Use `self.colors.happiness` to color the bar if the unit is pet based on pet happiness (boolean)
|
||||
.colorClass - Use `self.colors.class[class]` to color the bar based on unit class. `class` is defined by the
|
||||
second return of [UnitClass](http://wowprogramming.com/docs/api/UnitClass) (boolean)
|
||||
.colorClassNPC - Use `self.colors.class[class]` to color the bar if the unit is a NPC (boolean)
|
||||
.colorClassPet - Use `self.colors.class[class]` to color the bar if the unit is player controlled, but not a player
|
||||
(boolean)
|
||||
.colorReaction - Use `self.colors.reaction[reaction]` to color the bar based on the player's reaction towards the
|
||||
unit. `reaction` is defined by the return value of
|
||||
[UnitReaction](http://wowprogramming.com/docs/api/UnitReaction) (boolean)
|
||||
.colorSmooth - Use `smoothGradient` if present or `self.colors.smooth` to color the bar with a smooth gradient
|
||||
based on the player's current health percentage (boolean)
|
||||
.colorHealth - Use `self.colors.health` to color the bar. This flag is used to reset the bar color back to default
|
||||
if none of the above conditions are met (boolean)
|
||||
|
||||
## Sub-Widgets Options
|
||||
|
||||
.multiplier - Used to tint the background based on the main widgets R, G and B values. Defaults to 1 (number)[0-1]
|
||||
|
||||
## Attributes
|
||||
|
||||
.disconnected - Indicates whether the unit is disconnected (boolean)
|
||||
|
||||
## Examples
|
||||
|
||||
-- Position and size
|
||||
local Health = CreateFrame('StatusBar', nil, self)
|
||||
Health:SetHeight(20)
|
||||
Health:SetPoint('TOP')
|
||||
Health:SetPoint('LEFT')
|
||||
Health:SetPoint('RIGHT')
|
||||
|
||||
-- Add a background
|
||||
local Background = Health:CreateTexture(nil, 'BACKGROUND')
|
||||
Background:SetAllPoints(Health)
|
||||
Background:SetTexture(1, 1, 1, .5)
|
||||
|
||||
-- Options
|
||||
Health.frequentUpdates = true
|
||||
Health.colorTapping = true
|
||||
Health.colorDisconnected = true
|
||||
Health.colorClass = true
|
||||
Health.colorReaction = true
|
||||
Health.colorHealth = true
|
||||
|
||||
-- Make the background darker.
|
||||
Background.multiplier = .5
|
||||
|
||||
-- Register it with oUF
|
||||
Health.bg = Background
|
||||
self.Health = Health
|
||||
--]]
|
||||
|
||||
local ns = oUF
|
||||
local oUF = ns.oUF
|
||||
|
||||
local unpack = unpack
|
||||
|
||||
local GetPetHappiness = GetPetHappiness
|
||||
local UnitClass = UnitClass
|
||||
local UnitHealth = UnitHealth
|
||||
local UnitHealthMax = UnitHealthMax
|
||||
local UnitIsConnected = UnitIsConnected
|
||||
local UnitIsPlayer = UnitIsPlayer
|
||||
local UnitIsTapped = UnitIsTapped
|
||||
local UnitIsTappedByPlayer = UnitIsTappedByPlayer
|
||||
local UnitIsUnit = UnitIsUnit
|
||||
local UnitPlayerControlled = UnitPlayerControlled
|
||||
local UnitReaction = UnitReaction
|
||||
|
||||
local updateFrequentUpdates
|
||||
|
||||
local function UpdateColor(element, unit, cur, max)
|
||||
local parent = element.__owner
|
||||
|
||||
if element.frequentUpdates ~= element.__frequentUpdates then
|
||||
element.__frequentUpdates = element.frequentUpdates
|
||||
updateFrequentUpdates(parent, unit)
|
||||
end
|
||||
|
||||
local r, g, b, t
|
||||
if(element.colorTapping and not UnitPlayerControlled(unit) and (UnitIsTapped(unit) and not UnitIsTappedByPlayer(unit))) then
|
||||
t = parent.colors.tapped
|
||||
elseif(element.colorDisconnected and element.disconnected) then
|
||||
t = parent.colors.disconnected
|
||||
elseif(element.colorHappiness and UnitIsUnit(unit, 'pet') and GetPetHappiness()) then
|
||||
t = parent.colors.happiness[GetPetHappiness()]
|
||||
elseif(element.colorClass and UnitIsPlayer(unit)) or
|
||||
(element.colorClassNPC and not UnitIsPlayer(unit)) or
|
||||
(element.colorClassPet and UnitPlayerControlled(unit) and not UnitIsPlayer(unit)) then
|
||||
local _, class = UnitClass(unit)
|
||||
t = parent.colors.class[class]
|
||||
elseif(element.colorReaction and UnitReaction(unit, 'player')) then
|
||||
t = parent.colors.reaction[UnitReaction(unit, 'player')]
|
||||
elseif(element.colorSmooth) then
|
||||
r, g, b = parent.ColorGradient(cur, max, unpack(element.smoothGradient or parent.colors.smooth))
|
||||
elseif(element.colorHealth) then
|
||||
t = parent.colors.health
|
||||
end
|
||||
|
||||
if(t) then
|
||||
r, g, b = t[1], t[2], t[3]
|
||||
end
|
||||
|
||||
if(r or g or b) then
|
||||
element:SetStatusBarColor(r, g, b)
|
||||
|
||||
local bg = element.bg
|
||||
if(bg) then
|
||||
local mu = bg.multiplier or 1
|
||||
bg:SetVertexColor(r * mu, g * mu, b * mu)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function Update(self, event, unit)
|
||||
if(not unit or self.unit ~= unit) then return end
|
||||
local element = self.Health
|
||||
|
||||
--[[ Callback: Health:PreUpdate(unit)
|
||||
Called before the element has been updated.
|
||||
|
||||
* self - the Health element
|
||||
* unit - the unit for which the update has been triggered (string)
|
||||
--]]
|
||||
if(element.PreUpdate) then
|
||||
element:PreUpdate(unit)
|
||||
end
|
||||
|
||||
local cur, max = UnitHealth(unit), UnitHealthMax(unit)
|
||||
local disconnected = not UnitIsConnected(unit)
|
||||
element:SetMinMaxValues(0, max)
|
||||
|
||||
if(disconnected) then
|
||||
element:SetValue(max)
|
||||
else
|
||||
element:SetValue(cur)
|
||||
end
|
||||
|
||||
element.disconnected = disconnected
|
||||
|
||||
--[[ Override: Health:UpdateColor(unit, cur, max)
|
||||
Used to completely override the internal function for updating the widgets' colors.
|
||||
|
||||
* self - the Health element
|
||||
* unit - the unit for which the update has been triggered (string)
|
||||
* cur - the unit's current health value (number)
|
||||
* max - the unit's maximum possible health value (number)
|
||||
--]]
|
||||
element:UpdateColor(unit, cur, max)
|
||||
|
||||
--[[ Callback: Health:PostUpdate(unit, cur, max)
|
||||
Called after the element has been updated.
|
||||
|
||||
* self - the Health element
|
||||
* unit - the unit for which the update has been triggered (string)
|
||||
* cur - the unit's current health value (number)
|
||||
* max - the unit's maximum possible health value (number)
|
||||
--]]
|
||||
if(element.PostUpdate) then
|
||||
return element:PostUpdate(unit, cur, max)
|
||||
end
|
||||
end
|
||||
|
||||
local function Path(self, ...)
|
||||
--[[ Override: Health.Override(self, event, unit)
|
||||
Used to completely override the internal update function.
|
||||
|
||||
* self - the parent object
|
||||
* event - the event triggering the update (string)
|
||||
* unit - the unit accompanying the event (string)
|
||||
--]]
|
||||
return (self.Health.Override or Update) (self, unpack(arg))
|
||||
end
|
||||
|
||||
local function ForceUpdate(element)
|
||||
return Path(element.__owner, 'ForceUpdate', element.__owner.unit)
|
||||
end
|
||||
|
||||
local function onHealthUpdate()
|
||||
if(this.disconnected) then return end
|
||||
|
||||
local unit = this.__owner.unit
|
||||
local health = UnitHealth(unit)
|
||||
|
||||
if(health ~= this.min) then
|
||||
this.min = health
|
||||
|
||||
return Path(this.__owner, 'OnHealthUpdate', unit)
|
||||
end
|
||||
end
|
||||
|
||||
function updateFrequentUpdates(self, unit)
|
||||
if(not unit or string.match(unit, '%w+target$')) then return end
|
||||
|
||||
local element = self.Health
|
||||
if(element.frequentUpdates and not element:GetScript('OnUpdate')) then
|
||||
element:SetScript('OnUpdate', onHealthUpdate)
|
||||
|
||||
if((unit == 'party' or string.match(unit, 'party%d?$'))) then
|
||||
self:RegisterEvent('UNIT_HEALTH', Path)
|
||||
elseif(self:IsEventRegistered("UNIT_HEALTH")) then
|
||||
self:UnregisterEvent('UNIT_HEALTH', Path)
|
||||
end
|
||||
elseif(not element.frequentUpdates and element:GetScript('OnUpdate')) then
|
||||
element:SetScript('OnUpdate', nil)
|
||||
|
||||
self:RegisterEvent('UNIT_HEALTH', Path)
|
||||
end
|
||||
end
|
||||
|
||||
local function Enable(self, unit)
|
||||
local element = self.Health
|
||||
if(element) then
|
||||
element.__owner = self
|
||||
element.ForceUpdate = ForceUpdate
|
||||
element.__frequentUpdates = element.frequentUpdates
|
||||
updateFrequentUpdates(self, unit)
|
||||
|
||||
if(element.frequentUpdates and (unit and not string.match(unit, '%w+target$'))) then
|
||||
element:SetScript('OnUpdate', onHealthUpdate)
|
||||
|
||||
-- The party frames need this to handle disconnect states correctly.
|
||||
if(unit == 'party') then
|
||||
self:RegisterEvent('UNIT_HEALTH', Path)
|
||||
end
|
||||
else
|
||||
self:RegisterEvent('UNIT_HEALTH', Path)
|
||||
end
|
||||
|
||||
self:RegisterEvent('UNIT_MAXHEALTH', Path)
|
||||
self:RegisterEvent('UNIT_CONNECTION', Path)
|
||||
self:RegisterEvent('UNIT_FACTION', Path) -- For tapping
|
||||
self:RegisterEvent('UNIT_HAPPINESS', Path)
|
||||
|
||||
if(element:IsObjectType('StatusBar') and not element:GetStatusBarTexture()) then
|
||||
element:SetStatusBarTexture([[Interface\TargetingFrame\UI-StatusBar]])
|
||||
end
|
||||
|
||||
if(not element.UpdateColor) then
|
||||
element.UpdateColor = UpdateColor
|
||||
end
|
||||
|
||||
element:Show()
|
||||
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
local function Disable(self)
|
||||
local element = self.Health
|
||||
if(element) then
|
||||
if(element:GetScript('OnUpdate')) then
|
||||
element:SetScript('OnUpdate', nil)
|
||||
end
|
||||
|
||||
element:Hide()
|
||||
|
||||
self:UnregisterEvent('UNIT_HEALTH', Path)
|
||||
self:UnregisterEvent('UNIT_MAXHEALTH', Path)
|
||||
self:UnregisterEvent('UNIT_CONNECTION', Path)
|
||||
self:UnregisterEvent('UNIT_FACTION', Path)
|
||||
self:UnregisterEvent('UNIT_HAPPINESS', Path)
|
||||
end
|
||||
end
|
||||
|
||||
oUF:AddElement('Health', Path, Enable, Disable)
|
||||
@@ -0,0 +1,107 @@
|
||||
--[[
|
||||
# Element: Leader Indicator
|
||||
|
||||
Toggles the visibility of an indicator based on the unit's leader status.
|
||||
|
||||
## Widget
|
||||
|
||||
LeaderIndicator - Any UI widget.
|
||||
|
||||
## Notes
|
||||
|
||||
A default texture will be applied if the widget is a Texture and doesn't have a texture or a color set.
|
||||
|
||||
## Examples
|
||||
|
||||
-- Position and size
|
||||
local LeaderIndicator = self:CreateTexture(nil, 'OVERLAY')
|
||||
LeaderIndicator:SetSize(16, 16)
|
||||
LeaderIndicator:SetPoint('BOTTOM', self, 'TOP')
|
||||
|
||||
-- Register it with oUF
|
||||
self.LeaderIndicator = LeaderIndicator
|
||||
--]]
|
||||
|
||||
local ns = oUF
|
||||
local oUF = ns.oUF
|
||||
|
||||
local UnitInParty = UnitInParty
|
||||
local UnitInRaid = UnitInRaid
|
||||
local UnitIsPartyLeader = UnitIsPartyLeader
|
||||
|
||||
local function Update(self, event)
|
||||
local element = self.LeaderIndicator
|
||||
|
||||
--[[ Callback: LeaderIndicator:PreUpdate()
|
||||
Called before the element has been updated.
|
||||
|
||||
* self - the LeaderIndicator element
|
||||
--]]
|
||||
if(element.PreUpdate) then
|
||||
element:PreUpdate()
|
||||
end
|
||||
|
||||
local unit = self.unit
|
||||
local isLeader = (UnitInParty(unit) or UnitInRaid(unit)) and UnitIsPartyLeader(unit)
|
||||
if(isLeader) then
|
||||
element:Show()
|
||||
else
|
||||
element:Hide()
|
||||
end
|
||||
|
||||
--[[ Callback: LeaderIndicator:PostUpdate(isLeader)
|
||||
Called after the element has been updated.
|
||||
|
||||
* self - the LeaderIndicator element
|
||||
* isLeader - indicates whether the element is shown (boolean)
|
||||
--]]
|
||||
if(element.PostUpdate) then
|
||||
return element:PostUpdate(isLeader)
|
||||
end
|
||||
end
|
||||
|
||||
local function Path(self, ...)
|
||||
--[[ Override: LeaderIndicator.Override(self, event, ...)
|
||||
Used to completely override the internal update function.
|
||||
|
||||
* self - the parent object
|
||||
* event - the event triggering the update (string)
|
||||
* ... - the arguments accompanying the event
|
||||
--]]
|
||||
return (self.LeaderIndicator.Override or Update) (self, unpack(arg))
|
||||
end
|
||||
|
||||
local function ForceUpdate(element)
|
||||
return Path(element.__owner, 'ForceUpdate')
|
||||
end
|
||||
|
||||
local function Enable(self)
|
||||
local element = self.LeaderIndicator
|
||||
if(element) then
|
||||
element.__owner = self
|
||||
element.ForceUpdate = ForceUpdate
|
||||
|
||||
self:RegisterEvent('PARTY_LEADER_CHANGED', Path)
|
||||
self:RegisterEvent('PARTY_MEMBERS_CHANGED', Path)
|
||||
self:RegisterEvent('RAID_ROSTER_UPDATE', Path)
|
||||
|
||||
if(element:IsObjectType('Texture') and not element:GetTexture()) then
|
||||
element:SetTexture([[Interface\GroupFrame\UI-Group-LeaderIcon]])
|
||||
end
|
||||
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
local function Disable(self)
|
||||
local element = self.LeaderIndicator
|
||||
if(element) then
|
||||
element:Hide()
|
||||
|
||||
self:UnregisterEvent('PARTY_LEADER_CHANGED', Path)
|
||||
self:UnregisterEvent('PARTY_MEMBERS_CHANGED', Path)
|
||||
self:UnregisterEvent('RAID_ROSTER_UPDATE', Path)
|
||||
end
|
||||
end
|
||||
|
||||
oUF:AddElement('LeaderIndicator', Path, Enable, Disable)
|
||||
@@ -0,0 +1,126 @@
|
||||
--[[
|
||||
# Element: Master Looter Indicator
|
||||
|
||||
Toggles the visibility of an indicator based on the unit's master looter status.
|
||||
|
||||
## Widget
|
||||
|
||||
MasterLooterIndicator - Any UI widget.
|
||||
|
||||
## Notes
|
||||
|
||||
A default texture will be applied if the widget is a Texture and doesn't have a texture or a color set.
|
||||
|
||||
## Examples
|
||||
|
||||
-- Position and size
|
||||
local MasterLooterIndicator = self:CreateTexture(nil, 'OVERLAY')
|
||||
MasterLooterIndicator:SetSize(16, 16)
|
||||
MasterLooterIndicator:SetPoint('TOPRIGHT', self)
|
||||
|
||||
-- Register it with oUF
|
||||
self.MasterLooterIndicator = MasterLooterIndicator
|
||||
--]]
|
||||
|
||||
local ns = oUF
|
||||
local oUF = ns.oUF
|
||||
|
||||
local GetLootMethod = GetLootMethod
|
||||
local UnitInParty = UnitInParty
|
||||
local UnitInRaid = UnitInRaid
|
||||
local UnitIsUnit = UnitIsUnit
|
||||
|
||||
local function Update(self, event)
|
||||
local unit = self.unit
|
||||
local element = self.MasterLooterIndicator
|
||||
|
||||
--[[ Callback: MasterLooterIndicator:PreUpdate()
|
||||
Called before the element has been updated.
|
||||
|
||||
* self - the MasterLooterIndicator element
|
||||
--]]
|
||||
if(element.PreUpdate) then
|
||||
element:PreUpdate()
|
||||
end
|
||||
|
||||
local isShown = false
|
||||
if(UnitInParty(unit) or UnitInRaid(unit)) then
|
||||
local method, partyIndex, raidIndex = GetLootMethod()
|
||||
if(method == 'master') then
|
||||
local mlUnit
|
||||
if(partyIndex) then
|
||||
if(partyIndex == 0) then
|
||||
mlUnit = 'player'
|
||||
else
|
||||
mlUnit = 'party' .. partyIndex
|
||||
end
|
||||
elseif(raidIndex) then
|
||||
mlUnit = 'raid' .. raidIndex
|
||||
end
|
||||
|
||||
if(mlUnit and UnitIsUnit(unit, mlUnit)) then
|
||||
isShown = true
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if isShown then
|
||||
element:Show()
|
||||
else
|
||||
element:Hide()
|
||||
end
|
||||
|
||||
--[[ Callback: MasterLooterIndicator:PostUpdate(isShown)
|
||||
Called after the element has been updated.
|
||||
|
||||
* self - the MasterLooterIndicator element
|
||||
* isShown - indicates whether the element is shown (boolean)
|
||||
--]]
|
||||
if(element.PostUpdate) then
|
||||
return element:PostUpdate(isShown)
|
||||
end
|
||||
end
|
||||
|
||||
local function Path(self, ...)
|
||||
--[[ Override: MasterLooterIndicator.Override(self, event, ...)
|
||||
Used to completely override the internal update function.
|
||||
|
||||
* self - the parent object
|
||||
* event - the event triggering the update (string)
|
||||
* ... - the arguments accompanying the event
|
||||
--]]
|
||||
return (self.MasterLooterIndicator.Override or Update) (self, unpack(arg))
|
||||
end
|
||||
|
||||
local function ForceUpdate(element)
|
||||
return Path(element.__owner, 'ForceUpdate')
|
||||
end
|
||||
|
||||
local function Enable(self, unit)
|
||||
local element = self.MasterLooterIndicator
|
||||
if(element) then
|
||||
element.__owner = self
|
||||
element.ForceUpdate = ForceUpdate
|
||||
|
||||
self:RegisterEvent('PARTY_LOOT_METHOD_CHANGED', Path, true)
|
||||
self:RegisterEvent('PARTY_MEMBERS_CHANGED', Path, true)
|
||||
|
||||
if(element:IsObjectType('Texture') and not element:GetTexture()) then
|
||||
element:SetTexture([[Interface\GroupFrame\UI-Group-MasterLooter]])
|
||||
end
|
||||
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
local function Disable(self)
|
||||
local element = self.MasterLooterIndicator
|
||||
if(element) then
|
||||
element:Hide()
|
||||
|
||||
self:UnregisterEvent('PARTY_LOOT_METHOD_CHANGED', Path)
|
||||
self:UnregisterEvent('PARTY_MEMBERS_CHANGED', Path)
|
||||
end
|
||||
end
|
||||
|
||||
oUF:AddElement('MasterLooterIndicator', Path, Enable, Disable)
|
||||
@@ -0,0 +1,148 @@
|
||||
--[[
|
||||
# Element: Portraits
|
||||
|
||||
Handles the updating of the unit's portrait.
|
||||
|
||||
## Widget
|
||||
|
||||
Portrait - A `PlayerModel` or a `Texture` used to represent the unit's portrait.
|
||||
|
||||
## Notes
|
||||
|
||||
A question mark model will be used if the widget is a PlayerModel and the client doesn't have the model information for
|
||||
the unit.
|
||||
|
||||
## Examples
|
||||
|
||||
-- 3D Portrait
|
||||
-- Position and size
|
||||
local Portrait = CreateFrame('PlayerModel', nil, self)
|
||||
Portrait:SetSize(32, 32)
|
||||
Portrait:SetPoint('RIGHT', self, 'LEFT')
|
||||
|
||||
-- Register it with oUF
|
||||
self.Portrait = Portrait
|
||||
|
||||
-- 2D Portrait
|
||||
local Portrait = self:CreateTexture(nil, 'OVERLAY')
|
||||
Portrait:SetSize(32, 32)
|
||||
Portrait:SetPoint('RIGHT', self, 'LEFT')
|
||||
|
||||
-- Register it with oUF
|
||||
self.Portrait = Portrait
|
||||
--]]
|
||||
|
||||
local ns = oUF
|
||||
local oUF = ns.oUF
|
||||
|
||||
local SetPortraitTexture = SetPortraitTexture
|
||||
local UnitExists = UnitExists
|
||||
local UnitName = UnitName
|
||||
local UnitIsConnected = UnitIsConnected
|
||||
local UnitIsUnit = UnitIsUnit
|
||||
local UnitIsVisible = UnitIsVisible
|
||||
|
||||
local function Update(self, event, unit)
|
||||
if(not unit or not UnitIsUnit(self.unit, unit)) then return end
|
||||
|
||||
local element = self.Portrait
|
||||
|
||||
--[[ Callback: Portrait:PreUpdate(unit)
|
||||
Called before the element has been updated.
|
||||
|
||||
* self - the Portrait element
|
||||
* unit - the unit for which the update has been triggered (string)
|
||||
--]]
|
||||
if(element.PreUpdate) then element:PreUpdate(unit) end
|
||||
|
||||
local name = UnitName(unit)
|
||||
local isAvailable = UnitIsConnected(unit) and UnitIsVisible(unit)
|
||||
if(event ~= 'OnUpdate' or element.name ~= name or element.state ~= isAvailable) then
|
||||
if(element:IsObjectType('PlayerModel')) then
|
||||
if(not isAvailable) then
|
||||
element:SetModelScale(4.25)
|
||||
element:SetCamera(0)
|
||||
element:SetPosition(0, 0, -1.5)
|
||||
element:SetModel([[Interface\Buttons\TalkToMeQuestionMark.m2]])
|
||||
elseif(element.name ~= name or event == 'UNIT_MODEL_CHANGED') then
|
||||
element:ClearModel()
|
||||
element:SetUnit(unit)
|
||||
element:SetModelScale(1)
|
||||
element:SetCamera(0)
|
||||
element:SetPosition(0, 0, 0)
|
||||
else
|
||||
element:SetCamera(0)
|
||||
end
|
||||
else
|
||||
SetPortraitTexture(element, unit)
|
||||
end
|
||||
|
||||
element.name = name
|
||||
element.state = isAvailable
|
||||
end
|
||||
|
||||
--[[ Callback: Portrait:PostUpdate(unit)
|
||||
Called after the element has been updated.
|
||||
|
||||
* self - the Portrait element
|
||||
* unit - the unit for which the update has been triggered (string)
|
||||
--]]
|
||||
if(element.PostUpdate) then
|
||||
return element:PostUpdate(unit)
|
||||
end
|
||||
end
|
||||
|
||||
local function Path(self, ...)
|
||||
--[[ Override: Portrait.Override(self, event, unit)
|
||||
Used to completely override the internal update function.
|
||||
|
||||
* self - the parent object
|
||||
* event - the event triggering the update (string)
|
||||
* unit - the unit accompanying the event (string)
|
||||
--]]
|
||||
return (self.Portrait.Override or Update) (self, unpack(arg))
|
||||
end
|
||||
|
||||
local function ForceUpdate(element)
|
||||
return Path(element.__owner, 'ForceUpdate', element.__owner.unit)
|
||||
end
|
||||
|
||||
local function Enable(self, unit)
|
||||
local element = self.Portrait
|
||||
if(element) then
|
||||
element.__owner = self
|
||||
element.ForceUpdate = ForceUpdate
|
||||
|
||||
self:RegisterEvent('UNIT_PORTRAIT_UPDATE', Path)
|
||||
self:RegisterEvent('UNIT_MODEL_CHANGED', Path)
|
||||
self:RegisterEvent('UNIT_CONNECTION', Path)
|
||||
|
||||
-- The quest log uses PARTY_MEMBER_{ENABLE,DISABLE} to handle updating of
|
||||
-- party members overlapping quests. This will probably be enough to handle
|
||||
-- model updating.
|
||||
--
|
||||
-- DISABLE isn't used as it fires when we most likely don't have the
|
||||
-- information we want.
|
||||
if(unit == 'party') then
|
||||
self:RegisterEvent('PARTY_MEMBER_ENABLE', Path)
|
||||
end
|
||||
|
||||
element:Show()
|
||||
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
local function Disable(self)
|
||||
local element = self.Portrait
|
||||
if(element) then
|
||||
element:Hide()
|
||||
|
||||
self:UnregisterEvent('UNIT_PORTRAIT_UPDATE', Path)
|
||||
self:UnregisterEvent('UNIT_MODEL_CHANGED', Path)
|
||||
self:UnregisterEvent('PARTY_MEMBER_ENABLE', Path)
|
||||
self:UnregisterEvent('UNIT_CONNECTION', Path)
|
||||
end
|
||||
end
|
||||
|
||||
oUF:AddElement('Portrait', Path, Enable, Disable)
|
||||
@@ -0,0 +1,326 @@
|
||||
--[[
|
||||
# Element: Power Bar
|
||||
|
||||
Handles the updating of a status bar that displays the unit's power.
|
||||
|
||||
## Widget
|
||||
|
||||
Power - A `StatusBar` used to represent the unit's power.
|
||||
|
||||
## Sub-Widgets
|
||||
|
||||
.bg - A `Texture` used as a background. It will inherit the color of the main StatusBar.
|
||||
|
||||
## Notes
|
||||
|
||||
A default texture will be applied if the widget is a StatusBar and doesn't have a texture or a color set.
|
||||
|
||||
## Options
|
||||
|
||||
.frequentUpdates - Indicates whether to use OnUpdate script instead of UNIT_POWER to update the bar. Only valid for the
|
||||
player and pet units (boolean)
|
||||
.smoothGradient - 9 color values to be used with the .colorSmooth option (table)
|
||||
|
||||
The following options are listed by priority. The first check that returns true decides the color of the bar.
|
||||
|
||||
.colorTapping - Use `self.colors.tapping` to color the bar if the unit isn't tapped by the player (boolean)
|
||||
.colorDisconnected - Use `self.colors.disconnected` to color the bar if the unit is offline (boolean)
|
||||
.colorHappiness - Use `self.colors.happiness` to color the bar if the unit is pet based on pet happiness (boolean)
|
||||
.colorPower - Use `self.colors.power[token]` to color the bar based on the unit's power type. This method will
|
||||
fall-back to `:GetAlternativeColor()` if it can't find a color matching the token. If this function
|
||||
isn't defined, then it will attempt to color based upon the alternative power colors returned by
|
||||
[UnitPowerType](http://wowprogramming.com/docs/api/UnitPowerType). Finally, if these aren't
|
||||
defined, then it will attempt to color the bar based upon `self.colors.power[type]` (boolean)
|
||||
.colorClass - Use `self.colors.class[class]` to color the bar based on unit class. `class` is defined by the
|
||||
second return of [UnitClass](http://wowprogramming.com/docs/api/UnitClass) (boolean)
|
||||
.colorClassNPC - Use `self.colors.class[class]` to color the bar if the unit is a NPC (boolean)
|
||||
.colorClassPet - Use `self.colors.class[class]` to color the bar if the unit is player controlled, but not a player
|
||||
(boolean)
|
||||
.colorReaction - Use `self.colors.reaction[reaction]` to color the bar based on the player's reaction towards the
|
||||
unit. `reaction` is defined by the return value of
|
||||
[UnitReaction](http://wowprogramming.com/docs/api/UnitReaction) (boolean)
|
||||
.colorSmooth - Use `smoothGradient` if present or `self.colors.smooth` to color the bar with a smooth gradient
|
||||
based on the player's current power percentage (boolean)
|
||||
|
||||
## Sub-Widget Options
|
||||
|
||||
.multiplier - A multiplier used to tint the background based on the main widgets R, G and B values. Defaults to 1
|
||||
(number)[0-1]
|
||||
|
||||
## Attributes
|
||||
|
||||
.disconnected - Indicates whether the unit is disconnected (boolean)
|
||||
.tapped - Indicates whether the unit is tapped by the player (boolean)
|
||||
|
||||
## Examples
|
||||
|
||||
-- Position and size
|
||||
local Power = CreateFrame('StatusBar', nil, self)
|
||||
Power:SetHeight(20)
|
||||
Power:SetPoint('BOTTOM')
|
||||
Power:SetPoint('LEFT')
|
||||
Power:SetPoint('RIGHT')
|
||||
|
||||
-- Add a background
|
||||
local Background = Power:CreateTexture(nil, 'BACKGROUND')
|
||||
Background:SetAllPoints(Power)
|
||||
Background:SetTexture(1, 1, 1, .5)
|
||||
|
||||
-- Options
|
||||
Power.frequentUpdates = true
|
||||
Power.colorTapping = true
|
||||
Power.colorDisconnected = true
|
||||
Power.colorPower = true
|
||||
Power.colorClass = true
|
||||
Power.colorReaction = true
|
||||
|
||||
-- Make the background darker.
|
||||
Background.multiplier = .5
|
||||
|
||||
-- Register it with oUF
|
||||
Power.bg = Background
|
||||
self.Power = Power
|
||||
--]]
|
||||
|
||||
local ns = oUF
|
||||
local oUF = ns.oUF
|
||||
|
||||
local unpack = unpack
|
||||
|
||||
local GetPetHappiness = GetPetHappiness
|
||||
local UnitClass = UnitClass
|
||||
local UnitIsConnected = UnitIsConnected
|
||||
local UnitIsPlayer = UnitIsPlayer
|
||||
local UnitIsTapped = UnitIsTapped
|
||||
local UnitIsTappedByPlayer = UnitIsTappedByPlayer
|
||||
local UnitIsUnit = UnitIsUnit
|
||||
local UnitMana = UnitMana
|
||||
local UnitManaMax = UnitManaMax
|
||||
local UnitPlayerControlled = UnitPlayerControlled
|
||||
local UnitPowerType = UnitPowerType
|
||||
local UnitReaction = UnitReaction
|
||||
|
||||
local updateFrequentUpdates
|
||||
|
||||
local function UpdateColor(element, unit, cur, min, max)
|
||||
local parent = element.__owner
|
||||
|
||||
if element.frequentUpdates ~= element.__frequentUpdates then
|
||||
element.__frequentUpdates = element.frequentUpdates
|
||||
updateFrequentUpdates(element, unit)
|
||||
end
|
||||
|
||||
local ptype = UnitPowerType(unit)
|
||||
local r, g, b, t
|
||||
if(element.colorTapping and element.tapped) then
|
||||
t = parent.colors.tapped
|
||||
elseif(element.colorDisconnected and element.disconnected) then
|
||||
t = parent.colors.disconnected
|
||||
elseif(element.colorHappiness and UnitIsUnit(unit, 'pet') and GetPetHappiness()) then
|
||||
t = parent.colors.happiness[GetPetHappiness()]
|
||||
elseif(element.colorPower) then
|
||||
t = parent.colors.power[ptype]
|
||||
elseif(element.colorClass and UnitIsPlayer(unit)) or
|
||||
(element.colorClassNPC and not UnitIsPlayer(unit)) or
|
||||
(element.colorClassPet and UnitPlayerControlled(unit) and not UnitIsPlayer(unit)) then
|
||||
local _, class = UnitClass(unit)
|
||||
t = parent.colors.class[class]
|
||||
elseif(element.colorReaction and UnitReaction(unit, 'player')) then
|
||||
t = parent.colors.reaction[UnitReaction(unit, 'player')]
|
||||
elseif(element.colorSmooth) then
|
||||
local adjust = 0 - (min or 0)
|
||||
r, g, b = parent.ColorGradient(cur + adjust, max + adjust, unpack(element.smoothGradient or parent.colors.smooth))
|
||||
end
|
||||
|
||||
if(t) then
|
||||
r, g, b = t[1], t[2], t[3]
|
||||
end
|
||||
|
||||
t = parent.colors.power[ptype]
|
||||
|
||||
element:SetStatusBarTexture(element.texture)
|
||||
|
||||
if(r or g or b) then
|
||||
element:SetStatusBarColor(r, g, b)
|
||||
end
|
||||
|
||||
local bg = element.bg
|
||||
if(bg and b) then
|
||||
local mu = bg.multiplier or 1
|
||||
bg:SetVertexColor(r * mu, g * mu, b * mu)
|
||||
end
|
||||
end
|
||||
|
||||
local function Update(self, event, unit)
|
||||
if(self.unit ~= unit) then return end
|
||||
local element = self.Power
|
||||
|
||||
--[[ Callback: Power:PreUpdate(unit)
|
||||
Called before the element has been updated.
|
||||
|
||||
* self - the Power element
|
||||
* unit - the unit for which the update has been triggered (string)
|
||||
--]]
|
||||
if(element.PreUpdate) then
|
||||
element:PreUpdate(unit)
|
||||
end
|
||||
|
||||
local cur, max = UnitMana(unit), UnitManaMax(unit)
|
||||
local disconnected = not UnitIsConnected(unit)
|
||||
local tapped = not UnitPlayerControlled(unit) and (UnitIsTapped(unit) and not UnitIsTappedByPlayer(unit))
|
||||
element:SetMinMaxValues(0, max)
|
||||
|
||||
if(disconnected) then
|
||||
element:SetValue(max)
|
||||
else
|
||||
element:SetValue(cur)
|
||||
end
|
||||
|
||||
element.disconnected = disconnected
|
||||
element.tapped = tapped
|
||||
|
||||
--[[ Override: Power:UpdateColor(unit, cur, max)
|
||||
Used to completely override the internal function for updating the widget's colors.
|
||||
|
||||
* self - the Power element
|
||||
* unit - the unit for which the update has been triggered (string)
|
||||
* cur - the unit's current power value (number)
|
||||
* max - the unit's maximum possible power value (number)
|
||||
--]]
|
||||
element:UpdateColor(unit, cur, max)
|
||||
|
||||
--[[ Callback: Power:PostUpdate(unit, cur, max)
|
||||
Called after the element has been updated.
|
||||
|
||||
* self - the Power element
|
||||
* unit - the unit for which the update has been triggered (string)
|
||||
* cur - the unit's current power value (number)
|
||||
* max - the unit's maximum possible power value (number)
|
||||
--]]
|
||||
if(element.PostUpdate) then
|
||||
return element:PostUpdate(unit, cur, max)
|
||||
end
|
||||
end
|
||||
|
||||
local function Path(self, ...)
|
||||
--[[ Override: Power.Override(self, event, unit, ...)
|
||||
Used to completely override the internal update function.
|
||||
|
||||
* self - the parent object
|
||||
* event - the event triggering the update (string)
|
||||
* unit - the unit accompanying the event (string)
|
||||
* ... - the arguments accompanying the event
|
||||
--]]
|
||||
return (self.Power.Override or Update) (self, unpack(arg))
|
||||
end
|
||||
|
||||
local function ForceUpdate(element)
|
||||
return Path(element.__owner, 'ForceUpdate', element.__owner.unit)
|
||||
end
|
||||
|
||||
local function onPowerUpdate()
|
||||
if(this.disconnected) then return end
|
||||
|
||||
local unit = this.__owner.unit
|
||||
local power = UnitMana(unit)
|
||||
|
||||
if(power ~= this.min) then
|
||||
this.min = power
|
||||
|
||||
return Path(this.__owner, 'OnPowerUpdate', unit)
|
||||
end
|
||||
end
|
||||
|
||||
function updateFrequentUpdates(self, unit)
|
||||
if(not unit or (unit ~= 'player' and unit ~= 'pet')) then return end
|
||||
|
||||
local element = self.Power
|
||||
if(element.frequentUpdates and not element:GetScript('OnUpdate')) then
|
||||
element:SetScript('OnUpdate', onPowerUpdate)
|
||||
|
||||
self:UnregisterEvent('UNIT_MANA', Path)
|
||||
self:UnregisterEvent('UNIT_RAGE', Path)
|
||||
self:UnregisterEvent('UNIT_FOCUS', Path)
|
||||
self:UnregisterEvent('UNIT_ENERGY', Path)
|
||||
elseif(not element.frequentUpdates and element:GetScript('OnUpdate')) then
|
||||
element:SetScript('OnUpdate', nil)
|
||||
|
||||
self:RegisterEvent('UNIT_MANA', Path)
|
||||
self:RegisterEvent('UNIT_RAGE', Path)
|
||||
self:RegisterEvent('UNIT_FOCUS', Path)
|
||||
self:RegisterEvent('UNIT_ENERGY', Path)
|
||||
end
|
||||
end
|
||||
|
||||
local function Enable(self, unit)
|
||||
local element = self.Power
|
||||
if(element) then
|
||||
element.__owner = self
|
||||
element.ForceUpdate = ForceUpdate
|
||||
element.__frequentUpdates = element.frequentUpdates
|
||||
updateFrequentUpdates(self, unit)
|
||||
|
||||
if(element.frequentUpdates and (unit == 'player' or unit == 'pet')) then
|
||||
element:SetScript('OnUpdate', onPowerUpdate)
|
||||
else
|
||||
self:RegisterEvent('UNIT_MANA', Path)
|
||||
self:RegisterEvent('UNIT_RAGE', Path)
|
||||
self:RegisterEvent('UNIT_FOCUS', Path)
|
||||
self:RegisterEvent('UNIT_ENERGY', Path)
|
||||
end
|
||||
|
||||
self:RegisterEvent('UNIT_MAXMANA', Path)
|
||||
self:RegisterEvent('UNIT_MAXRAGE', Path)
|
||||
self:RegisterEvent('UNIT_MAXFOCUS', Path)
|
||||
self:RegisterEvent('UNIT_MAXENERGY', Path)
|
||||
self:RegisterEvent('UNIT_MAXRUNIC_POWER', Path)
|
||||
self:RegisterEvent('UNIT_DISPLAYPOWER', Path)
|
||||
|
||||
self:RegisterEvent('UNIT_CONNECTION', Path)
|
||||
self:RegisterEvent('UNIT_HAPPINESS', Path)
|
||||
self:RegisterEvent('UNIT_FACTION', Path) -- For tapping
|
||||
|
||||
if(element:IsObjectType('StatusBar')) then
|
||||
element.texture = element:GetStatusBarTexture() and element:GetStatusBarTexture():GetTexture() or [[Interface\TargetingFrame\UI-StatusBar]]
|
||||
element:SetStatusBarTexture(element.texture)
|
||||
end
|
||||
|
||||
if(not element.UpdateColor) then
|
||||
element.UpdateColor = UpdateColor
|
||||
end
|
||||
|
||||
element:Show()
|
||||
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
local function Disable(self)
|
||||
local element = self.Power
|
||||
if(element) then
|
||||
element:Hide()
|
||||
|
||||
if(element:GetScript('OnUpdate')) then
|
||||
element:SetScript('OnUpdate', nil)
|
||||
else
|
||||
self:UnregisterEvent('UNIT_MANA', Path)
|
||||
self:UnregisterEvent('UNIT_RAGE', Path)
|
||||
self:UnregisterEvent('UNIT_FOCUS', Path)
|
||||
self:UnregisterEvent('UNIT_ENERGY', Path)
|
||||
self:UnregisterEvent('UNIT_RUNIC_POWER', Path)
|
||||
end
|
||||
|
||||
self:UnregisterEvent('UNIT_MAXMANA', Path)
|
||||
self:UnregisterEvent('UNIT_MAXRAGE', Path)
|
||||
self:UnregisterEvent('UNIT_MAXFOCUS', Path)
|
||||
self:UnregisterEvent('UNIT_MAXENERGY', Path)
|
||||
self:UnregisterEvent('UNIT_MAXRUNIC_POWER', Path)
|
||||
self:UnregisterEvent('UNIT_DISPLAYPOWER', Path)
|
||||
|
||||
self:UnregisterEvent('UNIT_CONNECTION', Path)
|
||||
self:UnregisterEvent('UNIT_HAPPINESS', Path)
|
||||
self:UnregisterEvent('UNIT_FACTION', Path)
|
||||
end
|
||||
end
|
||||
|
||||
oUF:AddElement('Power', Path, Enable, Disable)
|
||||
@@ -0,0 +1,118 @@
|
||||
--[[
|
||||
# Element: PvP Icon
|
||||
|
||||
Handles the visibility and updating of an indicator based on the unit's PvP status.
|
||||
|
||||
## Widget
|
||||
|
||||
PvPIndicator - A `Texture` used to display faction, FFA PvP status icon.
|
||||
|
||||
## Notes
|
||||
|
||||
This element updates by changing the texture.
|
||||
|
||||
## Examples
|
||||
|
||||
-- Position and size
|
||||
local PvPIndicator = self:CreateTexture(nil, 'ARTWORK', nil, 1)
|
||||
PvPIndicator:SetSize(30, 30)
|
||||
PvPIndicator:SetPoint('RIGHT', self, 'LEFT')
|
||||
|
||||
-- Register it with oUF
|
||||
self.PvPIndicator = PvPIndicator
|
||||
--]]
|
||||
|
||||
local ns = oUF
|
||||
local oUF = ns.oUF
|
||||
|
||||
local UnitFactionGroup = UnitFactionGroup
|
||||
local UnitIsPVP = UnitIsPVP
|
||||
local UnitIsPVPFreeForAll = UnitIsPVPFreeForAll
|
||||
|
||||
local FFA_ICON = [[Interface\TargetingFrame\UI-PVP-FFA]]
|
||||
local FACTION_ICON = [[Interface\TargetingFrame\UI-PVP-]]
|
||||
|
||||
local function Update(self, event, unit)
|
||||
if(unit ~= self.unit) then return end
|
||||
|
||||
local element = self.PvPIndicator
|
||||
|
||||
--[[ Callback: PvPIndicator:PreUpdate(unit)
|
||||
Called before the element has been updated.
|
||||
|
||||
* self - the PvPIndicator element
|
||||
* unit - the unit for which the update has been triggered (string)
|
||||
--]]
|
||||
if(element.PreUpdate) then
|
||||
element:PreUpdate(unit)
|
||||
end
|
||||
|
||||
local status
|
||||
local factionGroup = UnitFactionGroup(unit)
|
||||
|
||||
if(UnitIsPVPFreeForAll(unit)) then
|
||||
element:SetTexture(FFA_ICON)
|
||||
element:SetTexCoord(0, 0.65625, 0, 0.65625)
|
||||
status = 'ffa'
|
||||
elseif(factionGroup and factionGroup ~= 'Neutral' and UnitIsPVP(unit)) then
|
||||
element:SetTexture(FACTION_ICON .. factionGroup)
|
||||
element:SetTexCoord(0, 0.65625, 0, 0.65625)
|
||||
status = factionGroup
|
||||
end
|
||||
|
||||
if(status) then
|
||||
element:Show()
|
||||
else
|
||||
element:Hide()
|
||||
end
|
||||
|
||||
--[[ Callback: PvPIndicator:PostUpdate(unit, status)
|
||||
Called after the element has been updated.
|
||||
|
||||
* self - the PvPIndicator element
|
||||
* unit - the unit for which the update has been triggered (string)
|
||||
* status - the unit's current PvP status or faction accounting for mercenary mode (string)['ffa', 'Alliance',
|
||||
'Horde']
|
||||
--]]
|
||||
if(element.PostUpdate) then
|
||||
return element:PostUpdate(unit, status)
|
||||
end
|
||||
end
|
||||
|
||||
local function Path(self, ...)
|
||||
--[[Override: PvPIndicator.Override(self, event, ...)
|
||||
Used to completely override the internal update function.
|
||||
|
||||
* self - the parent object
|
||||
* event - the event triggering the update (string)
|
||||
* ... - the arguments accompanying the event
|
||||
--]]
|
||||
return (self.PvPIndicator.Override or Update) (self, ...)
|
||||
end
|
||||
|
||||
local function ForceUpdate(element)
|
||||
return Path(element.__owner, 'ForceUpdate', element.__owner.unit)
|
||||
end
|
||||
|
||||
local function Enable(self)
|
||||
local element = self.PvPIndicator
|
||||
if(element) then
|
||||
element.__owner = self
|
||||
element.ForceUpdate = ForceUpdate
|
||||
|
||||
self:RegisterEvent('UNIT_FACTION', Path)
|
||||
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
local function Disable(self)
|
||||
local element = self.PvPIndicator
|
||||
if(element) then
|
||||
element:Hide()
|
||||
|
||||
self:UnregisterEvent('UNIT_FACTION', Path)
|
||||
end
|
||||
end
|
||||
|
||||
oUF:AddElement('PvPIndicator', Path, Enable, Disable)
|
||||
@@ -0,0 +1,114 @@
|
||||
--[[
|
||||
# Element: Raid Role Indicator
|
||||
|
||||
Handles the visibility and updating of an indicator based on the unit's raid assignment (main tank or main assist).
|
||||
|
||||
## Widget
|
||||
|
||||
RaidRoleIndicator - A `Texture` representing the unit's raid assignment.
|
||||
|
||||
## Notes
|
||||
|
||||
This element updates by changing the texture.
|
||||
|
||||
## Examples
|
||||
|
||||
-- Position and size
|
||||
local RaidRoleIndicator = self:CreateTexture(nil, 'OVERLAY')
|
||||
RaidRoleIndicator:SetSize(16, 16)
|
||||
RaidRoleIndicator:SetPoint('TOPLEFT')
|
||||
|
||||
-- Register it with oUF
|
||||
self.RaidRoleIndicator = RaidRoleIndicator
|
||||
--]]
|
||||
|
||||
local ns = oUF
|
||||
local oUF = ns.oUF
|
||||
|
||||
local GetPartyAssignment = GetPartyAssignment
|
||||
local UnitInRaid = UnitInRaid
|
||||
|
||||
local MAINTANK_ICON = [[Interface\GROUPFRAME\UI-GROUP-MAINTANKICON]]
|
||||
local MAINASSIST_ICON = [[Interface\GROUPFRAME\UI-GROUP-MAINASSISTICON]]
|
||||
|
||||
local function Update(self, event)
|
||||
local unit = self.unit
|
||||
|
||||
local element = self.RaidRoleIndicator
|
||||
|
||||
--[[ Callback: RaidRoleIndicator:PreUpdate()
|
||||
Called before the element has been updated.
|
||||
|
||||
* self - the RaidRoleIndicator element
|
||||
--]]
|
||||
if(element.PreUpdate) then
|
||||
element:PreUpdate()
|
||||
end
|
||||
|
||||
local role, isShown
|
||||
if(UnitInRaid(unit)) then
|
||||
if(GetPartyAssignment('MAINTANK', unit)) then
|
||||
isShown = true
|
||||
element:SetTexture(MAINTANK_ICON)
|
||||
role = 'MAINTANK'
|
||||
elseif(GetPartyAssignment('MAINASSIST', unit)) then
|
||||
isShown = true
|
||||
element:SetTexture(MAINASSIST_ICON)
|
||||
role = 'MAINASSIST'
|
||||
end
|
||||
end
|
||||
|
||||
if isShown then
|
||||
element:Show()
|
||||
else
|
||||
element:Hide()
|
||||
end
|
||||
|
||||
--[[ Callback: RaidRoleIndicator:PostUpdate(role)
|
||||
Called after the element has been updated.
|
||||
|
||||
* self - the RaidRoleIndicator element
|
||||
* role - the unit's raid assignment (string?)['MAINTANK', 'MAINASSIST']
|
||||
--]]
|
||||
if(element.PostUpdate) then
|
||||
return element:PostUpdate(role)
|
||||
end
|
||||
end
|
||||
|
||||
local function Path(self, ...)
|
||||
--[[ Override: RaidRoleIndicator.Override(self, event, ...)
|
||||
Used to completely override the internal update function.
|
||||
|
||||
* self - the parent object
|
||||
* event - the event triggering the update (string)
|
||||
* ... - the arguments accompanying the event
|
||||
--]]
|
||||
return (self.RaidRoleIndicator.Override or Update)(self, ...)
|
||||
end
|
||||
|
||||
local function ForceUpdate(element)
|
||||
return Path(element.__owner, 'ForceUpdate')
|
||||
end
|
||||
|
||||
local function Enable(self)
|
||||
local element = self.RaidRoleIndicator
|
||||
if(element) then
|
||||
element.__owner = self
|
||||
element.ForceUpdate = ForceUpdate
|
||||
|
||||
self:RegisterEvent('PARTY_MEMBERS_CHANGED', Path, true)
|
||||
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
local function Disable(self)
|
||||
local element = self.RaidRoleIndicator
|
||||
if(element) then
|
||||
element:Hide()
|
||||
|
||||
self:UnregisterEvent('PARTY_MEMBERS_CHANGED', Path)
|
||||
end
|
||||
end
|
||||
|
||||
oUF:AddElement('RaidRoleIndicator', Path, Enable, Disable)
|
||||
@@ -0,0 +1,102 @@
|
||||
--[[
|
||||
# Element: Raid Target Indicator
|
||||
|
||||
Handles the visibility and updating of an indicator based on the unit's raid target assignment.
|
||||
|
||||
## Widget
|
||||
|
||||
RaidTargetIndicator - A `Texture` used to display the raid target icon.
|
||||
|
||||
## Notes
|
||||
|
||||
A default texture will be applied if the widget is a Texture and doesn't have a texture set.
|
||||
|
||||
## Examples
|
||||
|
||||
-- Position and size
|
||||
local RaidTargetIndicator = self:CreateTexture(nil, 'OVERLAY')
|
||||
RaidTargetIndicator:SetSize(16, 16)
|
||||
RaidTargetIndicator:SetPoint('TOPRIGHT', self)
|
||||
|
||||
-- Register it with oUF
|
||||
self.RaidTargetIndicator = RaidTargetIndicator
|
||||
--]]
|
||||
|
||||
local ns = oUF
|
||||
local oUF = ns.oUF
|
||||
|
||||
local GetRaidTargetIndex = GetRaidTargetIndex
|
||||
local SetRaidTargetIconTexture = SetRaidTargetIconTexture
|
||||
|
||||
local function Update(self, event)
|
||||
local element = self.RaidTargetIndicator
|
||||
|
||||
--[[ Callback: RaidTargetIndicator:PreUpdate()
|
||||
Called before the element has been updated.
|
||||
|
||||
* self - the RaidTargetIndicator element
|
||||
--]]
|
||||
if(element.PreUpdate) then
|
||||
element:PreUpdate()
|
||||
end
|
||||
|
||||
local index = GetRaidTargetIndex(self.unit)
|
||||
if(index) then
|
||||
SetRaidTargetIconTexture(element, index)
|
||||
element:Show()
|
||||
else
|
||||
element:Hide()
|
||||
end
|
||||
|
||||
--[[ Callback: RaidTargetIndicator:PostUpdate(index)
|
||||
Called after the element has been updated.
|
||||
|
||||
* self - the RaidTargetIndicator element
|
||||
* index - the index of the raid target marker (number?)[1-8]
|
||||
--]]
|
||||
if(element.PostUpdate) then
|
||||
return element:PostUpdate(index)
|
||||
end
|
||||
end
|
||||
|
||||
local function Path(self, ...)
|
||||
--[[ Override: RaidTargetIndicator.Override(self, event)
|
||||
Used to completely override the internal update function.
|
||||
|
||||
* self - the parent object
|
||||
* event - the event triggering the update (string)
|
||||
--]]
|
||||
return (self.RaidTargetIndicator.Override or Update) (self, unpack(arg))
|
||||
end
|
||||
|
||||
local function ForceUpdate(element)
|
||||
if(not element.__owner.unit) then return end
|
||||
return Path(element.__owner, 'ForceUpdate')
|
||||
end
|
||||
|
||||
local function Enable(self)
|
||||
local element = self.RaidTargetIndicator
|
||||
if(element) then
|
||||
element.__owner = self
|
||||
element.ForceUpdate = ForceUpdate
|
||||
|
||||
self:RegisterEvent('RAID_TARGET_UPDATE', Path, true)
|
||||
|
||||
if(element:IsObjectType('Texture') and not element:GetTexture()) then
|
||||
element:SetTexture([[Interface\TargetingFrame\UI-RaidTargetingIcons]])
|
||||
end
|
||||
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
local function Disable(self)
|
||||
local element = self.RaidTargetIndicator
|
||||
if(element) then
|
||||
element:Hide()
|
||||
|
||||
self:UnregisterEvent('RAID_TARGET_UPDATE', Path)
|
||||
end
|
||||
end
|
||||
|
||||
oUF:AddElement('RaidTargetIndicator', Path, Enable, Disable)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user