Repository navigation
Expand file tree
/
Copy pathCommands.lua
More file actions
1725 lines (1614 loc) · 75.3 KB
/
Copy pathCommands.lua
File metadata and controls
1725 lines (1614 loc) · 75.3 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 -- what the player types and reads: the first-run greeting, the
-- test console, snooze, sharing settings, and the slash commands with their
-- diagnostics.
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 Queue.lua's, which load first.
local plain, caps, MANA = ns.plain, ns.caps, ns.MANA
local owed, LiveExpiry = ns.owed, ns.DebtExpiry
---------------------------------------------------------------------------
-- first run
--
-- A greeting, once: what the addon does, what it looks like and where, and the
-- one thing it cannot do for you -- otherwise nothing shows until a stranger
-- buffs you, which reads as an addon that does not work.
--
-- The flag lives in db.char, not the profile: every character starts on the
-- shared "Default" profile, so a profile flag would greet only the first
-- character. What it asks for (a macro, a key) is per character anyway.
---------------------------------------------------------------------------
-- What "Myself" is doing, for /manners debug and Diagnostics: what holds
-- everything on yourself back, if anything; your group buff when it is the one
-- on the prompt (Queue.lua, SelfEntry); then a line per family of your class's
-- own buffs, from the queue's own answers (Core.lua, OwnVerdict), so the two
-- cannot disagree. Nothing when "Myself" is off, and only the one line when
-- your own name is on the never-offer list. Whole sentences per case.
do
local HELD = {
fight = L["your own buffs: held back -- you are in a fight."],
skipped = L["your own buffs: held back -- skipped for now."],
noname = L["your own buffs: held back -- the game will not say your name."],
listed = L["your own buffs: held back -- you are on your never-offer list."],
}
local function FamilyLine(family, ctx)
local label = ns.OwnFamilyLabel(family)
local spell, has, _, why, about = ns.OwnVerdict(family, ctx)
local name = about and ns.BuffName(about)
if spell and has then
return L["%s: %s is running low -- a top-up is due."]:format(label, ns.BuffName(spell))
elseif spell and spell.item then
return L["%s: none up -- %s is the one to use."]:format(label, ns.BuffName(spell))
elseif spell then
return L["%s: none up -- %s is the one to cast."]:format(label, ns.BuffName(spell))
elseif why == "off" then
return L["%s: switched off (Don't remind me)."]:format(label)
elseif why == "up" and not name and family.enhance then
-- An enchant none of this family's items makes: the weapon is seen to.
return L["%s: the weapon already carries a temporary enchant."]:format(label)
elseif why == "up" and not name and family.imbue then
-- An oil, or an enchant no scroll makes: the weapon is seen to.
return L["%s: your main hand already carries a temporary enchant."]:format(label)
elseif why == "up" or why == "covered" then
-- "covered": somebody else's copy of it reaches you (a shared
-- family, Core.lua OwnAutoPick), and a second would not stack.
return L["%s: %s is up."]:format(label, name or "?")
elseif why == "bags" then
return L["%s: you have no %s in your bags."]:format(label, name or "?")
elseif why == "level" then
return L["%s: %s needs level %d."]:format(label, name or "?", about.level)
elseif why == "noweapon" and family.enhance then
-- The label names the hand.
return L["%s: there is no weapon in that hand."]:format(label)
elseif why == "noweapon" then
return L["%s: there is no weapon in your main hand."]:format(label)
elseif why == "weapon" and family.enhance then
return L["%s: %s does not fit the weapon in that hand."]:format(label, name or "?")
elseif why == "weapon" then
return L["%s: %s does not fit the weapon in your main hand."]:format(label, name or "?")
elseif why == "notank" then
return L["%s: Automatic, and your group role is not tank, so it is not offered."]:format(label)
elseif why == "tried" then
return L["%s: %s was pressed or skipped a moment ago."]:format(label, name or "?")
elseif why == "unusable" then
return L["%s: the game says %s cannot be cast right now."]:format(label, name or "?")
elseif why == "none" then
return L["%s: Automatic has nothing it would pick."]:format(label)
end
return L["%s: the game will not say whether it is up, so it is not offered."]:format(label)
end
function ns.MyselfLines(now)
local db = addon.db and addon.db.profile
local out = {}
if not db or db.sources.self ~= true then return out end
local families = ns.KnownOwnFamilies()
if #families == 0 and #ns.SelfBuffs() == 0 then return out end
local held = ns.MyselfHeldBack(db, now)
if held == "resting" then
out[#out + 1] = L["your own buffs: held back -- you are in a city or an inn, and %s is off."]
:format("|cffffd100" .. L["Also in cities and inns"] .. "|r")
elseif held then
out[#out + 1] = HELD[held]
end
-- On your own never-offer list nothing is offered to you, so no family
-- below would be "the one to cast": the line above says why, and is all.
if held == "listed" then return out end
-- Your group buff is due: the lines below wait behind it.
local first = #families > 0 and ns.SelfBuffFirst(db, now)
if first then
out[#out + 1] = L["your own %s comes first -- the buffs below wait until it has been cast."]
:format(ns.BuffName(first))
end
local ctx = { name = ns.UnitFullName("player"), now = now,
whenBuffed = db.filters.whenBuffed, refreshUnder = db.filters.refreshUnder }
for _, family in ipairs(families) do out[#out + 1] = FamilyLine(family, ctx) end
return out
end
end
-- The sentence for a character that will never have anything to offer, shared
-- by /manners debug and the greeting. Translators: the greeting and the login
-- line carry their own copy inside a longer key, kept in step by hand.
ns.NO_CLASS_BUFFS = L["this class has no buffs to cast on other players."]
-- Returns true once it has said its piece, false while it is still waiting
-- (for a probe answer, or a fight to end). `force` is /manners welcome;
-- `offSaid` is the login line having just said the profile is switched off.
function ns.Welcome(force, offSaid)
local store = addon.db and addon.db.char
if type(store) ~= "table" then return false end
if store.welcomed and not force then return true end
-- The probe's verdict on this character. Indexed off caps.class, so a
-- class not read (one secret value away on Forever and retail) is "not on
-- the list" and meets the gate below with everything else that is no
-- answer.
local nothingToGive = caps.class ~= nil and ns.CLASSES_WITHOUT_BUFFS ~= nil
and ns.CLASSES_WITHOUT_BUFFS[caps.class] == true
-- ...and of those, a hunter or a shaman with a buff of his own learned,
-- whose prompt reminds him of it: greeted with the prompt, not sent off.
local ownOnly = nothingToGive and (caps.anyOwnKnown == true or ns.OwnItemsHeld())
if ownOnly then nothingToGive = false end
-- Not until the probe has an answer. hasClassBuffs is false for a rogue,
-- for a class the client would not name, and for one an unrecognised
-- client's guessed buff data does not know; greeting the last two with
-- "no buffs" would state a guess as fact. Nothing is written down and the
-- next login asks again; /manners debug says which case it is.
if not (caps.hasClassBuffs or nothingToGive or ownOnly) then return false end
-- Not in a fight: a protected frame cannot be shown during lockdown, and
-- PLAYER_REGEN_ENABLED comes back for it. Except for the class with no
-- picture: words work in a fight.
if InCombatLockdown() and not nothingToGive then
if force then
addon:Print(L["|cffff8080not during a fight|r -- the prompt cannot be put on screen while one is on. Try again when it ends."])
end
return false
end
-- Written down before a word is printed: a line that throws then costs a
-- short greeting once rather than on every login.
store.welcomed = true
if nothingToGive then
-- No preview and no macro for a class that can never fill the prompt.
addon:Print(L["|cffffd100Manners|r is installed, but this class has no buffs to cast on other players."])
addon:Print(L["It is still worth keeping for an alt that does -- it will say hello again there."])
return true
end
-- Spells learned, but nothing any prompt will offer (all switched off, or
-- a pin on one not learned): name the setting instead of the tour. Not for
-- a character with nothing learned yet, who will learn a spell soon; nor
-- for one whose own buffs still put a prompt up, who gets the tour for it.
local othersOff = caps.anyKnown and not ns.ResolveBuff(true)
local ownLive = ns.OwnBuffsLive()
if othersOff and not ownLive then
addon:Print(L["|cffffd100Manners|r is installed, but nothing will be offered to anybody: %s."]
:format(ns.NothingToCast()))
addon:Print(L["|cffffd100/manners welcome|r brings the rest of this back once that changes."])
return true
end
-- A hunter or shaman with Myself (or every one of his own buffs) switched
-- off, perhaps by another character on the shared profile: no prompt will
-- ever come, so no tour and no preview of one. The launcher says the same.
if ownOnly and not ownLive then
addon:Print(L["Nothing to do: your own buffs are switched off under %s."]:format(L["Myself"]))
addon:Print(L["|cffffd100/manners welcome|r brings the rest of this back once that changes."])
return true
end
-- A class whose buffs reach only the party has no passer-by to offer to,
-- and one with nothing for anybody else has only itself.
if ownOnly then
addon:Print(L["|cffffd100Manners|r puts your own buffs on a small prompt when none of them is up -- your class has none for other players. Clicking the prompt casts it on you."])
elseif othersOff then
-- Your spells for others all switched off, and yours still offered.
addon:Print(L["|cffffd100Manners|r puts your own buffs on a small prompt when none of them is up; nothing is offered to anybody else: %s. Clicking the prompt casts it on you."]
:format(ns.NothingToCast()))
elseif ns.OnlyReachesGroup() then
local buff = ns.ResolveBuff(true)
if buff then
addon:Print(L["|cffffd100Manners|r puts anybody in your group who is missing your |cffffd100%s|r -- or who has just buffed you -- on a small prompt. Clicking the prompt casts it."]
:format(ns.BuffName(buff)))
else
addon:Print(L["|cffffd100Manners|r puts anybody in your group who is missing your |cffffd100buff|r -- or who has just buffed you -- on a small prompt. Clicking the prompt casts it."])
end
else
addon:Print(L["|cffffd100Manners|r puts anybody who buffs you -- and any stranger nearby who is missing one of yours -- on a small prompt. Clicking the prompt buffs them."])
end
addon:Print(L["The one thing that is not automatic: |cffffd100/manners macro|r or |cffffd100Make a macro|r in the options makes a macro for your bars, or bind a key under Options > Keybindings > Manners."])
-- Switched off (perhaps by another character, on the shared profile): name
-- the setting, unless the login line said so one line above.
if addon.db.profile and not addon.db.profile.enabled and not offSaid then
addon:Print(L["|cffff8080It is switched off on this profile|r, so no prompt will appear -- |cffffd100/manners on|r when you want it."])
end
-- Point at whichever panel will be on screen: somebody real already queued,
-- or the preview. Only somebody who can really be on the panel counts:
-- switched off, unlocked or snoozed, the queue fills but the button shows no
-- one, and the preview runs in all three.
local queued = 0
local profile = addon.db.profile
if profile and profile.enabled and profile.prompt.locked and not ns.SnoozeLeft() then
local ok, list = pcall(ns.BuildQueue)
if ok and type(list) == "table" then queued = #list end
end
if queued > 0 then
addon:Print(L["The prompt is on screen now, with somebody real on it already. |cffffd100/manners welcome|r brings this back."])
else
-- The existing preview: the real panel in its real place. ToggleTest is
-- a toggle, so only when none is running. The nil test is inside the
-- guard: ns.Prompt is nil when Prompt/Prompt.lua did not load.
ns.Guard("welcome preview", function()
if ns.Prompt and not ns.Prompt:InTest() then ns.Prompt:ToggleTest() end
end)
addon:Print(L["That is the prompt, with a pretend name on it. |cffffd100/manners welcome|r brings this back."])
end
return true
end
---------------------------------------------------------------------------
-- test console
--
-- Iterating on this client otherwise means one guess per /reload. /manners
-- try arms arbitrary macro text on the prompt; /manners look dumps every API
-- answer for a unit, including which come back as secret values. Everything
-- printed also lands in SavedVariables, to be read off disk afterwards.
---------------------------------------------------------------------------
ns.console = {}
local function say(fmt, ...)
local line = select("#", ...) > 0 and fmt:format(...) or fmt
addon:Print(line)
ns.console[#ns.console + 1] = line
while #ns.console > 60 do table.remove(ns.console, 1) end
end
ns.Say = say
-- Reports the value, and separately whether the client refused to show it.
-- "false" and "withheld" look identical once plain() has run, and telling them
-- apart is most of the work on this client.
local function show(label, ok, value)
if not ok then return ("%s=|cff808080n/a|r"):format(label) end
if issecretvalue and issecretvalue(value) then
return ("%s=|cffff8080SECRET|r"):format(label)
end
if value == nil then return ("%s=|cff808080nil|r"):format(label) end
return ("%s=|cffffffff%s|r"):format(label, tostring(value))
end
local function raw(fn, ...)
if type(fn) ~= "function" then return false end
local results = { pcall(fn, ...) }
if not results[1] then return false end
return true, results[2], results[3]
end
function ns.InspectUnit(unit)
unit = unit or (ns.lastTopUnit or "target")
say("|cffffd100--- %s ---|r", unit)
local okExists, exists = raw(UnitExists, unit)
if not okExists or not plain(exists) then
say(" %s", L["does not exist (or its existence is withheld)"])
return
end
local _, n1, n2 = raw(UnitName, unit)
local _, c1, c2 = raw(UnitClass, unit)
say(" %s %s", show("name", true, n1), show("second", true, n2))
say(" %s %s", show("class", true, c2), show("classLocalised", true, c1))
say(" %s", show("guid", raw(UnitGUID, unit)))
say(" %s %s %s",
show("isPlayer", raw(UnitIsPlayer, unit)),
show("canAssist", raw(UnitCanAssist, "player", unit)),
show("dead", raw(UnitIsDeadOrGhost, unit)))
say(" %s %s %s",
show("connected", raw(UnitIsConnected, unit)),
show("inParty", raw(UnitInParty, unit)),
show("inRaid", raw(UnitInRaid, unit)))
say(" %s %s %s",
show("level", raw(UnitLevel, unit)),
show("powerMax", raw(UnitPowerMax, unit, MANA)),
show("power", raw(UnitPower, unit, MANA)))
say(" %s %s",
show("pvp", raw(UnitIsPVP, unit)),
show("pvpFreeForAll", raw(UnitIsPVPFreeForAll, unit)))
if C_Secrets and C_Secrets.ShouldUnitIdentityBeSecret then
say(" %s", show("identitySecret", raw(C_Secrets.ShouldUnitIdentityBeSecret, unit)))
end
local buff = ns.ResolveBuff(true)
if buff then
local info = ns.BuffInfo(buff)
local id = info and info.topRank
-- Taken before an `and` could collapse raw()'s two returns into one.
local okById, byId
if id then okById, byId = raw(C_Spell and C_Spell.IsSpellInRange, id, unit) end
say(" %s %s",
show("inRangeById", okById, byId),
show("inRangeByName", raw(C_Spell and C_Spell.IsSpellInRange, ns.BuffName(buff), unit)))
if C_UnitAuras and C_UnitAuras.GetUnitAuraBySpellID then
-- Refusals kept apart from absence, the way UnitHasBuff keeps them.
local found
local withheld = {}
local unreadable = info and info.readable == false
for _, auraId in ipairs(buff.auraIds) do
local ok, aura = raw(C_UnitAuras.GetUnitAuraBySpellID, unit, auraId)
if ok and aura ~= nil and not (issecretvalue and issecretvalue(aura)) then
found = auraId
break
elseif not ok or (issecretvalue and issecretvalue(aura))
or (info and info.secrecy and info.secrecy[auraId] == true) then
withheld[#withheld + 1] = tostring(auraId)
end
end
if not found and (unreadable or #withheld > 0) then
say(" %s |cff808080%s|r", show("hasBuff", false), L["withheld: %s"]:format(
#withheld > 0 and table.concat(withheld, ", ") or L["this buff is not readable here"]))
else
say(" %s", show("hasBuff", true, found or false))
end
end
end
say(" %s", show("isNameplate", true, ns.nameplateUnits[unit] and true or false))
-- The verdict on this person, and which source took it and how often it
-- answers.
say(" %s", show("nearEnough", true, ns.NearEnough(unit, true)))
say(" proximity: %s", tostring(ns.ProximitySummary()))
end
-- Tokens so a test can name the current candidate without typing its name.
-- "target" stands in only when there is no candidate at all. A {unit} that
-- cannot be filled is not guessed at: this returns nil and the reason, and
-- the prompt leaves the button empty and says why.
function ns.ExpandTokens(text)
local entry = ns.lastTopEntry
local buff = entry and entry.buff or ns.ResolveBuff(true)
local info = buff and ns.BuffInfo(buff)
if entry and not entry.unit and text:find("{unit}", 1, true) then
return nil, L["%s has no unit token right now, so {unit} cannot be filled"]:format(
tostring(entry.targetName or entry.name))
end
text = ns.Swap(text, "{unit}", (entry and entry.unit) or "target")
text = ns.Swap(text, "{name}", (entry and entry.name) or "target")
-- {aim} is the spelling a targeting line wants (off Camelot, without the
-- realm); {name} stays the identity a debt is filed under.
text = ns.Swap(text, "{aim}", (entry and (entry.targetName or entry.name)) or "target")
-- FirstName answers nil for a one-word name, which is then the whole name.
text = ns.Swap(text, "{first}", entry
and (ns.FirstName(entry.name) or entry.targetName or entry.name) or "target")
text = ns.Swap(text, "{spell}", buff and ns.BuffName(buff))
text = ns.Swap(text, "{id}", tostring(info and info.topRank or ""))
return text
end
---------------------------------------------------------------------------
-- snooze
--
-- Keeping the prompt away for a while without switching the addon off. Off is
-- saved in the profile for every alt; a snooze lives in this session only, and
-- a /reload ends it. Favours are still noticed meanwhile.
--
-- The prompt is a secure frame and cannot be taken down in a fight, so a
-- snooze started in one takes effect when the fight ends: Prompt:Refresh reads
-- it below its combat branch.
---------------------------------------------------------------------------
ns.SNOOZE_CHOICES = { 5, 15, 30 }
ns.SNOOZE_DEFAULT = 15
ns.SNOOZE_MAX = 240
-- On GetTime's clock, like every other expiry here; the wall clock only
-- where the player reads the answer.
local snoozeUntil
function ns.SnoozeLeft(now)
if not snoozeUntil then return nil end
local left = snoozeUntil - (now or GetTime())
if left <= 0 then return nil end
return left
end
-- Whether the player's clock is a 12-hour one, as the game clock by the
-- minimap reads it. A client that will not answer gets the 24-hour clock.
local function TwelveHourClock()
local get = _G.GetCVar
if type(get) ~= "function" then return false end
local ok, value = pcall(get, "timeMgrUseMilitaryTime")
return ok and plain(value) == "0"
end
-- A time on a 12-hour clock as the client writes it in its own language, from
-- TIME_TWELVEHOURAM and TIME_TWELVEHOURPM, the strings Blizzard's GameTime
-- code formats the game clock's tooltip with ("%d:%02d AM", but "오전 %d:%02d"
-- in Korean, "%d:%02d a.m." in Spanish). English where the client has none.
local function TwelveHourText(hour, minute)
local twelve = hour % 12
if twelve == 0 then twelve = 12 end
local late = hour >= 12
local text = _G[late and "TIME_TWELVEHOURPM" or "TIME_TWELVEHOURAM"]
if type(text) == "string" then
local ok, out = pcall(text.format, text, twelve, minute)
if ok then return out end
end
return ("%d:%02d %s"):format(twelve, minute, late and "PM" or "AM")
end
-- When the snooze ends, on the clock on the player's screen.
function ns.SnoozeEndsAt()
local left = ns.SnoozeLeft()
if not left then return nil end
-- The minimap clock shows realm time unless the player ticked Local Time.
local get, realm = _G.GetCVar, _G.GetGameTime
local ok, useLocal = false, nil
if type(get) == "function" then ok, useLocal = pcall(get, "timeMgrUseLocalTime") end
if ok and plain(useLocal) == "0" and type(realm) == "function" then
local read, h, m = pcall(realm)
h, m = plain(h), plain(m)
if read and type(h) == "number" and type(m) == "number" then
local total = (h * 60 + m + math.floor(left / 60 + 0.5)) % 1440
local hour, minute = math.floor(total / 60), total % 60
if TwelveHourClock() then return TwelveHourText(hour, minute) end
return ("%02d:%02d"):format(hour, minute)
end
end
local at = time() + math.floor(left + 0.5)
if TwelveHourClock() then
local when = date("*t", at)
if type(when) == "table" and type(when.hour) == "number" and type(when.min) == "number" then
return TwelveHourText(when.hour, when.min)
end
end
return date("%H:%M", at)
end
-- Translators: "1 minute" is a whole string of its own, not an "s" glued on.
function ns.MinutesText(minutes)
if minutes == 1 then return L["1 minute"] end
return L["%d minutes"]:format(minutes)
end
-- What every route into a snooze says (slash command, minimap, options page).
local function SaySnoozeStarted(minutes)
local db = addon.db.profile
if not db.enabled then
-- Started anyway, and said so: the snooze outlives a /manners on.
addon:Print(L["snoozed for %s, until %s -- though Manners is switched off, so no prompt appears either way."]
:format(ns.MinutesText(minutes), ns.SnoozeEndsAt()))
elseif InCombatLockdown() then
-- Not "it goes when the fight ends": a panel the fight found up stays.
addon:Print(L["snoozed for %s, until %s. In a fight the prompt stays as the fight found it, and follows the snooze once this one ends. |cffffd100/manners snooze off|r ends it early."]
:format(ns.MinutesText(minutes), ns.SnoozeEndsAt()))
elseif not db.prompt.locked then
-- An unlocked prompt stays up through a snooze as something to drag.
addon:Print(L["snoozed for %s, until %s. The prompt is unlocked, so it stays up to be dragged and casts nothing; once you lock it, it stays away until the snooze ends. |cffffd100/manners snooze off|r ends it early."]
:format(ns.MinutesText(minutes), ns.SnoozeEndsAt()))
else
addon:Print(L["snoozed for %s -- no prompt until %s. |cffffd100/manners snooze off|r ends it early."]
:format(ns.MinutesText(minutes), ns.SnoozeEndsAt()))
end
end
-- The line for a snooze that has ended, however it ended, saying what the
-- prompt does next.
local function SnoozeOverText()
local db = addon.db.profile
if not db.enabled then
return L["the snooze is over, but Manners is switched off -- |cffffd100/manners on|r to see the prompt again."]
elseif InCombatLockdown() then
return L["the snooze is over -- the prompt can appear again once this fight ends."]
end
return L["the snooze is over -- the prompt can appear again."]
end
-- Units a length can be typed in, as minutes each: "15", "15m", "1h".
local SNOOZE_UNITS = {
[""] = 1, m = 1, min = 1, mins = 1, minute = 1, minutes = 1,
h = 60, hr = 60, hrs = 60, hour = 60, hours = 60,
}
-- Minutes from what was typed after /manners snooze, or nil when it is not a
-- length. Not checked against the range: the caller says what the range is.
function ns.SnoozeLength(text)
local number, unit = tostring(text or ""):lower():match("^%s*(%d*%.?%d+)%s*(%a*)%s*$")
local scale = unit and SNOOZE_UNITS[unit]
if not scale then return nil end
local minutes = tonumber(number)
if not minutes then return nil end
return math.floor(minutes * scale + 0.5)
end
-- Start a snooze of `minutes`, replacing any snooze already running rather
-- than adding to it: "snooze 5" means five minutes from now.
function ns.StartSnooze(minutes)
minutes = math.floor(tonumber(minutes) or ns.SNOOZE_DEFAULT)
minutes = math.max(1, math.min(ns.SNOOZE_MAX, minutes))
snoozeUntil = GetTime() + minutes * 60
-- Refresh decides for itself what it may do in a fight, and in one it
-- leaves the panel exactly as the fight found it.
ns.Guard("snooze", ns.Prompt.Refresh, ns.Prompt)
SaySnoozeStarted(minutes)
ns.RepaintOptions()
return minutes
end
function ns.StopSnooze(quiet)
local was = ns.SnoozeLeft() ~= nil
snoozeUntil = nil
if was then
ns.Guard("snooze", ns.Prompt.Refresh, ns.Prompt)
ns.RepaintOptions()
end
if not quiet then
addon:Print(was and SnoozeOverText() or L["not snoozed -- the prompt is free to appear."])
end
return was
end
-- From the scan: a snooze that has run out ends here, and says so only if the
-- player asked to be told what the addon is doing.
function ns.EndSnoozeIfDue(now)
if not snoozeUntil or snoozeUntil > (now or GetTime()) then return end
snoozeUntil = nil
if addon.db.profile.verbose then addon:Print(SnoozeOverText()) end
ns.RepaintOptions()
end
---------------------------------------------------------------------------
-- sharing settings
--
-- /manners export hands over the current profile as one line of text, and
-- /manners import (or the box on the Profiles tab) reads one back. Only
-- differences from the defaults are written.
--
-- Plain text read with string functions, never loadstring: this is text a
-- stranger pasted into a forum. Every name is looked up in a list built from
-- the defaults, every value must have its default's type, anything else is
-- refused before a setting is touched, and what survives goes through
-- ClampSettings like a saved profile at login.
--
-- MNR1:prompt.width=260;prompt.fontColor=1,0.8,0,1;buff.skip=wisdom:5f3a9c
--
-- A version, the name=value pairs, and a checksum over both, so a string cut
-- short is refused rather than half applied.
---------------------------------------------------------------------------
ns.SHARE_PREFIX = "MNR1:"
local SHARE_VERSION = 1
-- A ceiling on the work a hostile string can ask for, set well above what a
-- real profile holds (a long phrase box included), so the player's own export
-- always reads back. /manners export warns past it.
local SHARE_MAX = 64000
-- Everything below is private to this block and reached through ns, for the
-- same Lua 5.1 local limit as the friends section's.
do
-- Never shared: the on switch is a state, not a taste; the click logger is a
-- diagnostic; the minimap button's place is about this screen; the chat
-- lines are a personal noise preference, like the minimap button. The
-- Profiles tab promises a paste keeps all four. The never-offer list is
-- real players' names, each put there by hand: not for a line handed to
-- somebody, and kept through a paste as the page's reset keeps it. Its
-- default is empty, so the walk never found it; named here so that is a
-- decision rather than an accident.
local SHARE_SKIP = { enabled = true, debugClicks = true, never = true, minimap = true, verbose = true }
-- The same further down. The lock is a state, and a string copied while the
-- prompt was unlocked would unlock everybody's, and an unlocked prompt never
-- casts. Where the prompt sits is about the screen.
local SHARE_SKIP_NAMES = {
["prompt.locked"] = true,
["prompt.point"] = true,
["prompt.relPoint"] = true,
["prompt.x"] = true,
["prompt.y"] = true,
}
-- Imported only when the player already has it on: a pasted string must never
-- switch on speaking to other players, nor the /thank everybody near sees
-- (off by default for that reason). Each names what the import then says.
local SHARE_KEEP_MINE = { ["speech.enabled"] = "switch", ["prompt.thankEmote"] = "thank" }
-- What is said and where, kept as the player has it whenever speaking is on,
-- so a paste cannot start yelling a stranger's words. With speaking off they
-- travel, changing nothing anybody hears.
local SHARE_SPEECH = {
["speech.channel"] = true,
["speech.phrases"] = true,
["speech.presetChoice"] = true,
["speech.onlyWhenReturning"] = true,
}
-- Defaults that are not a constant: the phrase box is filled from the chosen
-- set at load.
local SHARE_DEFAULT = {
["speech.phrases"] = function(profile)
local speech = profile.speech or {}
return ns.PhraseSetText(speech.presetChoice) or ns.PhraseSetText("roleplay")
end,
}
local shareFields
-- Every setting that can be shared, walked out of the defaults table, so a
-- new setting is shareable as soon as it has a default.
local function ShareFields()
if shareFields then return shareFields end
local fields = {}
local function walk(defs, path, prefix)
for key, value in pairs(defs) do
if type(key) == "string" and not (prefix == "" and SHARE_SKIP[key])
and not SHARE_SKIP_NAMES[prefix .. key] then
local name = prefix .. key
local kind
if type(value) == "table" then
if type(value[1]) == "number" then
kind = "colour"
elseif name == "buff.skip" then
kind = "set"
elseif name == "filters.skipRaidGroups" then
-- A set too, of group numbers rather than names. Its
-- default is empty, so the walk below found nothing in
-- it and the groups switched off never travelled.
kind = "groups"
else
local inner = {}
for i = 1, #path do inner[i] = path[i] end
inner[#inner + 1] = key
walk(value, inner, name .. ".")
end
elseif type(value) == "boolean" or type(value) == "number"
or type(value) == "string" then
kind = type(value)
end
if kind then
fields[#fields + 1] = { name = name, kind = kind, path = path, key = key,
default = value }
end
end
end
end
walk(ns.defaults.profile, {}, "")
-- The phrase set's dropdown has no default (nil reads as Roleplay), so the
-- walk cannot find it.
fields[#fields + 1] = { name = "speech.presetChoice", kind = "string",
path = { "speech" }, key = "presetChoice" }
table.sort(fields, function(a, b) return a.name < b.name end)
shareFields = fields
return fields
end
local function Holder(profile, path, create)
local t = profile
for _, seg in ipairs(path) do
if type(t[seg]) ~= "table" then
if not create then return nil end
t[seg] = {}
end
t = t[seg]
end
return t
end
local function Finite(n)
return type(n) == "number" and n == n and n ~= math.huge and n ~= -math.huge
end
local function NumberText(n)
return ("%.10g"):format(n)
end
-- Anything but letters, digits and a little punctuation is written as %XX, and
-- a space as +: no separator (; = : ,) or chat escape (|) survives, and with
-- no spaces a line break a text box inserts can be stripped on the way in.
-- A line break goes as LF alone, and no other control character goes at all:
-- DecodeText refuses them, and a CR in the phrase box (a saved file can hold
-- one) made the player's own export a string nothing could read.
local function EncodeText(s)
s = s:gsub("\r\n?", "\n"):gsub("[%z\1-\8\11-\31\127]", "")
return (s:gsub("[^%w_%.%-!%?'%(%){}/ ]", function(c)
return ("%%%02X"):format(c:byte())
end):gsub(" ", "+"))
end
local function DecodeText(s)
-- Every % has to open a pair of hex digits; EncodeText never writes a lone one.
if s:gsub("%%%x%x", ""):find("%", 1, true) then return nil end
local text = s:gsub("%+", " "):gsub("%%(%x%x)", function(hex)
return string.char(tonumber(hex, 16))
end)
-- A CR is a line break too: up to 1.6.1 an export wrote the phrase box's
-- CRs as they were, and that string is still the player's own.
text = text:gsub("\r\n?", "\n")
-- No control characters, except a line break (one phrase per line) and a
-- tab, which a text box takes and ExportSettings therefore writes.
for i = 1, #text do
local b = text:byte(i)
if (b < 32 and b ~= 10 and b ~= 9) or b == 127 then return nil end
end
return text
end
local function ReadNumber(s)
if not s:match("^[%d%.%-%+eE]+$") then return nil end
local n = tonumber(s)
if not Finite(n) then return nil end
return n
end
local function DefaultOf(field, profile)
local fn = SHARE_DEFAULT[field.name]
if fn then return fn(profile) end
return field.default
end
-- A field's value as text, or nil when it is the default and need not travel.
local function EncodeValue(field, value, profile)
local kind = field.kind
if kind == "boolean" then
if type(value) ~= "boolean" or value == field.default then return nil end
return value and "1" or "0"
elseif kind == "number" then
if not Finite(value) or value == field.default then return nil end
return NumberText(value)
elseif kind == "string" then
if type(value) ~= "string" or value == DefaultOf(field, profile) then return nil end
return EncodeText(value)
elseif kind == "colour" then
if type(value) ~= "table" then return nil end
local parts, same = {}, true
for i = 1, 4 do
local c = value[i]
if c == nil and i == 4 then break end
if not Finite(c) then return nil end
parts[i] = NumberText(c)
if c ~= field.default[i] then same = false end
end
if same and #parts == #field.default then return nil end
return table.concat(parts, ",")
elseif kind == "set" then
if type(value) ~= "table" then return nil end
local keys = {}
for key, on in pairs(value) do
if on == true and type(key) == "string" and key:match("^[%w_]+$") then
keys[#keys + 1] = key
end
end
if #keys == 0 then return nil end
table.sort(keys)
return table.concat(keys, ",")
elseif kind == "groups" then
if type(value) ~= "table" then return nil end
local groups = {}
for group = 1, 8 do
if value[group] == true then groups[#groups + 1] = tostring(group) end
end
if #groups == 0 then return nil end
return table.concat(groups, ",")
end
end
local function DecodeValue(field, raw)
local kind = field.kind
if kind == "boolean" then
if raw == "1" then return true elseif raw == "0" then return false end
return nil
elseif kind == "number" then
return ReadNumber(raw)
elseif kind == "string" then
return DecodeText(raw)
elseif kind == "colour" then
local out = {}
for part in (raw .. ","):gmatch("([^,]*),") do
local n = ReadNumber(part)
if not n or #out >= 4 then return nil end
out[#out + 1] = math.max(0, math.min(1, n))
end
if #out < 3 then return nil end
return out
elseif kind == "set" then
local out, count = {}, 0
for part in (raw .. ","):gmatch("([^,]*),") do
if not part:match("^[%w_]+$") then return nil end
count = count + 1
if count > 64 then return nil end
out[part] = true
end
return out
elseif kind == "groups" then
-- A raid has eight groups; anything else is not one.
local out = {}
for part in (raw .. ","):gmatch("([^,]*),") do
if not part:match("^[1-8]$") then return nil end
out[tonumber(part)] = true
end
return out
end
end
local function Checksum(text)
local h = 0
for i = 1, #text do h = (h * 31 + text:byte(i)) % 16777213 end
return ("%06x"):format(h)
end
function ns.ExportSettings()
local profile = addon.db and addon.db.profile
if not profile then return nil end
local parts = {}
for _, field in ipairs(ShareFields()) do
local holder = Holder(profile, field.path)
local text = holder and EncodeValue(field, holder[field.key], profile)
if text then parts[#parts + 1] = field.name .. "=" .. text end
end
local signed = ns.SHARE_PREFIX .. table.concat(parts, ";")
return signed .. ":" .. Checksum(signed)
end
-- Why a string was refused, one sentence each, each one something the player
-- can act on.
ns.SHARE_ERRORS = {
empty = L["there is nothing to import -- paste a settings string that starts with MNR1:."],
notOurs = L["that is not a Manners settings string -- one starts with MNR1:."],
tooLong = L["that is far longer than any Manners settings string, so it was not read."],
newer = L["that string was made by a newer version of Manners -- update the addon to read it."],
incomplete = L["that string is incomplete or has been changed -- copy it again in one piece, and paste a long one into the box under Share as text on the Profiles tab of the options."],
malformed = L["that string is damaged -- part of it is not a setting Manners can read. Copy it again in one piece."],
badValue = L["that string gives %s a value it cannot have, so nothing was changed."],
}
-- Read a settings string without touching anything. Returns the values keyed
-- by field name and how many names this version does not know, or nil and the
-- sentence saying why not. `cap` is the longest string it will read.
local function Parse(text, cap)
if type(text) ~= "string" then return nil, ns.SHARE_ERRORS.empty end
if #text > cap * 2 then return nil, ns.SHARE_ERRORS.tooLong end
-- No setting's text holds whitespace (a space travels as +), so any here
-- was added on the way: a wrapped line, or blanks around a paste.
text = text:gsub("%s+", "")
if text == "" then return nil, ns.SHARE_ERRORS.empty end
if #text > cap then return nil, ns.SHARE_ERRORS.tooLong end
local version, body, sum = text:match("^MNR(%d+):(.*):(%x+)$")
if not version then
if text:sub(1, 3) == "MNR" then return nil, ns.SHARE_ERRORS.incomplete end
return nil, ns.SHARE_ERRORS.notOurs
end
if tonumber(version) ~= SHARE_VERSION then
if (tonumber(version) or 0) > SHARE_VERSION then return nil, ns.SHARE_ERRORS.newer end
return nil, ns.SHARE_ERRORS.notOurs
end
if Checksum("MNR" .. version .. ":" .. body) ~= sum:lower() then
return nil, ns.SHARE_ERRORS.incomplete
end
local byName = {}
for _, field in ipairs(ShareFields()) do byName[field.name] = field end
local values, unknown, count = {}, 0, 0
if body ~= "" then
for pair in (body .. ";"):gmatch("([^;]*);") do
local name, raw = pair:match("^([%w_%.]+)=(.*)$")
if not name then return nil, ns.SHARE_ERRORS.malformed end
local field = byName[name]
if field then
local value = DecodeValue(field, raw)
if value == nil then return nil, ns.SHARE_ERRORS.badValue:format(name) end
if values[name] == nil then count = count + 1 end
values[name] = value
elseif SHARE_SKIP[name:match("^[^%.]*")] or SHARE_SKIP_NAMES[name] then
-- A setting this version knows and keeps out of a paste,
-- dropped without a word: 1.4.0 wrote verbose=0 into its
-- strings, and calling that a newer version's setting is
-- a sentence the player can do nothing about.
elseif (ns.OWN_FAMILY_ANY_CLIENT or {})[name:match("^ownBuffs%.pick%.([%w_]+)$") or ""] then
-- Another game client's own buff (an Omen of Clarity pick
-- read on Forever): the same version made it, so nothing
-- newer exists to send the player looking for.
else
-- A setting a later version added: skipped, not refused.
unknown = unknown + 1
end
end
end
return { values = values, unknown = unknown, count = count }
end
-- Anything pasted or typed is read under the ceiling.
function ns.ParseSettings(text)
return Parse(text, SHARE_MAX)
end
-- The settings the last import replaced, in the shape Parse returns, for this
-- session, and the profile they came off: its table (AceDB hands back the same
-- table on returning to a profile) and its name, for the line that says so.
local lastImportUndo, undoProfile, undoProfileName
local function ProfileName()
local db = addon.db
if not db or type(db.GetCurrentProfile) ~= "function" then return nil end
local ok, name = pcall(db.GetCurrentProfile, db)
if ok and type(name) == "string" then return name end
return nil
end
function ns.ForgetImportUndo()
lastImportUndo, undoProfile, undoProfileName = nil, nil, nil
end
-- What a change of profile does to the undo. A switch leaves it with the
-- profile it was made on, waiting for the player to come back. A copy or reset
-- of that profile, or deleting it, ends it, and so does arriving at its name
-- with a different table: the profile made again from nothing.
function ns.ProfileChangedForUndo(event, name)
if not lastImportUndo then return end
local here = addon.db and addon.db.profile
if event == "OnProfileChanged" then
if here ~= undoProfile and undoProfileName and ProfileName() == undoProfileName then
ns.ForgetImportUndo()
end
elseif event == "OnProfileDeleted" then
if name ~= nil and name == undoProfileName then ns.ForgetImportUndo() end
elseif here == undoProfile then
ns.ForgetImportUndo()
end
end
local function CopyValue(v)
if type(v) ~= "table" then return v end
local out = {}
for k, inner in pairs(v) do out[k] = inner end
return out
end
local function SameValue(a, b)
if type(a) ~= "table" or type(b) ~= "table" then return a == b end
for k, v in pairs(a) do if b[k] ~= v then return false end end
for k, v in pairs(b) do if a[k] ~= v then return false end end
return true
end
-- Write a parsed string over the current profile; everything it does not name
-- goes back to its default. `own` is the undo, the player's own settings put
-- back exactly; anything else keeps speaking and the /thank as the player
-- has them. Returns what was kept back.
local function ApplySettings(profile, parsed, own)
local speaking = profile.speech and profile.speech.enabled == true
local kept = { switch = false, thank = false, words = false }
for _, field in ipairs(ShareFields()) do
local holder = Holder(profile, field.path, true)
local value = parsed.values[field.name]
if value == nil then value = CopyValue(field.default) end
if not own and SHARE_KEEP_MINE[field.name] then
if value == true and holder[field.key] ~= true then kept[SHARE_KEEP_MINE[field.name]] = true end
elseif not own and speaking and SHARE_SPEECH[field.name] then
-- Only what the string actually names counts as kept back.
if parsed.values[field.name] ~= nil
and not SameValue(parsed.values[field.name], holder[field.key]) then
kept.words = true
end
else
holder[field.key] = value
end
end
-- What a profile switch runs, since every setting changed at once. Safe in
-- a fight: ApplyStyle waits for the fight to end. It also forgets the
-- undo, which each caller then sets as it needs.
addon:RefreshConfig()
return kept