Repository navigation
Expand file tree
/
Copy pathQueue.lua
More file actions
2209 lines (2047 loc) · 94.4 KB
/
Copy pathQueue.lua
File metadata and controls
2209 lines (2047 loc) · 94.4 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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- Manners -- the candidate queue: who is owed a favour, what the game keeps
-- refusing, the never-offer list, friends and guildmates, and BuildQueue,
-- which puts everybody the prompt could offer in order.
local ns = select(2, ...)
local L = ns.L
local addon = ns.addon
local issecretvalue = _G.issecretvalue
local InCombatLockdown = _G.InCombatLockdown
local GetTime = _G.GetTime
-- Core.lua's and Range.lua's, which load first.
local plain, safecall, caps, MANA = ns.plain, ns.safecall, ns.caps, ns.MANA
local ShortName, SafeForMacro = ns.ShortName, ns.SafeForMacro
local UnitHasBuff, UnitHasMana, MANA_CLASSES = ns.UnitHasBuff, ns.UnitHasMana, ns.MANA_CLASSES
local IsBuffableUnit, InRange, ShoutReach, SameParty = ns.IsBuffableUnit, ns.InRange, ns.ShoutReach, ns.SameParty
local prox, Resting = ns.proximity, ns.Resting
---------------------------------------------------------------------------
-- candidate queue
---------------------------------------------------------------------------
-- People who buffed us: [name] = { expires, at, guid?, class?, pvp? }. `at` is
-- when the favour was noticed, which the grace window and LiveExpiry count
-- from; `pvp` the PvP flag last read off them (see "flagged for PvP").
local owed = {}
-- [name .. "\0" .. buffKey] = expiry for a buff we just tried on them, so
-- casting Fortitude does not stop the walk reaching Divine Spirit; and
-- [name .. "\0*"] = expiry for the whole person (a right-press skip, or a press
-- that reached nobody), so somebody behind a pillar does not walk the list.
local tried = {}
-- [name] = what the game has been refusing on this person (NoteRefusal). In
-- memory only, on purpose: whatever the server held against them (a phase, a
-- duel, a rule nobody names) rarely outlives a /reload or a new login.
local refusals = {}
ns.lastGave = {} -- [name] = buffKey, for rotating when auras cannot be read
ns.owed, ns.tried, ns.refusals = owed, tried, refusals
-- When a debt really runs out: the stamp it was filed with, or its age against
-- the window as it stands now, whichever comes first -- so lowering "Remember a
-- buff for" applies to debts already owed. Every reader asks this.
local function LiveExpiry(entry)
local db = addon.db and addon.db.profile
local window = db and db.timing and db.timing.reciprocateWindow
if type(entry.at) ~= "number" or type(window) ~= "number" then return entry.expires end
return math.min(entry.expires, entry.at + window)
end
ns.DebtExpiry = LiveExpiry
-- GetTime() is time since boot, so it restarts after a reboot and differs per
-- machine: debts go out on the wall clock and are rebased on the way back in,
-- `at` included. db.char, not the profile: a debt is owed to a character.
local function SaveDebts()
local store = addon.db and addon.db.char
local wall = plain(time and time())
if not store or type(wall) ~= "number" then return end
-- Switched off means the file is cleared, not merely not written.
if addon.db.profile and addon.db.profile.timing.keepDebts == false then
store.debts = nil
return
end
local now, out = GetTime(), nil
for name, entry in pairs(owed) do
local expires = LiveExpiry(entry)
if expires > now then
out = out or {}
-- The class and the PvP flag are all the tokenless fallback judges by. The
-- guid is not kept: nothing reads it back.
out[name] = {
expires = wall + (expires - now),
at = wall - (now - entry.at),
class = entry.class,
pvp = entry.pvp == true or nil,
}
end
end
store.debts = out -- nil when empty, so AceDB prunes the section on logout
end
ns.SaveDebts = SaveDebts
local function RestoreDebts()
local store = addon.db and addon.db.char
local saved = store and store.debts
local wall = plain(time and time())
if type(saved) ~= "table" or type(wall) ~= "number" then return end
-- Honoured on the way in too: a file can outlive the setting (a profile
-- switched between logins, or changed on another character).
if addon.db.profile and addon.db.profile.timing.keepDebts == false then
store.debts = nil
return
end
local now = GetTime()
local window = (addon.db and addon.db.profile.timing.reciprocateWindow) or 120
for name, entry in pairs(saved) do
if type(entry) == "table" and type(entry.expires) == "number"
and type(entry.at) == "number" and SafeForMacro(name) then
-- Clamped to the window as it stands now, counted from the favour
-- as LiveExpiry does. A stamp from the future (the clock set back
-- since it was written) counts as now, or the skew would be added
-- to the window.
local at = math.min(entry.at, wall)
local left = math.min(entry.expires, at + window) - wall
if left > 0 then
-- `at` goes negative just after a reboot, correctly: now - at
-- is still the real age of the debt.
owed[name] = {
expires = now + left,
at = now - (wall - at),
class = type(entry.class) == "string" and entry.class or nil,
pvp = entry.pvp == true or nil,
}
end
end
end
end
ns.RestoreDebts = RestoreDebts
-- AceDB fires this from its PLAYER_LOGOUT handler, before it strips the
-- defaults, so writing here is safe.
function addon:SaveDebts()
ns.Guard("SaveDebts", SaveDebts)
end
-- The only writers and reader of the two key shapes in `tried`, in a block of
-- their own for the main chunk's 200 locals.
do
-- One writer under both shapes. keepLonger extends a block and never
-- shortens it, so the two-second rewind of a press that went nowhere cannot
-- cancel a right-press skip at the full retry cooldown.
local function Block(key, seconds, keepLonger)
if not seconds then
local db = addon.db and addon.db.profile
seconds = (db and db.timing.retryCooldown) or 12
end
local expiry = GetTime() + seconds
local standing = tried[key]
if keepLonger and standing and standing > expiry then return end
tried[key] = expiry
end
function ns.MarkAttempted(name, buffKey, seconds, keepLonger)
if not name or not buffKey then return end
Block(name .. "\0" .. buffKey, seconds, keepLonger)
end
function ns.BlockPerson(name, seconds, keepLonger)
if not name then return end
Block(name .. "\0*", seconds, keepLonger)
end
-- The keys one person's blocks are filed under, built once per person and
-- kept, since IsBlocked is asked for everybody on every scan. The
-- whole-person key sits under a table key no buff can have.
local blockKeys, blockKeyCount = {}, 0
local WHOLE_PERSON = {}
local function BlockKeys(name)
local keys = blockKeys[name]
if keys then return keys end
-- Bounded: a city puts hundreds of people through the scan in a session.
if blockKeyCount >= 500 then
wipe(blockKeys)
blockKeyCount = 0
end
keys = { [WHOLE_PERSON] = name .. "\0*" }
blockKeys[name] = keys
blockKeyCount = blockKeyCount + 1
return keys
end
-- The whole-person key is always consulted, and so is a back-off after
-- refusals in a row, a block on the whole person too.
function ns.IsBlocked(name, buffKey, now)
if not name then return false end
now = now or GetTime()
local refused = refusals[name]
if refused and refused.blockUntil > now then return true end
if next(tried) == nil then return false end
local keys = BlockKeys(name)
local person = tried[keys[WHOLE_PERSON]]
if person and person > now then return true end
if not buffKey then return false end
local key = keys[buffKey]
if not key then
key = name .. "\0" .. buffKey
keys[buffKey] = key
end
local one = tried[key]
return one ~= nil and one > now
end
end
-- What the game keeps refusing, per person, and what follows. The spoken line
-- is held for a while after a refusal: a macro runs every line even when its
-- /cast fails, so a thank-you went out over a buff that never landed, once per
-- press (beta.8). And the person backs off further with each refusal in a row:
-- somebody the game will never let you buff came straight back after two
-- seconds, forever. A cast that lands forgets it all (PruneSettled).
do
-- How long each refusal in a row keeps the person off the prompt. The first
-- is the two seconds RewindClick has always written, so one stray refusal
-- costs nothing new. Somebody who buffed you backs off more gently:
-- returning the favour is the point, and the favour itself stays owed.
local STEPS = { 2, 30, 300 }
local OWED_STEPS = { 2, 20, 60 }
-- The refusal in a row that says so in chat, once per run.
local TELL_AT = 3
-- How long the spoken line stays held after a press came to nothing, and
-- past the end of any back-off.
local QUIET_SECONDS = 30
-- A run of refusals this long over is forgotten, and the sweep lets the
-- person go: somebody never seen again must not be kept all session.
local FORGET_SECONDS = 600
local CAP = 200
-- How close an error line and a refusal must be to be about the same cast.
local ERROR_SECONDS = 1
local lastError, lastErrorAt = nil, 0
-- Who the newest refusal was about, for an error line arriving just after.
local newest
-- Errors about the caster rather than the person (out of mana, moving, the
-- cooldown, still on a flying mount): they hold the spoken line, since
-- nothing landed, but say nothing about whether the game will refuse this
-- person next time. Named by the client's own global strings, since the
-- text is localised.
local CASTER_SIDE = { "ERR_OUT_OF_MANA", "SPELL_FAILED_MOVING", "SPELL_FAILED_NOT_READY",
"ERR_SPELL_COOLDOWN", "ERR_ABILITY_COOLDOWN", "SPELL_FAILED_SPELL_IN_PROGRESS",
"SPELL_FAILED_SILENCED", "SPELL_FAILED_STUNNED", "SPELL_FAILED_CASTER_DEAD",
"SPELL_FAILED_INTERRUPTED", "SPELL_FAILED_NOT_MOUNTED" }
-- Refusals the press asks about again before it lets a line go
-- (Prompt/Press.lua, HoldLine): the range, the mana, a cooldown or a cast
-- in progress, the target dead. A press that carried no line and was
-- refused for one of these leaves nothing to hold: the next press says the
-- line only if it finds that cleared.
local RECHECKED = { "ERR_OUT_OF_RANGE", "SPELL_FAILED_OUT_OF_RANGE", "ERR_OUT_OF_MANA",
"SPELL_FAILED_NOT_READY", "ERR_SPELL_COOLDOWN", "ERR_ABILITY_COOLDOWN",
"SPELL_FAILED_SPELL_IN_PROGRESS", "SPELL_FAILED_TARGETS_DEAD" }
-- Whether the game's words are one of these global strings.
local function OneOf(message, keys)
if type(message) ~= "string" then return false end
local bare = message:gsub("%.$", "")
for _, key in ipairs(keys) do
local text = plain(_G[key])
if type(text) == "string" and text:gsub("%.$", "") == bare then return true end
end
return false
end
local function AboutTheCaster(message)
return OneOf(message, CASTER_SIDE)
end
-- Said whether or not chat lines are on: it is the only thing that says
-- why somebody vanished from the prompt.
local function Tell(name, why)
-- Your own buff (SelfEntry) by what it is: your name in the third
-- person reads as somebody else who shares it. Targeting yourself
-- lifts it, as targeting anybody does (LiftBackoff).
if ns.IsPlayerName(name) then
addon:Print(type(why) == "string"
and L["|cffff8080the game keeps refusing your own buff|r (it said: %s) -- it will not be offered to you for a while; target yourself to try again."]
:format((why:gsub("%.$", "")))
or L["|cffff8080the game keeps refusing your own buff|r -- it will not be offered to you for a while; target yourself to try again."])
return
end
if type(why) == "string" then
addon:Print(L["|cffff8080the game keeps refusing buffs on %s|r (it said: %s) -- they will not be offered for a while; target them to try again."]
:format(name, (why:gsub("%.$", ""))))
else
addon:Print(L["|cffff8080the game keeps refusing buffs on %s|r -- they will not be offered for a while; target them to try again."]
:format(name))
end
end
function ns.SweepRefusals(now)
for name, r in pairs(refusals) do
if r.blockUntil <= now and r.quietUntil <= now and now - r.last > FORGET_SECONDS then
refusals[name] = nil
end
end
end
-- One person's record, room made for it first. Counted here, not tallied: a
-- new record is rare, and a count cannot drift from the table.
local function Record(name, now)
local r = refusals[name]
if r then return r end
local held, oldest, at = 0, nil, nil
for who, rec in pairs(refusals) do
held = held + 1
if not at or rec.last < at then oldest, at = who, rec.last end
end
-- Full even so: the person refused longest ago goes.
if held >= CAP then refusals[oldest] = nil end
r = { count = 0, last = now, blockUntil = 0, quietUntil = 0 }
refusals[name] = r
return r
end
-- Every error line the game raises. One arriving just after a refusal that
-- had no reason of its own is taken as that reason.
function ns.NoteGameError(message)
if type(message) ~= "string" then return end
local now = GetTime()
lastError, lastErrorAt = message, now
local r = newest and refusals[newest]
if r and r.why == nil and now - r.last <= ERROR_SECONDS and not AboutTheCaster(message) then
r.why = message
end
end
-- A press on this person came to nothing: an error inside the press's
-- window, or a refusal after it was sent. `why` is the game's own words
-- where the caller has them. `quietOnly` holds the spoken line and no more,
-- for a press the game never answered at all: nothing refused anybody
-- there, so it is no evidence the game will refuse them next time.
-- `spoke` is false for a press whose macro carried no line (PostClick
-- records it): refused for something the next press asks again
-- (RECHECKED), or not refused at all (quietOnly), that holds no line, or
-- the press that lands once they are back in reach would go out silent
-- too. The back-off stands either way.
function ns.NoteRefusal(name, why, quietOnly, spoke)
if not name then return end
local now = GetTime()
if why == nil and lastError and now - lastErrorAt <= ERROR_SECONDS then why = lastError end
local r = Record(name, now)
local hold = spoke ~= false or (not quietOnly and not OneOf(why, RECHECKED))
-- Never shortened: a quiet note must not cut the longer hold a back-off
-- below wrote.
if hold and now + QUIET_SECONDS > r.quietUntil then r.quietUntil = now + QUIET_SECONDS end
newest = name
if quietOnly or AboutTheCaster(why) then
r.last = now
return
end
-- A run long over was swept (SweepRefusals), so this starts again at one.
r.last = now
r.count = r.count + 1
r.why = type(why) == "string" and why or nil
local debt = owed[name]
local steps = (debt and LiveExpiry(debt) > now) and OWED_STEPS or STEPS
local seconds = steps[math.min(r.count, #steps)]
if now + seconds > r.blockUntil then r.blockUntil = now + seconds end
-- The line stays held past the back-off: somebody the game keeps refusing
-- comes back when it runs out, and the first press then would thank them
-- over yet another refused cast. A cast that lands clears it (NoteLanded).
if hold and r.blockUntil + QUIET_SECONDS > r.quietUntil then r.quietUntil = r.blockUntil + QUIET_SECONDS end
if r.count >= TELL_AT and not r.said then
r.said = true
if r.why or not (C_Timer and C_Timer.After) then
Tell(name, r.why)
else
-- The error line can arrive a moment after the refusal it explains.
C_Timer.After(0.3, function() ns.Guard("refusal line", Tell, name, r.why) end)
end
end
end
-- A cast on them landed: nothing the game refused before stands.
function ns.NoteLanded(name)
if name then refusals[name] = nil end
end
function ns.SpeechHeld(name, now)
local r = name and refusals[name]
return r ~= nil and r.quietUntil > (now or GetTime())
end
-- The player pointed at them on purpose (PLAYER_TARGET_CHANGED): the
-- back-off lifts, the count stays, so another refusal backs off again.
function ns.LiftBackoff(name)
local r = name and refusals[name]
if r then r.blockUntil = 0 end
end
-- For /manners debug: who is backed off or kept quiet, and for how long.
-- Seconds rather than a clock time: the minimap clock may be the realm's.
function ns.RefusalLines(now)
local out = {}
for name, r in pairs(refusals) do
if r.blockUntil > now then
out[#out + 1] = L["backed off for %ds more: |cffffffff%s|r -- refused %d times in a row"]
:format(math.ceil(r.blockUntil - now), name, r.count)
elseif r.quietUntil > now then
out[#out + 1] = L["no spoken line for %ds more: |cffffffff%s|r -- the game refused a cast on them"]
:format(math.ceil(r.quietUntil - now), name)
end
end
table.sort(out)
return out
end
end
-- The debt is paid. Written through, so a reload cannot raise it again.
function ns.SettleFavour(name)
if not name then return end
owed[name] = nil
SaveDebts()
end
---------------------------------------------------------------------------
-- the never-offer list
--
-- People the player has said never to offer anything to, filed under the same
-- name debts are, in the profile. It reaches the queue at its next rebuild (in
-- a fight, the end of it); nothing here touches the button.
---------------------------------------------------------------------------
-- Defined with the favour ledger's other hook further down, and declared here
-- so the never-offer list below can tell the ledger about a favour it lets go.
local TellLedger
local function NeverSet()
local db = addon.db and addon.db.profile
local never = db and db.never
if type(never) ~= "table" then return nil end
return never
end
local function CleanName(name)
if type(name) ~= "string" then return nil end
name = name:gsub("%s+", " "):match("^%s*(.-)%s*$")
if name == "" then return nil end
return name
end
-- Whether a listed name matches, regardless of case, since names are typed by
-- hand. Folded by the client's strcmputf8i where there is one (string.lower
-- leaves accented capitals alone); plain lower is the fallback, and all there
-- is to it for two names in A to Z. The scan asks this of every asker it
-- remembers against every request on every pass, so the pcall is kept for a
-- name that needs it.
local function SameName(a, b)
if not b then return false end
if a == b then return true end
local fold = _G.strcmputf8i
if type(fold) == "function" and (a:find("[\128-\255]") or b:find("[\128-\255]")) then
local ok, cmp = pcall(fold, a, b)
if ok and type(cmp) == "number" then return cmp == 0 end
end
return a:lower() == b:lower()
end
ns.SameName = SameName
-- Whether a sorts before b, case folded the same way SameName folds it, so a
-- name typed in small letters sorts among the capitalised ones in any script.
-- Not full collation (Ё still sorts apart from Е). Ties fall back to lower and
-- then to bytes, so the order is total, which table.sort needs.
local function NameBefore(a, b)
local fold = _G.strcmputf8i
if type(fold) == "function" then
local ok, cmp = pcall(fold, a, b)
if ok and type(cmp) == "number" and cmp ~= 0 then return cmp < 0 end
end
local la, lb = a:lower(), b:lower()
if la ~= lb then return la < lb end
return a < b
end
-- What the list walk has already answered, by name: the entry, or false. The
-- scan asks about everybody 2.5 times a second, two case-folded compares per
-- entry. Checked against a copy of the list rather than cleared by an editor,
-- because imports, profile switches and the scenarios write the table
-- directly; a different fold function throws the answers away too. `scan` is
-- the answers while BuildQueue walks the units.
local neverSeen = {
list = nil, fold = nil, size = 0, copy = {}, verdict = {}, count = 0,
max = 1000, scan = nil,
}
-- The answers, valid for the list as it stands now. nil when there is no list.
local function NeverVerdicts()
local never = NeverSet()
if not never then return nil end
local copy, fold = neverSeen.copy, _G.strcmputf8i
local fresh = neverSeen.list == never and neverSeen.fold == fold
if fresh then
local size = 0
for key, flag in pairs(never) do
if copy[key] ~= flag then fresh = false break end
size = size + 1
end
if size ~= neverSeen.size then fresh = false end
end
if not fresh then
wipe(copy)
local size = 0
for key, flag in pairs(never) do
copy[key] = flag
size = size + 1
end
neverSeen.list, neverSeen.fold, neverSeen.size = never, fold, size
wipe(neverSeen.verdict)
neverSeen.count = 0
end
return neverSeen.verdict
end
-- The entry on the list that names this person, or nil: exact, then regardless
-- of case, then with the realm taken off the name (as the prompt shows it) --
-- never the other way round. `verdict` is NeverVerdicts' table, passed only by
-- the scan; anybody else walks the list.
local function ListedAs(name, verdict)
local never = NeverSet()
if not never or type(name) ~= "string" or next(never) == nil then return nil end
if never[name] == true then return name end
if verdict then
local known = verdict[name]
if known ~= nil then return known or nil end
end
local short = ShortName(name)
local found
for key in pairs(never) do
if type(key) == "string" then
if SameName(key, name) or SameName(key, short) then found = key break end
end
end
if verdict then
-- Bounded like the other per-person caches.
if neverSeen.count >= neverSeen.max then
wipe(verdict)
neverSeen.count = 0
end
verdict[name] = found or false
neverSeen.count = neverSeen.count + 1
end
return found
end
ns.ListedAs = ListedAs
-- The scan's answers while it walks; between scans the same answers, checked
-- against the list as it stands (NeverVerdicts, table lookups alone), so an
-- edit is honoured at once. The repaint and the options page ask about the
-- same few names over and over, and a list walk per ask was most of the cost.
function ns.IsNeverOffered(name)
return ListedAs(name, neverSeen.scan or NeverVerdicts()) ~= nil
end
-- Whether somebody is on your /ignore list, the game's own "leave me alone":
-- by token (or name: IsIgnored takes either), else by GUID. Neither call
-- throws on a plain string, and each answers a plain yes or no, so nothing is
-- pcalled; false on a client without them. Unlike the never-offer list, a
-- favour is no exception: nobody you ignore is thanked or offered one back
-- (Favours.lua, Sight and the combat log), and no passer-by is offered at
-- all. A group member stays offered: buffing a teammate you ignore still
-- helps the group.
function ns.Ignored(unit, guid)
local friends = _G.C_FriendList
if type(friends) ~= "table" then return false end
if type(unit) == "string" and type(friends.IsIgnored) == "function"
and plain(friends.IsIgnored(unit)) == true then return true end
if type(guid) == "string" and type(friends.IsIgnoredByGuid) == "function"
and plain(friends.IsIgnoredByGuid(guid)) == true then return true end
return false
end
-- Whether the ignore list has anybody on it, asked once a scan so an empty
-- one costs the walk nothing.
local function IgnoresAnybody()
local friends = _G.C_FriendList
local count = type(friends) == "table" and type(friends.GetNumIgnores) == "function"
and plain(friends.GetNumIgnores()) or nil
return type(count) == "number" and count > 0
end
-- Puts somebody on the list. Returns the spelling now on it, and whether they
-- were already there (whose spelling is kept, so nobody is listed twice).
function ns.NeverOffer(name)
name = CleanName(name)
local never = NeverSet()
if not name or not never then return nil end
local already = ListedAs(name)
if already then return already, true end
never[name] = true
return name, false
end
-- Takes somebody off. Returns the spelling that came off, or nil when nobody
-- on the list answers to that name.
function ns.AllowAgain(name)
local listed = ListedAs(CleanName(name))
if not listed then return nil end
NeverSet()[listed] = nil
return listed
end
-- Everybody on it, sorted the way a reader looks for a name.
function ns.NeverList()
local names = {}
for name, flag in pairs(NeverSet() or {}) do
if flag == true then names[#names + 1] = name end
end
table.sort(names, NameBefore)
return names
end
function ns.ClearNeverList()
local never = NeverSet()
if never then wipe(never) end
end
-- Puts somebody on the list as a deliberate act (a shift-right-click on the
-- prompt, /manners never, the options box) and always says so, since it is
-- where the way back is written. Returns the spelling on the list, or nil for
-- a name that was only space. A favour they are owed goes with them, even when
-- already listed: owed people are exempt from the list (STATUS.md), so they
-- would come straight back once the skip ran out.
function ns.PutOnNeverList(name)
local listed, already = ns.NeverOffer(name)
if not listed then return nil end
local forgiven = false
-- Matched against the one entry just listed, by ListedAs' rule, rather than
-- walking the whole list once per favour.
for key in pairs(owed) do
if SameName(listed, key) or SameName(listed, ShortName(key)) then
owed[key] = nil
forgiven = true
-- The ledger's row goes with the debt: its own sweep walks the
-- debts and could never reach one let go here.
TellLedger("LetGo", key, "never")
end
end
-- Repainted here too, since somebody already listed never reaches the end.
if forgiven then
SaveDebts()
ns.RepaintOptions()
end
-- In a fight the secure button cannot be re-armed, so if the prompt names
-- the person just listed, a press still casts at them until it ends, and
-- the line has to say so. Guarded: the prompt may not have loaded.
local onPromptInFight = false
if InCombatLockdown() and ns.Prompt and ns.Prompt.Showing then
ns.Guard("never-offer prompt check", function()
local showing = ns.Prompt:Showing()
onPromptInFight = type(showing) == "table" and type(showing.name) == "string"
and ListedAs(showing.name) == listed
end)
end
if already then
if forgiven and onPromptInFight then
addon:Print(L["|cffffffff%s|r is already on your never-offer list, and the favour they did you is let go -- but the prompt cannot move off them in this fight, and a press still casts at them."]
:format(listed))
elseif onPromptInFight then
addon:Print(L["|cffffffff%s|r is already on your never-offer list -- but the prompt cannot move off them in this fight, and a press still casts at them."]
:format(listed))
elseif forgiven then
addon:Print(L["|cffffffff%s|r is already on your never-offer list, and the favour they did you is let go."]
:format(listed))
else
addon:Print(L["|cffffffff%s|r is already on your never-offer list."]:format(listed))
end
return listed
end
-- The way back goes in whole: it is typed exactly as shown in every language.
local undo = "/manners allow " .. listed
if forgiven and onPromptInFight then
addon:Print(L["|cffffffff%s|r will not be offered anything again unless they buff you, and their favour is let go -- but in this fight a press still casts at them. |cffffd100%s|r takes them off the list."]
:format(listed, undo))
elseif onPromptInFight then
addon:Print(L["|cffffffff%s|r will not be offered anything again unless they buff you -- but the prompt cannot move off them in this fight, and a press still casts at them. |cffffd100%s|r takes them off the list."]
:format(listed, undo))
elseif forgiven then
addon:Print(L["|cffffffff%s|r will not be offered anything again unless they buff you, and the favour they just did you is let go. |cffffd100%s|r takes them off the list."]
:format(listed, undo))
else
addon:Print(L["|cffffffff%s|r will not be offered anything again unless they buff you. |cffffd100%s|r takes them off the list."]
:format(listed, undo))
end
ns.RepaintOptions()
return listed
end
---------------------------------------------------------------------------
-- friends and guildmates
--
-- For "Who comes first": a preference about order, never a reason to offer or
-- drop anybody, so anything the client will not say reads as "not a friend".
---------------------------------------------------------------------------
-- The section's two entry points; the rest is private to the block below, for
-- the main chunk's 200 locals.
local SweepCloseness, Closeness
do
-- How long an answer about one person is kept: a friends list changes over
-- minutes, and the scan asks about everybody two and a half times a second.
local CLOSE_SECONDS = 10
local closeCache = {}
local friendNames, friendGuids, friendsReadAt = {}, {}, nil
-- The fallback for a client whose C_FriendList has no IsFriend: the list read
-- by index, the way the addons known to work on this client read it.
local function ReadFriendsList(now)
if friendsReadAt and now - friendsReadAt < CLOSE_SECONDS then return end
friendsReadAt = now
wipe(friendNames)
wipe(friendGuids)
local list = _G.C_FriendList
if type(list) ~= "table" then return end
local count = safecall(list.GetNumFriends)
if type(count) ~= "number" then return end
-- The game caps a friends list well below this; the bound is there so a
-- nonsense count cannot turn one scan into a very long one.
for i = 1, math.min(count, 200) do
local info = safecall(list.GetFriendInfoByIndex, i)
if type(info) == "table" then
local name, guid = plain(info.name), plain(info.guid)
if type(name) == "string" then friendNames[name:lower()] = true end
if type(guid) == "string" then friendGuids[guid] = true end
end
end
end
-- Old answers go, once per lifetime of an answer: Closeness checks an answer's
-- age before trusting it, so one left standing a little longer is never used.
local closeSweptAt
function SweepCloseness(now)
if closeSweptAt and now >= closeSweptAt and now - closeSweptAt < CLOSE_SECONDS then return end
closeSweptAt = now
for name, answer in pairs(closeCache) do
if now - answer.at >= CLOSE_SECONDS then closeCache[name] = nil end
end
end
-- GetGuildInfo's realm as something to compare: "" for your own realm, which
-- it answers as nil, and nil (matching nothing) for a secret or nonsense.
local function GuildRealm(realm)
if issecretvalue and issecretvalue(realm) then return nil end
if realm == nil then return "" end
if type(realm) ~= "string" then return nil end
return realm
end
-- "friend", "guild", or nil for neither and for could-not-tell alike; friend
-- first, the more particular thing for the tooltip to say. The GUID goes to
-- the client as handed over, and is never compared or read here: a secret
-- throws on both.
function Closeness(unit, full, now)
local cached = closeCache[full]
if cached and now - cached.at < CLOSE_SECONDS then return cached.kind or nil end
local kind
local rawGuid = UnitGUID(unit)
local list, bnet = _G.C_FriendList, _G.C_BattleNet
if type(list) == "table" and safecall(list.IsFriend, rawGuid) == true then
kind = "friend"
elseif type(bnet) == "table"
and type(safecall(bnet.GetGameAccountInfoByGUID, rawGuid)) == "table" then
-- Answers for Battle.net friends and nobody else; the Camelot social
-- addon accepts group invites from friends on exactly this.
kind = "friend"
else
ReadFriendsList(now)
local guid = plain(rawGuid)
if (type(guid) == "string" and friendGuids[guid])
or friendNames[full:lower()]
or friendNames[(ns.TargetName(full) or full):lower()] then
kind = "friend"
end
end
if not kind then
local inMine
if type(_G.UnitIsInMyGuild) == "function" then
local ok, answer = pcall(_G.UnitIsInMyGuild, unit)
if ok then inMine = plain(answer) end
end
if inMine == true then
kind = "guild"
elseif inMine == nil then
-- Only where UnitIsInMyGuild gave no answer (a plain no is one): the two guild
-- names and their realms, a guild's name being unique only on its realm.
-- pcall, not safecall: the realm is the fourth return.
local okTheirs, theirs, _, _, theirRealm = pcall(_G.GetGuildInfo, unit)
local okOurs, ours, _, _, ourRealm = pcall(_G.GetGuildInfo, "player")
theirs, ours = plain(theirs), plain(ours)
theirRealm, ourRealm = GuildRealm(theirRealm), GuildRealm(ourRealm)
if okTheirs and okOurs and type(theirs) == "string" and theirs ~= ""
and theirs == ours and theirRealm and theirRealm == ourRealm then
kind = "guild"
end
end
end
closeCache[full] = { at = now, kind = kind or false }
return kind
end
end
-- Tell the favour ledger (Ledger.lua) what happened to a favour: one way only,
-- so it never changes who is offered what, and guarded. Assigns the local
-- declared above the never-offer list.
function TellLedger(event, ...)
local ledger = ns.Ledger
local fn = ledger and ledger[event]
if type(fn) == "function" then ns.Guard("ledger " .. event, fn, ...) end
-- "In character" counts the exchanges with each person this session from
-- the same four moments, for its lines about meeting somebody again.
local heard = ns.InCharacter and ns.InCharacter.Heard
if type(heard) == "function" then ns.Guard("in character " .. event, heard, event, ...) end
-- The launcher counts the favours waiting to be returned.
if ns.RefreshBrokerText then ns.Guard("broker text", ns.RefreshBrokerText) end
end
ns.TellLedger = TellLedger
-- Somebody who asked comes after the people who buffed you and before your
-- group. One and a half rather than a renumbering, so the other numbers keep
-- meaning what they mean in the sort, the prompt's hold and bug reports.
local PRIORITY = { target = 0, owed = 1, asked = 1.5, group = 2, nearby = 3 }
-- A group member put first by a ready check or by coming back from the dead:
-- behind your deliberate target, ahead of everybody else.
PRIORITY.sweep = 0.5
-- Your own buff: behind everybody waiting on you for something -- your pick, a
-- ready check or a death, a favour, a request -- since they may walk off and
-- you will not; ahead of your group and passers-by, since what you carry is
-- what you fight with.
PRIORITY.self = 1.75
-- The group's unit tokens, spelled out once rather than joined on every scan.
local GROUP_TOKENS = { raid = {}, party = {} }
for i = 1, 40 do
GROUP_TOKENS.raid[i] = "raid" .. i
GROUP_TOKENS.party[i] = "party" .. i
end
-- fn(unit, pointed). `pointed` marks a unit the player deliberately picked out:
-- target and focus, which stand until the player changes them. Mouseover is
-- wherever the cursor happens to be, and counting it would flash distant
-- strangers onto the prompt. Focus comes before mouseover because one verdict
-- is reached per person per scan, on whichever token reaches them first.
local function IterateUnits(fn)
fn("target", true)
fn("focus", true)
fn("mouseover")
local n = plain(GetNumGroupMembers and GetNumGroupMembers()) or 0
if n > 0 then
local inRaid = plain(IsInRaid and IsInRaid()) == true
local prefix = inRaid and "raid" or "party"
local tokens = GROUP_TOKENS[prefix]
local count = inRaid and n or (n - 1)
for i = 1, count do
fn(tokens[i] or (prefix .. i))
end
end
-- Our own list from NAME_PLATE_UNIT_ADDED (ns.nameplateUnits, Core.lua): a
-- frame's token is a secret. The frames only when that list is empty.
local plated = 0
for token in pairs(ns.nameplateUnits) do
if plain(UnitExists(token)) then
plated = plated + 1
fn(token)
else
ns.nameplateUnits[token] = nil
end
end
if plated == 0 and caps.namePlates then
local plates = safecall(C_NamePlate.GetNamePlates)
if type(plates) == "table" then
for _, plate in pairs(plates) do
local token = plate and plain(plate.namePlateUnitToken)
if token then fn(token) end
end
end
end
end
-- The token that names this person at this moment, or nil. Asked by the
-- prompt's press (Prompt/Press.lua), which speaks only to somebody a token
-- still holds: a remembered passer-by and the tokenless favour have none, and
-- the token the scan found them by may name somebody else by now. Every token
-- the scan walks, compared by the name they are filed under (UnitFullName:
-- the surname on Forever, the realm elsewhere), so another "Weirbeard" is not
-- Weirbeard Jenkins. `hint`, the scan's token, is asked first. Once a press,
-- never on the scan.
function ns.UnitFor(name, hint)
if type(name) ~= "string" then return nil end
if hint and plain(UnitExists(hint)) and ns.UnitFullName(hint) == name then return hint end
local found
IterateUnits(function(unit)
if not found and unit ~= hint and plain(UnitExists(unit)) and ns.UnitFullName(unit) == name then
found = unit
end
end)
return found
end
---------------------------------------------------------------------------
-- dungeons and raids
--
-- Two moments put a group member missing your buff at the front: a ready
-- check, which is when a buffer sweeps the group before a pull, and coming
-- back from the dead, which costs every buff. And two limits on offers nobody
-- asked for: the mana you keep for yourself, and the raid groups you were
-- given. A favour owed and a request from chat are never held back by either.
---------------------------------------------------------------------------
-- How long a ready check counts as running when the client names no time, or
-- a nonsense one: the game's own lasts 35 seconds.
local READY_CHECK_SECONDS = 35
-- How long the group stays first once everybody has answered: the check is
-- where the pre-pull sweep starts, not all of it, and everybody answers in a
-- few seconds. The pull ends it sooner.
local READY_CHECK_AFTER = 60
-- How long somebody back from the dead stays at the front: long enough to be
-- rezzed, to stand up and to be buffed, short enough to be about the death.
local REVIVED_SECONDS = 120
-- Once mana is being saved, how far past the floor it must climb before the
-- group comes back, so that one cast dipping under it and the regen climbing
-- back do not blink the group on and off the prompt between casts.
local MANA_MARGIN = 5
-- readyUntil: when the group stops coming first for a ready check, or nil.
-- down: [unit token] = the name read when it was seen dead (false when none
-- could be read). revived: [name] = GetTime() they were seen alive again.
-- prefix: which tokens `down` is about. saving: true while the mana floor is
-- holding offers back. One table for the main chunk's 200 locals.
local sweep = { readyUntil = nil, down = {}, revived = {}, prefix = nil, saving = nil }
-- Either end of a ready check repaints at once rather than at the next scan:
-- a ready check lasts seconds.
function addon:READY_CHECK(_, _, timeLeft)
local seconds = plain(timeLeft)
if type(seconds) ~= "number" or seconds <= 0 or seconds > 120 then seconds = READY_CHECK_SECONDS end
sweep.readyUntil = GetTime() + seconds
if ns.Prompt then ns.Guard("ready check", ns.Prompt.Refresh, ns.Prompt) end
end
-- Everybody has answered, which in an organised raid takes seconds: the buffing
-- before the pull has only started, so the group stays first a while longer.
-- An end heard with no check running (a reload in the middle of one) starts
-- nothing.
function addon:READY_CHECK_FINISHED()
local now = GetTime()
if ns.ReadyCheckRunning(now) then
sweep.readyUntil = now + READY_CHECK_AFTER
else
sweep.readyUntil = nil
end
if ns.Prompt then ns.Guard("ready check over", ns.Prompt.Refresh, ns.Prompt) end
end
-- The pull is the real end of the sweep before it; called as the fight starts.
function ns.EndReadyCheck()
sweep.readyUntil = nil
end
function ns.ReadyCheckRunning(now)
local untilAt = sweep.readyUntil
return untilAt ~= nil and untilAt > (now or GetTime())
end
-- Who in the group has just come back from the dead, walked on every tick
-- rather than on UNIT_HEALTH, which fires hundreds of times a second in a raid
-- fight: forty questions every 0.4 s is cheaper, and the tick runs in fights
-- and while you are dead. A secret answer changes nothing. The name is read
-- as somebody dies, on every tick they lie dead, and as they stand up: a
-- roster change can hand the token to somebody else, dead or alive, and one
-- found under a new name is a new arrival, asked about Feign Death as such.
function ns.WatchGroupDeaths(now)
local db = addon.db and addon.db.profile
local down, revived = sweep.down, sweep.revived
local n = plain(GetNumGroupMembers and GetNumGroupMembers()) or 0
if not (db and db.priority.revived == true) or n <= 0 then
sweep.prefix = nil
if next(down) then wipe(down) end
if next(revived) then wipe(revived) end
return
end
local inRaid = plain(IsInRaid and IsInRaid()) == true
local prefix = inRaid and "raid" or "party"
-- A party that became a raid renumbered everybody.
if prefix ~= sweep.prefix then
wipe(down)
sweep.prefix = prefix
end
local tokens = GROUP_TOKENS[prefix]
local count = math.min(inRaid and n or (n - 1), 40)
-- Called directly, as UnitIsDeadOrGhost is: a group token never throws.
local feigning = _G.UnitIsFeignDeath
if type(feigning) ~= "function" then feigning = nil end