From 7b8d45c22978ff5e45e24c6beb79dff45999823a Mon Sep 17 00:00:00 2001 From: John Colvin Date: Wed, 23 Oct 2019 15:09:36 -0500 Subject: [PATCH] make pnl settings pretty --- .../Modules/Trading/PNL/PNLWindowFactory.cs | 750 +++++++++--------- .../VM/PNLAnchorHierarchyParameterVM.cs | 8 + .../VM/PNLCellAppearanceOverrideVM.cs | 170 ++-- .../PNL/Settings/VM/PNLCellAppearanceVM.cs | 55 +- .../Trading/PNL/Settings/VM/PNLColumnVM.cs | 311 +++++--- .../Settings/VM/PNLGroupRowAppearanceVM.cs | 88 +- .../Trading/PNL/Settings/VM/PNLSettingsVM.cs | 353 ++++----- .../spark/Modules/Trading/PNL/VM/PNLVM.cs | 2 +- .../Trading/PNL/View/PNLSettingsView.xaml | 174 ++++ .../Trading/PNL/View/PNLSettingsView.xaml.cs | 129 +++ .../spark/core/Utility/ViewModelBase.cs | 9 + .../DIYGrid/Settings/GridColumnSettingsVM.cs | 8 +- .../Settings/GridSettingsResources.xaml | 33 + .../DIYGrid/Settings/GridSettingsVM.cs | 60 +- .../Numeric/IntAdditionConverter.cs | 24 + .../Shell/Settings/ShellSettingsDialog.xaml | 303 +------ .../Settings/ShellSettingsDialog.xaml.cs | 108 +-- .../spark/view/Utility/DisplayNameHelper.cs | 3 + src/client/spark/view/Utility/EnumHelper.cs | 13 + .../view/ViewModels/ItemOrderParameterVM.cs | 122 +++ 20 files changed, 1425 insertions(+), 1298 deletions(-) create mode 100644 src/client/spark/Modules/Trading/PNL/Settings/VM/PNLAnchorHierarchyParameterVM.cs create mode 100644 src/client/spark/Modules/Trading/PNL/View/PNLSettingsView.xaml create mode 100644 src/client/spark/Modules/Trading/PNL/View/PNLSettingsView.xaml.cs create mode 100644 src/client/spark/view/Converters/Numeric/IntAdditionConverter.cs create mode 100644 src/client/spark/view/ViewModels/ItemOrderParameterVM.cs diff --git a/src/client/spark/Modules/Trading/PNL/PNLWindowFactory.cs b/src/client/spark/Modules/Trading/PNL/PNLWindowFactory.cs index 638c629f5..4d9587d87 100644 --- a/src/client/spark/Modules/Trading/PNL/PNLWindowFactory.cs +++ b/src/client/spark/Modules/Trading/PNL/PNLWindowFactory.cs @@ -1,375 +1,377 @@ -using bts.api; -using bts.collections; -using bts.settings; -using bts.shell.pnl; -using bts.spark; -using bts.utils; -using mbts; -using mbts.config; -using mbts.persist; -using mbts.spark; -using mbts.ui; -using mbts.ui.controls; -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.ComponentModel.Composition; -using System.Linq; -using System.Reactive.Linq; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Media; - -namespace bts.shell { - class PNLWindowFactory : ShellWindowFactory { - const string _window_type = "PNL", _window_title = "PNL"; - readonly IBus _bus; - readonly OrdersModel _orders_model; - readonly UserSettingsHub _settings_hub; - readonly PNLConfig _pnl_conf; - readonly IShellWindowThreadIDProvider _thread_id_provider; - - public PNLWindowFactory(IShellModule owner, IBus bus, UserSettingsHub settings_hub, OrdersModel orders_model) : base(owner, _window_type) { - _bus = bus; - _orders_model = orders_model; - _settings_hub = settings_hub; - _pnl_conf = new PNLConfig(Configuration.get()); - _thread_id_provider = ShellWindowThreadIDFactory.create(_window_type, Configuration.get().pnl); - _dispose = bus.subscribe(SparkTags.ShowPNLTag).OnDispatcher().Subscribe(_show); - } - - public override Task load(PNLSaveState state) => - Task.FromResult(_create(state.settings)); - - void _show(PNLSettings settings) => - _bus.post(SparkTags.ShowWindow, _create(settings)); - - IShellWindow _create(PNLSettings settings) { - var settings_manager = _settings_hub.create_pnl_settings_manager(settings); - // 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 cached_columns = ImmutableList.Empty; - return SparkWindow.create(_window_type, _window_title, _bus, this, Icons.Accounting, _thread_id_provider.next_id(), () => { - 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 = () => { - 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(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 }; - } - 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_criterion, - vm.anchors, - filters, - state.grid.with(columns: cols, background: vm.grid_background_color.rgb_color()), - calc_type, - vm.header_row_display); - return new PNLSaveState { use_defaults = false, settings = state }; - }; - IEnumerable commands = new[] { - new SparkCommandCommand("Collapse All", Icons.RightArrow, new DelegateCommand(() => vm.set_all_expanded(false))), - new SparkCommandCommand("Expand All", Icons.DownArrow, new DelegateCommand(() => vm.set_all_expanded(true))), - new SparkCommandCommand("Play", Icons.Play, new DelegateCommand(() => vm.is_paused = false)) { - show_in_context_menu = _pnl_conf.show_pause_resume, - show_in_toolbar = _pnl_conf.show_pause_resume - }, - new SparkCommandCommand("Pause", Icons.Pause, new DelegateCommand(() => vm.is_paused = true)) { - show_in_context_menu = _pnl_conf.show_pause_resume, - show_in_toolbar = _pnl_conf.show_pause_resume - }, - SparkCommands.window_settings_command(new DialogCommand(() => { - settings_manager.instance_settings = get_save_state().settings; - var dialog_vm = new ShellSettingsDialogVM( - settings_manager, - us => us.pnl, - UserSettings.FileExtensions.PNL, - s => new PNLSettingsVM(s)); - var dialog = new ShellSettingsDialog { DataContext = dialog_vm }; - dialog_vm.RequestClose += on_request_close; - return dialog; - void on_request_close(object sender, EventArgs e) => - WindowUtilities.force_close(dialog); - })) - }; - 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()) { - 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, s.grid.columns, cs => { - throw new InvalidOperationException(); - }, c => c.id.ToLower(), cs => cs.id.ToLower()); - }), - content._grid.Columns.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.Empty.AddRange(content._grid.Columns); - break; - } - void add_new() => - cached_columns = e.NewStartingIndex >= 0 ? - cached_columns.InsertRange(e.NewStartingIndex, e.NewItems.OfType()) : - cached_columns.AddRange(e.NewItems.OfType()); - - void remove_old() => - cached_columns = e.OldStartingIndex >= 0 ? - cached_columns.RemoveRange(e.OldStartingIndex, e.OldItems.Count) : - cached_columns.RemoveRange(e.OldItems.OfType()); - }), - Disposable.wrap_collection(commands.OfType()), - vm); - return (content, commands, get_save_state, dispose); - }, - min_width_offset: SystemParameters.HorizontalScrollBarButtonWidth + 8, - min_height_offset: 60); - } - - readonly struct PNLConfig { - public readonly bool - enable_animations, - show_pause_resume; - - public PNLConfig(bts.config.PNLOptions options) { - enable_animations = options.enable_animations; - show_pause_resume = options.show_pause_resume; - } - } - - [Export(typeof(IPNLSettingsMigrationRule))] - class AddMissingAnimationsMigrationRule : IPNLSettingsMigrationRule { - public bool apply(PNLSettings settings, out PNLSettings new_settings) { - if (settings != null && ( - _apply(ref settings, settings.animations, PNLSettings.default_animations, (s, anims) => s.with(animations: anims)) | - _apply(ref settings, settings.group_header_animations, PNLSettings.default_group_header_animations, (s, anims) => s.with(group_header_animations: anims)) | - _apply(ref settings, settings.header_row_animations, PNLSettings.default_header_row_animations, (s, anims) => s.with(header_row_animations: anims)))) { - // - new_settings = settings; - return true; - } - new_settings = null; - return false; - } - - static bool _apply(ref PNLSettings settings, IEnumerable actual_triggers, IEnumerable default_triggers, Func set_triggers) { - if (_apply(actual_triggers, default_triggers, out var result)) { - settings = set_triggers(settings, actual_triggers.Concat(result).ToArray()); - return true; - } - return false; - } - - static bool _apply(IEnumerable actual_triggers, IEnumerable default_triggers, out IEnumerable result) { - var default_trigger_map = default_triggers.ToDictionary(t => t.expression); - var actual_trigger_map = actual_triggers.ToImmutableDictionary(t => t.expression); - var snapshot = actual_trigger_map; - foreach (var kv in snapshot) { - if (default_trigger_map.TryGetValue(kv.Key, out var default_anims)) { - // assume 1 animation per column - var actual_col_anims = kv.Value.animations.ToDictionaryCrushed(a => a.column); - var default_col_anims = default_anims.animations.ToDictionaryCrushed(a => a.column); - actual_col_anims.Difference(default_col_anims, - out var exclusive_actual, - out var exclusive_defaults, - out var diff); - var new_col_anims = exclusive_defaults.ToList(); - if (new_col_anims.Count > 0) { - // add the original col animations to the new ones (combine them) - new_col_anims.AddRange(actual_col_anims); - actual_trigger_map = actual_trigger_map.SetItem(kv.Key, kv.Value.with(animations: new_col_anims.Select(col_anim => col_anim.Value).ToArray())); - } - } - } - foreach (var kv in default_trigger_map) { - if (!actual_trigger_map.ContainsKey(kv.Key)) - actual_trigger_map = actual_trigger_map.Add(kv.Key, kv.Value); - } - if (actual_trigger_map != snapshot) { - result = actual_trigger_map.Values; - return true; - } - result = null; - return false; - } - } - - [Export(typeof(IPNLSettingsMigrationRule))] - class AddMissingColumnsMigrationRule : IPNLSettingsMigrationRule { - public bool apply(PNLSettings settings, out PNLSettings new_settings) { - if (settings != null) { - var defaults = PNLSettings.Default; - if (_apply(ref settings, settings.grid.columns, defaults.grid.columns, (s, cols) => s.with(grid: s.grid.with(cols))) | - _apply(ref settings, settings.group_columns, defaults.group_columns, (s, cols) => s.with(group_columns: cols)) | - _apply(ref settings, settings.header_columns, defaults.header_columns, (s, cols) => s.with(header_columns: cols))) { - new_settings = settings; - return true; - } - } - new_settings = null; - return false; - } - - static bool _apply(ref PNLSettings settings, IEnumerable actual_columns, IEnumerable default_columns, Func, PNLSettings> set_columns) { - if (GridSettingsHelper.add_missing_columns(actual_columns, default_columns, out var new_cols)) { - settings = set_columns(settings, new_cols); - return true; - } - return false; - } - } - - [Export(typeof(IPNLSettingsMigrationRule))] - class RemoveColumnsMigrationRule : IPNLSettingsMigrationRule { - public bool apply(PNLSettings settings, out PNLSettings new_settings) { - if (settings != null) { - if (_apply(ref settings, settings.grid.columns, (s, cols) => s.with(grid: s.grid.with(cols))) | - _apply(ref settings, settings.group_columns, (s, cols) => s.with(group_columns: cols)) | - _apply(ref settings, settings.header_columns, (s, cols) => s.with(header_columns: cols))) { - new_settings = settings; - return true; - } - } - new_settings = null; - return false; - } - - bool _apply(ref PNLSettings settings, IEnumerable columns, Func, PNLSettings> set_columns) { - if (_apply(columns, out var new_cols)) { - settings = set_columns(settings, new_cols); - return true; - } - return false; - } - - bool _apply(IEnumerable columns, out IEnumerable result) { - var col_list = columns.ToList(); - int orig_count = col_list.Count; - col_list.RemoveWhere(c => !Enum.TryParse(c.id, true, out var _)); - if (col_list.Count < orig_count) { - result = col_list; - return true; - } - result = null; - return false; - } - } - - [Export(typeof(IPNLSettingsMigrationRule))] - class RemoveColumnAnimationsMigrationRule : IPNLSettingsMigrationRule { - public bool apply(PNLSettings settings, out PNLSettings new_settings) { - if (settings != null) { - if (_apply(ref settings, settings.animations, (s, t) => s.with(animations: t)) | - _apply(ref settings, settings.group_header_animations, (s, t) => s.with(group_header_animations: t)) | - _apply(ref settings, settings.header_row_animations, (s, t) => s.with(header_row_animations: t))) { - new_settings = settings; - return true; - } - } - new_settings = null; - return false; - } - - bool _apply(ref PNLSettings settings, IEnumerable triggers, Func, PNLSettings> set_triggers) { - if (_apply(triggers, out var new_triggers)) { - settings = set_triggers(settings, new_triggers); - return true; - } - return false; - } - - bool _apply(IEnumerable triggers, out IEnumerable result) { - var trigger_map = triggers.ToImmutableDictionary(t => t.expression); - var snapshot = trigger_map; - foreach (var t in trigger_map.Values) { - var anims = t.animations.ToList(); - int orig_count = anims.Count; - anims.RemoveWhere(a => !Enum.IsDefined(typeof(PNLView.Columns), a.column)); - if (anims.Count < orig_count) - trigger_map = trigger_map.SetItem(t.expression, t.with(animations: anims.ToArray())); - } - if (trigger_map != snapshot) { - result = trigger_map.Values; - return true; - } - result = null; - return false; - } - } - - [Export(typeof(IPNLSettingsMigrationRule))] - class EnableGridBackgroundColorMigrationRule : IPNLSettingsMigrationRule { - public bool apply(PNLSettings settings, out PNLSettings new_settings) { - if (settings != null && !settings.grid.enable_background_color) { - new_settings = settings.with(grid: settings.grid.with(enable_background_color: true)); - return true; - } - new_settings = null; - return false; - } - } - } +using bts.api; +using bts.collections; +using bts.settings; +using bts.shell.pnl; +using bts.spark; +using bts.utils; +using mbts; +using mbts.config; +using mbts.persist; +using mbts.spark; +using mbts.ui; +using mbts.ui.controls; +using mbts.ui.converters; +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.ComponentModel.Composition; +using System.Linq; +using System.Reactive.Linq; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Data; +using System.Windows.Media; + +namespace bts.shell { + class PNLWindowFactory : ShellWindowFactory { + const string _window_type = "PNL", _window_title = "PNL"; + readonly IBus _bus; + readonly OrdersModel _orders_model; + readonly UserSettingsHub _settings_hub; + readonly PNLConfig _pnl_conf; + readonly IShellWindowThreadIDProvider _thread_id_provider; + + public PNLWindowFactory(IShellModule owner, IBus bus, UserSettingsHub settings_hub, OrdersModel orders_model) : base(owner, _window_type) { + _bus = bus; + _orders_model = orders_model; + _settings_hub = settings_hub; + _pnl_conf = new PNLConfig(Configuration.get()); + _thread_id_provider = ShellWindowThreadIDFactory.create(_window_type, Configuration.get().pnl); + _dispose = bus.subscribe(SparkTags.ShowPNLTag).OnDispatcher().Subscribe(_show); + } + + public override Task load(PNLSaveState state) => + Task.FromResult(_create(state.settings)); + + void _show(PNLSettings settings) => + _bus.post(SparkTags.ShowWindow, _create(settings)); + + IShellWindow _create(PNLSettings settings) { + var settings_manager = _settings_hub.create_pnl_settings_manager(settings); + // 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 cached_columns = ImmutableList.Empty; + return SparkWindow.create(_window_type, _window_title, _bus, this, Icons.Accounting, _thread_id_provider.next_id(), () => { + 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 = () => { + 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(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 }; + } + 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_criterion, + vm.anchors, + filters, + state.grid.with(columns: cols, background: vm.grid_background_color.rgb_color()), + calc_type, + vm.header_row_display); + return new PNLSaveState { use_defaults = false, settings = state }; + }; + IEnumerable commands = new[] { + new SparkCommandCommand("Collapse All", Icons.RightArrow, new DelegateCommand(() => vm.set_all_expanded(false))), + new SparkCommandCommand("Expand All", Icons.DownArrow, new DelegateCommand(() => vm.set_all_expanded(true))), + new SparkCommandCommand("Play", Icons.Play, new DelegateCommand(() => vm.is_paused = false)) { + show_in_context_menu = _pnl_conf.show_pause_resume, + show_in_toolbar = _pnl_conf.show_pause_resume + }, + new SparkCommandCommand("Pause", Icons.Pause, new DelegateCommand(() => vm.is_paused = true)) { + show_in_context_menu = _pnl_conf.show_pause_resume, + show_in_toolbar = _pnl_conf.show_pause_resume + }, + SparkCommands.window_settings_command(new DialogCommand(() => { + settings_manager.instance_settings = get_save_state().settings; + var dialog_vm = new ShellSettingsDialogVM( + settings_manager, + us => us.pnl, + UserSettings.FileExtensions.PNL, + s => new PNLSettingsVM(s)); + var dialog = new ShellSettingsDialog { DataContext = dialog_vm }; + dialog_vm.RequestClose += on_request_close; + return dialog; + void on_request_close(object sender, EventArgs e) => + WindowUtilities.force_close(dialog); + })) + }; + 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()) { + 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, s.grid.columns, cs => { + throw new InvalidOperationException(); + }, c => c.id.ToLower(), cs => cs.id.ToLower()); + }), + content._grid.Columns.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.Empty.AddRange(content._grid.Columns); + break; + } + void add_new() => + cached_columns = e.NewStartingIndex >= 0 ? + cached_columns.InsertRange(e.NewStartingIndex, e.NewItems.OfType()) : + cached_columns.AddRange(e.NewItems.OfType()); + + void remove_old() => + cached_columns = e.OldStartingIndex >= 0 ? + cached_columns.RemoveRange(e.OldStartingIndex, e.OldItems.Count) : + cached_columns.RemoveRange(e.OldItems.OfType()); + }), + Disposable.wrap_collection(commands.OfType()), + vm); + return (content, commands, get_save_state, dispose); + }, + min_width_offset: SystemParameters.HorizontalScrollBarButtonWidth + 8, + min_height_offset: 60); + } + + readonly struct PNLConfig { + public readonly bool + enable_animations, + show_pause_resume; + + public PNLConfig(bts.config.PNLOptions options) { + enable_animations = options.enable_animations; + show_pause_resume = options.show_pause_resume; + } + } + + [Export(typeof(IPNLSettingsMigrationRule))] + class AddMissingAnimationsMigrationRule : IPNLSettingsMigrationRule { + public bool apply(PNLSettings settings, out PNLSettings new_settings) { + if (settings != null && ( + _apply(ref settings, settings.animations, PNLSettings.default_animations, (s, anims) => s.with(animations: anims)) | + _apply(ref settings, settings.group_header_animations, PNLSettings.default_group_header_animations, (s, anims) => s.with(group_header_animations: anims)) | + _apply(ref settings, settings.header_row_animations, PNLSettings.default_header_row_animations, (s, anims) => s.with(header_row_animations: anims)))) { + // + new_settings = settings; + return true; + } + new_settings = null; + return false; + } + + static bool _apply(ref PNLSettings settings, IEnumerable actual_triggers, IEnumerable default_triggers, Func set_triggers) { + if (_apply(actual_triggers, default_triggers, out var result)) { + settings = set_triggers(settings, actual_triggers.Concat(result).ToArray()); + return true; + } + return false; + } + + static bool _apply(IEnumerable actual_triggers, IEnumerable default_triggers, out IEnumerable result) { + var default_trigger_map = default_triggers.ToDictionary(t => t.expression); + var actual_trigger_map = actual_triggers.ToImmutableDictionary(t => t.expression); + var snapshot = actual_trigger_map; + foreach (var kv in snapshot) { + if (default_trigger_map.TryGetValue(kv.Key, out var default_anims)) { + // assume 1 animation per column + var actual_col_anims = kv.Value.animations.ToDictionaryCrushed(a => a.column); + var default_col_anims = default_anims.animations.ToDictionaryCrushed(a => a.column); + actual_col_anims.Difference(default_col_anims, + out var exclusive_actual, + out var exclusive_defaults, + out var diff); + var new_col_anims = exclusive_defaults.ToList(); + if (new_col_anims.Count > 0) { + // add the original col animations to the new ones (combine them) + new_col_anims.AddRange(actual_col_anims); + actual_trigger_map = actual_trigger_map.SetItem(kv.Key, kv.Value.with(animations: new_col_anims.Select(col_anim => col_anim.Value).ToArray())); + } + } + } + foreach (var kv in default_trigger_map) { + if (!actual_trigger_map.ContainsKey(kv.Key)) + actual_trigger_map = actual_trigger_map.Add(kv.Key, kv.Value); + } + if (actual_trigger_map != snapshot) { + result = actual_trigger_map.Values; + return true; + } + result = null; + return false; + } + } + + [Export(typeof(IPNLSettingsMigrationRule))] + class AddMissingColumnsMigrationRule : IPNLSettingsMigrationRule { + public bool apply(PNLSettings settings, out PNLSettings new_settings) { + if (settings != null) { + var defaults = PNLSettings.Default; + if (_apply(ref settings, settings.grid.columns, defaults.grid.columns, (s, cols) => s.with(grid: s.grid.with(cols))) | + _apply(ref settings, settings.group_columns, defaults.group_columns, (s, cols) => s.with(group_columns: cols)) | + _apply(ref settings, settings.header_columns, defaults.header_columns, (s, cols) => s.with(header_columns: cols))) { + new_settings = settings; + return true; + } + } + new_settings = null; + return false; + } + + static bool _apply(ref PNLSettings settings, IEnumerable actual_columns, IEnumerable default_columns, Func, PNLSettings> set_columns) { + if (GridSettingsHelper.add_missing_columns(actual_columns, default_columns, out var new_cols)) { + settings = set_columns(settings, new_cols); + return true; + } + return false; + } + } + + [Export(typeof(IPNLSettingsMigrationRule))] + class RemoveColumnsMigrationRule : IPNLSettingsMigrationRule { + public bool apply(PNLSettings settings, out PNLSettings new_settings) { + if (settings != null) { + if (_apply(ref settings, settings.grid.columns, (s, cols) => s.with(grid: s.grid.with(cols))) | + _apply(ref settings, settings.group_columns, (s, cols) => s.with(group_columns: cols)) | + _apply(ref settings, settings.header_columns, (s, cols) => s.with(header_columns: cols))) { + new_settings = settings; + return true; + } + } + new_settings = null; + return false; + } + + bool _apply(ref PNLSettings settings, IEnumerable columns, Func, PNLSettings> set_columns) { + if (_apply(columns, out var new_cols)) { + settings = set_columns(settings, new_cols); + return true; + } + return false; + } + + bool _apply(IEnumerable columns, out IEnumerable result) { + var col_list = columns.ToList(); + int orig_count = col_list.Count; + col_list.RemoveWhere(c => !Enum.TryParse(c.id, true, out var _)); + if (col_list.Count < orig_count) { + result = col_list; + return true; + } + result = null; + return false; + } + } + + [Export(typeof(IPNLSettingsMigrationRule))] + class RemoveColumnAnimationsMigrationRule : IPNLSettingsMigrationRule { + public bool apply(PNLSettings settings, out PNLSettings new_settings) { + if (settings != null) { + if (_apply(ref settings, settings.animations, (s, t) => s.with(animations: t)) | + _apply(ref settings, settings.group_header_animations, (s, t) => s.with(group_header_animations: t)) | + _apply(ref settings, settings.header_row_animations, (s, t) => s.with(header_row_animations: t))) { + new_settings = settings; + return true; + } + } + new_settings = null; + return false; + } + + bool _apply(ref PNLSettings settings, IEnumerable triggers, Func, PNLSettings> set_triggers) { + if (_apply(triggers, out var new_triggers)) { + settings = set_triggers(settings, new_triggers); + return true; + } + return false; + } + + bool _apply(IEnumerable triggers, out IEnumerable result) { + var trigger_map = triggers.ToImmutableDictionary(t => t.expression); + var snapshot = trigger_map; + foreach (var t in trigger_map.Values) { + var anims = t.animations.ToList(); + int orig_count = anims.Count; + anims.RemoveWhere(a => !Enum.IsDefined(typeof(PNLView.Columns), a.column)); + if (anims.Count < orig_count) + trigger_map = trigger_map.SetItem(t.expression, t.with(animations: anims.ToArray())); + } + if (trigger_map != snapshot) { + result = trigger_map.Values; + return true; + } + result = null; + return false; + } + } + + [Export(typeof(IPNLSettingsMigrationRule))] + class EnableGridBackgroundColorMigrationRule : IPNLSettingsMigrationRule { + public bool apply(PNLSettings settings, out PNLSettings new_settings) { + if (settings != null && !settings.grid.enable_background_color) { + new_settings = settings.with(grid: settings.grid.with(enable_background_color: true)); + return true; + } + new_settings = null; + return false; + } + } + } } \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLAnchorHierarchyParameterVM.cs b/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLAnchorHierarchyParameterVM.cs new file mode 100644 index 000000000..f16ee91fc --- /dev/null +++ b/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLAnchorHierarchyParameterVM.cs @@ -0,0 +1,8 @@ +using mbts.ui.viewmodels; + +namespace bts.shell.pnl { + class PNLAnchorHierarchyVM : ItemOrderParameterVM { + public PNLAnchorHierarchyVM() + : base("", PNLSettings.anchorable_columns) { } + } +} \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLCellAppearanceOverrideVM.cs b/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLCellAppearanceOverrideVM.cs index 3a4048680..7728af705 100644 --- a/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLCellAppearanceOverrideVM.cs +++ b/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLCellAppearanceOverrideVM.cs @@ -1,122 +1,88 @@ -using bts.proto; +using bts.collections; +using bts.proto; +using mbts; +using mbts.spark; using mbts.ui; -using mbts.ui.controls; using mbts.ui.settings; -using mbts.ui.shell; -using mbts.ui.utility.text; +using mbts.ui.viewmodels; +using System; using System.Windows; using System.Windows.Media; -using FontFamily = System.Windows.Media.FontFamily; namespace bts.shell.pnl { - class PNLCellAppearanceOverrideVM : ViewModelBase { - bool - _is_background_overridden, - _is_font_color_overridden, - _is_font_weight_overridden, - _is_font_family_overridden, - _is_font_size_overridden; + class PNLCellAppearanceOverrideVM : ParameterGroupVM { + public PNLCellAppearanceOverrideVM(string display_name, string rule = null) : base(display_name) { + parameters.AddRange(background, font_color, font_weight); + background.can_override = true; + font_color.can_override = true; + font_weight.can_override = true; + } - FontWeight _font_weight_override; - FontFamily _font_family_override; - double _font_size_override = double.NaN; - - // background - public bool is_background_overridden { get => _is_background_overridden; set => Set(ref _is_background_overridden, value); } - public ColorPickerPopupVM background_override { get; } = new ColorPickerPopupVM { - bind_opacity_to_alpha = true, - opacity = 1 - }; - // font color - public bool is_font_color_overridden { get => _is_font_color_overridden; set => Set(ref _is_font_color_overridden, value); } - public ColorPickerPopupVM font_color_override { get; } = new ColorPickerPopupVM(); - // font weight - public bool is_font_weight_overridden { get => _is_font_weight_overridden; set => Set(ref _is_font_weight_overridden, value); } - public FontWeight font_weight_override { get => _font_weight_override; set => Set(ref _font_weight_override, value); } - // font family - public bool is_font_family_overriden { get => _is_font_family_overridden; set => Set(ref _is_font_family_overridden, value); } - public FontFamily font_family_override { get => _font_family_override; set => Set(ref _font_family_override, value); } - // font size - public bool is_font_size_overriden { get => _is_font_size_overridden; set => Set(ref _is_font_size_overridden, value); } - public double font_size_override { get => _font_size_override; set => Set(ref _font_size_override, value); } + public ColorOverrideParameterVM background { get; } = new ColorOverrideParameterVM("Background"); + public ColorOverrideParameterVM font_color { get; } = new ColorOverrideParameterVM("Font Color"); + public FontWeightOverrideParameterVM font_weight { get; } = new FontWeightOverrideParameterVM("Font Weight"); public GridColumnSettings apply_to(GridColumnSettings target) => target.with( - font_weight_override: new NullableFontWeightProto(is_font_weight_overridden ? font_weight_override : (FontWeight?)null), - font_color_override: new NullableColorProto(is_font_color_overridden ? font_color_override.color : (Color?)null), - background_color_override: new NullableColorProto(is_background_overridden ? background_override.color : (Color?)null)); + font_weight_override: new NullableFontWeightProto(font_weight.effective_is_overridden ? font_weight.override_value : (FontWeight?)null), + font_color_override: new NullableColorProto(font_color.effective_is_overridden ? font_color.override_value : (Color?)null), + background_color_override: new NullableColorProto(background.effective_is_overridden ? background.override_value : (Color?)null)); - public void load(GridColumnSettings settings) { - if (settings != null) - load(settings.font_weight_override, settings.font_color_override, settings.background_color_override); + public IDisposable connect_default_values(GridSettingsVM grid_defaults) => + Disposable.Create( + grid_defaults.subscribe_font().Subscribe(v => { + font_weight.family = v.family; + font_weight.default_value = v.weight; + font_weight.size = v.size; + }), + grid_defaults.subscribe_font_color().Subscribe(v => { + font_color.default_value = v; + }), + grid_defaults.subscribe_background().Subscribe(v => { + background.default_value = v; + })); + + public PNLAnimation create(PNLView.Columns col_key) { + var rv = new PNLAnimation { + column = col_key + }; + if (background.effective_is_overridden) + rv.background = background.override_value.rgb_color(); + if (font_color.effective_is_overridden) + rv.foreground = font_color.override_value.rgb_color(); + if (font_weight.effective_is_overridden) + rv.font_weight = font_weight.override_value.ToOpenTypeWeight(); + return rv; } - public void load(FontParamsProto font_params) { - if (font_params == null) - return; + public void load(GridColumnSettings value) { // font weight - is_font_weight_overridden = font_params.font_weight > 0; - if (is_font_weight_overridden) - font_weight_override = FontWeight.FromOpenTypeWeight(font_params.font_weight); + font_weight.is_overridden = value.font_weight_override.HasValue; + if (font_weight.is_overridden) + font_weight.override_value = value.font_weight_override.Value; // font color - is_font_color_overridden = font_params.font_color > 0; - if (is_font_color_overridden) - font_color_override.color = font_params.font_color.rgb_color(); - // font family - if (!string.IsNullOrEmpty(font_params.font_family)) { - font_family_override = new FontFamily(font_params.font_family); - } - if (!double.IsNaN(font_params.font_size) && font_params.font_size > 0) { - font_size_override = font_params.font_size; - } else { - font_size_override = double.NaN; - } - } - - public void load(PNLAnimation animation) { - if (animation != null) - load( - animation.font_weight.HasValue ? FontWeight.FromOpenTypeWeight(animation.font_weight.Value) : (FontWeight?)null, - animation.foreground?.argb_color(), - animation.background?.argb_color()); - } - - public void load(FontWeight? font_weight, Color? font_color, Color? background) { - // font weight - is_font_weight_overridden = font_weight.HasValue; - if (is_font_weight_overridden) - font_weight_override = font_weight.Value; - // font color - is_font_color_overridden = font_color.HasValue; - if (is_font_color_overridden) - font_color_override.color = font_color.Value; + font_color.is_overridden = value.font_color_override.HasValue; + if (font_color.is_overridden) + font_color.override_value = value.font_color_override.Value; // background - is_background_overridden = background.HasValue; - if (background.HasValue) - background_override.color = background.Value; + background.is_overridden = value.background_color_override.HasValue; + if (background.is_overridden) + background.override_value = value.background_color_override.Value; } - public PNLAnimation to_animation(PNLView.Columns key) => - new PNLAnimation { - column = key, - foreground = is_font_color_overridden ? font_color_override.color.rgb_color() : (uint?)null, - background = is_background_overridden ? background_override.color.rgb_color() : (uint?)null, - font_weight = is_font_weight_overridden ? font_weight_override.ToOpenTypeWeight() : (int?)null - }; - - public PNLCellAppearanceProto to_appearance_proto() => - new PNLCellAppearanceProto { - background = is_background_overridden ? background_override.color.rgb_color() : (uint?)null, - font_params = to_font_params() - }; - - public FontParamsProto to_font_params() => - new FontParamsProto { - typeface = new TypefaceProto( - font_family_override?.name(), - is_font_weight_overridden ? font_weight_override.ToOpenTypeWeight() : 0), - font_color = is_font_color_overridden ? font_color_override.color.rgb_color() : 0, - font_size = font_size_override - }; + public void load(PNLAnimation value) { + // font weight + font_weight.is_overridden = value.font_weight.HasValue && value.font_weight.Value > 0; + if (font_weight.is_overridden) + font_weight.override_value = FontWeight.FromOpenTypeWeight(value.font_weight.Value); + // font color + font_color.is_overridden = value.foreground.HasValue; + if (font_color.is_overridden) + font_color.override_value = value.foreground.Value.argb_color(); + // background + background.is_overridden = value.background.HasValue; + if (background.is_overridden) + background.override_value = value.background.Value.argb_color(); + } } } \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLCellAppearanceVM.cs b/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLCellAppearanceVM.cs index 9d692b544..f268da3be 100644 --- a/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLCellAppearanceVM.cs +++ b/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLCellAppearanceVM.cs @@ -1,34 +1,51 @@ -using mbts.ui.controls; -using mbts.ui.shell; -using System.Windows; -using FontFamily = System.Windows.Media.FontFamily; +using bts.collections; +using mbts.ui.viewmodels; namespace bts.shell.pnl { - class PNLCellAppearanceVM : ViewModelBase { - FontWeight _font_weight; - FontFamily _font_family; - double _font_size = double.NaN; + class PNLHeaderRowCellAppearanceVM : ParameterGroupVM { + readonly FontParameterVM _font = new FontParameterVM("Font"); + readonly ColorParameterVM + _background = new ColorParameterVM("Background"), + _font_color = new ColorParameterVM("Font Color"); + readonly BooleanParameterVM + _show_totals = new BooleanParameterVM("Show Totals"), + _show_selected_totals = new BooleanParameterVM("Show Selected Totals"); - public ColorPickerPopupVM background { get; } = new ColorPickerPopupVM { bind_opacity_to_alpha = true, opacity = 1 }; - public ColorPickerPopupVM font_color { get; } = new ColorPickerPopupVM(); - public FontWeight font_weight { get => _font_weight; set => Set(ref _font_weight, value); } - public FontFamily font_family { get => _font_family; set => Set(ref _font_family, value); } - public double font_size { get => _font_size; set => Set(ref _font_size, value); } + public PNLHeaderRowCellAppearanceVM() : base("Header Row Display") { + parameters.AddRange( + HeaderedParameterGroupVM.create("Fonts/Colors", _font, _font_color, _background), + HeaderedParameterGroupVM.create("Display", _show_totals, _show_selected_totals)); + } + + public PNLHeaderRowDisplay display { + get { + var rv = PNLHeaderRowDisplay.None; + if (_show_totals.value) + rv |= PNLHeaderRowDisplay.Total; + if (_show_selected_totals.value) + rv |= PNLHeaderRowDisplay.SelectedTotal; + return rv; + } + set { + _show_totals.value = (display & PNLHeaderRowDisplay.Total) != 0; + _show_selected_totals.value = (display & PNLHeaderRowDisplay.SelectedTotal) != 0; + } + } public PNLCellAppearance to_appearance() => - new PNLCellAppearance(font_color.color, background.color, font_weight, font_family, font_size); + new PNLCellAppearance(_font_color.value, _background.value, _font.weight, _font.family, _font.size); public void load(PNLCellAppearance appearance) { if (appearance.background.HasValue) - background.color = appearance.background.Value; + _background.value = appearance.background.Value; if (appearance.foreground.HasValue) - font_color.color = appearance.foreground.Value; + _font_color.value = appearance.foreground.Value; if (appearance.font_family != null) - font_family = appearance.font_family; + _font.family = appearance.font_family; if (appearance.font_weight.HasValue) - font_weight = appearance.font_weight.Value; + _font.weight = appearance.font_weight.Value; if (appearance.font_size > 0) - font_size = appearance.font_size; + _font.size = appearance.font_size; } } } \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLColumnVM.cs b/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLColumnVM.cs index 1c0183349..81b9cf097 100644 --- a/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLColumnVM.cs +++ b/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLColumnVM.cs @@ -1,133 +1,216 @@ using bts.collections; +using bts.utils; +using mbts; using mbts.spark; using mbts.ui.controls; using mbts.ui.settings; -using mbts.ui.shell; +using mbts.ui.utilities; +using mbts.ui.utility; +using mbts.ui.viewmodels; using mbts.utils; using System; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.ComponentModel; +using System.Collections.Specialized; using System.Linq; using System.Reactive.Linq; -using System.Windows; namespace bts.shell.pnl { - class PNLColumnVM : ViewModelBase, ISimpleColumnVM { - readonly SimpleGridSettingsVM _owner; - readonly PNLView.Columns _pnl_id; - object _selected_item; - string _display_name; - bool _is_visible; - double _width; - HorizontalAlignment _horizontal_alignment; + class PNLModularCellAppearanceVM : TabularParameterGroupVM { + public static PNLModularCellAppearanceVM create(PNLColumnCellAppearanceVM default_cell_appearance, IReadOnlyObservableCollection rules) { + var composite = new ObservableAggregateCollection(new ObservableCollection { default_cell_appearance }); + composite.add_collection(rules); + return new PNLModularCellAppearanceVM(composite) { + selected_item = default_cell_appearance + }; + } - public PNLColumnVM(SimpleGridSettingsVM owner, PNLView.Columns id) { - _owner = owner; - _pnl_id = id; - default_column_vm.PropertyChanged += echo; - void echo(object sender, PropertyChangedEventArgs e) { - switch (e.PropertyName) { - case nameof(is_font_weight_overridden): - case nameof(is_font_color_overridden): - RaisePropertyChanged(e.PropertyName); + PNLModularCellAppearanceVM(ObservableCollection parameters) : base("", parameters) { } + } + + class PNLColumnCellAppearanceVM : ParameterGroupVM { + PNLCellAppearanceOverrideVM _selected_cell_mode; + + public static Rule create_rule(string rule) => + new Rule(rule); + + public PNLColumnCellAppearanceVM(string display_name) : base(display_name) { + parameters.AddRange(default_vm, group_vm, header_vm); + _selected_cell_mode = default_vm; + } + + public PNLCellAppearanceOverrideVM selected_cell_mode { get => _selected_cell_mode; set => Set(ref _selected_cell_mode, value); } + public PNLCellAppearanceOverrideVM default_vm { get; } = new PNLCellAppearanceOverrideVM("Row") { is_expanded = true }; + public PNLCellAppearanceOverrideVM group_vm { get; } = new PNLCellAppearanceOverrideVM("Group Row"); + public PNLCellAppearanceOverrideVM header_vm { get; } = new PNLCellAppearanceOverrideVM("Header Row"); + + IEnumerable _cell_modes { + get { + yield return default_vm; + yield return group_vm; + yield return header_vm; + } + } + + public IDisposable connect_default_values(GridSettingsVM grid_defaults) => + new System.Reactive.Disposables.CompositeDisposable( + _cell_modes.Select(c => c.connect_default_values(grid_defaults))); + + public class Rule : PNLColumnCellAppearanceVM { + public Rule(string rule_text) : base($"When {DisplayNameHelper.expression_snake_to_title_case(rule_text)}") => + this.rule_text = rule_text; + + public string rule_text { get; } + } + } + + class PNLColumnSettingsVM : GridColumnSettingsVM { + readonly ObservableAggregateCollection _cell_appearance_groups = new ObservableAggregateCollection(); + readonly _AutoRuleTabsWrapperVM _fonts_and_colors; + readonly PNLView.Columns _key; + + public PNLColumnSettingsVM(PNLView.Columns key) : base(null) { + _key = key; + _fonts_and_colors = new _AutoRuleTabsWrapperVM("Fonts/Colors", key); + column_layout = new HeaderedParameterGroupVM("Column Layout", new ObservableCollection { + header, width, horizontal_alignment + }); + apply_flags(GridColumnSettingsFeatureFlags.None); + } + + public HeaderedParameterGroupVM column_layout { get; } + public HeaderedParameterGroupVM fonts_and_colors => _fonts_and_colors; + public PNLColumnCellAppearanceVM default_cell_appearance => _fonts_and_colors.cell_appearance; + + IEnumerable _all_cell_modes => + _fonts_and_colors.parameters + .OfType() + .SelectMany(c => c.parameters.OfType()); + + public void load_from(GridColumnSettings value, IReadOnlyDictionary triggers, GridColumnSettings group, IReadOnlyDictionary group_triggers, IReadOnlyDictionary header_triggers, GridColumnSettings header) { + load_from(value); + _fonts_and_colors.load_from(value, triggers, group, group_triggers, header_triggers, header); + } + + public IEnumerable<(string expression, PNLAnimation row, PNLAnimation group, PNLAnimation header)> get_triggers() => + _fonts_and_colors.create(); + + public IDisposable connect_default_values(GridSettingsVM grid_defaults) => + _fonts_and_colors.connect_default_values(grid_defaults); + + public override string ToString() => "Default"; + + public override void sync_params() => + parameters.SetItems(column_layout, fonts_and_colors); + + /// + /// This class stores a instance in a collection of parameters, and automatically replaces it with a when rules are loaded. + /// Conversely, it replaces the with the original instance when rules are unloaded. + /// The impetus: A special 'TabControl' based DataTemplate is defined in PNLSettingsView.xaml as the default for content of type . + /// + class _AutoRuleTabsWrapperVM : HeaderedParameterGroupVM { + public readonly PNLColumnCellAppearanceVM cell_appearance; + + readonly ObservableAggregateCollection _composite_parameters; + readonly ObservableCollection _rules = new ObservableCollection(); + readonly IReadOnlyObservableCollection _wrapped_rules; + readonly DeferrableActionWrapper _sync_params; + PNLModularCellAppearanceVM _cell_appearance_rules; + PNLView.Columns _id; + + public _AutoRuleTabsWrapperVM(string display_name, PNLView.Columns id) + : this(display_name, id, new ObservableAggregateCollection()) { } + + _AutoRuleTabsWrapperVM(string display_name, PNLView.Columns id, ObservableAggregateCollection parameters) : base(display_name, parameters) { + _id = id; + _composite_parameters = parameters; + cell_appearance = new PNLColumnCellAppearanceVM("Default"); + _wrapped_rules = _rules.CastObservable(); + //_wrapped_rules = _rules.SelectObservable(_ => _, obj => (PNLColumnCellAppearanceVM)obj); + // If there are no rules present, the view should display a flat list of font/colors parameters. + // If there are rules present, the view should use TabItems to represent each rule its associated font/color parameters, + // as well as an additional Tab for the 'defaults.' + // It is the responsibility of this class, as the viewmodel, to organize the parameters appropriately. + // Listen to rules.CollectionChanged events, and toggle between the 'flat list of default parameters' and the TabItem groups when rules.Count > 0 changes. + _composite_parameters.add_collection(cell_appearance.parameters); + _composite_parameters.add_collection(_wrapped_rules); + bool rules_present = false; + _sync_params = new DeferrableActionWrapper(sync_params); + _rules.CollectionChanged += (s, e) => _sync_params.execute(); + void sync_params() { + if (rules_present != _rules.Count > 0) { + rules_present = !rules_present; + _composite_parameters.clear_collections(); + if (rules_present) { + if (_cell_appearance_rules == null) { + _cell_appearance_rules = PNLModularCellAppearanceVM.create(cell_appearance, _wrapped_rules); + } + _composite_parameters.insert_collection(0, new ObservableCollection { _cell_appearance_rules }); + } else { + _composite_parameters.insert_collection(0, new ObservableCollection { cell_appearance }); + } + } + } + } + + public IEnumerable<(string rule, PNLAnimation row, PNLAnimation group, PNLAnimation header)> create() => + _rules.Select(r => (r.rule_text, r.default_vm.create(_id), r.group_vm.create(_id), r.header_vm.create(_id))); + + public void load_from(GridColumnSettings value, IReadOnlyDictionary triggers, GridColumnSettings group, IReadOnlyDictionary group_triggers, IReadOnlyDictionary header_triggers, GridColumnSettings header) { + using (_sync_params.defer_execution()) { + _rules.Clear(); + cell_appearance.default_vm.load(value); + cell_appearance.group_vm.load(group); + cell_appearance.header_vm.load(header); + foreach (var kv in triggers) { + var rule_vm = PNLColumnCellAppearanceVM.create_rule(kv.Key); + rule_vm.default_vm.load(kv.Value); + if (group_triggers.TryGetValue(kv.Key, out var g)) { + rule_vm.group_vm.load(g); + } + if (header_triggers.TryGetValue(kv.Key, out var h)) + rule_vm.header_vm.load(h); + _rules.Add(rule_vm); + } + } + } + + GridSettingsVM _grid_defaults; + + public IDisposable connect_default_values(GridSettingsVM grid_defaults) { + Log.assert(_grid_defaults == null && grid_defaults != null); + if (_rules.Count > 0) { } + _grid_defaults = grid_defaults; + _rules.CollectionChanged += _wtf; + _wtf(_rules, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); + return Disposable.Create( + cell_appearance.connect_default_values(grid_defaults), + ObservableAutoWrapper.connect_item_hooks(_rules, r => r.connect_default_values(grid_defaults)), + ObservableAutoWrapper.connect_item_hooks(parameters, + obj => { + if (obj is PNLColumnCellAppearanceVM cell_app) { + return cell_app.connect_default_values(grid_defaults); + } else if (obj is PNLCellAppearanceOverrideVM cell_app_over) { + return cell_app_over.connect_default_values(grid_defaults); + } + return null; + })); + } + + private void _wtf(object sender, NotifyCollectionChangedEventArgs e) { + if (_rules.Count > 0) { + } + switch (e.Action) { + case NotifyCollectionChangedAction.Reset: + break; + case NotifyCollectionChangedAction.Add: + break; + case NotifyCollectionChangedAction.Remove: + break; + default: break; } } } - - public PNLCellAppearanceOverrideVM default_column_vm { get; } = new PNLCellAppearanceOverrideVM(); - public PNLCellAppearanceOverrideVM group_column_vm { get; } = new PNLCellAppearanceOverrideVM(); - public PNLCellAppearanceOverrideVM header_column_vm { get; } = new PNLCellAppearanceOverrideVM(); - // - public ObservableCollection rule_columns { get; } = new ObservableCollection(); - - public object selected_item { - get => _selected_item; - set { - if (value != null) - Set(ref _selected_item, value); - } - } - - public string id { get => _pnl_id.ToString(); set => Log.assert(value == _pnl_id.ToString()); } - public string display_name { get => _display_name; set => Set(ref _display_name, value); } - public double width { get => _width; set => Set(ref _width, value); } - public bool is_visible { get => _is_visible; set => Set(ref _is_visible, value); } - public bool is_font_color_overridden { - get => default_column_vm.is_font_color_overridden; - set => default_column_vm.is_font_color_overridden = value; - } - public HorizontalAlignment horizontal_alignment { get => _horizontal_alignment; set => Set(ref _horizontal_alignment, value); } - - public ColorPickerPopupVM font_color_override => default_column_vm.font_color_override; - - public bool is_font_weight_overridden { get => default_column_vm.is_font_weight_overridden; set => default_column_vm.is_font_weight_overridden = value; } - public FontWeight font_weight_override { get => default_column_vm.font_weight_override; set => default_column_vm.font_weight_override = value; } - - public void apply_flags(GridColumnSettingsFeatureFlags flags) { } - - public GridColumnSettings create() { - var result = new GridColumnSettings(id: id, display_name: display_name, is_visible: is_visible, horizontal_alignment: horizontal_alignment, width: width); - result = default_column_vm.apply_to(result); - return result; - } - - public void load_from(GridColumnSettings value) { - _assert_id(value.id); - default_column_vm.load(value); - display_name = value.display_name; - width = value.width; - is_visible = value.is_visible; - horizontal_alignment = value.horizontal_alignment; - } - - public void load_from(GridColumnSettings value, IReadOnlyDictionary triggers, GridColumnSettings group, IReadOnlyDictionary group_triggers, IReadOnlyDictionary header_triggers, GridColumnSettings header) { - _assert_id(value.id); - load_from(value); - if (group != null) - group_column_vm.load(group); - if (header != null) - header_column_vm.load(header); - rule_columns.SetItems(triggers.Select(kv => { - var rule_col = new PNLRuleColumnVM(kv.Key); - rule_col.load_from(kv.Value, group_triggers.GetValueOrDefault(kv.Key), header_triggers.GetValueOrDefault(kv.Key)); - return rule_col; - })); - } - - public IEnumerable<(string expression, PNLAnimation row, PNLAnimation group, PNLAnimation header)> get_triggers() { - foreach (var col in rule_columns) - yield return (col.rule_text, col.row_params.to_animation(_pnl_id), col.group_params.to_animation(_pnl_id), col.header_params.to_animation(_pnl_id)); - } - - void _assert_id(string id) => - Log.assert(id == _pnl_id.ToString(), $"PNLColumn id string '{id}' does not match the expected {typeof(PNLView.Columns)} key '{_pnl_id}.'"); - - public override string ToString() => "Default"; - } - - class PNLRuleColumnVM : ViewModelBase, IEquatable { - public PNLRuleColumnVM(string rule_text) => - this.rule_text = rule_text; - - public string rule_text { get; } - - public PNLCellAppearanceOverrideVM row_params { get; } = new PNLCellAppearanceOverrideVM(); - public PNLCellAppearanceOverrideVM group_params { get; } = new PNLCellAppearanceOverrideVM(); - public PNLCellAppearanceOverrideVM header_params { get; } = new PNLCellAppearanceOverrideVM(); - - public void load_from(PNLAnimation row, PNLAnimation group, PNLAnimation header) { - row_params.load(row); - group_params.load(group); - header_params.load(header); - } - - public bool Equals(PNLRuleColumnVM other) => - other != null && rule_text == other.rule_text; - - public override bool Equals(object obj) => Equals(obj as PNLRuleColumnVM); - public override int GetHashCode() => rule_text.GetHashCode(); - public override string ToString() => rule_text; } } \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLGroupRowAppearanceVM.cs b/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLGroupRowAppearanceVM.cs index 8c5bcaf8b..7e40fbe8e 100644 --- a/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLGroupRowAppearanceVM.cs +++ b/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLGroupRowAppearanceVM.cs @@ -1,58 +1,60 @@ using bts.collections; -using mbts.spark; -using mbts.ui; -using mbts.ui.controls; -using mbts.ui.shell; +using bts.utils; +using mbts.ui.utility; +using mbts.ui.viewmodels; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Windows; -using System.Windows.Input; +using System.Linq; using System.Windows.Media; -using FontFamily = System.Windows.Media.FontFamily; namespace bts.shell.pnl { - class PNLGroupRowAppearanceVM : ViewModelBase, IValueFactory<(PNLCellAppearance appearance, IReadOnlyList background_colors)> { - FontWeight _font_weight; - FontFamily _font_family; - double _font_size = double.NaN; + class PNLGroupRowCellAppearanceVM : ParameterGroupVM { + readonly PNLAlternatingRowBackgroundVM _alternating_background_vm = new PNLAlternatingRowBackgroundVM(); + readonly ColorParameterVM _font_color = new ColorParameterVM("Font Color"); + readonly FontParameterVM _font = new FontParameterVM("Font"); - public PNLGroupRowAppearanceVM() { - add_background_cmd = new DelegateCommand(_add_background); - // 4 elements is enough to alternate through any reasonable number of groups, - // and clicking to add new backgrounds seems awkward - for (int i = 0; i < 4; i++) - _add_background(); + public PNLGroupRowCellAppearanceVM() : base("Group") { + parameters.AddRange( + new HeaderedParameterGroupVM("Fonts/Colors", new ObservableCollection { _font, _font_color }), + _alternating_background_vm); } - public ObservableCollection background_colors { get; } = new ObservableCollection(); - public ColorPickerPopupVM font_color { get; } = new ColorPickerPopupVM(); - public FontWeight font_weight { get => _font_weight; set => Set(ref _font_weight, value); } - public FontFamily font_family { get => _font_family; set => Set(ref _font_family, value); } - public double font_size { get => _font_size; set => Set(ref _font_size, value); } - public ICommand add_background_cmd { get; } + ObservableCollection _alternating_backgrounds => _alternating_background_vm.items; - public (PNLCellAppearance appearance, IReadOnlyList background_colors) create() => - (new PNLCellAppearance(font_color.color, Colors.Transparent, font_weight, font_family, font_size), - background_colors.WrapSelectorRO(cp => cp.color)); + public (PNLCellAppearance appearance, IReadOnlyList alternating_backgrounds) create() => + (new PNLCellAppearance(_font_color.value, Colors.Transparent, _font.weight, _font.family, _font.size), + _alternating_backgrounds.Cast().Select(vm => vm.value).ToList()); - public void load_from((PNLCellAppearance appearance, IReadOnlyList background_colors) value) { - var (app, bg_colors) = value; - // background colors - while (background_colors.Count < bg_colors.Count) - _add_background(); - for (int i = 0; i < bg_colors.Count; i++) - background_colors[i].color = bg_colors[i]; - // - if (app.foreground.HasValue) font_color.color = app.foreground.Value; - if (app.font_family != null) font_family = app.font_family; - if (app.font_weight.HasValue) font_weight = app.font_weight.Value; - if (app.font_size > 0) font_size = app.font_size; + public void load((PNLCellAppearance appearance, IReadOnlyList alternating_backgrounds) value) { + var (appearance, alternating_backgrounds) = value; + for (int i = 0; i < alternating_backgrounds.Count; i++) { + if (_alternating_backgrounds.Count > i) { + var vm = _alternating_backgrounds[i]; + vm.value = alternating_backgrounds[i]; + } + } + while (alternating_backgrounds.Count > _alternating_backgrounds.Count) + _alternating_backgrounds.Add(new ColorParameterVM($"Background {_alternating_backgrounds.Count}") { + value = alternating_backgrounds[_alternating_backgrounds.Count] + }); + while (_alternating_backgrounds.Count > alternating_backgrounds.Count) + _alternating_backgrounds.RemoveAt(alternating_backgrounds.Count); + CollectionHelper.add_or_update_existing(_alternating_backgrounds, alternating_backgrounds, c => new ColorParameterVM("") { value = c }, (vm, c) => ((ColorParameterVM)vm).value = c); + if (appearance.foreground.HasValue) + _font_color.value = appearance.foreground.Value; + if (appearance.font_family != null) + _font.family = appearance.font_family; + if (appearance.font_weight.HasValue) + _font.weight = appearance.font_weight.Value; + if (appearance.font_size > 0) + _font.size = appearance.font_size; } + } - void _add_background() => - background_colors.Add(new NamedColorPickerPopupVM { - bind_opacity_to_alpha = true, - name = $"Background {background_colors.Count + 1}" - }); + class PNLAlternatingRowBackgroundVM : HeaderedParameterGroupVM { + public PNLAlternatingRowBackgroundVM() : base("Alternating Backgrounds") => + ObservableAutoWrapper.connect(items, parameters, c => c); + + public ObservableCollection items { get; } = new ObservableCollection(); } } \ No newline at end of file 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..21c5c22b2 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,145 @@ -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(); +using bts.collections; +using mbts; +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.Linq; +using ColumnKeys = bts.shell.pnl.PNLView.Columns; + +namespace bts.shell.pnl { + class PNLSettingsVM : DisposableViewModelBase, IWindowSettingsVM, IValueFactory, IObservable, ITemplateSelectorKey { + PNLCalculationType _calculation_type; + PNLSettings _last_loaded; + + public PNLSettingsVM(PNLSettings settings) { + core_settings_vm = new GridSettingsVM(); + columns = core_settings_vm.columns.CastObservable(); + load(settings); + _dispose = ObservableAutoWrapper.connect_item_hooks(columns, col => col.connect_default_values(core_settings_vm)); + } + + public PNLAnchorHierarchyVM anchor_hierarcy { get; } = new PNLAnchorHierarchyVM(); + public GridSettingsVM core_settings_vm { get; } + public PNLGroupRowCellAppearanceVM group_row_defaults { get; } = new PNLGroupRowCellAppearanceVM(); + public PNLHeaderRowCellAppearanceVM header_row_defaults { get; } = new PNLHeaderRowCellAppearanceVM(); + 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 IReadOnlyObservableCollection columns { get; } + 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.get_result(); // 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]); - } + int anchor_index = anchor_hierarcy.value.indexOf(key); + if (anchor_index != i && anchor_index >= 0) { + new_cols.Value.RemoveAt(i); + new_cols.Value.Insert(anchor_index, s.grid.columns[i]); } - } - // 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); - } - } + } + // rule-based animations + var trigger_anims = columns + .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_hierarcy.value, + grid: new_cols.IsValueCreated ? s.grid.with(columns: new_cols.Value) : null, + group_columns: columns.Select(c => { + var col_settings = c.create(); + col_settings = c.default_cell_appearance.group_vm.apply_to(col_settings); + return col_settings; + }), + header_columns: columns.Select(c => { + var col_settings = c.create(); + col_settings = c.default_cell_appearance.header_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_defaults.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((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(value.grid, false); + using (core_settings_vm.begin_change_columns()) { + core_settings_vm.columns.SetItems(value.grid.columns.Select(c => { + var key = EnumHelper.parse(c.id); + var vm = new PNLColumnSettingsVM(key); + var (col_settings, trigger_animations) = column_map[key]; + var group_data = group_column_map.GetNullable(key); + var header_data = header_column_map.GetNullable(key); + vm.load_from(col_settings, trigger_animations, group_data?.settings, group_data?.triggers, header_data?.triggers, header_data?.settings); + return vm; + })); + } + anchor_hierarcy.value = value.anchors.Intersect(PNLSettings.anchorable_columns); + header_row_defaults.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; + } + } } \ 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 ffef9f99f..4520f70c4 100644 --- a/src/client/spark/Modules/Trading/PNL/VM/PNLVM.cs +++ b/src/client/spark/Modules/Trading/PNL/VM/PNLVM.cs @@ -291,7 +291,7 @@ namespace bts.shell.pnl { }; public void load_from(PNLSettings settings) { - selection_highlight = settings.grid.selection_highlight.to_brush(); + selection_highlight = settings.grid.selection_highlight.to_argb_brush(); grid_background_color = settings.grid.background; calculation_type = settings.calculation_type; if (settings.filters != null) { diff --git a/src/client/spark/Modules/Trading/PNL/View/PNLSettingsView.xaml b/src/client/spark/Modules/Trading/PNL/View/PNLSettingsView.xaml new file mode 100644 index 000000000..624317393 --- /dev/null +++ b/src/client/spark/Modules/Trading/PNL/View/PNLSettingsView.xaml @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Check the groups you would like to use. + + + + Drag and drop them to change the grouping order. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/Modules/Trading/PNL/View/PNLSettingsView.xaml.cs b/src/client/spark/Modules/Trading/PNL/View/PNLSettingsView.xaml.cs new file mode 100644 index 000000000..25f2efaef --- /dev/null +++ b/src/client/spark/Modules/Trading/PNL/View/PNLSettingsView.xaml.cs @@ -0,0 +1,129 @@ +using bts; +using mbts.ui.controls.adorners; +using mbts.ui.extensions; +using mbts.utils; +using System; +using System.Collections; +using System.Reactive.Disposables; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Media; + +namespace mbts.ui.spark { + /// + /// Interaction logic for PNLSettingsView.xaml + /// + partial class PNLSettingsView : UserControl { + public PNLSettingsView() => + InitializeComponent(); + + IDisposable _anchor_items_drag_drop_behavior; + + void _anchor_items_loaded(object sender, RoutedEventArgs e) { + // connecting this drag/drop behavior is idempotent, just in case Loaded happens twice + Disposable.dispose(ref _anchor_items_drag_drop_behavior); + if (!(sender is ItemsControl ic)) + return; + var root_grid = Window.GetWindow(ic)?.Content as Grid; + bool is_dragging = false; + IDisposable drag_op = null; + var cursor_resources = new Lazy(); + _anchor_items_drag_drop_behavior = Disposable.Create(() => Disposable.dispose(ref drag_op)); + DragDropHelper.subscribe_drag_start(ic).Subscribe(pt => { + if (!is_dragging && + ic.InputHitTest(pt) is DependencyObject d && + ic.ContainerFromElement(d) is FrameworkElement item_view && + ic.ItemContainerGenerator.ItemFromContainer(item_view) is object item && + item != DependencyProperty.UnsetValue) { + // + item_view.SetCurrentValue(OpacityProperty, 0.5); + is_dragging = true; + var sz = item_view.RenderSize; + var dv = new DrawingVisual(); + using (var dc = dv.RenderOpen()) + dc.DrawRoundedRectangle(new VisualBrush(item_view) { Stretch = Stretch.Uniform }, null, new Rect(sz), 0, 0); + SetCurrentValue(CursorProperty, Cursors.ScrollWE); + SetCurrentValue(AllowDropProperty, true); + is_dragging = true; + Disposable.replace(ref drag_op, new CompositeDisposable { + MouseTraceAdorner.trace_drag(root_grid, dv, sz), + DragDropHelper.connect_vertical_insertion_adorner(ic, root_grid), + this.SubscribePreviewDrop(on_drop), + this.SubscribePreviewMouseUp(on_preview_mouse_up), + this.SubscribePreviewDragOver(on_drag), + this.SubscribePreviewDragLeave(on_drag), + this.SubscribePreviewDragEnter(on_drag), + () => { + ClearValue(CursorProperty); + ClearValue(AllowDropProperty); + item_view.ClearValue(OpacityProperty); + is_dragging = false; + }}); + DragDrop.DoDragDrop(this, new DataObject(DataFormats.StringFormat, item), DragDropEffects.Move); + } + }); + + void on_drag(object s, DragEventArgs de) => + de.Effects = DragDropEffects.Move; + + void on_drop(object _, DragEventArgs drop_e) { + drop_e.Handled = true; + if (!is_dragging) + return; + Disposable.dispose(ref drag_op); + if (drop_e.Data.GetDataPresent(DataFormats.StringFormat) && + drop_e.Data.GetData(DataFormats.StringFormat) is object from && + ic.ItemsSource is IList anchor_items && + anchor_items.Count > 1) { + // + var pt = drop_e.GetPosition(this); + if (!(InputHitTest(pt) is DependencyObject hit)) + return; + try { + int from_i = anchor_items.IndexOf(from); + // Set the container to the first item who's right edge is left of pt.X (or the last item if none satisfy that condition). + // The logic presumes that the items are laid out in a single, horizontal line, from left to right + // (not the most elegant way to get the drop target, but it's effective). + int to_i = -1; + if (!(ic.ContainerFromElement(hit) is FrameworkElement drop_target)) { + for (to_i = 0; to_i < ic.Items.Count; to_i++) { + if (ic.ItemContainerGenerator.ContainerFromIndex(to_i) is FrameworkElement c) { + drop_target = c; + var tl = c.TranslatePoint(new Point(0, 0), this); + var bottom_edge = tl.Y + c.ActualHeight; + if (bottom_edge >= pt.Y) + break; + } + } + } else if (drop_target.DataContext is object to) { + to_i = anchor_items.IndexOf(to); + var drop_target_pt = TranslatePoint(pt, drop_target); + if (drop_target_pt.Y > drop_target.ActualHeight / 2) { + // target is "Between drop_target and the item below it" + if (from_i > to_i) + to_i++; + } else { + // target is "Between drop_target and the item above it" + if (from_i < to_i) { + to_i--; + } + } + } + if (to_i < 0) + return; + if (to_i >= anchor_items.Count) + to_i = anchor_items.Count - 1; + if (from_i >= 0) + anchor_items.Move(from_i, to_i); + } catch (Exception ex) { + Log.Ui.warn($"Error dropping anchor hiearchy item in pnl settings dialog: {ex}."); + } + } + } + + void on_preview_mouse_up(object _, MouseButtonEventArgs __) => + Disposable.dispose(ref drag_op); + } + } +} \ No newline at end of file diff --git a/src/client/spark/core/Utility/ViewModelBase.cs b/src/client/spark/core/Utility/ViewModelBase.cs index 90f16328c..be1743ad9 100644 --- a/src/client/spark/core/Utility/ViewModelBase.cs +++ b/src/client/spark/core/Utility/ViewModelBase.cs @@ -79,6 +79,15 @@ namespace mbts.ui.shell { // ensure notifications will be in on the same thread as IProperty.Subscribe (don't use .Select extension) Observable.Create(o => property.Subscribe(ch => o.OnNext(ch.newval))); + public static IObservable SubscribeValue(this IProperty property, bool start_immediately) => + start_immediately ? + // ensure notifications will be in on the same thread as IProperty.Subscribe (don't use .Select extension) + Observable.Create(o => { + o.OnNext(property.Value); + return property.Subscribe(ch => o.OnNext(ch.newval)); + }) : + SubscribeValue(property); + //public static IDisposable S public static IProperty block_reentrancy(this IProperty source) => diff --git a/src/client/spark/view/Controls/DIYGrid/Settings/GridColumnSettingsVM.cs b/src/client/spark/view/Controls/DIYGrid/Settings/GridColumnSettingsVM.cs index cea55a03c..c5a6dd4e6 100644 --- a/src/client/spark/view/Controls/DIYGrid/Settings/GridColumnSettingsVM.cs +++ b/src/client/spark/view/Controls/DIYGrid/Settings/GridColumnSettingsVM.cs @@ -31,10 +31,14 @@ namespace mbts.spark { string _id = string.Empty; GridColumnSettings _settings; - public GridColumnSettingsVM() { + public GridColumnSettingsVM() + : this(GridColumnSettingsFeatureFlags.None) { } + + protected GridColumnSettingsVM(GridColumnSettingsFeatureFlags? init_flags) { if (font_color.override_value.A == 0) font_color.set_override(font_color.override_value.with(255)); - apply_flags(GridColumnSettingsFeatureFlags.None); + if (init_flags.HasValue) + apply_flags(init_flags.Value); } public string id { get => _id; private set => Set(ref _id, value); } diff --git a/src/client/spark/view/Controls/DIYGrid/Settings/GridSettingsResources.xaml b/src/client/spark/view/Controls/DIYGrid/Settings/GridSettingsResources.xaml index df341ced3..6c2f77ea4 100644 --- a/src/client/spark/view/Controls/DIYGrid/Settings/GridSettingsResources.xaml +++ b/src/client/spark/view/Controls/DIYGrid/Settings/GridSettingsResources.xaml @@ -557,6 +557,39 @@ + + + + + + + + + + + + + + + diff --git a/src/client/spark/view/Controls/DIYGrid/Settings/GridSettingsVM.cs b/src/client/spark/view/Controls/DIYGrid/Settings/GridSettingsVM.cs index 8dd50a510..76d2d777c 100644 --- a/src/client/spark/view/Controls/DIYGrid/Settings/GridSettingsVM.cs +++ b/src/client/spark/view/Controls/DIYGrid/Settings/GridSettingsVM.cs @@ -115,14 +115,23 @@ namespace mbts.spark { IEnumerable _visible_parameters { get { - yield return _selection_highlight; + var fonts_and_colors = HeaderedParameterGroupVM.create("Fonts/Colors", _font_vm, _font_color); if (_background_enabled) - yield return _background; - yield return _font_vm; - yield return _font_color; + fonts_and_colors.parameters.Add(_background); + fonts_and_colors.parameters.Add(_selection_highlight); + yield return fonts_and_colors; } } + public IDisposable begin_change_columns() { + var curr_col_id = current_column?.id; + return Disposable.Create(() => { + if (curr_col_id == null || !columns.TryGetFirst(c => c.id == curr_col_id, out var curr_column)) + curr_column = columns.FirstOrDefault(); + _current_column.set(curr_column); + }); + } + public GridSettings get_result() { var col_settings = new List(); foreach (var c in columns) { @@ -140,7 +149,10 @@ namespace mbts.spark { enable_background_color: _background_enabled); } - public void load(GridSettings settings) { + public void load(GridSettings settings) => + load(settings, true); + + public void load(GridSettings settings, bool sync_columns) { _font_vm.family = new FontFamily(settings.font_family); _font_vm.weight = settings.font_weight; _font_vm.size = settings.font_size; @@ -152,22 +164,30 @@ namespace mbts.spark { // assuming bind_opacity_to_alpha on the picker. _background_enabled = settings.enable_background_color; _background.value = settings.background; - - var curr_col_id = current_column?.id; - columns.SetItems(settings.columns.Select(col => { - var vm = new GridColumnSettingsVM(); - vm.load_from(col); - // reapply our favorite column flags - // this comes in handy when performing Load From Factory - the editor will contain - // a consistent view of what can be overridden and what cannot - if (_column_flags.TryGetValue(vm.id, out GridColumnSettingsFeatureFlags flags)) - vm.apply_flags(flags); - return vm; - })); - if (curr_col_id == null || !columns.TryGetFirst(c => c.id == curr_col_id, out var curr_column)) - curr_column = columns.FirstOrDefault(); - _current_column.set(curr_column); + if (sync_columns) { + using (begin_change_columns()) { + columns.SetItems(settings.columns.Select(col => { + var vm = new GridColumnSettingsVM(); + vm.load_from(col); + // reapply our favorite column flags + // this comes in handy when performing Load From Factory - the editor will contain + // a consistent view of what can be overridden and what cannot + if (_column_flags.TryGetValue(vm.id, out GridColumnSettingsFeatureFlags flags)) + vm.apply_flags(flags); + return vm; + })); + } + } _parameters.sync_with(_visible_parameters); } + + public IObservable subscribe_background() => + _background.SubscribeValue(true); + + public IObservable subscribe_font_color() => + _font_color.SubscribeValue(true); + + public IObservable<(FontFamily family, FontWeight weight, double size)> subscribe_font() => + _font_vm.SubscribeValue(true); } } \ No newline at end of file diff --git a/src/client/spark/view/Converters/Numeric/IntAdditionConverter.cs b/src/client/spark/view/Converters/Numeric/IntAdditionConverter.cs new file mode 100644 index 000000000..b89ffcc0d --- /dev/null +++ b/src/client/spark/view/Converters/Numeric/IntAdditionConverter.cs @@ -0,0 +1,24 @@ +using System; +using System.Globalization; +using System.Windows.Controls; +using System.Windows.Data; + +namespace mbts.ui.converters { + [ValueConversion(typeof(int), typeof(int))] + class IntAdditionConverter : IValueConverter { + public int Value { get; set; } + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { + if (value is int i) + return i + Value; + return new ValidationResult(false, "Not an integer."); + } + + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { + if (value is int i) + return i - Value; + return new ValidationResult(false, "Not an integer."); + } + } +} \ No newline at end of file diff --git a/src/client/spark/view/Shell/Settings/ShellSettingsDialog.xaml b/src/client/spark/view/Shell/Settings/ShellSettingsDialog.xaml index 9c312b139..cedf60ea4 100644 --- a/src/client/spark/view/Shell/Settings/ShellSettingsDialog.xaml +++ b/src/client/spark/view/Shell/Settings/ShellSettingsDialog.xaml @@ -4,7 +4,6 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ice="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options" xmlns:orderbook="clr-namespace:bts.shell.orderbook" - xmlns:pnl="clr-namespace:bts.shell.pnl" xmlns:u="clr-namespace:mbts.ui" xmlns:c="clr-namespace:mbts.ui.controls" xmlns:cv="clr-namespace:mbts.ui.converters" @@ -99,62 +98,6 @@ - - - - - - - - - - - - - - - Font - - Font Color (default) - - Background - - - - - - - - - - - - - - - - - - - Font - - Font Color (default) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Font - - Font Color (default) - - Selection Highlight - - Background - - - - - - - - - - - - - - - - - - - - - - Display - - - - - - - - - - - - - - - Calculation - - - - - - - - - - - + diff --git a/src/client/spark/view/Shell/Settings/ShellSettingsDialog.xaml.cs b/src/client/spark/view/Shell/Settings/ShellSettingsDialog.xaml.cs index 46a6714ac..dd8448cbb 100644 --- a/src/client/spark/view/Shell/Settings/ShellSettingsDialog.xaml.cs +++ b/src/client/spark/view/Shell/Settings/ShellSettingsDialog.xaml.cs @@ -1,14 +1,4 @@ -using bts.shell.pnl; -using mbts.utils; -using mbts.ui.extensions; -using System; -using System.Collections.ObjectModel; -using System.Reactive.Disposables; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Input; -using System.Windows.Media; -using mbts.ui.controls.adorners; +using System.Windows; namespace mbts.ui.spark { /// @@ -24,102 +14,6 @@ namespace mbts.ui.spark { LocalProfileItemTemplateKey = "LocalProfileItemTemplate", SaveAsStyleKey = "SaveAsStyle", SecurityMapKey = "SecurityMap"; - - #region PNL - // TODO: need to break up ShellSettingsDialog components into smaller parts, so the various settings dialogs can be more easily customized. - // Until then, certain esoteric behaviors for specific dialogs (e.g., pnl anchor items drag/drop behavior) will reside in this class. - IDisposable _pnl_anchor_items_drag_drop_behavior; - - void _pnl_anchor_items_loaded(object sender, RoutedEventArgs e) { - // connecting this drag/drop behavior is idempotent, just in case Loaded happens twice - Disposable.dispose(ref _pnl_anchor_items_drag_drop_behavior); - if (!(sender is ItemsControl ic)) - return; - bool is_dragging = false; - IDisposable drag_op = null; - var cursor_resources = new Lazy(); - _pnl_anchor_items_drag_drop_behavior = Disposable.Create(() => Disposable.dispose(ref drag_op)); - DragDropHelper.subscribe_drag_start(ic).Subscribe(pt => { - if (!is_dragging && - ic.InputHitTest(pt) is DependencyObject d && - ic.ContainerFromElement(d) is FrameworkElement item_view && - ic.ItemContainerGenerator.ItemFromContainer(item_view) is object item && - item != DependencyProperty.UnsetValue) { - // - item_view.SetCurrentValue(OpacityProperty, 0.5); - is_dragging = true; - var sz = item_view.RenderSize; - var dv = new DrawingVisual(); - using (var dc = dv.RenderOpen()) - dc.DrawRoundedRectangle(new VisualBrush(item_view) { Stretch = Stretch.Uniform }, null, new Rect(sz), 0, 0); - SetCurrentValue(CursorProperty, Cursors.ScrollWE); - SetCurrentValue(AllowDropProperty, true); - is_dragging = true; - Disposable.replace(ref drag_op, new CompositeDisposable { - MouseTraceAdorner.trace_drag(root_grid, dv, sz), - DragDropHelper.connect_horizontal_insertion_adorner(ic, root_grid), - this.SubscribePreviewDrop(on_drop), - this.SubscribePreviewMouseUp(on_preview_mouse_up), - this.SubscribePreviewDragOver(on_drag), - this.SubscribePreviewDragLeave(on_drag), - this.SubscribePreviewDragEnter(on_drag), - () => { - ClearValue(CursorProperty); - ClearValue(AllowDropProperty); - item_view.ClearValue(OpacityProperty); - is_dragging = false; - }}); - DragDrop.DoDragDrop(this, new DataObject(DataFormats.StringFormat, item), DragDropEffects.Move); - } - }); - - void on_drag(object s, DragEventArgs de) => - de.Effects = DragDropEffects.Move; - - void on_drop(object _, DragEventArgs drop_e) { - drop_e.Handled = true; - if (!is_dragging) - return; - Disposable.dispose(ref drag_op); - if (drop_e.Data.GetDataPresent(DataFormats.StringFormat) && - drop_e.Data.GetData(DataFormats.StringFormat) is PNLSettingsVM.AnchorItemVM from && - ic.ItemsSource is ObservableCollection anchor_items && - anchor_items.Count > 1) { - // - var pt = drop_e.GetPosition(this); - if (!(InputHitTest(pt) is DependencyObject hit)) - return; - int from_i = anchor_items.IndexOf(from); - // Set the container to the first item who's right edge is left of pt.X (or the last item if none satisfy that condition). - // The logic presumes that the items are laid out in a single, horizontal line, from left to right - // (not the most elegant way to get the drop target, but it's effective). - int to_i = -1; - if (!(ic.ContainerFromElement(hit) is FrameworkElement drop_target)) { - for (to_i = 0; to_i < ic.Items.Count; to_i++) { - if (ic.ItemContainerGenerator.ContainerFromIndex(to_i) is FrameworkElement c) { - drop_target = c; - var tl = c.TranslatePoint(new Point(0, 0), this); - var right_edge = tl.X + c.ActualWidth; - if (right_edge >= pt.X) - break; - } - } - } else if (drop_target.DataContext is PNLSettingsVM.AnchorItemVM to) { - to_i = anchor_items.IndexOf(to); - } - if (to_i < 0) - return; - if (to_i >= anchor_items.Count) - to_i = anchor_items.Count - 1; - if (from_i >= 0) - anchor_items.Move(from_i, to_i); - } - } - - void on_preview_mouse_up(object _, MouseButtonEventArgs __) => - Disposable.dispose(ref drag_op); - } - #endregion } static class GridSettingsTemplateKeys { diff --git a/src/client/spark/view/Utility/DisplayNameHelper.cs b/src/client/spark/view/Utility/DisplayNameHelper.cs index 77b9804ff..bf295f678 100644 --- a/src/client/spark/view/Utility/DisplayNameHelper.cs +++ b/src/client/spark/view/Utility/DisplayNameHelper.cs @@ -24,6 +24,9 @@ namespace mbts.ui.utilities { SnakeToTitleCaseConverter = ValueConverter.create(obj => snake_to_title_case(obj?.ToString())), ExpressionSnakeToTitleCaseConverter = ValueConverter.create(obj => snake_to_title_case(obj?.ToString(), @"[A-Za-z0-9_\-\s\(\)<>=]*")); + public static string expression_snake_to_title_case(string expression, TextCapitalizationFormat capitalization_format = TextCapitalizationFormat.Default) => + snake_to_title_case(expression, @"[A-Za-z0-9_\-\s\(\)<>=]*"); + // Adds spaces to CamelCase => "Camel Case" public static string camel_to_title_case(string name, TextCapitalizationFormat capitalization_format = TextCapitalizationFormat.Default) { if (name != null) { diff --git a/src/client/spark/view/Utility/EnumHelper.cs b/src/client/spark/view/Utility/EnumHelper.cs index 7829ce3e0..e0c981fad 100644 --- a/src/client/spark/view/Utility/EnumHelper.cs +++ b/src/client/spark/view/Utility/EnumHelper.cs @@ -24,6 +24,19 @@ namespace mbts.ui.utility { return Enum.GetValues(t); } + // TODO: avoid boxing + public static T add_flags(T value, T flags) where T : struct { + var v = (long)(object)value; + var f = (long)(object)flags; + return (T)(object)(v | f); + } + + public static T remove_flags(T value, T flags) where T : struct { + var v = (long)(object)value; + var f = (long)(object)flags; + return (T)(object)((v ^ f) & v); + } + public static T parse(string name) where T : struct /*(Enum, more specifically)*/ { if (!typeof(T).IsEnum) throw new InvalidOperationException($"{typeof(T)} is not an enum type."); if (!Enum.TryParse(name, true, out T result)) throw new ArgumentException(nameof(name), "Does not match any of the values"); diff --git a/src/client/spark/view/ViewModels/ItemOrderParameterVM.cs b/src/client/spark/view/ViewModels/ItemOrderParameterVM.cs new file mode 100644 index 000000000..345bd2f73 --- /dev/null +++ b/src/client/spark/view/ViewModels/ItemOrderParameterVM.cs @@ -0,0 +1,122 @@ +using bts.collections; +using bts.utils; +using mbts.collections; +using mbts.ui.shell; +using mbts.ui.utility; +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Linq; + +namespace mbts.ui.viewmodels { + class OrderedItemParameterVM : BooleanParameterVM { + int _index, _checked_index; + + public OrderedItemParameterVM(string name) : base(name) { } + + public int index { + get => _index; + set => Set(ref _index, value); + } + + public int checked_index { + get => _checked_index; + set => Set(ref _checked_index, value); + } + } + + class ItemOrderParameterVM : ParameterVM>, IDisposable { + readonly ObservableList _items = new ObservableList(); + //readonly IReadOnlyObservableCollection _checked_items; + readonly IList _wrapped_keys; + readonly DeferrableActionWrapper _refresh_indices, _refresh_value, _load_value; + IDisposable _dispose; + + public ItemOrderParameterVM(string name) + : base(name) { } + + public ItemOrderParameterVM(string name, IEnumerable items) + : this(name, items, EqualityComparer.Default) { } + + public ItemOrderParameterVM(string name, IEnumerable available_items, IEqualityComparer comparer) + : base(name) { + _wrapped_keys = _items.WrapSelector(item => item.key, k => new Item(k)); + _wrapped_keys.AddRange(available_items); + //_checked_items = ObservableFilterCollection.create(_items, item => item.value); + _refresh_indices = new DeferrableActionWrapper(refresh_indices); + _refresh_value = new DeferrableActionWrapper(refresh_value); + _load_value = new DeferrableActionWrapper(load_value); + // If this class is ever used with large collections, + // the 'refresh_indices' method may need to be optimized. + // It is naturally an O(n) op, but execution could be throttled. + refresh_indices(); + _dispose = Disposable.Create( + ObservableAutoWrapper.connect_item_hooks(items, + item => item.SubscribeValue().Subscribe(_ => _refresh_indices.execute())), + items.Subscribe((s, e) => _refresh_indices.execute())); + // + void refresh_indices() { + int checked_index = 0; + for (int i = 0; i < items.Count; i++) { + items[i].index = i; + items[i].checked_index = checked_index; + if (items[i].value) + checked_index++; + } + } + + void refresh_value() { + using (_refresh_value.supress_execution()) + value = _checked_keys.ToList(); + } + + void load_value() { + using (_load_value.supress_execution()) + using (_refresh_indices.defer_execution()) { + foreach (var v in _items) + v.value = false; + int i = 0; + foreach (var v in value) { + int curr_pos = _wrapped_keys.IndexOf(v); + if (curr_pos >= 0) { + _items[curr_pos].value = true; + if (curr_pos != i) + _items.Move(curr_pos, i++); + } + } + } + } + } + + public IReadOnlyObservableCollection items => _items; + + IEnumerable _checked_keys => + _items.Where(i => i.value).Select(i => i.key); + + public void Dispose() => + Disposable.dispose(ref _dispose); + + protected override void on_changed_end(IEnumerable oldval, IEnumerable newval) => + _load_value.execute(); + + public class Item : OrderedItemParameterVM, IEquatable { + public Item(T key) : base(EnumHelper.get_display_name(key)) => + this.key = key; + + public T key { get; } + + public bool Equals(Item other) => + other != null && + EqualityComparer.Default.Equals(key, other.key); + + public override bool Equals(object obj) => + Equals(obj as Item); + + public override int GetHashCode() => + key.GetHashCode(); + + public override string ToString() => + EnumHelper.get_display_name(key); + } + } +} \ No newline at end of file