File size: 2,488 Bytes
18a519f | 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 | using System;
using System.Collections.ObjectModel;
namespace Unity.VisualScripting
{
public sealed class UnitPortCollection<TPort> : KeyedCollection<string, TPort>, IUnitPortCollection<TPort>
where TPort : IUnitPort
{
public IUnit unit { get; }
public UnitPortCollection(IUnit unit)
{
this.unit = unit;
}
private void BeforeAdd(TPort port)
{
if (port.unit != null)
{
if (port.unit == unit)
{
throw new InvalidOperationException("Node ports cannot be added multiple time to the same unit.");
}
else
{
throw new InvalidOperationException("Node ports cannot be shared across nodes.");
}
}
port.unit = unit;
}
private void AfterAdd(TPort port)
{
unit.PortsChanged();
}
private void BeforeRemove(TPort port)
{
}
private void AfterRemove(TPort port)
{
port.unit = null;
unit.PortsChanged();
}
public TPort Single()
{
if (Count != 0)
{
throw new InvalidOperationException("Port collection does not have a single port.");
}
return this[0];
}
protected override string GetKeyForItem(TPort item)
{
return item.key;
}
public new bool TryGetValue(string key, out TPort value)
{
if (Dictionary == null)
{
value = default(TPort);
return false;
}
return Dictionary.TryGetValue(key, out value);
}
protected override void InsertItem(int index, TPort item)
{
BeforeAdd(item);
base.InsertItem(index, item);
AfterAdd(item);
}
protected override void RemoveItem(int index)
{
var item = this[index];
BeforeRemove(item);
base.RemoveItem(index);
AfterRemove(item);
}
protected override void SetItem(int index, TPort item)
{
throw new NotSupportedException();
}
protected override void ClearItems()
{
while (Count > 0)
{
RemoveItem(0);
}
}
}
}
|