DynamicEditorControlFactory.cs 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.Linq;
  5. using InABox.Core;
  6. using Syncfusion.Windows.Shared;
  7. namespace InABox.DynamicGrid
  8. {
  9. public static class DynamicEditorControlFactory
  10. {
  11. private static Dictionary<Type, List<(Type valueType, Type editor)>>? _editors;
  12. private static Dictionary<Type, List<(Type valueType, Type editor)>> GetEditors()
  13. {
  14. if(_editors is null)
  15. {
  16. _editors = [];
  17. foreach(var type in CoreUtils.TypeList(AppDomain.CurrentDomain.GetAssemblies(),
  18. x => x.IsClass
  19. && !x.IsAbstract
  20. && !x.IsGenericType
  21. && x.IsSubclassOfRawGeneric(typeof(DynamicEditorControl<,>))))
  22. {
  23. var editorClass = type.GetSuperclassDefinition(typeof(DynamicEditorControl<,>))!;
  24. var valueType = editorClass.GenericTypeArguments[0];
  25. var editor = editorClass.GenericTypeArguments[1];
  26. if (editor == typeof(IBaseEditor) || editor.HasInterface<IBaseEditor>())
  27. {
  28. _editors.GetValueOrAdd(editor).Add((valueType, type));
  29. }
  30. }
  31. }
  32. return _editors;
  33. }
  34. private static bool GetControlType(Type editorType, Type valueType, [NotNullWhen(true)] out Type? TControl)
  35. {
  36. var controls = GetEditors().Where(x => editorType == x.Key || editorType.IsAssignableTo(x.Key));
  37. Type? editType = null;
  38. List<(Type valueType, Type editor)>? tControls = null;
  39. TControl = null;
  40. foreach(var control in controls)
  41. {
  42. if(control.Key == editorType)
  43. {
  44. tControls = control.Value;
  45. break;
  46. }
  47. if(TControl is null || editType!.IsAssignableTo(control.Key))
  48. {
  49. (editType, tControls) = control;
  50. }
  51. }
  52. if (tControls is null) return false;
  53. Type? _valueType = null;
  54. foreach(var control in tControls)
  55. {
  56. if(control.valueType == valueType)
  57. {
  58. TControl = control.editor;
  59. return true;
  60. }
  61. if(valueType.IsAssignableTo(control.valueType)
  62. && (_valueType is null || _valueType.IsAssignableTo(control.valueType)))
  63. {
  64. (_valueType, TControl) = control;
  65. }
  66. }
  67. return TControl is not null;
  68. }
  69. public static BaseDynamicEditorControl? CreateControl(BaseEditor editor, Type valueType, IDynamicEditorHost host)
  70. {
  71. if (GetControlType(editor.GetType(), valueType, out var TControl))
  72. {
  73. var result = Activator.CreateInstance(TControl) as BaseDynamicEditorControl;
  74. if (result != null)
  75. {
  76. result.ValueType = valueType;
  77. result.Host = host;
  78. result.EditorDefinition = editor;
  79. }
  80. return result;
  81. }
  82. return null;
  83. }
  84. }
  85. }