Repository navigation
Expand file tree
/
Copy pathInFlight.lua
More file actions
2775 lines (2365 loc) · 99.7 KB
/
Copy pathInFlight.lua
File metadata and controls
2775 lines (2365 loc) · 99.7 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
-- GLOBALS -> LOCAL
local _G = getfenv(0)
local GetNumRoutes, GetTaxiMapID, GetTime, NumTaxiNodes, TaxiGetNodeSlot, TaxiNodeGetType, TaxiNodeName, UnitOnTaxi
= GetNumRoutes, GetTaxiMapID, GetTime, NumTaxiNodes, TaxiGetNodeSlot, TaxiNodeGetType, TaxiNodeName, UnitOnTaxi
local abs, floor, format, gsub, ipairs, pairs, print, strjoin, strfind
= abs, floor, format, gsub, ipairs, pairs, print, strjoin, strfind
local gtt = GameTooltip
-- WARNING if InFlight_Load is still present.
if C_AddOns.IsAddOnLoaded("InFlight_Load") then
print("|cffff0000\"InFlight_Load\" is no longer required for \"InFlight\". You can disable or remove it.|r")
C_AddOns.DisableAddOn("InFlight_Load")
-- Undo InFlight_Load.
InFlight = nil
end
local InFlight = CreateFrame("Frame", "InFlight") -- no parent is intentional
-- LIBRARIES
local smed = LibStub("LibSharedMedia-3.0")
local LLS = LibStub("LibLayoutSettings-1.0")
-- LOCALIZATION
local L = LibStub("AceLocale-3.0"):GetLocale("InFlight")
InFlight.L = L
InFlight.newPlayerSaveData = {}
InFlight.debug = false
-- LOCAL VARIABLES
local debug = InFlight.debug
local Print, PrintD = InFlight.Print, InFlight.PrintD
local profile -- the user's own settings, written only by the settings menu
local look -- what the bar is drawn from, see below
local taxiSrc, taxiSrcName, taxiDst, taxiDstName, endTime -- location data
local porttaken, takeoff, inworld, outworld, ontaxi -- flags
local ratio, endText = 0, "??" -- cache variables
local sb, spark, sparkGlow, timeText, locText, bord, back -- frame elements
local previewActive, previewRequests = nil, {} -- dummy flight, and who wants it
local totalTime, startTime, elapsed, throt = 0, 0, 0, 0 -- throttle variables
local oldTakeTaxiNode
-- A dropdown option tried on while the mouse rests on it, the way the barber
-- shop tries on a choice: drawn, never stored, so nothing that saves or compares
-- settings ever sees it. The bar reads its size, texture, border, spark, font
-- and font size through Drawn for that, and nothing else goes through it.
local hovered = {}
local function Drawn(key)
local value = hovered[key]
if value == nil then
value = look[key]
end
return value
end
-- While a colour picker is open for the known or the unknown fill, "known" or
-- "unknown": the bar shows that fill whatever it is showing otherwise, so that
-- the colour can be judged as it is picked. Drawn only, like hovered.
local pickedFill
local playerFaction = UnitFactionGroup("player")
-- Used to be local variable "vars = InFlight.db.global[faction]", but now we differentiate between faction-specific and factionless zones.
local function GetDstNodes(src, faction)
if InFlight.noFactionsZoneNodes[src] then
return InFlight.db.global["FactionslessZones"][src]
else
return InFlight.db.global[faction][src]
end
end
InFlight:SetScript("OnEvent", function(this, event, ...) this[event](this, ...) end)
InFlight:RegisterEvent("ADDON_LOADED")
--------------------------------
function InFlight:ADDON_LOADED()
--------------------------------
self:RegisterEvent("TAXIMAP_OPENED")
self:SetupInFlight()
self:LoadBulk()
self:UnregisterEvent("ADDON_LOADED")
end
-------------------------------------
function InFlight:TAXIMAP_OPENED(...)
-------------------------------------
-- Flight map might change (Dragon Isles / Zaralek Cavern).
if FlightMapFrame and not FlightMapFrame.inflight_hook then
hooksecurefunc(FlightMapFrame, "SetMapID", function()
InFlight:InitSource(false)
end)
FlightMapFrame.inflight_hook = true
end
local uiMapSystem = ...
local isTaxiMap = uiMapSystem == Enum.UIMapSystem.Taxi
self:InitSource(isTaxiMap)
end
-- The places gossip flights start from or go to, by AreaTable ID. The client
-- names them in its own language, in exactly the text GetMinimapZoneText
-- returns, and older clients use older names, so they are not translated here.
-- Honor Point has no area of its own and lies in Hellfire Peninsula. It and the
-- other destinations that are no area are translated in the locale files.
local areaIDs = {
["Amber Ledge"] = 4023,
["Argent Tournament Grounds"] = 4658,
["Blackwind Landing"] = 3973,
["Caverns of Time"] = 1941,
["Durnholde Keep"] = 2370,
["Expedition Point"] = 3815,
["Explorers' League Outpost"] = 3997,
["Hellfire Peninsula"] = 3483,
["Nighthaven"] = 2361,
["Old Hillsbrad Foothills"] = 2367,
["Rut'theran Village"] = 702,
["Shatter Point"] = 3920,
["Shattered Sun Staging Area"] = 4085,
["Skyguard Outpost"] = 3964,
["Stormwind City"] = 1519,
["Sun's Reach Harbor"] = 4087,
["The Sin'loren"] = 4082,
["Thunder Bluff"] = 1638,
["Valgarde"] = 3981,
}
-- The client's name for a place, nil for an area this client does not have.
local function AreaName(place)
local name = C_Map.GetAreaInfo(areaIDs[place])
if name and name ~= "" then
return name
end
end
-- A place's name for the bar: the client's, else the locale file's, else English.
local function PlaceName(place)
return areaIDs[place] and AreaName(place) or L[place]
end
-- Support for flightpaths that are started by gossip options, by the area the
-- flight master stands in.
local gossipFlights = {
["Amber Ledge"] = {{ find = L["AmberLedgeGossip"], s = "Amber Ledge", d = "Transitus Shield (Scenic Route)" }},
["Argent Tournament Grounds"] = {{ find = L["ArgentTournamentGossip"], s = "Argent Tournament Grounds", d = "Return" }},
["Blackwind Landing"] = {{ find = L["BlackwindLandingGossip"], s = "Blackwind Landing", d = "Skyguard Outpost" }},
["Caverns of Time"] = {{ find = L["CavernsOfTimeGossip"], s = "Caverns of Time", d = "Nozdormu's Lair" }},
["Expedition Point"] = {{ find = L["ExpeditionPointGossip"], s = "Expedition Point", d = "Shatter Point" }},
["Hellfire Peninsula"] = {{ find = L["HellfirePeninsulaGossip"], s = "Honor Point", d = "Shatter Point" }},
["Nighthaven"] = {{ find = L["NighthavenGossipA"], s = "Nighthaven", d = "Rut'theran Village" },
{ find = L["NighthavenGossipH"], s = "Nighthaven", d = "Thunder Bluff" }},
["Old Hillsbrad Foothills"] = {{ find = L["OldHillsbradGossip"], s = "Old Hillsbrad Foothills", d = "Durnholde Keep" }},
["Shatter Point"] = {{ find = L["ShatterPointGossip"], s = "Shatter Point", d = "Honor Point" }},
["Skyguard Outpost"] = {{ find = L["SkyguardOutpostGossip"], s = "Skyguard Outpost", d = "Blackwind Landing" }},
["Stormwind City"] = {{ find = L["StormwindCityGossip"], s = "Stormwind City", d = "Return" }},
["Sun's Reach Harbor"] = {{ find = L["SSSAGossip"], s = "Shattered Sun Staging Area", d = "Return" },
{ find = L["SSSAGossip2"], s = "Shattered Sun Staging Area", d = "The Sin'loren" }},
["The Sin'loren"] = {{ find = L["TheSin'lorenGossip"], s = "The Sin'loren", d = "Shattered Sun Staging Area" }},
["Valgarde"] = {{ find = L["ValgardeGossip"], s = "Valgarde", d = "Explorers' League Outpost" }},
}
-- The same flights by the client's name of the area, made on first use.
local gossipFlightsByArea
-- Gossip texts are compared without spaces and with typographic apostrophes
-- made plain, as clients and translations differ in both.
local function Simplify(text)
return (gsub(gsub(text, "’", "'"), "%s+", ""))
end
local function PrepareMiscFlight(buttonText)
if not buttonText or buttonText == "" then
return
end
if not gossipFlightsByArea then
gossipFlightsByArea = {}
for area, flights in pairs(gossipFlights) do
local name = AreaName(area)
if name then
gossipFlightsByArea[name] = flights
end
end
end
local tsz = gossipFlightsByArea[GetMinimapZoneText()]
if not tsz then
return
end
buttonText = Simplify(buttonText)
local source, destination
for _, sz in ipairs(tsz) do
if strfind(buttonText, Simplify(sz.find), 1, true) then
source = sz.s
destination = sz.d
break
end
end
if source and destination then
InFlight:StartMiscFlight(source, destination)
end
end
-- For Immersion addon.
if C_AddOns.IsAddOnLoaded("Immersion") then
local immersionHookFrame = CreateFrame("Frame")
immersionHookFrame:SetScript("OnEvent", function(_, event)
if ImmersionFrame and ImmersionFrame.TitleButtons then
local children = {ImmersionFrame.TitleButtons:GetChildren()}
for i, child in ipairs(children) do
if not child.inFlightHook then
child:HookScript("OnClick", function(this)
PrepareMiscFlight(this:GetText())
end)
child.inFlightHook = true
end
end
end
end)
immersionHookFrame:RegisterEvent("GOSSIP_SHOW")
immersionHookFrame:RegisterEvent("QUEST_GREETING")
immersionHookFrame:RegisterEvent("QUEST_PROGRESS")
-- Without Immersion addon.
else
hooksecurefunc(_G.GossipOptionButtonMixin, "OnClick", function(this)
local elementData = this:GetElementData()
if elementData.buttonType ~= _G.GOSSIP_BUTTON_TYPE_OPTION then
return
end
PrepareMiscFlight(this:GetText())
end)
end
-- LOCAL FUNCTIONS
local function FormatTime(secs) -- simple time format
if not secs then
return "??"
end
return format(TIMER_MINUTES_DISPLAY, secs / 60, secs % 60)
end
local function ShortenName(name) -- shorten name to lighten saved variables and display
return gsub(name, L["DestParse"], "")
end
-- GetTaxiMapID() does not take into account if the map was changed (Dragon Isles / Zaralek Cavern).
local function GetViewedTaxiMapID()
if FlightMapFrame and FlightMapFrame.GetMapID then
return FlightMapFrame:GetMapID()
else
return GetTaxiMapID()
end
end
local function GetNodeID(slot)
local taximapNodes = C_TaxiMap.GetAllTaxiNodes(GetViewedTaxiMapID())
for _, taxiNodeData in ipairs(taximapNodes) do
if (slot == taxiNodeData.slotIndex) then
return taxiNodeData.nodeID
end
end
end
local function SetPoints(f, lp, lrt, lrp, lx, ly, rp, rrt, rrp, rx, ry)
f:ClearAllPoints()
f:SetPoint(lp, lrt, lrp, lx, ly)
if rp then
f:SetPoint(rp, rrt, rrp, rx, ry)
end
end
-- The spark and the glow some sparks trail behind them go together, which
-- BarStyles.lua sees to.
local function ShowSpark(shown)
InFlight:ShowSpark(spark, sparkGlow, shown and Drawn("spark") ~= "None")
end
local function PlaceSpark(x) -- x from the bar's left end
InFlight:PlaceSpark(spark, sparkGlow, x)
end
-- A colour setting as the four numbers the API takes. AceDB fills every colour
-- in channel by channel, and a layout stores whole ones, so all four are there.
local function RGBA(color)
return color.r, color.g, color.b, color.a
end
local function ColorText(text, color) -- with a shadow that fades with it
text:SetShadowColor(0, 0, 0, color.a)
text:SetShadowOffset(1, -1)
text:SetTextColor(RGBA(color))
end
local function SetToUnknown() -- setup bar for flights with unknown time
sb:SetMinMaxValues(0, 1)
sb:SetValue(1)
sb:SetStatusBarColor(RGBA(look.unknowncolor))
ShowSpark(false)
end
-- The client loads a font file on demand. The first SetFont for a file returns
-- false and leaves the string on the font it had, and the load only completes on
-- a later frame, so the call has to be repeated. The load lasts for the session,
-- which is why a font only ever misbehaves the first time it is used after a
-- client start and never again after a reload. There is no API to load a font up
-- front, and every size and outline combination becomes available together once
-- the file is in, so there is nothing to avoid, only to wait for.
--
-- The catch is that the pending load is only picked up when the string is laid
-- out again. Repeating SetFont on a string that is otherwise left alone gets
-- false forever, no matter how long it is left. That is why changing any other
-- bar setting, which re-anchors these strings and rewrites their text, was what
-- used to make a newly picked font appear.
--
-- So: ask again, and make the string lay itself out between attempts. Dropping
-- the outline is kept as a cheap safety net, since the right font without one
-- would still beat the wrong font with one.
local fontRetryDelays = { 0.1, 0.25, 0.5, 1, 2, 4, 8 }
local fontRetryToken = 0
-- Returns true once the string carries the configured font, outline or not.
local function ApplyFontTo(fontString, fontPath, size, flags)
if fontPath and fontString:SetFont(fontPath, size, flags) then
return true
end
-- Not every font takes an outline at every size. The right font without one
-- beats keeping whatever font happened to be there before.
if fontPath and flags ~= "" and fontString:SetFont(fontPath, size, "") then
return true
end
-- A string that never got a font at all throws on the next SetText.
if not fontString:GetFont() then
fontString:SetFont(STANDARD_TEXT_FONT or GameFontNormal:GetFont(), size, flags)
end
-- The pending load is only picked up once the string is laid out again, so give
-- it a reason to be. Asking again without this never comes good, however long
-- it is left, which is why changing some other bar setting by hand was what used
-- to fix it.
local text = fontString:GetText() or ""
fontString:SetText(text .. " ")
fontString:SetText(text)
return false
end
-- Returns true once both strings carry the configured font.
local function ApplyBarFonts()
-- Fetch hands back the default, or a global override, in place of an unknown
-- key, and nil only when there is no media table at all. So a wrong key gives a
-- plausible wrong font rather than an error.
local fontPath = smed:Fetch("font", Drawn("font"))
-- Both have to run, so do not let "and" short circuit the second one away.
local locOk = ApplyFontTo(locText, fontPath, Drawn("fontsize"), look.outline and "OUTLINE" or "")
local timeOk = ApplyFontTo(timeText, fontPath, Drawn("fontsize"), look.outlinetime and "OUTLINE" or "")
return locOk and timeOk
end
local function ApplyBarFontsWithRetry()
if ApplyBarFonts() then
return
end
fontRetryToken = fontRetryToken + 1
local token = fontRetryToken
-- One pending timer at a time, each attempt booking the next, rather than the
-- whole chain queued at once: UpdateLook runs on every step of a slider drag,
-- and a chain per step would leave hundreds of timers pending for one font.
-- The delays are counted from this call, so each wait is the gap to the next.
local function Attempt(index)
local delay = fontRetryDelays[index]
if not delay then
return
end
C_Timer.After(delay - (fontRetryDelays[index - 1] or 0), function()
-- A newer attempt took over.
if token ~= fontRetryToken then
return
end
if not ApplyBarFonts() then
Attempt(index + 1)
end
end)
end
Attempt(1)
end
-- LibSharedMedia offers the client's Korean and Chinese font files to western
-- clients as well, on the strength of a glyph coverage check made in 2012. Their
-- own scripts do render, but a western client never asks for them, and their
-- latin letters mostly repeat one another. Measured at size 16 on 12.1.0, "2002
-- Bold" renders latin and digits pixel identical to Friz Quadrata, "2002"
-- differs only by a third of a pixel per digit, and the three AR files share one
-- latin set between them, a narrow one of their own. So a western client is
-- offered Friz Quadrata and one AR file for those, and a bar set to one of the
-- others gets the one it looks like, see InFlight:ReplacedFont.
--
-- Other locales keep the full list, because there these files are the point, and
-- fonts registered by other addons are never touched.
local westernFontReplacements = {
["2002"] = "Friz Quadrata TT",
["2002 Bold"] = "Friz Quadrata TT",
["AR CrystalzcuheiGBK Demibold"] = "AR ZhongkaiGBK Medium",
["AR ZhongkaiGBK Medium (Combat)"] = "AR ZhongkaiGBK Medium",
}
-- LibSharedMedia registers these for western and Russian clients only, so on a
-- Korean or Chinese one a bar set to one of them has always drawn in the
-- client's default font.
local westernAndRussianFonts = {
["2002"] = true,
["2002 Bold"] = true,
["AR CrystalzcuheiGBK Demibold"] = true,
["AR ZhongkaiGBK Medium"] = true,
["AR ZhongkaiGBK Medium (Combat)"] = true,
}
local nonWesternLocales = { koKR = true, zhCN = true, zhTW = true, ruRU = true }
-- The font a bar set to this one gets instead on this client, so that it looks
-- the same and the font lists have it selected. Nil to keep it, which a Russian
-- client always does, these being fonts of their own there.
------------------------------------
function InFlight:ReplacedFont(name)
------------------------------------
local locale = GetLocale()
if locale == "ruRU" then
return nil
elseif nonWesternLocales[locale] then
return westernAndRussianFonts[name] and smed:GetDefault("font") or nil
end
return westernFontReplacements[name]
end
-- The order the font lists offer them in. Any other, another addon's or one of a
-- Korean, Chinese or Russian client's own, follows by name.
local fontOrder = {
"Arial Narrow", "AR ZhongkaiGBK Medium", "Friz Quadrata TT", "Nimrod MT", "MoK", "Skurri", "Morpheus",
}
local fontPosition = {}
for i, name in ipairs(fontOrder) do
fontPosition[name] = i
end
local function FontSorter(a, b)
local i, j = fontPosition[a], fontPosition[b]
if i and j then
return i < j
elseif i or j then
return i ~= nil
end
return a:lower() < b:lower()
end
-------------------------------
function InFlight:GetFontList() -- the fonts worth offering on this client
-------------------------------
-- A copy, as LibSharedMedia's own list is not ours to sort.
local western = not nonWesternLocales[GetLocale()]
local offered = {}
for _, name in ipairs(smed:List("font")) do
if not (western and westernFontReplacements[name]) then
offered[#offered + 1] = name
end
end
table.sort(offered, FontSorter)
return offered
end
-- How far up the bar's text moves for each font, as a share of the font size,
-- down if negative. Letters sit higher or lower in their line from one font to
-- the next, and by as much more as the font is larger, so a share holds at every
-- size where pixels would not: 0.05 is a pixel at size 20. These are the fonts
-- LibSharedMedia registers itself, on every client. Any other, another addon's
-- say, is not moved.
local fontOffsets = {
["2002"] = 0,
["2002 Bold"] = 0,
["AR CrystalzcuheiGBK Demibold"] = 0,
["AR ZhongkaiGBK Medium"] = 0.05,
["AR ZhongkaiGBK Medium (Combat)"] = 0.05,
["Arial Narrow"] = -0.05,
["Friz Quadrata TT"] = -0.05,
["MoK"] = 0,
["Morpheus"] = 0,
["Nimrod MT"] = -0.05,
["Skurri"] = -0.1,
-- koKR
["굵은 글꼴"] = 0,
["기본 글꼴"] = 0,
["데미지 글꼴"] = 0,
["퀘스트 글꼴"] = 0,
-- zhCN and zhTW, which share 聊天 as a name
["伤害数字"] = 0,
["默认"] = 0,
["聊天"] = 0,
["提示訊息"] = 0,
["傷害數字"] = 0,
["預設"] = 0,
}
-- How far up the text in that font at that size moves, in pixels.
-----------------------------------------
function InFlight:FontOffsetY(name, size)
-----------------------------------------
return (fontOffsets[name] or 0) * size
end
-- Sample flight for the preview. Two real flight points, picked at the
-- median length of the 731 names in the defaults, so that the preview shows the
-- bar carrying about as much text as it usually will.
local previewTotal, previewDone = 90, 54
local previewSrcName, previewDstName = "Menethil Harbor", "Nethergarde Keep"
local function SetToPreview() -- fill the bar with the preview's dummy flight
-- The spark rides the filled edge, so it takes the bar's value rather than the
-- elapsed time, which are the same thing only when Fill Up is on.
local value = look.fill and previewDone or previewTotal - previewDone
sb:SetMinMaxValues(0, previewTotal)
sb:SetValue(value)
sb:SetStatusBarColor(RGBA(look.barcolor))
PlaceSpark(Drawn("width") * value / previewTotal)
ShowSpark(true)
end
-- The unknown fill is for a flight of unknown length, unless a colour picker is
-- open for the other fill.
local function ShowsUnknown()
if pickedFill then
return pickedFill == "unknown"
end
return not previewActive and not endTime
end
-- The time text, matching the fill: beside the unknown one the time flown up to
-- "??", beside a known one the time to go, or flown with Count Up, of its length.
local function ShowTime(flown, total, totalText)
if ShowsUnknown() then
timeText:SetFormattedText("%s / %s", FormatTime(flown), FormatTime(nil))
elseif not total then
-- A flight of unknown length wearing the preview's known fill.
ShowTime(previewDone, previewTotal)
else
timeText:SetFormattedText("%s / %s",
FormatTime(look.countup and flown or total - flown), totalText or FormatTime(total))
end
end
local function ShowFill() -- the fill the bar shows now, known or unknown
if ShowsUnknown() then
SetToUnknown()
elseif previewActive or not endTime then
-- The preview, or the preview's flight standing in for one of unknown length.
SetToPreview()
else
ratio = Drawn("width") / endTime
sb:SetMinMaxValues(0, endTime)
sb:SetStatusBarColor(RGBA(look.barcolor))
ShowSpark(true)
end
-- The bar may have been showing another fill, so a flight's own value and time
-- go back on with the next update, which this makes the very next frame.
elapsed = throt
end
local function GetEstimatedTime(slot) -- estimates flight times based on hops
local numRoutes = GetNumRoutes(slot)
if numRoutes < 2 then
return
end
local taxiNodes = {[1] = taxiSrc, [numRoutes + 1] = GetNodeID(slot)}
for hop = 2, numRoutes, 1 do
taxiNodes[hop] = GetNodeID(TaxiGetNodeSlot(slot, hop, true))
end
-- Intermediate hops of cross-map routes cannot always be resolved to a node ID,
-- because GetNodeID only searches the currently viewed taxi map. Without every
-- node ID the per-hop durations cannot be summed, so skip the estimate (caller
-- falls back to "-:--") instead of erroring on a nil node below.
for hop = 1, numRoutes + 1, 1 do
if not taxiNodes[hop] then
return
end
end
local etimes = { 0 }
local prevNode = {}
local nextNode = {}
local srcNode = 1
local dstNode = #taxiNodes - 1
PrintD("|cff208080New Route:|r", taxiSrcName.."("..taxiSrc..") -->", ShortenName(TaxiNodeName(slot)).."("..taxiNodes[#taxiNodes]..") -", #taxiNodes, "hops")
while srcNode and srcNode < #taxiNodes do
while dstNode and dstNode > srcNode do
PrintD("|cff208080Node:|r", taxiNodes[srcNode].."("..srcNode..") -->", taxiNodes[dstNode].."("..dstNode..")")
local dstNodes = GetDstNodes(taxiNodes[srcNode], playerFaction)
if dstNodes then
if not etimes[dstNode] and dstNodes[taxiNodes[dstNode]] then
etimes[dstNode] = etimes[srcNode] + dstNodes[taxiNodes[dstNode]] * InFlight:SpeedFactor(taxiNodes[dstNode])
PrintD(taxiNodes[dstNode].."("..dstNode..") time:", FormatTime(etimes[srcNode]), "+", FormatTime(dstNodes[taxiNodes[dstNode]]), "=", FormatTime(etimes[dstNode]))
nextNode[srcNode] = dstNode - 1
prevNode[dstNode] = srcNode
srcNode = dstNode
dstNode = #taxiNodes
else
dstNode = dstNode - 1
end
else
srcNode = prevNode[srcNode]
dstNode = nextNode[srcNode]
end
end
if not etimes[#taxiNodes] then
PrintD("<<")
srcNode = prevNode[srcNode]
dstNode = nextNode[srcNode]
end
end
PrintD(".")
return etimes[#taxiNodes]
end
local function addDuration(flightTime, estimated)
if flightTime > 0 then
gtt:AddLine(L["Duration"]..(estimated and "~" or "")..FormatTime(flightTime), 1, 1, 1)
else
gtt:AddLine(L["Duration"].."-:--", 0.8, 0.8, 0.8)
end
gtt:Show()
end
local function postTaxiNodeOnButtonEnter(button) -- adds duration info to taxi node tooltips
local id = button:GetID()
if TaxiNodeGetType(id) ~= "REACHABLE" then
return
end
local tmpTaxiDst = GetNodeID(id)
local dstNodes = GetDstNodes(taxiSrc, playerFaction)
local duration = dstNodes and dstNodes[tmpTaxiDst]
if duration then
addDuration(duration * InFlight:SpeedFactor(tmpTaxiDst))
else
addDuration(GetEstimatedTime(id) or 0, true)
end
end
local function postFlightNodeOnButtonEnter(button) -- adds duration info to flight node tooltips
if button.taxiNodeData.state ~= Enum.FlightPathState.Reachable or GetTaxiMapID() == 994 then
return
end
local dstNodes = GetDstNodes(taxiSrc, playerFaction)
local tmpTaxiDst = button.taxiNodeData.nodeID
local duration = dstNodes and dstNodes[tmpTaxiDst]
if duration then
addDuration(duration * InFlight:SpeedFactor(tmpTaxiDst))
else
addDuration(GetEstimatedTime(button.taxiNodeData.slotIndex) or 0, true)
end
end
function InFlight:SetupInFlight()
SlashCmdList.INFLIGHT = function(arg1)
if arg1 == "export" then
self:ExportFlightTimes()
else
self:ShowSettings()
end
end
SLASH_INFLIGHT1 = "/inflight"
-- The addon settings panel. It scrolls, because with the bar's settings on it
-- the page is taller than the settings window, with the settings window's own
-- scroll bar, which ScrollFrameTemplate would not give the Classic clients.
local panel = CreateFrame("Frame")
-- Hidden until the settings window shows it. It only calls Show, which does
-- nothing to a frame that is already shown, so OnShow would never run the
-- first time the page is opened.
panel:Hide()
local scroll = LLS:CreateScrollFrame(panel)
scroll:SetPoint("TOPLEFT", 0, -4)
scroll:SetPoint("BOTTOMRIGHT", -28, 4)
local content = CreateFrame("Frame", nil, scroll)
content:SetSize(1, 1)
scroll:SetScrollChild(content)
local t1 = content:CreateFontString(nil, "ARTWORK")
t1:SetFontObject(GameFontNormalLarge)
t1:SetJustifyH("LEFT")
t1:SetJustifyV("TOP")
t1:SetPoint("TOPLEFT", 16, -12)
t1:SetText("|cff0040ffIn|cff00aaffFlight|r")
local t2 = content:CreateFontString(nil, "ARTWORK")
t2:SetFontObject(GameFontHighlight)
t2:SetJustifyH("LEFT")
t2:SetJustifyV("TOP")
SetPoints(t2, "TOPLEFT", t1, "BOTTOMLEFT", 0, -8, "RIGHT", content, "RIGHT", -16, 0)
t2:SetNonSpaceWrap(true)
local function GetInfo(field)
return C_AddOns.GetAddOnMetadata("InFlight", field) or "N/A"
end
t2:SetFormattedText("|cff00aaffVersion:|r %s\n\n%s|r", GetInfo("Version"), GetInfo("Notes"))
-- The settings menu, the same one right-clicking the bar opens.
-- These two are sized and placed like the button rows below them, in the
-- rows' two columns, the first of which starts under the text above.
local firstColumn, secondColumn, buttonWidth, buttonHeight = LLS:GetButtonLayout()
local menuButton = CreateFrame("Button", nil, content, "UIPanelButtonTemplate")
menuButton:SetText(L["Menu"])
menuButton:SetSize(buttonWidth, buttonHeight)
menuButton:SetScript("OnClick", InFlight.ShowSettings)
menuButton:SetPoint("TOPLEFT", t2, "BOTTOMLEFT", 0, -8)
-- A made-up flight on the bar, to see the settings without flying anywhere.
-- Greyed out while a real flight is on the bar, which shows them already.
local previewButton = CreateFrame("Button", nil, content, "UIPanelButtonTemplate")
previewButton:SetPoint("LEFT", menuButton, "LEFT", secondColumn - firstColumn, 0)
previewButton:SetMotionScriptsWhileDisabled(true)
previewButton:SetSize(buttonWidth, buttonHeight)
previewButton:SetText(L["ShowPreview"])
local function RefreshPreviewButton()
previewButton:SetEnabled(not InFlight:IsShown())
previewButton:SetText(previewRequests.settings and L["HidePreview"] or L["ShowPreview"])
end
previewButton:SetScript("OnClick", function()
InFlight:SetPreview("settings", not previewRequests.settings)
RefreshPreviewButton()
end)
previewButton:SetScript("OnEnter", function(self)
GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
GameTooltip_SetTitle(GameTooltip, self:GetText())
GameTooltip_AddNormalLine(GameTooltip, L["PreviewTooltip"], true)
if not self:IsEnabled() then
GameTooltip_AddBlankLineToTooltip(GameTooltip)
GameTooltip_AddErrorLine(GameTooltip, L["PreviewInFlight"], true)
end
GameTooltip:Show()
end)
previewButton:SetScript("OnLeave", GameTooltip_Hide)
-- The InFlight frame runs only while a real flight does, so its showing and
-- hiding is a flight starting and ending, which may happen with the page open.
-- Taking off also ends the preview, which the label has to follow.
InFlight:HookScript("OnShow", RefreshPreviewButton)
InFlight:HookScript("OnHide", RefreshPreviewButton)
-- Below the buttons and a divider, the same rows the layout editor shows for
-- the bar. They change whatever the settings menu changes, and their Revert
-- Changes goes back to how the bar looked when the page was opened. Drawn when
-- the page is first opened, because the edit mode registration needs the saved
-- variables. The rows' first column starts firstColumn in from their frame's
-- left edge, so the frame goes that far left of the buttons, which start under
-- the text above.
local rows, divider
-- The scroll range has to reach the last thing shown, which is only laid out
-- by the frame after the page shows or changes.
local function FitContent()
local last = rows and rows:IsShown() and rows or menuButton
local top, bottom = content:GetTop(), last:GetBottom()
if top and bottom then
content:SetHeight(top - bottom + 16)
end
end
-- A scroll child takes no size from anchors, so it follows the scroll frame's
-- width by hand. The text above the buttons wraps to it.
scroll:HookScript("OnSizeChanged", function(_, width)
content:SetWidth(width)
C_Timer.After(0, FitContent)
end)
-- The rows only show while the bar does, as a flight or the preview, because
-- what they change is how it looks.
local function ShowRowsWithBar()
local shown = InFlight:GetBar():IsShown()
rows:SetShown(shown)
divider:SetShown(shown)
C_Timer.After(0, FitContent)
end
panel:SetScript("OnShow", function()
if not rows then
-- Opened by the whole page, so that the rows hiding and showing with the
-- bar does not move the point their Revert Changes goes back to.
rows = InFlight:CreateSettingsRows(content, panel)
if rows then
-- 32 down leaves the divider 16 and 8 either side of it.
rows:SetPoint("TOPLEFT", menuButton, "BOTTOMLEFT", -firstColumn, -32)
-- The divider the library draws between rows, centred over them the
-- way it centres its own.
divider = content:CreateTexture(nil, "ARTWORK")
divider:SetTexture([[Interface\FriendsFrame\UI-FriendsFrame-OnlineDivider]])
divider:SetSize(330, 16)
divider:SetPoint("BOTTOM", rows, "TOP", 0, 8)
local bar = InFlight:GetBar()
bar:HookScript("OnShow", ShowRowsWithBar)
bar:HookScript("OnHide", ShowRowsWithBar)
end
end
if rows then
ShowRowsWithBar()
end
RefreshPreviewButton()
InFlight:SetBarAboveSettings(true)
end)
-- The preview belongs to this page, so leaving the page takes it away, and the
-- bar goes back below the rest of the interface.
panel:SetScript("OnHide", function()
InFlight:SetPreview("settings", false)
InFlight:SetBarAboveSettings(false)
end)
panel.name = "InFlight"
local category = Settings.RegisterCanvasLayoutCategory(panel, panel.name)
-- Needed to be able to call `Settings.OpenToCategory("InFlight")`
category.ID = panel.name
Settings.RegisterAddOnCategory(category)
InFlight.SetupInFlight = nil
end
----------------------------
function InFlight.Print(...) -- prefix chat messages
----------------------------
print("|cff0040ffIn|cff00aaffFlight|r:", ...)
end
Print = InFlight.Print
-----------------------------
function InFlight.PrintD(...) -- debug print
-----------------------------
if debug then
print("|cff00ff40In|cff00aaffFlight|r:", ...)
end
end
PrintD = InFlight.PrintD
-- Not exporting flight times from PTR or beta clients. They have been wrong before,
-- and would replace the correct times of the live game. Except for WoW Forever
-- (WOW_PROJECT_CAMELOT, only defined there), whose times are not known yet at all.
local function CanExport()
return PTR_IssueReporter == nil or WOW_PROJECT_ID == WOW_PROJECT_CAMELOT
end
-------------------------------------
function InFlight:ExportFlightTimes() -- for the developers, from /inflight export or the menu
-------------------------------------
if CanExport() then
self:ExportDB()
else
print("Only exporting from the live game client. PTR has been unreliable before.")
end
end
----------------------------------
function InFlight:GetDestination()
----------------------------------
return taxiDstName
end
---------------------------------
function InFlight:GetFlightTime()
---------------------------------
return endTime
end
-- The profile defaults each settings version replaced, the keys whose default
-- changed and what it was before. Version 1 is everything up to 12.0.011.
local replacedDefaults = {
[1] = {
p = "BOTTOM",
y = -170,
countup = true,
texture = "Blizzard",
width = 300,
height = 14,
border = "Blizzard Dialog",
barcolor = { r = 0.5, g = 0.5, b = 0.8, a = 1.0, },
unknowncolor = { r = 0.2, g = 0.2, b = 0.4, a = 1.0, },
backcolor = { r = 0.1, g = 0.1, b = 0.1, a = 0.6, },
bordercolor = { r = 0.6, g = 0.6, b = 0.6, a = 0.8, },
inline = false,
totext = " >--In Route To--> ",
font = "2002 Bold", -- outside Russian clients replaced, see InFlight:ReplacedFont
fontsize = 12,
outline = false,
outlinetime = false,
},
}
local settingsVersion = #replacedDefaults + 1
-- AceDB leaves out of the saved variables every value that matches its default,
-- so a value missing from a profile stands for whatever the default was when it
-- was saved. A changed default would therefore change the bar of everyone who
-- never touched that setting. So every existing profile first gets the defaults
-- it was saved under written in as its own values, and settingsVersion records
-- which defaults the profiles have been brought past.
--
-- This has to run before AceDB fills the new defaults in, because until then an
-- absent value can only mean the old default. AceDB strips a colour channel by
-- channel, so a colour can be stored in part, and its missing channels are
-- filled in the same way. Values that match the new defaults are left out again
-- at logout, as usual.
--
-- A fresh install never had the old defaults, and neither has a profile made
-- from now on, so only the profiles there are now are brought along.
-----------------------------------------------
function InFlight:MigrateSettings(freshInstall)
-----------------------------------------------
if freshInstall then
InFlightDB.settingsVersion = settingsVersion
end
-- A profile that only ever held defaults may never have been saved at all.
-- It was on the old defaults all the same.
local profiles = InFlightDB.profiles or {}
InFlightDB.profiles = profiles
if (InFlightDB.settingsVersion or 1) < settingsVersion then
profiles.Default = profiles.Default or {}
for _, name in pairs(InFlightDB.profileKeys or {}) do
profiles[name] = profiles[name] or {}
end
end
for version = InFlightDB.settingsVersion or 1, settingsVersion - 1 do
for _, savedProfile in pairs(profiles) do
for key, old in pairs(replacedDefaults[version]) do
local saved = savedProfile[key]
if type(old) == "table" then
if type(saved) ~= "table" then
saved = {}
savedProfile[key] = saved
end
for channel, value in pairs(old) do
if saved[channel] == nil then
saved[channel] = value
end
end
-- Builds made while the "to" text was on its way to its new default
-- already wrote the old one in, and left this flag behind.
elseif saved == nil and not (key == "totext" and InFlightDB.totextMigrated) then