A game about forced loneliness, made by TACStudios
at master 135 lines 3.5 kB view raw
1using System; 2using System.Collections.Generic; 3using UnityEngine; 4 5namespace UnityEditor.U2D.Animation 6{ 7 [Serializable] 8 internal abstract class SerializableSelection<T> : ISelection<T>, ISerializationCallbackReceiver 9 { 10 internal static readonly int kInvalidID = -1; 11 12 [SerializeField] 13 private T[] m_Keys = new T[0]; 14 15 private HashSet<T> m_Selection = new HashSet<T>(); 16 private HashSet<T> m_TemporalSelection = new HashSet<T>(); 17 private bool m_SelectionInProgress = false; 18 19 public int Count => m_Selection.Count + m_TemporalSelection.Count; 20 21 public T activeElement 22 { 23 get { return First(); } 24 set 25 { 26 Clear(); 27 Select(value, true); 28 } 29 } 30 31 public T[] elements 32 { 33 get 34 { 35 var set = m_Selection; 36 37 if (m_SelectionInProgress) 38 { 39 var union = new HashSet<T>(m_Selection); 40 union.UnionWith(m_TemporalSelection); 41 set = union; 42 } 43 44 return new List<T>(set).ToArray(); 45 } 46 set 47 { 48 Clear(); 49 foreach (var element in value) 50 Select(element, true); 51 } 52 } 53 54 protected abstract T GetInvalidElement(); 55 56 public void Clear() 57 { 58 GetSelection().Clear(); 59 } 60 61 public void BeginSelection() 62 { 63 m_SelectionInProgress = true; 64 Clear(); 65 } 66 67 public void EndSelection(bool select) 68 { 69 m_SelectionInProgress = false; 70 71 if (select) 72 m_Selection.UnionWith(m_TemporalSelection); 73 else 74 m_Selection.ExceptWith(m_TemporalSelection); 75 76 m_TemporalSelection.Clear(); 77 } 78 79 public void Select(T element, bool select) 80 { 81 if (EqualityComparer<T>.Default.Equals(element, GetInvalidElement())) 82 return; 83 84 if (select) 85 GetSelection().Add(element); 86 else if (Contains(element)) 87 GetSelection().Remove(element); 88 } 89 90 public bool Contains(T element) 91 { 92 return m_Selection.Contains(element) || m_TemporalSelection.Contains(element); 93 } 94 95 private HashSet<T> GetSelection() 96 { 97 if (m_SelectionInProgress) 98 return m_TemporalSelection; 99 100 return m_Selection; 101 } 102 103 private T First() 104 { 105 T element = First(m_Selection); 106 107 if (EqualityComparer<T>.Default.Equals(element, GetInvalidElement())) 108 element = First(m_TemporalSelection); 109 110 return element; 111 } 112 113 private T First(HashSet<T> set) 114 { 115 if (set.Count == 0) 116 return GetInvalidElement(); 117 118 using (var enumerator = set.GetEnumerator()) 119 { 120 Debug.Assert(enumerator.MoveNext()); 121 return enumerator.Current; 122 } 123 } 124 125 void ISerializationCallbackReceiver.OnBeforeSerialize() 126 { 127 m_Keys = new List<T>(m_Selection).ToArray(); 128 } 129 130 void ISerializationCallbackReceiver.OnAfterDeserialize() 131 { 132 elements = m_Keys; 133 } 134 } 135}