DynamicEditorControlFactory.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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, Type>? _editors;
  12. private static Dictionary<Type, Type> 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(BaseDynamicEditorControl<>))))
  22. {
  23. var baseClass = type.GetSuperclassDefinition(typeof(BaseDynamicEditorControl<>))!;
  24. var editor = baseClass.GenericTypeArguments[0];
  25. if (editor == typeof(IBaseEditor) || editor.HasInterface<IBaseEditor>())
  26. {
  27. _editors[editor] = type;
  28. }
  29. }
  30. }
  31. return _editors;
  32. }
  33. private static bool GetControlType(Type editorType, [NotNullWhen(true)] out Type? TControl)
  34. {
  35. var controls = GetEditors().Where(x => editorType == x.Key || editorType.IsAssignableTo(x.Key));
  36. Type? editType = null;
  37. TControl = null;
  38. foreach(var control in controls)
  39. {
  40. if(control.Key == editorType)
  41. {
  42. TControl = control.Value;
  43. return true;
  44. }
  45. if(TControl is null || editType!.IsAssignableTo(control.Key))
  46. {
  47. (editType, TControl) = control;
  48. }
  49. }
  50. return TControl is not null;
  51. }
  52. public static BaseDynamicEditorControl? CreateControl(BaseEditor editor, IDynamicEditorHost host)
  53. {
  54. if (GetControlType(editor.GetType(), out var TControl))
  55. {
  56. var result = Activator.CreateInstance(TControl) as BaseDynamicEditorControl;
  57. if (result != null)
  58. {
  59. result.Host = host;
  60. result.EditorDefinition = editor;
  61. }
  62. return result;
  63. }
  64. return null;
  65. }
  66. }
  67. }