-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBulkMailInbox.lua
More file actions
1476 lines (1319 loc) · 58.6 KB
/
BulkMailInbox.lua
File metadata and controls
1476 lines (1319 loc) · 58.6 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
BulkMailInbox = LibStub("AceAddon-3.0"):NewAddon("BulkMailInbox", "AceConsole-3.0", "AceEvent-3.0", "AceTimer-3.0", "AceHook-3.0")
local mod, self, BulkMailInbox = BulkMailInbox, BulkMailInbox, BulkMailInbox
local VERSION = " @project-version@"
local LibStub = LibStub
local L = LibStub("AceLocale-3.0"):GetLocale("BulkMailInbox", false)
BulkMailInbox.L = L
local media = LibStub("LibSharedMedia-3.0")
local abacus = LibStub("LibAbacus-3.0")
local QTIP = LibStub("LibQTip-1.0")
local AC = LibStub("AceConfig-3.0")
local ACD = LibStub("AceConfigDialog-3.0")
local DB = LibStub("AceDB-3.0")
local LDB = LibStub("LibDataBroker-1.1", true)
local LD = LibStub("LibDropdown-1.0")
local MagicUtil = LibStub("LibMagicUtil-1.0")
local _G = _G
local fmt = string.format
local lower = string.lower
local hasCommandPending = C_Mail and C_Mail.IsCommandPending
local issecretvalue = issecretvalue or function() return false end
local sortFields, markTable -- tables
local ibIndex, ibAttachIndex, numInboxItems, inboxCash, cleanPass, cashOnly, markOnly, takeAllInProgress, invFull, filterText -- variables
local spinnerText = { "Working ", "Working. ", "Working.. ", "Working..." }
--[[----------------------------------------------------------------------------
Table Handling
------------------------------------------------------------------------------]]
local newHash, del
do
local list = setmetatable({}, {__mode='k'})
function newHash(...)
local t = next(list)
if t then
list[t] = nil
else
t = {}
end
for i = 1, select('#', ...), 2 do
t[select(i, ...)] = select(i+1, ...)
end
return t
end
function del(t)
for k in pairs(t) do
t[k] = nil
end
list[t] = true
return nil
end
end
--[[----------------------------------------------------------------------------
Local Processing
------------------------------------------------------------------------------]]
-- Build a table with info about all items and money in the Inbox
local inboxCache = {}
local _sortNameCache = {}
local function _sortInboxFunc(itemA,itemB)
local sf = sortFields[BulkMailInbox.db.char.sortField]
if itemA and itemB then
local a, b = itemA[sf], itemB[sf]
if sf == 'itemLink' then
a = a and _sortNameCache[a] or a
b = b and _sortNameCache[b] or b
elseif sf == 'qty' then
a = a or itemA["money"]
b = b or itemB["money"]
end
a = type(a) == "nil" and 0 or type(a) == "boolean" and tostring(a) or a
b = type(b) == "nil" and 0 or type(b) == "boolean" and tostring(b) or b
if mod.db.char.sortReversed then
if a > b then return true end
else
if a < b then return true end
end
end
end
-- These are the patterns that indicate that the item was received from the AH
-- In that case the items are not returnable
local AHReceivedPatterns = {
(gsub(AUCTION_REMOVED_MAIL_SUBJECT, "%%s", ".*")),
(gsub(AUCTION_EXPIRED_MAIL_SUBJECT, "%%s", ".*")),
(gsub(AUCTION_WON_MAIL_SUBJECT, "%%s", ".*"))
}
local function _isAHSentMail(subject)
if subject then
for key,pattern in ipairs(AHReceivedPatterns) do
if subject:find(pattern) ~= nil then
return true
end
end
end
end
local function _matchesFilter(text)
if not filterText or filterText:len() == 0 then
return true
end
return text:lower():find(filterText, 1, true) ~= nil
end
-- markedSlots is resolved from markTable before taking, so the take loop
-- doesn't need to reconstruct bmid keys (which drift due to daysLeft changing).
local markedSlots = {}
local function inboxCacheBuild()
local start = GetTime()
for k in ipairs(inboxCache) do inboxCache[k] = del(inboxCache[k]) end
inboxCash, numInboxItems = 0, 0
for i = 1, GetInboxNumItems() do
local _, _, sender, subject, money, cod, daysLeft, numItems, _, wasReturned, _, canReply, isGM = GetInboxHeaderInfo(i)
if money > 0 then
local _, itemName = GetInboxInvoiceInfo(i)
local title = itemName and ITEM_SOLD_COLON..' '..itemName or L["Cash"]
if _matchesFilter(title) then
-- Contributed by Scott Centoni
table.insert(inboxCache, newHash(
'index', i, 'sender', sender, 'bmid', daysLeft..subject..0, 'returnable', not wasReturned, 'cod', cod,
'daysLeft', daysLeft, 'itemLink', title, 'money', money, 'texture', "Interface\\Icons\\INV_Misc_Coin_01"
))
if not issecretvalue(money) then inboxCash = inboxCash + money end
end
end
if numItems then
local canReturnItem = not wasReturned
if isGM or not canReply or _isAHSentMail(subject) then
canReturnItem = false
end
for j=1, ATTACHMENTS_MAX_RECEIVE do
local itemName, itemID, itemTexture, itemCount = GetInboxItem(i, j)
if itemName and _matchesFilter(itemName) then
table.insert(inboxCache, newHash(
'index', i, 'attachment', j, 'sender', sender, 'bmid', daysLeft..subject..j, 'returnable', canReturnItem, 'cod', cod,
'daysLeft', daysLeft, 'itemLink', GetInboxItemLink(i,j), 'qty', itemCount, 'texture', itemTexture
))
numInboxItems = numInboxItems + 1
end
end
end
end
wipe(_sortNameCache)
for _, entry in ipairs(inboxCache) do
local link = entry.itemLink
if link and not _sortNameCache[link] then
_sortNameCache[link] = GetItemInfo(link) or link
end
end
table.sort(inboxCache, _sortInboxFunc)
end
local function takeAll(cash, mark)
-- Ace3 timers only allow one arg so support that hack
if type(cash) == "table" then
mark = cash.markOnly
cash = cash.cashOnly
end
cashOnly = cash
markOnly = mark
-- Resolve marked items to (index, attachment) pairs using the current
-- cache BEFORE rebuilding, so we don't depend on bmid key stability.
wipe(markedSlots)
if mark then
for _, entry in ipairs(inboxCache) do
if markTable[entry.bmid] then
markedSlots[entry.index * 1000 + (entry.attachment or 0)] = true
end
end
end
ibIndex = GetInboxNumItems()
ibAttachIndex = 0
takeAllInProgress = true
inboxCacheBuild()
mod:TakeNextItemFromMailbox()
end
--[[----------------------------------------------------------------------------
Setup
------------------------------------------------------------------------------]]
local function color(text, color)
return fmt("|cff%s%s|r", color, text or "")
end
function mod:OnInitialize()
if not BulkMail3InboxDB and BulkMail2InboxDB and BulkMail2InboxDB.chars then
BulkMail3InboxDB = { char = {} }
for charname, data in pairs(BulkMail2InboxDB) do
BulkMail3InboxDB.char[charname] = data
end
end
self.db = DB:New("BulkMail3InboxDB", {
char = {
altDel = false,
ctrlRet = true,
shiftTake = true,
takeAll = true,
inboxUI = true,
takeStackable = true,
sortField = 1,
},
profile = {
disableTooltips = false,
scale = 1.0,
font = "Friz Quadrata TT",
fontSize = 12,
pageSize = 50,
autoPageSize = true,
sizeMode = "page",
freePosition = false,
savedPos = nil,
}
}, "Default")
sortFields = { 'itemLink', 'qty', 'returnable', 'sender', 'daysLeft', 'index' }
markTable = {}
inboxCash = 0
invFull = false
self.opts = {
type = 'group',
args = {
altdel = {
name = L["Alt-click Delete"], type = 'toggle',
desc = L["Enable Alt-Click on inbox items to delete the mail in which they are contained."],
get = function() return self.db.char.altDel end,
set = function(args,v) self.db.char.altDel = v end,
},
ctrlret = {
name = L["Ctrl-click Return"], type = 'toggle',
desc = L["Enable Ctrl-click on inbox items to return the mail in which they are contained."],
get = function() return self.db.char.ctrlRet end,
set = function(args,v) self.db.char.ctrlRet = v end,
},
shifttake = {
name = L["Shift-click Take"], type = 'toggle',
desc = L["Enable Shift-click on inbox items to take them."],
get = function() return self.db.char.shiftTake end,
set = function(args,v) self.db.char.shiftTake = v end,
},
gui = {
name = L["Show Inbox GUI"], type = 'toggle',
desc = L["Show the Inbox Items GUI"],
get = function() return self.db.char.inboxUI end,
set = function(args,v) self.db.char.inboxUI = v self:RefreshInboxGUI() end,
},
takeStackable = {
name = L["Always Take Stackable Items"], type = 'toggle',
desc = L["Continue taking partial stacks of stackable items even if the mailbox is full."],
get = function() return self.db.char.takeStackable end,
set = function(args,v) self.db.char.takeStackable = v end,
},
disableTooltips = {
name = L["Disable Tooltips"], type = 'toggle',
desc = L["Disable the help tooltips for the toolbar buttons."],
get = function() return self.db.profile.disableTooltips end,
set = function(args,v) self.db.profile.disableTooltips = v end,
},
scale = {
type = "range",
name = L["GUI Scale"],
desc = L["Set the window scale of the Inbox GUI."],
min = 0.3, max = 3.0, step = 0.1,
set = function(_,val) mod.db.profile.scale = val mod:RefreshInboxGUI(true) end,
get = function() return mod.db.profile.scale end,
order = 500,
},
pageSize = {
type = "range",
name = L["Page Size"],
desc = L["Maximum number of items to display per page."],
min = 10, max = 100, step = 1,
set = function(_,val) mod.db.profile.pageSize = val mod:RefreshInboxGUI(true) end,
get = function() return mod.db.profile.pageSize end,
order = 500,
},
autoPageSize = {
name = L["Auto Page Size"],
type = 'toggle',
desc = L["Automatically calculate page size to fit the mail frame. When disabled, uses the configured page size. Only applies when Window Size is set to Match or Max."],
get = function() return self.db.profile.autoPageSize end,
set = function(_, v) self.db.profile.autoPageSize = v mod._matchMailRows = nil mod:RefreshInboxGUI(true) end,
disabled = function() return self.db.profile.freePosition or self.db.profile.sizeMode == "page" end,
order = 2510,
},
font = {
type = "select",
dialogControl = "LSM30_Font",
name = L["Font"],
desc = L["Font used in the inbox list"],
values = AceGUIWidgetLSMlists.font,
set = function(_,key) mod.db.profile.font = key mod:RefreshInboxGUI() end,
get = function() return mod.db.profile.font end,
order = 1000,
},
fontsize = {
type = "range",
name = L["Font size"],
min = 6, max = 30, step = 1,
set = function(_,val) mod.db.profile.fontSize = val mod:RefreshInboxGUI() end,
get = function() return mod.db.profile.fontSize end,
order = 2000,
},
sizeMode = {
name = L["Window Size"],
type = 'select',
desc = L["How the window height is determined. Page Size uses fixed rows. Match sets height to mail frame. Max limits height to mail frame."],
values = {
page = L["Page Size"],
match = L["Match Mail Frame"],
max = L["Max Mail Frame"],
},
get = function() return self.db.profile.sizeMode end,
set = function(_, v) self.db.profile.sizeMode = v mod._matchMailRows = nil mod:RefreshInboxGUI(true) end,
disabled = function() return self.db.profile.freePosition end,
order = 2500,
},
freePosition = {
name = L["Free Position"],
type = 'toggle',
desc = L["Disable automatic anchoring to the mail frame. The window will remember its position when dragged."],
get = function() return self.db.profile.freePosition end,
set = function(_, v)
self.db.profile.freePosition = v
if not v then
self.db.profile.savedPos = nil
if mod.inboxGUI then
mod.inboxGUI.moved = false
mod:RefreshInboxGUI(true)
end
end
end,
order = 3000,
},
},
}
-- set up LDB, but only if the user doesn't have Bulk Mail already
if LDB and not BulkMail then
self.ldb =
LDB:NewDataObject("BulkMailInbox",
{
type = "data source",
label = L["Bulk Mail Inbox"]..VERSION,
icon = [[Interface\Addons\BulkMail2Inbox\icon]],
tooltiptext = color(L["Bulk Mail Inbox"]..VERSION.."\n\n", "ffff00")..color(L["Hint:"].." "..L["Left click to open the config panel."].."\n"..
L["Right click to open the config menu."], "ffd200"),
OnClick = function(clickedframe, button)
if button == "RightButton" then
mod:OpenConfigMenu(clickedframe)
else
mod:ToggleConfigDialog()
end
end,
})
end
self._mainConfig = self:OptReg(L["Bulk Mail Inbox"], self.opts, { "bmi", "bulkmailinbox" })
if BulkMail and BulkMail.opts then
BulkMail.opts.args.inbox = { type = "group",
handler = mod,
name = L["Inbox"],
desc = L["Bulk Mail Inbox Options"],
args = BulkMailInbox.opts.args
}
end
end
function mod:OnEnable()
self:RegisterEvent('MAIL_SHOW')
self:RegisterEvent('MAIL_CLOSED')
self:RegisterEvent('PLAYER_ENTERING_WORLD')
self:RegisterEvent('UI_ERROR_MESSAGE')
self:RegisterEvent('MAIL_INBOX_UPDATE')
if not _G.GetContainerItemInfo then
self:RegisterEvent('PLAYER_INTERACTION_MANAGER_FRAME_HIDE')
end
-- Handle being LoD loaded while at the mailbox.
-- Check both MailFrame (default UI) and the player interaction state
-- (covers TSM or other addons that replace the mail frame).
local atMailbox = MailFrame:IsVisible()
if not atMailbox and C_PlayerInteractionManager and C_PlayerInteractionManager.IsInteractingWithNpcOfType then
atMailbox = C_PlayerInteractionManager.IsInteractingWithNpcOfType(Enum.PlayerInteractionType.MailInfo)
end
if atMailbox then
self:MAIL_SHOW()
-- After reload, inbox data may not be available yet; force a
-- server refresh so MAIL_INBOX_UPDATE fires and clears the
-- _suppressEmptyShow flag once items are known.
CheckInbox()
end
end
function mod:OnDisable()
self:UnregisterAllEvents()
end
------------------------------------------------------------------------------
-- Events
------------------------------------------------------------------------------
function mod:MAIL_SHOW()
ibIndex = GetInboxNumItems()
-- Allow TSM frame detection to re-scan (TSM may create its frame lazily)
MagicUtil:ResetTSMFrameCache()
if not self:IsHooked('CheckInbox') then
self:SecureHook('CheckInbox', 'RefreshInboxGUI')
self:SecureHook(GameTooltip, 'SetInboxItem')
self:Hook('InboxFrame_OnClick', nil, true)
self:SecureHookScript(MailFrameTab1, 'OnClick', 'ShowInboxGUI')
self:SecureHookScript(MailFrameTab2, 'OnClick', 'HideInboxGUI')
-- Reposition when OpenMailFrame is shown or hidden
if OpenMailFrame then
self:SecureHookScript(OpenMailFrame, 'OnShow', 'OnOpenMailFrameChanged')
self:SecureHookScript(OpenMailFrame, 'OnHide', 'OnOpenMailFrameChanged')
end
-- Detect external mail operations (TSM, base UI "Open All", etc.)
self:SecureHook('AutoLootMailItem', 'OnExternalMailAction')
self:SecureHook('TakeInboxItem', 'OnExternalMailAction')
self:SecureHook('TakeInboxMoney', 'OnExternalMailAction')
end
-- Don't show the GUI on initial open if there are no items or gold
inboxCacheBuild()
mod._suppressEmptyShow = not inboxCache or not next(inboxCache)
if not mod._suppressEmptyShow then
self:ShowInboxGUI()
end
-- Watch for mail frame changes (e.g. TSM toggling between its UI and the default)
mod._lastMailFrame = nil
if not mod._mailFrameWatcher then
mod._mailFrameWatcher = self:ScheduleRepeatingTimer("CheckMailFrameChanged", 0.2)
end
end
function mod:CheckMailFrameChanged()
local mailFrame, isTSM = MagicUtil:GetMailFrame()
if mailFrame ~= mod._lastMailFrame then
-- Don't commit the change while ShowInboxGUI is suppressed;
-- we need this to re-trigger once the GUI can actually appear.
if mod._suppressEmptyShow then return end
mod._lastMailFrame = mailFrame
mod._matchMailRows = nil
if isTSM then
-- TSM active: always show inbox alongside send queue
self:ShowInboxGUI()
-- Tell BulkMail2 to reposition send queue now that inbox is shown
if BulkMail and BulkMail.sendQueueTooltip then
BulkMail:ShowSendQueueGUI()
end
else
-- Switching to normal UI: show inbox only if on Inbox tab
if SendMailFrame and SendMailFrame:IsShown() then
self:HideInboxGUI()
else
self:ShowInboxGUI()
end
end
end
end
function mod:PLAYER_INTERACTION_MANAGER_FRAME_HIDE(_, type)
if type == Enum.PlayerInteractionType.MailInfo then
mod:MAIL_CLOSED()
end
end
function mod:MAIL_CLOSED()
takeAllInProgress = false
mod._suppressEmptyShow = nil
if mod._mailFrameWatcher then
self:CancelTimer(mod._mailFrameWatcher)
mod._mailFrameWatcher = nil
end
mod._lastMailFrame = nil
self:HideInboxGUI()
GameTooltip:Hide()
self:UnhookAll()
end
BulkMailInbox.PLAYER_ENTERING_WORLD = BulkMailInbox.MAIL_CLOSED -- MAIL_CLOSED doesn't get called if, for example, the player accepts a port with the mail window open
function mod:OnOpenMailFrameChanged()
if mod.inboxGUI and not mod.inboxGUI.moved then
mod:RepositionTooltip(mod.inboxGUI, mod.db.profile.scale, mod._toolbar and mod._toolbar:GetHeight() or 0)
end
end
function mod:UI_ERROR_MESSAGE(event, type, msg) -- prevent infinite loop when inventory is full
if msg == ERR_INV_FULL then
invFull = true
end
end
-- Track external mail operations (TSM, base UI "Open All", etc.)
local lastExternalMailAction = 0
function mod:OnExternalMailAction()
if not takeAllInProgress then
lastExternalMailAction = GetTime()
end
end
-- Take next inbox item or money skip past CoD items and letters.
local prevSubject = ''
function mod:SmartCancelTimer(name)
mod.timers = mod.timers or {}
if mod.timers[name] then
mod:CancelTimer(mod.timers[name], true)
mod.timers[name] = nil
end
end
function mod:SmartScheduleTimer(name, override, method, timeout, ...)
mod.timers = mod.timers or {}
if mod.timers[name] and override then
mod:CancelTimer(mod.timers[name], true)
mod.timers[name] = nil
end
if not mod.timers[name] then
mod.timers[name] = mod:ScheduleTimer(method, timeout, ...)
end
end
local POLL_INTERVAL = 0.05 -- 50ms between polls
local FALLBACK_DELAY = 0.15 -- fixed delay when C_Mail.IsCommandPending unavailable
local POLL_TIMEOUT = 5.0 -- safety timeout to avoid getting stuck
local pollStartTime = 0
function mod:PollAndTakeNext()
if not takeAllInProgress then return end
if hasCommandPending and C_Mail.IsCommandPending() then
if (GetTime() - pollStartTime) < POLL_TIMEOUT then
self:SmartScheduleTimer('BMI_TakeNextItem', true, "PollAndTakeNext", POLL_INTERVAL)
return
end
-- Timed out waiting for server, proceed anyway
end
self:TakeNextItemFromMailbox()
end
function mod:ScheduleNextMailAction()
pollStartTime = GetTime()
if hasCommandPending then
self:SmartScheduleTimer('BMI_TakeNextItem', true, "PollAndTakeNext", POLL_INTERVAL)
else
self:SmartScheduleTimer('BMI_TakeNextItem', true, "TakeNextItemFromMailbox", FALLBACK_DELAY)
end
end
function mod:MAIL_INBOX_UPDATE()
if takeAllInProgress then return end
-- Auto-show the GUI if mail with items/gold arrived while suppressed
if mod._suppressEmptyShow then
inboxCacheBuild()
if inboxCache and next(inboxCache) then
mod._suppressEmptyShow = nil
if not mod.inboxGUI then
local mf = MagicUtil:GetMailFrame()
if mf and mf:IsVisible() then
mod:SmartScheduleTimer('BMI_RefreshInboxGUI', true, "ShowInboxGUI", 1.0)
return
end
end
end
end
if (GetTime() - lastExternalMailAction) < 2.0 then
-- External addon/UI is actively processing mail; use non-overriding
-- timer so we refresh at ~2s intervals instead of on every event
mod:SmartScheduleTimer('BMI_RefreshInboxGUI', false, "RefreshInboxGUI", 2.0)
else
-- Normal operation: coalesce rapid events into one refresh
mod:SmartScheduleTimer('BMI_RefreshInboxGUI', true, "RefreshInboxGUI", 1.0)
end
end
local _fetchCount = 0
local _lastCount = -1
local function _updateSpinner()
local spinner = mod._toolbar and mod._toolbar.spinner
if not spinner or (takeAllInProgress and _fetchCount == _lastCount) then return end
_lastCount = _fetchCount
local isVisible = mod.buttons.Cancel:IsVisible()
if takeAllInProgress then
spinner:SetText(spinnerText[1+math.fmod(_fetchCount, #spinnerText)]);
if not isVisible then
mod.buttons.Cancel:Show()
end
elseif isVisible then
mod.buttons.Cancel:Hide()
spinner:SetText("")
end
end
function mod:TakeNextItemFromMailbox()
_updateSpinner()
if not takeAllInProgress then
return
end
local numMails = GetInboxNumItems()
cashOnly = cashOnly or (invFull and not mod.db.char.takeStackable)
if ibIndex <= 0 then
if cleanPass or numMails <= 0 then
takeAllInProgress = false
invFull = false
return self:RefreshInboxGUI()
else
ibIndex = numMails
ibAttachIndex = 0
cleanPass = true
return self:SmartScheduleTimer('BMI_takeAll', true, takeAll, .1, { cashOnly = cashOnly, markOnly = markOnly })
end
end
local curIndex, curAttachIndex = ibIndex, ibAttachIndex
local sender, subject, money, cod, daysLeft, item, _, _, text, _, isGM = select(3, GetInboxHeaderInfo(curIndex))
if subject then
prevSubject = subject
else
subject = prevSubject
end
if curAttachIndex == ATTACHMENTS_MAX_RECEIVE then
ibIndex = ibIndex - 1
ibAttachIndex = 0
else
ibAttachIndex = ibAttachIndex + 1
end
-- Fast path: loot entire mail at once when no filtering is needed
if curAttachIndex == 0 and not cashOnly and not markOnly
and (not filterText or filterText == "")
and cod == 0 and not invFull
and (money > 0 or item)
and not string.find(subject, "Sale Pending") then
if item then
AutoLootMailItem(curIndex)
end
if money > 0 then
TakeInboxMoney(curIndex)
end
ibIndex = curIndex - 1
ibAttachIndex = 0
cleanPass = false
self:SmartScheduleTimer('BMI_RefreshInboxGUI', false, "RefreshInboxGUI", 2.0)
self:ScheduleNextMailAction()
_fetchCount = _fetchCount + 1
return
end
local itemName, _, _, itemCount = GetInboxItem(curIndex, curAttachIndex)
local slotKey = curIndex * 1000 + curAttachIndex
if (sender == "The Postmaster" or sender == "Thaumaturge Vashreen") and not itemName and money == 0 and not item then
DeleteInboxItem(curIndex)
self:ScheduleNextMailAction()
return
end
if curAttachIndex > 0 and not itemName or markOnly and not markedSlots[slotKey] or itemName and not _matchesFilter(itemName)
then
return self:TakeNextItemFromMailbox()
end
local actionTaken
if not string.find(subject, "Sale Pending") then
if curAttachIndex == 0 and money > 0 then
local _, itemName = GetInboxInvoiceInfo(curIndex)
local title = itemName and ITEM_SOLD_COLON..' '..itemName or L["Cash"]
if _matchesFilter(title) then
cleanPass = false
actionTaken = true
TakeInboxMoney(curIndex)
end
elseif not cashOnly and cod == 0 then
cleanPass = invFull -- this ensures we'll die properly after a full mailbox iteration
local inboxitem = GetInboxItemLink(curIndex,curAttachIndex)
if inboxitem and
(not invFull or -- inventory not full
(mod.db.char.takeStackable and -- or continue taking stackable items even if full
itemCount < select(8, GetItemInfo(inboxitem)))) then
TakeInboxItem(curIndex, curAttachIndex)
markedSlots[slotKey] = nil
actionTaken = true
end
end
end
if actionTaken then
-- Since we did something, we'll add a delay to prevent erroring out
self:SmartScheduleTimer('BMI_RefreshInboxGUI', false, "RefreshInboxGUI", 2.0)
self:ScheduleNextMailAction()
_fetchCount = _fetchCount + 1
else
-- We didn't take any items so let's move on
self:TakeNextItemFromMailbox()
end
end
--[[----------------------------------------------------------------------------
Hooks
------------------------------------------------------------------------------]]
function mod:SetInboxItem(tooltip, index, attachment, ...)
if takeAllInProgress then return end
local money, _, _, _, _, wasReturned, _, canReply = select(5, GetInboxHeaderInfo(index))
if self.db.char.shiftTake then tooltip:AddLine(L["Shift - Take Item"]) end
if wasReturned then
if self.db.char.altDel then
tooltip:AddLine(L["Alt - Delete Containing Mail"])
end
elseif canReply and self.db.char.ctrlRet then
tooltip:AddLine(L["Ctrl - Return Containing Mail"])
end
end
function mod:InboxFrame_OnClick(parentself, index, attachment, ...)
takeAllInProgress = false
local _, _, _, _, money, cod, _, hasItem, _, wasReturned, _, canReply = GetInboxHeaderInfo(index)
if self.db.char.shiftTake and IsShiftKeyDown() then
if money > 0 then TakeInboxMoney(index)
elseif cod > 0 then return
elseif hasItem then TakeInboxItem(index, attachment) end
elseif self.db.char.ctrlRet and IsControlKeyDown() and not wasReturned and canReply then ReturnInboxItem(index)
elseif self.db.char.altDel and IsAltKeyDown() and wasReturned then DeleteInboxItem(index)
elseif parentself and parentself:GetObjectType() == 'CheckButton' then self.hooks.InboxFrame_OnClick(parentself, index, ...) end
mod:SmartScheduleTimer("BMI_RefreshInboxGUI", true, "RefreshInboxGUI", 0.1)
end
-- Inbox Items Tablet
local function highlightSameMailItems(index, ...)
if self.db.char.altDel and IsAltKeyDown() or self.db.char.ctrlRet and IsControlKeyDown() then
for i = 1, select('#', ...) do
local row = select(i, ...)
if row.col6 and row.col6:GetText() == index then
row.highlight:Show()
end
end
end
end
local function unhighlightSameMailItems(index, ...)
for i = 1, select('#', ...) do
local row = select(i, ...)
if row.col6 and row.col6:GetText() == index then
row.highlight:Hide()
end
end
end
--[[----------------------------------------------------------------------------
QTip GUI
------------------------------------------------------------------------------]]
-- For pagination
local startPage = 0
local function _closeHelpTooltip(parentFrame)
if mod.helpTooltip and mod.helpTooltip.owner == parentFrame then
mod.helpTooltip.owner = nil
QTIP:Release(mod.helpTooltip)
mod.helpTooltip = nil
end
end
local function _openHelpTooltip(parentFrame, header, text)
if self.db.profile.disableTooltips then return end
local tooltip = mod.helpTooltip or QTIP:Acquire("BulkMailInboxHelpTooltip")
mod.helpTooltip = tooltip
tooltip:Clear()
tooltip.owner = parentFrame
tooltip:SetColumnLayout(1, "LEFT")
tooltip:AddHeader(header)
tooltip:AddLine(color(text, "ffd200"))
tooltip:SmartAnchorTo(parentFrame)
tooltip:SetClampedToScreen(true)
tooltip:Show()
end
local function _addTooltipToFrame(frame, header, text)
frame:SetScript("OnEnter", function(self) _openHelpTooltip(self, header, text) end)
frame:SetScript("OnLeave", _closeHelpTooltip)
end
local function _addIndentedCell(tooltip, text, indentation, func, arg)
local y, x = tooltip:AddLine()
tooltip:SetCell(y, x, text, tooltip:GetFont(), "LEFT", 1, nil, indentation)
if func then
tooltip:SetLineScript(y, "OnMouseUp", func, arg)
end
return y, x
end
local function _addColspanCell(tooltip, text, colspan, func, arg, y)
y = y or tooltip:AddLine()
tooltip:SetCell(y, 1, text, tooltip:GetFont(), "LEFT", colspan)
if func then
tooltip:SetLineScript(y, "OnMouseUp", func, true)
else
tooltip:SetLineScript(y, "OnMouseUp", nil)
end
return y
end
function mod:HideInboxGUI()
mod:SmartCancelTimer('BMI_takeAll')
mod:SmartCancelTimer('BMI_TakeNextItem')
mod:SmartCancelTimer('BMI_RefreshInboxGUI')
if mod._toolbar then
mod._toolbar:Hide()
mod._toolbar:SetParent(nil)
end
local tooltip = mod.inboxGUI
if tooltip then
mod.inboxGUI = nil
tooltip:EnableMouse(false)
tooltip:SetScript("OnDragStart", nil)
tooltip:SetScript("OnDragStop", nil)
tooltip:SetMovable(false)
tooltip:RegisterForDrag()
tooltip:SetFrameStrata("TOOLTIP")
tooltip.moved = nil
tooltip:SetScale(GameTooltip:GetScale())
QTIP:Release(tooltip)
end
mod._wantGui = nil
end
function mod:RefreshInboxGUI(resetMoved)
_updateSpinner()
mod:SmartCancelTimer('BMI_RefreshInboxGUI')
if not mod.db.char.inboxUI then return end
inboxCacheBuild()
if mod.inboxGUI then
if resetMoved then
mod.inboxGUI.moved = nil
mod._matchMailRows = nil
end
-- Rebuild it since it's visible
mod:ShowInboxGUI()
end
end
local function _onLeaveFunc(frame, info)
if mod.tooltipShowing == frame then
GameTooltip:Hide()
mod.tooltipShowing = nil
frame:SetScript("OnKeyUp", nil)
frame:SetScript("OnKeyDown", nil)
end
end
local function _toggleCompareItem()
if IsShiftKeyDown() then
GameTooltip_ShowCompareItem()
else
-- There appears to be no other way. Sigh.
if ( GameTooltip.shoppingTooltips ) then
for _, frame in pairs(GameTooltip.shoppingTooltips) do
frame:Hide()
end
end
GameTooltip.comparing = false
end
end
local function _onEnterFunc(frame, info) -- contributed by bigzero
mod.tooltipShowing = frame
GameTooltip:SetOwner(frame, 'ANCHOR_BOTTOMRIGHT', 0, 0)
if info.index and info.attachment and GetInboxItem(info.index, info.attachment) then
GameTooltip:SetInboxItem(info.index, info.attachment)
end
if IsShiftKeyDown() then
GameTooltip_ShowCompareItem()
end
if info.money and not issecretvalue(info.money) then
GameTooltip:AddLine(ENCLOSED_MONEY, "", 1, 1, 1)
if pcall(SetTooltipMoney, GameTooltip, info.money) then
SetMoneyFrameColor('GameTooltipMoneyFrame', HIGHLIGHT_FONT_COLOR.r, HIGHLIGHT_FONT_COLOR.g, HIGHLIGHT_FONT_COLOR.b)
end
end
if (info.cod or 0) > 0 and not issecretvalue(info.cod) then
GameTooltip:AddLine(COD_AMOUNT, "", 1, 1, 1)
if pcall(SetTooltipMoney, GameTooltip, info.cod) then
SetMoneyFrameColor('GameTooltipMoneyFrame', HIGHLIGHT_FONT_COLOR.r, HIGHLIGHT_FONT_COLOR.g, HIGHLIGHT_FONT_COLOR.b)
end
end
GameTooltip:Show()
frame:SetScript("OnKeyDown", _toggleCompareItem)
frame:SetScript("OnKeyUp", _toggleCompareItem)
end
local function _createButton(title, parent, onclick, anchorTo, xoffset, tooltipHeader, tooltipText)
local buttons = mod.buttons or {}
mod.buttons = buttons
local button = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate")
button:SetText(title)
button:SetWidth(25)
button:SetHeight(20)
button:SetScript("OnClick", onclick)
buttons[title] = button
button:SetPoint("RIGHT", anchorTo, "LEFT", xoffset, 0)
_addTooltipToFrame(button, tooltipHeader, tooltipText)
return button
end
local function _createOrAttachSearchBar(tooltip)
local toolbar = mod._toolbar
if not toolbar then
local template = (TooltipBackdropTemplateMixin and "TooltipBackdropTemplate") or (BackdropTemplateMixin and "BackdropTemplate")
toolbar = CreateFrame("Frame", nil, UIParent, template)
toolbar:SetHeight(49)
local closeButton = CreateFrame("Button", "BulkMailInboxToolbarCloseButton", toolbar, "UIPanelCloseButton")
closeButton:SetPoint("TOPRIGHT", toolbar, "TOPRIGHT", 0, 0)
closeButton:SetScript("OnClick", function() mod:HideInboxGUI() end)
_addTooltipToFrame(closeButton, L["Close"], L["Close the window and stop taking items from the inbox."])
local nextButton = CreateFrame("Button", nil, toolbar)
nextButton:SetNormalTexture([[Interface\Buttons\UI-SpellbookIcon-NextPage-Up]])
nextButton:SetPushedTexture([[Interface\Buttons\UI-SpellbookIcon-NextPage-Down]])
nextButton:SetDisabledTexture([[Interface\Buttons\UI-SpellbookIcon-NextPage-Disabled]])
nextButton:SetHighlightTexture([[Interface\Buttons\UI-Common-MouseHilight]], "ADD")
nextButton:SetPoint("TOP", closeButton, "BOTTOM", 0, 9)
nextButton:SetScript("OnClick", function() startPage = startPage + 1 mod:ShowInboxGUI() end)
nextButton:SetWidth(25)
nextButton:SetHeight(25)
_addTooltipToFrame(nextButton, L["Next Page"], L["Go to the next page of items."])
local prevButton = CreateFrame("Button", nil, toolbar)
prevButton:SetNormalTexture([[Interface\Buttons\UI-SpellbookIcon-PrevPage-Up]])
prevButton:SetPushedTexture([[Interface\Buttons\UI-SpellbookIcon-PrevPage-Down]])
prevButton:SetDisabledTexture([[Interface\Buttons\UI-SpellbookIcon-PrevPage-Disabled]])
prevButton:SetHighlightTexture([[Interface\Buttons\UI-Common-MouseHilight]], "ADD")
prevButton:SetPoint("RIGHT", nextButton, "LEFT", 0, 0)
prevButton:SetScript("OnClick", function() startPage = startPage - 1 mod:ShowInboxGUI() end)
prevButton:SetWidth(25)
prevButton:SetHeight(25)
_addTooltipToFrame(prevButton, L["Previous Page"], L["Go to the previous page of items."])
local pageText = toolbar:CreateFontString(nil, nil, "GameFontNormalSmall")
pageText:SetTextColor(1,210/255.0,0,1)
pageText:SetPoint("RIGHT", prevButton, "LEFT", 0, 0)
toolbar.pageText = pageText
local itemText = toolbar:CreateFontString(nil, nil, "GameFontNormalSmall")
itemText:SetTextColor(1,210/255.0,0,1)
itemText:SetPoint("TOPRIGHT", pageText, "TOPLEFT", 0, 0)
itemText:SetPoint("BOTTOMRIGHT", pageText, "BOTTOMLEFT", 0, 0)
itemText:SetPoint("LEFT", toolbar, "LEFT", 5, 0)
itemText:SetJustifyH("LEFT")
toolbar.itemText = itemText
local button = _createButton("CS", toolbar, function() wipe(markTable) self:RefreshInboxGUI() end, closeButton, -2,
L["Clear Selected"], L["Clear the list of selected items."])
button = _createButton("TS", toolbar, function() takeAll(false, true) end, button, -2,
L["Take Selected"], L["Take all selected items from the mailbox."])
button = _createButton("TC", toolbar, function() takeAll(true) end, button, -2,
L["Take Cash"], L["Take all money from the mailbox. If the search filter is used,\nmoney will only be taken from mails which the search term."])
button = _createButton("TA", toolbar, function() takeAll() end, button, -2,
L["Take All"], L["Take all items from the mailbox. If the search filter is used,\nonly items matching the search term will be taken."])
mod.buttons.prev = prevButton
mod.buttons.next = nextButton
mod.buttons.close = closeButton
local editBox = CreateFrame("EditBox", "BulkMailInboxSearchFilterEditBox", toolbar, "InputBoxTemplate")
editBox:SetWidth(100)
editBox:SetHeight(30)
editBox:SetScript("OnTextChanged",
function()