diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookColumns.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookColumns.cs index 0a1448d66..81dd3d1cc 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookColumns.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookColumns.cs @@ -26,16 +26,6 @@ using OrderType = bts.api.orderman.CustomOrderDefinition.CustomOneofCase; namespace mbts.spark { // This interface is used to hide ColumnBase.SortDirection, and offer a SortDirection member that does NOT require a DependencyProperty lookup. - // In OrderBookRowVM, each "cell(property)" has a corresponding TreeComparable property that the column uses for sorting - // - each columns' sort_member_path points to the TreeComparable. - // The TreeComparable class needs to know which direction it is sorting so it can force child-orders to always be beneath their parents. - // - when comparing with their parent, it must return 1 if Ascending, -1 if Descending. - // Since the TreeComparables in each row must access their respective column SortDirections in their CompareTo methods, those DP lookups could add significant overhead in large collections. - // I considered adding ListSortDirection members directly to OrderBookVM, and letting the TreeComparables refer to that property, - // but decided it would be better to let the Columns own it so we wouldn't have to worry about keeping the 2 props in sync. - // TODO: Maybe binding to the SortDirection would be less smelly? - // - initially, I tried to bind to the SortDirection of each column, unfortunately, the binding target was not updated before the ICollectionView sorting took place. - // I decided it was not worth changing the DIYGrid.Sorting function to force the SortDirection binding targets to update immediately, before the ICollectionView sorting. interface ICVOrderBookColumn : IKeyedColumn, IGridColumn { string sort_member_path { get; } ListSortDirection? SortDirection { get; set; } @@ -43,8 +33,28 @@ namespace mbts.spark { IComparer comparer { get; } } + class OrderBookSortingData : IEquatable { + public readonly IReadOnlyList sorting_criterion; + public readonly IComparer comparer; + public readonly string desc; + + public OrderBookSortingData(IEnumerable column_sorting_hierarchy) { + var comp_builder = new ComparerBuilder(); + foreach (var col in column_sorting_hierarchy) + comp_builder.add(col.SortDirection.Value == ListSortDirection.Ascending ? col.comparer : col.comparer.reverse()); + comparer = comp_builder.to_comparer(); + sorting_criterion = column_sorting_hierarchy.Select(col => new SortingCriteria(col.id, col.SortDirection.GetValueOrDefault() == ListSortDirection.Ascending)).ToArray(); + desc = string.Join(", ", sorting_criterion); + } + + public bool Equals(OrderBookSortingData other) => other != null && EqualityComparer.safe_sequence_equals(sorting_criterion, other.sorting_criterion); + public override bool Equals(object obj) => base.Equals(obj); + public override int GetHashCode() => EqualityComparer.aggregate_hash(sorting_criterion); + public override string ToString() => desc; + } + partial class OrderBookVM { - public class OrderBookColumnCollection : ObservableCollection, IValueFactory, IDisposable { + public class OrderBookColumnCollection : ObservableCollection, IValueFactory<(FilterStates filters, IReadOnlyList sorting)>, IDisposable { readonly List _active_comparers = new List(); public OrderBookColumnCollection(IBus bus, OrdersModel model, IObservable<(IEnumerable added, IEnumerable removed)> order_securities) { @@ -298,7 +308,7 @@ namespace mbts.spark { public SimpleTextColumn order_key_column { get; } public SimpleTextColumn parent_key_column { get; } - public FilterStates create() => + public (FilterStates filters, IReadOnlyList sorting) create() => ( new FilterStates { order_key_regex = order_key_column.filter.get_state(), time_created = time_created_column.filter.get_state(), @@ -319,10 +329,11 @@ namespace mbts.spark { last_change = last_change_column.filter.get_state(), security_criteria = security_column.filter.get_state(), symbols = symbol_column.filter.get_state() - }; + }, + get_sorting_data().sorting_criterion); - public void load_from(FilterStates fs) { - if (fs != null) { + public void load_from((FilterStates filters, IReadOnlyList sorting) state) { + if (state.filters is FilterStates fs) { security_column.filter.load_state(fs.security_criteria); symbol_column.filter.load_state(fs.symbols); time_created_column.filter.load_state(fs.time_created); @@ -343,6 +354,23 @@ namespace mbts.spark { last_message_column.filter.load_state(fs.exchange_message_regex); last_change_column.filter.load_state(fs.last_change); } + _active_comparers.Clear(); + foreach (var col in this) + col.SortDirection = null; + if (state.sorting is IReadOnlyList sorting) { + foreach (var sc in sorting) { + this.OfType().ApplyToFirst(col => col.id.ic_equals(sc.col_name), + col => { + col.SortDirection = sc.is_ascending ? ListSortDirection.Ascending : ListSortDirection.Descending; + _active_comparers.Add(col); + }); + } + } + if (_active_comparers.Count == 0) { + // safeguard against empty sort, fallback to time-created + time_created_column.SortDirection = ListSortDirection.Descending; + _active_comparers.Add(time_created_column); + } } public Func get_filter() { @@ -350,7 +378,7 @@ namespace mbts.spark { return active_filters.Length == 0 ? null : new Func(r => active_filters.All(f => f.filter(r))); } - public (IComparer comp, string desc) get_comparer_data() { + public OrderBookSortingData get_sorting_data() { var desc_parts = new List(); var comp_builder = new ComparerBuilder(); // this should be unneccesary, safe_active_comparers is just an extra guard against unexpected results from future code changes @@ -362,11 +390,7 @@ namespace mbts.spark { _active_comparers.Add(time_created_column); safe_active_comparers = _active_comparers; } - foreach (var col in safe_active_comparers) { - desc_parts.Add($"{col.id}:{col.SortDirection.Value}"); - comp_builder.add(col.SortDirection.Value == ListSortDirection.Ascending ? col.comparer : col.comparer.reverse()); - } - return (comp_builder.to_comparer(), string.Join(", ", desc_parts)); + return new OrderBookSortingData(safe_active_comparers); } public void on_sorting(ICVOrderBookColumn col, bool clear_current_sort) { diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookRowCollection.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookRowCollection.cs index 33a90e7fd..dd462d4f4 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookRowCollection.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookRowCollection.cs @@ -28,14 +28,14 @@ namespace mbts.spark { set { _filter = value; _refresh_branches(_tree.RootNodes); - _reset(); + reset(); } } public IComparer comparer { get => _comparer; set { _tree = _tree.Resort(_comparer = value); - _reset(); + reset(); } } public IEnumerable all_rows => _tree; @@ -98,6 +98,9 @@ namespace mbts.spark { } } + /// + /// Refreshes the collection by calling with all visible rows. + /// public void refresh() { if (_is_refresh_deferred) { _is_refresh_pending = true; @@ -107,6 +110,19 @@ namespace mbts.spark { } } + /// + /// Resets the collection by calling , then adding all visible rows. + /// + public void reset(bool force = false) { + if (_is_refresh_deferred && !force) { + _is_refresh_pending = true; + } else { + Clear(); + this.AddRange(_visible_rows); + _is_refresh_pending = false; + } + } + public IDisposable defer_refresh(bool force_refresh_after = false) { // use a counter instead of a simple bool flag to gracefully handle recursive calls to defer_refresh(), // by only calling refresh() after all IDisposables returned by defer_refresh() have been disposed. @@ -154,16 +170,6 @@ namespace mbts.spark { static SortedTree _mk_tree(IComparer comp, IEnumerable init = null) => new SortedTree(comp, r => r.order_key, r => r.parent_order_key, init); - void _reset() { - if (_is_refresh_deferred) { - _is_refresh_pending = true; - } else { - Clear(); - this.AddRange(_visible_rows); - _is_refresh_pending = false; - } - } - void _refresh_branches(IEnumerable> roots) { if (filter == null) { foreach (var n in roots) diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs index 1eae3cc13..59de836a0 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs @@ -3,6 +3,7 @@ using bts.api; using bts.api.orderman; using bts.shell; using bts.spark; +using bts.utils; using mbts.ui; using mbts.ui.controls; using mbts.ui.settings; @@ -34,22 +35,20 @@ namespace mbts.spark { _bus = bus; _model = model; _columns = new OrderBookColumnCollection(bus, model, model.on_order_securities.Select(u => (u.added.Values.Select(smd => smd.security), u.removed.Values.Select(smd => smd.security)))); - _row_collection = new OrderBookRowCollection(ort => new OrderBookRowVM(this, ort), _columns.get_comparer_data().comp) { filter = _columns.get_filter() }; + _row_collection = new OrderBookRowCollection(ort => new OrderBookRowVM(this, ort), _columns.get_sorting_data().comparer) { filter = _columns.get_filter() }; _current_row = backing(nameof(current_row)); - _columns.filter_changed += on_filter_changed; + _columns.filter_changed += _on_filter_changed; collapse_all_rows_command = new DelegateCommand(_row_collection.collapse_all); expand_all_rows_command = new DelegateCommand(_row_collection.expand_all); _resources = new List { model.on_order_tuples_table.OnDispatcher().Subscribe(_row_collection.update), (grid_settings_manager = _create_grid_settings_manager(owner_title, bus, notification_service, model, columns)), Disposable.Create(() => { - _columns.filter_changed -= on_filter_changed; + _columns.filter_changed -= _on_filter_changed; Disposable.dispose(_row_collection); }), _columns }; - void on_filter_changed() => - _row_collection.filter = _columns.get_filter(); } public event Action selected_order_changed; @@ -71,23 +70,41 @@ namespace mbts.spark { public OrderBookStartupData create() { var (grid, animations) = grid_settings_manager.create(); - return new OrderBookStartupData(_columns.create(), grid, animations.Select(a => new OrderRecordTuplePredicateAnimations(a.predicate_builder, a.cell_animations, a.row_animations, a.sound_notifications))); + var (filters, sorting) = _columns.create(); + grid = grid.with(sorting_criterion: sorting); + return new OrderBookStartupData(filters, grid, animations.Select(a => new OrderRecordTuplePredicateAnimations(a.predicate_builder, a.cell_animations, a.row_animations, a.sound_notifications))); } public void load_from(OrderBookStartupData state) { if (state == null) return; + (var old_filter, var old_sort) = _columns.create(); _state = state; - grid_settings_manager.load_from((state.grid, state.predicate_animations)); - _columns.load_from(state.filters); + // unhook filter_changed; in the event that both filters AND sorting changes, we'll avoid resetting the rows twice (i.e. once for new filters, and again for new sorting). + _columns.filter_changed -= _on_filter_changed; + using (_row_collection.defer_refresh()) { + grid_settings_manager.load_from((state.grid, state.predicate_animations)); + _columns.load_from((state.filters, state.grid.sorting_criterion)); + (var new_filter, var new_sort) = _columns.create(); + if (!new_filter.Equals(old_filter) || !EqualityComparer.safe_sequence_equals(new_sort, old_sort)) { + // since we are in a 'defer_refresh()' scope, setting these properties will not cause a reset. + _row_collection.filter = _columns.get_filter(); + _row_collection.comparer = _columns.get_sorting_data().comparer; + // call reset() here so _row_collection does not internally call sync_with() when we exit the defer_refresh() scope. + // (in this case, sync_with potentially involves a lot of individual Remove() calls, which can be very expensive as the view responds to each CollectionChanged event) + _row_collection.reset(true); + } + } + // hook filter_changed back up + _columns.filter_changed += _on_filter_changed; } public void on_sorting(object sender, DIYGridSortingEventArgs e) { if (e.Column is ICVOrderBookColumn col) { e.Handled = true; _columns.on_sorting(col, !KeyboardExtensions.IsShiftDown()); - (var comp, var desc) = _columns.get_comparer_data(); - Log.Ui.info($"{nameof(OrderBookRowVM)} begin resort: {desc}"); - _row_collection.comparer = comp; + var sorting_data = _columns.get_sorting_data(); + Log.Ui.info($"{nameof(OrderBookRowVM)} begin resort: {sorting_data}"); + _row_collection.comparer = sorting_data.comparer; } else { Log.Ui.warn($"{nameof(OrderBookVM)} failed to process sorting event: Column was not of type {nameof(ICVOrderBookColumn)}"); } @@ -119,6 +136,9 @@ namespace mbts.spark { dr.is_visible = false; } + void _on_filter_changed() => + _row_collection.filter = _columns.get_filter(); + public OrderMetadata get_metadata(OrderBookRowVM row) => _model.factory.get_metadata(row.order_type); public void Dispose() { diff --git a/src/client/spark/view/Utility/SortingCriteria.cs b/src/client/spark/view/Utility/SortingCriteria.cs index 4b09ac9dc..6845f9470 100644 --- a/src/client/spark/view/Utility/SortingCriteria.cs +++ b/src/client/spark/view/Utility/SortingCriteria.cs @@ -21,5 +21,7 @@ namespace mbts.ui public bool is_ascending; public SortDescription to_sort_description() { return new SortDescription(col_name, is_ascending ? ListSortDirection.Ascending : ListSortDirection.Descending); } + + public override string ToString() => $"{col_name}:{(is_ascending ? "Ascending" : "Descending")}"; } } \ No newline at end of file diff --git a/src/client/spark_core/utils/GlobalExtensions.cs b/src/client/spark_core/utils/GlobalExtensions.cs index 8a094fdb6..ed021abed 100644 --- a/src/client/spark_core/utils/GlobalExtensions.cs +++ b/src/client/spark_core/utils/GlobalExtensions.cs @@ -18,6 +18,9 @@ namespace mbts { } return sb.ToString(); } + public static bool ic_equals(this string str, string comparand) => + string.Equals(str, comparand, StringComparison.CurrentCultureIgnoreCase); + public static T choose(this Random r, IEnumerable range) { var index = r.Next(0, range.Count()); return range.Skip(index).First();