From 4de77ce339831eb4fde9bf5752ba4008d1ecff79 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Thu, 14 Nov 2019 16:08:49 -0600 Subject: [PATCH] pnl sometimes duplicates grouping columns when they are changed in settings dialog --- .../Trading/PNL/Settings/VM/PNLSettingsVM.cs | 439 +++++++++--------- 1 file changed, 221 insertions(+), 218 deletions(-) diff --git a/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLSettingsVM.cs b/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLSettingsVM.cs index 47a36196f..518e259a6 100644 --- a/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLSettingsVM.cs +++ b/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLSettingsVM.cs @@ -1,220 +1,223 @@ -using bts.collections; -using bts.utils; -using mbts; -using mbts.collections; -using mbts.expression; -using mbts.spark; -using mbts.ui; -using mbts.ui.settings; -using mbts.ui.shell; -using mbts.ui.spark; -using mbts.ui.utility; -using mbts.utils; -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.Dynamic; -using System.Linq; -using ColumnKeys = bts.shell.pnl.PNLView.Columns; - -namespace bts.shell.pnl { - class PNLSettingsVM : DisposableViewModelBase, IWindowSettingsVM, IValueFactory, IObservable, ITemplateSelectorKey { - readonly IReadOnlyDictionary _anchor_cache; - readonly DeferrableActionWrapper _sync_anchors; - - PNLCalculationType _calculation_type; - PNLHeaderRowDisplay _header_row_display; - PNLSettings _last_loaded; - - public PNLSettingsVM(PNLSettings settings) { - // init anchor cache, deferrable resync - _anchor_cache = PNLSettings.anchorable_columns.ToDictionary(k => k, k => new AnchorItemVM(this, k)); - _sync_anchors = new DeferrableActionWrapper(() => { - for (int i = 0; i < anchor_items.Count; i++) { - anchor_items[i].anchor_index = i + 1; - anchor_items[i].refresh(); - } - }); - core_settings_vm = new SimpleGridSettingsVM(column_factory: col_settings => { - var col_vm = new PNLColumnVM(core_settings_vm, EnumHelper.parse(col_settings.id)); - col_vm.load_from(col_settings); - return col_vm; - }); - core_settings_vm.selection_highlight.bind_opacity_to_alpha = true; - _dispose = Disposable.Create( - anchor_items.Subscribe((s, e) => _sync_anchors.execute())); - load(settings); - } - - public IEnumerable anchor_item_headers => _anchor_cache.Values; - public ObservableCollection anchor_items { get; } = new ObservableCollection(); - public SimpleGridSettingsVM core_settings_vm { get; } - public PNLGroupRowAppearanceVM group_row_defaults { get; } = new PNLGroupRowAppearanceVM(); - public PNLCellAppearanceVM header_row_defaults { get; } = new PNLCellAppearanceVM(); - public PNLCalculationType calculation_type { get => _calculation_type; set => Set(ref _calculation_type, value); } - public IEnumerable calculation_types => EnumHelper.get_values_except(PNLCalculationType.None, PNLCalculationType.Same, PNLCalculationType.Opposite); - public PNLHeaderRowDisplay header_row_display { get => _header_row_display; set => Set(ref _header_row_display, value); } - public IEnumerable header_row_display_options => PNLSettings.header_row_display_options; - - string ITemplateSelectorKey.key => GridSettingsTemplateKeys.PNL; - - public PNLSettings get_result() { - var s = _last_loaded == null ? new PNLSettings() : SparkUtils.clone_proto(_last_loaded); - s.calculation_type = _calculation_type; - s.grid = core_settings_vm.create(); - // move anchor cols to the left, order wrt grouping hierarchy - var new_cols = new Lazy>(() => s.grid.columns.ToList()); - for (int i = 0; i < s.grid.columns.Count; i++) { - var key = s.grid.columns[i].strong_id(); - if (_anchor_cache.TryGetValue(key, out var a) && a.anchor_index.HasValue) { - // anchor index is 1 based, subtract 1 to get 0 based - int anchor_index = a.anchor_index.Value - 1; - if (anchor_index != i && anchor_index >= 0 && anchor_index < s.grid.columns.Count) { - new_cols.Value.RemoveAt(i); - new_cols.Value.Insert(anchor_index, s.grid.columns[i]); - } +using bts.collections; +using bts.utils; +using mbts; +using mbts.collections; +using mbts.expression; +using mbts.spark; +using mbts.ui; +using mbts.ui.settings; +using mbts.ui.shell; +using mbts.ui.spark; +using mbts.ui.utility; +using mbts.utils; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.Dynamic; +using System.Linq; +using ColumnKeys = bts.shell.pnl.PNLView.Columns; + +namespace bts.shell.pnl { + class PNLSettingsVM : DisposableViewModelBase, IWindowSettingsVM, IValueFactory, IObservable, ITemplateSelectorKey { + readonly IReadOnlyDictionary _anchor_cache; + readonly DeferrableActionWrapper _sync_anchors; + + PNLCalculationType _calculation_type; + PNLHeaderRowDisplay _header_row_display; + PNLSettings _last_loaded; + + public PNLSettingsVM(PNLSettings settings) { + // init anchor cache, deferrable resync + _anchor_cache = PNLSettings.anchorable_columns.ToDictionary(k => k, k => new AnchorItemVM(this, k)); + _sync_anchors = new DeferrableActionWrapper(() => { + for (int i = 0; i < anchor_items.Count; i++) { + anchor_items[i].anchor_index = i + 1; + anchor_items[i].refresh(); } - } - // rule-based animations - var trigger_anims = core_settings_vm.columns - .OfType() - .SelectMany(c => c.get_triggers()) - .GroupBy(tup => tup.expression) - .Where(g => CoreExpressionEvaluator.validate(g.Key)) - .Select(g => ( - expression: g.Key, - animations: g.ToArray())) - .ToList(); - - var normalized_anims = trigger_anims - .Where(tup => CoreExpressionEvaluator.validate(tup.expression)) - .ToList(); - - s = s.with(anchors: anchor_items.Select(vm => vm.key), - grid: new_cols.IsValueCreated ? s.grid.with(columns: new_cols.Value) : null, - group_columns: core_settings_vm.columns.OfType().Select(c => { - var col_settings = c.create(); - col_settings = c.group_column_vm.apply_to(col_settings); - return col_settings; - }), - header_columns: core_settings_vm.columns.OfType().Select(c => { - var col_settings = c.create(); - col_settings = c.header_column_vm.apply_to(col_settings); - return col_settings; - }), - animations: trigger_anims.Select( - ta => new PNLAnimationTriggerData { - expression = ta.expression, - animations = Array.ConvertAll(ta.animations, t => t.row) - }), - group_header_animations: normalized_anims - .Select( - ta => new PNLAnimationTriggerData { - expression = ta.expression, - animations = Array.ConvertAll(ta.animations, t => t.group) - }), - header_row_animations: normalized_anims.Select( - ta => new PNLAnimationTriggerData { - expression = ta.expression, - animations = Array.ConvertAll(ta.animations, t => t.header) - })); - s.header_row_display = header_row_display; - s.header_cell_appearance = PNLCellAppearanceProto.from_appearance(header_row_defaults.to_appearance()); - // group - var (group_cell_appearance, group_row_background_colors) = group_row_defaults.create(); - s.group_cell_appearance = PNLCellAppearanceProto.from_appearance(group_cell_appearance); - s.group_background_colors.SetItems(group_row_background_colors.Select(c => c.rgb_color())); - // - return s; - } - - public void load(PNLSettings value) { - _last_loaded = value; - header_row_defaults.load(value.header_cell_appearance.to_appearance()); - group_row_defaults.load_from((value.group_cell_appearance.to_appearance(), value.group_background_colors.WrapSelectorRO(c => c.argb_color()))); - var column_map = _map_column_data(value.grid.columns, value.animations); - var group_column_map = _map_column_data(value.group_columns, value.group_header_animations); - var header_column_map = _map_column_data(value.header_columns, value.header_row_animations); - - core_settings_vm.load_from(value.grid); - - for (int i = 0; i < core_settings_vm.columns.Count; i++) { - var col_vm = core_settings_vm.columns[i] as PNLColumnVM ?? throw new InvalidOperationException($"In {nameof(PNLSettingsVM)}, all columns should be of type {typeof(PNLColumnVM)}."); - var key = EnumHelper.parse(col_vm.id); - var (col_settings, trigger_animations) = column_map[key]; - var group_data = group_column_map.GetNullable(key); - var header_data = header_column_map.GetNullable(key); - col_vm.load_from(col_settings, trigger_animations, group_data?.settings, group_data?.triggers, header_data?.triggers, header_data?.settings); - } - using (_sync_anchors.defer_execution()) - anchor_items.WrapSelector(a => a.key, k => _anchor_cache[k]).sync_with(value.anchors.Intersect(PNLSettings.anchorable_columns)); - header_row_display = value.header_row_display; - calculation_type = value.calculation_type; - } - - PNLSettings IValueFactory.create() => get_result(); - void IValueFactory.load_from(PNLSettings value) => load(value); - IDisposable IObservable.Subscribe(IObserver observer) => throw new NotImplementedException(); - - static Dictionary triggers)> _map_column_data(IEnumerable columns, IEnumerable triggers) { - var map = columns.ToDictionary( - c => c.strong_id(), - c => (settings: c, triggers: new Dictionary())); - foreach (var trig in triggers) { - foreach (var anim in trig.animations) { - if (map.TryGetValue(anim.column, out var col_data)) - col_data.triggers[trig.expression] = anim; - } - } - return map; - } - - void _append_or_remove_anchor(ColumnKeys key, bool include) { - if (!_anchor_cache.TryGetValue(key, out var vm)) - throw new KeyNotFoundException($"Column key '{key}' is not anchorable (expected one of: {string.Join(", ", PNLSettings.anchorable_columns)})."); - if (vm.include == include) - return; - if (include) { - if (anchor_items.Any(a => a.key == key)) - throw new InvalidOperationException($"{nameof(anchor_items)} already contains an element with key '{key}.'"); - anchor_items.Add(vm); - vm.anchor_index = anchor_items.Count; - } else { - if (!anchor_items.Remove(vm)) - throw new InvalidOperationException($"{nameof(anchor_items)} does not contain an element with key '{key}.'"); - vm.anchor_index = null; - } - _sync_anchors.execute(); - } - - public class AnchorItemVM : ViewModelBase, IEquatable { - readonly PNLSettingsVM _owner; - int? _anchor_index; - - public AnchorItemVM(PNLSettingsVM owner, ColumnKeys key) { - _owner = owner; - this.key = key; - } - - public ColumnKeys key { get; } - public bool include { get => anchor_index.HasValue; set => _owner._append_or_remove_anchor(key, value); } - public int? anchor_index { get => _anchor_index; set => Set(ref _anchor_index, value); } - - public void refresh() => - RaisePropertyChanged(nameof(include), nameof(anchor_index)); - - public bool Equals(AnchorItemVM other) => - other != null && key == other.key; - - public override bool Equals(object obj) => - Equals(obj as AnchorItemVM); - - public override int GetHashCode() => - key.GetHashCode(); - - public override string ToString() => - EnumHelper.get_display_name(key); - } - } + }); + core_settings_vm = new SimpleGridSettingsVM(column_factory: col_settings => { + var col_vm = new PNLColumnVM(core_settings_vm, EnumHelper.parse(col_settings.id)); + col_vm.load_from(col_settings); + return col_vm; + }); + core_settings_vm.selection_highlight.bind_opacity_to_alpha = true; + _dispose = Disposable.Create( + anchor_items.Subscribe((s, e) => _sync_anchors.execute())); + load(settings); + } + + public IEnumerable anchor_item_headers => _anchor_cache.Values; + public ObservableCollection anchor_items { get; } = new ObservableCollection(); + public SimpleGridSettingsVM core_settings_vm { get; } + public PNLGroupRowAppearanceVM group_row_defaults { get; } = new PNLGroupRowAppearanceVM(); + public PNLCellAppearanceVM header_row_defaults { get; } = new PNLCellAppearanceVM(); + public PNLCalculationType calculation_type { get => _calculation_type; set => Set(ref _calculation_type, value); } + public IEnumerable calculation_types => EnumHelper.get_values_except(PNLCalculationType.None, PNLCalculationType.Same, PNLCalculationType.Opposite); + public PNLHeaderRowDisplay header_row_display { get => _header_row_display; set => Set(ref _header_row_display, value); } + public IEnumerable header_row_display_options => PNLSettings.header_row_display_options; + + string ITemplateSelectorKey.key => GridSettingsTemplateKeys.PNL; + + public PNLSettings get_result() { + var s = _last_loaded == null ? new PNLSettings() : SparkUtils.clone_proto(_last_loaded); + s.calculation_type = _calculation_type; + s.grid = core_settings_vm.create(); + // move anchor cols to the left, order wrt grouping hierarchy + List new_cols = null; + IEnumerable cols = s.grid.columns; + var sorted_anchors = anchor_items.OrderBy(a => a.anchor_index).ToList(); + for (int i = 0; i < sorted_anchors.Count; i++) { + if (GridSettingsHelper.try_find_column(cols, sorted_anchors[i].key, out var match, out int pos) && pos != i) { + if (new_cols == null) { + new_cols = s.grid.columns.ToList(); + // set cols to new_cols so subsequent position lookups + // take previous column order manipulations into account. + cols = new_cols; + } + new_cols.RemoveAt(pos); + new_cols.Insert(i, match); + } + } + // rule-based animations + var trigger_anims = core_settings_vm.columns + .OfType() + .SelectMany(c => c.get_triggers()) + .GroupBy(tup => tup.expression) + .Where(g => CoreExpressionEvaluator.validate(g.Key)) + .Select(g => ( + expression: g.Key, + animations: g.ToArray())) + .ToList(); + + var normalized_anims = trigger_anims + .Where(tup => CoreExpressionEvaluator.validate(tup.expression)) + .ToList(); + + s = s.with(anchors: anchor_items.Select(vm => vm.key), + grid: new_cols == null ? null : s.grid.with(columns: new_cols), + group_columns: core_settings_vm.columns.OfType().Select(c => { + var col_settings = c.create(); + col_settings = c.group_column_vm.apply_to(col_settings); + return col_settings; + }), + header_columns: core_settings_vm.columns.OfType().Select(c => { + var col_settings = c.create(); + col_settings = c.header_column_vm.apply_to(col_settings); + return col_settings; + }), + animations: trigger_anims.Select( + ta => new PNLAnimationTriggerData { + expression = ta.expression, + animations = Array.ConvertAll(ta.animations, t => t.row) + }), + group_header_animations: normalized_anims + .Select( + ta => new PNLAnimationTriggerData { + expression = ta.expression, + animations = Array.ConvertAll(ta.animations, t => t.group) + }), + header_row_animations: normalized_anims.Select( + ta => new PNLAnimationTriggerData { + expression = ta.expression, + animations = Array.ConvertAll(ta.animations, t => t.header) + })); + s.header_row_display = header_row_display; + s.header_cell_appearance = PNLCellAppearanceProto.from_appearance(header_row_defaults.to_appearance()); + // group + var (group_cell_appearance, group_row_background_colors) = group_row_defaults.create(); + s.group_cell_appearance = PNLCellAppearanceProto.from_appearance(group_cell_appearance); + s.group_background_colors.SetItems(group_row_background_colors.Select(c => c.rgb_color())); + // + return s; + } + + public void load(PNLSettings value) { + _last_loaded = value; + header_row_defaults.load(value.header_cell_appearance.to_appearance()); + group_row_defaults.load_from((value.group_cell_appearance.to_appearance(), value.group_background_colors.WrapSelectorRO(c => c.argb_color()))); + var column_map = _map_column_data(value.grid.columns, value.animations); + var group_column_map = _map_column_data(value.group_columns, value.group_header_animations); + var header_column_map = _map_column_data(value.header_columns, value.header_row_animations); + + core_settings_vm.load_from(value.grid); + + for (int i = 0; i < core_settings_vm.columns.Count; i++) { + var col_vm = core_settings_vm.columns[i] as PNLColumnVM ?? throw new InvalidOperationException($"In {nameof(PNLSettingsVM)}, all columns should be of type {typeof(PNLColumnVM)}."); + var key = EnumHelper.parse(col_vm.id); + var (col_settings, trigger_animations) = column_map[key]; + var group_data = group_column_map.GetNullable(key); + var header_data = header_column_map.GetNullable(key); + col_vm.load_from(col_settings, trigger_animations, group_data?.settings, group_data?.triggers, header_data?.triggers, header_data?.settings); + } + using (_sync_anchors.defer_execution()) + anchor_items.WrapSelector(a => a.key, k => _anchor_cache[k]).sync_with(value.anchors.Intersect(PNLSettings.anchorable_columns)); + header_row_display = value.header_row_display; + calculation_type = value.calculation_type; + } + + PNLSettings IValueFactory.create() => get_result(); + void IValueFactory.load_from(PNLSettings value) => load(value); + IDisposable IObservable.Subscribe(IObserver observer) => throw new NotImplementedException(); + + static Dictionary triggers)> _map_column_data(IEnumerable columns, IEnumerable triggers) { + var map = columns.ToDictionary( + c => c.strong_id(), + c => (settings: c, triggers: new Dictionary())); + foreach (var trig in triggers) { + foreach (var anim in trig.animations) { + if (map.TryGetValue(anim.column, out var col_data)) + col_data.triggers[trig.expression] = anim; + } + } + return map; + } + + void _append_or_remove_anchor(ColumnKeys key, bool include) { + if (!_anchor_cache.TryGetValue(key, out var vm)) + throw new KeyNotFoundException($"Column key '{key}' is not anchorable (expected one of: {string.Join(", ", PNLSettings.anchorable_columns)})."); + if (vm.include == include) + return; + if (include) { + if (anchor_items.Any(a => a.key == key)) + throw new InvalidOperationException($"{nameof(anchor_items)} already contains an element with key '{key}.'"); + anchor_items.Add(vm); + vm.anchor_index = anchor_items.Count; + } else { + if (!anchor_items.Remove(vm)) + throw new InvalidOperationException($"{nameof(anchor_items)} does not contain an element with key '{key}.'"); + vm.anchor_index = null; + } + _sync_anchors.execute(); + } + + public class AnchorItemVM : ViewModelBase, IEquatable { + readonly PNLSettingsVM _owner; + int? _anchor_index; + + public AnchorItemVM(PNLSettingsVM owner, ColumnKeys key) { + _owner = owner; + this.key = key; + } + + public ColumnKeys key { get; } + public bool include { get => anchor_index.HasValue; set => _owner._append_or_remove_anchor(key, value); } + public int? anchor_index { get => _anchor_index; set => Set(ref _anchor_index, value); } + + public void refresh() => + RaisePropertyChanged(nameof(include), nameof(anchor_index)); + + public bool Equals(AnchorItemVM other) => + other != null && key == other.key; + + public override bool Equals(object obj) => + Equals(obj as AnchorItemVM); + + public override int GetHashCode() => + key.GetHashCode(); + + public override string ToString() => + EnumHelper.get_display_name(key); + } + } } \ No newline at end of file