PriorityValue.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. // Copyright (c) The Avalonia Project. All rights reserved.
  2. // Licensed under the MIT license. See licence.md file in the project root for full license information.
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using Avalonia.Data;
  8. using Avalonia.Logging;
  9. using Avalonia.Utilities;
  10. namespace Avalonia
  11. {
  12. /// <summary>
  13. /// Maintains a list of prioritized bindings together with a current value.
  14. /// </summary>
  15. /// <remarks>
  16. /// Bindings, in the form of <see cref="IObservable{Object}"/>s are added to the object using
  17. /// the <see cref="Add"/> method. With the observable is passed a priority, where lower values
  18. /// represent higher priorities. The current <see cref="Value"/> is selected from the highest
  19. /// priority binding that doesn't return <see cref="AvaloniaProperty.UnsetValue"/>. Where there
  20. /// are multiple bindings registered with the same priority, the most recently added binding
  21. /// has a higher priority. Each time the value changes, the
  22. /// <see cref="IPriorityValueOwner.Changed"/> method on the
  23. /// owner object is fired with the old and new values.
  24. /// </remarks>
  25. internal sealed class PriorityValue : ISetAndNotifyHandler<(object,int)>
  26. {
  27. private readonly Type _valueType;
  28. private readonly SingleOrDictionary<int, PriorityLevel> _levels = new SingleOrDictionary<int, PriorityLevel>();
  29. private readonly Func<object, object> _validate;
  30. private (object value, int priority) _value;
  31. private DeferredSetter<object> _setter;
  32. /// <summary>
  33. /// Initializes a new instance of the <see cref="PriorityValue"/> class.
  34. /// </summary>
  35. /// <param name="owner">The owner of the object.</param>
  36. /// <param name="property">The property that the value represents.</param>
  37. /// <param name="valueType">The value type.</param>
  38. /// <param name="validate">An optional validation function.</param>
  39. public PriorityValue(
  40. IPriorityValueOwner owner,
  41. AvaloniaProperty property,
  42. Type valueType,
  43. Func<object, object> validate = null)
  44. {
  45. Owner = owner;
  46. Property = property;
  47. _valueType = valueType;
  48. _value = (AvaloniaProperty.UnsetValue, int.MaxValue);
  49. _validate = validate;
  50. }
  51. /// <summary>
  52. /// Gets a value indicating whether the property is animating.
  53. /// </summary>
  54. public bool IsAnimating
  55. {
  56. get
  57. {
  58. return ValuePriority <= (int)BindingPriority.Animation &&
  59. GetLevel(ValuePriority).ActiveBindingIndex != -1;
  60. }
  61. }
  62. /// <summary>
  63. /// Gets the owner of the value.
  64. /// </summary>
  65. public IPriorityValueOwner Owner { get; }
  66. /// <summary>
  67. /// Gets the property that the value represents.
  68. /// </summary>
  69. public AvaloniaProperty Property { get; }
  70. /// <summary>
  71. /// Gets the current value.
  72. /// </summary>
  73. public object Value => _value.value;
  74. /// <summary>
  75. /// Gets the priority of the binding that is currently active.
  76. /// </summary>
  77. public int ValuePriority => _value.priority;
  78. /// <summary>
  79. /// Adds a new binding.
  80. /// </summary>
  81. /// <param name="binding">The binding.</param>
  82. /// <param name="priority">The binding priority.</param>
  83. /// <returns>
  84. /// A disposable that will remove the binding.
  85. /// </returns>
  86. public IDisposable Add(IObservable<object> binding, int priority)
  87. {
  88. return GetLevel(priority).Add(binding);
  89. }
  90. /// <summary>
  91. /// Sets the value for a specified priority.
  92. /// </summary>
  93. /// <param name="value">The value.</param>
  94. /// <param name="priority">The priority</param>
  95. public void SetValue(object value, int priority)
  96. {
  97. GetLevel(priority).DirectValue = value;
  98. }
  99. /// <summary>
  100. /// Gets the currently active bindings on this object.
  101. /// </summary>
  102. /// <returns>An enumerable collection of bindings.</returns>
  103. public IEnumerable<PriorityBindingEntry> GetBindings()
  104. {
  105. foreach (var level in _levels)
  106. {
  107. foreach (var binding in level.Value.Bindings)
  108. {
  109. yield return binding;
  110. }
  111. }
  112. }
  113. /// <summary>
  114. /// Returns diagnostic string that can help the user debug the bindings in effect on
  115. /// this object.
  116. /// </summary>
  117. /// <returns>A diagnostic string.</returns>
  118. public string GetDiagnostic()
  119. {
  120. var b = new StringBuilder();
  121. var first = true;
  122. foreach (var level in _levels)
  123. {
  124. if (!first)
  125. {
  126. b.AppendLine();
  127. }
  128. b.Append(ValuePriority == level.Key ? "*" : string.Empty);
  129. b.Append("Priority ");
  130. b.Append(level.Key);
  131. b.Append(": ");
  132. b.AppendLine(level.Value.Value?.ToString() ?? "(null)");
  133. b.AppendLine("--------");
  134. b.Append("Direct: ");
  135. b.AppendLine(level.Value.DirectValue?.ToString() ?? "(null)");
  136. foreach (var binding in level.Value.Bindings)
  137. {
  138. b.Append(level.Value.ActiveBindingIndex == binding.Index ? "*" : string.Empty);
  139. b.Append(binding.Description ?? binding.Observable.GetType().Name);
  140. b.Append(": ");
  141. b.AppendLine(binding.Value?.ToString() ?? "(null)");
  142. }
  143. first = false;
  144. }
  145. return b.ToString();
  146. }
  147. /// <summary>
  148. /// Called when the value for a priority level changes.
  149. /// </summary>
  150. /// <param name="level">The priority level of the changed entry.</param>
  151. public void LevelValueChanged(PriorityLevel level)
  152. {
  153. if (level.Priority <= ValuePriority)
  154. {
  155. if (level.Value != AvaloniaProperty.UnsetValue)
  156. {
  157. UpdateValue(level.Value, level.Priority);
  158. }
  159. else
  160. {
  161. foreach (var i in _levels.Values.OrderBy(x => x.Priority))
  162. {
  163. if (i.Value != AvaloniaProperty.UnsetValue)
  164. {
  165. UpdateValue(i.Value, i.Priority);
  166. return;
  167. }
  168. }
  169. UpdateValue(AvaloniaProperty.UnsetValue, int.MaxValue);
  170. }
  171. }
  172. }
  173. /// <summary>
  174. /// Called when a priority level encounters an error.
  175. /// </summary>
  176. /// <param name="level">The priority level of the changed entry.</param>
  177. /// <param name="error">The binding error.</param>
  178. public void LevelError(PriorityLevel level, BindingNotification error)
  179. {
  180. Owner.LogError(Property, error.Error);
  181. }
  182. /// <summary>
  183. /// Causes a revalidation of the value.
  184. /// </summary>
  185. public void Revalidate()
  186. {
  187. if (_validate != null)
  188. {
  189. PriorityLevel level;
  190. if (_levels.TryGetValue(ValuePriority, out level))
  191. {
  192. UpdateValue(level.Value, level.Priority);
  193. }
  194. }
  195. }
  196. /// <summary>
  197. /// Gets the <see cref="PriorityLevel"/> with the specified priority, creating it if it
  198. /// doesn't already exist.
  199. /// </summary>
  200. /// <param name="priority">The priority.</param>
  201. /// <returns>The priority level.</returns>
  202. private PriorityLevel GetLevel(int priority)
  203. {
  204. PriorityLevel result;
  205. if (!_levels.TryGetValue(priority, out result))
  206. {
  207. result = new PriorityLevel(this, priority);
  208. _levels.Add(priority, result);
  209. }
  210. return result;
  211. }
  212. /// <summary>
  213. /// Updates the current <see cref="Value"/> and notifies all subscribers.
  214. /// </summary>
  215. /// <param name="value">The value to set.</param>
  216. /// <param name="priority">The priority level that the value came from.</param>
  217. private void UpdateValue(object value, int priority)
  218. {
  219. var newValue = (value, priority);
  220. if (newValue == _value)
  221. {
  222. return;
  223. }
  224. if (_setter == null)
  225. {
  226. _setter = Owner.GetNonDirectDeferredSetter(Property);
  227. }
  228. _setter.SetAndNotifyCallback(Property, this, ref _value, newValue);
  229. }
  230. void ISetAndNotifyHandler<(object, int)>.HandleSetAndNotify(AvaloniaProperty property, ref (object, int) backing, (object, int) value)
  231. {
  232. SetAndNotify(ref backing, value);
  233. }
  234. private void SetAndNotify(ref (object value, int priority) backing, (object value, int priority) update)
  235. {
  236. var val = update.value;
  237. var notification = val as BindingNotification;
  238. object castValue;
  239. if (notification != null)
  240. {
  241. val = (notification.HasValue) ? notification.Value : null;
  242. }
  243. if (TypeUtilities.TryConvertImplicit(_valueType, val, out castValue))
  244. {
  245. var old = backing.value;
  246. if (_validate != null && castValue != AvaloniaProperty.UnsetValue)
  247. {
  248. castValue = _validate(castValue);
  249. }
  250. backing = (castValue, update.priority);
  251. if (notification?.HasValue == true)
  252. {
  253. notification.SetValue(castValue);
  254. }
  255. if (notification == null || notification.HasValue)
  256. {
  257. Owner?.Changed(Property, ValuePriority, old, Value);
  258. }
  259. if (notification != null)
  260. {
  261. Owner?.BindingNotificationReceived(Property, notification);
  262. }
  263. }
  264. else
  265. {
  266. Logger.Error(
  267. LogArea.Binding,
  268. Owner,
  269. "Binding produced invalid value for {$Property} ({$PropertyType}): {$Value} ({$ValueType})",
  270. Property.Name,
  271. _valueType,
  272. val,
  273. val?.GetType());
  274. }
  275. }
  276. }
  277. }