/
cawidgets.lua
2644 lines (2239 loc) · 67.5 KB
/
cawidgets.lua
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
-- $Id: cawidgets.lua 4261 2009-03-31 16:34:36Z licho $
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- file: widgets.lua
-- brief: the widget manager, a call-in router
-- author: Dave Rodgers
--
-- modified by jK and quantum
--
-- Copyright (C) 2007,2008,2009.
-- Licensed under the terms of the GNU GPL, v2 or later.
--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local ignorelist = {count = 0, ignorees = {} } -- Ignore workaround for WG table.
local playerstate = {} -- for PlayerChangedTeam, PlayerResigned
local resetWidgetDetailLevel = false -- has widget detail level changed
local myPlayerID = Spring.GetLocalPlayerID()
local ORDER_VERSION = 8 --- change this to reset enabled/disabled widgets
local DATA_VERSION = 9 -- change this to reset widget settings
local PROFILE_INIT = false
local MEMORY_DEBUG = false
local vfs = VFS
local vfsInclude = vfs.Include
local vfsGame = vfs.GAME
WG = {}
Spring.Utilities = {}
Spring.Utilities.json = vfsInclude("LuaRules/Utilities/json.lua" , nil, vfsGame)
vfsInclude("LuaRules/Utilities/globals.lua" , nil, vfsGame)
vfsInclude("LuaRules/Utilities/tablefunctions.lua" , nil, vfsGame)
vfsInclude("LuaRules/Utilities/debugFunctions.lua" , nil, vfsGame)
vfsInclude("LuaRules/Utilities/versionCompare.lua" , nil, vfsGame)
vfsInclude("LuaRules/Utilities/unitStates.lua" , nil, vfsGame)
vfsInclude("LuaRules/Utilities/gametype.lua" , nil, vfsGame)
vfsInclude("LuaRules/Utilities/vector.lua" , nil, vfsGame)
vfsInclude("LuaRules/Utilities/unitTypeChecker.lua" , nil, vfsGame)
vfsInclude("LuaRules/Utilities/function_override.lua", nil, vfsGame)
vfsInclude("LuaRules/Utilities/minimap.lua" , nil, vfsGame)
vfsInclude("LuaRules/Utilities/lobbyStuff.lua" , nil, vfsGame)
vfsInclude("LuaUI/Utilities/truncate.lua" , nil, vfsGame)
vfsInclude("LuaUI/keysym.lua" , nil, vfsGame)
vfsInclude("LuaUI/system.lua" , nil, vfsGame)
vfsInclude("LuaUI/cache.lua" , nil, vfsGame)
vfsInclude("LuaUI/callins.lua" , nil, vfsGame)
vfsInclude("LuaUI/savetable.lua" , nil, vfsGame)
local CheckLUAFileAndBackup = vfsInclude("LuaUI/file_backups.lua", nil, vfsGame)
local MessageProcessor = vfsInclude("LuaUI/chat_preprocess.lua", nil, vfsGame)
local ORDER_FILENAME = LUAUI_DIRNAME .. 'Config/ZK_order.lua'
local CONFIG_FILENAME = LUAUI_DIRNAME .. 'Config/ZK_data.lua'
local WIDGET_DIRNAME = LUAUI_DIRNAME .. 'Widgets/'
-- make/load backup config in case of corruption
CheckLUAFileAndBackup(ORDER_FILENAME)
CheckLUAFileAndBackup(CONFIG_FILENAME)
local HANDLER_BASENAME = "cawidgets.lua"
local SELECTOR_BASENAME = 'selector.lua'
local lastTime = PROFILE_INIT and Spring.GetTimer()
local function TimeLoad(name)
if PROFILE_INIT then
local timeDiff = Spring.DiffTimers(Spring.GetTimer(), lastTime)
Spring.Echo(name, timeDiff)
lastTime = Spring.GetTimer()
end
end
do
local isMission = Game.modDesc:find("Mission Mutator")
if isMission then -- all missions will be forced to use a specific name
if not VFS.FileExists(ORDER_FILENAME) or not VFS.FileExists(CONFIG_FILENAME) then
ORDER_FILENAME = LUAUI_DIRNAME .. 'Config/ZK_order.lua' --use "ZK" name when running any mission mod (provided that there's no existing config file)
CONFIG_FILENAME = LUAUI_DIRNAME .. 'Config/ZK_data.lua'
end
end
end
local SAFEWRAP = 1
-- 0: disabled
-- 1: enabled, but can be overriden by widget.GetInfo().unsafe
-- 2: always enabled
local SAFEDRAW = false -- requires SAFEWRAP to work
local glPopAttrib = gl.PopAttrib
local glPushAttrib = gl.PushAttrib
local pairs = pairs
local ipairs = ipairs
-- read local widgets config
local localWidgetsFirst = false
local localWidgets = false
local disableLocalWidgets = (
Spring.GetModOptions().disable_local_widgets and
Spring.GetModOptions().disable_local_widgets ~= "0" and
Spring.GetModOptions().disable_local_widgets ~= 0 and
not (Spring.GetSpectatingState() or Spring.IsReplay())
)
if VFS.FileExists(CONFIG_FILENAME) then --check config file whether user want to use localWidgetsFirst
if not disableLocalWidgets then
local cadata = VFS.Include(CONFIG_FILENAME)
if cadata and cadata["Local Widgets Config"] then
localWidgetsFirst = cadata["Local Widgets Config"].useLocalWidgetsFirst or true
localWidgets = cadata["Local Widgets Config"].useLocalWidgets or true
end
end
end
Spring.Echo("localWidgets", disableLocalWidgets, localWidgets, localWidgetsFirst)
local VFSMODE
VFSMODE = localWidgetsFirst and VFS.RAW_FIRST
VFSMODE = VFSMODE or localWidgets and VFS.ZIP_FIRST
VFSMODE = VFSMODE or VFS.ZIP
local detailLevel = Spring.GetConfigInt("widgetDetailLevel", 3)
--------------------------------------------------------------------------------
-- install bindings for TweakMode and the Widget Selector
Spring.SendCommands({
"unbindkeyset Any+f11",
"unbindkeyset Ctrl+f11",
"bind f11 luaui selector",
"bind C+f11 luaui tweakgui",
"echo LuaUI: bound F11 to the widget selector",
"echo LuaUI: bound CTRL+F11 to tweak mode"
})
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- the widgetHandler object
--
widgetHandler = {
widgets = {},
configData = {},
orderList = {},
knownWidgets = {},
knownCount = 0,
knownChanged = true,
commands = {},
customCommands = {},
inCommandsChanged = false,
autoModWidgets = false,
actionHandler = include("actions.lua"),
WG = WG, -- shared table for widgets
globals = {}, -- global vars/funcs
mouseOwner = nil,
ownedButton = 0,
tweakMode = false,
}
-- these call-ins are set to 'nil' if not used
-- they are setup in UpdateCallIns()
local flexCallIns = {
'PlayerChangedTeam',
'PlayerResigned',
'GameOver',
'GamePaused',
'GameFrame',
'GameSetup',
'TeamDied',
'TeamChanged',
'PlayerAdded',
'PlayerChanged',
"PlayerRemoved",
'ShockFront',
'WorldTooltip',
'MapDrawCmd',
'DefaultCommand',
'UnitCreated',
'UnitFinished',
'UnitResurrected',
'UnitReverseBuilt',
'UnitFromFactory',
'UnitDestroyed',
'UnitDestroyedByTeam',
'RenderUnitDestroyed',
'UnitExperience',
'UnitTaken',
'UnitGiven',
'UnitIdle',
'UnitCommand',
'UnitCmdDone',
'UnitDamaged',
'UnitStunned',
'UnitEnteredRadar',
'UnitEnteredLos',
'UnitLeftRadar',
'UnitLeftLos',
'UnitEnteredWater',
'UnitEnteredAir',
'UnitLeftWater',
'UnitLeftAir',
'UnitSeismicPing',
'UnitLoaded',
'UnitUnloaded',
'UnitCloaked',
'UnitDecloaked',
'UnitMoveFailed',
'RecvLuaMsg',
'StockpileChanged',
'DrawGenesis',
'DrawWorld',
'DrawWorldPreUnit',
'DrawWorldPreParticles',
'DrawWorldShadow',
'DrawWorldReflection',
'DrawWorldRefraction',
'DrawUnitsPostDeferred',
'DrawFeaturesPostDeferred',
'DrawScreenEffects',
'DrawScreenPost',
'DrawInMiniMap',
'DrawOpaqueUnitsLua',
'DrawOpaqueFeaturesLua',
'DrawAlphaUnitsLua',
'DrawAlphaFeaturesLua',
'DrawShadowUnitsLua',
'DrawShadowFeaturesLua',
'RecvSkirmishAIMessage',
'SelectionChanged',
'AddConsoleMessage',
'Save',
'Load',
'GameID',
-- From gadgets
"UnitStructureMoved",
'MissileFired',
'MissileDestroyed',
}
local flexCallInMap = {}
for _, ci in ipairs(flexCallIns) do
flexCallInMap[ci] = true
end
local reverseCallIns = {
'DrawScreen',
'DrawGenesis',
'DrawWorld',
'DrawWorldPreUnit',
'DrawWorldPreParticles',
'DrawWorldShadow',
'DrawWorldReflection',
'DrawWorldRefraction',
'DrawUnitsPostDeferred',
'DrawFeaturesPostDeferred',
'DrawScreenEffects',
'DrawScreenPost',
'DrawInMiniMap',
'DefaultCommand',
}
local reverseCallInMap = {}
for _, ci in ipairs(reverseCallIns) do
reverseCallInMap[ci] = true
end
local callInLists = {
'PlayerChangedTeam',
'PlayerResigned',
'GamePreload',
'GameStart',
'Shutdown',
'Update',
'TextCommand',
'CommandNotify',
'UnitCommandNotify',
'AddConsoleLine',
'ReceiveUserInfo',
-- widget:ReceiveUserInfo(info)
-- info is a table with keys name, avatar, icon, badges, admin, clan, faction, country
-- values are strings except:
-- badges: comma separated string of badge names
-- admin: boolean
'ViewResize',
'DrawScreen',
'KeyPress',
'KeyRelease',
'TextInput',
'MousePress',
'MouseWheel',
'JoyAxis',
'JoyHat',
'JoyButtonDown',
'JoyButtonUp',
'IsAbove',
'GetTooltip',
'GroupChanged',
'CommandsChanged',
'TweakMousePress',
'TweakMouseWheel',
'TweakIsAbove',
'TweakGetTooltip',
'GameProgress',
'UnsyncedHeightMapUpdate',
'VisibleUnitAdded',
'VisibleUnitRemoved',
'VisibleUnitsChanged',
'AlliedUnitAdded',
'AlliedUnitRemoved',
'AlliedUnitsChanged',
-- these use mouseOwner instead of lists
-- 'MouseMove',
-- 'MouseRelease',
-- 'TweakKeyPress',
-- 'TweakKeyRelease',
-- 'TweakMouseMove',
-- 'TweakMouseRelease',
-- uses the DrawScreenList
-- 'TweakDrawScreen',
}
-- append the flex call-ins
for _, uci in ipairs(flexCallIns) do
table.insert(callInLists, uci)
end
-- initialize the call-in lists
do
for _, listname in ipairs(callInLists) do
widgetHandler[listname..'List'] = {}
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- array-table reverse iterator
--
-- all callin handlers use this so that widgets can
-- RemoveWidget() themselves (during iteration over
-- a callin list) without causing a miscount
--
-- Reverse iteration for drawing is achieved by adding
-- callins to the lists in the non-reverse order.
--
-- c.f. Array{Insert,Remove,InsertReverse}
--
local function r_iter(tbl, key)
if (key <= 1) then
return nil
end
-- next idx, next val
return (key - 1), tbl[key - 1]
end
local function r_ipairs(tbl)
return r_iter, tbl, (1 + #tbl)
end
-- String helper to split by delimiter (userinfo)
function string:split(delimiter)
local result = { }
local from = 1
local delim_from, delim_to = string.find( self, delimiter, from )
while delim_from do
table.insert( result, string.sub( self, from , delim_from-1 ) )
from = delim_to + 1
delim_from, delim_to = string.find( self, delimiter, from )
end
table.insert( result, string.sub( self, from ) )
return result
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- helper functions
---include chat preprocess here
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widgetHandler:LoadOrderList()
local chunk, err = loadfile(ORDER_FILENAME)
if (chunk == nil) then
self.orderList = {} -- safety
return {}
else
local tmp = {}
setfenv(chunk, tmp)
self.orderList = chunk()
if (not self.orderList) then
self.orderList = {} -- safety
end
if (self.orderList.version or 0) < ORDER_VERSION then
self.orderList = {}
self.orderList.version = ORDER_VERSION
end
local detailLevel = Spring.GetConfigInt("widgetDetailLevel", 2)
if (self.orderList.lastWidgetDetailLevel ~= detailLevel) then
resetWidgetDetailLevel = true
self.orderList.lastWidgetDetailLevel = detailLevel
end
end
end
function widgetHandler:SaveOrderList()
-- update the current order
for i, w in ipairs(self.widgets) do
self.orderList[w.whInfo.name] = i
end
table.save(self.orderList, ORDER_FILENAME, '-- Widget Order List (0 disables a widget)')
end
--------------------------------------------------------------------------------
function widgetHandler:LoadConfigData()
local chunk, err = loadfile(CONFIG_FILENAME)
if (chunk == nil) then
return {}
else
local tmp = {}
setfenv(chunk, tmp)
self.configData = chunk()
if (not self.configData) then
self.configData = {} -- safety
end
if (self.configData.version or 0) < DATA_VERSION then
self.configData = {}
self.configData.version = DATA_VERSION
end
end
end
function widgetHandler:SaveConfigData()
resetWidgetDetailLevel = false
self:LoadConfigData()
for _, w in ipairs(self.widgets) do
if (w.GetConfigData) then
local ok, err = pcall(function()
self.configData[w.whInfo.name] = w:GetConfigData()
end)
if not ok then Spring.Log(HANDLER_BASENAME, LOG.ERROR, "Failed to GetConfigData from: " .. w.whInfo.name.." ("..err..")") end
end
end
table.save(self.configData, CONFIG_FILENAME, '-- Widget Custom Data')
end
function widgetHandler:SendConfigData()
self:LoadConfigData()
for _, w in ipairs(self.widgets) do
local data = self.configData[w.whInfo.name]
if (w.SetConfigData and data) then
w:SetConfigData(data)
end
end
end
--------------------------------------------------------------------------------
local function InitPlayerData(playerID)
local _, _, spectator, teamID = Spring.GetPlayerInfo(playerID)
return {team = teamID, spectator = spectator}
end
function widgetHandler:Initialize()
TimeLoad("==== widgetHandler Begin ====")
local gaia = Spring.GetGaiaTeamID()
local playerList = Spring.GetPlayerList()
for i = 1, #playerList do
playerstate[playerList[i]] = InitPlayerData(playerList[i])
end
-- Add ignorelist --
--Spring.Echo("Spring.GetMyPlayerID()", Spring.GetMyPlayerID())
local customkeys = select(10, Spring.GetPlayerInfo(Spring.GetMyPlayerID(), true))
--Spring.Echo("Spring.GetMyPlayerID() done", customkeys)
if customkeys["ignored"] then
if string.find(customkeys["ignored"], ",") then
local newignorelist = string.gsub(customkeys["ignored"], ",", " ")
Spring.Echo("Setting Serverside ignorelist: " .. newignorelist)
for ignoree in string.gmatch(newignorelist, "%S+") do
ignorelist.ignorees[ignoree] = true
ignorelist.count = ignorelist.count + 1
end
newignorelist = nil
elseif string.len(customkeys["ignored"]) > 1 then
ignorelist.ignorees[customkeys["ignored"]] = true
ignorelist.count = ignorelist.count + 1
end
end
customkeys = nil
TimeLoad("Add ignorelist")
self:LoadOrderList()
TimeLoad("LoadOrderList")
self:LoadConfigData()
TimeLoad("LoadConfigData")
local autoModWidgets = Spring.GetConfigInt('LuaAutoModWidgets', 1)
self.autoModWidgets = (autoModWidgets ~= 0)
-- create the "LuaUI/Config" directory
Spring.CreateDir(LUAUI_DIRNAME .. 'Config')
local unsortedWidgets = {}
TimeLoad("Start loading widget files")
-- stuff the widgets into unsortedWidgets
local widgetFiles = VFS.DirList(WIDGET_DIRNAME, "*.lua", VFSMODE)
local wantYield = Spring.Yield and Spring.Yield()
for k, wf in ipairs(widgetFiles) do
local widget = self:LoadWidget(wf)
TimeLoad("LoadWidget " .. wf)
if (widget) then
table.insert(unsortedWidgets, widget)
end
if wantYield then
Spring.Yield()
end
end
TimeLoad("End loading widget files")
-- sort the widgets
table.sort(unsortedWidgets, function(w1, w2)
local l1 = w1.whInfo.layer
local l2 = w2.whInfo.layer
if (l1 ~= l2) then
return (l1 < l2)
end
local n1 = w1.whInfo.name
local n2 = w2.whInfo.name
local o1 = self.orderList[n1]
local o2 = self.orderList[n2]
if (o1 ~= o2) then
return (o1 < o2)
else
return (n1 < n2)
end
end)
TimeLoad("sort the widgets")
-- first add the api widgets
for _, w in ipairs(unsortedWidgets) do
if (w.whInfo.api) then
widgetHandler:InsertWidget(w)
local name = w.whInfo.name
local basename = w.whInfo.basename
TimeLoad("Add widget " .. name)
Spring.Echo(string.format("Loaded API widget: %-18s <%s>", name, basename))
end
end
-- add the widgets
for _, w in ipairs(unsortedWidgets) do
if (not w.whInfo.api) then
widgetHandler:InsertWidget(w)
local name = w.whInfo.name
local basename = w.whInfo.basename
TimeLoad("Add widget " .. name)
Spring.Echo(string.format("Loaded widget: %-18s <%s>", name, basename))
end
end
-- save the active widgets, and their ordering
self:SaveOrderList()
TimeLoad("SaveOrderList")
self:SaveConfigData()
TimeLoad("SaveConfigData")
end
local springRestricted = {}
local restrictedFunctions = {
--[[ These are blocked for being unfair because of latency and performance.
Feel free to make a gadget instead though. See https://zero-k.info/Forum/Thread/34108 ]]
"GetVisibleProjectiles",
"GetProjectilesInRectangle",
}
local restrictedWhitelist = {
--[[ Other widgets have security holes and there is
no reason for them to have access anyway. ]]
['LuaUI/Widgets/gfx_projectile_lights.lua'] = true,
}
for i = 1, #restrictedFunctions do
local funcName = restrictedFunctions[i]
springRestricted[funcName] = Spring[funcName]
Spring[funcName] = nil
end
function widgetHandler:LoadWidget(filename, _VFSMODE)
local kbytes = 0
if MEMORY_DEBUG then
collectgarbage("collect") -- call it twice, mark
collectgarbage("collect") -- sweep
kbytes = gcinfo()
end
_VFSMODE = _VFSMODE or VFSMODE
local basename = Basename(filename)
local fromZip
if _VFSMODE == VFS.ZIP then
fromZip = true
elseif _VFSMODE == VFS.RAW_FIRST then
fromZip = not VFS.FileExists(filename, VFS.RAW_ONLY)
else
fromZip = VFS.FileExists(filename, VFS.ZIP_ONLY)
end
local text = VFS.LoadFile(filename, _VFSMODE)
if (text == nil) then
Spring.Log(HANDLER_BASENAME, LOG.ERROR, 'Failed to load: ' .. basename .. ' (missing file: ' .. filename ..')')
return nil
end
local chunk, err = loadstring(text, filename)
if (chunk == nil) then
Spring.Log(HANDLER_BASENAME, LOG.ERROR, 'Failed to load: ' .. basename, err)
return nil
end
local exposeRestricted = fromZip and restrictedWhitelist[filename]
local widget = widgetHandler:NewWidget(exposeRestricted)
setfenv(chunk, widget)
local success, err = pcall(chunk)
if (not success) then
Spring.Echo('Failed to load: ' .. basename, err)
return nil
end
if (err == false) then
return nil -- widget asked for a silent death
end
-- raw access to widgetHandler
if (widget.GetInfo and widget:GetInfo().handler) then
widget.widgetHandler = self
end
self:FinalizeWidget(widget, filename, basename)
local name = widget.whInfo.name
if (basename == SELECTOR_BASENAME) then
self.orderList[name] = 1 -- always enabled
end
err = self:ValidateWidget(widget)
if (err) then
Spring.Echo('Failed to load: ' .. basename .. ' (' .. err .. ')')
return nil
end
local knownInfo = self.knownWidgets[name]
if (knownInfo) then
if (knownInfo.active) then
Spring.Log(HANDLER_BASENAME, LOG.ERROR, 'Failed to load: ' .. basename .. ' (duplicate name)')
return nil
end
else
-- create a knownInfo table
knownInfo = {}
knownInfo.desc = widget.whInfo.desc
knownInfo.author = widget.whInfo.author
knownInfo.basename = widget.whInfo.basename
knownInfo.filename = widget.whInfo.filename
knownInfo.alwaysStart = widget.whInfo.alwaysStart
knownInfo.fromZip = fromZip
self.knownWidgets[name] = knownInfo
self.knownCount = self.knownCount + 1
self.knownChanged = true
end
knownInfo.active = true
if (widget.GetInfo == nil) then
Spring.Log(HANDLER_BASENAME, LOG.ERROR, 'Failed to load: ' .. basename .. ' (no GetInfo() call)')
return nil
end
local info = widget:GetInfo()
local order = self.orderList[name]
local enabled = ((order ~= nil) and (order > 0)) or ((order == nil) and -- unknown widget
(info.enabled and ((not knownInfo.fromZip) or self.autoModWidgets))) or info.alwaysStart
if resetWidgetDetailLevel and info.detailsDefault ~= nil then
if type(info.detailsDefault) == "table" then
enabled = info.detailsDefault[detailLevel] and true
elseif type(info.detailsDefault) == "number" then
enabled = detailLevel >= info.detailsDefault
elseif tonumber(info.detailsDefault) then
enabled = detailLevel >= tonumber(info.detailsDefault)
end
end
if (enabled) then
-- this will be an active widget
if (order == nil) then
self.orderList[name] = 12345 -- back of the pack
else
self.orderList[name] = order
end
else
self.orderList[name] = 0
self.knownWidgets[name].active = false
return nil
end
-- load the config data
local config = self.configData[name]
if (widget.SetConfigData and config) then
widget:SetConfigData(config)
end
if kbytes > 0 then
collectgarbage("collect") -- mark
collectgarbage("collect") -- sweep
Spring.Echo("LoadWidget\t" .. filename .. "\t" .. (gcinfo() - kbytes) .. "\t" .. gcinfo())
end
return widget
end
function widgetHandler:NewWidget(exposeRestricted)
local widget = {}
-- copy the system calls into the widget table
-- don't use metatable redirection to System so as not to pollute it
for k, v in pairs(System) do
widget[k] = v
end
if exposeRestricted then
widget.SpringRestricted = springRestricted
end
widget.WG = self.WG -- the shared table
widget.widget = widget -- easy self referencing
-- wrapped calls (closures)
widget.widgetHandler = {}
local wh = widget.widgetHandler
local self = self
widget.include = function (f, _, MODE) return include(f, widget, MODE) end
wh.ForceLayout = function (_) self:ForceLayout() end
wh.RaiseWidget = function (_) self:RaiseWidget(widget) end
wh.LowerWidget = function (_) self:LowerWidget(widget) end
wh.RemoveWidget = function (_) self:RemoveWidget(widget) end
wh.GetCommands = function (_) return self.commands end
wh.InTweakMode = function (_) return self.tweakMode end
wh.GetViewSizes = function (_) return self:GetViewSizes() end
wh.GetHourTimer = function (_) return self:GetHourTimer() end
wh.IsMouseOwner = function (_) return (self.mouseOwner == widget) end
wh.DisownMouse = function (_)
if (self.mouseOwner == widget) then
self.mouseOwner = nil
end
end
wh.Ignore = function (_, name)
if not ignorelist.ignorees[name] then
ignorelist.ignorees[name] = true
ignorelist.count = ignorelist.count + 1
end
end
wh.Unignore = function (_, name)
ignorelist.ignorees[name] = nil
ignorelist.count = ignorelist.count - 1
end
wh.GetIgnoreList = function (_)
return ignorelist["ignorees"], ignorelist.count
end
wh.UpdateCallIn = function (_, name)
self:UpdateWidgetCallIn(name, widget)
end
wh.RemoveCallIn = function (_, name)
self:RemoveWidgetCallIn(name, widget)
end
wh.AddAction = function (_, cmd, func, data, types)
return self.actionHandler:AddAction(widget, cmd, func, data, types)
end
wh.RemoveAction = function (_, cmd, types)
return self.actionHandler:RemoveAction(widget, cmd, types)
end
wh.AddLayoutCommand = function (_, cmd)
if (self.inCommandsChanged) then
table.insert(self.customCommands, cmd)
else
Spring.Log(HANDLER_BASENAME, LOG.ERROR, "AddLayoutCommand() can only be used in CommandsChanged()")
end
end
wh.RegisterGlobal = function(_, name, value)
return self:RegisterGlobal(widget, name, value)
end
wh.DeregisterGlobal = function(_, name)
return self:DeregisterGlobal(widget, name)
end
wh.SetGlobal = function(_, name, value)
return self:SetGlobal(widget, name, value)
end
wh.ConfigLayoutHandler = function(_, d) self:ConfigLayoutHandler(d) end
----
widget.ProcessConsoleBuffer = function(_, _, num) -- FIXME: probably not the least hacky way to make ProcessConsoleBuffer accessible to widgets
return MessageProcessor:ProcessConsoleBuffer(num) --chat_preprocess.lua
end
----
return widget
end
function widgetHandler:FinalizeWidget(widget, filename, basename)
local wi
if (widget.GetInfo == nil) then
wi = {}
wi.filename = filename
wi.basename = basename
wi.name = basename
wi.layer = 0
else
local info = widget:GetInfo()
wi = info
wi.filename = filename
wi.basename = basename
wi.name = wi.name or basename
wi.layer = wi.layer or 0
wi.desc = wi.desc or ""
wi.author = wi.author or ""
wi.license = wi.license or ""
wi.enabled = wi.enabled or false
wi.api = wi.api or false
end
widget.whInfo = {} -- a proxy table
local mt = {
__index = wi,
__newindex = function() error("whInfo tables are read-only") end,
__metatable = "protected"
}
setmetatable(widget.whInfo, mt)
end
function widgetHandler:ValidateWidget(widget)
if (widget.GetTooltip and not widget.IsAbove) then
return "Widget has GetTooltip() but not IsAbove()"
end
if (widget.TweakGetTooltip and not widget.TweakIsAbove) then
return "Widget has TweakGetTooltip() but not TweakIsAbove()"
end
return nil
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function HandleError(widget, funcName, status, ...)
if (status) then
return ...
end
if (funcName ~= 'Shutdown') then
widgetHandler:RemoveWidget(widget)
else
Spring.Log(HANDLER_BASENAME, LOG.ERROR, 'Error in Shutdown()')
end
local name = widget.whInfo.name
local error_message = select(1, ...)
Spring.Log(HANDLER_BASENAME, LOG.ERROR, 'Error in ' .. funcName ..'(): ' .. tostring(error_message))
Spring.Log(HANDLER_BASENAME, LOG.ERROR, 'Removed widget: ' .. name)
return nil
end
local function SafeWrapFuncNoGL(func, funcName)
return function(w, ...)
return HandleError(w, funcName, pcall(func, w, ...))
end
end
local function SafeWrapFuncGL(func, funcName)
local wh = widgetHandler
return function(w, ...)
glPushAttrib(GL.ALL_ATTRIB_BITS)
local r1, r2, r3 = pcall(func, w, ...)
glPopAttrib()
if r1 then
return r2, r3
else
if (funcName ~= 'Shutdown') then
widgetHandler:RemoveWidget(w)
else
Spring.Log(HANDLER_BASENAME, LOG.ERROR, 'Error in Shutdown()')
end
local name = w.whInfo.name
Spring.Log(HANDLER_BASENAME, LOG.ERROR, 'Error in ' .. funcName ..'(): ' .. tostring(r[2]))
Spring.Log(HANDLER_BASENAME, LOG.ERROR, 'Removed widget: ' .. name)
return nil
end
end
end
local function SafeWrapFunc(func, funcName)
if (not SAFEDRAW) then
return SafeWrapFuncNoGL(func, funcName)
else
if (string.sub(funcName, 1, 4) ~= 'Draw') then
return SafeWrapFuncNoGL(func, funcName)
else
return SafeWrapFuncGL(func, funcName)
end
end
end
local function SafeWrapWidget(widget)
if (SAFEWRAP <= 0) then
return
elseif (SAFEWRAP == 1) then
if (widget.GetInfo and widget.GetInfo().unsafe) then
Spring.Log(HANDLER_BASENAME, LOG.ERROR, 'LuaUI: loaded unsafe widget: ' .. widget.whInfo.name)
return
end
end
for _, ciName in ipairs(callInLists) do
if (widget[ciName]) then
widget[ciName] = SafeWrapFunc(widget[ciName], ciName)
end
end
if (widget.Initialize) then
widget.Initialize = SafeWrapFunc(widget.Initialize, 'Initialize')
end
end
--------------------------------------------------------------------------------
local function ArrayInsert(t, f, w)
if (f) then
local layer = w.whInfo.layer
local index = 1
for i, v in ipairs(t) do
if (v == w) then
return -- already in the table
end
-- insert-sort the gadget based on its layer
-- note: reversed value ordering, highest to lowest
-- iteration over the callin lists is also reversed
if (layer < v.whInfo.layer) then
index = i + 1
end
end
table.insert(t, index, w)
end
end
-- This is the reverse insertion because arrays are iterated over backwards.
local function ArrayInsertReverse(t, f, w)
if (f) then
local layer = w.whInfo.layer
local index = 1
for i, v in ipairs(t) do
if (v == w) then
return -- already in the table