using Avalonia.Collections; using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mesen.Utilities { //Copy of Avalonia's AvaloniaList with an added Replace function to avoid triggering 2 updates public partial class MesenList { public void Replace(IList items) { _inner.Clear(); _inner.Capacity = items.Count; _inner.AddRange(items); _collectionChanged?.Invoke(this, EventArgsCache.ResetCollectionChanged); } public List GetInnerList() { return _inner; } } /// /// A notifying list. /// /// The type of the list items. /// /// /// AvaloniaList is similar to /// with a few added features: /// /// /// /// /// It can be configured to notify the event with a /// action instead of a /// when the list is cleared by /// setting to . /// removed /// /// /// A function can be used to validate each item before insertion. /// removed /// /// /// public partial class MesenList : IAvaloniaList, IList { private readonly List _inner; private NotifyCollectionChangedEventHandler? _collectionChanged; /// /// Initializes a new instance of the class. /// public MesenList() { _inner = new List(); } /// /// Initializes a new instance of the . /// /// Initial list capacity. public MesenList(int capacity) { _inner = new List(capacity); } /// /// Initializes a new instance of the class. /// /// The initial items for the collection. public MesenList(IEnumerable items) { _inner = new List(items); } /// /// Initializes a new instance of the class. /// /// The initial items for the collection. public MesenList(params T[] items) { _inner = new List(items); } /// /// Raised when a change is made to the collection's items. /// public event NotifyCollectionChangedEventHandler? CollectionChanged { add => _collectionChanged += value; remove => _collectionChanged -= value; } /// /// Raised when a property on the collection changes. /// public event PropertyChangedEventHandler? PropertyChanged; /// /// Gets the number of items in the collection. /// public int Count => _inner.Count; /// /// Gets or sets the reset behavior of the list. /// public ResetBehavior ResetBehavior { get; set; } /// /// Gets or sets a validation routine that can be used to validate items before they are /// added. /// public Action? Validate { get; set; } /// bool IList.IsFixedSize => false; /// bool IList.IsReadOnly => false; /// int ICollection.Count => _inner.Count; /// bool ICollection.IsSynchronized => false; /// object ICollection.SyncRoot => this; /// bool ICollection.IsReadOnly => false; /// /// Gets or sets the item at the specified index. /// /// The index. /// The item. public T this[int index] { get { return _inner[index]; } set { Validate?.Invoke(value); T old = _inner[index]; if(!EqualityComparer.Default.Equals(old, value)) { _inner[index] = value; if(_collectionChanged != null) { var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Replace, value, old, index); _collectionChanged(this, e); } } } } /// /// Gets or sets the item at the specified index. /// /// The index. /// The item. object? IList.this[int index] { get { return this[index]; } set { this[index] = (T)value!; } } /// /// Gets or sets the total number of elements the internal data structure can hold without resizing. /// public int Capacity { get => _inner.Capacity; set => _inner.Capacity = value; } /// /// Adds an item to the collection. /// /// The item. public virtual void Add(T item) { Validate?.Invoke(item); int index = _inner.Count; _inner.Add(item); NotifyAdd(item, index); } /// /// Adds multiple items to the collection. /// /// The items. public virtual void AddRange(IEnumerable items) => InsertRange(_inner.Count, items); /// /// Removes all items from the collection. /// public virtual void Clear() { if(Count > 0) { if(_collectionChanged != null) { var e = ResetBehavior == ResetBehavior.Reset ? EventArgsCache.ResetCollectionChanged : new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, _inner.ToArray(), 0); _inner.Clear(); _collectionChanged(this, e); } else { _inner.Clear(); } NotifyCountChanged(); } } /// /// Tests if the collection contains the specified item. /// /// The item. /// True if the collection contains the item; otherwise false. public bool Contains(T item) { return _inner.Contains(item); } /// /// Copies the collection's contents to an array. /// /// The array. /// The first index of the array to copy to. public void CopyTo(T[] array, int arrayIndex) { _inner.CopyTo(array, arrayIndex); } /// /// Returns an enumerator that enumerates the items in the collection. /// /// An . IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(_inner); } /// IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(_inner); } public Enumerator GetEnumerator() { return new Enumerator(_inner); } /// /// Gets a range of items from the collection. /// /// The zero-based index at which the range starts. /// The number of elements in the range. public IEnumerable GetRange(int index, int count) { return _inner.GetRange(index, count); } /// /// Gets the index of the specified item in the collection. /// /// The item. /// /// The index of the item or -1 if the item is not contained in the collection. /// public int IndexOf(T item) { return _inner.IndexOf(item); } /// /// Inserts an item at the specified index. /// /// The index. /// The item. public virtual void Insert(int index, T item) { Validate?.Invoke(item); _inner.Insert(index, item); NotifyAdd(item, index); } /// /// Inserts multiple items at the specified index. /// /// The index. /// The items. public virtual void InsertRange(int index, IEnumerable items) { _ = items ?? throw new ArgumentNullException(nameof(items)); bool willRaiseCollectionChanged = _collectionChanged != null; bool hasValidation = Validate != null; if(items is IList list) { if(list.Count > 0) { if(list is ICollection collection) { if(hasValidation) { foreach(T item in collection) { Validate!(item); } } _inner.InsertRange(index, collection); NotifyAdd(list, index); } else { EnsureCapacity(_inner.Count + list.Count); using(IEnumerator en = items.GetEnumerator()) { int insertIndex = index; while(en.MoveNext()) { T item = en.Current; if(hasValidation) { Validate!(item); } _inner.Insert(insertIndex++, item); } } NotifyAdd(list, index); } } } else { using(IEnumerator en = items.GetEnumerator()) { if(en.MoveNext()) { // Avoid allocating list for collection notification if there is no event subscriptions. List? notificationItems = willRaiseCollectionChanged ? new List() : null; int insertIndex = index; do { T item = en.Current; if(hasValidation) { Validate!(item); } _inner.Insert(insertIndex++, item); notificationItems?.Add(item); } while(en.MoveNext()); if(notificationItems is not null) { NotifyAdd(notificationItems, index); } else { NotifyCountChanged(); } } } } } /// /// Moves an item to a new index. /// /// The index of the item to move. /// The index to move the item to. public void Move(int oldIndex, int newIndex) { var item = this[oldIndex]; _inner.RemoveAt(oldIndex); _inner.Insert(newIndex, item); if(_collectionChanged != null) { var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Move, item, newIndex, oldIndex); _collectionChanged(this, e); } } /// /// Moves multiple items to a new index. /// /// The first index of the items to move. /// The number of items to move. /// The index to move the items to. public void MoveRange(int oldIndex, int count, int newIndex) { var items = _inner.GetRange(oldIndex, count); var modifiedNewIndex = newIndex; _inner.RemoveRange(oldIndex, count); if(newIndex > oldIndex) { modifiedNewIndex -= count; } _inner.InsertRange(modifiedNewIndex, items); if(_collectionChanged != null) { var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Move, items, newIndex, oldIndex); _collectionChanged(this, e); } } /// /// Ensures that the capacity of the list is at least . /// /// The capacity. public void EnsureCapacity(int capacity) { // Adapted from List implementation. var currentCapacity = _inner.Capacity; if(currentCapacity < capacity) { var newCapacity = currentCapacity == 0 ? 4 : currentCapacity * 2; if(newCapacity < capacity) { newCapacity = capacity; } _inner.Capacity = newCapacity; } } /// /// Removes an item from the collection. /// /// The item. /// True if the item was found and removed, otherwise false. public virtual bool Remove(T item) { int index = _inner.IndexOf(item); if(index != -1) { _inner.RemoveAt(index); NotifyRemove(item, index); return true; } return false; } /// /// Removes multiple items from the collection. /// /// The items. public virtual void RemoveAll(IEnumerable items) { _ = items ?? throw new ArgumentNullException(nameof(items)); var hItems = new HashSet(items); int counter = 0; for(int i = _inner.Count - 1; i >= 0; --i) { if(hItems.Contains(_inner[i])) { counter += 1; } else if(counter > 0) { RemoveRange(i + 1, counter); counter = 0; } } if(counter > 0) RemoveRange(0, counter); } /// /// Removes the item at the specified index. /// /// The index. public virtual void RemoveAt(int index) { T item = _inner[index]; _inner.RemoveAt(index); NotifyRemove(item, index); } /// /// Removes a range of elements from the collection. /// /// The first index to remove. /// The number of items to remove. public virtual void RemoveRange(int index, int count) { if(count > 0) { var list = _inner.GetRange(index, count); _inner.RemoveRange(index, count); NotifyRemove(list, index); } } /// int IList.Add(object? value) { int index = Count; Add((T)value!); return index; } /// bool IList.Contains(object? value) { return Contains((T)value!); } /// void IList.Clear() { Clear(); } /// int IList.IndexOf(object? value) { return IndexOf((T)value!); } /// void IList.Insert(int index, object? value) { Insert(index, (T)value!); } /// void IList.Remove(object? value) { Remove((T)value!); } /// void IList.RemoveAt(int index) { RemoveAt(index); } /// void ICollection.CopyTo(Array array, int index) { if(array == null) { throw new ArgumentNullException(nameof(array)); } if(array.Rank != 1) { throw new ArgumentException("Multi-dimensional arrays are not supported."); } if(array.GetLowerBound(0) != 0) { throw new ArgumentException("Non-zero lower bounds are not supported."); } if(index < 0) { throw new ArgumentException("Invalid index."); } if(array.Length - index < Count) { throw new ArgumentException("The target array is too small."); } if(array is T[] tArray) { _inner.CopyTo(tArray, index); } else { // // Catch the obvious case assignment will fail. // We can't find all possible problems by doing the check though. // For example, if the element type of the Array is derived from T, // we can't figure out if we can successfully copy the element beforehand. // Type targetType = array.GetType().GetElementType()!; Type sourceType = typeof(T); if(!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) { throw new ArgumentException("Invalid array type"); } // // We can't cast array of value type to object[], so we don't support // widening of primitive types here. // if(array is not object?[] objects) { throw new ArgumentException("Invalid array type"); } int count = _inner.Count; try { for(int i = 0; i < count; i++) { objects[index++] = _inner[i]; } } catch(ArrayTypeMismatchException) { throw new ArgumentException("Invalid array type"); } } } /// /// Raises the event with an add action. /// /// The items that were added. /// The starting index. private void NotifyAdd(IList t, int index) { if(_collectionChanged != null) { var e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, t, index); _collectionChanged(this, e); } NotifyCountChanged(); } /// /// Raises the event with a add action. /// /// The item that was added. /// The starting index. private void NotifyAdd(T item, int index) { if(_collectionChanged != null) { var e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, new[] { item }, index); _collectionChanged(this, e); } NotifyCountChanged(); } /// /// Raises the event when the property /// changes. /// private void NotifyCountChanged() { PropertyChanged?.Invoke(this, EventArgsCache.CountPropertyChanged); } /// /// Raises the event with a remove action. /// /// The items that were removed. /// The starting index. private void NotifyRemove(IList t, int index) { if(_collectionChanged != null) { var e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, t, index); _collectionChanged(this, e); } NotifyCountChanged(); } /// /// Raises the event with a remove action. /// /// The item that was removed. /// The starting index. private void NotifyRemove(T item, int index) { if(_collectionChanged != null) { var e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, new[] { item }, index); _collectionChanged(this, e); } NotifyCountChanged(); } /// /// Enumerates the elements of a . /// public struct Enumerator : IEnumerator { private List.Enumerator _innerEnumerator; public Enumerator(List inner) { _innerEnumerator = inner.GetEnumerator(); } public bool MoveNext() { return _innerEnumerator.MoveNext(); } void IEnumerator.Reset() { ((IEnumerator)_innerEnumerator).Reset(); } public T Current => _innerEnumerator.Current; object? IEnumerator.Current => Current; public void Dispose() { _innerEnumerator.Dispose(); } } } internal static class EventArgsCache { internal static readonly PropertyChangedEventArgs CountPropertyChanged = new PropertyChangedEventArgs(nameof(AvaloniaList.Count)); internal static readonly NotifyCollectionChangedEventArgs ResetCollectionChanged = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset); } }