Fix re-entrancy bug in PNLWindow when cols are changing

* Log column collection change events for diagnostic purposes
* Clean up code a bit
This commit is contained in:
John Colvin committed 2022-02-04 17:41:32 -05:00
1 parent 0a8a3bf6f2
commit 4dcf296af2
2 files changed
+200 -127

No files matched your search

@@ -1,39 +1,43 @@
using bts.api;
using bts.api.position;
using bts.collections;
using bts.settings;
using bts.shell.pnl;
using bts.spark;
using bts.utils;
using bts.view;
using mbts;
using mbts.config;
using mbts.persist;
using mbts.spark;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.controls.property_editor;
using mbts.ui.settings;
using mbts.ui.spark;
using mbts.ui.utility;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Composition;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
namespace bts.shell {
using bts.api;
using bts.api.position;
using bts.collections;
using bts.settings;
using bts.shell.pnl;
using bts.spark;
using bts.utils;
using bts.view;
using mbts;
using mbts.config;
using mbts.persist;
using mbts.spark;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.controls.property_editor;
using mbts.ui.settings;
using mbts.ui.spark;
using mbts.ui.utility;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Composition;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
class PNLWindowFactory : ShellWindowFactory<PNLSaveState> {
const string _window_type = "PNL", _window_title = "PNL";
static int _window_id_counter = 0;
readonly IBus _bus;
readonly OrdersModel _orders_model;
readonly UserSettingsHub _settings_hub;
@@ -59,12 +63,23 @@ namespace bts.shell {
IShellWindow _create(PNLSettings settings) {
var settings_manager = _settings_hub.create_pnl_settings_manager(settings);
int window_id = Interlocked.Increment(ref _window_id_counter);
var logger = new LoggerContext(Log.Ui, $"[PNLWindow_{window_id}] ", null);
// Need to keep a local copy of the columns, since they are defined in xaml (not the viewmodel), and get_save_state may be called on a non-dispatcher thread.
// If that happens, we would be unable to access _grid.Columns, and thus unable to get the current column settings.
// 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;
Action<SparkWindowView> on_parent_view_created_impl = null;
return SparkWindow<PNLSaveState>.create(_window_type, _window_title, _bus, this, Icons.Accounting, _thread_id_provider.next_id(), () => {
return SparkWindow<PNLSaveState>.create(_window_type, _window_title, _bus, this, Icons.Accounting, _thread_id_provider.next_id(), thread_init,
// the on_parent_view_created_impl delegate is initialized in the main create delegate,
// so it can't be passed directly as an argument because it would just be null,
// hence the proxy/wrapper delegate below.
on_parent_view_created: pview => on_parent_view_created_impl?.Invoke(pview),
min_width_offset: SystemParameters.HorizontalScrollBarButtonWidth + 8,
min_height_offset: 60);
(UIElement, IEnumerable<SparkCommand>, Func<PNLSaveState>, IDisposable) thread_init() {
var init_settings = settings ?? PNLSettings.Default;
var menu_display_vm = new SparkMenuDisplayVM();
menu_display_vm.load_from(init_settings.menu_display);
@@ -84,35 +99,6 @@ namespace bts.shell {
.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 = () => {
var cols = cached_columns.ToArray(c => c.create());
var filters = vm.get_filters_states();
var sorting_criteria = 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_criteria.SequenceEqual(sorting_criteria) &&
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 };
}
state = defaults;
}
// 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(
sorting_criteria,
vm.anchors,
filters,
state.grid.with(columns: cols, background: vm.grid_background_color.rgb_color()),
calc_type,
vm.header_row_display,
menu_display: menu_display_vm.create());
return new PNLSaveState { use_defaults = false, settings = state };
};
IDisposable cpp_override_dialog = null;
IEnumerable<SparkCommand> commands = new[] {
new SparkCommandCommand("Collapse All", Icons.RightArrow, new DelegateCommand(() => vm.set_all_expanded(false))),
@@ -160,76 +146,149 @@ namespace bts.shell {
})),
menu_display_vm.spark_cmd
};
IDisposable dispose = Disposable.Create(
settings_manager.subscribe_current().OnDispatcher().Subscribe(s => {
vm.load_from(s);
var col_setting_map = s.grid.columns.ToDictionary(c => c.id);
var fallback_family = new FontFamily(s.grid.font_family);
// group
var group_col_setting_map = s.group_columns.ToDictionary(c => c.id);
var group_appearance = s.group_cell_appearance.to_appearance();
// header
var header_col_setting_map = s.header_columns.ToDictionary(c => c.id);
var header_appearance = s.header_cell_appearance.to_appearance();
//
foreach (var c in content._grid.Columns.OfType<PNLColumn>()) {
if (col_setting_map.TryGetValue(c.id, out var cs)) {
c.load_from(cs);
}
if (group_col_setting_map.TryGetValue(c.id, out var gcs)) {
c.load_group_params(
group_appearance.font_size,
gcs.font_weight_override ?? group_appearance.font_weight,
gcs.font_color_override ?? group_appearance.foreground,
group_appearance.font_family);
}
if (header_col_setting_map.TryGetValue(c.id, out var hcs)) {
c.load_header_params(
header_appearance.font_size,
hcs.font_weight_override ?? header_appearance.font_weight,
hcs.font_color_override ?? header_appearance.foreground,
header_appearance.font_family);
}
}
CollectionHelper.sync_with_never_duplicate(content._grid.Columns.as_mutable(), s.grid.columns, cs => {
throw new InvalidOperationException();
}, c => c.id.ToLower(), cs => cs.id.ToLower());
}),
(content._grid.Columns as INotifyCollectionChanged)?.Subscribe((s, e) => {
switch (e.Action) {
case NotifyCollectionChangedAction.Add: add_new(); break;
case NotifyCollectionChangedAction.Remove: remove_old(); break;
case NotifyCollectionChangedAction.Replace:
case NotifyCollectionChangedAction.Move:
remove_old();
add_new();
break;
case NotifyCollectionChangedAction.Reset:
cached_columns = ImmutableList<DIYGrid.ColumnBase>.Empty.AddRange(content._grid.Columns);
break;
}
void add_new() =>
cached_columns = e.NewStartingIndex >= 0 ?
cached_columns.InsertRange(e.NewStartingIndex, e.NewItems.OfType<DIYGrid.ColumnBase>()) :
cached_columns.AddRange(e.NewItems.OfType<DIYGrid.ColumnBase>());
void remove_old() =>
cached_columns = e.OldStartingIndex >= 0 ?
cached_columns.RemoveRange(e.OldStartingIndex, e.OldItems.Count) :
cached_columns.RemoveRange(e.OldItems.OfType<DIYGrid.ColumnBase>());
}),
PNLSettings pending_settings = null;
PropertyUpdateGate column_update = new();
var grid_cols = content._grid.Columns as ObservableCollection<DIYGrid.ColumnBase>;
grid_cols.CollectionChanged += on_grid_cols_changed;
IDisposable dispose = Disposable.Create(
settings_manager.subscribe_current().OnDispatcher().Subscribe(on_settings),
Disposable.wrap_collection(commands.OfType<IDisposable>()),
Disposable.Create(() => Disposable.dispose(ref cpp_override_dialog)),
menu_display_vm,
vm);
return (content, commands, get_save_state, dispose);
},
// the on_parent_view_created_impl delegate is initialized in the main create delegate,
// so it can't be passed directly as an argument because it would just be null,
// hence the proxy/wrapper delegate below.
on_parent_view_created: pview => on_parent_view_created_impl?.Invoke(pview),
min_width_offset: SystemParameters.HorizontalScrollBarButtonWidth + 8,
min_height_offset: 60);
PNLSaveState get_save_state() {
var cols = cached_columns.ToArray(c => c.create());
var filters = vm.get_filters_states();
var sorting_criteria = 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_criteria.SequenceEqual(sorting_criteria) &&
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 };
}
state = defaults;
}
// 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(
sorting_criteria,
vm.anchors,
filters,
state.grid.with(columns: cols, background: vm.grid_background_color.rgb_color()),
calc_type,
vm.header_row_display,
menu_display: menu_display_vm.create());
return new PNLSaveState { use_defaults = false, settings = state };
}
void on_settings(PNLSettings s) {
if (column_update.is_updating) {
logger.info($"Postpone on_settings (columns-update in progress): {s}");
pending_settings = s;
return;
}
logger.info($"on_settings: {s}");
pending_settings = null;
vm.load_from(s);
var col_setting_map = s.grid.columns.ToDictionary(c => c.id);
var fallback_family = new FontFamily(s.grid.font_family);
// group
var group_col_setting_map = s.group_columns.ToDictionary(c => c.id);
var group_appearance = s.group_cell_appearance.to_appearance();
// header
var header_col_setting_map = s.header_columns.ToDictionary(c => c.id);
var header_appearance = s.header_cell_appearance.to_appearance();
//
foreach (var c in content._grid.Columns.OfType<PNLColumn>()) {
if (col_setting_map.TryGetValue(c.id, out var cs)) {
c.load_from(cs);
}
if (group_col_setting_map.TryGetValue(c.id, out var gcs)) {
c.load_group_params(
group_appearance.font_size,
gcs.font_weight_override ?? group_appearance.font_weight,
gcs.font_color_override ?? group_appearance.foreground,
group_appearance.font_family);
}
if (header_col_setting_map.TryGetValue(c.id, out var hcs)) {
c.load_header_params(
header_appearance.font_size,
hcs.font_weight_override ?? header_appearance.font_weight,
hcs.font_color_override ?? header_appearance.foreground,
header_appearance.font_family);
}
}
var keys = new HashSet<string>(s.grid.columns.Select(c => c.id));
Log.assert(keys.Count == s.grid.columns.Count);
var cols_view = content._grid.Columns;
var mcols_view = cols_view.as_mutable(true);
CollectionHelper.sync_with_never_duplicate(mcols_view, s.grid.columns, cs => {
throw new InvalidOperationException();
}, c => c.id.ToLower(), cs => cs.id.ToLower());
for (int i = 0; i < keys.Count; i++) {
var cv = cols_view[i];
var mcv = mcols_view[i];
if (cv.id != mcv.id) {
CollectionHelper.sync_with_never_duplicate(mcols_view, s.grid.columns, cs => {
throw new InvalidOperationException();
}, c => c.id.ToLower(), cs => cs.id.ToLower());
Log.assert(false);
}
}
}
void on_grid_cols_changed(object s, NotifyCollectionChangedEventArgs e) {
logger.info($"on_grid_cols_changed: {CollectionHelper.fmt_collection_change(e)}");
using var _ = column_update.update();
switch (e.Action) {
case NotifyCollectionChangedAction.Add: add_new(); break;
case NotifyCollectionChangedAction.Remove: remove_old(); break;
case NotifyCollectionChangedAction.Replace:
case NotifyCollectionChangedAction.Move:
remove_old();
add_new();
break;
case NotifyCollectionChangedAction.Reset:
cached_columns = ImmutableList<DIYGrid.ColumnBase>.Empty.AddRange(content._grid.Columns);
break;
}
Log.assert(cached_columns.SequenceEqual(grid_cols));
if (pending_settings is not null) {
logger.info("restore pending_settings");
on_settings(pending_settings);
}
void add_new() =>
cached_columns = e.NewStartingIndex >= 0 ?
cached_columns.InsertRange(e.NewStartingIndex, e.NewItems.OfType<DIYGrid.ColumnBase>()) :
cached_columns.AddRange(e.NewItems.OfType<DIYGrid.ColumnBase>());
void remove_old() {
var orig_count = cached_columns.Count;
cached_columns = e.OldStartingIndex >= 0 ?
cached_columns.RemoveRange(e.OldStartingIndex, e.OldItems.Count) :
cached_columns.RemoveRange(e.OldItems.OfType<DIYGrid.ColumnBase>());
var num_removed = orig_count - cached_columns.Count;
if (num_removed != e.OldItems.Count) {
Log.assert(false);
}
}
}
}
}
readonly struct PNLConfig {
@@ -7,6 +7,7 @@ using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
namespace bts.utils {
static class CollectionHelper {
@@ -116,6 +117,19 @@ namespace bts.utils {
}
}
public static string fmt_collection_change(NotifyCollectionChangedEventArgs e) {
return e.Action switch {
NotifyCollectionChangedAction.Add => $"Insert at {e.NewStartingIndex} [{fmt_items(e.NewItems)}]",
NotifyCollectionChangedAction.Remove => $"Remove from {e.OldStartingIndex} [{fmt_items(e.OldItems)}]",
NotifyCollectionChangedAction.Move => $"Move from {e.OldStartingIndex} to {e.NewStartingIndex} [{fmt_items(e.NewItems)}]",
NotifyCollectionChangedAction.Replace => $"Replace at {e.OldStartingIndex} [{fmt_items(e.OldItems)}] with [{fmt_items(e.NewItems)}]",
NotifyCollectionChangedAction.Reset => "Reset",
_ => $"Unknown-action {e.Action}"
};
static string fmt_items(IList items) => ", ".join(items.Cast<object>());
}
public static void reflect_change<T, TData>(IList<T> target, IEnumerable<TData> source, Func<TData, T> create_item, Action<T> on_removed, NotifyCollectionChangedEventArgs e) {
switch (e.Action) {
case NotifyCollectionChangedAction.Add: