ActionEditors.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using InABox.Core;
  2. using InABox.DynamicGrid;
  3. using InABox.WPF;
  4. using Microsoft.CodeAnalysis.VisualBasic.Syntax;
  5. using PRS.Shared.Events;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.ComponentModel;
  9. using System.Linq;
  10. using System.Runtime.CompilerServices;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. using System.Windows;
  14. using System.Windows.Controls;
  15. using System.Windows.Media;
  16. namespace PRS.Shared.Grids.EventEditor;
  17. public interface IEventActionEditor
  18. {
  19. bool Edit(IEventAction trigger, IEventDataModelDefinition dataModelDefinition);
  20. }
  21. public interface IEventActionEditor<TAction> : IEventActionEditor
  22. where TAction : IEventAction
  23. {
  24. bool Edit(TAction trigger, IEventDataModelDefinition dataModelDefinition);
  25. bool IEventActionEditor.Edit(IEventAction trigger, IEventDataModelDefinition dataModelDefinition) => Edit((TAction)trigger, dataModelDefinition);
  26. }
  27. public static class EventActionEditors
  28. {
  29. private static Dictionary<Type, Type>? _actionEditors;
  30. private static Dictionary<Type, Type> GetActionEditors()
  31. {
  32. if(_actionEditors is null)
  33. {
  34. _actionEditors = new Dictionary<Type, Type>();
  35. foreach(var type in CoreUtils.TypeList(x => true))
  36. {
  37. if (type.GetInterfaceDefinition(typeof(IEventActionEditor<>)) is Type editorInterface)
  38. {
  39. var actionType = editorInterface.GenericTypeArguments[0];
  40. actionType = actionType.IsGenericType ? actionType.GetGenericTypeDefinition() : actionType;
  41. _actionEditors[actionType] = type;
  42. }
  43. }
  44. }
  45. return _actionEditors;
  46. }
  47. public static Type? GetActionEditorType(Type actionType)
  48. {
  49. var genericActionType = actionType.IsGenericType ? actionType.GetGenericTypeDefinition() : actionType;
  50. if(GetActionEditors().GetValueOrDefault(genericActionType) is Type editorType)
  51. {
  52. return editorType.IsGenericType ? editorType.MakeGenericType(actionType.GenericTypeArguments) : editorType;
  53. }
  54. else
  55. {
  56. return null;
  57. }
  58. }
  59. public static bool EditAction<TEvent, TDataModel>(IEventAction<TEvent> action, IEventDataModelDefinition dataModelDefinition)
  60. where TEvent : IEvent<TDataModel>
  61. where TDataModel : IEventDataModel
  62. {
  63. var editorType = GetActionEditorType(action.GetType());
  64. if (editorType is null) return true;
  65. var editor = (Activator.CreateInstance(editorType) as IEventActionEditor)!;
  66. return editor.Edit(action, dataModelDefinition);
  67. }
  68. }