diff --git a/src/embed/AddOns/!!!ClassicAPI/!!!ClassicAPI.toc b/src/embed/AddOns/!!!ClassicAPI/!!!ClassicAPI.toc index 117d3dd7..76a52699 100644 --- a/src/embed/AddOns/!!!ClassicAPI/!!!ClassicAPI.toc +++ b/src/embed/AddOns/!!!ClassicAPI/!!!ClassicAPI.toc @@ -22,13 +22,18 @@ Util\SoundKitConstants.lua Util\TableUtil.lua Util\EnumUtil.lua Util\StringUtil.lua +Util\TypeUtil.lua Util\MathUtil.lua +Util\SortUtil.lua +Util\Spline.lua Util\PixelUtil.lua Util\FrameUtil.lua Util\InputUtil.lua Util\FormattingUtil.lua Util\TimeUtil.lua Util\Flags.lua +Util\TaggableObject.lua +Util\ExportUtil.lua Util\ButtonStateBehavior.lua Util\CallbackRegistry.lua Util\GlobalCallbackRegistry.lua @@ -46,10 +51,14 @@ Util\ContinuableContainer.lua Util\AsyncCallbackSystem.lua Util\Item.lua Util\Spell.lua +Util\ObjectCache.lua +Util\SpellBookItemLocation.lua Util\ItemUtil.lua Util\ContainerFrame.lua Util\AddOnCompat.lua Util\FunctionUtil.lua +Util\MixinUtil.lua +Util\ObjectUpdater.lua Util\CacheUtil.lua Util\SecureTypes.lua Util\ProxyUtil.lua @@ -60,6 +69,9 @@ Util\TimedCallback.lua Util\EasingUtil.lua Util\ScriptAnimationUtil.lua Util\Interpolator.lua +Util\Sequencer.lua +Util\SmoothStatusBar.lua +Util\AnimationSystem.lua Util\AnchorUtil.lua Util\RegionUtil.lua Util\GridLayoutUtil.lua diff --git a/src/embed/AddOns/!!!ClassicAPI/Util/AnimationSystem.lua b/src/embed/AddOns/!!!ClassicAPI/Util/AnimationSystem.lua new file mode 100644 index 00000000..3e411b1e --- /dev/null +++ b/src/embed/AddOns/!!!ClassicAPI/Util/AnimationSystem.lua @@ -0,0 +1,76 @@ +-- Backport of retail's Blizzard_FrameXMLUtil/AnimationSystem.lua. + +--[[ animTable = { --Note that only consistent data should be in here. These tables are meant to be shared across "sessions" of animations. Put changing data in the frame. + totalTime = number, --Time to complete the animation in seconds. + updateFunc = function, --The function called to do the actual change. Takes self, elapsed fraction. Usually frame.SetPoint, frame.SetAlpha, ect. + getPosFunc = function, --The function returning the data being passed into updateFunc. For example. might return .18 if updateFunc is frame.SetAlpha. +--]] +local AnimatingFrames = {}; + +local AnimUpdateFrame = CreateFrame("Frame"); + +local function Animation_UpdateFrame(self, animElapsed, animTable) + local totalTime = animTable.totalTime + if ( animElapsed and (animElapsed < totalTime)) then --Should be animating + local elapsedFraction = self.animReverse and (1-animElapsed/totalTime) or (animElapsed/totalTime); + animTable.updateFunc(self, animTable.getPosFunc(self, elapsedFraction)); + else --Just finished animating + animTable.updateFunc(self, animTable.getPosFunc(self, self.animReverse and 0 or 1)); + self.animating = false; + + AnimatingFrames[self][animTable.updateFunc] = 0; --We use 0 instead of nil'ing out because we don't want to mess with 'next' (used in pairs) + + if ( self.animPostFunc ) then + self.animPostFunc(self); + end + + end +end + +local totalElapsed = 0; +local function Animation_OnUpdate(self, elapsed) + totalElapsed = totalElapsed + elapsed; + local isAnyFrameAnimating = false; + for frame, frameTable in pairs(AnimatingFrames) do + for _, animTable in pairs(frameTable) do + if ( animTable ~= 0 ) then + Animation_UpdateFrame(frame, totalElapsed - frame.animStartTime, animTable); + isAnyFrameAnimating = true; + end + end + end + if ( not isAnyFrameAnimating ) then + table.wipe(AnimatingFrames); + AnimUpdateFrame:SetScript("OnUpdate", nil); + end +end + +function SetUpAnimation(frame, animTable, postFunc, reverse) + if ( type(animTable.updateFunc) == "string" ) then + animTable.updateFunc = frame[animTable.updateFunc]; + end + if ( not AnimatingFrames[frame] ) then + AnimatingFrames[frame] = {}; + end + + AnimatingFrames[frame][animTable.updateFunc] = animTable; + + frame.animStartTime = totalElapsed; + frame.animReverse = reverse; + frame.animPostFunc = postFunc; + frame.animating = true; + + animTable.updateFunc(frame, animTable.getPosFunc(frame, frame.animReverse and 1 or 0)); + + AnimUpdateFrame:SetScript("OnUpdate", Animation_OnUpdate); +end + +function CancelAnimations(frame) + local anims = AnimatingFrames[frame]; + if ( anims ) then + for k, v in pairs(anims) do + anims[k] = 0; + end + frame.animating = false; + end +end diff --git a/src/embed/AddOns/!!!ClassicAPI/Util/ExportUtil.lua b/src/embed/AddOns/!!!ClassicAPI/Util/ExportUtil.lua new file mode 100644 index 00000000..559be8fa --- /dev/null +++ b/src/embed/AddOns/!!!ClassicAPI/Util/ExportUtil.lua @@ -0,0 +1,149 @@ +-- Backport of retail's Blizzard_SharedXMLBase/ExportUtil.lua. + +-- Utility for compressing and uncompressing data into strings for export and import. + +ExportUtil = {}; + +local BitsPerChar = 6; + +local function MakeBase64ConversionTable() + local base64ConversionTable = {}; + base64ConversionTable[0] = 'A'; + for num = 1, 25 do + table.insert(base64ConversionTable, string.char(65 + num)); + end + + for num = 0, 25 do + table.insert(base64ConversionTable, string.char(97 + num)); + end + + for num = 0, 9 do + table.insert(base64ConversionTable, tostring(num)); + end + + table.insert(base64ConversionTable, '+'); + table.insert(base64ConversionTable, '/'); + return base64ConversionTable; +end + +local NumberToBase64CharConversionTable = MakeBase64ConversionTable(); +local Base64CharToNumberConversionTable = tInvert(MakeBase64ConversionTable()); + +function ExportUtil.ConvertToBase64(dataEntries) + local exportString = ""; + local currentValue = 0; + local currentReservedBits = 0; + local totalBits = 0; + for i, dataEntry in ipairs(dataEntries) do + local remainingValue = dataEntry.value; + local remainingRequiredBits = dataEntry.bitWidth; + -- TODO: bit.lshift doesnt work with > 32 bits. Maybe use maxValue = 2^X instead? + local maxValue = bit.lshift(1, remainingRequiredBits); + if remainingValue >= maxValue then + error(("Data entry has higher value than storable in bitWidth. (%d in %d bits)"):format(remainingValue, remainingRequiredBits)); + return ""; + end + + totalBits = totalBits + remainingRequiredBits; + while remainingRequiredBits > 0 do + local spaceInCurrentValue = (BitsPerChar - currentReservedBits); + local maxStorableValue = bit.lshift(1, spaceInCurrentValue); + local remainder = remainingValue % maxStorableValue; + remainingValue = bit.rshift(remainingValue, spaceInCurrentValue); + currentValue = currentValue + bit.lshift(remainder, currentReservedBits); + + if spaceInCurrentValue > remainingRequiredBits then + currentReservedBits = (currentReservedBits + remainingRequiredBits) % BitsPerChar; + remainingRequiredBits = 0; + else + exportString = exportString..NumberToBase64CharConversionTable[currentValue]; + currentValue = 0; + currentReservedBits = 0; + remainingRequiredBits = remainingRequiredBits - spaceInCurrentValue; + end + end + end + + if currentReservedBits > 0 then + exportString = exportString..NumberToBase64CharConversionTable[currentValue]; + end + + return exportString; +end + +function ExportUtil.ConvertFromBase64(exportString) + local dataValues = {}; + for i = 1, #exportString do + table.insert(dataValues, Base64CharToNumberConversionTable[string.sub(exportString, i, i)]); + end + + return dataValues; +end + +function ExportUtil.MakeExportDataStream() + return CreateAndInitFromMixin(ExportDataStreamMixin); +end + +function ExportUtil.MakeImportDataStream(exportString) + return CreateAndInitFromMixin(ImportDataStreamMixin, exportString); +end + + +ExportDataStreamMixin = {}; + +function ExportDataStreamMixin:Init() + self.dataEntries = {}; +end + +function ExportDataStreamMixin:AddValue(bitWidth, value) + table.insert(self.dataEntries, { bitWidth = bitWidth, value = value, }); +end + +function ExportDataStreamMixin:GetExportString() + return ExportUtil.ConvertToBase64(self.dataEntries); +end + +ImportDataStreamMixin = {}; + +function ImportDataStreamMixin:Init(exportString) + self.dataValues = ExportUtil.ConvertFromBase64(exportString); + self.currentIndex = 1; + self.currentExtractedBits = 0; + self.currentRemainingValue = self.dataValues[1]; +end + +function ImportDataStreamMixin:ExtractValue(bitWidth) + if self.currentIndex > #self.dataValues then + return nil; + end + + local value = 0; + local bitsNeeded = bitWidth; + local extractedBits = 0; + while bitsNeeded > 0 do + local remainingBits = BitsPerChar - self.currentExtractedBits; + local bitsToExtract = math.min(remainingBits, bitsNeeded); + self.currentExtractedBits = self.currentExtractedBits + bitsToExtract; + local maxStorableValue = bit.lshift(1, bitsToExtract); + local remainder = self.currentRemainingValue % maxStorableValue; + self.currentRemainingValue = bit.rshift(self.currentRemainingValue, bitsToExtract); + value = value + bit.lshift(remainder, extractedBits); + extractedBits = extractedBits + bitsToExtract; + bitsNeeded = bitsNeeded - bitsToExtract; + + if bitsToExtract < remainingBits then + break; + elseif bitsToExtract >= remainingBits then + self.currentIndex = self.currentIndex + 1; + self.currentExtractedBits = 0; + self.currentRemainingValue = self.dataValues[self.currentIndex]; + end + end + + return value; +end + +function ImportDataStreamMixin:GetNumberOfBits() + return BitsPerChar * getn(self.dataValues); +end + diff --git a/src/embed/AddOns/!!!ClassicAPI/Util/MathUtil.lua b/src/embed/AddOns/!!!ClassicAPI/Util/MathUtil.lua index 8cef791b..3654e277 100644 --- a/src/embed/AddOns/!!!ClassicAPI/Util/MathUtil.lua +++ b/src/embed/AddOns/!!!ClassicAPI/Util/MathUtil.lua @@ -78,8 +78,8 @@ function DeltaLerp(startValue, endValue, amount, timeSec) return Lerp(startValue, endValue, Saturate(amount * timeSec * TARGET_FRAME_PER_SEC)) end -function FrameDeltaLerp(startValue, endValue, amount, elapsed) - return DeltaLerp(startValue, endValue, amount, elapsed) +function FrameDeltaLerp(startValue, endValue, amount) + return DeltaLerp(startValue, endValue, amount, GetTickTime()) end function RandomFloatInRange(minValue, maxValue) diff --git a/src/embed/AddOns/!!!ClassicAPI/Util/MixinUtil.lua b/src/embed/AddOns/!!!ClassicAPI/Util/MixinUtil.lua new file mode 100644 index 00000000..8b070351 --- /dev/null +++ b/src/embed/AddOns/!!!ClassicAPI/Util/MixinUtil.lua @@ -0,0 +1,465 @@ +-- Backport of retail's Blizzard_SharedXML/MixinUtil.lua. +-- +-- Implementation differences from the retail source: +-- - wipe is table.wipe here. + +local wipe = table.wipe; + +-- The following function is used with permission from Daniel Stephens +-- texture - Texture +-- canvasFrame - Canvas Frame (for anchoring) +-- startX,startY - Coordinate of start of line +-- endX,endY - Coordinate of end of line +-- lineWidth - Width of line +-- relPoint - Relative point on canvas to interpret coords (Default BOTTOMLEFT) +function DrawLine(texture, canvasFrame, startX, startY, endX, endY, lineWidth, lineFactor, relPoint) + if (not relPoint) then relPoint = "BOTTOMLEFT"; end + lineFactor = lineFactor * .5; + + -- Determine dimensions and center point of line + local dx,dy = endX - startX, endY - startY; + local cx,cy = (startX + endX) / 2, (startY + endY) / 2; + + -- Normalize direction if necessary + if (dx < 0) then + dx,dy = -dx,-dy; + end + + -- Calculate actual length of line + local lineLength = sqrt((dx * dx) + (dy * dy)); + + -- Quick escape if it'sin zero length + if (lineLength == 0) then + texture:SetTexCoord(0,0,0,0,0,0,0,0); + texture:SetPoint("BOTTOMLEFT", canvasFrame, relPoint, cx,cy); + texture:SetPoint("TOPRIGHT", canvasFrame, relPoint, cx,cy); + return; + end + + -- Sin and Cosine of rotation, and combination (for later) + local sin, cos = -dy / lineLength, dx / lineLength; + local sinCos = sin * cos; + + -- Calculate bounding box size and texture coordinates + local boundingWidth, boundingHeight, bottomLeftX, bottomLeftY, topLeftX, topLeftY, topRightX, topRightY, bottomRightX, bottomRightY; + if (dy >= 0) then + boundingWidth = ((lineLength * cos) - (lineWidth * sin)) * lineFactor; + boundingHeight = ((lineWidth * cos) - (lineLength * sin)) * lineFactor; + + bottomLeftX = (lineWidth / lineLength) * sinCos; + bottomLeftY = sin * sin; + bottomRightY = (lineLength / lineWidth) * sinCos; + bottomRightX = 1 - bottomLeftY; + + topLeftX = bottomLeftY; + topLeftY = 1 - bottomRightY; + topRightX = 1 - bottomLeftX; + topRightY = bottomRightX; + else + boundingWidth = ((lineLength * cos) + (lineWidth * sin)) * lineFactor; + boundingHeight = ((lineWidth * cos) + (lineLength * sin)) * lineFactor; + + bottomLeftX = sin * sin; + bottomLeftY = -(lineLength / lineWidth) * sinCos; + bottomRightX = 1 + (lineWidth / lineLength) * sinCos; + bottomRightY = bottomLeftX; + + topLeftX = 1 - bottomRightX; + topLeftY = 1 - bottomLeftX; + topRightY = 1 - bottomLeftY; + topRightX = topLeftY; + end + + -- Set texture coordinates and anchors + texture:ClearAllPoints(); + texture:SetTexCoord(topLeftX, topLeftY, bottomLeftX, bottomLeftY, topRightX, topRightY, bottomRightX, bottomRightY); + texture:SetPoint("BOTTOMLEFT", canvasFrame, relPoint, cx - boundingWidth, cy - boundingHeight); + texture:SetPoint("TOPRIGHT", canvasFrame, relPoint, cx + boundingWidth, cy + boundingHeight); +end + +-- Mix this into a Texture to be able to treat it like a line +LineMixin = {}; + +function LineMixin:SetStartPoint(x, y) + self.startX, self.startY = x, y; +end + +function LineMixin:SetEndPoint(x, y) + self.endX, self.endY = x, y; +end + +function LineMixin:SetThickness(thickness) + self.thickness = thickness; +end + +function LineMixin:Draw() + local parent = self:GetParent(); + local x, y = parent:GetLeft(), parent:GetBottom(); + + self:ClearAllPoints(); + DrawLine(self, parent, self.startX - x, self.startY - y, self.endX - x, self.endY - y, self.thickness or 32, 1); +end + +-- Mix this into a FontString to have it animate towards its value, call UpdateAnimatedValue every frame +AnimatedNumericFontStringMixin = {}; + +-- How long should it take to animate +function AnimatedNumericFontStringMixin:SetAnimatedDurationTimeSec(animatedDurationTimeSec) + self.animatedDurationTimeSec = animatedDurationTimeSec; +end + +function AnimatedNumericFontStringMixin:GetAnimatedDurationTimeSec() + return self.animatedDurationTimeSec or 1.0; +end + +function AnimatedNumericFontStringMixin:SetAnimatedValue(value) + self.targetAnimatedValue = value; + if not self.currentAnimatedValue then + self.currentAnimatedValue = self.targetAnimatedValue; + end + self.initialAnimatedValueDelta = math.abs(self.targetAnimatedValue - self.currentAnimatedValue); +end + +-- Stops animating the value and just snaps to it +function AnimatedNumericFontStringMixin:SnapToTarget() + if self.targetAnimatedValue then + self:SetText(BreakUpLargeNumbers(Round(self.targetAnimatedValue))); + self.currentAnimatedValue = self.targetAnimatedValue; + self.targetAnimatedValue = nil; + end +end + +-- Call this every frame +function AnimatedNumericFontStringMixin:UpdateAnimatedValue(elapsed) + if self.targetAnimatedValue then + local change = self.initialAnimatedValueDelta * (elapsed / self:GetAnimatedDurationTimeSec()); + if math.abs(self.targetAnimatedValue - self.currentAnimatedValue) <= change then + self:SnapToTarget(); + else + local direction = self.targetAnimatedValue > self.currentAnimatedValue and 1 or -1; + self.currentAnimatedValue = self.currentAnimatedValue + direction * change; + + self:SetText(BreakUpLargeNumbers(Round(self.currentAnimatedValue))); + end + end +end + +SparseGridMixin = {}; + +function SparseGridMixin:OnLoad(width, height) + self.width = width; + self.height = height; + self.cells = {}; +end + +function SparseGridMixin:SetCell(x, y, data) + if not self:IsInRange(x, y) then + error("index of out of range"); + end + + local linearIndex = self:CalculateLinearIndex(x, y); + self.cells[linearIndex] = data; +end + +function SparseGridMixin:GetCell(x, y) + if not self:IsInRange(x, y) then + error("index of out of range"); + end + + local linearIndex = self:CalculateLinearIndex(x, y); + return self.cells[linearIndex]; +end + +function SparseGridMixin:IsInRange(x, y) + return x > 0 and x <= self.width and y > 0 and y <= self.height; +end + +function SparseGridMixin:Clear() + wipe(self.cells); +end + +function SparseGridMixin:CalculateLinearIndex(x, y) + return x + self.width * (y - 1); +end + +-- Mix this in to make an object a doublyLinkedList +DoublyLinkedListMixin = {nodeCount = 0}; + +function DoublyLinkedListMixin:PushFront(nodeToInsert) + self:InsertBefore(nodeToInsert, self.front); +end + +function DoublyLinkedListMixin:PushBack(nodeToInsert) + self:InsertAfter(nodeToInsert, self.back); +end + +function DoublyLinkedListMixin:PopFront() + return self:Remove(self.front); +end + +function DoublyLinkedListMixin:PopBack() + return self:Remove(self.back); +end + +function DoublyLinkedListMixin:EnumerateNodes() + local index = 0; + local currentNode = self.front; + + return function() + index = index + 1; + if currentNode then + local returnNode = currentNode; + currentNode = currentNode.next; + return index, returnNode; + else + return nil; + end + end; +end + +function DoublyLinkedListMixin:EnumerateNodesReverse() + local index = 0; + local currentNode = self.back; + + return function() + index = index + 1; + if currentNode then + local returnNode = currentNode; + currentNode = currentNode.prev; + return index, returnNode; + else + return nil; + end + end; +end + +function DoublyLinkedListMixin:InsertBefore(nodeToInsert, listNode) + nodeToInsert.next = listNode; + + if listNode then + if listNode.prev then + listNode.prev.next = nodeToInsert; + end + + nodeToInsert.prev = listNode.prev; + listNode.prev = nodeToInsert; + end + + if self.front == listNode then + self.front = nodeToInsert; + end + + if not self.back then + self.back = nodeToInsert; + end + + self.nodeCount = self.nodeCount + 1; +end + +function DoublyLinkedListMixin:InsertAfter(nodeToInsert, listNode) + nodeToInsert.prev = listNode; + + if listNode then + if listNode.next then + listNode.next.prev = nodeToInsert; + end + + nodeToInsert.next = listNode.next; + listNode.next = nodeToInsert; + end + + if self.back == listNode then + self.back = nodeToInsert; + end + + if not self.front then + self.front = nodeToInsert; + end + + self.nodeCount = self.nodeCount + 1; +end + +function DoublyLinkedListMixin:Remove(node) + if node then + if self.front == node then + self.front = node.next; + end + + if self.back == node then + self.back = node.prev; + end + + if node.prev then + node.prev.next = node.next; + end + + if node.next then + node.next.prev = node.prev; + end + + node.prev = nil; + node.next = nil; + + self.nodeCount = self.nodeCount - 1; + end + + return node; +end + +TextureLoadingGroupMixin = {}; + +function TextureLoadingGroupMixin:AddTexture(texture) + self.textures = self.textures or {}; + self.textures[texture] = true; +end + +function TextureLoadingGroupMixin:RemoveTexture(texture) + if self.textures then + self.textures[texture] = nil; + end +end + +function TextureLoadingGroupMixin:Reset() + self.textures = nil; +end + +function TextureLoadingGroupMixin:EnumerateTextures() + if self.textures then + return pairs(self.textures); + end + return nop; +end + +function TextureLoadingGroupMixin:IsFullyLoaded() + if self.textures then + for texture in pairs(self.textures) do + if not texture:IsObjectLoaded() then + return false; + end + end + end + return true; +end + +DirtiableMixin = {}; + +function DirtiableMixin:SetDirtyMethod(method) + self.dirtyCallback = function() + method(self); + self.dirty = nil; + end; +end + +function DirtiableMixin:MarkDirty() + if not self.dirty then + RunNextFrame(self.dirtyCallback); + end + + self.dirty = true; +end + +-- This mixin implements a small ordered dirty-update runner. Consumers +-- define their own dirty flags and phase order. Phase methods return any +-- downstream flags that should be processed later in the same pass. +DirtyPhaseMixin = {}; + +function DirtyPhaseMixin:InitDirtyPhases() + self.dirty = false; + self.dirtyFlags = CreateFlags(); + self.dirtyPhases = {}; +end + +function DirtyPhaseMixin:OnDirtyChanged(_dirty) + -- Override in the consumer to schedule or cancel dirty processing. +end + +function DirtyPhaseMixin:SetDirtyPhases(phases) + assert(type(phases) == "table", "phases must be a table."); + + for _index, phase in ipairs(phases) do + assert(phase.flag ~= nil, "phase.flag must be provided."); + assert(type(phase.handler) == "function", "phase.handler must be a function."); + end + + self.dirtyPhases = phases; +end + +function DirtyPhaseMixin:IsDirty(mask) + if mask == nil then + return self.dirty; + end + + return self.dirtyFlags:IsSet(mask); +end + +function DirtyPhaseMixin:UpdateDirtyState() + local dirty = self.dirtyFlags:IsAnySet(); + + if self.dirty ~= dirty then + self.dirty = dirty; + self:OnDirtyChanged(dirty); + end +end + +function DirtyPhaseMixin:MarkDirty(mask) + self.dirtyFlags:Set(mask); + + if not self.dirty then + self:UpdateDirtyState(); + end +end + +function DirtyPhaseMixin:MarkClean(mask) + self.dirtyFlags:Clear(mask); + + if self.dirty then + self:UpdateDirtyState(); + end +end + +function DirtyPhaseMixin:ProcessDirtyFlags() + if not self:IsDirty() then + return; + end + + -- Dirty processing is single-pass; phases should only return later phases. + for _index, phase in ipairs(self.dirtyPhases) do + if self.dirtyFlags:IsSet(phase.flag) then + self.dirtyFlags:Clear(phase.flag); + + local downstreamMask = phase.handler(); + if downstreamMask ~= nil then + self.dirtyFlags:Set(downstreamMask); + end + end + end + + self:UpdateDirtyState(); + + if self:IsDirty() then + assertsafe(false, "Dirty flags were not fully cleared during update pass (remaining flags: %d)", self.dirtyFlags:GetFlags()); + end +end + +MixinUtil = {}; + +-- Calls an owned function on each entry of a table of mixin instances, checking that the instance does define that function +function MixinUtil.CallMethodOnAllSafe(instances, methodName, ...) + if not instances then + return; + end + + for _, instance in ipairs(instances) do + if instance[methodName] then + instance[methodName](instance, ...); + end + end +end + +-- Check existence of an element, then invoke the provided method by name with its arguments if it exists. +-- e.g. frame.Text:SetText("text") -> CallMethodSafe(frame.Text, "SetText", "text"); +function MixinUtil.CallMethodSafe(element, methodName, ...) + if element then + element[methodName](element, ...); + end +end diff --git a/src/embed/AddOns/!!!ClassicAPI/Util/ObjectCache.lua b/src/embed/AddOns/!!!ClassicAPI/Util/ObjectCache.lua new file mode 100644 index 00000000..0f1c9803 --- /dev/null +++ b/src/embed/AddOns/!!!ClassicAPI/Util/ObjectCache.lua @@ -0,0 +1,22 @@ +-- Backport of retail's Blizzard_ObjectAPI/Mainline/ObjectCache.lua. + +function ObjectCache_Create(mixin) + return { + objects = {}, + + Get = function(self, key) + local object = self.objects[key]; + if object then + if object.CheckRefresh then + object:CheckRefresh(); + end + return object; + end + + object = CreateFromMixins(mixin); + object:Init(key); + self.objects[key] = object; + return object; + end, + } +end diff --git a/src/embed/AddOns/!!!ClassicAPI/Util/ObjectUpdater.lua b/src/embed/AddOns/!!!ClassicAPI/Util/ObjectUpdater.lua new file mode 100644 index 00000000..8a5f40ae --- /dev/null +++ b/src/embed/AddOns/!!!ClassicAPI/Util/ObjectUpdater.lua @@ -0,0 +1,59 @@ +-- Backport of retail's Blizzard_SharedXMLBase/ObjectUpdater.lua. + +local States = EnumUtil.MakeEnum("Ready", "Begin", "Update", "End"); + +local ObjectUpdaterMixin = {}; +function ObjectUpdaterMixin:Init(data, updateFunc, isCompleteFunc, finishFunc) + self.data = data; + self:SetUpdateFunction(updateFunc); + self:SetIsCompleteFunction(isCompleteFunc); + self:SetFinishFunction(finishFunc); + self.state = States.Begin; + self.ticker = C_Timer.NewTicker(0.01, GenerateClosure(self.Advance, self)); +end + +function ObjectUpdaterMixin:SetUpdateFunction(updateFunc) + self.updateFunc = updateFunc; +end + +function ObjectUpdaterMixin:SetIsCompleteFunction(isCompleteFunc) + self.isCompleteFunc = isCompleteFunc; +end + +function ObjectUpdaterMixin:SetFinishFunction(finishFunc) + self.finishFunc = finishFunc; +end + +function ObjectUpdaterMixin:Cancel() + self.ticker:Cancel(); + self.state = States.Ready; +end + +function ObjectUpdaterMixin:Finished() + self:Cancel(); + if self.finishFunc then + self.finishFunc(self.data); + end +end + +function ObjectUpdaterMixin:Advance() + if self.state == States.Begin then + if self.isCompleteFunc(self.data) then + self.state = States.End; + else + self.state = States.Update; + end + elseif self.state == States.Update then + self.updateFunc(self.data); + if self.isCompleteFunc(self.data) then + self.state = States.End; + end + elseif self.state == States.End then + self:Finished(); + return; + end +end + +function CreateObjectUpdater(data, updateFunc, isCompleteFunc, finishFunc) + return CreateAndInitFromMixin(ObjectUpdaterMixin, data, updateFunc, isCompleteFunc, finishFunc); +end diff --git a/src/embed/AddOns/!!!ClassicAPI/Util/Sequencer.lua b/src/embed/AddOns/!!!ClassicAPI/Util/Sequencer.lua new file mode 100644 index 00000000..9eba5b65 --- /dev/null +++ b/src/embed/AddOns/!!!ClassicAPI/Util/Sequencer.lua @@ -0,0 +1,50 @@ +-- Backport of retail's Blizzard_SharedXML/Sequencer.lua. + +SequencerMixin = {}; + +function SequencerMixin:Init() + self.original = {}; + self.onFinish = GenerateClosure(self.ExecuteNext, self); +end + +function SequencerMixin:AddInterpolated(v1, v2, time, interpType, func) + local interpolation = {v1 = v1, v2 = v2, time = time, interpType = interpType}; + table.insert(self.original, 1, {interpolation = interpolation, func = func}); +end + +function SequencerMixin:Add(func) + table.insert(self.original, 1, {func = func}); +end + +function SequencerMixin:ExecuteNext() + local sequence = table.remove(self.sequences); + if sequence then + local interpolation = sequence.interpolation; + if interpolation then + self.interpolator = CreateInterpolator(sequence.interpType); + self.interpolator:Interpolate(interpolation.v1, interpolation.v2, interpolation.time, sequence.func, self.onFinish); + else + sequence.func(); + self:ExecuteNext(); + end + end +end + +function SequencerMixin:Cancel() + if self.interpolator then + self.interpolator:Cancel(); + end + self.sequences = {}; +end + +function SequencerMixin:Play() + local shallow = true; + self.sequences = CopyTable(self.original, shallow); + self:ExecuteNext(); +end + +function CreateSequencer() + local sequencer = CreateFromMixins(SequencerMixin); + sequencer:Init(); + return sequencer; +end diff --git a/src/embed/AddOns/!!!ClassicAPI/Util/SmoothStatusBar.lua b/src/embed/AddOns/!!!ClassicAPI/Util/SmoothStatusBar.lua new file mode 100644 index 00000000..c56dd898 --- /dev/null +++ b/src/embed/AddOns/!!!ClassicAPI/Util/SmoothStatusBar.lua @@ -0,0 +1,62 @@ +-- Backport of retail's Blizzard_SharedXML/SmoothStatusBar.lua. + +local g_updatingBars = {}; + +local function IsCloseEnough(bar, newValue, targetValue) + local min, max = bar:GetMinMaxValues(); + local range = max - min; + if range > 0.0 then + return math.abs((newValue - targetValue) / range) < .00001; + end + + return true; +end + +local function ProcessSmoothStatusBars() + for bar, targetValue in pairs(g_updatingBars) do + local effectiveTargetValue = Clamp(targetValue, bar:GetMinMaxValues()); + local newValue = FrameDeltaLerp(bar:GetValue(), effectiveTargetValue, .25); + + if IsCloseEnough(bar, newValue, effectiveTargetValue) then + g_updatingBars[bar] = nil; + bar:SetValue(effectiveTargetValue); + else + bar:SetValue(newValue); + end + end +end + +C_Timer.NewTicker(0, ProcessSmoothStatusBars); + +SmoothStatusBarMixin = {}; + +function SmoothStatusBarMixin:ResetSmoothedValue(value) --If nil, tries to set to the last target value + local targetValue = g_updatingBars[self]; + if targetValue then + g_updatingBars[self] = nil; + self:SetValue(value or targetValue); + elseif value then + self:SetValue(value); + end +end + +function SmoothStatusBarMixin:SetSmoothedValue(value) + g_updatingBars[self] = value; +end + +function SmoothStatusBarMixin:SetMinMaxSmoothedValue(min, max) + self:SetMinMaxValues(min, max); + + local targetValue = g_updatingBars[self]; + if targetValue then + local ratio = 1; + if max ~= 0 and self.lastSmoothedMax and self.lastSmoothedMax ~= 0 then + ratio = max / self.lastSmoothedMax; + end + + g_updatingBars[self] = targetValue * ratio; + end + + self.lastSmoothedMin = min; + self.lastSmoothedMax = max; +end diff --git a/src/embed/AddOns/!!!ClassicAPI/Util/SortUtil.lua b/src/embed/AddOns/!!!ClassicAPI/Util/SortUtil.lua new file mode 100644 index 00000000..c1db2667 --- /dev/null +++ b/src/embed/AddOns/!!!ClassicAPI/Util/SortUtil.lua @@ -0,0 +1,92 @@ +-- Backport of retail's Blizzard_SharedXML/SortUtil.lua. + +SortUtil = {}; + +function SortUtil.CompareNumeric(lhs, rhs) + return Sign(lhs - rhs); +end + +function SortUtil.CompareUtf8i(lhs, rhs) + return Sign(strcmputf8i(lhs, rhs)); +end + +local SortManagerMixin = {}; + +function SortManagerMixin:Init() + self.comparatorsTbls = {}; +end + +function SortManagerMixin:InsertComparator(sortOrder, comparator) + assert(sortOrder, comparator); + table.insert(self.comparatorsTbls, {sortOrder = sortOrder, comparator = comparator, ascending = false}); +end + +function SortManagerMixin:SetDefaultComparator(defaultComparatorFunc) + self.defaultComparatorFunc = defaultComparatorFunc; +end + +function SortManagerMixin:SetSortOrderFunc(sortOrderFunc) + self.sortOrderFunc = sortOrderFunc; +end + +function SortManagerMixin:FindComparatorTbl(sortOrder) + return FindValueInTableIf(self.comparatorsTbls, function(comparatorsTbl) + return comparatorsTbl.sortOrder == sortOrder; + end); +end + +function SortManagerMixin:ToggleSortAscending(sortOrder) + local comparatorTbl = self:FindComparatorTbl(sortOrder); + comparatorTbl.ascending = not comparatorTbl.ascending; +end + +function SortManagerMixin:SetSortAscending(sortOrder, ascending) + local comparatorTbl = self:FindComparatorTbl(sortOrder); + comparatorTbl.ascending = ascending; +end + +function SortManagerMixin:IsSortAscending(sortOrder) + local comparatorTbl = self:FindComparatorTbl(sortOrder); + return comparatorTbl.ascending; +end + +function SortManagerMixin:CreateComparator() + return function(lhs, rhs) + local comparatorsTbls = self.comparatorsTbls; + + local result = 0; + local sortOrder = self.sortOrderFunc(); + if sortOrder then + local comparatorTbl = self:FindComparatorTbl(sortOrder); + if comparatorTbl then + result = NegateIf(comparatorTbl.comparator(lhs, rhs), comparatorTbl.ascending); + end + end + + if result == 0 then + for _, comparatorTbl in ipairs(comparatorsTbls) do + if comparatorTbl.sortOrder ~= sortOrder then + result = NegateIf(comparatorTbl.comparator(lhs, rhs), comparatorTbl.ascending); + if result < 0 then + return true; + elseif result > 0 then + return false; + end + end + end + + if not self.defaultComparatorFunc then + error("Provide a default comparator that guarantees strict ordering."); + end + return self.defaultComparatorFunc(lhs, rhs); + end + + return result < 0; + end; +end + +function SortUtil.CreateSortManager() + local sortManager = CreateFromMixins(SortManagerMixin); + sortManager:Init(); + return sortManager; +end diff --git a/src/embed/AddOns/!!!ClassicAPI/Util/SpellBookItemLocation.lua b/src/embed/AddOns/!!!ClassicAPI/Util/SpellBookItemLocation.lua new file mode 100644 index 00000000..0cd61e9b --- /dev/null +++ b/src/embed/AddOns/!!!ClassicAPI/Util/SpellBookItemLocation.lua @@ -0,0 +1,46 @@ +-- Backport of retail's Blizzard_ObjectAPI/Mainline/SpellBookItemLocation.lua. + +SpellBookItemLocation = {}; +SpellBookItemLocationMixin = {}; + +--[[static]] function SpellBookItemLocation:CreateEmpty() + local spelLBookItemLocation = CreateFromMixins(SpellBookItemLocationMixin); + return spelLBookItemLocation; +end + +-- slotIndex: int +-- spellBank: Enum.SpellBookSpellBank (see SpellBookConstantsDocumentation.lua) +--[[static]] function SpellBookItemLocation:CreateFromIndexAndBank(slotIndex, spellBank) + local spellBookItemLocation = SpellBookItemLocation:CreateEmpty(); + spellBookItemLocation:SetIndexAndBank(slotIndex, spellBank); + return spellBookItemLocation; +end + +function SpellBookItemLocationMixin:Clear() + self.slotIndex = nil; + self.spellBank = nil; +end + +function SpellBookItemLocationMixin:SetIndexAndBank(slotIndex, spellBank) + self:Clear(); + self.slotIndex = slotIndex; + self.spellBank = spellBank; +end + +function SpellBookItemLocationMixin:GetIndexAndBank() + return self.slotIndex, self.spellBank; +end + +function SpellBookItemLocationMixin:IsEqualToIndexAndBank(otherSlotIndex, otherSpellBank) + local slotIndex, spellBank = self:GetIndexAndBank(); + return slotIndex == otherSlotIndex and spellBank == otherSpellBank; +end + +function SpellBookItemLocationMixin:IsEqualTo(otherSpellBookItemLocation) + if not otherSpellBookItemLocation then + return false; + end + + local otherSlotIndex, otherSpellBank = otherSpellBookItemLocation:GetIndexAndBank(); + return self:IsEqualToIndexAndBank(otherSlotIndex, otherSpellBank); +end diff --git a/src/embed/AddOns/!!!ClassicAPI/Util/Spline.lua b/src/embed/AddOns/!!!ClassicAPI/Util/Spline.lua new file mode 100644 index 00000000..0b7c0c40 --- /dev/null +++ b/src/embed/AddOns/!!!ClassicAPI/Util/Spline.lua @@ -0,0 +1,133 @@ +-- Backport of retail's Blizzard_SharedXML/Spline.lua. + +local function CatmullRom_CalculatePointOnCurveHelper(t, tSquared, tCubed, p1, p2, p3, p4) + local term1 = 2.0 * p2 + (p3 - p1) * t; + local term2 = (2.0 * p1 - 5.0 * p2 + 4.0 * p3 - p4) * tSquared; + local term3 = (3.0 * p2 - p1 - 3.0 * p3 + p4) * tCubed; + + return 0.5 * (term1 + term2 + term3); +end + +function CatmullRom_CalculatePointOnCurve(t, p1, p2, p3, p4) + local tSquared = t * t; + local tCubed = tSquared * t; + return CatmullRom_CalculatePointOnCurveHelper(t, tSquared, tCubed, p1, p2, p3, p4); +end + +function CatmullRom_Calculate2DPointOnCurve(t, p1x, p1y, p2x, p2y, p3x, p3y, p4x, p4y) + local tSquared = t * t; + local tCubed = tSquared * t; + return + CatmullRom_CalculatePointOnCurveHelper(t, tSquared, tCubed, p1x, p2x, p3x, p4x), + CatmullRom_CalculatePointOnCurveHelper(t, tSquared, tCubed, p1y, p2y, p3y, p4y); +end + +function CatmullRom_Calculate3DPointOnCurve(t, p1x, p1y, p1z, p2x, p2y, p2z, p3x, p3y, p3z, p4x, p4y, p4z) + local tSquared = t * t; + local tCubed = tSquared * t; + return + CatmullRom_CalculatePointOnCurveHelper(t, tSquared, tCubed, p1x, p2x, p3x, p4x), + CatmullRom_CalculatePointOnCurveHelper(t, tSquared, tCubed, p1y, p2y, p3y, p4y), + CatmullRom_CalculatePointOnCurveHelper(t, tSquared, tCubed, p1z, p2z, p3z, p4z); +end + +function CatmullRom_Calculate4DPointOnCurve(t, p1x, p1y, p1z, p1w, p2x, p2y, p2z, p2w, p3x, p3y, p3z, p3w, p4x, p4y, p4z, p4w) + local tSquared = t * t; + local tCubed = tSquared * t; + return + CatmullRom_CalculatePointOnCurveHelper(t, tSquared, tCubed, p1x, p2x, p3x, p4x), + CatmullRom_CalculatePointOnCurveHelper(t, tSquared, tCubed, p1y, p2y, p3y, p4y), + CatmullRom_CalculatePointOnCurveHelper(t, tSquared, tCubed, p1z, p2z, p3z, p4z), + CatmullRom_CalculatePointOnCurveHelper(t, tSquared, tCubed, p1w, p2w, p3w, p4w); +end + +CatmullRomSplineMixin = {}; + +function CreateCatmullRomSpline(numDimensions) + local spline = CreateFromMixins(CatmullRomSplineMixin); + spline:OnLoad(numDimensions) + return spline; +end + +function CatmullRomSplineMixin:OnLoad(numDimensions) + if numDimensions == 1 then + self.calculateFunction = CatmullRom_CalculatePointOnCurve; + elseif numDimensions == 2 then + self.calculateFunction = CatmullRom_Calculate2DPointOnCurve; + elseif numDimensions == 3 then + self.calculateFunction = CatmullRom_Calculate3DPointOnCurve; + elseif numDimensions == 4 then + self.calculateFunction = CatmullRom_Calculate4DPointOnCurve; + else + -- In the interest of performance, limiting number of dimensions + error("Unsupported number of dimensions"); + end + + self.numDimensions = numDimensions; + self:ClearPoints(); +end + +function CatmullRomSplineMixin:GetNumDimensions() + return self.numDimensions; +end + +local function AddPointHelper(pointData, startIndex, ...) + local pointIndex = 1; + for i = startIndex, startIndex + select("#", ...) do + pointData[i] = select(pointIndex, ...); + pointIndex = pointIndex + 1; + end +end + +function CatmullRomSplineMixin:AddPoint(...) + assert(select("#", ...) == self.numDimensions); + + if #self.pointData == 0 then + -- If first point, put it in the list three times times to simplify the curve calculation, at this time the curve represents a single point + AddPointHelper(self.pointData, 1, ...); + AddPointHelper(self.pointData, 1 + self.numDimensions, ...); + AddPointHelper(self.pointData, 1 + self.numDimensions * 2, ...); + else + -- For each other point, add it to the end twice but replacing the last one that was added twice + AddPointHelper(self.pointData, #self.pointData - self.numDimensions + 1, ...); + AddPointHelper(self.pointData, #self.pointData + 1, ...); + end + + self.numPoints = self.numPoints + 1; +end + +function CatmullRomSplineMixin:GetPoint(pointIndex) + if pointIndex > 0 and pointIndex <= self:GetNumPoints() then + return unpack(self.pointData, (pointIndex + 1) * self.numDimensions + 1, (pointIndex + 2) * self.numDimensions); + end +end + +function CatmullRomSplineMixin:GetNumPoints() + return self.numPoints; +end + +function CatmullRomSplineMixin:ClearPoints() + self.numPoints = 0; + self.pointData = {}; +end + +function CatmullRomSplineMixin:CalculatePointOnGlobalCurve(t) + local startSegmentIndex, localT = self:FindSegmentOnGlobalCurve(t); + if startSegmentIndex then + return self:CalculatePointOnLocalCurveSegment(startSegmentIndex, localT); + end +end + +function CatmullRomSplineMixin:CalculatePointOnLocalCurveSegment(startSegmentIndex, t) + return self.calculateFunction(t, unpack(self.pointData, (startSegmentIndex - 2) * self.numDimensions + 1, (startSegmentIndex + 2) * self.numDimensions)); +end + +function CatmullRomSplineMixin:FindSegmentOnGlobalCurve(t) + local numPoints = self:GetNumPoints(); + if numPoints > 1 then + local numSegments = numPoints - 1; + local segment = numSegments * t; + local segmentIndex = Clamp(math.floor(segment), 0, numSegments - 1) + 2; + return segmentIndex, PercentageBetween(segment + 2, segmentIndex, segmentIndex + 1); + end +end diff --git a/src/embed/AddOns/!!!ClassicAPI/Util/TaggableObject.lua b/src/embed/AddOns/!!!ClassicAPI/Util/TaggableObject.lua new file mode 100644 index 00000000..4ec7b19c --- /dev/null +++ b/src/embed/AddOns/!!!ClassicAPI/Util/TaggableObject.lua @@ -0,0 +1,87 @@ +-- Backport of retail's Blizzard_SharedXMLBase/TaggableObject.lua. + +local TAG_BANK_SIZE = 31; + +local function GetTagValues(tag) + local index = math.floor(tag / TAG_BANK_SIZE); + local tagIndexInBank = tag - (index * TAG_BANK_SIZE); + local tagBit = bit.lshift(1, tagIndexInBank); + + return index, tagBit; +end + +local function AddTagToTable(tags, tag) + local index, tagBit = GetTagValues(tag); + local tagValue = tags[index] or 0; + tags[index] = bit.bor(tagValue, tagBit); +end + +local function RemoveTagFromTable(tags, tag) + local index, tagBit = GetTagValues(tag); + local tagValue = tags[index]; + if tagValue ~= nil and tagValue > 0 then + tags[index] = bit.band(tagValue, bit.bnot(tagBit)); + end +end + +local function TableHasTag(tags, tag) + local index, tagBit = GetTagValues(tag); + local tagValue = tags[index]; + if tagValue ~= nil and tagValue > 0 then + return bit.band(tagValue, tagBit) == tagBit; + end + + return false; +end + +TaggableObjectMixin = {}; + +function TaggableObjectMixin:AddTag(tag) + AddTagToTable(GetOrCreateTableEntry(self, "tags"), tag); +end + +function TaggableObjectMixin:RemoveTag(tag) + if self.tags then + RemoveTagFromTable(self.tags, tag); + end +end + +function TaggableObjectMixin:RemoveAllTags() + self.tags = nil; +end + +function TaggableObjectMixin:MatchesTag(tag) + if self.tags then + return TableHasTag(self.tags, tag); + end + + return false; +end + +function TaggableObjectMixin:MatchesAnyTag(...) + if self.tags then + for i = 1, select("#", ...) do + local tag = select(i, ...); + if TableHasTag(self.tags, tag) then + return true; + end + end + end + + return false; +end + +function TaggableObjectMixin:MatchesAllTags(...) + if self.tags then + for i = 1, select("#", ...) do + local tag = select(i, ...); + if not TableHasTag(self.tags, tag) then + return false; + end + end + + return true; + end + + return false; +end diff --git a/src/embed/AddOns/!!!ClassicAPI/Util/TypeUtil.lua b/src/embed/AddOns/!!!ClassicAPI/Util/TypeUtil.lua new file mode 100644 index 00000000..c529b101 --- /dev/null +++ b/src/embed/AddOns/!!!ClassicAPI/Util/TypeUtil.lua @@ -0,0 +1,31 @@ +-- Backport of retail's Blizzard_SharedXML/TypeUtil.lua. + +--These functions are terrible, but they support legacy slash commands. +function ValueToBoolean(valueToCheck, defaultValue, defaultReturn) + if ( type(valueToCheck) == "nil" ) then + return false; + elseif ( type(valueToCheck) == "boolean" ) then + return valueToCheck; + elseif ( type(valueToCheck) == "number" ) then + return valueToCheck ~= 0; + elseif ( type(valueToCheck) == "string" ) then + return StringToBoolean(valueToCheck, defaultReturn); + else + return defaultReturn; + end +end + +function StringToBoolean(stringToCheck, defaultReturn) + stringToCheck = string.lower(stringToCheck); + local firstChar = string.sub(stringToCheck, 1, 1); + + if ( firstChar == "0" or firstChar == "n" or firstChar == "f" or stringToCheck == "off" or stringToCheck == "disabled" ) then + return false; + elseif ( firstChar == "1" or firstChar == "2" or firstChar == "3" or firstChar == "4" or firstChar == "5" or + firstChar == "6" or firstChar == "7" or firstChar == "8" or firstChar == "9" or firstChar == "y" or + firstChar == "t" or stringToCheck == "on" or stringToCheck == "enabled" ) then + return true; + end + + return defaultReturn; +end diff --git a/src/embed/AddOns/ClassicAPI_DebugTools/DebugTools.lua b/src/embed/AddOns/ClassicAPI_DebugTools/DebugTools.lua index a5326850..aaf520d0 100644 --- a/src/embed/AddOns/ClassicAPI_DebugTools/DebugTools.lua +++ b/src/embed/AddOns/ClassicAPI_DebugTools/DebugTools.lua @@ -1027,20 +1027,6 @@ end FRAMESTACK_UPDATE_TIME = .1; --- Blizzard_SharedXML's StringToBoolean, for the /framestack arguments. -local function _StringToBoolean(stringToCheck, defaultReturn) - stringToCheck = string.lower(stringToCheck); - local firstChar = string.sub(stringToCheck, 1, 1); - if (firstChar == "0" or firstChar == "n" or firstChar == "f" or - stringToCheck == "off" or stringToCheck == "disabled") then - return false; - elseif (string.find(firstChar, "^[1-9yt]") or - stringToCheck == "on" or stringToCheck == "enabled") then - return true; - end - return defaultReturn; -end - local function _WrapColor(text, colorHex) return "|c" .. colorHex .. text .. "|r"; end @@ -1266,8 +1252,8 @@ function FrameStackTooltip_HandleSlashCmd(msg) showHiddenArg, msg = string.match(msg or "", "^%s*(%S+)(.*)$"); showRegionsArg, msg = string.match(msg or "", "^%s*(%S+)(.*)$"); - local showHidden = _StringToBoolean(showHiddenArg or "", false); - local showRegions = _StringToBoolean(showRegionsArg or "", true); + local showHidden = StringToBoolean(showHiddenArg or "", false); + local showRegions = StringToBoolean(showRegionsArg or "", true); FrameStackTooltip_Toggle(showHidden, showRegions); end