-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPreferenceSystemManager.cs
More file actions
1485 lines (1372 loc) · 63.4 KB
/
PreferenceSystemManager.cs
File metadata and controls
1485 lines (1372 loc) · 63.4 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
using Kitchen;
using Kitchen.Modules;
using PreferenceSystem.Event;
using PreferenceSystem.Menus;
using PreferenceSystem.Preferences;
using PreferenceSystem.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text.RegularExpressions;
using UnityEngine;
using static PreferenceSystem.Utils.TypeUtils;
namespace PreferenceSystem
{
public class PreferenceSystemManager
{
public enum MenuType
{
MainMenu,
PauseMenu
}
public readonly string MOD_GUID;
public readonly string MOD_NAME;
private bool _isPreferencesEventsRegistered = false;
public bool IsPreferencesEventsRegistered
{
get { return _isPreferencesEventsRegistered; }
}
AssemblyBuilder _assemblyBuilder;
ModuleBuilder _moduleBuilder;
private static readonly Regex sWhitespace = new Regex(@"\s+");
private PreferenceManager _prefManager;
private Dictionary<string, Type> _registeredPreferences = new Dictionary<string, Type>();
private Dictionary<string, Action<bool>> boolPreferencesOnChanged = new Dictionary<string, Action<bool>>();
private Dictionary<string, Action<int>> intPreferencesOnChanged = new Dictionary<string, Action<int>>();
private Dictionary<string, Action<float>> floatPreferencesOnChanged = new Dictionary<string, Action<float>>();
private Dictionary<string, Action<string>> stringPreferencesOnChanged = new Dictionary<string, Action<string>>();
private Dictionary<string, object> _defaultValues;
public Dictionary<string, object> Defaults => new Dictionary<string, object>(_defaultValues);
public static Type[] AllowedTypes => new Type[]
{
typeof(bool),
typeof(int),
typeof(float),
typeof(string)
};
public static Dictionary<string, Type> AllowedTypesDict => AllowedTypes.ToDictionary(x => x.FullName, x => x);
private bool _menuRegistered = false;
//private bool _mainMenuRegistered = false;
//private bool _pauseMenuRegistered = false;
private Type _topLevelTypeKey;
//private Type _mainTopLevelTypeKey;
//private Type _pauseTopLevelTypeKey;
private Queue<Type> _menuTypeKeys = new Queue<Type>();
//private Queue<Type> _mainMenuTypeKeys = new Queue<Type>();
//private Queue<Type> _pauseMenuTypeKeys = new Queue<Type>();
private Queue<List<(ElementType, object)>> _completedElements = new Queue<List<(ElementType, object)>>();
private Stack<Type> _tempMenuTypeKeys = new Stack<Type>();
//private Stack<Type> _tempMainMenuTypeKeys = new Stack<Type>();
//private Stack<Type> _tempPauseMenuTypeKeys = new Stack<Type>();
private Stack<List<(ElementType, object)>> _elements = new Stack<List<(ElementType, object)>>();
private Stack<int> _conditionalBlockers = new Stack<int>();
internal enum ElementType
{
Label,
Info,
Select,
Button,
ButtonWithConfirm,
PlayerRow,
SubmenuButton,
ProfileSelector,
DeleteProfileButton,
BoolOption,
IntOption,
FloatOption,
StringOption,
Spacer,
ConditionalBlocker,
ConditionalBlockerDone,
ActionButton,
PageSelector,
PagedItem,
PagedItemDone
}
internal bool IsSelectableElement(ElementType elementType)
{
switch (elementType)
{
case ElementType.Select:
case ElementType.Button:
case ElementType.ButtonWithConfirm:
case ElementType.PlayerRow:
case ElementType.SubmenuButton:
case ElementType.ProfileSelector:
case ElementType.DeleteProfileButton:
case ElementType.BoolOption:
case ElementType.IntOption:
case ElementType.FloatOption:
case ElementType.StringOption:
case ElementType.ActionButton:
case ElementType.PageSelector:
return true;
default:
return false;
}
}
/// <summary>
/// Create PreferenceSystemManager instance.
/// </summary>
/// <param name="modGUID">Unique mod identifier</param>
/// <param name="modName">Name displayed on mod menu button</param>
public PreferenceSystemManager(string modGUID, string modName)
{
MOD_GUID = modGUID;
MOD_NAME = modName;
_prefManager = new PreferenceManager(modGUID);
_assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName($"{this.GetType().Namespace}.{MOD_GUID}"), AssemblyBuilderAccess.Run);
_moduleBuilder = _assemblyBuilder.DefineDynamicModule("Module");
_topLevelTypeKey = CreateTypeKey($"{sWhitespace.Replace(MOD_NAME, "")}");
//_mainTopLevelTypeKey = CreateTypeKey($"{sWhitespace.Replace(MOD_NAME, "")}_Main");
//_pauseTopLevelTypeKey = CreateTypeKey($"{sWhitespace.Replace(MOD_NAME, "")}_Pause");
_elements.Push(new List<(ElementType, object)>());
_conditionalBlockers.Push(0);
_completedElements = new Queue<List<(ElementType, object)>>();
PreferenceSystemRegistry.Add(this);
}
private static bool IsAllowedType(Type type, bool throwExceptionIfNotAllowed = false)
{
if (!type.IsEnum &&
!AllowedTypes.Contains(type))
{
if (throwExceptionIfNotAllowed)
ThrowTypeException();
return false;
}
return true;
}
private static void ThrowTypeException()
{
string allowedTypesStr = "";
for (int i = 0; i < AllowedTypes.Length; i++)
{
allowedTypesStr += AllowedTypes[i].ToString();
if (i != AllowedTypes.Length - 1) allowedTypesStr += ", ";
}
throw new ArgumentException($"Type TPref is not supported! Only use enums, {allowedTypesStr}.");
}
private bool IsUsedKey(string key, bool throwExceptionIfUsed = false)
{
if (_registeredPreferences.ContainsKey(key))
{
if (throwExceptionIfUsed)
ThrowKeyException(key);
return true;
}
return false;
}
private static void ThrowKeyException(string key)
{
throw new ArgumentException($"Key {key} already exists!");
}
private void Preference_OnChanged<T>(string key, T value)
{
Set(key, value);
}
/// <summary>
/// Create selector with a linked preference
/// </summary>
/// <typeparam name="T">Type of preference value</typeparam>
/// <param name="key">Unique preference identifier</param>
/// <param name="initialValue">Starting value when preference is created for the first time</param>
/// <param name="values">Array of allowed values</param>
/// <param name="strings">Array of string representations for each value</param>
/// <returns>Instance of PreferenceSystemManager (for method chaining)</returns>
public PreferenceSystemManager AddOption<T>(string key, T initialValue, T[] values, string[] strings)
{
return PrivateAddOption<T>(key, initialValue, values, strings, false, null);
}
/// <summary>
/// Create selector with a linked preference
/// </summary>
/// <typeparam name="T">Type of preference value</typeparam>
/// <param name="key">Unique identifier</param>
/// <param name="initialValue">Starting value when preference is created for the first time</param>
/// <param name="values">Array of allowed values</param>
/// <param name="strings">Array of string representations for each value</param>
/// <param name="on_changed">Callback when selector value is changed</param>
/// <returns>Instance of PreferenceSystemManager (for method chaining)</returns>
public PreferenceSystemManager AddOption<T>(string key, T initialValue, T[] values, string[] strings, Action<T> on_changed)
{
return PrivateAddOption<T>(key, initialValue, values, strings, false, on_changed);
}
/// <summary>
/// Create selector with a linked preference
/// </summary>
/// <typeparam name="T">Type of preference value</typeparam>
/// <param name="key">Unique preference identifier</param>
/// <param name="initialValue">Starting value when preference is created for the first time</param>
/// <param name="values">Array of allowed values</param>
/// <param name="strings">Array of string representations for each value</param>
/// <param name="redraw">Redraw menu when selector value is changed</param>
/// <returns>Instance of PreferenceSystemManager (for method chaining)</returns>
public PreferenceSystemManager AddOption<T>(string key, T initialValue, T[] values, string[] strings, bool redraw)
{
return PrivateAddOption<T>(key, initialValue, values, strings, false, null, redraw);
}
/// <summary>
/// Create selector with a linked preference
/// </summary>
/// <typeparam name="T">Type of preference value</typeparam>
/// <param name="key">Unique preference identifier</param>
/// <param name="initialValue">Starting value when preference is created for the first time</param>
/// <param name="values">Array of allowed values</param>
/// <param name="strings">Array of string representations for each value</param>
/// <param name="on_changed">Callback when selector value is changed</param>
/// <param name="redraw">Redraw menu when selector value is changed</param>
/// <returns>Instance of PreferenceSystemManager (for method chaining)</returns>
public PreferenceSystemManager AddOption<T>(string key, T initialValue, T[] values, string[] strings, Action<T> on_changed, bool redraw)
{
return PrivateAddOption<T>(key, initialValue, values, strings, false, on_changed, redraw);
}
/// <summary>
/// Create hidden preference which is not displayed in menu
/// </summary>
/// <typeparam name="T">Type of preference value</typeparam>
/// <param name="key">Unique preference identifier</param>
/// <param name="initialValue">Starting value when preference is created for the first time</param>
/// <param name="doLoad">Set true if called after RegisterMenu. Otherwise, false.</param>>
/// <returns>Instance of PreferenceSystemManager (for method chaining)</returns>
public PreferenceSystemManager AddProperty<T>(string key, T initialValue, bool doLoad = false)
{
PrivateAddOption<T>(key, initialValue, null, null, true, null);
if (doLoad)
Load();
return this;
}
private PreferenceSystemManager PrivateAddOption<T>(string key, T initialValue, T[] values, string[] strings, bool doNotShow, Action<T> on_changed, bool redraw = false)
{
IsAllowedType(typeof(T), true);
IsUsedKey(key, true);
if (typeof(T) == typeof(bool))
{
PreferenceBool preference = _prefManager.RegisterPreference(new PreferenceBool(key, ChangeType<bool>(initialValue)));
if (on_changed != null)
boolPreferencesOnChanged[key] = ChangeType<Action<bool>>(on_changed);
if (!doNotShow)
{
EventHandler<bool> handler = delegate (object _, bool b)
{
Preference_OnChanged(key, b);
if (on_changed != null)
on_changed(ChangeType<T>(b));
};
_elements.Peek().Add((ElementType.BoolOption, new OptionData<bool>(MOD_GUID, key, values.Cast<bool>().ToList(), strings.ToList(), handler, redraw)));
}
}
else if (typeof(T) == typeof(int))
{
PreferenceInt preference = _prefManager.RegisterPreference(new PreferenceInt(key, ChangeType<int>(initialValue)));
if (on_changed != null)
intPreferencesOnChanged[key] = ChangeType<Action<int>>(on_changed);
if (!doNotShow)
{
EventHandler<int> handler = delegate (object _, int i)
{
Preference_OnChanged(key, i);
if (on_changed != null)
on_changed(ChangeType<T>(i));
};
_elements.Peek().Add((ElementType.IntOption, new OptionData<int>(MOD_GUID, key, values.Cast<int>().ToList(), strings.ToList(), handler, redraw)));
}
}
else if (typeof(T) == typeof(float))
{
PreferenceFloat preference = _prefManager.RegisterPreference(new PreferenceFloat(key, ChangeType<float>(initialValue)));
if (on_changed != null)
floatPreferencesOnChanged[key] = ChangeType<Action<float>>(on_changed);
if (!doNotShow)
{
EventHandler<float> handler = delegate (object _, float f)
{
Preference_OnChanged(key, f);
if (on_changed != null)
on_changed(ChangeType<T>(f));
};
_elements.Peek().Add((ElementType.FloatOption, new OptionData<float>(MOD_GUID, key, values.Cast<float>().ToList(), strings.ToList(), handler, redraw)));
}
}
else if (typeof(T) == typeof(string))
{
PreferenceString preference = _prefManager.RegisterPreference(new PreferenceString(key, ChangeType<string>(initialValue)));
if (on_changed != null)
stringPreferencesOnChanged[key] = ChangeType<Action<string>>(on_changed);
if (!doNotShow)
{
EventHandler<string> handler = delegate (object _, string s)
{
Preference_OnChanged(key, s);
if (on_changed != null)
on_changed(ChangeType<T>(s));
};
_elements.Peek().Add((ElementType.StringOption, new OptionData<string>(MOD_GUID, key, values.Cast<string>().ToList(), strings.ToList(), handler, redraw)));
}
}
else if (typeof(T).IsEnum)
{
PreferenceString preference = _prefManager.RegisterPreference(new PreferenceString(key, initialValue.ToString()));
if (on_changed != null)
stringPreferencesOnChanged[key] = (string s) =>
{
on_changed(ChangeType<T>(s));
};
if (!doNotShow)
{
EventHandler<string> handler = delegate (object _, string s)
{
Preference_OnChanged(key, s);
if (on_changed != null)
on_changed(ChangeType<T>(s));
};
_elements.Peek().Add((ElementType.StringOption, new OptionData<string>(MOD_GUID, key, values.Select(x => x.ToString()).ToList(), strings.ToList(), handler, redraw)));
}
}
_registeredPreferences.Add(key, typeof(T));
return this;
}
/// <summary>
/// Retrieve preference value
/// </summary>
/// <typeparam name="T">Type of preference value.</typeparam>
/// <param name="key">Unique preference identifier</param>
/// <returns>Value of preference. If preference does not exist, default is returned instead.</returns>
public T Get<T>(string key)
{
return (T)(Get(key, typeof(T)) ?? default(T));
}
/// <summary>
/// Try to retrieve preference value
/// </summary>
/// <typeparam name="T">Type of preference value.</typeparam>
/// <param name="key">Unique preference identifier</param>
/// <param name="value">Value of preference, if it exists. Otherwise, default</param>
/// <returns>True if value successfully retrieved, otherwise false. Value of preference. If preference does not exist, default is returned instead.</returns>
public bool TryGet<T>(string key, out T value)
{
if (!Has<T>(key))
{
value = default;
return false;
}
value = Get<T>(key);
return true;
}
/// <summary>
/// Check if prference key is registered
/// </summary>
/// <typeparam name="T">Type of preference value.</typeparam>
/// <param name="key">Unique preference identifier</param>
/// <returns></returns>
public bool Has<T>(string key)
{
return Has(key, typeof(T));
}
private bool Has(string key, Type valueType)
{
IsAllowedType(valueType, true);
if (valueType == typeof(bool))
return _prefManager.HasPreference<PreferenceBool>(key);
else if (valueType == typeof(int))
return _prefManager.HasPreference<PreferenceInt>(key);
else if (valueType == typeof(float))
return _prefManager.HasPreference<PreferenceFloat>(key);
else if (valueType == typeof(string))
return _prefManager.HasPreference<PreferenceString>(key);
else if (valueType.IsEnum)
return _prefManager.HasPreference<PreferenceString>(key);
return false;
}
private object Get(string key, Type valueType)
{
IsAllowedType(valueType, true);
object value = null;
if (valueType == typeof(bool))
{
value = _prefManager.GetPreference<PreferenceBool>(key)?.Get();
}
else if (valueType == typeof(int))
{
value = _prefManager.GetPreference<PreferenceInt>(key)?.Get();
}
else if (valueType == typeof(float))
{
value = _prefManager.GetPreference<PreferenceFloat>(key)?.Get();
}
else if (valueType == typeof(string))
{
value = _prefManager.GetPreference<PreferenceString>(key)?.Get();
}
else if (valueType.IsEnum)
{
value = _prefManager.GetPreference<PreferenceString>(key)?.Get();
if (value != null)
{
try
{
value = Enum.Parse(valueType, value.ToString());
}
catch
{
Main.LogError($"Failed to parse {value} as {valueType}");
value = null;
}
}
}
return value;
}
/// <summary>
/// Set preference value
/// </summary>
/// <typeparam name="T">Type of preference value.</typeparam>
/// <param name="key">Unique preference identifier</param>
/// <param name="value">Value to be applied</param>
public void Set<T>(string key, T value)
{
Set(key, typeof(T), value);
}
private void Set(string key, Type valueType , object value)
{
IsAllowedType(valueType, true);
if (valueType == typeof(bool))
{
bool b = ChangeType<bool>(value);
_prefManager.GetPreference<PreferenceBool>(key)?.Set(b);
if (boolPreferencesOnChanged.TryGetValue(key, out var on_changed))
on_changed(b);
}
else if (valueType == typeof(int))
{
int i = ChangeType<int>(value);
_prefManager.GetPreference<PreferenceInt>(key)?.Set(i);
if (intPreferencesOnChanged.TryGetValue(key, out var on_changed))
on_changed(i);
}
else if (valueType == typeof(float))
{
float f = ChangeType<float>(value);
_prefManager.GetPreference<PreferenceFloat>(key)?.Set(f);
if (floatPreferencesOnChanged.TryGetValue(key, out var on_changed))
on_changed(f);
}
else if (valueType == typeof(string))
{
string s = ChangeType<string>(value);
_prefManager.GetPreference<PreferenceString>(key)?.Set(s);
if (stringPreferencesOnChanged.TryGetValue(key, out var on_changed))
on_changed(s);
}
else if (valueType.IsEnum)
{
string s = value.ToString();
_prefManager.GetPreference<PreferenceString>(key)?.Set(s);
if (stringPreferencesOnChanged.TryGetValue(key, out var on_changed))
on_changed(s);
}
Save();
}
/// <summary>
/// Change current preference profile and loads preference values. If profile name does not exist, a new preference profile is created.
/// </summary>
/// <param name="profileName">Profile name</param>
public void SetProfile(string profileName)
{
if (!GlobalPreferences.DoesProfileExist(MOD_GUID, profileName))
{
GlobalPreferences.AddProfile(MOD_GUID, profileName);
}
GlobalPreferences.SetProfile(MOD_GUID, profileName);
_prefManager.SetProfile(profileName);
_prefManager.Load();
_prefManager.Save();
}
/// <summary>
/// Try to change current preference profile and loads preference values, if profile exists.
/// </summary>
/// <param name="profileName">Profile name</param>
/// <returns>True if profile was changed. Otherwise, false</returns>
public bool TrySetProfile(string profileName)
{
if (!GlobalPreferences.DoesProfileExist(MOD_GUID, profileName))
{
return false;
}
SetProfile(profileName);
return true;
}
private void Save()
{
_prefManager.Save();
}
private void Load()
{
_prefManager.Load();
}
internal PreferenceSystemManagerData GetData()
{
PreferenceSystemManagerData result = new PreferenceSystemManagerData()
{
ModGuid = MOD_GUID,
ModName = MOD_NAME
};
foreach (KeyValuePair<string, Type> pref in _registeredPreferences)
{
result.Add(pref.Key, Get(pref.Key, pref.Value));
}
return result;
}
internal bool LoadData(string preferenceSetName, PreferenceSystemManagerData data)
{
SetProfile($"{preferenceSetName}_Loaded");
foreach (PreferenceData prefData in data.Preferences)
{
try
{
Set(prefData.Key, prefData.ValueType, prefData.Value);
}
catch (Exception ex)
{
Main.LogError($"{ex.Message}\n{ex.StackTrace}");
return false;
}
}
return true;
}
internal bool IsPreferencesEqual(PreferenceSystemManagerData data)
{
foreach (PreferenceData prefData in data.Preferences)
{
object value = Get(prefData.Key, prefData.ValueType);
if (value == null)
continue;
if (prefData.Value != value)
return false;
}
return true;
}
private readonly struct LabelData
{
public readonly string Text;
public LabelData(string text)
{
Text = text;
}
}
private readonly struct InfoData
{
public readonly string Text;
public InfoData(string text)
{
Text = text;
}
}
private readonly struct SelectData
{
public readonly List<string> Options;
public readonly Action<int> OnActivate;
public readonly int Index;
public readonly bool Redraw;
public SelectData(List<string> options, Action<int> on_activate, int index = 0, bool redraw = false)
{
Options = options;
OnActivate = on_activate;
Index = index;
Redraw = redraw;
}
}
private readonly struct ButtonData
{
public readonly string ButtonText;
public readonly Action<int> OnActivate;
public readonly int Arg;
public readonly float Scale;
public readonly float Padding;
public readonly bool CloseOnPress;
public ButtonData(string button_text, Action<int> on_activate, int arg = 0, float scale = 1f, float padding = 0.2f)
{
ButtonText = button_text;
OnActivate = on_activate;
Arg = arg;
Scale = scale;
Padding = padding;
}
public ButtonData(string button_text, Action<int> on_activate, bool closeOnPress = false, int arg = 0, float scale = 1f, float padding = 0.2f)
{
ButtonText = button_text;
OnActivate = on_activate;
Arg = arg;
Scale = scale;
Padding = padding;
CloseOnPress = closeOnPress;
}
}
private readonly struct ButtonWithConfirmData
{
public readonly string ButtonText;
public readonly string InfoText;
public readonly Action<GenericChoiceDecision> Callback;
public readonly int Arg;
public readonly float Scale;
public readonly float Padding;
public ButtonWithConfirmData(string button_text, string info_text, Action<GenericChoiceDecision> callback, int arg = 0, float scale = 1f, float padding = 0.2f)
{
ButtonText = button_text;
InfoText = info_text;
Callback = callback;
Arg = arg;
Scale = scale;
Padding = padding;
}
}
private readonly struct PlayerRowData
{
public readonly string Username;
public readonly PlayerInfo Player;
public readonly Action<int> OnKick;
public readonly Action<int> OnRemove;
public readonly int Arg;
public readonly float Scale;
public readonly float Padding;
public PlayerRowData(string username, PlayerInfo player, Action<int> on_kick, Action<int> on_remove, int arg = 0, float scale = 1f, float padding = 0.2f)
{
Username = username;
Player = player;
OnKick = on_kick;
OnRemove = on_remove;
Arg = arg;
Scale = scale;
Padding = padding;
}
}
private readonly struct SubmenuButtonData
{
public readonly string ButtonText;
public readonly Type MenuKey;
//public readonly Type MainMenuKey;
//public readonly Type PauseMenuKey;
public readonly bool SkipStack;
public SubmenuButtonData(string button_text, Type menu_key, bool skip_stack = false)
{
ButtonText = button_text;
MenuKey = menu_key;
SkipStack = skip_stack;
}
}
private readonly struct ActionButtonData
{
public readonly Type MenuType;
public readonly string ButtonText;
private readonly MenuAction MenuAction;
public object Action => (MenuType == typeof(MenuAction)) ? MenuAction.Action : ((MenuType == typeof(MenuAction)) ? MenuAction.PauseAction : null);
public ActionButtonData(string button_text, object action)
{
ButtonText = button_text;
MenuType = action.GetType();
if (action is MainMenuAction mainMenuAction)
{
MenuAction = new MenuAction(mainMenuAction);
}
else if (action is PauseMenuAction pauseMenuAction)
{
MenuAction = new MenuAction(pauseMenuAction);
}
else
{
throw new Exception("ActionButton action type must be a MainMenuAction or PauseMenuAction!");
}
}
}
private readonly struct OptionData<T>
{
public readonly string ModGUID;
public readonly string Key;
public readonly List<T> Values;
public readonly List<string> Strings;
public readonly EventHandler<T> EventHandler;
public readonly bool Redraw;
public OptionData(string modGuid, string key, List<T> values, List<string> strings, EventHandler<T> eventHandler, bool redraw)
{
ModGUID = modGuid;
Key = key;
Values = values;
Strings = strings;
EventHandler = eventHandler;
Redraw = redraw;
}
}
private readonly struct DeleteProfileButtonData
{
public readonly string ButtonText;
public readonly int Arg;
public readonly float Scale;
public readonly float Padding;
public DeleteProfileButtonData(string button_text, int arg = 0, float scale = 1f, float padding = 0.2f)
{
ButtonText = button_text;
Arg = arg;
Scale = scale;
Padding = padding;
}
}
private readonly struct ConditionalBlockerData
{
public readonly Func<bool> ShouldBlock;
public ConditionalBlockerData(Func<bool> shouldBlock)
{
ShouldBlock = shouldBlock;
}
}
private readonly struct PageSelectorData
{
public readonly int MaxItemsPerPage;
public PageSelectorData(int maxItemsPerPage)
{
MaxItemsPerPage = maxItemsPerPage;
}
}
public PreferenceSystemManager AddLabel(string text)
{
_elements.Peek().Add((ElementType.Label, new LabelData(text)));
return this;
}
public PreferenceSystemManager AddInfo(string text)
{
_elements.Peek().Add((ElementType.Info, new InfoData(text)));
return this;
}
public PreferenceSystemManager AddSelect(List<string> options, Action<int> on_activate, int index = 0, bool redraw = false)
{
_elements.Peek().Add((ElementType.Select, new SelectData(options, on_activate, index, redraw)));
return this;
}
public PreferenceSystemManager AddButton(string button_text, Action<int> on_activate, int arg = 0, float scale = 1f, float padding = 0.2f)
{
_elements.Peek().Add((ElementType.Button, new ButtonData(button_text, on_activate, arg, scale, padding)));
return this;
}
public PreferenceSystemManager AddButton(string button_text, Action<int> on_activate, bool closeOnPress, int arg = 0, float scale = 1f, float padding = 0.2f)
{
_elements.Peek().Add((ElementType.Button, new ButtonData(button_text, on_activate, closeOnPress, arg, scale, padding)));
return this;
}
public PreferenceSystemManager AddButtonWithConfirm(string button_text, string info_text, Action<GenericChoiceDecision> callback, int arg = 0, float scale = 1f, float padding = 0.2f)
{
_elements.Peek().Add((ElementType.ButtonWithConfirm, new ButtonWithConfirmData(button_text, info_text, callback, arg, scale, padding)));
return this;
}
public PreferenceSystemManager AddPlayerRow(string username, PlayerInfo player, Action<int> on_kick, Action<int> on_remove, int arg = 0, float scale = 1f, float padding = 0.2f)
{
_elements.Peek().Add((ElementType.PlayerRow, new PlayerRowData(username, player, on_kick, on_remove, arg, scale, padding)));
return this;
}
public PreferenceSystemManager AddSubmenu(string button_text, string submenu_key, bool skip_stack = false)
{
Type typeKey = CreateTypeKey($"{sWhitespace.Replace(MOD_NAME, "")}_{sWhitespace.Replace(submenu_key, "")}");
if (_menuTypeKeys.Contains(typeKey) || _tempMenuTypeKeys.Contains(typeKey))
{
throw new ArgumentException("Submenu key already exists!");
}
_tempMenuTypeKeys.Push(typeKey);
_elements.Peek().Add((ElementType.SubmenuButton, new SubmenuButtonData(button_text, typeKey, skip_stack)));
_elements.Push(new List<(ElementType, object)>());
_conditionalBlockers.Push(0);
return this;
}
public PreferenceSystemManager AddSelfRegisteredSubmenu<TMenu>(string button_text, bool skip_stack = false) where TMenu : Menu<MenuAction>
{
_elements.Peek().Add((ElementType.SubmenuButton, new SubmenuButtonData(button_text, typeof(TMenu), skip_stack)));
return this;
}
public PreferenceSystemManager AddActionButton(string button_text, PauseMenuAction action)
{
_elements.Peek().Add((ElementType.ActionButton, new ActionButtonData(button_text, action)));
return this;
}
public PreferenceSystemManager AddActionButton(string button_text, MainMenuAction action)
{
_elements.Peek().Add((ElementType.ActionButton, new ActionButtonData(button_text, action)));
return this;
}
public PreferenceSystemManager AddProfileSelector()
{
_elements.Peek().Add((ElementType.ProfileSelector, null));
return this;
}
public PreferenceSystemManager AddDeleteProfileButton(string button_text = "Delete Profile", int arg = 0, float scale = 1f, float padding = 0.2f)
{
_elements.Peek().Add((ElementType.DeleteProfileButton, new DeleteProfileButtonData(button_text, arg, scale, padding)));
return this;
}
public PreferenceSystemManager AddResetPreferencesButton(string button_text, Action onReset = null, bool requireConfirm = true, string confirmInfoText = "Are you sure you want to reset all preferences?", int arg = 0, float scale = 1f, float padding = 0.2f)
{
Action<int> onChanged = (int _) =>
{
ResetToDefault();
if (onReset != null)
onReset();
};
if (requireConfirm)
{
AddButtonWithConfirm(button_text, confirmInfoText, (GenericChoiceDecision gcd) =>
{
switch (gcd)
{
case GenericChoiceDecision.Accept:
onChanged(arg);
break;
default:
break;
}
}, arg, scale, padding);
}
else
{
AddButton(button_text, onChanged, arg, scale, padding);
}
return this;
}
public PreferenceSystemManager AddSpacer()
{
_elements.Peek().Add((ElementType.Spacer, null));
return this;
}
public PreferenceSystemManager SubmenuDone()
{
if (_elements.Count < 2)
{
throw new Exception("Submenu depth already at highest level.");
}
CompletedSubmenuTransfer();
return this;
}
public PreferenceSystemManager AddHostStatusConditionalBlocker(bool block_if_host = false, bool block_if_client = true)
{
if (block_if_host)
{
_elements.Peek().Add((ElementType.ConditionalBlocker, new ConditionalBlockerData(() => Session.HostIdentifier == 0)));
_conditionalBlockers.Push(_conditionalBlockers.Pop() + 1);
}
if (block_if_client)
{
_elements.Peek().Add((ElementType.ConditionalBlocker, new ConditionalBlockerData(() => Session.HostIdentifier != 0)));
_conditionalBlockers.Push(_conditionalBlockers.Pop() + 1);
}
return this;
}
public PreferenceSystemManager AddConditionalBlocker(Func<bool> shouldBlock)
{
_elements.Peek().Add((ElementType.ConditionalBlocker, new ConditionalBlockerData(shouldBlock)));
_conditionalBlockers.Push(_conditionalBlockers.Pop() + 1);
return this;
}
public PreferenceSystemManager ConditionalBlockerDone()
{
if (_conditionalBlockers.Peek() < 1)
{
throw new Exception("No conditional blockers to terminate.");
}
int conditionalBlockerLevel = 1;
int pagedItemLevel = 0;
bool shouldThrowException = false;
foreach (ElementType elementType in _elements.Peek().Select(x => x.Item1).Reverse())
{
bool shouldBreak = false;
switch (elementType)
{
case ElementType.ConditionalBlocker:
if (conditionalBlockerLevel == 1)
{
shouldThrowException = pagedItemLevel != 0;
shouldBreak = true;
}
else
conditionalBlockerLevel--;
break;
case ElementType.ConditionalBlockerDone:
conditionalBlockerLevel++;
break;
case ElementType.PagedItem:
pagedItemLevel++;
break;
case ElementType.PagedItemDone:
pagedItemLevel--;
break;
}
if (shouldBreak)
{
break;
}
}
if (shouldThrowException)
{
throw new Exception("Conditional blocker must not cross paged item boundary!");
}
_conditionalBlockers.Push(_conditionalBlockers.Pop() - 1);
_elements.Peek().Add((ElementType.ConditionalBlockerDone, null));
return this;
}
public PreferenceSystemManager AddPageSelector(int maxItemsPerPage)
{
foreach (ElementType elementType in _elements.Peek().Select(x => x.Item1))
{
if (IsSelectableElement(elementType))
throw new Exception("Page selector must be the first selectable element!");
}
_elements.Peek().Add((ElementType.PageSelector, new PageSelectorData(maxItemsPerPage)));
return this;
}
public PreferenceSystemManager StartPagedItem()