9 Commits

Author SHA1 Message Date
florian.berthold ef1003b4c9 fix(options): use SetSelectedID so the text-size dropdown selection sticks
release / release (push) Successful in 3s
2026-05-29 10:43:54 +02:00
florian.berthold f109964880 ci: respect GITHUB_REPOSITORY + tolerate per-asset upload failures
release / release (push) Successful in 3s
2026-05-25 12:16:47 +02:00
florian.berthold f43681df48 ci: add Gitea Actions release workflow (per-addon git-archive zip)
release / release (push) Successful in 2s
2026-05-25 12:01:37 +02:00
florian.berthold 769a9ee042 chore: remove .github/ (upstream templates, not relevant on Gitea) 2026-05-25 11:02:49 +02:00
florian.berthold aa9a4919c9 chore: align with Exiles fork-layout convention (standard .gitignore + .gitattributes) 2026-05-25 10:59:31 +02:00
florian.berthold 3ed0021c7b fix(libs): pick up coa-ace3 9583952 (AceDB falsy-defaults PR #10 backport)
Re-sync after coa-ace3 9583952 backported WoWUIDev/Ace3 PR #10 which fixes
the AceDB-3.0 simple-value defaults metatable: previously falsy defaults
like ["*"] = false read back as nil because of `k2~=nil and v or nil`
short-circuiting. Now they round-trip correctly.
2026-05-24 19:31:44 +02:00
florian.berthold 6ef1f9dab8 fix: name+guard Woodcutting/Woodworking, drop regex+deprecated this+InterfaceOptions guards
ProfessionMenu.lua:
- profList: add Name="Woodcutting" (spell 13977860) and Name="Woodworking"
  (spells 1005008-1005011) so getProfessionRanks can find the matching
  GetSkillLineInfo entry. Without Name, both fell through GetSpellInfo+match
  with no result and returned nil,nil.
- getProfessionRanks: replace compName:match(name) (regex) with compName == name
  (plain compare); GetSkillLineInfo names are exact, regex was a bug magnet.
- Guard rank concat at lines ~394/397/400: skip the " (rank)" / " (max)" /
  " (rank/max)" append when getProfessionRanks returns nil so unknown
  skill lines don't error.
- InterfaceOptionsFrame:HookScript: wrap in 'if InterfaceOptionsFrame then';
  CoA's reworked FrameXML has no InterfaceOptionsFrame.

ProfessionMenuOptions.lua:
- Guard InterfaceOptionsFrame / InterfaceOptionsFrame_OpenToCategory /
  InterfaceOptions_AddCategory call sites (Options_Toggle, ProfessionMenu_
  OpenOptions, CreateOptionsUI). All nil on CoA's FrameXML.
- TxtSize dropdown func: drop deprecated WoW-2.x global 'this'; use
  UIDropDownMenu_GetSelectedID(ProfessionMenuOptions_TxtSizeMenu) instead.
2026-05-24 17:40:22 +02:00
florian.berthold 6d099f6db1 chore(libs): bump LibDataBroker-1.1 to v4 (from canonical) 2026-05-24 17:08:21 +02:00
florian.berthold 3fe1f67a0d chore(libs): sync Ace3 to coa-ace3 (WoWUIDev master @ 52e5f2c)
Bring every embedded Ace3 / CallbackHandler / LibStub copy in line with the
canonical Exiles/coa-ace3 bundle so LibStub resolution is predictable across
all Exiles forks regardless of which addons are enabled.

Libraries updated in this fork:
  AceAddon-3.0           13  (5 → 13)
  AceComm-3.0            14  (6 → 14)
  AceConsole-3.0         7
  AceDB-3.0              33  (21 → 33)
  AceEvent-3.0           4  (3 → 4)
  AceSerializer-3.0      5  (3 → 5)
  AceTimer-3.0           17  (5 → 17)
  CallbackHandler-1.0    8  (3 → 8)
  LibStub                2
2026-05-23 13:42:18 +02:00
23 changed files with 1057 additions and 966 deletions
+1 -2
View File
@@ -1,2 +1 @@
# Auto detect text files and perform LF normalization * -text
* text=auto
+71
View File
@@ -0,0 +1,71 @@
name: release
on:
push:
tags:
- '*-coa.*' # Asc-1.1.6-coa.2, 9.1.40-coa.3, etc.
- 'v*' # v0.3.0 for repos without an upstream version
jobs:
release:
runs-on: linux-amd64
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0 # build_zip uses git archive HEAD; full history is fine
- name: Build per-addon zip(s)
run: bash tools/build_zip.sh
- name: Publish release (Gitea API direct; no action dependency)
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPO: ${{ github.repository }}
TAG: ${{ github.ref_name }}
API: ${{ github.server_url }}/api/v1
# Gitea attachment ceiling is 200 MiB (see roles/gitea config).
# Skip anything larger so one oversized asset doesn't fail the job.
MAX_BYTES: 209715200
run: |
set -euo pipefail
# Create the release (or reuse if it already exists for this tag).
RID=$(curl -s -H "Authorization: token $GITEA_TOKEN" \
"$API/repos/$REPO/releases/tags/$TAG" 2>/dev/null \
| jq -r '.id // empty')
if [ -z "$RID" ]; then
RID=$(curl -sf -X POST -H "Authorization: token $GITEA_TOKEN" \
-H "Content-Type: application/json" \
"$API/repos/$REPO/releases" \
-d "$(jq -nc --arg t "$TAG" '{tag_name:$t,name:$t,draft:false,prerelease:false}')" \
| jq -r '.id')
fi
echo "release id: $RID"
# Upload every dist/*.zip. Per-asset failures don't fail the job —
# we want partial releases to still publish rather than block the
# whole pipeline on one big file.
failed=0
uploaded=0
for f in dist/*.zip; do
name=$(basename "$f")
size=$(stat -c '%s' "$f")
if [ "$size" -gt "$MAX_BYTES" ]; then
echo "::warning::skip $name (${size} B > ${MAX_BYTES} B Gitea limit; host on CDN instead)"
failed=$((failed+1))
continue
fi
echo "uploading $name ($(numfmt --to=iec "$size"))"
if curl -sf -X POST -H "Authorization: token $GITEA_TOKEN" \
-F "attachment=@$f" \
"$API/repos/$REPO/releases/$RID/assets?name=$name" \
| jq -r '" -> " + .browser_download_url'; then
uploaded=$((uploaded+1))
else
echo "::warning::upload failed for $name"
failed=$((failed+1))
fi
done
echo "release published: $uploaded uploaded, $failed skipped/failed"
# Only fail the job if NO assets uploaded — a release with zero
# attachments isn't useful to anyone.
[ "$uploaded" -gt 0 ]
-77
View File
@@ -1,77 +0,0 @@
name: "Bug Report"
description: Create a report to help us improve this addon
labels: '🐛 Bug'
body:
- type: markdown
attributes:
value: |
Please search for existing issues before creating a new one.
- type: textarea
attributes:
label: Description
description: What did you expect to happen and what happened instead?
validations:
required: true
- type: dropdown
id: flavor
attributes:
label: Realm
description: What realm did this occur on?
options:
- Area 52 (Default)
- Seasonal
- Grizzly Hills
- Rexxar
- Other
validations:
required: true
- type: checkboxes
id: testing
attributes:
label: Tested with only this addon
description: Did you try having just this addon as the only enabled addon and everything else disabled?
options:
- label: "Yes"
- label: "No"
validations:
required: true
- type: textarea
attributes:
label: Lua Error
description: |
Do you have an error log of what happened? If you don't see any errors, make sure that error reporting is enabled (`/console scriptErrors 1`)
validations:
required: false
- type: textarea
attributes:
label: Reproduction Steps
description: Please list out the steps to reproduce your bug.
placeholder: |
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
validations:
required: true
- type: input
attributes:
label: Last Good Version
description: |
Was it working in a previous version? If yes, which update did it stop working? If you don't know, when was the last date you were aware it was working
placeholder: "MM/DD/YYYY"
validations:
required: false
- type: textarea
attributes:
label: Screenshots
description: If applicable, add screenshots to help explain your problem.
placeholder: Click here to attach your screenshots via the editor button in the top right.
validations:
required: false
-1
View File
@@ -1 +0,0 @@
blank_issues_enabled: false
-20
View File
@@ -1,20 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
-28
View File
@@ -1,28 +0,0 @@
# Description
Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context.
<!-- A #issueNumber will be sufficient. -->
Fixes #(issue)
## Type of change
Please delete options that are not relevant.
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
## How Has This Been Tested
Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration
- [ ] Test A
- [ ] Test B
## Checklist
<!-- These can be checked off after the pull request is submitted, in case you want discussion before they are completely ready -->
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
<!-- Is there any additional work that needs to be done? If so, add it to the above list -->
+1
View File
@@ -5,3 +5,4 @@
.lua/* .lua/*
.vscode .vscode
.idea .idea
dist/
@@ -28,9 +28,9 @@
-- end -- end
-- @class file -- @class file
-- @name AceAddon-3.0.lua -- @name AceAddon-3.0.lua
-- @release $Id: AceAddon-3.0.lua 895 2009-12-06 16:28:55Z nevcairiel $ -- @release $Id$
local MAJOR, MINOR = "AceAddon-3.0", 5 local MAJOR, MINOR = "AceAddon-3.0", 13
local AceAddon, oldminor = LibStub:NewLibrary(MAJOR, MINOR) local AceAddon, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
if not AceAddon then return end -- No Upgrade needed. if not AceAddon then return end -- No Upgrade needed.
@@ -49,10 +49,6 @@ local select, pairs, next, type, unpack = select, pairs, next, type, unpack
local loadstring, assert, error = loadstring, assert, error local loadstring, assert, error = loadstring, assert, error
local setmetatable, getmetatable, rawset, rawget = setmetatable, getmetatable, rawset, rawget 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 xpcall safecall implementation
]] ]]
@@ -62,43 +58,12 @@ local function errorhandler(err)
return geterrorhandler()(err) return geterrorhandler()(err)
end 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, ...) 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 -- 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 -- this safecall is used for optional functions like OnInitialize OnEnable etc. When they are not
-- present execution should continue without hinderance -- present execution should continue without hinderance
if type(func) == "function" then if type(func) == "function" then
return Dispatchers[select('#', ...)](func, ...) return xpcall(func, errorhandler, ...)
end end
end end
@@ -108,6 +73,16 @@ local Enable, Disable, EnableModule, DisableModule, Embed, NewModule, GetModule,
-- used in the addon metatable -- used in the addon metatable
local function addontostring( self ) return self.name end local function addontostring( self ) return self.name end
-- Check if the addon is queued for initialization
local function queuedForInitialization(addon)
for i = 1, #AceAddon.initializequeue do
if AceAddon.initializequeue[i] == addon then
return true
end
end
return false
end
--- Create a new AceAddon-3.0 addon. --- Create a new AceAddon-3.0 addon.
-- Any libraries you specified will be embeded, and the addon will be scheduled for -- Any libraries you specified will be embeded, and the addon will be scheduled for
-- its OnInitialize and OnEnable callbacks. -- its OnInitialize and OnEnable callbacks.
@@ -153,6 +128,7 @@ function AceAddon:NewAddon(objectorname, ...)
setmetatable( object, addonmeta ) setmetatable( object, addonmeta )
self.addons[name] = object self.addons[name] = object
object.modules = {} object.modules = {}
object.orderedModules = {}
object.defaultModuleLibraries = {} object.defaultModuleLibraries = {}
Embed( object ) -- embed NewModule, GetModule methods Embed( object ) -- embed NewModule, GetModule methods
self:EmbedLibraries(object, select(i,...)) self:EmbedLibraries(object, select(i,...))
@@ -285,6 +261,7 @@ function NewModule(self, name, prototype, ...)
safecall(self.OnModuleCreated, self, module) -- Was in Ace2 and I think it could be a cool thing to have handy. safecall(self.OnModuleCreated, self, module) -- Was in Ace2 and I think it could be a cool thing to have handy.
self.modules[name] = module self.modules[name] = module
tinsert(self.orderedModules, module)
return module return module
end end
@@ -312,7 +289,12 @@ end
-- MyModule:Enable() -- MyModule:Enable()
function Enable(self) function Enable(self)
self:SetEnabledState(true) self:SetEnabledState(true)
return AceAddon:EnableAddon(self)
-- nevcairiel 2013-04-27: don't enable an addon/module if its queued for init still
-- it'll be enabled after the init process
if not queuedForInitialization(self) then
return AceAddon:EnableAddon(self)
end
end end
--- Disables the Addon, if possible, return true or false depending on success. --- Disables the Addon, if possible, return true or false depending on success.
@@ -489,12 +471,14 @@ local pmixins = {
-- target (object) - target object to embed aceaddon in -- target (object) - target object to embed aceaddon in
-- --
-- this is a local function specifically since it's meant to be only called internally -- this is a local function specifically since it's meant to be only called internally
function Embed(target) function Embed(target, skipPMixins)
for k, v in pairs(mixins) do for k, v in pairs(mixins) do
target[k] = v target[k] = v
end end
for k, v in pairs(pmixins) do if not skipPMixins then
target[k] = target[k] or v for k, v in pairs(pmixins) do
target[k] = target[k] or v
end
end end
end end
@@ -547,8 +531,9 @@ function AceAddon:EnableAddon(addon)
end end
-- enable possible modules. -- enable possible modules.
for name, module in pairs(addon.modules) do local modules = addon.orderedModules
self:EnableAddon(module) for i = 1, #modules do
self:EnableAddon(modules[i])
end end
end end
return self.statuses[addon.name] -- return true if we're disabled return self.statuses[addon.name] -- return true if we're disabled
@@ -580,8 +565,9 @@ function AceAddon:DisableAddon(addon)
if lib then safecall(lib.OnEmbedDisable, lib, addon) end if lib then safecall(lib.OnEmbedDisable, lib, addon) end
end end
-- disable possible modules. -- disable possible modules.
for name, module in pairs(addon.modules) do local modules = addon.orderedModules
self:DisableAddon(module) for i = 1, #modules do
self:DisableAddon(modules[i])
end end
end end
@@ -611,9 +597,20 @@ function AceAddon:IterateAddonStatus() return pairs(self.statuses) end
function AceAddon:IterateEmbedsOnAddon(addon) return pairs(self.embeds[addon]) end function AceAddon:IterateEmbedsOnAddon(addon) return pairs(self.embeds[addon]) end
function AceAddon:IterateModulesOfAddon(addon) return pairs(addon.modules) end function AceAddon:IterateModulesOfAddon(addon) return pairs(addon.modules) end
-- Blizzard AddOns which can load very early in the loading process and mess with Ace3 addon loading
local BlizzardEarlyLoadAddons = {
Blizzard_DebugTools = true,
Blizzard_TimeManager = true,
Blizzard_BattlefieldMap = true,
Blizzard_MapCanvas = true,
Blizzard_SharedMapDataProviders = true,
Blizzard_CombatLog = true,
}
-- Event Handling -- Event Handling
local function onEvent(this, event, arg1) local function onEvent(this, event, arg1)
if event == "ADDON_LOADED" or event == "PLAYER_LOGIN" then -- 2020-08-28 nevcairiel - ignore the load event of Blizzard addons which occur early in the loading process
if (event == "ADDON_LOADED" and (arg1 == nil or not BlizzardEarlyLoadAddons[arg1])) 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 -- 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 while(#AceAddon.initializequeue > 0) do
local addon = tremove(AceAddon.initializequeue, 1) local addon = tremove(AceAddon.initializequeue, 1)
@@ -638,5 +635,15 @@ AceAddon.frame:SetScript("OnEvent", onEvent)
-- upgrade embeded -- upgrade embeded
for name, addon in pairs(AceAddon.addons) do for name, addon in pairs(AceAddon.addons) do
Embed(addon) Embed(addon, true)
end
-- 2010-10-27 nevcairiel - add new "orderedModules" table
if oldminor and oldminor < 10 then
for name, addon in pairs(AceAddon.addons) do
addon.orderedModules = {}
for module_name, module in pairs(addon.modules) do
tinsert(addon.orderedModules, module)
end
end
end end
+58 -66
View File
@@ -9,7 +9,7 @@
-- make into AceComm. -- make into AceComm.
-- @class file -- @class file
-- @name AceComm-3.0 -- @name AceComm-3.0
-- @release $Id: AceComm-3.0.lua 895 2009-12-06 16:28:55Z nevcairiel $ -- @release $Id$
--[[ AceComm-3.0 --[[ AceComm-3.0
@@ -17,24 +17,23 @@ TODO: Time out old data rotting around from dead senders? Not a HUGE deal since
]] ]]
local MAJOR, MINOR = "AceComm-3.0", 6 local CallbackHandler = LibStub("CallbackHandler-1.0")
local CTL = assert(ChatThrottleLib, "AceComm-3.0 requires ChatThrottleLib")
local MAJOR, MINOR = "AceComm-3.0", 14
local AceComm,oldminor = LibStub:NewLibrary(MAJOR, MINOR) local AceComm,oldminor = LibStub:NewLibrary(MAJOR, MINOR)
if not AceComm then return end if not AceComm then return end
local CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0")
local CTL = assert(ChatThrottleLib, "AceComm-3.0 requires ChatThrottleLib")
-- Lua APIs -- Lua APIs
local type, next, pairs, tostring = type, next, pairs, tostring local type, next, pairs, tostring = type, next, pairs, tostring
local strsub, strfind = string.sub, string.find local strsub, strfind = string.sub, string.find
local match = string.match
local tinsert, tconcat = table.insert, table.concat local tinsert, tconcat = table.insert, table.concat
local error, assert = error, assert local error, assert = error, assert
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- WoW APIs
-- List them here for Mikk's FindGlobals script local Ambiguate = Ambiguate
-- GLOBALS: LibStub, DEFAULT_CHAT_FRAME, geterrorhandler
AceComm.embeds = AceComm.embeds or {} AceComm.embeds = AceComm.embeds or {}
@@ -42,21 +41,32 @@ AceComm.embeds = AceComm.embeds or {}
local MSG_MULTI_FIRST = "\001" local MSG_MULTI_FIRST = "\001"
local MSG_MULTI_NEXT = "\002" local MSG_MULTI_NEXT = "\002"
local MSG_MULTI_LAST = "\003" local MSG_MULTI_LAST = "\003"
local MSG_ESCAPE = "\004"
AceComm.multipart_origprefixes = AceComm.multipart_origprefixes or {} -- e.g. "Prefix\001"="Prefix", "Prefix\002"="Prefix" -- remove old structures (pre WoW 4.0)
AceComm.multipart_reassemblers = AceComm.multipart_reassemblers or {} -- e.g. "Prefix\001"="OnReceiveMultipartFirst" AceComm.multipart_origprefixes = nil
AceComm.multipart_reassemblers = nil
-- the multipart message spool: indexed by a combination of sender+distribution+ -- the multipart message spool: indexed by a combination of sender+distribution+
AceComm.multipart_spool = AceComm.multipart_spool or {} AceComm.multipart_spool = AceComm.multipart_spool or {}
--- Register for Addon Traffic on a specified prefix --- Register for Addon Traffic on a specified prefix
-- @param prefix A printable character (\032-\255) classification of the message (typically AddonName or AddonNameEvent) -- @param prefix A printable character (\032-\255) classification of the message (typically AddonName or AddonNameEvent), max 16 characters
-- @param method Callback to call on message reception: Function reference, or method name (string) to call on self. Defaults to "OnCommReceived" -- @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) function AceComm:RegisterComm(prefix, method)
if method == nil then if method == nil then
method = "OnCommReceived" method = "OnCommReceived"
end end
if #prefix > 16 then -- TODO: 15?
error("AceComm:RegisterComm(prefix,method): prefix length is limited to 16 characters")
end
if C_ChatInfo then
C_ChatInfo.RegisterAddonMessagePrefix(prefix)
else
RegisterAddonMessagePrefix(prefix)
end
return AceComm._RegisterComm(self, prefix, method) -- created by CallbackHandler return AceComm._RegisterComm(self, prefix, method) -- created by CallbackHandler
end end
@@ -75,57 +85,55 @@ function AceComm:SendCommMessage(prefix, text, distribution, target, prio, callb
if not( type(prefix)=="string" and if not( type(prefix)=="string" and
type(text)=="string" and type(text)=="string" and
type(distribution)=="string" and type(distribution)=="string" and
(target==nil or type(target)=="string") and (target==nil or type(target)=="string" or type(target)=="number") and
(prio=="BULK" or prio=="NORMAL" or prio=="ALERT") (prio=="BULK" or prio=="NORMAL" or prio=="ALERT")
) then ) then
error('Usage: SendCommMessage(addon, "prefix", "text", "distribution"[, "target"[, "prio"[, callbackFn, callbackarg]]])', 2) error('Usage: SendCommMessage(addon, "prefix", "text", "distribution"[, "target"[, "prio"[, callbackFn, callbackarg]]])', 2)
end 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 textlen = #text
local maxtextlen = 254 - #prefix -- 254 is the max length of prefix + text that can be sent in one message local maxtextlen = 255 -- Yes, the max is 255 even if the dev post said 256. I tested. Char 256+ get silently truncated. /Mikk, 20110327
local queueName = prefix..distribution..(target or "") local queueName = prefix
local ctlCallback = nil local ctlCallback = nil
if callbackFn then if callbackFn then
ctlCallback = function(sent) ctlCallback = function(sent, sendResult)
return callbackFn(callbackArg, sent, textlen) return callbackFn(callbackArg, sent, textlen, sendResult)
end end
end end
if textlen <= maxtextlen then local forceMultipart
if match(text, "^[\001-\009]") then -- 4.1+: see if the first character is a control character
-- we need to escape the first character with a \004
if textlen+1 > maxtextlen then -- would we go over the size limit?
forceMultipart = true -- just make it multipart, no escape problems then
else
text = "\004" .. text
end
end
if not forceMultipart and textlen <= maxtextlen then
-- fits all in one message -- fits all in one message
CTL:SendAddonMessage(prio, prefix, text, distribution, target, queueName, ctlCallback, textlen) CTL:SendAddonMessage(prio, prefix, text, distribution, target, queueName, ctlCallback, textlen)
else else
maxtextlen = maxtextlen - 1 -- 1 extra byte for part indicator in prefix maxtextlen = maxtextlen - 1 -- 1 extra byte for part indicator in prefix(4.0)/start of message(4.1)
-- first part -- first part
local chunk = strsub(text, 1, maxtextlen) local chunk = strsub(text, 1, maxtextlen)
CTL:SendAddonMessage(prio, prefix..MSG_MULTI_FIRST, chunk, distribution, target, queueName, ctlCallback, maxtextlen) CTL:SendAddonMessage(prio, prefix, MSG_MULTI_FIRST..chunk, distribution, target, queueName, ctlCallback, maxtextlen)
-- continuation -- continuation
local pos = 1+maxtextlen local pos = 1+maxtextlen
local prefix2 = prefix..MSG_MULTI_NEXT
while pos+maxtextlen <= textlen do while pos+maxtextlen <= textlen do
chunk = strsub(text, pos, pos+maxtextlen-1) chunk = strsub(text, pos, pos+maxtextlen-1)
CTL:SendAddonMessage(prio, prefix2, chunk, distribution, target, queueName, ctlCallback, pos+maxtextlen-1) CTL:SendAddonMessage(prio, prefix, MSG_MULTI_NEXT..chunk, distribution, target, queueName, ctlCallback, pos+maxtextlen-1)
pos = pos + maxtextlen pos = pos + maxtextlen
end end
-- final part -- final part
chunk = strsub(text, pos) chunk = strsub(text, pos)
CTL:SendAddonMessage(prio, prefix..MSG_MULTI_LAST, chunk, distribution, target, queueName, ctlCallback, textlen) CTL:SendAddonMessage(prio, prefix, MSG_MULTI_LAST..chunk, distribution, target, queueName, ctlCallback, textlen)
end end
end end
@@ -222,47 +230,31 @@ end
---------------------------------------- ----------------------------------------
if not AceComm.callbacks then if not AceComm.callbacks then
-- ensure that 'prefix to watch' table is consistent with registered
-- callbacks
AceComm.__prefixes = {}
AceComm.callbacks = CallbackHandler:New(AceComm, AceComm.callbacks = CallbackHandler:New(AceComm,
"_RegisterComm", "_RegisterComm",
"UnregisterComm", "UnregisterComm",
"UnregisterAllComm") "UnregisterAllComm")
end end
function AceComm.callbacks:OnUsed(target, prefix) AceComm.callbacks.OnUsed = nil
AceComm.multipart_origprefixes[prefix..MSG_MULTI_FIRST] = prefix AceComm.callbacks.OnUnused = nil
AceComm.multipart_reassemblers[prefix..MSG_MULTI_FIRST] = "OnReceiveMultipartFirst"
AceComm.multipart_origprefixes[prefix..MSG_MULTI_NEXT] = prefix local function OnEvent(self, event, prefix, message, distribution, sender)
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 if event == "CHAT_MSG_ADDON" then
local prefix,message,distribution,sender = ... sender = Ambiguate(sender, "none")
local reassemblername = AceComm.multipart_reassemblers[prefix] local control, rest = match(message, "^([\001-\009])(.*)")
if reassemblername then if control then
-- multipart: reassemble if control==MSG_MULTI_FIRST then
local aceCommReassemblerFunc = AceComm[reassemblername] AceComm:OnReceiveMultipartFirst(prefix, rest, distribution, sender)
local origprefix = AceComm.multipart_origprefixes[prefix] elseif control==MSG_MULTI_NEXT then
aceCommReassemblerFunc(AceComm, origprefix, message, distribution, sender) AceComm:OnReceiveMultipartNext(prefix, rest, distribution, sender)
elseif control==MSG_MULTI_LAST then
AceComm:OnReceiveMultipartLast(prefix, rest, distribution, sender)
elseif control==MSG_ESCAPE then
AceComm.callbacks:Fire(prefix, rest, distribution, sender)
else
-- unknown control character, ignore SILENTLY (dont warn unnecessarily about future extensions!)
end
else else
-- single part: fire it off immediately and let CallbackHandler decide if it's registered or not -- single part: fire it off immediately and let CallbackHandler decide if it's registered or not
AceComm.callbacks:Fire(prefix, message, distribution, sender) AceComm.callbacks:Fire(prefix, message, distribution, sender)
@@ -20,8 +20,10 @@
-- --
-- Can run as a standalone addon also, but, really, just embed it! :-) -- Can run as a standalone addon also, but, really, just embed it! :-)
-- --
-- LICENSE: ChatThrottleLib is released into the Public Domain
--
local CTL_VERSION = 21 local CTL_VERSION = 31
local _G = _G local _G = _G
@@ -71,8 +73,8 @@ local math_min = math.min
local math_max = math.max local math_max = math.max
local next = next local next = next
local strlen = string.len local strlen = string.len
local GetFrameRate = GetFrameRate local GetFramerate = GetFramerate
local unpack,type,pairs,wipe = unpack,type,pairs,table.wipe
----------------------------------------------------------------------- -----------------------------------------------------------------------
@@ -111,28 +113,41 @@ function Ring:Remove(obj)
end end
end end
-- Note that this is local because there's no upgrade logic for existing ring
-- metatables, and this isn't present on rings created in versions older than
-- v25.
local function Ring_Link(self, other) -- Move and append all contents of another ring to this ring
if not self.pos then
-- This ring is empty, so just transfer ownership.
self.pos = other.pos
other.pos = nil
elseif other.pos then
-- Our tail should point to their head, and their tail to our head.
self.pos.prev.next, other.pos.prev.next = other.pos, self.pos
-- Our head should point to their tail, and their head to our tail.
self.pos.prev, other.pos.prev = other.pos.prev, self.pos.prev
other.pos = nil
end
end
----------------------------------------------------------------------- -----------------------------------------------------------------------
-- Recycling bin for pipes -- Recycling bin for pipes
-- A pipe is a plain integer-indexed queue, which also happens to be a ring member -- A pipe is a plain integer-indexed queue of messages
-- Pipes normally live in Rings of pipes (3 rings total, one per priority)
ChatThrottleLib.PipeBin = nil -- pre-v19, drastically different ChatThrottleLib.PipeBin = nil -- pre-v19, drastically different
local PipeBin = setmetatable({}, {__mode="k"}) local PipeBin = setmetatable({}, {__mode="k"})
local function DelPipe(pipe) local function DelPipe(pipe)
for i = #pipe, 1, -1 do
pipe[i] = nil
end
pipe.prev = nil
pipe.next = nil
PipeBin[pipe] = true PipeBin[pipe] = true
end end
local function NewPipe() local function NewPipe()
local pipe = next(PipeBin) local pipe = next(PipeBin)
if pipe then if pipe then
wipe(pipe)
PipeBin[pipe] = nil PipeBin[pipe] = nil
return pipe return pipe
end end
@@ -179,6 +194,13 @@ function ChatThrottleLib:Init()
self.Prio["BULK"] = { ByName = {}, Ring = Ring:New(), avail = 0 } self.Prio["BULK"] = { ByName = {}, Ring = Ring:New(), avail = 0 }
end end
if not self.BlockedQueuesDelay then
-- v25: Add blocked queues to rings to handle new client throttles.
for _, Prio in pairs(self.Prio) do
Prio.Blocked = Ring:New()
end
end
-- v4: total send counters per priority -- v4: total send counters per priority
for _, Prio in pairs(self.Prio) do for _, Prio in pairs(self.Prio) do
Prio.nTotalSent = Prio.nTotalSent or 0 Prio.nTotalSent = Prio.nTotalSent or 0
@@ -201,6 +223,7 @@ function ChatThrottleLib:Init()
self.Frame:SetScript("OnEvent", self.OnEvent) -- v11: Monitor P_E_W so we can throttle hard for a few seconds 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.Frame:RegisterEvent("PLAYER_ENTERING_WORLD")
self.OnUpdateDelay = 0 self.OnUpdateDelay = 0
self.BlockedQueuesDelay = 0
self.LastAvailUpdate = GetTime() self.LastAvailUpdate = GetTime()
self.HardThrottlingBeginTime = GetTime() -- v11: Throttle hard for a few seconds after startup self.HardThrottlingBeginTime = GetTime() -- v11: Throttle hard for a few seconds after startup
@@ -209,14 +232,43 @@ function ChatThrottleLib:Init()
-- Use secure hooks as of v16. Old regular hook support yanked out in v21. -- Use secure hooks as of v16. Old regular hook support yanked out in v21.
self.securelyHooked = true self.securelyHooked = true
--SendChatMessage --SendChatMessage
hooksecurefunc("SendChatMessage", function(...) if _G.C_ChatInfo and _G.C_ChatInfo.SendChatMessage then
return ChatThrottleLib.Hook_SendChatMessage(...) hooksecurefunc(_G.C_ChatInfo, "SendChatMessage", function(...)
end) return ChatThrottleLib.Hook_SendChatMessage(...)
end)
else
hooksecurefunc("SendChatMessage", function(...)
return ChatThrottleLib.Hook_SendChatMessage(...)
end)
end
--SendAddonMessage --SendAddonMessage
hooksecurefunc("SendAddonMessage", function(...) hooksecurefunc(_G.C_ChatInfo, "SendAddonMessage", function(...)
return ChatThrottleLib.Hook_SendAddonMessage(...) return ChatThrottleLib.Hook_SendAddonMessage(...)
end) end)
end end
-- v26: Hook SendAddonMessageLogged for traffic logging
if not self.securelyHookedLogged then
self.securelyHookedLogged = true
hooksecurefunc(_G.C_ChatInfo, "SendAddonMessageLogged", function(...)
return ChatThrottleLib.Hook_SendAddonMessageLogged(...)
end)
end
-- v29: Hook BNSendGameData for traffic logging
if not self.securelyHookedBNGameData then
self.securelyHookedBNGameData = true
if _G.C_BattleNet and _G.C_BattleNet.SendGameData then
hooksecurefunc(_G.C_BattleNet, "SendGameData", function(...)
return ChatThrottleLib.Hook_BNSendGameData(...)
end)
else
hooksecurefunc("BNSendGameData", function(...)
return ChatThrottleLib.Hook_BNSendGameData(...)
end)
end
end
self.nBypass = 0 self.nBypass = 0
end end
@@ -245,6 +297,12 @@ function ChatThrottleLib.Hook_SendAddonMessage(prefix, text, chattype, destinati
self.avail = self.avail - size self.avail = self.avail - size
self.nBypass = self.nBypass + size -- just a statistic self.nBypass = self.nBypass + size -- just a statistic
end end
function ChatThrottleLib.Hook_SendAddonMessageLogged(prefix, text, chattype, destination, ...)
ChatThrottleLib.Hook_SendAddonMessage(prefix, text, chattype, destination, ...)
end
function ChatThrottleLib.Hook_BNSendGameData(destination, prefix, text)
ChatThrottleLib.Hook_SendAddonMessage(prefix, text, "WHISPER", destination)
end
@@ -281,27 +339,93 @@ end
----------------------------------------------------------------------- -----------------------------------------------------------------------
-- Despooling logic -- Despooling logic
-- Reminder:
-- - We have 3 Priorities, each containing a "Ring" construct ...
-- - ... made up of N "Pipe"s (1 for each destination/pipename)
-- - and each pipe contains messages
local SendAddonMessageResult = Enum.SendAddonMessageResult or {
Success = 0,
AddonMessageThrottle = 3,
NotInGroup = 5,
ChannelThrottle = 8,
GeneralError = 9,
}
local function MapToSendResult(ok, ...)
local result
if not ok then
-- The send function itself errored; don't look at anything else.
result = SendAddonMessageResult.GeneralError
else
-- Grab the last return value from the send function and remap
-- it from a boolean to an enum code. If there are no results,
-- assume success (true).
result = select(-1, true, ...)
if result == true then
result = SendAddonMessageResult.Success
elseif result == false then
result = SendAddonMessageResult.GeneralError
end
end
return result
end
local function IsThrottledSendResult(result)
return result == SendAddonMessageResult.AddonMessageThrottle
end
-- A copy of this function exists in FrameXML, but for clarity it's here too.
local function CallErrorHandler(...)
return geterrorhandler()(...)
end
local function PerformSend(sendFunction, ...)
bMyTraffic = true
local sendResult = MapToSendResult(xpcall(sendFunction, CallErrorHandler, ...))
bMyTraffic = false
return sendResult
end
function ChatThrottleLib:Despool(Prio) function ChatThrottleLib:Despool(Prio)
local ring = Prio.Ring local ring = Prio.Ring
while ring.pos and Prio.avail > ring.pos[1].nSize do while ring.pos and Prio.avail > ring.pos[1].nSize do
local msg = table_remove(Prio.Ring.pos, 1) local pipe = ring.pos
if not Prio.Ring.pos[1] then local msg = pipe[1]
local pipe = Prio.Ring.pos local sendResult = PerformSend(msg.f, unpack(msg, 1, msg.n))
if IsThrottledSendResult(sendResult) then
-- Message was throttled; move the pipe into the blocked ring.
Prio.Ring:Remove(pipe) Prio.Ring:Remove(pipe)
Prio.ByName[pipe.name] = nil Prio.Blocked:Add(pipe)
DelPipe(pipe)
else else
Prio.Ring.pos = Prio.Ring.pos.next -- Dequeue message after submission.
end table_remove(pipe, 1)
Prio.avail = Prio.avail - msg.nSize DelMsg(msg)
bMyTraffic = true
msg.f(unpack(msg, 1, msg.n)) if not pipe[1] then -- did we remove last msg in this pipe?
bMyTraffic = false Prio.Ring:Remove(pipe)
Prio.nTotalSent = Prio.nTotalSent + msg.nSize Prio.ByName[pipe.name] = nil
DelMsg(msg) DelPipe(pipe)
if msg.callbackFn then else
msg.callbackFn (msg.callbackArg) ring.pos = ring.pos.next
end
-- Update bandwidth counters on successful sends.
local didSend = (sendResult == SendAddonMessageResult.Success)
if didSend then
Prio.avail = Prio.avail - msg.nSize
Prio.nTotalSent = Prio.nTotalSent + msg.nSize
end
-- Notify caller of message submission.
if msg.callbackFn then
securecallfunction(msg.callbackFn, msg.callbackArg, didSend, sendResult)
end
end end
end end
end end
@@ -321,6 +445,7 @@ function ChatThrottleLib.OnUpdate(this,delay)
local self = ChatThrottleLib local self = ChatThrottleLib
self.OnUpdateDelay = self.OnUpdateDelay + delay self.OnUpdateDelay = self.OnUpdateDelay + delay
self.BlockedQueuesDelay = self.BlockedQueuesDelay + delay
if self.OnUpdateDelay < 0.08 then if self.OnUpdateDelay < 0.08 then
return return
end end
@@ -332,40 +457,60 @@ function ChatThrottleLib.OnUpdate(this,delay)
return -- argh. some bastard is spewing stuff past the lib. just bail early to save cpu. return -- argh. some bastard is spewing stuff past the lib. just bail early to save cpu.
end end
-- See how many of our priorities have queued messages (we only have 3, don't worry about the loop) -- Integrate blocked queues back into their rings periodically.
local n = 0 if self.BlockedQueuesDelay >= 0.35 then
for prioname,Prio in pairs(self.Prio) do for _, Prio in pairs(self.Prio) do
if Prio.Ring.pos or Prio.avail < 0 then Ring_Link(Prio.Ring, Prio.Blocked)
n = n + 1
end end
self.BlockedQueuesDelay = 0
end end
-- Anything queued still? -- See how many of our priorities have queued messages. This is split
if n<1 then -- into two counters because priorities that consist only of blocked
-- Nope. Move spillover bandwidth to global availability gauge and clear self.bQueueing -- queues must keep our OnUpdate alive, but shouldn't count toward
for prioname, Prio in pairs(self.Prio) do -- bandwidth distribution.
local nSendablePrios = 0
local nBlockedPrios = 0
for prioname, Prio in pairs(self.Prio) do
if Prio.Ring.pos then
nSendablePrios = nSendablePrios + 1
elseif Prio.Blocked.pos then
nBlockedPrios = nBlockedPrios + 1
end
-- Collect unused bandwidth from priorities with nothing to send.
if not Prio.Ring.pos then
self.avail = self.avail + Prio.avail self.avail = self.avail + Prio.avail
Prio.avail = 0 Prio.avail = 0
end end
self.bQueueing = false end
self.Frame:Hide()
-- Bandwidth reclamation may take us back over the burst cap.
self.avail = math_min(self.avail, self.BURST)
-- If we can't currently send on any priorities, stop processing early.
if nSendablePrios == 0 then
-- If we're completely out of data to send, disable queue processing.
if nBlockedPrios == 0 then
self.bQueueing = false
self.Frame:Hide()
end
return return
end end
-- There's stuff queued. Hand out available bandwidth to priorities as needed and despool their queues -- There's stuff queued. Hand out available bandwidth to priorities as needed and despool their queues
local avail = self.avail/n local avail = self.avail / nSendablePrios
self.avail = 0 self.avail = 0
for prioname, Prio in pairs(self.Prio) do for prioname, Prio in pairs(self.Prio) do
if Prio.Ring.pos or Prio.avail < 0 then if Prio.Ring.pos then
Prio.avail = Prio.avail + avail Prio.avail = Prio.avail + avail
if Prio.Ring.pos and Prio.avail > Prio.Ring.pos[1].nSize then self:Despool(Prio)
self:Despool(Prio)
-- Note: We might not get here if the user-supplied callback function errors out! Take care!
end
end end
end end
end end
@@ -374,7 +519,6 @@ end
----------------------------------------------------------------------- -----------------------------------------------------------------------
-- Spooling logic -- Spooling logic
function ChatThrottleLib:Enqueue(prioname, pipename, msg) function ChatThrottleLib:Enqueue(prioname, pipename, msg)
local Prio = self.Prio[prioname] local Prio = self.Prio[prioname]
local pipe = Prio.ByName[pipename] local pipe = Prio.ByName[pipename]
@@ -391,8 +535,6 @@ function ChatThrottleLib:Enqueue(prioname, pipename, msg)
self.bQueueing = true self.bQueueing = true
end end
function ChatThrottleLib:SendChatMessage(prio, prefix, text, chattype, language, destination, queueName, callbackFn, callbackArg) 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 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) error('Usage: ChatThrottleLib:SendChatMessage("{BULK||NORMAL||ALERT}", "prefix", "text"[, "chattype"[, "language"[, "destination"]]]', 2)
@@ -411,20 +553,27 @@ function ChatThrottleLib:SendChatMessage(prio, prefix, text, chattype, languag
-- Check if there's room in the global available bandwidth gauge to send directly -- Check if there's room in the global available bandwidth gauge to send directly
if not self.bQueueing and nSize < self:UpdateAvail() then if not self.bQueueing and nSize < self:UpdateAvail() then
self.avail = self.avail - nSize local sendResult = PerformSend(_G.C_ChatInfo.SendChatMessage or _G.SendChatMessage, text, chattype, language, destination)
bMyTraffic = true
_G.SendChatMessage(text, chattype, language, destination) if not IsThrottledSendResult(sendResult) then
bMyTraffic = false local didSend = (sendResult == SendAddonMessageResult.Success)
self.Prio[prio].nTotalSent = self.Prio[prio].nTotalSent + nSize
if callbackFn then if didSend then
callbackFn (callbackArg) self.avail = self.avail - nSize
self.Prio[prio].nTotalSent = self.Prio[prio].nTotalSent + nSize
end
if callbackFn then
securecallfunction(callbackFn, callbackArg, didSend, sendResult)
end
return
end end
return
end end
-- Message needs to be queued -- Message needs to be queued
local msg = NewMsg() local msg = NewMsg()
msg.f = _G.SendChatMessage msg.f = _G.C_ChatInfo.SendChatMessage or _G.SendChatMessage
msg[1] = text msg[1] = text
msg[2] = chattype or "SAY" msg[2] = chattype or "SAY"
msg[3] = language msg[3] = language
@@ -434,42 +583,36 @@ function ChatThrottleLib:SendChatMessage(prio, prefix, text, chattype, languag
msg.callbackFn = callbackFn msg.callbackFn = callbackFn
msg.callbackArg = callbackArg msg.callbackArg = callbackArg
self:Enqueue(prio, queueName or (prefix..(chattype or "SAY")..(destination or "")), msg) self:Enqueue(prio, queueName or prefix, msg)
end end
function ChatThrottleLib:SendAddonMessage(prio, prefix, text, chattype, target, queueName, callbackFn, callbackArg) local function SendAddonMessageInternal(self, sendFunction, 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 local nSize = #text + self.MSG_OVERHEAD
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 -- Check if there's room in the global available bandwidth gauge to send directly
if not self.bQueueing and nSize < self:UpdateAvail() then if not self.bQueueing and nSize < self:UpdateAvail() then
self.avail = self.avail - nSize local sendResult = PerformSend(sendFunction, prefix, text, chattype, target)
bMyTraffic = true
_G.SendAddonMessage(prefix, text, chattype, target) if not IsThrottledSendResult(sendResult) then
bMyTraffic = false local didSend = (sendResult == SendAddonMessageResult.Success)
self.Prio[prio].nTotalSent = self.Prio[prio].nTotalSent + nSize
if callbackFn then if didSend then
callbackFn (callbackArg) self.avail = self.avail - nSize
self.Prio[prio].nTotalSent = self.Prio[prio].nTotalSent + nSize
end
if callbackFn then
securecallfunction(callbackFn, callbackArg, didSend, sendResult)
end
return
end end
return
end end
-- Message needs to be queued -- Message needs to be queued
local msg = NewMsg() local msg = NewMsg()
msg.f = _G.SendAddonMessage msg.f = sendFunction
msg[1] = prefix msg[1] = prefix
msg[2] = text msg[2] = text
msg[3] = chattype msg[3] = chattype
@@ -479,10 +622,65 @@ function ChatThrottleLib:SendAddonMessage(prio, prefix, text, chattype, target,
msg.callbackFn = callbackFn msg.callbackFn = callbackFn
msg.callbackArg = callbackArg msg.callbackArg = callbackArg
self:Enqueue(prio, queueName or (prefix..chattype..(target or "")), msg) self:Enqueue(prio, queueName or prefix, msg)
end 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)
elseif callbackFn and type(callbackFn)~="function" then
error('ChatThrottleLib:SendAddonMessage(): callbackFn: expected function, got '..type(callbackFn), 2)
elseif #text>255 then
error("ChatThrottleLib:SendAddonMessage(): message length cannot exceed 255 bytes", 2)
end
local sendFunction = _G.C_ChatInfo.SendAddonMessage
SendAddonMessageInternal(self, sendFunction, prio, prefix, text, chattype, target, queueName, callbackFn, callbackArg)
end
function ChatThrottleLib:SendAddonMessageLogged(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:SendAddonMessageLogged("{BULK||NORMAL||ALERT}", "prefix", "text", "chattype"[, "target"])', 2)
elseif callbackFn and type(callbackFn)~="function" then
error('ChatThrottleLib:SendAddonMessageLogged(): callbackFn: expected function, got '..type(callbackFn), 2)
elseif #text>255 then
error("ChatThrottleLib:SendAddonMessageLogged(): message length cannot exceed 255 bytes", 2)
end
local sendFunction = _G.C_ChatInfo.SendAddonMessageLogged
SendAddonMessageInternal(self, sendFunction, prio, prefix, text, chattype, target, queueName, callbackFn, callbackArg)
end
local function BNSendGameDataReordered(prefix, text, _, gameAccountID)
local bnSendFunc = _G.C_BattleNet and _G.C_BattleNet.SendGameData or _G.BNSendGameData
return bnSendFunc(gameAccountID, prefix, text)
end
function ChatThrottleLib:BNSendGameData(prio, prefix, text, chattype, gameAccountID, queueName, callbackFn, callbackArg)
-- Note that this API is intentionally limited to 255 bytes of data
-- for reasons of traffic fairness, which is less than the 4078 bytes
-- BNSendGameData natively supports. Additionally, a chat type is required
-- but must always be set to 'WHISPER' to match what is exposed by the
-- receipt event.
--
-- If splitting messages, callers must also be aware that message
-- delivery over BNSendGameData is unordered.
if not self or not prio or not prefix or not text or not gameAccountID or not chattype or not self.Prio[prio] then
error('Usage: ChatThrottleLib:BNSendGameData("{BULK||NORMAL||ALERT}", "prefix", "text", "chattype", gameAccountID)', 2)
elseif callbackFn and type(callbackFn)~="function" then
error('ChatThrottleLib:BNSendGameData(): callbackFn: expected function, got '..type(callbackFn), 2)
elseif #text>255 then
error("ChatThrottleLib:BNSendGameData(): message length cannot exceed 255 bytes", 2)
elseif chattype ~= "WHISPER" then
error("ChatThrottleLib:BNSendGameData(): chat type must be 'WHISPER'", 2)
end
local sendFunction = BNSendGameDataReordered
SendAddonMessageInternal(self, sendFunction, prio, prefix, text, chattype, gameAccountID, queueName, callbackFn, callbackArg)
end
----------------------------------------------------------------------- -----------------------------------------------------------------------
@@ -9,7 +9,7 @@
-- make into AceConsole. -- make into AceConsole.
-- @class file -- @class file
-- @name AceConsole-3.0 -- @name AceConsole-3.0
-- @release $Id: AceConsole-3.0.lua 878 2009-11-02 18:51:58Z nevcairiel $ -- @release $Id$
local MAJOR,MINOR = "AceConsole-3.0", 7 local MAJOR,MINOR = "AceConsole-3.0", 7
local AceConsole, oldminor = LibStub:NewLibrary(MAJOR, MINOR) local AceConsole, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
@@ -29,10 +29,6 @@ local max = math.max
-- WoW APIs -- WoW APIs
local _G = _G 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 tmp={}
local function Print(self,frame,...) local function Print(self,frame,...)
local n=0 local n=0
@@ -136,7 +132,7 @@ end
--- Retreive one or more space-separated arguments from a string. --- Retreive one or more space-separated arguments from a string.
-- Treats quoted strings and itemlinks as non-spaced. -- Treats quoted strings and itemlinks as non-spaced.
-- @param string The raw argument string -- @param str The raw argument string
-- @param numargs How many arguments to get (default 1) -- @param numargs How many arguments to get (default 1)
-- @param startpos Where in the string to start scanning (default 1) -- @param startpos Where in the string to start scanning (default 1)
-- @return Returns arg1, arg2, ..., nextposition\\ -- @return Returns arg1, arg2, ..., nextposition\\
@@ -174,7 +170,7 @@ function AceConsole:GetArgs(str, numargs, startpos)
while true do while true do
-- find delimiter or hyperlink -- find delimiter or hyperlink
local ch,_ local _
pos,_,ch = strfind(str, delim_or_pipe, pos) pos,_,ch = strfind(str, delim_or_pipe, pos)
if not pos then break end if not pos then break end
+111 -34
View File
@@ -10,6 +10,7 @@
-- * **race** Race-specific data. All of the players characters of the same race 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. -- * **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. -- * **factionrealm** Faction and realm specific data. All of the players characters on the same realm and of the same faction share this database.
-- * **locale** Locale specific data, based on the locale of the players game client.
-- * **global** Global Data. All characters on the same account share this database. -- * **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. -- * **profile** Profile-specific data. All characters using the same profile share this database. The user can control which profile should be used.
-- --
@@ -39,23 +40,19 @@
-- end -- end
-- @class file -- @class file
-- @name AceDB-3.0.lua -- @name AceDB-3.0.lua
-- @release $Id: AceDB-3.0.lua 940 2010-06-19 08:01:47Z nevcairiel $ -- @release $Id$
local ACEDB_MAJOR, ACEDB_MINOR = "AceDB-3.0", 21 local ACEDB_MAJOR, ACEDB_MINOR = "AceDB-3.0", 33
local AceDB, oldminor = LibStub:NewLibrary(ACEDB_MAJOR, ACEDB_MINOR) local AceDB = LibStub:NewLibrary(ACEDB_MAJOR, ACEDB_MINOR)
if not AceDB then return end -- No upgrade needed if not AceDB then return end -- No upgrade needed
-- Lua APIs -- Lua APIs
local type, pairs, next, error = type, pairs, next, error local type, pairs, next, error = type, pairs, next, error
local setmetatable, getmetatable, rawset, rawget = setmetatable, getmetatable, rawset, rawget local setmetatable, rawset, rawget = setmetatable, rawset, rawget
-- WoW APIs -- WoW APIs
local _G = _G 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.db_registry = AceDB.db_registry or {}
AceDB.frame = AceDB.frame or CreateFrame("Frame") AceDB.frame = AceDB.frame or CreateFrame("Frame")
@@ -97,11 +94,11 @@ local function copyDefaults(dest, src)
-- This is a metatable used for table defaults -- This is a metatable used for table defaults
local mt = { local mt = {
-- This handles the lookup and creation of new subtables -- This handles the lookup and creation of new subtables
__index = function(t,k) __index = function(t,k2)
if k == nil then return nil end if k2 == nil then return nil end
local tbl = {} local tbl = {}
copyDefaults(tbl, v) copyDefaults(tbl, v)
rawset(t, k, tbl) rawset(t, k2, tbl)
return tbl return tbl
end, end,
} }
@@ -114,7 +111,15 @@ local function copyDefaults(dest, src)
end end
else else
-- Values are not tables, so this is just a simple return -- 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} -- (PR #10 backport: the old `k2~=nil and v or nil` short-circuits to
-- nil whenever the default `v` itself is falsy — so `["*"] = false`
-- defaults silently became nil. Make the read explicit instead.)
local mt = {
__index = function(t,k2)
if k2 == nil then return nil end
return v
end,
}
setmetatable(dest, mt) setmetatable(dest, mt)
end end
elseif type(v) == "table" then elseif type(v) == "table" then
@@ -260,6 +265,12 @@ local _, classKey = UnitClass("player")
local _, raceKey = UnitRace("player") local _, raceKey = UnitRace("player")
local factionKey = UnitFactionGroup("player") local factionKey = UnitFactionGroup("player")
local factionrealmKey = factionKey .. " - " .. realmKey local factionrealmKey = factionKey .. " - " .. realmKey
local localeKey = GetLocale():lower()
local regionTable = { "US", "KR", "EU", "TW", "CN" }
local regionKey = regionTable[GetCurrentRegion()] or GetCurrentRegionName() or "TR"
local factionrealmregionKey = factionrealmKey .. " - " .. regionKey
-- Actual database initialization function -- Actual database initialization function
local function initdb(sv, defaults, defaultProfile, olddb, parent) local function initdb(sv, defaults, defaultProfile, olddb, parent)
-- Generate the database keys for each section -- Generate the database keys for each section
@@ -295,7 +306,9 @@ local function initdb(sv, defaults, defaultProfile, olddb, parent)
["race"] = raceKey, ["race"] = raceKey,
["faction"] = factionKey, ["faction"] = factionKey,
["factionrealm"] = factionrealmKey, ["factionrealm"] = factionrealmKey,
["factionrealmregion"] = factionrealmregionKey,
["profile"] = profileKey, ["profile"] = profileKey,
["locale"] = localeKey,
["global"] = true, ["global"] = true,
["profiles"] = true, ["profiles"] = true,
} }
@@ -355,7 +368,7 @@ local function logoutHandler(frame, event)
-- cleanup sections that are empty without defaults -- cleanup sections that are empty without defaults
local sv = rawget(db, "sv") local sv = rawget(db, "sv")
for section in pairs(db.keys) do for section in pairs(rawget(db, "keys")) do
if rawget(sv, section) then if rawget(sv, section) then
-- global is special, all other sections have sub-entrys -- global is special, all other sections have sub-entrys
-- also don't delete empty profiles on main dbs, only on namespaces -- also don't delete empty profiles on main dbs, only on namespaces
@@ -372,6 +385,26 @@ local function logoutHandler(frame, event)
end end
end end
end end
-- second pass after everything else is cleaned up to remove empty namespaces
-- can't be run in-loop above since there is no guaranteed order
for db in pairs(AceDB.db_registry) do
local sv = rawget(db, "sv")
local namespaces = rawget(sv, "namespaces")
if namespaces then
for name in pairs(namespaces) do
-- cleanout empty profiles table, if still present
if namespaces[name].profiles and not next(namespaces[name].profiles) then
namespaces[name].profiles = nil
end
-- remove entire namespace, if needed
if not next(namespaces[name]) then
namespaces[name] = nil
end
end
end
end
end end
end end
@@ -388,7 +421,7 @@ AceDB.frame:SetScript("OnEvent", logoutHandler)
-- @param defaults A table of defaults for this database -- @param defaults A table of defaults for this database
function DBObjectLib:RegisterDefaults(defaults) function DBObjectLib:RegisterDefaults(defaults)
if defaults and type(defaults) ~= "table" then if defaults and type(defaults) ~= "table" then
error("Usage: AceDBObject:RegisterDefaults(defaults): 'defaults' - table or nil expected.", 2) error(("Usage: AceDBObject:RegisterDefaults(defaults): 'defaults' - table or nil expected, got %q."):format(type(defaults)), 2)
end end
validateDefaults(defaults, self.keys) validateDefaults(defaults, self.keys)
@@ -420,7 +453,7 @@ end
-- @param name The name of the profile to set as the current profile -- @param name The name of the profile to set as the current profile
function DBObjectLib:SetProfile(name) function DBObjectLib:SetProfile(name)
if type(name) ~= "string" then if type(name) ~= "string" then
error("Usage: AceDBObject:SetProfile(name): 'name' - string expected.", 2) error(("Usage: AceDBObject:SetProfile(name): 'name' - string expected, got %q."):format(type(name)), 2)
end end
-- changing to the same profile, dont do anything -- changing to the same profile, dont do anything
@@ -462,7 +495,7 @@ end
-- @param tbl A table to store the profile names in (optional) -- @param tbl A table to store the profile names in (optional)
function DBObjectLib:GetProfiles(tbl) function DBObjectLib:GetProfiles(tbl)
if tbl and type(tbl) ~= "table" then if tbl and type(tbl) ~= "table" then
error("Usage: AceDBObject:GetProfiles(tbl): 'tbl' - table or nil expected.", 2) error(("Usage: AceDBObject:GetProfiles(tbl): 'tbl' - table or nil expected, got %q."):format(type(tbl)), 2)
end end
-- Clear the container table -- Clear the container table
@@ -500,15 +533,15 @@ end
-- @param silent If true, do not raise an error when the profile does not exist -- @param silent If true, do not raise an error when the profile does not exist
function DBObjectLib:DeleteProfile(name, silent) function DBObjectLib:DeleteProfile(name, silent)
if type(name) ~= "string" then if type(name) ~= "string" then
error("Usage: AceDBObject:DeleteProfile(name): 'name' - string expected.", 2) error(("Usage: AceDBObject:DeleteProfile(name): 'name' - string expected, got %q."):format(type(name)), 2)
end end
if self.keys.profile == name then if self.keys.profile == name then
error("Cannot delete the active profile in an AceDBObject.", 2) error(("Cannot delete the active profile (%q) in an AceDBObject."):format(name), 2)
end end
if not rawget(self.profiles, name) and not silent then if not rawget(self.profiles, name) and not silent then
error("Cannot delete profile '" .. name .. "'. It does not exist.", 2) error(("Cannot delete profile %q as it does not exist."):format(name), 2)
end end
self.profiles[name] = nil self.profiles[name] = nil
@@ -520,6 +553,26 @@ function DBObjectLib:DeleteProfile(name, silent)
end end
end end
-- remove from unloaded namespaces
if self.sv.namespaces then
for nsname, data in pairs(self.sv.namespaces) do
if self.children and self.children[nsname] then
-- already a mapped namespace
elseif data.profiles then
data.profiles[name] = nil
end
end
end
-- switch all characters that use this profile back to the default
if self.sv.profileKeys then
for key, profile in pairs(self.sv.profileKeys) do
if profile == name then
self.sv.profileKeys[key] = nil
end
end
end
-- Callback: OnProfileDeleted, database, profileKey -- Callback: OnProfileDeleted, database, profileKey
self.callbacks:Fire("OnProfileDeleted", self, name) self.callbacks:Fire("OnProfileDeleted", self, name)
end end
@@ -530,15 +583,15 @@ end
-- @param silent If true, do not raise an error when the profile does not exist -- @param silent If true, do not raise an error when the profile does not exist
function DBObjectLib:CopyProfile(name, silent) function DBObjectLib:CopyProfile(name, silent)
if type(name) ~= "string" then if type(name) ~= "string" then
error("Usage: AceDBObject:CopyProfile(name): 'name' - string expected.", 2) error(("Usage: AceDBObject:CopyProfile(name): 'name' - string expected, got %q."):format(type(name)), 2)
end end
if name == self.keys.profile then if name == self.keys.profile then
error("Cannot have the same source and destination profiles.", 2) error(("Cannot have the same source and destination profiles (%q)."):format(name), 2)
end end
if not rawget(self.profiles, name) and not silent then if not rawget(self.profiles, name) and not silent then
error("Cannot copy profile '" .. name .. "'. It does not exist.", 2) error(("Cannot copy profile %q as it does not exist."):format(name), 2)
end end
-- Reset the profile before copying -- Reset the profile before copying
@@ -556,6 +609,20 @@ function DBObjectLib:CopyProfile(name, silent)
end end
end end
-- copy unloaded namespaces
if self.sv.namespaces then
for nsname, data in pairs(self.sv.namespaces) do
if self.children and self.children[nsname] then
-- already a mapped namespace
elseif data.profiles then
-- reset the current profile
data.profiles[self.keys.profile] = {}
-- copy data
copyTable(data.profiles[name], data.profiles[self.keys.profile])
end
end
end
-- Callback: OnProfileCopied, database, sourceProfileKey -- Callback: OnProfileCopied, database, sourceProfileKey
self.callbacks:Fire("OnProfileCopied", self, name) self.callbacks:Fire("OnProfileCopied", self, name)
end end
@@ -582,6 +649,18 @@ function DBObjectLib:ResetProfile(noChildren, noCallbacks)
end end
end end
-- reset unloaded namespaces
if self.sv.namespaces and not noChildren then
for nsname, data in pairs(self.sv.namespaces) do
if self.children and self.children[nsname] then
-- already a mapped namespace
elseif data.profiles then
-- reset the current profile
data.profiles[self.keys.profile] = nil
end
end
end
-- Callback: OnProfileReset, database -- Callback: OnProfileReset, database
if not noCallbacks then if not noCallbacks then
self.callbacks:Fire("OnProfileReset", self) self.callbacks:Fire("OnProfileReset", self)
@@ -592,8 +671,8 @@ end
-- profile. -- profile.
-- @param defaultProfile The profile name to use as the default -- @param defaultProfile The profile name to use as the default
function DBObjectLib:ResetDB(defaultProfile) function DBObjectLib:ResetDB(defaultProfile)
if defaultProfile and type(defaultProfile) ~= "string" then if defaultProfile and type(defaultProfile) ~= "string" and defaultProfile ~= true then
error("Usage: AceDBObject:ResetDB(defaultProfile): 'defaultProfile' - string or nil expected.", 2) error(("Usage: AceDBObject:ResetDB(defaultProfile): 'defaultProfile' - string or true expected, got %q."):format(type(defaultProfile)), 2)
end end
local sv = self.sv local sv = self.sv
@@ -601,8 +680,6 @@ function DBObjectLib:ResetDB(defaultProfile)
sv[k] = nil sv[k] = nil
end end
local parent = self.parent
initdb(sv, self.defaults, defaultProfile, self) initdb(sv, self.defaults, defaultProfile, self)
-- fix the child namespaces -- fix the child namespaces
@@ -629,13 +706,13 @@ end
-- @param defaults A table of values to use as defaults -- @param defaults A table of values to use as defaults
function DBObjectLib:RegisterNamespace(name, defaults) function DBObjectLib:RegisterNamespace(name, defaults)
if type(name) ~= "string" then if type(name) ~= "string" then
error("Usage: AceDBObject:RegisterNamespace(name, defaults): 'name' - string expected.", 2) error(("Usage: AceDBObject:RegisterNamespace(name, defaults): 'name' - string expected, got %q."):format(type(name)), 2)
end end
if defaults and type(defaults) ~= "table" then if defaults and type(defaults) ~= "table" then
error("Usage: AceDBObject:RegisterNamespace(name, defaults): 'defaults' - table or nil expected.", 2) error(("Usage: AceDBObject:RegisterNamespace(name, defaults): 'defaults' - table or nil expected, got %q."):format(type(defaults)), 2)
end end
if self.children and self.children[name] then if self.children and self.children[name] then
error ("Usage: AceDBObject:RegisterNamespace(name, defaults): 'name' - a namespace with that name already exists.", 2) error(("Usage: AceDBObject:RegisterNamespace(name, defaults): 'name' - a namespace called %q already exists."):format(name), 2)
end end
local sv = self.sv local sv = self.sv
@@ -659,10 +736,10 @@ end
-- @return the namespace object if found -- @return the namespace object if found
function DBObjectLib:GetNamespace(name, silent) function DBObjectLib:GetNamespace(name, silent)
if type(name) ~= "string" then if type(name) ~= "string" then
error("Usage: AceDBObject:GetNamespace(name): 'name' - string expected.", 2) error(("Usage: AceDBObject:GetNamespace(name): 'name' - string expected, got %q."):format(type(name)), 2)
end end
if not silent and not (self.children and self.children[name]) then if not silent and not (self.children and self.children[name]) then
error ("Usage: AceDBObject:GetNamespace(name): 'name' - namespace does not exist.", 2) error(("Usage: AceDBObject:GetNamespace(name): 'name' - namespace %q does not exist."):format(name), 2)
end end
if not self.children then self.children = {} end if not self.children then self.children = {} end
return self.children[name] return self.children[name]
@@ -701,15 +778,15 @@ function AceDB:New(tbl, defaults, defaultProfile)
end end
if type(tbl) ~= "table" then if type(tbl) ~= "table" then
error("Usage: AceDB:New(tbl, defaults, defaultProfile): 'tbl' - table expected.", 2) error(("Usage: AceDB:New(tbl, defaults, defaultProfile): 'tbl' - table expected, got %q."):format(type(tbl)), 2)
end end
if defaults and type(defaults) ~= "table" then if defaults and type(defaults) ~= "table" then
error("Usage: AceDB:New(tbl, defaults, defaultProfile): 'defaults' - table expected.", 2) error(("Usage: AceDB:New(tbl, defaults, defaultProfile): 'defaults' - table expected, got %q."):format(type(defaults)), 2)
end end
if defaultProfile and type(defaultProfile) ~= "string" and defaultProfile ~= true then if defaultProfile and type(defaultProfile) ~= "string" and defaultProfile ~= true then
error("Usage: AceDB:New(tbl, defaults, defaultProfile): 'defaultProfile' - string or true expected.", 2) error(("Usage: AceDB:New(tbl, defaults, defaultProfile): 'defaultProfile' - string or true expected, got %q."):format(type(defaultProfile)), 2)
end end
return initdb(tbl, defaults, defaultProfile) return initdb(tbl, defaults, defaultProfile)
@@ -9,8 +9,10 @@
-- make into AceEvent. -- make into AceEvent.
-- @class file -- @class file
-- @name AceEvent-3.0 -- @name AceEvent-3.0
-- @release $Id: AceEvent-3.0.lua 877 2009-11-02 15:56:50Z nevcairiel $ -- @release $Id$
local MAJOR, MINOR = "AceEvent-3.0", 3 local CallbackHandler = LibStub("CallbackHandler-1.0")
local MAJOR, MINOR = "AceEvent-3.0", 4
local AceEvent = LibStub:NewLibrary(MAJOR, MINOR) local AceEvent = LibStub:NewLibrary(MAJOR, MINOR)
if not AceEvent then return end if not AceEvent then return end
@@ -18,8 +20,6 @@ if not AceEvent then return end
-- Lua APIs -- Lua APIs
local pairs = pairs local pairs = pairs
local CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0")
AceEvent.frame = AceEvent.frame or CreateFrame("Frame", "AceEvent30Frame") -- our event frame AceEvent.frame = AceEvent.frame or CreateFrame("Frame", "AceEvent30Frame") -- our event frame
AceEvent.embeds = AceEvent.embeds or {} -- what objects embed this lib AceEvent.embeds = AceEvent.embeds or {} -- what objects embed this lib
@@ -55,7 +55,7 @@ local mixins = {
} }
--- Register for a Blizzard Event. --- 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. -- The callback will be called with the optional `arg` as the first argument (if supplied), and the event name as the second (or first, if no arg was supplied)
-- Any arguments to the event will be passed on after that. -- Any arguments to the event will be passed on after that.
-- @name AceEvent:RegisterEvent -- @name AceEvent:RegisterEvent
-- @class function -- @class function
@@ -71,7 +71,7 @@ local mixins = {
-- @param event The event to unregister -- @param event The event to unregister
--- Register for a custom AceEvent-internal message. --- 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. -- The callback will be called with the optional `arg` as the first argument (if supplied), and the event name as the second (or first, if no arg was supplied)
-- Any arguments to the event will be passed on after that. -- Any arguments to the event will be passed on after that.
-- @name AceEvent:RegisterMessage -- @name AceEvent:RegisterMessage
-- @class function -- @class function
@@ -10,8 +10,8 @@
-- make into AceSerializer. -- make into AceSerializer.
-- @class file -- @class file
-- @name AceSerializer-3.0 -- @name AceSerializer-3.0
-- @release $Id: AceSerializer-3.0.lua 910 2010-02-11 21:54:24Z mikk $ -- @release $Id$
local MAJOR,MINOR = "AceSerializer-3.0", 3 local MAJOR,MINOR = "AceSerializer-3.0", 5
local AceSerializer, oldminor = LibStub:NewLibrary(MAJOR, MINOR) local AceSerializer, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
if not AceSerializer then return end if not AceSerializer then return end
@@ -24,9 +24,11 @@ local pairs, select, frexp = pairs, select, math.frexp
local tconcat = table.concat local tconcat = table.concat
-- quick copies of string representations of wonky numbers -- quick copies of string representations of wonky numbers
local serNaN = tostring(0/0) local inf = math.huge
local serInf = tostring(1/0)
local serNegInf = tostring(-1/0) local serNaN -- can't do this in 4.3, see ace3 ticket 268
local serInf, serInfMac = "1.#INF", "inf"
local serNegInf, serNegInfMac = "-1.#INF", "-inf"
-- Serialization functions -- Serialization functions
@@ -60,11 +62,15 @@ local function SerializeValue(v, res, nres)
elseif t=="number" then -- ^N = number (just tostring()ed) or ^F (float components) elseif t=="number" then -- ^N = number (just tostring()ed) or ^F (float components)
local str = tostring(v) local str = tostring(v)
if tonumber(str)==v or str==serNaN or str==serInf or str==serNegInf then if tonumber(str)==v --[[not in 4.3 or str==serNaN]] then
-- translates just fine, transmit as-is -- translates just fine, transmit as-is
res[nres+1] = "^N" res[nres+1] = "^N"
res[nres+2] = str res[nres+2] = str
nres=nres+2 nres=nres+2
elseif v == inf or v == -inf then
res[nres+1] = "^N"
res[nres+2] = v == inf and serInf or serNegInf
nres=nres+2
else else
local m,e = frexp(v) local m,e = frexp(v)
res[nres+1] = "^F" res[nres+1] = "^F"
@@ -77,9 +83,9 @@ local function SerializeValue(v, res, nres)
elseif t=="table" then -- ^T...^t = table (list of key,value pairs) elseif t=="table" then -- ^T...^t = table (list of key,value pairs)
nres=nres+1 nres=nres+1
res[nres] = "^T" res[nres] = "^T"
for k,v in pairs(v) do for key,value in pairs(v) do
nres = SerializeValue(k, res, nres) nres = SerializeValue(key, res, nres)
nres = SerializeValue(v, res, nres) nres = SerializeValue(value, res, nres)
end end
nres=nres+1 nres=nres+1
res[nres] = "^t" res[nres] = "^t"
@@ -143,12 +149,12 @@ local function DeserializeStringHelper(escape)
end end
local function DeserializeNumberHelper(number) local function DeserializeNumberHelper(number)
if number == serNaN then --[[ not in 4.3 if number == serNaN then
return 0/0 return 0/0
elseif number == serNegInf then else]]if number == serNegInf or number == serNegInfMac then
return -1/0 return -inf
elseif number == serInf then elseif number == serInf or number == serInfMac then
return 1/0 return inf
else else
return tonumber(number) return tonumber(number)
end end
+167 -362
View File
@@ -1,12 +1,12 @@
--- **AceTimer-3.0** provides a central facility for registering timers. --- **AceTimer-3.0** provides a central facility for registering timers.
-- AceTimer supports one-shot timers and repeating timers. All timers are stored in an efficient -- AceTimer supports one-shot timers and repeating timers. All timers are stored in an efficient
-- data structure that allows easy dispatching and fast rescheduling. Timers can be registered, rescheduled -- data structure that allows easy dispatching and fast rescheduling. Timers can be registered
-- or canceled at any time, even from within a running timer, without conflict or large overhead.\\ -- or canceled at any time, even from within a running timer, without conflict or large overhead.\\
-- AceTimer is currently limited to firing timers at a frequency of 0.1s. This constant may change -- AceTimer is currently limited to firing timers at a frequency of 0.01s as this is what the WoW timer API
-- in the future, but for now it seemed like a good compromise in efficiency and accuracy. -- restricts us to.
-- --
-- All `:Schedule` functions will return a handle to the current timer, which you will need to store if you -- All `:Schedule` functions will return a handle to the current timer, which you will need to store if you
-- need to cancel or reschedule the timer you just registered. -- need to cancel the timer you just registered.
-- --
-- **AceTimer-3.0** can be embeded into your addon, either explicitly by calling AceTimer:Embed(MyAddon) or by -- **AceTimer-3.0** can be embeded into your addon, either explicitly by calling AceTimer:Embed(MyAddon) or by
-- specifying it as an embeded library in your AceAddon. All functions will be available on your addon object -- specifying it as an embeded library in your AceAddon. All functions will be available on your addon object
@@ -15,282 +15,110 @@
-- make into AceTimer. -- make into AceTimer.
-- @class file -- @class file
-- @name AceTimer-3.0 -- @name AceTimer-3.0
-- @release $Id: AceTimer-3.0.lua 895 2009-12-06 16:28:55Z nevcairiel $ -- @release $Id$
--[[ local MAJOR, MINOR = "AceTimer-3.0", 17 -- Bump minor on changes
Basic assumptions:
* In a typical system, we do more re-scheduling per second than there are timer pulses per second
* Regardless of timer implementation, we cannot guarantee timely delivery due to FPS restriction (may be as low as 10)
This implementation:
CON: The smallest timer interval is constrained by HZ (currently 1/10s).
PRO: It will still correctly fire any timer slower than HZ over a length of time, e.g. 0.11s interval -> 90 times over 10 seconds
PRO: In lag bursts, the system simly skips missed timer intervals to decrease load
CON: Algorithms depending on a timer firing "N times per minute" will fail
PRO: (Re-)scheduling is O(1) with a VERY small constant. It's a simple linked list insertion in a hash bucket.
CAUTION: The BUCKETS constant constrains how many timers can be efficiently handled. With too many hash collisions, performance will decrease.
Major assumptions upheld:
- ALLOWS scheduling multiple timers with the same funcref/method
- ALLOWS scheduling more timers during OnUpdate processing
- ALLOWS unscheduling ANY timer (including the current running one) at any time, including during OnUpdate processing
]]
local MAJOR, MINOR = "AceTimer-3.0", 5
local AceTimer, oldminor = LibStub:NewLibrary(MAJOR, MINOR) local AceTimer, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
if not AceTimer then return end -- No upgrade needed if not AceTimer then return end -- No upgrade needed
AceTimer.activeTimers = AceTimer.activeTimers or {} -- Active timer list
AceTimer.hash = AceTimer.hash or {} -- Array of [0..BUCKET-1] = linked list of timers (using .next member) local activeTimers = AceTimer.activeTimers -- Upvalue our private data
-- Linked list gets around ACE-88 and ACE-90.
AceTimer.selfs = AceTimer.selfs or {} -- Array of [self]={[handle]=timerobj, [handle2]=timerobj2, ...}
AceTimer.frame = AceTimer.frame or CreateFrame("Frame", "AceTimer30Frame")
-- Lua APIs -- Lua APIs
local assert, error, loadstring = assert, error, loadstring local type, unpack, next, error, select = type, unpack, next, error, select
local setmetatable, rawset, rawget = setmetatable, rawset, rawget
local select, pairs, type, next, tostring = select, pairs, type, next, tostring
local floor, max, min = math.floor, math.max, math.min
local tconcat = table.concat
-- WoW APIs -- WoW APIs
local GetTime = GetTime local GetTime, C_TimerAfter = GetTime, C_Timer.After
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded local function new(self, loop, func, delay, ...)
-- List them here for Mikk's FindGlobals script if delay < 0.01 then
-- GLOBALS: DEFAULT_CHAT_FRAME, geterrorhandler delay = 0.01 -- Restrict to the lowest time that the C_Timer API allows us
-- Simple ONE-SHOT timer cache. Much more efficient than a full compost for our purposes.
local timerCache = nil
--[[
Timers will not be fired more often than HZ-1 times per second.
Keep at intended speed PLUS ONE or we get bitten by floating point rounding errors (n.5 + 0.1 can be n.599999)
If this is ever LOWERED, all existing timers need to be enforced to have a delay >= 1/HZ on lib upgrade.
If this number is ever changed, all entries need to be rehashed on lib upgrade.
]]
local HZ = 11
--[[
Prime for good distribution
If this number is ever changed, all entries need to be rehashed on lib upgrade.
]]
local BUCKETS = 131
local hash = AceTimer.hash
for i=1,BUCKETS do
hash[i] = hash[i] or false -- make it an integer-indexed array; it's faster than hashes
end
--[[
xpcall safecall implementation
]]
local xpcall = xpcall
local function errorhandler(err)
return geterrorhandler()(err)
end
local function CreateDispatcher(argCount)
local code = [[
local xpcall, eh = ... -- our arguments are received as unnamed values in "..." since we don't have a proper function declaration
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 end
})
Dispatchers[0] = function(func)
return xpcall(func, errorhandler)
end
local function safecall(func, ...) local timer = {
return Dispatchers[select('#', ...)](func, ...) object = self,
end func = func,
looping = loop,
argsCount = select("#", ...),
delay = delay,
ends = GetTime() + delay,
...
}
local lastint = floor(GetTime() * HZ) activeTimers[timer] = timer
-- -------------------------------------------------------------------- -- Create new timer closure to wrap the "timer" object
-- OnUpdate handler timer.callback = function()
-- if not timer.cancelled then
-- traverse buckets, always chasing "now", and fire timers that have expired if type(timer.func) == "string" then
-- We manually set the unpack count to prevent issues with an arg set that contains nil and ends with nil
-- e.g. local t = {1, 2, nil, 3, nil} print(#t) will result in 2, instead of 5. This fixes said issue.
timer.object[timer.func](timer.object, unpack(timer, 1, timer.argsCount))
else
timer.func(unpack(timer, 1, timer.argsCount))
end
local function OnUpdate() if timer.looping and not timer.cancelled then
local now = GetTime() -- Compensate delay to get a perfect average delay, even if individual times don't match up perfectly
local nowint = floor(now * HZ) -- due to fps differences
local time = GetTime()
-- Have we passed into a new hash bucket? local ndelay = timer.delay - (time - timer.ends)
if nowint == lastint then return end -- Ensure the delay doesn't go below the threshold
if ndelay < 0.01 then ndelay = 0.01 end
local soon = now + 1 -- +1 is safe as long as 1 < HZ < BUCKETS/2 C_TimerAfter(ndelay, timer.callback)
timer.ends = time + ndelay
-- Pass through each bucket at most once else
-- Happens on e.g. instance loads, but COULD happen on high local load situations also activeTimers[timer.handle or timer] = nil
for curint = (max(lastint, nowint - BUCKETS) + 1), nowint do -- loop until we catch up with "now", usually only 1 iteration end
local curbucket = (curint % BUCKETS)+1
-- Yank the list of timers out of the bucket and empty it. This allows reinsertion in the currently-processed bucket from callbacks.
local nexttimer = hash[curbucket]
hash[curbucket] = false -- false rather than nil to prevent the array from becoming a hash
while nexttimer do
local timer = nexttimer
nexttimer = timer.next
local when = timer.when
if when < soon then
-- Call the timer func, either as a method on given object, or a straight function ref
local callback = timer.callback
if type(callback) == "string" then
safecall(timer.object[callback], timer.object, timer.arg)
elseif callback then
safecall(callback, timer.arg)
else
-- probably nilled out by CancelTimer
timer.delay = nil -- don't reschedule it
end
local delay = timer.delay -- NOW make a local copy, can't do it earlier in case the timer cancelled itself in the callback
if not delay then
-- single-shot timer (or cancelled)
AceTimer.selfs[timer.object][tostring(timer)] = nil
timerCache = timer
else
-- repeating timer
local newtime = when + delay
if newtime < now then -- Keep lag from making us firing a timer unnecessarily. (Note that this still won't catch too-short-delay timers though.)
newtime = now + delay
end
timer.when = newtime
-- add next timer execution to the correct bucket
local bucket = (floor(newtime * HZ) % BUCKETS) + 1
timer.next = hash[bucket]
hash[bucket] = timer
end
else -- if when>=soon
-- reinsert (yeah, somewhat expensive, but shouldn't be happening too often either due to hash distribution)
timer.next = hash[curbucket]
hash[curbucket] = timer
end -- if when<soon ... else
end -- while nexttimer do
end -- for curint=lastint,nowint
lastint = nowint
end
-- ---------------------------------------------------------------------
-- Reg( callback, delay, arg, repeating )
--
-- callback( function or string ) - direct function ref or method name in our object for the callback
-- delay(int) - delay for the timer
-- arg(variant) - any argument to be passed to the callback function
-- repeating(boolean) - repeating timer, or oneshot
--
-- returns the handle of the timer for later processing (canceling etc)
local function Reg(self, callback, delay, arg, repeating)
if type(callback) ~= "string" and type(callback) ~= "function" then
local error_origin = repeating and "ScheduleRepeatingTimer" or "ScheduleTimer"
error(MAJOR..": " .. error_origin .. "(callback, delay, arg): 'callback' - function or method name expected.", 3)
end
if type(callback) == "string" then
if type(self)~="table" then
local error_origin = repeating and "ScheduleRepeatingTimer" or "ScheduleTimer"
error(MAJOR..": " .. error_origin .. "(\"methodName\", delay, arg): 'self' - must be a table.", 3)
end
if type(self[callback]) ~= "function" then
local error_origin = repeating and "ScheduleRepeatingTimer" or "ScheduleTimer"
error(MAJOR..": " .. error_origin .. "(\"methodName\", delay, arg): 'methodName' - method not found on target object.", 3)
end end
end end
if delay < (1 / (HZ - 1)) then C_TimerAfter(delay, timer.callback)
delay = 1 / (HZ - 1) return timer
end
-- Create and stuff timer in the correct hash bucket
local now = GetTime()
local timer = timerCache or {} -- Get new timer object (from cache if available)
timerCache = nil
timer.object = self
timer.callback = callback
timer.delay = (repeating and delay)
timer.arg = arg
timer.when = now + delay
local bucket = (floor((now+delay)*HZ) % BUCKETS) + 1
timer.next = hash[bucket]
hash[bucket] = timer
-- Insert timer in our self->handle->timer registry
local handle = tostring(timer)
local selftimers = AceTimer.selfs[self]
if not selftimers then
selftimers = {}
AceTimer.selfs[self] = selftimers
end
selftimers[handle] = timer
selftimers.__ops = (selftimers.__ops or 0) + 1
return handle
end end
--- Schedule a new one-shot timer. --- Schedule a new one-shot timer.
-- The timer will fire once in `delay` seconds, unless canceled before. -- The timer will fire once in `delay` seconds, unless canceled before.
-- @param callback Callback function for the timer pulse (funcref or method name). -- @param func Callback function for the timer pulse (funcref or method name).
-- @param delay Delay for the timer, in seconds. -- @param delay Delay for the timer, in seconds.
-- @param arg An optional argument to be passed to the callback function. -- @param ... An optional, unlimited amount of arguments to pass to the callback function.
-- @usage -- @usage
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("TimerTest", "AceTimer-3.0") -- MyAddOn = LibStub("AceAddon-3.0"):NewAddon("MyAddOn", "AceTimer-3.0")
-- --
-- function MyAddon:OnEnable() -- function MyAddOn:OnEnable()
-- self:ScheduleTimer("TimerFeedback", 5) -- self:ScheduleTimer("TimerFeedback", 5)
-- end -- end
-- --
-- function MyAddon:TimerFeedback() -- function MyAddOn:TimerFeedback()
-- print("5 seconds passed") -- print("5 seconds passed")
-- end -- end
function AceTimer:ScheduleTimer(callback, delay, arg) function AceTimer:ScheduleTimer(func, delay, ...)
return Reg(self, callback, delay, arg) if not func or not delay then
error(MAJOR..": ScheduleTimer(callback, delay, args...): 'callback' and 'delay' must have set values.", 2)
end
if type(func) == "string" then
if type(self) ~= "table" then
error(MAJOR..": ScheduleTimer(callback, delay, args...): 'self' - must be a table.", 2)
elseif not self[func] then
error(MAJOR..": ScheduleTimer(callback, delay, args...): Tried to register '"..func.."' as the callback, but it doesn't exist in the module.", 2)
end
end
return new(self, nil, func, delay, ...)
end end
--- Schedule a repeating timer. --- Schedule a repeating timer.
-- The timer will fire every `delay` seconds, until canceled. -- The timer will fire every `delay` seconds, until canceled.
-- @param callback Callback function for the timer pulse (funcref or method name). -- @param func Callback function for the timer pulse (funcref or method name).
-- @param delay Delay for the timer, in seconds. -- @param delay Delay for the timer, in seconds.
-- @param arg An optional argument to be passed to the callback function. -- @param ... An optional, unlimited amount of arguments to pass to the callback function.
-- @usage -- @usage
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("TimerTest", "AceTimer-3.0") -- MyAddOn = LibStub("AceAddon-3.0"):NewAddon("MyAddOn", "AceTimer-3.0")
-- --
-- function MyAddon:OnEnable() -- function MyAddOn:OnEnable()
-- self.timerCount = 0 -- self.timerCount = 0
-- self.testTimer = self:ScheduleRepeatingTimer("TimerFeedback", 5) -- self.testTimer = self:ScheduleRepeatingTimer("TimerFeedback", 5)
-- end -- end
-- --
-- function MyAddon:TimerFeedback() -- function MyAddOn:TimerFeedback()
-- self.timerCount = self.timerCount + 1 -- self.timerCount = self.timerCount + 1
-- print(("%d seconds passed"):format(5 * self.timerCount)) -- print(("%d seconds passed"):format(5 * self.timerCount))
-- -- run 30 seconds in total -- -- run 30 seconds in total
@@ -298,129 +126,124 @@ end
-- self:CancelTimer(self.testTimer) -- self:CancelTimer(self.testTimer)
-- end -- end
-- end -- end
function AceTimer:ScheduleRepeatingTimer(callback, delay, arg) function AceTimer:ScheduleRepeatingTimer(func, delay, ...)
return Reg(self, callback, delay, arg, true) if not func or not delay then
error(MAJOR..": ScheduleRepeatingTimer(callback, delay, args...): 'callback' and 'delay' must have set values.", 2)
end
if type(func) == "string" then
if type(self) ~= "table" then
error(MAJOR..": ScheduleRepeatingTimer(callback, delay, args...): 'self' - must be a table.", 2)
elseif not self[func] then
error(MAJOR..": ScheduleRepeatingTimer(callback, delay, args...): Tried to register '"..func.."' as the callback, but it doesn't exist in the module.", 2)
end
end
return new(self, true, func, delay, ...)
end end
--- Cancels a timer with the given handle, registered by the same addon object as used for `:ScheduleTimer` --- Cancels a timer with the given id, registered by the same addon object as used for `:ScheduleTimer`
-- Both one-shot and repeating timers can be canceled with this function, as long as the `handle` is valid -- Both one-shot and repeating timers can be canceled with this function, as long as the `id` is valid
-- and the timer has not fired yet or was canceled before. -- and the timer has not fired yet or was canceled before.
-- @param handle The handle of the timer, as returned by `:ScheduleTimer` or `:ScheduleRepeatingTimer` -- @param id The id of the timer, as returned by `:ScheduleTimer` or `:ScheduleRepeatingTimer`
-- @param silent If true, no error is raised if the timer handle is invalid (expired or already canceled) function AceTimer:CancelTimer(id)
-- @return True if the timer was successfully cancelled. local timer = activeTimers[id]
function AceTimer:CancelTimer(handle, silent)
if not handle then return end -- nil handle -> bail out without erroring if not timer then
if type(handle) ~= "string" then return false
error(MAJOR..": CancelTimer(handle): 'handle' - expected a string", 2) -- for now, anyway
end
local selftimers = AceTimer.selfs[self]
local timer = selftimers and selftimers[handle]
if silent then
if timer then
timer.callback = nil -- don't run it again
timer.delay = nil -- if this is the currently-executing one: don't even reschedule
-- The timer object is removed in the OnUpdate loop
end
return not not timer -- might return "true" even if we double-cancel. we'll live.
else else
if not timer then timer.cancelled = true
geterrorhandler()(MAJOR..": CancelTimer(handle[, silent]): '"..tostring(handle).."' - no such timer registered") activeTimers[id] = nil
return false
end
if not timer.callback then
geterrorhandler()(MAJOR..": CancelTimer(handle[, silent]): '"..tostring(handle).."' - timer already cancelled or expired")
return false
end
timer.callback = nil -- don't run it again
timer.delay = nil -- if this is the currently-executing one: don't even reschedule
return true return true
end end
end end
--- Cancels all timers registered to the current addon object ('self') --- Cancels all timers registered to the current addon object ('self')
function AceTimer:CancelAllTimers() function AceTimer:CancelAllTimers()
if not(type(self) == "string" or type(self) == "table") then for k,v in next, activeTimers do
error(MAJOR..": CancelAllTimers(): 'self' - must be a string or a table",2) if v.object == self then
end AceTimer.CancelTimer(self, k)
if self == AceTimer then
error(MAJOR..": CancelAllTimers(): supply a meaningful 'self'", 2)
end
local selftimers = AceTimer.selfs[self]
if selftimers then
for handle,v in pairs(selftimers) do
if type(v) == "table" then -- avoid __ops, etc
AceTimer.CancelTimer(self, handle, true)
end
end end
end end
end end
--- Returns the time left for a timer with the given handle, registered by the current addon object ('self'). --- Returns the time left for a timer with the given id, registered by the current addon object ('self').
-- This function will raise a warning when the handle is invalid, but not stop execution. -- This function will return 0 when the id is invalid.
-- @param handle The handle of the timer, as returned by `:ScheduleTimer` or `:ScheduleRepeatingTimer` -- @param id The id of the timer, as returned by `:ScheduleTimer` or `:ScheduleRepeatingTimer`
-- @return The time left on the timer, or false if the handle is invalid. -- @return The time left on the timer.
function AceTimer:TimeLeft(handle) function AceTimer:TimeLeft(id)
if not handle then return end local timer = activeTimers[id]
if type(handle) ~= "string" then
error(MAJOR..": TimeLeft(handle): 'handle' - expected a string", 2) -- for now, anyway
end
local selftimers = AceTimer.selfs[self]
local timer = selftimers and selftimers[handle]
if not timer then if not timer then
geterrorhandler()(MAJOR..": TimeLeft(handle): '"..tostring(handle).."' - no such timer registered") return 0
return false else
return timer.ends - GetTime()
end end
return timer.when - GetTime()
end end
-- --------------------------------------------------------------------- -- ---------------------------------------------------------------------
-- PLAYER_REGEN_ENABLED: Run through our .selfs[] array step by step -- Upgrading
-- and clean it out - otherwise the table indices can grow indefinitely
-- if an addon starts and stops a lot of timers. AceBucket does this!
--
-- See ACE-94 and tests/AceTimer-3.0-ACE-94.lua
local lastCleaned = nil -- Upgrade from old hash-bucket based timers to C_Timer.After timers.
if oldminor and oldminor < 10 then
local function OnEvent(this, event) -- disable old timer logic
if event~="PLAYER_REGEN_ENABLED" then AceTimer.frame:SetScript("OnUpdate", nil)
return AceTimer.frame:SetScript("OnEvent", nil)
AceTimer.frame:UnregisterAllEvents()
-- convert timers
for object,timers in next, AceTimer.selfs do
for handle,timer in next, timers do
if type(timer) == "table" and timer.callback then
local newTimer
if timer.delay then
newTimer = AceTimer.ScheduleRepeatingTimer(timer.object, timer.callback, timer.delay, timer.arg)
else
newTimer = AceTimer.ScheduleTimer(timer.object, timer.callback, timer.when - GetTime(), timer.arg)
end
-- Use the old handle for old timers
activeTimers[newTimer] = nil
activeTimers[handle] = newTimer
newTimer.handle = handle
end
end
end
AceTimer.selfs = nil
AceTimer.hash = nil
AceTimer.debug = nil
elseif oldminor and oldminor < 17 then
-- Upgrade from old animation based timers to C_Timer.After timers.
AceTimer.inactiveTimers = nil
AceTimer.frame = nil
local oldTimers = AceTimer.activeTimers
-- Clear old timer table and update upvalue
AceTimer.activeTimers = {}
activeTimers = AceTimer.activeTimers
for handle, timer in next, oldTimers do
local newTimer
-- Stop the old timer animation
local duration, elapsed = timer:GetDuration(), timer:GetElapsed()
timer:GetParent():Stop()
if timer.looping then
newTimer = AceTimer.ScheduleRepeatingTimer(timer.object, timer.func, duration, unpack(timer.args, 1, timer.argsCount))
else
newTimer = AceTimer.ScheduleTimer(timer.object, timer.func, duration - elapsed, unpack(timer.args, 1, timer.argsCount))
end
-- Use the old handle for old timers
activeTimers[newTimer] = nil
activeTimers[handle] = newTimer
newTimer.handle = handle
end end
-- Get the next 'self' to process -- Migrate transitional handles
local selfs = AceTimer.selfs if oldminor < 13 and AceTimer.hashCompatTable then
local self = next(selfs, lastCleaned) for handle, id in next, AceTimer.hashCompatTable do
if not self then local t = activeTimers[id]
self = next(selfs) if t then
activeTimers[id] = nil
activeTimers[handle] = t
t.handle = handle
end
end
AceTimer.hashCompatTable = nil
end end
lastCleaned = self
if not self then -- should only happen if .selfs[] is empty
return
end
-- Time to clean it out?
local list = selfs[self]
if (list.__ops or 0) < 250 then -- 250 slosh indices = ~10KB wasted (max!). For one 'self'.
return
end
-- Create a new table and copy all members over
local newlist = {}
local n=0
for k,v in pairs(list) do
newlist[k] = v
n=n+1
end
newlist.__ops = 0 -- Reset operation count
-- And since we now have a count of the number of live timers, check that it's reasonable. Emit a warning if not.
if n>BUCKETS then
DEFAULT_CHAT_FRAME:AddMessage(MAJOR..": Warning: The addon/module '"..tostring(self).."' has "..n.." live timers. Surely that's not intended?")
end
selfs[self] = newlist
end end
-- --------------------------------------------------------------------- -- ---------------------------------------------------------------------
@@ -436,38 +259,20 @@ local mixins = {
function AceTimer:Embed(target) function AceTimer:Embed(target)
AceTimer.embeds[target] = true AceTimer.embeds[target] = true
for _,v in pairs(mixins) do for _,v in next, mixins do
target[v] = AceTimer[v] target[v] = AceTimer[v]
end end
return target return target
end end
-- AceTimer:OnEmbedDisable( target ) -- AceTimer:OnEmbedDisable(target)
-- target (object) - target object that AceTimer is embedded in. -- target (object) - target object that AceTimer is embedded in.
-- --
-- cancel all timers registered for the object -- cancel all timers registered for the object
function AceTimer:OnEmbedDisable( target ) function AceTimer:OnEmbedDisable(target)
target:CancelAllTimers() target:CancelAllTimers()
end end
for addon in next, AceTimer.embeds do
for addon in pairs(AceTimer.embeds) do
AceTimer:Embed(addon) AceTimer:Embed(addon)
end end
-- ---------------------------------------------------------------------
-- Debug tools (expose copies of internals to test suites)
AceTimer.debug = AceTimer.debug or {}
AceTimer.debug.HZ = HZ
AceTimer.debug.BUCKETS = BUCKETS
-- ---------------------------------------------------------------------
-- Finishing touchups
AceTimer.frame:SetScript("OnUpdate", OnUpdate)
AceTimer.frame:SetScript("OnEvent", OnEvent)
AceTimer.frame:RegisterEvent("PLAYER_REGEN_ENABLED")
-- In theory, we should hide&show the frame based on there being timers or not.
-- However, this job is fairly expensive, and the chance that there will
-- actually be zero timers running is diminuitive to say the lest.
@@ -1,61 +1,26 @@
--[[ $Id: CallbackHandler-1.0.lua 3 2008-09-29 16:54:20Z nevcairiel $ ]] --[[ $Id: CallbackHandler-1.0.lua 25 2022-12-12 15:02:36Z nevcairiel $ ]]
local MAJOR, MINOR = "CallbackHandler-1.0", 3 local MAJOR, MINOR = "CallbackHandler-1.0", 8
local CallbackHandler = LibStub:NewLibrary(MAJOR, MINOR) local CallbackHandler = LibStub:NewLibrary(MAJOR, MINOR)
if not CallbackHandler then return end -- No upgrade needed if not CallbackHandler then return end -- No upgrade needed
local meta = {__index = function(tbl, key) tbl[key] = {} return tbl[key] end} local meta = {__index = function(tbl, key) tbl[key] = {} return tbl[key] end}
local type = type -- Lua APIs
local pcall = pcall local securecallfunction, error = securecallfunction, error
local pairs = pairs local setmetatable, rawget = setmetatable, rawget
local assert = assert local next, select, pairs, type, tostring = next, select, pairs, type, tostring
local concat = table.concat
local loadstring = loadstring
local next = next
local select = select
local type = type
local xpcall = xpcall
local function errorhandler(err)
return geterrorhandler()(err) local function Dispatch(handlers, ...)
local index, method = next(handlers)
if not method then return end
repeat
securecallfunction(method, ...)
index, method = next(handlers, index)
until not method
end end
local function CreateDispatcher(argCount)
local code = [[
local next, xpcall, eh = ...
local method, ARGS
local function call() method(ARGS) end
local function dispatch(handlers, ...)
local index
index, method = next(handlers)
if not method then return end
local OLD_ARGS = ARGS
ARGS = ...
repeat
xpcall(call, eh)
index, method = next(handlers, index)
until not method
ARGS = OLD_ARGS
end
return dispatch
]]
local ARGS, OLD_ARGS = {}, {}
for i = 1, argCount do ARGS[i], OLD_ARGS[i] = "arg"..i, "old_arg"..i end
code = code:gsub("OLD_ARGS", concat(OLD_ARGS, ", ")):gsub("ARGS", concat(ARGS, ", "))
return assert(loadstring(code, "safecall Dispatcher["..argCount.."]"))(next, xpcall, errorhandler)
end
local Dispatchers = setmetatable({}, {__index=function(self, argCount)
local dispatcher = CreateDispatcher(argCount)
rawset(self, argCount, dispatcher)
return dispatcher
end})
-------------------------------------------------------------------------- --------------------------------------------------------------------------
-- CallbackHandler:New -- CallbackHandler:New
-- --
@@ -64,9 +29,7 @@ end})
-- UnregisterName - name of the callback unregistration API, default "UnregisterCallback" -- UnregisterName - name of the callback unregistration API, default "UnregisterCallback"
-- UnregisterAllName - name of the API to unregister all callbacks, default "UnregisterAllCallbacks". false == don't publish this API. -- UnregisterAllName - name of the API to unregister all callbacks, default "UnregisterAllCallbacks". false == don't publish this API.
function CallbackHandler:New(target, RegisterName, UnregisterName, UnregisterAllName, OnUsed, OnUnused) function CallbackHandler.New(_self, target, RegisterName, UnregisterName, UnregisterAllName)
-- TODO: Remove this after beta has gone out
assert(not OnUsed and not OnUnused, "ACE-80: OnUsed/OnUnused are deprecated. Callbacks are now done to registry.OnUsed and registry.OnUnused")
RegisterName = RegisterName or "RegisterCallback" RegisterName = RegisterName or "RegisterCallback"
UnregisterName = UnregisterName or "UnregisterCallback" UnregisterName = UnregisterName or "UnregisterCallback"
@@ -88,19 +51,19 @@ function CallbackHandler:New(target, RegisterName, UnregisterName, UnregisterAll
local oldrecurse = registry.recurse local oldrecurse = registry.recurse
registry.recurse = oldrecurse + 1 registry.recurse = oldrecurse + 1
Dispatchers[select('#', ...) + 1](events[eventname], eventname, ...) Dispatch(events[eventname], eventname, ...)
registry.recurse = oldrecurse registry.recurse = oldrecurse
if registry.insertQueue and oldrecurse==0 then if registry.insertQueue and oldrecurse==0 then
-- Something in one of our callbacks wanted to register more callbacks; they got queued -- Something in one of our callbacks wanted to register more callbacks; they got queued
for eventname,callbacks in pairs(registry.insertQueue) do for event,callbacks in pairs(registry.insertQueue) do
local first = not rawget(events, eventname) or not next(events[eventname]) -- test for empty before. not test for one member after. that one member may have been overwritten. local first = not rawget(events, event) or not next(events[event]) -- test for empty before. not test for one member after. that one member may have been overwritten.
for self,func in pairs(callbacks) do for object,func in pairs(callbacks) do
events[eventname][self] = func events[event][object] = func
-- fire OnUsed callback? -- fire OnUsed callback?
if first and registry.OnUsed then if first and registry.OnUsed then
registry.OnUsed(registry, target, eventname) registry.OnUsed(registry, target, event)
first = nil first = nil
end end
end end
@@ -146,9 +109,9 @@ function CallbackHandler:New(target, RegisterName, UnregisterName, UnregisterAll
regfunc = function(...) self[method](self,...) end regfunc = function(...) self[method](self,...) end
end end
else else
-- function ref with self=object or self="addonId" -- function ref with self=object or self="addonId" or self=thread
if type(self)~="table" and type(self)~="string" then if type(self)~="table" and type(self)~="string" and type(self)~="thread" then
error("Usage: "..RegisterName.."(self or \"addonId\", eventname, method): 'self or addonId': table or string expected.", 2) error("Usage: "..RegisterName.."(self or \"addonId\", eventname, method): 'self or addonId': table or string or thread expected.", 2)
end end
if select("#",...)>=1 then -- this is not the same as testing for arg==nil! if select("#",...)>=1 then -- this is not the same as testing for arg==nil!
@@ -2,7 +2,7 @@
assert(LibStub, "LibDataBroker-1.1 requires LibStub") assert(LibStub, "LibDataBroker-1.1 requires LibStub")
assert(LibStub:GetLibrary("CallbackHandler-1.0", true), "LibDataBroker-1.1 requires CallbackHandler-1.0") assert(LibStub:GetLibrary("CallbackHandler-1.0", true), "LibDataBroker-1.1 requires CallbackHandler-1.0")
local lib, oldminor = LibStub:NewLibrary("LibDataBroker-1.1", 3) local lib, oldminor = LibStub:NewLibrary("LibDataBroker-1.1", 4)
if not lib then return end if not lib then return end
oldminor = oldminor or 0 oldminor = oldminor or 0
@@ -64,3 +64,27 @@ if oldminor < 1 then
return self.namestorage[dataobject] return self.namestorage[dataobject]
end end
end end
if oldminor < 4 then
local next = pairs(attributestorage)
function lib:pairs(dataobject_or_name)
local t = type(dataobject_or_name)
assert(t == "string" or t == "table", "Usage: ldb:pairs('dataobjectname') or ldb:pairs(dataobject)")
local dataobj = self.proxystorage[dataobject_or_name] or dataobject_or_name
assert(attributestorage[dataobj], "Data object not found")
return next, attributestorage[dataobj], nil
end
local ipairs_iter = ipairs(attributestorage)
function lib:ipairs(dataobject_or_name)
local t = type(dataobject_or_name)
assert(t == "string" or t == "table", "Usage: ldb:ipairs('dataobjectname') or ldb:ipairs(dataobject)")
local dataobj = self.proxystorage[dataobject_or_name] or dataobject_or_name
assert(attributestorage[dataobj], "Data object not found")
return ipairs_iter, attributestorage[dataobj], 0
end
end
@@ -0,0 +1,13 @@
LibDataBroker is a small WoW addon library designed to provide a "MVC":http://en.wikipedia.org/wiki/Model-view-controller interface for use in various addons.
LDB's primary goal is to "detach" plugins for TitanPanel and FuBar from the display addon.
Plugins can provide data into a simple table, and display addons can receive callbacks to refresh their display of this data.
LDB also provides a place for addons to register "quicklaunch" functions, removing the need for authors to embed many large libraries to create minimap buttons.
Users who do not wish to be "plagued" by these buttons simply do not install an addon to render them.
Due to it's simple generic design, LDB can be used for any design where you wish to have an addon notified of changes to a table.
h2. Links
* "API documentation":http://github.com/tekkub/libdatabroker-1-1/wikis/api
* "Data specifications":http://github.com/tekkub/libdatabroker-1-1/wikis/data-specifications
* "Addons using LDB":http://github.com/tekkub/libdatabroker-1-1/wikis/addons-using-ldb
+1 -1
View File
@@ -10,7 +10,7 @@ if not LibStub or LibStub.minor < LIBSTUB_MINOR then
function LibStub:NewLibrary(major, minor) function LibStub:NewLibrary(major, minor)
assert(type(major) == "string", "Bad argument #2 to `NewLibrary' (string expected)") assert(type(major) == "string", "Bad argument #2 to `NewLibrary' (string expected)")
minor = assert(tonumber(strmatch(minor, "%d+")), "Minor version must either be a number or contain a number.") minor = assert(tonumber(string.match(minor, "%d+")), "Minor version must either be a number or contain a number.")
local oldminor = self.minors[major] local oldminor = self.minors[major]
if oldminor and oldminor >= minor then return nil end if oldminor and oldminor >= minor then return nil end
-13
View File
@@ -1,13 +0,0 @@
## Interface: 20400
## Title: Lib: LibStub
## Notes: Universal Library Stub
## Credits: Kaelten, Cladhaire, ckknight, Mikk, Ammo, Nevcairiel
## X-Website: http://jira.wowace.com/browse/LS
## X-Category: Library
## X-License: Public Domain
## X-Curse-Packaged-Version: 1.0
## X-Curse-Project-Name: LibStub
## X-Curse-Project-ID: libstub
## X-Curse-Repository-ID: wow/libstub/mainline
LibStub.lua
+13 -10
View File
@@ -197,12 +197,13 @@ local profList = {
3274, -- Journeyman 150 3274, -- Journeyman 150
3273, -- Apprentice 75 3273, -- Apprentice 75
}, --FIRSTAID }, --FIRSTAID
{13977860}, --WOODCUTTING {13977860, Name = "Woodcutting"}, --WOODCUTTING
{ {
1005011, -- Artisan 300 1005011, -- Artisan 300
1005010, -- Expert 225 1005010, -- Expert 225
1005009, -- Journeyman 150 1005009, -- Journeyman 150
1005008, -- Apprentice 75 1005008, -- Apprentice 75
Name = "Woodworking",
}, --WOODWORKING }, --WOODWORKING
} }
@@ -372,7 +373,7 @@ function PM:AddProfessions()
local function getProfessionRanks(compName) local function getProfessionRanks(compName)
for skillIndex = 1, GetNumSkillLines() do for skillIndex = 1, GetNumSkillLines() do
local name, _, _, rank, _, _, maxRank, _, _, _, _, _, _ = GetSkillLineInfo(skillIndex) local name, _, _, rank, _, _, maxRank, _, _, _, _, _, _ = GetSkillLineInfo(skillIndex)
if compName:match(name) then if compName == name then
return rank, maxRank return rank, maxRank
end end
end end
@@ -391,13 +392,13 @@ function PM:AddProfessions()
end end
local rank, maxRank = getProfessionRanks(profName) local rank, maxRank = getProfessionRanks(profName)
if not self.db.hideRank and self.db.hideMaxRank then if not self.db.hideRank and self.db.hideMaxRank then
name = name .. " |cFF00FFFF("..rank..")" if rank then name = name .. " |cFF00FFFF("..rank..")" end
end end
if not self.db.hideMaxRank and self.db.hideRank then if not self.db.hideMaxRank and self.db.hideRank then
name = name .. " |cFF00FFFF("..maxRank..")" if maxRank then name = name .. " |cFF00FFFF("..maxRank..")" end
end end
if not self.db.hideMaxRank and not self.db.hideRank then if not self.db.hideMaxRank and not self.db.hideRank then
name = name .. " |cFF00FFFF("..rank.."/"..maxRank..")" if rank and maxRank then name = name .. " |cFF00FFFF("..rank.."/"..maxRank..")" end
end end
local secure = { local secure = {
type1 = 'spell', type1 = 'spell',
@@ -604,11 +605,13 @@ function PM:CreateUI()
end end
PM:CreateUI() PM:CreateUI()
InterfaceOptionsFrame:HookScript("OnShow", function() if InterfaceOptionsFrame then
if InterfaceOptionsFrame and ProfessionMenuOptionsFrame:IsVisible() then InterfaceOptionsFrame:HookScript("OnShow", function()
ProfessionMenu_OpenOptions() if InterfaceOptionsFrame and ProfessionMenuOptionsFrame:IsVisible() then
end ProfessionMenu_OpenOptions()
end) end
end)
end
-- toggle the main button frame -- toggle the main button frame
function PM:ToggleMainFrame() function PM:ToggleMainFrame()
+10 -6
View File
@@ -1,15 +1,18 @@
local PM = LibStub("AceAddon-3.0"):GetAddon("ProfessionMenu") local PM = LibStub("AceAddon-3.0"):GetAddon("ProfessionMenu")
function PM:Options_Toggle() function PM:Options_Toggle()
if not InterfaceOptionsFrame then return end
if InterfaceOptionsFrame:IsVisible() then if InterfaceOptionsFrame:IsVisible() then
InterfaceOptionsFrame:Hide() InterfaceOptionsFrame:Hide()
else else
InterfaceOptionsFrame_OpenToCategory("ProfessionMenu") if InterfaceOptionsFrame_OpenToCategory then
InterfaceOptionsFrame_OpenToCategory("ProfessionMenu")
end
end end
end end
function ProfessionMenu_OpenOptions() function ProfessionMenu_OpenOptions()
if InterfaceOptionsFrame:GetWidth() < 850 then InterfaceOptionsFrame:SetWidth(850) end if InterfaceOptionsFrame and InterfaceOptionsFrame:GetWidth() < 850 then InterfaceOptionsFrame:SetWidth(850) end
ProfessionMenu_DropDownInitialize() ProfessionMenu_DropDownInitialize()
UIDropDownMenu_SetText(ProfessionMenuOptions_TxtSizeMenu, PM.db.txtSize) UIDropDownMenu_SetText(ProfessionMenuOptions_TxtSizeMenu, PM.db.txtSize)
end end
@@ -17,14 +20,16 @@ end
--Creates the options frame and all its assets --Creates the options frame and all its assets
function PM:CreateOptionsUI() function PM:CreateOptionsUI()
if InterfaceOptionsFrame:GetWidth() < 850 then InterfaceOptionsFrame:SetWidth(850) end if InterfaceOptionsFrame and InterfaceOptionsFrame:GetWidth() < 850 then InterfaceOptionsFrame:SetWidth(850) end
local mainframe = {} local mainframe = {}
mainframe.panel = CreateFrame("FRAME", "ProfessionMenuOptionsFrame", UIParent, nil) mainframe.panel = CreateFrame("FRAME", "ProfessionMenuOptionsFrame", UIParent, nil)
local fstring = mainframe.panel:CreateFontString(mainframe, "OVERLAY", "GameFontNormal") local fstring = mainframe.panel:CreateFontString(mainframe, "OVERLAY", "GameFontNormal")
fstring:SetText("Profession Menu Settings") fstring:SetText("Profession Menu Settings")
fstring:SetPoint("TOPLEFT", 15, -15) fstring:SetPoint("TOPLEFT", 15, -15)
mainframe.panel.name = "ProfessionMenu" mainframe.panel.name = "ProfessionMenu"
InterfaceOptions_AddCategory(mainframe.panel) if InterfaceOptions_AddCategory then
InterfaceOptions_AddCategory(mainframe.panel)
end
local hideMenu = CreateFrame("CheckButton", "ProfessionMenuOptions_HideMenu", ProfessionMenuOptionsFrame, "UICheckButtonTemplate") local hideMenu = CreateFrame("CheckButton", "ProfessionMenuOptions_HideMenu", ProfessionMenuOptionsFrame, "UICheckButtonTemplate")
hideMenu:SetPoint("TOPLEFT", 15, -60) hideMenu:SetPoint("TOPLEFT", 15, -60)
@@ -145,8 +150,7 @@ PM:CreateOptionsUI()
text = i; text = i;
func = function() func = function()
PM.db.txtSize = i PM.db.txtSize = i
local thisID = this:GetID(); UIDropDownMenu_SetSelectedID(ProfessionMenuOptions_TxtSizeMenu, i - 9)
UIDropDownMenu_SetSelectedID(ProfessionMenuOptions_TxtSizeMenu, thisID)
end; end;
}; };
UIDropDownMenu_AddButton(info); UIDropDownMenu_AddButton(info);
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env bash
# Build per-addon zip artefacts from HEAD via git-archive.
#
# - Discovers top-level addon folders (Foo/Foo.toc).
# - Re-creates dist/ each run.
# - Always archives HEAD, so the working tree state is irrelevant.
# - If more than one addon folder is present, also emits <repo>-all.zip
# with every addon folder side-by-side at the zip root.
# - When run inside Gitea Actions the working tree lives under a
# per-job dir like /var/lib/act_runner/work/.../hostexecutor, so the
# repo name comes from $GITHUB_REPOSITORY (set by the runner) and
# only falls back to the toplevel basename for local invocations.
set -euo pipefail
root=$(git rev-parse --show-toplevel)
cd "$root"
# Gitea Actions sets GITHUB_REPOSITORY=owner/repo. The basename of
# `git rev-parse --show-toplevel` inside the runner is the worker dir
# (e.g. `hostexecutor`), which would name the bundle wrong.
if [ -n "${GITHUB_REPOSITORY:-}" ]; then
repo_name="${GITHUB_REPOSITORY##*/}"
else
repo_name=$(basename "$root")
fi
dist="$root/dist"
# Find Foo/Foo.toc pairs at depth 1; ignore libs nested deeper.
addons=()
while IFS= read -r toc; do
dir=$(dirname "$toc")
folder=$(basename "$dir")
base=$(basename "$toc" .toc)
# Accept Foo.toc and Foo_Wrath.toc style flavour variants; folder must match
# at least one toc basename prefix (Foo).
case "$base" in
"$folder"|"$folder"_*) addons+=("$folder") ;;
esac
done < <(command find . -mindepth 2 -maxdepth 2 -type f -name '*.toc' | sed 's|^\./||' | sort)
# Dedupe (a folder with Foo.toc + Foo_Wrath.toc shows up twice).
if [ ${#addons[@]} -gt 0 ]; then
mapfile -t addons < <(printf '%s\n' "${addons[@]}" | awk '!seen[$0]++')
fi
if [ ${#addons[@]} -eq 0 ]; then
echo "no addon folders found (looking for */Foo.toc with matching folder name)" >&2
exit 1
fi
rm -rf "$dist"
mkdir -p "$dist"
for folder in "${addons[@]}"; do
out="$dist/$folder.zip"
# No --prefix: the folder already sits at the repo root, so git-archive
# emits entries as <folder>/... which is exactly what
# Interface/AddOns/ expects after extraction.
git archive HEAD --format=zip -o "$out" -- "$folder"
echo "built dist/$folder.zip"
done
# Combined bundle only makes sense when there are multiple addons.
if [ ${#addons[@]} -gt 1 ]; then
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
git archive HEAD --format=tar -- "${addons[@]}" | tar -x -C "$tmp"
out="$dist/$repo_name-all.zip"
( cd "$tmp" && zip -qr "$out" "${addons[@]}" )
echo "built dist/$repo_name-all.zip"
fi