From 080f1697e97e13461ec6df4d31c8924d01257a1b Mon Sep 17 00:00:00 2001 From: Roy Ben Shabat Date: Tue, 9 Apr 2019 01:47:48 +0300 Subject: MERGE --- .../Utils/ObserveAddRemoveCollection.cs | 63 ++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Software/Visual_Studio/Scripting/Tango.Scripting.Editors/Utils/ObserveAddRemoveCollection.cs (limited to 'Software/Visual_Studio/Scripting/Tango.Scripting.Editors/Utils/ObserveAddRemoveCollection.cs') diff --git a/Software/Visual_Studio/Scripting/Tango.Scripting.Editors/Utils/ObserveAddRemoveCollection.cs b/Software/Visual_Studio/Scripting/Tango.Scripting.Editors/Utils/ObserveAddRemoveCollection.cs new file mode 100644 index 000000000..091de0d91 --- /dev/null +++ b/Software/Visual_Studio/Scripting/Tango.Scripting.Editors/Utils/ObserveAddRemoveCollection.cs @@ -0,0 +1,63 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Collections.ObjectModel; + +namespace Tango.Scripting.Editors.Utils +{ + /// + /// A collection where adding and removing items causes a callback. + /// It is valid for the onAdd callback to throw an exception - this will prevent the new item from + /// being added to the collection. + /// + sealed class ObserveAddRemoveCollection : Collection + { + readonly Action onAdd, onRemove; + + public ObserveAddRemoveCollection(Action onAdd, Action onRemove) + { + this.onAdd = onAdd; + this.onRemove = onRemove; + } + + protected override void ClearItems() + { + if (onRemove != null) { + foreach (T val in this) + onRemove(val); + } + base.ClearItems(); + } + + protected override void InsertItem(int index, T item) + { + if (onAdd != null) + onAdd(item); + base.InsertItem(index, item); + } + + protected override void RemoveItem(int index) + { + if (onRemove != null) + onRemove(this[index]); + base.RemoveItem(index); + } + + protected override void SetItem(int index, T item) + { + if (onRemove != null) + onRemove(this[index]); + try { + if (onAdd != null) + onAdd(item); + } catch { + // When adding the new item fails, just remove the old one + // (we cannot keep the old item since we already successfully called onRemove for it) + base.RemoveAt(index); + throw; + } + base.SetItem(index, item); + } + } +} -- cgit v1.3.1