From d1210b06cc894e77318e95e2c3e7130530dff8a9 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Sun, 15 Sep 2019 16:36:16 -0500 Subject: [PATCH] fix pnl group-row sort --- .../Modules/Trading/PNL/PNLWindowFactory.cs | 22 ++-- .../Trading/PNL/VM/PNLCellIndexBuilder.cs | 2 +- .../spark/Modules/Trading/PNL/VM/PNLCellVM.cs | 61 +++++++++-- .../Modules/Trading/PNL/VM/PNLRowComparer.cs | 101 ++++++++++++++++++ .../spark/Modules/Trading/PNL/VM/PNLVM.cs | 96 +++++++++++++++-- .../Modules/Trading/PNL/View/PNLView.xaml | 10 +- .../spark/view/Controls/DIYGrid/DIYGrid.cs | 64 +++++++++++ 7 files changed, 328 insertions(+), 28 deletions(-) create mode 100644 src/client/spark/Modules/Trading/PNL/VM/PNLRowComparer.cs diff --git a/src/client/spark/Modules/Trading/PNL/PNLWindowFactory.cs b/src/client/spark/Modules/Trading/PNL/PNLWindowFactory.cs index 5b02309f9..cfae1cce7 100644 --- a/src/client/spark/Modules/Trading/PNL/PNLWindowFactory.cs +++ b/src/client/spark/Modules/Trading/PNL/PNLWindowFactory.cs @@ -17,6 +17,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.Specialized; +using System.ComponentModel; using System.ComponentModel.Composition; using System.Linq; using System.Reactive.Linq; @@ -55,25 +56,32 @@ namespace bts.shell { // Use an ImmutableList to avoid any threading issues when responding to CollectionChanged events on the dispatcher thread. ImmutableList cached_columns = ImmutableList.Empty; return SparkWindow.create(_window_type, _window_title, _bus, this, Icons.Accounting, _thread_id_provider.next_id(), () => { - IEnumerable last_sorting_criterion = null; var vm = new PNLVM(_bus, _orders_model, settings ?? PNLSettings.Default); var content = new PNLView { DataContext = vm }; + vm.sorting_changed += sh => { + try { + DIYGridSortHelper.set_sort_directions(sh, content._grid.Columns); + } catch { } + }; + vm.SubscribeDisposed( + DIYGridSortHelper.observe_active_comparers(content._grid, PNLVM.get_column_comparer) + .OnDispatcher() + .Subscribe(sh => vm.sorting_hierarchy = sh.Select(s => (s.key, s.direction)).ToList())); cached_columns = ImmutableList.Empty.AddRange(content._grid.Columns); Func get_save_state = () => { - if (last_sorting_criterion == null) - last_sorting_criterion = PNLSettings.Default.sorting_criterion; var cols = cached_columns.ToArray(c => c.create()); var filters = vm.get_filters_states(); + var sorting_criterion = vm.sorting_hierarchy.Select(tup => new SortingCriteria(tup.key.ToString(), tup.direction == ListSortDirection.Ascending)).ToArray(); var calc_type = vm.calculation_type; var state = settings_manager.instance_settings; if (state == null) { // don't use defaults if the user manipulated the window state outside of the settings dialog (e.g., resized column(s) via drag, or changed sort/filter) var defaults = settings_manager.default_settings; if (calc_type == defaults.calculation_type && - defaults.sorting_criterion.SequenceEqual(last_sorting_criterion) && + defaults.sorting_criterion.SequenceEqual(sorting_criterion) && defaults.grid.columns.SequenceEqual(cols) && defaults.filters.safe_equals(filters)) { // the user's current state still matches the defaults (i.e., no outside manipulation was performed); return null so this window will use the latest default settings when restored return new PNLSaveState { use_defaults = true, settings = null }; @@ -82,7 +90,7 @@ namespace bts.shell { } // assign latest values, as they may have be modified outside of the settings dialog (in which case the settings manager would be out of date) state = state.with( - last_sorting_criterion, + sorting_criterion, vm.anchors, filters, state.grid.with(columns: cols), @@ -146,14 +154,10 @@ namespace bts.shell { header_appearance.font_family); } } - vm.rows_view.set_sort_descriptions(s.sorting_criterion, content._grid.Columns); CollectionHelper.sync_with_never_duplicate(content._grid.Columns, s.grid.columns, cs => { throw new InvalidOperationException(); }, c => c.id.ToLower(), cs => cs.id.ToLower()); }), - vm.rows_view - .subscribe_sorting_criterion(sm => content._grid.Columns.TryGetFirst(dc => dc.sort_member_path == sm, out var match) ? match.id : null) - .Subscribe(sc => last_sorting_criterion = sc), content._grid.Columns.Subscribe((s, e) => { switch (e.Action) { case NotifyCollectionChangedAction.Add: add_new(); break; diff --git a/src/client/spark/Modules/Trading/PNL/VM/PNLCellIndexBuilder.cs b/src/client/spark/Modules/Trading/PNL/VM/PNLCellIndexBuilder.cs index c8f384396..530e7d641 100644 --- a/src/client/spark/Modules/Trading/PNL/VM/PNLCellIndexBuilder.cs +++ b/src/client/spark/Modules/Trading/PNL/VM/PNLCellIndexBuilder.cs @@ -89,7 +89,7 @@ namespace bts.shell.pnl { } public PNLCellVM add(PNLView.Columns key, Func get, Func fmt, IEqualityComparer eq_comparer, IComparer comparer) { - var cell = new PNLCellVM(get, fmt, eq_comparer, comparer); + var cell = new PNLCellVM(key, get, fmt, eq_comparer, comparer); _cell_index[key] = cell; return cell; } diff --git a/src/client/spark/Modules/Trading/PNL/VM/PNLCellVM.cs b/src/client/spark/Modules/Trading/PNL/VM/PNLCellVM.cs index 35610a4b3..93ffbf6bf 100644 --- a/src/client/spark/Modules/Trading/PNL/VM/PNLCellVM.cs +++ b/src/client/spark/Modules/Trading/PNL/VM/PNLCellVM.cs @@ -1,6 +1,8 @@ -using mbts.ui; +using bts.utils; +using mbts.ui; using mbts.ui.shell; using System; +using System.Collections; using System.Collections.Generic; using System.Windows; using System.Windows.Media; @@ -8,6 +10,7 @@ using System.Windows.Media; namespace bts.shell.pnl { interface IPNLCellVM { object value { get; } + IPNLCellData cell_data { get; } FontWeight font_weight { get; set; } Color foreground { get; set; } Color background { get; set; } @@ -18,38 +21,79 @@ namespace bts.shell.pnl { void on_row(TRow row); } + /// is needed for the non-generic rows/group IComparer impl. + /// The groups are bound to IPNLCellData, so the column property can be used to retrieve the appropriate comparer for that cell. + interface IPNLCellData { + PNLView.Columns column { get; } + object value { get; } + } + + readonly struct PNLCellValue : IPNLCellData { + public readonly T value; + readonly string _text; + + public PNLCellValue(PNLView.Columns column, T value, string text) { + this.value = value; + this.column = column; + _text = text; + } + + public PNLView.Columns column { get; } + object IPNLCellData.value => value; + + public bool Equals(PNLCellValue other) => + column == other.column && + Equals(value, other.value); + + public override bool Equals(object obj) => + obj is PNLCellValue other && Equals(other); + + public override int GetHashCode() => + EqualityComparer.auto_phase((int)column, value?.GetHashCode() ?? 0); + + public override string ToString() => _text; + } + class PNLCellVM : ViewModelBase, IObserver, IPNLCellVM, IComparable>, IComparable { readonly Func _fmt; readonly Func _get; readonly IEqualityComparer _eq_comparer; readonly IComparer _comparer; + readonly PNLView.Columns _column; + IComparer _value_comparer; Color _foreground = Colors.Black, _background = Colors.Transparent, _border = Colors.Transparent; string _text; TValue _value; + IPNLCellData _cell_value; - public PNLCellVM(Func get) - : this(get, null, EqualityComparer.Default, Comparer.Default) { } + public PNLCellVM(PNLView.Columns column, Func get) + : this(column, get, null, EqualityComparer.Default, Comparer.Default) { } - public PNLCellVM(Func get, Func fmt) - : this(get, fmt, EqualityComparer.Default, Comparer.Default) { } + public PNLCellVM(PNLView.Columns column, Func get, Func fmt) + : this(column, get, fmt, EqualityComparer.Default, Comparer.Default) { } - public PNLCellVM(Func get, Func fmt, IEqualityComparer eq_comparer, IComparer comparer) { + public PNLCellVM(PNLView.Columns column, Func get, Func fmt, IEqualityComparer eq_comparer, IComparer comparer) { + _column = column; _get = get; _fmt = fmt; _eq_comparer = eq_comparer; _comparer = comparer; } + public IComparer value_comparer => _value_comparer ?? (_value_comparer = _comparer.to_non_generic()); + object IPNLCellVM.value => value; + public IPNLCellData cell_data => _cell_value ?? (_cell_value = new PNLCellValue(_column, _value, text)); public TValue value { get => _value; set { if (Set(ref _value, value)) { _text = null; - RaisePropertyChanged(nameof(text)); + _cell_value = null; + RaisePropertyChanged(nameof(cell_data), nameof(text)); } } } @@ -93,6 +137,9 @@ namespace bts.shell.pnl { public void OnError(Exception error) { } public void OnCompleted() { } + bool Equals(PNLCellVM other) => + Equals(value, other.value); + public override string ToString() => text; diff --git a/src/client/spark/Modules/Trading/PNL/VM/PNLRowComparer.cs b/src/client/spark/Modules/Trading/PNL/VM/PNLRowComparer.cs new file mode 100644 index 000000000..0932b01db --- /dev/null +++ b/src/client/spark/Modules/Trading/PNL/VM/PNLRowComparer.cs @@ -0,0 +1,101 @@ +using bts.utils; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Windows.Data; +using ColumnKeys = bts.shell.pnl.PNLView.Columns; + +namespace bts.shell.pnl { + interface IPNLColumnComparer { + IComparer value_comparer { get; } + IComparer row_comparer { get; } + } + + class PNLColumnComparer : IPNLColumnComparer, IComparer, IComparer { + public readonly IComparer inner_comparer; + IComparer _value_comparer; + readonly Func _get; + + public PNLColumnComparer(Func get) + : this(get, Comparer.Default) { } + + public PNLColumnComparer(Func get, IComparer inner_comparer) { + _get = get; + this.inner_comparer = inner_comparer; + } + + public IComparer value_comparer => _value_comparer ?? (_value_comparer = inner_comparer.to_non_generic()); + public IComparer row_comparer => this; + + public int Compare(object x, object y) => + Compare(x as PNLRowVM, y as PNLRowVM); + + public int Compare(PNLRowVM x, PNLRowVM y) { + if (x == null) return y == null ? 0 : -1; + if (y == null) return 1; + var xval = _get(x); + var yval = _get(y); + return inner_comparer.Compare(xval, yval); + } + } + + class ReversePNLColumnComparer : IPNLColumnComparer, IComparer, IComparer { + readonly IPNLColumnComparer _comp_tuple; + + public ReversePNLColumnComparer(IPNLColumnComparer comp_tuple) => + _comp_tuple = comp_tuple; + + public IComparer value_comparer => this; + public IComparer row_comparer => this; + + int IComparer.Compare(object x, object y) => + _comp_tuple.value_comparer.Compare(y, x); + + int IComparer.Compare(PNLRowVM x, PNLRowVM y) => + _comp_tuple.row_comparer.Compare(y, x); + } + + /// + /// An that can compare 2 objects of type , and 2 objects of type + /// (assuming the latter's is of type ). Cross type comparisons are not supported. + /// + class PNLSuperRowComparer : IComparer, IComparer, IComparer { + readonly Func _get_column_comparer; + IComparer _row_comp; + + public PNLSuperRowComparer(IComparer row_comp, Func get_column_comparer) { + _row_comp = row_comp; + _get_column_comparer = get_column_comparer; + } + + public int Compare(object x, object y) { + var rc = _try_compare_rows(x as PNLRowVM, y as PNLRowVM); + if (rc.HasValue) + return rc.Value; + var gc = _try_compare_groups(x as CollectionViewGroup, y as CollectionViewGroup); + if (gc.HasValue) + return gc.Value; + throw new InvalidOperationException($"{nameof(PNLSuperRowComparer)} unexpected comparison '{x}' with '{y}.'"); + } + + int IComparer.Compare(PNLRowVM x, PNLRowVM y) => + _try_compare_rows(x, y) ?? throw new InvalidOperationException($"Failed to compare '{x}' with '{y}' (expected both to be of type {typeof(PNLRowVM)})."); + + int IComparer.Compare(CollectionViewGroup x, CollectionViewGroup y) => + _try_compare_groups(x, y) ?? throw new InvalidOperationException($"Failed to compare '{x}' with '{y}' (expected both to be of type {typeof(CollectionViewGroup)}, with Names of type {typeof(IPNLCellVM)})."); + + int? _try_compare_rows(PNLRowVM x, PNLRowVM y) { + if (x == null || y == null) return null; + return _row_comp.Compare(x, y); + } + + int? _try_compare_groups(CollectionViewGroup x, CollectionViewGroup y) { + if (x == null || y == null) + return null; + var xcell = (IPNLCellData)x.Name; + var ycell = (IPNLCellData)y.Name; + var comp = _get_column_comparer(xcell.column); + return comp.value_comparer.Compare(xcell.value, ycell.value); + } + } +} \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/PNL/VM/PNLVM.cs b/src/client/spark/Modules/Trading/PNL/VM/PNLVM.cs index bbcdf088e..169f219fc 100644 --- a/src/client/spark/Modules/Trading/PNL/VM/PNLVM.cs +++ b/src/client/spark/Modules/Trading/PNL/VM/PNLVM.cs @@ -44,6 +44,7 @@ namespace bts.shell.pnl { readonly Property _calculation_type; PNLHeaderRowDisplay _header_row_display = PNLHeaderRowDisplay.Total; PNLRowCollectionView _rows_view; + IReadOnlyList<(ColumnKeys key, ListSortDirection direction)> _sorting_hierarchy; Brush _selection_highlight; bool _is_paused; // default appearances @@ -69,6 +70,7 @@ namespace bts.shell.pnl { _orders_model = orders_model; _rows_data_wrapper = rows.WrapSelector(r => r.data, d => new PNLRowVM(d, _default_appearances, _triggers)); _rows_key_wrapper = rows.WrapSelector(r => r.key, null); + _rows_view = new PNLRowCollectionView(rows, _default_group_appearances, _group_triggers); _calculation_type = backing(nameof(calculation_type), PNLCalculationType.Waterfall); anchors.AddRange(settings.anchors); _group_background_converter.Values.AddRange(BTSColors.PNL.group_alternating_background_colors); @@ -93,7 +95,6 @@ namespace bts.shell.pnl { selected_aggregate = new PNLHeaderRowVM(settings.header_background_color, _default_header_appearances, _header_triggers); // load/subscribe to data load_from(settings); - _rows_view = new PNLRowCollectionView(rows, _default_group_appearances, _group_triggers); _dispose = Disposable.Create( pnl_source.Operate( _calculation_type.observe_current(), @@ -109,6 +110,7 @@ namespace bts.shell.pnl { })); } + public event Action> sorting_changed; event Action _selection_changed; event Action> _updated; event Action> _filter_changed; @@ -119,6 +121,27 @@ namespace bts.shell.pnl { public int filtered_row_count => rows.Count; public int total_row_count { get; private set; } public IReadOnlyObservableCollection selected_rows => _selected_rows; + // sorting + public IReadOnlyList<(ColumnKeys key, ListSortDirection direction)> sorting_hierarchy { + get => _sorting_hierarchy ?? (_sorting_hierarchy = Array.Empty<(ColumnKeys, ListSortDirection)>()); + set { + _sorting_hierarchy = value; + // use 'sorting_hierarchy' instead of 'value' bc the getter ensures not null + comparer = DIYGridSortHelper.build_comparer(sorting_hierarchy, get_column_comparer, ColumnKeys.Account, ColumnKeys.Security); + var column_comp_map = sorting_hierarchy.ToDictionary(c => c.key, c => _get_column_comparer(c.key, c.direction)); + var rows_view_comparer = new PNLSuperRowComparer(comparer, col => { + if (column_comp_map.TryGetValue(col, out var comp_tup)) + return comp_tup; + return _get_column_comparer(col); + }); + _rows_view.CustomSort = rows_view_comparer; + foreach (var g in _rows_view.GroupDescriptions) + g.CustomSort = _rows_view.CustomSort; + sorting_changed?.Invoke(sorting_hierarchy); + } + } + + public IComparer comparer { get; private set; } // display/grouping public PNLHeaderRowDisplay header_row_display { get => _header_row_display; set => Set(ref _header_row_display, value); } public ObservableCollection anchors { get; } = new ObservableCollection(); @@ -157,7 +180,6 @@ namespace bts.shell.pnl { public void set_all_expanded(bool is_expanded) => _rows_view.set_all_expanded(is_expanded); - #region Filters /// security public IDataGridColumnPersistentFilter account_filter { get; } public IDataGridColumnPersistentFilter exchange_filter { get; } = DiscreteValuesFilterVM.Common.exchange(r => r.security.exchange_or_default(), nameof(PNLRowVM.exchange)); @@ -211,6 +233,9 @@ namespace bts.shell.pnl { IEnumerable> _all_filters => _filter_getters.Select(get => get(this)); + public static IComparer get_column_comparer(ColumnKeys column) => + _get_column_comparer(column).row_comparer; + public FilterStates get_filters_states() => new FilterStates { account = account_filter.get_state(), exchange = exchange_filter.get_state(), @@ -257,7 +282,6 @@ namespace bts.shell.pnl { settlement_price = settlement_price_filter.get_state(), pnl_price = pnl_price_filter.get_state(), }; - #endregion public void load_from(PNLSettings settings) { selection_highlight = settings.grid.selection_highlight.to_brush(); @@ -315,6 +339,7 @@ namespace bts.shell.pnl { } anchors.sync_with(settings.anchors); header_row_display = settings.header_row_display; + sorting_hierarchy = DIYGridSortHelper.convert_sorting_criterion(settings.sorting_criterion).ToList(); // group background colors _group_background_converter = new AlternationConverter(); _group_background_converter.Values.AddRange(settings.group_background_colors.Select(c => c.argb_color())); @@ -338,9 +363,8 @@ namespace bts.shell.pnl { } from = dabd.ToImmutable(); } - if (_rows_view == null) - _rows_view = new PNLRowCollectionView(rows, _default_group_appearances, _group_triggers); - else _rows_view.on_settings(_default_group_appearances, _group_triggers); + _rows_view.on_settings(_default_group_appearances, _group_triggers); + _rows_view.Refresh(); } #region FillsVM Factory @@ -465,6 +489,66 @@ namespace bts.shell.pnl { } #endregion + static IPNLColumnComparer _get_column_comparer(ColumnKeys column, ListSortDirection direction) { + var comp = _get_column_comparer(column); + if (direction == ListSortDirection.Descending) + comp = new ReversePNLColumnComparer(comp); + return comp; + } + + static IPNLColumnComparer _get_column_comparer(ColumnKeys column) { + switch (column) { + case ColumnKeys.Account: return wrap(r => r.account_name); + case ColumnKeys.Exchange: return wrap(r => r.exchange); + case ColumnKeys.SecurityType: return wrap(r => r.security?.ContractCase ?? SecurityType.None); + case ColumnKeys.Symbol: return wrap(r => r.symbol); + case ColumnKeys.Security: return wrap(r => r.security); + case ColumnKeys.CPP: return wrap(r => r.cpp); + /// SOD + case ColumnKeys.SODPNL: return wrap(r => r.sod_pnl); + case ColumnKeys.SODLongPos: return wrap(r => r.sod_long_pos); + case ColumnKeys.SODLongAvgPrice: return wrap(r => r.sod_long_avg_price); + case ColumnKeys.SODShortPos: return wrap(r => r.sod_short_pos); + case ColumnKeys.SODShortAvgPrice: return wrap(r => r.sod_short_avg_price); + case ColumnKeys.SODNetPos: return wrap(r => r.sod_net_pos); + /// Day + case ColumnKeys.DayPNL: return wrap(r => r.day_pnl); + case ColumnKeys.DayLongPos: return wrap(r => r.day_long_pos); + case ColumnKeys.DayLongAvgPrice: return wrap(r => r.day_long_avg_price); + case ColumnKeys.DayShortPos: return wrap(r => r.day_short_pos); + case ColumnKeys.DayShortAvgPrice: return wrap(r => r.day_short_avg_price); + case ColumnKeys.DayNetPos: return wrap(r => r.day_net_pos); + case ColumnKeys.HasDayTrades: return wrap(r => r.has_day_trades); + /// RawDay + case ColumnKeys.RawDayLongPos: return wrap(r => r.raw_day_long_pos); + case ColumnKeys.RawDayShortPos: return wrap(r => r.raw_day_short_pos); + case ColumnKeys.RawDayNetPos: return wrap(r => r.raw_day_net_pos); + /// Total + case ColumnKeys.TotalPNL: return wrap(r => r.total_pnl); + case ColumnKeys.TotalLongPos: return wrap(r => r.total_long_pos); + case ColumnKeys.TotalLongAvgPrice: return wrap(r => r.total_long_avg_price); + case ColumnKeys.TotalShortPos: return wrap(r => r.total_short_pos); + case ColumnKeys.TotalShortAvgPrice: return wrap(r => r.total_short_avg_price); + case ColumnKeys.TotalNetPos: return wrap(r => r.total_net_pos); + /// Working + case ColumnKeys.WorkingLongPos: return wrap(r => r.working_long_pos); + case ColumnKeys.WorkingLongAvgPrice: return wrap(r => r.working_long_avg_price); + case ColumnKeys.WorkingShortPos: return wrap(r => r.working_short_pos); + case ColumnKeys.WorkingShortAvgPrice: return wrap(r => r.working_short_avg_price); + case ColumnKeys.WorkingNetPos: return wrap(r => r.working_net_pos); + /// Market + case ColumnKeys.BidPrice: return wrap(r => r.bid_price); + case ColumnKeys.MidPrice: return wrap(r => r.mid_price); + case ColumnKeys.AskPrice: return wrap(r => r.ask_price); + case ColumnKeys.LastPrice: return wrap(r => r.last_price); + case ColumnKeys.SettlementPrice: return wrap(r => r.settlement_price); + case ColumnKeys.PNLPrice: return wrap(r => r.pnl_price); + default: throw ExceptionBuilder.Argument.unexpected_case(column, nameof(column)); + } + PNLColumnComparer wrap(Func selector) => + new PNLColumnComparer(selector); + } + static GridSettings _hide_cols(GridSettings grid, IEnumerable columns) => grid.with(_hide_cols(grid.columns, columns)); diff --git a/src/client/spark/Modules/Trading/PNL/View/PNLView.xaml b/src/client/spark/Modules/Trading/PNL/View/PNLView.xaml index dba89ad23..6644ac6be 100644 --- a/src/client/spark/Modules/Trading/PNL/View/PNLView.xaml +++ b/src/client/spark/Modules/Trading/PNL/View/PNLView.xaml @@ -653,7 +653,7 @@ c:DataGridFilterProperties.FilterTemplate="{StaticResource {x:Static ft:DataGridFilterKnownTemplates.DiscreteValues}}" c:DataGridFilterProperties.FilterActive="{Binding DataContext.account_filter.active, Source={u:DirectReference _grid}}" key="Account" - data_member_path="account_name" + data_member_path="account_name_cell.cell_data" sort_member_path="account_name" HeaderTemplate="{StaticResource AnchorableColumnHeaderTemplate}" /> @@ -663,7 +663,7 @@ c:DataGridFilterProperties.FilterTemplate="{StaticResource {x:Static ft:DataGridFilterKnownTemplates.EnumValues}}" c:DataGridFilterProperties.FilterActive="{Binding DataContext.exchange_filter.active, Source={u:DirectReference _grid}}" key="Exchange" - data_member_path="exchange" + data_member_path="exchange_cell.cell_data" sort_member_path="exchange" HeaderTemplate="{StaticResource AnchorableColumnHeaderTemplate}" /> @@ -673,7 +673,7 @@ c:DataGridFilterProperties.FilterTemplate="{StaticResource {x:Static ft:DataGridFilterKnownTemplates.DiscreteValues}}" c:DataGridFilterProperties.FilterActive="{Binding DataContext.symbol_filter.active, Source={u:DirectReference _grid}}" key="Symbol" - data_member_path="symbol" + data_member_path="symbol_cell.cell_data" sort_member_path="symbol" HeaderTemplate="{StaticResource AnchorableColumnHeaderTemplate}" /> @@ -683,7 +683,7 @@ c:DataGridFilterProperties.FilterTemplate="{StaticResource {x:Static ft:DataGridFilterKnownTemplates.DiscreteValues}}" c:DataGridFilterProperties.FilterActive="{Binding DataContext.security_type_filter.active, Source={u:DirectReference _grid}}" key="SecurityType" - data_member_path="security_type" + data_member_path="security_type_cell.cell_data" sort_member_path="security_type" HeaderTemplate="{StaticResource AnchorableColumnHeaderTemplate}" /> @@ -693,7 +693,7 @@ c:DataGridFilterProperties.FilterTemplate="{StaticResource {x:Static ft:DataGridFilterKnownTemplates.Regex}}" c:DataGridFilterProperties.FilterActive="{Binding DataContext.security_filter.active, Source={u:DirectReference _grid}}" key="Security" - sort_member_path="security" + sort_member_path="security_cell.cell_data" data_member_path="security" HeaderTemplate="{StaticResource AnchorableColumnHeaderTemplate}" /> diff --git a/src/client/spark/view/Controls/DIYGrid/DIYGrid.cs b/src/client/spark/view/Controls/DIYGrid/DIYGrid.cs index ab4297102..1fa622608 100644 --- a/src/client/spark/view/Controls/DIYGrid/DIYGrid.cs +++ b/src/client/spark/view/Controls/DIYGrid/DIYGrid.cs @@ -9,6 +9,7 @@ using mbts.utils; using System; using System.Collections; using System.Collections.Generic; +using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; @@ -50,6 +51,61 @@ namespace mbts.ui.controls { delegate void GroupItemSelectionPivotEventHandler(object sender, GroupItemSelectionPivotEventArgs e); static class DIYGridSortHelper { + public static IComparer build_comparer(IEnumerable<(TColumnKey key, ListSortDirection direction)> sorting_hierarchy, Func> get_column_comparer, params TColumnKey[] primary_key) { + // ensure primary key is included for deterministic sort (combination of account/security) + for (int i = 0; i < primary_key.Length; i++) { + var key = primary_key[i]; + if (!sorting_hierarchy.Any(tup => tup.key.Equals(key))) + sorting_hierarchy = sorting_hierarchy.Append((key, ListSortDirection.Ascending)); + } + return new ComparerBuilder( + sorting_hierarchy + .Select(tup => { + var col_comp = get_column_comparer(tup.key); + return tup.direction == ListSortDirection.Ascending ? col_comp : col_comp.reverse(); + })) + .to_comparer(); + } + + public static IEnumerable<(TKey key, ListSortDirection direction)> convert_sorting_criterion(IEnumerable sorting_criterion) where TKey : struct { + foreach (var sc in sorting_criterion) { + if (Enum.TryParse(sc.col_name, false, out TKey key)) + yield return (key, sc.direction()); + } + } + + public static IObservable comparer, ListSortDirection direction)>> observe_active_comparers( + DIYGrid grid, Func> get_comparer, bool mark_handled = true) => + // + Observable.Create comparer, ListSortDirection direction)>>(o => { + var active_comparers = ImmutableList<(TKey key, IComparer comp, ListSortDirection dir)>.Empty; + grid.Sorting += on_sorting; + return Disposable.Create(() => grid.Sorting -= on_sorting); + void on_sorting(object sender, DIYGridSortingEventArgs e) { + if (mark_handled) + e.Handled = true; + if (e.Column is DIYGrid.IKeyedColumn kc) { + var comp = get_comparer(kc.key); + if (comp == null) + return; + var dir = e.Column.SortDirection; + var next = dir.HasValue && dir.Value == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending; + if (!KeyboardExtensions.IsShiftDown()) { + e.Column.SortDirection = next; + active_comparers = active_comparers.Clear(); + active_comparers = active_comparers.Add((kc.key, comp, next)); + } else { + if (active_comparers.TryGetFirst(tup => tup.key.Equals(kc.key), out var match, out int i)) { + active_comparers = active_comparers.SetItem(i, (kc.key, comp, next)); + } else { + active_comparers = active_comparers.Add((kc.key, comp, next)); + } + } + } + o.OnNext(active_comparers); + } + }); + /// Important: All columns MUST IMPLEMENT . public static IReadOnlyList<(TColKey col, ListSortDirection direction)> get_sorting_data(List<(DIYGrid.ColumnBase col, TColKey key, ListSortDirection direction)> active_comparers, TColKey primary_key) { var rv = new List<(TColKey col, ListSortDirection direction)>(); @@ -76,6 +132,14 @@ namespace mbts.ui.controls { public static IComparer reverse_if_descending(IComparer comp, ListSortDirection direction) => direction == ListSortDirection.Descending ? comp.reverse() : comp; + public static void set_sort_directions(IEnumerable<(TColumnKey key, ListSortDirection direction)> sorting_hierarchy, IEnumerable columns) { + foreach (var col in columns) { + col.SortDirection = col is DIYGrid.IKeyedColumn kc && sorting_hierarchy.TryGetFirst(tup => tup.key.Equals(kc.key), out var match) ? + match.direction : + (ListSortDirection?)null; + } + } + /// Important: All columns MUST IMPLEMENT . static IReadOnlyList<(TColKey col, ListSortDirection direction)> _on_sorting(DIYGridSortingEventArgs e, ref List<(DIYGrid.ColumnBase col, TColKey key, ListSortDirection direction)> active_comparers, TColKey primary_key, bool clear_current) { if (e.Column is DIYGrid.IKeyedColumn col) {