This commit is contained in:
2026-11-24 15:51:02 +01:00
parent cca4d73e41
commit f4aa17114a
22092 changed files with 5042406 additions and 0 deletions
@@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace Unity.CodeEditor.Utils
{
/// <summary>
/// This class is used to prevent stack overflows by representing a 'busy' flag
/// that prevents reentrance when another call is running.
/// However, using a simple 'bool busy' is not thread-safe, so we use a
/// thread-static BusyManager.
/// </summary>
internal static class BusyManager
{
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")]
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible",
Justification = "Should always be used with 'var'")]
internal struct BusyLock : IDisposable
{
internal static readonly BusyLock Failed = new BusyLock(null);
private readonly List<object> _objectList;
internal BusyLock(List<object> objectList)
{
_objectList = objectList;
}
internal bool Success => _objectList != null;
public void Dispose()
{
_objectList?.RemoveAt(_objectList.Count - 1);
}
}
[ThreadStatic] private static List<object> _activeObjects;
internal static BusyLock Enter(object obj)
{
var activeObjects = _activeObjects ?? (_activeObjects = new List<object>());
if (activeObjects.Any(t => t == obj))
{
return BusyLock.Failed;
}
activeObjects.Add(obj);
return new BusyLock(activeObjects);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: a2601a7e62a84d3e95fe8be6d25a7280
timeCreated: 1710774675
@@ -0,0 +1,46 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Threading;
namespace Unity.CodeEditor.Utils
{
/// <summary>
/// Invokes an action when it is disposed.
/// </summary>
/// <remarks>
/// This class ensures the callback is invoked at most once,
/// even when Dispose is called on multiple threads.
/// </remarks>
internal sealed class CallbackOnDispose : IDisposable
{
private Action _action;
internal CallbackOnDispose(Action action)
{
_action = action ?? throw new ArgumentNullException(nameof(action));
}
public void Dispose()
{
var a = Interlocked.Exchange(ref _action, null);
a?.Invoke();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: cb2fb351949604785bb11ffdb44f18b7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,264 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.IO;
namespace Unity.CodeEditor.Utils
{
/// <summary>
/// Poor man's template specialization: extension methods for Rope&lt;char&gt;.
/// </summary>
internal static class CharRope
{
/// <summary>
/// Creates a new rope from the specified text.
/// </summary>
internal static Rope<char> Create(string text)
{
if (text == null)
throw new ArgumentNullException(nameof(text));
return new Rope<char>(InitFromString(text));
}
/// <summary>
/// Retrieves the text for a portion of the rope.
/// Runs in O(lg N + M), where M=<paramref name="length"/>.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">offset or length is outside the valid range.</exception>
/// <remarks>
/// This method counts as a read access and may be called concurrently to other read accesses.
/// </remarks>
internal static string ToString(this Rope<char> rope, int startIndex, int length)
{
if (rope == null)
throw new ArgumentNullException(nameof(rope));
#if DEBUG
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be >= 0");
#endif
if (length == 0)
return string.Empty;
char[] buffer = new char[length];
rope.CopyTo(startIndex, buffer, 0, length);
return new string(buffer);
}
/// <summary>
/// Retrieves the text for a portion of the rope as ReadOnlyMemory.
/// Runs in O(lg N + M), where M=<paramref name="length"/>.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">offset or length is outside the valid range.</exception>
/// <remarks>
/// This method counts as a read access and may be called concurrently to other read accesses.
/// When the requested range falls entirely within a single leaf node, this method returns
/// a slice of the internal buffer without allocation. Otherwise, a new buffer is allocated.
/// </remarks>
internal static ReadOnlyMemory<char> GetMemory(this Rope<char> rope, int startIndex, int length)
{
if (rope == null)
throw new ArgumentNullException(nameof(rope));
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be >= 0");
if (length == 0)
return ReadOnlyMemory<char>.Empty;
rope.VerifyRange(startIndex, length);
// Try to get a zero-allocation slice if the range fits within a single leaf node
var entry = rope.FindNodeUsingCache(startIndex).PeekOrDefault();
int offsetWithinNode = startIndex - entry.NodeStartIndex;
// Check if the entire requested range fits within this leaf node
if (offsetWithinNode + length <= entry.Node.Length)
{
// Return a slice of the existing buffer - no allocation needed
return new ReadOnlyMemory<char>(entry.Node.Contents, offsetWithinNode, length);
}
// Range spans multiple nodes - must allocate and copy
char[] buffer = new char[length];
rope.CopyTo(startIndex, buffer, 0, length);
return new ReadOnlyMemory<char>(buffer);
}
/// <summary>
/// Retrieves the text for a portion of the rope and writes it to the specified text writer.
/// Runs in O(lg N + M), where M=<paramref name="length"/>.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">offset or length is outside the valid range.</exception>
/// <remarks>
/// This method counts as a read access and may be called concurrently to other read accesses.
/// </remarks>
internal static void WriteTo(this Rope<char> rope, TextWriter output, int startIndex, int length)
{
if (rope == null)
throw new ArgumentNullException(nameof(rope));
if (output == null)
throw new ArgumentNullException(nameof(output));
rope.VerifyRange(startIndex, length);
rope.Root.WriteTo(startIndex, output, length);
}
/// <summary>
/// Appends text to this rope.
/// Runs in O(lg N + M).
/// </summary>
/// <exception cref="ArgumentNullException">newElements is null.</exception>
internal static void AddText(this Rope<char> rope, string text)
{
InsertText(rope, rope.Length, text);
}
/// <summary>
/// Inserts text into this rope.
/// Runs in O(lg N + M).
/// </summary>
/// <exception cref="ArgumentNullException">newElements is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">index or length is outside the valid range.</exception>
internal static void InsertText(this Rope<char> rope, int index, string text)
{
if (rope == null)
throw new ArgumentNullException(nameof(rope));
rope.InsertRange(index, text.ToCharArray(), 0, text.Length);
/*if (index < 0 || index > rope.Length) {
throw new ArgumentOutOfRangeException("index", index, "0 <= index <= " + rope.Length.ToString(CultureInfo.InvariantCulture));
}
if (text == null)
throw new ArgumentNullException("text");
if (text.Length == 0)
return;
rope.root = rope.root.Insert(index, text);
rope.OnChanged();*/
}
internal static RopeNode<char> InitFromString(string text)
{
if (text.Length == 0) {
return RopeNode<char>.EmptyRopeNode;
}
RopeNode<char> node = RopeNode<char>.CreateNodes(text.Length);
FillNode(node, text, 0);
return node;
}
static void FillNode(RopeNode<char> node, string text, int start)
{
if (node.Contents != null) {
text.CopyTo(start, node.Contents, 0, node.Length);
} else {
FillNode(node.Left, text, start);
FillNode(node.Right, text, start + node.Left.Length);
}
}
internal static void WriteTo(this RopeNode<char> node, int index, TextWriter output, int count)
{
if (node.Height == 0) {
if (node.Contents == null) {
// function node
node.GetContentNode().WriteTo(index, output, count);
} else {
// leaf node: append data
output.Write(node.Contents, index, count);
}
} else {
// concat node: do recursive calls
if (index + count <= node.Left.Length) {
node.Left.WriteTo(index, output, count);
} else if (index >= node.Left.Length) {
node.Right.WriteTo(index - node.Left.Length, output, count);
} else {
int amountInLeft = node.Left.Length - index;
node.Left.WriteTo(index, output, amountInLeft);
node.Right.WriteTo(0, output, count - amountInLeft);
}
}
}
/// <summary>
/// Gets the index of the first occurrence of any element in the specified array.
/// </summary>
/// <param name="rope">The target rope.</param>
/// <param name="anyOf">Array of characters being searched.</param>
/// <param name="startIndex">Start index of the search.</param>
/// <param name="length">Length of the area to search.</param>
/// <returns>The first index where any character was found; or -1 if no occurrence was found.</returns>
internal static int IndexOfAny(this Rope<char> rope, char[] anyOf, int startIndex, int length)
{
if (rope == null)
throw new ArgumentNullException(nameof(rope));
if (anyOf == null)
throw new ArgumentNullException(nameof(anyOf));
rope.VerifyRange(startIndex, length);
while (length > 0) {
var entry = rope.FindNodeUsingCache(startIndex).Peek();
char[] contents = entry.Node.Contents;
int startWithinNode = startIndex - entry.NodeStartIndex;
int nodeLength = Math.Min(entry.Node.Length, startWithinNode + length);
for (int i = startIndex - entry.NodeStartIndex; i < nodeLength; i++) {
char element = contents[i];
foreach (char needle in anyOf) {
if (element == needle)
return entry.NodeStartIndex + i;
}
}
length -= nodeLength - startWithinNode;
startIndex = entry.NodeStartIndex + nodeLength;
}
return -1;
}
/// <summary>
/// Gets the index of the first occurrence of the search text.
/// </summary>
internal static int IndexOf(this Rope<char> rope, string searchText, int startIndex, int length, StringComparison comparisonType)
{
if (rope == null)
throw new ArgumentNullException(nameof(rope));
if (searchText == null)
throw new ArgumentNullException(nameof(searchText));
rope.VerifyRange(startIndex, length);
int pos = rope.ToString(startIndex, length).IndexOf(searchText, comparisonType);
if (pos < 0)
return -1;
else
return pos + startIndex;
}
/// <summary>
/// Gets the index of the last occurrence of the search text.
/// </summary>
internal static int LastIndexOf(this Rope<char> rope, string searchText, int startIndex, int length, StringComparison comparisonType)
{
if (rope == null)
throw new ArgumentNullException(nameof(rope));
if (searchText == null)
throw new ArgumentNullException(nameof(searchText));
rope.VerifyRange(startIndex, length);
int pos = rope.ToString(startIndex, length).LastIndexOf(searchText, comparisonType);
if (pos < 0)
return -1;
else
return pos + startIndex;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5ee3d35631cb64c49a9cbb6083e3757c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 1103767005f14426aff2dce0443ef707
timeCreated: 1710774748
@@ -0,0 +1,28 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
namespace Unity.CodeEditor.Utils
{
internal static class Constants
{
/// <summary>
/// Multiply with this constant to convert from points to device-independent pixels.
/// </summary>
internal const double PixelPerPoint = 4 / 3.0;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e4e07079374247849fcb35aa912e2421
timeCreated: 1710774763
@@ -0,0 +1,64 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
namespace Unity.CodeEditor.Utils
{
/// <summary>
/// Maintains a list of delayed events to raise.
/// </summary>
internal sealed class DelayedEvents
{
private struct EventCall
{
private readonly EventHandler _handler;
private readonly object _sender;
private readonly EventArgs _e;
internal EventCall(EventHandler handler, object sender, EventArgs e)
{
_handler = handler;
_sender = sender;
_e = e;
}
internal void Call()
{
_handler(_sender, _e);
}
}
private readonly Queue<EventCall> _eventCalls = new Queue<EventCall>();
internal void DelayedRaise(EventHandler handler, object sender, EventArgs e)
{
if (handler != null)
{
_eventCalls.Enqueue(new EventCall(handler, sender, e));
}
}
internal void RaiseEvents()
{
while (_eventCalls.Count > 0)
_eventCalls.Dequeue().Call();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b82decbecd7e9441b9e870133239aeee
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,184 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
namespace Unity.CodeEditor.Utils
{
/// <summary>
/// Double-ended queue.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
internal sealed class Deque<T> : ICollection<T>
{
private T[] _arr = Array.Empty<T>();
private int _head;
private int _tail;
/// <inheritdoc/>
public int Count { get; private set; }
/// <inheritdoc/>
public void Clear()
{
_arr = Array.Empty<T>();
Count = 0;
_head = 0;
_tail = 0;
}
/// <summary>
/// Gets/Sets an element inside the deque.
/// </summary>
internal T this[int index] {
get {
ThrowUtil.CheckInRangeInclusive(index, "index", 0, Count - 1);
return _arr[(_head + index) % _arr.Length];
}
set {
ThrowUtil.CheckInRangeInclusive(index, "index", 0, Count - 1);
_arr[(_head + index) % _arr.Length] = value;
}
}
/// <summary>
/// Adds an element to the end of the deque.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "PushBack")]
internal void PushBack(T item)
{
if (Count == _arr.Length)
SetCapacity(Math.Max(4, _arr.Length * 2));
_arr[_tail++] = item;
if (_tail == _arr.Length) _tail = 0;
Count++;
}
/// <summary>
/// Pops an element from the end of the deque.
/// </summary>
internal T PopBack()
{
if (Count == 0)
throw new InvalidOperationException();
if (_tail == 0)
_tail = _arr.Length - 1;
else
_tail--;
T val = _arr[_tail];
_arr[_tail] = default(T); // allow GC to collect the element
Count--;
return val;
}
/// <summary>
/// Adds an element to the front of the deque.
/// </summary>
internal void PushFront(T item)
{
if (Count == _arr.Length)
SetCapacity(Math.Max(4, _arr.Length * 2));
if (_head == 0)
_head = _arr.Length - 1;
else
_head--;
_arr[_head] = item;
Count++;
}
/// <summary>
/// Pops an element from the end of the deque.
/// </summary>
internal T PopFront()
{
if (Count == 0)
throw new InvalidOperationException();
T val = _arr[_head];
_arr[_head] = default(T); // allow GC to collect the element
_head++;
if (_head == _arr.Length) _head = 0;
Count--;
return val;
}
private void SetCapacity(int capacity)
{
T[] newArr = new T[capacity];
CopyTo(newArr, 0);
_head = 0;
_tail = (Count == capacity) ? 0 : Count;
_arr = newArr;
}
/// <inheritdoc/>
public IEnumerator<T> GetEnumerator()
{
if (_head < _tail) {
for (int i = _head; i < _tail; i++)
yield return _arr[i];
} else {
for (int i = _head; i < _arr.Length; i++)
yield return _arr[i];
for (int i = 0; i < _tail; i++)
yield return _arr[i];
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
bool ICollection<T>.IsReadOnly => false;
void ICollection<T>.Add(T item)
{
PushBack(item);
}
/// <inheritdoc/>
public bool Contains(T item)
{
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
foreach (T element in this)
if (comparer.Equals(item, element))
return true;
return false;
}
/// <inheritdoc/>
public void CopyTo(T[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (_head < _tail) {
Array.Copy(_arr, _head, array, arrayIndex, _tail - _head);
} else {
int num1 = _arr.Length - _head;
Array.Copy(_arr, _head, array, arrayIndex, num1);
Array.Copy(_arr, 0, array, arrayIndex + num1, _tail);
}
}
bool ICollection<T>.Remove(T item)
{
throw new NotSupportedException();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fdf371b229de34c7a8f364e3cb759548
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,29 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
namespace Unity.CodeEditor.Utils
{
/// <summary>
/// Provides immutable empty list instances.
/// </summary>
internal static class Empty<T>
{
internal static readonly T[] Array = new T[0];
//public static readonly ReadOnlyCollection<T> ReadOnlyCollection = new ReadOnlyCollection<T>(Array);
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 917f880bb43743a3869e281c51dfdc43
timeCreated: 1710774885
@@ -0,0 +1,149 @@
using System;
using System.Collections.Generic;
using Unity.CodeEditor.Editing;
using UnityEngine;
namespace Unity.CodeEditor.Utils
{
//PENDING TO COMPLETE
internal static class ExtensionMethods
{
#region Rectangle
internal static Rect WithY(this Rect rect, float y)
{
return new Rect(rect.x, y, rect.width, rect.height);
}
internal static Rect WithWidth(this Rect rect, float width)
{
return new Rect(rect.x, rect.y, width, rect.height);
}
#endregion
#region Vector2
internal static bool IsClose(this Vector2 v, Vector2 other)
{
return IsClose(v.x, other.x) && IsClose(v.y, other.y);
}
internal static Vector2 RelativeTo(this Vector2 v, Rect rect)
{
return new Vector2(v.x - rect.x, v.y - rect.y);
}
#endregion
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
internal const float Epsilon = 0.01f;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
internal static bool IsClose(this float d1, float d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
internal static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
/*public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}*/
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
internal static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
internal static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region AddRange / Sequence
internal static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
internal static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
internal static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
/// <summary>
/// Gets the union of two rectangles.
/// </summary>
/// <param name="other">The other rectangle.</param>
/// <returns>The union.</returns>
internal static Rect Union(this Rect rect, Rect other)
{
if (rect.width == 0 && rect.height == 0)
{
return other;
}
else if (other.width == 0 && other.height == 0)
{
return rect;
}
else
{
var x1 = Math.Min(rect.x, other.x);
var x2 = Math.Max(rect.xMax, other.xMax);
var y1 = Math.Min(rect.y, other.y);
var y2 = Math.Max(rect.yMax, other.yMax);
return new Rect(new Vector2(x1, y1), new Vector2(x2, y2));
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 4d6e238ada664d43b3e1f3652c5c7119
timeCreated: 1710758639
@@ -0,0 +1,288 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.IO;
using System.Text;
namespace Unity.CodeEditor.Utils
{
/// <summary>
/// Class that can open text files with auto-detection of the encoding.
/// </summary>
internal static class FileReader
{
/// <summary>
/// Gets if the given encoding is a Unicode encoding (UTF).
/// </summary>
/// <remarks>
/// Returns true for UTF-7, UTF-8, UTF-16 LE, UTF-16 BE, UTF-32 LE and UTF-32 BE.
/// Returns false for all other encodings.
/// </remarks>
internal static bool IsUnicode(Encoding encoding)
{
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
switch (encoding)
{
case UnicodeEncoding _:
case UTF8Encoding _:
return true;
default:
return false;
}
//switch (encoding) {
// case 65000: // UTF-7
// case 65001: // UTF-8
// case 1200: // UTF-16 LE
// case 1201: // UTF-16 BE
// case 12000: // UTF-32 LE
// case 12001: // UTF-32 BE
// return true;
// default:
// return false;
//}
}
private static bool IsAsciiCompatible(Encoding encoding)
{
var bytes = encoding.GetBytes("Az");
return bytes.Length == 2 && bytes[0] == 'A' && bytes[1] == 'z';
}
private static Encoding RemoveBom(Encoding encoding)
{
if (encoding is UTF8Encoding)
{
return UTF8NoBOM;
}
return encoding;
//switch (encoding.CodePage) {
// case 65001: // UTF-8
// return UTF8NoBOM;
// default:
// return encoding;
//}
}
/// <summary>
/// Reads the content of the given stream.
/// </summary>
/// <param name="stream">The stream to read.
/// The stream must support seeking and must be positioned at its beginning.</param>
/// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param>
/// <returns>The file content as string.</returns>
internal static string ReadFileContent(Stream stream, Encoding defaultEncoding)
{
using (var reader = OpenStream(stream, defaultEncoding))
{
return reader.ReadToEnd();
}
}
/// <summary>
/// Reads the content of the file.
/// </summary>
/// <param name="fileName">The file name.</param>
/// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param>
/// <returns>The file content as string.</returns>
internal static string ReadFileContent(string fileName, Encoding defaultEncoding)
{
throw new NotImplementedException();
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) {
// return ReadFileContent(fs, defaultEncoding);
//}
}
/// <summary>
/// Opens the specified file for reading.
/// </summary>
/// <param name="fileName">The file to open.</param>
/// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param>
/// <returns>Returns a StreamReader that reads from the stream. Use
/// <see cref="StreamReader.CurrentEncoding"/> to get the encoding that was used.</returns>
internal static StreamReader OpenFile(string fileName, Encoding defaultEncoding)
{
throw new NotImplementedException();
//if (fileName == null)
// throw new ArgumentNullException("fileName");
//FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
//try {
// return OpenStream(fs, defaultEncoding);
// // don't use finally: the stream must be kept open until the StreamReader closes it
//} catch {
// fs.Dispose();
// throw;
//}
}
/// <summary>
/// Opens the specified stream for reading.
/// </summary>
/// <param name="stream">The stream to open.</param>
/// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param>
/// <returns>Returns a StreamReader that reads from the stream. Use
/// <see cref="StreamReader.CurrentEncoding"/> to get the encoding that was used.</returns>
internal static StreamReader OpenStream(Stream stream, Encoding defaultEncoding)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (stream.Position != 0)
throw new ArgumentException("stream is not positioned at beginning.", nameof(stream));
if (defaultEncoding == null)
throw new ArgumentNullException(nameof(defaultEncoding));
if (stream.Length >= 2)
{
// the autodetection of StreamReader is not capable of detecting the difference
// between ISO-8859-1 and UTF-8 without BOM.
var firstByte = stream.ReadByte();
var secondByte = stream.ReadByte();
switch ((firstByte << 8) | secondByte)
{
case 0x0000: // either UTF-32 Big Endian or a binary file; use StreamReader
case 0xfffe: // Unicode BOM (UTF-16 LE or UTF-32 LE)
case 0xfeff: // UTF-16 BE BOM
case 0xefbb: // start of UTF-8 BOM
// StreamReader autodetection works
stream.Position = 0;
return new StreamReader(stream);
default:
return AutoDetect(stream, (byte) firstByte, (byte) secondByte, defaultEncoding);
}
}
return new StreamReader(stream, defaultEncoding);
}
// ReSharper disable once InconsistentNaming
private static readonly Encoding UTF8NoBOM = new UTF8Encoding(false);
private static StreamReader AutoDetect(Stream fs, byte firstByte, byte secondByte, Encoding defaultEncoding)
{
var max = (int)Math.Min(fs.Length, 500000); // look at max. 500 KB
// ReSharper disable InconsistentNaming
const int ASCII = 0;
const int Error = 1;
const int UTF8 = 2;
const int UTF8Sequence = 3;
// ReSharper restore InconsistentNaming
var state = ASCII;
var sequenceLength = 0;
for (var i = 0; i < max; i++)
{
byte b;
if (i == 0)
{
b = firstByte;
}
else if (i == 1)
{
b = secondByte;
}
else
{
b = (byte)fs.ReadByte();
}
if (b < 0x80)
{
// normal ASCII character
if (state == UTF8Sequence)
{
state = Error;
break;
}
}
else if (b < 0xc0)
{
// 10xxxxxx : continues UTF8 byte sequence
if (state == UTF8Sequence)
{
--sequenceLength;
if (sequenceLength < 0)
{
state = Error;
break;
}
else if (sequenceLength == 0)
{
state = UTF8;
}
}
else
{
state = Error;
break;
}
}
else if (b >= 0xc2 && b < 0xf5)
{
// beginning of byte sequence
if (state == UTF8 || state == ASCII)
{
state = UTF8Sequence;
if (b < 0xe0)
{
sequenceLength = 1; // one more byte following
}
else if (b < 0xf0)
{
sequenceLength = 2; // two more bytes following
}
else
{
sequenceLength = 3; // three more bytes following
}
}
else
{
state = Error;
break;
}
}
else
{
// 0xc0, 0xc1, 0xf5 to 0xff are invalid in UTF-8 (see RFC 3629)
state = Error;
break;
}
}
fs.Position = 0;
switch (state)
{
case ASCII:
// TODO: Encoding.ASCII
return new StreamReader(fs, IsAsciiCompatible(defaultEncoding) ? RemoveBom(defaultEncoding) : Encoding.UTF8);
case Error:
// When the file seems to be non-UTF8,
// we read it using the user-specified encoding so it is saved again
// using that encoding.
if (IsUnicode(defaultEncoding))
{
// the file is not Unicode, so don't read it using Unicode even if the
// user has choosen Unicode as the default encoding.
defaultEncoding = Encoding.UTF8; // use system encoding instead
}
return new StreamReader(fs, RemoveBom(defaultEncoding));
default:
return new StreamReader(fs, UTF8NoBOM);
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 205856b2c6304b8d8cdf7811e8494c72
timeCreated: 1710774859
@@ -0,0 +1,117 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace Unity.CodeEditor.Utils
{
internal interface IFreezable
{
/// <summary>
/// Gets if this instance is frozen. Frozen instances are immutable and thus thread-safe.
/// </summary>
bool IsFrozen { get; }
/// <summary>
/// Freezes this instance.
/// </summary>
void Freeze();
}
internal static class FreezableHelper
{
internal static void ThrowIfFrozen(IFreezable freezable)
{
if (freezable.IsFrozen)
throw new InvalidOperationException("Cannot mutate frozen " + freezable.GetType().Name);
}
internal static IList<T> FreezeListAndElements<T>(IList<T> list)
{
if (list != null) {
foreach (var item in list)
Freeze(item);
}
return FreezeList(list);
}
internal static IList<T> FreezeList<T>(IList<T> list)
{
if (list == null || list.Count == 0)
return Empty<T>.Array;
if (list.IsReadOnly) {
// If the list is already read-only, return it directly.
// This is important, otherwise we might undo the effects of interning.
return list;
} else {
return new ReadOnlyCollection<T>(list.ToArray());
}
}
public static void Freeze(object item)
{
var f = item as IFreezable;
f?.Freeze();
}
internal static T FreezeAndReturn<T>(T item) where T : IFreezable
{
item.Freeze();
return item;
}
/// <summary>
/// If the item is not frozen, this method creates and returns a frozen clone.
/// If the item is already frozen, it is returned without creating a clone.
/// </summary>
internal static T GetFrozenClone<T>(T item) where T : IFreezable, ICloneable
{
if (!item.IsFrozen) {
item = (T)item.Clone();
item.Freeze();
}
return item;
}
}
internal abstract class AbstractFreezable : IFreezable
{
/// <summary>
/// Gets if this instance is frozen. Frozen instances are immutable and thus thread-safe.
/// </summary>
public bool IsFrozen { get; private set; }
/// <summary>
/// Freezes this instance.
/// </summary>
public void Freeze()
{
if (!IsFrozen) {
FreezeInternal();
IsFrozen = true;
}
}
protected virtual void FreezeInternal()
{
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 036a88373b074a0cb5c99d4568e77563
timeCreated: 1710774872
@@ -0,0 +1,47 @@
//
// IImmutableStack.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections;
using System.Collections.Generic;
namespace Unity.CodeEditor.Utils
{
internal interface IImmutableStack<T> : IEnumerable<T>, IEnumerable
{
bool IsEmpty
{
get;
}
IImmutableStack<T> Clear();
T Peek();
IImmutableStack<T> Pop();
IImmutableStack<T> Push(T value);
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 3dce8f801e8649c8951ef1edd8c8df5c
timeCreated: 1710758565
@@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
namespace Unity.CodeEditor.Utils
{
internal interface IServiceContainer : IServiceProvider
{
void AddService(Type serviceType, object serviceInstance);
void RemoveService(Type serviceType);
}
internal static class ServiceExtensions
{
internal static T GetService<T>(this IServiceProvider provider) where T : class
{
return provider.GetService(typeof(T)) as T;
}
public static void AddService<T>(this IServiceContainer container, T serviceInstance)
{
if (container == null) throw new ArgumentNullException(nameof(container));
container.AddService(typeof(T), serviceInstance);
}
public static void RemoveService<T>(this IServiceContainer container)
{
if (container == null) throw new ArgumentNullException(nameof(container));
container.RemoveService(typeof(T));
}
}
internal class ServiceContainer : IServiceContainer
{
private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
internal ServiceContainer()
{
_services.Add(typeof(IServiceProvider), this);
_services.Add(typeof(IServiceContainer), this);
}
public object GetService(Type serviceType)
{
_services.TryGetValue(serviceType, out var service);
return service;
}
public void AddService(Type serviceType, object serviceInstance)
{
_services[serviceType] = serviceInstance;
}
public void RemoveService(Type serviceType)
{
_services.Remove(serviceType);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5d04019d947ff4be294c29c0faebb79f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,205 @@
//
// ImmutableStack.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections;
using System.Collections.Generic;
namespace Unity.CodeEditor.Utils
{
internal class ImmutableStack<T> : IImmutableStack<T>
{
readonly T head;
readonly ImmutableStack<T> tail;
internal ImmutableStack()
{
}
ImmutableStack(T head, ImmutableStack<T> tail)
{
this.head = head;
this.tail = tail;
}
#region IImmutableStack implementation
internal static readonly ImmutableStack<T> Empty = new ImmutableStack<T>();
public bool IsEmpty
{
get { return tail == null; }
}
public ImmutableStack<T> Clear()
{
return Empty;
}
IImmutableStack<T> IImmutableStack<T>.Clear()
{
return Empty;
}
public T Peek()
{
if (IsEmpty)
throw new InvalidOperationException("Stack is empty.");
return head;
}
public ImmutableStack<T> Pop()
{
if (IsEmpty)
throw new InvalidOperationException("Stack is empty.");
return tail;
}
public ImmutableStack<T> Pop(out T value)
{
value = Peek();
return Pop();
}
IImmutableStack<T> IImmutableStack<T>.Pop()
{
return Pop();
}
public ImmutableStack<T> Push(T value)
{
return new ImmutableStack<T>(value, this);
}
IImmutableStack<T> IImmutableStack<T>.Push(T value)
{
return Push(value);
}
#endregion
#region IEnumerable<T> implementation
public IEnumerator<T> GetEnumerator()
{
return new Enumerator(this);
}
struct Enumerator : IEnumerator<T>
{
readonly ImmutableStack<T> start;
IImmutableStack<T> current;
internal Enumerator(ImmutableStack<T> stack)
{
this.start = stack;
this.current = null;
}
#region IEnumerator implementation
bool IEnumerator.MoveNext()
{
if (current == null)
{
current = this.start;
}
else if (!current.IsEmpty)
{
current = current.Pop();
}
return !current.IsEmpty;
}
void IEnumerator.Reset()
{
current = null;
}
object IEnumerator.Current
{
get { return this.Current; }
}
#endregion
#region IDisposable implementation
void IDisposable.Dispose()
{
}
#endregion
#region IEnumerator implementation
public T Current
{
get
{
return current != null ? current.Peek() : default(T);
}
}
#endregion
}
#endregion
#region IEnumerable implementation
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
}
internal static class ImmutableStack
{
internal static ImmutableStack<T> Create<T>()
{
return ImmutableStack<T>.Empty;
}
internal static ImmutableStack<T> Create<T>(T item)
{
return Create<T>().Push(item);
}
internal static ImmutableStack<T> Create<T>(IEnumerable<T> items)
{
var result = ImmutableStack<T>.Empty;
foreach (var item in items)
result = result.Push(item);
return result;
}
internal static ImmutableStack<T> Create<T>(params T[] items)
{
return Create((IEnumerable<T>)items);
}
public static IImmutableStack<T> Pop<T>(this IImmutableStack<T> stack, out T value)
{
if (stack == null)
throw new ArgumentNullException("stack");
value = stack.Peek();
return stack.Pop();
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 9f34ddd268be4f129abea2667eff4185
timeCreated: 1710758528
@@ -0,0 +1,45 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.ObjectModel;
namespace Unity.CodeEditor.Utils
{
/// <summary>
/// A collection that cannot contain null values.
/// </summary>
internal class NullSafeCollection<T> : Collection<T> where T : class
{
/// <inheritdoc/>
protected override void InsertItem(int index, T item)
{
if (item == null)
throw new ArgumentNullException(nameof(item));
base.InsertItem(index, item);
}
/// <inheritdoc/>
protected override void SetItem(int index, T item)
{
if (item == null)
throw new ArgumentNullException(nameof(item));
base.SetItem(index, item);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 1e99e51622924592820f5d5c09296780
timeCreated: 1710774948
@@ -0,0 +1,86 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.ObjectModel;
namespace Unity.CodeEditor.Utils
{
/// <summary>
/// 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.
/// </summary>
internal sealed class ObserveAddRemoveCollection<T> : Collection<T>
{
private readonly Action<T> _onAdd;
private readonly Action<T> _onRemove;
/// <summary>
/// Creates a new ObserveAddRemoveCollection using the specified callbacks.
/// </summary>
internal ObserveAddRemoveCollection(Action<T> onAdd, Action<T> onRemove)
{
_onAdd = onAdd ?? throw new ArgumentNullException(nameof(onAdd));
_onRemove = onRemove ?? throw new ArgumentNullException(nameof(onRemove));
}
/// <inheritdoc/>
protected override void ClearItems()
{
if (_onRemove != null)
{
foreach (T val in this)
_onRemove(val);
}
base.ClearItems();
}
/// <inheritdoc/>
protected override void InsertItem(int index, T item)
{
_onAdd?.Invoke(item);
base.InsertItem(index, item);
}
/// <inheritdoc/>
protected override void RemoveItem(int index)
{
_onRemove?.Invoke(this[index]);
base.RemoveItem(index);
}
/// <inheritdoc/>
protected override void SetItem(int index, T item)
{
_onRemove?.Invoke(this[index]);
try
{
_onAdd?.Invoke(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)
RemoveAt(index);
throw;
}
base.SetItem(index, item);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: c14f63df55204483b94566ff24521e70
timeCreated: 1710774960
@@ -0,0 +1,109 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Drawing;
using UnityEngine;
namespace Unity.CodeEditor.Utils
{
/// <summary>
/// Contains static helper methods for aligning stuff on a whole number of pixels.
/// </summary>
internal static class PixelSnapHelpers
{
/// <summary>
/// Gets the pixel size on the screen containing visual.
/// This method does not take transforms on visual into account.
/// </summary>
internal static Vector2 GetPixelSize(object visual)
{
if (visual == null)
throw new ArgumentNullException(nameof(visual));
// TODO-avedit
//PresentationSource source = PresentationSource.FromVisual(visual);
//if (source != null) {
// Matrix matrix = source.CompositionTarget.TransformFromDevice;
// return new Size(matrix.M11, matrix.M22);
//} else {
return new Vector2(1, 1);
//}
}
/// <summary>
/// Aligns <paramref name="value"/> on the next middle of a pixel.
/// </summary>
/// <param name="value">The value that should be aligned</param>
/// <param name="pixelSize">The size of one pixel</param>
internal static float PixelAlign(float value, float pixelSize)
{
// 0 -> 0.5
// 0.1 -> 0.5
// 0.5 -> 0.5
// 0.9 -> 0.5
// 1 -> 1.5
return pixelSize * ((float)Math.Round((value / pixelSize) + 0.5f, MidpointRounding.AwayFromZero) - 0.5f);
}
/// <summary>
/// Aligns the borders of rect on the middles of pixels.
/// </summary>
internal static Rect PixelAlign(Rect rect, Vector2 pixelSize)
{
var x = PixelAlign(rect.x, pixelSize.x);
var y = PixelAlign(rect.y, pixelSize.y);
var width = Round(rect.width, pixelSize.x);
var height = Round(rect.height, pixelSize.y);
return new Rect(x, y, width, height);
}
/// <summary>
/// Rounds <paramref name="point"/> to whole number of pixels.
/// </summary>
internal static Point Round(Point point, Vector2 pixelSize)
{
return new Point((int)Round(point.X, pixelSize.x), (int)Round(point.Y, pixelSize.y));
}
/// <summary>
/// Rounds val to whole number of pixels.
/// </summary>
internal static Rect Round(Rect rect, Vector2 pixelSize)
{
return new Rect((float)Round(rect.x, pixelSize.x), (float)Round(rect.y, pixelSize.y),
(float)Round(rect.width, pixelSize.x), (float)Round(rect.height, pixelSize.y));
}
/// <summary>
/// Rounds <paramref name="value"/> to a whole number of pixels.
/// </summary>
internal static float Round(double value, double pixelSize)
{
return (float)(pixelSize * Math.Round(value / pixelSize, MidpointRounding.AwayFromZero));
}
/// <summary>
/// Rounds <paramref name="value"/> to an whole odd number of pixels.
/// </summary>
internal static double RoundToOdd(float value, float pixelSize)
{
return Round(value - pixelSize, pixelSize * 2) + pixelSize;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 3fcf00e98ccc48b9beb80ae65c586683
timeCreated: 1710764729
@@ -0,0 +1,32 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System.ComponentModel;
namespace Unity.CodeEditor.Utils
{
/// <summary>
/// WeakEventManager for INotifyPropertyChanged.PropertyChanged.
/// </summary>
internal sealed class PropertyChangedWeakEventManager : WeakEventManagerBase<PropertyChangedWeakEventManager, INotifyPropertyChanged, PropertyChangedEventHandler, PropertyChangedEventArgs>
{
protected override void StartListening(INotifyPropertyChanged source) => source.PropertyChanged += DeliverEvent;
protected override void StopListening(INotifyPropertyChanged source) => source.PropertyChanged -= DeliverEvent;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8e419520e9d6e49c8bae5052896fe460
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,887 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Text;
namespace Unity.CodeEditor.Utils
{
/// <summary>
/// A kind of List&lt;T&gt;, but more efficient for random insertions/removal.
/// Also has cheap Clone() and SubRope() implementations.
/// </summary>
/// <remarks>
/// This class is not thread-safe: multiple concurrent write operations or writes concurrent to reads have undefined behaviour.
/// Concurrent reads, however, are safe.
/// However, clones of a rope are safe to use on other threads even though they share data with the original rope.
/// </remarks>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
internal sealed class Rope<T> : IList<T>, ICloneable
{
internal RopeNode<T> Root { get; set; }
internal Rope(RopeNode<T> root)
{
Root = root;
root.CheckInvariants();
}
/// <summary>
/// Creates a new rope representing the empty string.
/// </summary>
internal Rope()
{
// we'll construct the empty rope as a clone of an imaginary static empty rope
Root = RopeNode<T>.EmptyRopeNode;
Root.CheckInvariants();
}
/// <summary>
/// Creates a rope from the specified input.
/// This operation runs in O(N).
/// </summary>
/// <exception cref="ArgumentNullException">input is null.</exception>
internal Rope(IEnumerable<T> input)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
if (input is Rope<T> inputRope)
{
// clone ropes instead of copying them
inputRope.Root.Publish();
Root = inputRope.Root;
}
else
{
// ReSharper disable ConditionIsAlwaysTrueOrFalse
// ReSharper disable ExpressionIsAlwaysNull
// ReSharper disable SuspiciousTypeConversion.Global
#pragma warning disable IDE0019 // Use pattern matching
var text = input as string;
#pragma warning restore IDE0019 // Use pattern matching
// ReSharper restore SuspiciousTypeConversion.Global
if (text != null)
// ReSharper restore ConditionIsAlwaysTrueOrFalse
// ReSharper restore ExpressionIsAlwaysNull
// ReSharper disable HeuristicUnreachableCode
{
// if a string is IEnumerable<T>, then T must be char
((Rope<char>)(object)this).Root = CharRope.InitFromString(text);
}
// ReSharper restore HeuristicUnreachableCode
else
{
var arr = ToArray(input);
Root = RopeNode<T>.CreateFromArray(arr, 0, arr.Length);
}
}
Root.CheckInvariants();
}
/// <summary>
/// Creates a rope from a part of the array.
/// This operation runs in O(N).
/// </summary>
/// <exception cref="ArgumentNullException">input is null.</exception>
internal Rope(T[] array, int arrayIndex, int count)
{
VerifyArrayWithRange(array, arrayIndex, count);
Root = RopeNode<T>.CreateFromArray(array, arrayIndex, count);
Root.CheckInvariants();
}
/// <summary>
/// Creates a new rope that lazily initalizes its content.
/// </summary>
/// <param name="length">The length of the rope that will be lazily loaded.</param>
/// <param name="initializer">
/// The callback that provides the content for this rope.
/// <paramref name="initializer"/> will be called exactly once when the content of this rope is first requested.
/// It must return a rope with the specified length.
/// Because the initializer function is not called when a rope is cloned, and such clones may be used on another threads,
/// it is possible for the initializer callback to occur on any thread.
/// </param>
/// <remarks>
/// Any modifications inside the rope will also cause the content to be initialized.
/// However, insertions at the beginning and the end, as well as inserting this rope into another or
/// using the <see cref="Concat(Rope{T},Rope{T})"/> method, allows constructions of larger ropes where parts are
/// lazily loaded.
/// However, even methods like Concat may sometimes cause the initializer function to be called, e.g. when
/// two short ropes are concatenated.
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
internal Rope(int length, Func<Rope<T>> initializer)
{
if (initializer == null)
throw new ArgumentNullException(nameof(initializer));
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), length, "Length must not be negative");
Root = length == 0 ? RopeNode<T>.EmptyRopeNode : new FunctionNode<T>(length, initializer);
Root.CheckInvariants();
}
private static T[] ToArray(IEnumerable<T> input)
{
var arr = input as T[];
return arr ?? input.ToArray();
}
/// <summary>
/// Clones the rope.
/// This operation runs in linear time to the number of rope nodes touched since the last clone was created.
/// If you count the per-node cost to the operation modifying the rope (doing this doesn't increase the complexity of the modification operations);
/// the remainder of Clone() runs in O(1).
/// </summary>
/// <remarks>
/// This method counts as a read access and may be called concurrently to other read accesses.
/// </remarks>
public Rope<T> Clone()
{
// The Publish() call actually modifies this rope instance; but this modification is thread-safe
// as long as the tree structure doesn't change during the operation.
Root.Publish();
return new Rope<T>(Root);
}
object ICloneable.Clone()
{
return Clone();
}
/// <summary>
/// Resets the rope to an empty list.
/// Runs in O(1).
/// </summary>
public void Clear()
{
Root = RopeNode<T>.EmptyRopeNode;
OnChanged();
}
/// <summary>
/// Gets the length of the rope.
/// Runs in O(1).
/// </summary>
/// <remarks>
/// This method counts as a read access and may be called concurrently to other read accesses.
/// </remarks>
internal int Length => Root.Length;
/// <summary>
/// Gets the length of the rope.
/// Runs in O(1).
/// </summary>
/// <remarks>
/// This method counts as a read access and may be called concurrently to other read accesses.
/// </remarks>
public int Count => Root.Length;
/// <summary>
/// Inserts another rope into this rope.
/// Runs in O(lg N + lg M), plus a per-node cost as if <c>newElements.Clone()</c> was called.
/// </summary>
/// <exception cref="ArgumentNullException">newElements is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">index or length is outside the valid range.</exception>
internal void InsertRange(int index, Rope<T> newElements)
{
if (index < 0 || index > Length)
{
throw new ArgumentOutOfRangeException(nameof(index), index, "0 <= index <= " + Length.ToString(CultureInfo.InvariantCulture));
}
if (newElements == null)
throw new ArgumentNullException(nameof(newElements));
newElements.Root.Publish();
Root = Root.Insert(index, newElements.Root);
OnChanged();
}
/// <summary>
/// Inserts new elemetns into this rope.
/// Runs in O(lg N + M), where N is the length of this rope and M is the number of new elements.
/// </summary>
/// <exception cref="ArgumentNullException">newElements is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">index or length is outside the valid range.</exception>
internal void InsertRange(int index, IEnumerable<T> newElements)
{
if (newElements == null)
throw new ArgumentNullException(nameof(newElements));
if (newElements is Rope<T> newElementsRope)
{
InsertRange(index, newElementsRope);
}
else
{
var arr = ToArray(newElements);
InsertRange(index, arr, 0, arr.Length);
}
}
/// <summary>
/// Inserts new elements into this rope.
/// Runs in O(lg N + M), where N is the length of this rope and M is the number of new elements.
/// </summary>
/// <exception cref="ArgumentNullException">newElements is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">index or length is outside the valid range.</exception>
internal void InsertRange(int index, T[] array, int arrayIndex, int count)
{
if (index < 0 || index > Length)
{
throw new ArgumentOutOfRangeException(nameof(index), index, "0 <= index <= " + Length.ToString(CultureInfo.InvariantCulture));
}
VerifyArrayWithRange(array, arrayIndex, count);
if (count > 0)
{
Root = Root.Insert(index, array, arrayIndex, count);
OnChanged();
}
}
/// <summary>
/// Appends multiple elements to the end of this rope.
/// Runs in O(lg N + M), where N is the length of this rope and M is the number of new elements.
/// </summary>
/// <exception cref="ArgumentNullException">newElements is null.</exception>
internal void AddRange(IEnumerable<T> newElements)
{
InsertRange(Length, newElements);
}
/// <summary>
/// Appends another rope to the end of this rope.
/// Runs in O(lg N + lg M), plus a per-node cost as if <c>newElements.Clone()</c> was called.
/// </summary>
/// <exception cref="ArgumentNullException">newElements is null.</exception>
internal void AddRange(Rope<T> newElements)
{
InsertRange(Length, newElements);
}
/// <summary>
/// Appends new elements to the end of this rope.
/// Runs in O(lg N + M), where N is the length of this rope and M is the number of new elements.
/// </summary>
/// <exception cref="ArgumentNullException">array is null.</exception>
internal void AddRange(T[] array, int arrayIndex, int count)
{
InsertRange(Length, array, arrayIndex, count);
}
/// <summary>
/// Removes a range of elements from the rope.
/// Runs in O(lg N).
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">offset or length is outside the valid range.</exception>
internal void RemoveRange(int index, int count)
{
VerifyRange(index, count);
if (count > 0)
{
Root = Root.RemoveRange(index, count);
OnChanged();
}
}
/// <summary>
/// Copies a range of the specified array into the rope, overwriting existing elements.
/// Runs in O(lg N + M).
/// </summary>
internal void SetRange(int index, T[] array, int arrayIndex, int count)
{
VerifyRange(index, count);
VerifyArrayWithRange(array, arrayIndex, count);
if (count > 0)
{
Root = Root.StoreElements(index, array, arrayIndex, count);
OnChanged();
}
}
/// <summary>
/// Creates a new rope and initializes it with a part of this rope.
/// Runs in O(lg N) plus a per-node cost as if <c>this.Clone()</c> was called.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">offset or length is outside the valid range.</exception>
/// <remarks>
/// This method counts as a read access and may be called concurrently to other read accesses.
/// </remarks>
internal Rope<T> GetRange(int index, int count)
{
VerifyRange(index, count);
var newRope = Clone();
var endIndex = index + count;
newRope.RemoveRange(endIndex, newRope.Length - endIndex);
newRope.RemoveRange(0, index);
return newRope;
}
/*
#region Equality
/// <summary>
/// Gets whether the two ropes have the same content.
/// Runs in O(N + M).
/// </summary>
/// <remarks>
/// This method counts as a read access and may be called concurrently to other read accesses.
/// </remarks>
internal bool Equals(Rope other)
{
if (other == null)
return false;
// quick detection for ropes that are clones of each other:
if (other.root == this.root)
return true;
if (other.Length != this.Length)
return false;
using (RopeTextReader a = new RopeTextReader(this, false)) {
using (RopeTextReader b = new RopeTextReader(other, false)) {
int charA, charB;
do {
charA = a.Read();
charB = b.Read();
if (charA != charB)
return false;
} while (charA != -1);
return true;
}
}
}
/// <summary>
/// Gets whether two ropes have the same content.
/// Runs in O(N + M).
/// </summary>
public override bool Equals(object obj)
{
return Equals(obj as Rope);
}
/// <summary>
/// Calculates the hash code of the rope's content.
/// Runs in O(N).
/// </summary>
/// <remarks>
/// This method counts as a read access and may be called concurrently to other read accesses.
/// </remarks>
public override int GetHashCode()
{
int hashcode = 0;
using (RopeTextReader reader = new RopeTextReader(this, false)) {
unchecked {
int val;
while ((val = reader.Read()) != -1) {
hashcode = hashcode * 31 + val;
}
}
}
return hashcode;
}
#endregion
*/
/// <summary>
/// Concatenates two ropes. The input ropes are not modified.
/// Runs in O(lg N + lg M).
/// </summary>
/// <remarks>
/// This method counts as a read access and may be called concurrently to other read accesses.
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")]
internal static Rope<T> Concat(Rope<T> left, Rope<T> right)
{
if (left == null)
throw new ArgumentNullException(nameof(left));
if (right == null)
throw new ArgumentNullException(nameof(right));
left.Root.Publish();
right.Root.Publish();
return new Rope<T>(RopeNode<T>.Concat(left.Root, right.Root));
}
/// <summary>
/// Concatenates multiple ropes. The input ropes are not modified.
/// </summary>
/// <remarks>
/// This method counts as a read access and may be called concurrently to other read accesses.
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")]
internal static Rope<T> Concat(params Rope<T>[] ropes)
{
if (ropes == null)
throw new ArgumentNullException(nameof(ropes));
var result = new Rope<T>();
foreach (var r in ropes)
result.AddRange(r);
return result;
}
#region Caches / Changed event
internal struct RopeCacheEntry
{
internal RopeNode<T> Node { get; }
internal int NodeStartIndex { get; }
internal RopeCacheEntry(RopeNode<T> node, int nodeStartOffset)
{
Node = node;
NodeStartIndex = nodeStartOffset;
}
internal bool IsInside(int offset)
{
return offset >= NodeStartIndex && offset < NodeStartIndex + Node.Length;
}
}
// cached pointer to 'last used node', used to speed up accesses by index that are close together
private volatile ImmutableStack<RopeCacheEntry> _lastUsedNodeStack;
internal void OnChanged()
{
_lastUsedNodeStack = null;
Root.CheckInvariants();
}
#endregion
#region GetChar / SetChar
/// <summary>
/// Gets/Sets a single character.
/// Runs in O(lg N) for random access. Sequential read-only access benefits from a special optimization and runs in amortized O(1).
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">Offset is outside the valid range (0 to Length-1).</exception>
/// <remarks>
/// The getter counts as a read access and may be called concurrently to other read accesses.
/// </remarks>
public T this[int index]
{
get
{
// use unsigned integers - this way negative values for index overflow and can be tested for with the same check
if (unchecked((uint)index >= (uint)Length))
{
throw new ArgumentOutOfRangeException(nameof(index), index, "0 <= index < " + Length.ToString(CultureInfo.InvariantCulture));
}
var entry = FindNodeUsingCache(index).PeekOrDefault();
return entry.Node.Contents[index - entry.NodeStartIndex];
}
set
{
if (index < 0 || index >= Length)
{
throw new ArgumentOutOfRangeException(nameof(index), index, "0 <= index < " + Length.ToString(CultureInfo.InvariantCulture));
}
Root = Root.SetElement(index, value);
OnChanged();
/* Here's a try at implementing the setter using the cached node stack (UNTESTED code!).
* However I don't use the code because it's complicated and doesn't integrate correctly with change notifications.
* Instead, I'll use the much easier to understand recursive solution.
* Oh, and it also doesn't work correctly with function nodes.
ImmutableStack<RopeCacheEntry> nodeStack = FindNodeUsingCache(offset);
RopeCacheEntry entry = nodeStack.Peek();
if (!entry.node.isShared) {
entry.node.contents[offset - entry.nodeStartOffset] = value;
// missing: clear the caches except for the node stack cache (e.g. ToString() cache?)
} else {
RopeNode oldNode = entry.node;
RopeNode newNode = oldNode.Clone();
newNode.contents[offset - entry.nodeStartOffset] = value;
for (nodeStack = nodeStack.Pop(); !nodeStack.IsEmpty; nodeStack = nodeStack.Pop()) {
RopeNode parentNode = nodeStack.Peek().node;
RopeNode newParentNode = parentNode.CloneIfShared();
if (newParentNode.left == oldNode) {
newParentNode.left = newNode;
} else {
Debug.Assert(newParentNode.right == oldNode);
newParentNode.right = newNode;
}
if (parentNode == newParentNode) {
// we were able to change the existing node (it was not shared);
// there's no reason to go further upwards
ClearCacheOnModification();
return;
} else {
oldNode = parentNode;
newNode = newParentNode;
}
}
// we reached the root of the rope.
Debug.Assert(root == oldNode);
root = newNode;
ClearCacheOnModification();
}*/
}
}
internal ImmutableStack<RopeCacheEntry> FindNodeUsingCache(int index)
{
Debug.Assert(index >= 0 && index < Length);
// thread safety: fetch stack into local variable
var stack = _lastUsedNodeStack;
var oldStack = stack;
if (stack == null)
{
stack = ImmutableStack<RopeCacheEntry>.Empty.Push(new RopeCacheEntry(Root, 0));
}
while (!stack.PeekOrDefault().IsInside(index))
stack = stack.Pop();
while (true)
{
var entry = stack.PeekOrDefault();
// check if we've reached a leaf or function node
if (entry.Node.Height == 0)
{
if (entry.Node.Contents == null)
{
// this is a function node - go down into its subtree
entry = new RopeCacheEntry(entry.Node.GetContentNode(), entry.NodeStartIndex);
// entry is now guaranteed NOT to be another function node
}
if (entry.Node.Contents != null)
{
// this is a node containing actual content, so we're done
break;
}
}
// go down towards leaves
stack = stack.Push(index - entry.NodeStartIndex >= entry.Node.Left.Length
? new RopeCacheEntry(entry.Node.Right, entry.NodeStartIndex + entry.Node.Left.Length)
: new RopeCacheEntry(entry.Node.Left, entry.NodeStartIndex));
}
// write back stack to volatile cache variable
// (in multithreaded access, it doesn't matter which of the threads wins - it's just a cache)
if (oldStack != stack)
{
// no need to write when we the cache variable didn't change
_lastUsedNodeStack = stack;
}
// this method guarantees that it finds a leaf node
Debug.Assert(stack.Peek().Node.Contents != null);
return stack;
}
#endregion
#region ToString / WriteTo
internal void VerifyRange(int startIndex, int length)
{
if (startIndex < 0 || startIndex > Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), startIndex, "0 <= startIndex <= " + Length.ToString(CultureInfo.InvariantCulture));
}
if (length < 0 || startIndex + length > Length)
{
throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, startIndex(" + startIndex + ")+length <= " + Length.ToString(CultureInfo.InvariantCulture));
}
}
internal static void VerifyArrayWithRange(T[] array, int arrayIndex, int count)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, "0 <= arrayIndex <= " + array.Length.ToString(CultureInfo.InvariantCulture));
}
if (count < 0 || arrayIndex + count > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(count), count, "0 <= length, arrayIndex(" + arrayIndex + ")+count <= " + array.Length.ToString(CultureInfo.InvariantCulture));
}
}
/// <summary>
/// Creates a string from the rope. Runs in O(N).
/// </summary>
/// <returns>A string consisting of all elements in the rope as comma-separated list in {}.
/// As a special case, Rope&lt;char&gt; will return its contents as string without any additional separators or braces,
/// so it can be used like StringBuilder.ToString().</returns>
/// <remarks>
/// This method counts as a read access and may be called concurrently to other read accesses.
/// </remarks>
public override string ToString()
{
#pragma warning disable IDE0019 // Use pattern matching
var charRope = this as Rope<char>;
#pragma warning restore IDE0019 // Use pattern matching
if (charRope != null)
{
return charRope.ToString(0, Length);
}
var b = new StringBuilder();
foreach (var element in this)
{
if (b.Length == 0)
b.Append('{');
else
b.Append(", ");
b.Append(element);
}
b.Append('}');
return b.ToString();
}
internal string GetTreeAsString()
{
#if DEBUG
return Root.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
#endregion
bool ICollection<T>.IsReadOnly => false;
/// <summary>
/// Finds the first occurance of item.
/// Runs in O(N).
/// </summary>
/// <returns>The index of the first occurance of item, or -1 if it cannot be found.</returns>
/// <remarks>
/// This method counts as a read access and may be called concurrently to other read accesses.
/// </remarks>
public int IndexOf(T item)
{
return IndexOf(item, 0, Length);
}
/// <summary>
/// Gets the index of the first occurrence the specified item.
/// </summary>
/// <param name="item">Item to search for.</param>
/// <param name="startIndex">Start index of the search.</param>
/// <param name="count">Length of the area to search.</param>
/// <returns>The first index where the item was found; or -1 if no occurrence was found.</returns>
/// <remarks>
/// This method counts as a read access and may be called concurrently to other read accesses.
/// </remarks>
public int IndexOf(T item, int startIndex, int count)
{
VerifyRange(startIndex, count);
while (count > 0)
{
var entry = FindNodeUsingCache(startIndex).PeekOrDefault();
var contents = entry.Node.Contents;
var startWithinNode = startIndex - entry.NodeStartIndex;
var nodeLength = Math.Min(entry.Node.Length, startWithinNode + count);
var r = Array.IndexOf(contents, item, startWithinNode, nodeLength - startWithinNode);
if (r >= 0)
return entry.NodeStartIndex + r;
count -= nodeLength - startWithinNode;
startIndex = entry.NodeStartIndex + nodeLength;
}
return -1;
}
/// <summary>
/// Gets the index of the last occurrence of the specified item in this rope.
/// </summary>
internal int LastIndexOf(T item)
{
return LastIndexOf(item, 0, Length);
}
/// <summary>
/// Gets the index of the last occurrence of the specified item in this rope.
/// </summary>
/// <param name="item">The search item</param>
/// <param name="startIndex">Start index of the area to search.</param>
/// <param name="count">Length of the area to search.</param>
/// <returns>The last index where the item was found; or -1 if no occurrence was found.</returns>
/// <remarks>The search proceeds backwards from (startIndex+count) to startIndex.
/// This is different than the meaning of the parameters on Array.LastIndexOf!</remarks>
internal int LastIndexOf(T item, int startIndex, int count)
{
VerifyRange(startIndex, count);
var comparer = EqualityComparer<T>.Default;
for (var i = startIndex + count - 1; i >= startIndex; i--)
{
if (comparer.Equals(this[i], item))
return i;
}
return -1;
}
/// <summary>
/// Inserts the item at the specified index in the rope.
/// Runs in O(lg N).
/// </summary>
public void Insert(int index, T item)
{
InsertRange(index, new[] { item }, 0, 1);
}
/// <summary>
/// Removes a single item from the rope.
/// Runs in O(lg N).
/// </summary>
public void RemoveAt(int index)
{
RemoveRange(index, 1);
}
/// <summary>
/// Appends the item at the end of the rope.
/// Runs in O(lg N).
/// </summary>
public void Add(T item)
{
InsertRange(Length, new[] { item }, 0, 1);
}
/// <summary>
/// Searches the item in the rope.
/// Runs in O(N).
/// </summary>
/// <remarks>
/// This method counts as a read access and may be called concurrently to other read accesses.
/// </remarks>
public bool Contains(T item)
{
return IndexOf(item) >= 0;
}
/// <summary>
/// Copies the whole content of the rope into the specified array.
/// Runs in O(N).
/// </summary>
/// <remarks>
/// This method counts as a read access and may be called concurrently to other read accesses.
/// </remarks>
public void CopyTo(T[] array, int arrayIndex)
{
CopyTo(0, array, arrayIndex, Length);
}
/// <summary>
/// Copies the a part of the rope into the specified array.
/// Runs in O(lg N + M).
/// </summary>
/// <remarks>
/// This method counts as a read access and may be called concurrently to other read accesses.
/// </remarks>
public void CopyTo(int index, T[] array, int arrayIndex, int count)
{
VerifyRange(index, count);
VerifyArrayWithRange(array, arrayIndex, count);
Root.CopyTo(index, array, arrayIndex, count);
}
/// <summary>
/// Removes the first occurance of an item from the rope.
/// Runs in O(N).
/// </summary>
public bool Remove(T item)
{
var index = IndexOf(item);
if (index >= 0)
{
RemoveAt(index);
return true;
}
return false;
}
/// <summary>
/// Retrieves an enumerator to iterate through the rope.
/// The enumerator will reflect the state of the rope from the GetEnumerator() call, further modifications
/// to the rope will not be visible to the enumerator.
/// </summary>
/// <remarks>
/// This method counts as a read access and may be called concurrently to other read accesses.
/// </remarks>
public IEnumerator<T> GetEnumerator()
{
Root.Publish();
return Enumerate(Root);
}
/// <summary>
/// Creates an array and copies the contents of the rope into it.
/// Runs in O(N).
/// </summary>
/// <remarks>
/// This method counts as a read access and may be called concurrently to other read accesses.
/// </remarks>
internal T[] ToArray()
{
var arr = new T[Length];
Root.CopyTo(0, arr, 0, arr.Length);
return arr;
}
/// <summary>
/// Creates an array and copies the contents of the rope into it.
/// Runs in O(N).
/// </summary>
/// <remarks>
/// This method counts as a read access and may be called concurrently to other read accesses.
/// </remarks>
internal T[] ToArray(int startIndex, int count)
{
VerifyRange(startIndex, count);
var arr = new T[count];
CopyTo(startIndex, arr, 0, count);
return arr;
}
private static IEnumerator<T> Enumerate(RopeNode<T> node)
{
var stack = new Stack<RopeNode<T>>();
while (node != null)
{
// go to leftmost node, pushing the right parts that we'll have to visit later
while (node.Contents == null)
{
if (node.Height == 0)
{
// go down into function nodes
node = node.GetContentNode();
continue;
}
Debug.Assert(node.Right != null);
stack.Push(node.Right);
node = node.Left;
}
// yield contents of leaf node
for (var i = 0; i < node.Length; i++)
{
yield return node.Contents[i];
}
// go up to the next node not visited yet
node = stack.Count > 0 ? stack.Pop() : null;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: be335b59f9a9647afa183fd170bab963
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,712 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Diagnostics;
using System.Text;
namespace Unity.CodeEditor.Utils
{
/// <summary>
/// Class used to represent a node in the tree.
/// </summary>
/// <remarks>
/// There are three types of nodes:
/// Concat nodes: height&gt;0, left!=null, right!=null, contents==null
/// Leaf nodes: height==0, left==null, right==null, contents!=null
/// Function nodes: height==0, left==null, right==null, contents==null, are of type FunctionNode&lt;T&gt;
/// </remarks>
/// <typeparam name="T"></typeparam>
internal class RopeNode<T>
{
internal const int NodeSize = 256;
internal static RopeNode<T> EmptyRopeNode { get; } = new RopeNode<T>(isShared: true) { Contents = new T[NodeSize] };
// Fields for pointers to sub-nodes. Only non-null for concat nodes (height>=1)
internal RopeNode<T> Left { get; set; }
internal RopeNode<T> Right { get; set; }
// specifies whether this node is shared between multiple ropes
// the total length of all text in this subtree
private volatile bool _isShared;
internal int Length;
// the height of this subtree: 0 for leaf nodes; 1+max(left.height,right.height) for concat nodes
internal byte Height;
// The character data. Only non-null for leaf nodes (height=0) that aren't function nodes.
internal T[] Contents { get; set; }
internal RopeNode() { }
protected RopeNode(bool isShared)
{
_isShared = isShared;
}
internal int Balance => Right.Height - Left.Height;
[Conditional("DATACONSISTENCYTEST")]
internal void CheckInvariants()
{
if (Height == 0)
{
Debug.Assert(Left == null && Right == null);
if (Contents == null)
{
Debug.Assert(this is FunctionNode<T>);
Debug.Assert(Length > 0);
Debug.Assert(_isShared);
}
else
{
Debug.Assert(Contents != null && Contents.Length == NodeSize);
Debug.Assert(Length >= 0 && Length <= NodeSize);
}
}
else
{
Debug.Assert(Left != null && Right != null);
Debug.Assert(Contents == null);
Debug.Assert(Length == Left.Length + Right.Length);
Debug.Assert(Height == 1 + Math.Max(Left.Height, Right.Height));
Debug.Assert(Math.Abs(Balance) <= 1);
// this is an additional invariant that forces the tree to combine small leafs to prevent excessive memory usage:
Debug.Assert(Length > NodeSize);
// note that this invariant ensures that all nodes except for the empty rope's single node have at least length 1
if (_isShared)
Debug.Assert(Left._isShared && Right._isShared);
Left.CheckInvariants();
Right.CheckInvariants();
}
}
internal RopeNode<T> Clone()
{
if (Height == 0)
{
// If a function node needs cloning, we'll evaluate it.
if (Contents == null)
return GetContentNode().Clone();
var newContents = new T[NodeSize];
Contents.CopyTo(newContents, 0);
return new RopeNode<T>
{
Length = Length,
Contents = newContents
};
}
return new RopeNode<T>
{
Left = Left,
Right = Right,
Length = Length,
Height = Height
};
}
internal RopeNode<T> CloneIfShared()
{
if (_isShared)
return Clone();
return this;
}
internal void Publish()
{
if (!_isShared)
{
Left?.Publish();
Right?.Publish();
// it's important that isShared=true is set at the end:
// Publish() must not return until the whole subtree is marked as shared, even when
// Publish() is called concurrently.
_isShared = true;
}
}
internal static RopeNode<T> CreateFromArray(T[] arr, int index, int length)
{
if (length == 0)
{
return EmptyRopeNode;
}
var node = CreateNodes(length);
return node.StoreElements(0, arr, index, length);
}
internal static RopeNode<T> CreateNodes(int totalLength)
{
var leafCount = (totalLength + NodeSize - 1) / NodeSize;
return CreateNodes(leafCount, totalLength);
}
private static RopeNode<T> CreateNodes(int leafCount, int totalLength)
{
Debug.Assert(leafCount > 0);
Debug.Assert(totalLength > 0);
var result = new RopeNode<T> { Length = totalLength };
if (leafCount == 1)
{
result.Contents = new T[NodeSize];
}
else
{
var rightSide = leafCount / 2;
var leftSide = leafCount - rightSide;
var leftLength = leftSide * NodeSize;
result.Left = CreateNodes(leftSide, leftLength);
result.Right = CreateNodes(rightSide, totalLength - leftLength);
result.Height = (byte)(1 + Math.Max(result.Left.Height, result.Right.Height));
}
return result;
}
/// <summary>
/// Balances this node and recomputes the 'height' field.
/// This method assumes that the children of this node are already balanced and have an up-to-date 'height' value.
/// </summary>
internal void Rebalance()
{
// Rebalance() shouldn't be called on shared nodes - it's only called after modifications!
Debug.Assert(!_isShared);
// leaf nodes are always balanced (we don't use 'height' to detect leaf nodes here
// because Balance is supposed to recompute the height).
if (Left == null)
return;
// ensure we didn't miss a MergeIfPossible step
Debug.Assert(Length > NodeSize);
// We need to loop until it's balanced. Rotations might cause two small leaves to combine to a larger one,
// which changes the height and might mean we need additional balancing steps.
while (Math.Abs(Balance) > 1)
{
// AVL balancing
// note: because we don't care about the identity of concat nodes, this works a little different than usual
// tree rotations: in our implementation, the "this" node will stay at the top, only its children are rearranged
if (Balance > 1)
{
if (Right.Balance < 0)
{
Right = Right.CloneIfShared();
Right.RotateRight();
}
RotateLeft();
// If 'this' was unbalanced by more than 2, we've shifted some of the inbalance to the left node; so rebalance that.
Left.Rebalance();
}
else if (Balance < -1)
{
if (Left.Balance > 0)
{
Left = Left.CloneIfShared();
Left.RotateLeft();
}
RotateRight();
// If 'this' was unbalanced by more than 2, we've shifted some of the inbalance to the right node; so rebalance that.
Right.Rebalance();
}
}
Debug.Assert(Math.Abs(Balance) <= 1);
Height = (byte)(1 + Math.Max(Left.Height, Right.Height));
}
private void RotateLeft()
{
Debug.Assert(!_isShared);
/* Rotate tree to the left
*
* this this
* / \ / \
* A right ===> left C
* / \ / \
* B C A B
*/
var a = Left;
var b = Right.Left;
var c = Right.Right;
// reuse right concat node, if possible
Left = Right._isShared ? new RopeNode<T>() : Right;
Left.Left = a;
Left.Right = b;
Left.Length = a.Length + b.Length;
Left.Height = (byte)(1 + Math.Max(a.Height, b.Height));
Right = c;
Left.MergeIfPossible();
}
private void RotateRight()
{
Debug.Assert(!_isShared);
/* Rotate tree to the right
*
* this this
* / \ / \
* left C ===> A right
* / \ / \
* A B B C
*/
var a = Left.Left;
var b = Left.Right;
var c = Right;
// reuse left concat node, if possible
Right = Left._isShared ? new RopeNode<T>() : Left;
Right.Left = b;
Right.Right = c;
Right.Length = b.Length + c.Length;
Right.Height = (byte)(1 + Math.Max(b.Height, c.Height));
Left = a;
Right.MergeIfPossible();
}
private void MergeIfPossible()
{
Debug.Assert(!_isShared);
if (Length <= NodeSize)
{
// Convert this concat node to leaf node.
// We know left and right cannot be concat nodes (they would have merged already),
// but they could be function nodes.
Height = 0;
var lengthOnLeftSide = Left.Length;
if (Left._isShared)
{
Contents = new T[NodeSize];
Left.CopyTo(0, Contents, 0, lengthOnLeftSide);
}
else
{
// must be a leaf node: function nodes are always marked shared
Debug.Assert(Left.Contents != null);
// steal buffer from left side
Contents = Left.Contents;
#if DEBUG
// In debug builds, explicitly mark left node as 'damaged' - but no one else should be using it
// because it's not shared.
Left.Contents = Array.Empty<T>();
#endif
}
Left = null;
Right.CopyTo(0, Contents, lengthOnLeftSide, Right.Length);
Right = null;
}
}
/// <summary>
/// Copies from the array to this node.
/// </summary>
internal RopeNode<T> StoreElements(int index, T[] array, int arrayIndex, int count)
{
var result = CloneIfShared();
// result cannot be function node after a call to Clone()
if (result.Height == 0)
{
// leaf node:
Array.Copy(array, arrayIndex, result.Contents, index, count);
}
else
{
// concat node:
if (index + count <= result.Left.Length)
{
result.Left = result.Left.StoreElements(index, array, arrayIndex, count);
}
else if (index >= Left.Length)
{
result.Right = result.Right.StoreElements(index - result.Left.Length, array, arrayIndex, count);
}
else
{
var amountInLeft = result.Left.Length - index;
result.Left = result.Left.StoreElements(index, array, arrayIndex, amountInLeft);
result.Right = result.Right.StoreElements(0, array, arrayIndex + amountInLeft, count - amountInLeft);
}
result.Rebalance(); // tree layout might have changed if function nodes were replaced with their content
}
return result;
}
/// <summary>
/// Copies from this node to the array.
/// </summary>
internal void CopyTo(int index, T[] array, int arrayIndex, int count)
{
if (Height == 0)
{
if (Contents == null)
{
// function node
GetContentNode().CopyTo(index, array, arrayIndex, count);
}
else
{
// leaf node
Array.Copy(Contents, index, array, arrayIndex, count);
}
}
else
{
// concat node
if (index + count <= Left.Length)
{
Left.CopyTo(index, array, arrayIndex, count);
}
else if (index >= Left.Length)
{
Right.CopyTo(index - Left.Length, array, arrayIndex, count);
}
else
{
var amountInLeft = Left.Length - index;
Left.CopyTo(index, array, arrayIndex, amountInLeft);
Right.CopyTo(0, array, arrayIndex + amountInLeft, count - amountInLeft);
}
}
}
internal RopeNode<T> SetElement(int offset, T value)
{
var result = CloneIfShared();
// result of CloneIfShared() is leaf or concat node
if (result.Height == 0)
{
result.Contents[offset] = value;
}
else
{
if (offset < result.Left.Length)
{
result.Left = result.Left.SetElement(offset, value);
}
else
{
result.Right = result.Right.SetElement(offset - result.Left.Length, value);
}
result.Rebalance(); // tree layout might have changed if function nodes were replaced with their content
}
return result;
}
internal static RopeNode<T> Concat(RopeNode<T> left, RopeNode<T> right)
{
if (left.Length == 0)
return right;
if (right.Length == 0)
return left;
if (left.Length + right.Length <= NodeSize)
{
left = left.CloneIfShared();
// left is guaranteed to be leaf node after cloning:
// - it cannot be function node (due to clone)
// - it cannot be concat node (too short)
right.CopyTo(0, left.Contents, left.Length, right.Length);
left.Length += right.Length;
return left;
}
var concatNode = new RopeNode<T>
{
Left = left,
Right = right,
Length = left.Length + right.Length
};
concatNode.Rebalance();
return concatNode;
}
/// <summary>
/// Splits this leaf node at offset and returns a new node with the part of the text after offset.
/// </summary>
private RopeNode<T> SplitAfter(int offset)
{
Debug.Assert(!_isShared && Height == 0 && Contents != null);
var newPart = new RopeNode<T>
{
Contents = new T[NodeSize],
Length = Length - offset
};
Array.Copy(Contents, offset, newPart.Contents, 0, newPart.Length);
Length = offset;
return newPart;
}
internal RopeNode<T> Insert(int offset, RopeNode<T> newElements)
{
if (offset == 0)
{
return Concat(newElements, this);
}
if (offset == Length)
{
return Concat(this, newElements);
}
// first clone this node (converts function nodes to leaf or concat nodes)
var result = CloneIfShared();
if (result.Height == 0)
{
// leaf node: we'll need to split this node
var left = result;
var right = left.SplitAfter(offset);
return Concat(Concat(left, newElements), right);
}
// concat node
if (offset < result.Left.Length)
{
result.Left = result.Left.Insert(offset, newElements);
}
else
{
result.Right = result.Right.Insert(offset - result.Left.Length, newElements);
}
result.Length += newElements.Length;
result.Rebalance();
return result;
}
internal RopeNode<T> Insert(int offset, T[] array, int arrayIndex, int count)
{
Debug.Assert(count > 0);
if (Length + count < RopeNode<char>.NodeSize)
{
var result = CloneIfShared();
// result must be leaf node (Clone never returns function nodes, too short for concat node)
var lengthAfterOffset = result.Length - offset;
var resultContents = result.Contents;
for (var i = lengthAfterOffset; i >= 0; i--)
{
resultContents[i + offset + count] = resultContents[i + offset];
}
Array.Copy(array, arrayIndex, resultContents, offset, count);
result.Length += count;
return result;
}
if (Height == 0)
{
// TODO: implement this more efficiently?
return Insert(offset, CreateFromArray(array, arrayIndex, count));
}
{
// this is a concat node (both leafs and function nodes are handled by the case above)
var result = CloneIfShared();
if (offset < result.Left.Length)
{
result.Left = result.Left.Insert(offset, array, arrayIndex, count);
}
else
{
result.Right = result.Right.Insert(offset - result.Left.Length, array, arrayIndex, count);
}
result.Length += count;
result.Rebalance();
return result;
}
}
internal RopeNode<T> RemoveRange(int index, int count)
{
Debug.Assert(count > 0);
// produce empty node when one node is deleted completely
if (index == 0 && count == Length)
return EmptyRopeNode;
var endIndex = index + count;
var result = CloneIfShared(); // convert function node to concat/leaf
if (result.Height == 0)
{
var remainingAfterEnd = result.Length - endIndex;
for (var i = 0; i < remainingAfterEnd; i++)
{
result.Contents[index + i] = result.Contents[endIndex + i];
}
result.Length -= count;
}
else
{
if (endIndex <= result.Left.Length)
{
// deletion is only within the left part
result.Left = result.Left.RemoveRange(index, count);
}
else if (index >= result.Left.Length)
{
// deletion is only within the right part
result.Right = result.Right.RemoveRange(index - result.Left.Length, count);
}
else
{
// deletion overlaps both parts
var deletionAmountOnLeftSide = result.Left.Length - index;
result.Left = result.Left.RemoveRange(index, deletionAmountOnLeftSide);
result.Right = result.Right.RemoveRange(0, count - deletionAmountOnLeftSide);
}
// The deletion might have introduced empty nodes. Those must be removed.
if (result.Left.Length == 0)
return result.Right;
if (result.Right.Length == 0)
return result.Left;
result.Length -= count;
result.MergeIfPossible();
result.Rebalance();
}
return result;
}
#region Debug Output
#if DEBUG
internal virtual void AppendTreeToString(StringBuilder b, int indent)
{
b.AppendLine(ToString());
indent += 2;
if (Left != null)
{
b.Append(' ', indent);
b.Append("L: ");
Left.AppendTreeToString(b, indent);
}
if (Right != null)
{
b.Append(' ', indent);
b.Append("R: ");
Right.AppendTreeToString(b, indent);
}
}
public override string ToString()
{
if (Contents != null)
{
#pragma warning disable IDE0019 // Use pattern matching
var charContents = Contents as char[];
#pragma warning restore IDE0019 // Use pattern matching
if (charContents != null)
return "[Leaf length=" + Length + ", isShared=" + _isShared + ", text=\"" + new string(charContents, 0, Length) + "\"]";
return "[Leaf length=" + Length + ", isShared=" + _isShared + "\"]";
}
return "[Concat length=" + Length + ", isShared=" + _isShared + ", height=" + Height + ", Balance=" + Balance + "]";
}
internal string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(b, 0);
return b.ToString();
}
#endif
#endregion
/// <summary>
/// Gets the root node of the subtree from a lazily evaluated function node.
/// Such nodes are always marked as shared.
/// GetContentNode() will return either a Concat or Leaf node, never another FunctionNode.
/// </summary>
internal virtual RopeNode<T> GetContentNode()
{
throw new InvalidOperationException("Called GetContentNode() on non-FunctionNode.");
}
}
internal sealed class FunctionNode<T> : RopeNode<T>
{
private Func<Rope<T>> _initializer;
private RopeNode<T> _cachedResults;
internal FunctionNode(int length, Func<Rope<T>> initializer) : base(isShared: true)
{
Debug.Assert(length > 0);
Debug.Assert(initializer != null);
Length = length;
_initializer = initializer;
// Function nodes are immediately shared, but cannot be cloned.
// This ensures we evaluate every initializer only once.
}
internal override RopeNode<T> GetContentNode()
{
lock (this)
{
if (_cachedResults == null)
{
if (_initializer == null)
throw new InvalidOperationException("Trying to load this node recursively; or: a previous call to a rope initializer failed.");
var initializerCopy = _initializer;
_initializer = null;
var resultRope = initializerCopy();
if (resultRope == null)
throw new InvalidOperationException("Rope initializer returned null.");
var resultNode = resultRope.Root;
resultNode.Publish(); // result is shared between returned rope and the rope containing this function node
if (resultNode.Length != Length)
throw new InvalidOperationException("Rope initializer returned rope with incorrect length.");
if (resultNode.Height == 0 && resultNode.Contents == null)
{
// ResultNode is another function node.
// We want to guarantee that GetContentNode() never returns function nodes, so we have to
// go down further in the tree.
_cachedResults = resultNode.GetContentNode();
}
else
{
_cachedResults = resultNode;
}
}
return _cachedResults;
}
}
#if DEBUG
internal override void AppendTreeToString(StringBuilder b, int indent)
{
RopeNode<T> resultNode;
lock (this)
{
b.AppendLine(ToString());
resultNode = _cachedResults;
}
indent += 2;
if (resultNode != null)
{
b.Append(' ', indent);
b.Append("C: ");
resultNode.AppendTreeToString(b, indent);
}
}
public override string ToString()
{
return "[FunctionNode length=" + Length + " initializerRan=" + (_initializer == null) + "]";
}
#endif
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0641486b650184309b79f60e69b8a796
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,120 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace Unity.CodeEditor.Utils
{
/// <summary>
/// TextReader implementation that reads text from a rope.
/// </summary>
internal sealed class RopeTextReader : TextReader
{
private readonly Stack<RopeNode<char>> _stack = new Stack<RopeNode<char>>();
private RopeNode<char> _currentNode;
private int _indexInsideNode;
/// <summary>
/// Creates a new RopeTextReader.
/// Internally, this method creates a Clone of the rope; so the text reader will always read through the old
/// version of the rope if it is modified. <seealso cref="Rope{T}.Clone()"/>
/// </summary>
internal RopeTextReader(Rope<char> rope)
{
if (rope == null)
throw new ArgumentNullException(nameof(rope));
// We force the user to iterate through a clone of the rope to keep the API contract of RopeTextReader simple
// (what happens when a rope is modified while iterating through it?)
rope.Root.Publish();
// special case for the empty rope:
// leave currentNode initialized to null (RopeTextReader doesn't support empty nodes)
if (rope.Length != 0) {
_currentNode = rope.Root;
GoToLeftMostLeaf();
}
}
private void GoToLeftMostLeaf()
{
while (_currentNode.Contents == null) {
if (_currentNode.Height == 0) {
// this is a function node - move to its contained rope
_currentNode = _currentNode.GetContentNode();
continue;
}
Debug.Assert(_currentNode.Right != null);
_stack.Push(_currentNode.Right);
_currentNode = _currentNode.Left;
}
Debug.Assert(_currentNode.Height == 0);
}
/// <inheritdoc/>
public override int Peek()
{
if (_currentNode == null)
return -1;
return _currentNode.Contents[_indexInsideNode];
}
/// <inheritdoc/>
public override int Read()
{
if (_currentNode == null)
return -1;
char result = _currentNode.Contents[_indexInsideNode++];
if (_indexInsideNode >= _currentNode.Length)
GoToNextNode();
return result;
}
private void GoToNextNode()
{
if (_stack.Count == 0) {
_currentNode = null;
} else {
_indexInsideNode = 0;
_currentNode = _stack.Pop();
GoToLeftMostLeaf();
}
}
/// <inheritdoc/>
public override int Read(char[] buffer, int index, int count)
{
if (_currentNode == null)
return 0;
int amountInCurrentNode = _currentNode.Length - _indexInsideNode;
if (count < amountInCurrentNode) {
Array.Copy(_currentNode.Contents, _indexInsideNode, buffer, index, count);
_indexInsideNode += count;
return count;
} else {
// read to end of current node
Array.Copy(_currentNode.Contents, _indexInsideNode, buffer, index, amountInCurrentNode);
GoToNextNode();
return amountInCurrentNode;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5657a4950f10e4c4ebafc41e8539ef61
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,109 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
namespace Unity.CodeEditor.Utils
{
/// <summary>
/// Represents a string with a segment.
/// Similar to System.ArraySegment&lt;T&gt;, but for strings instead of arrays.
/// </summary>
internal struct StringSegment : IEquatable<StringSegment>
{
/// <summary>
/// Creates a new StringSegment.
/// </summary>
internal StringSegment(string text, int offset, int count)
{
if (text == null)
throw new ArgumentNullException(nameof(text));
if (offset < 0 || offset > text.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (offset + count > text.Length)
throw new ArgumentOutOfRangeException(nameof(count));
Text = text;
Offset = offset;
Count = count;
}
/// <summary>
/// Creates a new StringSegment.
/// </summary>
internal StringSegment(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
Offset = 0;
Count = text.Length;
}
/// <summary>
/// Gets the string used for this segment.
/// </summary>
internal string Text { get; }
/// <summary>
/// Gets the start offset of the segment with the text.
/// </summary>
internal int Offset { get; }
/// <summary>
/// Gets the length of the segment.
/// </summary>
internal int Count { get; }
#region Equals and GetHashCode implementation
/// <inheritdoc/>
public override bool Equals(object obj)
{
if (obj is StringSegment)
return Equals((StringSegment)obj); // use Equals method below
return false;
}
/// <inheritdoc/>
public bool Equals(StringSegment other)
{
// add comparisions for all members here
return ReferenceEquals(Text, other.Text) && Offset == other.Offset && Count == other.Count;
}
/// <inheritdoc/>
public override int GetHashCode()
{
return Text.GetHashCode() ^ Offset ^ Count;
}
/// <summary>
/// Equality operator.
/// </summary>
public static bool operator ==(StringSegment left, StringSegment right)
{
return left.Equals(right);
}
/// <summary>
/// Inequality operator.
/// </summary>
public static bool operator !=(StringSegment left, StringSegment right)
{
return !left.Equals(right);
}
#endregion
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: a52c35f662f24edfa2eb9af08478b6d6
timeCreated: 1710767348
@@ -0,0 +1,71 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Globalization;
namespace Unity.CodeEditor.Utils
{
/// <summary>
/// Contains exception-throwing helper methods.
/// </summary>
internal static class ThrowUtil
{
/// <summary>
/// Throws an ArgumentNullException if <paramref name="val"/> is null; otherwise
/// returns val.
/// </summary>
/// <example>
/// Use this method to throw an ArgumentNullException when using parameters for base
/// constructor calls.
/// <code>
/// public VisualLineText(string text) : base(ThrowUtil.CheckNotNull(text, "text").Length)
/// </code>
/// </example>
internal static T CheckNotNull<T>(T val, string parameterName) where T : class
{
if (val == null)
throw new ArgumentNullException(parameterName);
return val;
}
internal static int CheckNotNegative(int val, string parameterName)
{
if (val < 0)
throw new ArgumentOutOfRangeException(parameterName, val, "value must not be negative");
return val;
}
internal static int CheckInRangeInclusive(int val, string parameterName, int lower, int upper)
{
if (val < lower || val > upper)
throw new ArgumentOutOfRangeException(parameterName, val, "Expected: " + lower.ToString(CultureInfo.InvariantCulture) + " <= " + parameterName + " <= " + upper.ToString(CultureInfo.InvariantCulture));
return val;
}
internal static InvalidOperationException NoDocumentAssigned()
{
return new InvalidOperationException("Document is null");
}
internal static InvalidOperationException NoValidCaretPosition()
{
return new InvalidOperationException("Could not find a valid caret position in the line");
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: ff7e226153604720b3e883e52ec9a606
timeCreated: 1710756082
@@ -0,0 +1,357 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
namespace Unity.CodeEditor.Utils
{
/// <summary>
/// WeakEventManager base class. Inspired by the WPF WeakEventManager class and the code in
/// https://social.msdn.microsoft.com/Forums/silverlight/en-US/34d85c3f-52ea-4adc-bb32-8297f5549042/command-binding-memory-leak?forum=silverlightbugs
/// </summary>
/// <remarks>Copied here from ReactiveUI due to bugs in its design (singleton instance for multiple events).</remarks>
/// <typeparam name="TEventManager"></typeparam>
/// <typeparam name="TEventSource">The type of the event source.</typeparam>
/// <typeparam name="TEventHandler">The type of the event handler.</typeparam>
/// <typeparam name="TEventArgs">The type of the event arguments.</typeparam>
internal abstract class WeakEventManagerBase<TEventManager, TEventSource, TEventHandler, TEventArgs>
where TEventManager : WeakEventManagerBase<TEventManager, TEventSource, TEventHandler, TEventArgs>, new()
{
// ReSharper disable once StaticMemberInGenericType
private static readonly object StaticSource = new object();
/// <summary>
/// Mapping between the target of the delegate (for example a Button) and the handler (EventHandler).
/// Windows Phone needs this, otherwise the event handler gets garbage collected.
/// </summary>
private readonly ConditionalWeakTable<object, List<Delegate>> _targetToEventHandler = new ConditionalWeakTable<object, List<Delegate>>();
/// <summary>
/// Mapping from the source of the event to the list of handlers. This is a CWT to ensure it does not leak the source of the event.
/// </summary>
private readonly ConditionalWeakTable<object, WeakHandlerList> _sourceToWeakHandlers = new ConditionalWeakTable<object, WeakHandlerList>();
private static readonly Lazy<TEventManager> CurrentLazy = new Lazy<TEventManager>(() => new TEventManager());
private static TEventManager Current => CurrentLazy.Value;
/// <summary>
/// Adds a weak reference to the handler and associates it with the source.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="handler">The handler.</param>
internal static void AddHandler(TEventSource source, TEventHandler handler)
{
Current.PrivateAddHandler(source, handler);
}
/// <summary>
/// Removes the association between the source and the handler.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="handler">The handler.</param>
internal static void RemoveHandler(TEventSource source, TEventHandler handler)
{
Current.PrivateRemoveHandler(source, handler);
}
/// <summary>
/// Delivers the event to the handlers registered for the source.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="args">The <see cref="TEventArgs"/> instance containing the event data.</param>
protected static void DeliverEvent(object sender, TEventArgs args)
{
Current.PrivateDeliverEvent(sender, args);
}
/// <summary>
/// Override this method to attach to an event.
/// </summary>
/// <param name="source">The source.</param>
protected abstract void StartListening(TEventSource source);
/// <summary>
/// Override this method to detach from an event.
/// </summary>
/// <param name="source">The source.</param>
protected abstract void StopListening(TEventSource source);
protected void PrivateAddHandler(TEventSource source, TEventHandler handler)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (handler == null) throw new ArgumentNullException(nameof(handler));
if (!typeof(TEventHandler).GetTypeInfo().IsSubclassOf(typeof(Delegate)))
{
throw new ArgumentException("Handler must be Delegate type");
}
AddWeakHandler(source, handler);
AddTargetHandler(handler);
}
private void AddWeakHandler(TEventSource source, TEventHandler handler)
{
if (_sourceToWeakHandlers.TryGetValue(source, out var weakHandlers))
{
// clone list if we are currently delivering an event
if (weakHandlers.IsDeliverActive)
{
weakHandlers = weakHandlers.Clone();
_sourceToWeakHandlers.Remove(source);
_sourceToWeakHandlers.Add(source, weakHandlers);
}
weakHandlers.AddWeakHandler(source, handler);
}
else
{
weakHandlers = new WeakHandlerList();
weakHandlers.AddWeakHandler(source, handler);
_sourceToWeakHandlers.Add(source, weakHandlers);
StartListening(source);
}
Purge(source);
}
private void AddTargetHandler(TEventHandler handler)
{
var @delegate = handler as Delegate;
var key = @delegate?.Target ?? StaticSource;
if (_targetToEventHandler.TryGetValue(key, out var delegates))
{
delegates.Add(@delegate);
}
else
{
delegates = new List<Delegate> { @delegate };
_targetToEventHandler.Add(key, delegates);
}
}
protected void PrivateRemoveHandler(TEventSource source, TEventHandler handler)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (handler == null) throw new ArgumentNullException(nameof(handler));
if (!typeof(TEventHandler).GetTypeInfo().IsSubclassOf(typeof(Delegate)))
{
throw new ArgumentException("handler must be Delegate type");
}
RemoveWeakHandler(source, handler);
RemoveTargetHandler(handler);
}
private void RemoveWeakHandler(TEventSource source, TEventHandler handler)
{
if (_sourceToWeakHandlers.TryGetValue(source, out var weakHandlers))
{
// clone list if we are currently delivering an event
if (weakHandlers.IsDeliverActive)
{
weakHandlers = weakHandlers.Clone();
_sourceToWeakHandlers.Remove(source);
_sourceToWeakHandlers.Add(source, weakHandlers);
}
if (weakHandlers.RemoveWeakHandler(source, handler) && weakHandlers.Count == 0)
{
_sourceToWeakHandlers.Remove(source);
StopListening(source);
}
}
}
private void RemoveTargetHandler(TEventHandler handler)
{
var @delegate = handler as Delegate;
var key = @delegate?.Target ?? StaticSource;
if (_targetToEventHandler.TryGetValue(key, out var delegates))
{
delegates.Remove(@delegate);
if (delegates.Count == 0)
{
_targetToEventHandler.Remove(key);
}
}
}
private void PrivateDeliverEvent(object sender, TEventArgs args)
{
var source = sender ?? StaticSource;
var hasStaleEntries = false;
if (_sourceToWeakHandlers.TryGetValue(source, out var weakHandlers))
{
using (weakHandlers.DeliverActive())
{
hasStaleEntries = weakHandlers.DeliverEvent(source, args);
}
}
if (hasStaleEntries)
{
Purge(source);
}
}
private void Purge(object source)
{
if (_sourceToWeakHandlers.TryGetValue(source, out var weakHandlers))
{
if (weakHandlers.IsDeliverActive)
{
weakHandlers = weakHandlers.Clone();
_sourceToWeakHandlers.Remove(source);
_sourceToWeakHandlers.Add(source, weakHandlers);
}
else
{
weakHandlers.Purge();
}
}
}
internal class WeakHandler
{
private readonly WeakReference _source;
private readonly WeakReference _originalHandler;
internal bool IsActive => _source != null && _source.IsAlive && _originalHandler != null && _originalHandler.IsAlive;
internal TEventHandler Handler
{
get
{
if (_originalHandler == null)
{
return default(TEventHandler);
}
return (TEventHandler)_originalHandler.Target;
}
}
internal WeakHandler(object source, TEventHandler originalHandler)
{
_source = new WeakReference(source);
_originalHandler = new WeakReference(originalHandler);
}
internal bool Matches(object o, TEventHandler handler)
{
return _source != null &&
ReferenceEquals(_source.Target, o) &&
_originalHandler != null &&
(ReferenceEquals(_originalHandler.Target, handler) ||
_originalHandler.Target is TEventHandler &&
handler is TEventHandler &&
handler is Delegate del && _originalHandler.Target is Delegate origDel && Equals(del.Target, origDel.Target));
}
}
internal class WeakHandlerList
{
private int _deliveries;
private readonly List<WeakHandler> _handlers;
internal WeakHandlerList()
{
_handlers = new List<WeakHandler>();
}
internal void AddWeakHandler(TEventSource source, TEventHandler handler)
{
var handlerSink = new WeakHandler(source, handler);
_handlers.Add(handlerSink);
}
internal bool RemoveWeakHandler(TEventSource source, TEventHandler handler)
{
foreach (var weakHandler in _handlers)
{
if (weakHandler.Matches(source, handler))
{
return _handlers.Remove(weakHandler);
}
}
return false;
}
internal WeakHandlerList Clone()
{
var newList = new WeakHandlerList();
newList._handlers.AddRange(_handlers.Where(h => h.IsActive));
return newList;
}
internal int Count => _handlers.Count;
internal bool IsDeliverActive => _deliveries > 0;
internal IDisposable DeliverActive()
{
Interlocked.Increment(ref _deliveries);
return new Disposable(() => Interlocked.Decrement(ref _deliveries));
}
// ReSharper disable once MemberHidesStaticFromOuterClass
internal virtual bool DeliverEvent(object sender, TEventArgs args)
{
var hasStaleEntries = false;
foreach (var handler in _handlers)
{
if (handler.IsActive)
{
var @delegate = handler.Handler as Delegate;
@delegate?.DynamicInvoke(sender, args);
}
else
{
hasStaleEntries = true;
}
}
return hasStaleEntries;
}
internal void Purge()
{
for (var i = _handlers.Count - 1; i >= 0; i--)
{
if (!_handlers[i].IsActive)
{
_handlers.RemoveAt(i);
}
}
}
}
}
internal sealed class Disposable : IDisposable
{
private volatile Action _dispose;
internal Disposable(Action dispose)
{
_dispose = dispose;
}
internal bool IsDisposed => _dispose == null;
public void Dispose()
{
Interlocked.Exchange(ref _dispose, null)?.Invoke();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 49e8281cb9a76452484efab10014acf8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: