From 72e35a59145b6c144d03111b3f08dab8f884e39e Mon Sep 17 00:00:00 2001 From: John Colvin Date: Mon, 8 Jul 2019 13:03:37 -0500 Subject: [PATCH 01/20] fix typos ExceptionBuilder.ArgumentOutOfRange --- src/client/spark_core/utils/Exceptions/ExceptionBuilder.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/client/spark_core/utils/Exceptions/ExceptionBuilder.cs b/src/client/spark_core/utils/Exceptions/ExceptionBuilder.cs index bf87ee8af..e5763b63b 100644 --- a/src/client/spark_core/utils/Exceptions/ExceptionBuilder.cs +++ b/src/client/spark_core/utils/Exceptions/ExceptionBuilder.cs @@ -26,10 +26,10 @@ namespace mbts.utils { public static class ArgumentOutOfRange { public static ArgumentOutOfRangeException lt_zero(string name) => - new ArgumentOutOfRangeException(name, "Index is less than 0"); + new ArgumentOutOfRangeException(name, "Value is less than 0."); public static ArgumentOutOfRangeException gte_length(string name) => - new ArgumentOutOfRangeException(name, "Index is greater than or equal to the number of elements."); + new ArgumentOutOfRangeException(name, "Value is greater than or equal to the number of elements."); } public static class Format { From 7428f9dbfbc57caeaf9f0758a93c1895bbad2552 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Mon, 8 Jul 2019 13:06:03 -0500 Subject: [PATCH 02/20] make ObservableSortedCollection a standalone collection (not a wrapper); implement IObservableCollectionAddRemoveOnly --- .../Collections/ObservableKeyedCollection.cs | 7 +- .../Collections/ObservableSortedCollection.cs | 55 ---- .../Filters/VM/DiscreteValuesFilterVM.cs | 4 +- .../DataGridEx/Model/DataGridExModel.cs | 29 +- .../Collections/IObservableCollection.cs | 3 + .../Collections/ObservableSortedCollection.cs | 144 ++++++++++ src/client/spark_core/utils/ArrayUtils.cs | 48 +++- .../spark_core/utils/CollectionHelper.cs | 50 ++++ .../utils}/ComparerBuilder.cs | 0 .../utils/Exceptions/ExceptionBuilder.cs | 9 + .../ObservableSortedCollectionTests.cs | 267 ++++++++++++++++++ src/client/spark_test/Utils/Data/Person.cs | 49 ++++ 12 files changed, 568 insertions(+), 97 deletions(-) delete mode 100644 src/client/spark/core/Collections/ObservableSortedCollection.cs create mode 100644 src/client/spark_core/Collections/ObservableSortedCollection.cs rename src/client/{spark/core/Utility => spark_core/utils}/ComparerBuilder.cs (100%) create mode 100644 src/client/spark_test/Collections/ObservableSortedCollectionTests.cs create mode 100644 src/client/spark_test/Utils/Data/Person.cs diff --git a/src/client/spark/core/Collections/ObservableKeyedCollection.cs b/src/client/spark/core/Collections/ObservableKeyedCollection.cs index 20541289d..d0b54a824 100644 --- a/src/client/spark/core/Collections/ObservableKeyedCollection.cs +++ b/src/client/spark/core/Collections/ObservableKeyedCollection.cs @@ -14,7 +14,6 @@ namespace mbts.collections { interface IObservableKeyedCollection : IObservableCollection, IDictionary { } class ObservableKeyedCollection : ObservableCollection, IObservableCollection, IDictionary, IReadOnlyObservableKeyedCollection { - const string _indexer_name = "Item[]"; readonly Func _key; readonly Dictionary _map; @@ -41,7 +40,7 @@ namespace mbts.collections { int index = Items.IndexOf(curr); Items[index] = value; _map[key] = value; - OnPropertyChanged(new PropertyChangedEventArgs(_indexer_name)); + OnPropertyChanged(new PropertyChangedEventArgs(CollectionHelper.indexer_name)); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, value, curr, index)); } else { Items.Add(value); @@ -93,7 +92,7 @@ namespace mbts.collections { _map.Remove(old_key); _map[_key(new_value)] = new_value; Items[index] = new_value; - OnPropertyChanged(new PropertyChangedEventArgs(_indexer_name)); + OnPropertyChanged(new PropertyChangedEventArgs(CollectionHelper.indexer_name)); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, new_value, old_value, index)); return true; } @@ -188,7 +187,7 @@ namespace mbts.collections { void _set(T item) => _map[_key(item)] = item; void _notify_props_changed() { OnPropertyChanged(new PropertyChangedEventArgs(nameof(Count))); - OnPropertyChanged(new PropertyChangedEventArgs(_indexer_name)); + OnPropertyChanged(new PropertyChangedEventArgs(CollectionHelper.indexer_name)); } public bool ContainsKey(TKey key) => _map.ContainsKey(key); diff --git a/src/client/spark/core/Collections/ObservableSortedCollection.cs b/src/client/spark/core/Collections/ObservableSortedCollection.cs deleted file mode 100644 index 8a087bacc..000000000 --- a/src/client/spark/core/Collections/ObservableSortedCollection.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.Linq; - -namespace mbts.collections -{ - public class ObservableSortedCollection : ObservableCollection - { - public ObservableSortedCollection(ObservableCollection source) : this(source, Comparer.Default) { } - - public ObservableSortedCollection(ObservableCollection source, IComparer comparer) { - _comparer = comparer; - foreach (var item in source) _insert_sorted(item); - source.CollectionChanged += source_CollectionChanged; - } - - private IComparer _comparer; - public IComparer comparer { get { return _comparer; } set { _comparer = value; sort(); } } - - protected void sort() { this.sync_with(this.OrderBy(t => t, _comparer)); } - - private void source_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { - switch (e.Action) { - case NotifyCollectionChangedAction.Add: foreach (T item in e.NewItems) _insert_sorted(item); return; - case NotifyCollectionChangedAction.Remove: foreach (T item in e.OldItems) Remove(item); return; - default: - if (e.OldItems != null) foreach (T item in e.OldItems) Remove(item); - if (e.NewItems != null) foreach (T item in e.NewItems) _insert_sorted(item); - return; - } - } - - private void _insert_sorted(T item) { _insert_sorted(item, 0, Count); } - // Takes advantage of the fact that all elements are assumed to be sorted, recursively hones in on the insert index. - private void _insert_sorted(T item, int index_range_begin, int index_range_end) { - if (index_range_begin == index_range_end) { Insert(index_range_begin, item); return; } - if (index_range_end == (index_range_begin + 1)) { - if (_comparer.Compare(item, this[index_range_begin]) <= 0) Insert(index_range_begin, item); - else Insert(index_range_end, item); - return; - } - int middle_index = index_range_begin + (int)((index_range_end - index_range_begin) * 0.5); - int comp = _comparer.Compare(item, this[middle_index]); - if (comp > 0) _insert_sorted(item, middle_index + 1, index_range_end); - else if (comp < 0) { - if (_comparer.Compare(item, this[middle_index - 1]) >= 0) { Insert(middle_index, item); return; } - _insert_sorted(item, index_range_begin, middle_index - 1); - } - else { Insert(middle_index, item); return; } - } - } -} \ No newline at end of file diff --git a/src/client/spark/view/Controls/DataGridEx/Filters/VM/DiscreteValuesFilterVM.cs b/src/client/spark/view/Controls/DataGridEx/Filters/VM/DiscreteValuesFilterVM.cs index b00374fa1..861292a4f 100644 --- a/src/client/spark/view/Controls/DataGridEx/Filters/VM/DiscreteValuesFilterVM.cs +++ b/src/client/spark/view/Controls/DataGridEx/Filters/VM/DiscreteValuesFilterVM.cs @@ -167,11 +167,11 @@ namespace mbts.spark.filters { _selected_items_set = new HashSet(_equality_comparer); _items_set = new HashSet(_equality_comparer); _unsorted_items = new ObservableCollection(); - items = comparer != null ? new ObservableSortedCollection(_unsorted_items, comparer) : _unsorted_items; + items = comparer != null ? ObservableAutoWrapper.create_sorted_wrapper(_unsorted_items, comparer) : ObservableAutoWrapper.create_read_only_wrapper(_unsorted_items); selected_items.CollectionChanged += _on_selected_items_CollectionChanged; } - public ObservableCollection items { get; } + public IReadOnlyObservableCollection items { get; } public ObservableCollectionEx selected_items { get; } = new ObservableCollectionEx(); public void Dispose() { diff --git a/src/client/spark/view/Controls/DataGridEx/Model/DataGridExModel.cs b/src/client/spark/view/Controls/DataGridEx/Model/DataGridExModel.cs index 14ed984e3..7591bf245 100644 --- a/src/client/spark/view/Controls/DataGridEx/Model/DataGridExModel.cs +++ b/src/client/spark/view/Controls/DataGridEx/Model/DataGridExModel.cs @@ -1,13 +1,7 @@ -using mbts.collections; -using mbts.ui.shell; +using mbts.ui.shell; using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.Linq; -namespace mbts.ui.controls -{ +namespace mbts.ui.controls { public interface IDataGridExRow { object get_cell(object col_key); @@ -28,25 +22,6 @@ namespace mbts.ui.controls void update(TData data); } - public class DataGridExRowCollection : ObservableSortedCollection, IComparer where TRow : IDataGridExRow - { - public DataGridExRowCollection(ObservableCollection source) : base (source) { - hierarchical_sorting = new ObservableCollection, bool>>(); - hierarchical_sorting.CollectionChanged += (s, e) => sort(); - comparer = this; - } - - public ObservableCollection, bool>> hierarchical_sorting { get; private set; } - - public int Compare(TRow x, TRow y) { - foreach(var tup in hierarchical_sorting) { - int c = tup.Item1(x, y); - if (c != 0) return tup.Item2 ? c : -c; - } - return 0; - } - } - public abstract class DataGridExRow : ViewModelBase, IDataGridExRow, IDataGridExRow { protected DataGridExRow() { } diff --git a/src/client/spark_core/Collections/IObservableCollection.cs b/src/client/spark_core/Collections/IObservableCollection.cs index 99e4fdabd..ec74eee64 100644 --- a/src/client/spark_core/Collections/IObservableCollection.cs +++ b/src/client/spark_core/Collections/IObservableCollection.cs @@ -4,4 +4,7 @@ using System.Collections.Specialized; namespace bts.collections { interface IReadOnlyObservableCollection : IReadOnlyList, IReadOnlyCollection, INotifyCollectionChanged { } interface IObservableCollection : IList, INotifyCollectionChanged { } + interface IObservableCollectionAddRemoveOnly : ICollection, IReadOnlyObservableCollection { + new int Count { get; } + } } \ No newline at end of file diff --git a/src/client/spark_core/Collections/ObservableSortedCollection.cs b/src/client/spark_core/Collections/ObservableSortedCollection.cs new file mode 100644 index 000000000..5384a18df --- /dev/null +++ b/src/client/spark_core/Collections/ObservableSortedCollection.cs @@ -0,0 +1,144 @@ +using bts.utils; +using mbts; +using mbts.utils; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.ComponentModel; + +namespace bts.collections { + /// + /// Supports duplicate items (sort doesn't have to be deterministic). + /// + public class ObservableSortedCollection : IObservableCollectionAddRemoveOnly, INotifyPropertyChanged { + IComparer _comparer; + IEqualityComparer _eq_comparer; + T[] _values; + int _size; + + public ObservableSortedCollection() + : this(Comparer.Default) { } + + public ObservableSortedCollection(IComparer comparer) + : this(comparer, EqualityComparer.Default) { } + + public ObservableSortedCollection(IComparer comparer, IEqualityComparer eq_comparer, int capacity = 4) { + _comparer = comparer ?? throw new ArgumentNullException(nameof(comparer)); + _eq_comparer = eq_comparer ?? throw new ArgumentNullException(nameof(eq_comparer)); + _values = new T[capacity > 0 ? capacity : throw ExceptionBuilder.ArgumentOutOfRange.lte_zero(nameof(capacity))]; + } + + public event NotifyCollectionChangedEventHandler CollectionChanged; + public event PropertyChangedEventHandler PropertyChanged; + + public T this[int index] => _values[index]; + public int Count => _size; + + public bool IsReadOnly => false; + + public IComparer comparer { + get => _comparer; + set { + _comparer = value ?? throw new ArgumentNullException(nameof(value)); + _resort(); + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(comparer))); + } + } + + public void Add(T item) { + int i = _binary_search(item); + _insert_and_notify(i < 0 ? ~i : i, item); + } + + public void Clear() { + if (_size > 0) { + Array.Clear(_values, 0, _size); + _size = 0; + CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Count))); + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(CollectionHelper.indexer_name)); + } + } + + public bool Contains(T item) => _binary_search(item) >= 0; + public void CopyTo(T[] array, int arrayIndex) => Array.Copy(_values, 0, array, arrayIndex, _size); + public bool Remove(T item) { + int pos = _binary_search(item); + if (pos < 0) + return false; + _remove_and_notify(pos); + return true; + } + + public IEnumerator GetEnumerator() { + for (int i = 0; i < _size; i++) + yield return _values[i]; + } + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + void _resort() { + var new_values = new T[_values.Length]; + Array.Copy(_values, 0, new_values, 0, _size); + Array.Sort(new_values, 0, _size, _comparer); + new ListWrapper(this).sync_with(new_values.WrapSubRange(0, _size), _eq_comparer); + } + + int _binary_search(T item) => + CollectionHelper.binary_search(_values, item, 0, _size, _comparer, _eq_comparer); + + void _insert_and_notify(int index, T item) { + ArrayHelper.insert(ref _values, index, item, ref _size); + CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index)); + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Count))); + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(CollectionHelper.indexer_name)); + } + + void _remove_and_notify(int index) { + var cc = CollectionChanged; + if (cc == null) { + ArrayHelper.remove_at(ref _values, ref _size, index); + } else { + var old_item = _values[index]; + ArrayHelper.remove_at(ref _values, ref _size, index); + cc(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, old_item, index)); + } + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Count))); + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(CollectionHelper.indexer_name)); + } + + /// This impl should not be exposed to the public, + /// as it has the potential to break the sort order via incorrect Insert calls. + /// The only reason it is used internally is to call . + class ListWrapper : IList { + readonly ObservableSortedCollection _target; + + public ListWrapper(ObservableSortedCollection target) => + _target = target; + + public T this[int index] { + get => _target[index]; + set { + _target._remove_and_notify(index); + _target._insert_and_notify(index, value); + } + } + + public int Count => _target.Count; + public bool IsReadOnly => false; + + public void Insert(int index, T item) => _target._insert_and_notify(index, item); + public void RemoveAt(int index) => _target._remove_and_notify(index); + public IEnumerator GetEnumerator() => _target.GetEnumerator(); + + int IList.IndexOf(T item) => _target._binary_search(item); + void ICollection.Add(T item) => _target.Add(item); + void ICollection.Clear() => _target.Clear(); + bool ICollection.Contains(T item) => _target.Contains(item); + void ICollection.CopyTo(T[] array, int arrayIndex) => _target.CopyTo(array, arrayIndex); + bool ICollection.Remove(T item) => _target.Remove(item); + IEnumerator IEnumerable.GetEnumerator() => _target.GetEnumerator(); + } + } +} \ No newline at end of file diff --git a/src/client/spark_core/utils/ArrayUtils.cs b/src/client/spark_core/utils/ArrayUtils.cs index 3c9d3a70f..9628ed105 100644 --- a/src/client/spark_core/utils/ArrayUtils.cs +++ b/src/client/spark_core/utils/ArrayUtils.cs @@ -1,4 +1,5 @@ -using System; +using mbts.utils; +using System; using System.Collections.Generic; namespace bts.utils { @@ -44,16 +45,45 @@ namespace bts.utils { return rv; } - public static T[] remove(T[] source, T value) { - int i = Array.IndexOf(source, value); - return i < 0 ? source : remove_at(source, i); + public static void insert(ref T[] array, int index, T value, ref int size) { + // validate size/index + if (size < 0) + throw ExceptionBuilder.ArgumentOutOfRange.lt_zero(nameof(size)); + if (size > array.Length) + throw ExceptionBuilder.ArgumentOutOfRange.gt_length(nameof(size)); + if (index < 0) + throw ExceptionBuilder.IndexOutOfRange.lt_zero(); + if (index > size) + throw ExceptionBuilder.IndexOutOfRange.gt_length(); + T[] old_array = array; + checked { + if (size == array.Length) { + array = new T[array.Length * 2]; + Array.Copy(old_array, 0, array, 0, index); + } + if (index < size) + Array.Copy(old_array, index, array, index + 1, size - index); + array[index] = value; + size++; + } } - public static T[] remove_at(T[] array, int index) { - T[] clone = new T[array.Length - 1]; - Array.Copy(array, 0, clone, 0, index); - Array.Copy(array, index + 1, clone, index, clone.Length - index); - return clone; + public static void remove_at(ref T[] array, ref int size, int index) { + // validate size/index + if (size < 0) + throw ExceptionBuilder.ArgumentOutOfRange.lt_zero(nameof(size)); + if (size > array.Length) + throw ExceptionBuilder.ArgumentOutOfRange.gte_length(nameof(size)); + if (index < 0) + throw ExceptionBuilder.IndexOutOfRange.lt_zero(); + if (index >= size) + throw ExceptionBuilder.IndexOutOfRange.gte_length(); + // shift [any]items right of 'index' left 1 pos. + if (index < size - 1) { + Array.Copy(array, index + 1, array, index, size - index - 1); + } + // clear last item, and decrement size + Array.Clear(array, --size, 1); } public static void remove_sorted(ref T[] array, ref int size, T value, IComparer comparer) => diff --git a/src/client/spark_core/utils/CollectionHelper.cs b/src/client/spark_core/utils/CollectionHelper.cs index 9009e1765..467590e0d 100644 --- a/src/client/spark_core/utils/CollectionHelper.cs +++ b/src/client/spark_core/utils/CollectionHelper.cs @@ -7,6 +7,8 @@ using System.Linq; namespace bts.utils { static class CollectionHelper { + public const string indexer_name = "Item[]"; + public static int binary_search(IList items, T value, IComparer comparer) => binary_search(items, value, 0, items.Count, comparer); @@ -27,6 +29,54 @@ namespace bts.utils { return ~lo; } + /// + /// Like , but doesn't require deterministic sort + /// (i.e., a comparison of adjacent items in the collection may yield '0'). + /// + public static int binary_search(IList items, T value, IComparer comparer, IEqualityComparer eq_comparer) => + binary_search(items, value, 0, items.Count, comparer, eq_comparer); + + /// + /// Like , but doesn't require deterministic sort + /// (i.e., a comparison of adjacent items in the collection may yield '0'). + /// + public static int binary_search(IList items, T value, int index, int length, IComparer comparer, IEqualityComparer eq_comparer) { + if (comparer == null) comparer = Comparer.Default; + int lo = index; + int hi = index + length - 1; + while (lo <= hi) { + int i = lo + ((hi - lo) >> 1); + int c = comparer.Compare(items[i], value); + if (c == 0) { + if (eq_comparer.Equals(items[i], value)) { + return i; + } else { + lo = i; + goto try_find_exact; + } + } + if (c < 0) { + lo = i + 1; + } else { + hi = i - 1; + } + } + return ~lo; + try_find_exact: + // move right + for (hi = lo + 1; hi < items.Count && comparer.Compare(items[hi], value) == 0; hi++) { + if (eq_comparer.Equals(items[hi], value)) + return hi; + } + hi = lo; + // move left + while (--lo >= 0 && comparer.Compare(items[lo], value) == 0) { + if (eq_comparer.Equals(items[lo], value)) + return lo; + } + return ~hi; + } + public static void reflect_change(IList target, IEnumerable source, Func create_item, Action on_removed, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: diff --git a/src/client/spark/core/Utility/ComparerBuilder.cs b/src/client/spark_core/utils/ComparerBuilder.cs similarity index 100% rename from src/client/spark/core/Utility/ComparerBuilder.cs rename to src/client/spark_core/utils/ComparerBuilder.cs diff --git a/src/client/spark_core/utils/Exceptions/ExceptionBuilder.cs b/src/client/spark_core/utils/Exceptions/ExceptionBuilder.cs index e5763b63b..5c6515ac3 100644 --- a/src/client/spark_core/utils/Exceptions/ExceptionBuilder.cs +++ b/src/client/spark_core/utils/Exceptions/ExceptionBuilder.cs @@ -20,6 +20,9 @@ namespace mbts.utils { public static IndexOutOfRangeException lt_zero() => new IndexOutOfRangeException("Index is less than 0"); + public static IndexOutOfRangeException gt_length() => + new IndexOutOfRangeException("Index is greater than the number of elements."); + public static IndexOutOfRangeException gte_length() => new IndexOutOfRangeException("Index is greater than or equal to the number of elements."); } @@ -28,6 +31,12 @@ namespace mbts.utils { public static ArgumentOutOfRangeException lt_zero(string name) => new ArgumentOutOfRangeException(name, "Value is less than 0."); + public static ArgumentOutOfRangeException lte_zero(string name) => + new ArgumentOutOfRangeException(name, "Value is less than or equal to 0."); + + public static ArgumentOutOfRangeException gt_length(string name) => + new ArgumentOutOfRangeException(name, "Value is greater than the number of elements."); + public static ArgumentOutOfRangeException gte_length(string name) => new ArgumentOutOfRangeException(name, "Value is greater than or equal to the number of elements."); } diff --git a/src/client/spark_test/Collections/ObservableSortedCollectionTests.cs b/src/client/spark_test/Collections/ObservableSortedCollectionTests.cs new file mode 100644 index 000000000..886e4fe88 --- /dev/null +++ b/src/client/spark_test/Collections/ObservableSortedCollectionTests.cs @@ -0,0 +1,267 @@ +using bts.test; +using bts.collections; +using mbts; +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Linq; + +namespace bts.tests { + [TestGroup] + class ObservableSortedCollectionTests { + const int + _max_age = 100, + _population_size = 512; + + static readonly string[] _first_names = new[] { + "Jobin", + "Fred", + "Tina", + "Mac", + "Dee", + "Bebe", + "Doug", + "Maria", + "Meredith", + "Penelope", + "Gerald" + }; + + static readonly string[] _last_names = new[] { + "Pancake", + "Stack", + "Benedict", + "Arnold", + "French", + "Woods", + "Santa Claus", + "Appleseed", + "Hill", + "Hootie" + }; + + static readonly Random _rand = new Random(); + + [Test] + public void test() { + var random_people = Enumerable.Range(0, _population_size).Select(_ => _mk_random_person()).ToList(); + var sorted_people = new ObservableSortedCollection(PersonComparers.age); + // use echo list to build a collection in response to collection changed events, + // to verify they are always fired, and always with the right indices + var echo_list = new List(); + // in the collection changed callback, the relative position of the incremental changes is asserted according to the current sorted_people's comparer. + // Such assertions are not valid while the collection is synchronizing with a new comparer, as the changes are optimized (internally, the collection uses sync_with). + bool is_resorting = false; + sorted_people.CollectionChanged += echo_collection_change; + + impl(PersonComparers.age); + impl(PersonComparers.last_name); + impl(PersonComparers.first_name); + // + void impl(IComparer comp) { + // pre test comparer change: + // 1) add all + // 2) change the comparer + // 3) remove all + _test_add_all(sorted_people, echo_list, random_people); + is_resorting = true; + _assert_change_comparer(sorted_people, echo_list, comp); + is_resorting = false; + _test_clear(sorted_people, echo_list); + // main test + _test(sorted_people, echo_list, random_people); + } + + void echo_collection_change(object sender, NotifyCollectionChangedEventArgs e) { + switch (e.Action) { + case NotifyCollectionChangedAction.Add: + Assert.That(e.NewItems != null, "NewItems is null."); + Assert.That(e.NewItems != null && e.NewItems.Count == 1, $"NewItems has {e.NewItems.Count} items (expected 1)."); + Assert.That(e.NewStartingIndex >= 0, "NewStartingIndex is less than 0."); + Assert.That(e.NewStartingIndex <= echo_list.Count, $"NewStartingIndex is less than {nameof(echo_list)} Count."); + Assert.That(e.NewItems[0] is Person, $"NewItems element is not of the expected type '{typeof(Person)}.'"); + var new_person = (Person)e.NewItems[0]; + if (!is_resorting) { + if (e.NewStartingIndex > 0) { + Assert.That(sorted_people.comparer.Compare(echo_list[e.NewStartingIndex - 1], new_person) <= 0); + } + if (e.NewStartingIndex < echo_list.Count - 1) { + Assert.That(sorted_people.comparer.Compare(echo_list[e.NewStartingIndex + 1], new_person) >= 0); + } + } + for (int i = 0; i < e.NewItems.Count; i++) + echo_list.Insert(e.NewStartingIndex + i, (Person)e.NewItems[i]); + break; + case NotifyCollectionChangedAction.Remove: + Assert.That(e.OldItems != null, "OldItems is null."); + Assert.That(e.OldItems != null && e.OldItems.Count == 1, $"OldItems has {e.OldItems.Count} items (expected 1)."); + Assert.That(e.OldStartingIndex >= 0, "OldStartingIndex is less than 0."); + Assert.That(e.OldStartingIndex < echo_list.Count, $"OldStartingIndex is less than {nameof(echo_list)} Count."); + var old_person = (Person)e.OldItems[0]; + if (!is_resorting) { + if (e.OldStartingIndex > 0) { + Assert.That(sorted_people.comparer.Compare(echo_list[e.OldStartingIndex - 1], old_person) <= 0); + } + if (e.OldStartingIndex < echo_list.Count - 1) { + Assert.That(sorted_people.comparer.Compare(echo_list[e.OldStartingIndex + 1], old_person) >= 0); + } + } + for (int i = 0; i < e.OldItems.Count; i++) + echo_list.RemoveAt(e.OldStartingIndex); + break; + case NotifyCollectionChangedAction.Reset: + Assert.That(e.OldItems == null, $"OldItems should be null in {e.Action} events."); + Assert.That(e.NewItems == null, $"NewItems should be null in {e.Action} events."); + Assert.That(e.OldStartingIndex == -1, $"OldStartingIndex should be -1 in {e.Action} events."); + Assert.That(e.NewStartingIndex == -1, $"NewStartingIndex should be -1 in {e.Action} events."); + Assert.That(sorted_people.Count == 0, $"ObservableSortedCollection should not have any elements during {e.Action} event callbacks."); + echo_list.Clear(); + break; + default: + Assert.Failure($"NotifyCollectionChange {e.Action} events not supported."); + break; + } + } + } + + static Person _mk_random_person() => + new Person( + _first_names[_rand.Next() % _first_names.Length], + _last_names[_rand.Next() % _last_names.Length], + _rand.Next(_max_age)); + + void _test(ObservableSortedCollection sorted_people, List echo_list, IReadOnlyList population) { + // there are a lot of redundant checks among these micro tests; this is another one. + Assert.That(population.Count == _population_size, $"{nameof(population)} should have {_population_size} elements at the beginning of this test (sub)routine."); + Assert.That(sorted_people.Count == 0, $"{nameof(sorted_people)} should be empty at the beginning of this test (sub)routine."); + // add all + add_all(); + // remove all + remove_all(); + // clear (add all back to prepare) + add_all(); + _test_clear(sorted_people, echo_list); + // remove overflow (add all back to prepare) + add_all(); + var rand_person = _rand.choose(sorted_people); + remove_overflow(rand_person); + // add duplicates back + const int overflow_count = 3; + int diff = population.Count - sorted_people.Count; + Assert.That(diff > 0, $"{nameof(remove_overflow)} subroutine should have terminated with {nameof(sorted_people)} having fewer people than the total {nameof(population)}."); + using (_begin_test(sorted_people, echo_list)) + _assert_add(sorted_people, echo_list, rand_person, diff + overflow_count); + Assert.That(sorted_people.Count == population.Count + overflow_count, $"Add overflow op should have terminated with {nameof(sorted_people)} having {overflow_count} more people than the total {nameof(population)}."); + // remove all to reset the state + remove_all(); + Assert.That(sorted_people.Count == overflow_count && sorted_people.All(p => p.Equals(rand_person)), + $"{nameof(remove_all)} should have terminated with {nameof(sorted_people)} being empty except for the {overflow_count} overflow/duplicate items."); + _test_clear(sorted_people, echo_list); + // impl + void add_all() => + _test_add_all(sorted_people, echo_list, population); + + void remove_all() { + using (_begin_test(sorted_people, echo_list)) { + foreach (var p in population) + _assert_remove(sorted_people, echo_list, p); + } + } + + void remove_overflow(Person person) { + int instance_count = sorted_people.Count(p => p.Equals(person)); + Assert.That(instance_count > 0, "Expected at least 1 instance of a person chosen randomly from the population."); + Assert.AreEqual(instance_count, echo_list.FindAll(p => p.Equals(person)).Count); + using (_begin_test(sorted_people, echo_list)) + _assert_remove(sorted_people, echo_list, person, instance_count + overflow_count, overflow_count); + } + } + + void _test_add_all(ObservableSortedCollection source, List echo_list, IReadOnlyList population) { + Assert.That(source.Count == 0, $"{nameof(source)} should not have any elements present when beginning {nameof(_test_add_all)}."); + Assert.That(population.Count > 0, $"{nameof(population)} should have some elements present when beginning {nameof(_test_add_all)}."); + using (_begin_test(source, echo_list)) { + foreach (var p in population) + _assert_add(source, echo_list, p); + } + } + + void _test_clear(ObservableSortedCollection source, List echo_list) { + using (_begin_test(source, echo_list)) { + source.Clear(); + Assert.That(source.Count == 0, "Source collection did not actually clear its elements."); + } + } + + void _test_remove_all(ObservableSortedCollection source, List echo_list, IReadOnlyList population) { + Assert.That(source.Count > 0, $"{nameof(source)} should have some elements present when beginning {nameof(_test_remove_all)}."); + using (_begin_test(source, echo_list)) { + foreach (var p in population) + _assert_remove(source, echo_list, p); + } + } + + void _assert_add(ObservableSortedCollection source, List echo_list, Person person, int add_count = 1) { + int source_count = source.Count; + int already_present = source.Where(p => p.Equals(person)).Count(); + for (int i = add_count; i > 0; i--) { + source.Add(person); + Assert.That(source.Count == ++source_count, "Add op did not increment Count."); + } + Assert.That(source.Where(p => p.Equals(person)).Count() == add_count + already_present); + } + + void _assert_remove(ObservableSortedCollection source, List echo_list, Person person) { + int orig_count = source.Count; + source.Remove(person); + Assert.That(source.Count == orig_count - 1, "Remove op did not decrement Count."); + } + + void _assert_remove(ObservableSortedCollection source, List echo_list, Person person, int remove_count, int expected_overflow) { + _assert_instance_count(source, person, remove_count - expected_overflow); + int orig_count = source.Count; + while (remove_count-- > expected_overflow) { + source.Remove(person); + Assert.That(source.Count == --orig_count, "Remove op did not decrement Count."); + } + while (expected_overflow-- > 0) { + source.Remove(person); + Assert.That(source.Count == orig_count, "Remove op decremented the Count when it was expected to overflow (i.e., there were not supposed to be any instances of the value left to remove)."); + } + _assert_instance_count(source, person, 0); + } + + void _assert_change_comparer(ObservableSortedCollection source, List echo_list, IComparer new_comparer) { + source.comparer = new_comparer; + _assert_in_sync(source, echo_list); + } + + void _assert_instance_count(ObservableSortedCollection source, Person person, int expected_instances) => + Assert.That(source.Where(p => p.Equals(person)).Count() == expected_instances, + "Expected a different number of instances of the specified person."); + + void _assert_in_sync(ObservableSortedCollection source, List echo_list) { + Assert.That(_is_sorted(echo_list, source.comparer)); + Assert.That(source.SequenceEqual(echo_list), "Bad state: echo list sequence differs from source "); + } + + bool _is_sorted(IEnumerable vals, IComparer comparer) { + using (var en = vals.GetEnumerator()) { + if (en.MoveNext()) { + var last_val = en.Current; + while (en.MoveNext()) { + if (comparer.Compare(en.Current, last_val) < 0) + return false; + last_val = en.Current; + } + } + } + return true; + } + + IDisposable _begin_test(ObservableSortedCollection source, List echo_list) { + _assert_in_sync(source, echo_list); + return Disposable.Create(() => _assert_in_sync(source, echo_list)); + } + } +} \ No newline at end of file diff --git a/src/client/spark_test/Utils/Data/Person.cs b/src/client/spark_test/Utils/Data/Person.cs new file mode 100644 index 000000000..1adc62621 --- /dev/null +++ b/src/client/spark_test/Utils/Data/Person.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; + +namespace bts.tests { + static class PersonComparers { + public static readonly IComparer + first_name = Comparer.Create((a, b) => string.Compare(a.first_name, b.first_name)), + last_name = Comparer.Create((a, b) => string.Compare(a.last_name, b.last_name)), + age = Comparer.Create((a, b) => a.age.CompareTo(b.age)); + } + + struct Person : IEquatable, IComparable { + public readonly string first_name, last_name; + public readonly int age; + + public Person(string first_name, string last_name, int age) { + this.first_name = first_name; + this.last_name = last_name; + this.age = age; + } + + public int CompareTo(Person other) { + int comp = string.Compare(last_name, other.last_name); + if (comp != 0) + return comp; + comp = string.Compare(first_name, other.first_name); + if (comp != 0) + return comp; + comp = age.CompareTo(other.age); + return comp; + } + + public bool Equals(Person other) => + first_name == other.first_name && + last_name == other.last_name && + age == other.age; + + public override bool Equals(object obj) => + obj is Person other && Equals(other); + + public override int GetHashCode() => + ((first_name?.GetHashCode() ?? 0) % (1 << 9)) | + (((last_name?.GetHashCode() ?? 0) % (1 << 9)) << 10) | + ((age % (1 << 9)) << 20); + + public static bool operator ==(Person a, Person b) => a.Equals(b); + public static bool operator !=(Person a, Person b) => !a.Equals(b); + } +} \ No newline at end of file From a363421de0212b205fa9cf0eada6a1c8f0b68ba0 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Thu, 18 Jul 2019 17:51:42 -0500 Subject: [PATCH 03/20] fix CommonValueMonitor 'SubscribeThrottled()' extensions --- .../spark/core/Utility/CommonValueMonitor.cs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/client/spark/core/Utility/CommonValueMonitor.cs b/src/client/spark/core/Utility/CommonValueMonitor.cs index a57c7dfe3..5fdcd4bca 100644 --- a/src/client/spark/core/Utility/CommonValueMonitor.cs +++ b/src/client/spark/core/Utility/CommonValueMonitor.cs @@ -284,8 +284,9 @@ namespace bts.utils { dirty = true; return; } - dirty = false; + busy = true; do { + dirty = false; o.OnNext(monitor.common_value); await Task.Delay(throttle); } while (dirty); @@ -304,8 +305,9 @@ namespace bts.utils { dirty = true; return; } - dirty = false; + busy = true; do { + dirty = false; notify(); await Task.Delay(throttle); } while (dirty); @@ -326,8 +328,9 @@ namespace bts.utils { dirty = true; return; } - dirty = false; + busy = true; do { + dirty = false; notify(); await Task.Delay(throttle); } while (dirty); @@ -354,8 +357,9 @@ namespace bts.utils { dirty = true; return; } - dirty = false; + busy = true; do { + dirty = false; notify(); await Task.Delay(throttle); } while (dirty); @@ -379,8 +383,9 @@ namespace bts.utils { dirty = true; return; } - dirty = false; + busy = true; do { + dirty = false; o.OnNext(monitor.plurality); await Task.Delay(throttle); } while (dirty); From c1f7b030ba7b8020344ba1be6ba30af8ccc64e74 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Sun, 21 Jul 2019 21:52:49 -0500 Subject: [PATCH 04/20] remove unused algo 'template' code, leftover from the original algo studio spec --- src/client/spark/Daemons/ShellServices.cs | 33 +- .../AlgoStudio/AlgoPersistenceHelper.cs | 112 ------ .../Trading/AlgoStudio/AlgoStudioView.xaml | 184 ++------- .../Trading/AlgoStudio/AlgoStudioView.xaml.cs | 22 +- .../AlgoStudio/AlgoStudioViewController.cs | 82 +--- .../Trading/AlgoStudio/AlgoStudioWindow.cs | 68 +--- .../AlgoStudioDefinitionTemplateModel.cs | 319 --------------- .../Model/AlgoStudioFlatDefinitionModel.cs | 8 +- .../AlgoStudio/Model/IAlgoStudioModel.cs | 26 +- .../AlgoStudio/VM/AlgoDefinitionTemplateVM.cs | 243 ------------ .../Trading/AlgoStudio/VM/AlgoDefinitionVM.cs | 99 +---- .../Trading/AlgoStudio/VM/AlgoStudioVM.cs | 164 +++----- .../Trading/Ladder/VM/LadderSettingsVM.cs | 2 +- .../Modules/Trading/OrderBook/OrderBookVM.cs | 13 +- .../spark/Orders/OrderPropertiesEditorVM.cs | 202 ++-------- .../Order/AlgoContentTemplateSelector.xaml | 8 - .../Order/AlgoContentTemplateSelector.xaml.cs | 4 +- .../Controls/Order/AlgoPickerNodeView.xaml.cs | 2 +- .../AlgoTemplateFavoriteButtonsView.xaml | 43 +- .../Controls/Order/AlgoTemplateToolBar.xaml | 223 +---------- .../Order/AlgoTemplateToolBar.xaml.cs | 366 ------------------ .../Controls/Order/AlgoTemplateTreeView.xaml | 270 ------------- .../Order/AlgoTemplateTreeView.xaml.cs | 33 -- .../Order/OrderDetailsPopupControl.xaml | 49 +-- src/lib/config/protos/UI.proto | 25 +- 25 files changed, 171 insertions(+), 2429 deletions(-) delete mode 100644 src/client/spark/Modules/Trading/AlgoStudio/AlgoPersistenceHelper.cs delete mode 100644 src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStudioDefinitionTemplateModel.cs delete mode 100644 src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionTemplateVM.cs delete mode 100644 src/client/spark/view/Controls/Order/AlgoTemplateTreeView.xaml delete mode 100644 src/client/spark/view/Controls/Order/AlgoTemplateTreeView.xaml.cs diff --git a/src/client/spark/Daemons/ShellServices.cs b/src/client/spark/Daemons/ShellServices.cs index bcfd91e6e..eb8c4ed65 100644 --- a/src/client/spark/Daemons/ShellServices.cs +++ b/src/client/spark/Daemons/ShellServices.cs @@ -2,6 +2,7 @@ using bts.api.core; using bts.api.md.auxiliary; using bts.api.orderman; +using bts.api.orderman.algo; using bts.api.persistence; using bts.api.position; using bts.api.synthetic; @@ -45,41 +46,11 @@ namespace Spark { [Export] public MarketDataRelay md_replay => context.locate(); - //[Export] - //public AlgoService algo_service => context.locate(); - AlgoServiceWrapper _algo_service_wrapper; [Export] - public AlgoServiceWrapper algo_service_wrapper => _algo_service_wrapper ?? (_algo_service_wrapper = new AlgoServiceWrapper(context)); + public AlgoDefinitionService algo_definition_service => context.locate(); [Export] public MBOService mbo_service => context.locate(); } - - class AlgoServiceWrapper { - public enum Mode { - None, - Hierarchical, - Flat - } - - public AlgoServiceWrapper(ServiceContext context) { - var flat_model_options = mbts.config.Configuration.get(); - if (flat_model_options.enabled) { - flat = context.locate(); - } else { - hierarhical = context.locate(); - } - } - - public AlgoService hierarhical { get; } - public bts.api.orderman.algo.AlgoDefinitionService flat { get; } - public Mode mode { - get { - if (hierarhical != null) return Mode.Hierarchical; - if (flat != null) return Mode.Flat; - return Mode.None; - } - } - } } diff --git a/src/client/spark/Modules/Trading/AlgoStudio/AlgoPersistenceHelper.cs b/src/client/spark/Modules/Trading/AlgoStudio/AlgoPersistenceHelper.cs deleted file mode 100644 index 2660bc149..000000000 --- a/src/client/spark/Modules/Trading/AlgoStudio/AlgoPersistenceHelper.cs +++ /dev/null @@ -1,112 +0,0 @@ -using bts.api.core; -using bts.collections; -using mbts.collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Threading.Tasks; - -namespace mbts.spark { - /// - /// This class's primary purpose is to handle async AlgoService persistence calls for the AlgoStudioVM/OrderPropertiesEditorVM. - /// When a new definition/template item is persisted for the first time, it's corresponding viewmodel (, ) - /// must be removed and replaced with a new one that has the brand new persisted id (). As part of its duty, this class makes sure that the new persisted items are inserted into the same index as their unpersisted predecessor. - /// - static class AlgoPersistenceHelper { - public static (int? def_index, int? tmp_index) selection_snapshot(IList definitions, AlgoDefinitionVM selected_definition, AlgoDefinitionTemplateVM selected_template) { - var def = selected_definition; - var tmp = selected_template; - int? def_index = def == null ? (int?)null : definitions.IndexOf(def); - int? tmp_index = tmp == null ? (int?)null : tmp.owner.templates.IndexOf(tmp); - return (def_index, tmp_index); - } - - public static async Task> persist_definition(OrdersModel model, IList definitions, AlgoDefinitionVM definition) { - int def_index = definitions.IndexOf(definition); - return await persist(model, definitions.WrapSubRange(def_index, 1).WrapSelector(def => (def, definition.templates.AsList()), t => t.def)); - } - - public static async Task> persist_template(OrdersModel model, IList definitions, AlgoDefinitionTemplateVM template) { - switch (template.owner.key.mode) { - case AlgoKey.Mode.Unpersisted: return await persist_definition(model, definitions, template.owner); - case AlgoKey.Mode.Persisted: - int def_index = definitions.IndexOf(template.owner); - int tmp_index = template.owner.templates.IndexOf(template); - return await persist(model, definitions.WrapSubRange(def_index, 1).WrapSelector(def => (def, def.templates.WrapSubRange(tmp_index, 1)), t => t.def)); - default: return DictionaryHelper.empty(); - } - } - - public static async Task> persist_all(OrdersModel model, ObservableKeyedCollection definitions) => - await persist(model, definitions.WrapSelector(def => (def, def.templates.AsList()), t => t.def)); - - /// - /// Persists each pair of definition/templates, then returns a map of non-persisted keys to persisted ones (, , ). - /// The key-map gives callers the ability to replace unpersisted items with persisted ones before the next update arrives. - /// Note: use a to suspend updates while awaiting this task; don't resume them until all unpersisted items have been replaced. - /// caters to this pre-emptive adding behavior, in it's callback, it checks if added items are already present, and if so, treats them as changes instead. - /// PS: the reason for all this madness is so newly persisted items are inserted in the same index as their placeholder counterpart. The only way to connect the non-persisted keys with their persisted counterparts - /// is to await each save-op individually, and build a map with the results..hence the returned key-map. - /// - /// - /// - /// An AlgoKey->AlgoKey map of old placeholder ids to newly persisted ones. - public static async Task> persist(OrdersModel model, IList<(AlgoDefinitionVM definition, IList templates)> definition_templates) { - var placeholder_to_persisted_keys = new Dictionary(); - for (int i = 0; i < definition_templates.Count; i++) { - (var def, var templates) = definition_templates[i]; - var persisted_def = def; - if (def.is_dirty) { - var def_record = await model.algo_model.save_definition(def.create_algo_def()); - if (def_record.HasValue) { - switch (def.key.mode) { - case AlgoKey.Mode.Factory: - case AlgoKey.Mode.Unpersisted: - persisted_def = def.to_persisted(def_record.Value); - foreach (var tmp in templates) { - AlgoDefinitionTemplateVM persisted_tmp; - var tmp_record = await model.algo_model.save_template(tmp.create(def_record.Value)); - if (tmp_record.HasValue) { - persisted_def.templates.Add(persisted_tmp = tmp.to_persisted(persisted_def, new AlgoData(tmp_record.Value.value, tmp_record.Value.name, tmp_record.Value.key))); - } else { - /// If the save-op fails, the unpersisted template is cloned and added to the persisted def's template items, so the user may try to save it again without having to re-enter all the templated-values. - /// Q: "why don't we just re-add the same template to the persisted def, the save-op failed, so nothing changed...why do we need a new one?" - /// A: "A new template vm must be created because its owner has changed (it's a readonly prop, )." - persisted_def.templates.Add(persisted_tmp = new AlgoDefinitionTemplateVM(persisted_def, model, tmp.create_def_data())); - } - placeholder_to_persisted_keys[tmp.key] = persisted_tmp.key; - } - persisted_def.connect(); - if (def.key.mode == AlgoKey.Mode.Unpersisted) { - definition_templates[i] = (persisted_def, persisted_def.templates); - } else { - definition_templates.Add((persisted_def, persisted_def.templates)); - } - placeholder_to_persisted_keys[def.key] = persisted_def.key; - break; - } - } - } else { - // so the def isn't dirty, but it still might have dirty templates - using (persisted_def.buffer_updates()) { - for (int j = 0; j < templates.Count; j++) { - var tmp = templates[j]; - if (!tmp.is_dirty) - continue; - var tmp_record = await model.algo_model.save_template(tmp.create()); - if (tmp_record.HasValue) { - switch (tmp.key.mode) { - case AlgoKey.Mode.Unpersisted: - var persisted_tmp = tmp.to_persisted(persisted_def, new AlgoData(tmp_record.Value.value, tmp_record.Value.name, tmp_record.Value.key)); - templates[j] = persisted_tmp; - placeholder_to_persisted_keys[tmp.key] = persisted_tmp.key; - break; - } - } - } - } - } - } - return placeholder_to_persisted_keys; - } - } -} \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioView.xaml b/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioView.xaml index bd8136fad..07fbecf35 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioView.xaml +++ b/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioView.xaml @@ -12,14 +12,11 @@ xmlns:uag="clr-namespace:mbts.ui.spark.algo" xmlns:uspcv="clr-namespace:mbts.ui.spark.converters" xmlns:sys="clr-namespace:System;assembly=mscorlib" - u:StateManager.VisualState="{Binding content_source.algo_root, Converter={x:Static usp:AlgoStudioView.EditPaneVisualStateConverter}}" + u:StateManager.VisualState="{Binding selected_definition.algo_root, Converter={x:Static usp:AlgoStudioView.EditPaneVisualStateConverter}}" Background="{StaticResource CommonBackground}" > - - - 4 8 @@ -33,9 +30,6 @@ - - - AbbreviationActive AbbreviationInactive @@ -130,70 +124,8 @@ - - @@ -221,94 +153,26 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - - - - - - - + - - + + @@ -430,7 +294,7 @@ Margin="{StaticResource Margin.LP1}" HorizontalAlignment="Stretch" VerticalAlignment="Center" - Text="{Binding content_source.name, UpdateSourceTrigger=PropertyChanged, Delay=25}" + Text="{Binding selected_definition.name, UpdateSourceTrigger=PropertyChanged, Delay=25}" /> @@ -452,7 +316,7 @@ Abbrev. - + @@ -478,8 +342,8 @@ Hint: the default color is that of the algo-root ( ). @@ -496,7 +360,7 @@ x:Name="default_badge" Grid.Column="1" Margin="{StaticResource Margin.LP1}" - Fill="{Binding content_source.algo_root.meta.Color, Converter={StaticResource ColorToBrushConverter}}" + Fill="{Binding selected_definition.algo_root.meta.Color, Converter={StaticResource ColorToBrushConverter}}" Style="{StaticResource RectangleBadgeStyle}" /> @@ -506,7 +370,7 @@ VerticalAlignment="Center" VerticalContentAlignment="Center" Margin="{StaticResource Margin.LP2}" - IsChecked="{Binding content_source.custom_badge_color.enabled}" + IsChecked="{Binding selected_definition.custom_badge_color.enabled}" GroupName="Badge" > @@ -526,7 +390,7 @@ Grid.Row="1" Grid.Column="1" Margin="3,0" - Fill="{Binding content_source.custom_badge_color.value, Converter={StaticResource ColorToBrushConverter}}" + Fill="{Binding selected_definition.custom_badge_color.value, Converter={StaticResource ColorToBrushConverter}}" Style="{StaticResource RectangleBadgeStyle}" /> to open the color picker popup. @@ -541,7 +405,7 @@ - @@ -580,4 +444,4 @@ - \ No newline at end of file + diff --git a/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioView.xaml.cs b/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioView.xaml.cs index 95214f635..f14a1798f 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioView.xaml.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioView.xaml.cs @@ -1,13 +1,10 @@ using mbts.spark; using mbts.ui.converters; -using System; using System.Windows.Controls; using System.Windows.Data; -using System.Windows.Input; namespace mbts.ui.spark { partial class AlgoStudioView : UserControl { - public const string BadgesInTreeViewVisibilityKey = nameof(BadgesInTreeViewVisibilityKey); public static readonly IValueConverter EditPaneVisualStateConverter = ValueConverter.create(obj => obj == null ? VisualStates.Inactive : VisualStates.Active); @@ -18,7 +15,7 @@ namespace mbts.ui.spark { DataContextChanged += (s, e) => set_controller(); set_controller(); // local methods - void set_controller() => Disposable.replace(ref _controller, AlgoStudioViewControllerFactory.create(DataContext, _tree_view, name_text_box, custom_badge_color_picker_button, custom_badge_color_picker_popup)); + void set_controller() => Disposable.replace(ref _controller, AlgoStudioViewControllerFactory.create(DataContext, name_text_box, custom_badge_color_picker_button, custom_badge_color_picker_popup)); } public new AlgoStudioVM DataContext { @@ -28,15 +25,6 @@ namespace mbts.ui.spark { public void add_definition() => _controller.add_definition(); public void add_definition_clone(AlgoDefinitionVM src_definition) => _controller.add_definition_clone(src_definition); - public void add_template(AlgoDefinitionVM definition) => _controller.add_template(definition); - public void rename_definition(AlgoDefinitionVM definition) => _controller.rename_definition(definition); - public void rename_template(AlgoDefinitionTemplateVM template) => _controller.rename_template(template); - public void select_definition(AlgoDefinitionVM definition) => _controller.select_definition(definition); - public void select_template(AlgoDefinitionTemplateVM template) => _controller.select_template(template); - public IDisposable preserve_selected_definition() => _controller.preserve_selected_definition(); - - void _end_edit_executed(object s, ExecutedRoutedEventArgs e) => - _controller.end_edit(e); public static class VisualStateNames { public static class EditPane { @@ -75,14 +63,6 @@ namespace mbts.ui.spark { Inactive = $"{GroupName}{VisualStates.Inactive}"; } - public static class TreeViewBadge { - public const string GroupName = nameof(TreeViewBadge); - - public static readonly string - Active = $"{GroupName}{VisualStates.Active}", - Inactive = $"{GroupName}{VisualStates.Inactive}"; - } - public static class FavoriteToggleButton { public const string GroupName = nameof(FavoriteToggleButton); diff --git a/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioViewController.cs b/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioViewController.cs index dbdbd1f7b..6fa462c60 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioViewController.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioViewController.cs @@ -1,8 +1,6 @@ using mbts.spark; using mbts.ui.controls; using System; -using System.Collections.Generic; -using System.Linq; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; @@ -11,21 +9,14 @@ namespace mbts.ui.spark { interface IAlgoStudioViewController : IDisposable { void add_definition(); void add_definition_clone(AlgoDefinitionVM src_definition); - void add_template(AlgoDefinitionVM definition); - void rename_definition(AlgoDefinitionVM definition); - void rename_template(AlgoDefinitionTemplateVM template); - void end_edit(ExecutedRoutedEventArgs e); - void select_definition(AlgoDefinitionVM definition); - void select_template(AlgoDefinitionTemplateVM template); - IDisposable preserve_selected_definition(); } class AlgoStudioViewControllerFactory { static readonly IAlgoStudioViewController _empty = new EmptyController(); - public static IAlgoStudioViewController create(AlgoStudioVM vm, TreeView tree_view, TextBox name_text_box, Button color_picker_button, Popup color_picker_popup) => - vm == null || tree_view == null || name_text_box == null || color_picker_button == null || color_picker_popup == null ? - _empty : new Controller(vm, tree_view, name_text_box, color_picker_button, color_picker_popup); + public static IAlgoStudioViewController create(AlgoStudioVM vm, TextBox name_text_box, Button color_picker_button, Popup color_picker_popup) => + vm == null || name_text_box == null || color_picker_button == null || color_picker_popup == null ? + _empty : new Controller(vm, name_text_box, color_picker_button, color_picker_popup); /// /// This wrapper class is returned by when the vm or tree_view is null. @@ -34,25 +25,16 @@ namespace mbts.ui.spark { class EmptyController : IAlgoStudioViewController { public void add_definition() { } public void add_definition_clone(AlgoDefinitionVM src_definition) { } - public void add_template(AlgoDefinitionVM definition) { } - public void rename_definition(AlgoDefinitionVM definition) { } - public void rename_template(AlgoDefinitionTemplateVM template) { } - public void end_edit(ExecutedRoutedEventArgs e) { } - public void select_definition(AlgoDefinitionVM definition) { } - public void select_template(AlgoDefinitionTemplateVM template) { } - public IDisposable preserve_selected_definition() => Disposable.empty; public void Dispose() { } } class Controller : IAlgoStudioViewController { readonly AlgoStudioVM _vm; - readonly TreeView _tree_view; readonly TextBox _name_text_box; IDisposable _dispose; - public Controller(AlgoStudioVM vm, TreeView tree_view, TextBox name_text_box, Button color_picker_button, Popup color_picker_popup) { + public Controller(AlgoStudioVM vm, TextBox name_text_box, Button color_picker_button, Popup color_picker_popup) { _vm = vm; - _tree_view = tree_view; _name_text_box = name_text_box; _dispose = PopupViewController.attach(color_picker_popup, color_picker_button); } @@ -67,67 +49,11 @@ namespace mbts.ui.spark { _begin_edit(); } - public void add_template(AlgoDefinitionVM def) { - var new_tmp = def.template_factory(); - def.templates.Add(new_tmp); - _begin_edit(); - } - - public void end_edit(ExecutedRoutedEventArgs e) { - if (e.OriginalSource is EditableTextBlock etb) { - etb.end_edit(); - _get_container(etb.DataContext)?.SetCurrentValue(TreeViewItem.IsSelectedProperty, true); - } - } - - public void rename_definition(AlgoDefinitionVM definition) { - if (_tree_view.ItemContainerGenerator.ContainerFromItem(definition) is TreeViewItem tvi) { - var etb = tvi.descendants_of_type().FirstOrDefault(); - etb.SetCurrentValue(EditableTextBlock.IsEditingProperty, true); - } - } - - public void rename_template(AlgoDefinitionTemplateVM template) { - if (_tree_view.ItemContainerGenerator.ContainerFromItem(template.owner) is TreeViewItem tvi) { - if (tvi.ItemContainerGenerator.ContainerFromItem(template) is TreeViewItem ttvi) { - var etb = ttvi.descendants_of_type().FirstOrDefault(); - etb.SetCurrentValue(EditableTextBlock.IsEditingProperty, true); - } - } - } - - public void select_definition(AlgoDefinitionVM definition) => - _tree_view.ItemContainerGenerator.ContainerFromItem(definition)?.SetCurrentValue(TreeViewItem.IsSelectedProperty, true); - - public void select_template(AlgoDefinitionTemplateVM template) { - if (_tree_view.ItemContainerGenerator.ContainerFromItem(template.owner) is TreeViewItem def_view) { - def_view.SetCurrentValue(TreeViewItem.IsSelectedProperty, true); - def_view.ItemContainerGenerator.ContainerFromItem(template)?.SetCurrentValue(TreeViewItem.IsSelectedProperty, true); - } - } - - public IDisposable preserve_selected_definition() => - Disposable.Create(() => { - var name = _vm.selected_definition.name; - if (_vm.definitions.TryGetFirst(d => d.name == name, out AlgoDefinitionVM def)) - _tree_view.ItemContainerGenerator.ContainerFromItem(def)?.SetCurrentValue(TreeViewItem.IsSelectedProperty, true); - }); - public void Dispose() => Disposable.dispose(ref _dispose); void _begin_edit() => WPFHelper.push_frame_until(() => Keyboard.Focus(_name_text_box) == _name_text_box); - - TreeViewItem _get_container(object obj) => - obj is AlgoDefinitionTemplateVM t ? _get_container(t) : - obj is AlgoDefinitionVM d ? _get_container(d) : null; - - TreeViewItem _get_container(AlgoDefinitionVM d) => - _tree_view.ItemContainerGenerator.ContainerFromItem(d) as TreeViewItem; - - TreeViewItem _get_container(AlgoDefinitionTemplateVM t) => - _get_container(t.owner) is TreeViewItem dview ? dview.ItemContainerGenerator.ContainerFromItem(t) as TreeViewItem : null; } } } \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioWindow.cs b/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioWindow.cs index 24164b38f..d0e80f526 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioWindow.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioWindow.cs @@ -62,35 +62,18 @@ namespace mbts.spark { _vm = new AlgoStudioVM(_model); _vm.load_from(_state); _view = new AlgoStudioView { DataContext = _vm }; - _view.Resources[AlgoStudioView.BadgesInTreeViewVisibilityKey] = _ui_configuration.show_badges_in_tree_view ? Visibility.Visible : Visibility.Collapsed; _resources = new CompositeDisposable(); - // observable sources - var content_src = _vm.observe_selected().Select(_ => _vm.content_source); // add definition _commands.Add(new SparkCommandCommand("Add Algo", Icons.AddBoxes, new DelegateCommand(_view.add_definition))); // add definition clone var add_definition_clone_spark_cmd = new ObservantSparkCommandCommand(Icons.DocumentCopy, d => $"Clone '{d?.name}'", d => d != null, _view.add_definition_clone); _commands.Add(add_definition_clone_spark_cmd); - // add template - var add_template_spark_cmd = new ObservantSparkCommandCommand(Icons.AddFile, d => $"Add '{d?.name}' Template", d => d != null, _view.add_template) { - show_in_toolbar = (_ui_configuration.add_template_button & bts.config.AlgoStudioOptions.AddTemplateButton.MainToolBar) == bts.config.AlgoStudioOptions.AddTemplateButton.MainToolBar, - show_in_context_menu = (_ui_configuration.add_template_button & bts.config.AlgoStudioOptions.AddTemplateButton.DefinitionContextMenu) == bts.config.AlgoStudioOptions.AddTemplateButton.DefinitionContextMenu - }; - _commands.Add(add_template_spark_cmd); - _resources.Add(_vm.subscribe_definition().OnDispatcher().Subscribe(add_definition_clone_spark_cmd, add_template_spark_cmd)); + _resources.Add(_vm.subscribe_definition().OnDispatcher().Subscribe(add_definition_clone_spark_cmd)); // save if (_ui_configuration.can_save_specific) { - var content_is_dirty_src = _vm.observe_selected().SelectManyInSeries(t => { - if (t.template != null) { - return t.template.observe_is_dirty(); - } else if (t.definition != null) { - return t.definition.subscribe_is_definition_dirty(); - } else return Observable.Return(false); - }); - _commands.Add(new ReactiveSparkCommand(content_src.OnDispatcher().Select(c => $"Save '{c?.name}'"), Icons.DiskFile, () => { - if (_vm.selected_template is AlgoDefinitionTemplateVM t) - _vm.save_template(t).ignore(); - else if (_vm.selected_definition is AlgoDefinitionVM d) + var content_is_dirty_src = _vm.subscribe_definition().SelectManyInSeries(def => def?.subscribe_is_definition_dirty() ?? Observable.Return(false)); + _commands.Add(new ReactiveSparkCommand(_vm.subscribe_definition().OnDispatcher().Select(c => $"Save '{c?.name}'"), Icons.DiskFile, () => { + if (_vm.selected_definition is AlgoDefinitionVM d) _vm.save_definition(d).ignore(); }, content_is_dirty_src)); } @@ -101,48 +84,39 @@ namespace mbts.spark { // undo/redo if (_ui_configuration.can_undo_redo) { // undo - var undo_cmd = new ObservantCommand(() => _vm.content_source?.try_undo()); + var undo_cmd = new ObservantCommand(() => _vm.selected_definition?.try_undo()); var undo_spark_cmd = new SparkCommandCommand("Undo", Icons.UndoCircular, undo_cmd); - var can_undo_source = _vm.observe_selected().SelectManyInSeries(tup => { - IAlgoStudioContentVM content = (IAlgoStudioContentVM)tup.template ?? tup.definition; - return content != null ? + var can_undo_source = _vm.subscribe_definition().SelectManyInSeries(def => + def != null ? Observable.Create(o => { - content.can_undo_changed += notify; + def.can_undo_changed += notify; notify(); - return Disposable.Create(() => content.can_undo_changed -= notify); - void notify() => o.OnNext(content.can_undo); + return Disposable.Create(() => def.can_undo_changed -= notify); + void notify() => o.OnNext(def.can_undo); }) : - Observable.Return(false); - }); + Observable.Return(false)); _commands.Add(undo_spark_cmd); _resources.Add(can_undo_source.Subscribe(undo_cmd)); // redo - var redo_cmd = new ObservantCommand(() => _vm.content_source?.try_redo()); + var redo_cmd = new ObservantCommand(() => _vm.selected_definition?.try_redo()); var redo_spark_cmd = new SparkCommandCommand("Redo", Icons.RedoCircular, redo_cmd); - var can_redo_source = _vm.observe_selected().SelectManyInSeries(tup => { - IAlgoStudioContentVM content = (IAlgoStudioContentVM)tup.template ?? tup.definition; - return content != null ? + var can_redo_source = _vm.subscribe_definition().SelectManyInSeries(def => + def != null ? Observable.Create(o => { - content.can_redo_changed += notify; + def.can_redo_changed += notify; notify(); - return Disposable.Create(() => content.can_redo_changed -= notify); - void notify() => o.OnNext(content.can_redo); + return Disposable.Create(() => def.can_redo_changed -= notify); + void notify() => o.OnNext(def.can_redo); }) : - Observable.Return(false); - }); + Observable.Return(false)); _commands.Add(redo_spark_cmd); _resources.Add(can_redo_source.Subscribe(redo_cmd)); } // remove var remove_spark_cmd = new ObservantSparkCommandCommand(Icons.Trash, v => $"Remove '{v?.name}'", v => v != null, value => { - if (value is AlgoDefinitionTemplateVM t) { - _vm.remove_template(t).ignore(); - } else if (value is AlgoDefinitionVM d) { + if (value is AlgoDefinitionVM d) { string prompt; MessageBoxImage icon; - if (_model.algo_model.templates_enabled() && d.templates.Count > 0) { - prompt = $"Deleting this definition ({d.name}) will also delete its templates ({d.templates.Count}).\n\nDo you wan to Continue?"; - icon = MessageBoxImage.Warning; - } else if (d.key.mode == AlgoKey.Mode.Persisted) { + if (d.key.mode == AlgoKey.Mode.Persisted) { prompt = $"Are you sure you want to delete '{d.name}?'"; icon = MessageBoxImage.Question; } else { @@ -162,7 +136,7 @@ namespace mbts.spark { } }); _commands.Add(remove_spark_cmd); - _resources.Add(content_src.OnDispatcher().Subscribe(remove_spark_cmd)); + _resources.Add(_vm.subscribe_definition().OnDispatcher().Subscribe(remove_spark_cmd)); } void _dispose_core() { diff --git a/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStudioDefinitionTemplateModel.cs b/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStudioDefinitionTemplateModel.cs deleted file mode 100644 index b036f0671..000000000 --- a/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStudioDefinitionTemplateModel.cs +++ /dev/null @@ -1,319 +0,0 @@ -using bts; -using bts.api.core; -using bts.api.orderman; -using bts.persist.algo; -using bts.spark; -using mbts.utils; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reactive.Disposables; -using System.Reactive.Linq; -using System.Threading.Tasks; - -namespace mbts.spark { - class AlgoStudioDefinitionTemplateModel : IAlgoStudioModel, IDisposable { - readonly AlgoService _service; - readonly AdminModel _admin_model; - readonly ErrorReporter _error_reporter; - readonly ObservableDemuxer _metadata_demuxer = new ObservableDemuxer(); - readonly TableUpdateDemuxer _definition_templates_demuxer; - IReadOnlyDictionary _algos = DictionaryHelper.empty(); - IReadOnlyDictionary _algo_templates = DictionaryHelper.empty(); - IDisposable _dispose; - - public AlgoStudioDefinitionTemplateModel(AlgoService service, IAlgoDefinitionMetadataService meta, AdminModel admin_model, ErrorReporter error_reporter, bts.config.AlgoStudioOptions ui_configuration) { - _service = service; - metadata_service = meta; - _admin_model = admin_model; - _error_reporter = error_reporter; - this.ui_configuration = ui_configuration; - _definition_templates_demuxer = new TableUpdateDemuxer(t => t.key, t => t.definition_key); - definitions = _service.subscribei_algos() - .Select(u => new Update( - u.all.Select(_Utils.definition_data).ToList(), - u.added.Select(_Utils.definition_data).ToList(), - u.changes.Select(ch => new Change(_Utils.definition_data(ch.Old), _Utils.definition_data(ch.New))).ToList(), - u.removed.Select(d => _Utils.definition_data(d)).ToList(), - def => def.key)) - .Table() - .Cache(); - templates = _service.subscribei_algo_templates() - .Select(u => new Update( - u.all.Select(_Utils.template_data).ToList(), - u.added.Select(_Utils.template_data).ToList(), - u.changes.Select(ch => new Change(_Utils.template_data(ch.Old), _Utils.template_data(ch.New))).ToList(), - u.removed.Select(_Utils.template_data).ToList(), - def => def.key)) - .Table() - .Cache(); - _dispose = new CompositeDisposable( - definitions.OnDispatcher().Subscribe(t => _algos = t.state), - templates.OnDispatcher().Subscribe(t => _algo_templates = t.state), - templates.Subscribe(_definition_templates_demuxer), - metadata_service.subscribe_metadata().Subscribe(_metadata_demuxer)); - } - - public IObservable> definitions { get; } - public IObservable> templates { get; } - public IAlgoDefinitionMetadataService metadata_service { get; } - public bts.config.AlgoStudioOptions ui_configuration { get; } - - public IObservable> subscribe_definition_templates(AlgoKey definition) => - _definition_templates_demuxer.subscribe(definition); - - public async Task save_definition(AlgoData definition_data) { - if (definition_data.key.is_persisted) { - // TODO: implement update op when backend ready - } else { - // create op - return await _create_definition(new CompositeAlgoDefinitionImmutable(_Utils.to_definition(definition_data))); - } - return null; - } - public async Task save_template(AlgoTemplateData template_data) { - if (template_data.key.is_persisted) { - // update op - return await _update_template(_Utils.to_recordi(template_data)); - } else { - // create op - return await _create_template(_Utils.to_templatei(template_data)); - } - } - - /// - /// The api is not used here (there are some unresolved dependency issues with definitions on the backend). - /// The definition is marked as hidden in the AlgoMetadata stored on the server. - /// - /// For implementation details, see: , - /// - public async Task remove_definition(AlgoKey key) { - if (_algos.TryGetValue(key, out AlgoData curr)) { - if (_definition_templates_demuxer.try_get_values(key, out IReadOnlyDictionary tmps)) { - foreach (var t in tmps.Values) - await remove_template(t.key); - } - await metadata_service.hide_definition(key); - return true; - } - return false; - } - - public async Task remove_template(AlgoKey template_key) { - var req = new AlgoServiceRemoveRequest(); - _Utils.set_key(ref req, template_key); - var reply = await _safe_execute(() => _service.remove_template_async(req), ActionMetadata.remove_template); - return reply.success && reply.value.Success; - } - - public void Dispose() => - Disposable.dispose(ref _dispose); - - async Task _create_definition(CompositeAlgoDefinitionImmutable definition) => - await _create_definition(definition, _admin_model.user.id); - - async Task _create_template(AlgoTemplateImmutable template) { - var (value, success) = await _error_reporter.safe_execute(() => _service.create_template_async( - new TemplateCreateRequest { UserId = _admin_model.user.id, NewTemplate = template.CloneToMutable() }), - r => r.Success, r => r.ErrMsg, ActionMetadata.CreateTemplate); - if (success) - return _Utils.template_data(value.Record); - return null; - } - - async Task _update_template(AlgoTemplateRecordImmutable template) { - var (value, success) = await _error_reporter.safe_execute(() => _service.update_template_async( - new TemplateUpdateRequest { Key = template.Key, UpdatedTemplate = template.AlgoTemplate.CloneToMutable() }), - r => r.Success, r => r.ErrMsg.ToString(), ActionMetadata.UpdateTemplate); - if (success) - return _Utils.template_data(template); - return null; - } - - async Task _create_definition(CompositeAlgoDefinitionImmutable definition, uint user_id) { - (var result, var success) = await _error_reporter.safe_execute(() => _service.create_composite_algo_async( - new CompositeAlgoCreateRequest { - NewAlgo = definition.CloneToMutable(), - UserId = user_id - }), r => r.Success, r => r.ErrMsg, "create definition"); - return success ? _Utils.definition_data(new CompositeAlgoRecordImmutable(result.Record)) : (AlgoData?)null; - } - - async Task> _safe_execute(Func>> execute, IActionMetadata am) { - try { - var result = await execute(); - if (!result.success) { - _report_error(am.present_progressive_desc, result.error_message); - } else if (!am.get_success(result.value)) { - _report_error(am.present_progressive_desc, am.get_error_msg(result.value)); - } - return result; - } catch (Exception ex) { - _report_error(am.present_progressive_desc, ex.ToString()); - } - return new Result(bts.api.ApiError.UnexpectedResponse); - } - - void _report_error(string present_progressive_desc, string msg) => - _error_reporter.report_error($"Error {present_progressive_desc}: {msg}", AlgoStudioWindow.NAME, System.Windows.MessageBoxImage.Warning); - - void _report_no_user_id(string desc) => - _error_reporter.report_error($"{desc} failed: did not find current user id"); - - // used for error handling/reporting - interface IActionMetadata { - string desc { get; } - string present_progressive_desc { get; } - } - - interface IActionMetadata : IActionMetadata { - bool get_success(TReply reply); - string get_error_msg(TReply reply); - } - - static class ActionMetadata { - public const string - CreateDefinition = "create definition", - UpdateDefinition = "update definition", - CreateTemplate = "create template", - UpdateTemplate = "update template"; - public static readonly IActionMetadata update_template = new Impl(_update, _template, r => r.Success, r => r.ErrMsg.ToString()); - public static readonly IActionMetadata remove_template = new Impl(_delete, _template, r => r.Success, r => r.ErrMsg.ToString()); - public static readonly IActionMetadata create_template = new Impl(_create, _template, r => r.Success, r => r.ErrMsg); - public static readonly IActionMetadata create_definition = new Impl(_create, _definition, r => r.Success, r => r.ErrMsg); - - static readonly DescTuple _create = new DescTuple("create", "creating"), _update = new DescTuple("update", "updating"), _delete = new DescTuple("delete", "deleting"); - static readonly string _definition = "definition", _template = "template"; - - class Impl : IActionMetadata { - readonly DescTuple _desc; - readonly string _subject; - readonly Func _get_success; - readonly Func _get_error_msg; - - public Impl(DescTuple desc, string subject, Func get_success, Func get_error_msg) { - _desc = desc; - _subject = subject; - _get_success = get_success; - _get_error_msg = get_error_msg; - } - public string desc => _desc.desc; - public string present_progressive_desc => _desc.present_progressive_desc; - public bool get_success(T reply) => _get_success(reply); - public string get_error_msg(T reply) => _get_error_msg(reply); - } - - struct DescTuple { - public readonly string desc, present_progressive_desc; - public DescTuple(string desc, string present_progressive_desc) { - this.desc = desc; - this.present_progressive_desc = present_progressive_desc; - } - } - } - - /// - /// The AlgoService protobuf types have been extracted out of the viewmodels (, , , ). - /// The viewmodels instead use these types to represent the data: is used in place of , and is used in place of . - /// This thin abstraction isolates the server-side from the client-side, so if one day the server side types change, we won't need to change any client-side code except the methods below which handle the conversion from server type to corresponding client type. - /// There are a couple other methods in here as well (this is an extensions class afterall), but [John]I am going out of town soon (1/6/18) and did not get a chance to organize these methods beyond containing them in . - /// - static class _Utils { - // AlgoTemplateImmutable custom_order_definition(i) - public static CustomOrderDefinitionImmutable custom_order_definitioni(AlgoTemplateImmutable templatei) { - switch (templatei.AlgoParamsCase) { - case AlgoTemplate.AlgoParamsOneofCase.CompositeAlgoParams: return templatei.CompositeAlgoParams.Algo; - case AlgoTemplate.AlgoParamsOneofCase.SystemAlgoParams: return templatei.SystemAlgoParams; - default: throw ExceptionBuilder.Argument.unexpected_case(templatei.AlgoParamsCase, nameof(templatei)); - } - } - - public static AlgoData definition_data(AlgoTemplateImmutable templatei) { - switch (templatei.AlgoParamsCase) { - case AlgoTemplate.AlgoParamsOneofCase.CompositeAlgoParams: return definition_data(templatei.CompositeAlgoParams); - case AlgoTemplate.AlgoParamsOneofCase.SystemAlgoParams: - return new AlgoData( - templatei.SystemAlgoParams, - templatei.SystemAlgoParams.CustomCase.display_name(), - get_key(templatei.SystemAlgoParams)); - default: throw ExceptionBuilder.Argument.unexpected_case(templatei.AlgoParamsCase, nameof(templatei)); - } - } - - public static AlgoData definition_data(CompositeAlgoRecordImmutable recordi) => new AlgoData(recordi.AlgoDefinition.Algo, recordi.AlgoDefinition.Name, get_key(recordi)); - - public static AlgoData definition_data(CompositeAlgoDefinitionImmutable definitioni) => - new AlgoData(definitioni.Algo, definitioni.Name, get_key(definitioni)); - - public static AlgoData? definition_data(Result result) { - if (result.success && result.value.Success) { - var r = result.value.Record; - return new AlgoData(new CustomOrderDefinitionImmutable(r.AlgoDefinition.Algo), r.AlgoDefinition.Name, new AlgoKey(new AlgoPersistedKey(r.Key))); - } else return null; - } - - // AlgoTemplateRecord(Immutable) template data - public static AlgoTemplateData template_data(AlgoTemplateRecord record) => template_data(new AlgoTemplateRecordImmutable(record)); - public static AlgoTemplateData template_data(AlgoTemplateRecordImmutable recordi) => new AlgoTemplateData(custom_order_definitioni(recordi.AlgoTemplate), recordi.AlgoTemplate.Name, get_key(recordi), definition_data(recordi.AlgoTemplate)); - - public static CompositeAlgoDefinition to_definition(AlgoData definition_data) => - new CompositeAlgoDefinition { - Name = definition_data.name, - Algo = definition_data.value.CloneToMutable() - }; - - // AlgoTemplateData to_record(i) - public static AlgoTemplateRecord to_record(AlgoTemplateData template) { - var record = new AlgoTemplateRecord { - AlgoTemplate = new AlgoTemplate { - Name = template.name, - CompositeAlgoParams = new CompositeAlgoDefinition { - Name = template.definition.name, - Algo = template.value.CloneToMutable() - } - } - }; - set_key(ref record, template.key); - return record; - } - public static AlgoTemplateRecordImmutable to_recordi(AlgoTemplateData template) => new AlgoTemplateRecordImmutable(to_record(template)); - - // AlgoTemplateData to_template(i) - public static AlgoTemplate to_template(AlgoTemplateData template) => - new AlgoTemplate { - Name = template.name, - CompositeAlgoParams = new CompositeAlgoDefinition { - Name = template.definition.name, - Algo = template.value.CloneToMutable() - } - }; - public static AlgoTemplateImmutable to_templatei(AlgoTemplateData template) => new AlgoTemplateImmutable(to_template(template)); - - public static AlgoKey get_key(CompositeAlgoRecordImmutable recordi) => new AlgoKey(new AlgoPersistedKey(recordi.Key)); - public static AlgoKey get_key(AlgoTemplateRecordImmutable recordi) => new AlgoKey(new AlgoPersistedKey(recordi.Key)); - public static AlgoKey get_key(CompositeAlgoDefinitionImmutable definitioni) => new AlgoKey(new AlgoPersistedKey(definitioni.Name)); - public static AlgoKey get_key(CustomOrderDefinitionImmutable custom_order_definitioni) => new AlgoKey(custom_order_definitioni.CustomCase); - - public static void set_key(ref AlgoTemplateRecord record, AlgoKey key) { - switch (key.mode) { - case AlgoKey.Mode.Persisted: - switch (key.persisted.mode) { - case AlgoPersistedKey.Mode.String: - record.Key = key.persisted.id_string; break; - } - break; - } - } - public static void set_key(ref AlgoServiceRemoveRequest request, AlgoKey key) { - switch (key.mode) { - case AlgoKey.Mode.Persisted: - switch (key.persisted.mode) { - case AlgoPersistedKey.Mode.String: - request.Key = key.persisted.id_string; break; - } - break; - } - } - } - } -} \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStudioFlatDefinitionModel.cs b/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStudioFlatDefinitionModel.cs index 57518ae9f..2d859112d 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStudioFlatDefinitionModel.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStudioFlatDefinitionModel.cs @@ -6,10 +6,12 @@ using bts.spark; using mbts.utils; using System; using System.Collections.Generic; +using System.ComponentModel.Composition; using System.Reactive.Linq; using System.Threading.Tasks; namespace mbts.spark { + [Export(typeof(IAlgoStudioModel))] class AlgoStudioFlatDefinitionModel : IAlgoStudioModel, IDisposable { readonly AlgoDefinitionService _service; readonly AdminModel _admin_model; @@ -18,12 +20,12 @@ namespace mbts.spark { IReadOnlyDictionary _algo_templates = DictionaryHelper.empty(); IDisposable _dispose; - public AlgoStudioFlatDefinitionModel(AlgoDefinitionService service, IAlgoDefinitionMetadataService metadata_service, AdminModel admin_model, ErrorReporter error_reporter, bts.config.AlgoStudioOptions ui_configuration) { + [ImportingConstructor] + public AlgoStudioFlatDefinitionModel(AlgoDefinitionService service, IAlgoDefinitionMetadataService metadata_service, AdminModel admin_model, ErrorReporter error_reporter) { _service = service; this.metadata_service = metadata_service; _admin_model = admin_model; _error_reporter = error_reporter; - this.ui_configuration = ui_configuration; definitions = service.subscribei_algo_definitions() .Filter(r => r.Metadata.IsActive && r.Metadata.CreatorUserId == _admin_model.user.id) @@ -35,7 +37,7 @@ namespace mbts.spark { public IObservable> definitions { get; } public IObservable> templates => Observable.Empty>(); public IAlgoDefinitionMetadataService metadata_service { get; } - public bts.config.AlgoStudioOptions ui_configuration { get; } + public bts.config.AlgoStudioOptions ui_configuration { get; } = config.Configuration.get(); public IObservable> subscribe_definition_templates(AlgoKey definition_key) => Observable.Return(TableUpdate.mk_empty(t => t.key)); diff --git a/src/client/spark/Modules/Trading/AlgoStudio/Model/IAlgoStudioModel.cs b/src/client/spark/Modules/Trading/AlgoStudio/Model/IAlgoStudioModel.cs index 0d2b85cbe..acbcdffb5 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/Model/IAlgoStudioModel.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/Model/IAlgoStudioModel.cs @@ -1,10 +1,7 @@ using bts; -using bts.api; using bts.api.core; -using bts.spark; using System; using System.Collections.Generic; -using System.ComponentModel.Composition; using System.Threading.Tasks; namespace mbts.spark { @@ -20,34 +17,13 @@ namespace mbts.spark { bts.config.AlgoStudioOptions ui_configuration { get; } } - class AlgoStudioModelExporter { - [ImportingConstructor] - AlgoStudioModelExporter(Spark.AlgoServiceWrapper service_wrapper, IAlgoDefinitionMetadataService meta, AdminModel admin_model, ErrorReporter error_reporter) { - var ui_configuration = config.Configuration.get(); - switch (service_wrapper.mode) { - case Spark.AlgoServiceWrapper.Mode.Flat: model = new AlgoStudioFlatDefinitionModel(service_wrapper.flat, meta, admin_model, error_reporter, ui_configuration); break; - case Spark.AlgoServiceWrapper.Mode.Hierarchical: model = new AlgoStudioDefinitionTemplateModel(service_wrapper.hierarhical, meta, admin_model, error_reporter, ui_configuration); break; - } - } - - [Export] - public IAlgoStudioModel model { get; } - } - static class AlgoStudioModelUtils { - public static bool templates_enabled(this IAlgoStudioModel model) => - get_templates_enabled(model.ui_configuration); - - public static bool get_templates_enabled(bts.config.AlgoStudioOptions ui_configuration) => - ui_configuration.add_template_button != bts.config.AlgoStudioOptions.AddTemplateButton.None; - public static IReadOnlyDictionary get_dynamic_resources(bts.config.AlgoStudioOptions ui_configuration) => new Dictionary { { AlgoStudioWindow.ShowAlgoToolBarRenameDefinitionKey, ui_configuration.can_modify_definition_name && ui_configuration.show_algo_toolbar_rename }, { AlgoStudioWindow.ShowAlgoToolBarSaveDefinitionKey, ui_configuration.can_modify_definition_values && ui_configuration.show_algo_toolbar_save }, { AlgoStudioWindow.ShowAlgoToolBarRevertDefinitionKey, ui_configuration.show_algo_toolbar_revert }, - { AlgoStudioWindow.ShowAlgoToolBarUndoRedoDefinitionKey, ui_configuration.show_algo_toolbar_undo_redo }, - { AlgoStudioWindow.TemplatesEnabledKey, get_templates_enabled(ui_configuration) } + { AlgoStudioWindow.ShowAlgoToolBarUndoRedoDefinitionKey, ui_configuration.show_algo_toolbar_undo_redo } }; } } \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionTemplateVM.cs b/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionTemplateVM.cs deleted file mode 100644 index 27cfd6f91..000000000 --- a/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionTemplateVM.cs +++ /dev/null @@ -1,243 +0,0 @@ -using bts; -using bts.api.orderman; -using bts.utils; -using mbts.spark.utilities; -using mbts.ui; -using mbts.ui.shell; -using mbts.ui.utility; -using mbts.utils; -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Reactive.Linq; -using System.Windows.Input; -using VisualStateNames = mbts.ui.spark.AlgoStudioView.VisualStateNames; - -namespace mbts.spark { - class AlgoDefinitionTemplateVM : DisposableViewModelBase, IAlgoStudioContentVM, IEquatable { - /// is referenced by an x:Static extension in OrderDetailsPopupControl.xaml . - /// In most cases, works just like , but for nested types, such as . - /// However, when the former is used to denote the DataType of a DataTemplate, a strange XamlReader exception is thrown at runtime. - /// After spending ~15 minutes investigating what was happening, [John]I decided it was more trouble than it was worth and opted for this workaround. - public static readonly Type CustomType = typeof(CustomTemplatePlaceholderVM); - readonly OrdersModel _model; - readonly VisualStateModel _edit_pane_vs_model = new VisualStateModel(), _tree_view_vs_model = new VisualStateModel(); - /// Note: the difference between and is that the former implements push/pop functionality so the user may undo/redo (like ctrl+z/ctrl+y in text editors), - /// while the latter is a lazy delegate-based container for the most recent value (). - readonly EditStack _edit_stack = new EditStack(); - readonly VersionContainer _version; - readonly DeferrableActionWrapper _refresh_on_local_change; - readonly Property _algo_root; - readonly DelegateProperty _can_undo, _can_redo, _is_dirty; - readonly Property _is_default, _is_favorite, _is_selected; - readonly Property _name, _abbreviation; - // maintains the state of each algo-root, so the user may change the definition root back and forth without any loss of state amongst the templates - Snapshot _committed; - - public AlgoDefinitionTemplateVM(AlgoDefinitionVM owner, OrdersModel model, AlgoData data, AlgoEditingPermissions editing_permissions = AlgoEditingPermissions.AllowEditValues) { - // init core data - this.owner = owner; - _model = model; - key = data.key; - _version = new VersionContainer(_snapshot); - // maintain states for different algo roots, so they aren't lost when the user changes the root algo type - var algo_map = new Dictionary { - { data.key, algo_vm_factory(data.value) } - }; - // init backing props - _name = backing(nameof(this.name), name); - _abbreviation = backing(nameof(abbreviation), string.Empty); - _is_default = backing(nameof(is_default), false); - _is_favorite = backing(nameof(is_favorite), false); - _is_selected = backing(nameof(is_selected), false); - _algo_root = backing(nameof(algo_root), get_algo_root(owner.algo_root)); - _committed = _version.value; - _can_redo = backing(nameof(can_redo), () => _edit_stack.get_can_redo(_version.value)); - _can_undo = backing(nameof(can_undo), () => _edit_stack.get_can_undo(_version.value)); - _is_dirty = backing(nameof(is_dirty), () => !_committed.Equals(_version.value)); - _can_redo.Changed += on_can_redo_changed; - _can_undo.Changed += on_can_undo_changed; - set_as_default_cmd = new DelegateCommand(() => { - if (!is_default && key.mode == AlgoKey.Mode.Persisted) - _model.algo_model.metadata_service.set_as_default(owner.key, key).ignore(); - }); - // init visual states - // TODO: implement these features in IAlgoMetadataService; until then, set the appropriate visual states. - _edit_pane_vs_model.set_state(VisualStateNames.Abbreviation.GroupName, VisualStateNames.Abbreviation.NotSupportedForTemplates); - _tree_view_vs_model.set_state(VisualStateNames.FavoriteToggleButton.GroupName, VisualStateNames.FavoriteToggleButton.Inactive); - switch (key.mode) { - case AlgoKey.Mode.Persisted: - _edit_stack.push(_committed); - _edit_pane_vs_model.set_state(VisualStateNames.Name.GroupName, VisualStateNames.Name.Active); - break; - case AlgoKey.Mode.Unpersisted: _edit_pane_vs_model.set_state(VisualStateNames.Name.GroupName, VisualStateNames.Name.Active); break; - case AlgoKey.Mode.Factory: _edit_pane_vs_model.set_state(VisualStateNames.Name.GroupName, VisualStateNames.Name.Inactive); break; - } - // set hooks/subscriptions - _refresh_on_local_change = new DeferrableActionWrapper(on_local_changed); - _dispose = new System.Reactive.Disposables.CompositeDisposable( - as_demuxer().subscribe_many(_refresh_on_local_change.execute, nameof(name), nameof(abbreviation), nameof(is_default), nameof(is_favorite)), - owner.observe_algo_root().Subscribe(r => _algo_root.set(get_algo_root(r))), - _algo_root.observe_current(true).SelectManyInSeries(r => r?.subscribe_definition()).Subscribe(_ => _refresh_on_local_change.execute()), - Disposable.wrap_collection(algo_map.Values)) { - () => { - _can_redo.Changed -= on_can_redo_changed; - _can_undo.Changed -= on_can_undo_changed; - } - }; - // local methods - IAlgoVM algo_vm_factory(CustomOrderDefinitionImmutable def) => OrderTypeVMFactory.create(new AlgoData(def, def.CustomCase.display_name(), OrderDataHelper.get_shallow_factory_key(def)), editing_permissions); - IAlgoVM get_algo_root(IAlgoVM owner_root) { - var key = new AlgoKey(owner_root.order_type); - if (algo_map.TryGetValue(key, out IAlgoVM vm)) { - vm.load_structure(owner_root.definition); - } else { - vm = algo_map.GetOrAdd(key, ot => algo_vm_factory(owner_root.definition)); - } - return vm; - } - void on_can_undo_changed(bool oldval, bool newval) => can_undo_changed?.Invoke(); - void on_can_redo_changed(bool oldval, bool newval) => can_redo_changed?.Invoke(); - void on_local_changed() { - _version.increment_version(); - _edit_stack.push_distinct(_version.value); - _is_dirty.refresh(); - _refresh_undo_redo(); - } - } - - public event Action can_redo_changed, can_undo_changed; - public event PropertyChange algo_root_changed { add => _algo_root.Changed += value; remove => _algo_root.Changed -= value; } - - public AlgoDefinitionVM owner { get; } - public AlgoKey owner_key => owner.key; - public AlgoKey key { get; } - public string name { get => _name.Value; set => _name.set(value); } - public string abbreviation { get => _abbreviation.Value; set => _abbreviation.set(value); } - public bool is_dirty => _is_dirty.Value; - public bool can_redo => _can_redo.Value; - public bool can_undo => _can_undo.Value; - public bool is_default => _is_default.Value; - public bool is_favorite { get => _is_favorite.Value; set => _is_favorite.set(value); } - public IAlgoVM algo_root => _algo_root.Value; - public virtual bool is_custom_placeholder => false; - public bool is_selected { get => _is_selected.Value; set => _is_selected.set(value); } - public bool is_expanded => false; - public bool is_persisted => key.mode == AlgoKey.Mode.Persisted; - public ObservableCollection edit_pane_visual_states => _edit_pane_vs_model.states; - public ObservableCollection tree_view_visual_states => _tree_view_vs_model.states; - public ICommand set_as_default_cmd { get; } - - public IObservable observe_is_dirty() => _is_dirty.observe_current(true); - public void undo() => _restore(_edit_stack.try_undo); - public void redo() => _restore(_edit_stack.try_redo); - - public void on_meta(bool is_default, bool is_favorite) { - _is_default.set(is_default); - _is_favorite.set(is_favorite); - } - - public AlgoData create_def_data() => - new AlgoData(algo_root.definition, name, key); - - public AlgoTemplateData create() => - create(owner.create_algo_def()); - - public AlgoTemplateData create(AlgoData record) { - if (!OrderDataHelper.EqualsHelpers.structure_equals(algo_root.definition, record.value)) - throw new InvalidOperationException("AlgoTemplate's algo structure does not match that of its parent."); - return new AlgoTemplateData(algo_root.definition, name, key, record); - } - - public AlgoDefinitionTemplateVM to_persisted(AlgoDefinitionVM persisted_owner, AlgoData template) => - new AlgoDefinitionTemplateVM(persisted_owner, _model, template); - - public void load_committed() => _load_from(_committed.name, _committed.definition, true); - - public void load_from(AlgoTemplateData value) { - if (key.mode != AlgoKey.Mode.Persisted) - throw new InvalidOperationException("AlgoStructure has not been saved yet."); - else if (value.key != key) - throw new InvalidOperationException("Value id does not match this id."); - _load_from(value.name, value.value, true); - } - - public bool Equals(AlgoDefinitionTemplateVM other) => other != null && key == other.key; - public override bool Equals(object obj) => Equals(obj as AlgoDefinitionTemplateVM); - public override int GetHashCode() => key.GetHashCode(); - - void _load_from(string new_name, CustomOrderDefinitionImmutable new_def, bool update_committed) { - using (_refresh_on_local_change.defer_execution()) { - name = new_name; - algo_root.load_from(new_def); - } - if (update_committed) { - _committed = _version.value; - _is_dirty.refresh(); - } - } - - void _refresh_undo_redo() { - _can_redo.refresh(); - _can_undo.refresh(); - } - - void _restore(TryGetValue try_get_snapshot) { - while (try_get_snapshot(out Snapshot next_state)) { - if (!_version.value.Equals(next_state)) { - _load_from(next_state.name, next_state.definition, false); - break; - } - } - } - - Snapshot _snapshot() => - new Snapshot(name, abbreviation, algo_root?.definition ?? new CustomOrderDefinitionImmutable(new CustomOrderDefinition()), is_default, is_favorite); - - struct Snapshot : IEquatable { - public readonly string name, abbreviation; - public readonly CustomOrderDefinitionImmutable definition; - public readonly bool is_default, is_favorite; - - public Snapshot(string name, string abbreviation, CustomOrderDefinitionImmutable definition, bool is_default, bool is_favorite) { - this.name = name; - this.abbreviation = abbreviation; - this.definition = definition; - this.is_default = is_default; - this.is_favorite = is_favorite; - } - - public bool Equals(Snapshot other) => - name == other.name && - abbreviation == other.abbreviation && - is_default == other.is_default && - is_favorite == other.is_favorite && - OrderDataHelper.EqualsHelpers.equals(definition, other.definition); - - public override bool Equals(object obj) => - EqualityComparer.equals_obj(this, obj); - - public override int GetHashCode() => - EqualityComparer.aggregate_hash( - EqualityComparer.safe_aggregate_hash(name), - EqualityComparer.safe_aggregate_hash(abbreviation), - is_default.GetHashCode(), - is_favorite.GetHashCode(), - OrderDataHelper.EqualsHelpers.custom_order_def_compareri.GetHashCode(definition)); - - public static bool operator ==(Snapshot a, Snapshot b) => a.Equals(b); - public static bool operator !=(Snapshot a, Snapshot b) => !a.Equals(b); - } - - public class CustomTemplatePlaceholderVM : AlgoDefinitionTemplateVM { - const string _custom_name = "(Custom)"; - - public CustomTemplatePlaceholderVM(AlgoDefinitionVM owner, OrdersModel model, CustomOrderDefinitionImmutable definition) - : base(owner, model, new AlgoData(definition, _custom_name, new AlgoKey(Guid.NewGuid())), AlgoEditingPermissions.AllowEditStructure | AlgoEditingPermissions.AllowEditValues) { - _edit_stack.reset(_snapshot()); - } - - public override bool is_custom_placeholder => true; - } - } -} \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionVM.cs b/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionVM.cs index 7ec794043..40f7d4ef9 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionVM.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionVM.cs @@ -6,7 +6,6 @@ using bts.utils; using mbts.collections; using mbts.spark.utilities; using mbts.ui; -using mbts.ui.controls; using mbts.ui.controls.color_picker; using mbts.ui.shell; using mbts.ui.utility; @@ -18,7 +17,6 @@ using System.Collections.Specialized; using System.Linq; using System.Reactive.Disposables; using System.Reactive.Linq; -using System.Windows.Data; using System.Windows.Media; using VisualStateNames = mbts.ui.spark.AlgoStudioView.VisualStateNames; @@ -36,18 +34,14 @@ namespace mbts.spark { public static readonly CustomOrderDefinitionImmutable new_algo_def = OrderDataHelper.Defaults.CustomOrderDefinitionImmutable(CustomOrderDefinition.CustomOneofCase.Iceberg); readonly OrdersModel _model; readonly VisualStateModel _edit_pane_vs_model = new VisualStateModel(), _tree_view_vs_model = new VisualStateModel(); - readonly ObservableKeyedCollection _templates = new ObservableKeyedCollection(t => t.key); readonly EditStack _edit_stack = new EditStack(); readonly VersionContainer _version; readonly Property _is_expanded, _is_selected; readonly Property _algo_root, _visible_algo_root; - readonly Property _selected_template; readonly DelegateProperty _is_favorite, _is_dirty, _can_undo, _can_redo; readonly Property _name, _abbreviation; readonly ObservableKeyedCollection _algo_roots = new ObservableKeyedCollection(vm => vm.id); - readonly ObservableAppendCollection _templates_with_custom; readonly DeferrableActionWrapper _refresh_on_local_changes; - readonly ReactiveThresholdMonitor _any_templates_dirty_monitor = new ReactiveThresholdMonitor(t => t.observe_is_dirty()); readonly Property _selected_format; readonly EnumMaskInt32 _permissions_mask = new EnumMaskInt32(); @@ -55,15 +49,9 @@ namespace mbts.spark { Brush _badge_fill; Snapshot? _committed; AlgoDefinitionMetadata _metadata; - TableUpdateBuffer _template_update_buffer; - bool _connected; - public static AlgoDefinitionVM create(OrdersModel model, AlgoData data, bool connect = false, AlgoFormats init_format = AlgoFormats.Exchange, AlgoEditingPermissions editing_permissions = (AlgoEditingPermissions)int.MaxValue) { - var rv = new AlgoDefinitionVM(model, data, init_format, editing_permissions); - if (connect) - rv.connect(); - return rv; - } + public static AlgoDefinitionVM create(OrdersModel model, AlgoData data, AlgoFormats init_format = AlgoFormats.Exchange, AlgoEditingPermissions editing_permissions = (AlgoEditingPermissions)int.MaxValue) => + new AlgoDefinitionVM(model, data, init_format, editing_permissions); public static AlgoDefinitionVM create_placeholder(OrdersModel model, CustomOrderDefinitionImmutable def, string name, AlgoFormats init_format) => new AlgoDefinitionVM(model, new AlgoData(def, name, new AlgoKey(Guid.NewGuid())), init_format, (AlgoEditingPermissions)int.MaxValue); @@ -78,20 +66,8 @@ namespace mbts.spark { editing_permissions_mask ^= (AlgoEditingPermissions.AllowEditValues | AlgoEditingPermissions.AllowSaveValues); if (!model.algo_model.ui_configuration.can_modify_definition_structure) editing_permissions_mask ^= (AlgoEditingPermissions.AllowEditStructure | AlgoEditingPermissions.AllowSaveStructure); - else if (model.algo_model.templates_enabled()) { - resources.Add(_templates.Subscribe((s, e) => { - if (_templates.Count == 0) { - editing_permissions_mask |= AlgoEditingPermissions.AllowEditStructure | AlgoEditingPermissions.AllowSaveStructure; - } else { - editing_permissions_mask ^= (AlgoEditingPermissions.AllowEditStructure | AlgoEditingPermissions.AllowSaveStructure); - } - })); - } key = def_data.key; algos_view = ObservableAutoWrapper.create_sorted_wrapper(_algo_roots, AlgoCollectionHelper.algo_vm_comparer); - _template_update_buffer = new TableUpdateBuffer(t => t.key); - _templates_with_custom = new ObservableAppendCollection(templates); - templates_view = (ListCollectionView)CollectionViewSource.GetDefaultView(_templates_with_custom); custom_badge_color_palettes.AddRange(ColorPalette.all_presets(model.factory).Select(p => new ColorPaletteVM(p))); _version = new VersionContainer(_snapshot); var conf = _model.algo_model.ui_configuration; @@ -99,7 +75,6 @@ namespace mbts.spark { _name = backing(nameof(name), def_data.name); _abbreviation = backing(nameof(abbreviation), string.Empty); _selected_format = backing(nameof(selected_format), init_format); - _selected_template = backing(nameof(selected_template)); _is_favorite = backing(nameof(is_favorite), () => _favorite_index.HasValue); _is_expanded = backing(nameof(is_expanded), true); _is_selected = backing(nameof(is_selected), true); @@ -117,13 +92,7 @@ namespace mbts.spark { async void init_async() { // visible_algo_root is selected_template.algo_root if user can add templates, otherwise algo_root // - this behavior is configurable in 'AlgoStudioOptions' in UI.proto (01/28/2018) - if (_model.algo_model.templates_enabled()) { - resources.Add(_selected_template.observe_current(true).Subscribe(t => _visible_algo_root.set(t?.algo_root))); - } else { - resources.Add(_algo_root.observe_current(true).Subscribe(_visible_algo_root.set)); - } - // init tree view item visual state - _tree_view_vs_model.set_state(VisualStateNames.TreeViewBadge.GroupName, conf.show_badges_in_tree_view ? VisualStateNames.TreeViewBadge.Active : VisualStateNames.TreeViewBadge.Inactive); + resources.Add(_algo_root.observe_current(true).Subscribe(_visible_algo_root.set)); // set hooks/subscriptions using (_refresh_on_local_changes.supress_execution()) { resources.AddRange( @@ -142,7 +111,6 @@ namespace mbts.spark { }), vm.subscribe_definition().Subscribe(_ => _refresh_on_local_changes.execute()))), ObservableAutoWrapper.connect_item_hooks(algo_roots, a => a as IDisposable ?? Disposable.empty, true), - ObservableAutoWrapper.connect_item_hooks(templates, t => new CompositeDisposable(_any_templates_dirty_monitor.join(t), t), true), Disposable.Create(() => { _can_redo.Changed -= on_can_redo_changed; _can_undo.Changed -= on_can_undo_changed; @@ -150,7 +118,6 @@ namespace mbts.spark { switch (key.mode) { case AlgoKey.Mode.Persisted: _metadata = new AlgoDefinitionMetadata(key); - resources.Add(_template_update_buffer.OnDispatcher().Subscribe(_on_templates)); resources.Add(model.algo_model.metadata_service.subscribe_metadata(key).OnDispatcher().Subscribe(_on_metadata)); _edit_pane_vs_model.set_state(VisualStateNames.Name.GroupName, conf.can_modify_definition_name ? VisualStateNames.Name.Active : VisualStateNames.Name.CannotRenameDefinition); break; @@ -206,7 +173,6 @@ namespace mbts.spark { public IReadOnlyObservableCollection algos_view { get; } public IAlgoVM algo_root { get => _algo_root.Value; set => _algo_root.set(value); } public IAlgoVM visible_algo_root => _visible_algo_root.Value; - public AlgoDefinitionTemplateVM selected_template { get => _selected_template.Value; set => _selected_template.set(value); } public int? favorite_index { get => _favorite_index; set { @@ -238,15 +204,6 @@ namespace mbts.spark { public EnabledValueVM custom_badge_color { get; } = new EnabledValueVM(); public ObservableCollection custom_badge_color_palettes { get; } = new ObservableCollection(); public Brush badge_fill => _badge_fill; - public ObservableCollection templates => _templates; - /// has the same elements as , plus the custom-placeholder-item, which is always at index 0. - /// The custom-placeholder supports legacy behavior in the ladder/ticket algo popup by allowing the user to manipulate the algo-structure (e.g. change an iceberg-limit order to iceberg-lean-cover-offset etc.). - /// However, the custom-placeholder item cannot be used to create/save algo-templates. - /// Algo-templates are just a set of values used to populate a concrete algo-structure; the 'structures' can be created in the AlgoStudio (). - /// If we were to strictly follow this paradigm, the user would no longer be able to freely change the algo-structure in the ladder/ticket popup (they would be forced to open up a new , and we know how much they hate more clicks!). - /// Some users might consider this a regression. The custom-placeholder-item addresses that concern. - public ObservableAppendCollection templates_with_custom => _templates_with_custom; - public ListCollectionView templates_view { get; } // format public AlgoFormats selected_format { get => _selected_format.Value; set => _selected_format.set(value); } public ObservableCollection formats { get; } = new ObservableCollection { AlgoFormats.Exchange, AlgoFormats.Spreader, AlgoFormats.Exchange | AlgoFormats.Spreader }; @@ -321,24 +278,7 @@ namespace mbts.spark { } } - // idempotent - public void prepend_custom_template() { - if (_templates_with_custom.appended_front.Count == 0) - _templates_with_custom.insert_front(new AlgoDefinitionTemplateVM.CustomTemplatePlaceholderVM(this, _model, algo_root.definition)); - } - - public AlgoDefinitionTemplateVM template_factory() => - new AlgoDefinitionTemplateVM(this, _model, algo_root.create_def_data().with(name: new_template_name)) { - is_selected = true - }; - public IObservable subscribe_is_definition_dirty() => _is_dirty.observe_current(true); - public IObservable subscribe_any_templates_dirty() => _any_templates_dirty_monitor; - public IObservable subscribe_is_definition_or_any_templates_dirty() => - Observable.Merge( - subscribe_is_definition_dirty().Select(v => v || _any_templates_dirty_monitor.is_above_threshold), - subscribe_any_templates_dirty().Select(v => v || is_dirty)) - .DistinctUntilChanged(); public void undo() => _restore(_edit_stack.try_undo); public void redo() => _restore(_edit_stack.try_redo); @@ -347,17 +287,6 @@ namespace mbts.spark { _assign_from_data(_committed.Value); _on_committed_changed(); } - /// - /// Subscribes to the templates source for this definition if it has been persisted (subscription requires a persistant id); does nothing if this definition has not been persisted, or if it is already subscribed (idempotent). - /// - public void connect() { - if (!_connected) { - _connected = true; - concat_disposable(_model.algo_model.subscribe_definition_templates(key).OnDispatcher().Subscribe(_template_update_buffer.OnNext)); - } - } - - public IDisposable buffer_updates() => _template_update_buffer.buffer_updates(); public void load_def(CustomOrderDefinitionImmutable def) { var key = OrderDataHelper.get_shallow_factory_key(def); @@ -464,12 +393,6 @@ namespace mbts.spark { using (_refresh_on_local_changes.supress_execution()) { _abbreviation.set(metadata.abbreviation); custom_badge_color.set_nullable(metadata.badge_color); - foreach (var t in templates) { - if (t.key.mode == AlgoKey.Mode.Persisted) - t.on_meta(t.key == metadata.default_template, metadata.favorite_templates.Contains(t.key)); - else - t.on_meta(false, false); - } _version.increment_version(); if (_edit_stack.size == 1 && _edit_stack.pos == 1) { // this is a hack to account for the metadata being part of the committed state, @@ -482,22 +405,6 @@ namespace mbts.spark { } } - void _on_templates(TableUpdate table) { - foreach (var rec in table.removed) - _templates.Remove(rec.key); - foreach (var rec in table.changed) - _templates[rec.key].load_from(rec); - foreach (var rec in table.added) { - if (_templates.TryGetValue(rec.key, out AlgoDefinitionTemplateVM tmp)) { - tmp.load_from(rec); - } else { - tmp = new AlgoDefinitionTemplateVM(this, _model, new AlgoData(rec.value, rec.name, rec.key)); - tmp.on_meta(tmp.key == _metadata.default_template, _metadata.favorite_templates.Contains(tmp.key)); - _templates.Add(tmp); - } - } - } - void _refresh_undo_redo() { _can_undo.refresh(); _can_redo.refresh(); diff --git a/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoStudioVM.cs b/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoStudioVM.cs index 3f08d209a..d27b6b0e8 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoStudioVM.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoStudioVM.cs @@ -1,6 +1,5 @@ using bts; using bts.api.orderman; -using bts.collections; using bts.utils; using mbts.collections; using mbts.ui; @@ -14,6 +13,7 @@ using System.Linq; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Threading.Tasks; +using System.Windows; using System.Windows.Input; using StartupData = bts.shell.AlgoStudioWindowFactory.StartupData; @@ -37,24 +37,22 @@ namespace mbts.spark { }); } - class AlgoStudioVM : DisposableViewModelBase, IHandleSelectedItemChanged { + class AlgoStudioVM : DisposableViewModelBase { static readonly AlgoFormats _studio_formats = AlgoFormats.Exchange; readonly OrdersModel _model; readonly Property _selected_definition; - readonly Property _selected_template; readonly Property _editable_content; readonly DelegateProperty _save_cmd_tooltip, _revert_cmd_tooltip; readonly ObservableKeyedCollection _definitions = new ObservableKeyedCollection(d => d.key); readonly ListCollectionView _definitions_view; readonly TableUpdateBuffer _definitions_update_buffer; - readonly ReactiveThresholdMonitor _any_dirty_monitor = new ReactiveThresholdMonitor(d => d.subscribe_is_definition_or_any_templates_dirty()); + readonly ReactiveThresholdMonitor _any_dirty_monitor = new ReactiveThresholdMonitor(d => d.subscribe_is_definition_dirty()); IReadOnlyDictionary _persisted_meta = new Dictionary(); public AlgoStudioVM(OrdersModel model) { _model = model; _selected_definition = backing(nameof(selected_definition)); - _selected_template = backing(nameof(selected_template)); - _editable_content = backing(nameof(editable_content), observe_selected().SelectManyInSeries(tup => tup.template?.observe_algo_root() ?? tup.definition?.observe_algo_root()).OnDispatcher()); + _editable_content = backing(nameof(editable_content), subscribe_definition().SelectManyInSeries(def => def?.observe_algo_root()).OnDispatcher()); _definitions_update_buffer = new TableUpdateBuffer(def => def.key); _definitions_view = new ListCollectionView(definitions) { CustomSort = AlgoCollectionHelper.algo_definition_vm_comparer.to_non_generic() @@ -71,13 +69,18 @@ namespace mbts.spark { // _dispose = new CompositeDisposable( _model.algo_model.definitions.Subscribe(_definitions_update_buffer), - _definitions_update_buffer.OnDispatcher().Subscribe(u => AlgoCollectionHelper.update_persisted_definitions(_definitions, u, d => AlgoDefinitionVM.create(model, d, true, _studio_formats))), + _definitions_update_buffer.OnDispatcher().Subscribe(u => { + var orig_selected_def = selected_definition; + AlgoCollectionHelper.update_persisted_definitions(_definitions, u, d => AlgoDefinitionVM.create(model, d, _studio_formats)); + if (selected_definition == null) + selected_definition = definitions.FirstOrDefault(); + }), _model.algo_model.metadata_service.subscribe_metadata().OnDispatcher().Subscribe(meta => { _persisted_meta = meta; definitions_view.Refresh(); }), - ObservableAutoWrapper.connect(observe_selected().Select(t => t.template?.edit_pane_visual_states ?? t.definition?.edit_pane_visual_states ?? new ObservableCollection()), content_visual_states), - observe_selected().SelectManyInSeries(t => t.template?.observe_is_dirty() ?? t.definition?.subscribe_is_definition_or_any_templates_dirty() ?? Observable.Return(false)).OnDispatcher() + ObservableAutoWrapper.connect(subscribe_definition().Select(def => def?.edit_pane_visual_states ?? new ObservableCollection()), content_visual_states), + subscribe_definition().SelectManyInSeries(def => def?.subscribe_is_definition_dirty() ?? Observable.Return(false)).OnDispatcher() .Subscribe(new CompositeObserver(save_cmd, revert_cmd) { val => { _save_cmd_tooltip.refresh(); _revert_cmd_tooltip.refresh(); @@ -85,47 +88,30 @@ namespace mbts.spark { ObservableAutoWrapper.connect_item_hooks(definitions, d => new CompositeDisposable(_any_dirty_monitor.join(d), d), true)); // local methods string get_revert_tooltip() { - if (content_source is AlgoDefinitionTemplateVM tmp) { - switch (tmp.key.mode) { - case AlgoKey.Mode.Persisted: return tmp.is_dirty ? $"Revert changes to '{tmp.name}'" : "No changes to revert"; - } - } else if (content_source is AlgoDefinitionVM def) { - switch (def.key.mode) { - case AlgoKey.Mode.Persisted: return def.is_dirty || def.templates.Any(t => t.is_dirty) ? $"Revert changes to '{def.name}' templates" : "No changes to revert"; - } - } - return null; + var def = selected_definition; + return def != null && def.key.mode == AlgoKey.Mode.Persisted ? + (def.is_dirty ? $"Revert changes to '{def.name}' templates" : "No changes to revert") : + null; } async Task save_async(IAlgoStudioContentVM content) { - if (content is AlgoDefinitionTemplateVM tmp) { - await save_template(tmp); - } else if (content is AlgoDefinitionVM def) { + if (content is AlgoDefinitionVM def) await save_definition(def); - } } string get_save_tooltip() { - if (content_source is AlgoDefinitionTemplateVM tmp) { - switch (tmp.key.mode) { - case AlgoKey.Mode.Unpersisted: return tmp.is_dirty ? $"Save '{tmp.name}'" : $"Cannot Save '{tmp.name}'"; - case AlgoKey.Mode.Persisted: return tmp.is_dirty ? $"Save changes to '{tmp.name}'" : "No changes to save"; - } - } else if (content_source is AlgoDefinitionVM def) { + var def = selected_definition; + if (def != null) { switch (def.key.mode) { - case AlgoKey.Mode.Unpersisted: return def.is_dirty || def.templates.Any(t => t.is_dirty) ? $"Save '{def.name}'" : $"Cannot Save '{def.name}'"; - case AlgoKey.Mode.Persisted: return def.is_dirty || def.templates.Any(t => t.is_dirty) ? $"Save changes to '{def.name}' templates" : "No changes to save"; + case AlgoKey.Mode.Unpersisted: return def.is_dirty ? $"Save '{def.name}'" : $"Cannot Save '{def.name}'"; + case AlgoKey.Mode.Persisted: return def.is_dirty ? $"Save changes to '{def.name}' templates" : "No changes to save"; } } return null; } } - event Action<(AlgoDefinitionVM definition, AlgoDefinitionTemplateVM template)> _selected_changed; - public ObservableCollection definitions => _definitions; public ObservableCollection content_visual_states { get; } = new ObservableCollection(); public AlgoDefinitionVM selected_definition { get => _selected_definition.Value; set => _selected_definition.set(value); } - public AlgoDefinitionTemplateVM selected_template { get => _selected_template.Value; set => _selected_template.set(value); } - public IAlgoStudioContentVM content_source => (IAlgoStudioContentVM)selected_template ?? selected_definition; public IAlgoVM editable_content => _editable_content.Value; public ICollectionView definitions_view => _definitions_view; public ICommand save_cmd { get; } @@ -150,12 +136,6 @@ namespace mbts.spark { public StartupData create() => new StartupData(); public void load_from(StartupData state) { } public IObservable subscribe_definition() => _selected_definition.observe_current(true); - public IObservable subscribe_template() => _selected_template.observe_current(true); - public IObservable<(AlgoDefinitionVM definition, AlgoDefinitionTemplateVM template)> observe_selected() => - Observable.Create<(AlgoDefinitionVM definition, AlgoDefinitionTemplateVM template)>(o => { - _selected_changed += o.OnNext; - return Disposable.Create(() => _selected_changed -= o.OnNext); - }); public IObservable subscribe_dirty() => _any_dirty_monitor; public async Task remove_definition(AlgoDefinitionVM definition) { @@ -163,87 +143,43 @@ namespace mbts.spark { await _model.algo_model.remove_definition(definition.key); } else { // This is a new definition, which hasn't been saved/persisted yet. No need to call the server. - definition.templates.Clear(); definitions.Remove(definition); } } - public async Task remove_template(AlgoDefinitionTemplateVM template) { - if (template.key.mode == AlgoKey.Mode.Persisted) { - await _model.algo_model.remove_template(template.key); - } else { - // This is a new template, which hasn't been saved/persisted yet. No need to call the server. - template.owner.templates.Remove(template); - } - } + public Task save_definition(AlgoDefinitionVM definition) => + _save(new[] { definition }); - public async Task save_definition(AlgoDefinitionVM definition) { - using (_save_op()) { - var newly_persisted_keys = await AlgoPersistenceHelper.persist_definition(_model, _definitions, definition); - AlgoKey pkey; - switch (definition.key.mode) { - case AlgoKey.Mode.Unpersisted: - if (!newly_persisted_keys.TryGetValue(definition.key, out pkey)) - return; - break; - case AlgoKey.Mode.Persisted: - pkey = definition.key; - break; - default: return; - } - await _model.algo_model.metadata_service.update_metadata(pkey, _ => definition.create_metadata().with(id: pkey)); - } - } + public Task save_all() => + _save(definitions); - public async Task save_template(AlgoDefinitionTemplateVM template) { - using (_save_op()) - await AlgoPersistenceHelper.persist_template(_model, _definitions, template); - } - - public async Task save_all() => - await _save(definitions.WrapSelector(def => (def, def.templates.AsList()), t => t.def)); - - async Task _save(IList<(AlgoDefinitionVM definition, IList templates)> definition_templates) { - using (_save_op()) - await AlgoPersistenceHelper.persist(_model, definition_templates); - } - - IDisposable _save_op() { - int? def_index = selected_definition == null ? (int?)null : _definitions.IndexOf(selected_definition); - int? tmp_index = selected_template == null ? (int?)null : selected_definition.templates.IndexOf(selected_template); - return new CompositeDisposable(_definitions_update_buffer.buffer_updates()) { - () => { - if (def_index.HasValue) { - var def = _definitions[def_index.Value]; - if (tmp_index.HasValue) { - var tmp = def.templates[tmp_index.Value]; - tmp.is_selected = true; - } else def.is_selected = true; + async Task _save(IEnumerable definitions) { + var orig_selected = selected_definition; + var orig_selected_index = orig_selected == null ? -1 : this.definitions.IndexOf(orig_selected); + using (_definitions_update_buffer.buffer_updates()) { + var def_list = definitions as IList ?? definitions.ToList(); + await Task.WhenAll(definitions.Select(async d => { + var def = await _model.algo_model.save_definition(d.create_algo_def()); + if (def.HasValue) { + // don't forget to save metadata + await _model.algo_model.metadata_service.update_metadata(def.Value.key, _ => d.create_metadata().with(def.Value.key)); } - } - }; - } - - /// Despite the existence of these properties: , and , - /// still implements to update the properties that depend on the . - /// [John]I am going to Uganda in 3 days (today is 1/3/2019), and decided against removing this legacy-dependency at the last minute. - /// Fwiw, and are bound to . - /// They serve to prevent a quirky default behavior in TreeView: double clicking any TreeViewItem collapses the entire TreeView. - /// This behavior wasn't just quirky either, it actually conflicted with the double-click-to-set-template-as-default behavior. - /// (for details, ) - void IHandleSelectedItemChanged.on_selected_item_changed(object old_value, object new_value) { - if (new_value is AlgoDefinitionVM def) { - selected_definition = def; - selected_template = null; - } else if (new_value is AlgoDefinitionTemplateVM templ) { - selected_definition = templ.owner; - selected_template = templ; - } else { - selected_definition = null; - selected_template = null; + return def; + })).ContinueOnDispatcher(t => { + if (t.Status != TaskStatus.RanToCompletion) { + Log.Ui.debug_fatal($"Algo Studio error saving definitions: unexpected Task.Status '{t.Status}'."); + return; + } + var persisted_data = t.Result; + Log.assert(persisted_data.Length == def_list.Count); + for (int i = 0; i < persisted_data.Length; i++) { + if (!def_list[i].key.is_persisted && persisted_data[i].HasValue) + _definitions.Replace(def_list[i].key, def_list[i].to_persisted(persisted_data[i].Value)); + } + if (selected_definition != orig_selected && orig_selected_index >= 0 && orig_selected_index < this.definitions.Count) + selected_definition = this.definitions[orig_selected_index]; + }); } - _selected_changed?.Invoke((selected_definition, selected_template)); - RaisePropertyChanged(nameof(content_source)); } } } \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs index 82e95beb8..00c27f954 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs @@ -136,7 +136,7 @@ namespace mbts.spark { c.PropertyChanged -= on_prop_changed; } AccountTuple? account_factory(KeyValuePair kv) => new AccountTuple(kv.Key, kv.Value); - AlgoDefinitionVM algo_factory(AlgoData data) => AlgoDefinitionVM.create(_model, data, false); + AlgoDefinitionVM algo_factory(AlgoData data) => AlgoDefinitionVM.create(_model, data); } public event Action result_changed; diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs index 7dc1fb12a..5411de8cf 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs @@ -318,14 +318,13 @@ namespace mbts.spark { }), // custom templates (created by user) _model.algo_model.definitions.OnDispatcher().Subscribe(u => - AlgoCollectionHelper.update_persisted_definition_wrappers(attach_vm.algo_vm.algo_roots_index, u, mk_factory(true))))); + AlgoCollectionHelper.update_persisted_definition_wrappers(attach_vm.algo_vm.algo_roots_index, u, mk_algo_def_vm)))); // vm factory - Func mk_factory(bool connect) => - fd => { - var vm = AlgoDefinitionVM.create(_model, fd, connect, OrderDataHelper.get_algo_format(_selected_params_mon.security?.ContractCase), AlgoEditingPermissions.AllowEditValues); - vm.selected_format = OrderDataHelper.get_algo_format(_selected_params_mon.security?.ContractCase); - return vm; - }; + AlgoDefinitionVM mk_algo_def_vm(AlgoData fd) { + var vm = AlgoDefinitionVM.create(_model, fd, OrderDataHelper.get_algo_format(_selected_params_mon.security?.ContractCase), AlgoEditingPermissions.AllowEditValues); + vm.selected_format = OrderDataHelper.get_algo_format(_selected_params_mon.security?.ContractCase); + return vm; + } } void on_end_attaching() => Disposable.dispose(ref attach_vm_hooks); diff --git a/src/client/spark/Orders/OrderPropertiesEditorVM.cs b/src/client/spark/Orders/OrderPropertiesEditorVM.cs index 81354eae0..27ecfe045 100644 --- a/src/client/spark/Orders/OrderPropertiesEditorVM.cs +++ b/src/client/spark/Orders/OrderPropertiesEditorVM.cs @@ -52,7 +52,6 @@ namespace mbts.spark { class OrderPropertiesEditorVM : DisposableViewModelBase { readonly OrdersModel _model; readonly Property _security; - readonly Property _selected_algo_template, _selected_favorite_algo_template; readonly SelectorProperty _accounts; readonly SelectorProperty _time_in_force; readonly SelectionModel _selected_algo_definition; @@ -60,8 +59,6 @@ namespace mbts.spark { readonly ObservableKeyedCollection _algo_definitions = new ObservableKeyedCollection(d => d.key); readonly ListCollectionView _algo_definitions_view, _favorite_algo_definitions_view; readonly TableUpdateBuffer _definitions_buffer = new TableUpdateBuffer(d => d.key); - readonly EditableCollectionModel _algo_template_collection_model; - readonly ObservableKeyedCollection _favorite_templates = new ObservableKeyedCollection(tvm => tvm.key); readonly ObservableAggregateCollection _algo_param_rows = new ObservableAggregateCollection(); IReadOnlyDictionary _algo_metadata = DictionaryHelper.empty(); IReadOnlyDictionary _favorite_algos_index = DictionaryHelper.empty(); @@ -74,7 +71,6 @@ namespace mbts.spark { var security_source = security_md_source.Select(smd => smd.security); _security = backing(nameof(security), security_source, SecurityDataHelper.Defaults.SecurityImmutable); security_source = _security.observe_current(true); - _selected_algo_template = backing(nameof(selected_algo_template)); _selected_algo_definition = new SelectionModel(algo_definitions, () => { var t = _model.factory.default_order_type(security); @@ -131,29 +127,8 @@ namespace mbts.spark { order_properties.Select(ops => ops.time_in_force), () => model.factory.default_time_in_force(security), tif => time_in_forces.Contains(tif)); - _selected_favorite_algo_template = backing(nameof(selected_favorite_algo_template)); - // items source views - algo_templates_view = CollectionViewSource.GetDefaultView(algo_templates); - var favorite_algo_templates_view = new ListCollectionView(ObservableAggregateCollection.create(_algo_definitions.AsCollection(), d => d.templates)); - favorite_algo_templates_view.LiveGroupingProperties.Add(nameof(AlgoDefinitionTemplateVM.owner_key)); - favorite_algo_templates_view.LiveFilteringProperties.Add(nameof(AlgoDefinitionTemplateVM.is_favorite)); - favorite_algo_templates_view.Filter = item => (item as AlgoDefinitionTemplateVM)?.is_favorite ?? false; - favorite_algo_templates_view.IsLiveFiltering = true; - this.favorite_algo_templates_view = favorite_algo_templates_view; // commands save_definition_cmd = new AsyncCommand(save_definition_async); - save_template_cmd = new AsyncCommand(save_template_async); - remove_template_cmd = new AsyncCommand(tvm => _model.algo_model.remove_template(tvm.key)); - toggle_is_favorite_cmd = new DelegateCommand(tvm => _favorite_templates.Add(tvm)); - _algo_template_collection_model = new EditableCollectionModel(d => selected_algo_definition == null ? default : selected_algo_definition.template_factory(), d => d != null); - redo_cmd = ObservantCommand.create( - t => t?.redo(), - t => t == null ? Observable.Return(false) : System.Reactive.Linq.ObservableExtensions.FromEvent(cb => t.can_redo_changed += cb, cb => t.can_redo_changed -= cb, () => t.can_redo).OnDispatcher(), - out IObserver redo_observer); - undo_cmd = ObservantCommand.create( - t => t?.undo(), - t => t == null ? Observable.Return(false) : System.Reactive.Linq.ObservableExtensions.FromEvent(cb => t.can_undo_changed += cb, cb => t.can_undo_changed -= cb, () => t.can_undo).OnDispatcher(), - out IObserver undo_observer); undo_definition_cmd = ObservantCommand.create( d => d?.undo(), d => d == null ? Observable.Return(false) : System.Reactive.Linq.ObservableExtensions.FromEvent(cb => d.can_undo_changed += cb, cb => d.can_undo_changed -= cb, () => d.can_undo).OnDispatcher(), @@ -186,31 +161,10 @@ namespace mbts.spark { algo_params_dirty_mon.Subscribe(set_default_algo_params_observer, revert_algo_params_observer), ObservableAutoWrapper.connect_item_hooks(_algo_param_rows, algo_params_dirty_mon.join), _selected_algo_definition.subscribe_changed(_selected_algo_definition_Changed), - as_demuxer().subscribe(nameof(selected_algo_template)).Subscribe( - undo_observer, - redo_observer), as_demuxer().subscribe(nameof(selected_algo_definition)).Subscribe( undo_definition_observer, redo_definition_observer, revert_definition_observer), - algo_definitions.Subscribe((s, e) => { - if (e.OldItems != null) - e.OldItems.OfType().DisposeAll(); - if (e.NewItems != null) { - foreach (AlgoDefinitionVM d in e.NewItems) { - switch (d.key.mode) { - case AlgoKey.Mode.Persisted: - if (_model.algo_model.ui_configuration.include_custom_templates && _model.algo_model.templates_enabled()) - d.prepend_custom_template(); - break; - case AlgoKey.Mode.Factory: - if (_model.algo_model.ui_configuration.include_legacy_custom_templates && _model.algo_model.templates_enabled()) - d.prepend_custom_template(); - break; - } - } - } - }), security_md_source.Select(smd => model.factory.default_algos(smd.security)).Table(s => s.key).Subscribe(factory_defs => { using (_selected_algo_definition.begin_update()) AlgoCollectionHelper.update_persisted_definitions(_algo_definitions, factory_defs, fd => { @@ -222,43 +176,41 @@ namespace mbts.spark { model.algo_model.definitions.Subscribe(_definitions_buffer), _definitions_buffer.OnDispatcher().Subscribe(u => { AlgoCollectionHelper.update_persisted_definitions(_algo_definitions, u, def_data => { - var def_vm = AlgoDefinitionVM.create(model, def_data, true, OrderDataHelper.get_algo_format(security.ContractCase), AlgoEditingPermissions.AllowEditValues); + var def_vm = AlgoDefinitionVM.create(model, def_data, OrderDataHelper.get_algo_format(security.ContractCase), AlgoEditingPermissions.AllowEditValues); def_vm.selected_format = OrderDataHelper.get_algo_format(security.ContractCase); def_vm.favorite_index = _get_favorite_algo_index(def_vm.key); return def_vm; }); - }), + }), model.algo_model.metadata_service.subscribe_metadata().OnDispatcher().Subscribe(_on_template_metadata), ObservableAutoWrapper.connect_item_hooks(algo_definitions, vm => - Disposable.Create( - vm.connect_data(nullable_security_md_source), - security_source.Subscribe(s => { - var fmt = OrderDataHelper.get_algo_format(s.ContractCase); - foreach (var d in algo_definitions) - d.selected_format = fmt; - }), - vm), true)) { - () => { - Disposable.dispose(ref _template_collection_sync); - Disposable.dispose(ref _algo_param_rows_hook); - } + Disposable.Create( + vm.connect_data(nullable_security_md_source), + security_source.Subscribe(s => { + var fmt = OrderDataHelper.get_algo_format(s.ContractCase); + foreach (var d in algo_definitions) + d.selected_format = fmt; + }), + vm), + true)) { + () => Disposable.dispose(ref _algo_param_rows_hook) }; // local methods - async Task save_template_async(AlgoDefinitionTemplateVM template) { - using (_preserve_selection_by_index()) - await AlgoPersistenceHelper.persist_template(model, algo_definitions, template); - } async Task save_definition_async(AlgoDefinitionVM definition) { switch (definition.key.mode) { case AlgoKey.Mode.Persisted: - await AlgoPersistenceHelper.persist_definition(model, algo_definitions, definition); + using (_definitions_buffer.buffer_updates()) + await _model.algo_model.save_definition(definition.create_algo_def()); break; case AlgoKey.Mode.Factory: case AlgoKey.Mode.Unpersisted: using (_definitions_buffer.buffer_updates()) { - var persisted_key_lookup = await AlgoPersistenceHelper.persist_definition(model, algo_definitions, definition); - if (persisted_key_lookup.TryGetValue(definition.key, out AlgoKey pkey) && _algo_definitions.TryGetValue(pkey, out AlgoDefinitionVM pdef)) - selected_algo_definition = pdef; + var persisted_def = await model.algo_model.save_definition(definition.create_algo_def()); + if (persisted_def.HasValue) { + int pos = algo_definitions.IndexOf(definition); + if (pos >= 0) + selected_algo_definition = algo_definitions[pos] = definition.to_persisted(persisted_def.Value); + } if (definition.key.mode == AlgoKey.Mode.Factory) { /// Revert the factory definition to its original state. /// Note: this won't revert the parameters in the algo popup since the newly persisted definition () is selected now. @@ -283,32 +235,19 @@ namespace mbts.spark { new InlineUserProperty(); } - IDisposable _template_collection_sync; void _selected_algo_definition_Changed(AlgoDefinitionVM old_value, AlgoDefinitionVM new_value, SelectionReason reason) { - Disposable.dispose(ref _template_collection_sync); Disposable.dispose(ref _algo_param_rows_hook); if (new_value != null) { - _template_collection_sync = ObservableAutoWrapper.connect_two_way(new_value.templates_with_custom, algo_templates); if (use_algo_param_grid) _algo_param_rows_hook = _connect_algo_param_rows(new_value, _algo_param_rows); if (reason != SelectionReason.Explicit) _selected_algo_stack.Push(new_value.key); - } else { - algo_templates.Clear(); } if (open_algo_popup_on_select) { if (reason == SelectionReason.UserSelectedNewValue && new_value?.algo_root is IAlgoVM ar && ar.can_expand) ar.is_expanded = true; } - if (selected_algo_template == null && _model.algo_model.templates_enabled()) { - if (new_value != null) - selected_algo_template = new_value.templates.FirstOrDefault(tvm => tvm.is_default, tvm => _favorite_templates.ContainsKey(tvm.key), tvm => true) ?? new_value.templates_with_custom.FirstOrDefault(); - } else { - RaisePropertyChanged(nameof(selected_algo_template)); - } RaisePropertyChanged(nameof(selected_algo_definition), nameof(selected_favorite_algo_definition), nameof(can_expand), nameof(is_expanded)); - _selected_favorite_algo_template.Value = selected_algo_template is AlgoDefinitionTemplateVM t && t.is_favorite ? t : null; - _algo_template_collection_model.OnNext(new_value); } public SecurityImmutable security => _security.Value; @@ -316,7 +255,6 @@ namespace mbts.spark { public AccountTuple? selected_account { get => _accounts.selected_item; set => _accounts.selected_item = value; } public ReadOnlyObservableCollection time_in_forces => _time_in_force.items; public TimeInForce selected_time_in_force { get => _time_in_force.selected_item; set => _time_in_force.selected_item = value; } - public CustomOrderDefinitionImmutable? definition => selected_algo_template?.algo_root?.definition; public int favorite_algos_column_count { get => _favorite_algos_column_count; private set => Set(ref _favorite_algos_column_count, value); } public bool use_algo_param_grid { get => _use_algo_param_grid; @@ -331,47 +269,14 @@ namespace mbts.spark { } // items sources public ObservableCollection algo_definitions => _algo_definitions; - public ObservableCollection algo_templates { get; } = new ObservableCollection(); public IReadOnlyObservableCollection algo_param_rows => _algo_param_rows; public ICollectionView algo_definitions_view => _algo_definitions_view; public ICollectionView favorite_algo_definitions_view => _favorite_algo_definitions_view; - public ICollectionView algo_templates_view { get; } - public ICollectionView favorite_algo_templates_view { get; } // selected items public AlgoDefinitionVM selected_algo_definition { get => _selected_algo_definition.selected_item; set => _selected_algo_definition.selected_item = value; } - public AlgoDefinitionTemplateVM selected_algo_template { - get => selected_algo_definition?.selected_template; - set { - if (value != selected_algo_template) { - if (value == null) { - if (selected_algo_definition != null) - selected_algo_definition.selected_template = null; - _selected_favorite_algo_template.set(null); - } else { - value.owner.selected_template = value; - _selected_algo_definition.select_explicit(value.owner); // idempotent - _selected_favorite_algo_template.Value = value.is_favorite ? value : null; // idempotent - } - RaisePropertyChanged(); - } - } - } - public AlgoDefinitionTemplateVM selected_favorite_algo_template { - get => _selected_favorite_algo_template.Value; - set { - if (_selected_favorite_algo_template.set_new(value)) { - if (value != null) { - value.owner.selected_template = value; - if (value.owner != selected_algo_definition) - _selected_algo_definition.select_explicit(value.owner); - RaisePropertyChanged(nameof(selected_algo_template)); - } - } - } - } public AlgoDefinitionVM selected_favorite_algo_definition { get => selected_algo_definition?.is_favorite ?? false ? selected_algo_definition : null; set { @@ -403,13 +308,10 @@ namespace mbts.spark { public ICommand revert_definition_cmd { get; } public ICommand set_default_algo_params_cmd { get; } public ICommand revert_algo_params_cmd { get; } - public ICommand undo_cmd { get; } - public ICommand redo_cmd { get; } public ICommand undo_definition_cmd { get; } public ICommand redo_definition_cmd { get; } public ICommand remove_template_cmd { get; } public ICommand toggle_is_favorite_cmd { get; } - public IEditableCollectionModel algo_template_collection_model => _algo_template_collection_model; public IObservable observe_account(bool start_immediately = false) => _accounts.observe_current(start_immediately); @@ -418,9 +320,7 @@ namespace mbts.spark { _time_in_force.observe_current(start_immediately); public IObservable observe_order_type(bool start_immediately = false) => - _model.algo_model.templates_enabled() ? - _selected_algo_template.observe_current(start_immediately).Select(t => t?.algo_root) : - _selected_algo_definition.observe_selected_item(start_immediately).Select(d => d?.algo_root); + _selected_algo_definition.observe_selected_item(start_immediately).Select(d => d?.algo_root); public OrderDefinition create(Side side) { if (HasErrors) @@ -428,25 +328,21 @@ namespace mbts.spark { var order = _model.factory.order(security, selected_account); order.TimeInForce = selected_time_in_force; order.Side = side; - if (_model.algo_model.templates_enabled()) { - selected_algo_template.algo_root.assign_to(order.CustomDef); - } else { - var algo = new CustomOrderDefinition(); - selected_algo_definition.algo_root.assign_to(algo); - switch (selected_algo_definition.key.mode) { - case AlgoKey.Mode.Persisted: - order.CustomDef = new CustomOrderDefinition { - Composite = new CompositeOrderDefinition { - AlgoTemplateKey = selected_algo_definition.key.persisted.id_uint, - Definition = algo - } - }; - selected_algo_definition.algo_root.assign_to(order.CustomDef.Composite.Definition); - break; - default: - order.CustomDef = algo; - break; - } + var algo = new CustomOrderDefinition(); + selected_algo_definition.algo_root.assign_to(algo); + switch (selected_algo_definition.key.mode) { + case AlgoKey.Mode.Persisted: + order.CustomDef = new CustomOrderDefinition { + Composite = new CompositeOrderDefinition { + AlgoTemplateKey = selected_algo_definition.key.persisted.id_uint, + Definition = algo + } + }; + selected_algo_definition.algo_root.assign_to(order.CustomDef.Composite.Definition); + break; + default: + order.CustomDef = algo; + break; } return order; } @@ -458,10 +354,6 @@ namespace mbts.spark { _favorite_algos_index = value.favorite_algos.Select((v, i) => (v, i)).ToDictionaryCrushed(t => t.v, t => t.i); foreach (var d in algo_definitions) { d.favorite_index = _get_favorite_algo_index(d.key); - foreach (var t in d.templates) { - if (t.key.mode == AlgoKey.Mode.Persisted) - t.is_favorite = _favorite_algos_index.ContainsKey(t.key); - } } favorite_algos_column_count = value.column_count; } @@ -479,29 +371,7 @@ namespace mbts.spark { void _on_template_metadata(IReadOnlyDictionary meta) { _algo_metadata = meta; - var curr_selected_template = selected_algo_template; - if (curr_selected_template?.is_favorite ?? false) - selected_favorite_algo_template = curr_selected_template; algo_definitions_view.Refresh(); } - - // This preserves the selected items through a save op. - // When a definition/template is persisted for the first time, its unpersisted-placeholder item is removed and replaced with a new persisted one. - // If an unpersisted item is selected when it is removed, the view will automatically select null - this method is a workaround for that. - IDisposable _preserve_selection_by_index() { - (int? selected_def_index, int? selected_tmp_index) = AlgoPersistenceHelper.selection_snapshot(algo_definitions, selected_algo_definition, selected_algo_template); - return new CompositeDisposable(_definitions_buffer.buffer_updates()) { - () => { - if (selected_def_index is int di && algo_definitions.check_index(di)) { - var def = algo_definitions[di]; - if (selected_tmp_index is int ti && def.templates.check_index(ti)) { - selected_algo_template = def.templates[ti]; - } else { - selected_algo_definition = def; - } - } - } - }; - } } } diff --git a/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml b/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml index a3b82fee1..ffde55bfd 100644 --- a/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml +++ b/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml @@ -55,14 +55,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -378,36 +188,9 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/client/spark/view/Controls/Order/AlgoTemplateToolBar.xaml.cs b/src/client/spark/view/Controls/Order/AlgoTemplateToolBar.xaml.cs index 5aff7d5e5..cd208a10b 100644 --- a/src/client/spark/view/Controls/Order/AlgoTemplateToolBar.xaml.cs +++ b/src/client/spark/view/Controls/Order/AlgoTemplateToolBar.xaml.cs @@ -1,16 +1,7 @@ using mbts.spark; -using mbts.ui.controls; -using mbts.ui.converters; -using mbts.ui.extensions; using mbts.ui.utility; -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Linq; using System.Windows; using System.Windows.Controls; -using System.Windows.Data; using System.Windows.Input; namespace mbts.ui.spark.algo { @@ -18,51 +9,6 @@ namespace mbts.ui.spark.algo { /// Interaction logic for AlgoTemplateToolBar.xaml /// class AlgoTemplateToolBar : HeaderedItemsControl { - // The Favorites toggle button exists in 2 forms: as a MenuItem in AlgoTemplateToolBar, and as a ToggleButton in AlgoStudioView - // The const strings below are used to store this text in 1 place. - public const string - AddToFavoritesToolTip = "Add to Favorites", - RemoveFromFavoritesToolTip = "Remove from Favorites"; - - public static readonly IValueConverter FavoriteToggleButtonToolTipConverter = - ValueConverter.create(is_checked => is_checked ? RemoveFromFavoritesToolTip : AddToFavoritesToolTip); - - public static readonly RoutedUICommand - BeginAddNewCommand = new RoutedUICommand("Add New Template", "Add New", typeof(AlgoTemplateToolBar)), - BeginSaveCommand = new RoutedUICommand("Save Template", "Save", typeof(AlgoTemplateToolBar)), - BeginSaveDefinitionCommand = new RoutedUICommand("Save Definition", "Save", typeof(AlgoTemplateToolBar)), - BeginSaveAsCommand = new RoutedUICommand("Save Template As", "Save As", typeof(AlgoTemplateToolBar)), - BeginSaveDefinitionAsCommand = new RoutedUICommand("Save Definition As", "Save As", typeof(AlgoTemplateToolBar)), - BeginRevertCommand = new RoutedUICommand("Revert to Template", "Revert", typeof(AlgoTemplateToolBar)), - BeginRevertDefinitionCommand = new RoutedUICommand("Revert to Definition", "Revert", typeof(AlgoTemplateToolBar)), - BeginRedoCommand = new RoutedUICommand("Redo", "Redo", typeof(AlgoTemplateToolBar)), - BeginUndoCommand = new RoutedUICommand("Undo", "Undo", typeof(AlgoTemplateToolBar)), - BeginRedoDefinitionCommand = new RoutedUICommand("Redo Definition", "Redo Definition", typeof(AlgoTemplateToolBar)), - BeginUndoDefinitionCommand = new RoutedUICommand("Undo Definition", "Undo Definition", typeof(AlgoTemplateToolBar)), - BeginRemoveCommand = new RoutedUICommand("Delete Template", "Delete", typeof(AlgoTemplateToolBar)), - BeginToggleFavoriteCommand = new RoutedUICommand("Toggle Favorite", "Toggle Favorite", typeof(AlgoTemplateToolBar)); - - public static readonly ExecutedRoutedEventHandler - BeginAddNewExecuted = WPFHelper.create_cmd_executed((tb, _) => tb._add_new()), - BeginSaveExecuted = WPFHelper.create_cmd_executed((tb, _) => tb._save()), - BeginSaveDefinitionExecuted = WPFHelper.create_cmd_executed((tb, _) => tb._save_definition()), - BeginSaveAsExecuted = WPFHelper.create_cmd_executed((tb, _) => tb._save_as()), - BeginSaveDefinitionAsExecuted = WPFHelper.create_cmd_executed((tb, _) => tb._save_definition_as()), - BeginRevertExecuted = WPFHelper.create_cmd_executed((tb, _) => tb._revert()), - BeginRevertDefinitionExecuted = WPFHelper.create_cmd_executed((tb, _) => tb._revert_definition()), - BeginRedoExecuted = WPFHelper.create_cmd_executed((tb, _) => tb._redo()), - BeginUndoExecuted = WPFHelper.create_cmd_executed((tb, _) => tb._undo()), - BeginRedoDefinitionExecuted = WPFHelper.create_cmd_executed((tb, _) => tb._redo_definition()), - BeginUndoDefinitionExecuted = WPFHelper.create_cmd_executed((tb, _) => tb._undo_definition()), - BeginRemoveExecuted = WPFHelper.create_cmd_executed((tb, t) => tb._remove(t)), - BeginToggleFavoriteExecuted = WPFHelper.create_cmd_executed((tb, param) => tb.ToggleFavoriteCommand.TryExecuteIfCan(param)); - - ComboBox _templates_combo; - EditableTextBlock _definition_name_text; - IDisposable _input_hooks; - // this is a casted backing for 'Items' - IEditableCollectionViewAddNewItem _editable_items; - static AlgoTemplateToolBar() => DefaultStyleKeyProperty.OverrideMetadata(typeof(AlgoTemplateToolBar), new FrameworkPropertyMetadata(typeof(AlgoTemplateToolBar))); @@ -73,37 +19,6 @@ namespace mbts.ui.spark.algo { VisualStateNames.apply_all(this); } - #region ShowTemplatesDropDown - public static readonly DependencyProperty ShowTemplatesDropDownProperty = - WPFHelper.create_dp( - nameof(ShowTemplatesDropDown), - (o, v) => { - string dropdown_state, rename_state; - if (v) { - dropdown_state = VisualStateNames.TemplatesDropDown.Active; - rename_state = VisualStateNames.RenameTemplate.Active; - } else { - dropdown_state = VisualStateNames.TemplatesDropDown.Inactive; - rename_state = VisualStateNames.RenameTemplate.Inactive; - } - o._vsm.set_state(VisualStateNames.TemplatesDropDown.GroupName, dropdown_state); - o._vsm.set_state(VisualStateNames.RenameTemplate.GroupName, rename_state); - }, - coerce_require_persisted); - - public bool ShowTemplatesDropDown { get => (bool)GetValue(ShowTemplatesDropDownProperty); set => SetValue(ShowTemplatesDropDownProperty, value); } - #endregion - - #region ShowToggleFavorite - public static readonly DependencyProperty ShowToggleFavoriteProperty = - WPFHelper.create_dp( - nameof(ShowToggleFavorite), - (o, v) => VisualStateNames.ToggleFavorite.apply(o._vsm, v), - coerce_require_persisted); - - public bool ShowToggleFavorite { get => (bool)GetValue(ShowToggleFavoriteProperty); set => SetValue(ShowToggleFavoriteProperty, value); } - #endregion - #region ShowDefinitionName public static readonly DependencyProperty ShowDefinitionNameProperty = WPFHelper.create_dp(nameof(ShowDefinitionName)); @@ -130,16 +45,6 @@ namespace mbts.ui.spark.algo { public bool ShowRevertDefinition { get => (bool)GetValue(ShowRevertDefinitionProperty); set => SetValue(ShowRevertDefinitionProperty, value); } #endregion - #region ShowRenameDefinition - public static readonly DependencyProperty ShowRenameDefinitionProperty = - WPFHelper.create_dp( - nameof(ShowRenameDefinition), - (o, v) => VisualStateNames.RenameDefinition.apply(o._vsm, v), - coerce_require_persisted); - - public bool ShowRenameDefinition { get => (bool)GetValue(ShowRenameDefinitionProperty); set => SetValue(ShowRenameDefinitionProperty, value); } - #endregion - #region ShowSaveDefinition public static readonly DependencyProperty ShowSaveDefinitionProperty = WPFHelper.create_dp( @@ -154,7 +59,6 @@ namespace mbts.ui.spark.algo { public static readonly DependencyProperty DefinitionProperty = WPFHelper.create_dp(nameof(Definition), (o, v) => { - o.CoerceValue(ShowRenameDefinitionProperty); o.CoerceValue(ShowSaveDefinitionProperty); //o.CoerceValue(ShowRevertDefinitionProperty); o.CoerceValue(ShowUndoRedoButtonsProperty); @@ -163,51 +67,6 @@ namespace mbts.ui.spark.algo { public AlgoDefinitionVM Definition { get => GetValue(DefinitionProperty) as AlgoDefinitionVM; set => SetValue(DefinitionProperty, value); } #endregion - #region SelectedItem - public static readonly DependencyProperty SelectedItemProperty = - WPFHelper.create_dp( - nameof(SelectedItem), - FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, - (o, oldval, newval) => { - // TODO: consider an alternate solution to the problem here, subscribing to PropertyChanged for 1 property feels a little hackey. - // We could make IsEdited a non-readonly dp, and just bind to SelectedItem.is_edited; however, this compromises the AlgoTemplateToolBar's public interface bc the concept this value represents is not ambiguous. - // IsEdited always means 1 thing: the SelectedItem's (algo-template) order-definition is 'dirty' - different from the values currently in the OrderPropertiesEditor. - // The reason this is useful: - /// When the algo template becomes dirty (which is easy to tell via a dpchanged callback), we call . - /// Then, in any subsequent Save/SaveAs Executed callbacks, we check if an item is currently being edited (). - /// If that is true, we update the IAlgoTemplateItem's order-definition (). - /// - if (oldval is INotifyPropertyChanged oldnpc) oldnpc.PropertyChanged -= o._on_SelectedItem_PropertyChanged; - if (newval is INotifyPropertyChanged newnpc) newnpc.PropertyChanged += o._on_SelectedItem_PropertyChanged; - o.CoerceValue(IsEditedProperty); - }); - - void _on_SelectedItem_PropertyChanged(object sender, PropertyChangedEventArgs e) { - if (e.PropertyName == nameof(AlgoDefinitionTemplateVM.is_dirty)) - CoerceValue(IsEditedProperty); - } - - public AlgoDefinitionTemplateVM SelectedItem { get => GetValue(SelectedItemProperty) as AlgoDefinitionTemplateVM; set => SetValue(SelectedItemProperty, value); } - #endregion - - #region EditableCollectionModel - public static readonly DependencyProperty EditableCollectionModelProperty = - WPFHelper.create_dp, AlgoTemplateToolBar>(nameof(EditableCollectionModel)); - public IEditableCollectionModel EditableCollectionModel { get => GetValue(EditableCollectionModelProperty) as IEditableCollectionModel; set => SetValue(EditableCollectionModelProperty, value); } - #endregion - - #region AddNew - public static readonly DependencyProperty AddNewCommandProperty = - WPFHelper.create_dp(nameof(AddNewCommand)); - public ICommand AddNewCommand { get => GetValue(AddNewCommandProperty) as ICommand; set => SetValue(AddNewCommandProperty, value); } - #endregion - - #region Save - public static readonly DependencyProperty SaveCommandProperty = - WPFHelper.create_dp(nameof(SaveCommand)); - public ICommand SaveCommand { get => GetValue(SaveCommandProperty) as ICommand; set => SetValue(SaveCommandProperty, value); } - #endregion - #region SaveDefinition public static readonly DependencyProperty SaveDefinitionCommandProperty = WPFHelper.create_dp(nameof(SaveDefinitionCommand)); @@ -220,36 +79,12 @@ namespace mbts.ui.spark.algo { public ICommand SetDefaultsCommand { get => GetValue(SetDefaultsCommandProperty) as ICommand; set => SetValue(SetDefaultsCommandProperty, value); } #endregion - #region Revert - public static readonly DependencyProperty RevertCommandProperty = - WPFHelper.create_dp(nameof(RevertCommand)); - public ICommand RevertCommand { get => GetValue(RevertCommandProperty) as ICommand; set => SetValue(RevertCommandProperty, value); } - #endregion - #region RevertDefinition public static readonly DependencyProperty RevertDefinitionCommandProperty = WPFHelper.create_dp(nameof(RevertDefinitionCommand)); public ICommand RevertDefinitionCommand { get => GetValue(RevertDefinitionCommandProperty) as ICommand; set => SetValue(RevertDefinitionCommandProperty, value); } #endregion - #region Remove - public static readonly DependencyProperty RemoveCommandProperty = - WPFHelper.create_dp(nameof(RemoveCommand)); - public ICommand RemoveCommand { get => GetValue(RemoveCommandProperty) as ICommand; set => SetValue(RemoveCommandProperty, value); } - #endregion - - #region Undo - public static readonly DependencyProperty UndoCommandProperty = - WPFHelper.create_dp(nameof(UndoCommand)); - public ICommand UndoCommand { get => GetValue(UndoCommandProperty) as ICommand; set => SetValue(UndoCommandProperty, value); } - #endregion - - #region Redo - public static readonly DependencyProperty RedoCommandProperty = - WPFHelper.create_dp(nameof(RedoCommand)); - public ICommand RedoCommand { get => GetValue(RedoCommandProperty) as ICommand; set => SetValue(RedoCommandProperty, value); } - #endregion - #region UndoDefinition public static readonly DependencyProperty UndoDefinitionCommandProperty = WPFHelper.create_dp(nameof(UndoDefinitionCommand)); @@ -262,33 +97,6 @@ namespace mbts.ui.spark.algo { public ICommand RedoDefinitionCommand { get => GetValue(RedoDefinitionCommandProperty) as ICommand; set => SetValue(RedoDefinitionCommandProperty, value); } #endregion - #region ToggleFavorite - public static readonly DependencyProperty ToggleFavoriteCommandProperty = - WPFHelper.create_dp(nameof(ToggleFavoriteCommand)); - public ICommand ToggleFavoriteCommand { get => GetValue(ToggleFavoriteCommandProperty) as ICommand; set => SetValue(ToggleFavoriteCommandProperty, value); } - #endregion - - #region ToggleFavorite Parameter - public static readonly DependencyProperty ToggleFavoriteCommandParameterProperty = - WPFHelper.create_dp(nameof(ToggleFavoriteCommandParameter)); - public object ToggleFavoriteCommandParameter { get => GetValue(ToggleFavoriteCommandParameterProperty); set => SetValue(ToggleFavoriteCommandParameterProperty, value); } - #endregion - - #region IsEdited - /// - /// This property indicates whether or not the order definition held by the is 'dirty' - different from the one that would be created by the OrderPropertiesEditor at this time. - /// When it becomes dirty, we call . This leads the viewmodel to take a snapshot of its current state, - /// so in the event that another template is selected, or the values in the OrderPropertiesEditor are reverted, we can snap everything back into place by calling - /// - static readonly DependencyPropertyKey IsEditedPropertyKey = - WPFHelper.create_ro_dp( - nameof(IsEdited), - null, - (o, v) => o.SelectedItem is AlgoDefinitionTemplateVM t && t.is_dirty && !t.is_custom_placeholder); - internal static readonly DependencyProperty IsEditedProperty = IsEditedPropertyKey.DependencyProperty; - internal bool IsEdited { get => (bool)GetValue(IsEditedProperty); private set => SetValue(IsEditedPropertyKey, value); } - #endregion - #region IsEditing public static readonly DependencyProperty IsEditingProperty = WPFHelper.create_dp(nameof(IsEditing)); @@ -301,152 +109,14 @@ namespace mbts.ui.spark.algo { public bool IsReadOnly { get => (bool)GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } #endregion - public override void OnApplyTemplate() { - Disposable.dispose(ref _input_hooks); - _templates_combo = this.assert_template_child("PART_Templates_ComboBox"); - _definition_name_text = this.assert_template_child("PART_DefinitionName_EditableTextBlock"); - _input_hooks = Disposable.Create( - _definition_name_text.SubscribePreviewKeyDown((s, e) => { - switch (e.Key) { - case Key.Escape: - if (_definition_name_text.IsEditing) - _definition_name_text.abort(); - break; - } - }), - _templates_combo.SubscribePreviewKeyDown((s, e) => { - switch (e.Key) { - case Key.Enter: - Keyboard.ClearFocus(); - _commit(); - break; - case Key.Escape: - _cancel(); - Keyboard.ClearFocus(); - SetCurrentValue(IsEditingProperty, false); - break; - } - })); - } - - protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e) { - base.OnItemsChanged(e); - _editable_items = Items; - } - static bool coerce_require_persisted(AlgoTemplateToolBar d, bool value) => value && d.Definition is AlgoDefinitionVM vm && vm.key.mode == AlgoKey.Mode.Persisted; - #region Transactional - void _add_new() { - _prepare_edit(); - var model = EditableCollectionModel; - if (model != null && model.can_add_new) - _editable_items.AddNewItem(model.new_item_factory()); - } - - void _cancel() => _editable_items.CancelAny(); - - void _commit(bool execute_save = false) { - if (_editable_items.IsEditingItem) { - var editing_item = (AlgoDefinitionTemplateVM)_editable_items.CurrentEditItem; - editing_item.name = _templates_combo.Text; - _editable_items.CommitEdit(); - SetCurrentValue(SelectedItemProperty, editing_item); - if (execute_save) - SaveCommand.TryExecuteIfCan(editing_item); - SetCurrentValue(IsEditingProperty, false); - } else if (_editable_items.IsAddingNew) { - var new_item = (AlgoDefinitionTemplateVM)_editable_items.CurrentAddItem; - new_item.name = _templates_combo.Text; - _editable_items.CommitNew(); - SetCurrentValue(SelectedItemProperty, new_item); - if (execute_save) - SaveCommand.TryExecuteIfCan(new_item); - SetCurrentValue(IsEditingProperty, false); - } else { - SaveCommand.TryExecuteIfCan(SelectedItem); - } - } - - void _revert() => RevertCommand.TryExecuteIfCan(null); - void _revert_definition() => RevertDefinitionCommand.TryExecuteIfCan(null); - - void _redo() => _redo(SelectedItem); - void _undo() => _undo(SelectedItem); - void _redo_definition() => _redo(Definition); - void _undo_definition() => _undo(Definition); - - void _redo(IAlgoStudioContentVM c) { - if (c != null && c.can_redo) - c.redo(); - } - void _undo(IAlgoStudioContentVM c) { - if (c != null && c.can_undo) - c.undo(); - } - - void _remove(object template) { - _editable_items?.Remove(template); - RemoveCommand.TryExecuteIfCan(template); - } - - void _save() { - if (SelectedItem == null) { - _add_new(); - } else _commit(true); - } - - void _save_definition() { - if (Definition is AlgoDefinitionVM d && d.is_dirty) { - _definition_name_text?.end_edit(); - SaveDefinitionCommand?.TryExecuteIfCan(d); - } - } - - void _save_as() { - if (SelectedItem == null) { - _add_new(); - } else { - _prepare_edit(); - _editable_items.EditItem(SelectedItem); - } - } - - void _save_definition_as() { - _definition_name_text?.begin_edit(); - } - - bool _focus() { - if (_templates_combo == null || !_templates_combo.IsEnabled) return false; - var textbox = _templates_combo.descendants_of_type().FirstOrDefault(); - if (textbox == null) return false; - FocusManager.SetFocusedElement(this, textbox); - Focus(); - Keyboard.Focus(textbox); - return true; - } - - void _prepare_edit() { - _editable_items.CancelAny(); - SetCurrentValue(IsEditingProperty, true); - // This is a hack ¯\_(ツ)_/¯ but it is effective and simple. - // The correct/non-hack way to achieve this behavior most likely requires re-templating the ComboBox - a lot of work. - /// The goal: auto-focus the textbox inside the ComboBox. - /// The dilemma: the textbox does not exist until the ComboBox is rendered again (since we just changed ComboBox.IsEditing to true in the previous line, this has not happened yet). - WPFHelper.push_frame_until(() => _focus()); - } - #endregion - public static class VisualStateNames { public static void apply_all(AlgoTemplateToolBar toolbar) { UndoRedo.apply(toolbar._vsm, toolbar.ShowUndoRedoButtons); RevertDefinition.apply(toolbar, toolbar.ShowRevertDefinition); - RenameDefinition.apply(toolbar._vsm, toolbar.ShowRenameDefinition); SaveDefinition.apply(toolbar._vsm, toolbar.ShowSaveDefinition); - TemplatesDropDown.apply(toolbar._vsm, toolbar.ShowTemplatesDropDown); - RenameTemplate.apply(toolbar._vsm, toolbar.ShowTemplatesDropDown); // there is no corresponding 'CanUserRenameTemplate' property at the moment, for now it just refers to ShowTemplates. - ToggleFavorite.apply(toolbar._vsm, toolbar.ShowToggleFavorite); } public static class UndoRedo { public const string GroupName = nameof(UndoRedo); @@ -466,15 +136,6 @@ namespace mbts.ui.spark.algo { public static void apply(AlgoTemplateToolBar owner, bool active) => owner.Dispatcher.InvokeAsync(() => owner._vsm.set_state(GroupName, active ? Active : Inactive)); } - public static class RenameDefinition { - public const string GroupName = nameof(RenameDefinition); - public static readonly string - Active = $"{GroupName}{VisualStates.Active}", - Inactive = $"{GroupName}{VisualStates.Inactive}"; - - public static void apply(VisualStateModel vsm, bool active) => - vsm.set_state(GroupName, active ? Active : Inactive); - } public static class SaveDefinition { public const string GroupName = nameof(SaveDefinition); public static readonly string @@ -484,33 +145,6 @@ namespace mbts.ui.spark.algo { public static void apply(VisualStateModel vsm, bool active) => vsm.set_state(GroupName, active ? Active : Inactive); } - public static class TemplatesDropDown { - public const string GroupName = nameof(TemplatesDropDown); - public static readonly string - Active = $"{GroupName}{VisualStates.Active}", - Inactive = $"{GroupName}{VisualStates.Inactive}"; - - public static void apply(VisualStateModel vsm, bool active) => - vsm.set_state(GroupName, active ? Active : Inactive); - } - public static class RenameTemplate { - public const string GroupName = nameof(RenameTemplate); - public static readonly string - Active = $"{GroupName}{VisualStates.Active}", - Inactive = $"{GroupName}{VisualStates.Inactive}"; - - public static void apply(VisualStateModel vsm, bool active) => - vsm.set_state(GroupName, active ? Active : Inactive); - } - public static class ToggleFavorite { - public const string GroupName = nameof(ToggleFavorite); - public static readonly string - Active = $"{GroupName}{VisualStates.Active}", - Inactive = $"{GroupName}{VisualStates.Inactive}"; - - public static void apply(VisualStateModel vsm, bool active) => - vsm.set_state(GroupName, active ? Active : Inactive); - } } } } \ No newline at end of file diff --git a/src/client/spark/view/Controls/Order/AlgoTemplateTreeView.xaml b/src/client/spark/view/Controls/Order/AlgoTemplateTreeView.xaml deleted file mode 100644 index aae546707..000000000 --- a/src/client/spark/view/Controls/Order/AlgoTemplateTreeView.xaml +++ /dev/null @@ -1,270 +0,0 @@ - - - White - - - - #FFCCCCCC - #FF888888 - #FF444444 - #FF888888 - #FF444444 - #FFAAAAAA - #FF888888 - Black - - - - - - - - - - - - #FFFFFFFF - #FF818181 - #FFCCEEFB - #FF27C7F7 - #FF595959 - #FF262626 - #FF82DFFB - #FF1CC4F7 - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/client/spark/view/Controls/Order/AlgoTemplateTreeView.xaml.cs b/src/client/spark/view/Controls/Order/AlgoTemplateTreeView.xaml.cs deleted file mode 100644 index 815a421b5..000000000 --- a/src/client/spark/view/Controls/Order/AlgoTemplateTreeView.xaml.cs +++ /dev/null @@ -1,33 +0,0 @@ -using mbts.ui.converters; -using System.Windows; -using System.Windows.Data; - -namespace mbts.ui.spark.algo { - static class AlgoTemplateTreeView { - public static readonly IMultiValueConverter ItemsMarginConverter = - ValueConverter.create((margin, level) => new Thickness(level * margin.Left, margin.Top, margin.Right, margin.Bottom)); - - public static readonly IValueConverter NodeLevelConverter = - ValueConverter.create(pnode => pnode + 1); - - public static readonly DependencyProperty ItemsMarginProperty = - DependencyProperty.RegisterAttached( - "ItemsMargin", - typeof(Thickness), - typeof(AlgoTemplateTreeView), - new PropertyMetadata(new Thickness(1))); - - public static Thickness GetItemsMargin(DependencyObject d) => (Thickness)d.GetValue(ItemsMarginProperty); - public static void SetItemsMargin(DependencyObject d, Thickness value) => d.SetValue(ItemsMarginProperty, value); - - public static readonly DependencyProperty NodeLevelProperty = - DependencyProperty.RegisterAttached( - "NodeLevel", - typeof(int), - typeof(AlgoTemplateTreeView), - new PropertyMetadata(0)); - - public static int GetNodeLevel(DependencyObject d) => (int)d.GetValue(NodeLevelProperty); - public static void SetNodeLevel(DependencyObject d, int value) => d.SetValue(NodeLevelProperty, value); - } -} \ No newline at end of file diff --git a/src/client/spark/view/Controls/Order/OrderDetailsPopupControl.xaml b/src/client/spark/view/Controls/Order/OrderDetailsPopupControl.xaml index 28976f379..fea5ff2e8 100644 --- a/src/client/spark/view/Controls/Order/OrderDetailsPopupControl.xaml +++ b/src/client/spark/view/Controls/Order/OrderDetailsPopupControl.xaml @@ -22,12 +22,6 @@ 12 -