fix pnl group-row sort

This commit is contained in:
John Colvin committed 2019-09-15 19:07:34 -05:00
1 parent caeda6c12a
commit d1210b06cc
7 files changed
+328 -28

No files matched your search

@@ -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<DIYGrid.ColumnBase> cached_columns = ImmutableList<DIYGrid.ColumnBase>.Empty;
return SparkWindow<PNLSaveState>.create(_window_type, _window_title, _bus, this, Icons.Accounting, _thread_id_provider.next_id(), () => {
IEnumerable<SortingCriteria> 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<PNLView.Columns, PNLRowVM>(content._grid, PNLVM.get_column_comparer)
.OnDispatcher()
.Subscribe(sh => vm.sorting_hierarchy = sh.Select(s => (s.key, s.direction)).ToList()));
cached_columns = ImmutableList<DIYGrid.ColumnBase>.Empty.AddRange(content._grid.Columns);
Func<PNLSaveState> 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;
@@ -89,7 +89,7 @@ namespace bts.shell.pnl {
}
public PNLCellVM<TRow, T> add<T>(PNLView.Columns key, Func<TRow, T> get, Func<T, string> fmt, IEqualityComparer<T> eq_comparer, IComparer<T> comparer) {
var cell = new PNLCellVM<TRow, T>(get, fmt, eq_comparer, comparer);
var cell = new PNLCellVM<TRow, T>(key, get, fmt, eq_comparer, comparer);
_cell_index[key] = cell;
return cell;
}
@@ -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);
}
/// <see cref="IPNLCellData"/> 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<T> : 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<T> other) =>
column == other.column &&
Equals(value, other.value);
public override bool Equals(object obj) =>
obj is PNLCellValue<T> other && Equals(other);
public override int GetHashCode() =>
EqualityComparer.auto_phase((int)column, value?.GetHashCode() ?? 0);
public override string ToString() => _text;
}
class PNLCellVM<TRow, TValue> : ViewModelBase, IObserver<PNLAnimation>, IPNLCellVM<TRow>, IComparable<PNLCellVM<TRow, TValue>>, IComparable {
readonly Func<TValue, string> _fmt;
readonly Func<TRow, TValue> _get;
readonly IEqualityComparer<TValue> _eq_comparer;
readonly IComparer<TValue> _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<TRow, TValue> get)
: this(get, null, EqualityComparer<TValue>.Default, Comparer<TValue>.Default) { }
public PNLCellVM(PNLView.Columns column, Func<TRow, TValue> get)
: this(column, get, null, EqualityComparer<TValue>.Default, Comparer<TValue>.Default) { }
public PNLCellVM(Func<TRow, TValue> get, Func<TValue, string> fmt)
: this(get, fmt, EqualityComparer<TValue>.Default, Comparer<TValue>.Default) { }
public PNLCellVM(PNLView.Columns column, Func<TRow, TValue> get, Func<TValue, string> fmt)
: this(column, get, fmt, EqualityComparer<TValue>.Default, Comparer<TValue>.Default) { }
public PNLCellVM(Func<TRow, TValue> get, Func<TValue, string> fmt, IEqualityComparer<TValue> eq_comparer, IComparer<TValue> comparer) {
public PNLCellVM(PNLView.Columns column, Func<TRow, TValue> get, Func<TValue, string> fmt, IEqualityComparer<TValue> eq_comparer, IComparer<TValue> 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<TValue>(_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<TRow, TValue> other) =>
Equals(value, other.value);
public override string ToString() =>
text;
@@ -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<PNLRowVM> row_comparer { get; }
}
class PNLColumnComparer<TInner> : IPNLColumnComparer, IComparer<PNLRowVM>, IComparer {
public readonly IComparer<TInner> inner_comparer;
IComparer _value_comparer;
readonly Func<PNLRowVM, TInner> _get;
public PNLColumnComparer(Func<PNLRowVM, TInner> get)
: this(get, Comparer<TInner>.Default) { }
public PNLColumnComparer(Func<PNLRowVM, TInner> get, IComparer<TInner> inner_comparer) {
_get = get;
this.inner_comparer = inner_comparer;
}
public IComparer value_comparer => _value_comparer ?? (_value_comparer = inner_comparer.to_non_generic());
public IComparer<PNLRowVM> 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<PNLRowVM>, IComparer {
readonly IPNLColumnComparer _comp_tuple;
public ReversePNLColumnComparer(IPNLColumnComparer comp_tuple) =>
_comp_tuple = comp_tuple;
public IComparer value_comparer => this;
public IComparer<PNLRowVM> row_comparer => this;
int IComparer.Compare(object x, object y) =>
_comp_tuple.value_comparer.Compare(y, x);
int IComparer<PNLRowVM>.Compare(PNLRowVM x, PNLRowVM y) =>
_comp_tuple.row_comparer.Compare(y, x);
}
/// <summary>
/// An <see cref="IComparer"/> that can compare 2 objects of type <see cref="PNLRowVM"/>, and 2 objects of type <see cref="CollectionViewGroup"/>
/// (assuming the latter's <see cref="CollectionViewGroup.Name"/> is of type <see cref="IPNLCellData"/>). Cross type comparisons are not supported.
/// </summary>
class PNLSuperRowComparer : IComparer, IComparer<PNLRowVM>, IComparer<CollectionViewGroup> {
readonly Func<ColumnKeys, IPNLColumnComparer> _get_column_comparer;
IComparer<PNLRowVM> _row_comp;
public PNLSuperRowComparer(IComparer<PNLRowVM> row_comp, Func<ColumnKeys, IPNLColumnComparer> 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<PNLRowVM>.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<CollectionViewGroup>.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);
}
}
}
@@ -44,6 +44,7 @@ namespace bts.shell.pnl {
readonly Property<PNLCalculationType> _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<IReadOnlyList<(ColumnKeys key, ListSortDirection direction)>> sorting_changed;
event Action<SelectionChangedEventArgs> _selection_changed;
event Action<TableUpdate<PNLRowData, PNLKey>> _updated;
event Action<Func<PNLRowData, bool>> _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<PNLRowVM> 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<PNLRowVM> comparer { get; private set; }
// display/grouping
public PNLHeaderRowDisplay header_row_display { get => _header_row_display; set => Set(ref _header_row_display, value); }
public ObservableCollection<ColumnKeys> anchors { get; } = new ObservableCollection<ColumnKeys>();
@@ -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<PNLRowData, uint[]> account_filter { get; }
public IDataGridColumnPersistentFilter<PNLRowData, Venue[]> exchange_filter { get; } = DiscreteValuesFilterVM.Common.exchange<PNLRowData>(r => r.security.exchange_or_default(), nameof(PNLRowVM.exchange));
@@ -211,6 +233,9 @@ namespace bts.shell.pnl {
IEnumerable<IDataGridColumnFilter<PNLRowData>> _all_filters =>
_filter_getters.Select(get => get(this));
public static IComparer<PNLRowVM> 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<ColumnKeys>(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<T> wrap<T>(Func<PNLRowVM, T> selector) =>
new PNLColumnComparer<T>(selector);
}
static GridSettings _hide_cols(GridSettings grid, IEnumerable<ColumnKeys> columns) =>
grid.with(_hide_cols(grid.columns, columns));
@@ -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}"
/>
@@ -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<TRow> build_comparer<TColumnKey, TRow>(IEnumerable<(TColumnKey key, ListSortDirection direction)> sorting_hierarchy, Func<TColumnKey, IComparer<TRow>> 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<TRow>(
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<TKey>(IEnumerable<SortingCriteria> 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<ImmutableList<(TKey key, IComparer<TRow> comparer, ListSortDirection direction)>> observe_active_comparers<TKey, TRow>(
DIYGrid grid, Func<TKey, IComparer<TRow>> get_comparer, bool mark_handled = true) =>
//
Observable.Create<ImmutableList<(TKey key, IComparer<TRow> comparer, ListSortDirection direction)>>(o => {
var active_comparers = ImmutableList<(TKey key, IComparer<TRow> 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<TKey> 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 <see cref="DIYGrid.IKeyedColumn{TColKey}"/>.
public static IReadOnlyList<(TColKey col, ListSortDirection direction)> get_sorting_data<TColKey>(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<T> reverse_if_descending<T>(IComparer<T> comp, ListSortDirection direction) =>
direction == ListSortDirection.Descending ? comp.reverse() : comp;
public static void set_sort_directions<TColumnKey>(IEnumerable<(TColumnKey key, ListSortDirection direction)> sorting_hierarchy, IEnumerable<DIYGrid.ColumnBase> columns) {
foreach (var col in columns) {
col.SortDirection = col is DIYGrid.IKeyedColumn<TColumnKey> kc && sorting_hierarchy.TryGetFirst(tup => tup.key.Equals(kc.key), out var match) ?
match.direction :
(ListSortDirection?)null;
}
}
/// Important: All columns MUST IMPLEMENT <see cref="DIYGrid.IKeyedColumn{TColKey}"/>.
static IReadOnlyList<(TColKey col, ListSortDirection direction)> _on_sorting<TColKey>(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<TColKey> col) {