-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCore.lua
More file actions
513 lines (476 loc) · 17.5 KB
/
Copy pathCore.lua
File metadata and controls
513 lines (476 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
-- Event-driven runtime coordinator for PETAL.
--
-- The coordinator owns no visible frames. It listens for state transitions,
-- coalesces them into one short delayed evaluation, and keeps a low-frequency
-- safety check while the addon is enabled. There is intentionally no frame
-- update loop: a missing pet is handled by events, bounded timers, and the
-- post-combat resume path.
local ADDON_NAME, PRIVATE = ...
local _G = _G
local APS = _G.PETAL
if not APS then
APS = CreateFrame("Frame")
_G.PETAL = APS
end
PRIVATE = type(PRIVATE) == "table" and PRIVATE or (APS.NS or {})
APS.NS = PRIVATE
local R = APS._runtime or {}
APS._runtime = R
R.listeners = R.listeners or {}
R.requestSerial = R.requestSerial or 0
R.recoverySerial = R.recoverySerial or 0
R.shuffleSerial = R.shuffleSerial or 0
R.loaded = R.loaded or false
local function secret(value)
return APS.IsSecret and APS:IsSecret(value) or false
end
local function safeString(value)
if value == nil or secret(value) then return nil end
return type(value) == "string" and value or nil
end
local function safeNumber(value)
if value == nil or secret(value) then return nil end
local number = tonumber(value)
return number and number == number and number or nil
end
local function safeBool(value)
return not secret(value) and value == true
end
local function notify(kind, payload)
for key, callback in pairs(R.listeners) do
if type(callback) == "function" then
local ok, err = pcall(callback, kind, payload)
if not ok and APS.Debug then
APS:Debug("Listener", tostring(key), "failed:", err)
end
end
end
end
function APS:RegisterStateListener(key, callback)
if type(key) ~= "string" or type(callback) ~= "function" then
return false
end
R.listeners[key] = callback
return true
end
function APS:UnregisterStateListener(key)
if type(key) == "string" then
R.listeners[key] = nil
end
end
-- Alias used by lightweight UI integrations.
APS.RegisterCallback = APS.RegisterStateListener
APS.UnregisterCallback = APS.UnregisterStateListener
local function cancelTimer(timer)
if timer and type(timer.Cancel) == "function" then
pcall(timer.Cancel, timer)
end
end
function APS:RequestEvaluation(delay, reason)
R.requestSerial = (R.requestSerial or 0) + 1
local serial = R.requestSerial
R.requestReason = reason or "state changed"
if R.evaluationTimer then
cancelTimer(R.evaluationTimer)
R.evaluationTimer = nil
end
delay = safeNumber(delay) or 0
if delay < 0 then delay = 0 end
local function run()
if serial ~= R.requestSerial or not R.loaded then
return
end
R.evaluationTimer = nil
self:Evaluate(false, R.requestReason)
end
if delay <= 0 then
run()
elseif _G.C_Timer and type(_G.C_Timer.After) == "function" then
_G.C_Timer.After(delay, run)
else
run()
end
end
-- Some state-changing events fire before the client has fully cleared a
-- blocker (resurrection, pet battle, vehicle, loading screen). Evaluate once
-- promptly and once more after a short settling delay. Both paths are
-- debounced and EnsurePet remains no-churn when a pet is already eligible.
function APS:RequestRecoveryEvaluation(delay, reason, settleDelay)
self:RequestEvaluation(delay, reason)
if not R.loaded or not (_G.C_Timer and type(_G.C_Timer.After) == "function") then
return
end
R.recoverySerial = (R.recoverySerial or 0) + 1
local serial = R.recoverySerial
delay = safeNumber(delay) or 0
settleDelay = safeNumber(settleDelay) or 1
if delay < 0 then delay = 0 end
if settleDelay < 0 then settleDelay = 0 end
_G.C_Timer.After(delay + settleDelay, function()
if R.loaded and serial == R.recoverySerial then
self:RequestEvaluation(0, (reason or "state recovered") .. " settled")
end
end)
end
function APS:ResetScheduler()
if R.ticker then
cancelTimer(R.ticker)
R.ticker = nil
end
if not R.loaded or not self:IsEnabled() then
self:ResetShuffleScheduler()
return
end
local timer = _G.C_Timer
if not timer or type(timer.NewTicker) ~= "function" then
return
end
local interval = self:GetIntervalSeconds()
R.ticker = timer.NewTicker(interval, function()
if R.loaded and self:IsEnabled() then
self:Evaluate(false, "safety check")
end
end)
self:ResetShuffleScheduler()
end
-- One-shot timer rather than a second fixed ticker: every successful timed
-- change draws a new interval from the player's chosen range. It has no
-- frame update and becomes inert immediately when the option is off.
function APS:ResetShuffleScheduler(retrySeconds)
R.shuffleSerial = (R.shuffleSerial or 0) + 1
local serial = R.shuffleSerial
if R.shuffleTimer then
cancelTimer(R.shuffleTimer)
R.shuffleTimer = nil
end
R.shuffleDueAt = nil
if not R.loaded or not self:IsEnabled() or type(self.GetRandomShuffleRangeSeconds) ~= "function" then
return
end
local minimum, maximum = self:GetRandomShuffleRangeSeconds()
if not minimum or not maximum then return end
local delay = safeNumber(retrySeconds)
if not delay then
if maximum > minimum and type(math.random) == "function" then
delay = math.random(math.floor(minimum), math.floor(maximum))
else
delay = minimum
end
end
delay = math.max(1, delay)
R.shuffleDueAt = (type(_G.GetTime) == "function" and _G.GetTime() or 0) + delay
local timer = _G.C_Timer
if not timer or type(timer.NewTimer) ~= "function" then return end
R.shuffleTimer = timer.NewTimer(delay, function()
if serial ~= R.shuffleSerial or not R.loaded or not self:IsEnabled() then return end
R.shuffleTimer = nil
R.shuffleDueAt = nil
local changed, reason = false, "scheduler unavailable"
if type(self.SummonNextMatchingPet) == "function" then
changed, reason = self:SummonNextMatchingPet()
end
-- A protected or temporary state is retried shortly. Any normal
-- attempt (including a single-pet pool) gets a fresh random interval.
if changed then
self:ResetShuffleScheduler()
elseif reason == "in combat" or reason == "mounted" or reason == "dead" or reason == "casting" or reason == "channeling" then
self:ResetShuffleScheduler(20)
else
self:ResetShuffleScheduler()
end
end)
end
-- Compatibility name retained for the original addon and lightweight UI
-- integrations. The scheduler is still one debounced ticker, never a frame
-- update loop.
APS.ResetTicker = APS.ResetScheduler
function APS:GetRuntimeStatus()
local state = R.petState or {}
return {
loaded = safeBool(R.loaded),
enabled = self:IsEnabled(),
currentPetGUID = self.GetSummonedPetGUID and self:GetSummonedPetGUID() or nil,
pendingPetGUID = state.pendingPetGUID,
lastDesiredPetGUID = state.lastDesiredPetGUID,
lastRuleID = state.lastRuleID,
lastEvaluationAt = R.lastEvaluationAt,
lastEvaluationReason = R.lastEvaluationReason,
lastEvaluationResult = R.lastEvaluationResult,
context = R.lastContext,
dismissGraceRemaining = self.GetDismissGraceRemaining and self:GetDismissGraceRemaining() or 0,
dismissGraceReason = self.GetDismissGraceReason and self:GetDismissGraceReason() or nil,
blockedReason = R.lastBlockedReason,
}
end
function APS:Evaluate(force, reason)
if not R.loaded then
return false, "runtime not loaded"
end
R.lastEvaluationAt = self.Now and self:Now() or 0
R.lastEvaluationReason = reason or (force and "forced evaluation" or "automatic evaluation")
if not self:IsEnabled() and not force then
R.lastEvaluationResult = "disabled"
R.lastBlockedReason = "addon disabled"
notify("state", self:GetRuntimeStatus())
return false, "addon disabled"
end
local context = self.GetContext and self:GetContext() or nil
local rule = self.GetActiveRule and self:GetActiveRule(context) or nil
if not rule then
R.lastEvaluationResult = "no matching rule"
R.lastBlockedReason = "no matching rule"
notify("state", self:GetRuntimeStatus())
return false, "no matching rule"
end
local ensured, status, activeRule, activeContext = self:EnsurePet(safeBool(force), reason, {
context = context,
rule = rule,
allowDisabled = false,
})
R.lastRuleID = activeRule and activeRule.id or nil
R.lastContext = activeContext or context
R.lastEvaluationResult = status
R.lastBlockedReason = (status ~= "summon requested" and status ~= "already satisfied") and status or nil
notify("state", self:GetRuntimeStatus())
return ensured, status, activeRule, activeContext
end
function APS:AutoCheck(force)
return self:Evaluate(safeBool(force), safeBool(force) and "forced check" or "automatic check")
end
function APS:SlashCommand(message)
message = type(message) == "string" and message or ""
message = string.lower((message:gsub("^%s+", ""):gsub("%s+$", "")))
if message == "next" then
return self:SummonNextMatchingPet()
elseif message == "summon" or message == "now" then
return self:SummonNow()
elseif message == "check" or message == "audit" then
return self:AutoCheck(true)
elseif message == "pause" or message == "off" then
self:SetEnabled(false)
return false, "disabled"
elseif message == "resume" or message == "on" then
self:SetEnabled(true)
return self:AutoCheck(false)
elseif message == "options" or message == "config" or message == "" then
if type(self.OpenOptions) == "function" then
return self:OpenOptions()
end
end
local printer = _G.print
if type(printer) == "function" then
printer("|cffc7b7ffPETAL:|r /petal, /petal next, /petal summon, /petal check, /petal pause, /petal resume")
end
end
function PETAL_KeybindChangePet()
local addon = _G.PETAL
if addon and type(addon.SummonNextMatchingPet) == "function" then
local changed, reason, rule, context = addon:SummonNextMatchingPet()
if addon.UI and type(addon.UI.HandleChangePetResult) == "function" then
pcall(addon.UI.HandleChangePetResult, addon.UI, changed, reason, rule, context)
end
return changed, reason, rule, context
end
end
function APS:HandlePetStateChange(reason)
local current = self.ObservePetState and self:ObservePetState(reason or "pet state changed") or nil
notify("pet", {
currentPetGUID = current,
graceRemaining = self.GetDismissGraceRemaining and self:GetDismissGraceRemaining() or 0,
})
return current
end
local coreFrame = CreateFrame("Frame")
R.coreFrame = coreFrame
local events = {
"ADDON_LOADED",
"PLAYER_LOGIN",
"PLAYER_ENTERING_WORLD",
"PLAYER_DEAD",
"PLAYER_ALIVE",
"PLAYER_UNGHOST",
"PLAYER_REGEN_ENABLED",
"PLAYER_REGEN_DISABLED",
"ZONE_CHANGED_NEW_AREA",
"ZONE_CHANGED",
"ZONE_CHANGED_INDOORS",
"GROUP_ROSTER_UPDATE",
"PLAYER_UPDATE_RESTING",
"PLAYER_CONTROL_GAINED",
"PLAYER_MOUNT_DISPLAY_CHANGED",
"PLAYER_GAINS_VEHICLE_DATA",
"PLAYER_LOSES_VEHICLE_DATA",
"PET_BATTLE_OPENING_START",
"PET_BATTLE_CLOSE",
"COMPANION_UPDATE",
"PET_JOURNAL_LIST_UPDATE",
"PLAYER_SPECIALIZATION_CHANGED",
"ACTIVE_TALENT_GROUP_CHANGED",
"PLAYER_EQUIPMENT_CHANGED",
"EQUIPMENT_SWAP_FINISHED",
"TRANSMOGRIFY_UPDATE",
"PLAYER_DIFFICULTY_CHANGED",
"UNIT_SPELLCAST_STOP",
"UNIT_SPELLCAST_CHANNEL_STOP",
"UNIT_SPELLCAST_INTERRUPTED",
"UNIT_SPELLCAST_FAILED",
"UNIT_SPELLCAST_FAILED_QUIET",
"UNIT_FLAGS",
"PLAYER_LOGOUT",
}
for _, event in ipairs(events) do
pcall(coreFrame.RegisterEvent, coreFrame, event)
end
local contextEvents = {
PLAYER_ENTERING_WORLD = true,
ZONE_CHANGED_NEW_AREA = true,
ZONE_CHANGED = true,
ZONE_CHANGED_INDOORS = true,
GROUP_ROSTER_UPDATE = true,
PLAYER_UPDATE_RESTING = true,
PLAYER_CONTROL_GAINED = true,
PLAYER_MOUNT_DISPLAY_CHANGED = true,
PLAYER_GAINS_VEHICLE_DATA = true,
PLAYER_LOSES_VEHICLE_DATA = true,
PET_BATTLE_OPENING_START = true,
PET_BATTLE_CLOSE = true,
PLAYER_SPECIALIZATION_CHANGED = true,
ACTIVE_TALENT_GROUP_CHANGED = true,
PLAYER_EQUIPMENT_CHANGED = true,
EQUIPMENT_SWAP_FINISHED = true,
TRANSMOGRIFY_UPDATE = true,
PLAYER_DIFFICULTY_CHANGED = true,
}
local settleEvents = {
PLAYER_ENTERING_WORLD = { delay = 1.5, settle = 1.5 },
ZONE_CHANGED_NEW_AREA = { delay = 0.2, settle = 1.0 },
ZONE_CHANGED = { delay = 0.2, settle = 1.0 },
ZONE_CHANGED_INDOORS = { delay = 0.2, settle = 1.0 },
PLAYER_REGEN_ENABLED = { delay = 0.1, settle = 0.8 },
PLAYER_CONTROL_GAINED = { delay = 0.25, settle = 1.0 },
PLAYER_MOUNT_DISPLAY_CHANGED = { delay = 0.2, settle = 1.0 },
PLAYER_LOSES_VEHICLE_DATA = { delay = 0.25, settle = 1.0 },
PET_BATTLE_CLOSE = { delay = 0.35, settle = 1.25 },
}
local castRecoveryEvents = {
UNIT_SPELLCAST_STOP = true,
UNIT_SPELLCAST_CHANNEL_STOP = true,
UNIT_SPELLCAST_INTERRUPTED = true,
UNIT_SPELLCAST_FAILED = true,
UNIT_SPELLCAST_FAILED_QUIET = true,
}
local function initialize()
if not R.loaded then
APS:NormalizeDB()
R.loaded = true
else
APS:NormalizeDB()
end
-- Modern Retail owns the random generator and no longer exposes
-- math.randomseed. Older clients may still expose it, so only seed when
-- that API is actually available.
if not R.randomSeeded then
local seed = type(_G.time) == "function" and _G.time() or math.floor((APS.Now and APS:Now() or 1) * 1000)
if type(seed) == "number" and type(math.randomseed) == "function" then
math.randomseed(seed)
if type(math.random) == "function" then
math.random(); math.random(); math.random()
end
end
R.randomSeeded = true
end
if APS.ObservePetState then
APS:ObservePetState("runtime initialized")
end
_G.SLASH_PETAL1 = "/petal"
if type(_G.SlashCmdList) == "table" then
_G.SlashCmdList.PETAL = function(message)
APS:SlashCommand(message)
end
end
APS:ResetScheduler()
notify("ready", APS:GetRuntimeStatus())
end
coreFrame:SetScript("OnEvent", function(_, event, arg1)
if event == "ADDON_LOADED" then
if arg1 ~= (ADDON_NAME or APS.ADDON_NAME or "PETAL") and arg1 ~= "PETAL" then
return
end
initialize()
APS:RequestEvaluation(1.0, "addon loaded")
return
end
if event == "PLAYER_LOGIN" then
if not R.loaded then initialize() end
APS:RequestEvaluation(1.0, "player login")
return
end
if event == "PLAYER_LOGOUT" then
R.loaded = false
if R.ticker then cancelTimer(R.ticker); R.ticker = nil end
if R.shuffleTimer then cancelTimer(R.shuffleTimer); R.shuffleTimer = nil end
if R.evaluationTimer then cancelTimer(R.evaluationTimer); R.evaluationTimer = nil end
return
end
if not R.loaded then
return
end
if event == "PLAYER_REGEN_DISABLED" then
APS:HandlePetStateChange("combat started")
return
end
if event == "PLAYER_REGEN_ENABLED" then
APS:HandlePetStateChange("combat ended")
APS:RequestRecoveryEvaluation(0.1, "combat ended", 0.8)
return
end
if event == "PLAYER_DEAD" then
-- Death temporarily removes a companion. Do not treat that as a
-- manual dismissal, or the normal grace window would block revival.
R.deathRecoveryPending = true
if APS.ClearDismissGrace then APS:ClearDismissGrace() end
APS:HandlePetStateChange("player died")
return
end
if event == "PLAYER_ALIVE" or event == "PLAYER_UNGHOST" then
R.deathRecoveryPending = nil
if APS.ClearDismissGrace then APS:ClearDismissGrace() end
APS:HandlePetStateChange(event)
APS:RequestRecoveryEvaluation(0.5, "resurrection", 1.25)
return
end
if castRecoveryEvents[event] then
-- Retry only when a previous evaluation was blocked by this cast.
-- This avoids an automatic check after every ordinary spell.
if arg1 == "player" and (R.lastBlockedReason == "casting" or R.lastBlockedReason == "channeling") then
APS:RequestRecoveryEvaluation(0.1, "cast ended", 0.5)
end
return
end
if event == "PET_JOURNAL_LIST_UPDATE" then
if APS.InvalidatePetPool then APS:InvalidatePetPool() end
APS:HandlePetStateChange("pet journal updated")
APS:RequestEvaluation(0.25, "pet journal updated")
notify("journal", APS:GetRuntimeStatus())
return
end
if event == "COMPANION_UPDATE" or event == "UNIT_FLAGS" then
if event ~= "UNIT_FLAGS" or arg1 == "player" then
APS:HandlePetStateChange(event)
APS:RequestEvaluation(0.2, event)
end
return
end
if contextEvents[event] then
if APS.InvalidateContext then APS:InvalidateContext() end
APS:HandlePetStateChange(event)
local settle = settleEvents[event]
if settle then
APS:RequestRecoveryEvaluation(settle.delay, event, settle.settle)
else
APS:RequestEvaluation(0.2, event)
end
end
end)
-- The frame is intentionally hidden and has no visible or protected state.
APS._coreFrame = coreFrame