No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UnitPortCollection.cs 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using System;
  2. using System.Collections.ObjectModel;
  3. namespace Unity.VisualScripting
  4. {
  5. public sealed class UnitPortCollection<TPort> : KeyedCollection<string, TPort>, IUnitPortCollection<TPort>
  6. where TPort : IUnitPort
  7. {
  8. public IUnit unit { get; }
  9. public UnitPortCollection(IUnit unit)
  10. {
  11. this.unit = unit;
  12. }
  13. private void BeforeAdd(TPort port)
  14. {
  15. if (port.unit != null)
  16. {
  17. if (port.unit == unit)
  18. {
  19. throw new InvalidOperationException("Node ports cannot be added multiple time to the same unit.");
  20. }
  21. else
  22. {
  23. throw new InvalidOperationException("Node ports cannot be shared across nodes.");
  24. }
  25. }
  26. port.unit = unit;
  27. }
  28. private void AfterAdd(TPort port)
  29. {
  30. unit.PortsChanged();
  31. }
  32. private void BeforeRemove(TPort port)
  33. {
  34. }
  35. private void AfterRemove(TPort port)
  36. {
  37. port.unit = null;
  38. unit.PortsChanged();
  39. }
  40. public TPort Single()
  41. {
  42. if (Count != 0)
  43. {
  44. throw new InvalidOperationException("Port collection does not have a single port.");
  45. }
  46. return this[0];
  47. }
  48. protected override string GetKeyForItem(TPort item)
  49. {
  50. return item.key;
  51. }
  52. public new bool TryGetValue(string key, out TPort value)
  53. {
  54. if (Dictionary == null)
  55. {
  56. value = default(TPort);
  57. return false;
  58. }
  59. return Dictionary.TryGetValue(key, out value);
  60. }
  61. protected override void InsertItem(int index, TPort item)
  62. {
  63. BeforeAdd(item);
  64. base.InsertItem(index, item);
  65. AfterAdd(item);
  66. }
  67. protected override void RemoveItem(int index)
  68. {
  69. var item = this[index];
  70. BeforeRemove(item);
  71. base.RemoveItem(index);
  72. AfterRemove(item);
  73. }
  74. protected override void SetItem(int index, TPort item)
  75. {
  76. throw new NotSupportedException();
  77. }
  78. protected override void ClearItems()
  79. {
  80. while (Count > 0)
  81. {
  82. RemoveItem(0);
  83. }
  84. }
  85. }
  86. }