WoWInterface SVN ProcWatch

[/] [trunk/] [zz_ProcWatch/] [Libs/] [LibzzAddOnInit/] [LibzzAddOnInit.lua] - Rev 2

Go to most recent revision | Compare with Previous | Blame | View Log

--
-- LibzzAddOnInit - Library for standardized initialisation of my AddOns
--

local MAJOR,MINOR = "LibzzAddOnInit", 25
local LibzzAddOnInit, oldminor = LibStub:NewLibrary(MAJOR, MINOR)

if(not LibzzAddOnInit) then return end

LibzzAddOnInit['embeds'] = LibzzAddOnInit['embeds'] or {}

local mixins = {
  "Init",
  "Print",
  "pinfo",
  "get",
  "set",
  "getPref",
  "setPref",
  "changedPref",
  "ldbEmbed",
  "OnText",
  "GetMainOptions",
  "AddConfigMenu",
  "AddConfigEntry",
  "colorize",
  "setIconSize",
  "pdebug"
}

LibzzAddOnInit['AddOnTable'] = LibzzAddOnInit['AddOnTable'] or {}
LibzzAddOnInit['AddOnTable']['title'] = LibzzAddOnInit['AddOnTable']['title'] or 'LibzzAddOnInit'
LibzzAddOnInit['AddOnTable']['Debug'] = LibzzAddOnInit['AddOnTable']['Debug'] or nil
LibzzAddOnInit['AddOnTable']['ConsoleColor'] = LibzzAddOnInit['AddOnTable']['ConsoleColor'] or '444488'
LibzzAddOnInit['AddOnTable']['commPrefix'] = LibzzAddOnInit['AddOnTable']['commPrefix'] or 'Libzz'
LibzzAddOnInit['AddOnTable']['iconSize'] = LibzzAddOnInit['AddOnTable']['iconSize'] or 14
LibzzAddOnInit['AddOnTable']['apps'] = LibzzAddOnInit['AddOnTable']['apps'] or {}

local iconSize = LibzzAddOnInit['AddOnTable']['iconSize'] or 14
local goldicon = format("\124TInterface\\MoneyFrame\\UI-GoldIcon:%d:%d:1:0\124t", iconSize, iconSize)
local silvericon = format("\124TInterface\\MoneyFrame\\UI-SilverIcon:%d:%d:1:0\124t", iconSize, iconSize)
local coppericon = format("\124TInterface\\MoneyFrame\\UI-CopperIcon:%d:%d:1:0\124t", iconSize, iconSize)

if(not LibzzAddOnInit['CommInit']) then
  LibzzAddOnInit['CommInit'] = true
  LibStub("AceComm-3.0"):Embed(LibzzAddOnInit)
  if(LibzzAddOnInit['AddOnTable']['commPrefix']) then
    LibzzAddOnInit:RegisterComm(LibzzAddOnInit['AddOnTable']['commPrefix'],function(prefix, message, distribution, sender)
      LibzzAddOnInit:lineIn(prefix, message, distribution, sender)
    end)
  end
end

local L = LibStub("AceLocale-3.0"):GetLocale("LibzzAddOnInit", true)
local ldb = LibStub:GetLibrary("LibDataBroker-1.1")
local ldbicon = LibStub("LibDBIcon-1.0")

function LibzzAddOnInit:Embed( target )
        for _, v in pairs( mixins ) do
                target[v] = self[v]
        end
        self['embeds'][target] = true
        return target
end

for addon in pairs(LibzzAddOnInit['embeds']) do
        LibzzAddOnInit:Embed(addon)
end

--
--
--

function LibzzAddOnInit:GetName()
 return MAJOR
end

local function zzLibSlash(self, command)
        if(not command or command == "" or command:lower() == 'version') then
                self:Print(format("%s %s - %s",L['Version'],self:get('version'),self:get('appinfo')))
                self:Print(format("/%s version",self:get('title'):lower()))
                self:Print(format("/%s config",self:get('title'):lower()))
                if(command:lower() == 'version') then
                        LibzzAddOnInit:checkVersion(self, self:get('title'), true)
                end
        elseif(command=='config') then
                InterfaceOptionsFrame_OpenToCategory(self:GetName())
        end
        if(type(self['OnSlashCommand']) == "function") then
                self:OnSlashCommand(command)
        end
end

local function zzLibOnEvent(self,event,arg1)
        local name = self:GetName()
        if(event=="ADDON_LOADED") then
                if(arg1==name) then
                        self['L'] = LibStub("AceLocale-3.0"):GetLocale(name, true)
                        if(not self:get("skipAceEvent")) then
                                LibStub("AceEvent-3.0"):Embed(self)
                        end
                        if(not self:get("skipAceTimer")) then
                                LibStub("AceTimer-3.0"):Embed(self)
                        end
                        if(not self:get("skipAceConsole")) then
                                LibStub("AceConsole-3.0"):RegisterChatCommand(self:get('title'):lower(),function(command) zzLibSlash(self, command) end)
                        end
                        self:UnregisterEvent(event)
                        self['AddOnTable']['defaults'] = self['AddOnTable']['defaults'] or {}
                        self['AddOnTable']['defaults']['profile'] = self['AddOnTable']['defaults']['profile'] or {
                                ['startupMessage'] = true,
                                ['showMMIcon'] = true,
                        }
                        if(not self:get('dbtype')) then
                                self:set('dbtype','CharDB')
                        end
                        if(self:get('noDefault')) then
                                self['db'] = LibStub("AceDB-3.0"):New(format("%s%s",name,self:get('dbtype')),self:get('defaults'))
                        else
                                self['db'] = LibStub("AceDB-3.0"):New(format("%s%s",name,self:get('dbtype')),self:get('defaults'),self:get('defaultProfile') or "Default")
                        end

                        self['AddOnTable']['options']['args']['profile'] = LibStub("AceDBOptions-3.0"):GetOptionsTable(self['db'])
                        
                        LibStub("AceConfig-3.0"):RegisterOptionsTable(name, self['AddOnTable']['options'])
                        LibStub("AceConfigDialog-3.0"):AddToBlizOptions(name, name)
                        if(self['db']['profile']['startupMessage']) then
                                self:Print(L["AddOn loaded"])
                        end
                        if(not self:get("noldb")) then
                                self:ldbEmbed()
                        end
                        if(type(self['ADDON_LOADED']) == "function") then
                                self:ADDON_LOADED()
                        end
                        if(IsAddOnLoaded("AddonLoader")==1) then
                                LibzzAddOnInit:checkVersion(self, self:get('title'))
                                self:UnregisterEvent("PLAYER_LOGIN")
                                if(type(self['PLAYER_LOGIN']) == "function") then
                                        self:PLAYER_LOGIN()
                                end
                        end
                end
        elseif(event=="PLAYER_LOGIN") then
                LibzzAddOnInit:checkVersion(self, self:get('title'))
                self:UnregisterEvent(event)
                if(type(self['PLAYER_LOGIN']) == "function") then
                        self:PLAYER_LOGIN()
                end
        elseif(event=="PLAYER_LOGOUT") then
                if(type(self['PLAYER_LOGOUT']) == "function") then
                        self:PLAYER_LOGOUT()
                end
        elseif(event=="PLAYER_ENTERING_WORLD") then
                self:UnregisterEvent(event)
        end
end

local function getname(self)
        return self['name']
end

function LibzzAddOnInit:Init(name,tab)
  local frame = CreateFrame("FRAME",format("zzMF_%s",name),UIParent)
        frame['name'] = name
  frame['AddOnTable'] = tab
  if(not frame['AddOnTable']['options']) then
    frame['AddOnTable']['options'] = {
      ['type']='group',
      ['handler']=frame,
      ['childGroups']='tab',
      ['args']={
      }
    }
  end
  frame['AddOnTable']['ConsoleColor'] = frame['AddOnTable']['ConsoleColor'] or "FFFF00"
  frame['GetName'] = getname
  LibzzAddOnInit:Embed(frame)
  LibzzAddOnInit['AddOnTable']['apps'][frame:get('title')] = {
    ['version'] = frame:get('version'),
    ['name'] = frame:get('title'),
    ['info'] = frame:get('appinfo'),
  }
  frame:GetMainOptions()
  frame:RegisterEvent("ADDON_LOADED")
  frame:RegisterEvent("PLAYER_LOGIN")
  frame:RegisterEvent("PLAYER_LOGOUT")
  frame:RegisterEvent("PLAYER_ENTERING_WORLD")
  frame:SetScript("OnEvent", zzLibOnEvent)
  return frame
end

function LibzzAddOnInit:OnText(newtext)
  self:get('ldbDataobj')['text'] = newtext
end

local function zzLibldbOnClick(self, button)
        if(type(self['OnButton']) == "function") then
                self:OnButton(button)
        else
                InterfaceOptionsFrame_OpenToCategory(self:GetName())
        end
end

local function zzLibOnTooltipShow(self)
        if(type(self['OnTooltip']) == "function") then
                self:OnTooltip()
        else
                GameTooltip:AddLine(format("%s %s",self:get('title'),self:get('version')))
        end
end

function LibzzAddOnInit:ldbEmbed()
  local name = self:GetName()
  self:set('ldbDataobj', ldb:GetDataObjectByName(name) or ldb:NewDataObject(name, {
    ['type'] = self:get('ldbtype') or 'launcher',
    ['text'] = name,
    ['icon'] = self:get('iconPath'),
  }))
  if(self:get('ldbDataobj')) then
    if(not self['db']['profile']['ldbicon']) then
      self['db']['profile']['ldbicon'] = { ['hide'] = false,}
    end
                self:get('ldbDataobj')['OnClick'] = function(_,button) zzLibldbOnClick(self,button) end
    self:get('ldbDataobj')['OnTooltipShow'] = function() zzLibOnTooltipShow(self) end
    ldbicon:Register(name,self:get('ldbDataobj'),self['db']['profile']['ldbicon'])
  end
end

function LibzzAddOnInit:AddConfigMenu(menuName, parentMenu)
  if(not parentMenu) then
    parentMenu = self['AddOnTable']['options']
  end
  local menuHandler, menuChildGroups, menuGet, menuSet, menuOrder, menuDesc
  if(type(menuName) == 'table') then
    menuHandler = menuName['menuHandler'] or self
    menuChildGroups = menuName['childGroups'] or 'tree'
    menuGet = menuName['menuGet']  or 'getPref'
    menuSet = menuName['menuSet'] or 'setPref'
    menuOrder = menuName['order'] or 1
    menuDesc = menuName['desc']  or ''
    menuName = menuName['name']
  else
    menuHandler = self
    menuGet = 'getPref'
    menuSet = 'setPref'
    menuOrder = 1
    menuDesc = ''
  end
  parentMenu['args'][menuName] = {
      ['type'] = 'group',
      ['name'] = menuName,
      ['desc'] = menuDesc,
      ['childGroups'] = menuChildGroups,
      ['handler'] = menuHandler,
      ['get'] = menuGet,
      ['set'] = menuSet,
      ['order'] = menuOrder,
      ['args']  = {}
  }
  return parentMenu['args'][menuName]
end

function LibzzAddOnInit:AddConfigEntry(...)
  local menu = select(10,...) or self['AddOnTable']['options']['args'][self:get('title')]
  if(menu) then
    menu['args'][select(2,...)] = {
      ['type'] = select(1,...),
      ['name'] = select(3,...),
      ['desc'] = select(4,...),
      ['order'] = select(5,...)
    }
    if(select(1,...) == 'range') then
      menu['args'][select(2,...)]['min'] =  select(6,...)
      menu['args'][select(2,...)]['max'] =  select(7,...)
      menu['args'][select(2,...)]['step'] =  select(8,...)
      menu['args'][select(2,...)]['isPercent'] =  select(9,...)
                elseif(select(1,...) == 'execute') then
                        menu['args'][select(2,...)]['func'] =  select(6,...)
    elseif(select(1,...) == 'color') then
      menu['args'][select(2,...)]['get'] =  select(6,...)
      menu['args'][select(2,...)]['set'] =  select(7,...)
                        menu['args'][select(2,...)]['hasAlpha'] = true
                elseif(select(1,...) == 'select') then
      menu['args'][select(2,...)]['values'] = select(6,...)
    end
  end
end

function LibzzAddOnInit:GetMainOptions()
  self:AddConfigMenu(self:get('title'))
  self:AddConfigEntry("header",'breakIt',L['General Settings'],nil,20)
  self:AddConfigEntry("header",'breakIt2',L['AddOn Settings'],nil,1)
  self:AddConfigEntry("toggle",'startupMessage',L['Start message'],L['Show addon message on startup'],21)
  self:AddConfigEntry("toggle",'showMMIcon',L['Show Minimapicon'],nil,21)
self:AddConfigEntry("toggle",'vercheck',L['Check version'],L['Checks with your guild/group if a new version is available on startup'],22)
end

function LibzzAddOnInit:getPref(info)
  return self['db']['profile'][info[#info]]
end

function LibzzAddOnInit:setPref(info,value)
  self['db']['profile'][info[#info]] = value
  self:changedPref(info[#info])
end

function LibzzAddOnInit:changedPref(value)
  if(value=="showMMIcon") then
    if(self['db']['profile']['showMMIcon']) then
      ldbicon:Show(self:GetName())
    else
      ldbicon:Hide(self:GetName())
    end
    if(self['db']['profile']['ldbicon']) then
      self['db']['profile']['ldbicon']['hide'] = not self['db']['profile']['showMMIcon']
    else
      self['db']['profile']['ldbicon'] = { ['hide'] = not self['db']['profile']['showMMIcon'] }
    end
  end
  if(type(self['Updated_Pref']) == "function") then
    self:Updated_Pref(value)
  end
end

function LibzzAddOnInit:get(tableValue)
  return self['AddOnTable'][tableValue] or false
end

function LibzzAddOnInit:set(tableValue, newValue)
  self['AddOnTable'][tableValue] = newValue
end

--
-- Message Port
--

local function sendMessage(act,name,version,info,dest)
  local party,guild,whisper = false, false, false
  local prefix = LibzzAddOnInit:get('commPrefix')
  act = act or 'ver'
  name = name or '-'
  version = version or '-'
  info = info or '-'
  
  dest = dest or UnitName("player")
  if(act=='ver' and version=='-' and name~='-') then
    party = true
    guild = true
    whisper = false
  end
  if(LibzzAddOnInit['AddOnTable']['Debug']) then
    whisper = true
    dest = UnitName("player")
  end
  message = strjoin("_",act,name,version,info)
  if(party) then
    LibzzAddOnInit:SendCommMessage(prefix, message, "PARTY")
  end
  if(IsInGuild() and guild) then
    LibzzAddOnInit:SendCommMessage(prefix, message, "GUILD")
  end
  if(whisper and dest~='-') then
    LibzzAddOnInit:SendCommMessage(prefix, message, "WHISPER", dest)
  end
--  LibzzAddOnInit:pdebug(prefix.." "..message.."->"..dest)
end

function LibzzAddOnInit:lineIn(prefix, message, distribution, sender)      
  local act,name,version,info = strsplit("_",message)
  if(act=='ver') then
    if(version=='-') then
      if(LibzzAddOnInit['AddOnTable']['apps'][name]) then
        if(LibzzAddOnInit['AddOnTable']['apps'][name]['version'] and LibzzAddOnInit['AddOnTable']['apps'][name]['info']) then
          sendMessage(act,name,LibzzAddOnInit['AddOnTable']['apps'][name]['version'],LibzzAddOnInit['AddOnTable']['apps'][name]['info'],dest)
        end
      end
    else
      if(LibzzAddOnInit['AddOnTable']['apps'][name]) then
        LibzzAddOnInit:Print(format("|cffffff00%s|r %s %s %s",tostring(sender),tostring(name),tostring(version),tostring(info)))
        LibzzAddOnInit:versioncheck(name,version,sender)
      end
    end
  end
  if(version~='-') then
    LibzzAddOnInit:Print(format("%s %s %s %s",tostring(sender),tostring(name),tostring(version),tostring(info)))
  end
--  LibzzAddOnInit:pdebug(prefix.." "..message.." "..distribution.." "..sender)
end

function LibzzAddOnInit:versioncheck(name,ver,sender)
  local major,minor,ma,mi,vn,rn
  major, minor = strsplit(".",LibzzAddOnInit['AddOnTable']['apps'][name]['version'] or '0.0')
  ma,mi = strsplit(".",ver or 0.0)
  m2,m3 = strsplit(".",LibzzAddOnInit['AddOnTable']['apps'][name]['latestversion'] or '0.0')
  vn = major * 1000 + minor
  rn = ma * 1000 + mi
  nn = m2*1000 + m3
  if(nn < vn) then
    LibzzAddOnInit['AddOnTable']['apps'][name]['latestversion'] = LibzzAddOnInit['AddOnTable']['apps'][name]['version']
    LibzzAddOnInit['AddOnTable']['apps'][name]['sender'] = name
  end
  if(rn > vn) then
    LibzzAddOnInit['AddOnTable']['apps'][name]['latestversion'] = ver
    LibzzAddOnInit['AddOnTable']['apps'][name]['sender'] = sender
  end
end

function LibzzAddOnInit:checkVersion(self, name, force)
        if( UnitAffectingCombat("player") == 1 ) then return end
        if(self['db']['profile']['vercheck'] or force) then
                sendMessage("ver",name,"-","-","-")
        end
end

function zzLib_IsTwink(addon, name)
  if(addon['db']['sv']['profileKeys']) then
    for k,v in pairs(addon['db']['sv']['profileKeys']) do
      local n,m = strsplit(" - ",k,2)
      _,m = strsplit(" ",m,2)
      if(n) then
        if(n == name and m == addon['AddOnTable']['crealm']) then
          return true
        end
      end
    end
  end
  return false
end

function LibzzAddOnInit:updateIconSize(v)
  LibzzAddOnInit['AddOnTable']['iconSize'] = v
  iconSize = v
  goldicon = format("\124TInterface\\MoneyFrame\\UI-GoldIcon:%d:%d:1:0\124t", iconSize, iconSize)
  silvericon = format("\124TInterface\\MoneyFrame\\UI-SilverIcon:%d:%d:1:0\124t", iconSize, iconSize)
  coppericon = format("\124TInterface\\MoneyFrame\\UI-CopperIcon:%d:%d:1:0\124t", iconSize, iconSize)
end

function LibzzAddOnInit:setIconSize(v)
  LibzzAddOnInit:updateIconSize(v)
end

function zzLib_buildMoneyString(money,color)
  local moneystring
  local g,s,c
  local neg = false
  if(money <0) then 
    neg = true
    money = money * -1
  end
  g=floor(money/10000)
  s=floor((money-(g*10000))/100)
  c=money-s*100-g*10000
  moneystring = format("%s%s%s%s%s%s",g,goldicon,s,silvericon,c,coppericon)
  if(neg) then
    moneystring = format("-%s",moneystring)
  end
  if(color) then
    if(neg) then
      moneystring = LibzzAddOnInit:colorize(moneystring,"ff0000")
    elseif(money ~= 0) then
      moneystring = LibzzAddOnInit:colorize(moneystring,"44dd44")
    end
  end
  return moneystring
end

function LibzzAddOnInit:colorize(text,color)
  return format("|cff%s%s|r",color,text)
end

--
--
--

function LibzzAddOnInit:Print(message)
  DEFAULT_CHAT_FRAME:AddMessage(format("|cFF%s%s|r %s",self:get("ConsoleColor"),self:get('title'),tostring(message)))
end

function LibzzAddOnInit:pinfo(info)
  if(type(info) == 'table') then
    for n in pairs(info) do
      self:pdebug(format("1:%s-->%s",tostring(n),tostring(info[n])))
    end
  end
end

function LibzzAddOnInit:pdebug(msg)
  if(self['AddOnTable']['Debug']) then
    DEFAULT_CHAT_FRAME:AddMessage(msg)
  end
end

Go to most recent revision | Compare with Previous | Blame