added TriggerAnimation facilities for DIYGrid

This commit is contained in:
John Colvin committed 2019-08-14 00:24:35 -05:00
1 parent d780777c7c
commit c58e892b0a
5 files changed
+526 -6

No files matched your search

@@ -0,0 +1,34 @@
using mbts.ui.spark;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace bts.shell.pnl {
readonly struct AnimationFrame<TColumn> where TColumn : struct {
public readonly TimeSpan timestamp;
public readonly ImmutableDictionary<SymbolKey<TColumn>, Animation> animation;
public AnimationFrame(TimeSpan timestamp) {
this.timestamp = timestamp;
animation = ImmutableDictionary<SymbolKey<TColumn>, Animation>.Empty;
}
public AnimationFrame(TimeSpan timestamp, ImmutableDictionary<SymbolKey<TColumn>, Animation> animation) {
this.timestamp = timestamp;
this.animation = animation;
}
}
static class AnimationFrameFactory {
public static IEnumerable<AnimationFrame<TColumn>> flash<TColumn>(TColumn column, params Animation[] animation) where TColumn : struct =>
flash(column, TimeSpan.FromSeconds(2), animation);
public static IEnumerable<AnimationFrame<TColumn>> flash<TColumn>(TColumn column, TimeSpan duration, params Animation[] animation) where TColumn : struct {
var anims = ImmutableDictionary<SymbolKey<TColumn>, Animation>.Empty;
for (int i = 0; i < animation.Length; i++)
anims = anims.Add(new SymbolKey<TColumn>(column, animation[i].type), animation[i]);
yield return new AnimationFrame<TColumn>(TimeSpan.Zero, anims);
yield return new AnimationFrame<TColumn>(duration);
}
}
}
@@ -0,0 +1,133 @@
using mbts.ui.spark;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading.Tasks;
using System.Windows.Threading;
namespace bts.shell.pnl {
class DIYGridAnimationModel<TColumn, TRow> : IObservable<ImmutableDictionary<SymbolKey<TColumn>, Animation>> where TColumn : struct {
readonly Dictionary<int, ITriggerAnimation<TRow, TColumn>> _triggers = new Dictionary<int, ITriggerAnimation<TRow, TColumn>>();
readonly Subject<ImmutableDictionary<SymbolKey<TColumn>, Animation>> _subject = new Subject<ImmutableDictionary<SymbolKey<TColumn>, Animation>>();
readonly TimeSpan? _delay;
TRow _pending_update;
bool _is_busy, _is_dirty;
ImmutableDictionary<int, int> _versions = ImmutableDictionary<int, int>.Empty;
ImmutableDictionary<SymbolKey<TColumn>, Animation> _full_state = ImmutableDictionary<SymbolKey<TColumn>, Animation>.Empty;
// Since animations may begin before the previous one is finished, there may be symbol use conflicts (i.e., animation units, like arrow, border, etc.).
// The Symbol Access map below indicates which symbols are in use, and which trigger is using them (value).
// When the a particular trigger begins a new animation timeline (in response to quick data changes), before the previous one completed,
// the symbols being used by the previous animation are removed from the overall state.
ImmutableDictionary<SymbolKey<TColumn>, int> _symbol_access = ImmutableDictionary<SymbolKey<TColumn>, int>.Empty;
public DIYGridAnimationModel() { }
public DIYGridAnimationModel(TimeSpan delay) {
_delay = delay;
}
int _trigger_id = 0;
public void add_trigger(ITriggerAnimation<TRow, TColumn> trigger) =>
_triggers.Add(++_trigger_id, trigger);
public void add_trigger(int id, ITriggerAnimation<TRow, TColumn> trigger) =>
_triggers.Add(id, trigger);
public async void on_row(TRow r) {
if (_delay.HasValue) {
if (_is_busy) {
_is_dirty = true;
_pending_update = r;
} else {
_is_busy = true;
_pending_update = r;
do {
_is_dirty = false;
int thread = System.Threading.Thread.CurrentThread.ManagedThreadId;
await Task.Delay(_delay.Value);
int thread_after = System.Threading.Thread.CurrentThread.ManagedThreadId;
Log.assert(thread == thread_after, "Delayed execution returned on a different thread.");
on_row(_pending_update, _triggers);
} while (_is_dirty);
_is_busy = false;
}
} else {
on_row(r, _triggers);
}
}
public void on_row(TRow r, IEnumerable<KeyValuePair<int, ITriggerAnimation<TRow, TColumn>>> triggers) {
var timeline = ImmutableSortedDictionary<TimeSpan, ImmutableDictionary<int, ImmutableDictionary<SymbolKey<TColumn>, Animation>>>.Empty;
foreach (var kv in triggers) {
var frames = kv.Value.on_data(r).ToList();
if (frames.Count > 0) {
// clear previous animation-state for this trigger
foreach (var sym_kv in _symbol_access) {
if (sym_kv.Value == kv.Key) {
_symbol_access = _symbol_access.Remove(sym_kv.Key);
_full_state = _full_state.Remove(sym_kv.Key);
}
}
foreach (var f in frames) {
if (timeline.TryGetValue(f.timestamp, out var tanims)) {
tanims = tanims.Add(kv.Key, f.animation);
timeline = timeline.SetItem(f.timestamp, tanims);
} else {
timeline = timeline.Add(f.timestamp, ImmutableDictionary<int, ImmutableDictionary<SymbolKey<TColumn>, Animation>>.Empty.Add(kv.Key, f.animation));
}
}
_versions = _versions.SetItem(kv.Key, _versions.TryGetValue(kv.Key, out int vers) ? vers + 1 : 1);
}
}
if (timeline.Count > 0)
_animate(timeline);
}
void _animate(ImmutableSortedDictionary<TimeSpan, ImmutableDictionary<int, ImmutableDictionary<SymbolKey<TColumn>, Animation>>> timeline) {
var active = ImmutableDictionary<SymbolKey<TColumn>, int>.Empty;
var snapshot = _versions;
Log.assert(timeline.First().Key == TimeSpan.Zero);
// ObserveOnDispatcher() is critical here, since all the animation timelines share access to a finite set of symbols (n per cell).
// Unless this demonstrably hurts performance, it is probably not worth the trouble of implementing concurrent symbol sharing.
var begin = timeline.GetEnumerator();
DispatcherObservable.ObserveOnDispatcher(
Observable.Generate(begin,
en => begin.MoveNext() && begin.Current.Key < TimeSpan.MaxValue,
en => en,
en => begin.Current.Value,
en => begin.Current.Key),
DispatcherPriority.ApplicationIdle
).Subscribe(on_animation);
void on_animation(ImmutableDictionary<int, ImmutableDictionary<SymbolKey<TColumn>, Animation>> changes) {
var abd = active.ToBuilder();
foreach (var kv in active) {
if (changes.TryGetValue(kv.Value, out var new_trig_state)) {
if (!new_trig_state.ContainsKey(kv.Key)) {
abd.Remove(kv.Key);
_symbol_access = _symbol_access.Remove(kv.Key);
_full_state = _full_state.Remove(kv.Key);
}
}
}
foreach (var kv in changes) {
if (_versions.TryGetValue(kv.Key, out int vers) && vers == snapshot[kv.Key]) {
foreach (var akv in kv.Value) {
_symbol_access = _symbol_access.SetItem(akv.Key, kv.Key);
_full_state = _full_state.SetItem(akv.Key, akv.Value);
abd[akv.Key] = kv.Key;
}
}
}
active = abd.ToImmutable();
_subject.OnNext(_full_state);
}
}
public IDisposable Subscribe(IObserver<ImmutableDictionary<SymbolKey<TColumn>, Animation>> observer) =>
_subject.Subscribe(observer);
}
}
@@ -0,0 +1,271 @@
using mbts.ui.spark;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reactive.Linq;
using System.Windows.Media;
using CellAnimationType = mbts.ui.spark.CellAnimation.Type;
namespace bts.shell.pnl {
interface ITriggerAnimation<T, TColumn> where TColumn : struct {
IEnumerable<AnimationFrame<TColumn>> on_data(T value);
}
static class DIYGridTriggerAnimations {
static readonly TimeSpan _default_flash_duration = TimeSpan.FromSeconds(2);
public static ITriggerAnimation<T, TColumn> create<T, TColumn>(Func<T, IEnumerable<AnimationFrame<TColumn>>> animate) where TColumn : struct =>
new AnonymousAnimator<T, TColumn>(animate);
public static ITriggerAnimation<T, TColumn> delta_trigger<T, TColumn>(TColumn column, Color increase, Color decrease) where T : struct, IComparable<T> where TColumn : struct =>
new DeltaTimeline<T, TColumn>(column, increase, decrease, _default_flash_duration);
public static ITriggerAnimation<T, TColumn> delta_trigger<T, TColumn>(TColumn column, Color increase, Color decrease, IComparer<T> comparer) where T : struct where TColumn : struct =>
new DeltaTimeline<T, TColumn>(column, increase, decrease, _default_flash_duration, comparer);
public static ITriggerAnimation<T, TColumn> delta_trigger<T, TColumn>(TColumn column, Color increase, Color decrease, TimeSpan flash_duration) where T : struct, IComparable<T> where TColumn : struct =>
new DeltaTimeline<T, TColumn>(column, increase, decrease, flash_duration);
public static ITriggerAnimation<T, TColumn> append<T, TColumn>(this ITriggerAnimation<T, TColumn> first, ITriggerAnimation<T, TColumn> second) where TColumn : struct =>
new AppendTrigger<T, TColumn>(first, second);
public static ITriggerAnimation<T, TColumn> zip_indefinite_frame<T, TColumn>(this ITriggerAnimation<T, TColumn> trigger, Func<T, ImmutableDictionary<SymbolKey<TColumn>, Animation>> get_indefinite) where TColumn : struct =>
new IndefiniteFrameZipper<T, TColumn>(trigger, get_indefinite);
public static ITriggerAnimation<T, TColumn> where<T, TColumn>(this ITriggerAnimation<T, TColumn> trigger, Func<T, bool> predicate) where T : struct, IComparable<T> where TColumn : struct =>
new WhereTrigger<T, TColumn>(trigger, predicate);
class DeltaTimeline<T, TColumn> : ITriggerAnimation<T, TColumn> where T : struct where TColumn : struct {
readonly TColumn _column;
readonly Color _increase_color, _decrease_color;
readonly TimeSpan _flash_duration;
readonly IComparer<T> _comparer;
T _last_value;
public DeltaTimeline(TColumn column, Color increase, Color decrease, TimeSpan flash_duration)
: this(column, increase, decrease, flash_duration, Comparer<T>.Default) { }
public DeltaTimeline(TColumn column, Color increase, Color decrease, TimeSpan flash_duration, IComparer<T> comparer) {
_column = column;
_increase_color = increase;
_decrease_color = decrease;
_flash_duration = flash_duration;
_comparer = comparer;
}
public IEnumerable<AnimationFrame<TColumn>> on_data(T value) {
int delta = _comparer.Compare(value, _last_value);
var temp = _last_value;
_last_value = value;
if (delta > 0) {
return AnimationFrameFactory.flash(_column,
new Animation(CellAnimationType.UpArrow, _increase_color));
} else if (delta < 0) {
return AnimationFrameFactory.flash(_column,
new Animation(CellAnimationType.DownArrow, _decrease_color));
} else {
return Enumerable.Empty<AnimationFrame<TColumn>>();
}
}
}
class WhereTrigger<T, TColumn> : ITriggerAnimation<T, TColumn> where T : struct, IComparable<T> where TColumn : struct {
readonly ITriggerAnimation<T, TColumn> _trigger;
readonly Func<T, bool> _predicate;
public WhereTrigger(ITriggerAnimation<T, TColumn> trigger, Func<T, bool> predicate) {
_trigger = trigger;
_predicate = predicate;
}
public IEnumerable<AnimationFrame<TColumn>> on_data(T value) =>
_predicate(value) ? _trigger.on_data(value) : Enumerable.Empty<AnimationFrame<TColumn>>();
}
class AppendTrigger<T, TColumn> : ITriggerAnimation<T, TColumn> where TColumn : struct {
readonly ITriggerAnimation<T, TColumn> _first, _second;
public AppendTrigger(ITriggerAnimation<T, TColumn> first, ITriggerAnimation<T, TColumn> second) {
_first = first;
_second = second;
}
public IEnumerable<AnimationFrame<TColumn>> on_data(T value) {
//_predicate(value) ? _first.on_data(value) : Enumerable.Empty<(ImmutableDictionary<SymbolKey<TColumn>, Animation> animation, TimeSpan timestamp)>();
var first_anims = _first.on_data(value);
var second_anims = _second.on_data(value);
var first_en = _first.on_data(value).GetEnumerator();
var second_en = _second.on_data(value).GetEnumerator();
while (first_en.MoveNext()) {
if (second_en.MoveNext()) {
while (first_en.Current.timestamp < second_en.Current.timestamp) {
yield return first_en.Current;
if (!first_en.MoveNext())
goto finish_with_second;
}
while (second_en.Current.timestamp < first_en.Current.timestamp) {
yield return second_en.Current;
if (!second_en.MoveNext())
goto finish_with_first;
}
if (first_en.Current.timestamp == second_en.Current.timestamp) {
var combined_anims = first_en.Current.animation;
foreach (var kv in second_en.Current.animation) {
if (!combined_anims.ContainsKey(kv.Key))
combined_anims = combined_anims.Add(kv.Key, kv.Value);
}
yield return new AnimationFrame<TColumn>(first_en.Current.timestamp, combined_anims);
}
} else {
goto finish_with_first;
}
}
if (second_en.MoveNext())
goto finish_with_second;
yield break;
finish_with_first:
do yield return first_en.Current;
while (first_en.MoveNext());
yield break;
finish_with_second:
do yield return second_en.Current;
while (second_en.MoveNext());
yield break;
}
}
class AnonymousAnimator<T, TColumn> : ITriggerAnimation<T, TColumn> where TColumn : struct {
readonly Func<T, IEnumerable<AnimationFrame<TColumn>>> _on_data;
public AnonymousAnimator(Func<T, IEnumerable<AnimationFrame<TColumn>>> on_data) =>
_on_data = on_data;
public IEnumerable<AnimationFrame<TColumn>> on_data(T value) =>
_on_data(value);
}
/// <summary>
/// When c
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TColumn"></typeparam>
class IndefiniteFrameZipper<T, TColumn> : ITriggerAnimation<T, TColumn> where TColumn : struct {
readonly ITriggerAnimation<T, TColumn> _trigger;
readonly Func<T, ImmutableDictionary<SymbolKey<TColumn>, Animation>> _get_indefinite;
bool _active;
public IndefiniteFrameZipper(ITriggerAnimation<T, TColumn> trigger, Func<T, ImmutableDictionary<SymbolKey<TColumn>, Animation>> get_indefinite) {
_get_indefinite = get_indefinite;
_trigger = trigger;
}
public IEnumerable<AnimationFrame<TColumn>> on_data(T value) {
var rv = _trigger.on_data(value);
var indef = _get_indefinite(value);
if (indef != null && indef.Count > 0) {
_active = true;
if (rv == null || !rv.Any()) {
return new[] { new AnimationFrame<TColumn>(TimeSpan.Zero, indef) };
} else {
return rv.Select(f => new AnimationFrame<TColumn>(f.timestamp, f.animation.SetItems(indef))).ToList();
}
}
if (_active) {
_active = false;
if (rv == null || !rv.Any()) {
return new[] { new AnimationFrame<TColumn>(TimeSpan.Zero, ImmutableDictionary<SymbolKey<TColumn>, Animation>.Empty) };
} else {
return rv;
}
}
return rv;
}
}
}
static class DIYGridAnimationExtensions {
public static ITriggerAnimation<TOuter, TColumn> wrap<T, TOuter, TColumn>(this ITriggerAnimation<T, TColumn> timeline, Func<TOuter, T> selector) where TColumn : struct =>
new SelectorWrapper<T, TOuter, TColumn>(timeline, selector);
public static ITriggerAnimation<T, TColumn> aggregate<T, TAccum, TColumn>(this ITriggerAnimation<TAccum, TColumn> timeline, Func<TAccum, T, TAccum> accumulate, TAccum seed = default) where TColumn : struct =>
new AggregatorWrapper<T, TAccum, TColumn>(timeline, accumulate, seed);
public static ITriggerAnimation<T, TColumn> delta<T, TColumn>(this ITriggerAnimation<T, TColumn> animator, Func<T, T, T> get_delta) where TColumn : struct =>
new DeltaWrapper<T, TColumn>(animator, get_delta);
class ComparisonAnimation<T, TColumn> : ITriggerAnimation<T, TColumn> where T : struct, IComparable<T> where TColumn : struct {
readonly TColumn _column;
readonly Animation[] _animations;
readonly T[] _sorted_values;
IComparer<T> _comparer;
public ComparisonAnimation(TColumn column, params (T value, Animation animation)[] sorted_animation_buckets)
: this(column, Comparer<T>.Default, sorted_animation_buckets) { }
public ComparisonAnimation(TColumn column, IComparer<T> comparer, params (T value, Animation animation)[] sorted_animation_buckets) {
_column = column;
_comparer = comparer;
_animations = Array.ConvertAll(sorted_animation_buckets, a => a.animation);
_sorted_values = Array.ConvertAll(sorted_animation_buckets, a => a.value);
}
public IEnumerable<AnimationFrame<TColumn>> on_data(T value) {
int pos = Array.BinarySearch(_sorted_values, value);
if (pos < 0)
pos = ~pos;
var anim = pos == _animations.Length ? _animations[_animations.Length - 1] : _animations[pos];
yield return new AnimationFrame<TColumn>(
TimeSpan.Zero,
ImmutableDictionary<SymbolKey<TColumn>, Animation>.Empty.Add(new SymbolKey<TColumn>(_column, anim.type), anim));
}
}
class SelectorWrapper<T, TOuter, TColumn> : ITriggerAnimation<TOuter, TColumn> where TColumn : struct {
readonly ITriggerAnimation<T, TColumn> _timeline;
readonly Func<TOuter, T> _selector;
public SelectorWrapper(ITriggerAnimation<T, TColumn> timeline, Func<TOuter, T> selector) {
_timeline = timeline;
_selector = selector;
}
public IEnumerable<AnimationFrame<TColumn>> on_data(TOuter value) =>
_timeline.on_data(_selector(value));
}
class AggregatorWrapper<T, TAccum, TColumn> : ITriggerAnimation<T, TColumn> where TColumn : struct {
readonly ITriggerAnimation<TAccum, TColumn> _timeline;
readonly Func<TAccum, T, TAccum> _accumulate;
TAccum _seed;
public AggregatorWrapper(ITriggerAnimation<TAccum, TColumn> timeline, Func<TAccum, T, TAccum> accumulate, TAccum seed = default) {
_timeline = timeline;
_accumulate = accumulate;
_seed = seed;
}
public IEnumerable<AnimationFrame<TColumn>> on_data(T value) =>
_timeline.on_data(_seed = _accumulate(_seed, value));
}
class DeltaWrapper<T, TColumn> : ITriggerAnimation<T, TColumn> where TColumn : struct {
readonly Func<T, T, T> _get_delta;
readonly ITriggerAnimation<T, TColumn> _animator;
T _last_value;
public DeltaWrapper(ITriggerAnimation<T, TColumn> animator, Func<T, T, T> get_delta, T default_value = default) {
_animator = animator;
_get_delta = get_delta;
_last_value = default_value;
}
public IEnumerable<AnimationFrame<TColumn>> on_data(T value) {
T delta = _get_delta(_last_value, value);
_last_value = value;
return _animator.on_data(delta);
}
}
}
}
@@ -0,0 +1,26 @@
using bts.utils;
using System;
using CellAnimationType = mbts.ui.spark.CellAnimation.Type;
namespace bts.shell.pnl {
readonly struct SymbolKey<T> : IEquatable<SymbolKey<T>> where T : struct {
public readonly T column;
public readonly CellAnimationType type;
public SymbolKey(T column, CellAnimationType type) {
this.column = column;
this.type = type;
}
public bool Equals(SymbolKey<T> other) =>
column.Equals(other.column) &&
type == other.type;
public override bool Equals(object obj) =>
obj is SymbolKey<T> other && Equals(other);
public override int GetHashCode() =>
(column.GetHashCode() % MathUtils.Primes.P_65449) |
((type.GetHashCode() % MathUtils.Primes.P_65449) << 16);
}
}
@@ -1,10 +1,19 @@
using System.Windows.Media;
using bts.utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Windows.Media;
namespace mbts.ui.spark
{
internal class CellAnimation
{
public enum Type { Border, Background, UpArrow, DownArrow }
namespace mbts.ui.spark {
readonly struct CellAnimation {
public enum Type {
None,
Border,
Background,
UpArrow,
DownArrow
}
public CellAnimation(object column, Type type, Brush brush) {
this.column = column;
@@ -15,4 +24,51 @@ namespace mbts.ui.spark
public readonly Type type;
public readonly Brush brush;
}
readonly struct Animation : IEquatable<Animation> {
public readonly CellAnimation.Type type;
public readonly Color color;
public Animation(CellAnimation.Type type, Color color) {
this.type = type;
this.color = color;
}
public bool Equals(Animation other) =>
type == other.type &&
color == other.color;
public override bool Equals(object obj) =>
obj is Animation other && Equals(other);
public override int GetHashCode() =>
(type.GetHashCode() % MathUtils.Primes.P_65449) |
((color.GetHashCode() % MathUtils.Primes.P_65449) << 16);
public static bool operator ==(Animation a, Animation b) => a.Equals(b);
public static bool operator !=(Animation a, Animation b) => !a.Equals(b);
}
readonly struct CellAnimation<T> : IEquatable<CellAnimation<T>> where T : struct {
public readonly ImmutableList<Animation> animations;
public readonly T column;
public CellAnimation(T column, CellAnimation.Type type, Color color) {
this.column = column;
animations = ImmutableList<Animation>.Empty.Add(new Animation(type, color));
}
public CellAnimation(T column, ImmutableList<Animation> animations) {
this.column = column;
this.animations = animations;
}
public IEnumerable<CellAnimation> to_generic() {
var col = column;
foreach (var a in animations)
yield return new CellAnimation(col, a.type, new SolidColorBrush(a.color));
}
public bool Equals(CellAnimation<T> other) =>
column.Equals(other.column) &&
EqualityComparer.safe_sequence_equals(animations, other.animations);
}
}