diff --git a/src/client/spark/Daemons/OrderTicketDaemon.cs b/src/client/spark/Daemons/OrderTicketDaemon.cs index 84e473c46..cf18c0835 100644 --- a/src/client/spark/Daemons/OrderTicketDaemon.cs +++ b/src/client/spark/Daemons/OrderTicketDaemon.cs @@ -11,6 +11,7 @@ using System.Collections.Generic; using System.ComponentModel.Composition; using System.Reactive.Linq; using System.Windows; +using LadderSettings = mbts.spark.LadderSettings; namespace bts.shell { [Export(typeof(IShellDaemon))] @@ -48,14 +49,14 @@ namespace bts.shell { void _show_order_ticket(SecurityMD smd) => _show_order_window(new OrderTicket { DataContext = new NewOrderTicketVM(_model, smd, - Observable.Return(_model.factory.default_ladder_settings(smd.security))) + Observable.Return(LadderSettings.Default)) }); void _show_order_ticket((OrderDefinitionImmutable def, double price, uint size) ops) { if (_md_map.TryGetValue(ops.def.SecurityKey, out SecurityMD smd)) _show_order_window(new OrderTicket { DataContext = new NewOrderTicketVM(_model, smd, ops.def, ops.price, ops.size, - Observable.Return(_model.factory.default_ladder_settings(smd.security).calculator_buttons)) + Observable.Return(LadderSettings.Default.calculator_buttons)) }); } @@ -66,7 +67,7 @@ namespace bts.shell { _show_order_window(new OrderModificationDialog { DataContext = new ExistingOrderTicketVM(_model, Observable.Return((md,ori.order)), - Observable.Return(_model.factory.default_ladder_settings(ori.sec.Value).calculator_buttons) + Observable.Return(LadderSettings.Default.calculator_buttons) ) }); } diff --git a/src/client/spark/Images/Icons.cs b/src/client/spark/Images/Icons.cs index dcc11df03..3cc17164d 100644 --- a/src/client/spark/Images/Icons.cs +++ b/src/client/spark/Images/Icons.cs @@ -24,6 +24,7 @@ namespace mbts.ui { AddFileThinGeometryKey = nameof(AddFileThinGeometryKey), AttachAlgosKey = nameof(AttachAlgosKey), CheckMarkGeometryKey = nameof(CheckMarkGeometryKey), + CopyWFGeometryKey = nameof(CopyWFGeometryKey), DataEditGeometryKey = nameof(DataEditGeometryKey), DetachAlgosKey = nameof(DetachAlgosKey), DiskGeometryKey = nameof(DiskGeometryKey), @@ -147,6 +148,7 @@ namespace mbts.ui { public static ImageSource ModifyOrder { get { return load_resource_and_freeze("ModifyOrder"); } } public static ImageSource CheckMark => create_icon(CheckMarkGeometryKey); public static ImageSource Clock { get { return load_resource_and_freeze("Clock"); } } + public static ImageSource CopyWF => create_icon(CopyWFGeometryKey); public static ImageSource DataEdit => create_icon(DataEditGeometryKey, Brushes.White, new Pen(Brushes.Black, 1).frozen()); public static ImageSource Defrag { get { return load_resource_and_freeze("Defrag"); } } public static ImageSource DetachAlgos => create_icon_and_rotate(DetachAlgosKey, Brushes.Red); diff --git a/src/client/spark/Images/Vector/Icons.xaml b/src/client/spark/Images/Vector/Icons.xaml index e5c29b5e4..a0ce61363 100644 --- a/src/client/spark/Images/Vector/Icons.xaml +++ b/src/client/spark/Images/Vector/Icons.xaml @@ -48,6 +48,10 @@ + + M14.733902,12.084991L9.751783,17.388992 12.982842,17.436005C13.569886,17.462997 14.5229,17.350998 14.876848,17.005005 14.954852,16.929993 15.031879,16.824005 15.02486,16.593002 14.986895,15.457993 14.838883,13.438004 14.733902,12.084991z M22.507753,11.134453C22.480678,11.134323,22.467085,11.135494,22.469961,11.136993L20.64694,11.145004 16.291904,11.192993C16.388891,12.405991 16.596901,15.100998 16.647928,16.539001 16.668924,17.177994 16.448888,17.742004 16.007904,18.168991 15.210897,18.947998 13.893864,19.065002 13.179865,19.065002L9.2818066,19.005005 9.3258129,25.522003 9.3728109,25.528 9.3278271,25.882996 9.3317944,26.395996 9.3107983,26.397995C9.3167797,26.789993,9.3378369,27.552994,9.3958212,29.065994L9.4068075,29.393005C9.4207855,29.819992 9.5648295,29.994995 9.6707884,30.089005 9.9807898,30.365997 10.539817,30.390991 10.717799,30.369003L10.717799,30.375C10.88284,30.354996 11.280855,30.356003 12.823844,30.365997 13.867863,30.371002 15.206869,30.376999 16.594886,30.376999 20.757965,30.376999 23.270998,30.354996 23.862007,30.311005 24.454971,30.268005 24.661029,29.154999 24.690021,28.729996 24.690021,28.729996 24.677997,27.876999 24.661029,26.582993 24.612016,22.671005 24.51198,14.697998 24.472002,12.802002 24.461013,12.302994 24.316969,11.929993 24.034008,11.662003 23.547475,11.200003 22.697284,11.13536 22.507753,11.134453z M8.8867823,2.8410034L2.5417312,10.296997 6.4037791,10.356995C6.8917614,10.390991 8.3258005,10.341003 8.9567896,9.7299957 9.1738335,9.5189972 9.2667919,9.2659912 9.2558046,8.9089966 9.2067934,7.3889923 9.0258213,4.7480011 8.8867823,2.8410034z M10.424826,1.6239929C10.551842,3.302002 10.816799,6.951004 10.876797,8.8560028 10.903836,9.6750031 10.636804,10.360992 10.083818,10.897995 9.0667769,11.882004 7.3527657,11.987991 6.6627546,11.987991 6.4657918,11.987991 6.3367616,11.979004 6.3177796,11.977005L1.6477377,11.905991C1.6387044,14.278992 1.6236895,20.283997 1.6496909,22.358994 1.651705,22.569992 1.6437093,22.780991 1.6366904,22.992004 1.6117265,23.593994 1.5926833,24.112991 1.8537338,24.386002 2.0716933,24.612991 2.6497034,24.886002 4.1457549,24.886002 6.0127832,24.886002 7.0867711,24.876999 7.6967641,24.867004L7.6457993,17.259995 14.853899,9.5849915 16.681924,9.5650024 16.681924,9.5429993 19.454908,9.5289917 19.406934,2.6210022C19.323925,2.3549957,18.960945,1.6239929,17.387928,1.6239929z M9.1738335,0L17.387928,0C19.94692,0,20.874971,1.5299988,21.022983,2.4329987L21.077976,9.5209961 22.446951,9.5139923C22.43395,9.5130005 24.031017,9.4250031 25.148035,10.481995 25.753999,11.054001 26.071996,11.822998 26.092992,12.766998 26.142006,15.065994 26.281044,26.268997 26.307047,28.412003L26.311014,28.764999C26.279029,29.817993 25.750032,31.802002 23.979013,31.931 23.342958,31.977005 20.887972,32 16.683878,32 13.798893,32 11.107818,31.988998 10.808803,31.987991 10.789821,31.990997 9.5147806,32.112 8.6008288,31.309006 8.0858074,30.854996 7.8107797,30.229004 7.7838017,29.444992L7.7728153,29.126999C7.721789,27.759995 7.6978022,26.970993 7.6898061,26.490005 7.0547882,26.5 5.9867817,26.509003 4.1457549,26.509003 2.4377257,26.509003 1.3387128,26.192001 0.68367504,25.509003 -0.055286743,24.742004 -0.017322397,23.742004 0.012707477,22.938004 0.020702986,22.744003 0.028698692,22.559998 0.026684528,22.378998 -0.00029337304,20.240997 0.016674615,13.856995 0.026684528,11.212997L0.026684528,10.867004 0.14167619,10.610992 8.7147823,0.54100037 8.7088009,0.45899963 8.8018194,0.43800354z + + M10.830011,12.05L13.334007,12.05 13.334007,16.535997 17.819998,16.535997 17.819998,19.03902 13.334007,19.03902 13.334007,23.525016 10.830988,23.525016 10.830988,19.03902 6.3460046,19.03902 6.3449975,16.53499 10.830988,16.535997z M2.2799975,2.4149805L2.2799975,29.580015 22.121998,29.580015 22.121998,8.500008 15.83599,8.500008 15.83599,2.4149805z M0,0L15.83599,0 17.125998,0 22.681996,5.439977 24.407,7.125007 24.407,32.000001 0,32.000001z diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs b/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs index 10d875227..a9652edcf 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs @@ -144,7 +144,7 @@ namespace mbts.spark { SparkCommands.change_securities_command(() => (update_securities_cmd, _state.security_criteria)), // wrap the grid settings view factory in a dialogCommand here since the vm is destroyed/recreated when the security criteria changes SparkCommands.window_settings_command(new DialogCommand(() => { - var vm = new WindowSettingsDialogVM( + var vm = new ShellSettingsDialogVM( _settings_manager, us => us.market_view_grid, UserSettings.FileExtensions.GRID, @@ -156,7 +156,7 @@ namespace mbts.spark { ) ); // TODO: bind to main window's Title - var dialog = new SimpleGridSettingsDialog { Title = "Market View Grid Settings", DataContext = vm }; + var dialog = new ShellSettingsDialog { Title = "Market View Grid Settings", DataContext = vm }; vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog); return dialog; })) diff --git a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs index b075d16ef..8ab059534 100644 --- a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs +++ b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs @@ -70,7 +70,7 @@ namespace mbts.spark { SparkCommands.change_securities_command(() => (update_securities_cmd, _state.security_criteria)), // wrap the grid settings view factory in a dialogCommand here since the vm is destroyed/recreated when the security criteria changes SparkCommands.window_settings_command(new DialogCommand(() => { - var vm = new WindowSettingsDialogVM( + var vm = new ShellSettingsDialogVM( _settings_manager, s => s.time_and_sales_grid, UserSettings.FileExtensions.GRID, @@ -82,7 +82,7 @@ namespace mbts.spark { ) ); // TODO: bind to main window's Title - var dialog = new SimpleGridSettingsDialog { Title = "Time and Sales Grid Settings", DataContext = vm }; + var dialog = new ShellSettingsDialog { Title = "Time and Sales Grid Settings", DataContext = vm }; vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog); return dialog; })) diff --git a/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs b/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs index 86d656b3e..6cfa693d2 100644 --- a/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs +++ b/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs @@ -75,7 +75,7 @@ namespace mbts.spark { }; return ob_settings; }), SparkCommands.window_settings_command(new DialogCommand(() => { - var vm = new WindowSettingsDialogVM( + var vm = new ShellSettingsDialogVM( _settings_manager, us => us.synthetic_management_grid, UserSettings.FileExtensions.GRID, @@ -87,7 +87,7 @@ namespace mbts.spark { ) ); // TODO: bind to main window's Title - var dialog = new SimpleGridSettingsDialog { Title = "Synthetic Management Grid Settings", DataContext = vm }; + var dialog = new ShellSettingsDialog { Title = "Synthetic Management Grid Settings", DataContext = vm }; vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog); return dialog; })) diff --git a/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoKey.cs b/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoKey.cs index f063fb01c..e7b16bc26 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoKey.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoKey.cs @@ -1,6 +1,7 @@ using bts.api.orderman; using bts.persist.algo; using bts.utils; +using mbts.ui.utility; using ProtoBuf; using System; using System.Linq; @@ -38,26 +39,34 @@ namespace mbts.spark { _persisted_key = persisted_key; } - public static AlgoID from_order_def(OrderDefinitionImmutable order_def) { - switch (order_def.CustomDef.CustomCase) { - case CustomOrderDefinition.CustomOneofCase.Composite: return new AlgoID(order_def.CustomDef.Composite.AlgoTemplateKey); - case CustomOrderDefinition.CustomOneofCase.Dynamic: return new AlgoID(order_def.CustomDef.Dynamic.DynamicOrderType); - default: return new AlgoID(order_def.CustomDef.CustomCase); + public static AlgoID from_custom_def(CustomOrderDefinitionImmutable custom_def) { + switch (custom_def.CustomCase) { + case CustomOrderDefinition.CustomOneofCase.Composite: return new AlgoID(custom_def.Composite.AlgoTemplateKey); + case CustomOrderDefinition.CustomOneofCase.Dynamic: return new AlgoID(custom_def.Dynamic.DynamicOrderType); + default: return new AlgoID(custom_def.CustomCase); } } - public static AlgoID from_algo_key(AlgoKey key) { + public static AlgoID from_algo_key(AlgoKey key, IMaskIndexInt32 dynamic_type_index) { switch (key.mode) { case AlgoKey.Mode.Factory: - if (key.factory.structure.structure.Count > 0) - return new AlgoID((CustomOrderDefinition.CustomOneofCase)key.factory.structure.structure[0]); - break; + return AlgoStructureSerializer.to_algo_id(key.factory.structure, dynamic_type_index); case AlgoKey.Mode.Persisted: return new AlgoID(key.persisted.id_uint); } return new AlgoID(CustomOrderDefinition.CustomOneofCase.None); } + public static AlgoKey to_algo_key(AlgoID id, IMaskIndexInt32 dynamic_type_index) { + if (id._factory_key.HasValue) + return new AlgoKey(id._factory_key.Value); + if (id._persisted_key.HasValue) + return new AlgoKey(new AlgoPersistedKey(id._persisted_key.Value)); + if (id._dynamic_key != null) + return new AlgoKey(new AlgoNameStructureKey(id._dynamic_key, AlgoStructureSerializer.structure_key(dynamic_type_index.to_int(id._dynamic_key)))); + return default; + } + public bool Equals(AlgoID other) => _factory_key == other._factory_key && _dynamic_key == other._dynamic_key && diff --git a/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStructureKey.cs b/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStructureKey.cs index 95c1c9110..5b4bd573f 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStructureKey.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStructureKey.cs @@ -73,6 +73,9 @@ namespace mbts.spark { public static CustomOrderDefinition.CustomOneofCase order_type(this AlgoStructureKey structure_key) => structure_key.structure.Count > 0 ? (CustomOrderDefinition.CustomOneofCase)structure_key.structure[0] : CustomOrderDefinition.CustomOneofCase.None; + public static AlgoStructureKey structure_key(int dynamic_type) => + new AlgoStructureKey(new[] { dynamic_type | _dynamic_mask }); + public static AlgoStructureKey structure_key(CustomOrderDefinitionImmutable algo, IMaskIndexInt32 dynamic_type_index) => new AlgoStructureKey(to_array(algo, dynamic_type_index)); @@ -103,6 +106,13 @@ namespace mbts.spark { return mdef; } + public static AlgoID to_algo_id(AlgoStructureKey key, IMaskIndexInt32 dynamic_type_index) { + if (key.structure.Count == 0) + return new AlgoID(CustomOrderDefinition.CustomOneofCase.None); + int i = key.structure[0]; + return BitHelper.remove_flags(ref i, _dynamic_mask) ? new AlgoID(dynamic_type_index.from_int(i)) : new AlgoID((CustomOrderDefinition.CustomOneofCase)i); + } + static void _build_structure(CustomOrderDefinition algo, ref int[] structure, IMaskIndexInt32 dynamic_type_index) { if (structure == null || structure.Length == 0) structure = new int[1]; diff --git a/src/client/spark/Modules/Trading/Fills/FillsWindow.cs b/src/client/spark/Modules/Trading/Fills/FillsWindow.cs index 9c4e93dab..20c36e90d 100644 --- a/src/client/spark/Modules/Trading/Fills/FillsWindow.cs +++ b/src/client/spark/Modules/Trading/Fills/FillsWindow.cs @@ -60,7 +60,7 @@ namespace mbts.spark { _commands = new List { // wrap the grid settings view factory in a dialogCommand here since the vm is destroyed/recreated when the security criteria changes SparkCommands.window_settings_command(new DialogCommand(() => { - var vm = new WindowSettingsDialogVM( + var vm = new ShellSettingsDialogVM( _settings_manager, us => us.fills_grid, UserSettings.FileExtensions.GRID, @@ -72,7 +72,7 @@ namespace mbts.spark { ) ); // TODO: bind to main window's Title - var dialog = new SimpleGridSettingsDialog { Title = $"{window_type_name} Grid Settings", DataContext = vm }; + var dialog = new ShellSettingsDialog { Title = $"{window_type_name} Grid Settings", DataContext = vm }; vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog); return dialog; })) diff --git a/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs b/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs index e20468abe..abe7111fa 100644 --- a/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs +++ b/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs @@ -286,8 +286,8 @@ namespace mbts.spark { volume_column = VolumeColumnSettings.Default, calculator_buttons = new[] { 1, 5, 10, 25, 50, 100 }, scroll_bar_visible = false, - default_order_type = CustomOrderDefinition.CustomOneofCase.Limit, default_time_in_force = TimeInForce.Day, + default_algo = new AlgoID(CustomOrderDefinition.CustomOneofCase.Limit), animate_recenter = true, badge_style = BadgeStyle.Normal, bid_break_line = new LadderMarketBreakLine { color = 0, show = true }, @@ -362,6 +362,10 @@ namespace mbts.spark { public bool scroll_bar_visible { get; set; } // USED [ProtoMember(11)] // USED [ProtoMember(12)] + [ProtoMember(51)] + public uint default_account { get; set; } + [ProtoMember(52)] + public AlgoID default_algo { get; set; } [ProtoMember(13)] public CustomOrderDefinition.CustomOneofCase default_order_type { get; set; } [ProtoMember(14)] @@ -372,6 +376,8 @@ namespace mbts.spark { public bool animate_recenter { get; set; } = true; [ProtoMember(17)] public BadgeStyle badge_style { get; set; } + [ProtoMember(53)] + public bool auto_clear { get; set; } [ProtoMember(18)] public LadderMarketBreakLine bid_break_line { get; set; } @@ -467,11 +473,13 @@ namespace mbts.spark { piq_column.safe_equals(other.piq_column) && calculator_buttons.safe_equals(other.calculator_buttons, (a, b) => a.SequenceEqual(b)) && scroll_bar_visible == other.scroll_bar_visible && - default_order_type == other.default_order_type && + default_account == other.default_account && + default_algo == other.default_algo && default_time_in_force == other.default_time_in_force && size == other.size && animate_recenter == other.animate_recenter && badge_style == other.badge_style && + auto_clear == other.auto_clear && bid_break_line.safe_equals(other.bid_break_line) && ask_break_line.safe_equals(other.ask_break_line) && mid_break_line.safe_equals(other.mid_break_line) && @@ -520,7 +528,6 @@ namespace mbts.spark { EqualityComparer.safe_get_hash_code(piq_column), EqualityComparer.safe_get_hash_code(calculator_buttons), scroll_bar_visible.GetHashCode(), - default_order_type.GetHashCode(), default_time_in_force.GetHashCode(), size.GetHashCode(), animate_recenter.GetHashCode(), diff --git a/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs b/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs index 6f3e43c41..507a736a8 100644 --- a/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs +++ b/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs @@ -4,13 +4,16 @@ using mbts; using mbts.config; using mbts.persist; using mbts.spark; +using mbts.spark.utilities; using mbts.ui; using mbts.ui.spark; using ProtoBuf; using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Linq; using System.Reactive.Linq; +using System.Reactive.Subjects; using System.Threading; using System.Threading.Tasks; using System.Windows; @@ -52,37 +55,175 @@ namespace bts.shell { public async override Task load(LadderSaveState state) { await Wait.until_true(() => _securities.ContainsKey(state.security_key), _ladder_conf.security_timeout); if (_securities.TryGetValue(state.security_key, out SecurityMD security)) { - return create_ladder_window(security, state.settings); + return create_ladder_window(security, state.settings, state.settings_id); } return null; } - static LadderSaveState _get_state(LadderVM vm) => - new LadderSaveState { security_key = vm.security.Id, settings = vm.get_save_state() }; + LadderSaveState _get_state(LadderVM vm, uint id) { + LadderSettings s = vm.get_save_state(); + if (id != 0) { + if (!_settings_hub.current.ladder_profiles.TryGetFirst(lp => lp.id == id, out var result)) { + // profile was deleted + id = 0; + } else { + var curr_profile = _fit_to_sec(result.value, vm.security.ContractCase); + if (!s.Equals(curr_profile)) { + // ladder's settings diverged from the profile (this happens when the user changes settings outside of the settings dialog, such as column widths, left panel width, etc.) + id = 0; + } + } + } + return new LadderSaveState { security_key = vm.security.Id, settings = s, settings_id = id }; + } int _ladder_count = 0; - IShellWindow create_ladder_window(SecurityMD md, LadderSettings state_settings) { - var id = Interlocked.Increment(ref _ladder_count) % Environment.ProcessorCount; + IShellWindow create_ladder_window(SecurityMD md, LadderSettings state_settings, uint settings_id = 0) { + IDisposable active_settings_dialog = null; + var thread_id = Interlocked.Increment(ref _ladder_count) % Environment.ProcessorCount; var view = new Lazy(() => { + // resources var model = new LadderModel(md, _orders_model, _mbo); - var settings_manager = new WindowSettingsManager( - _settings_hub, state_settings == null || state_settings.use_defaults ? null : state_settings, - us => sanitize_ladder_settings(us.ladder), - (us, v) => us.with(sanitize_ladder_settings(v))); - var init = state_settings ?? settings_manager.default_settings; - init.use_defaults |= state_settings == null; - var vm = LadderVM.create(_bus, model, settings_manager, init); + var profile_service = new SettingsProfileService(_settings_hub, + us => ImmutableDictionary>.Empty.AddRange(us.ladder_profiles.ToDictionary( + lp => lp.id, + lp => new SettingsProfile(lp.id, lp.name, sanitize_ladder_settings(lp.value), lp.security_criteria))), + (us, lps) => us.with(ladder_profiles: lps.Values.Select(lp => new LadderSettingsProfile(lp.id, lp.name, lp.value, lp.security_criteria)).ToArray())); + LadderSettings last_value = fit_to_sec(state_settings); + var settings_subject = new BehaviorSubject(last_value); + // vm + var vm = LadderVM.create(_bus, model, last_value ?? _settings_hub.current.ladder, settings_subject.Where(s => s != null)); vm.order_properties_vm.open_algo_popup_on_select = _ladder_conf.open_algo_popup_on_select; vm.order_properties_vm.use_algo_param_grid = _ladder_conf.use_algo_param_grid; + vm.request_settings_dialog += open_settings_dialog; + bool initialized = false; + var settings_subscription = _settings_hub.subscribe_default_settings().Subscribe(on_user_settings); + vm.OnDisposed += disposing => { + Disposable.dispose(ref active_settings_dialog); + Disposable.dispose(ref settings_subject); + }; + // view var lv = new LadderView(vm); foreach (var kv in AlgoStudioModelUtils.get_dynamic_resources(vm.model.order_gateway.algo_model.ui_configuration)) lv.Resources[kv.Key] = kv.Value; return lv; + // local methods + LadderSettings fit_to_sec(LadderSettings s) => + _fit_to_sec(s, md.security.ContractCase); + + void on_user_settings(UserSettings us) { + if (initialized) { + if (settings_id == 0) { + // not on a profile, don't respond to default settings changes + return; + } else if (us.ladder_profiles.TryGetFirst(p => p.id == settings_id, out var profile)) { + if (!last_value.Equals(vm.get_save_state())) { + settings_id = 0; + } else { + settings_subject.OnNext(last_value = fit_to_sec(profile.value)); + } + } else { + // profile was deleted; keep the current settings and switch to the 'Local' profile. + settings_id = 0; + } + } else if (_settings_hub.initialized) { + initialized = true; + if (settings_id != 0) { + if (us.ladder_profiles.TryGetFirst(p => p.id == settings_id, out var profile)) { + last_value = fit_to_sec(profile.value); + } else { + settings_id = 0; + } + } + if (settings_id == 0 && last_value == null) { + foreach (var lp in _settings_hub.current.ladder_profiles) { + // TODO: Use a kind of 'match priority' to resolve conflicts when the security is included in more than 1 profile's security criteria. + // In the meantime, simply use the first match. + if (lp.security_criteria.includes(md.security)) { + last_value = fit_to_sec(lp.value); + settings_id = lp.id; + break; + } + } + if (last_value == null) + last_value = fit_to_sec(_settings_hub.current.ladder); + } + settings_subject.OnNext(last_value); + } + } + + void open_settings_dialog() { + // dialog vm + var dialog_vm = new ProfiledShellSettingsDialogVM( + profile_service, + us => us.ladder ?? LadderSettings.Default, + s => { + var svm = new LadderSettingsVM(model.order_gateway, vm.security); + svm.load(s); + return svm; + }, + fit_to_sec, + vm.get_save_state(), + UserSettings.FileExtensions.LADDER, + settings_id); + dialog_vm.applied += apply; + // dialog + var dialog = new ShellSettingsDialog { + DataContext = dialog_vm, + Title = $"Ladder Settings - '{vm.security}'" + }; + dialog.Resources[ShellSettingsDialog.SecurityMapKey] = _securities; + dialog_vm.RequestClose += on_request_close; + dialog.Closed += on_closed; + Disposable.replace(ref active_settings_dialog, Disposable.Create(destroy_all)); + dialog.move_to_mouse(-500, -500); + dialog.Show(); + // local methods + void apply(SettingsProfile profile) { + settings_id = profile.id; + last_value = profile.value; + settings_subject.OnNext(profile.value); + } + // idempotent + void destroy_all() { + destroy_window(); + destroy_vm(); + } + // idempotent + void destroy_window() { + if (dialog == null) return; + try { + var temp = dialog; + dialog = null; + temp.Closed -= on_closed; + temp.Close(); + } catch (Exception ex) { + on_error("closing window", ex); + } + } + // idempotent + void destroy_vm() { + if (dialog_vm == null) return; + try { + var temp = dialog_vm; + dialog_vm = null; + temp.applied -= apply; + temp.RequestClose -= on_request_close; + temp.Dispose(); + } catch (Exception ex) { + on_error("disposing vm", ex); + } + } + void on_closed(object sender, EventArgs e) => destroy_all(); + void on_request_close(object sender, EventArgs e) => destroy_all(); + void on_error(string action_desc, Exception error) => + Log.Ui.warn($"LadderSettingsDialog error {action_desc}: {error}."); + } }); - string thread = _ladder_conf.ladders_on_threads ? $"Ladder{id:00}" : ""; + string thread = _ladder_conf.ladders_on_threads ? $"Ladder{thread_id:00}" : ""; return ShellWindow.create( module, md.security.ToString(), _window_type, view, - (v,s) => save(_get_state(((LadderView)v).vm), s), + (v,s) => save(_get_state(((LadderView)v).vm, settings_id), s), icon: Icons.Ladder, thread_id: thread); // if there are new props, make sure they are not null, invalid, etc. @@ -125,26 +266,19 @@ namespace bts.shell { } } - // TODO: whenever we re-implement the linked ladder, need to add some field to the LadderSaveState to indicate the owning window - //void show_linked(IObservable keystream) { - // var view = new LadderView(); - // IDisposable sub = null; - // var window = - // ShellWindow.create(module, "loading", view, - // Disposable.Create(() => { - // (view.DataContext as LadderVM)?.Dispose(); - // sub?.Dispose(); - // }), s => { - // var vm = view.DataContext as LadderVM; - // if (vm != null) save(_get_state(vm), s); - // }, Icons.Ladder); - // sub = - // keystream - // .Select(smd => new LadderVM(_bus, new LadderModel(smd, _orders_model), - // Observable.Return(_orders_model.factory.default_ladder_settings(smd.security))) - // ).Aggregate((old, vm) => { old.Dispose(); return vm; }) - // .Subscribe(vm => { view.DataContext = vm; window.Title = vm.security.ToString(); }); - //} + LadderSettings _fit_to_sec(LadderSettings s, Security.ContractOneofCase sec_type) { + if (s == null) return null; + var algo_key = AlgoID.to_algo_key(s.default_algo, _orders_model.dynamic_helper.dynamic_type_index); + if (algo_key.mode == AlgoKey.Mode.Factory) { + var fitted_algo = OrderDataHelper.fit_to_type(algo_key.factory.structure.build_algo(_orders_model.dynamic_helper), sec_type); + if (fitted_algo.HasValue) { + // be sure to clone ('s' may be shared) + s = SparkUtils.clone_proto(s); + s.default_algo = AlgoID.from_custom_def(fitted_algo.Value); + } + } + return s; + } readonly struct LadderConfig { public readonly uint max_open_ladders; @@ -167,5 +301,7 @@ namespace bts.shell { public UInt32 security_key; [ProtoMember(2)] public mbts.spark.LadderSettings settings; + [ProtoMember(3)] + public uint settings_id; } } \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs index e1c33486b..83077c7e2 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs @@ -1,4 +1,6 @@ -using bts.api; +using bts; +using bts.api; +using bts.api.orderman; using bts.collections; using bts.utils; using mbts.collections; @@ -8,10 +10,14 @@ using mbts.ui.controls.color_picker; 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.ComponentModel; using System.Linq; +using System.Reactive.Disposables; using System.Reactive.Linq; using System.Windows; using System.Windows.Input; @@ -19,12 +25,22 @@ using System.Windows.Media; using TextUtils = mbts.ui.utility.text.TextUtils; namespace mbts.spark { - class LadderSettingsVM : ViewModelBase, IWindowSettingsVM, ITemplateSelectorKey, IDisposable { + class LadderSettingsVM : DisposableViewModelBase, IWindowSettingsVM, IValueFactory, IObservable, ITemplateSelectorKey { readonly Property _badge_style; readonly Property _alternate_order_size; readonly DelegateProperty _row_height; + readonly UserProperty _default_account; + readonly UserProperty _default_algo; + readonly DeferrableActionWrapper _update; + readonly ObservableKeyedCollection _accounts = new ObservableKeyedCollection(AccountTuple.nullable_key_fn); + readonly ObservableKeyedCollection _algo_definitions = new ObservableKeyedCollection(d => d.key); + readonly OrdersModel _model; + uint? _desired_account; + AlgoID? _desired_algo; + TimeInForce _default_time_in_force; LadderSettings.NetChangeTerms _price_format; - Func _get_order_entry_panel_width, _get_zoom_factor; + double _order_entry_panel_width, _zoom_factor; + bool _auto_clear; LadderSettings _current; LadderColumnSettingsVM _orders = new OrdersColumnSettingsVM(), @@ -61,16 +77,17 @@ namespace mbts.spark { _cancel_sells_visibility = new OrderEntryPanelItemVisibilityVM("Cancel Sells"), _cancel_all_visibility = new OrderEntryPanelItemVisibilityVM("Cancel All"); - public LadderSettingsVM(OrdersModel model, bool is_synthetic, Func get_left_panel_width, Func get_zoom_factor) { - this.is_synthetic = is_synthetic; - favorite_algos_vm = new FavoriteAlgosVM(model); + public LadderSettingsVM(OrdersModel model, SecurityImmutable security) { + _model = model; + is_synthetic = security.ContractCase == Security.ContractOneofCase.Synthetic; + favorite_algos_vm = new FavoriteAlgosVM(_algo_definitions); size_presets = new ObservableEditableCollection>(_create_size_preset_vm); size_presets.CollectionChanged += (s, e) => RaisePropertyChanged(nameof(size_presets_text)); _badge_style = backing(nameof(badge_style)); _badge_style.Changed += _badge_style_Changed; _alternate_order_size = backing(nameof(alternate_order_size)); - _get_order_entry_panel_width = get_left_panel_width; - _get_zoom_factor = get_zoom_factor; + _default_account = user_backing(nameof(default_account)); + _default_algo = user_backing(nameof(default_algo)); // be sure to initialize backings before this measure_row_height call _row_height = backing(nameof(row_height), () => LadderRender.measure_row_height(get_result())); _orders.font_size_changed += on_font_size_changed; @@ -79,10 +96,47 @@ namespace mbts.spark { _ask.font_size_changed += on_font_size_changed; _last.font_size_changed += on_font_size_changed; _piq.font_size_changed += on_font_size_changed; - + // accounts + accounts_view = new ListCollectionView(_accounts) { + CustomSort = Comparer.Default.to_nullable().to_non_generic() + }; + // update + _update = new DeferrableActionWrapper(() => result_changed?.Invoke()); + foreach (var c in _observable_components) + c.PropertyChanged += on_prop_changed; + favorite_algos_vm.items.CollectionChanged += on_favorite_algo_items_CollectionChanged; + _algo_definitions.AddRange(_model.factory.default_algos(security).Values.Select(algo_factory)); + _dispose = new CompositeDisposable( + _model.factory.subscribe_accounts().OnDispatcher().Subscribe(acc_map => { + _accounts.SyncWithDictionary(MappedDictionary.create(acc_map, account_factory)); + _try_select_desired_account(); + }), + ObservableAutoWrapper.connect_item_hooks(favorite_algos_vm.items, connect_favorite_algo), + _model.algo_model.definitions.OnDispatcher().Subscribe(update => { + AlgoCollectionHelper.update_persisted_definitions(_algo_definitions, update, algo_factory); + _try_select_desired_algo(); + }) + ) { dispose_resources }; + // local methods void on_font_size_changed(double oldval, double newval) => _row_height.refresh(); + void on_prop_changed(object sender, PropertyChangedEventArgs e) => _update.execute(); + void on_favorite_algo_items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) => _update.execute(); + IDisposable connect_favorite_algo(FavoriteAlgoItem item) { + item.PropertyChanged += on_prop_changed; + return Disposable.Create(() => item.PropertyChanged -= on_prop_changed); + } + void dispose_resources() { + favorite_algos_vm.items.CollectionChanged -= on_favorite_algo_items_CollectionChanged; + favorite_algos_vm.Dispose(); + foreach (var c in _observable_components) + c.PropertyChanged -= on_prop_changed; + } + AccountTuple? account_factory(KeyValuePair kv) => new AccountTuple(kv.Key, kv.Value); + AlgoDefinitionVM algo_factory(AlgoData data) => AlgoDefinitionVM.create(_model, data, false); } + public event Action result_changed; + private void _badge_style_Changed(LadderSettings.BadgeStyle oldval, LadderSettings.BadgeStyle newval) { if (newval == LadderSettings.BadgeStyle.Alternate && _orders.font_size == 10) { _orders.font_size = 7; @@ -103,8 +157,23 @@ namespace mbts.spark { } public MarketSizeDisplayVM size_display { get; } = new MarketSizeDisplayVM(); + // price format public LadderSettings.NetChangeTerms price_format { get => _price_format; set => Set(ref _price_format, value); } public IEnumerable price_format_options => EnumHelper.get_values(); + // time in force + public TimeInForce default_time_in_force { get => _default_time_in_force; set => Set(ref _default_time_in_force, value); } + public IEnumerable time_in_force_options => EnumHelper.get_values_except(TimeInForce.Undefined); + // account + public AccountTuple? default_account { get => _default_account.Value; set => _default_account.Value = value; } + public ICollectionView accounts_view { get; } + // algo + public AlgoDefinitionVM default_algo { get => _default_algo.Value; set => _default_algo.Value = value; } + public IReadOnlyObservableCollection algo_definitions => _algo_definitions; + // left-panel (components) + public bool auto_clear { get => _auto_clear; set => Set(ref _auto_clear, value); } + public double order_entry_panel_width { get => _order_entry_panel_width; set => Set(ref _order_entry_panel_width, value); } + public double zoom_factor { get => _zoom_factor; set => Set(ref _zoom_factor, value); } + // favorites public FavoriteAlgosVM favorite_algos_vm { get; } public double row_height => _row_height.Value; @@ -172,49 +241,106 @@ namespace mbts.spark { public string key => GridSettingsTemplateKeys.Ladder; + IEnumerable _observable_components { + get { + // columns + yield return _orders; + yield return _bid; + yield return _price; + yield return _ask; + yield return _last; + yield return _piq; + yield return _volume; + yield return _volume.general; + // market break lines + yield return _bid_mkt_line; + yield return _ask_mkt_line; + yield return _mid_mkt_line; + yield return _session_low_mkt_line; + yield return _session_high_mkt_line; + yield return _session_range_fill; + // left panel + yield return _zoom_slider_visbility; + yield return _day_visibility; + yield return _high_visibility; + yield return _low_visibility; + yield return _open_visibility; + yield return _settle_visibility; + yield return _volume_visibility; + yield return _account_visibility; + yield return _tif_visibility; + yield return _order_type_visibility; + yield return _account_position_visibility; + yield return _day_position_visibility; + yield return _size_preset_visibility; + yield return _auto_clear_visibility; + yield return _clear_visibility; + yield return _cancel_buys_visibility; + yield return _cancel_sells_visibility; + yield return _cancel_all_visibility; + // other + yield return size_display; + yield return favorite_algos_vm; + yield return this; + } + } + public void load(LadderSettings settings) { - _current = settings; - badge_style = settings.badge_style; - alternate_order_size = settings.alternate_order_size; - favorite_algos_vm.load_from(settings.favorite_algos); - size_display.load_from(settings.size_display); - size_presets.SetItems(settings.calculator_buttons.empty_if_null().Select(s => _create_size_preset_vm((uint)s))); - _orders.assign_from(_current.orders_column); - _bid.assign_from(_current.bid_column); - _ask.assign_from(_current.ask_column); - _price.assign_from(_current.price_column); - _volume.assign_from(_current.volume_column); - _last.assign_from(_current.last_column); - _piq.assign_from(_current.piq_column); - _bid_mkt_line.assign_from(_current.bid_break_line); - _ask_mkt_line.assign_from(_current.ask_break_line); - _mid_mkt_line.assign_from(_current.mid_break_line); - _session_low_mkt_line.assign_from(_current.session_low_line); - _session_high_mkt_line.assign_from(_current.session_high_line); - _session_range_fill.assign_from(_current.session_range_fill); - _zoom_slider_visbility.show = settings.zoom_slider_visible; - _day_visibility.show = settings.day_visible; - _high_visibility.show = settings.high_visible; - _low_visibility.show = settings.low_visible; - _open_visibility.show = settings.open_visible; - _settle_visibility.show = settings.settle_visible; - _volume_visibility.show = settings.volume_visible; - _account_visibility.show = settings.account_visible; - _tif_visibility.show = settings.tif_visible; - _order_type_visibility.show = settings.order_type_visible; - _account_position_visibility.show = settings.account_position_visible; - _day_position_visibility.show = settings.day_position_visible; - _size_preset_visibility.show = settings.size_presets_visible; - _clear_visibility.show = settings.clear_visible; - _auto_clear_visibility.show = settings.auto_clear_visible; - _cancel_buys_visibility.show = settings.cancel_buys_visible; - _cancel_sells_visibility.show = settings.cancel_sells_visible; - _cancel_all_visibility.show = settings.cancel_all_visible; - price_format = settings.net_change; - // do not read the order entry panel width here from settings - // because it could have changed from the UI - // there might be a better way of doing this, like how - // does the widths of the ladder grid column pull this off? + using (_update.defer_execution()) { + _current = settings; + badge_style = settings.badge_style; + alternate_order_size = settings.alternate_order_size; + favorite_algos_vm.load_from(settings.favorite_algos); + size_display.load_from(settings.size_display); + size_presets.SetItems(settings.calculator_buttons.empty_if_null().Select(s => _create_size_preset_vm((uint)s))); + // columns + _orders.assign_from(_current.orders_column); + _bid.assign_from(_current.bid_column); + _ask.assign_from(_current.ask_column); + _price.assign_from(_current.price_column); + _volume.assign_from(_current.volume_column); + _last.assign_from(_current.last_column); + _piq.assign_from(_current.piq_column); + // market break lines + _bid_mkt_line.assign_from(_current.bid_break_line); + _ask_mkt_line.assign_from(_current.ask_break_line); + _mid_mkt_line.assign_from(_current.mid_break_line); + _session_low_mkt_line.assign_from(_current.session_low_line); + _session_high_mkt_line.assign_from(_current.session_high_line); + _session_range_fill.assign_from(_current.session_range_fill); + // left-panel (defaults) + default_time_in_force = settings.default_time_in_force; + // - account + _desired_account = settings.default_account; + _try_select_desired_account(true); + // - algo + _desired_algo = settings.default_algo; + _try_select_desired_algo(true); + // - components + auto_clear = settings.auto_clear; + order_entry_panel_width = settings.order_entry_panel_initial_width; + zoom_factor = settings.zoom_factor; + // left-panel (show/hide) + _zoom_slider_visbility.show = settings.zoom_slider_visible; + _day_visibility.show = settings.day_visible; + _high_visibility.show = settings.high_visible; + _low_visibility.show = settings.low_visible; + _open_visibility.show = settings.open_visible; + _settle_visibility.show = settings.settle_visible; + _volume_visibility.show = settings.volume_visible; + _account_visibility.show = settings.account_visible; + _tif_visibility.show = settings.tif_visible; + _order_type_visibility.show = settings.order_type_visible; + _account_position_visibility.show = settings.account_position_visible; + _day_position_visibility.show = settings.day_position_visible; + _size_preset_visibility.show = settings.size_presets_visible; + _clear_visibility.show = settings.clear_visible; + _auto_clear_visibility.show = settings.auto_clear_visible; + _cancel_buys_visibility.show = settings.cancel_buys_visible; + _cancel_sells_visibility.show = settings.cancel_sells_visible; + _cancel_all_visibility.show = settings.cancel_all_visible; + price_format = settings.net_change; + } } public LadderSettings get_result() { @@ -224,6 +350,7 @@ namespace mbts.spark { clone.favorite_algos = favorite_algos_vm.create(); clone.size_display = size_display.create(); clone.calculator_buttons = size_presets.Select(vm => (int)vm.value).ToArray(); + // columns, row height (the latter determined by columns font size) clone.orders_column = _orders.get_settings(); clone.bid_column = _bid.get_settings(); clone.price_column = _price.get_settings(); @@ -231,13 +358,28 @@ namespace mbts.spark { clone.volume_column = _volume.get_settings(); clone.last_column = _last.get_settings(); clone.piq_column = _piq.get_settings(); + clone.row_height = LadderRender.measure_row_height(clone); + // market break lines clone.bid_break_line = _bid_mkt_line.get_settings(); clone.ask_break_line = _ask_mkt_line.get_settings(); clone.mid_break_line = _mid_mkt_line.get_settings(); clone.session_low_line = _session_low_mkt_line.get_settings(); clone.session_high_line = _session_high_mkt_line.get_settings(); clone.session_range_fill = _session_range_fill.get_settings(); - clone.row_height = LadderRender.measure_row_height(clone); + // left-panel (defaults) + clone.default_time_in_force = default_time_in_force; + // - account + if (default_account.HasValue) + clone.default_account = default_account.Value.id; + // - algo + clone.default_algo = default_algo != null ? + AlgoID.from_algo_key(default_algo.key, _model.dynamic_helper.dynamic_type_index) : + (_desired_algo ?? LadderSettings.Default.default_algo); + // - components + clone.auto_clear = auto_clear; + clone.order_entry_panel_initial_width = _order_entry_panel_width; + clone.zoom_factor = zoom_factor; + // left-panel (components) clone.day_visible = _day_visibility.show; clone.high_visible = _high_visibility.show; clone.low_visible = _low_visibility.show; @@ -255,14 +397,21 @@ namespace mbts.spark { clone.cancel_buys_visible = _cancel_buys_visibility.show; clone.cancel_sells_visible = _cancel_sells_visibility.show; clone.cancel_all_visible = _cancel_all_visibility.show; - clone.order_entry_panel_initial_width = _get_order_entry_panel_width(); clone.zoom_slider_visible = _zoom_slider_visbility.show; - clone.zoom_factor = _get_zoom_factor(); clone.net_change = price_format; return clone; } - public void Dispose() => favorite_algos_vm.Dispose(); + public IDisposable defer_updates() => _update.defer_execution(); + + IDisposable IObservable.Subscribe(IObserver observer) { + result_changed += notify; + return Disposable.Create(() => result_changed -= notify); + void notify() => observer.OnNext(get_result()); + } + + LadderSettings IValueFactory.create() => get_result(); + void IValueFactory.load_from(LadderSettings value) => load(value); IMutableValueWrapperVM _create_size_preset_vm() => _create_size_preset_vm(0); IMutableValueWrapperVM _create_size_preset_vm(uint init) { @@ -270,6 +419,20 @@ namespace mbts.spark { vm.PropertyChanged += (s, e) => RaisePropertyChanged(nameof(size_presets_text)); return vm; } + + void _try_select_desired_account(bool bypass_setter = false) { + if (_desired_account.HasValue && (!_default_account.setter_called || bypass_setter) && _accounts.TryGetValue(_desired_account.Value, out var acc_tup)) { + _desired_account = null; + _default_account.bypass_setter(acc_tup); + } + } + + void _try_select_desired_algo(bool bypass_setter = false) { + if (_desired_algo.HasValue && (!_default_algo.setter_called || bypass_setter) && _algo_definitions.TryGetValue(AlgoID.to_algo_key(_desired_algo.Value, _model.dynamic_helper.dynamic_type_index), out var vm)) { + _desired_algo = null; + _default_algo.bypass_setter(vm); + } + } public class LadderColumnSettingsVM : ViewModelBase, ITemplateSelectorKey { readonly Property _font_size; @@ -280,6 +443,7 @@ namespace mbts.spark { readonly DelegateProperty _font_display_name; readonly Property _show; readonly string _template_key; + uint _width; public LadderColumnSettingsVM(string name, string template_key = null, bool can_toggle_show = false) { this.name = name; @@ -311,7 +475,7 @@ namespace mbts.spark { public FontWeight font_weight => _font_weight.Value; public string font_display_name => _font_display_name.Value; public double font_size { get => _font_size.Value; set => _font_size.Value = value; } - public uint width { get; set; } + public uint width { get => _width; set => Set(ref _width, value); } public bool show { get => _show.Value; set => _show.Value = value; } public bool can_toggle_show { get; } public bool show_details { get; private set; } @@ -336,7 +500,6 @@ namespace mbts.spark { show = settings.show; foreground = settings.foreground.rgb_color(); background = settings.background.rgb_color(); - RaisePropertyChanged(nameof(width), nameof(show)); } public LadderColumnSettings get_settings() { @@ -532,17 +695,15 @@ namespace mbts.spark { } public class FavoriteAlgosVM : DisposableViewModelBase, IValueFactoryVM { - readonly ObservableKeyedCollection _algo_definitions = new ObservableKeyedCollection(d => d.key); + readonly IObservableCollection _algo_definitions; readonly ObservableCollection _raw_items = new ObservableCollection(); int _column_count = 2; - public FavoriteAlgosVM(OrdersModel model) { + public FavoriteAlgosVM(IObservableCollection algo_definitions) { + _algo_definitions = algo_definitions; items = new ObservableAggregateCollection(_raw_items, new ObservableCollection { FavoriteAlgoItem.AddButtonPlaceholderItem }); add_item_cmd = new DelegateCommand(() => _raw_items.Add(_item_factory())); remove_item_cmd = new DelegateCommand(fai => _raw_items.Remove(fai)); - _dispose = model.algo_model.definitions.OnDispatcher().Subscribe(update => { - AlgoCollectionHelper.update_persisted_definitions(_algo_definitions, update, d => AlgoDefinitionVM.create(model, d, false)); - }); } public ObservableCollection items { get; } @@ -562,11 +723,17 @@ namespace mbts.spark { } public LadderFavoriteAlgosSettings create() => - new LadderFavoriteAlgosSettings(_raw_items.Where(fai => fai.algo_definition != null).Select(fai => fai.algo_definition.key).ToArray(), column_count); + new LadderFavoriteAlgosSettings(_raw_items + .Select(fai => fai.algo_definition?.key ?? fai.selector.desired_key) + .Where(k => k.HasValue && k.Value.is_persisted) + .Select(k => k.Value) + .ToArray(), + column_count); FavoriteAlgoItem _item_factory() => new FavoriteAlgoItem(_algo_definitions, new ListCollectionView(_algo_definitions) { - CustomSort = AlgoCollectionHelper.algo_definition_vm_comparer.to_non_generic() + CustomSort = AlgoCollectionHelper.algo_definition_vm_comparer.to_non_generic(), + Filter = obj => obj is AlgoDefinitionVM vm && vm.key.is_persisted }); } @@ -577,7 +744,7 @@ namespace mbts.spark { protected FavoriteAlgoItem() { } - public FavoriteAlgoItem(ObservableKeyedCollection algo_definitions, ICollectionView algo_definitions_view) { + public FavoriteAlgoItem(IObservableCollection algo_definitions, ICollectionView algo_definitions_view) { selector = new KeyedItemSelector(this, nameof(algo_definition), algo_definitions, d => d.key); this.algo_definitions_view = algo_definitions_view; } @@ -590,4 +757,4 @@ namespace mbts.spark { } } } -} \ No newline at end of file +} diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs index 350ce7c72..b2fb11823 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs @@ -1,13 +1,11 @@ -using bts.api; +using bts.api; using bts.api.orderman; using bts.shell; using bts.spark; using bts.utils; using mbts.co2; -using mbts.persist; using mbts.ui; using mbts.ui.shell; -using mbts.ui.utility; using mbts.utils; using System; using System.Collections.Generic; @@ -36,32 +34,29 @@ namespace mbts.spark { readonly PropertyAutoWrapper _bid_background, _bid_foreground, _ask_background, _ask_foreground; double _position, _day_position; bool _show_account_position, _show_day_position; - IWindowSettingsManager _settings_manager; ulong _misc_time = 0; ulong _last_trade_time = 0; IEqualityComparer _equality; Dictionary _slot_price_vs_orders; IReadOnlyDictionary _cache = DictionaryHelper.empty(); + LadderSettings _current_settings; - public static LadderVM create(IBus bus, LadderModel model, IWindowSettingsManager settings_manager, LadderSettings init) { - var non_shared_wsm = settings_manager.as_non_shared(); - return new LadderVM(bus, model, settings_manager, non_shared_wsm, init, new OrderPropertiesEditorVM(model.order_gateway, Observable.Return(model.security_md), settings_manager.subscribe_current().Select(s => new InlineOrderProperties(model.order_gateway, s)))); - } + public static LadderVM create(IBus bus, LadderModel model, LadderSettings init, IObservable settings) => + new LadderVM(bus, model, init, settings, new OrderPropertiesEditorVM(model.order_gateway, Observable.Return(model.security_md), settings.Select(s => new InlineOrderProperties(model.order_gateway, s)))); - public static LadderVM create_readonly(IBus bus, LadderModel model) { - var default_settings = LadderSettings.Default; - return create_readonly(bus, model, new WindowSettingsManager.DisconnectedImpl(default_settings), default_settings); - } + public static LadderVM create_readonly(IBus bus, LadderModel model, IObservable settings) => + create_readonly(bus, model, LadderSettings.Default, settings); - public static LadderVM create_readonly(IBus bus, LadderModel model, IWindowSettingsManager settings_manager, LadderSettings init) => - new LadderVM(bus, model, settings_manager, settings_manager.as_non_shared(), init); + public static LadderVM create_readonly(IBus bus, LadderModel model, LadderSettings init, IObservable settings) => + new LadderVM(bus, model, init, settings); - LadderVM(IBus bus, LadderModel model, IWindowSettingsManager settings_manager, IWindowSettingsManagerNonShared non_shared_wsm, LadderSettings init, OrderPropertiesEditorVM order_properties_vm = null) { + LadderVM(IBus bus, LadderModel model, LadderSettings init, IObservable settings, OrderPropertiesEditorVM order_properties_vm = null) { _bus = bus; _model = model; + _current_settings = init; + this.settings = settings; _equality = TickUtils.tick_equality_comparer(_model.security.ContractSpec); _slot_price_vs_orders = new Dictionary(_equality); - _settings_manager = non_shared_wsm; this.order_properties_vm = order_properties_vm; _high = backing(nameof(high), double.NaN); _low = backing(nameof(low), double.NaN); @@ -81,12 +76,14 @@ namespace mbts.spark { _zoom_factor = backing(nameof(zoom_factor), ws.zoom_factor); // remember: account_positions needs to subscribe to selected_account; both the sub and account_positions need to be disposed _volume = backing(nameof(volume), 0ul); - _auto_clear = backing(nameof(auto_clear), false); + _auto_clear = backing(nameof(auto_clear), init.auto_clear); _status = backing(nameof(status_message), ""); _status_brush = backing(nameof(status_background), _transparent_status_brush); // All settings observers should be aggregated together, so they can all share the same subscription to the settings // (these subscriptions are not horribly expensive, but they're not free either - even more so with the .OnDispatcher() extension). var settings_observer = new CompositeObserver { + /// first things first: assign our + (s => _current_settings = s), // brush props (_bid_background = brush_prop(nameof(bid_background), s => s.bid_column.background)).set, (_bid_foreground = brush_prop(nameof(bid_foreground), s => s.bid_column.foreground)).set, @@ -113,6 +110,19 @@ namespace mbts.spark { if (Set(ref _show_account_position, s.account_position_visible, nameof(show_account_position)) | Set(ref _show_day_position, s.day_position_visible, nameof(show_day_position))) { RaisePropertyChanged(nameof(position_display_text)); } + size_calculator.buttons = s.calculator_buttons; + _auto_clear.set(s.auto_clear); + // column widths + _orders_column_width.set(s.orders_column.width); + _bid_column_width.set(s.bid_column.width); + _price_column_width.set(s.price_column.width); + _ask_column_width.set(s.ask_column.width); + _last_column_width.set(s.last_column.width); + _piq_column_width.set(s.piq_column.width); + _volume_column_width.set(s.volume_column.general.width); + // left panel/zoom + _left_panel_width.set(s.order_entry_panel_initial_width); + _zoom_factor.set(s.zoom_factor); } }; PropertyAutoWrapper bool_prop(string name, Func get_bool) => @@ -128,30 +138,13 @@ namespace mbts.spark { cancel_command = new AsyncCommand(_model.cancel_orders, true); show_book_command = new DelegateCommand(_show_book); show_ticket_command = new DelegateCommand(_show_ticket); - settings_command = new DialogCommand(() => { - var vm = new WindowSettingsDialogVM( - settings_manager, s => s.ladder, UserSettings.FileExtensions.LADDER, - s => { - var svm = new LadderSettingsVM(model.order_gateway, security.ContractCase == Security.ContractOneofCase.Synthetic, () => left_panel_width, () => zoom_factor); - svm.load(s); - return svm; - }, s => s.with_window_specifics(get_save_state().get_window_specifics())); - var dialog = new ui.spark.SimpleGridSettingsDialog { - DataContext = vm, - Title = $"Ladder Settings - '{security}'" - }; - vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog); - return dialog; - }, -500, -500); + settings_command = new DelegateCommand(() => request_settings_dialog?.Invoke()); orders = new ObservableCollection(); _dispose = Disposable.Create( - settings_manager.subscribe_current().OnDispatcher().Subscribe(settings_observer), - settings_command, - non_shared_wsm, + settings.OnDispatcher().Subscribe(settings_observer), get_order_properties_editor_hooks(), - size_calculator = new CalculatorLogic(0, _settings_manager.subscribe_current().Select(s => s.calculator_buttons)), bus.subscribe(SparkTags.LogActivity).OnDispatcher().Subscribe(status_update), // we need to hook this up to model.orders which is filtered for just the security model.orders.OnDispatcher().Subscribe(working => { @@ -176,7 +169,7 @@ namespace mbts.spark { if (_slot_price_vs_orders.TryGetValue(slot_price_target, out LadderOrderVM slot_vm)) { slot_vm.add_order((wo, os.piq, os.algo, os.meta)); } else { - slot_vm = new LadderOrderVM((wo, os.piq, os.algo, os.meta), slot_price_target, this, _bus, _settings_manager.subscribe_current().Select(s => s.badge_style)); + slot_vm = new LadderOrderVM((wo, os.piq, os.algo, os.meta), slot_price_target, this, _bus, settings.Select(s => s.badge_style).OnDispatcher()); _slot_price_vs_orders[slot_price_target] = slot_vm; } @@ -250,7 +243,7 @@ namespace mbts.spark { public IBus bus => _bus; - public event Action on_tick; + public event Action on_tick, request_settings_dialog; public MDConsumerHandle md => _model.md; // we return only entries who have piqs and whose piqs are not uint.Max @@ -294,7 +287,7 @@ namespace mbts.spark { public double day_position => _day_position; public ulong volume => _volume.Value; public bool auto_clear { get => _auto_clear.Value; set => _auto_clear.set(value); } - public CalculatorLogic size_calculator { get; } + public CalculatorLogic size_calculator { get; } = new CalculatorLogic(0); /// Important: can be null. public OrderPropertiesEditorVM order_properties_vm { get; } public ObservableCollection orders { get; } @@ -302,11 +295,11 @@ namespace mbts.spark { public ICommand send_order_command { get; } public ICommand show_book_command { get; } public ICommand show_ticket_command { get; } + public ICommand settings_command { get; } public Brush bid_background => _bid_background.view; public Brush bid_foreground => _bid_foreground.view; public Brush ask_background => _ask_background.view; public Brush ask_foreground => _ask_foreground.view; - public DialogCommand settings_command { get; } public bool show_day => _show_day.view; public bool show_high => _show_high.view; public bool show_low => _show_low.view; @@ -347,7 +340,7 @@ namespace mbts.spark { public uint piq_column_width { get => _piq_column_width.Value; set => _piq_column_width.set(value); } public uint volume_column_width { get => _volume_column_width.Value; set => _volume_column_width.set(value); } internal LadderModel model => _model; - internal IObservable settings => _settings_manager.subscribe_current(); + internal IObservable settings { get; } internal OrderRecordImmutable get_root_at_price((OrderRecordImmutable order, uint? _, AlgoData? __, AlgoDefinitionMetadata? meta) op) { var order = op.order; double p = order.price(); @@ -366,10 +359,26 @@ namespace mbts.spark { } public LadderSettings get_save_state() { - var state = _settings_manager.current_settings(); - state = state.with_window_specifics(new LadderSettings.WindowSpecifics(left_panel_width, orders_column_width, bid_column_width, price_column_width, ask_column_width, last_column_width, volume_column_width, zoom_factor, piq_column_width)); - state.use_defaults = _settings_manager.instance_settings == null; - return state; + var rv = _current_settings.with_window_specifics( + new LadderSettings.WindowSpecifics( + left_panel_width, + orders_column_width, + bid_column_width, + price_column_width, + ask_column_width, + last_column_width, + volume_column_width, + zoom_factor, + piq_column_width)); + rv.auto_clear = auto_clear; + if (order_properties_vm != null) { + rv.default_time_in_force = order_properties_vm.selected_time_in_force; + if (order_properties_vm.selected_account.HasValue) + rv.default_account = order_properties_vm.selected_account.Value.id; + if (order_properties_vm.selected_algo_definition != null) + rv.default_algo = AlgoID.from_algo_key(order_properties_vm.selected_algo_definition.key, _model.order_gateway.dynamic_helper.dynamic_type_index); + } + return rv; } public void key_down(KeyEventArgs e) { @@ -384,20 +393,18 @@ namespace mbts.spark { } } - public void send_order((double price, Side? side, MouseButton buton) args) { - if (args.buton == MouseButton.Middle) return; - var size_from_alternate = args.buton == MouseButton.Right; - if (order_properties_vm == null) + public void send_order((double price, Side? side, MouseButton button) args) { + if (order_properties_vm == null || args.button == MouseButton.Middle) return; - var s = _settings_manager.current_settings(); - if (DoubleHelper.IsNaNOrInfinity(args.price) || !args.side.HasValue || HasErrors || order_properties_vm.HasErrors || (size_from_alternate && s.alternate_order_size == 0)) { + var size_from_alternate = args.button == MouseButton.Right; + if (DoubleHelper.IsNaNOrInfinity(args.price) || !args.side.HasValue || HasErrors || order_properties_vm.HasErrors || (size_from_alternate && _current_settings.alternate_order_size == 0)) { return; } if (!size_from_alternate && (!size_calculator.value.HasValue || size_calculator.value.Value == 0)) { size_calculator.flash_error(); } else { - uint size = size_from_alternate ? s.alternate_order_size : (uint)Math.Abs(size_calculator.value ?? 0); + uint size = size_from_alternate ? _current_settings.alternate_order_size : (uint)Math.Abs(size_calculator.value ?? 0); send_order_async(args.side.Value, size, args.price).ignore(); } } diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml b/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml index 879ac260f..23a767e3a 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml @@ -4,15 +4,16 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ice="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options" + xmlns:sp="clr-namespace:mbts.spark" xmlns:u="clr-namespace:mbts.ui" xmlns:c="clr-namespace:mbts.ui.controls" xmlns:cv="clr-namespace:mbts.ui.converters" xmlns:usp="clr-namespace:mbts.ui.spark" xmlns:sys="clr-namespace:System;assembly=mscorlib" + xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase" TextElement.FontSize="{x:Static u:FontSizes.Small}" > - 4 8 12 @@ -27,6 +28,7 @@ 57 70 81 + 50 160 153 @@ -43,11 +45,13 @@ - + + + + - - - - - - - + + + 22 + 32 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Left Panel Width + + + + + + + + + + + + + Zoom Factor + + + + + + + + + + + + + + Account + + + Time In Force + + + Algo + + + + + + + + + + + + + Auto Clear + + + + + + + + + + + + + + + + + + + + + + + + + + + + + #3D26A0DA + #FF26A0DA + #FFF5F5F5 + #FFF1F1F1 + #FFE2E3E3 + #FF212121 #FFFFFFFF diff --git a/src/client/spark/view/Controls/DIYGrid/Settings/GridSettingsView.xaml b/src/client/spark/view/Controls/DIYGrid/Settings/GridSettingsView.xaml index be5ca7445..88fd35b7f 100644 --- a/src/client/spark/view/Controls/DIYGrid/Settings/GridSettingsView.xaml +++ b/src/client/spark/view/Controls/DIYGrid/Settings/GridSettingsView.xaml @@ -230,6 +230,7 @@ SelectedCriteria="{Binding value}" SecurityMap="{Binding Path='[security_map]', UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" Header="{Binding SelectedCriteria, RelativeSource={RelativeSource Self}}" + ToolTip="{Binding SelectedCriteria, RelativeSource={RelativeSource Self}, Converter={x:Static c:ContractPickerPopup.SecurityCriteriaTextConverter}, Mode=OneWay}" /> diff --git a/src/client/spark/view/Controls/DIYGrid/Settings/SimpleGridSettingsDialog.xaml b/src/client/spark/view/Controls/DIYGrid/Settings/SimpleGridSettingsDialog.xaml deleted file mode 100644 index d114c1cb1..000000000 --- a/src/client/spark/view/Controls/DIYGrid/Settings/SimpleGridSettingsDialog.xaml +++ /dev/null @@ -1,143 +0,0 @@ - - - - 4 - 8 - 240 - - - - - - - - - - - - - - - - - - - - - - - - Font - - - - - - - - - - - Font Color (default) - - Selection Highlight - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/client/spark/view/Controls/DIYGrid/Settings/SimpleGridSettingsDialog.xaml.cs b/src/client/spark/view/Controls/DIYGrid/Settings/SimpleGridSettingsDialog.xaml.cs deleted file mode 100644 index d69574424..000000000 --- a/src/client/spark/view/Controls/DIYGrid/Settings/SimpleGridSettingsDialog.xaml.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Windows; - -namespace mbts.ui.spark { - /// - /// Interaction logic for SimpleGridSettingsDialog.xaml - /// - public partial class SimpleGridSettingsDialog : Window { - public SimpleGridSettingsDialog() => - InitializeComponent(); - - public const string ResetToFactoryKey = "Reset", CopyFromOtherKey = "Copy"; - } - - static class GridSettingsTemplateKeys { - public const string - SimpleGrid = nameof(SimpleGrid), - Ladder = nameof(Ladder), - OrderBook = nameof(OrderBook); - } -} \ No newline at end of file diff --git a/src/client/spark/view/Controls/Dialogs/OKCancelDialog.xaml b/src/client/spark/view/Controls/Dialogs/OKCancelDialog.xaml new file mode 100644 index 000000000..89a555391 --- /dev/null +++ b/src/client/spark/view/Controls/Dialogs/OKCancelDialog.xaml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/view/Controls/Dialogs/OKCancelDialog.xaml.cs b/src/client/spark/view/Controls/Dialogs/OKCancelDialog.xaml.cs new file mode 100644 index 000000000..fc376904a --- /dev/null +++ b/src/client/spark/view/Controls/Dialogs/OKCancelDialog.xaml.cs @@ -0,0 +1,66 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; + +namespace mbts.ui.controls { + /// + /// Interaction logic for TextBoxDialog.xaml + /// + partial class OKCancelDialog : Window { + UIElement _core_content_view; + Panel _content_root; + + public OKCancelDialog() => + InitializeComponent(); + + #region CoreContent + public static readonly DependencyProperty CoreContentProperty = + WPFHelper.create_dp( + nameof(CoreContent), + (o, v) => o._try_load_content()); + + public object CoreContent { + get => GetValue(CoreContentProperty); + set => SetValue(CoreContentProperty, value); + } + #endregion + + #region OKCommand + public static readonly DependencyProperty OKCommandProperty = + WPFHelper.create_dp(nameof(OKCommand)); + + public ICommand OKCommand { + get => GetValue(OKCommandProperty) as ICommand; + set => SetValue(OKCommandProperty, value); + } + #endregion + + #region CancelCommand + public static readonly DependencyProperty CancelCommandProperty = + WPFHelper.create_dp(nameof(CancelCommand)); + + public ICommand CancelCommand { + get => GetValue(CancelCommandProperty) as ICommand; + set => SetValue(CancelCommandProperty, value); + } + #endregion + + void _content_root_Loaded(object sender, RoutedEventArgs e) { + if (_content_root == null) { + _content_root = sender as Panel; + _try_load_content(); + } + } + + void _try_load_content() { + if (_content_root == null) + return; + try { + if (_core_content_view != null) + _content_root.Children.Remove(_core_content_view); + var c = CoreContent; + _content_root.Children.Add(_core_content_view = c as UIElement ?? new ContentControl { Content = c }); + } catch { } + } + } +} \ No newline at end of file diff --git a/src/client/spark/view/Controls/ToolBar/ToolBar.xaml b/src/client/spark/view/Controls/ToolBar/ToolBar.xaml new file mode 100644 index 000000000..b35eef748 --- /dev/null +++ b/src/client/spark/view/Controls/ToolBar/ToolBar.xaml @@ -0,0 +1,226 @@ + + + 4 + 8 + 240 + #FFE8EDF9 + #FFC5CBF9 + #FF888888 + + #FFC5CBF9 + #FFDDDDDD + + White + #FFCCCCCC + #FFAAAAAA + #200080FF + #800080FF + #FFE5E5E5 + #FFF0F0F0 + + + #FF888888 + #FF888888 + #80DADADA + #90006CD9 + #FFAAAAAA + Black + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/view/Resources/ComboBoxes.xaml b/src/client/spark/view/Resources/ComboBoxes.xaml index f10ac608f..f623fdf2e 100644 --- a/src/client/spark/view/Resources/ComboBoxes.xaml +++ b/src/client/spark/view/Resources/ComboBoxes.xaml @@ -20,6 +20,18 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Profile: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Hint: this will not apply to existing ladders. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/view/Shell/Settings/ShellSettingsDialog.xaml.cs b/src/client/spark/view/Shell/Settings/ShellSettingsDialog.xaml.cs new file mode 100644 index 000000000..36e1c97f7 --- /dev/null +++ b/src/client/spark/view/Shell/Settings/ShellSettingsDialog.xaml.cs @@ -0,0 +1,25 @@ +using System.Windows; + +namespace mbts.ui.spark { + /// + /// Interaction logic for ShellSettingsDialog.xaml + /// + public partial class ShellSettingsDialog : Window { + public ShellSettingsDialog() => + InitializeComponent(); + + public const string + ResetToFactoryKey = "Reset", + CopyFromOtherKey = "Copy", + LocalProfileItemTemplateKey = "LocalProfileItemTemplate", + SaveAsStyleKey = "SaveAsStyle", + SecurityMapKey = "SecurityMap"; + } + + static class GridSettingsTemplateKeys { + public const string + SimpleGrid = nameof(SimpleGrid), + Ladder = nameof(Ladder), + OrderBook = nameof(OrderBook); + } +} \ No newline at end of file diff --git a/src/client/spark/view/Shell/Settings/ShellSettingsDialogVM.cs b/src/client/spark/view/Shell/Settings/ShellSettingsDialogVM.cs new file mode 100644 index 000000000..f6cdeafd6 --- /dev/null +++ b/src/client/spark/view/Shell/Settings/ShellSettingsDialogVM.cs @@ -0,0 +1,416 @@ +using bts.collections; +using bts.utils; +using mbts.collections; +using mbts.persist; +using mbts.ui; +using mbts.ui.controls; +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.Linq; +using System.Reactive.Linq; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; + +namespace mbts.spark { + interface IWindowSettingsVM where T : class { + void load(T value); + T get_result(); + } + + class ShellSettingsDialogVM : ViewModelBase, IRequestViewClose, IDisposable where T : class, IEquatable where TVM : IWindowSettingsVM { + readonly Property _use_default; + readonly DialogSkirtItem _ok_item, _apply_item, _cancel_item, _apply_to_defaults_item; + readonly DelegateProperty> _left_skirt_items; + readonly List _resources = new List(2); // initialize with 2 capacity bc the only potential disposables are the instance/default vms + + public ShellSettingsDialogVM(IWindowSettingsManager settings_manager, Func get_factory_settings, string settings_file_ext, Func vm_factory, Func merge_with_current = null, bool show_save_as_defaults = true) { + if (merge_with_current == null) + merge_with_current = s => s; + // by default, each new window will use their own instance settings + _use_default = backing(nameof(use_default), settings_manager.instance_settings == null); + default_vm = vm_factory(settings_manager.default_settings); + // instance vm is what will always be visible on the screen + instance_vm = vm_factory(settings_manager.current_settings()); + // items + const string import_group = "i", export_group = "e"; + (string name, string[] extensions) file_filter = ($"{settings_file_ext} settings files", new[] { settings_file_ext }); + var import_to_custom_cmd = FileDialogCommand.import_proto(s => instance_vm.load(s), type_name: settings_file_ext, filter_items: file_filter); + var export_to_custom_cmd = FileDialogCommand.export_proto(() => instance_vm.get_result(), filter_items: file_filter); + action_menu_items = new IMenuItemVM[] { + new MenuItemVM("Load Settings File ...", import_to_custom_cmd, Icons.Import, import_group), + new MenuItemVM("Save Settings File ...", export_to_custom_cmd, Icons.Export, export_group), + new MenuItemVM("Load Factory Defaults", + new DelegateCommand(() => instance_vm.load(get_factory_settings(UserSettings.factory_defaults))), + Icons.Factory + ) + }; + _left_skirt_items = backing(nameof(left_skirt_items), left_skirt_factory); + _apply_item = new DialogSkirtItem("Apply", new DelegateCommand(() => { + use_default = false; + apply(); + })); + _ok_item = new DialogSkirtItem("OK", new DelegateCommand(() => { + use_default = false; + apply(); + close(); + })) { is_default = true }; + _cancel_item = new DialogSkirtItem("Cancel", new DelegateCommand(close)) { is_cancel = true }; + _apply_to_defaults_item = new DialogSkirtItem("Save As Defaults", new DelegateCommand(() => { + use_default = true; + apply(); + close(); + }), ui.spark.LadderSettingsDialog.ResetToFactoryKey); + // maybe dispose vms + if (instance_vm is IDisposable dispose_ivm) + _resources.Add(dispose_ivm); + if (default_vm is IDisposable dispose_dvm) + _resources.Add(dispose_dvm); + // local methods + void apply() { + var result = merge_with_current(instance_vm.get_result()); + if (!use_default) { + settings_manager.instance_settings = result; + } else { + settings_manager.instance_settings = null; + + // copy the current instance settings and persist + if (!result.safe_equals(settings_manager.default_settings)) + settings_manager.save_default_settings(result).ignore(); + } + } + + void close() => RequestClose?.Invoke(this, new EventArgs()); + + IEnumerable left_skirt_factory() { + if (show_save_as_defaults) + yield return _apply_to_defaults_item; + }; + } + + public event EventHandler RequestClose; + + public TVM instance_vm { get; } + public TVM default_vm { get; } + public IReadOnlyCollection action_menu_items { get; } + public IEnumerable left_skirt_items => _left_skirt_items.Value; + public IEnumerable right_skirt_items { + get { + yield return _apply_item; + yield return _ok_item; + yield return _cancel_item; + } + } + public bool use_default { + get => _use_default.Value; + set => _use_default.Value = value; + } + + public void Dispose() => + Disposable.dispose(_resources); + } + + class ProfiledShellSettingsDialogVM : DisposableViewModelBase, IRequestViewClose where T : class, IEquatable where TVM : class, IValueFactory, IObservable where TProfile : ISettingsProfile { + readonly IComparer> _key_comp = Comparer.Default.wrap(SettingsProfile.key_fn); + readonly Property _selected_profile; + readonly Func _vm_factory; + readonly ProfileVM _local_profile; + bool _is_copy_menu_open; + DialogSkirtItem _apply_item, _ok_item, _cancel_item; + MenuItemVM _import_item, _export_item, _load_factory_item; + + public ProfiledShellSettingsDialogVM(ISettingsProfileService profile_service, Func get_fallback, Func vm_factory, Func normalize, T init, string file_ext, uint settings_id = 0) { + _vm_factory = vm_factory; + // profile collections + var skip_local = profiles.WrapSkip(1); + var skip_local_wrapper = skip_local.WrapSelector( + p => new SettingsProfile(p.id, p.name, p.value.create(), p.security_criteria), + ns => new ProfileVM(ns.id, vm_factory(ns.value), ns.name, ns.security_criteria)); + profiles.Add(_local_profile = new ProfileVM(0, vm_factory(init), "local", template_key: ShellSettingsDialog.LocalProfileItemTemplateKey)); + _selected_profile = backing(nameof(selected_profile), _local_profile); + // dialog skirt items + _apply_item = new DialogSkirtItem("Apply", new DelegateCommand(apply)); + _ok_item = new DialogSkirtItem("OK", new DelegateCommand(new Action(apply) + close)) { is_default = true }; + _cancel_item = new DialogSkirtItem("Cancel", new DelegateCommand(close)) { is_cancel = true }; + // cmds + add_profile_cmd = new DelegateCommand(begin_add_profile); + copy_profile_cmd = new DelegateCommand(copy_profile); + revert_profile_cmd = ObservantCommand.create(revert_profile, ProfileVM.subscribe_is_dirty_fn, out var revert_profile_observer); + save_profile_cmd = ObservantCommand.create(save_profile, ProfileVM.subscribe_is_global_dirty_fn, out var save_profile_observer); + save_profile_as_cmd = ObservantCommand.create(begin_save_profile_as, ProfileVM.is_global_fn, out var save_as_observer); + save_all_cmd = ObservantCommand.create(save_all, out var save_all_observer); + delete_profile_cmd = ObservantCommand.create(delete, ProfileVM.is_global_fn, out var delete_observer); + // toolbar + const string import_group = "i", export_group = "e"; + (string name, string[] extensions) file_filter = ($"{file_ext} settings files", new[] { file_ext }); + var import_cmd = FileDialogCommand.import_proto(s => selected_profile?.load_value_from(s), type_name: file_ext, filter_items: file_filter); + var export_cmd = FileDialogCommand.export_proto(() => instance_vm.create(), filter_items: file_filter); + _load_factory_item = new MenuItemVM("Load Factory Defaults", new DelegateCommand(() => selected_profile?.load_value_from(get_fallback(UserSettings.factory_defaults))), Icons.Factory); + _import_item = new MenuItemVM("Load Settings File ...", import_cmd, Icons.Import, import_group); + _export_item = new MenuItemVM("Save Settings File ...", export_cmd, Icons.Export, export_group); + // + var is_global_dirty_mon = new ReactiveThresholdMonitor(ProfileVM.subscribe_is_global_dirty_fn); + _dispose = Disposable.Create( + ObservableAutoWrapper.connect_item_hooks(profiles, p => Disposable.Create(is_global_dirty_mon.join(p), p)), + is_global_dirty_mon.Subscribe(save_all_observer), + _selected_profile.observe_current(true).Subscribe(v => { + revert_profile_observer.OnNext(v); + save_profile_observer.OnNext(v); + save_as_observer.OnNext(v); + delete_observer.OnNext(v); + RaisePropertyChanged(nameof(instance_vm)); + }), + profile_service.subscribe_all().OnDispatcher().Subscribe(table => { + var prev_selected_name = selected_profile?.name; + skip_local_wrapper.RemoveSorted(table.removed, _key_comp); + foreach (var ns in table.changed) { + int i = CollectionHelper.binary_search(skip_local_wrapper, ns, _key_comp); + if (i >= 0) + skip_local[i].commit(ns); + } + foreach (var ns in table.added) { + int i = CollectionHelper.binary_search(skip_local_wrapper, ns, _key_comp); + if (i >= 0) + continue; + i = ~i; + var temp = ns.with(value: normalize(ns.value)); + skip_local_wrapper.Insert(i, temp); + if (settings_id == temp.id) { + if (temp.value.Equals(init)) + selected_profile = skip_local[i]; + settings_id = 0; + } + } + })); + + void apply() { + if (selected_profile != null) { + var newval = selected_profile.create(); + if (selected_profile.id != 0) + profile_service.add_or_update(newval); + selected_profile.commit_current(); + applied?.Invoke(newval); + } + } + void close() => RequestClose?.Invoke(this, new EventArgs()); + void delete(ProfileVM target) { + if (target.id != 0 && BTSMessageBox.Confirm($"Are you sure you want to delete '{target.name}?'", "Settings Profile")) + profile_service.remove(target.id); + } + void copy_profile(ProfileVM target) { + if (selected_profile != null) { + if (target == null) { + // copy to new + var profile = selected_profile.create().with(0, $"{selected_profile.name} - Copy"); + target = new ProfileVM(profile_service.add_or_update(profile), _vm_factory(profile.value), profile.name); + } + target.load_value_from(selected_profile.create().value); + is_copy_menu_open = false; + selected_profile = target; + } + } + // cmd impl + void begin_add_profile() => choose_name_dialog("New Profile", selected_profile, (t, n) => save_profile_as(null, n)).Show(); + void begin_save_profile_as(ProfileVM target) => choose_name_dialog($"Rename '{target.name}'", target, (t, n) => save_profile_as(t ?? target, n)).Show(); + void revert_profile(ProfileVM target) => target?.revert(); + void save_profile(ProfileVM target) => save_profile_as(target, target?.name); + // + void save_profile_as(ProfileVM target, string name) { + if (name == null || selected_profile == null) + return; + SettingsProfile val; + if (target != null) { + // overwrite target profile + val = selected_profile.create().with(name: name); + target.commit(val); + selected_profile = target; + profile_service.add_or_update(val); + } else { + // create new profile (set id=0 so 'store' knows to add a new profile, rather than update an existing one) + val = selected_profile.create().with(0, name); + uint id = profile_service.add_or_update(val); + /// Add the new profile to () so it can then be assigned to without being immediately unselected. + /// remember: val needs the new id before it can be added. + val = val.with(id); + // the save process is asynchronous now, but if that were to change, the new setting vm would have been added (already) in the iobservable settings callback. + // check that a vm with this id doesn't already exist before adding it . + int i = CollectionHelper.binary_search(skip_local_wrapper, val, _key_comp); + if (i < 0) + skip_local_wrapper.Insert(i = ~i, val); + selected_profile = skip_local[i]; + } + } + void save_all() => + profile_service.add_or_update(skip_local.Select(p => p.create())); + + Window choose_name_dialog(string title, ProfileVM target, Action commit) { + var text_box = new TextBox { Width = 160, Margin = new Thickness(8, 0, 0, 0), Text = target?.name ?? string.Empty }; + TextBoxBehavior.SetFocusOnLoaded(text_box, true); + WPFTextBoxAutoComplete.AutoCompleteBehavior.SetAutoCompleteItemsSource(text_box, skip_local.Select(vm => vm.name).ToList()); + // panel + var panel = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(8) }; + panel.Children.Add(new TextBlock { Text = "Name:", VerticalAlignment = VerticalAlignment.Center }); + panel.Children.Add(text_box); + // dialog + var dialog = new OKCancelDialog { + Title = title, + OKCommand = new DelegateCommand(() => commit(skip_local.FirstOrDefault(vm => vm.name == text_box.Text), text_box.Text)), + CoreContent = panel, + Topmost = true + }; + dialog.move_to_mouse(-100, -80); + return dialog; + } + } + + public event Action> applied; + public event EventHandler RequestClose; + + public ObservableCollection profiles { get; } = new ObservableCollection(); + public ProfileVM selected_profile { + get => _selected_profile.Value; + set { + if (_selected_profile.set_new(value) && value != null) + value.is_selected = true; + } + } + public TVM instance_vm => selected_profile?.value; + public bool is_copy_menu_open { get => _is_copy_menu_open; set => Set(ref _is_copy_menu_open, value); } + + public ICommand add_profile_cmd { get; } + public ICommand copy_profile_cmd { get; } + public ICommand delete_profile_cmd { get; } + public ICommand revert_profile_cmd { get; } + public ICommand edit_profile_securities_cmd { get; } + public ICommand save_profile_cmd { get; } + public ICommand save_profile_as_cmd { get; } + public ICommand save_all_cmd { get; } + + public IEnumerable action_menu_items { + get { + yield return _import_item; + yield return _export_item; + yield return _load_factory_item; + } + } + public IEnumerable left_skirt_items { get { yield break; } } + public IEnumerable right_skirt_items { + get { + yield return _apply_item; + yield return _ok_item; + yield return _cancel_item; + } + } + + public class ProfileVM : ViewModelBase, IValueFactory>, IEquatable, ITemplateSelectorKey, IDisposable { + // static delegates + public static readonly Func is_global_fn = p => p != null && p.is_global; + public static readonly Func> subscribe_is_global_dirty_fn = p => p?.is_global ?? false ? p.subscribe_is_dirty() : Observable.Return(false); + public static readonly Func> subscribe_is_dirty_fn = p => p != null ? p.subscribe_is_dirty() : Observable.Return(false); + // + readonly DeferrableActionWrapper _refresh_is_dirty; + readonly DelegateProperty _is_dirty; + // + SecurityCriteria _security_criteria; + SettingsProfile _committed, _last_result; + string _name, _template_key; + bool _is_selected; + IDisposable _dispose; + + public ProfileVM(uint id, TVM value, string name, SecurityCriteria security_criteria = null, string template_key = null) { + this.id = id; + this.value = value; + _name = name; + _security_criteria = security_criteria; + _template_key = template_key; + _committed = _last_result = create(); + _is_dirty = backing(nameof(is_dirty), () => !_last_result.Equals(_committed)); + _refresh_is_dirty = new DeferrableActionWrapper(_is_dirty.refresh); + var sub = value.Subscribe(v => { + _last_result = _last_result.with(value: v); + _refresh_is_dirty.execute(); + }); + _dispose = value is IDisposable d ? Disposable.Create(sub, d) : sub; + } + + public uint id { get; } + public TVM value { get; } + public string name { + get => _name; + set { + if (Set(ref _name, value)) { + _last_result = _last_result.with(name: value); + _is_dirty.refresh(); + } + } + } + public bool is_global => id != 0; + public bool is_dirty => _is_dirty.Value; + public bool is_selected { get => _is_selected; set => Set(ref _is_selected, value); } + public SecurityCriteria security_criteria { + get => _security_criteria; + set { + if (Set(ref _security_criteria, value)) { + _last_result = _last_result.with(security_criteria: security_criteria); + _is_dirty.refresh(); + } + } + } + + string ITemplateSelectorKey.key => _template_key; + + public SettingsProfile create() => + new SettingsProfile(id, name, value.create(), security_criteria); + + public void load_from(SettingsProfile data) { + using (_refresh_is_dirty.defer_execution()) { + _load_from(data); + /// assign directly to , to capture props that aren't visible in the dialog (i.e., props that are manipulated in the main window) + _last_result = data; + } + } + + public void load_value_from(T value) { + using (_refresh_is_dirty.defer_execution()) + this.value.load_from(value); + } + + public void commit(SettingsProfile data) { + using (_refresh_is_dirty.defer_execution()) + _load_from(_committed = data); + } + + public void commit_current() { + _committed = _last_result; + _refresh_is_dirty.execute(); + } + + public void revert() { + using (_refresh_is_dirty.defer_execution()) { + _load_from(_committed); + _last_result = _committed; + } + } + + public IObservable subscribe_is_dirty() => _is_dirty.observe_current(true); + + public void Dispose() => Disposable.dispose(ref _dispose); + + public bool Equals(ProfileVM other) => id == other?.id; + public override bool Equals(object obj) => Equals(obj as ProfileVM); + public override int GetHashCode() => id.GetHashCode(); + public override string ToString() => _name; + + void _load_from(SettingsProfile data) { + name = data.name; + security_criteria = data.security_criteria; + value.load_from(data.value); + } + } + } +} \ No newline at end of file diff --git a/src/client/spark/view/Spark/ContractPicker/ContractPickerPopup.xaml b/src/client/spark/view/Spark/ContractPicker/ContractPickerPopup.xaml index 6bc4b493e..35af16a13 100644 --- a/src/client/spark/view/Spark/ContractPicker/ContractPickerPopup.xaml +++ b/src/client/spark/view/Spark/ContractPicker/ContractPickerPopup.xaml @@ -5,7 +5,6 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sp="clr-namespace:mbts.spark" xmlns:c="clr-namespace:mbts.ui.controls" - ToolTip="{Binding SelectedCriteria, RelativeSource={RelativeSource Self}, Converter={x:Static c:ContractPickerPopup.SecurityCriteriaTextConverter}, Mode=OneWay}" ShowExpanderArrow="False" Padding="2,0" > diff --git a/src/client/spark/view/Spark/ContractPicker/SecurityCriteriaExtensions.cs b/src/client/spark/view/Spark/ContractPicker/SecurityCriteriaExtensions.cs index 4eefe61b0..d97a0a99a 100644 --- a/src/client/spark/view/Spark/ContractPicker/SecurityCriteriaExtensions.cs +++ b/src/client/spark/view/Spark/ContractPicker/SecurityCriteriaExtensions.cs @@ -96,5 +96,8 @@ namespace mbts.spark { clause.security_types.is_null_or_empty() && !clause.security_keys.is_null_or_empty() && !clause.security_keys.Distinct().Skip(1).Any(); + + public static bool includes(this SecurityCriteria security_criteria, SecurityImmutable security) => + security_criteria != null && ContractPickerModel.security_in_criteria(security_criteria, security); } } \ No newline at end of file diff --git a/src/client/spark/view/Spark/PAndL/PAndLWindow.cs b/src/client/spark/view/Spark/PAndL/PAndLWindow.cs index 67524836d..4efa927b1 100644 --- a/src/client/spark/view/Spark/PAndL/PAndLWindow.cs +++ b/src/client/spark/view/Spark/PAndL/PAndLWindow.cs @@ -57,7 +57,7 @@ namespace mbts.spark { _view.DataContext = _vm; _commands = new List { SparkCommands.window_settings_command(new DialogCommand(() => { - var vm = new WindowSettingsDialogVM( + var vm = new ShellSettingsDialogVM( _settings_manager, us => us.pnl_grid, UserSettings.FileExtensions.GRID, @@ -69,7 +69,7 @@ namespace mbts.spark { ) ); // TODO: bind to main window's Title - var dialog = new SimpleGridSettingsDialog { Title = "PnL Grid Settings", DataContext = vm }; + var dialog = new ShellSettingsDialog { Title = "PnL Grid Settings", DataContext = vm }; vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog); return dialog; })) diff --git a/src/client/spark/view/Spark/Shell/CalculatorLogic.cs b/src/client/spark/view/Spark/Shell/CalculatorLogic.cs index 56a81f4fb..6433e10e1 100644 --- a/src/client/spark/view/Spark/Shell/CalculatorLogic.cs +++ b/src/client/spark/view/Spark/Shell/CalculatorLogic.cs @@ -7,17 +7,18 @@ using System.Windows.Input; namespace mbts.spark { public class CalculatorLogic : DisposableViewModelBase { readonly UserProperty _value; - readonly Property _buttons; + int[] _buttons; - public CalculatorLogic(uint? initial_size, IObservable buttons_source) { + public CalculatorLogic(uint? initial_size) => _value = new UserProperty(backing(nameof(value), initial_size)); - _buttons = backing(nameof(buttons), buttons_source); - } + + public CalculatorLogic(uint? initial_size, IObservable buttons_source) : this(initial_size) => + _dispose = buttons_source.Subscribe(newval => buttons = newval); public uint? value { get => _value.Value; set => _value.Value = value; } public bool value_setter_called => _value.setter_called; public IObservable value_observable => _value.Select(vals => vals.newval); - public int[] buttons { get => _buttons.Value; set => _buttons.set(value); } + public int[] buttons { get => _buttons; set => Set(ref _buttons, value); } public ICommand click => new DelegateCommand(handle_calculator_click); public ICommand set_value_command => new DelegateCommand(v => _value.Value = v); public ICommand clear => new DelegateCommand(() => _value.Value = null); diff --git a/src/client/spark/view/Spark/Utilities/WindowSettingsDialogVM.cs b/src/client/spark/view/Spark/Utilities/WindowSettingsDialogVM.cs deleted file mode 100644 index 4340f2724..000000000 --- a/src/client/spark/view/Spark/Utilities/WindowSettingsDialogVM.cs +++ /dev/null @@ -1,105 +0,0 @@ -using mbts.persist; -using mbts.ui; -using mbts.ui.controls; -using mbts.ui.shell; -using System; -using System.Collections.Generic; - -namespace mbts.spark { - interface IWindowSettingsVM where T : class { - void load(T value); - T get_result(); - } - - class WindowSettingsDialogVM : ViewModelBase, IRequestViewClose, IDisposable where T : class, IEquatable where TVM : IWindowSettingsVM { - readonly Property _use_default; - readonly DialogSkirtItem _ok_item, _apply_item, _cancel_item, _apply_to_defaults_item; - readonly DelegateProperty> _left_skirt_items; - readonly List _resources = new List(2); // initialize with 2 capacity bc the only potential disposables are the instance/default vms - - public WindowSettingsDialogVM(IWindowSettingsManager settings_manager, Func get_factory_settings, string settings_file_ext, Func vm_factory, Func merge_with_current = null, bool show_save_as_defaults = true) { - if (merge_with_current == null) - merge_with_current = s => s; - // by default, each new window will use their own instance settings - _use_default = backing(nameof(use_default), settings_manager.instance_settings == null); - default_vm = vm_factory(settings_manager.default_settings); - // instance vm is what will always be visible on the screen - instance_vm = vm_factory(settings_manager.current_settings()); - // items - const string import_group = "i", export_group = "e"; - (string name, string[] extensions) file_filter = ($"{settings_file_ext} settings files", new[] { settings_file_ext }); - var import_to_custom_cmd = FileDialogCommand.import_proto(s => instance_vm.load(s), type_name: settings_file_ext, filter_items: file_filter); - var export_to_custom_cmd = FileDialogCommand.export_proto(() => instance_vm.get_result(), filter_items: file_filter); - action_menu_items = new IMenuItemVM[] { - new MenuItemVM("Load Settings File ...", import_to_custom_cmd, Icons.Import, import_group), - new MenuItemVM("Save Settings File ...", export_to_custom_cmd, Icons.Export, export_group), - new MenuItemVM("Load Factory Defaults", - new DelegateCommand(() => instance_vm.load(get_factory_settings(UserSettings.factory_defaults))), - Icons.Factory - ) - }; - _left_skirt_items = backing(nameof(left_skirt_items), left_skirt_factory); - _apply_item = new DialogSkirtItem("Apply", new DelegateCommand(() => { - use_default = false; - apply(); - })); - _ok_item = new DialogSkirtItem("OK", new DelegateCommand(() => { - use_default = false; - apply(); - close(); - })) { is_default = true }; - _cancel_item = new DialogSkirtItem("Cancel", new DelegateCommand(close)) { is_cancel = true }; - _apply_to_defaults_item = new DialogSkirtItem("Save As Defaults", new DelegateCommand(() => { - use_default = true; - apply(); - close(); - }), ui.spark.LadderSettingsDialog.ResetToFactoryKey); - // maybe dispose vms - if (instance_vm is IDisposable dispose_ivm) - _resources.Add(dispose_ivm); - if (default_vm is IDisposable dispose_dvm) - _resources.Add(dispose_dvm); - // local methods - void apply() { - var result = merge_with_current(instance_vm.get_result()); - if (!use_default) { - settings_manager.instance_settings = result; - } else { - settings_manager.instance_settings = null; - - // copy the current instance settings and persist - if (!result.safe_equals(settings_manager.default_settings)) - settings_manager.save_default_settings(result).ignore(); - } - } - - void close() => RequestClose?.Invoke(this, new EventArgs()); - - IEnumerable left_skirt_factory() { - if (show_save_as_defaults) - yield return _apply_to_defaults_item; - }; - } - - public event EventHandler RequestClose; - - public TVM instance_vm { get; } - public TVM default_vm { get; } - public IReadOnlyCollection action_menu_items { get; } - public IEnumerable left_skirt_items => _left_skirt_items.Value; - public IEnumerable right_skirt_items { - get { - yield return _apply_item; - yield return _ok_item; - yield return _cancel_item; - } - } - public bool use_default { - get => _use_default.Value; - set => _use_default.Value = value; - } - - public void Dispose() => - Disposable.dispose(_resources); - } -} diff --git a/src/client/spark/view/Utility/KeyedStyleSelector.cs b/src/client/spark/view/Utility/KeyedStyleSelector.cs index be8fe33d5..043b66483 100644 --- a/src/client/spark/view/Utility/KeyedStyleSelector.cs +++ b/src/client/spark/view/Utility/KeyedStyleSelector.cs @@ -26,7 +26,7 @@ namespace mbts.ui { protected virtual bool _try_get_item_key(object item, out TKey result) { if (item is IStyleSelectorKey ssk) { result = ssk.key; - return true; + return result != null; } result = default; return false; diff --git a/src/client/spark/view/Utility/WPFHelper.cs b/src/client/spark/view/Utility/WPFHelper.cs index b1aea246d..03c5171e7 100644 --- a/src/client/spark/view/Utility/WPFHelper.cs +++ b/src/client/spark/view/Utility/WPFHelper.cs @@ -16,6 +16,9 @@ namespace mbts.ui { static class WPFHelper { public delegate void PropertyChangedCallback(TOwner owner, TValue old_value, TValue new_value); + public static DependencyProperty create_dp(string name, Action callback, object default_value = null) => + DependencyProperty.Register(name, typeof(object), typeof(TOwner), new PropertyMetadata(default_value, (d, e) => callback(ConvertUtils.try_convert(d), e.NewValue))); + public static DependencyProperty create_dp(string name, TValue default_value = default) => DependencyProperty.Register(name, typeof(TValue), typeof(TOwner), new PropertyMetadata(default_value)); diff --git a/src/client/spark_core/Collections/Extensions/DictionaryExtensions.cs b/src/client/spark_core/Collections/Extensions/DictionaryExtensions.cs index e1f450d91..ac6be385d 100644 --- a/src/client/spark_core/Collections/Extensions/DictionaryExtensions.cs +++ b/src/client/spark_core/Collections/Extensions/DictionaryExtensions.cs @@ -246,11 +246,30 @@ namespace System.Collections.Generic { public static class DictionaryHelper { public static IReadOnlyDictionary empty() => - Empty.value; + Impl.empty; - static class Empty { - public static readonly IReadOnlyDictionary value = + public static IComparer> key_comparer() => + Impl.key_comparer; + + static class Impl { + public static readonly IReadOnlyDictionary empty = new ReadOnlyDictionary(new Dictionary(0)); + + public static readonly IComparer> key_comparer = + new KeyComparer(Comparer.Default); + + class KeyComparer : IComparer>, IComparer { + readonly IComparer _comparer; + + public KeyComparer(IComparer comparer) => + _comparer = comparer; + + public int Compare(KeyValuePair x, KeyValuePair y) => + _comparer.Compare(x.Key, y.Key); + + public int Compare(object x, object y) => + x is KeyValuePair xkv ? (y is KeyValuePair ykv ? Compare(xkv, ykv) : 1) : -1; + } } } } \ No newline at end of file diff --git a/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs b/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs index 3b0c6d69d..831f297e7 100644 --- a/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs +++ b/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs @@ -382,6 +382,25 @@ namespace System.Collections.Generic { } #endregion + #region MinOrDefault + public static T MinOrDefault(this IEnumerable source) where T : IComparable => + MinOrDefault(source, default); + + public static T MinOrDefault(this IEnumerable source, T default_value) where T : IComparable { + using (var en = source.GetEnumerator()) { + if (en.MoveNext()) { + T min = en.Current; + while (en.MoveNext()) { + if (min.CompareTo(en.Current) > 0) + min = en.Current; + } + return min; + } + } + return default_value; + } + #endregion + #region MinElement public static TElement MinElement(this IEnumerable enumerable, Func select_value) where T : IComparable => MinElement(enumerable, select_value, default(TElement)); @@ -448,6 +467,25 @@ namespace System.Collections.Generic { } #endregion + #region MaxOrDefault + public static T MaxOrDefault(this IEnumerable source) where T : IComparable => + MaxOrDefault(source, default); + + public static T MaxOrDefault(this IEnumerable source, T default_value) where T : IComparable { + using (var en = source.GetEnumerator()) { + if (en.MoveNext()) { + T max = en.Current; + while (en.MoveNext()) { + if (max.CompareTo(en.Current) < 0) + max = en.Current; + } + return max; + } + } + return default_value; + } + #endregion + #region MaxElement public static TElement MaxElement(this IEnumerable enumerable, Func select_value) where T : IComparable => MaxElement(enumerable, select_value, default(TElement)); diff --git a/src/client/spark_core/Collections/Extensions/ListExtensions.cs b/src/client/spark_core/Collections/Extensions/ListExtensions.cs index a056e754f..194085d20 100644 --- a/src/client/spark_core/Collections/Extensions/ListExtensions.cs +++ b/src/client/spark_core/Collections/Extensions/ListExtensions.cs @@ -116,6 +116,9 @@ namespace bts.collections { public static IList WrapSubRange(this IList list, int start, int length) => new SubRangeWrapper(list, start, length); + public static IList WrapSkip(this IList list, int skip) => + new SkipFrontWrapper(list, skip); + public static IList WrapSelector(this IList list, Func convert, Func convert_back = null) => new SelectorWrapper(list, convert, convert_back); @@ -408,5 +411,69 @@ namespace bts.collections { public void RemoveAt(int index) => _source.RemoveAt(index); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } + + class SkipFrontWrapper : IList, IReadOnlyList { + readonly IList _source; + readonly int _skip; + + public SkipFrontWrapper(IList source, int skip) { + _source = source; + _skip = skip; + } + + public T this[int index] { + get => _source[_skip + index]; + set => _source[_skip + index] = value; + } + + public int Count { + get { + int c = _source.Count; + return c > _skip ? (c - _skip) : 0; + } + } + + public bool IsReadOnly => _source.IsReadOnly; + + public void Add(T item) => _source.Add(item); + public void Clear() { + int c = Count; + if (c == 0) + return; + if (_source is List l) { + l.RemoveRange(_skip, c); + } else { + for (int i = 0; i < c; i++) + _source.RemoveAt(_skip); + } + } + public bool Contains(T item) => IndexOf(item) >= 0; + public void CopyTo(T[] array, int arrayIndex) { + arrayIndex -= _skip; + for (int i = _skip; i < _source.Count; i++) + array[arrayIndex + i] = _source[i]; + } + public IEnumerator GetEnumerator() { + for (int i = _skip; i < _source.Count; i++) + yield return _source[i]; + } + public int IndexOf(T item) { + for (int i = _skip; i < _source.Count; i++) { + if (_source[i].Equals(item)) + return i - _skip; + } + return -1; + } + public void Insert(int index, T item) => _source.Insert(index + _skip, item); + public bool Remove(T item) { + int i = IndexOf(item); + if (i >= 0) { + _source.RemoveAt(i + _skip); + return true; + } else return false; + } + public void RemoveAt(int index) => _source.RemoveAt(index + _skip); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } } } \ No newline at end of file