/
MechJebModuleCustomInfoWindow.cs
1108 lines (944 loc) · 43.5 KB
/
MechJebModuleCustomInfoWindow.cs
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 System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using KSP.Localization;
using UnityEngine;
using static MechJebLib.Statics;
using Object = UnityEngine.Object;
namespace MuMech
{
public class MechJebModuleCustomInfoWindow : DisplayModule
{
[Persistent(pass = (int)Pass.GLOBAL)]
public string title = Localizer.Format("#MechJeb_WindowEd_CustomInfoWindow_title"); //Custom Info Window
[Persistent(collectionIndex = "InfoItem", pass = (int)Pass.GLOBAL)]
public List<InfoItem> items = new List<InfoItem>();
[SerializeField]
[Persistent(pass = (int)Pass.GLOBAL)]
private bool isCompact;
public bool IsCompact
{
get => isCompact;
set
{
Dirty = isCompact != value;
isCompact = value;
}
}
[Persistent(pass = (int)Pass.GLOBAL)]
public Color backgroundColor = new Color(0, 0, 0, 1);
[Persistent(pass = (int)Pass.GLOBAL)]
public Color text = new Color(1, 1, 1, 1);
public Texture2D background;
private GUISkin localSkin;
private TimeSpan refreshInterval = TimeSpan.FromSeconds(0.1);
private DateTime lastRefresh = DateTime.MinValue;
[SerializeField]
[Persistent(pass = (int)Pass.GLOBAL)]
private EditableInt refreshRate = 10;
public void UpdateRefreshRate() => refreshInterval = TimeSpan.FromSeconds(1d / refreshRate);
public override void OnDestroy()
{
if (background)
{
Object.Destroy(background);
}
base.OnDestroy();
}
public override void OnSave(ConfigNode local, ConfigNode type, ConfigNode global)
{
//Do nothing: custom info windows will be saved in MechJebModuleCustomWindowEditor.OnSave
}
public virtual void UpdateWindowItems()
{
DateTime now = DateTime.Now;
if (now - lastRefresh < refreshInterval) return;
foreach (InfoItem item in items)
if (HighLogic.LoadedSceneIsEditor ? item.showInEditor : item.showInFlight)
item.UpdateItem();
lastRefresh = now;
}
private void RefreshRateGUI()
{
int oldRate = refreshRate;
if (GuiUtils.showAdvancedWindowSettings)
GuiUtils.SimpleTextBox("Update Interval", refreshRate, "Hz");
if (oldRate != refreshRate)
{
refreshRate = Math.Max(refreshRate, 1);
UpdateRefreshRate();
}
}
protected override void WindowGUI(int windowID)
{
GUI.skin = isCompact ? GuiUtils.compactSkin : GuiUtils.skin;
GUI.contentColor = text;
// Only run the updater during the Layout pass, not the Repaint pass
if (Event.current.type == EventType.Layout)
UpdateWindowItems();
GUILayout.BeginVertical();
foreach (InfoItem item in items)
{
if (HighLogic.LoadedSceneIsEditor ? item.showInEditor : item.showInFlight)
item.DrawItem();
else
GUILayout.Label(item.localizedName); //
}
if (items.Count == 0)
GUILayout.Label(CachedLocalizer.Instance
.MechJeb_WindowEd_CustomInfoWindow_Label1); //Add items to this window with the custom window editor.
RefreshRateGUI();
GUILayout.EndVertical();
if (!IsOverlay && GUI.Button(new Rect(10, 0, 13, 20), "E", GuiUtils.yellowOnHover))
{
MechJebModuleCustomWindowEditor editor = Core.GetComputerModule<MechJebModuleCustomWindowEditor>();
if (editor != null)
{
editor.Enabled = true;
editor.editedWindow = this;
}
}
if (!IsOverlay && GUI.Button(new Rect(25, 0, 13, 20), "C", GuiUtils.yellowOnHover))
{
MuUtils.SystemClipboard = ToSharingString();
ScreenMessages.PostScreenMessage(Localizer.Format("#MechJeb_WindowEd_CustomInfoWindow_Scrmsg1", GetName()), 3.0f,
ScreenMessageStyle.UPPER_RIGHT); //Configuration of <<1>> window copied to clipboard.
}
base.WindowGUI(windowID);
}
public override GUILayoutOption[] WindowOptions() => new[] { GUILayout.Width(250), GUILayout.Height(30) };
public override void DrawGUI(bool inEditor)
{
Init();
if (IsOverlay)
{
GUI.skin = localSkin;
}
base.DrawGUI(inEditor);
if (IsOverlay)
GUI.skin = GuiUtils.skin;
}
public void Init()
{
if (!background)
{
background = new Texture2D(1, 1, TextureFormat.ARGB32, false);
background.SetPixel(0, 0, backgroundColor);
background.Apply();
}
if (IsOverlay && !localSkin)
{
localSkin = Object.Instantiate(GuiUtils.transparentSkin);
localSkin.window.normal.background = background;
localSkin.window.onNormal.background = background;
}
}
public string ToSharingString()
{
string windowSharingString = "--- MechJeb Custom Window ---\n";
windowSharingString += "Name: " + GetName() + "\n";
windowSharingString += "Show in:" + (ShowInEditor ? " editor" : "") + (ShowInFlight ? " flight" : "") + "\n";
for (int i = 0; i < items.Count; i++)
{
InfoItem item = items[i];
windowSharingString += item.id + "\n";
}
windowSharingString += "-----------------------------\n";
windowSharingString = windowSharingString.Replace("\n", Environment.NewLine);
return windowSharingString;
}
public void FromSharingString(string[] lines, List<InfoItem> registry)
{
if (lines.Length > 1 && lines[1].StartsWith("Name: ")) title = lines[1].Trim().Substring("Name: ".Length);
if (lines.Length > 2 && lines[2].StartsWith("Show in:"))
{
ShowInEditor = lines[2].Contains("editor");
ShowInFlight = lines[2].Contains("flight");
}
for (int i = 3; i < lines.Length; i++)
{
string id = lines[i].Trim();
InfoItem match = registry.FirstOrDefault(item => item.id == id);
if (match != null) items.Add(match);
}
}
public override string GetName() => title;
public override string IconName() => title;
public MechJebModuleCustomInfoWindow(MechJebCore core) : base(core) { }
}
public class MechJebModuleCustomWindowEditor : DisplayModule
{
public List<InfoItem> registry = new List<InfoItem>();
public MechJebModuleCustomInfoWindow editedWindow;
private int selectedItemIndex = -1;
[Persistent(pass = (int)Pass.GLOBAL)]
private InfoItem.Category itemCategory = InfoItem.Category.Orbit;
private static readonly string[] categories = Enum.GetNames(typeof(InfoItem.Category));
private int presetIndex;
private bool editingBackground;
private bool editingText;
public override void OnLoad(ConfigNode local, ConfigNode type, ConfigNode global)
{
base.OnLoad(local, type, global);
registry.Clear();
editedWindow = null;
RegisterInfoItems(VesselState);
foreach (ComputerModule m in Core.GetComputerModules<ComputerModule>())
{
RegisterInfoItems(m);
}
if (global == null) return;
//Load custom info windows, which are stored in our ConfigNode:
ConfigNode[] windowNodes = global.GetNodes(typeof(MechJebModuleCustomInfoWindow).Name);
foreach (ConfigNode windowNode in windowNodes)
{
var window = new MechJebModuleCustomInfoWindow(Core);
ConfigNode.LoadObjectFromConfig(window, windowNode);
window.UpdateRefreshRate();
bool useOldConfig = true;
if (windowNode.HasValue("enabledEditor"))
{
bool loadedEnabled;
if (bool.TryParse(windowNode.GetValue("enabledEditor"), out loadedEnabled))
{
window.enabledEditor = loadedEnabled;
useOldConfig = false;
if (HighLogic.LoadedSceneIsEditor)
window.Enabled = loadedEnabled;
}
}
if (windowNode.HasValue("enabledFlight"))
{
bool loadedEnabled;
if (bool.TryParse(windowNode.GetValue("enabledFlight"), out loadedEnabled))
{
window.enabledFlight = loadedEnabled;
useOldConfig = false;
if (HighLogic.LoadedSceneIsFlight)
window.Enabled = loadedEnabled;
}
}
if (useOldConfig)
{
if (windowNode.HasValue("enabled"))
{
bool loadedEnabled;
if (bool.TryParse(windowNode.GetValue("enabled"), out loadedEnabled))
{
window.Enabled = loadedEnabled;
window.enabledEditor = window.Enabled;
window.enabledFlight = window.Enabled;
}
}
window.enabledEditor = window.Enabled;
window.enabledFlight = window.Enabled;
}
window.items = new List<InfoItem>();
if (windowNode.HasNode("items"))
{
ConfigNode itemCollection = windowNode.GetNode("items");
ConfigNode[] itemNodes = itemCollection.GetNodes("InfoItem");
foreach (ConfigNode itemNode in itemNodes)
{
string id = itemNode.GetValue("id");
InfoItem match = registry.FirstOrDefault(item => item.id == id);
if (match != null) window.items.Add(match);
}
}
Core.AddComputerModuleLater(window);
}
}
public override void OnSave(ConfigNode local, ConfigNode type, ConfigNode global)
{
base.OnSave(local, type, global);
//Save custom info windows within our ConfigNode:
if (global == null) return;
foreach (MechJebModuleCustomInfoWindow window in Core.GetComputerModules<MechJebModuleCustomInfoWindow>())
{
string name = typeof(MechJebModuleCustomInfoWindow).Name;
var windowNode = ConfigNode.CreateConfigFromObject(window, (int)Pass.GLOBAL, null);
if (HighLogic.LoadedSceneIsEditor)
window.enabledEditor = window.Enabled;
if (HighLogic.LoadedSceneIsFlight)
window.enabledFlight = window.Enabled;
windowNode.AddValue("enabledFlight", window.enabledFlight);
windowNode.AddValue("enabledEditor", window.enabledEditor);
windowNode.CopyTo(global.AddNode(name));
window.Dirty = false;
}
}
public override void OnStart(PartModule.StartState state) => editedWindow = Core.GetComputerModule<MechJebModuleCustomInfoWindow>();
private void RegisterInfoItems(object obj)
{
foreach (MemberInfo member in obj.GetType().GetMembers(BindingFlags.GetField | BindingFlags.GetProperty | BindingFlags.Instance |
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy))
{
foreach (Attribute attribute in member.GetCustomAttributes(true))
{
if (attribute is ValueInfoItemAttribute) registry.Add(new ValueInfoItem(obj, member, (ValueInfoItemAttribute)attribute));
else if (attribute is ActionInfoItemAttribute)
registry.Add(new ActionInfoItem(obj, (MethodInfo)member, (ActionInfoItemAttribute)attribute));
else if (attribute is ToggleInfoItemAttribute) registry.Add(new ToggleInfoItem(obj, member, (ToggleInfoItemAttribute)attribute));
else if (attribute is GeneralInfoItemAttribute)
registry.Add(new GeneralInfoItem(obj, (MethodInfo)member, (GeneralInfoItemAttribute)attribute));
else if (attribute is EditableInfoItemAttribute)
registry.Add(new EditableInfoItem(obj, member, (EditableInfoItemAttribute)attribute));
}
}
}
private void AddNewWindow()
{
editedWindow = new MechJebModuleCustomInfoWindow(Core);
if (HighLogic.LoadedSceneIsEditor) editedWindow.ShowInEditor = true;
if (HighLogic.LoadedSceneIsFlight) editedWindow.ShowInFlight = true;
Core.AddComputerModule(editedWindow);
editedWindow.Enabled = true;
editedWindow.Dirty = true;
}
private void RemoveCurrentWindow()
{
if (editedWindow == null) return;
Core.RemoveComputerModule(editedWindow);
editedWindow = Core.GetComputerModule<MechJebModuleCustomInfoWindow>();
}
public override void DrawGUI(bool inEditor)
{
base.DrawGUI(inEditor);
if (editingBackground)
{
if (editedWindow != null)
{
editedWindow.Init();
Color newColor = ColorPickerRGB.DrawGUI((int)windowPos.xMax + 5, (int)windowPos.yMin, editedWindow.backgroundColor);
if (editedWindow.backgroundColor != newColor)
{
editedWindow.backgroundColor = newColor;
editedWindow.background.SetPixel(0, 0, editedWindow.backgroundColor);
editedWindow.background.Apply();
editedWindow.Dirty = true;
}
}
}
if (editingText)
{
if (editedWindow != null)
{
Color newColor = ColorPickerRGB.DrawGUI((int)windowPos.xMax + 5, (int)windowPos.yMin, editedWindow.text);
if (editedWindow.text != newColor)
{
editedWindow.text = newColor;
editedWindow.Dirty = true;
}
}
}
}
private Vector2 scrollPos, scrollPos2;
protected override void WindowGUI(int windowID)
{
GUILayout.BeginVertical();
if (editedWindow == null) editedWindow = Core.GetComputerModule<MechJebModuleCustomInfoWindow>();
if (editedWindow == null)
{
if (GUILayout.Button(Localizer.Format("#MechJeb_WindowEd_button1"))) AddNewWindow(); //New window
}
else
{
GUILayout.BeginHorizontal();
if (GUILayout.Button(Localizer.Format("#MechJeb_WindowEd_button1"))) AddNewWindow(); //New window
if (GUILayout.Button(Localizer.Format("#MechJeb_WindowEd_button2"))) RemoveCurrentWindow(); //Delete window
GUILayout.EndHorizontal();
}
if (editedWindow != null)
{
List<ComputerModule> allWindows = Core.GetComputerModules<MechJebModuleCustomInfoWindow>();
GUILayout.BeginHorizontal();
GUILayout.Label(Localizer.Format("#MechJeb_WindowEd_Edtitle"), GUILayout.ExpandWidth(false)); //Title:
int editedWindowIndex = allWindows.IndexOf(editedWindow);
editedWindowIndex = GuiUtils.ArrowSelector(editedWindowIndex, allWindows.Count, () =>
{
string newTitle = GUILayout.TextField(editedWindow.title, GUILayout.Width(120), GUILayout.ExpandWidth(false));
if (editedWindow.title != newTitle)
{
editedWindow.title = newTitle;
editedWindow.Dirty = true;
}
});
editedWindow = (MechJebModuleCustomInfoWindow)allWindows[editedWindowIndex];
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label(Localizer.Format("#MechJeb_WindowEd_label1")); //Show in:
editedWindow.ShowInFlight =
GUILayout.Toggle(editedWindow.ShowInFlight, Localizer.Format("#MechJeb_WindowEd_checkbox1"), GUILayout.Width(60)); //Flight
editedWindow.ShowInEditor = GUILayout.Toggle(editedWindow.ShowInEditor, Localizer.Format("#MechJeb_WindowEd_checkbox2")); //Editor
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
editedWindow.IsOverlay = GUILayout.Toggle(editedWindow.IsOverlay, Localizer.Format("#MechJeb_WindowEd_checkbox3")); //Overlay
editedWindow.Locked = GUILayout.Toggle(editedWindow.Locked, Localizer.Format("#MechJeb_WindowEd_checkbox4")); //Locked
editedWindow.IsCompact = GUILayout.Toggle(editedWindow.IsCompact, Localizer.Format("#MechJeb_WindowEd_checkbox5")); //Compact
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label(Localizer.Format("#MechJeb_WindowEd_label2")); //Color:
bool previous = editingText;
editingText = GUILayout.Toggle(editingText, Localizer.Format("#MechJeb_WindowEd_checkbox6")); //Text
if (editingText && editingText != previous)
editingBackground = false;
previous = editingBackground;
editingBackground = GUILayout.Toggle(editingBackground, Localizer.Format("#MechJeb_WindowEd_checkbox7")); //Background
if (editingBackground && editingBackground != previous)
editingText = false;
GUILayout.EndHorizontal();
GUILayout.Label(Localizer.Format("#MechJeb_WindowEd_label3")); //Window contents (click to edit):
GUILayout.BeginVertical(GUILayout.Height(100));
scrollPos = GUILayout.BeginScrollView(scrollPos);
for (int i = 0; i < editedWindow.items.Count; i++)
{
GUIStyle s = i == selectedItemIndex ? GuiUtils.yellowLabel : GUI.skin.label;
if (GUILayout.Button(Localizer.Format(editedWindow.items[i].description), s)) selectedItemIndex = i; //
}
GUILayout.EndScrollView();
GUILayout.EndVertical();
GUILayout.BeginHorizontal();
if (!(selectedItemIndex >= 0 && selectedItemIndex < editedWindow.items.Count)) selectedItemIndex = -1;
if (GUILayout.Button(Localizer.Format("#MechJeb_WindowEd_button3")) && selectedItemIndex != -1)
editedWindow.items.RemoveAt(selectedItemIndex); //Remove
if (GUILayout.Button(Localizer.Format("#MechJeb_WindowEd_button4")) && selectedItemIndex != -1) //"Move up"
{
if (selectedItemIndex > 0)
{
InfoItem item = editedWindow.items[selectedItemIndex];
editedWindow.items.RemoveAt(selectedItemIndex);
editedWindow.items.Insert(selectedItemIndex - 1, item);
selectedItemIndex -= 1;
}
}
if (GUILayout.Button(Localizer.Format("#MechJeb_WindowEd_button5")) && selectedItemIndex != -1) //Move down
{
if (selectedItemIndex < editedWindow.items.Count)
{
InfoItem item = editedWindow.items[selectedItemIndex];
editedWindow.items.RemoveAt(selectedItemIndex);
editedWindow.items.Insert(selectedItemIndex + 1, item);
selectedItemIndex += 1;
}
}
GUILayout.EndHorizontal();
GUILayout.Label(Localizer.Format("#MechJeb_WindowEd_label4")); //Click an item to add it to the info window:
itemCategory = (InfoItem.Category)GuiUtils.ComboBox.Box((int)itemCategory, categories, this);
scrollPos2 = GUILayout.BeginScrollView(scrollPos2);
foreach (InfoItem item in registry.Where(it => it.category == itemCategory).OrderBy(it => it.description))
{
if (GUILayout.Button(Localizer.Format(item.description), GuiUtils.yellowOnHover)) //
{
editedWindow.items.Add(item);
}
}
GUILayout.EndScrollView();
}
GUILayout.Label(Localizer.Format("#MechJeb_WindowEd_label5"), GuiUtils.middleCenterLabel); //Window presets:
presetIndex = GuiUtils.ArrowSelector(presetIndex, CustomWindowPresets.presets.Length, () =>
{
if (GUILayout.Button(CustomWindowPresets.presets[presetIndex].name))
{
MechJebModuleCustomInfoWindow newWindow = CreateWindowFromSharingString(CustomWindowPresets.presets[presetIndex].sharingString);
if (newWindow != null) editedWindow = newWindow;
}
});
GUILayout.EndVertical();
base.WindowGUI(windowID);
}
public override GUILayoutOption[] WindowOptions() => new[] { GUILayout.Width(200), GUILayout.Height(540) };
public override string GetName() => CachedLocalizer.Instance.MechJeb_WindowEd_title; //Custom Window Editor
public override string IconName() => "Custom Window Editor";
public MechJebModuleCustomWindowEditor(MechJebCore core)
: base(core)
{
ShowInFlight = true;
ShowInEditor = true;
}
public void AddDefaultWindows()
{
CreateWindowFromSharingString(CustomWindowPresets.presets[0].sharingString).Enabled = false;
CreateWindowFromSharingString(CustomWindowPresets.presets[1].sharingString).Enabled = false;
CreateWindowFromSharingString(CustomWindowPresets.presets[2].sharingString).Enabled = false;
CreateWindowFromSharingString(CustomWindowPresets.presets[3].sharingString).Enabled = false;
CreateWindowFromSharingString(CustomWindowPresets.presets[4].sharingString).Enabled = false;
CreateWindowFromSharingString(CustomWindowPresets.presets[5].sharingString).Enabled = false;
CreateWindowFromSharingString(CustomWindowPresets.presets[6].sharingString).Enabled = false;
CreateWindowFromSharingString(CustomWindowPresets.presets[7].sharingString).Enabled = false;
CreateWindowFromSharingString(CustomWindowPresets.presets[10].sharingString).Enabled = false;
}
public MechJebModuleCustomInfoWindow CreateWindowFromSharingString(string sharingString)
{
string[] lines = sharingString.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
if (lines[0] != "--- MechJeb Custom Window ---")
{
ScreenMessages.PostScreenMessage(Localizer.Format("#MechJeb_WindowEd_CustomInfoWindow_Scrmsg2"), 3.0f,
ScreenMessageStyle.UPPER_RIGHT); //"Pasted text wasn't a MechJeb custom window descriptor."
return null;
}
var window = new MechJebModuleCustomInfoWindow(Core);
Core.AddComputerModule(window);
window.Enabled = true;
window.FromSharingString(lines, registry);
return window;
}
}
public class InfoItem
{
public string name;
public string localizedName;
public string description;
public bool showInEditor;
public bool showInFlight;
public enum Category
{
Orbit,
Surface,
Vessel,
Target,
Recorder,
Thrust,
Rover,
Misc
}
public Category category;
[Persistent]
public string id;
public InfoItem() { }
public InfoItem(InfoItemAttribute attribute)
{
name = attribute.name;
localizedName = Localizer.Format(name);
category = attribute.category;
description = attribute.description;
showInEditor = attribute.showInEditor;
showInFlight = attribute.showInFlight;
}
public virtual void DrawItem() { }
public virtual void UpdateItem() { }
}
//A ValueInfoItem is an info item that shows the value of some field, or the return value of some method.
public class ValueInfoItem : InfoItem
{
private readonly string units;
private readonly string format;
public const string SI = "SI";
public const string TIME = "TIME";
public const string ANGLE = "ANGLE";
public const string ANGLE_NS = "ANGLE_NS";
public const string ANGLE_EW = "ANGLE_EW";
private readonly int siSigFigs; //only used with the "SI" format
private readonly int siMaxPrecision; //only used with the "SI" format
private readonly int timeDecimalPlaces; //only used with the "TIME" format
private readonly Func<object> getValue;
private string stringValue;
private int cacheValidity = -1;
public bool externalRefresh;
public ValueInfoItem(object obj, MemberInfo member, ValueInfoItemAttribute attribute)
: base(attribute)
{
id = GetType().Name.Replace("InfoItem", "") + ":" + obj.GetType().Name.Replace("MechJebModule", "") + "." + member.Name;
units = attribute.units;
format = attribute.format;
siSigFigs = attribute.siSigFigs;
siMaxPrecision = attribute.siMaxPrecision;
timeDecimalPlaces = attribute.timeDecimalPlaces;
// This ugly stuff compiles a small function to grab the value of member, so that we don't
// have to use reflection to get it every frame.
ParameterExpression objExpr = Expression.Parameter(typeof(object), ""); // obj
Expression castObjExpr = Expression.Convert(objExpr, obj.GetType()); // (T)obj
Expression memberExpr;
if (member is MethodInfo) memberExpr = Expression.Call(castObjExpr, (MethodInfo)member);
else memberExpr = Expression.MakeMemberAccess(castObjExpr, member); // ((T)obj).member
Expression castMemberExpr = Expression.Convert(memberExpr, typeof(object)); // (object)(((T)obj).member);
Func<object, object> getFromObj = Expression.Lambda<Func<object, object>>(castMemberExpr, objExpr).Compile();
getValue = () => getFromObj(obj);
}
private string GetStringValue(object value)
{
if (value == null) return "null";
if (value is string) return $"{(string)value} {units}";
if (value is int) return $"{(int)value} {units}";
double doubleValue = -999;
if (value is double) doubleValue = (double)value;
else if (value is float) doubleValue = (float)value;
else if (value is MovingAverage) doubleValue = (MovingAverage)value;
else if (value is Vector3d) doubleValue = ((Vector3d)value).magnitude;
else if (value is Vector3) doubleValue = ((Vector3)value).magnitude;
else if (value is EditableDouble) doubleValue = (EditableDouble)value;
if (format == TIME) return GuiUtils.TimeToDHMS(doubleValue, timeDecimalPlaces);
if (format == ANGLE) return Coordinates.AngleToDMS(doubleValue);
if (format == ANGLE_NS) return Coordinates.AngleToDMS(doubleValue) + (doubleValue > 0 ? " N" : " S");
if (format == ANGLE_EW) return Coordinates.AngleToDMS(doubleValue) + (doubleValue > 0 ? " E" : " W");
if (format == SI) return doubleValue.ToSI(siSigFigs, siMaxPrecision) + units;
return doubleValue.ToString(format) + " " + units;
}
private void UpdateItemCache()
{
int frameCount = Time.frameCount;
if (frameCount != cacheValidity)
{
object value = getValue();
stringValue = Localizer.Format(GetStringValue(value));
cacheValidity = frameCount;
}
}
public override void UpdateItem()
{
externalRefresh = true;
cacheValidity = 0;
UpdateItemCache();
}
public override void DrawItem()
{
if (!externalRefresh) UpdateItemCache();
GUILayout.BeginHorizontal();
GUILayout.Label(localizedName); //
GUILayout.Label(stringValue, GUILayout.ExpandWidth(false)); //
GUILayout.EndHorizontal();
}
}
public class ActionInfoItem : InfoItem
{
private readonly Action action;
public ActionInfoItem(object obj, MethodInfo method, ActionInfoItemAttribute attribute)
: base(attribute)
{
id = GetType().Name.Replace("InfoItem", "") + ":" + obj.GetType().Name.Replace("MechJebModule", "") + "." + method.Name;
action = (Action)Delegate.CreateDelegate(typeof(Action), obj, method);
}
public override void DrawItem()
{
if (GUILayout.Button(localizedName)) action(); //
}
}
public class ToggleInfoItem : InfoItem
{
private readonly object obj;
private readonly MemberInfo member;
public ToggleInfoItem(object obj, MemberInfo member, ToggleInfoItemAttribute attribute)
: base(attribute)
{
id = GetType().Name.Replace("InfoItem", "") + ":" + obj.GetType().Name.Replace("MechJebModule", "") + "." + member.Name;
this.obj = obj;
this.member = member;
}
public override void DrawItem()
{
bool currentValue = false;
if (member is FieldInfo) currentValue = (bool)((FieldInfo)member).GetValue(obj);
else if (member is PropertyInfo) currentValue = (bool)((PropertyInfo)member).GetValue(obj, new object[] { });
bool newValue = GUILayout.Toggle(currentValue, localizedName); //
if (newValue != currentValue)
{
if (member is FieldInfo) ((FieldInfo)member).SetValue(obj, newValue);
else if (member is PropertyInfo) ((PropertyInfo)member).SetValue(obj, newValue, new object[] { });
}
}
}
public class GeneralInfoItem : InfoItem
{
private readonly Action draw;
private readonly object obj;
public GeneralInfoItem(object obj, MethodInfo method, GeneralInfoItemAttribute attribute)
: base(attribute)
{
id = GetType().Name.Replace("InfoItem", "") + ":" + obj.GetType().Name.Replace("MechJebModule", "") + "." + method.Name;
draw = (Action)Delegate.CreateDelegate(typeof(Action), obj, method);
this.obj = obj;
}
public override void DrawItem() => draw();
public override void UpdateItem()
{
if (obj is MechJebModuleInfoItems items)
items.UpdateItems();
}
}
public class EditableInfoItem : InfoItem
{
public string rightLabel;
public float width;
private readonly IEditable val;
public EditableInfoItem(object obj, MemberInfo member, EditableInfoItemAttribute attribute)
: base(attribute)
{
id = GetType().Name.Replace("InfoItem", "") + ":" + obj.GetType().Name.Replace("MechJebModule", "") + "." + member.Name;
rightLabel = attribute.rightLabel;
width = attribute.width;
if (member is FieldInfo) val = (IEditable)((FieldInfo)member).GetValue(obj);
else if (member is PropertyInfo) val = (IEditable)((PropertyInfo)member).GetValue(obj, new object[] { });
}
public override void DrawItem()
{
if (val != null)
{
GuiUtils.SimpleTextBox(localizedName, val, rightLabel, width); //
}
}
}
public abstract class InfoItemAttribute : Attribute
{
public string name; //the name displayed in the info window
public InfoItem.Category category;
public string description = ""; //the description shown in the window editor list
public bool showInEditor = false;
public bool showInFlight = true;
public InfoItemAttribute(string name, InfoItem.Category category)
{
this.name = name;
this.category = category;
description = name; //description defaults to name, but can be set to be something different
}
}
//Apply this attribute to a field or method to make the field or method eligible to be made into a ValueInfoItem
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method)]
public class ValueInfoItemAttribute : InfoItemAttribute
{
public string units = "";
public string format = "";
public int siSigFigs = 4;
public int siMaxPrecision = -33;
public int timeDecimalPlaces = 0;
public ValueInfoItemAttribute(string name, InfoItem.Category category) : base(name, category) { }
}
//Apply this attribute to a method to make the method callable via an ActionInfoItem
[AttributeUsage(AttributeTargets.Method)]
public class ActionInfoItemAttribute : InfoItemAttribute
{
public ActionInfoItemAttribute(string name, InfoItem.Category category) : base(name, category) { }
}
//Apply this attribute to a boolean to make the boolean toggleable via a ToggleInfoItem
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class ToggleInfoItemAttribute : InfoItemAttribute
{
public ToggleInfoItemAttribute(string name, InfoItem.Category category) : base(name, category) { }
}
//Apply this attribute to a method to indicate that it is a method that will draw
//an InfoItem
[AttributeUsage(AttributeTargets.Method)]
public class GeneralInfoItemAttribute : InfoItemAttribute
{
public GeneralInfoItemAttribute(string name, InfoItem.Category category) : base(name, category) { }
}
//Apply this attribute to a IEditable to make the contents editable via an EditableInfoItem
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class EditableInfoItemAttribute : InfoItemAttribute
{
public string rightLabel = "";
public float width = 100;
public EditableInfoItemAttribute(string name, InfoItem.Category category) : base(name, category) { }
}
public static class CustomWindowPresets
{
public struct Preset
{
public string name;
public string sharingString;
}
public static Preset[] presets =
{
new Preset
{
name = Localizer.Format("#MechJeb_WindowEd_Presetname1"), //Orbit Info
sharingString =
@"--- MechJeb Custom Window ---
Name: " + Localizer.Format("#MechJeb_WindowEd_Presetname1") + @"
Show in: flight
Value:VesselState.speedOrbital
Value:VesselState.orbitApA
Value:VesselState.orbitPeA
Value:VesselState.orbitPeriod
Value:VesselState.orbitTimeToAp
Value:VesselState.orbitTimeToPe
Value:VesselState.orbitSemiMajorAxis
Value:VesselState.orbitInclination
Value:VesselState.orbitEccentricity
Value:VesselState.orbitLAN
Value:VesselState.orbitArgumentOfPeriapsis
Value:VesselState.angleToPrograde
Value:InfoItems.RelativeInclinationToTarget
-----------------------------" //Orbit Info
},
new Preset
{
name = Localizer.Format("#MechJeb_WindowEd_Presetname2"), //Surface Info
sharingString =
@"--- MechJeb Custom Window ---
Name: " + Localizer.Format("#MechJeb_WindowEd_Presetname2") + @"
Show in: flight
Value:VesselState.altitudeASL
Value:VesselState.altitudeTrue
Value:VesselState.vesselPitch
Value:VesselState.vesselHeading
Value:VesselState.vesselRoll
Value:VesselState.speedSurface
Value:VesselState.speedVertical
Value:VesselState.speedSurfaceHorizontal
Value:InfoItems.GetCoordinateString
Value:InfoItems.CurrentBiome
-----------------------------" //Surface Info
},
new Preset
{
name = Localizer.Format("#MechJeb_WindowEd_Presetname3"), //Vessel Info
sharingString =
@"--- MechJeb Custom Window ---
Name: " + Localizer.Format("#MechJeb_WindowEd_Presetname3") + @"
Show in: flight editor
Value:InfoItems.MaxAcceleration
Value:InfoItems.CurrentAcceleration
Value:InfoItems.MaxThrust
Value:InfoItems.VesselMass
Value:InfoItems.SurfaceTWR
Value:InfoItems.CrewCapacity
-----------------------------" //Vessel Info
},
new Preset
{
name = Localizer.Format("#MechJeb_WindowEd_Presetname4"), //Delta-V Stats
sharingString =
@"--- MechJeb Custom Window ---
Name: " + Localizer.Format("#MechJeb_WindowEd_Presetname4") + @"
Show in: flight editor
Toggle:StageStats.DVLinearThrust
Value:InfoItems.StageDeltaVAtmosphereAndVac
Value:InfoItems.TotalDeltaVAtmosphereAndVac
General:InfoItems.AllStageStats
-----------------------------" //Delta-V Stats
},
new Preset
{
name = Localizer.Format("#MechJeb_WindowEd_Presetname5"), //Ascent Stats
sharingString =
@"--- MechJeb Custom Window ---
Name: " + Localizer.Format("#MechJeb_WindowEd_Presetname5") + @"
Show in: flight
Value:FlightRecorder.deltaVExpended
Value:FlightRecorder.gravityLosses
Value:FlightRecorder.dragLosses
Value:FlightRecorder.steeringLosses
Value:FlightRecorder.timeSinceMark
Value:FlightRecorder.phaseAngleFromMark
Value:FlightRecorder.GroundDistanceFromMark
-----------------------------" //Ascent Stats
},
new Preset
{
name = Localizer.Format("#MechJeb_WindowEd_Presetname6"), //Rendezvous Info
sharingString =
@"--- MechJeb Custom Window ---
Name: " + Localizer.Format("#MechJeb_WindowEd_Presetname6") + @"
Show in: flight
Value:InfoItems.TargetTimeToClosestApproach
Value:InfoItems.TargetClosestApproachDistance
Value:InfoItems.TargetClosestApproachRelativeVelocity