-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUIEditorVM.cs
More file actions
1199 lines (1155 loc) · 56.6 KB
/
UIEditorVM.cs
File metadata and controls
1199 lines (1155 loc) · 56.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
extern alias MountAndBlade;
using System;
using System.Linq;
using System.Xml;
using TaleWorlds.Engine.GauntletUI;
using TaleWorlds.GauntletUI;
using TaleWorlds.GauntletUI.BaseTypes;
using TaleWorlds.GauntletUI.PrefabSystem;
using TaleWorlds.Library;
using TaleWorlds.ScreenSystem;
using MountAndBlade.System.Numerics;
using System.Collections.Generic;
using HarmonyLib;
using TaleWorlds.GauntletUI.Layout;
using TaleWorlds.GauntletUI.Data;
using TaleWorlds.InputSystem;
using TaleWorlds.MountAndBlade.GauntletUI.Widgets;
using HorizontalAlignment = TaleWorlds.GauntletUI.HorizontalAlignment;
using System.Text;
using InGameUIDesigner.EditorOperations;
using TaleWorlds.GauntletUI.ExtraWidgets;
using System.Windows.Controls;
using TaleWorlds.Core;
using TaleWorlds.CampaignSystem;
using TaleWorlds.GauntletUI.ExtraWidgets.Graph;
namespace InGameUIDesigner
{
public class UIEditorVM : ViewModel
{
public static UIEditorVM Instance;
// See PreventNullScopePatch.cs
public static bool DontDisconnectScopeFromRoot
{
get => Instance == null ? false : Instance._dontDisconnectScopeFromRoot;
set
{
if (Instance != null) Instance._dontDisconnectScopeFromRoot = value;
}
}
public static Widget PreviewRootWidget { get => Instance?._previewRootWidget; }
[DataSourceProperty]
public MBBindingList<WidgetResourceVM> AvailableBasicWidgetNames
{
get => _availableBasicWidgetNames;
set
{
if (value != _availableBasicWidgetNames)
{
_availableBasicWidgetNames = value;
OnPropertyChangedWithValue(value, "AvailableBasicWidgetNames");
}
}
}
[DataSourceProperty]
public MBBindingList<WidgetResourceVM> AvailablePrefabWidgetNames
{
get => _availablePrefabWidgetNames;
set
{
if (value != _availablePrefabWidgetNames)
{
_availablePrefabWidgetNames = value;
OnPropertyChangedWithValue(value, "AvailablePrefabWidgetNames");
}
}
}
[DataSourceProperty]
public MBBindingList<WidgetPropertyVM> SelectedWidgetProperties
{
get => _selectedWidgetProperties;
set
{
if (value != _selectedWidgetProperties)
{
_selectedWidgetProperties = value;
OnPropertyChangedWithValue(value, "SelectedWidgetProperties");
}
}
}
[DataSourceProperty]
public MBBindingList<WidgetHierarchyVM> WidgetHierarchy
{
get => _widgetHierarchy;
set
{
if (value != _widgetHierarchy)
{
_widgetHierarchy = value;
OnPropertyChangedWithValue(value, "WidgetHierarchy");
}
}
}
[DataSourceProperty]
public string BasicWidgetsSearchText
{
get => _basicWidgetsSearchText;
set
{
if (value != _basicWidgetsSearchText)
{
_basicWidgetsSearchText = value;
OnPropertyChangedWithValue(value, "BasicWidgetsSearchText");
FilterBasicWidgetsList();
}
}
}
[DataSourceProperty]
public string PrefabWidgetsSearchText
{
get => _prefabWidgetsSearchText;
set
{
if (value != _prefabWidgetsSearchText)
{
_prefabWidgetsSearchText = value;
OnPropertyChangedWithValue(value, "PrefabWidgetsSearchText");
FilterPrefabWidgetsList();
}
}
}
[DataSourceProperty]
public string PropertySearchText
{
get => _propertySearchText;
set
{
if (value != _propertySearchText)
{
_propertySearchText = value;
OnPropertyChangedWithValue(value, "PropertySearchText");
FilterPropertiesList();
}
}
}
public bool WidgetPickerMode { get => _widgetPickerMode; }
public UIEditorVM(UIEditorScreen screen)
{
_ownerScreen = screen;
Instance = this;
DontDisconnectScopeFromRoot = false;
_unfilteredBasicWidgetNames = new MBBindingList<WidgetResourceVM>();
_unfilteredPrefabWidgetNames = new MBBindingList<WidgetResourceVM>();
AvailableBasicWidgetNames = new MBBindingList<WidgetResourceVM>();
AvailablePrefabWidgetNames = new MBBindingList<WidgetResourceVM>();
SelectedWidgetProperties = new MBBindingList<WidgetPropertyVM>();
WidgetHierarchy = new MBBindingList<WidgetHierarchyVM>();
_undoOperationsStack = new DropOutStack<UIEditorOperation>(MAX_UNDO_COUNT);
_redoOperationsStack = new DropOutStack<UIEditorOperation>(MAX_UNDO_COUNT);
var factory = UIResourceManager.WidgetFactory;
foreach (var name in factory.GetWidgetTypes())
{
// Ignore any widget containing __ in its name, since it's most likely an auto-generated widget
if (name.Contains("__") || name == "DragCarrierWidget" || name == "TextureWidget" || name == "Container" || name == "EditorWidgetScalerWidget") continue;
if (factory.IsBuiltinType(name)) _unfilteredBasicWidgetNames.Add(new WidgetResourceVM(name, this));
else if (factory.IsCustomType(name)) _unfilteredPrefabWidgetNames.Add(new WidgetResourceVM(name, this));
}
BasicWidgetsSearchText = "";
PrefabWidgetsSearchText = "";
PropertySearchText = "";
AddExcludedProperties();
}
private void AddExcludedProperties()
{
// These properties are excluded from being viewed in the selected widget properties
_excludedWidgetProperties = new List<string>
{
"ParentWidget",
"DragWidget",
"Tag",
"PosOffset",
"LayoutImp",
"ScaledSuggestedWidth",
"ScaledSuggestedHeight",
"ScaledPositionXOffset",
"ScaledPositionYOffset",
"VisualDefinition"
};
_excludedBrushProperties = new List<string>
{
"Name",
"DefaultStyle",
"SoundProperties",
"Layers",
"DefaultStyleLayer",
"DefaultLayer"
};
}
public void Initialize(Widget previewRoot, UIContext uiContext, WidgetFactory widgetFactory, GauntletMovie movie)
{
_previewRootWidget = previewRoot;
_selectedWidgetScaler = (EditorWidgetScalerWidget) uiContext.Root.FindChild("ActiveWidgetScaler", true);
_context = uiContext;
_widgetFactory = widgetFactory;
_widgetFactory.PrefabExtensionContext.AddExtension(new PrefabWidgetExtensions());
_movie = movie;
}
public override void OnFinalize()
{
Instance = null;
base.OnFinalize();
}
private void FilterBasicWidgetsList()
{
if (BasicWidgetsSearchText.Length < 4) AvailableBasicWidgetNames = _unfilteredBasicWidgetNames;
else
{
AvailableBasicWidgetNames = new MBBindingList<WidgetResourceVM>();
foreach (var widget in _unfilteredBasicWidgetNames)
{
if (widget.Name.ToLower().Contains(BasicWidgetsSearchText.ToLower())) AvailableBasicWidgetNames.Add(widget);
}
}
}
private void FilterPrefabWidgetsList()
{
if (PrefabWidgetsSearchText.Length < 4) AvailablePrefabWidgetNames = _unfilteredPrefabWidgetNames;
else
{
AvailablePrefabWidgetNames = new MBBindingList<WidgetResourceVM>();
foreach (var widget in _unfilteredPrefabWidgetNames)
{
if (widget.Name.ToLower().Contains(PrefabWidgetsSearchText.ToLower())) AvailablePrefabWidgetNames.Add(widget);
}
}
}
private void FilterPropertiesList()
{
if (_selectedWidget == null) return;
if (PropertySearchText.Length < 3)
{
SelectedWidgetProperties = _selectedWidget.EditorGetProperties();
}
else
{
SelectedWidgetProperties = new MBBindingList<WidgetPropertyVM>();
foreach (var property in _selectedWidget.EditorGetProperties())
{
if (property.DisplayedPropertyName.ToLower().Contains(PropertySearchText.ToLower())) SelectedWidgetProperties.Add(property);
}
}
}
public void ExecuteDone()
{
ScreenManager.PopScreen();
}
public void ExecuteCancel()
{
ScreenManager.PopScreen();
}
public void ShowBrushList()
{
_ownerScreen.ShowBrushPreviewList();
}
public void ShowSpriteList()
{
_ownerScreen.ShowSpritePreviewList();
}
public void ExportButtonAction()
{
_ownerScreen.OpenExportPrompt();
}
/// <summary/>
/// <param name="property">Colour property that is going to change</param>
public void EnterColourPickerMode(WidgetPropertyVM property)
{
_ownerScreen.ShowColourPicker(property);
}
public void Exit()
{
_ownerScreen.OpenExitPrompt();
}
public void ExportPrefab(string path)
{
var xmlDoc = new XmlDocument();
var prefabNode = xmlDoc.CreateElement("Prefab");
var windowNode = xmlDoc.CreateElement("Window");
AppendXMLNodeFromWidget(_previewRootWidget, _context, windowNode, xmlDoc);
prefabNode.AppendChild(windowNode);
xmlDoc.AppendChild(prefabNode);
xmlDoc.Save(path);
}
private void AppendXMLNodeFromWidget(Widget widget, UIContext uiContext, XmlNode parentNode, XmlDocument document)
{
var nodeName = widget.EditorIsPrefabRoot() ? widget.EditorGetPrefabName() : widget.GetType().Name;
if (string.IsNullOrEmpty(nodeName)) nodeName="ErrorWith" + widget.GetType().Name;
var widgetNode = document.CreateElement(nodeName);
// Create a widget of the same type to compare properties. Any property that is unchanged isn't exported.
// This is to create a smaller XML which is less cluttered with useless properties.
var defaultWidgetOfType = widget.GetType().GetConstructor(new Type[] { typeof(UIContext) }).Invoke(new object[] { uiContext });
var widgetTypeProperties = widget.GetType().GetProperties();
foreach (var propertyInfo in widgetTypeProperties)
{
// Ignore the Id property of the PreviewRootWidget, as well any methods without a public setter function
// Ignore properties that are unchanged from the default value, and empty strings
if ((widget == _previewRootWidget && propertyInfo.Name == "Id") || _excludedWidgetProperties.Contains(propertyInfo.Name) || propertyInfo.SetMethod == null || !propertyInfo.SetMethod.IsPublic) continue;
var defaultValue = propertyInfo.GetValue(defaultWidgetOfType);
if (widget.EditorIsPrefabRoot())
{
var widgetPrefab = UIResourceManager.WidgetFactory.GetCustomType(widget.EditorGetPrefabName());
if (widgetPrefab.RootTemplate.Attributes[typeof(WidgetAttributeKeyTypeAttribute)].TryGetValue(propertyInfo.Name, out var attributeTemplate))
{
var templateDefault = WidgetPropertyVM.CastStringToValue(attributeTemplate.Value, defaultValue?.GetType(), widget);
if (templateDefault != null) defaultValue = templateDefault;
}
}
var widgetValue = propertyInfo.GetValue(widget);
if (widgetValue == null) continue;
if (widgetValue is string str && str == String.Empty) continue;
if (widgetValue.Equals(defaultValue)) continue;
var attribute = document.CreateAttribute(propertyInfo.Name);
widgetNode.Attributes.Append(attribute);
if (propertyInfo.PropertyType == typeof(Brush))
{
// For brushes, set the name to the original brush (without (Cloned) ) and then export all properties that are
// different from the original brush
var brush = widgetValue as Brush;
var val = brush.ClonedFrom == null ? brush.Name : brush.ClonedFrom.Name;
widgetNode.SetAttribute(attribute.Name, val);
foreach (var brushPropertyInfo in typeof(Brush).GetProperties())
{
if (_excludedBrushProperties.Contains(brushPropertyInfo.Name) || brushPropertyInfo.SetMethod == null || !brushPropertyInfo.SetMethod.IsPublic) continue;
var currentBrushValue = brushPropertyInfo.GetValue(brush);
var defaultBrushValue = brushPropertyInfo.GetValue(brush.ClonedFrom ?? brush);
if (currentBrushValue == null || currentBrushValue.Equals(defaultBrushValue)) continue;
var brushAttribute = document.CreateAttribute("Brush." + brushPropertyInfo.Name);
brushAttribute.Value = currentBrushValue.ToString();
widgetNode.Attributes.Append(brushAttribute);
}
}
else if (propertyInfo.PropertyType == typeof(bool))
{
// Bools are only valid in lower-case when imported
widgetNode.SetAttribute(attribute.Name, widgetValue.ToString().ToLower());
}
else if (typeof(Widget).IsAssignableFrom(propertyInfo.PropertyType))
{
// Get the path of the property widget relative to the current widget
var widgetPath = GetWidgetPathFromWidget(widget, propertyInfo.GetValue(widget) as Widget, true);
widgetNode.SetAttribute(attribute.Name, widgetPath);
}
else widgetNode.SetAttribute(attribute.Name, widgetValue.ToString());
}
// Prefab parameters exporting
if (widget.EditorIsPrefabRoot())
{
foreach (var parameterKeyValuePair in widget.EditorGetParameterValues())
{
// Key is parameter name, Value is the parameter value
var attribute = document.CreateAttribute("Parameter." + parameterKeyValuePair.Key);
widgetNode.Attributes.Append(attribute);
widgetNode.SetAttribute(attribute.Name, parameterKeyValuePair.Value.ToString());
}
}
// Nested properties are currently unsupported, so list panels and grids get special export rules
if (widget is ListPanel listPanel)
{
var attribute = document.CreateAttribute("StackLayout.LayoutMethod");
widgetNode.Attributes.Append(attribute);
widgetNode.SetAttribute(attribute.Name, listPanel.StackLayout.LayoutMethod.ToString());
}
else if (widget is GridWidget grid)
{
var directionAttribute = document.CreateAttribute("GridLayout.Direction");
widgetNode.Attributes.Append(directionAttribute);
widgetNode.SetAttribute(directionAttribute.Name, grid.GridLayout.Direction.ToString());
var horzLayoutAttribute = document.CreateAttribute("GridLayout.HorizontalLayoutMethod");
widgetNode.Attributes.Append(horzLayoutAttribute);
widgetNode.SetAttribute(horzLayoutAttribute.Name, grid.GridLayout.HorizontalLayoutMethod.ToString());
var vertLayoutAttribute = document.CreateAttribute("GridLayout.VerticalLayoutMethod");
widgetNode.Attributes.Append(vertLayoutAttribute);
widgetNode.SetAttribute(vertLayoutAttribute.Name, grid.GridLayout.VerticalLayoutMethod.ToString());
}
var childrenNode = document.CreateElement("Children");
foreach (var child in widget.Children)
{
// Only export children that are shown in the hierarchy. i.e. extrinsic children of prefabs and not the intrinsic ones
if (!child.EditorIsShownInHierarchy()) continue;
AppendXMLNodeFromWidget(child, uiContext, childrenNode, document);
}
// When using logical children location there is a discrepency between actual parent widget in-game, and the parent widget
// in the xml file. If a logical children location is found for this widget, its children are exported under this widget
// rather than the logical children location widget itself.
var logicalChildrenLocation = widget.EditorGetLogicalChildrenLocation();
if (logicalChildrenLocation != null && logicalChildrenLocation != widget)
{
foreach (var child in logicalChildrenLocation.Children)
{
if (!child.EditorIsShownInHierarchy()) continue;
AppendXMLNodeFromWidget(child, uiContext, childrenNode, document);
}
}
if (childrenNode.ChildNodes.Count > 0) widgetNode.AppendChild(childrenNode);
parentNode.AppendChild(widgetNode);
}
public Widget AddWidget(Widget parent, string typeName)
{
if (_widgetFactory.IsBuiltinType(typeName))
{
var type = _widgetFactory.GetBuiltinType(typeName);
if (Game.Current == null && IsTableauWidgetType(type))
{
InformationManager.DisplayMessage(new InformationMessage("Could not add TableauWidget. Try starting the editor within a campaign or custom battle screen",
Color.FromVector3(new Vec3(1f, 0.1f, 0.1f))));
return null;
}
var widget = (Widget)type.GetConstructor(new Type[] { typeof(UIContext) }).Invoke(new object[] { _context });
if (parent == null) _previewRootWidget.AddChild(widget);
else parent.AddChild(widget);
InitializeWidgetProperties(widget);
UpdateWidgetHierarchy();
UpdateWidgetProperties(widget);
AddUndoOp(new AddWidgetOperation(widget));
return widget;
}
else if (_widgetFactory.IsCustomType(typeName))
{
if (parent == null) parent = _previewRootWidget;
var prefab = _widgetFactory.GetCustomType(typeName);
var createData = new WidgetCreationData(_context, _widgetFactory, parent);
createData.AddExtensionData(_movie);
var widget = prefab.Instantiate(createData).Widget;
widget.EditorSetPrefabName(typeName);
widget.EditorSetShownInHierarchy(true);
widget.EditorSetLocked(false);
AddItemTemplateWidgets(widget, 0);
UpdateWidgetHierarchy();
UpdateWidgetProperties(widget);
AddUndoOp(new AddWidgetOperation(widget));
return widget;
}
return null;
}
/// <summary>
/// Adds a prefab as a regular widget and allows its intrinsic children to be edited
/// </summary>
/// <param name="prefabName"></param>
public void ImportPrefab(string prefabName)
{
var widget = AddWidget(_previewRootWidget, prefabName);
PrefabUnlockChildrenRecursive(widget, widget);
widget.GetComponent<WidgetEditorData>().IsPrefabRoot = false;
widget.EditorGetProperties().Clear();
UpdateWidgetProperties(widget);
UpdateWidgetHierarchy();
}
private void AddItemTemplateWidgets(Widget widget, int numberOfAddedTemplates)
{
PrefabWidgetExtensions.IsAddingItemTemplate = true;
var view = widget.GetComponent<GauntletView>();
var createData = new WidgetCreationData(_context, _widgetFactory, widget);
createData.AddExtensionData(_movie);
// Some prefabs refer to themselves as item templates, numberOfAddedTemplates makes sure we don't enter a infinite loop
// A side effect is that any item template after a 'depth' of 20 will not be added, but I think actual prefabs will rarely
// reach that many item templates.
if (view != null && view.ItemTemplateUsageWithData != null && numberOfAddedTemplates <= 20)
{
view.ItemTemplateUsageWithData.DefaultItemTemplate.Instantiate(createData, view.ItemTemplateUsageWithData.GivenParameters);
numberOfAddedTemplates++;
}
for (int i = 0; i < widget.ChildCount; i++)
{
AddItemTemplateWidgets(widget.GetChild(i), numberOfAddedTemplates);
}
PrefabWidgetExtensions.IsAddingItemTemplate = false;
}
private void PrefabUnlockChildrenRecursive(Widget parent, Widget root)
{
for (int i = 0; i < parent.ChildCount; i++)
{
var widget = parent.GetChild(i);
if (widget.EditorIntrinsicChildOf() == root)
{
widget.EditorSetShownInHierarchy(true);
widget.EditorSetLocked(false);
UpdateWidgetProperties(widget);
}
PrefabUnlockChildrenRecursive(widget, root);
}
}
public Widget DuplicateWidget(Widget source)
{
var typeName = source.GetType().Name;
var type = _widgetFactory.GetBuiltinType(typeName);
if (Game.Current == null && IsTableauWidgetType(type))
{
InformationManager.DisplayMessage(new InformationMessage("Could not add TableauWidget. Try starting the editor within a campaign or custom battle screen",
Color.FromVector3(new Vec3(1f, 0.1f, 0.1f))));
return null;
}
var widget = (Widget)type.GetConstructor(new Type[] { typeof(UIContext) }).Invoke(new object[] { _context });
source.ParentWidget.AddChild(widget);
var equivalentWidgets = new Dictionary<Widget, Widget>();
equivalentWidgets.Add(source, widget);
foreach (var child in source.Children)
{
DuplicateWidgetRecursive(child, widget, equivalentWidgets);
}
foreach (var sourceChild in source.GetAllChildrenAndThisRecursive())
{
CopyWidgetProperties(equivalentWidgets[sourceChild], sourceChild, equivalentWidgets);
}
UpdateWidgetHierarchy();
UpdateWidgetProperties(widget);
AddUndoOp(new AddWidgetOperation(widget));
return widget;
}
private Widget DuplicateWidgetRecursive(Widget source, Widget parent, Dictionary<Widget, Widget> equivalentWidgets)
{
var typeName = source.GetType().Name;
var type = _widgetFactory.GetBuiltinType(typeName);
if (Game.Current == null && IsTableauWidgetType(type))
{
InformationManager.DisplayMessage(new InformationMessage("Could not add TableauWidget. Try starting the editor within a campaign or custom battle screen",
Color.FromVector3(new Vec3(1f, 0.1f, 0.1f))));
return null;
}
var widget = (Widget)type.GetConstructor(new Type[] { typeof(UIContext) }).Invoke(new object[] { _context });
parent.AddChild(widget);
equivalentWidgets.Add(source, widget);
foreach (var child in source.Children)
{
DuplicateWidgetRecursive(child, widget, equivalentWidgets);
}
UpdateWidgetProperties(widget);
return widget;
}
/// <summary>
/// Sets a place-holder value for some common properties, and adds the GauntletView, and WidgetEditorData to the widget
/// </summary>
/// <param name="widget"></param>
private void InitializeWidgetProperties(Widget widget)
{
widget.VerticalAlignment = VerticalAlignment.Center;
widget.HorizontalAlignment = HorizontalAlignment.Center;
widget.SuggestedHeight = 200;
widget.SuggestedWidth = 200;
var parentGauntletView = widget.ParentWidget.GetComponent<GauntletView>();
var gauntletViewConstructor = AccessTools.Constructor(typeof(GauntletView), new Type[] { typeof(GauntletMovie), typeof(GauntletView), typeof(Widget), typeof(int) });
var gauntletView = (GauntletView)gauntletViewConstructor.Invoke(new Object[] { _movie, parentGauntletView, widget, 64 });
widget.AddComponent(gauntletView);
widget.AddComponent(new WidgetEditorData(widget));
gauntletView.RefreshBindingWithChildren();
switch (widget)
{
case TextWidget text:
text.Text = "Text";
break;
case RichTextWidget richText:
richText.Text = "Text";
break;
case FillBar fillBar:
fillBar.Brush = UIResourceManager.BrushFactory.GetBrush("FillBarBrush");
break;
case GraphWidget graph:
graph.LineBrush = UIResourceManager.BrushFactory.GetBrush("Encyclopedia.CharacterTree.Line");
graph.HorizontalValueLabelsBrush = UIResourceManager.BrushFactory.GetBrush("DefaultBrush");
graph.VerticalValueLabelsBrush = UIResourceManager.BrushFactory.GetBrush("DefaultBrush");
break;
case CharacterTableauWidget charTableau:
charTableau.BodyProperties = "<BodyProperties version=\"4\" age=\"21.66\" weight=\"0.4938\" build=\"0.307\" key=\"001BE40D8000261283CACD43ADCD7C3AB6495819F4BB5ADA30C177898038A892038000350863C503000000000000000000000000000000000000000073182046\" />";
charTableau.IsFemale = false;
charTableau.EquipmentCode = "+0-broad_ild_sword_t3-@null+1-@null-@null+2-@null-@null+3-@null-@null+4-@null-@null+5-@null-@null+6-khuzait_civil_coat-@null+7-leather_shoes-@null+8-@null-@null+9-@null-@null+10-@null-@null+11-@null-@null";
charTableau.CharStringId = "Character";
charTableau.StanceIndex = 0;
charTableau.MountCreationKey = MountCreationKey.GetRandomMountKeyString(null, 0);
charTableau.ArmorColor1 = 4282552449;
charTableau.ArmorColor2 = 4293904784;
charTableau.Race = 0;
break;
case ItemTableauWidget itemTableau:
itemTableau.StringId = "cotton";
itemTableau.ItemModifierId = "";
itemTableau.BannerCode = "";
break;
case BannerTableauWidget bannerTableau:
bannerTableau.BannerCodeText = "34.25.10.1536.1536.764.764.1.0.0.314.22.35.444.444.764.764.0.0.270";
break;
}
// Create place-holder widgets of the appropriate types to prevent any properties from being null.
// This prevents crashes in widgets that are dependent on other widgets.
foreach (var propertyInfo in widget.GetType().GetProperties())
{
if (propertyInfo.Name == "DragWidget" || propertyInfo.Name == "ParentWidget") continue;
if (typeof(Widget).IsAssignableFrom(propertyInfo.PropertyType) && propertyInfo.SetMethod != null)
{
var widgetProperty = AddWidget(widget, propertyInfo.PropertyType.Name);
// Place-holder ID for the new widget to be obvious in the editor hierarchy
widgetProperty.Id = propertyInfo.Name;
propertyInfo.SetValue(widget, widgetProperty);
// Stores this property as a dependent property in the new widget. If the new widget is removed it will set this
// property to null.
widgetProperty.EditorAddDependentProperty(widget, propertyInfo);
}
}
}
private bool IsTableauWidgetType(Type type)
{
return typeof(BannerTableauWidget).IsAssignableFrom(type) || typeof(CharacterTableauWidget).IsAssignableFrom(type) || typeof(ItemTableauWidget).IsAssignableFrom(type);
}
public void CopyWidgetProperties(Widget widget, Widget source, Dictionary<Widget, Widget> equivalentWidgets)
{
// Make sure the source and target are the same type to avoid having different properties
if (widget.GetType() != source.GetType()) return;
var parentGauntletView = widget.ParentWidget?.GetComponent<GauntletView>();
var gauntletViewConstructor = AccessTools.Constructor(typeof(GauntletView), new Type[] { typeof(GauntletMovie), typeof(GauntletView), typeof(Widget), typeof(int) });
var gauntletView = (GauntletView)gauntletViewConstructor.Invoke(new Object[] { _movie, parentGauntletView, widget, 64 });
widget.AddComponent(gauntletView);
var widgetEditorData = source.GetComponent<WidgetEditorData>().CreateCopy(widget, equivalentWidgets);
widget.AddComponent(widgetEditorData);
gauntletView.RefreshBindingWithChildren();
foreach (var propertyInfo in widget.GetType().GetProperties())
{
if (propertyInfo.SetMethod == null || propertyInfo.SetMethod.IsPrivate || propertyInfo.GetMethod == null || _excludedWidgetProperties.Contains(propertyInfo.Name)) continue;
if (propertyInfo.PropertyType == typeof(Brush))
{
var brush = propertyInfo.GetValue(source) as Brush;
propertyInfo.SetValue(widget, brush);
var newBrush = propertyInfo.GetValue(widget) as Brush;
if (newBrush != null && brush != null) newBrush.Name = brush.Name;
}
else if (typeof(Widget).IsAssignableFrom(propertyInfo.PropertyType))
{
var propertyWidget = propertyInfo.GetValue(source) as Widget;
if (propertyWidget != null)
{
if (equivalentWidgets.TryGetValue(propertyWidget, out var equivalentWidget));
else equivalentWidget = propertyWidget;
propertyInfo.SetValue(widget, equivalentWidget);
}
}
else propertyInfo.SetValue(widget, propertyInfo.GetValue(source));
}
if (widget is ListPanel listPanel)
{
listPanel.StackLayout.LayoutMethod = (source as ListPanel).StackLayout.LayoutMethod;
}
else if (widget is GridWidget grid)
{
grid.GridLayout.Direction = (source as GridWidget).GridLayout.Direction;
grid.GridLayout.HorizontalLayoutMethod = (source as GridWidget).GridLayout.HorizontalLayoutMethod;
grid.GridLayout.VerticalLayoutMethod = (source as GridWidget).GridLayout.VerticalLayoutMethod;
}
else if (widget is TextWidget text)
{
text.Text = (source as TextWidget).Text;
}
}
/// <summary>
/// Removes the widget temporarily without clearing its editor data properties or its clearing its events
/// </summary>
/// <param name="widget"></param>
/// <param name="addUndoOp"></param>
public void RemoveWidget(Widget widget, bool addUndoOp)
{
if (addUndoOp) AddUndoOp(new RemoveWidgetOperation(widget, widget.ParentWidget));
widget.ParentWidget = null;
foreach (var child in widget.GetAllChildrenAndThisRecursive())
{
child.EditorRemoveAllDependencies();
}
SelectWidget(null);
UpdateWidgetHierarchy();
}
/// <summary>
/// Removes the widget permanently and clears its editor data properties and events
/// </summary>
/// <param name="widget"></param>
/// <param name="addUndoOp"></param>
public void RemoveWidgetPerma(Widget widget)
{
widget.ParentWidget = null;
var ClearEventHandlersWithChildren = AccessTools.Method(typeof(GauntletView), "ClearEventHandlersWithChildren");
var view = widget.GetComponent<GauntletView>();
if (view != null) ClearEventHandlersWithChildren.Invoke(view, new object[] { });
foreach (var child in widget.GetAllChildrenAndThisRecursive())
{
child.EditorGetProperties()?.Clear();
child.EditorRemoveAllDependencies();
}
}
public void RemoveSelectedWidget()
{
if (_selectedWidget == null) return;
RemoveWidget(_selectedWidget, true);
}
public void MoveSelectedWidgetUpChain()
{
if (_selectedWidget == null) return;
var myIndex = _selectedWidget.GetSiblingIndex();
if (myIndex > 0) _selectedWidget.SetSiblingIndex(myIndex - 1);
UpdateWidgetHierarchy();
}
public void MoveSelectedWidgetDownChain()
{
if (_selectedWidget == null) return;
var myIndex = _selectedWidget.GetSiblingIndex();
if (myIndex < _selectedWidget.ParentWidget.ChildCount - 1) _selectedWidget.SetSiblingIndex(myIndex + 1);
UpdateWidgetHierarchy();
}
public void ParentSelectedWidget()
{
if (_selectedWidget == null) return;
var myIndex = _selectedWidget.GetSiblingIndex();
var nextSibling = _selectedWidget.ParentWidget.GetChild(myIndex + 1);
if (nextSibling == null) return;
DontDisconnectScopeFromRoot = true;
var newParent = nextSibling.EditorGetLogicalChildrenLocation();
var newOffset = newParent.GetLocalPoint(_selectedWidget.GlobalPosition);
_selectedWidget.ParentWidget = newParent;
//_selectedWidget.PosOffset = newOffset;
UpdateWidgetHierarchy();
DontDisconnectScopeFromRoot = false;
}
public void UnparentSelectedWidget()
{
if (_selectedWidget == null) return;
if (_selectedWidget.ParentWidget == _previewRootWidget) return;
DontDisconnectScopeFromRoot = true;
var logicalParent = _selectedWidget.ParentWidget.EditorGetIAmLogicalChildLocationFor();
var grandParent = logicalParent == null ? _selectedWidget.ParentWidget.ParentWidget : logicalParent.ParentWidget;
var oldParentOffset = _selectedWidget.ParentWidget.PosOffset;
_selectedWidget.ParentWidget = grandParent;
//_selectedWidget.PosOffset += oldParentOffset;
UpdateWidgetHierarchy();
DontDisconnectScopeFromRoot = false;
}
public void DuplicateSelectedWidget()
{
if (_selectedWidget == null) return;
SelectWidget(DuplicateWidget(_selectedWidget));
}
public void SelectWidget(Widget widget)
{
if (_widgetPickerMode)
{
OnWidgetPicked(widget);
return;
}
if (_selectedWidget == widget) return;
if (_selectedWidget != null) _selectedWidget.EditorSetSelected(false);
_selectedWidget = widget;
_selectedWidgetScaler.SelectedWidget = widget;
if (widget == null)
{
SelectedWidgetProperties = _emptyWidgetProperties;
_selectedWidgetScaler.IsDisabled = true;
_selectedWidgetScaler.IsVisible = false;
return;
}
_selectedWidget.EditorSetSelected(true);
// Refresh the properties of the selected widget to reflect any changes
UpdateWidgetProperties(_selectedWidget);
FilterPropertiesList();
//SelectedWidgetProperties = _selectedWidget.EditorGetProperties();
_selectedWidgetScaler.IsEnabled = true;
_selectedWidgetScaler.IsVisible = true;
UpdateSelectedWidgetScaler();
}
private void UpdateSelectedWidgetScaler()
{
// Updates the position and scale of the box that marks the selected widget
var newX = _selectedWidget.GlobalPosition.X * _context.InverseScale;
var newY = _selectedWidget.GlobalPosition.Y * _context.InverseScale;
_selectedWidgetScaler.PositionXOffset = newX;
_selectedWidgetScaler.PositionYOffset = newY;
_selectedWidgetScaler.SuggestedWidth = _selectedWidget.Size.X * _context.InverseScale;
_selectedWidgetScaler.SuggestedHeight = _selectedWidget.Size.Y * _context.InverseScale;
}
private void UpdateWidgetProperties(Widget widget)
{
if (widget == null) return;
var widgetPropertiesVM = widget.EditorGetProperties();
// If property view models have been already added, only update their values
if (widgetPropertiesVM.Count > 0)
{
foreach (var property in widgetPropertiesVM)
{
property.UpdateEditorValueFromObjectProperty();
}
return;
}
var propList = new MBBindingList<WidgetPropertyVM>();
if (widget.EditorIsPrefabRoot())
{
var values = widget.EditorGetParameterValues();
for (int i = values.Keys.Count - 1; i >= 0; i--)
{
var param = values.Keys.ElementAt(i);
if (!widget.EditorGetParameterBindingData().TryGetValue(param, out var paramBindingData)) continue;
propList.Add(new WidgetPropertyVM(prefabWidget: widget, param, paramBindingData));
}
}
else if (widget is ListPanel listPanel)
{
propList.Add(new WidgetPropertyVM(widget, AccessTools.Property(typeof(StackLayout), nameof(StackLayout.LayoutMethod)), listPanel.StackLayout));
}
else if (widget is GridWidget grid)
{
propList.Add(new WidgetPropertyVM(widget, AccessTools.Property(typeof(GridLayout), nameof(GridLayout.Direction)), grid.GridLayout));
propList.Add(new WidgetPropertyVM(widget, AccessTools.Property(typeof(GridLayout), nameof(GridLayout.VerticalLayoutMethod)), grid.GridLayout));
propList.Add(new WidgetPropertyVM(widget, AccessTools.Property(typeof(GridLayout), nameof(GridLayout.HorizontalLayoutMethod)), grid.GridLayout));
}
var widgetTypeProperties = widget.GetType().GetProperties();
foreach (var propertyInfo in widgetTypeProperties)
{
if (_excludedWidgetProperties.Contains(propertyInfo.Name) || propertyInfo.SetMethod == null || !propertyInfo.SetMethod.IsPublic) continue;
propList.Add(new WidgetPropertyVM(widget, propertyInfo));
if (typeof(Brush).IsAssignableFrom(propertyInfo.PropertyType))
{
foreach (var brushPropertyInfo in typeof(Brush).GetProperties())
{
if (_excludedBrushProperties.Contains(brushPropertyInfo.Name) || brushPropertyInfo.SetMethod == null || !brushPropertyInfo.SetMethod.IsPublic) continue;
propList.Add(new WidgetPropertyVM(widget, propertyInfo, brushPropertyInfo));
}
}
}
widget.EditorSetProperties(propList);
}
public void SelectWidgetResource(string widgetTypeName)
{
if (_selectedWidget == null) SelectWidget(AddWidget(_previewRootWidget, widgetTypeName));
else
{
SelectWidget(AddWidget(_selectedWidget.EditorGetLogicalChildrenLocation(), widgetTypeName));
}
}
public int GetChildLevel(Widget widget, ref int level)
{
if (widget.ParentWidget == _previewRootWidget || widget.ParentWidget == null) return level;
else
{
if (widget.EditorIsShownInHierarchy()) level++;
return GetChildLevel(widget.ParentWidget, ref level);
}
}
public void UpdateWidgetHierarchy()
{
WidgetHierarchy.Clear();
foreach (var child in _previewRootWidget.GetAllChildrenRecursive())
{
if (!child.EditorIsShownInHierarchy()) continue;
var wasCollapsed = (child.EditorGetWidgetHierarchyVM() == null) ? false : child.EditorGetWidgetHierarchyVM().IsCollapsed;
var vm = new WidgetHierarchyVM(child, this);
WidgetHierarchy.Add(vm);
vm.IsCollapsed = wasCollapsed;
child.EditorSetWidgetHierarchyVM(vm);
}
}
public void Tick(float dt)
{
if (_selectedWidget == null) return;
var mousePos = _context.EventManager.MousePosition;
if (_mouseDown)
{
if (_isScaling) HandleScaleSelectedWidget(mousePos);
else if (Vector2.DistanceSquared(mousePos, _lastClickPosition) > 100)
{
_isDragging = true;
}
}
if (_isDragging)
{
HandleDragSelectedWidget(mousePos);
}
UpdateSelectedWidgetScaler();
}
private void HandleDragSelectedWidget(Vector2 mousePos)
{
if (Input.IsKeyDown(InputKey.LeftShift))
{
var vecToMouse = mousePos - _lastClickPosition;
vecToMouse = Vector2.Normalize(vecToMouse);
if (MathF.Abs(Vector2.Dot(Vector2.UnitX, vecToMouse)) < 0.7f)
{
_selectedWidget.PositionYOffset = _draggedWidgetInitOffset.Y + (mousePos.Y - _lastClickPosition.Y) * _context.InverseScale;
_selectedWidget.PositionXOffset = _draggedWidgetInitOffset.X;
}
else
{
_selectedWidget.PositionXOffset = _draggedWidgetInitOffset.X + (mousePos.X - _lastClickPosition.X) * _context.InverseScale;
_selectedWidget.PositionYOffset = _draggedWidgetInitOffset.Y;
}
}
else _selectedWidget.PosOffset = _draggedWidgetInitOffset + (mousePos - _lastClickPosition) * _context.InverseScale;
}
private void HandleScaleSelectedWidget(Vector2 mousePos)
{
var deltaMouseX = (mousePos.X - _lastClickPosition.X) * _context.InverseScale;
var deltaMouseY = (mousePos.Y - _lastClickPosition.Y) * _context.InverseScale;
if (Input.IsKeyDown(InputKey.LeftShift))
{
if (_scalingRight || _scalingDown) _scalingRight = _scalingDown = true;
else if (_scalingLeft || _scalingUp) _scalingLeft = _scalingUp = true;
var aspectRatio = _scaledWidgetInitSize.X / _scaledWidgetInitSize.Y;
deltaMouseY = deltaMouseX / aspectRatio;
}
if (_scalingRight)
{
var newScale = _scaledWidgetInitSize.X * _context.InverseScale + deltaMouseX;
_selectedWidget.SuggestedWidth = MathF.Abs(newScale);
switch (_selectedWidget.HorizontalAlignment)
{
case HorizontalAlignment.Center:
_selectedWidget.PositionXOffset = _draggedWidgetInitOffset.X + deltaMouseX / 2f;
break;
case HorizontalAlignment.Right:
_selectedWidget.PositionXOffset = _draggedWidgetInitOffset.X + deltaMouseX;
break;
}
}
else if (_scalingLeft)
{
var newScale = _scaledWidgetInitSize.X * _context.InverseScale - deltaMouseX;
_selectedWidget.SuggestedWidth = MathF.Abs(newScale);
switch (_selectedWidget.HorizontalAlignment)
{
case HorizontalAlignment.Center:
_selectedWidget.PositionXOffset = _draggedWidgetInitOffset.X + deltaMouseX / 2f;
break;
case HorizontalAlignment.Left:
_selectedWidget.PositionXOffset = _draggedWidgetInitOffset.X + deltaMouseX;
break;
}
}
if (_scalingDown)
{
var newScale = _scaledWidgetInitSize.Y * _context.InverseScale + deltaMouseY;
_selectedWidget.SuggestedHeight = MathF.Abs(newScale);
switch (_selectedWidget.VerticalAlignment)
{
case VerticalAlignment.Center:
_selectedWidget.PositionYOffset = _draggedWidgetInitOffset.Y + deltaMouseY / 2f;
break;
case VerticalAlignment.Bottom:
_selectedWidget.PositionYOffset = _draggedWidgetInitOffset.Y + deltaMouseY;
break;
}
}
else if (_scalingUp)
{
var newScale = _scaledWidgetInitSize.Y * _context.InverseScale - deltaMouseY;
_selectedWidget.SuggestedHeight = MathF.Abs(newScale);
switch (_selectedWidget.VerticalAlignment)
{
case VerticalAlignment.Center:
_selectedWidget.PositionYOffset = _draggedWidgetInitOffset.Y + deltaMouseY / 2f;
break;
case VerticalAlignment.Top:
_selectedWidget.PositionYOffset = _draggedWidgetInitOffset.Y + deltaMouseY;
break;
}
}
}
public void OnMousePressed()
{
var mousePos = _context.EventManager.MousePosition;
if (!_previewRootWidget.IsPointInsideMeasuredArea(mousePos)) return;
_mouseDown = true;
Widget clickedWidget = null;
foreach (var editWidget in _previewRootWidget.GetAllChildrenRecursive())
{
if (editWidget.EditorIsLocked()) continue;
if (editWidget.IsVisible && editWidget.IsPointInsideMeasuredArea(mousePos))
{
clickedWidget = editWidget;
}
}
if (clickedWidget != null)
{
_draggedWidgetInitOffset = clickedWidget.PosOffset;
_scaledWidgetInitSize = clickedWidget.Size;
var localMousePos = clickedWidget.GetLocalPoint(mousePos);
if (clickedWidget.WidthSizePolicy == SizePolicy.Fixed)