/trunk
-- |
-- 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! :-) |
-- |
local CTL_VERSION = 21 |
local _G = _G |
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 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 |
----------------------------------------------------------------------- |
-- 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, which also happens to be a ring member |
ChatThrottleLib.PipeBin = nil -- pre-v19, drastically different |
local PipeBin = setmetatable({}, {__mode="k"}) |
local function DelPipe(pipe) |
for i = #pipe, 1, -1 do |
pipe[i] = nil |
end |
pipe.prev = nil |
pipe.next = nil |
PipeBin[pipe] = true |
end |
local function NewPipe() |
local pipe = next(PipeBin) |
if pipe then |
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(...) |
return ChatThrottleLib.Hook_SendChatMessage(...) |
end) |
--SendAddonMessage |
hooksecurefunc("SendAddonMessage", function(...) |
return ChatThrottleLib.Hook_SendAddonMessage(...) |
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 = tostring(text or ""):len() + tostring(prefix or ""):len(); |
size = size + tostring(destination or ""):len() + 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 |
function ChatThrottleLib:Despool(Prio) |
local ring = Prio.Ring |
while ring.pos and Prio.avail > ring.pos[1].nSize do |
local msg = table_remove(Prio.Ring.pos, 1) |
if not Prio.Ring.pos[1] then |
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 |
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) |
if msg.callbackFn then |
msg.callbackFn (msg.callbackArg) |
end |
end |
end |
function ChatThrottleLib.OnEvent(this,event) |
-- 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(this,delay) |
local self = ChatThrottleLib |
self.OnUpdateDelay = self.OnUpdateDelay + delay |
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 |
pipe[#pipe + 1] = 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 = text:len() |
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) |
end |
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 = prefix:len() + 1 + text:len(); |
if nSize>255 then |
error("ChatThrottleLib:SendAddonMessage(): prefix + message length cannot exceed 254 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.SendAddonMessage(prefix, text, chattype, target) |
bMyTraffic = false |
self.Prio[prio].nTotalSent = self.Prio[prio].nTotalSent + nSize |
if callbackFn then |
callbackFn (callbackArg) |
end |
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 |
]] |
<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="ChatThrottleLib.lua"/> |
<Script file="AceComm-3.0.lua"/> |
</Ui> |
--- **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 895 2009-12-06 16:28:55Z 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", 6 |
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 strsub, strfind = string.sub, string.find |
local tinsert, tconcat = table.insert, table.concat |
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 |
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" |
AceComm.multipart_origprefixes = AceComm.multipart_origprefixes or {} -- e.g. "Prefix\001"="Prefix", "Prefix\002"="Prefix" |
AceComm.multipart_reassemblers = AceComm.multipart_reassemblers or {} -- e.g. "Prefix\001"="OnReceiveMultipartFirst" |
-- 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) |
-- @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 |
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 |
if strfind(prefix, "[\001-\009]") then |
if strfind(prefix, "[\001-\003]") then |
error("SendCommMessage: Characters \\001--\\003 in prefix are reserved for AceComm metadata", 2) |
elseif not warnedPrefix then |
-- I have some ideas about future extensions that require more control characters /mikk, 20090808 |
geterrorhandler()("SendCommMessage: Heads-up developers: Characters \\004--\\009 in prefix are reserved for AceComm future extension") |
warnedPrefix = true |
end |
end |
local textlen = #text |
local maxtextlen = 254 - #prefix -- 254 is the max length of prefix + text that can be sent in one message |
local queueName = prefix..distribution..(target or "") |
local ctlCallback = nil |
if callbackFn then |
ctlCallback = function(sent) |
return callbackFn(callbackArg, sent, textlen) |
end |
end |
if 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 |
-- 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 |
local prefix2 = prefix..MSG_MULTI_NEXT |
while pos+maxtextlen <= textlen do |
chunk = strsub(text, pos, pos+maxtextlen-1) |
CTL:SendAddonMessage(prio, prefix2, 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=#t,3,-1 do -- faster than pairs loop. don't even nil out 1/2 since they'll be overwritten |
t[i]=nil |
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, 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, olddata..message, distribution, sender) |
end |
end |
end |
---------------------------------------- |
-- Embed CallbackHandler |
---------------------------------------- |
if not AceComm.callbacks then |
-- ensure that 'prefix to watch' table is consistent with registered |
-- callbacks |
AceComm.__prefixes = {} |
AceComm.callbacks = CallbackHandler:New(AceComm, |
"_RegisterComm", |
"UnregisterComm", |
"UnregisterAllComm") |
end |
function AceComm.callbacks:OnUsed(target, prefix) |
AceComm.multipart_origprefixes[prefix..MSG_MULTI_FIRST] = prefix |
AceComm.multipart_reassemblers[prefix..MSG_MULTI_FIRST] = "OnReceiveMultipartFirst" |
AceComm.multipart_origprefixes[prefix..MSG_MULTI_NEXT] = prefix |
AceComm.multipart_reassemblers[prefix..MSG_MULTI_NEXT] = "OnReceiveMultipartNext" |
AceComm.multipart_origprefixes[prefix..MSG_MULTI_LAST] = prefix |
AceComm.multipart_reassemblers[prefix..MSG_MULTI_LAST] = "OnReceiveMultipartLast" |
end |
function AceComm.callbacks:OnUnused(target, prefix) |
AceComm.multipart_origprefixes[prefix..MSG_MULTI_FIRST] = nil |
AceComm.multipart_reassemblers[prefix..MSG_MULTI_FIRST] = nil |
AceComm.multipart_origprefixes[prefix..MSG_MULTI_NEXT] = nil |
AceComm.multipart_reassemblers[prefix..MSG_MULTI_NEXT] = nil |
AceComm.multipart_origprefixes[prefix..MSG_MULTI_LAST] = nil |
AceComm.multipart_reassemblers[prefix..MSG_MULTI_LAST] = nil |
end |
local function OnEvent(this, event, ...) |
if event == "CHAT_MSG_ADDON" then |
local prefix,message,distribution,sender = ... |
local reassemblername = AceComm.multipart_reassemblers[prefix] |
if reassemblername then |
-- multipart: reassemble |
local aceCommReassemblerFunc = AceComm[reassemblername] |
local origprefix = AceComm.multipart_origprefixes[prefix] |
aceCommReassemblerFunc(AceComm, origprefix, message, distribution, sender) |
else |
-- single part: fire it off immediately and let CallbackHandler decide if it's registered or not |
AceComm.callbacks:Fire(prefix, 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 |
<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="AceDBOptions-3.0.lua"/> |
</Ui> |
--- AceDBOptions-3.0 provides a universal AceConfig options screen for managing AceDB-3.0 profiles. |
-- @class file |
-- @name AceDBOptions-3.0 |
-- @release $Id: AceDBOptions-3.0.lua 895 2009-12-06 16:28:55Z nevcairiel $ |
local ACEDBO_MAJOR, ACEDBO_MINOR = "AceDBOptions-3.0", 11 |
local AceDBOptions, oldminor = LibStub:NewLibrary(ACEDBO_MAJOR, ACEDBO_MINOR) |
if not AceDBOptions then return end -- No upgrade needed |
-- Lua APIs |
local pairs, next = pairs, next |
-- WoW APIs |
local UnitClass = UnitClass |
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded |
-- List them here for Mikk's FindGlobals script |
-- GLOBALS: NORMAL_FONT_COLOR_CODE, FONT_COLOR_CODE_CLOSE |
AceDBOptions.optionTables = AceDBOptions.optionTables or {} |
AceDBOptions.handlers = AceDBOptions.handlers or {} |
--[[ |
Localization of AceDBOptions-3.0 |
]] |
local L = { |
default = "Default", |
intro = "You can change the active database profile, so you can have different settings for every character.", |
reset_desc = "Reset the current profile back to its default values, in case your configuration is broken, or you simply want to start over.", |
reset = "Reset Profile", |
reset_sub = "Reset the current profile to the default", |
choose_desc = "You can either create a new profile by entering a name in the editbox, or choose one of the already exisiting profiles.", |
new = "New", |
new_sub = "Create a new empty profile.", |
choose = "Existing Profiles", |
choose_sub = "Select one of your currently available profiles.", |
copy_desc = "Copy the settings from one existing profile into the currently active profile.", |
copy = "Copy From", |
delete_desc = "Delete existing and unused profiles from the database to save space, and cleanup the SavedVariables file.", |
delete = "Delete a Profile", |
delete_sub = "Deletes a profile from the database.", |
delete_confirm = "Are you sure you want to delete the selected profile?", |
profiles = "Profiles", |
profiles_sub = "Manage Profiles", |
current = "Current Profile:", |
} |
local LOCALE = GetLocale() |
if LOCALE == "deDE" then |
L["default"] = "Standard" |
L["intro"] = "Hier kannst du das aktive Datenbankprofile \195\164ndern, damit du verschiedene Einstellungen f\195\188r jeden Charakter erstellen kannst, wodurch eine sehr flexible Konfiguration m\195\182glich wird." |
L["reset_desc"] = "Setzt das momentane Profil auf Standardwerte zur\195\188ck, f\195\188r den Fall das mit der Konfiguration etwas schief lief oder weil du einfach neu starten willst." |
L["reset"] = "Profil zur\195\188cksetzen" |
L["reset_sub"] = "Das aktuelle Profil auf Standard zur\195\188cksetzen." |
L["choose_desc"] = "Du kannst ein neues Profil erstellen, indem du einen neuen Namen in der Eingabebox 'Neu' eingibst, oder w\195\164hle eines der vorhandenen Profile aus." |
L["new"] = "Neu" |
L["new_sub"] = "Ein neues Profil erstellen." |
L["choose"] = "Vorhandene Profile" |
L["choose_sub"] = "W\195\164hlt ein bereits vorhandenes Profil aus." |
L["copy_desc"] = "Kopiere die Einstellungen von einem vorhandenen Profil in das aktive Profil." |
L["copy"] = "Kopieren von..." |
L["delete_desc"] = "L\195\182sche vorhandene oder unbenutzte Profile aus der Datenbank um Platz zu sparen und um die SavedVariables Datei 'sauber' zu halten." |
L["delete"] = "Profil l\195\182schen" |
L["delete_sub"] = "L\195\182scht ein Profil aus der Datenbank." |
L["delete_confirm"] = "Willst du das ausgew\195\164hlte Profil wirklich l\195\182schen?" |
L["profiles"] = "Profile" |
L["profiles_sub"] = "Profile verwalten" |
--L["current"] = "Current Profile:" |
elseif LOCALE == "frFR" then |
L["default"] = "D\195\169faut" |
L["intro"] = "Vous pouvez changer le profil actuel afin d'avoir des param\195\168tres diff\195\169rents pour chaque personnage, permettant ainsi d'avoir une configuration tr\195\168s flexible." |
L["reset_desc"] = "R\195\169initialise le profil actuel au cas o\195\185 votre configuration est corrompue ou si vous voulez tout simplement faire table rase." |
L["reset"] = "R\195\169initialiser le profil" |
L["reset_sub"] = "R\195\169initialise le profil actuel avec les param\195\168tres par d\195\169faut." |
L["choose_desc"] = "Vous pouvez cr\195\169er un nouveau profil en entrant un nouveau nom dans la bo\195\174te de saisie, ou en choississant un des profils d\195\169j\195\160 existants." |
L["new"] = "Nouveau" |
L["new_sub"] = "Cr\195\169\195\169e un nouveau profil vierge." |
L["choose"] = "Profils existants" |
L["choose_sub"] = "Permet de choisir un des profils d\195\169j\195\160 disponibles." |
L["copy_desc"] = "Copie les param\195\168tres d'un profil d\195\169j\195\160 existant dans le profil actuellement actif." |
L["copy"] = "Copier \195\160 partir de" |
L["delete_desc"] = "Supprime les profils existants inutilis\195\169s de la base de donn\195\169es afin de gagner de la place et de nettoyer le fichier SavedVariables." |
L["delete"] = "Supprimer un profil" |
L["delete_sub"] = "Supprime un profil de la base de donn\195\169es." |
L["delete_confirm"] = "Etes-vous s\195\187r de vouloir supprimer le profil s\195\169lectionn\195\169 ?" |
L["profiles"] = "Profils" |
L["profiles_sub"] = "Gestion des profils" |
--L["current"] = "Current Profile:" |
elseif LOCALE == "koKR" then |
L["default"] = "기본ê°" |
L["intro"] = "모ë ìºë¦í°ì ë¤ìí ì¤ì ê³¼ ì¬ì©ì¤ì¸ ë°ì´í°ë² ì´ì¤ íë¡í, ì´ëê²ì´ëì§ ë§¤ì° ë¤ë£¨ê¸° ì½ê² ë°ê¿ì ììµëë¤." |
L["reset_desc"] = "ë¨ìí ë¤ì ìë¡ê² 구ì±ì ìíë ê²½ì°, íì¬ íë¡íì 기본ê°ì¼ë¡ ì´ê¸°í í©ëë¤." |
L["reset"] = "íë¡í ì´ê¸°í" |
L["reset_sub"] = "íì¬ì íë¡íì 기본ê°ì¼ë¡ ì´ê¸°í í©ëë¤" |
L["choose_desc"] = "ìë¡ì´ ì´ë¦ì ì ë ¥íê±°ë, ì´ë¯¸ ìë íë¡íì¤ íë를 ì ííì¬ ìë¡ì´ íë¡íì ë§ë¤ ì ììµëë¤." |
L["new"] = "ìë¡ì´ íë¡í" |
L["new_sub"] = "ìë¡ì´ íë¡íì ë§ëëë¤." |
L["choose"] = "íë¡í ì í" |
L["choose_sub"] = "ë¹ì ì´ íì¬ ì´ì©í ì ìë íë¡íì ì íí©ëë¤." |
L["copy_desc"] = "íì¬ ì¬ì©ì¤ì¸ íë¡íì, ì íí íë¡íì ì¤ì ì ë³µì¬í©ëë¤." |
L["copy"] = "ë³µì¬" |
L["delete_desc"] = "ë°ì´í°ë² ì´ì¤ì ì¬ì©ì¤ì´ê±°ë ì ì¥ë íë¡íì¼ ìì ë¡ SavedVariables íì¼ì ì 리ì ê³µê° ì ì½ì´ ë©ëë¤." |
L["delete"] = "íë¡í ìì " |
L["delete_sub"] = "ë°ì´í°ë² ì´ì¤ì íë¡íì ìì í©ëë¤." |
L["delete_confirm"] = "ì ë§ë¡ ì íí íë¡íì ìì 를 ìíìëê¹?" |
L["profiles"] = "íë¡í" |
L["profiles_sub"] = "íë¡í ì¤ì " |
--L["current"] = "Current Profile:" |
elseif LOCALE == "esES" or LOCALE == "esMX" then |
L["default"] = "Por defecto" |
L["intro"] = "Puedes cambiar el perfil activo de tal manera que cada personaje tenga diferentes configuraciones." |
L["reset_desc"] = "Reinicia el perfil actual a los valores por defectos, en caso de que se haya estropeado la configuración o quieras volver a empezar de nuevo." |
L["reset"] = "Reiniciar Perfil" |
L["reset_sub"] = "Reinicar el perfil actual al de por defecto" |
L["choose_desc"] = "Puedes crear un nuevo perfil introduciendo un nombre en el recuadro o puedes seleccionar un perfil de los ya existentes." |
L["new"] = "Nuevo" |
L["new_sub"] = "Crear un nuevo perfil vacio." |
L["choose"] = "Perfiles existentes" |
L["choose_sub"] = "Selecciona uno de los perfiles disponibles." |
L["copy_desc"] = "Copia los ajustes de un perfil existente al perfil actual." |
L["copy"] = "Copiar de" |
L["delete_desc"] = "Borra los perfiles existentes y sin uso de la base de datos para ganar espacio y limpiar el archivo SavedVariables." |
L["delete"] = "Borrar un Perfil" |
L["delete_sub"] = "Borra un perfil de la base de datos." |
L["delete_confirm"] = "¿Estas seguro que quieres borrar el perfil seleccionado?" |
L["profiles"] = "Perfiles" |
L["profiles_sub"] = "Manejar Perfiles" |
--L["current"] = "Current Profile:" |
elseif LOCALE == "zhTW" then |
L["default"] = "é è¨" |
L["intro"] = "ä½ å¯ä»¥é¸æä¸åæ´»åçè³æè¨å®æªï¼éæ¨£ä½ çæ¯åè§è²å°±å¯ä»¥ææä¸åçè¨å®å¼ï¼å¯ä»¥çµ¦ä½ çæ件è¨å®å¸¶ä¾æ¥µå¤§çéæ´»æ§ã" |
L["reset_desc"] = "å°ç¶åçè¨å®æªæ¢å¾©å°å®çé è¨å¼ï¼ç¨æ¼ä½ çè¨å®æªæå£ï¼æè ä½ åªæ¯æ³éä¾çæ æ³ã" |
L["reset"] = "éç½®è¨å®æª" |
L["reset_sub"] = "å°ç¶åçè¨å®æªæ¢å¾©çºé è¨å¼" |
L["choose_desc"] = "ä½ å¯ä»¥ééå¨ææ¬æ¡å §è¼¸å ¥ä¸ååååµç«ä¸åæ°çè¨å®æªï¼ä¹å¯ä»¥é¸æä¸åå·²ç¶åå¨çè¨å®æªã" |
L["new"] = "æ°å»º" |
L["new_sub"] = "æ°å»ºä¸å空çè¨å®æªã" |
L["choose"] = "ç¾æçè¨å®æª" |
L["choose_sub"] = "å¾ç¶åå¯ç¨çè¨å®æªè£é¢é¸æä¸åã" |
L["copy_desc"] = "å¾ç¶åæåå·²ä¿åçè¨å®æªè¤è£½å°ç¶åæ£ä½¿ç¨çè¨å®æªã" |
L["copy"] = "è¤è£½èª" |
L["delete_desc"] = "å¾è³æ庫è£åªé¤ä¸å使ç¨çè¨å®æªï¼ä»¥ç¯ç空éï¼ä¸¦ä¸æ¸ çSavedVariablesæªã" |
L["delete"] = "åªé¤ä¸åè¨å®æª" |
L["delete_sub"] = "å¾è³æ庫è£åªé¤ä¸åè¨å®æªã" |
L["delete_confirm"] = "ä½ ç¢ºå®è¦åªé¤æé¸æçè¨å®æªåï¼" |
L["profiles"] = "è¨å®æª" |
L["profiles_sub"] = "管çè¨å®æª" |
--L["current"] = "Current Profile:" |
elseif LOCALE == "zhCN" then |
L["default"] = "é»è®¤" |
L["intro"] = "ä½ å¯ä»¥éæ©ä¸ä¸ªæ´»å¨çæ°æ®é ç½®æ件ï¼è¿æ ·ä½ çæ¯ä¸ªè§è²å°±å¯ä»¥æ¥æä¸åç设置å¼ï¼å¯ä»¥ç»ä½ çæ件é 置带æ¥æ大ççµæ´»æ§ã" |
L["reset_desc"] = "å°å½åçé ç½®æ件æ¢å¤å°å®çé»è®¤å¼ï¼ç¨äºä½ çé ç½®æ件æåï¼æè ä½ åªæ¯æ³éæ¥çæ åµã" |
L["reset"] = "éç½®é ç½®æ件" |
L["reset_sub"] = "å°å½åçé ç½®æ件æ¢å¤ä¸ºé»è®¤å¼" |
L["choose_desc"] = "ä½ å¯ä»¥éè¿å¨ææ¬æ¡å è¾å ¥ä¸ä¸ªåååç«ä¸ä¸ªæ°çé ç½®æ件ï¼ä¹å¯ä»¥éæ©ä¸ä¸ªå·²ç»åå¨çé ç½®æ件ã" |
L["new"] = "æ°å»º" |
L["new_sub"] = "æ°å»ºä¸ä¸ªç©ºçé ç½®æ件ã" |
L["choose"] = "ç°æçé ç½®æ件" |
L["choose_sub"] = "ä»å½åå¯ç¨çé ç½®æ件éé¢éæ©ä¸ä¸ªã" |
L["copy_desc"] = "ä»å½åæ个已ä¿åçé ç½®æ件å¤å¶å°å½åæ£ä½¿ç¨çé ç½®æ件ã" |
L["copy"] = "å¤å¶èª" |
L["delete_desc"] = "ä»æ°æ®åºéå é¤ä¸å使ç¨çé ç½®æ件ï¼ä»¥èç空é´ï¼å¹¶ä¸æ¸ çSavedVariablesæ件ã" |
L["delete"] = "å é¤ä¸ä¸ªé ç½®æ件" |
L["delete_sub"] = "ä»æ°æ®åºéå é¤ä¸ä¸ªé ç½®æ件ã" |
L["delete_confirm"] = "ä½ ç¡®å®è¦å é¤æéæ©çé ç½®æ件ä¹ï¼" |
L["profiles"] = "é ç½®æ件" |
L["profiles_sub"] = "管çé ç½®æ件" |
--L["current"] = "Current Profile:" |
elseif LOCALE == "ruRU" then |
L["default"] = "Ðо ÑмолÑаниÑ" |
L["intro"] = "ÐзменÑÑ Ð°ÐºÑивнÑй пÑоÑилÑ, Ð²Ñ Ð¼Ð¾Ð¶ÐµÑе задаÑÑ ÑазлиÑнÑе наÑÑÑойки модиÑикаÑий Ð´Ð»Ñ ÐºÐ°Ð¶Ð´Ð¾Ð³Ð¾ пеÑÑонажа." |
L["reset_desc"] = "ÐÑли ваÑа конÑигÑÑаÑии иÑпоÑÑена или еÑли Ð²Ñ Ñ Ð¾ÑиÑе наÑÑÑоиÑÑ Ð²ÑÑ Ð·Ð°Ð½Ð¾Ð²Ð¾ - ÑбÑоÑÑÑе ÑекÑÑий пÑоÑÐ¸Ð»Ñ Ð½Ð° ÑÑандаÑÑнÑе знаÑениÑ." |
L["reset"] = "СбÑÐ¾Ñ Ð¿ÑоÑилÑ" |
L["reset_sub"] = "СбÑÐ¾Ñ ÑекÑÑего пÑоÑÐ¸Ð»Ñ Ð½Ð° ÑÑандаÑÑнÑй" |
L["choose_desc"] = "ÐÑ Ð¼Ð¾Ð¶ÐµÑе ÑоздаÑÑ Ð½Ð¾Ð²Ñй пÑоÑилÑ, Ð²Ð²ÐµÐ´Ñ Ð½Ð°Ð·Ð²Ð°Ð½Ð¸Ðµ в поле ввода, или вÑбÑаÑÑ Ð¾Ð´Ð¸Ð½ из Ñже ÑÑÑеÑÑвÑÑÑÐ¸Ñ Ð¿ÑоÑилей." |
L["new"] = "ÐовÑй" |
L["new_sub"] = "СоздаÑÑ Ð½Ð¾Ð²Ñй ÑиÑÑÑй пÑоÑилÑ" |
L["choose"] = "СÑÑеÑÑвÑÑÑие пÑоÑили" |
L["choose_sub"] = "ÐÑÐ±Ð¾Ñ Ð¾Ð´Ð¸Ð½Ð¾Ð³Ð¾ из Ñже доÑÑÑпнÑÑ Ð¿ÑоÑилей" |
L["copy_desc"] = "СкопиÑоваÑÑ Ð½Ð°ÑÑÑойки из вÑбÑанного пÑоÑÐ¸Ð»Ñ Ð² акÑивнÑй." |
L["copy"] = "СкопиÑоваÑÑ Ð¸Ð·" |
L["delete_desc"] = "УдалиÑÑ ÑÑÑеÑÑвÑÑÑий и неиÑполÑзÑемÑй пÑоÑÐ¸Ð»Ñ Ð¸Ð· ÐÐ Ð´Ð»Ñ ÑÐ¾Ñ ÑÐ°Ð½ÐµÐ½Ð¸Ñ Ð¼ÐµÑÑа, и оÑиÑÑиÑÑ SavedVariables Ñайл." |
L["delete"] = "УдалиÑÑ Ð¿ÑоÑилÑ" |
L["delete_sub"] = "Удаление пÑоÑÐ¸Ð»Ñ Ð¸Ð· ÐÐ" |
L["delete_confirm"] = "ÐÑ ÑвеÑенÑ, ÑÑо Ð²Ñ Ñ Ð¾ÑиÑе ÑдалиÑÑ Ð²ÑбÑаннÑй пÑоÑилÑ?" |
L["profiles"] = "ÐÑоÑили" |
L["profiles_sub"] = "УпÑавление пÑоÑилÑми" |
--L["current"] = "Current Profile:" |
end |
local defaultProfiles |
local tmpprofiles = {} |
-- Get a list of available profiles for the specified database. |
-- You can specify which profiles to include/exclude in the list using the two boolean parameters listed below. |
-- @param db The db object to retrieve the profiles from |
-- @param common If true, getProfileList will add the default profiles to the return list, even if they have not been created yet |
-- @param nocurrent If true, then getProfileList will not display the current profile in the list |
-- @return Hashtable of all profiles with the internal name as keys and the display name as value. |
local function getProfileList(db, common, nocurrent) |
local profiles = {} |
-- copy existing profiles into the table |
local currentProfile = db:GetCurrentProfile() |
for i,v in pairs(db:GetProfiles(tmpprofiles)) do |
if not (nocurrent and v == currentProfile) then |
profiles[v] = v |
end |
end |
-- add our default profiles to choose from ( or rename existing profiles) |
for k,v in pairs(defaultProfiles) do |
if (common or profiles[k]) and not (nocurrent and k == currentProfile) then |
profiles[k] = v |
end |
end |
return profiles |
end |
--[[ |
OptionsHandlerPrototype |
prototype class for handling the options in a sane way |
]] |
local OptionsHandlerPrototype = {} |
--[[ Reset the profile ]] |
function OptionsHandlerPrototype:Reset() |
self.db:ResetProfile() |
end |
--[[ Set the profile to value ]] |
function OptionsHandlerPrototype:SetProfile(info, value) |
self.db:SetProfile(value) |
end |
--[[ returns the currently active profile ]] |
function OptionsHandlerPrototype:GetCurrentProfile() |
return self.db:GetCurrentProfile() |
end |
--[[ |
List all active profiles |
you can control the output with the .arg variable |
currently four modes are supported |
(empty) - return all available profiles |
"nocurrent" - returns all available profiles except the currently active profile |
"common" - returns all avaialble profiles + some commonly used profiles ("char - realm", "realm", "class", "Default") |
"both" - common except the active profile |
]] |
function OptionsHandlerPrototype:ListProfiles(info) |
local arg = info.arg |
local profiles |
if arg == "common" and not self.noDefaultProfiles then |
profiles = getProfileList(self.db, true, nil) |
elseif arg == "nocurrent" then |
profiles = getProfileList(self.db, nil, true) |
elseif arg == "both" then -- currently not used |
profiles = getProfileList(self.db, (not self.noDefaultProfiles) and true, true) |
else |
profiles = getProfileList(self.db) |
end |
return profiles |
end |
function OptionsHandlerPrototype:HasNoProfiles(info) |
local profiles = self:ListProfiles(info) |
return ((not next(profiles)) and true or false) |
end |
--[[ Copy a profile ]] |
function OptionsHandlerPrototype:CopyProfile(info, value) |
self.db:CopyProfile(value) |
end |
--[[ Delete a profile from the db ]] |
function OptionsHandlerPrototype:DeleteProfile(info, value) |
self.db:DeleteProfile(value) |
end |
--[[ fill defaultProfiles with some generic values ]] |
local function generateDefaultProfiles(db) |
defaultProfiles = { |
["Default"] = L["default"], |
[db.keys.char] = db.keys.char, |
[db.keys.realm] = db.keys.realm, |
[db.keys.class] = UnitClass("player") |
} |
end |
--[[ create and return a handler object for the db, or upgrade it if it already existed ]] |
local function getOptionsHandler(db, noDefaultProfiles) |
if not defaultProfiles then |
generateDefaultProfiles(db) |
end |
local handler = AceDBOptions.handlers[db] or { db = db, noDefaultProfiles = noDefaultProfiles } |
for k,v in pairs(OptionsHandlerPrototype) do |
handler[k] = v |
end |
AceDBOptions.handlers[db] = handler |
return handler |
end |
--[[ |
the real options table |
]] |
local optionsTable = { |
desc = { |
order = 1, |
type = "description", |
name = L["intro"] .. "\n", |
}, |
descreset = { |
order = 9, |
type = "description", |
name = L["reset_desc"], |
}, |
reset = { |
order = 10, |
type = "execute", |
name = L["reset"], |
desc = L["reset_sub"], |
func = "Reset", |
}, |
current = { |
order = 11, |
type = "description", |
name = function(info) return L["current"] .. " " .. NORMAL_FONT_COLOR_CODE .. info.handler:GetCurrentProfile() .. FONT_COLOR_CODE_CLOSE end, |
width = "default", |
}, |
choosedesc = { |
order = 20, |
type = "description", |
name = "\n" .. L["choose_desc"], |
}, |
new = { |
name = L["new"], |
desc = L["new_sub"], |
type = "input", |
order = 30, |
get = false, |
set = "SetProfile", |
}, |
choose = { |
name = L["choose"], |
desc = L["choose_sub"], |
type = "select", |
order = 40, |
get = "GetCurrentProfile", |
set = "SetProfile", |
values = "ListProfiles", |
arg = "common", |
}, |
copydesc = { |
order = 50, |
type = "description", |
name = "\n" .. L["copy_desc"], |
}, |
copyfrom = { |
order = 60, |
type = "select", |
name = L["copy"], |
desc = L["copy_desc"], |
get = false, |
set = "CopyProfile", |
values = "ListProfiles", |
disabled = "HasNoProfiles", |
arg = "nocurrent", |
}, |
deldesc = { |
order = 70, |
type = "description", |
name = "\n" .. L["delete_desc"], |
}, |
delete = { |
order = 80, |
type = "select", |
name = L["delete"], |
desc = L["delete_sub"], |
get = false, |
set = "DeleteProfile", |
values = "ListProfiles", |
disabled = "HasNoProfiles", |
arg = "nocurrent", |
confirm = true, |
confirmText = L["delete_confirm"], |
}, |
} |
--- Get/Create a option table that you can use in your addon to control the profiles of AceDB-3.0. |
-- @param db The database object to create the options table for. |
-- @return The options table to be used in AceConfig-3.0 |
-- @usage |
-- -- Assuming `options` is your top-level options table and `self.db` is your database: |
-- options.args.profiles = LibStub("AceDBOptions-3.0"):GetOptionsTable(self.db) |
function AceDBOptions:GetOptionsTable(db, noDefaultProfiles) |
local tbl = AceDBOptions.optionTables[db] or { |
type = "group", |
name = L["profiles"], |
desc = L["profiles_sub"], |
} |
tbl.handler = getOptionsHandler(db, noDefaultProfiles) |
tbl.args = optionsTable |
AceDBOptions.optionTables[db] = tbl |
return tbl |
end |
-- upgrade existing tables |
for db,tbl in pairs(AceDBOptions.optionTables) do |
tbl.handler = getOptionsHandler(db) |
tbl.args = optionsTable |
end |
<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="AceConsole-3.0.lua"/> |
</Ui> |
--- **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 878 2009-11-02 18:51:58Z nevcairiel $ |
local MAJOR,MINOR = "AceConsole-3.0", 7 |
local AceConsole, oldminor = LibStub:NewLibrary(MAJOR, MINOR) |
if not AceConsole then return end -- No upgrade needed |
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 tconcat, tostring, select = table.concat, tostring, select |
local type, pairs, error = type, pairs, error |
local format, strfind, strsub = string.format, string.find, string.sub |
local max = math.max |
-- WoW APIs |
local _G = _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 tmp={} |
local function Print(self,frame,...) |
local n=0 |
if self ~= AceConsole then |
n=n+1 |
tmp[n] = "|cff33ff99"..tostring( self ).."|r:" |
end |
for i=1, select("#", ...) do |
n=n+1 |
tmp[n] = tostring(select(i, ...)) |
end |
frame:AddMessage( tconcat(tmp," ",1,n) ) |
end |
--- 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 = ... |
if type(frame) == "table" and frame.AddMessage then -- Is first argument something with an .AddMessage member? |
return Print(self, frame, select(2,...)) |
else |
return Print(self, DEFAULT_CHAT_FRAME, ...) |
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(...) |
local frame = ... |
if type(frame) == "table" and frame.AddMessage then -- Is first argument something with an .AddMessage member? |
return Print(self, frame, format(select(2,...))) |
else |
return Print(self, DEFAULT_CHAT_FRAME, format(...)) |
end |
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_"..command:upper() |
if type( func ) == "string" then |
SlashCmdList[name] = function(input, editBox) |
self[func](self, input, editBox) |
end |
else |
SlashCmdList[name] = func |
end |
_G["SLASH_"..name.."1"] = "/"..command:lower() |
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 |
hash_SlashCmdList["/" .. command:upper()] = 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, ...) |
if n>1 then |
return nil, nils(n-1, ...) |
elseif n==1 then |
return nil, ... |
else |
return ... |
end |
end |
--- Retreive one or more space-separated arguments from a string. |
-- Treats quoted strings and itemlinks as non-spaced. |
-- @param string 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, 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, 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 |
<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="AceConfigRegistry-3.0\AceConfigRegistry-3.0.xml"/> |
<Include file="AceConfigCmd-3.0\AceConfigCmd-3.0.xml"/> |
<Include file="AceConfigDialog-3.0\AceConfigDialog-3.0.xml"/> |
<!--<Include file="AceConfigDropdown-3.0\AceConfigDropdown-3.0.xml"/>--> |
<Script file="AceConfig-3.0.lua"/> |
</Ui> |
--- AceConfig-3.0 wrapper library. |
-- Provides an API to register an options table with the config registry, |
-- as well as associate it with a slash command. |
-- @class file |
-- @name AceConfig-3.0 |
-- @release $Id: AceConfig-3.0.lua 877 2009-11-02 15:56:50Z nevcairiel $ |
--[[ |
AceConfig-3.0 |
Very light wrapper library that combines all the AceConfig subcomponents into one more easily used whole. |
]] |
local MAJOR, MINOR = "AceConfig-3.0", 2 |
local AceConfig = LibStub:NewLibrary(MAJOR, MINOR) |
if not AceConfig then return end |
local cfgreg = LibStub("AceConfigRegistry-3.0") |
local cfgcmd = LibStub("AceConfigCmd-3.0") |
local cfgdlg = LibStub("AceConfigDialog-3.0") |
--TODO: local cfgdrp = LibStub("AceConfigDropdown-3.0") |
-- Lua APIs |
local pcall, error, type, pairs = pcall, error, type, pairs |
-- ------------------------------------------------------------------- |
-- :RegisterOptionsTable(appName, options, slashcmd, persist) |
-- |
-- - appName - (string) application name |
-- - options - table or function ref, see AceConfigRegistry |
-- - slashcmd - slash command (string) or table with commands, or nil to NOT create a slash command |
--- Register a option table with the AceConfig registry. |
-- You can supply a slash command (or a table of slash commands) to register with AceConfigCmd directly. |
-- @paramsig appName, options [, slashcmd] |
-- @param appName The application name for the config table. |
-- @param options The option table (or a function to generate one on demand) |
-- @param slashcmd A slash command to register for the option table, or a table of slash commands. |
-- @usage |
-- local AceConfig = LibStub("AceConfig-3.0") |
-- AceConfig:RegisterOptionsTable("MyAddon", myOptions, {"/myslash", "/my"}) |
function AceConfig:RegisterOptionsTable(appName, options, slashcmd) |
local ok,msg = pcall(cfgreg.RegisterOptionsTable, self, appName, options) |
if not ok then error(msg, 2) end |
if slashcmd then |
if type(slashcmd) == "table" then |
for _,cmd in pairs(slashcmd) do |
cfgcmd:CreateChatCommand(cmd, appName) |
end |
else |
cfgcmd:CreateChatCommand(slashcmd, appName) |
end |
end |
end |
<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="AceConfigDialog-3.0.lua"/> |
</Ui> |
--- AceConfigDialog-3.0 generates AceGUI-3.0 based windows based on option tables. |
-- @class file |
-- @name AceConfigDialog-3.0 |
-- @release $Id: AceConfigDialog-3.0.lua 902 2009-12-12 14:56:14Z nevcairiel $ |
local LibStub = LibStub |
local MAJOR, MINOR = "AceConfigDialog-3.0", 43 |
local AceConfigDialog, oldminor = LibStub:NewLibrary(MAJOR, MINOR) |
if not AceConfigDialog then return end |
AceConfigDialog.OpenFrames = AceConfigDialog.OpenFrames or {} |
AceConfigDialog.Status = AceConfigDialog.Status or {} |
AceConfigDialog.frame = AceConfigDialog.frame or CreateFrame("Frame") |
AceConfigDialog.frame.apps = AceConfigDialog.frame.apps or {} |
AceConfigDialog.frame.closing = AceConfigDialog.frame.closing or {} |
local gui = LibStub("AceGUI-3.0") |
local reg = LibStub("AceConfigRegistry-3.0") |
-- Lua APIs |
local tconcat, tinsert, tsort, tremove = table.concat, table.insert, table.sort, table.remove |
local strmatch, format = string.match, string.format |
local assert, loadstring, error = assert, loadstring, error |
local pairs, next, select, type, unpack = pairs, next, select, type, unpack |
local rawset, tostring = rawset, tostring |
local math_min, math_max, math_floor = math.min, math.max, math.floor |
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded |
-- List them here for Mikk's FindGlobals script |
-- GLOBALS: NORMAL_FONT_COLOR, GameTooltip, StaticPopupDialogs, ACCEPT, CANCEL, StaticPopup_Show |
-- GLOBALS: PlaySound, GameFontHighlight, GameFontHighlightSmall, GameFontHighlightLarge |
-- GLOBALS: CloseSpecialWindows, InterfaceOptions_AddCategory, geterrorhandler |
local emptyTbl = {} |
--[[ |
xpcall safecall implementation |
]] |
local xpcall = xpcall |
local function errorhandler(err) |
return geterrorhandler()(err) |
end |
local function CreateDispatcher(argCount) |
local code = [[ |
local xpcall, eh = ... |
local method, ARGS |
local function call() return method(ARGS) end |
local function dispatch(func, ...) |
method = func |
if not method then return end |
ARGS = ... |
return xpcall(call, eh) |
end |
return dispatch |
]] |
local ARGS = {} |
for i = 1, argCount do ARGS[i] = "arg"..i end |
code = code:gsub("ARGS", tconcat(ARGS, ", ")) |
return assert(loadstring(code, "safecall Dispatcher["..argCount.."]"))(xpcall, errorhandler) |
end |
local Dispatchers = setmetatable({}, {__index=function(self, argCount) |
local dispatcher = CreateDispatcher(argCount) |
rawset(self, argCount, dispatcher) |
return dispatcher |
end}) |
Dispatchers[0] = function(func) |
return xpcall(func, errorhandler) |
end |
local function safecall(func, ...) |
return Dispatchers[select('#', ...)](func, ...) |
end |
local width_multiplier = 170 |
--[[ |
Group Types |
Tree - All Descendant Groups will all become nodes on the tree, direct child options will appear above the tree |
- Descendant Groups with inline=true and thier children will not become nodes |
Tab - Direct Child Groups will become tabs, direct child options will appear above the tab control |
- Grandchild groups will default to inline unless specified otherwise |
Select- Same as Tab but with entries in a dropdown rather than tabs |
Inline Groups |
- Will not become nodes of a select group, they will be effectivly part of thier parent group seperated by a border |
- If declared on a direct child of a root node of a select group, they will appear above the group container control |
- When a group is displayed inline, all descendants will also be inline members of the group |
]] |
-- Recycling functions |
local new, del, copy |
--newcount, delcount,createdcount,cached = 0,0,0 |
do |
local pool = setmetatable({},{__mode='k'}) |
function new() |
--newcount = newcount + 1 |
local t = next(pool) |
if t then |
pool[t] = nil |
return t |
else |
--createdcount = createdcount + 1 |
return {} |
end |
end |
function copy(t) |
local c = new() |
for k, v in pairs(t) do |
c[k] = v |
end |
return c |
end |
function del(t) |
--delcount = delcount + 1 |
for k in pairs(t) do |
t[k] = nil |
end |
pool[t] = true |
end |
-- function cached() |
-- local n = 0 |
-- for k in pairs(pool) do |
-- n = n + 1 |
-- end |
-- return n |
-- end |
end |
-- picks the first non-nil value and returns it |
local function pickfirstset(...) |
for i=1,select("#",...) do |
if select(i,...)~=nil then |
return select(i,...) |
end |
end |
end |
--gets an option from a given group, checking plugins |
local function GetSubOption(group, key) |
if group.plugins then |
for plugin, t in pairs(group.plugins) do |
if t[key] then |
return t[key] |
end |
end |
end |
return group.args[key] |
end |
--Option member type definitions, used to decide how to access it |
--Is the member Inherited from parent options |
local isInherited = { |
set = true, |
get = true, |
func = true, |
confirm = true, |
validate = true, |
disabled = true, |
hidden = true |
} |
--Does a string type mean a literal value, instead of the default of a method of the handler |
local stringIsLiteral = { |
name = true, |
desc = true, |
icon = true, |
usage = true, |
width = true, |
image = true, |
fontSize = true, |
} |
--Is Never a function or method |
local allIsLiteral = { |
type = true, |
descStyle = true, |
imageWidth = true, |
imageHeight = true, |
} |
--gets the value for a member that could be a function |
--function refs are called with an info arg |
--every other type is returned |
local function GetOptionsMemberValue(membername, option, options, path, appName, ...) |
--get definition for the member |
local inherits = isInherited[membername] |
--get the member of the option, traversing the tree if it can be inherited |
local member |
if inherits then |
local group = options |
if group[membername] ~= nil then |
member = group[membername] |
end |
for i = 1, #path do |
group = GetSubOption(group, path[i]) |
if group[membername] ~= nil then |
member = group[membername] |
end |
end |
else |
member = option[membername] |
end |
--check if we need to call a functon, or if we have a literal value |
if ( not allIsLiteral[membername] ) and ( type(member) == "function" or ((not stringIsLiteral[membername]) and type(member) == "string") ) then |
--We have a function to call |
local info = new() |
--traverse the options table, picking up the handler and filling the info with the path |
local handler |
local group = options |
handler = group.handler or handler |
for i = 1, #path do |
group = GetSubOption(group, path[i]) |
info[i] = path[i] |
handler = group.handler or handler |
end |
info.options = options |
info.appName = appName |
info[0] = appName |
info.arg = option.arg |
info.handler = handler |
info.option = option |
info.type = option.type |
info.uiType = 'dialog' |
info.uiName = MAJOR |
local a, b, c ,d |
--using 4 returns for the get of a color type, increase if a type needs more |
if type(member) == "function" then |
--Call the function |
a,b,c,d = member(info, ...) |
else |
--Call the method |
if handler and handler[member] then |
a,b,c,d = handler[member](handler, info, ...) |
else |
error(format("Method %s doesn't exist in handler for type %s", member, membername)) |
end |
end |
del(info) |
return a,b,c,d |
else |
--The value isnt a function to call, return it |
return member |
end |
end |
--[[calls an options function that could be inherited, method name or function ref |
local function CallOptionsFunction(funcname ,option, options, path, appName, ...) |
local info = new() |
local func |
local group = options |
local handler |
--build the info table containing the path |
-- pick up functions while traversing the tree |
if group[funcname] ~= nil then |
func = group[funcname] |
end |
handler = group.handler or handler |
for i, v in ipairs(path) do |
group = GetSubOption(group, v) |
info[i] = v |
if group[funcname] ~= nil then |
func = group[funcname] |
end |
handler = group.handler or handler |
end |
info.options = options |
info[0] = appName |
info.arg = option.arg |
local a, b, c ,d |
if type(func) == "string" then |
if handler and handler[func] then |
a,b,c,d = handler[func](handler, info, ...) |
else |
error(string.format("Method %s doesn't exist in handler for type func", func)) |
end |
elseif type(func) == "function" then |
a,b,c,d = func(info, ...) |
end |
del(info) |
return a,b,c,d |
end |
--]] |
--tables to hold orders and names for options being sorted, will be created with new() |
--prevents needing to call functions repeatedly while sorting |
local tempOrders |
local tempNames |
local function compareOptions(a,b) |
if not a then |
return true |
end |
if not b then |
return false |
end |
local OrderA, OrderB = tempOrders[a] or 100, tempOrders[b] or 100 |
if OrderA == OrderB then |
local NameA = (type(tempNames[a] == "string") and tempNames[a]) or "" |
local NameB = (type(tempNames[b] == "string") and tempNames[b]) or "" |
return NameA:upper() < NameB:upper() |
end |
if OrderA < 0 then |
if OrderB > 0 then |
return false |
end |
else |
if OrderB < 0 then |
return true |
end |
end |
return OrderA < OrderB |
end |
--builds 2 tables out of an options group |
-- keySort, sorted keys |
-- opts, combined options from .plugins and args |
local function BuildSortedOptionsTable(group, keySort, opts, options, path, appName) |
tempOrders = new() |
tempNames = new() |
if group.plugins then |
for plugin, t in pairs(group.plugins) do |
for k, v in pairs(t) do |
if not opts[k] then |
tinsert(keySort, k) |
opts[k] = v |
path[#path+1] = k |
tempOrders[k] = GetOptionsMemberValue("order", v, options, path, appName) |
tempNames[k] = GetOptionsMemberValue("name", v, options, path, appName) |
path[#path] = nil |
end |
end |
end |
end |
for k, v in pairs(group.args) do |
if not opts[k] then |
tinsert(keySort, k) |
opts[k] = v |
path[#path+1] = k |
tempOrders[k] = GetOptionsMemberValue("order", v, options, path, appName) |
tempNames[k] = GetOptionsMemberValue("name", v, options, path, appName) |
path[#path] = nil |
end |
end |
tsort(keySort, compareOptions) |
del(tempOrders) |
del(tempNames) |
end |
local function DelTree(tree) |
if tree.children then |
local childs = tree.children |
for i = 1, #childs do |
DelTree(childs[i]) |
del(childs[i]) |
end |
del(childs) |
end |
end |
local function CleanUserData(widget, event) |
local user = widget:GetUserDataTable() |
if user.path then |
del(user.path) |
end |
if widget.type == "TreeGroup" then |
local tree = user.tree |
widget:SetTree(nil) |
if tree then |
for i = 1, #tree do |
DelTree(tree[i]) |
del(tree[i]) |
end |
del(tree) |
end |
end |
if widget.type == "TabGroup" then |
widget:SetTabs(nil) |
if user.tablist then |
del(user.tablist) |
end |
end |
if widget.type == "DropdownGroup" then |
widget:SetGroupList(nil) |
if user.grouplist then |
del(user.grouplist) |
end |
end |
end |
-- - Gets a status table for the given appname and options path. |
-- @param appName The application name as given to `:RegisterOptionsTable()` |
-- @param path The path to the options (a table with all group keys) |
-- @return |
function AceConfigDialog:GetStatusTable(appName, path) |
local status = self.Status |
if not status[appName] then |
status[appName] = {} |
status[appName].status = {} |
status[appName].children = {} |
end |
status = status[appName] |
if path then |
for i = 1, #path do |
local v = path[i] |
if not status.children[v] then |
status.children[v] = {} |
status.children[v].status = {} |
status.children[v].children = {} |
end |
status = status.children[v] |
end |
end |
return status.status |
end |
--- Selects the specified path in the options window. |
-- The path specified has to match the keys of the groups in the table. |
-- @param appName The application name as given to `:RegisterOptionsTable()` |
-- @param ... The path to the key that should be selected |
function AceConfigDialog:SelectGroup(appName, ...) |
local path = new() |
local app = reg:GetOptionsTable(appName) |
if not app then |
error(("%s isn't registed with AceConfigRegistry, unable to open config"):format(appName), 2) |
end |
local options = app("dialog", MAJOR) |
local group = options |
local status = self:GetStatusTable(appName, path) |
if not status.groups then |
status.groups = {} |
end |
status = status.groups |
local treevalue |
local treestatus |
for n = 1, select('#',...) do |
local key = select(n, ...) |
if group.childGroups == "tab" or group.childGroups == "select" then |
--if this is a tab or select group, select the group |
status.selected = key |
--children of this group are no longer extra levels of a tree |
treevalue = nil |
else |
--tree group by default |
if treevalue then |
--this is an extra level of a tree group, build a uniquevalue for it |
treevalue = treevalue.."\001"..key |
else |
--this is the top level of a tree group, the uniquevalue is the same as the key |
treevalue = key |
if not status.groups then |
status.groups = {} |
end |
--save this trees status table for any extra levels or groups |
treestatus = status |
end |
--make sure that the tree entry is open, and select it. |
--the selected group will be overwritten if a child is the final target but still needs to be open |
treestatus.selected = treevalue |
treestatus.groups[treevalue] = true |
end |
--move to the next group in the path |
group = GetSubOption(group, key) |
if not group then |
break |
end |
tinsert(path, key) |
status = self:GetStatusTable(appName, path) |
if not status.groups then |
status.groups = {} |
end |
status = status.groups |
end |
del(path) |
reg:NotifyChange(appName) |
end |
local function OptionOnMouseOver(widget, event) |
--show a tooltip/set the status bar to the desc text |
local user = widget:GetUserDataTable() |
local opt = user.option |
local options = user.options |
local path = user.path |
local appName = user.appName |
GameTooltip:SetOwner(widget.frame, "ANCHOR_TOPRIGHT") |
local name = GetOptionsMemberValue("name", opt, options, path, appName) |
local desc = GetOptionsMemberValue("desc", opt, options, path, appName) |
local usage = GetOptionsMemberValue("usage", opt, options, path, appName) |
local descStyle = opt.descStyle |
if descStyle and descStyle ~= "tooltip" then return end |
GameTooltip:SetText(name, 1, .82, 0, 1) |
if opt.type == 'multiselect' then |
GameTooltip:AddLine(user.text,0.5, 0.5, 0.8, 1) |
end |
if type(desc) == "string" then |
GameTooltip:AddLine(desc, 1, 1, 1, 1) |
end |
if type(usage) == "string" then |
GameTooltip:AddLine("Usage: "..usage, NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b, 1) |
end |
GameTooltip:Show() |
end |
local function OptionOnMouseLeave(widget, event) |
GameTooltip:Hide() |
end |
local function GetFuncName(option) |
local type = option.type |
if type == 'execute' then |
return 'func' |
else |
return 'set' |
end |
end |
local function confirmPopup(appName, rootframe, basepath, info, message, func, ...) |
if not StaticPopupDialogs["ACECONFIGDIALOG30_CONFIRM_DIALOG"] then |
StaticPopupDialogs["ACECONFIGDIALOG30_CONFIRM_DIALOG"] = {} |
end |
local t = StaticPopupDialogs["ACECONFIGDIALOG30_CONFIRM_DIALOG"] |
for k in pairs(t) do |
t[k] = nil |
end |
t.text = message |
t.button1 = ACCEPT |
t.button2 = CANCEL |
local dialog, oldstrata |
t.OnAccept = function() |
safecall(func, unpack(t)) |
if dialog and oldstrata then |
dialog:SetFrameStrata(oldstrata) |
end |
AceConfigDialog:Open(appName, rootframe, unpack(basepath or emptyTbl)) |
del(info) |
end |
t.OnCancel = function() |
if dialog and oldstrata then |
dialog:SetFrameStrata(oldstrata) |
end |
AceConfigDialog:Open(appName, rootframe, unpack(basepath or emptyTbl)) |
del(info) |
end |
for i = 1, select('#', ...) do |
t[i] = select(i, ...) or false |
end |
t.timeout = 0 |
t.whileDead = 1 |
t.hideOnEscape = 1 |
dialog = StaticPopup_Show("ACECONFIGDIALOG30_CONFIRM_DIALOG") |
if dialog then |
oldstrata = dialog:GetFrameStrata() |
dialog:SetFrameStrata("TOOLTIP") |
end |
end |
local function ActivateControl(widget, event, ...) |
--This function will call the set / execute handler for the widget |
--widget:GetUserDataTable() contains the needed info |
local user = widget:GetUserDataTable() |
local option = user.option |
local options = user.options |
local path = user.path |
local info = new() |
local func |
local group = options |
local funcname = GetFuncName(option) |
local handler |
local confirm |
local validate |
--build the info table containing the path |
-- pick up functions while traversing the tree |
if group[funcname] ~= nil then |
func = group[funcname] |
end |
handler = group.handler or handler |
confirm = group.confirm |
validate = group.validate |
for i = 1, #path do |
local v = path[i] |
group = GetSubOption(group, v) |
info[i] = v |
if group[funcname] ~= nil then |
func = group[funcname] |
end |
handler = group.handler or handler |
if group.confirm ~= nil then |
confirm = group.confirm |
end |
if group.validate ~= nil then |
validate = group.validate |
end |
end |
info.options = options |
info.appName = user.appName |
info.arg = option.arg |
info.handler = handler |
info.option = option |
info.type = option.type |
info.uiType = 'dialog' |
info.uiName = MAJOR |
local name |
if type(option.name) == "function" then |
name = option.name(info) |
elseif type(option.name) == "string" then |
name = option.name |
else |
name = "" |
end |
local usage = option.usage |
local pattern = option.pattern |
local validated = true |
if option.type == "input" then |
if type(pattern)=="string" then |
if not strmatch(..., pattern) then |
validated = false |
end |
end |
end |
local success |
if validated and option.type ~= "execute" then |
if type(validate) == "string" then |
if handler and handler[validate] then |
success, validated = safecall(handler[validate], handler, info, ...) |
if not success then validated = false end |
else |
error(format("Method %s doesn't exist in handler for type execute", validate)) |
end |
elseif type(validate) == "function" then |
success, validated = safecall(validate, info, ...) |
if not success then validated = false end |
end |
end |
local rootframe = user.rootframe |
if type(validated) == "string" then |
--validate function returned a message to display |
if rootframe.SetStatusText then |
rootframe:SetStatusText(validated) |
else |
-- TODO: do something else. |
end |
PlaySound("igPlayerInviteDecline") |
del(info) |
return true |
elseif not validated then |
--validate returned false |
if rootframe.SetStatusText then |
if usage then |
rootframe:SetStatusText(name..": "..usage) |
else |
if pattern then |
rootframe:SetStatusText(name..": Expected "..pattern) |
else |
rootframe:SetStatusText(name..": Invalid Value") |
end |
end |
else |
-- TODO: do something else |
end |
PlaySound("igPlayerInviteDecline") |
del(info) |
return true |
else |
local confirmText = option.confirmText |
--call confirm func/method |
if type(confirm) == "string" then |
if handler and handler[confirm] then |
success, confirm = safecall(handler[confirm], handler, info, ...) |
if success and type(confirm) == "string" then |
confirmText = confirm |
confirm = true |
elseif not success then |
confirm = false |
end |
else |
error(format("Method %s doesn't exist in handler for type confirm", confirm)) |
end |
elseif type(confirm) == "function" then |
success, confirm = safecall(confirm, info, ...) |
if success and type(confirm) == "string" then |
confirmText = confirm |
confirm = true |
elseif not success then |
confirm = false |
end |
end |
--confirm if needed |
if type(confirm) == "boolean" then |
if confirm then |
if not confirmText then |
local name, desc = option.name, option.desc |
if type(name) == "function" then |
name = name(info) |
end |
if type(desc) == "function" then |
desc = desc(info) |
end |
confirmText = name |
if desc then |
confirmText = confirmText.." - "..desc |
end |
end |
local iscustom = user.rootframe:GetUserData('iscustom') |
local rootframe |
if iscustom then |
rootframe = user.rootframe |
end |
local basepath = user.rootframe:GetUserData('basepath') |
if type(func) == "string" then |
if handler and handler[func] then |
confirmPopup(user.appName, rootframe, basepath, info, confirmText, handler[func], handler, info, ...) |
else |
error(format("Method %s doesn't exist in handler for type func", func)) |
end |
elseif type(func) == "function" then |
confirmPopup(user.appName, rootframe, basepath, info, confirmText, func, info, ...) |
end |
--func will be called and info deleted when the confirm dialog is responded to |
return |
end |
end |
--call the function |
if type(func) == "string" then |
if handler and handler[func] then |
safecall(handler[func],handler, info, ...) |
else |
error(format("Method %s doesn't exist in handler for type func", func)) |
end |
elseif type(func) == "function" then |
safecall(func,info, ...) |
end |
local iscustom = user.rootframe:GetUserData('iscustom') |
local basepath = user.rootframe:GetUserData('basepath') or emptyTbl |
--full refresh of the frame, some controls dont cause this on all events |
if option.type == "color" then |
if event == "OnValueConfirmed" then |
if iscustom then |
AceConfigDialog:Open(user.appName, user.rootframe, unpack(basepath)) |
else |
AceConfigDialog:Open(user.appName, unpack(basepath)) |
end |
end |
elseif option.type == "range" then |
if event == "OnMouseUp" then |
if iscustom then |
AceConfigDialog:Open(user.appName, user.rootframe, unpack(basepath)) |
else |
AceConfigDialog:Open(user.appName, unpack(basepath)) |
end |
end |
--multiselects don't cause a refresh on 'OnValueChanged' only 'OnClosed' |
elseif option.type == "multiselect" then |
user.valuechanged = true |
else |
if iscustom then |
AceConfigDialog:Open(user.appName, user.rootframe, unpack(basepath)) |
else |
AceConfigDialog:Open(user.appName, unpack(basepath)) |
end |
end |
end |
del(info) |
end |
local function ActivateSlider(widget, event, value) |
local option = widget:GetUserData('option') |
local min, max, step = option.min or 0, option.max or 100, option.step |
if step then |
value = math_floor((value - min) / step + 0.5) * step + min |
else |
value = math_max(math_min(value,max),min) |
end |
ActivateControl(widget,event,value) |
end |
--called from a checkbox that is part of an internally created multiselect group |
--this type is safe to refresh on activation of one control |
local function ActivateMultiControl(widget, event, ...) |
ActivateControl(widget, event, widget:GetUserData('value'), ...) |
local user = widget:GetUserDataTable() |
local iscustom = user.rootframe:GetUserData('iscustom') |
local basepath = user.rootframe:GetUserData('basepath') or emptyTbl |
if iscustom then |
AceConfigDialog:Open(user.appName, user.rootframe, unpack(basepath)) |
else |
AceConfigDialog:Open(user.appName, unpack(basepath)) |
end |
end |
local function MultiControlOnClosed(widget, event, ...) |
local user = widget:GetUserDataTable() |
if user.valuechanged then |
local iscustom = user.rootframe:GetUserData('iscustom') |
local basepath = user.rootframe:GetUserData('basepath') or emptyTbl |
if iscustom then |
AceConfigDialog:Open(user.appName, user.rootframe, unpack(basepath)) |
else |
AceConfigDialog:Open(user.appName, unpack(basepath)) |
end |
end |
end |
local function FrameOnClose(widget, event) |
local appName = widget:GetUserData('appName') |
AceConfigDialog.OpenFrames[appName] = nil |
gui:Release(widget) |
end |
local function CheckOptionHidden(option, options, path, appName) |
--check for a specific boolean option |
local hidden = pickfirstset(option.dialogHidden,option.guiHidden) |
if hidden ~= nil then |
return hidden |
end |
return GetOptionsMemberValue("hidden", option, options, path, appName) |
end |
local function CheckOptionDisabled(option, options, path, appName) |
--check for a specific boolean option |
local disabled = pickfirstset(option.dialogDisabled,option.guiDisabled) |
if disabled ~= nil then |
return disabled |
end |
return GetOptionsMemberValue("disabled", option, options, path, appName) |
end |
--[[ |
local function BuildTabs(group, options, path, appName) |
local tabs = new() |
local text = new() |
local keySort = new() |
local opts = new() |
BuildSortedOptionsTable(group, keySort, opts, options, path, appName) |
for i = 1, #keySort do |
local k = keySort[i] |
local v = opts[k] |
if v.type == "group" then |
path[#path+1] = k |
local inline = pickfirstset(v.dialogInline,v.guiInline,v.inline, false) |
local hidden = CheckOptionHidden(v, options, path, appName) |
if not inline and not hidden then |
tinsert(tabs, k) |
text[k] = GetOptionsMemberValue("name", v, options, path, appName) |
end |
path[#path] = nil |
end |
end |
del(keySort) |
del(opts) |
return tabs, text |
end |
]] |
local function BuildSelect(group, options, path, appName) |
local groups = new() |
local keySort = new() |
local opts = new() |
BuildSortedOptionsTable(group, keySort, opts, options, path, appName) |
for i = 1, #keySort do |
local k = keySort[i] |
local v = opts[k] |
if v.type == "group" then |
path[#path+1] = k |
local inline = pickfirstset(v.dialogInline,v.guiInline,v.inline, false) |
local hidden = CheckOptionHidden(v, options, path, appName) |
if not inline and not hidden then |
groups[k] = GetOptionsMemberValue("name", v, options, path, appName) |
end |
path[#path] = nil |
end |
end |
del(keySort) |
del(opts) |
return groups |
end |
local function BuildSubGroups(group, tree, options, path, appName) |
local keySort = new() |
local opts = new() |
BuildSortedOptionsTable(group, keySort, opts, options, path, appName) |
for i = 1, #keySort do |
local k = keySort[i] |
local v = opts[k] |
if v.type == "group" then |
path[#path+1] = k |
local inline = pickfirstset(v.dialogInline,v.guiInline,v.inline, false) |
local hidden = CheckOptionHidden(v, options, path, appName) |
if not inline and not hidden then |
local entry = new() |
entry.value = k |
entry.text = GetOptionsMemberValue("name", v, options, path, appName) |
entry.icon = GetOptionsMemberValue("icon", v, options, path, appName) |
entry.disabled = CheckOptionDisabled(v, options, path, appName) |
if not tree.children then tree.children = new() end |
tinsert(tree.children,entry) |
if (v.childGroups or "tree") == "tree" then |
BuildSubGroups(v,entry, options, path, appName) |
end |
end |
path[#path] = nil |
end |
end |
del(keySort) |
del(opts) |
end |
local function BuildGroups(group, options, path, appName, recurse) |
local tree = new() |
local keySort = new() |
local opts = new() |
BuildSortedOptionsTable(group, keySort, opts, options, path, appName) |
for i = 1, #keySort do |
local k = keySort[i] |
local v = opts[k] |
if v.type == "group" then |
path[#path+1] = k |
local inline = pickfirstset(v.dialogInline,v.guiInline,v.inline, false) |
local hidden = CheckOptionHidden(v, options, path, appName) |
if not inline and not hidden then |
local entry = new() |
entry.value = k |
entry.text = GetOptionsMemberValue("name", v, options, path, appName) |
entry.icon = GetOptionsMemberValue("icon", v, options, path, appName) |
entry.disabled = CheckOptionDisabled(v, options, path, appName) |
tinsert(tree,entry) |
if recurse and (v.childGroups or "tree") == "tree" then |
BuildSubGroups(v,entry, options, path, appName) |
end |
end |
path[#path] = nil |
end |
end |
del(keySort) |
del(opts) |
return tree |
end |
local function InjectInfo(control, options, option, path, rootframe, appName) |
local user = control:GetUserDataTable() |
for i = 1, #path do |
user[i] = path[i] |
end |
user.rootframe = rootframe |
user.option = option |
user.options = options |
user.path = copy(path) |
user.appName = appName |
control:SetCallback("OnRelease", CleanUserData) |
control:SetCallback("OnLeave", OptionOnMouseLeave) |
control:SetCallback("OnEnter", OptionOnMouseOver) |
end |
--[[ |
options - root of the options table being fed |
container - widget that controls will be placed in |
rootframe - Frame object the options are in |
path - table with the keys to get to the group being fed |
--]] |
local function FeedOptions(appName, options,container,rootframe,path,group,inline) |
local keySort = new() |
local opts = new() |
BuildSortedOptionsTable(group, keySort, opts, options, path, appName) |
for i = 1, #keySort do |
local k = keySort[i] |
local v = opts[k] |
tinsert(path, k) |
local hidden = CheckOptionHidden(v, options, path, appName) |
local name = GetOptionsMemberValue("name", v, options, path, appName) |
if not hidden then |
if v.type == "group" then |
if inline or pickfirstset(v.dialogInline,v.guiInline,v.inline, false) then |
--Inline group |
local GroupContainer |
if name and name ~= "" then |
GroupContainer = gui:Create("InlineGroup") |
GroupContainer:SetTitle(name or "") |
else |
GroupContainer = gui:Create("SimpleGroup") |
end |
GroupContainer.width = "fill" |
GroupContainer:SetLayout("flow") |
container:AddChild(GroupContainer) |
FeedOptions(appName,options,GroupContainer,rootframe,path,v,true) |
end |
else |
--Control to feed |
local control |
local name = GetOptionsMemberValue("name", v, options, path, appName) |
if v.type == "execute" then |
local imageCoords = GetOptionsMemberValue("imageCoords",v, options, path, appName) |
local image, width, height = GetOptionsMemberValue("image",v, options, path, appName) |
if type(image) == 'string' then |
control = gui:Create("Icon") |
if not width then |
width = GetOptionsMemberValue("imageWidth",v, options, path, appName) |
end |
if not height then |
height = GetOptionsMemberValue("imageHeight",v, options, path, appName) |
end |
if type(imageCoords) == 'table' then |
control:SetImage(image, unpack(imageCoords)) |
else |
control:SetImage(image) |
end |
if type(width) ~= "number" then |
width = 32 |
end |
if type(height) ~= "number" then |
height = 32 |
end |
control:SetImageSize(width, height) |
control:SetLabel(name) |
else |
control = gui:Create("Button") |
control:SetText(name) |
end |
control:SetCallback("OnClick",ActivateControl) |
elseif v.type == "input" then |
local controlType = v.dialogControl or v.control or (v.multiline and "MultiLineEditBox") or "EditBox" |
control = gui:Create(controlType) |
if not control then |
geterrorhandler()(("Invalid Custom Control Type - %s"):format(tostring(controlType))) |
control = gui:Create(v.multiline and "MultiLineEditBox" or "EditBox") |
end |
if v.multiline then |
local lines = 4 |
if type(v.multiline) == "number" then |
lines = v.multiline |
end |
control:SetHeight(60 + (14*lines)) |
end |
control:SetLabel(name) |
control:SetCallback("OnEnterPressed",ActivateControl) |
local text = GetOptionsMemberValue("get",v, options, path, appName) |
if type(text) ~= "string" then |
text = "" |
end |
control:SetText(text) |
elseif v.type == "toggle" then |
control = gui:Create("CheckBox") |
control:SetLabel(name) |
control:SetTriState(v.tristate) |
local value = GetOptionsMemberValue("get",v, options, path, appName) |
control:SetValue(value) |
control:SetCallback("OnValueChanged",ActivateControl) |
if v.descStyle == "inline" then |
local desc = GetOptionsMemberValue("desc", v, options, path, appName) |
control:SetDescription(desc) |
end |
local image = GetOptionsMemberValue("image", v, options, path, appName) |
local imageCoords = GetOptionsMemberValue("imageCoords", v, options, path, appName) |
if type(image) == 'string' then |
if type(imageCoords) == 'table' then |
control:SetImage(image, unpack(imageCoords)) |
else |
control:SetImage(image) |
end |
end |
elseif v.type == "range" then |
control = gui:Create("Slider") |
control:SetLabel(name) |
control:SetSliderValues(v.min or 0,v.max or 100, v.bigStep or v.step or 0) |
control:SetIsPercent(v.isPercent) |
local value = GetOptionsMemberValue("get",v, options, path, appName) |
if type(value) ~= "number" then |
value = 0 |
end |
control:SetValue(value) |
control:SetCallback("OnValueChanged",ActivateSlider) |
control:SetCallback("OnMouseUp",ActivateSlider) |
elseif v.type == "select" then |
local values = GetOptionsMemberValue("values", v, options, path, appName) |
local controlType = v.dialogControl or v.control or "Dropdown" |
control = gui:Create(controlType) |
if not control then |
geterrorhandler()(("Invalid Custom Control Type - %s"):format(tostring(controlType))) |
control = gui:Create("Dropdown") |
end |
control:SetLabel(name) |
control:SetList(values) |
local value = GetOptionsMemberValue("get",v, options, path, appName) |
if not values[value] then |
value = nil |
end |
control:SetValue(value) |
control:SetCallback("OnValueChanged",ActivateControl) |
elseif v.type == "multiselect" then |
local values = GetOptionsMemberValue("values", v, options, path, appName) |
local disabled = CheckOptionDisabled(v, options, path, appName) |
local controlType = v.dialogControl or v.control |
local valuesort = new() |
if values then |
for value, text in pairs(values) do |
tinsert(valuesort, value) |
end |
end |
tsort(valuesort) |
if controlType then |
control = gui:Create(controlType) |
if not control then |
geterrorhandler()(("Invalid Custom Control Type - %s"):format(tostring(controlType))) |
end |
end |
if control then |
control:SetMultiselect(true) |
control:SetLabel(name) |
control:SetList(values) |
control:SetDisabled(disabled) |
control:SetCallback("OnValueChanged",ActivateControl) |
control:SetCallback("OnClosed", MultiControlOnClosed) |
local width = GetOptionsMemberValue("width",v,options,path,appName) |
if width == "double" then |
control:SetWidth(width_multiplier * 2) |
elseif width == "half" then |
control:SetWidth(width_multiplier / 2) |
elseif width == "full" then |
control.width = "fill" |
else |
control:SetWidth(width_multiplier) |
end |
--check:SetTriState(v.tristate) |
for i = 1, #valuesort do |
local key = valuesort[i] |
local value = GetOptionsMemberValue("get",v, options, path, appName, key) |
control:SetItemValue(key,value) |
end |
else |
control = gui:Create("InlineGroup") |
control:SetLayout("Flow") |
control:SetTitle(name) |
control.width = "fill" |
control:PauseLayout() |
local width = GetOptionsMemberValue("width",v,options,path,appName) |
for i = 1, #valuesort do |
local value = valuesort[i] |
local text = values[value] |
local check = gui:Create("CheckBox") |
check:SetLabel(text) |
check:SetUserData('value', value) |
check:SetUserData('text', text) |
check:SetDisabled(disabled) |
check:SetTriState(v.tristate) |
check:SetValue(GetOptionsMemberValue("get",v, options, path, appName, value)) |
check:SetCallback("OnValueChanged",ActivateMultiControl) |
InjectInfo(check, options, v, path, rootframe, appName) |
control:AddChild(check) |
if width == "double" then |
check:SetWidth(width_multiplier * 2) |
elseif width == "half" then |
check:SetWidth(width_multiplier / 2) |
elseif width == "full" then |
check.width = "fill" |
else |
check:SetWidth(width_multiplier) |
end |
end |
control:ResumeLayout() |
control:DoLayout() |
end |
del(valuesort) |
elseif v.type == "color" then |
control = gui:Create("ColorPicker") |
control:SetLabel(name) |
control:SetHasAlpha(v.hasAlpha) |
control:SetColor(GetOptionsMemberValue("get",v, options, path, appName)) |
control:SetCallback("OnValueChanged",ActivateControl) |
control:SetCallback("OnValueConfirmed",ActivateControl) |
elseif v.type == "keybinding" then |
control = gui:Create("Keybinding") |
control:SetLabel(name) |
control:SetKey(GetOptionsMemberValue("get",v, options, path, appName)) |
control:SetCallback("OnKeyChanged",ActivateControl) |
elseif v.type == "header" then |
control = gui:Create("Heading") |
control:SetText(name) |
control.width = "fill" |
elseif v.type == "description" then |
control = gui:Create("Label") |
control:SetText(name) |
local fontSize = GetOptionsMemberValue("fontSize",v, options, path, appName) |
if fontSize == "medium" then |
control:SetFontObject(GameFontHighlight) |
elseif fontSize == "large" then |
control:SetFontObject(GameFontHighlightLarge) |
else -- small or invalid |
control:SetFontObject(GameFontHighlightSmall) |
end |
local imageCoords = GetOptionsMemberValue("imageCoords",v, options, path, appName) |
local image, width, height = GetOptionsMemberValue("image",v, options, path, appName) |
if type(image) == 'string' then |
if not width then |
width = GetOptionsMemberValue("imageWidth",v, options, path, appName) |
end |
if not height then |
height = GetOptionsMemberValue("imageHeight",v, options, path, appName) |
end |
if type(imageCoords) == 'table' then |
control:SetImage(image, unpack(imageCoords)) |
else |
control:SetImage(image) |
end |
if type(width) ~= "number" then |
width = 32 |
end |
if type(height) ~= "number" then |
height = 32 |
end |
control:SetImageSize(width, height) |
end |
local width = GetOptionsMemberValue("width",v,options,path,appName) |
control.width = not width and "fill" |
end |
--Common Init |
if control then |
if control.width ~= "fill" then |
local width = GetOptionsMemberValue("width",v,options,path,appName) |
if width == "double" then |
control:SetWidth(width_multiplier * 2) |
elseif width == "half" then |
control:SetWidth(width_multiplier / 2) |
elseif width == "full" then |
control.width = "fill" |
else |
control:SetWidth(width_multiplier) |
end |
end |
if control.SetDisabled then |
local disabled = CheckOptionDisabled(v, options, path, appName) |
control:SetDisabled(disabled) |
end |
InjectInfo(control, options, v, path, rootframe, appName) |
container:AddChild(control) |
end |
end |
end |
tremove(path) |
end |
container:ResumeLayout() |
container:DoLayout() |
del(keySort) |
del(opts) |
end |
local function BuildPath(path, ...) |
for i = 1, select('#',...) do |
tinsert(path, (select(i,...))) |
end |
end |
local function TreeOnButtonEnter(widget, event, uniquevalue, button) |
local user = widget:GetUserDataTable() |
if not user then return end |
local options = user.options |
local option = user.option |
local path = user.path |
local appName = user.appName |
local feedpath = new() |
for i = 1, #path do |
feedpath[i] = path[i] |
end |
BuildPath(feedpath, ("\001"):split(uniquevalue)) |
local group = options |
for i = 1, #feedpath do |
if not group then return end |
group = GetSubOption(group, feedpath[i]) |
end |
local name = GetOptionsMemberValue("name", group, options, feedpath, appName) |
local desc = GetOptionsMemberValue("desc", group, options, feedpath, appName) |
GameTooltip:SetOwner(button, "ANCHOR_NONE") |
if widget.type == "TabGroup" then |
GameTooltip:SetPoint("BOTTOM",button,"TOP") |
else |
GameTooltip:SetPoint("LEFT",button,"RIGHT") |
end |
GameTooltip:SetText(name, 1, .82, 0, 1) |
if type(desc) == "string" then |
GameTooltip:AddLine(desc, 1, 1, 1, 1) |
end |
GameTooltip:Show() |
end |
local function TreeOnButtonLeave(widget, event, value, button) |
GameTooltip:Hide() |
end |
local function GroupExists(appName, options, path, uniquevalue) |
if not uniquevalue then return false end |
local feedpath = new() |
local temppath = new() |
for i = 1, #path do |
feedpath[i] = path[i] |
end |
BuildPath(feedpath, ("\001"):split(uniquevalue)) |
local group = options |
for i = 1, #feedpath do |
local v = feedpath[i] |
temppath[i] = v |
group = GetSubOption(group, v) |
if not group or group.type ~= "group" or CheckOptionHidden(group, options, temppath, appName) then |
del(feedpath) |
del(temppath) |
return false |
end |
end |
del(feedpath) |
del(temppath) |
return true |
end |
local function GroupSelected(widget, event, uniquevalue) |
local user = widget:GetUserDataTable() |
local options = user.options |
local option = user.option |
local path = user.path |
local rootframe = user.rootframe |
local feedpath = new() |
for i = 1, #path do |
feedpath[i] = path[i] |
end |
BuildPath(feedpath, ("\001"):split(uniquevalue)) |
local group = options |
for i = 1, #feedpath do |
group = GetSubOption(group, feedpath[i]) |
end |
widget:ReleaseChildren() |
AceConfigDialog:FeedGroup(user.appName,options,widget,rootframe,feedpath) |
del(feedpath) |
end |
--[[ |
-- INTERNAL -- |
This function will feed one group, and any inline child groups into the given container |
Select Groups will only have the selection control (tree, tabs, dropdown) fed in |
and have a group selected, this event will trigger the feeding of child groups |
Rules: |
If the group is Inline, FeedOptions |
If the group has no child groups, FeedOptions |
If the group is a tab or select group, FeedOptions then add the Group Control |
If the group is a tree group FeedOptions then |
its parent isnt a tree group: then add the tree control containing this and all child tree groups |
if its parent is a tree group, its already a node on a tree |
--]] |
function AceConfigDialog:FeedGroup(appName,options,container,rootframe,path, isRoot) |
local group = options |
--follow the path to get to the curent group |
local inline |
local grouptype, parenttype = options.childGroups, "none" |
--temp path table to pass to callbacks as we traverse the tree |
local temppath = new() |
for i = 1, #path do |
local v = path[i] |
temppath[i] = v |
group = GetSubOption(group, v) |
inline = inline or pickfirstset(v.dialogInline,v.guiInline,v.inline, false) |
parenttype = grouptype |
grouptype = group.childGroups |
end |
del(temppath) |
if not parenttype then |
parenttype = "tree" |
end |
--check if the group has child groups |
local hasChildGroups |
for k, v in pairs(group.args) do |
if v.type == "group" and not pickfirstset(v.dialogInline,v.guiInline,v.inline, false) and not CheckOptionHidden(v, options, path, appName) then |
hasChildGroups = true |
end |
end |
if group.plugins then |
for plugin, t in pairs(group.plugins) do |
for k, v in pairs(t) do |
if v.type == "group" and not pickfirstset(v.dialogInline,v.guiInline,v.inline, false) and not CheckOptionHidden(v, options, path, appName) then |
hasChildGroups = true |
end |
end |
end |
end |
container:SetLayout("flow") |
local scroll |
--Add a scrollframe if we are not going to add a group control, this is the inverse of the conditions for that later on |
if (not (hasChildGroups and not inline)) or (grouptype ~= "tab" and grouptype ~= "select" and (parenttype == "tree" and not isRoot)) then |
if container.type ~= "InlineGroup" and container.type ~= "SimpleGroup" then |
scroll = gui:Create("ScrollFrame") |
scroll:SetLayout("flow") |
scroll.width = "fill" |
scroll.height = "fill" |
container:SetLayout("fill") |
container:AddChild(scroll) |
container = scroll |
end |
end |
FeedOptions(appName,options,container,rootframe,path,group,nil) |
if scroll then |
container:PerformLayout() |
local status = self:GetStatusTable(appName, path) |
if not status.scroll then |
status.scroll = {} |
end |
scroll:SetStatusTable(status.scroll) |
end |
if hasChildGroups and not inline then |
local name = GetOptionsMemberValue("name", group, options, path, appName) |
if grouptype == "tab" then |
local tab = gui:Create("TabGroup") |
InjectInfo(tab, options, group, path, rootframe, appName) |
tab:SetCallback("OnGroupSelected", GroupSelected) |
tab:SetCallback("OnTabEnter", TreeOnButtonEnter) |
tab:SetCallback("OnTabLeave", TreeOnButtonLeave) |
local status = AceConfigDialog:GetStatusTable(appName, path) |
if not status.groups then |
status.groups = {} |
end |
tab:SetStatusTable(status.groups) |
tab.width = "fill" |
tab.height = "fill" |
local tabs = BuildGroups(group, options, path, appName) |
tab:SetTabs(tabs) |
tab:SetUserData("tablist", tabs) |
for i = 1, #tabs do |
local entry = tabs[i] |
if not entry.disabled then |
tab:SelectTab((GroupExists(appName, options, path,status.groups.selected) and status.groups.selected) or entry.value) |
break |
end |
end |
container:AddChild(tab) |
elseif grouptype == "select" then |
local select = gui:Create("DropdownGroup") |
select:SetTitle(name) |
InjectInfo(select, options, group, path, rootframe, appName) |
select:SetCallback("OnGroupSelected", GroupSelected) |
local status = AceConfigDialog:GetStatusTable(appName, path) |
if not status.groups then |
status.groups = {} |
end |
select:SetStatusTable(status.groups) |
local grouplist = BuildSelect(group, options, path, appName) |
select:SetGroupList(grouplist) |
select:SetUserData("grouplist", grouplist) |
local firstgroup |
for k, v in pairs(grouplist) do |
if not firstgroup or k < firstgroup then |
firstgroup = k |
end |
end |
if firstgroup then |
select:SetGroup((GroupExists(appName, options, path,status.groups.selected) and status.groups.selected) or firstgroup) |
end |
select.width = "fill" |
select.height = "fill" |
container:AddChild(select) |
--assume tree group by default |
--if parenttype is tree then this group is already a node on that tree |
elseif (parenttype ~= "tree") or isRoot then |
local tree = gui:Create("TreeGroup") |
InjectInfo(tree, options, group, path, rootframe, appName) |
tree:EnableButtonTooltips(false) |
tree.width = "fill" |
tree.height = "fill" |
tree:SetCallback("OnGroupSelected", GroupSelected) |
tree:SetCallback("OnButtonEnter", TreeOnButtonEnter) |
tree:SetCallback("OnButtonLeave", TreeOnButtonLeave) |
local status = AceConfigDialog:GetStatusTable(appName, path) |
if not status.groups then |
status.groups = {} |
end |
local treedefinition = BuildGroups(group, options, path, appName, true) |
tree:SetStatusTable(status.groups) |
tree:SetTree(treedefinition) |
tree:SetUserData("tree",treedefinition) |
for i = 1, #treedefinition do |
local entry = treedefinition[i] |
if not entry.disabled then |
tree:SelectByValue((GroupExists(appName, options, path,status.groups.selected) and status.groups.selected) or entry.value) |
break |
end |
end |
container:AddChild(tree) |
end |
end |
end |
local old_CloseSpecialWindows |
local function RefreshOnUpdate(this) |
for appName in pairs(this.closing) do |
if AceConfigDialog.OpenFrames[appName] then |
AceConfigDialog.OpenFrames[appName]:Hide() |
end |
if AceConfigDialog.BlizOptions and AceConfigDialog.BlizOptions[appName] then |
for key, widget in pairs(AceConfigDialog.BlizOptions[appName]) do |
if not widget:IsVisible() then |
widget:ReleaseChildren() |
end |
end |
end |
this.closing[appName] = nil |
end |
if this.closeAll then |
for k, v in pairs(AceConfigDialog.OpenFrames) do |
v:Hide() |
end |
this.closeAll = nil |
end |
for appName in pairs(this.apps) do |
if AceConfigDialog.OpenFrames[appName] then |
local user = AceConfigDialog.OpenFrames[appName]:GetUserDataTable() |
AceConfigDialog:Open(appName, unpack(user.basepath or emptyTbl)) |
end |
if AceConfigDialog.BlizOptions and AceConfigDialog.BlizOptions[appName] then |
for key, widget in pairs(AceConfigDialog.BlizOptions[appName]) do |
local user = widget:GetUserDataTable() |
if widget:IsVisible() then |
AceConfigDialog:Open(widget:GetUserData('appName'), widget, unpack(user.basepath or emptyTbl)) |
end |
end |
end |
this.apps[appName] = nil |
end |
this:SetScript("OnUpdate", nil) |
end |
-- Upgrade the OnUpdate script as well, if needed. |
if AceConfigDialog.frame:GetScript("OnUpdate") then |
AceConfigDialog.frame:SetScript("OnUpdate", RefreshOnUpdate) |
end |
--- Close all open options windows |
function AceConfigDialog:CloseAll() |
AceConfigDialog.frame.closeAll = true |
AceConfigDialog.frame:SetScript("OnUpdate", RefreshOnUpdate) |
if next(self.OpenFrames) then |
return true |
end |
end |
--- Close a specific options window. |
-- @param appName The application name as given to `:RegisterOptionsTable()` |
function AceConfigDialog:Close(appName) |
if self.OpenFrames[appName] then |
AceConfigDialog.frame.closing[appName] = true |
AceConfigDialog.frame:SetScript("OnUpdate", RefreshOnUpdate) |
return true |
end |
end |
-- Internal -- Called by AceConfigRegistry |
function AceConfigDialog:ConfigTableChanged(event, appName) |
AceConfigDialog.frame.apps[appName] = true |
AceConfigDialog.frame:SetScript("OnUpdate", RefreshOnUpdate) |
end |
reg.RegisterCallback(AceConfigDialog, "ConfigTableChange", "ConfigTableChanged") |
--- Sets the default size of the options window for a specific application. |
-- @param appName The application name as given to `:RegisterOptionsTable()` |
-- @param width The default width |
-- @param height The default height |
function AceConfigDialog:SetDefaultSize(appName, width, height) |
local status = AceConfigDialog:GetStatusTable(appName) |
if type(width) == "number" and type(height) == "number" then |
status.width = width |
status.height = height |
end |
end |
--- Open an option window at the specified path (if any). |
-- This function can optionally feed the group into a pre-created container |
-- instead of creating a new container frame. |
-- @paramsig appName [, container][, ...] |
-- @param appName The application name as given to `:RegisterOptionsTable()` |
-- @param container An optional container frame to feed the options into |
-- @param ... The path to open after creating the options window (see `:SelectGroup` for details) |
function AceConfigDialog:Open(appName, container, ...) |
if not old_CloseSpecialWindows then |
old_CloseSpecialWindows = CloseSpecialWindows |
CloseSpecialWindows = function() |
local found = old_CloseSpecialWindows() |
return self:CloseAll() or found |
end |
end |
local app = reg:GetOptionsTable(appName) |
if not app then |
error(("%s isn't registed with AceConfigRegistry, unable to open config"):format(appName), 2) |
end |
local options = app("dialog", MAJOR) |
local f |
local path = new() |
local name = GetOptionsMemberValue("name", options, options, path, appName) |
--If an optional path is specified add it to the path table before feeding the options |
--as container is optional as well it may contain the first element of the path |
if type(container) == "string" then |
tinsert(path, container) |
container = nil |
end |
for n = 1, select('#',...) do |
tinsert(path, (select(n, ...))) |
end |
--if a container is given feed into that |
if container then |
f = container |
f:ReleaseChildren() |
f:SetUserData('appName', appName) |
f:SetUserData('iscustom', true) |
if #path > 0 then |
f:SetUserData('basepath', copy(path)) |
end |
local status = AceConfigDialog:GetStatusTable(appName) |
if not status.width then |
status.width = 700 |
end |
if not status.height then |
status.height = 500 |
end |
if f.SetStatusTable then |
f:SetStatusTable(status) |
end |
if f.SetTitle then |
f:SetTitle(name or "") |
end |
else |
if not self.OpenFrames[appName] then |
f = gui:Create("Frame") |
self.OpenFrames[appName] = f |
else |
f = self.OpenFrames[appName] |
end |
f:ReleaseChildren() |
f:SetCallback("OnClose", FrameOnClose) |
f:SetUserData('appName', appName) |
if #path > 0 then |
f:SetUserData('basepath', copy(path)) |
end |
f:SetTitle(name or "") |
local status = AceConfigDialog:GetStatusTable(appName) |
f:SetStatusTable(status) |
end |
self:FeedGroup(appName,options,f,f,path,true) |
if f.Show then |
f:Show() |
end |
del(path) |
end |
-- convert pre-39 BlizOptions structure to the new format |
if oldminor and oldminor < 39 and AceConfigDialog.BlizOptions then |
local old = AceConfigDialog.BlizOptions |
local new = {} |
for key, widget in pairs(old) do |
local appName = widget:GetUserData('appName') |
if not new[appName] then new[appName] = {} end |
new[appName][key] = widget |
end |
AceConfigDialog.BlizOptions = new |
else |
AceConfigDialog.BlizOptions = AceConfigDialog.BlizOptions or {} |
end |
local function FeedToBlizPanel(widget, event) |
local path = widget:GetUserData('path') |
AceConfigDialog:Open(widget:GetUserData('appName'), widget, unpack(path or emptyTbl)) |
end |
local function ClearBlizPanel(widget, event) |
local appName = widget:GetUserData('appName') |
AceConfigDialog.frame.closing[appName] = true |
AceConfigDialog.frame:SetScript("OnUpdate", RefreshOnUpdate) |
end |
--- Add an option table into the Blizzard Interface Options panel. |
-- You can optionally supply a descriptive name to use and a parent frame to use, |
-- as well as a path in the options table.\\ |
-- If no name is specified, the appName will be used instead. |
-- |
-- If you specify a proper `parent` (by name), the interface options will generate a |
-- tree layout. Note that only one level of children is supported, so the parent always |
-- has to be a head-level note. |
-- |
-- This function returns a reference to the container frame registered with the Interface |
-- Options. You can use this reference to open the options with the API function |
-- `InterfaceOptionsFrame_OpenToCategory`. |
-- @param appName The application name as given to `:RegisterOptionsTable()` |
-- @param name A descriptive name to display in the options tree (defaults to appName) |
-- @param parent The parent to use in the interface options tree. |
-- @param ... The path in the options table to feed into the interface options panel. |
-- @return The reference to the frame registered into the Interface Options. |
function AceConfigDialog:AddToBlizOptions(appName, name, parent, ...) |
local BlizOptions = AceConfigDialog.BlizOptions |
local key = appName |
for n = 1, select('#', ...) do |
key = key..'\001'..select(n, ...) |
end |
if not BlizOptions[appName] then |
BlizOptions[appName] = {} |
end |
if not BlizOptions[appName][key] then |
local group = gui:Create("BlizOptionsGroup") |
BlizOptions[appName][key] = group |
group:SetName(name or appName, parent) |
group:SetTitle(name or appName) |
group:SetUserData('appName', appName) |
if select('#', ...) > 0 then |
local path = {} |
for n = 1, select('#',...) do |
tinsert(path, (select(n, ...))) |
end |
group:SetUserData('path', path) |
end |
group:SetCallback("OnShow", FeedToBlizPanel) |
group:SetCallback("OnHide", ClearBlizPanel) |
InterfaceOptions_AddCategory(group.frame) |
return group.frame |
else |
error(("%s has already been added to the Blizzard Options Window with the given path"):format(appName), 2) |
end |
end |
<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="AceConfigCmd-3.0.lua"/> |
</Ui> |
--- AceConfigCmd-3.0 handles access to an options table through the "command line" interface via the ChatFrames. |
-- @class file |
-- @name AceConfigCmd-3.0 |
-- @release $Id: AceConfigCmd-3.0.lua 904 2009-12-13 11:56:37Z nevcairiel $ |
--[[ |
AceConfigCmd-3.0 |
Handles commandline optionstable access |
REQUIRES: AceConsole-3.0 for command registration (loaded on demand) |
]] |
-- TODO: plugin args |
local MAJOR, MINOR = "AceConfigCmd-3.0", 12 |
local AceConfigCmd = LibStub:NewLibrary(MAJOR, MINOR) |
if not AceConfigCmd then return end |
AceConfigCmd.commands = AceConfigCmd.commands or {} |
local commands = AceConfigCmd.commands |
local cfgreg = LibStub("AceConfigRegistry-3.0") |
local AceConsole -- LoD |
local AceConsoleName = "AceConsole-3.0" |
-- Lua APIs |
local strsub, strsplit, strlower, strmatch, strtrim = string.sub, string.split, string.lower, string.match, string.trim |
local format, tonumber, tostring = string.format, tonumber, tostring |
local tsort, tinsert = table.sort, table.insert |
local select, pairs, next, type = select, pairs, next, type |
local error, assert = error, assert |
-- WoW APIs |
local _G = _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, SELECTED_CHAT_FRAME, DEFAULT_CHAT_FRAME |
local L = setmetatable({}, { -- TODO: replace with proper locale |
__index = function(self,k) return k end |
}) |
local function print(msg) |
(SELECTED_CHAT_FRAME or DEFAULT_CHAT_FRAME):AddMessage(msg) |
end |
-- constants used by getparam() calls below |
local handlertypes = {["table"]=true} |
local handlermsg = "expected a table" |
local functypes = {["function"]=true, ["string"]=true} |
local funcmsg = "expected function or member name" |
-- pickfirstset() - picks the first non-nil value and returns it |
local function pickfirstset(...) |
for i=1,select("#",...) do |
if select(i,...)~=nil then |
return select(i,...) |
end |
end |
end |
-- err() - produce real error() regarding malformed options tables etc |
local function err(info,inputpos,msg ) |
local cmdstr=" "..strsub(info.input, 1, inputpos-1) |
error(MAJOR..": /" ..info[0] ..cmdstr ..": "..(msg or "malformed options table"), 2) |
end |
-- usererr() - produce chatframe message regarding bad slash syntax etc |
local function usererr(info,inputpos,msg ) |
local cmdstr=strsub(info.input, 1, inputpos-1); |
print("/" ..info[0] .. " "..cmdstr ..": "..(msg or "malformed options table")) |
end |
-- callmethod() - call a given named method (e.g. "get", "set") with given arguments |
local function callmethod(info, inputpos, tab, methodtype, ...) |
local method = info[methodtype] |
if not method then |
err(info, inputpos, "'"..methodtype.."': not set") |
end |
info.arg = tab.arg |
info.option = tab |
info.type = tab.type |
if type(method)=="function" then |
return method(info, ...) |
elseif type(method)=="string" then |
if type(info.handler[method])~="function" then |
err(info, inputpos, "'"..methodtype.."': '"..method.."' is not a member function of "..tostring(info.handler)) |
end |
return info.handler[method](info.handler, info, ...) |
else |
assert(false) -- type should have already been checked on read |
end |
end |
-- callfunction() - call a given named function (e.g. "name", "desc") with given arguments |
local function callfunction(info, tab, methodtype, ...) |
local method = tab[methodtype] |
info.arg = tab.arg |
info.option = tab |
info.type = tab.type |
if type(method)=="function" then |
return method(info, ...) |
else |
assert(false) -- type should have already been checked on read |
end |
end |
-- do_final() - do the final step (set/execute) along with validation and confirmation |
local function do_final(info, inputpos, tab, methodtype, ...) |
if info.validate then |
local res = callmethod(info,inputpos,tab,"validate",...) |
if type(res)=="string" then |
usererr(info, inputpos, "'"..strsub(info.input, inputpos).."' - "..res) |
return |
end |
end |
-- console ignores .confirm |
callmethod(info,inputpos,tab,methodtype, ...) |
end |
-- getparam() - used by handle() to retreive and store "handler", "get", "set", etc |
local function getparam(info, inputpos, tab, depth, paramname, types, errormsg) |
local old,oldat = info[paramname], info[paramname.."_at"] |
local val=tab[paramname] |
if val~=nil then |
if val==false then |
val=nil |
elseif not types[type(val)] then |
err(info, inputpos, "'" .. paramname.. "' - "..errormsg) |
end |
info[paramname] = val |
info[paramname.."_at"] = depth |
end |
return old,oldat |
end |
-- iterateargs(tab) - custom iterator that iterates both t.args and t.plugins.* |
local dummytable={} |
local function iterateargs(tab) |
if not tab.plugins then |
return pairs(tab.args) |
end |
local argtabkey,argtab=next(tab.plugins) |
local v |
return function(_, k) |
while argtab do |
k,v = next(argtab, k) |
if k then return k,v end |
if argtab==tab.args then |
argtab=nil |
else |
argtabkey,argtab = next(tab.plugins, argtabkey) |
if not argtabkey then |
argtab=tab.args |
end |
end |
end |
end |
end |
local function checkhidden(info, inputpos, tab) |
if tab.cmdHidden~=nil then |
return tab.cmdHidden |
end |
local hidden = tab.hidden |
if type(hidden) == "function" or type(hidden) == "string" then |
info.hidden = hidden |
hidden = callmethod(info, inputpos, tab, 'hidden') |
info.hidden = nil |
end |
return hidden |
end |
local function showhelp(info, inputpos, tab, depth, noHead) |
if not noHead then |
print("|cff33ff99"..info.appName.."|r: Arguments to |cffffff78/"..info[0].."|r "..strsub(info.input,1,inputpos-1)..":") |
end |
local sortTbl = {} -- [1..n]=name |
local refTbl = {} -- [name]=tableref |
for k,v in iterateargs(tab) do |
if not refTbl[k] then -- a plugin overriding something in .args |
tinsert(sortTbl, k) |
refTbl[k] = v |
end |
end |
tsort(sortTbl, function(one, two) |
local o1 = refTbl[one].order or 100 |
local o2 = refTbl[two].order or 100 |
if type(o1) == "function" or type(o1) == "string" then |
info.order = o1 |
info[#info+1] = one |
o1 = callmethod(info, inputpos, refTbl[one], "order") |
info[#info] = nil |
info.order = nil |
end |
if type(o2) == "function" or type(o1) == "string" then |
info.order = o2 |
info[#info+1] = two |
o2 = callmethod(info, inputpos, refTbl[two], "order") |
info[#info] = nil |
info.order = nil |
end |
if o1<0 and o2<0 then return o1<o2 end |
if o2<0 then return true end |
if o1<0 then return false end |
if o1==o2 then return tostring(one)<tostring(two) end -- compare names |
return o1<o2 |
end) |
for i = 1, #sortTbl do |
local k = sortTbl[i] |
local v = refTbl[k] |
if not checkhidden(info, inputpos, v) then |
if v.type ~= "description" and v.type ~= "header" then |
-- recursively show all inline groups |
local name, desc = v.name, v.desc |
if type(name) == "function" then |
name = callfunction(info, v, 'name') |
end |
if type(desc) == "function" then |
desc = callfunction(info, v, 'desc') |
end |
if v.type == "group" and pickfirstset(v.cmdInline, v.inline, false) then |
print(" "..(desc or name)..":") |
local oldhandler,oldhandler_at = getparam(info, inputpos, v, depth, "handler", handlertypes, handlermsg) |
showhelp(info, inputpos, v, depth, true) |
info.handler,info.handler_at = oldhandler,oldhandler_at |
else |
local key = k:gsub(" ", "_") |
print(" |cffffff78"..key.."|r - "..(desc or name or "")) |
end |
end |
end |
end |
end |
local function keybindingValidateFunc(text) |
if text == nil or text == "NONE" then |
return nil |
end |
text = text:upper() |
local shift, ctrl, alt |
local modifier |
while true do |
if text == "-" then |
break |
end |
modifier, text = strsplit('-', text, 2) |
if text then |
if modifier ~= "SHIFT" and modifier ~= "CTRL" and modifier ~= "ALT" then |
return false |
end |
if modifier == "SHIFT" then |
if shift then |
return false |
end |
shift = true |
end |
if modifier == "CTRL" then |
if ctrl then |
return false |
end |
ctrl = true |
end |
if modifier == "ALT" then |
if alt then |
return false |
end |
alt = true |
end |
else |
text = modifier |
break |
end |
end |
if text == "" then |
return false |
end |
if not text:find("^F%d+$") and text ~= "CAPSLOCK" and text:len() ~= 1 and (text:byte() < 128 or text:len() > 4) and not _G["KEY_" .. text] then |
return false |
end |
local s = text |
if shift then |
s = "SHIFT-" .. s |
end |
if ctrl then |
s = "CTRL-" .. s |
end |
if alt then |
s = "ALT-" .. s |
end |
return s |
end |
-- handle() - selfrecursing function that processes input->optiontable |
-- - depth - starts at 0 |
-- - retfalse - return false rather than produce error if a match is not found (used by inlined groups) |
local function handle(info, inputpos, tab, depth, retfalse) |
if not(type(tab)=="table" and type(tab.type)=="string") then err(info,inputpos) end |
------------------------------------------------------------------- |
-- Grab hold of handler,set,get,func,etc if set (and remember old ones) |
-- Note that we do NOT validate if method names are correct at this stage, |
-- the handler may change before they're actually used! |
local oldhandler,oldhandler_at = getparam(info,inputpos,tab,depth,"handler",handlertypes,handlermsg) |
local oldset,oldset_at = getparam(info,inputpos,tab,depth,"set",functypes,funcmsg) |
local oldget,oldget_at = getparam(info,inputpos,tab,depth,"get",functypes,funcmsg) |
local oldfunc,oldfunc_at = getparam(info,inputpos,tab,depth,"func",functypes,funcmsg) |
local oldvalidate,oldvalidate_at = getparam(info,inputpos,tab,depth,"validate",functypes,funcmsg) |
--local oldconfirm,oldconfirm_at = getparam(info,inputpos,tab,depth,"confirm",functypes,funcmsg) |
------------------------------------------------------------------- |
-- Act according to .type of this table |
if tab.type=="group" then |
------------ group -------------------------------------------- |
if type(tab.args)~="table" then err(info, inputpos) end |
if tab.plugins and type(tab.plugins)~="table" then err(info,inputpos) end |
-- grab next arg from input |
local _,nextpos,arg = (info.input):find(" *([^ ]+) *", inputpos) |
if not arg then |
showhelp(info, inputpos, tab, depth) |
return |
end |
nextpos=nextpos+1 |
-- loop .args and try to find a key with a matching name |
for k,v in iterateargs(tab) do |
if not(type(k)=="string" and type(v)=="table" and type(v.type)=="string") then err(info,inputpos, "options table child '"..tostring(k).."' is malformed") end |
-- is this child an inline group? if so, traverse into it |
if v.type=="group" and pickfirstset(v.cmdInline, v.inline, false) then |
info[depth+1] = k |
if handle(info, inputpos, v, depth+1, true)==false then |
info[depth+1] = nil |
-- wasn't found in there, but that's ok, we just keep looking down here |
else |
return -- done, name was found in inline group |
end |
-- matching name and not a inline group |
elseif strlower(arg)==strlower(k:gsub(" ", "_")) then |
info[depth+1] = k |
return handle(info,nextpos,v,depth+1) |
end |
end |
-- no match |
if retfalse then |
-- restore old infotable members and return false to indicate failure |
info.handler,info.handler_at = oldhandler,oldhandler_at |
info.set,info.set_at = oldset,oldset_at |
info.get,info.get_at = oldget,oldget_at |
info.func,info.func_at = oldfunc,oldfunc_at |
info.validate,info.validate_at = oldvalidate,oldvalidate_at |
--info.confirm,info.confirm_at = oldconfirm,oldconfirm_at |
return false |
end |
-- couldn't find the command, display error |
usererr(info, inputpos, "'"..arg.."' - " .. L["unknown argument"]) |
return |
end |
local str = strsub(info.input,inputpos); |
if tab.type=="execute" then |
------------ execute -------------------------------------------- |
do_final(info, inputpos, tab, "func") |
elseif tab.type=="input" then |
------------ input -------------------------------------------- |
local res = true |
if tab.pattern then |
if not(type(tab.pattern)=="string") then err(info, inputpos, "'pattern' - expected a string") end |
if not strmatch(str, tab.pattern) then |
usererr(info, inputpos, "'"..str.."' - " .. L["invalid input"]) |
return |
end |
end |
do_final(info, inputpos, tab, "set", str) |
elseif tab.type=="toggle" then |
------------ toggle -------------------------------------------- |
local b |
local str = strtrim(strlower(str)) |
if str=="" then |
b = callmethod(info, inputpos, tab, "get") |
if tab.tristate then |
--cycle in true, nil, false order |
if b then |
b = nil |
elseif b == nil then |
b = false |
else |
b = true |
end |
else |
b = not b |
end |
elseif str==L["on"] then |
b = true |
elseif str==L["off"] then |
b = false |
elseif tab.tristate and str==L["default"] then |
b = nil |
else |
if tab.tristate then |
usererr(info, inputpos, format(L["'%s' - expected 'on', 'off' or 'default', or no argument to toggle."], str)) |
else |
usererr(info, inputpos, format(L["'%s' - expected 'on' or 'off', or no argument to toggle."], str)) |
end |
return |
end |
do_final(info, inputpos, tab, "set", b) |
elseif tab.type=="range" then |
------------ range -------------------------------------------- |
local val = tonumber(str) |
if not val then |
usererr(info, inputpos, "'"..str.."' - "..L["expected number"]) |
return |
end |
if type(info.step)=="number" then |
val = val- (val % info.step) |
end |
if type(info.min)=="number" and val<info.min then |
usererr(info, inputpos, val.." - "..format(L["must be equal to or higher than %s"], tostring(info.min)) ) |
return |
end |
if type(info.max)=="number" and val>info.max then |
usererr(info, inputpos, val.." - "..format(L["must be equal to or lower than %s"], tostring(info.max)) ) |
return |
end |
do_final(info, inputpos, tab, "set", val) |
elseif tab.type=="select" then |
------------ select ------------------------------------ |
local str = strtrim(strlower(str)) |
local values = tab.values |
if type(values) == "function" or type(values) == "string" then |
info.values = values |
values = callmethod(info, inputpos, tab, "values") |
info.values = nil |
end |
if str == "" then |
local b = callmethod(info, inputpos, tab, "get") |
local fmt = "|cffffff78- [%s]|r %s" |
local fmt_sel = "|cffffff78- [%s]|r %s |cffff0000*|r" |
print(L["Options for |cffffff78"..info[#info].."|r:"]) |
for k, v in pairs(values) do |
if b == k then |
print(fmt_sel:format(k, v)) |
else |
print(fmt:format(k, v)) |
end |
end |
return |
end |
local ok |
for k,v in pairs(values) do |
if strlower(k)==str then |
str = k -- overwrite with key (in case of case mismatches) |
ok = true |
break |
end |
end |
if not ok then |
usererr(info, inputpos, "'"..str.."' - "..L["unknown selection"]) |
return |
end |
do_final(info, inputpos, tab, "set", str) |
elseif tab.type=="multiselect" then |
------------ multiselect ------------------------------------------- |
local str = strtrim(strlower(str)) |
local values = tab.values |
if type(values) == "function" or type(values) == "string" then |
info.values = values |
values = callmethod(info, inputpos, tab, "values") |
info.values = nil |
end |
if str == "" then |
local fmt = "|cffffff78- [%s]|r %s" |
local fmt_sel = "|cffffff78- [%s]|r %s |cffff0000*|r" |
print(L["Options for |cffffff78"..info[#info].."|r (multiple possible):"]) |
for k, v in pairs(values) do |
if callmethod(info, inputpos, tab, "get", k) then |
print(fmt_sel:format(k, v)) |
else |
print(fmt:format(k, v)) |
end |
end |
return |
end |
--build a table of the selections, checking that they exist |
--parse for =on =off =default in the process |
--table will be key = true for options that should toggle, key = [on|off|default] for options to be set |
local sels = {} |
for v in str:gmatch("[^ ]+") do |
--parse option=on etc |
local opt, val = v:match('(.+)=(.+)') |
--get option if toggling |
if not opt then |
opt = v |
end |
--check that the opt is valid |
local ok |
for k,v in pairs(values) do |
if strlower(k)==opt then |
opt = k -- overwrite with key (in case of case mismatches) |
ok = true |
break |
end |
end |
if not ok then |
usererr(info, inputpos, "'"..opt.."' - "..L["unknown selection"]) |
return |
end |
--check that if val was supplied it is valid |
if val then |
if val == L["on"] or val == L["off"] or (tab.tristate and val == L["default"]) then |
--val is valid insert it |
sels[opt] = val |
else |
if tab.tristate then |
usererr(info, inputpos, format(L["'%s' '%s' - expected 'on', 'off' or 'default', or no argument to toggle."], v, val)) |
else |
usererr(info, inputpos, format(L["'%s' '%s' - expected 'on' or 'off', or no argument to toggle."], v, val)) |
end |
return |
end |
else |
-- no val supplied, toggle |
sels[opt] = true |
end |
end |
for opt, val in pairs(sels) do |
local newval |
if (val == true) then |
--toggle the option |
local b = callmethod(info, inputpos, tab, "get", opt) |
if tab.tristate then |
--cycle in true, nil, false order |
if b then |
b = nil |
elseif b == nil then |
b = false |
else |
b = true |
end |
else |
b = not b |
end |
newval = b |
else |
--set the option as specified |
if val==L["on"] then |
newval = true |
elseif val==L["off"] then |
newval = false |
elseif val==L["default"] then |
newval = nil |
end |
end |
do_final(info, inputpos, tab, "set", opt, newval) |
end |
elseif tab.type=="color" then |
------------ color -------------------------------------------- |
local str = strtrim(strlower(str)) |
if str == "" then |
--TODO: Show current value |
return |
end |
local r, g, b, a |
if tab.hasAlpha then |
if str:len() == 8 and str:find("^%x*$") then |
--parse a hex string |
r,g,b,a = tonumber(str:sub(1, 2), 16) / 255, tonumber(str:sub(3, 4), 16) / 255, tonumber(str:sub(5, 6), 16) / 255, tonumber(str:sub(7, 8), 16) / 255 |
else |
--parse seperate values |
r,g,b,a = str:match("^([%d%.]+) ([%d%.]+) ([%d%.]+) ([%d%.]+)$") |
r,g,b,a = tonumber(r), tonumber(g), tonumber(b), tonumber(a) |
end |
if not (r and g and b and a) then |
usererr(info, inputpos, format(L["'%s' - expected 'RRGGBBAA' or 'r g b a'."], str)) |
return |
end |
if r >= 0.0 and r <= 1.0 and g >= 0.0 and g <= 1.0 and b >= 0.0 and b <= 1.0 and a >= 0.0 and a <= 1.0 then |
--values are valid |
elseif r >= 0 and r <= 255 and g >= 0 and g <= 255 and b >= 0 and b <= 255 and a >= 0 and a <= 255 then |
--values are valid 0..255, convert to 0..1 |
r = r / 255 |
g = g / 255 |
b = b / 255 |
a = a / 255 |
else |
--values are invalid |
usererr(info, inputpos, format(L["'%s' - values must all be either in the range 0..1 or 0..255."], str)) |
end |
else |
a = 1.0 |
if str:len() == 6 and str:find("^%x*$") then |
--parse a hex string |
r,g,b = tonumber(str:sub(1, 2), 16) / 255, tonumber(str:sub(3, 4), 16) / 255, tonumber(str:sub(5, 6), 16) / 255 |
else |
--parse seperate values |
r,g,b = str:match("^([%d%.]+) ([%d%.]+) ([%d%.]+)$") |
r,g,b = tonumber(r), tonumber(g), tonumber(b) |
end |
if not (r and g and b) then |
usererr(info, inputpos, format(L["'%s' - expected 'RRGGBB' or 'r g b'."], str)) |
return |
end |
if r >= 0.0 and r <= 1.0 and g >= 0.0 and g <= 1.0 and b >= 0.0 and b <= 1.0 then |
--values are valid |
elseif r >= 0 and r <= 255 and g >= 0 and g <= 255 and b >= 0 and b <= 255 then |
--values are valid 0..255, convert to 0..1 |
r = r / 255 |
g = g / 255 |
b = b / 255 |
else |
--values are invalid |
usererr(info, inputpos, format(L["'%s' - values must all be either in the range 0-1 or 0-255."], str)) |
end |
end |
do_final(info, inputpos, tab, "set", r,g,b,a) |
elseif tab.type=="keybinding" then |
------------ keybinding -------------------------------------------- |
local str = strtrim(strlower(str)) |
if str == "" then |
--TODO: Show current value |
return |
end |
local value = keybindingValidateFunc(str:upper()) |
if value == false then |
usererr(info, inputpos, format(L["'%s' - Invalid Keybinding."], str)) |
return |
end |
do_final(info, inputpos, tab, "set", value) |
elseif tab.type=="description" then |
------------ description -------------------- |
-- ignore description, GUI config only |
else |
err(info, inputpos, "unknown options table item type '"..tostring(tab.type).."'") |
end |
end |
--- Handle the chat command. |
-- This is usually called from a chat command handler to parse the command input as operations on an aceoptions table.\\ |
-- AceConfigCmd uses this function internally when a slash command is registered with `:CreateChatCommand` |
-- @param slashcmd The slash command WITHOUT leading slash (only used for error output) |
-- @param appName The application name as given to `:RegisterOptionsTable()` |
-- @param input The commandline input (as given by the WoW handler, i.e. without the command itself) |
-- @usage |
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon", "AceConsole-3.0") |
-- -- Use AceConsole-3.0 to register a Chat Command |
-- MyAddon:RegisterChatCommand("mychat", "ChatCommand") |
-- |
-- -- Show the GUI if no input is supplied, otherwise handle the chat input. |
-- function MyAddon:ChatCommand(input) |
-- -- Assuming "MyOptions" is the appName of a valid options table |
-- if not input or input:trim() == "" then |
-- LibStub("AceConfigDialog-3.0"):Open("MyOptions") |
-- else |
-- LibStub("AceConfigCmd-3.0").HandleCommand(MyAddon, "mychat", "MyOptions", input) |
-- end |
-- end |
function AceConfigCmd:HandleCommand(slashcmd, appName, input) |
local optgetter = cfgreg:GetOptionsTable(appName) |
if not optgetter then |
error([[Usage: HandleCommand("slashcmd", "appName", "input"): 'appName' - no options table "]]..tostring(appName)..[[" has been registered]], 2) |
end |
local options = assert( optgetter("cmd", MAJOR) ) |
local info = { -- Don't try to recycle this, it gets handed off to callbacks and whatnot |
[0] = slashcmd, |
appName = appName, |
options = options, |
input = input, |
self = self, |
handler = self, |
uiType = "cmd", |
uiName = MAJOR, |
} |
handle(info, 1, options, 0) -- (info, inputpos, table, depth) |
end |
--- Utility function to create a slash command handler. |
-- Also registers tab completion with AceTab |
-- @param slashcmd The slash command WITHOUT leading slash (only used for error output) |
-- @param appName The application name as given to `:RegisterOptionsTable()` |
function AceConfigCmd:CreateChatCommand(slashcmd, appName) |
if not AceConsole then |
AceConsole = LibStub(AceConsoleName) |
end |
if AceConsole.RegisterChatCommand(self, slashcmd, function(input) |
AceConfigCmd.HandleCommand(self, slashcmd, appName, input) -- upgradable |
end, |
true) then -- succesfully registered so lets get the command -> app table in |
commands[slashcmd] = appName |
end |
end |
--- Utility function that returns the options table that belongs to a slashcommand. |
-- Designed to be used for the AceTab interface. |
-- @param slashcmd The slash command WITHOUT leading slash (only used for error output) |
-- @return The options table associated with the slash command (or nil if the slash command was not registered) |
function AceConfigCmd:GetChatCommandOptions(slashcmd) |
return commands[slashcmd] |
end |
<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="AceConfigRegistry-3.0.lua"/> |
</Ui> |
--- AceConfigRegistry-3.0 handles central registration of options tables in use by addons and modules.\\ |
-- Options tables can be registered as raw tables, OR as function refs that return a table.\\ |
-- Such functions receive three arguments: "uiType", "uiName", "appName". \\ |
-- * Valid **uiTypes**: "cmd", "dropdown", "dialog". This is verified by the library at call time. \\ |
-- * The **uiName** field is expected to contain the full name of the calling addon, including version, e.g. "FooBar-1.0". This is verified by the library at call time.\\ |
-- * The **appName** field is the options table name as given at registration time \\ |
-- |
-- :IterateOptionsTables() (and :GetOptionsTable() if only given one argument) return a function reference that the requesting config handling addon must call with valid "uiType", "uiName". |
-- @class file |
-- @name AceConfigRegistry-3.0 |
-- @release $Id: AceConfigRegistry-3.0.lua 890 2009-12-06 12:50:05Z nevcairiel $ |
local MAJOR, MINOR = "AceConfigRegistry-3.0", 11 |
local AceConfigRegistry = LibStub:NewLibrary(MAJOR, MINOR) |
if not AceConfigRegistry then return end |
AceConfigRegistry.tables = AceConfigRegistry.tables or {} |
local CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0") |
if not AceConfigRegistry.callbacks then |
AceConfigRegistry.callbacks = CallbackHandler:New(AceConfigRegistry) |
end |
-- Lua APIs |
local tinsert, tconcat = table.insert, table.concat |
local strfind, strmatch = string.find, string.match |
local type, tostring, select, pairs = type, tostring, select, pairs |
local error, assert = error, assert |
----------------------------------------------------------------------- |
-- Validating options table consistency: |
AceConfigRegistry.validated = { |
-- list of options table names ran through :ValidateOptionsTable automatically. |
-- CLEARED ON PURPOSE, since newer versions may have newer validators |
cmd = {}, |
dropdown = {}, |
dialog = {}, |
} |
local function err(msg, errlvl, ...) |
local t = {} |
for i=select("#",...),1,-1 do |
tinsert(t, (select(i, ...))) |
end |
error(MAJOR..":ValidateOptionsTable(): "..tconcat(t,".")..msg, errlvl+2) |
end |
local isstring={["string"]=true, _="string"} |
local isstringfunc={["string"]=true,["function"]=true, _="string or funcref"} |
local istable={["table"]=true, _="table"} |
local ismethodtable={["table"]=true,["string"]=true,["function"]=true, _="methodname, funcref or table"} |
local optstring={["nil"]=true,["string"]=true, _="string"} |
local optstringfunc={["nil"]=true,["string"]=true,["function"]=true, _="string or funcref"} |
local optnumber={["nil"]=true,["number"]=true, _="number"} |
local optmethod={["nil"]=true,["string"]=true,["function"]=true, _="methodname or funcref"} |
local optmethodfalse={["nil"]=true,["string"]=true,["function"]=true,["boolean"]={[false]=true}, _="methodname, funcref or false"} |
local optmethodnumber={["nil"]=true,["string"]=true,["function"]=true,["number"]=true, _="methodname, funcref or number"} |
local optmethodtable={["nil"]=true,["string"]=true,["function"]=true,["table"]=true, _="methodname, funcref or table"} |
local optmethodbool={["nil"]=true,["string"]=true,["function"]=true,["boolean"]=true, _="methodname, funcref or boolean"} |
local opttable={["nil"]=true,["table"]=true, _="table"} |
local optbool={["nil"]=true,["boolean"]=true, _="boolean"} |
local optboolnumber={["nil"]=true,["boolean"]=true,["number"]=true, _="boolean or number"} |
local basekeys={ |
type=isstring, |
name=isstringfunc, |
desc=optstringfunc, |
descStyle=optstring, |
order=optmethodnumber, |
validate=optmethodfalse, |
confirm=optmethodbool, |
confirmText=optstring, |
disabled=optmethodbool, |
hidden=optmethodbool, |
guiHidden=optmethodbool, |
dialogHidden=optmethodbool, |
dropdownHidden=optmethodbool, |
cmdHidden=optmethodbool, |
icon=optstringfunc, |
iconCoords=optmethodtable, |
handler=opttable, |
get=optmethodfalse, |
set=optmethodfalse, |
func=optmethodfalse, |
arg={["*"]=true}, |
width=optstring, |
} |
local typedkeys={ |
header={}, |
description={ |
image=optstringfunc, |
imageCoords=optmethodtable, |
imageHeight=optnumber, |
imageWidth=optnumber, |
fontSize=optstringfunc, |
}, |
group={ |
args=istable, |
plugins=opttable, |
inline=optbool, |
cmdInline=optbool, |
guiInline=optbool, |
dropdownInline=optbool, |
dialogInline=optbool, |
childGroups=optstring, |
}, |
execute={ |
image=optstringfunc, |
imageCoords=optmethodtable, |
imageHeight=optnumber, |
imageWidth=optnumber, |
}, |
input={ |
pattern=optstring, |
usage=optstring, |
control=optstring, |
dialogControl=optstring, |
dropdownControl=optstring, |
multiline=optboolnumber, |
}, |
toggle={ |
tristate=optbool, |
image=optstringfunc, |
imageCoords=optmethodtable, |
}, |
tristate={ |
}, |
range={ |
min=optnumber, |
max=optnumber, |
step=optnumber, |
bigStep=optnumber, |
isPercent=optbool, |
}, |
select={ |
values=ismethodtable, |
style={ |
["nil"]=true, |
["string"]={dropdown=true,radio=true}, |
_="string: 'dropdown' or 'radio'" |
}, |
control=optstring, |
dialogControl=optstring, |
dropdownControl=optstring, |
}, |
multiselect={ |
values=ismethodtable, |
style=optstring, |
tristate=optbool, |
control=optstring, |
dialogControl=optstring, |
dropdownControl=optstring, |
}, |
color={ |
hasAlpha=optbool, |
}, |
keybinding={ |
-- TODO |
}, |
} |
local function validateKey(k,errlvl,...) |
errlvl=(errlvl or 0)+1 |
if type(k)~="string" then |
err("["..tostring(k).."] - key is not a string", errlvl,...) |
end |
if strfind(k, "[%c\127]") then |
err("["..tostring(k).."] - key name contained control characters", errlvl,...) |
end |
end |
local function validateVal(v, oktypes, errlvl,...) |
errlvl=(errlvl or 0)+1 |
local isok=oktypes[type(v)] or oktypes["*"] |
if not isok then |
err(": expected a "..oktypes._..", got '"..tostring(v).."'", errlvl,...) |
end |
if type(isok)=="table" then -- isok was a table containing specific values to be tested for! |
if not isok[v] then |
err(": did not expect "..type(v).." value '"..tostring(v).."'", errlvl,...) |
end |
end |
end |
local function validate(options,errlvl,...) |
errlvl=(errlvl or 0)+1 |
-- basic consistency |
if type(options)~="table" then |
err(": expected a table, got a "..type(options), errlvl,...) |
end |
if type(options.type)~="string" then |
err(".type: expected a string, got a "..type(options.type), errlvl,...) |
end |
-- get type and 'typedkeys' member |
local tk = typedkeys[options.type] |
if not tk then |
err(".type: unknown type '"..options.type.."'", errlvl,...) |
end |
-- make sure that all options[] are known parameters |
for k,v in pairs(options) do |
if not (tk[k] or basekeys[k]) then |
err(": unknown parameter", errlvl,tostring(k),...) |
end |
end |
-- verify that required params are there, and that everything is the right type |
for k,oktypes in pairs(basekeys) do |
validateVal(options[k], oktypes, errlvl,k,...) |
end |
for k,oktypes in pairs(tk) do |
validateVal(options[k], oktypes, errlvl,k,...) |
end |
-- extra logic for groups |
if options.type=="group" then |
for k,v in pairs(options.args) do |
validateKey(k,errlvl,"args",...) |
validate(v, errlvl,k,"args",...) |
end |
if options.plugins then |
for plugname,plugin in pairs(options.plugins) do |
if type(plugin)~="table" then |
err(": expected a table, got '"..tostring(plugin).."'", errlvl,tostring(plugname),"plugins",...) |
end |
for k,v in pairs(plugin) do |
validateKey(k,errlvl,tostring(plugname),"plugins",...) |
validate(v, errlvl,k,tostring(plugname),"plugins",...) |
end |
end |
end |
end |
end |
--- Validates basic structure and integrity of an options table \\ |
-- Does NOT verify that get/set etc actually exist, since they can be defined at any depth |
-- @param options The table to be validated |
-- @param name The name of the table to be validated (shown in any error message) |
-- @param errlvl (optional number) error level offset, default 0 (=errors point to the function calling :ValidateOptionsTable) |
function AceConfigRegistry:ValidateOptionsTable(options,name,errlvl) |
errlvl=(errlvl or 0)+1 |
name = name or "Optionstable" |
if not options.name then |
options.name=name -- bit of a hack, the root level doesn't really need a .name :-/ |
end |
validate(options,errlvl,name) |
end |
--- Fires a "ConfigTableChange" callback for those listening in on it, allowing config GUIs to refresh. |
-- You should call this function if your options table changed from any outside event, like a game event |
-- or a timer. |
-- @param appName The application name as given to `:RegisterOptionsTable()` |
function AceConfigRegistry:NotifyChange(appName) |
if not AceConfigRegistry.tables[appName] then return end |
AceConfigRegistry.callbacks:Fire("ConfigTableChange", appName) |
end |
-- ------------------------------------------------------------------- |
-- Registering and retreiving options tables: |
-- validateGetterArgs: helper function for :GetOptionsTable (or, rather, the getter functions returned by it) |
local function validateGetterArgs(uiType, uiName, errlvl) |
errlvl=(errlvl or 0)+2 |
if uiType~="cmd" and uiType~="dropdown" and uiType~="dialog" then |
error(MAJOR..": Requesting options table: 'uiType' - invalid configuration UI type, expected 'cmd', 'dropdown' or 'dialog'", errlvl) |
end |
if not strmatch(uiName, "[A-Za-z]%-[0-9]") then -- Expecting e.g. "MyLib-1.2" |
error(MAJOR..": Requesting options table: 'uiName' - badly formatted or missing version number. Expected e.g. 'MyLib-1.2'", errlvl) |
end |
end |
--- Register an options table with the config registry. |
-- @param appName The application name as given to `:RegisterOptionsTable()` |
-- @param options The options table, OR a function reference that generates it on demand. \\ |
-- See the top of the page for info on arguments passed to such functions. |
function AceConfigRegistry:RegisterOptionsTable(appName, options) |
if type(options)=="table" then |
if options.type~="group" then -- quick sanity checker |
error(MAJOR..": RegisterOptionsTable(appName, options): 'options' - missing type='group' member in root group", 2) |
end |
AceConfigRegistry.tables[appName] = function(uiType, uiName, errlvl) |
errlvl=(errlvl or 0)+1 |
validateGetterArgs(uiType, uiName, errlvl) |
if not AceConfigRegistry.validated[uiType][appName] then |
AceConfigRegistry:ValidateOptionsTable(options, appName, errlvl) -- upgradable |
AceConfigRegistry.validated[uiType][appName] = true |
end |
return options |
end |
elseif type(options)=="function" then |
AceConfigRegistry.tables[appName] = function(uiType, uiName, errlvl) |
errlvl=(errlvl or 0)+1 |
validateGetterArgs(uiType, uiName, errlvl) |
local tab = assert(options(uiType, uiName, appName)) |
if not AceConfigRegistry.validated[uiType][appName] then |
AceConfigRegistry:ValidateOptionsTable(tab, appName, errlvl) -- upgradable |
AceConfigRegistry.validated[uiType][appName] = true |
end |
return tab |
end |
else |
error(MAJOR..": RegisterOptionsTable(appName, options): 'options' - expected table or function reference", 2) |
end |
end |
--- Returns an iterator of ["appName"]=funcref pairs |
function AceConfigRegistry:IterateOptionsTables() |
return pairs(AceConfigRegistry.tables) |
end |
--- Query the registry for a specific options table. |
-- If only appName is given, a function is returned which you |
-- can call with (uiType,uiName) to get the table.\\ |
-- If uiType&uiName are given, the table is returned. |
-- @param appName The application name as given to `:RegisterOptionsTable()` |
-- @param uiType The type of UI to get the table for, one of "cmd", "dropdown", "dialog" |
-- @param uiName The name of the library/addon querying for the table, e.g. "MyLib-1.0" |
function AceConfigRegistry:GetOptionsTable(appName, uiType, uiName) |
local f = AceConfigRegistry.tables[appName] |
if not f then |
return nil |
end |
if uiType then |
return f(uiType,uiName,1) -- get the table for us |
else |
return f -- return the function |
end |
end |
<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="AceEvent-3.0.lua"/> |
</Ui> |
--- 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 877 2009-11-02 15:56:50Z 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 always be called with the event as the first argument, and if supplied, the `arg` as second argument. |
-- 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 always be called with the event as the first argument, and if supplied, the `arg` as second argument. |
-- 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 |
local events = AceEvent.events |
AceEvent.frame:SetScript("OnEvent", function(this, event, ...) |
events:Fire(event, ...) |
end) |
--- Finally: upgrade our old embeds |
for target, v in pairs(AceEvent.embeds) do |
AceEvent:Embed(target) |
end |
<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="AceAddon-3.0.lua"/> |
</Ui> |
--- **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 895 2009-12-06 16:28:55Z nevcairiel $ |
local MAJOR, MINOR = "AceAddon-3.0", 5 |
local AceAddon, oldminor = LibStub:NewLibrary(MAJOR, MINOR) |
if not AceAddon then return end -- No Upgrade needed. |
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 = table.insert, table.concat, table.remove |
local fmt, tostring = string.format, tostring |
local select, pairs, next, type, unpack = select, 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 xpcall = xpcall |
local function errorhandler(err) |
return geterrorhandler()(err) |
end |
local function CreateDispatcher(argCount) |
local code = [[ |
local xpcall, eh = ... |
local method, ARGS |
local function call() return method(ARGS) end |
local function dispatch(func, ...) |
method = func |
if not method then return end |
ARGS = ... |
return xpcall(call, eh) |
end |
return dispatch |
]] |
local ARGS = {} |
for i = 1, argCount do ARGS[i] = "arg"..i end |
code = code:gsub("ARGS", tconcat(ARGS, ", ")) |
return assert(loadstring(code, "safecall Dispatcher["..argCount.."]"))(xpcall, errorhandler) |
end |
local Dispatchers = setmetatable({}, {__index=function(self, argCount) |
local dispatcher = CreateDispatcher(argCount) |
rawset(self, argCount, dispatcher) |
return dispatcher |
end}) |
Dispatchers[0] = function(func) |
return xpcall(func, errorhandler) |
end |
local function safecall(func, ...) |
-- 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 Dispatchers[select('#', ...)](func, ...) |
end |
end |
-- 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 |
--- 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, ...) |
local object,name |
local i=1 |
if type(objectorname)=="table" then |
object=objectorname |
name=... |
i=2 |
else |
name=objectorname |
end |
if type(name)~="string" then |
error(("Usage: NewAddon([object,] name, [lib, lib, lib, ...]): 'name' - string expected got '%s'."):format(type(name)), 2) |
end |
if self.addons[name] then |
error(("Usage: NewAddon([object,] name, [lib, lib, lib, ...]): 'name' - Addon '%s' already exists."):format(name), 2) |
end |
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.defaultModuleLibraries = {} |
Embed( object ) -- embed NewModule, GetModule methods |
self:EmbedLibraries(object, select(i,...)) |
-- 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(("Usage: GetAddon(name): 'name' - Cannot find an AceAddon '%s'."):format(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, ...) |
for i=1,select("#", ... ) do |
local libname = select(i, ...) |
self:EmbedLibrary(addon, libname, 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(("Usage: EmbedLibrary(addon, libname, silent, offset): 'libname' - Cannot find a library instance of %q."):format(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(("Usage: EmbedLibrary(addon, libname, silent, offset): 'libname' - Library '%s' is not Embed capable"):format(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(("Usage: GetModule(name, silent): 'name' - Cannot find module '%s'."):format(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, ...) |
if type(name) ~= "string" then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'name' - string expected got '%s'."):format(type(name)), 2) end |
if type(prototype) ~= "string" and type(prototype) ~= "table" and type(prototype) ~= "nil" then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'prototype' - table (prototype), string (lib) or nil expected got '%s'."):format(type(prototype)), 2) end |
if self.modules[name] then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'name' - Module '%s' already exists."):format(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(fmt("%s_%s", self.name or tostring(self), name)) |
module.IsModule = IsModuleTrue |
module:SetEnabledState(self.defaultModuleState) |
module.moduleName = name |
if type(prototype) == "string" then |
AceAddon:EmbedLibraries(module, prototype, ...) |
else |
AceAddon:EmbedLibraries(module, ...) |
end |
AceAddon:EmbedLibraries(module, unpack(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, self, module) -- Was in Ace2 and I think it could be a cool thing to have handy. |
self.modules[name] = 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) |
return AceAddon:EnableAddon(self) |
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, ...) |
if next(self.modules) then |
error("Usage: SetDefaultModuleLibraries(...): cannot change the module defaults after a module has been registered.", 2) |
end |
self.defaultModuleLibraries = {...} |
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(("Usage: SetDefaultModulePrototype(prototype): 'prototype' - table expected got '%s'."):format(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) |
for k, v in pairs(mixins) do |
target[k] = v |
end |
for k, v in pairs(pmixins) do |
target[k] = target[k] or v |
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, addon) |
local embeds = self.embeds[addon] |
for i = 1, #embeds do |
local lib = LibStub:GetLibrary(embeds[i], true) |
if lib then safecall(lib.OnEmbedInitialize, 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, addon) |
-- make sure we're still enabled before continueing |
if self.statuses[addon.name] then |
local embeds = self.embeds[addon] |
for i = 1, #embeds do |
local lib = LibStub:GetLibrary(embeds[i], true) |
if lib then safecall(lib.OnEmbedEnable, lib, addon) end |
end |
-- enable possible modules. |
for name, module in pairs(addon.modules) do |
self:EnableAddon(module) |
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, addon ) |
-- make sure we're still disabling... |
if not self.statuses[addon.name] then |
local embeds = self.embeds[addon] |
for i = 1, #embeds do |
local lib = LibStub:GetLibrary(embeds[i], true) |
if lib then safecall(lib.OnEmbedDisable, lib, addon) end |
end |
-- disable possible modules. |
for name, module in pairs(addon.modules) do |
self:DisableAddon(module) |
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 |
-- Event Handling |
local function onEvent(this, event, arg1) |
if event == "ADDON_LOADED" 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 |
while(#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 IsLoggedIn() then |
while(#AceAddon.enablequeue > 0) do |
local addon = tremove(AceAddon.enablequeue, 1) |
AceAddon:EnableAddon(addon) |
end |
end |
end |
end |
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) |
end |
<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="AceDB-3.0.lua"/> |
</Ui> |
--- **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. |
-- * **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 877 2009-11-02 15:56:50Z nevcairiel $ |
local ACEDB_MAJOR, ACEDB_MINOR = "AceDB-3.0", 19 |
local AceDB, oldminor = LibStub:NewLibrary(ACEDB_MAJOR, ACEDB_MINOR) |
if not AceDB then return end -- No upgrade needed |
-- Lua APIs |
local type, pairs, next, error = type, pairs, next, error |
local setmetatable, getmetatable, rawset, rawget = setmetatable, getmetatable, rawset, rawget |
-- WoW APIs |
local _G = _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 = {} |
--[[------------------------------------------------------------------------- |
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 |
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 |
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 |
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 |
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 |
local new = initSection(t, section, "profiles", key, defaults) |
if new then |
-- Callback: OnNewProfile, database, newProfileKey |
t.callbacks:Fire("OnNewProfile", 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") |
local factionrealmKey = factionKey .. " - " .. realmKey |
-- 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"] = factionrealmKey, |
["profile"] = profileKey, |
["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 |
local function logoutHandler(frame, event) |
if event == "PLAYER_LOGOUT" then |
for db in pairs(AceDB.db_registry) do |
db.callbacks:Fire("OnDatabaseShutdown", db) |
for section, key in pairs(db.keys) do |
if db.defaults and db.defaults[section] and rawget(db, section) then |
removeDefaults(db[section], db.defaults[section]) |
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", 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", 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.sv.profiles, name) and not silent then |
error("Cannot delete profile '" .. name .. "'. It does not exist.", 2) |
end |
self.sv.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 |
-- Callback: OnProfileDeleted, database, profileKey |
self.callbacks:Fire("OnProfileDeleted", 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.sv.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.sv.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", 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", self) |
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", self) |
-- Callback: OnProfileChanged, database, profileKey |
self.callbacks:Fire("OnProfileChanged", 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 |