-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLibSFUtils.lua
More file actions
1223 lines (1077 loc) · 38.6 KB
/
Copy pathLibSFUtils.lua
File metadata and controls
1223 lines (1077 loc) · 38.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
-- LibSFUtils is already defined in prior loaded file
local sfutil = LibSFUtils or {}
local SF_Color = sfutil.SF_Color
--[[ ---------------------
convenience color tables
These tables contain definitions for commonly used colors along with
names to easily indicate the color.
Using these can somewhat reduce your addon's computational load as
these are calculated once, when the library is loaded instead of
whenever you go from hex to ZO_ColorDef/rgb or from ZO_ColorDef/rgb
to hex again. It might be miniscule, but when you are doing the
ZO_ColorDef creations and conversions with a lot of colors many many
times, it all adds up.
SF_Color is defined in SFUtils_Color.lua
--]]
sfutil.colors = {
gold = SF_Color:New("FFD700"), -- {hex ="FFD700", rgb = {1, 215/255, 0}, },
red = SF_Color:New("FF0000"), -- {hex ="FF0000", rgb = {1, 0, 0}, },
teal = SF_Color:New("00EFBB"), -- {hex ="00EFBB", rgb = {0, 239/255, 187/255}, },
lime = SF_Color:New("00E600"), -- {hex ="00E600", rgb = {0, 230/255, 0}, },
green = SF_Color:New("2dc50e"), -- {hex ="2dc50e", rgb = {45/255, 197/255, 14/255}, },
goldenrod = SF_Color:New("EECA00"), -- {hex ="EECA00", rgb = {238/255, 202/255, 0}, },
blue = SF_Color:New("0000FF"), -- {hex ="0000FF", rgb = {0, 0, 1}, },
purple = SF_Color:New("b000ff"), -- {hex ="b000ff", rgb = {176/255, 0, 1}, },
bronze = SF_Color:New("ff9900"), -- {hex ="ff9900", rgb = {1, 153/255, 0}, },
ltskyblue = SF_Color:New("87cefa"), -- {hex ="87cefa", rgb = {135/255, 206/255, 250/255}, },
lemon = SF_Color:New("FFFACD"), -- {hex ="FFFACD", rgb = {1, 250/255, 205/255}, },
mocassin = SF_Color:New("FFE4B5"), -- {hex ="FFE4B5", rgb = {1, 228/255, 181/255}, },
frangipani = SF_Color:New("fad7a0"),
--brick = SF_Color:New("cb4154"),
aquamarine = SF_Color:New("7fffd4"), -- {hex ="7fffd4", rgb = {127/255, 1, 212/255}, },
lightsalmon = SF_Color:New("FFA07A"), -- {hex ="FFA07A", rgb = {1, 160/255, 122/255}, },
junk = SF_Color:New("7f7f7f"), -- {hex = "7f7f7f", rgb = {127/255, 127/255, 127/255}, },
normal = SF_Color:New("FFFFFF"), -- {hex = "FFFFFF", rgb = {1, 1, 1}, },
fine = SF_Color:New("2dc50e"), -- {hex = "2dc50e", rgb = {45/255, 197/255, 14/255}, },
superior = SF_Color:New("3a92ff"), -- {hex = "3a92ff", rgb = {58/255, 146/255, 1}, },
epic = SF_Color:New("a02ef7"), -- {hex = "a02ef7", rgb = {160/255, 46/255, 247/255}, },
legendary = SF_Color:New("EECA00"), -- {hex = "EECA00", rgb = {238/255, 202/255, 0}, },
mythic = SF_Color:New("ffaa00") -- {hex = "ffaa00", rgb = {1, 170/255, 0}, },
--violet = GetItemQualityColor(ITEM_DISPLAY_QUALITY_ARTIFACT),
--gold = GetItemQualityColor(ITEM_DISPLAY_QUALITY_LEGENDARY),
--mythic = GetItemQualityColor(ITEM_DISPLAY_QUALITY_MYTHIC_OVERRIDE),
}
-- convenience lookup table for hex-value colors
sfutil.hex = {
gold = sfutil.colors.gold.hex,
red = sfutil.colors.red.hex,
teal = sfutil.colors.teal.hex,
lime = sfutil.colors.lime.hex,
goldenrod = sfutil.colors.goldenrod.hex,
blue = sfutil.colors.blue.hex,
purple = sfutil.colors.purple.hex,
bronze = sfutil.colors.bronze.hex,
ltskyblue = sfutil.colors.ltskyblue.hex,
lemon = sfutil.colors.lemon.hex,
mocassin = sfutil.colors.mocassin.hex,
frangipani = sfutil.colors.frangipani.hex,
--brick = sfutil.colors.brick.hex,
junk = sfutil.colors.junk.hex,
normal = sfutil.colors.normal.hex,
fine = sfutil.colors.fine.hex,
superior = sfutil.colors.superior.hex,
epic = sfutil.colors.epic.hex,
legendary = sfutil.colors.legendary.hex,
mythic = sfutil.colors.mythic.hex
}
-- convenience lookup table for rgb-value colors
sfutil.rgb = {
gold = sfutil.colors.gold.rgb,
red = sfutil.colors.red.rgb,
teal = sfutil.colors.teal.rgb,
lime = sfutil.colors.lime.rgb,
goldenrod = sfutil.colors.goldenrod.rgb,
blue = sfutil.colors.blue.rgb,
purple = sfutil.colors.purple.rgb,
bronze = sfutil.colors.bronze.rgb,
ltskyblue = sfutil.colors.ltskyblue.rgb,
lemon = sfutil.colors.lemon.rgb,
mocassin = sfutil.colors.mocassin.rgb,
frangipani = sfutil.colors.frangipani.rgb,
--brick = sfutils.colors.brick.rgb,
junk = sfutil.colors.junk.rgb,
normal = sfutil.colors.normal.rgb,
fine = sfutil.colors.fine.rgb,
superior = sfutil.colors.superior.rgb,
epic = sfutil.colors.epic.rgb,
legendary = sfutil.colors.legendary.rgb,
mythic = sfutil.colors.mythic.rgb
}
local select = select
local unpack = unpack
local function ZOS_addSystemMsg(msg)
CHAT_ROUTER:AddSystemMessage(msg)
end
-- create a varargs iterator function
-- without using the 5.2 table.pack()
-- returns index, value, total with each iteration. (total does not change until ... does)
function sfutil.iter_args(...)
local args = {...}
local n = select("#", ...)
local i = 0
return function()
i=i+1
if i<=n then
return i,args[i], n
else
return nil, nil, n
end
end
end
--[[ closure for pure functions and varargs
@param callback function - The function to be invoked later.
@param ... - any Arguments to bind to the callback.
@return function - A function that calls callback with the bound arguments,
followed by any arguments supplied when the returned function is invoked.
Yes, you can just pass self as the first or only arg, but having closure() and
methodClosure() make the code intention clearer to understand.
--]]
function sfutil.closure(callback, ...)
local bound = {...}
local boundCount = select("#", ...)
return function(...)
local providedcnt = select("#", ...)
if providedcnt == 0 then
-- no additional parameters
return callback(unpack(bound, 1, boundCount))
end
-- merge base and additional parameters into single arg list
local args = {}
for i = 1, boundCount do
args[i] = bound[i]
end
local provided = {...}
for i = 1, providedcnt do
args[boundCount + i] = provided[i]
end
return callback(unpack(args))
end
end
--[[ closure for method functions, self, and varargs
@param callback function - The function to be invoked later.
@param tblself table|nil - Value passed as first argument to callback.
@param ... - any Arguments to bind to the callback.
@return function - A function that calls callback with the bound arguments (including tblself),
followed by any arguments supplied when the returned function is invoked.
--]]
function sfutil.methodClosure(callback, tblself, ...)
local bound = {...}
local boundCount = select("#", ...)
return function(...)
local providedcnt = select("#", ...)
if providedcnt == 0 then
-- no additional parameters
return callback(tblself, unpack(bound, 1, boundCount))
end
-- merge base and additional parameters into single arg list
local args = {}
for i=1,boundCount do
args[i] = bound[i]
end
local provided = {...}
for i=1, providedcnt do
args[boundCount+i] = provided[i]
end
return callback(tblself, unpack(args))
end
end
--- Executes `fn` safely. If an error occurs, it returns false and the error message.
--- Otherwise it returns true and then up to 10 the other return values from the function call.
--- (Does not create a table to pass back the returned values!)
--- Executes a function safely and returns 10 of its results.
--- @param fn function The function to protect.
--- @param ... any Arguments forwarded to `fn`.
--- @return boolean ok True if the call succeeded.
--- @return ... All values returned by `fn` (or the error object on failure).
function sfutil.safeCall10(fn, ...)
-- pcall returns: statusFlag, <all results from fn>
local ok, r1, r2, r3, r4, r5,
r6, r7, r8, r9, r10 = pcall(fn, ...)
if not ok then
return false, r1
end
-- Re‑emit the status flag followed by every returned value.
return true,
r1, r2, r3, r4, r5,
r6, r7, r8, r9, r10
end
-- Executes `fn` safely. If an error occurs, it returns false and the error message.
-- Otherwise it returns true and then all of the other return values from the function call.
--- (Does create a table to pass back the returned values!)
--- Executes a function safely and returns *all* of its results.
--- @param fn function The function to protect.
--- @param ... any Arguments forwarded to `fn`.
--- @return boolean ok True if the call succeeded.
--- @return ... All values returned by `fn` (or the error object on failure).
function sfutil.safeCall(fn, ...)
-- Call the function once and keep the whole multivalued result in a temporary variable
local results = { pcall(fn, ...) } -- results[1] = ok, results[2..] = fn's returns
local ok = results[1]
if not ok then
-- The error message is the first value after the status flag
local err = results[2]
return false, err
end
-- Success path – return true followed by everything that came after the status flag
-- `select(2, ...)` would give us the same thing, but we already have the table.
return true, unpack(results, 2) -- unpack from index 2 to the end
end
--[[
ternary trick
(condition and {ifTrue} or {ifFalse})[1]
ifTrue and ifFalse can be functions
--]]
--[[ ---------------------
Used to be able to wrap an existing function with another so that subsequent
calls to the function will actually invoke the wrapping function.
The wrapping function should accept a function as the first parameter, followed
by the parameters expected by the original function. It will be passed in the
original function so the wrapping function can call it (if it chooses).
Can be called with or without the namespace parameter (which defines the namespace
where the original function is defined). If the namespace parameter is not provided
then assume the global namespace _G.
Parameters:
namespace - (optional) when provided, this is a table where the function to be wrapped resides.
If not provided, the global namespace _G is assumed.
functionName - a string with the name of the function to be wrapped
(used as a key to the namespace table)
wrapper - a function which accepts a function, followed by the parameters that the
original function expects to be provided. Therefore the wrapped function
can call the original function if it wishes to.
Examples:
WrapFunction(myfunc, mywrapper)
will wrap the global function myfunc to call mywrapper
WrapFunction(TT, myfunc, mywrapper)
will wrap TT.myfunc with a call to mywrapper
--]]
function sfutil.WrapFunction(namespace, functionName, wrapper)
if type(namespace) == "string" then
-- We did not get a namespace parameter,
-- shift the values to their proper places.
wrapper = functionName
functionName = namespace
namespace = _G
elseif type(namespace) ~= "table" then
-- invalid parameters
return nil
end
assert(type(namespace[functionName])=="function")
local originalFunction = namespace[functionName]
namespace[functionName] = function(...)
return wrapper(originalFunction, ...)
end
end
---------------------
-- turn a boolean value into a string
-- suitable for display
function sfutil.bool2str(bool)
if (sfutil.isTrue(bool)) then
return "true"
end
return "false"
end
-- turn a string (hopefully containing a boolean value) into a boolean
function sfutil.str2bool(str)
if type(str) ~= "string" then
return false
end
str = string.lower(str)
return str=="true" or str=="1"
end
---------------------
-- a non-lua default test for value is true where
-- the value true is only returned if val was some
-- value equivalent to true or 1
-- Any other value will return false
function sfutil.isTrue(val)
-- must be a variety of true value
if val == 1 or val == "1" or val == true or val == "true" then
return true
end
return false
end
---------------------
-- return the value of val; unless it is nil when we
-- then will return defaultval instead of the nil.
--
-- The var = val or default does not do the same job,
-- because if val evaluates to false according to lua then
-- the default value would be assigned.
-- Here we specifically only want the default value if
-- val == nil.
function sfutil.nilDefault(val, defaultval)
if val == nil then
return defaultval
end
return val
end
---------------------
-- return the value of val; unless it is nil or an empty string
-- when we then will return defaultval instead of the nil.
--
function sfutil.nilDefaultStr(val, defaultval)
if val == nil then
return defaultval
end
if val == "" then
return defaultval
end
return val
end
---------------------
-- Get various addon meta info
-- namespace is a table to add the info to,
-- if the namespace is not a table, create a table and return it.
-- Always returns a table with the info inside it
function sfutil.addonMeta(namespace, name)
if type(namespace) == "string" then
name = namespace
namespace = nil
end
namespace = sfutil.safeTable(namespace)
namespace.addonName = name -- addon name for these saved vars
namespace.server = GetWorldName()
namespace.account = GetDisplayName()
namespace.charId = GetCurrentCharacterId()
namespace.charName = GetUnitName("player")
namespace.fmtCharName = zo_strformat(SI_UNIT_NAME, GetUnitName("player"))
namespace.API = GetAPIVersion()
return namespace
end
---------------------
-- Convert a number of seconds into an
-- HH:MM:SS string.
function sfutil.secondsToClock(seconds)
seconds = tonumber(seconds) or 0
if seconds <= 0 then
return "00:00:00"
else
local hours = string.format("%02.f", math.floor(seconds / 3600))
local mins = string.format("%02.f", math.floor(seconds / 60 - (hours * 60)))
local secs = string.format("%02.f", math.floor(seconds - hours * 3600 - mins * 60))
return hours .. ":" .. mins .. ":" .. secs
end
end
---------------------
-- Addon Chat MESSAGE / DEBUG --
---------------------
-- Set the prefix msg to be used for chat messages
function sfutil.initSystemMsgPrefix(addon_name, hexcolor)
hexcolor = sfutil.nilDefault(hexcolor, sfutil.hex.goldenrod)
return sfutil.ColorText(sfutil.str("[", addon_name, "] "), hexcolor)
end
-- Send a system message to chat with the specified prefix and the text in the specified color.
-- (Standalone function - not part of addonChatter.)
function sfutil.systemMsg(prefix, text, hexcolor)
hexcolor = sfutil.nilDefault(hexcolor, sfutil.hex.normal)
local msg = sfutil.str(prefix, sfutil.ColorText(text, hexcolor))
ZOS_addSystemMsg(msg)
end
sfutil.addonChatter = {}
sfutil.addonChatter.__index = sfutil.addonChatter
local NOOP = function() end
function sfutil.addonChatter:New(addon_name)
local o = setmetatable({}, self)
o.addonName = addon_name
o.namecolor = sfutil.hex.goldenrod
o.normalcolor = sfutil.hex.mocassin
o.debugcolor = sfutil.hex.ltskyblue
o.prefix = sfutil.initSystemMsgPrefix(addon_name, o.namecolor)
o.d = NOOP -- debug messages off by default
o.isdbgon = false
return o
end
-- private version of the d function
local function _d(self, ...)
local msg = sfutil.ColorText(sfutil.dstr(" ", ...), self.debugcolor)
ZOS_addSystemMsg(self.prefix .. msg)
end
-- ------------- set colors for chat messages
function sfutil.addonChatter:setNormalColor(hexcolor)
self.normalcolor = hexcolor
end
function sfutil.addonChatter:setDebugColor(hexcolor)
self.debugcolor = hexcolor
end
function sfutil.addonChatter:setNameColor(hexcolor)
self.namecolor = hexcolor
self.prefix = sfutil.initSystemMsgPrefix(self.addonName, self.namecolor)
end
-- ------------- debug state
function sfutil.addonChatter:disableDebug()
self.isdbgon = false
self.d = NOOP
end
function sfutil.addonChatter:enableDebug()
self.isdbgon = true
self.d = _d
end
function sfutil.addonChatter:toggleDebug()
if self.isdbgon then
self:disableDebug()
else
self:enableDebug()
end
end
function sfutil.addonChatter:isDebugEnabled()
return self.isdbgon
end
function sfutil.addonChatter:getDebugState()
-- as a debug function, this returns a string
return sfutil.bool2str(self.isdbgon)
end
-- ------------- send messages to chat
-- print normal messages to chat
function sfutil.addonChatter:systemMessage(...)
local msg = sfutil.str(self.prefix, sfutil.ColorText(sfutil.dstr(" ", ...), self.normalcolor))
ZOS_addSystemMsg(msg)
end
-- print debug messages to chat
function sfutil.addonChatter:debugMsg(...)
self.d(self, ...)
end
-- -------------------------------------------------------
-- Slash utilities
-- display in chat a table of slash commands with descriptions
-- (using the addonChatter)
function sfutil.addonChatter:slashHelp(title, cmdstable)
local sysmsg = function(cmd, desc)
cmd = sfutil.ColorText(cmd, sfutil.hex.teal)
if (type(desc) == "number") then
desc = GetString(desc)
end
desc = sfutil.ColorText(" = " .. sfutil.str(desc), self.normalcolor)
local msg = sfutil.dstr(" ", self.prefix, cmd, desc)
ZOS_addSystemMsg(msg)
end
self:systemMessage(title)
for _, value in pairs(cmdstable) do
sysmsg(value[1], value[2])
end
end
-- -----------------------------------------------------------------------
-- Utility for parsing delimited strings
-- Split a string into sections using a pattern as a delimiter
-- When delimiter starts or ends the string, an empty string is considered
-- to be before/after the delimiter. When two or more delimiters are together,
-- there is considered to be empty strings between them.
-- str = string
-- pat = delimiter pattern
--
-- Returns table of strings that were separated by delimiters
-- (The delimiters are NOT included in the table.)
function sfutil.gsplit(str, pat)
local t1 = {}
if not str then
return {}
end
if not pat or pat == "" then
-- special case - no delimiter
return {str}
end
local fpat = "(.-)" .. pat
local last_end = 1
local s1, e1, cap = str:find(fpat, 1)
local tbl_insert = table.insert
if not s1 then
-- special case - string does not contain delimiter
tbl_insert(t1, str)
return t1
end
while s1 do
if not cap then
-- delimiter was the beginning of the string
-- so first capture is empty string
cap = ""
end
-- save the front captured piece of the string
tbl_insert(t1, cap)
last_end = e1 + 1
s1, e1, cap = str:find(fpat, last_end)
end
-- we have run out of delimiters to find
if last_end - 1 <= #str then
-- still have the last piece of string without delimiters
cap = str:sub(last_end)
tbl_insert(t1, cap)
end
return t1
end
-- -----------------------------------------------------------------------
-- Utilities for parsing colors in chat messages
--[[ Returns a table containing all ESO color delimiters found in a string.
Searches the string for color start markers (`|cRRGGBB`) and color reset
markers (`|r`). The returned table is always valid (never nil), but may
be empty if no delimiters are found.
Color markers are normalized to lowercase if they were found as uppercase.
Each entry in the returned table has the form:
{
start = number, -- 1-based starting position of the delimiter
estr = number, -- 1-based ending position of the delimiter
code = string -- "c" for color start or "r" for color reset
}
For color start markers, `estr` includes the entire color sequence:
|cRRGGBB
For reset markers, `estr` includes:
|r
Returns:
{
{ start = 1, estr = 8, code = "c" },
{ start = 11, estr = 12, code = "r" }
}
@param str string|nil The string to search for color delimiters.
@return table Array of delimiter entries; never nil.
--]]
function sfutil.getAllColorDelim(str)
if not str then
return {}
end
-- get positions of all of the desired delimiters
local t1 = {}
local s1, e1, c = str:find("|+([CcRr])", 1)
local strlen = #str
local tbl_insert = table.insert
while s1 do
if s1 == strlen then
break
end
local code = string.lower(c)
if code == "c" then
e1 = e1 + 6 -- include color code
end
tbl_insert(t1, {start = s1, estr = e1, code = code})
-- look for next
s1, e1, c = str:find("|+([CcRr])", e1)
end
-- we have run out of delimiters to find
return t1
end
--[[
Regularizes an ESO color delimiter table against a string.
Examines the supplied markers table and identifies delimiter corrections
needed to make the color sequence valid and balanced.
The markers table must contain entries sorted by start position.
The function may:
* Mark unnecessary reset markers (`|r`) for removal.
* Insert missing reset markers (`|r`) when a new color starts before the
previous color has been closed.
* Mark empty color sections (`|cRRGGBB|r`) for removal.
* Append a missing final reset marker when the string ends while a color
is still active.
Each markers table entry has the form:
{
start = number, -- 1-based start position
estr = number, -- 1-based end position
code = "c"|"r", -- color start or reset marker
action = nil|"+"|"-" -- correction to apply: keep, add, or remove
}
The input markers table is modified in place and returned.
@param markers table Existing color delimiter entries sorted by start position.
@param str string Source string being validated.
@return table Modified markers table; empty table if str or markers table is nil/empty.
--]]
--[[
function sfutil.regularizeColors(markers, str)
if not str then return {} end
if not markers or #markers == 0 then return {} end
local result = {}
local tbl_insert = table.insert
local prev_v
local inColor = false
for _, v in ipairs(markers) do
local marker = v
if marker.code == "r" then
if not inColor then
-- unnecessary |r
marker.action = "-"
else
inColor = false
end
elseif marker.code == "c" then
if inColor then
-- previous color was not closed
-- insert missing |r before this color
local reset = {
start = marker.start,
estr = marker.start,
code = "r",
action = "+"
}
tbl_insert(result, reset)
inColor = false
end
inColor = true
end
-- remove empty colors: |cRRGGBB|r
if prev_v and prev_v.code == "c" and prev_v.estr + 1 == marker.start
then
prev_v.action = "-"
marker.action = "-"
end
tbl_insert(result, marker)
prev_v = marker
end
-- add missing final reset
if inColor then
tbl_insert(result, {
start = #str + 1,
estr = #str + 1,
code = "r",
action = "+"
})
end
return result
end
--]]
function sfutil.regularizeColors(markers, str)
if not str then return {} end
if not markers or #markers == 0 then return {} end
local result = {}
local tbl_insert = table.insert
local prev_v
local inColor = false
for _, marker in ipairs(markers) do
if marker.code == "r" then
if not inColor then
-- unnecessary |r
marker.action = "-"
else
-- remove empty color: |cRRGGBB|r
if prev_v
and prev_v.code == "c"
and prev_v.estr + 1 == marker.start
then
prev_v.action = "-"
marker.action = "-"
end
inColor = false
end
elseif marker.code == "c" then
if inColor then
-- Adjacent colors: |cAAAAAA|cBBBBBB
-- discard the previous color and keep the new one.
if prev_v
and prev_v.code == "c"
and prev_v.estr + 1 == marker.start
then
prev_v.action = "-"
else
-- Previous color contained text and was not closed.
-- Insert a missing |r before the new color.
tbl_insert(result, {
start = marker.start,
estr = marker.start,
code = "r",
action = "+"
})
end
end
inColor = true
end
tbl_insert(result, marker)
prev_v = marker
end
-- Add missing final reset.
if inColor then
tbl_insert(result, {
start = #str + 1,
estr = #str + 1,
code = "r",
action = "+"
})
end
return result
end
function sfutil.applyColor(str, colorhex)
if not str then
return nil
end
if not colorhex then
return str
end
local parsetbl = sfutil.getAllColorDelim(str)
sfutil.regularizeColors(parsetbl, str)
local newtbl = {}
local incolor = false
for _, v in ipairs(parsetbl) do
if string.find(str, "|+[Cc]", v) then
-- starting embedded color
if incolor == true then
newtbl[#newtbl] = "|r"
incolor = false
end
newtbl[#newtbl] = v
elseif string.find(str, "|+[Rr]", v) then
-- exitting embedded color
newtbl[#newtbl] = v
newtbl[#newtbl] = string.format("|c%s", colorhex)
incolor = true
else
if incolor == false then
newtbl[#newtbl] = string.format("|c%s", colorhex)
incolor = true
end
newtbl[#newtbl] = v
end
end
return table.concat(newtbl)
end
-- Strip all of the color markers out of the string.
-- Uses the source string and a marker table as produced by
-- getAllColorDelim().
--
-- Returns a string which is the source string with all of the color
-- markers removed.
--
-- Havok allows "|" escape character for "|" (user input) so we must handle doubled pipes.
function sfutil.stripColors(markertable, str)
if not str then
return nil
end
if not markertable or #markertable == 0 then
return str
end
local t2 = {}
local lastv = 0
local tbl_insert = table.insert
for _, v in ipairs(markertable) do
local code = v.code
local action = v.action
if not action then
-- it's a section we're keeping
-- string fragment
if code == "c" then
if v.start > lastv + 1 then
tbl_insert(t2, str:sub(lastv + 1, v.start - 1))
end
local _, es = string.find(str, "|+[Cc]%x%x%x%x%x%x", v.start)
lastv = es or #str
elseif code == "r" then
-- end color
if v.start > lastv + 1 then
tbl_insert(t2, str:sub(lastv + 1, v.start - 1))
end
local _, es = string.find(str, "|+[Rr]", v.start)
lastv = es or #str
end
elseif action == "+" then
-- new string fragment (|r)
if v.start > lastv + 1 then
tbl_insert(t2, str:sub(lastv + 1, v.start - 1))
end
lastv = v.start + 1
else -- action == "-"
if code == "c" then
local _, es = string.find(str, "|+[Cc]%x%x%x%x%x%x", v.start)
lastv = es or #str
elseif code == "r" and v.start ~= -1 then
local _, es = string.find(str, "|+[Rr]", v.start)
lastv = es or #str
end
end
end
if lastv and lastv <= #str then
lastv = lastv + 1
tbl_insert(t2, str:sub(lastv))
end
return table.concat(t2)
end
-- Splits the string into sections corresponding the color markers themselves
-- and the text around the markers. Doing a table.concat() will join the contents
-- of the returned table into a properly color-marked string.
-- Returns the table of sections
function sfutil.colorsplit(markertable, str)
if not str then
return {}
end
if not markertable or #markertable == 0 then
-- no delimiters in string
return {str}
end
-- break string into sections with color markers separated out
local t2 = {}
local lastv = 0
local ss, es, cs
local tbl_insert = table.insert
for _, v in ipairs(markertable) do
if v then
local code = v.code
local action = v.action
if not action then
-- it's a section we're keeping
if v.start > lastv + 1 then
tbl_insert(t2, str:sub(lastv + 1, v.start - 1))
end
-- string fragment
if code == "c" then
-- expect color
ss, es, cs = string.find(str, "|+[Cc](%x%x%x%x%x%x)", v.start)
if ss == nil or es == nil then
break
end
tbl_insert(t2, string.format("|c%s", cs))
lastv = es
elseif code == "r" then
-- end color
ss, es = string.find(str, "|+[Rr]", v.start)
if ss == nil or es == nil then
break
end
tbl_insert(t2, "|r")
lastv = es
end
elseif action == "+" then
-- new string fragment (|r)
if v.start > lastv + 1 then
tbl_insert(t2, str:sub(lastv + 1, v.start - 1))
end
tbl_insert(t2, "|r")
lastv = v.start + 1
else -- action == "-"
if code == "c" then
ss, es = string.find(str, "|+[Cc]%x%x%x%x%x%x", v.start)
if ss == nil or es == nil then
break
end
lastv = es
elseif code == "r" and v.start ~= -1 then
ss, es = string.find(str, "|+[Rr]", v.start)
if ss == nil or es == nil then
break
end
lastv = es
end
end
end
end
if lastv <= #str then
lastv = lastv + 1
tbl_insert(t2, str:sub(lastv))
end
return t2
end
-- -----------------------------------------------------------------------
-- temporary hacks
function sfutil.add2linesctl()
--[[ -- only needed when LibAddonMenu is having clipping problems
return {
type = "description",
title = " ",
text = " ",
disabled = true,
}
--]]
end
function sfutil.addlinectl()
--[[ -- only needed when LibAddonMenu is having clipping problems
return {
type = "description",
text = " ",
disabled = true,
}
--]]
end
-- -----------------------------------------------------------------------
-- easily manage values and choice tables for dropdowns
-- creates a simple lookup table for potential choices
-- for dropdowns, each entry with an index key (ndx), a
-- choice (strId), and the optional choiceValue (val)
--
-- Then you can create choices and choiceValues lists